mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-10-20 08:14:26 +00:00
Compare commits
2
Commits
main
..
tls-update
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab507b7a0d | ||
|
|
969e5b6c11 |
@@ -109,7 +109,7 @@ func (h *HealthPingRTTS) getStatistics() *HealthPingStats {
|
|||||||
stats.Min = 0
|
stats.Min = 0
|
||||||
return stats
|
return stats
|
||||||
}
|
}
|
||||||
stats.Average = sum / time.Duration(cnt)
|
stats.Average = time.Duration(int(sum) / cnt)
|
||||||
var std float64
|
var std float64
|
||||||
if cnt < 2 {
|
if cnt < 2 {
|
||||||
// no enough data for standard deviation, we assume it's half of the average rtt
|
// no enough data for standard deviation, we assume it's half of the average rtt
|
||||||
|
|||||||
+1
-1
@@ -20,7 +20,7 @@ import (
|
|||||||
var (
|
var (
|
||||||
Version_x byte = 26
|
Version_x byte = 26
|
||||||
Version_y byte = 10
|
Version_y byte = 10
|
||||||
Version_z byte = 17
|
Version_z byte = 10
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|||||||
@@ -1,15 +1,11 @@
|
|||||||
package conf
|
package conf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
utls "github.com/refraction-networking/utls"
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/serial"
|
"github.com/xtls/xray-core/common/serial"
|
||||||
"github.com/xtls/xray-core/transport/internet"
|
"github.com/xtls/xray-core/transport/internet"
|
||||||
"github.com/xtls/xray-core/transport/internet/tls"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type TransportProtocol string
|
type TransportProtocol string
|
||||||
@@ -104,14 +100,6 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
|
|||||||
tm := serial.ToTypedMessage(ts)
|
tm := serial.ToTypedMessage(ts)
|
||||||
config.SecuritySettings = append(config.SecuritySettings, tm)
|
config.SecuritySettings = append(config.SecuritySettings, tm)
|
||||||
config.SecurityType = tm.Type
|
config.SecurityType = tm.Type
|
||||||
if config.ProtocolName == "xdrive" && tlsSettings.ALPN != nil && slices.Equal(*tlsSettings.ALPN, StringList{"http/1.1"}) && tlsSettings.ECHConfigList == "" {
|
|
||||||
// a fingerprint puts its own ALPN into the hello, except Go TLS and the
|
|
||||||
// randomized ones, which take it from the config or send none
|
|
||||||
if fp := tls.GetFingerprint(strings.ToLower(tlsSettings.Fingerprint)); fp != nil && fp.Client != utls.HelloGolang.Client &&
|
|
||||||
!strings.HasPrefix(fp.Client, utls.HelloRandomized.Client) {
|
|
||||||
errors.LogWarning(context.Background(), `XDRIVE: "alpn" ["http/1.1"] reaches the wire only inside ECH, without "echConfigList" the hello carries the ALPN of the fingerprint and the server may pick h2`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case "reality":
|
case "reality":
|
||||||
if config.ProtocolName != "tcp" && config.ProtocolName != "splithttp" && config.ProtocolName != "grpc" {
|
if config.ProtocolName != "tcp" && config.ProtocolName != "splithttp" && config.ProtocolName != "grpc" {
|
||||||
return nil, errors.New("REALITY only supports RAW, XHTTP and gRPC for now.")
|
return nil, errors.New("REALITY only supports RAW, XHTTP and gRPC for now.")
|
||||||
|
|||||||
@@ -1004,10 +1004,6 @@ func (c *XDriveConfig) Build() (proto.Message, error) {
|
|||||||
switch c.Service {
|
switch c.Service {
|
||||||
case "local":
|
case "local":
|
||||||
case "Google Drive":
|
case "Google Drive":
|
||||||
errors.PrintDeprecatedFeatureWarning(`"service": "Google Drive"`, `"service": "google-drive"`)
|
|
||||||
c.Service = "google-drive"
|
|
||||||
fallthrough
|
|
||||||
case "google-drive":
|
|
||||||
if len(c.Secrets) != 3 {
|
if len(c.Secrets) != 3 {
|
||||||
return nil, errors.New("Google Drive needs 3 secrets in order of ClientID, ClientSecret, RefreshToken")
|
return nil, errors.New("Google Drive needs 3 secrets in order of ClientID, ClientSecret, RefreshToken")
|
||||||
}
|
}
|
||||||
@@ -1016,7 +1012,7 @@ func (c *XDriveConfig) Build() (proto.Message, error) {
|
|||||||
return nil, errors.New(`service "template" needs a "template" object`)
|
return nil, errors.New(`service "template" needs a "template" object`)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
return nil, errors.New(`unknown "service": "`, c.Service, `", use "google-drive", "template" or "local"`)
|
return nil, errors.New("unsupported service")
|
||||||
}
|
}
|
||||||
config := &xdrive.Config{
|
config := &xdrive.Config{
|
||||||
RemoteFolder: c.RemoteFolder,
|
RemoteFolder: c.RemoteFolder,
|
||||||
|
|||||||
@@ -5,11 +5,9 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/log"
|
|
||||||
. "github.com/xtls/xray-core/infra/conf"
|
. "github.com/xtls/xray-core/infra/conf"
|
||||||
"github.com/xtls/xray-core/transport/internet"
|
"github.com/xtls/xray-core/transport/internet"
|
||||||
finalmaskcustom "github.com/xtls/xray-core/transport/internet/finalmask/header/custom"
|
finalmaskcustom "github.com/xtls/xray-core/transport/internet/finalmask/header/custom"
|
||||||
"github.com/xtls/xray-core/transport/internet/xdrive"
|
|
||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -323,25 +321,8 @@ func TestXDriveRejectsUnknownService(t *testing.T) {
|
|||||||
if err := json.Unmarshal([]byte(`{"remoteFolder": "/tmp/xdrive", "service": "Dropbox"}`), config); err != nil {
|
if err := json.Unmarshal([]byte(`{"remoteFolder": "/tmp/xdrive", "service": "Dropbox"}`), config); err != nil {
|
||||||
t.Fatalf("Unmarshal: %v", err)
|
t.Fatalf("Unmarshal: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := config.Build(); err == nil || !strings.Contains(err.Error(), `use "google-drive", "template" or "local"`) {
|
|
||||||
t.Fatalf("expected an unknown service error, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestXDriveGoogleDriveName(t *testing.T) {
|
|
||||||
for _, service := range []string{"google-drive", "Google Drive"} {
|
|
||||||
config := &XDriveConfig{RemoteFolder: "folder-id", Service: service, Secrets: []string{"a", "b", "c"}}
|
|
||||||
built, err := config.Build()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("%s: %v", service, err)
|
|
||||||
}
|
|
||||||
if got := built.(*xdrive.Config).Service; got != "google-drive" {
|
|
||||||
t.Errorf("%s: service is %q, want google-drive", service, got)
|
|
||||||
}
|
|
||||||
config = &XDriveConfig{RemoteFolder: "folder-id", Service: service, Secrets: []string{"a", "b"}}
|
|
||||||
if _, err := config.Build(); err == nil {
|
if _, err := config.Build(); err == nil {
|
||||||
t.Errorf("%s: accepted two secrets", service)
|
t.Fatal("Build accepted an unsupported service")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -374,56 +355,6 @@ func TestXDriveTemplateStreamConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type logLines []string
|
|
||||||
|
|
||||||
func (l *logLines) Handle(msg log.Message) {
|
|
||||||
*l = append(*l, msg.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// "alpn" ["http/1.1"] is warned about where the hello does not carry it, which
|
|
||||||
// is outside ECH with a fingerprint that has an ALPN of its own
|
|
||||||
func TestXDriveHTTP1ALPNWarning(t *testing.T) {
|
|
||||||
var lines logLines
|
|
||||||
log.RegisterHandler(&lines)
|
|
||||||
|
|
||||||
for _, c := range []struct {
|
|
||||||
method, tlsSettings string
|
|
||||||
warn bool
|
|
||||||
}{
|
|
||||||
{"xdrive", `{}`, false},
|
|
||||||
{"xdrive", `{"alpn": ["http/1.1"]}`, true},
|
|
||||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "Firefox"}`, true},
|
|
||||||
{"raw", `{"alpn": ["http/1.1"]}`, false},
|
|
||||||
{"xdrive", `{"alpn": ["h2", "http/1.1"]}`, false},
|
|
||||||
{"xdrive", `{"alpn": ["http/1.1"], "echConfigList": "udp://1.1.1.1"}`, false},
|
|
||||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "unsafe"}`, false},
|
|
||||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "hellogolang"}`, false},
|
|
||||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "randomized"}`, false},
|
|
||||||
{"xdrive", `{"alpn": ["http/1.1"], "fingerprint": "hellorandomizednoalpn"}`, false},
|
|
||||||
} {
|
|
||||||
lines = nil
|
|
||||||
config := new(StreamConfig)
|
|
||||||
if err := json.Unmarshal([]byte(`{
|
|
||||||
"method": "`+c.method+`",
|
|
||||||
"security": "tls",
|
|
||||||
"tlsSettings": `+c.tlsSettings+`,
|
|
||||||
"xdriveSettings": {"remoteFolder": "/tmp/xdrive", "service": "local"}
|
|
||||||
}`), config); err != nil {
|
|
||||||
t.Fatalf("Unmarshal: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := config.Build(); err != nil {
|
|
||||||
t.Fatalf("%s %s: %v", c.method, c.tlsSettings, err)
|
|
||||||
}
|
|
||||||
warned := false
|
|
||||||
for _, line := range lines {
|
|
||||||
warned = warned || strings.HasPrefix(line, "[Warning]") && strings.Contains(line, `"alpn"`)
|
|
||||||
}
|
|
||||||
if warned != c.warn {
|
|
||||||
t.Errorf("%s %s: warned %v, want %v", c.method, c.tlsSettings, warned, c.warn)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestXDriveTemplateNeedsTemplate(t *testing.T) {
|
func TestXDriveTemplateNeedsTemplate(t *testing.T) {
|
||||||
config := new(XDriveConfig)
|
config := new(XDriveConfig)
|
||||||
if err := json.Unmarshal([]byte(`{"remoteFolder": "f", "service": "template"}`), config); err != nil {
|
if err := json.Unmarshal([]byte(`{"remoteFolder": "f", "service": "template"}`), config); err != nil {
|
||||||
@@ -433,83 +364,3 @@ func TestXDriveTemplateNeedsTemplate(t *testing.T) {
|
|||||||
t.Fatal("Build accepted a template service without a template")
|
t.Fatal("Build accepted a template service without a template")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
|
||||||
xdriveStream = `"streamSettings": {"network": "xdrive", "xdriveSettings": {"remoteFolder": "f", "service": "local"}}`
|
|
||||||
xdriveID = `"id": "27848739-7e62-4138-9fd3-098a63964b6b"`
|
|
||||||
xdriveServer = `"address": "127.0.0.1", "port": 443, ` + xdriveID
|
|
||||||
xdriveEnc = `"encryption": "mlkem768x25519plus.native.0rtt.XKbaq1BuzJKKKPxZbwgRpn-gYQbnhrYketgezASCL1I"`
|
|
||||||
xdriveDec = `"decryption": "mlkem768x25519plus.native.600s.UKfUEMDdjlEnycTMBP0a08acky8vRRKSrM1MRnaYk3s"`
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestXDriveOutboundConfig(t *testing.T) {
|
|
||||||
build := func(s string) error {
|
|
||||||
c := new(OutboundDetourConfig)
|
|
||||||
if err := json.Unmarshal([]byte(s), c); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err := c.Build()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, input := range []string{
|
|
||||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
|
||||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": 0, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}`,
|
|
||||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
|
|
||||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}]}, ` + xdriveStream + `, "mux": {"enabled": true}}`,
|
|
||||||
} {
|
|
||||||
if err := build(input); err != nil {
|
|
||||||
t.Errorf("%s: %v", input, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, c := range []struct{ input, err string }{
|
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
|
||||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"encryption"`},
|
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"mux"`},
|
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": false}}`, `"mux"`},
|
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"mux"`},
|
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpConcurrency": -1}}`, `"mux"`},
|
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true, "xudpProxyUDP443": "skip"}}`, `"mux"`},
|
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
|
|
||||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}]}, ` + xdriveStream + `, "mux": {"enabled": true, "concurrency": -1}}`, `"flow"`},
|
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"testpre"`},
|
|
||||||
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
|
||||||
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
|
||||||
{`{"protocol": "freedom", ` + xdriveStream + `}`, "VLESS"},
|
|
||||||
} {
|
|
||||||
if err := build(c.input); err == nil || !strings.Contains(err.Error(), "xdrive transport") || !strings.Contains(err.Error(), c.err) {
|
|
||||||
t.Errorf("expected an xdrive error about %s for %s, got %v", c.err, c.input, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestXDriveInboundConfig(t *testing.T) {
|
|
||||||
build := func(s string) error {
|
|
||||||
c := new(InboundDetourConfig)
|
|
||||||
if err := json.Unmarshal([]byte(s), c); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err := c.Build()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, input := range []string{
|
|
||||||
`{"protocol": "vless", "port": 443, "settings": {"clients": [{` + xdriveID + `}], ` + xdriveDec + `}, ` + xdriveStream + `}`,
|
|
||||||
`{"protocol": "vless", "listen": "@xdrive", "settings": {"clients": [{` + xdriveID + `}], ` + xdriveDec + `}, ` + xdriveStream + `}`,
|
|
||||||
} {
|
|
||||||
if err := build(input); err != nil {
|
|
||||||
t.Errorf("%s: %v", input, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, c := range []struct{ input, err string }{
|
|
||||||
{`{"protocol": "vless", "port": 443, "settings": {"clients": [{` + xdriveID + `}], "decryption": "none"}, ` + xdriveStream + `}`, `"decryption"`},
|
|
||||||
{`{"protocol": "vless", "port": 443, "settings": {"clients": [{` + xdriveID + `}], ` + xdriveDec + `, "flow": "xtls-rprx-vision"}, ` + xdriveStream + `}`, `"flow"`},
|
|
||||||
{`{"protocol": "vless", "port": 443, "settings": {"clients": [{` + xdriveID + `, "flow": "xtls-rprx-vision"}], ` + xdriveDec + `}, ` + xdriveStream + `}`, `"flow"`},
|
|
||||||
{`{"protocol": "vmess", "port": 443, "settings": {"clients": [{` + xdriveID + `}]}, ` + xdriveStream + `}`, "VLESS"},
|
|
||||||
{`{"protocol": "vless", "port": "10800-10803", "settings": {"clients": [{` + xdriveID + `}], ` + xdriveDec + `}, ` + xdriveStream + `}`, "one port"},
|
|
||||||
} {
|
|
||||||
if err := build(c.input); err == nil || !strings.Contains(err.Error(), "xdrive transport") || !strings.Contains(err.Error(), c.err) {
|
|
||||||
t.Errorf("expected an xdrive error about %s for %s, got %v", c.err, c.input, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -17,11 +17,7 @@ import (
|
|||||||
core "github.com/xtls/xray-core/core"
|
core "github.com/xtls/xray-core/core"
|
||||||
"github.com/xtls/xray-core/proxy/freedom"
|
"github.com/xtls/xray-core/proxy/freedom"
|
||||||
"github.com/xtls/xray-core/proxy/masque"
|
"github.com/xtls/xray-core/proxy/masque"
|
||||||
"github.com/xtls/xray-core/proxy/vless"
|
|
||||||
"github.com/xtls/xray-core/proxy/vless/inbound"
|
|
||||||
"github.com/xtls/xray-core/proxy/vless/outbound"
|
|
||||||
"github.com/xtls/xray-core/transport/internet"
|
"github.com/xtls/xray-core/transport/internet"
|
||||||
"google.golang.org/protobuf/proto"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -213,9 +209,6 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
|
|||||||
if _, ok := ts.(*masque.ServerConfig); !ok && receiverSettings.StreamSettings != nil && receiverSettings.StreamSettings.ProtocolName == "masque" {
|
if _, ok := ts.(*masque.ServerConfig); !ok && receiverSettings.StreamSettings != nil && receiverSettings.StreamSettings.ProtocolName == "masque" {
|
||||||
return nil, errors.New("the masque transport can only be used by the masque inbound")
|
return nil, errors.New("the masque transport can only be used by the masque inbound")
|
||||||
}
|
}
|
||||||
if err := validateXDrive(ts, receiverSettings.StreamSettings, nil, receiverSettings.PortList); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &core.InboundHandlerConfig{
|
return &core.InboundHandlerConfig{
|
||||||
Tag: c.Tag,
|
Tag: c.Tag,
|
||||||
@@ -269,54 +262,6 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateXDrive allows only VLESS with encryption on xdrive, and on the client Mux.Cool for every connection
|
|
||||||
func validateXDrive(ts proto.Message, ss *internet.StreamConfig, ms *proxyman.MultiplexingConfig, pl *net.PortList) error {
|
|
||||||
if ss == nil || ss.ProtocolName != "xdrive" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
switch c := ts.(type) {
|
|
||||||
case *outbound.Config:
|
|
||||||
a, err := c.Vnext.User.Account.GetInstance()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
account := a.(*vless.Account)
|
|
||||||
if account.Flow != "" {
|
|
||||||
return errors.New(`the xdrive transport doesn't support VLESS "flow"`)
|
|
||||||
}
|
|
||||||
if account.Encryption == "none" {
|
|
||||||
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
|
|
||||||
}
|
|
||||||
// reverse opens its own mux
|
|
||||||
if account.Reverse == nil && (ms == nil || !ms.Enabled || ms.Concurrency < 0 || ms.XudpConcurrency < 0 || ms.XudpProxyUDP443 == "skip") {
|
|
||||||
return errors.New(`the xdrive transport needs "mux" enabled, with no negative "concurrency" or "xudpConcurrency" and no "xudpProxyUDP443":"skip"`)
|
|
||||||
}
|
|
||||||
if account.Testpre != 0 {
|
|
||||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
|
||||||
}
|
|
||||||
case *inbound.Config:
|
|
||||||
if c.Decryption == "none" {
|
|
||||||
return errors.New(`the xdrive transport needs VLESS "decryption", run "xray vlessenc" to get one`)
|
|
||||||
}
|
|
||||||
for _, user := range c.Users {
|
|
||||||
a, err := user.Account.GetInstance()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if a.(*vless.Account).Flow != "" {
|
|
||||||
return errors.New(`the xdrive transport doesn't support VLESS "flow"`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// every port gets its own listener on the same folder, and each of them accepts the same session
|
|
||||||
if pl != nil && len(pl.Ports()) != 1 {
|
|
||||||
return errors.New("the xdrive transport can only listen on one port")
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return errors.New("the xdrive transport can only be used by VLESS")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build implements Buildable.
|
// Build implements Buildable.
|
||||||
func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||||
if c.ProxySettings != nil {
|
if c.ProxySettings != nil {
|
||||||
@@ -395,9 +340,6 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
|
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
|
||||||
}
|
}
|
||||||
if err := validateXDrive(ts, senderSettings.StreamSettings, senderSettings.MultiplexSettings, nil); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,7 +153,7 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
|
|||||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||||
}
|
}
|
||||||
epoch := binary.BigEndian.Uint64(bodyPlain[1:9])
|
epoch := binary.BigEndian.Uint64(bodyPlain[1:9])
|
||||||
diff := math.Abs(float64(time.Now().Unix() - int64(epoch)))
|
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
|
||||||
if diff > 30 {
|
if diff > 30 {
|
||||||
return DecodedUDPPacket{}, ErrBadTimestamp
|
return DecodedUDPPacket{}, ErrBadTimestamp
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,12 +49,12 @@ func (f *SlidingWindow) Add(counter uint64) {
|
|||||||
|
|
||||||
if counter > f.last {
|
if counter > f.last {
|
||||||
lastBlockIndex := f.last >> swBlockBitLog
|
lastBlockIndex := f.last >> swBlockBitLog
|
||||||
diff := blockIndex - lastBlockIndex
|
diff := int(blockIndex - lastBlockIndex)
|
||||||
if diff > swRingBlocks {
|
if diff > swRingBlocks {
|
||||||
diff = swRingBlocks
|
diff = swRingBlocks
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := 0; i < int(diff); i++ {
|
for i := 0; i < diff; i++ {
|
||||||
lastBlockIndex = (lastBlockIndex + 1) & swBlockMask
|
lastBlockIndex = (lastBlockIndex + 1) & swBlockMask
|
||||||
f.ring[lastBlockIndex] = 0
|
f.ring[lastBlockIndex] = 0
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -254,7 +254,7 @@ func ReadClientRequestHeaderWithFixed(reader *StreamReader, fixedChunk []byte) (
|
|||||||
}
|
}
|
||||||
|
|
||||||
epoch := binary.BigEndian.Uint64(plainFixed[1:9])
|
epoch := binary.BigEndian.Uint64(plainFixed[1:9])
|
||||||
diff := math.Abs(float64(time.Now().Unix() - int64(epoch)))
|
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch))))
|
||||||
if diff > 30 {
|
if diff > 30 {
|
||||||
return nil, ErrBadTimestamp
|
return nil, ErrBadTimestamp
|
||||||
}
|
}
|
||||||
@@ -431,7 +431,7 @@ func ReadTCPResponse(r io.Reader, method *CipherMethod, psk []byte, clientSalt [
|
|||||||
}
|
}
|
||||||
|
|
||||||
serverEpoch := binary.BigEndian.Uint64(decryptedFixed[1:9])
|
serverEpoch := binary.BigEndian.Uint64(decryptedFixed[1:9])
|
||||||
diff := math.Abs(float64(time.Now().Unix() - int64(serverEpoch)))
|
diff := int(math.Abs(float64(time.Now().Unix() - int64(serverEpoch))))
|
||||||
if diff > 30 {
|
if diff > 30 {
|
||||||
return nil, ErrBadTimestamp
|
return nil, ErrBadTimestamp
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -144,8 +144,7 @@ func (t *Handler) Start() error {
|
|||||||
errors.LogInfo(context.Background(), "[tun] falied to set interface > iface == nil")
|
errors.LogInfo(context.Background(), "[tun] falied to set interface > iface == nil")
|
||||||
return errors.New("iface not found")
|
return errors.New("iface not found")
|
||||||
}
|
}
|
||||||
var controlErr, sockErr error
|
return c.Control(func(fd uintptr) {
|
||||||
controlErr = c.Control(func(fd uintptr) {
|
|
||||||
addrPort, _ := netip.ParseAddrPort(address)
|
addrPort, _ := netip.ParseAddrPort(address)
|
||||||
// skip loopback
|
// skip loopback
|
||||||
if addrPort.Addr().IsLoopback() || strings.HasPrefix(strings.ToLower(address), "localhost:") {
|
if addrPort.Addr().IsLoopback() || strings.HasPrefix(strings.ToLower(address), "localhost:") {
|
||||||
@@ -153,13 +152,9 @@ func (t *Handler) Start() error {
|
|||||||
}
|
}
|
||||||
err := setinterface(network, address, fd, iface)
|
err := setinterface(network, address, fd, iface)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
sockErr = errors.New("[tun] falied to set interface").Base(err)
|
errors.LogInfoInner(context.Background(), err, "[tun] falied to set interface")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
if sockErr != nil {
|
|
||||||
return sockErr
|
|
||||||
}
|
|
||||||
return controlErr
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-11
@@ -16,9 +16,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type bind struct {
|
type bind struct {
|
||||||
ctx context.Context
|
|
||||||
resolveFunc func(host string) (net.IP, error)
|
resolveFunc func(host string) (net.IP, error)
|
||||||
listenFunc func(ctx context.Context) (net.PacketConn, error)
|
listenFunc func() (net.PacketConn, error)
|
||||||
downFunc func() error
|
downFunc func() error
|
||||||
reserved []byte
|
reserved []byte
|
||||||
|
|
||||||
@@ -27,12 +26,6 @@ type bind struct {
|
|||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *bind) SetCtx(ctx context.Context) {
|
|
||||||
b.mu.Lock()
|
|
||||||
defer b.mu.Unlock()
|
|
||||||
b.ctx = ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err error) {
|
func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err error) {
|
||||||
b.mu.Lock()
|
b.mu.Lock()
|
||||||
defer b.mu.Unlock()
|
defer b.mu.Unlock()
|
||||||
@@ -41,7 +34,7 @@ func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err
|
|||||||
return nil, 0, conn.ErrBindAlreadyOpen
|
return nil, 0, conn.ErrBindAlreadyOpen
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := b.listenFunc(b.ctx)
|
c, err := b.listenFunc()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@@ -59,9 +52,12 @@ func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err
|
|||||||
case <-ch:
|
case <-ch:
|
||||||
default:
|
default:
|
||||||
errors.LogErrorInner(context.Background(), err, "unexpected closed")
|
errors.LogErrorInner(context.Background(), err, "unexpected closed")
|
||||||
if b.downFunc != nil {
|
b.mu.Lock()
|
||||||
|
downFunc := b.downFunc
|
||||||
|
b.mu.Unlock()
|
||||||
|
if downFunc != nil {
|
||||||
go func() {
|
go func() {
|
||||||
common.Must(b.downFunc())
|
common.Must(downFunc())
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -83,6 +79,13 @@ func (b *bind) Open(port uint16) (fns []conn.ReceiveFunc, actualPort uint16, err
|
|||||||
}, uint16(c.LocalAddr().(*net.UDPAddr).Port), nil
|
}, uint16(c.LocalAddr().(*net.UDPAddr).Port), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// setDownFunc sets downFunc after the device is created, since the device may already be using the bind.
|
||||||
|
func (b *bind) setDownFunc(f func() error) {
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
b.downFunc = f
|
||||||
|
}
|
||||||
|
|
||||||
func (b *bind) Close() error {
|
func (b *bind) Close() error {
|
||||||
b.mu.Lock()
|
b.mu.Lock()
|
||||||
defer b.mu.Unlock()
|
defer b.mu.Unlock()
|
||||||
|
|||||||
+114
-130
@@ -7,7 +7,6 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.zx2c4.com/wireguard/tun"
|
"golang.zx2c4.com/wireguard/tun"
|
||||||
@@ -32,13 +31,17 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
p policy.Manager
|
conf *DeviceConfig
|
||||||
|
policyManager policy.Manager
|
||||||
|
dns dns.Client
|
||||||
|
|
||||||
canup *atomic.Bool
|
streamSettings *internet.MemoryStreamConfig
|
||||||
|
uplinkCounter stats.Counter
|
||||||
|
downlinkCounter stats.Counter
|
||||||
|
|
||||||
|
tun tun.Device
|
||||||
tnet *Net
|
tnet *Net
|
||||||
bind *bind
|
|
||||||
dev *device.Device
|
dev *device.Device
|
||||||
ipc string
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,86 +124,17 @@ func NewClient(ctx context.Context, conf *DeviceConfig) (*Handler, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
blockup := newblockup(tun)
|
|
||||||
bind := &bind{}
|
|
||||||
logger := &device.Logger{
|
|
||||||
Verbosef: func(format string, args ...any) {
|
|
||||||
log.Record(&log.GeneralMessage{
|
|
||||||
Severity: log.Severity_Debug,
|
|
||||||
Content: fmt.Sprintf(format, args...),
|
|
||||||
})
|
|
||||||
},
|
|
||||||
Errorf: func(format string, args ...any) {
|
|
||||||
log.Record(&log.GeneralMessage{
|
|
||||||
Severity: log.Severity_Error,
|
|
||||||
Content: fmt.Sprintf(format, args...),
|
|
||||||
})
|
|
||||||
},
|
|
||||||
}
|
|
||||||
dev := device.NewDevice(blockup, bind, logger)
|
|
||||||
bind.ctx = context.Background()
|
|
||||||
bind.resolveFunc = MakeResolveLocal(d, streamSettings)
|
|
||||||
bind.listenFunc = func(ctx context.Context) (net.PacketConn, error) {
|
|
||||||
dest, err := net.ParseDestination("udp:" + conf.Peers[0].Endpoint)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var pktConn net.PacketConn
|
|
||||||
if streamSettings.FinalMask != nil {
|
|
||||||
conn, err := streamSettings.FinalMask.DialUDP(ctx, dest)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("failed to dial to dest").Base(err)
|
|
||||||
}
|
|
||||||
pktConn = conn.(*net.PacketConnWrapper).PacketConn
|
|
||||||
} else {
|
|
||||||
conn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("failed to dial to dest").Base(err)
|
|
||||||
}
|
|
||||||
switch c := conn.(type) {
|
|
||||||
case *net.PacketConnWrapper:
|
|
||||||
pktConn = c.PacketConn
|
|
||||||
case *cnc.Connection:
|
|
||||||
pktConn = &internet.FakePacketConn{Conn: c}
|
|
||||||
default:
|
|
||||||
panic(reflect.TypeOf(c))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if uplinkCounter != nil || downlinkCounter != nil {
|
|
||||||
pktConn = &PacketCounterConnection{
|
|
||||||
PacketConn: pktConn,
|
|
||||||
ReadCounter: downlinkCounter,
|
|
||||||
WriteCounter: uplinkCounter,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return pktConn, nil
|
|
||||||
}
|
|
||||||
bind.downFunc = dev.Down
|
|
||||||
bind.reserved = conf.Reserved
|
|
||||||
var cfg strings.Builder
|
|
||||||
cfg.WriteString("private_key=" + conf.SecretKey + "\n")
|
|
||||||
for _, peer := range conf.Peers {
|
|
||||||
cfg.WriteString("public_key=" + peer.PublicKey + "\n")
|
|
||||||
if peer.PreSharedKey != "" {
|
|
||||||
cfg.WriteString("preshared_key=" + peer.PreSharedKey + "\n")
|
|
||||||
}
|
|
||||||
cfg.WriteString("endpoint=" + peer.Endpoint + "\n")
|
|
||||||
for _, ip := range peer.AllowedIps {
|
|
||||||
cfg.WriteString("allowed_ip=" + ip + "\n")
|
|
||||||
}
|
|
||||||
if peer.KeepAlive != "" {
|
|
||||||
cfg.WriteString("persistent_keepalive_interval=" + peer.KeepAlive + "\n")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Handler{
|
return &Handler{
|
||||||
p: p,
|
conf: conf,
|
||||||
|
policyManager: p,
|
||||||
|
dns: d,
|
||||||
|
|
||||||
canup: blockup.canup,
|
streamSettings: streamSettings,
|
||||||
|
uplinkCounter: uplinkCounter,
|
||||||
|
downlinkCounter: downlinkCounter,
|
||||||
|
|
||||||
|
tun: tun,
|
||||||
tnet: tnet,
|
tnet: tnet,
|
||||||
bind: bind,
|
|
||||||
dev: dev,
|
|
||||||
ipc: cfg.String(),
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,7 +149,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
|||||||
ob.CanSpliceCopy = 3
|
ob.CanSpliceCopy = 3
|
||||||
dialer.SetOutboundGateway(ctx, ob)
|
dialer.SetOutboundGateway(ctx, ob)
|
||||||
|
|
||||||
if err := h.up(ctx); err != nil {
|
if err := h.init(ctx); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,7 +159,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
|
|||||||
newCtx, newCancel = context.WithCancel(context.Background())
|
newCtx, newCancel = context.WithCancel(context.Background())
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionPolicy := h.p.ForLevel(0)
|
sessionPolicy := h.policyManager.ForLevel(0)
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||||
cancel()
|
cancel()
|
||||||
@@ -300,40 +234,119 @@ func (h *Handler) Close() (err error) {
|
|||||||
if h.dev != nil {
|
if h.dev != nil {
|
||||||
h.dev.Close()
|
h.dev.Close()
|
||||||
h.dev = nil
|
h.dev = nil
|
||||||
|
h.tun = nil
|
||||||
|
} else if h.tun != nil {
|
||||||
|
h.tun.Close()
|
||||||
|
h.tun = nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) up(ctx context.Context) error {
|
func (h *Handler) init(ctx context.Context) error {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
defer h.mu.Unlock()
|
defer h.mu.Unlock()
|
||||||
if h.dev == nil {
|
if h.tun == nil {
|
||||||
return errors.New("closed")
|
return errors.New("closed")
|
||||||
}
|
}
|
||||||
h.bind.SetCtx(ctx)
|
if h.dev != nil {
|
||||||
if !h.canup.Load() {
|
|
||||||
h.canup.Store(true)
|
|
||||||
}
|
|
||||||
if len(h.ipc) > 0 {
|
|
||||||
if err := h.dev.IpcSet(h.ipc); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
h.ipc = ""
|
|
||||||
}
|
|
||||||
return h.dev.Up()
|
return h.dev.Up()
|
||||||
}
|
}
|
||||||
|
resolveFunc := h.resolveLocal
|
||||||
|
listenFunc := func() (net.PacketConn, error) {
|
||||||
|
dest, err := net.ParseDestination("udp:" + h.conf.Peers[0].Endpoint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var pktConn net.PacketConn
|
||||||
|
if h.streamSettings.FinalMask != nil {
|
||||||
|
conn, err := h.streamSettings.FinalMask.DialUDP(ctx, dest)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("failed to dial to dest").Base(err)
|
||||||
|
}
|
||||||
|
pktConn = conn.(*net.PacketConnWrapper).PacketConn
|
||||||
|
} else {
|
||||||
|
conn, err := internet.DialSystem(ctx, dest, h.streamSettings.SocketSettings)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("failed to dial to dest").Base(err)
|
||||||
|
}
|
||||||
|
switch c := conn.(type) {
|
||||||
|
case *net.PacketConnWrapper:
|
||||||
|
pktConn = c.PacketConn
|
||||||
|
case *cnc.Connection:
|
||||||
|
pktConn = &internet.FakePacketConn{Conn: c}
|
||||||
|
default:
|
||||||
|
panic(reflect.TypeOf(c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if h.uplinkCounter != nil || h.downlinkCounter != nil {
|
||||||
|
pktConn = &PacketCounterConnection{
|
||||||
|
PacketConn: pktConn,
|
||||||
|
ReadCounter: h.downlinkCounter,
|
||||||
|
WriteCounter: h.uplinkCounter,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pktConn, nil
|
||||||
|
}
|
||||||
|
// device.NewDevice may use the bind right away (Up -> BindUpdate -> Open),
|
||||||
|
// so everything it reads must be set before creating the device.
|
||||||
|
bind := &bind{
|
||||||
|
resolveFunc: resolveFunc,
|
||||||
|
listenFunc: listenFunc,
|
||||||
|
reserved: h.conf.Reserved,
|
||||||
|
}
|
||||||
|
logger := &device.Logger{
|
||||||
|
Verbosef: func(format string, args ...any) {
|
||||||
|
log.Record(&log.GeneralMessage{
|
||||||
|
Severity: log.Severity_Debug,
|
||||||
|
Content: fmt.Sprintf(format, args...),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
Errorf: func(format string, args ...any) {
|
||||||
|
log.Record(&log.GeneralMessage{
|
||||||
|
Severity: log.Severity_Error,
|
||||||
|
Content: fmt.Sprintf(format, args...),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}
|
||||||
|
dev := device.NewDevice(h.tun, bind, logger)
|
||||||
|
bind.setDownFunc(dev.Down)
|
||||||
|
var cfg strings.Builder
|
||||||
|
cfg.WriteString("private_key=" + h.conf.SecretKey + "\n")
|
||||||
|
for _, peer := range h.conf.Peers {
|
||||||
|
cfg.WriteString("public_key=" + peer.PublicKey + "\n")
|
||||||
|
if peer.PreSharedKey != "" {
|
||||||
|
cfg.WriteString("preshared_key=" + peer.PreSharedKey + "\n")
|
||||||
|
}
|
||||||
|
cfg.WriteString("endpoint=" + peer.Endpoint + "\n")
|
||||||
|
for _, ip := range peer.AllowedIps {
|
||||||
|
cfg.WriteString("allowed_ip=" + ip + "\n")
|
||||||
|
}
|
||||||
|
if peer.KeepAlive != "" {
|
||||||
|
cfg.WriteString("persistent_keepalive_interval=" + peer.KeepAlive + "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err := dev.IpcSet(cfg.String())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = dev.Up()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
h.dev = dev
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func MakeResolveLocal(d dns.Client, streamSettings *internet.MemoryStreamConfig) func(host string) (net.IP, error) {
|
func (h *Handler) resolveLocal(host string) (net.IP, error) {
|
||||||
return func(host string) (net.IP, error) {
|
|
||||||
if ip := net.ParseIP(host); ip != nil {
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
return ip, nil
|
return ip, nil
|
||||||
}
|
}
|
||||||
ips, _, err := d.LookupIP(host, dns.IPOption{IPv4Enable: true, IPv6Enable: true})
|
ips, _, err := h.dns.LookupIP(host, dns.IPOption{IPv4Enable: true, IPv6Enable: true})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
got := ips
|
got := ips
|
||||||
if streamSettings.SocketSettings != nil {
|
if h.streamSettings.SocketSettings != nil {
|
||||||
var got4, got6 []net.IP
|
var got4, got6 []net.IP
|
||||||
for _, ip := range ips {
|
for _, ip := range ips {
|
||||||
if ip.To4() != nil {
|
if ip.To4() != nil {
|
||||||
@@ -342,7 +355,7 @@ func MakeResolveLocal(d dns.Client, streamSettings *internet.MemoryStreamConfig)
|
|||||||
got6 = append(got6, ip)
|
got6 = append(got6, ip)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
switch streamSettings.SocketSettings.DomainStrategy {
|
switch h.streamSettings.SocketSettings.DomainStrategy {
|
||||||
case internet.DomainStrategy_AS_IS, internet.DomainStrategy_USE_IP, internet.DomainStrategy_FORCE_IP:
|
case internet.DomainStrategy_AS_IS, internet.DomainStrategy_USE_IP, internet.DomainStrategy_FORCE_IP:
|
||||||
got = ips
|
got = ips
|
||||||
case internet.DomainStrategy_USE_IP4, internet.DomainStrategy_FORCE_IP4:
|
case internet.DomainStrategy_USE_IP4, internet.DomainStrategy_FORCE_IP4:
|
||||||
@@ -366,7 +379,6 @@ func MakeResolveLocal(d dns.Client, streamSettings *internet.MemoryStreamConfig)
|
|||||||
}
|
}
|
||||||
return got[dice.Roll(len(got))], nil
|
return got[dice.Roll(len(got))], nil
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
type UDPConnClient struct {
|
type UDPConnClient struct {
|
||||||
net.PacketConn
|
net.PacketConn
|
||||||
@@ -498,31 +510,3 @@ func (c *cache) Cache(host string, saddr []string, ttl uint32) {
|
|||||||
deadline: time.Now().Add(time.Second * time.Duration(ttl)),
|
deadline: time.Now().Add(time.Second * time.Duration(ttl)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type blockup struct {
|
|
||||||
tun.Device
|
|
||||||
ch chan tun.Event
|
|
||||||
canup *atomic.Bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newblockup(t tun.Device) *blockup {
|
|
||||||
ch := make(chan tun.Event, cap(t.Events()))
|
|
||||||
canup := &atomic.Bool{}
|
|
||||||
go func() {
|
|
||||||
for e := range t.Events() {
|
|
||||||
if e&tun.EventUp != 0 && !canup.Load() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case ch <- e:
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
close(ch)
|
|
||||||
}()
|
|
||||||
return &blockup{Device: t, ch: ch, canup: canup}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *blockup) Events() <-chan tun.Event {
|
|
||||||
return b.ch
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -255,7 +255,7 @@ func (s *Server) Start() error {
|
|||||||
if s.src.Address.Family().IsDomain() {
|
if s.src.Address.Family().IsDomain() {
|
||||||
return errors.New("address is domain")
|
return errors.New("address is domain")
|
||||||
}
|
}
|
||||||
listenFunc := func(context.Context) (net.PacketConn, error) {
|
listenFunc := func() (net.PacketConn, error) {
|
||||||
var pktConn net.PacketConn
|
var pktConn net.PacketConn
|
||||||
var err error
|
var err error
|
||||||
if s.streamSettings.FinalMask != nil {
|
if s.streamSettings.FinalMask != nil {
|
||||||
|
|||||||
@@ -22,12 +22,6 @@ type interConn struct {
|
|||||||
|
|
||||||
client bool
|
client bool
|
||||||
user *protocol.MemoryUser
|
user *protocol.MemoryUser
|
||||||
lock chan struct{}
|
|
||||||
mu sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *interConn) unlock() {
|
|
||||||
<-c.lock
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *interConn) User() *protocol.MemoryUser {
|
func (c *interConn) User() *protocol.MemoryUser {
|
||||||
@@ -39,9 +33,6 @@ func (c *interConn) Read(b []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *interConn) Write(b []byte) (int, error) {
|
func (c *interConn) Write(b []byte) (int, error) {
|
||||||
c.lock <- struct{}{}
|
|
||||||
defer c.unlock()
|
|
||||||
|
|
||||||
if c.client {
|
if c.client {
|
||||||
c.client = false
|
c.client = false
|
||||||
if _, err := c.stream.Write(append(quicvarint.Append(nil, FrameTypeTCPRequest), b...)); err != nil {
|
if _, err := c.stream.Write(append(quicvarint.Append(nil, FrameTypeTCPRequest), b...)); err != nil {
|
||||||
@@ -49,20 +40,11 @@ func (c *interConn) Write(b []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
return len(b), nil
|
return len(b), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.stream.Write(b)
|
return c.stream.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *interConn) Close() error {
|
func (c *interConn) Close() error {
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
select {
|
|
||||||
case c.lock <- struct{}{}:
|
|
||||||
defer c.unlock()
|
|
||||||
default:
|
|
||||||
c.stream.CancelRead(0)
|
|
||||||
c.stream.CancelWrite(0)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
c.stream.CancelRead(0)
|
c.stream.CancelRead(0)
|
||||||
return c.stream.Close()
|
return c.stream.Close()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -257,7 +257,6 @@ func (c *client) tcp(ctx context.Context) (stat.Connection, error) {
|
|||||||
remote: c.conn.RemoteAddr(),
|
remote: c.conn.RemoteAddr(),
|
||||||
|
|
||||||
client: true,
|
client: true,
|
||||||
lock: make(chan struct{}, 1),
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -134,7 +134,6 @@ func (h *httpHandler) StreamDispatcher(ft http3.FrameType, stream *quic.Stream,
|
|||||||
remote: h.conn.RemoteAddr(),
|
remote: h.conn.RemoteAddr(),
|
||||||
|
|
||||||
user: h.user,
|
user: h.user,
|
||||||
lock: make(chan struct{}, 1),
|
|
||||||
})
|
})
|
||||||
return true, nil
|
return true, nil
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -28,22 +28,3 @@ func (v *SocketConfig) ParseTFOValue() int {
|
|||||||
}
|
}
|
||||||
return tfo
|
return tfo
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dial should fail on bind errors, return this to indicate such errors.
|
|
||||||
type BindError struct {
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *BindError) Unwrap() error {
|
|
||||||
return e.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *BindError) Error() string {
|
|
||||||
return "failed to bind to interface: " + e.err.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBindError(err error) *BindError {
|
|
||||||
return &BindError{
|
|
||||||
err: err,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -136,15 +136,15 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
|
|||||||
if config.Interface != "" {
|
if config.Interface != "" {
|
||||||
iface, err := net.InterfaceByName(config.Interface)
|
iface, err := net.InterfaceByName(config.Interface)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return NewBindError(errors.New("failed to get interface ", config.Interface).Base(err))
|
return errors.New("failed to get interface ", config.Interface).Base(err)
|
||||||
}
|
}
|
||||||
if network == "tcp6" || network == "udp6" {
|
if network == "tcp6" || network == "udp6" {
|
||||||
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, iface.Index); err != nil {
|
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, iface.Index); err != nil {
|
||||||
return NewBindError(errors.New("failed to set IPV6_BOUND_IF").Base(err))
|
return errors.New("failed to set IPV6_BOUND_IF").Base(err)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, iface.Index); err != nil {
|
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, iface.Index); err != nil {
|
||||||
return NewBindError(errors.New("failed to set IP_BOUND_IF").Base(err))
|
return errors.New("failed to set IP_BOUND_IF").Base(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
|
|||||||
|
|
||||||
if config.Interface != "" {
|
if config.Interface != "" {
|
||||||
if err := syscall.BindToDevice(int(fd), config.Interface); err != nil {
|
if err := syscall.BindToDevice(int(fd), config.Interface); err != nil {
|
||||||
return NewBindError(errors.New("failed to set Interface").Base(err))
|
return errors.New("failed to set Interface").Base(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
|
|||||||
if config.Interface != "" {
|
if config.Interface != "" {
|
||||||
inf, err := net.InterfaceByName(config.Interface)
|
inf, err := net.InterfaceByName(config.Interface)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return NewBindError(errors.New("failed to find the interface").Base(err))
|
return errors.New("failed to find the interface").Base(err)
|
||||||
}
|
}
|
||||||
// easy way to check if the address is ipv4
|
// easy way to check if the address is ipv4
|
||||||
isV4 := strings.Contains(address, ".")
|
isV4 := strings.Contains(address, ".")
|
||||||
@@ -47,20 +47,20 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
|
|||||||
binary.BigEndian.PutUint32(bytes[:], uint32(inf.Index))
|
binary.BigEndian.PutUint32(bytes[:], uint32(inf.Index))
|
||||||
idx := *(*uint32)(unsafe.Pointer(&bytes[0]))
|
idx := *(*uint32)(unsafe.Pointer(&bytes[0]))
|
||||||
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, IP_UNICAST_IF, int(idx)); err != nil {
|
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, IP_UNICAST_IF, int(idx)); err != nil {
|
||||||
return NewBindError(errors.New("failed to set IP_UNICAST_IF").Base(err))
|
return errors.New("failed to set IP_UNICAST_IF").Base(err)
|
||||||
}
|
}
|
||||||
if ip := net.ParseIP(host); ip != nil && ip.IsMulticast() && isUDPSocket(network) {
|
if ip := net.ParseIP(host); ip != nil && ip.IsMulticast() && isUDPSocket(network) {
|
||||||
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, syscall.IP_MULTICAST_IF, int(idx)); err != nil {
|
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, syscall.IP_MULTICAST_IF, int(idx)); err != nil {
|
||||||
return NewBindError(errors.New("failed to set IP_MULTICAST_IF").Base(err))
|
return errors.New("failed to set IP_MULTICAST_IF").Base(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, IPV6_UNICAST_IF, inf.Index); err != nil {
|
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, IPV6_UNICAST_IF, inf.Index); err != nil {
|
||||||
return NewBindError(errors.New("failed to set IPV6_UNICAST_IF").Base(err))
|
return errors.New("failed to set IPV6_UNICAST_IF").Base(err)
|
||||||
}
|
}
|
||||||
if ip := net.ParseIP(host); ip != nil && ip.IsMulticast() && isUDPSocket(network) {
|
if ip := net.ParseIP(host); ip != nil && ip.IsMulticast() && isUDPSocket(network) {
|
||||||
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, syscall.IPV6_MULTICAST_IF, inf.Index); err != nil {
|
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, syscall.IPV6_MULTICAST_IF, inf.Index); err != nil {
|
||||||
return NewBindError(errors.New("failed to set IPV6_MULTICAST_IF").Base(err))
|
return errors.New("failed to set IPV6_MULTICAST_IF").Base(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,27 +68,19 @@ func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest ne
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
var lc net.ListenConfig
|
var lc net.ListenConfig
|
||||||
if sockopt != nil || len(Controllers) > 0 {
|
|
||||||
lc.Control = func(network, address string, c syscall.RawConn) error {
|
lc.Control = func(network, address string, c syscall.RawConn) error {
|
||||||
for _, ctl := range Controllers {
|
for _, ctl := range Controllers {
|
||||||
if err := ctl(network, address, c); err != nil {
|
if err := ctl(network, address, c); err != nil {
|
||||||
return errors.New("failed to apply external controller").Base(err)
|
errors.LogInfoInner(ctx, err, "failed to apply external controller")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return c.Control(func(fd uintptr) {
|
||||||
if sockopt != nil {
|
if sockopt != nil {
|
||||||
var sockErr, controlErr error
|
if err := applyOutboundSocketOptions(network, destAddr.String(), fd, sockopt); err != nil {
|
||||||
controlErr = c.Control(func(fd uintptr) {
|
errors.LogInfo(ctx, err, "failed to apply socket options")
|
||||||
if sockErr = applyOutboundSocketOptions(network, destAddr.String(), fd, sockopt); sockErr != nil {
|
}
|
||||||
errors.LogInfoInner(ctx, sockErr, "failed to apply socket options")
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
if _, ok := sockErr.(*BindError); ok {
|
|
||||||
return sockErr
|
|
||||||
}
|
|
||||||
return controlErr
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
packetConn, err := lc.ListenPacket(ctx, srcAddr.Network(), srcAddr.String())
|
packetConn, err := lc.ListenPacket(ctx, srcAddr.Network(), srcAddr.String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -136,22 +128,16 @@ func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest ne
|
|||||||
dialer.Control = func(network, address string, c syscall.RawConn) error {
|
dialer.Control = func(network, address string, c syscall.RawConn) error {
|
||||||
for _, ctl := range Controllers {
|
for _, ctl := range Controllers {
|
||||||
if err := ctl(network, address, c); err != nil {
|
if err := ctl(network, address, c); err != nil {
|
||||||
return errors.New("failed to apply external controller").Base(err)
|
errors.LogInfoInner(ctx, err, "failed to apply external controller")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return c.Control(func(fd uintptr) {
|
||||||
if sockopt != nil {
|
if sockopt != nil {
|
||||||
var sockErr, controlErr error
|
if err := applyOutboundSocketOptions(network, address, fd, sockopt); err != nil {
|
||||||
controlErr = c.Control(func(fd uintptr) {
|
errors.LogInfoInner(ctx, err, "failed to apply socket options")
|
||||||
if sockErr = applyOutboundSocketOptions(network, address, fd, sockopt); sockErr != nil {
|
}
|
||||||
errors.LogInfoInner(ctx, sockErr, "failed to apply socket options")
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
if _, ok := sockErr.(*BindError); ok {
|
|
||||||
return sockErr
|
|
||||||
}
|
|
||||||
return controlErr
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,124 +2,44 @@ package xdrive
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"io"
|
gotls "crypto/tls"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/net"
|
"github.com/xtls/xray-core/common/net"
|
||||||
"github.com/xtls/xray-core/transport/internet"
|
"github.com/xtls/xray-core/transport/internet"
|
||||||
|
"github.com/xtls/xray-core/transport/internet/reality"
|
||||||
"github.com/xtls/xray-core/transport/internet/tls"
|
"github.com/xtls/xray-core/transport/internet/tls"
|
||||||
|
"golang.org/x/net/http2"
|
||||||
)
|
)
|
||||||
|
|
||||||
var errStalled = errors.New("the request made no progress")
|
|
||||||
|
|
||||||
type serviceTransport struct {
|
type serviceTransport struct {
|
||||||
plain http.RoundTripper
|
plain http.RoundTripper
|
||||||
secure http.RoundTripper
|
secure http.RoundTripper
|
||||||
stall time.Duration
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// RoundTrip ends a request that stands still for t.stall, with no answer that
|
|
||||||
// long after its body went out or no byte of either body, but not one that just
|
|
||||||
// runs long: a large object on a slow link takes minutes and is fine as long as
|
|
||||||
// its bytes move
|
|
||||||
func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||||
next := t.plain
|
|
||||||
if r.URL.Scheme == "https" {
|
if r.URL.Scheme == "https" {
|
||||||
next = t.secure
|
return t.secure.RoundTrip(r)
|
||||||
|
}
|
||||||
|
return t.plain.RoundTrip(r)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithCancelCause(r.Context())
|
func newServiceClient(streamSettings *internet.MemoryStreamConfig, timeout time.Duration, maxConns int) *http.Client {
|
||||||
timer := time.AfterFunc(t.stall, func() { cancel(errStalled) })
|
|
||||||
alive := func() { timer.Reset(t.stall) }
|
|
||||||
end := func() {
|
|
||||||
timer.Stop()
|
|
||||||
cancel(nil)
|
|
||||||
}
|
|
||||||
r = r.WithContext(ctx)
|
|
||||||
if r.Body != nil && r.Body != http.NoBody {
|
|
||||||
r.Body = &progressBody{ReadCloser: r.Body, alive: alive}
|
|
||||||
}
|
|
||||||
// a body sent again by the transport itself, after a GOAWAY or on a reused
|
|
||||||
// connection that failed, moves just the same
|
|
||||||
if getBody := r.GetBody; getBody != nil {
|
|
||||||
r.GetBody = func() (io.ReadCloser, error) {
|
|
||||||
body, err := getBody()
|
|
||||||
if err != nil || body == http.NoBody {
|
|
||||||
return body, err
|
|
||||||
}
|
|
||||||
return &progressBody{ReadCloser: body, alive: alive}, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := next.RoundTrip(r)
|
|
||||||
if err != nil {
|
|
||||||
err = stalled(ctx, err)
|
|
||||||
end()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
alive()
|
|
||||||
resp.Body = &progressBody{ReadCloser: resp.Body, alive: alive, end: end, ctx: ctx}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// stalled returns errStalled for an error that the stall gave, which http2 reports
|
|
||||||
// as a plain cancel
|
|
||||||
func stalled(ctx context.Context, err error) error {
|
|
||||||
if context.Cause(ctx) == errStalled {
|
|
||||||
return errStalled
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
type progressBody struct {
|
|
||||||
io.ReadCloser
|
|
||||||
alive func()
|
|
||||||
end func()
|
|
||||||
// ctx is that of the request, for the body of its response
|
|
||||||
ctx context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *progressBody) Read(p []byte) (int, error) {
|
|
||||||
// http2 reads a request body up to 512 KiB at a time and sends it all before
|
|
||||||
// the next read, which on a slow link could look like no progress
|
|
||||||
n, err := b.ReadCloser.Read(p[:min(len(p), 16<<10)])
|
|
||||||
if n > 0 {
|
|
||||||
b.alive()
|
|
||||||
}
|
|
||||||
if err != nil && err != io.EOF && b.ctx != nil {
|
|
||||||
err = stalled(b.ctx, err)
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *progressBody) Close() error {
|
|
||||||
err := b.ReadCloser.Close()
|
|
||||||
if b.end != nil {
|
|
||||||
b.end()
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// newServiceClient returns a client whose requests end after stall without
|
|
||||||
// progress, see serviceTransport.RoundTrip
|
|
||||||
func newServiceClient(streamSettings *internet.MemoryStreamConfig, stall time.Duration, maxConns int) *http.Client {
|
|
||||||
var (
|
var (
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
|
realityConfig *reality.Config
|
||||||
sockopt *internet.SocketConfig
|
sockopt *internet.SocketConfig
|
||||||
fronting *net.Destination
|
fronting *net.Destination
|
||||||
)
|
)
|
||||||
if streamSettings != nil {
|
if streamSettings != nil {
|
||||||
tlsConfig = tls.ConfigFromStreamSettings(streamSettings)
|
tlsConfig = tls.ConfigFromStreamSettings(streamSettings)
|
||||||
|
realityConfig = reality.ConfigFromStreamSettings(streamSettings)
|
||||||
sockopt = streamSettings.SocketSettings
|
sockopt = streamSettings.SocketSettings
|
||||||
fronting = streamSettings.Destination
|
fronting = streamSettings.Destination
|
||||||
}
|
}
|
||||||
if tlsConfig == nil {
|
overHTTP2 := allowsHTTP2(tlsConfig, realityConfig)
|
||||||
tlsConfig = &tls.Config{}
|
|
||||||
}
|
|
||||||
fingerprint := tls.GetFingerprint(tlsConfig.Fingerprint)
|
|
||||||
|
|
||||||
dial := func(ctx context.Context, addr string) (net.Conn, net.Destination, error) {
|
dial := func(ctx context.Context, addr string) (net.Conn, net.Destination, error) {
|
||||||
host, err := net.ParseDestination("tcp:" + addr)
|
host, err := net.ParseDestination("tcp:" + addr)
|
||||||
@@ -152,40 +72,58 @@ func newServiceClient(streamSettings *internet.MemoryStreamConfig, stall time.Du
|
|||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// http.Transport picks h2 or h1 by the ALPN in the ConnectionState of the conn
|
dialTLS := func(ctx context.Context, addr string) (net.Conn, error) {
|
||||||
dialTLS := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
||||||
conn, host, err := dial(ctx, addr)
|
conn, host, err := dial(ctx, addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
gotlsConfig := tlsConfig.GetTLSConfig(tls.WithDestination(host))
|
if realityConfig != nil {
|
||||||
var tlsConn net.Conn
|
return reality.UClient(conn, realityConfig, ctx, host)
|
||||||
if fingerprint == nil {
|
|
||||||
tlsConn = tls.Client(conn, gotlsConfig)
|
|
||||||
} else {
|
|
||||||
tlsConn = tls.UClient(conn, gotlsConfig, fingerprint)
|
|
||||||
}
|
}
|
||||||
// the dial outlives the request that started it, and a handshake that hangs
|
|
||||||
// would keep the one connection of the host to itself
|
gotlsConfig := &gotls.Config{ServerName: host.Address.String()}
|
||||||
ctx, cancel := context.WithTimeout(ctx, stall)
|
if tlsConfig != nil {
|
||||||
defer cancel()
|
gotlsConfig = tlsConfig.GetTLSConfig(tls.WithDestination(host))
|
||||||
if err := tlsConn.(tls.Interface).HandshakeContext(ctx); err != nil {
|
}
|
||||||
|
if len(gotlsConfig.NextProtos) != 1 {
|
||||||
|
if overHTTP2 {
|
||||||
|
gotlsConfig.NextProtos = []string{"h2"}
|
||||||
|
} else {
|
||||||
|
gotlsConfig.NextProtos = []string{"http/1.1"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if tlsConfig != nil {
|
||||||
|
if fingerprint := tls.GetFingerprint(tlsConfig.Fingerprint); fingerprint != nil {
|
||||||
|
uconn := tls.UClient(conn, gotlsConfig, fingerprint)
|
||||||
|
if err := uconn.(*tls.UConn).HandshakeContext(ctx); err != nil {
|
||||||
conn.Close()
|
conn.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return tlsConn, nil
|
return uconn, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tls.Client(conn, gotlsConfig), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
secure := func(connsPerHost int) *http.Transport {
|
var secure http.RoundTripper
|
||||||
return &http.Transport{
|
if overHTTP2 {
|
||||||
DialTLSContext: dialTLS,
|
secure = &http2.Transport{
|
||||||
ForceAttemptHTTP2: true,
|
DialTLSContext: func(ctx context.Context, network, addr string, cfg *gotls.Config) (net.Conn, error) {
|
||||||
|
return dialTLS(ctx, addr)
|
||||||
|
},
|
||||||
|
IdleConnTimeout: net.ConnIdleTimeout,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
secure = &http.Transport{
|
||||||
|
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
return dialTLS(ctx, addr)
|
||||||
|
},
|
||||||
IdleConnTimeout: net.ConnIdleTimeout,
|
IdleConnTimeout: net.ConnIdleTimeout,
|
||||||
MaxIdleConns: maxConns,
|
MaxIdleConns: maxConns,
|
||||||
MaxIdleConnsPerHost: maxConns,
|
MaxIdleConnsPerHost: maxConns,
|
||||||
MaxConnsPerHost: connsPerHost,
|
MaxConnsPerHost: maxConns,
|
||||||
HTTP2: &http.HTTP2Config{SendPingTimeout: net.ChromeH2KeepAlivePeriod},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,27 +136,18 @@ func newServiceClient(streamSettings *internet.MemoryStreamConfig, stall time.Du
|
|||||||
MaxIdleConnsPerHost: maxConns,
|
MaxIdleConnsPerHost: maxConns,
|
||||||
MaxConnsPerHost: maxConns,
|
MaxConnsPerHost: maxConns,
|
||||||
},
|
},
|
||||||
secure: &secureTransport{h2: secure(1), h1: secure(maxConns)},
|
secure: secure,
|
||||||
stall: stall,
|
|
||||||
},
|
},
|
||||||
|
Timeout: timeout,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// secureTransport keeps a host to one connection, all that h2 needs, as without
|
func allowsHTTP2(tlsConfig *tls.Config, realityConfig *reality.Config) bool {
|
||||||
// a limit parallel requests would each dial their own. A host that answers over
|
if realityConfig != nil {
|
||||||
// h1 moves to a transport with more, since h1 carries one request at a time
|
return true
|
||||||
type secureTransport struct {
|
|
||||||
h2, h1 http.RoundTripper
|
|
||||||
h1Hosts sync.Map
|
|
||||||
}
|
}
|
||||||
|
if tlsConfig == nil {
|
||||||
func (t *secureTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
return false
|
||||||
if _, ok := t.h1Hosts.Load(r.URL.Host); ok {
|
|
||||||
return t.h1.RoundTrip(r)
|
|
||||||
}
|
}
|
||||||
resp, err := t.h2.RoundTrip(r)
|
return len(tlsConfig.NextProtocol) == 1 && tlsConfig.NextProtocol[0] == "h2"
|
||||||
if err == nil && resp.ProtoMajor == 1 {
|
|
||||||
t.h1Hosts.Store(r.URL.Host, true)
|
|
||||||
}
|
|
||||||
return resp, err
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,11 @@
|
|||||||
package xdrive
|
package xdrive
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
gotls "crypto/tls"
|
gotls "crypto/tls"
|
||||||
"encoding/base64"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
|
||||||
"slices"
|
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -106,403 +99,3 @@ func TestServiceSNIOverride(t *testing.T) {
|
|||||||
t.Fatalf("explicit serverName gave SNI %q, want www.google.com", got)
|
t.Fatalf("explicit serverName gave SNI %q, want www.google.com", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// slowReader hands out one byte every gap, the way a body crosses a slow link
|
|
||||||
type slowReader struct {
|
|
||||||
left int
|
|
||||||
gap time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *slowReader) Read(p []byte) (int, error) {
|
|
||||||
if r.left == 0 {
|
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
time.Sleep(r.gap)
|
|
||||||
r.left--
|
|
||||||
p[0] = 'x'
|
|
||||||
return 1, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// a request that keeps moving outlives the stall limit many times over, one
|
|
||||||
// that stands still does not get much past it
|
|
||||||
func TestServiceClientEndsOnlyStalledRequests(t *testing.T) {
|
|
||||||
const stall = 200 * time.Millisecond
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
io.Copy(io.Discard, r.Body)
|
|
||||||
switch r.URL.Path {
|
|
||||||
case "/slow":
|
|
||||||
for i := 0; i < 20; i++ {
|
|
||||||
w.Write([]byte("x"))
|
|
||||||
w.(http.Flusher).Flush()
|
|
||||||
time.Sleep(stall / 4)
|
|
||||||
}
|
|
||||||
case "/stuck":
|
|
||||||
w.Write([]byte("x"))
|
|
||||||
w.(http.Flusher).Flush()
|
|
||||||
time.Sleep(5 * stall)
|
|
||||||
case "/silent":
|
|
||||||
time.Sleep(5 * stall)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
client := newServiceClient(&internet.MemoryStreamConfig{}, stall, 8)
|
|
||||||
|
|
||||||
fetch := func(path string, body io.Reader) (int, error) {
|
|
||||||
req, err := http.NewRequest(http.MethodPost, server.URL+path, body)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
got, err := io.ReadAll(resp.Body)
|
|
||||||
return len(got), err
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := fetch("/", &slowReader{left: 20, gap: stall / 4}); err != nil {
|
|
||||||
t.Errorf("a slow upload failed: %v", err)
|
|
||||||
}
|
|
||||||
if n, err := fetch("/slow", nil); err != nil || n != 20 {
|
|
||||||
t.Errorf("a slow download gave %d bytes, %v", n, err)
|
|
||||||
}
|
|
||||||
for _, path := range []string{"/stuck", "/silent"} {
|
|
||||||
start := time.Now()
|
|
||||||
_, err := fetch(path, nil)
|
|
||||||
if !errors.Is(err, errStalled) {
|
|
||||||
t.Errorf("%s gave %v, want %v", path, err, errStalled)
|
|
||||||
}
|
|
||||||
if took := time.Since(start); took > 4*stall {
|
|
||||||
t.Errorf("%s took %v to give up", path, took)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// a body that the transport sends again by itself keeps the request going too
|
|
||||||
replay := &serviceTransport{stall: stall, plain: roundTrip(func(r *http.Request) (*http.Response, error) {
|
|
||||||
body, err := r.GetBody()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for b := make([]byte, 1); ; time.Sleep(stall / 4) {
|
|
||||||
if _, err := body.Read(b); err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := context.Cause(r.Context()); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil
|
|
||||||
})}
|
|
||||||
req, err := http.NewRequest(http.MethodPost, "http://drive/", bytes.NewReader(make([]byte, 20)))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if resp, err := replay.RoundTrip(req); err != nil {
|
|
||||||
t.Errorf("a body sent again failed: %v", err)
|
|
||||||
} else {
|
|
||||||
resp.Body.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// over TLS a request that stands still ends the same way, and says so, on h2
|
|
||||||
// as on h1
|
|
||||||
func TestServiceClientStallOverTLS(t *testing.T) {
|
|
||||||
const stall = 200 * time.Millisecond
|
|
||||||
for _, protos := range [][]string{chromeALPN, {"http/1.1"}} {
|
|
||||||
server := newTLSServer(t, &gotls.Config{NextProtos: protos}, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.URL.Path == "/stuck" {
|
|
||||||
w.Write([]byte("x"))
|
|
||||||
w.(http.Flusher).Flush()
|
|
||||||
}
|
|
||||||
time.Sleep(5 * stall)
|
|
||||||
})
|
|
||||||
client := newServiceClient(server.settings(&tls.Config{}), stall, 8)
|
|
||||||
|
|
||||||
for _, path := range []string{"/stuck", "/silent"} {
|
|
||||||
start := time.Now()
|
|
||||||
resp, err := client.Get(server.URL + path)
|
|
||||||
if err == nil {
|
|
||||||
if resp.Proto != picked(protos) {
|
|
||||||
t.Fatalf("%s went over %s", path, resp.Proto)
|
|
||||||
}
|
|
||||||
_, err = io.ReadAll(resp.Body)
|
|
||||||
resp.Body.Close()
|
|
||||||
}
|
|
||||||
if !errors.Is(err, errStalled) {
|
|
||||||
t.Errorf("server %v: %s gave %v, want %v", protos, path, err, errStalled)
|
|
||||||
}
|
|
||||||
if took := time.Since(start); took > 4*stall {
|
|
||||||
t.Errorf("server %v: %s took %v to give up", protos, path, took)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// tlsServer is a TLS server that keeps the last hello it got and counts its
|
|
||||||
// connections
|
|
||||||
type tlsServer struct {
|
|
||||||
*httptest.Server
|
|
||||||
mu sync.Mutex
|
|
||||||
hello *gotls.ClientHelloInfo
|
|
||||||
conns atomic.Int32
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTLSServer(t *testing.T, config *gotls.Config, handler http.HandlerFunc) *tlsServer {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
s := &tlsServer{Server: httptest.NewUnstartedServer(handler)}
|
|
||||||
config.GetConfigForClient = func(hello *gotls.ClientHelloInfo) (*gotls.Config, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
s.hello = hello
|
|
||||||
s.mu.Unlock()
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
s.TLS = config
|
|
||||||
s.Config.ConnState = func(_ net.Conn, state http.ConnState) {
|
|
||||||
if state == http.StateNew {
|
|
||||||
s.conns.Add(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s.StartTLS()
|
|
||||||
t.Cleanup(s.Close)
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *tlsServer) lastHello() *gotls.ClientHelloInfo {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
return s.hello
|
|
||||||
}
|
|
||||||
|
|
||||||
// settings pins the certificate of the server in config
|
|
||||||
func (s *tlsServer) settings(config *tls.Config) *internet.MemoryStreamConfig {
|
|
||||||
config.PinnedPeerCertSha256 = [][]byte{tls.GenerateCertHash(s.Certificate())}
|
|
||||||
return &internet.MemoryStreamConfig{ProtocolName: protocolName, SecuritySettings: config}
|
|
||||||
}
|
|
||||||
|
|
||||||
// picked is the protocol a server with ALPN protos answers a Chrome hello with
|
|
||||||
func picked(protos []string) string {
|
|
||||||
if protos[0] == "h2" {
|
|
||||||
return "HTTP/2.0"
|
|
||||||
}
|
|
||||||
return "HTTP/1.1"
|
|
||||||
}
|
|
||||||
|
|
||||||
var chromeALPN = []string{"h2", "http/1.1"}
|
|
||||||
|
|
||||||
// the hello offers the ALPN of the fingerprint whatever "alpn" says, or with Go
|
|
||||||
// TLS that of the config, h2 and http/1.1 by default, and the client speaks what
|
|
||||||
// the server picks from it
|
|
||||||
func TestServiceClientSpeaksWhatServerPicks(t *testing.T) {
|
|
||||||
for _, protos := range [][]string{chromeALPN, {"http/1.1"}} {
|
|
||||||
server := newTLSServer(t, &gotls.Config{NextProtos: protos}, func(w http.ResponseWriter, r *http.Request) {})
|
|
||||||
for _, config := range []*tls.Config{{}, {NextProtocol: []string{"h2"}}, {NextProtocol: []string{"http/1.1"}}, {Fingerprint: "unsafe"}} {
|
|
||||||
client := newServiceClient(server.settings(config), 5*time.Second, 8)
|
|
||||||
resp, err := client.Get(server.URL)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("server %v, alpn %v, fingerprint %q: %v", protos, config.NextProtocol, config.Fingerprint, err)
|
|
||||||
}
|
|
||||||
resp.Body.Close()
|
|
||||||
if resp.Proto != picked(protos) {
|
|
||||||
t.Errorf("server %v, alpn %v, fingerprint %q: went over %s", protos, config.NextProtocol, config.Fingerprint, resp.Proto)
|
|
||||||
}
|
|
||||||
if offered := server.lastHello().SupportedProtos; !slices.Equal(offered, chromeALPN) {
|
|
||||||
t.Errorf("server %v, alpn %v, fingerprint %q: the hello offered %v, want %v", protos, config.NextProtocol, config.Fingerprint, offered, chromeALPN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// with no tlsSettings the hello is that of Chrome too, which unlike Go TLS
|
|
||||||
// offers certificate compression
|
|
||||||
func TestServiceClientDefaultsToChrome(t *testing.T) {
|
|
||||||
server := newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, func(w http.ResponseWriter, r *http.Request) {})
|
|
||||||
client := newServiceClient(&internet.MemoryStreamConfig{}, 5*time.Second, 8)
|
|
||||||
// the test certificate is not trusted, the hello is all that is needed
|
|
||||||
if resp, err := client.Get(server.URL); err == nil {
|
|
||||||
resp.Body.Close()
|
|
||||||
}
|
|
||||||
hello := server.lastHello()
|
|
||||||
if hello == nil {
|
|
||||||
t.Fatal("no hello")
|
|
||||||
}
|
|
||||||
if !slices.Equal(hello.SupportedProtos, chromeALPN) || !slices.Contains(hello.Extensions, 27) {
|
|
||||||
t.Errorf("the hello offered %v with extensions %v, not like Chrome", hello.SupportedProtos, hello.Extensions)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// parallel requests share one h2 connection instead of dialing one each, the
|
|
||||||
// first ones as the later ones, and next to a host that answers over h1
|
|
||||||
func TestServiceClientOneConnection(t *testing.T) {
|
|
||||||
server := newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
time.Sleep(50 * time.Millisecond)
|
|
||||||
})
|
|
||||||
h1 := newTLSServer(t, &gotls.Config{NextProtos: []string{"http/1.1"}}, func(w http.ResponseWriter, r *http.Request) {})
|
|
||||||
client := newServiceClient(server.settings(&tls.Config{}), 5*time.Second, driveMaxInflight)
|
|
||||||
get := func(url string) {
|
|
||||||
resp, err := client.Get(url)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
resp.Body.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := range 2 {
|
|
||||||
if i == 1 {
|
|
||||||
get(h1.URL)
|
|
||||||
}
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for range driveMaxInflight {
|
|
||||||
wg.Go(func() { get(server.URL) })
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
if n := server.conns.Load(); n != 1 {
|
|
||||||
t.Errorf("round %d: %d parallel requests took %d connections", i, driveMaxInflight, n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// in the format of xray tls ech, for public name public.example
|
|
||||||
const (
|
|
||||||
testECHConfigList = "AEH+DQA9AAAgACBziE85FLxJySxZAPRHs8CDCbuz1h76I9pLhctC/kgScAAEAAEAAQAOcHVibGljLmV4YW1wbGUAAA=="
|
|
||||||
testECHServerKeys = "ACD2AjC5yuBQ3430geNDLdIRndloCry/DBb9ZeYp0TmeowBB/g0APQAAIAAgc4hPORS8ScksWQD0R7PAgwm7s9Ye+iPaS4XLQv5IEnAABAABAAEADnB1YmxpYy5leGFtcGxlAAA="
|
|
||||||
)
|
|
||||||
|
|
||||||
// a server that speaks only h1, or gets ALPN http/1.1 inside ECH or from Go TLS,
|
|
||||||
// answers over h1, and after that answer parallel requests get more than one
|
|
||||||
// connection
|
|
||||||
func TestServiceClientHTTP1(t *testing.T) {
|
|
||||||
keys, err := base64.StdEncoding.DecodeString(testECHServerKeys)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
echKeys, err := tls.ConvertToGoECHKeys(keys)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
ech := &tls.Config{ServerName: "example.com", NextProtocol: []string{"http/1.1"}, EchConfigList: testECHConfigList}
|
|
||||||
|
|
||||||
for _, c := range []struct {
|
|
||||||
protos, seen []string
|
|
||||||
config *tls.Config
|
|
||||||
}{
|
|
||||||
{[]string{"http/1.1"}, chromeALPN, &tls.Config{}},
|
|
||||||
{chromeALPN, []string{"http/1.1"}, ech},
|
|
||||||
{chromeALPN, []string{"http/1.1"}, &tls.Config{NextProtocol: []string{"http/1.1"}, Fingerprint: "unsafe"}},
|
|
||||||
} {
|
|
||||||
server := newTLSServer(t, &gotls.Config{NextProtos: c.protos, EncryptedClientHelloKeys: echKeys}, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
time.Sleep(50 * time.Millisecond)
|
|
||||||
})
|
|
||||||
client := newServiceClient(server.settings(c.config), 5*time.Second, 8)
|
|
||||||
get := func() {
|
|
||||||
resp, err := client.Get(server.URL)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
resp.Body.Close()
|
|
||||||
if resp.Proto != "HTTP/1.1" || resp.TLS.ECHAccepted != (c.config.EchConfigList != "") {
|
|
||||||
t.Errorf("server %v, ALPN %v: went over %s, ECH accepted %v", c.protos, c.seen, resp.Proto, resp.TLS.ECHAccepted)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
get()
|
|
||||||
first := server.conns.Load()
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for range 4 {
|
|
||||||
wg.Go(get)
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
if offered := server.lastHello().SupportedProtos; !slices.Equal(offered, c.seen) {
|
|
||||||
t.Errorf("server %v: saw ALPN %v, want %v", c.protos, offered, c.seen)
|
|
||||||
}
|
|
||||||
if n := server.conns.Load() - first; n < 2 {
|
|
||||||
t.Errorf("server %v, ALPN %v: 4 parallel requests over h1 took %d connections", c.protos, c.seen, n)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// without the keys the server gets the outer hello, which offers the ALPN of
|
|
||||||
// Chrome
|
|
||||||
outer := newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, func(w http.ResponseWriter, r *http.Request) {})
|
|
||||||
if resp, err := newServiceClient(outer.settings(ech), 5*time.Second, 8).Get(outer.URL); err == nil {
|
|
||||||
resp.Body.Close()
|
|
||||||
}
|
|
||||||
if hello := outer.lastHello(); hello == nil {
|
|
||||||
t.Error("no outer hello")
|
|
||||||
} else if !slices.Equal(hello.SupportedProtos, chromeALPN) {
|
|
||||||
t.Errorf("the outer hello offered %v, want %v", hello.SupportedProtos, chromeALPN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// muteFirst leaves the first connection it accepts unanswered
|
|
||||||
type muteFirst struct {
|
|
||||||
net.Listener
|
|
||||||
muted net.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *muteFirst) Accept() (net.Conn, error) {
|
|
||||||
if l.muted == nil {
|
|
||||||
conn, err := l.Listener.Accept()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
l.muted = conn
|
|
||||||
}
|
|
||||||
return l.Listener.Accept()
|
|
||||||
}
|
|
||||||
|
|
||||||
// a handshake that hangs ends after stall, and does not keep the host from
|
|
||||||
// getting another connection
|
|
||||||
func TestServiceClientHungHandshake(t *testing.T) {
|
|
||||||
const stall = 200 * time.Millisecond
|
|
||||||
for _, fingerprint := range []string{"", "unsafe"} {
|
|
||||||
server := &tlsServer{Server: httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))}
|
|
||||||
server.Listener = &muteFirst{Listener: server.Listener}
|
|
||||||
server.StartTLS()
|
|
||||||
t.Cleanup(server.Close)
|
|
||||||
client := newServiceClient(server.settings(&tls.Config{Fingerprint: fingerprint}), stall, 8)
|
|
||||||
|
|
||||||
if _, err := client.Get(server.URL); err == nil {
|
|
||||||
t.Fatalf("fingerprint %q: a request got through a handshake that hung", fingerprint)
|
|
||||||
}
|
|
||||||
for i := range 2 {
|
|
||||||
resp, err := client.Get(server.URL)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("fingerprint %q: request %d after a handshake that hung: %v", fingerprint, i, err)
|
|
||||||
}
|
|
||||||
resp.Body.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// a connection whose handshake failed is closed, not left to the garbage
|
|
||||||
// collector
|
|
||||||
func TestServiceClientClosesFailedHandshake(t *testing.T) {
|
|
||||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer ln.Close()
|
|
||||||
|
|
||||||
for _, fingerprint := range []string{"", "unsafe"} {
|
|
||||||
settings := &internet.MemoryStreamConfig{ProtocolName: protocolName, SecuritySettings: &tls.Config{Fingerprint: fingerprint}}
|
|
||||||
go newServiceClient(settings, 5*time.Second, 8).Get("https://" + ln.Addr().String())
|
|
||||||
conn, err := ln.Accept()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
// not TLS, so the handshake fails at once
|
|
||||||
conn.Write([]byte("HTTP/1.1 400 Bad Request\r\n\r\n"))
|
|
||||||
conn.SetReadDeadline(time.Now().Add(2 * time.Second))
|
|
||||||
if _, err := io.Copy(io.Discard, conn); err != nil {
|
|
||||||
t.Errorf("fingerprint %q: the client left the connection open: %v", fingerprint, err)
|
|
||||||
}
|
|
||||||
conn.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type roundTrip func(*http.Request) (*http.Response, error)
|
|
||||||
|
|
||||||
func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ const (
|
|||||||
driveMaxAttempts = 8
|
driveMaxAttempts = 8
|
||||||
driveMaxInflight = 32
|
driveMaxInflight = 32
|
||||||
driveInlineLimit = 12000
|
driveInlineLimit = 12000
|
||||||
// driveTimeout ends a request that makes no progress for that long
|
|
||||||
driveTimeout = 60 * time.Second
|
driveTimeout = 60 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -154,7 +153,7 @@ func jitter(backoff time.Duration) time.Duration {
|
|||||||
if half <= 0 {
|
if half <= 0 {
|
||||||
return backoff
|
return backoff
|
||||||
}
|
}
|
||||||
return half + time.Duration(dice.RollInt63n(int64(half)))
|
return half + time.Duration(dice.Roll(int(half)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func rateLimited(payload []byte) bool {
|
func rateLimited(payload []byte) bool {
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ func liveDriveConfig(t *testing.T) *Config {
|
|||||||
|
|
||||||
config := &Config{
|
config := &Config{
|
||||||
RemoteFolder: secrets.Folder,
|
RemoteFolder: secrets.Folder,
|
||||||
Service: "google-drive",
|
Service: "Google Drive",
|
||||||
Secrets: []string{secrets.ClientID, secrets.ClientSecret, secrets.RefreshToken},
|
Secrets: []string{secrets.ClientID, secrets.ClientSecret, secrets.RefreshToken},
|
||||||
SegmentBytes: 256 * 1024,
|
SegmentBytes: 256 * 1024,
|
||||||
FlushIntervalMs: 100,
|
FlushIntervalMs: 100,
|
||||||
|
|||||||
@@ -317,7 +317,7 @@ func driveSettings() *internet.MemoryStreamConfig {
|
|||||||
ProtocolName: protocolName,
|
ProtocolName: protocolName,
|
||||||
ProtocolSettings: &Config{
|
ProtocolSettings: &Config{
|
||||||
RemoteFolder: "folder-id",
|
RemoteFolder: "folder-id",
|
||||||
Service: "google-drive",
|
Service: "Google Drive",
|
||||||
Secrets: []string{"client", "secret", "refresh"},
|
Secrets: []string{"client", "secret", "refresh"},
|
||||||
FlushIntervalMs: 5,
|
FlushIntervalMs: 5,
|
||||||
PollIntervalMs: 5,
|
PollIntervalMs: 5,
|
||||||
@@ -564,16 +564,6 @@ func TestDriveSharedClient(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDriveOldServiceName(t *testing.T) {
|
|
||||||
newFakeDrive(t)
|
|
||||||
|
|
||||||
settings := driveSettings()
|
|
||||||
settings.ProtocolSettings.(*Config).Service = "Google Drive"
|
|
||||||
if _, err := newStorage(settings); err != nil {
|
|
||||||
t.Fatalf("newStorage: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDriveInlineListing(t *testing.T) {
|
func TestDriveInlineListing(t *testing.T) {
|
||||||
drive := newFakeDrive(t)
|
drive := newFakeDrive(t)
|
||||||
storage := newDriveBackend(t)
|
storage := newDriveBackend(t)
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ func newStorage(streamSettings *internet.MemoryStreamConfig) (Storage, error) {
|
|||||||
switch config.Service {
|
switch config.Service {
|
||||||
case "local":
|
case "local":
|
||||||
return newLocalStorage(config.RemoteFolder)
|
return newLocalStorage(config.RemoteFolder)
|
||||||
case "google-drive", "Google Drive":
|
case "Google Drive":
|
||||||
return sharedStorage(streamSettings, config, func() (Storage, error) {
|
return sharedStorage(streamSettings, config, func() (Storage, error) {
|
||||||
return newDriveStorage(streamSettings, config)
|
return newDriveStorage(streamSettings, config)
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user