mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-25 19:11:45 +00:00
Compare commits
6
Commits
findprocess
...
xdrive
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
328167bb1e | ||
|
|
499a9e1df5 | ||
|
|
b56ffef338 | ||
|
|
862e59a2f2 | ||
|
|
35805f9377 | ||
|
|
5d8b20239f |
@@ -7,7 +7,6 @@ import (
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/core"
|
||||
@@ -184,9 +183,6 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound
|
||||
Mark: streamSettings.SocketSettings.Mark,
|
||||
})
|
||||
}
|
||||
if streamSettings != nil && (streamSettings.ProtocolName == "splithttp" || streamSettings.ProtocolName == "masque") {
|
||||
ctx = session.ContextWithAllowedNetwork(ctx, net.Network_UDP)
|
||||
}
|
||||
|
||||
return NewAlwaysOnInboundHandler(ctx, tag, receiverSettings, proxySettings)
|
||||
}
|
||||
|
||||
@@ -71,7 +71,6 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
|
||||
}
|
||||
common.CloseIfExists(t.checkTask)
|
||||
t.checkTask = newCheckTask
|
||||
t.Update()
|
||||
common.Must(newCheckTask.Start())
|
||||
}
|
||||
|
||||
|
||||
@@ -58,15 +58,11 @@ func (t *Periodic) Start() error {
|
||||
return nil
|
||||
}
|
||||
t.running = true
|
||||
t.timer = time.AfterFunc(t.Interval, func() {
|
||||
t.checkedExecute()
|
||||
})
|
||||
t.access.Unlock()
|
||||
|
||||
if err := t.checkedExecute(); err != nil {
|
||||
t.access.Lock()
|
||||
t.running = false
|
||||
t.access.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 5)
|
||||
common.Must(task.Close())
|
||||
if value != 3 {
|
||||
t.Fatal("expected 3, but got ", value)
|
||||
if value != 2 {
|
||||
t.Fatal("expected 2, but got ", value)
|
||||
}
|
||||
time.Sleep(time.Second * 4)
|
||||
if value != 3 {
|
||||
t.Fatal("expected 3, but got ", value)
|
||||
if value != 2 {
|
||||
t.Fatal("expected 2, but got ", value)
|
||||
}
|
||||
common.Must(task.Start())
|
||||
time.Sleep(time.Second * 3)
|
||||
if value != 5 {
|
||||
t.Fatal("Expected 5, but ", value)
|
||||
if value != 3 {
|
||||
t.Fatal("Expected 3, but ", value)
|
||||
}
|
||||
common.Must(task.Close())
|
||||
}
|
||||
|
||||
@@ -159,6 +159,7 @@ func TestTunConfigGUID(t *testing.T) {
|
||||
for _, guid := range []string{
|
||||
"xray0",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
||||
"6ba7b8109-dad-11d1-80b4-00c04fd430c8", // the right length, a hyphen out of place
|
||||
"6ba7b8109dad11d180b400c04fd430c8",
|
||||
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
||||
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||
|
||||
+6
-1
@@ -367,10 +367,15 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
|
||||
}
|
||||
|
||||
if senderSettings.StreamSettings != nil && senderSettings.StreamSettings.ProtocolName == "splithttp" {
|
||||
if v, ok := ts.(*outbound.Config); ok && v.Multiplex != nil && v.Multiplex.Concurrency != 0 {
|
||||
errors.LogWarning(context.Background(), `ATTENTION: Using VLESS Multiplex over XHTTP XMUX`)
|
||||
}
|
||||
}
|
||||
if err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
)
|
||||
|
||||
// wait to drain all the possible incoming UDP data
|
||||
// because re-established QUIC UDP may bypass the sniffer
|
||||
func DropUDP(ctx context.Context, reader buf.Reader) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
||||
cancel()
|
||||
}, time.Duration(30+rand.N(60))*time.Second)
|
||||
context.AfterFunc(ctx, func() {
|
||||
common.Interrupt(reader)
|
||||
})
|
||||
buf.Copy(reader, buf.Discard, buf.UpdateActivity(timer))
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
@@ -49,3 +50,18 @@ func (updater *InterfaceUpdater) Update() {
|
||||
updater.iface = got
|
||||
errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index)
|
||||
}
|
||||
|
||||
// ParseGUID parses a canonical textual GUID, as in
|
||||
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
|
||||
// The form is all that is accepted, not the other ones uuid.Parse takes,
|
||||
// such as one without hyphens; the length check is what rules those out.
|
||||
func ParseGUID(s string) ([16]byte, error) {
|
||||
if len(s) != 36 {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
|
||||
}
|
||||
id, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
)
|
||||
|
||||
// ParseGUID parses a canonical textual GUID, as in
|
||||
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
|
||||
// The form is all that is accepted, not the other ones uuid.Parse takes,
|
||||
// such as one without hyphens; the length check is what rules those out.
|
||||
func ParseGUID(s string) ([16]byte, error) {
|
||||
if len(s) != 36 {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
|
||||
}
|
||||
id, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package tun_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/proxy/tun"
|
||||
)
|
||||
|
||||
func TestParseGUID(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
guid string
|
||||
raw [16]byte
|
||||
}{
|
||||
{"00000000-0000-0000-0000-000000000000", [16]byte{}},
|
||||
{"00010203-0405-0607-0809-0a0b0c0d0e0f", [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
|
||||
{"6ba7b810-9dad-11d1-80b4-00c04fd430c8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
|
||||
{"6BA7B810-9DAD-11D1-80B4-00C04FD430C8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
|
||||
{"ffffffff-ffff-ffff-ffff-ffffffffffff", [16]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
|
||||
} {
|
||||
raw, err := tun.ParseGUID(c.guid)
|
||||
if err != nil {
|
||||
t.Errorf("ParseGUID(%q) failed: %v", c.guid, err)
|
||||
continue
|
||||
}
|
||||
if raw != c.raw {
|
||||
t.Errorf("ParseGUID(%q) = %x, want %x", c.guid, raw, c.raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGUIDInvalid(t *testing.T) {
|
||||
for _, guid := range []string{
|
||||
"",
|
||||
" ",
|
||||
"xray0",
|
||||
// right characters, wrong places of the hyphens
|
||||
"6ba7b8109-dad-11d1-80b4-00c04fd430c8",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c88",
|
||||
"6ba7b810-9dad-11d1-80b4_00c04fd430c8",
|
||||
// not hexadecimal
|
||||
"6ba7b81g-9dad-11d1-80b4-00c04fd430c8",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430cg",
|
||||
// forms other than the canonical one
|
||||
"6ba7b8109dad11d180b400c04fd430c8",
|
||||
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
||||
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c8 ",
|
||||
} {
|
||||
if raw, err := tun.ParseGUID(guid); err == nil {
|
||||
t.Errorf("ParseGUID(%q) = %x, want an error", guid, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func TestAdapterGUID(t *testing.T) {
|
||||
// a configured GUID has to be the adapter GUID the text names: the groups
|
||||
// are field values, not the bytes of the text in order
|
||||
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := windows.GUID{
|
||||
Data1: 0x01020304,
|
||||
Data2: 0x0506,
|
||||
Data3: 0x0708,
|
||||
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
|
||||
}
|
||||
if *guid != want {
|
||||
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
|
||||
}
|
||||
// the same struct Windows builds from that text, and the text Windows shows
|
||||
// for it
|
||||
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if *guid != fromText {
|
||||
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
|
||||
}
|
||||
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
|
||||
t.Errorf("adapterGUID = %s, want %s", got, want)
|
||||
}
|
||||
|
||||
// without one, the bytes of the MD5 of the name, as they always were; that
|
||||
// GUID is never read back as text, so its byte order does not matter
|
||||
guid, err = adapterGUID("xray0", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := md5.Sum([]byte("xray0"))
|
||||
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
|
||||
t.Errorf("adapterGUID = %x, want %x", got, sum)
|
||||
}
|
||||
|
||||
if _, err := adapterGUID("xray0", "xray0"); err == nil {
|
||||
t.Error("an invalid guid was accepted")
|
||||
}
|
||||
}
|
||||
@@ -1,390 +0,0 @@
|
||||
//go:build freebsd
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type probeCall struct {
|
||||
inboundTag string
|
||||
source string
|
||||
address string
|
||||
}
|
||||
|
||||
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||
// records how it was called, so tests can assert the probe is representative.
|
||||
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||
t.Helper()
|
||||
original := verifyDNSRouting
|
||||
calls := []probeCall{}
|
||||
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||
calls = append(calls, probeCall{inboundTag, source, address})
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { verifyDNSRouting = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||
// the captured invocations, each as the arguments followed by the stdin in
|
||||
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||
// otherwise the named subcommand fails.
|
||||
func recorder(t *testing.T, failOn string) *[]string {
|
||||
t.Helper()
|
||||
original := resolvconfRunner
|
||||
calls := []string{}
|
||||
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
call := strings.Join(args, " ")
|
||||
if stdin != "" {
|
||||
call += " <" + stdin + ">"
|
||||
}
|
||||
calls = append(calls, call)
|
||||
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
t.Cleanup(func() { resolvconfRunner = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// files replaces the resolver files read by the applied check for the
|
||||
// duration of a test. A path not in the map does not exist.
|
||||
func files(t *testing.T, contents map[string]string) {
|
||||
t.Helper()
|
||||
original := readResolverFile
|
||||
readResolverFile = func(path string) ([]byte, error) {
|
||||
if data, ok := contents[path]; ok {
|
||||
return []byte(data), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
t.Cleanup(func() { readResolverFile = original })
|
||||
}
|
||||
|
||||
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||
// the exclusive one.
|
||||
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||
|
||||
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||
// place.
|
||||
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||
|
||||
func optedInTun() *FreeBSDTun {
|
||||
return &FreeBSDTun{
|
||||
options: &Config{
|
||||
Name: "tun7",
|
||||
Gateway: []string{"192.168.100.1/30"},
|
||||
AutoSystemDnsToGateway: true,
|
||||
},
|
||||
name: "tun7",
|
||||
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||
local: netip.MustParseAddr("192.168.100.2"),
|
||||
}
|
||||
}
|
||||
|
||||
func joined(calls []string) string {
|
||||
return strings.Join(calls, " | ")
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.options.AutoSystemDnsToGateway = false
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != 0 || len(*probes) != 0 {
|
||||
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the option is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||
stubDNSRouting(t, errors.New("no route"))
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the probe fails")
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the probe fails")
|
||||
}
|
||||
}
|
||||
|
||||
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||
// address is the one after the gateway, and the gateway itself has no owner,
|
||||
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||
// and the resolver has to be pointed at the gateway.
|
||||
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*probes) != 1 {
|
||||
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||
}
|
||||
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||
if (*probes)[0] != want {
|
||||
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||
}
|
||||
|
||||
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||
if got := joined(*calls); got != want {
|
||||
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||
// the entry for the interface, but runs no subscriber, so success has to be
|
||||
// confirmed in what the subscribers wrote.
|
||||
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||
}
|
||||
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
before := len(*calls)
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != before {
|
||||
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-a")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when resolvconf -a fails")
|
||||
}
|
||||
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||
t.Error("a failed add leaves nothing to clean up")
|
||||
}
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
// If the removal after a failed check fails too, the entry may still be
|
||||
// installed, so the state has to be remembered rather than silently dropped.
|
||||
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the check fails")
|
||||
}
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal must leave the resolver marked dirty")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// A dirty resolver is retried before anything new is applied.
|
||||
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSDirty = true
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := joined(*calls)
|
||||
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||
t.Errorf("expected the stale removal first, got %q", got)
|
||||
}
|
||||
if t1.systemDNSDirty {
|
||||
t.Error("a successful retry should clear the dirty flag")
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Error("the takeover should proceed once the retry succeeds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("setup failed: %v", err)
|
||||
}
|
||||
*calls = nil
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet should be false after unset")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||
}
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSSet = true
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal during unset must be remembered")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("expected a removal attempt, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||
// them; that is the leak the option exists to close, and it must not pass.
|
||||
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||
// (local_unbound with the libc subscriber left on), not a leak.
|
||||
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||
}
|
||||
}
|
||||
|
||||
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||
})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||
})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||
files(t, map[string]string{})
|
||||
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,11 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/net/route"
|
||||
@@ -148,3 +152,381 @@ func TestDefaultRouteFamilyRejectsShortAddrs(t *testing.T) {
|
||||
t.Fatal("message without addresses must not match")
|
||||
}
|
||||
}
|
||||
|
||||
type probeCall struct {
|
||||
inboundTag string
|
||||
source string
|
||||
address string
|
||||
}
|
||||
|
||||
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||
// records how it was called, so tests can assert the probe is representative.
|
||||
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||
t.Helper()
|
||||
original := verifyDNSRouting
|
||||
calls := []probeCall{}
|
||||
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||
calls = append(calls, probeCall{inboundTag, source, address})
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() { verifyDNSRouting = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||
// the captured invocations, each as the arguments followed by the stdin in
|
||||
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||
// otherwise the named subcommand fails.
|
||||
func recorder(t *testing.T, failOn string) *[]string {
|
||||
t.Helper()
|
||||
original := resolvconfRunner
|
||||
calls := []string{}
|
||||
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||
call := strings.Join(args, " ")
|
||||
if stdin != "" {
|
||||
call += " <" + stdin + ">"
|
||||
}
|
||||
calls = append(calls, call)
|
||||
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
t.Cleanup(func() { resolvconfRunner = original })
|
||||
return &calls
|
||||
}
|
||||
|
||||
// files replaces the resolver files read by the applied check for the
|
||||
// duration of a test. A path not in the map does not exist.
|
||||
func files(t *testing.T, contents map[string]string) {
|
||||
t.Helper()
|
||||
original := readResolverFile
|
||||
readResolverFile = func(path string) ([]byte, error) {
|
||||
if data, ok := contents[path]; ok {
|
||||
return []byte(data), nil
|
||||
}
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
t.Cleanup(func() { readResolverFile = original })
|
||||
}
|
||||
|
||||
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||
// the exclusive one.
|
||||
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||
|
||||
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||
// place.
|
||||
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||
|
||||
func optedInTun() *FreeBSDTun {
|
||||
return &FreeBSDTun{
|
||||
options: &Config{
|
||||
Name: "tun7",
|
||||
Gateway: []string{"192.168.100.1/30"},
|
||||
AutoSystemDnsToGateway: true,
|
||||
},
|
||||
name: "tun7",
|
||||
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||
local: netip.MustParseAddr("192.168.100.2"),
|
||||
}
|
||||
}
|
||||
|
||||
func joined(calls []string) string {
|
||||
return strings.Join(calls, " | ")
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.options.AutoSystemDnsToGateway = false
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != 0 || len(*probes) != 0 {
|
||||
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the option is off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||
stubDNSRouting(t, errors.New("no route"))
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the probe fails")
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the probe fails")
|
||||
}
|
||||
}
|
||||
|
||||
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||
// address is the one after the gateway, and the gateway itself has no owner,
|
||||
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||
// and the resolver has to be pointed at the gateway.
|
||||
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||
probes := stubDNSRouting(t, nil)
|
||||
recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*probes) != 1 {
|
||||
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||
}
|
||||
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||
if (*probes)[0] != want {
|
||||
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||
}
|
||||
|
||||
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||
if got := joined(*calls); got != want {
|
||||
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||
// the entry for the interface, but runs no subscriber, so success has to be
|
||||
// confirmed in what the subscribers wrote.
|
||||
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||
}
|
||||
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
before := len(*calls)
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(*calls) != before {
|
||||
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-a")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when resolvconf -a fails")
|
||||
}
|
||||
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||
t.Error("a failed add leaves nothing to clean up")
|
||||
}
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
// If the removal after a failed check fails too, the entry may still be
|
||||
// installed, so the state has to be remembered rather than silently dropped.
|
||||
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
|
||||
t1 := optedInTun()
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||
t.Fatal("expected an error when the check fails")
|
||||
}
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal must leave the resolver marked dirty")
|
||||
}
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// A dirty resolver is retried before anything new is applied.
|
||||
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSDirty = true
|
||||
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := joined(*calls)
|
||||
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||
t.Errorf("expected the stale removal first, got %q", got)
|
||||
}
|
||||
if t1.systemDNSDirty {
|
||||
t.Error("a successful retry should clear the dirty flag")
|
||||
}
|
||||
if !t1.systemDNSSet {
|
||||
t.Error("the takeover should proceed once the retry succeeds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||
t.Fatalf("setup failed: %v", err)
|
||||
}
|
||||
*calls = nil
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if t1.systemDNSSet {
|
||||
t.Error("systemDNSSet should be false after unset")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||
}
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if len(*calls) != 1 {
|
||||
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||
stubDNSRouting(t, nil)
|
||||
calls := recorder(t, "-d")
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
|
||||
t1 := optedInTun()
|
||||
t1.systemDNSSet = true
|
||||
|
||||
t1.unsetSystemDNS()
|
||||
if !t1.systemDNSDirty {
|
||||
t.Error("a failed removal during unset must be remembered")
|
||||
}
|
||||
if got := joined(*calls); got != "-d tun7" {
|
||||
t.Errorf("expected a removal attempt, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||
// them; that is the leak the option exists to close, and it must not pass.
|
||||
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||
// (local_unbound with the libc subscriber left on), not a leak.
|
||||
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||
}
|
||||
}
|
||||
|
||||
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||
})
|
||||
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||
files(t, map[string]string{
|
||||
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||
})
|
||||
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||
files(t, map[string]string{})
|
||||
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
//go:build linux && !android
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
const (
|
||||
routeTestInboundTag = "tun"
|
||||
routeTestSource = "192.168.100.1"
|
||||
routeTestDNSAddress = "192.168.100.2"
|
||||
)
|
||||
|
||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||
func port53Rule() *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
InboundTag: []string{routeTestInboundTag},
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||
}
|
||||
}
|
||||
|
||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||
// that only matches because the real request carries a source.
|
||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
SourceIp: []*geodata.IPRule{{
|
||||
Value: &geodata.IPRule_Custom{
|
||||
Custom: &geodata.CIDRRule{
|
||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||
},
|
||||
},
|
||||
}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||
}
|
||||
}
|
||||
|
||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||
// running resolver. The instance is placed in the context through the key core
|
||||
// exports for tests.
|
||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||
t.Helper()
|
||||
|
||||
apps := []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||
}
|
||||
if withDNSApp {
|
||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||
}
|
||||
|
||||
instance, err := core.New(&core.Config{
|
||||
App: apps,
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("core.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = instance.Close() })
|
||||
|
||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||
}
|
||||
|
||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||
return []*appdns.NameServer{{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||
Port: 53,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||
// resolves through the system resolver.
|
||||
func localNameServer() *appdns.NameServer {
|
||||
return &appdns.NameServer{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||
Port: 53,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||
// false positive in the takeover decision itself, which is what assertions on
|
||||
// the resolvectl arguments could never catch.
|
||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
withDNSApp bool
|
||||
nameServers []*appdns.NameServer
|
||||
rules []*router.RoutingRule
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "independent upstream reaches the dns outbound",
|
||||
withDNSApp: true,
|
||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no dns section falls back to the system resolver",
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "dns section without name servers falls back too",
|
||||
withDNSApp: true,
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
// An independent upstream is not enough on its own: name servers are
|
||||
// selected per domain, so a local one can still be the one chosen.
|
||||
// The refusal is deliberately domain-agnostic for that reason.
|
||||
name: "a local name server alongside an independent one",
|
||||
withDNSApp: true,
|
||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "a rule on the interface address diverts the real query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "does not handle DNS",
|
||||
},
|
||||
{
|
||||
name: "a rule on another address does not match it",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no rule matches the query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
wantErr: "no route",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||
// carries IPv6 addresses.
|
||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,18 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
appdns "github.com/xtls/xray-core/app/dns"
|
||||
"github.com/xtls/xray-core/app/proxyman"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||
"github.com/xtls/xray-core/app/router"
|
||||
"github.com/xtls/xray-core/common/geodata"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/core"
|
||||
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||
"github.com/xtls/xray-core/proxy/freedom"
|
||||
)
|
||||
|
||||
// testLink returns a minimal netlink.Link whose Attrs().Name is name, so the
|
||||
@@ -443,3 +455,185 @@ func TestBuildResolvectlArgs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
routeTestInboundTag = "tun"
|
||||
routeTestSource = "192.168.100.1"
|
||||
routeTestDNSAddress = "192.168.100.2"
|
||||
)
|
||||
|
||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||
func port53Rule() *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
InboundTag: []string{routeTestInboundTag},
|
||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||
}
|
||||
}
|
||||
|
||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||
// that only matches because the real request carries a source.
|
||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||
return &router.RoutingRule{
|
||||
SourceIp: []*geodata.IPRule{{
|
||||
Value: &geodata.IPRule_Custom{
|
||||
Custom: &geodata.CIDRRule{
|
||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||
},
|
||||
},
|
||||
}},
|
||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||
}
|
||||
}
|
||||
|
||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||
// running resolver. The instance is placed in the context through the key core
|
||||
// exports for tests.
|
||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||
t.Helper()
|
||||
|
||||
apps := []*serial.TypedMessage{
|
||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||
}
|
||||
if withDNSApp {
|
||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||
}
|
||||
|
||||
instance, err := core.New(&core.Config{
|
||||
App: apps,
|
||||
Outbound: []*core.OutboundHandlerConfig{
|
||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("core.New: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = instance.Close() })
|
||||
|
||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||
}
|
||||
|
||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||
return []*appdns.NameServer{{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||
Port: 53,
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||
// resolves through the system resolver.
|
||||
func localNameServer() *appdns.NameServer {
|
||||
return &appdns.NameServer{
|
||||
Address: &net.Endpoint{
|
||||
Network: net.Network_UDP,
|
||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||
Port: 53,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||
// false positive in the takeover decision itself, which is what assertions on
|
||||
// the resolvectl arguments could never catch.
|
||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
withDNSApp bool
|
||||
nameServers []*appdns.NameServer
|
||||
rules []*router.RoutingRule
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "independent upstream reaches the dns outbound",
|
||||
withDNSApp: true,
|
||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no dns section falls back to the system resolver",
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "dns section without name servers falls back too",
|
||||
withDNSApp: true,
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
// An independent upstream is not enough on its own: name servers are
|
||||
// selected per domain, so a local one can still be the one chosen.
|
||||
// The refusal is deliberately domain-agnostic for that reason.
|
||||
name: "a local name server alongside an independent one",
|
||||
withDNSApp: true,
|
||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||
rules: []*router.RoutingRule{port53Rule()},
|
||||
wantErr: "system resolver",
|
||||
},
|
||||
{
|
||||
name: "a rule on the interface address diverts the real query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "does not handle DNS",
|
||||
},
|
||||
{
|
||||
name: "a rule on another address does not match it",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
rules: []*router.RoutingRule{
|
||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||
port53Rule(),
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "no rule matches the query",
|
||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||
wantErr: "no route",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||
// carries IPv6 addresses.
|
||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||
}
|
||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||
}
|
||||
}
|
||||
@@ -710,3 +710,109 @@ func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, erro
|
||||
}
|
||||
return net.InterfaceByIndex(int(index))
|
||||
}
|
||||
|
||||
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
|
||||
// keeps Xray's own connections out of the TUN. With weak host send or
|
||||
// forwarding on for an IP version on the bound interface, Windows sends them
|
||||
// where the routes lead, into the TUN, from that interface's address, and
|
||||
// drops what comes back to that address through the TUN, so they stall.
|
||||
//
|
||||
// For the IP versions routed to the TUN, weak host send is turned off on the
|
||||
// bound interface while the TUN runs, and turned on again when the TUN stops
|
||||
// or another interface takes over. Forwarding is what Mobile Hotspot and
|
||||
// Internet Connection Sharing need, so it is only reported.
|
||||
type outboundGuard struct {
|
||||
sync.Mutex
|
||||
families []winipcfg.AddressFamily
|
||||
luid winipcfg.LUID // of the interface last checked
|
||||
name string // of that interface
|
||||
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
|
||||
forwarding bool // whether forwarding was on there
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// check turns weak host send off on the bound interface, and warns when
|
||||
// forwarding comes on there, but not again while it stays on.
|
||||
func (g *outboundGuard) check() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
if g.stopped {
|
||||
return
|
||||
}
|
||||
var luid winipcfg.LUID
|
||||
var name string
|
||||
if iface := updater.Get(); iface != nil {
|
||||
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
|
||||
name = iface.Name
|
||||
}
|
||||
if luid != g.luid {
|
||||
g.restoreLocked()
|
||||
g.luid, g.name = luid, name
|
||||
g.forwarding = false // to warn about the new interface as well
|
||||
}
|
||||
if luid == 0 {
|
||||
return
|
||||
}
|
||||
var forwarding []string
|
||||
for _, family := range g.families {
|
||||
row, err := luid.IPInterface(family)
|
||||
if err != nil {
|
||||
continue // the interface lacks that IP version
|
||||
}
|
||||
if row.ForwardingEnabled {
|
||||
forwarding = append(forwarding, familyName(family))
|
||||
}
|
||||
if !row.WeakHostSend {
|
||||
continue
|
||||
}
|
||||
if err := setWeakHostSend(row, false); err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(g.turnedOff, family) {
|
||||
g.turnedOff = append(g.turnedOff, family)
|
||||
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
|
||||
}
|
||||
}
|
||||
wasOn := g.forwarding
|
||||
g.forwarding = len(forwarding) > 0
|
||||
if g.forwarding && !wasOn {
|
||||
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// restore turns weak host send on again where check turned it off, for good.
|
||||
func (g *outboundGuard) restore() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
g.restoreLocked()
|
||||
g.stopped = true
|
||||
}
|
||||
|
||||
func (g *outboundGuard) restoreLocked() {
|
||||
for _, family := range g.turnedOff {
|
||||
row, err := g.luid.IPInterface(family)
|
||||
if err == nil {
|
||||
err = setWeakHostSend(row, true)
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
|
||||
}
|
||||
}
|
||||
g.turnedOff = nil
|
||||
}
|
||||
|
||||
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
|
||||
row.WeakHostSend = on
|
||||
if row.Family == windows.AF_INET {
|
||||
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
|
||||
}
|
||||
return row.Set()
|
||||
}
|
||||
|
||||
func familyName(family winipcfg.AddressFamily) string {
|
||||
if family == windows.AF_INET {
|
||||
return "IPv4"
|
||||
}
|
||||
return "IPv6"
|
||||
}
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"golang.org/x/sys/windows"
|
||||
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
|
||||
)
|
||||
|
||||
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
|
||||
// keeps Xray's own connections out of the TUN. With weak host send or
|
||||
// forwarding on for an IP version on the bound interface, Windows sends them
|
||||
// where the routes lead, into the TUN, from that interface's address, and
|
||||
// drops what comes back to that address through the TUN, so they stall.
|
||||
//
|
||||
// For the IP versions routed to the TUN, weak host send is turned off on the
|
||||
// bound interface while the TUN runs, and turned on again when the TUN stops
|
||||
// or another interface takes over. Forwarding is what Mobile Hotspot and
|
||||
// Internet Connection Sharing need, so it is only reported.
|
||||
type outboundGuard struct {
|
||||
sync.Mutex
|
||||
families []winipcfg.AddressFamily
|
||||
luid winipcfg.LUID // of the interface last checked
|
||||
name string // of that interface
|
||||
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
|
||||
forwarding bool // whether forwarding was on there
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// check turns weak host send off on the bound interface, and warns when
|
||||
// forwarding comes on there, but not again while it stays on.
|
||||
func (g *outboundGuard) check() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
if g.stopped {
|
||||
return
|
||||
}
|
||||
var luid winipcfg.LUID
|
||||
var name string
|
||||
if iface := updater.Get(); iface != nil {
|
||||
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
|
||||
name = iface.Name
|
||||
}
|
||||
if luid != g.luid {
|
||||
g.restoreLocked()
|
||||
g.luid, g.name = luid, name
|
||||
g.forwarding = false // to warn about the new interface as well
|
||||
}
|
||||
if luid == 0 {
|
||||
return
|
||||
}
|
||||
var forwarding []string
|
||||
for _, family := range g.families {
|
||||
row, err := luid.IPInterface(family)
|
||||
if err != nil {
|
||||
continue // the interface lacks that IP version
|
||||
}
|
||||
if row.ForwardingEnabled {
|
||||
forwarding = append(forwarding, familyName(family))
|
||||
}
|
||||
if !row.WeakHostSend {
|
||||
continue
|
||||
}
|
||||
if err := setWeakHostSend(row, false); err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(g.turnedOff, family) {
|
||||
g.turnedOff = append(g.turnedOff, family)
|
||||
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
|
||||
}
|
||||
}
|
||||
wasOn := g.forwarding
|
||||
g.forwarding = len(forwarding) > 0
|
||||
if g.forwarding && !wasOn {
|
||||
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
|
||||
}
|
||||
}
|
||||
|
||||
// restore turns weak host send on again where check turned it off, for good.
|
||||
func (g *outboundGuard) restore() {
|
||||
g.Lock()
|
||||
defer g.Unlock()
|
||||
g.restoreLocked()
|
||||
g.stopped = true
|
||||
}
|
||||
|
||||
func (g *outboundGuard) restoreLocked() {
|
||||
for _, family := range g.turnedOff {
|
||||
row, err := g.luid.IPInterface(family)
|
||||
if err == nil {
|
||||
err = setWeakHostSend(row, true)
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
|
||||
}
|
||||
}
|
||||
g.turnedOff = nil
|
||||
}
|
||||
|
||||
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
|
||||
row.WeakHostSend = on
|
||||
if row.Family == windows.AF_INET {
|
||||
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
|
||||
}
|
||||
return row.Set()
|
||||
}
|
||||
|
||||
func familyName(family winipcfg.AddressFamily) string {
|
||||
if family == windows.AF_INET {
|
||||
return "IPv4"
|
||||
}
|
||||
return "IPv6"
|
||||
}
|
||||
@@ -4,6 +4,7 @@ package tun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
go_errors "errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
@@ -340,3 +341,46 @@ func TestFlushDNSCache(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterGUID(t *testing.T) {
|
||||
// a configured GUID has to be the adapter GUID the text names: the groups
|
||||
// are field values, not the bytes of the text in order
|
||||
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := windows.GUID{
|
||||
Data1: 0x01020304,
|
||||
Data2: 0x0506,
|
||||
Data3: 0x0708,
|
||||
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
|
||||
}
|
||||
if *guid != want {
|
||||
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
|
||||
}
|
||||
// the same struct Windows builds from that text, and the text Windows shows
|
||||
// for it
|
||||
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if *guid != fromText {
|
||||
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
|
||||
}
|
||||
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
|
||||
t.Errorf("adapterGUID = %s, want %s", got, want)
|
||||
}
|
||||
|
||||
// without one, the bytes of the MD5 of the name, as they always were; that
|
||||
// GUID is never read back as text, so its byte order does not matter
|
||||
guid, err = adapterGUID("xray0", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := md5.Sum([]byte("xray0"))
|
||||
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
|
||||
t.Errorf("adapterGUID = %x, want %x", got, sum)
|
||||
}
|
||||
|
||||
if _, err := adapterGUID("xray0", "xray0"); err == nil {
|
||||
t.Error("an invalid guid was accepted")
|
||||
}
|
||||
}
|
||||
@@ -8,20 +8,6 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// BenchmarkUDPNewSession measures what one new UDP flow costs the
|
||||
// inbound while it stays open: QUIC and DNS open many short flows, and each
|
||||
// one lives until the connection idle timeout.
|
||||
func BenchmarkUDPNewSession(b *testing.B) {
|
||||
u := newUdpConnectionHandler(func(conn net.Conn, dest net.Destination) {}, nil)
|
||||
dst := net.UDPDestination(net.ParseAddress("1.1.1.1"), 443)
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
src := net.UDPDestination(net.IPAddress([]byte{10, byte(i >> 16), byte(i >> 8), byte(i)}), net.Port(1024+i%60000))
|
||||
u.HandlePacket(src, dst, &buf.Buffer{})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketQueueOrderAndClose(t *testing.T) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
for i := 0; i < 3; i++ {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package tun
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
)
|
||||
|
||||
const benchBatch = 64
|
||||
|
||||
// Raw cost of queueing and draining a small burst, as one flow's reader does.
|
||||
func BenchmarkQueueBurstChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
ch <- p
|
||||
}
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
<-ch
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkQueueBurstPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
q.push(p)
|
||||
}
|
||||
for j := 0; j < benchBatch; j++ {
|
||||
q.pop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Producer and consumer on different goroutines; the producer yields when the
|
||||
// queue is full instead of spinning, like a blocking channel send would.
|
||||
func BenchmarkQueueStreamChan(b *testing.B) {
|
||||
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for range ch {
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
ch <- p
|
||||
}
|
||||
close(ch)
|
||||
<-done
|
||||
}
|
||||
|
||||
func BenchmarkQueueStreamPacketQueue(b *testing.B) {
|
||||
q := newPacketQueue(udpQueueLimit)
|
||||
p := &buf.Buffer{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for {
|
||||
if _, ok := q.pop(); !ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
for !q.push(p) {
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
q.close()
|
||||
<-done
|
||||
}
|
||||
@@ -80,43 +80,3 @@ func TestExpandWfpBlockLeak(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeakCovers(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
value string
|
||||
protocol string
|
||||
port uint16
|
||||
covers bool
|
||||
}{
|
||||
{"tcp", "tcp", 1, true},
|
||||
{"tcp", "udp", 53, false},
|
||||
{"udp/53", "udp", 53, true},
|
||||
{"udp/53", "udp", 54, false},
|
||||
{"tcp/10-20", "tcp", 10, true},
|
||||
{"tcp/10-20", "tcp", 20, true},
|
||||
{"tcp/10-20", "tcp", 21, false},
|
||||
{"tcp/10-20", "tcp", 9, false},
|
||||
{"53", "udp", 53, true},
|
||||
{"53", "tcp", 53, true},
|
||||
{"10-20", "tcp", 15, true},
|
||||
{"10-20", "udp", 21, false},
|
||||
{"1.1.1.0/24:udp/53", "udp", 53, true},
|
||||
{"[::/0]:tcp", "tcp", 443, true},
|
||||
{"[2001:db8::/32]:53", "tcp", 53, true},
|
||||
{"0.0.0.0/0:icmp", "udp", 53, false},
|
||||
{"all", "udp", 53, true},
|
||||
{"1.1.1.1/32:all", "tcp", 1, true},
|
||||
{"allexceptlan", "udp", 53, false},
|
||||
{"misconfigtun", "udp", 53, false},
|
||||
{"windnsclient", "udp", 53, false},
|
||||
} {
|
||||
l, ok := parseLeak(c.value)
|
||||
if !ok {
|
||||
t.Errorf("%q was not parsed", c.value)
|
||||
continue
|
||||
}
|
||||
if got := l.covers(c.protocol, c.port); got != c.covers {
|
||||
t.Errorf("%q covers %s/%d = %v", c.value, c.protocol, c.port, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
@@ -72,6 +73,7 @@ func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, erro
|
||||
if target.Network == net.Network_UDP && target.Port == 443 {
|
||||
switch c.config.GetXudpProxyUDP443() {
|
||||
case "reject", "":
|
||||
proxy.DropUDP(ctx, link.Reader)
|
||||
return true, errors.New("XUDP rejected UDP/443 traffic")
|
||||
case "skip":
|
||||
return false, nil
|
||||
|
||||
@@ -26,7 +26,9 @@ func TestClientUDP443Policy(t *testing.T) {
|
||||
opened = true
|
||||
return nil, nil, context.Canceled
|
||||
})
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{})
|
||||
r, w := pipe.New()
|
||||
common.Close(w)
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
|
||||
wantRejected := policy == "reject"
|
||||
if opened || handled != wantRejected || (err != nil) != wantRejected {
|
||||
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
|
||||
|
||||
@@ -191,6 +191,13 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
|
||||
rec := h.server
|
||||
var conn stat.Connection
|
||||
|
||||
account := rec.User.Account.(*vless.MemoryAccount)
|
||||
|
||||
if !native && ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 && account.Flow == vless.XRV {
|
||||
proxy.DropUDP(ctx, link.Reader)
|
||||
return nil, nil, errors.New("XTLS rejected UDP/443 traffic")
|
||||
}
|
||||
|
||||
if h.testpre > 0 {
|
||||
h.initpre.Do(func() {
|
||||
h.preConns = make(chan *ConnExpire)
|
||||
@@ -272,27 +279,20 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
|
||||
request.Address, request.Port = target.Address, target.Port
|
||||
}
|
||||
|
||||
account := request.User.Account.(*vless.MemoryAccount)
|
||||
|
||||
requestAddons := &encoding.Addons{
|
||||
Flow: account.Flow,
|
||||
}
|
||||
|
||||
var input *bytes.Reader
|
||||
var rawInput **bytes.Buffer
|
||||
allowUDP443 := false
|
||||
switch requestAddons.Flow {
|
||||
case vless.XRV + "-udp443":
|
||||
allowUDP443 = true
|
||||
requestAddons.Flow = requestAddons.Flow[:16]
|
||||
fallthrough
|
||||
case vless.XRV:
|
||||
ob.CanSpliceCopy = 2
|
||||
switch request.Command {
|
||||
case protocol.RequestCommandUDP:
|
||||
if !allowUDP443 && request.Port == 443 {
|
||||
return nil, nil, errors.New("XTLS rejected UDP/443 traffic")
|
||||
}
|
||||
case protocol.RequestCommandTCP, protocol.RequestCommandMux, protocol.RequestCommandRvs:
|
||||
var target net.Conn
|
||||
if commonConn, ok := conn.(*encryption.CommonConn); ok {
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
http_proto "github.com/xtls/xray-core/common/protocol/http"
|
||||
"github.com/xtls/xray-core/common/signal/done"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion"
|
||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
|
||||
@@ -78,10 +79,9 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession {
|
||||
h.sessions.Store(sessionId, s)
|
||||
|
||||
shouldReap := done.New()
|
||||
go func() {
|
||||
time.Sleep(30 * time.Second)
|
||||
time.AfterFunc(30*time.Second, func() {
|
||||
shouldReap.Close()
|
||||
}()
|
||||
})
|
||||
go func() {
|
||||
select {
|
||||
case <-shouldReap.Wait():
|
||||
@@ -222,15 +222,15 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
|
||||
scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs()
|
||||
hasLegacyRefererCompatMarker := request.Header.Get("Referer") != ""
|
||||
if (hasLegacyRefererCompatMarker || obfsPaddingAccepted) && scStreamUpServerSecs.To > 0 {
|
||||
go func() {
|
||||
for {
|
||||
writePadding := &task.Periodic{
|
||||
Execute: func() error {
|
||||
_, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second)
|
||||
}
|
||||
}()
|
||||
return err
|
||||
},
|
||||
Interval: time.Duration(scStreamUpServerSecs.rand()) * time.Second,
|
||||
}
|
||||
defer writePadding.Close()
|
||||
writePadding.Start()
|
||||
}
|
||||
select {
|
||||
case <-request.Context().Done():
|
||||
|
||||
@@ -6,9 +6,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
)
|
||||
|
||||
var _ buf.Writer = (*connection)(nil)
|
||||
@@ -20,25 +22,27 @@ type connection struct {
|
||||
conn *websocket.Conn
|
||||
reader io.Reader
|
||||
remoteAddr net.Addr
|
||||
keepalive *task.Periodic
|
||||
}
|
||||
|
||||
func NewConnection(conn *websocket.Conn, remoteAddr net.Addr, extraReader io.Reader, heartbeatPeriod uint32) *connection {
|
||||
if heartbeatPeriod != 0 {
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(time.Duration(heartbeatPeriod) * time.Second)
|
||||
if err := conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{}); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return &connection{
|
||||
wrappedConn := &connection{
|
||||
conn: conn,
|
||||
remoteAddr: remoteAddr,
|
||||
reader: extraReader,
|
||||
}
|
||||
if heartbeatPeriod != 0 {
|
||||
keepalive := task.Periodic{
|
||||
Execute: func() error {
|
||||
return conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{})
|
||||
},
|
||||
Interval: time.Duration(heartbeatPeriod) * time.Second,
|
||||
}
|
||||
keepalive.Start()
|
||||
wrappedConn.keepalive = &keepalive
|
||||
}
|
||||
|
||||
return wrappedConn
|
||||
}
|
||||
|
||||
// Read implements net.Conn.Read()
|
||||
@@ -93,6 +97,7 @@ func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
}
|
||||
|
||||
func (c *connection) Close() error {
|
||||
common.CloseIfExists(c.keepalive)
|
||||
var errs []interface{}
|
||||
if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
|
||||
errs = append(errs, err)
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
# XDRIVE
|
||||
|
||||
xDrive carries an ordered byte stream in each direction. Use matching releases on
|
||||
both peers. Drive uses slots; local, URL-template and S3 stores keep their WAL.
|
||||
This repository is a review candidate based on the maintainer's fork, not a merge
|
||||
of the current upstream branch.
|
||||
|
||||
## Drive protocol
|
||||
|
||||
The announcement names a table of file IDs and one reader-owned watermark for
|
||||
**each direction**. IDs are allocated in batches. The first lap creates files
|
||||
on first publication. Established sessions do not list files to find data:
|
||||
sequence `n` maps directly to `slots[n % depth]`. If present, the announcement's
|
||||
first payload is sequence zero, not an additional record.
|
||||
|
||||
Mode 1 carries up to 14 KiB in metadata, mode 5 a media body, modes 3 and 4
|
||||
mean end and error. See "Transport model" below.
|
||||
|
||||
- **Write:** one goroutine batches caller input and assigns sequence numbers.
|
||||
Input is gathered for 25 ms; after idle, a small write has a 2 ms window.
|
||||
The planner uses up to 24 available inline positions; larger bursts can use
|
||||
media. There are at most 32 upload workers per direction and never more than
|
||||
the ring depth. For the eager window after a media upload starts (default 2 s),
|
||||
later bursts do not split into inline waves even if few uploads remain.
|
||||
Reuse requires previous local completion and cumulative remote credit.
|
||||
- **Read:** idle polling focuses on the head. After a minute without a head,
|
||||
one bounded background probe at a time rotates through other slot descriptions
|
||||
to distinguish a gap from a genuinely idle peer. During activity, up to
|
||||
24 known descriptions are prefetched, with one metadata GET per worker at a
|
||||
time. Empty-slot polling reaches only four positions beyond the observed
|
||||
frontier (or head); new observations advance that frontier immediately.
|
||||
All media sizes may be prefetched; byte admission follows sequence
|
||||
order, bounded to 4 MiB per media connection and held until head promotion.
|
||||
Ordinary media has four HTTP permits per connection (capped at 64); head
|
||||
media has separate permits (up to four), including queued requests promoted
|
||||
to head. Both use the same connections; the head has its own frame allowance.
|
||||
A prefetched frame returns its local byte reservation when promoted, even if
|
||||
its body is still downloading. Completed successors retain theirs until promoted.
|
||||
Workers can finish out of order; one coordinator alone delivers bytes.
|
||||
Ordered delivery refreshes the eager timer; speculative body downloads do not.
|
||||
- **Media:** frames through 1 MiB use one progressive GET; larger frames
|
||||
use up to four block ranges at once, capped by the media connection count
|
||||
and targeting at least 512 KiB of payload per range.
|
||||
If the first range returns a full HTTP 200 body, keep it and cancel the other
|
||||
ranges instead of downloading the full body four times. Validate every
|
||||
block's sequence tag, HTTP range/length and EOF. One retry can resume an
|
||||
incomplete span without delivering the same bytes twice. No media GET runs
|
||||
before discovering its frame description.
|
||||
- **Close:** Close discards unread input, drains its writer and publishes END.
|
||||
It keeps verifying input and returning credit until it reads the peer's END,
|
||||
then flushes any remaining verified watermark. The peer may still have a full
|
||||
ring to drain after our writer finishes. Interrupt cancels instead.
|
||||
|
||||
Unlike v6, a unilateral graceful Close can time out if the peer never publishes
|
||||
END. The one-minute watchdog tracks outbound progress until the local writer
|
||||
finishes, then also counts successful inbound watermark writes during Close.
|
||||
Receiving END alone does not close the outbound half.
|
||||
|
||||
## Transport model (Drive)
|
||||
|
||||
Each direction is a ring of `depth` Drive files plus one watermark file owned
|
||||
by the reader. Sequence `n` always lives in `slots[n % depth]`.
|
||||
|
||||
1. **Gather.** The writer collects caller input for up to 25 ms (2 ms after
|
||||
idle for a single small write) or until the current frame size is reached.
|
||||
With 4 or more uploads in flight the writer is streaming: it keeps
|
||||
gathering while input keeps arriving, up to 200 ms or a full frame, and
|
||||
sends once input pauses for 25 ms, so a reply burst goes out as one frame.
|
||||
2. **Frame size grows every round.** It starts at `segmentBytes` (512 KiB)
|
||||
and doubles after each round that filled a whole frame, up to 4 MiB (below
|
||||
Drive's 5 MB multipart limit). It halves (not below the start) when an
|
||||
upload waited more than 5 s for ring credit outside Drive cooldown.
|
||||
Cooldown freezes frame size instead of shrinking it: smaller frames spend
|
||||
more requests per byte. Routine credit takes 1-3 s; shorter waits only mean
|
||||
the writer is a ring ahead. Larger frames carry more bytes per position.
|
||||
3. **Publish.** Up to 14 KiB goes inline in the file description (one PATCH;
|
||||
an idle writer may split a burst into up to 24 inline frames, a streaming
|
||||
writer never does, because the reader finds only about 24 frames per round
|
||||
trip and 14 KiB frames would cap throughput near 1 MB/s). Larger frames
|
||||
are one multipart PATCH: the description holds `XDRVSL03`, sequence, mode
|
||||
and length; the body is blocks of an 8-byte sequence tag followed by up to
|
||||
256 KiB of data. At most 32 uploads and
|
||||
4 MiB of unfinished uploads per media connection run per direction (one
|
||||
frame may exceed it alone). Media requests rotate per request over
|
||||
the media connections (XMUX `maxConnections`, default 4): one Google
|
||||
connection carries only a fraction of a link (a measured single-connection
|
||||
client download averaged ~0.22 MB/s). The byte bound,
|
||||
about one 4 MiB frame per connection, bounds payload bytes, not request count
|
||||
or duplicated network traffic. Head reads have separate HTTP permits, not
|
||||
extra connections. Bounded look-ahead overlaps service latency between frames
|
||||
instead of forcing one large frame to finish before starting the next.
|
||||
4. **Discover.** The reader polls the head slot's description (25 ms while
|
||||
active; no duplicate hedged GET) and prefetches up to 24 descriptions. Slots
|
||||
beyond the observed frontier plus four wait without polling; the head always
|
||||
polls, and the existing gap probe still covers otherwise unobserved gaps.
|
||||
Bodies of all sizes download ahead within the byte budget, admitted in sequence
|
||||
order so distant successors cannot reserve it before nearer frames. The head
|
||||
bypasses that budget, and a queued media request switches to the reserved
|
||||
HTTP permits when promoted. Admission waits for the previous frame's ready
|
||||
signal, not its completed download.
|
||||
Promotion releases any existing look-ahead reservation, not remote ring credit.
|
||||
Thus a head discovered in advance no longer consumes both its own allowance
|
||||
and the successors' budget. Cancellation also releases each reservation once.
|
||||
5. **Fetch.** Media up to 1 MiB uses one streaming GET; larger frames use
|
||||
two to four block-aligned ranges with the default four connections,
|
||||
targeting at least 512 KiB per range and reaching four ranges at 2 MiB.
|
||||
They start together for each admitted frame: every block carries
|
||||
the sequence tag, so each range rejects an older lap by itself (before,
|
||||
later ranges waited for the first one, costing a second time-to-first-byte,
|
||||
~1 s, per large frame).
|
||||
A full HTTP 200 response to the first range replaces all ranges; the others
|
||||
are canceled before any of their bytes are delivered. Bytes are delivered
|
||||
in 32 KiB pieces as they arrive. One retry resumes
|
||||
after the delivered bytes; the declared length and exact EOF are checked.
|
||||
6. **Credit.** The reader writes its cumulative watermark every `depth/6`
|
||||
frames or 1.5 s. A slot is rewritten only after that credit. Frame size
|
||||
changes are logged at debug level (`xdrive frame size A -> B`), as is
|
||||
each media frame: `xdrive upload seq` (credit wait, PUT time) and
|
||||
`xdrive read seq` (time to find, admission/byte-budget wait, body time).
|
||||
`xdrive watermark seq N put P` records successful ACK publications, and
|
||||
`xdrive credit seq N ack A` records the writer observing newer credit.
|
||||
`xdrive span seq` records range status, wire bytes, time waiting for headers
|
||||
(including permit wait, retries and service latency), and time after headers.
|
||||
`xdrive span retry seq` records emitted payload bytes and the error that
|
||||
triggered the one stream resume; successful final reads can hide this error.
|
||||
`xdrive request retry seq` exposes retries before headers or buffered success.
|
||||
`xdrive cooldown D` records the shared delay after quota/service rejections.
|
||||
|
||||
There are no CRCs: integrity relies on TLS, the length checks and the
|
||||
per-block sequence tags, and VLESS encryption authenticates the payload. Both
|
||||
peers must run this release (`XDRVSL03` is not readable by older peers).
|
||||
|
||||
## Implementation and trade-offs
|
||||
|
||||
`slots.go` contains the frame codec, ring announcement and
|
||||
publication, outbound writer, and inbound reader, in that order. One reader
|
||||
ACK loop owns both periodic and final watermark writes. `drive.go` owns OAuth,
|
||||
Drive requests, quotas, object CRUD, ID allocation, and media verification.
|
||||
`client.go` is shared with the URL-template and S3 transports. It retains the
|
||||
configured TLS/QUIC dial path, socket and mask settings, stall timeout, HTTP/2
|
||||
keepalive and XMUX leases. Drive uses distinct metadata, priority and media
|
||||
pools. Metadata and priority select a lease once per session; media rotates
|
||||
per request across one-connection XMUX lanes instead of random selection
|
||||
(the upper `maxConnections` bound, default 4). Request/reuse/lifetime limits
|
||||
still apply within each lane; the media byte budget follows the same count.
|
||||
Peer-supplied IDs are checked for valid syntax and uniqueness. An existing
|
||||
object must match its announced session name and configured parent on first
|
||||
use. Keep the folder private to the two peers; these checks do not authenticate
|
||||
a writer who already has access to the session folder.
|
||||
|
||||
Removed from the larger implementation: custom spare-connection probes,
|
||||
background connection/token/ID keepers, eager spare rings, duplicated media
|
||||
rescue and latency controllers, and detailed per-burst telemetry. A Drive ID
|
||||
allocation failure now fails the dial explicitly instead of switching to WAL.
|
||||
Announcements are also created with reserved IDs. After a lost reply, read back
|
||||
the exact slot, watermark or inline announcement description; for a media
|
||||
announcement also compare the complete body. Never replay an ambiguous write.
|
||||
If an announcement was already deleted, a 404 is not proof of delivery. If confirmation fails,
|
||||
the original write error is preserved. Graceful close reports final ACK errors. These are
|
||||
behavior differences, not just source rearrangement. Historical throughput
|
||||
and tail-latency measurements from the larger version are **not** measurements
|
||||
of this one. Empty Drive announcements are rejected rather than opened as WAL
|
||||
sessions. Uploads and OAuth refresh requests do not follow redirects.
|
||||
|
||||
## Failure handling and verification
|
||||
|
||||
A fatal upload, media-read or watermark error cancels both halves of a Drive
|
||||
connection with the first error as the cause. A normal END only closes its
|
||||
own direction. Readers reject an overwritten sequence; a writer verifies that
|
||||
a cumulative ACK cannot cover its own unpublished sequence before reusing a slot.
|
||||
Buffered GETs can retry an interrupted response body. Streamed media resumes
|
||||
by delivered offset, and an ambiguous mutation is not replayed. Listing and ID allocation
|
||||
use the app-data space when `remoteFolder` is `appDataFolder`. Drive announcement
|
||||
age is seeded from `createdTime` and the listing response’s `Date`, so an expired
|
||||
announcement does not become fresh when a listener restarts. This is not a
|
||||
persistent exactly-once claim within the TTL. An unprovable gap (no subsequent
|
||||
frame) still looks like an idle connection; use a read deadline when one is required.
|
||||
|
||||
Transient OAuth transport and service failures can retry before any file operation
|
||||
is sent. All Drive file attempts, including retries, reserve spaced starts at
|
||||
80 requests/s per shared storage instance, across sessions and lanes. Two peers
|
||||
at this ceiling use about 9,600 attempts/minute against the observed 12,000
|
||||
quota, leaving headroom, not a guarantee for other processes or profiles sharing
|
||||
the project. Queued requests recheck cooldown before proceeding. Cancellation
|
||||
may leave unused pacing turns, but releases the request permit.
|
||||
Drive rate-limit responses and 503 responses with `Retry-After` apply a shared
|
||||
exponential cooldown (jittered 2–30 s base), reset after a minute without a new
|
||||
cooldown. Concurrent rejections in one cooldown do not escalate independently;
|
||||
a longer `Retry-After` still extends it. A 503 never permits mutation replay.
|
||||
Quota retry logs omit the repetitive JSON error body. Cleanup excludes
|
||||
folders and Google-native objects. Conflicting regular files with the exact same
|
||||
announcement name are not selected or deleted as a group; resolve them manually.
|
||||
The admission deadline also applies while loading or binding the announcement,
|
||||
not to the resulting connection. Use a dedicated folder for one listener and its clients.
|
||||
|
||||
### Verification of this candidate
|
||||
|
||||
This version descends from the v7 candidate, which began as a literal merge
|
||||
of v6's four slot files. The per-block CRCs, the checksum table and the
|
||||
checksummed media reader are gone here. Retry safety rules remain, but media
|
||||
reading, request pacing and shared cooldown now differ from v6.
|
||||
|
||||
The quota refinement passes `gofmt -l`, `go build ./...` and xdrive `go vet`.
|
||||
A Python virtual-clock model checks pacing, cancellation, cooldown extension,
|
||||
Retry-After, frontier progression and frame-size freezing; it is not a Go
|
||||
HTTP/race workload or a live-Drive throughput benchmark. No test files are added.
|
||||
|
||||
The receive-credit refinement releases local look-ahead bytes on head promotion;
|
||||
watermarks still advance only after verified ordered delivery and exact EOF.
|
||||
No budgets, request limits or wire-format fields changed. Validate with slow
|
||||
heads, completed successors, cancellation and unequal Close workloads under race
|
||||
detection before attributing a sustained-speed improvement to this change.
|
||||
|
||||
The following are **Python model checks against the v7 candidate, not runs of
|
||||
this Go package**:
|
||||
|
||||
- At ring depth two, the v6 and candidate models each delivered 1,096,163
|
||||
bytes in each direction, with separate deterministic payloads. All received
|
||||
bytes matched. The fixture crossed the inline, prefix and multi-range
|
||||
thresholds. It cut 16 model responses after a complete block plus 17 bytes;
|
||||
eight resumes simulated a server ignoring Range. No duplicated bytes.
|
||||
- Seven scripted quota/status cases per version checked the retry decision for
|
||||
429, rate-limited and ordinary 403, and 500/503, including a 503 with
|
||||
Retry-After on a mutation. Delays used a virtual clock, not HTTP or Drive.
|
||||
- A small exhaustive close model let the empty writer publish END before the
|
||||
opposite writer finished four data frames. Three v6 terminal states could
|
||||
not progress; none of the candidate's 45 reachable states was stuck. This
|
||||
is a bounded ordering check, not a goroutine race test.
|
||||
|
||||
**Release gates:** the candidate workspace had no Go 1.27 or `gofmt`, so the
|
||||
model checks above did not build it. This snapshot was formatted with `gofmt`
|
||||
(and the repository's `vformat`/`vprotogen` checks), vetted and built with the
|
||||
`go.mod` toolchain; it has not been run against an HTTP mock in Go, with a
|
||||
`-race` workload, or against live Drive. The inventory below is the physical
|
||||
post-`gofmt` count. No XDrive test file is shipped.
|
||||
|
||||
For deeper assurance, in a disposable checkout, run the same depth-two
|
||||
transfers against v6 and the candidate with a fault-injecting Drive HTTP mock
|
||||
under `go test -race`: compare both byte streams, truncate media responses,
|
||||
return 429/403/503, and close both peers with unequal outstanding writes.
|
||||
Also check one-sided Close, final ACK failure and Interrupt. A plain
|
||||
`go test -race` without a workload is not a concurrency test. Repeat the
|
||||
bidirectional transfer with a dedicated live Drive folder.
|
||||
|
||||
## Drive source budget (physical lines, including comments and blanks)
|
||||
|
||||
Count all three implementation files in full, including the shared HTTP client.
|
||||
For mixed files, the following inventory charges whole integration functions
|
||||
where practical, including generic code within them. The remaining WAL/backend,
|
||||
protocol-wide listener, configuration and generated protobuf code is shared or
|
||||
unrelated, not a hidden second Drive implementation. Ranges below are inclusive
|
||||
for this snapshot, relative to `transport/internet/xdrive` unless marked `infra/`.
|
||||
|
||||
| Source | Inclusive lines counted | Count |
|
||||
|---|---|---:|
|
||||
| `drive.go` | whole file | 1056 |
|
||||
| `slots.go` | whole file | 879 |
|
||||
| `client.go` | whole file | 537 |
|
||||
| `conn.go` | 65–79, 185–217, 219–244 | 74 |
|
||||
| `xdrive.go` | 9, 139–223, 276, 323–413, 479–490, 492–512, 538–572, 588–670 | 329 |
|
||||
| `params.go` | 75–91 | 17 |
|
||||
| `storage.go` | 9, 20–24, 36–63, 65–75 | 45 |
|
||||
| `storage_lease.go` | 26–32, 42–45, 47–63, 69–70, 89, 157–162 | 37 |
|
||||
| `infra/conf/transport_method.go` | 1020–1027, 1037, 1045–1050 | 15 |
|
||||
| `infra/conf/transport_internet.go` | 266–275 | 10 |
|
||||
| **Total** | | **2999** |
|
||||
+200
-182
@@ -32,10 +32,7 @@ type serviceTransport struct {
|
||||
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
|
||||
// Cancel stalled requests, not long transfers that continue to make progress.
|
||||
func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
next := t.plain
|
||||
if r.URL.Scheme == "https" {
|
||||
@@ -43,29 +40,46 @@ func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancelCause(r.Context())
|
||||
timer := time.AfterFunc(t.stall, func() { cancel(errStalled) })
|
||||
alive := func() { timer.Reset(t.stall) }
|
||||
var timerMu sync.Mutex
|
||||
ended := false
|
||||
deadline := time.Now().Add(t.stall)
|
||||
timer := time.AfterFunc(t.stall, func() {
|
||||
timerMu.Lock()
|
||||
defer timerMu.Unlock()
|
||||
if !ended && !time.Now().Before(deadline) {
|
||||
cancel(errStalled)
|
||||
}
|
||||
})
|
||||
alive := func() {
|
||||
timerMu.Lock()
|
||||
defer timerMu.Unlock()
|
||||
if !ended {
|
||||
deadline = time.Now().Add(t.stall)
|
||||
timer.Reset(t.stall)
|
||||
}
|
||||
}
|
||||
end := func() {
|
||||
timerMu.Lock()
|
||||
ended = true
|
||||
timer.Stop()
|
||||
timerMu.Unlock()
|
||||
cancel(nil)
|
||||
}
|
||||
r = r.WithContext(ctx)
|
||||
// the headers of chrome as with XHTTP and DoH, net/http and http3 would send
|
||||
// their own user agent after a hello of chrome
|
||||
// Clone before setting defaults: the caller owns the original headers.
|
||||
r.Header = r.Header.Clone()
|
||||
utils.TryDefaultHeadersWith(r.Header, "fetch")
|
||||
if r.Body != nil && r.Body != http.NoBody {
|
||||
r.Body = &progressBody{ReadCloser: r.Body, alive: alive}
|
||||
r.Body = &progressBody{ReadCloser: r.Body, alive: alive, upload: true}
|
||||
}
|
||||
// a body sent again by the transport itself, after a GOAWAY or on a reused
|
||||
// connection that failed, moves just the same
|
||||
// Rewinds performed by the transport must also reset the stall timer.
|
||||
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
|
||||
return &progressBody{ReadCloser: body, alive: alive, upload: true}, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,8 +94,18 @@ func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// stalled returns errStalled for an error that the stall gave, which http2 reports
|
||||
// as a plain cancel
|
||||
func (t *serviceTransport) CloseIdleConnections() {
|
||||
closeIdleTransport(t.plain)
|
||||
closeIdleTransport(t.secure)
|
||||
}
|
||||
|
||||
func closeIdleTransport(t http.RoundTripper) {
|
||||
if closer, ok := t.(interface{ CloseIdleConnections() }); ok {
|
||||
closer.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
|
||||
// HTTP/2 can report the stall timeout as an ordinary cancellation.
|
||||
func stalled(ctx context.Context, err error) error {
|
||||
if context.Cause(ctx) == errStalled {
|
||||
return errStalled
|
||||
@@ -91,16 +115,19 @@ func stalled(ctx context.Context, err error) error {
|
||||
|
||||
type progressBody struct {
|
||||
io.ReadCloser
|
||||
alive func()
|
||||
end func()
|
||||
alive func()
|
||||
end func()
|
||||
upload bool
|
||||
// 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)])
|
||||
// Short upload reads keep the stall timer meaningful on slow connections.
|
||||
if b.upload {
|
||||
p = p[:min(len(p), 16<<10)]
|
||||
}
|
||||
n, err := b.ReadCloser.Read(p)
|
||||
if n > 0 {
|
||||
b.alive()
|
||||
}
|
||||
@@ -118,29 +145,27 @@ func (b *progressBody) Close() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// newServiceClient returns a client whose requests end after stall without
|
||||
// progress, see serviceTransport.RoundTrip, and whose connections close when
|
||||
// connCtx is done. Clients that share h1Hosts share which hosts answer over h1
|
||||
// connCtx owns sockets; h1Hosts shares ALPN observations between clients.
|
||||
func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings *internet.MemoryStreamConfig, stall time.Duration, maxConns int) *http.Client {
|
||||
var (
|
||||
tlsConfig *tls.Config
|
||||
sockopt *internet.SocketConfig
|
||||
fronting *net.Destination
|
||||
keepAlive = net.ChromeH2KeepAlivePeriod
|
||||
// h3 keeps alive only when asked to, see below
|
||||
h3KeepAlive time.Duration
|
||||
// Detect silent h2 loss unless XMUX supplies an explicit keepalive.
|
||||
h2Idle, h2PingWait = 1500 * time.Millisecond, 2500 * time.Millisecond
|
||||
h3KeepAlive time.Duration
|
||||
)
|
||||
if streamSettings != nil {
|
||||
tlsConfig = tls.ConfigFromStreamSettings(streamSettings)
|
||||
sockopt = streamSettings.SocketSettings
|
||||
fronting = streamSettings.Destination
|
||||
if config, ok := streamSettings.ProtocolSettings.(*Config); ok && config.Xmux != nil {
|
||||
if config, ok := streamSettings.ProtocolSettings.(*Config); ok && config != nil && config.Xmux != nil {
|
||||
switch period := config.Xmux.HKeepAlivePeriod; {
|
||||
case period > 0:
|
||||
keepAlive = time.Duration(period) * time.Second
|
||||
h3KeepAlive = keepAlive
|
||||
h3KeepAlive = time.Duration(period) * time.Second
|
||||
h2Idle, h2PingWait = h3KeepAlive, 0
|
||||
case period < 0:
|
||||
keepAlive = 0
|
||||
h2Idle, h2PingWait = 0, 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,9 +174,15 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
}
|
||||
fingerprint := tls.GetFingerprint(tlsConfig.Fingerprint)
|
||||
|
||||
// fronting takes only the address and port, the network stays that of the
|
||||
// dial, which is UDP for h3 though the destination is built as TCP
|
||||
// A configured front replaces the address, not the transport network.
|
||||
dial := func(ctx context.Context, network, addr string) (net.Conn, net.Destination, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
stop := context.AfterFunc(connCtx, cancel)
|
||||
defer stop()
|
||||
defer cancel()
|
||||
if err := connCtx.Err(); err != nil {
|
||||
return nil, net.Destination{}, err
|
||||
}
|
||||
host, err := net.ParseDestination(network + ":" + addr)
|
||||
if err != nil {
|
||||
return nil, host, errors.New("bad address: ", addr).Base(err)
|
||||
@@ -167,7 +198,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
|
||||
var conn net.Conn
|
||||
switch {
|
||||
case streamSettings.FinalMask == nil:
|
||||
case streamSettings == nil || streamSettings.FinalMask == nil:
|
||||
conn, err = internet.DialSystem(ctx, target, sockopt)
|
||||
case target.Network == net.Network_UDP:
|
||||
conn, err = streamSettings.FinalMask.DialUDP(ctx, target)
|
||||
@@ -177,15 +208,13 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
if err != nil {
|
||||
return nil, host, errors.New("failed to dial to dest").Base(err)
|
||||
}
|
||||
// h3 closes its QUIC connection instead, as the server never hears of a UDP
|
||||
// socket that closes
|
||||
// HTTP/3 must close QUIC itself as well as its UDP socket.
|
||||
if network == "udp" {
|
||||
return conn, host, nil
|
||||
}
|
||||
// CloseIdleConnections leaves an h2 connection open while a stream just
|
||||
// canceled has not left it yet
|
||||
stop := context.AfterFunc(connCtx, func() { conn.Close() })
|
||||
return &ctxConn{Conn: conn, stop: stop}, host, nil
|
||||
// A recently canceled h2 stream may still own the socket.
|
||||
stopConn := context.AfterFunc(connCtx, func() { conn.Close() })
|
||||
return &ctxConn{Conn: conn, stop: stopConn}, host, nil
|
||||
}
|
||||
|
||||
dialPlain := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
@@ -207,8 +236,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
} 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
|
||||
// Bound the handshake independently of connection reuse.
|
||||
ctx, cancel := context.WithTimeout(ctx, stall)
|
||||
defer cancel()
|
||||
if err := tlsConn.(tls.Interface).HandshakeContext(ctx); err != nil {
|
||||
@@ -226,7 +254,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
MaxIdleConns: maxConns,
|
||||
MaxIdleConnsPerHost: maxConns,
|
||||
MaxConnsPerHost: connsPerHost,
|
||||
HTTP2: &http.HTTP2Config{SendPingTimeout: keepAlive},
|
||||
HTTP2: &http.HTTP2Config{SendPingTimeout: h2Idle, PingTimeout: h2PingWait},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,9 +265,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
if quicParams == nil {
|
||||
quicParams = &internet.QuicParams{BbrProfile: string(bbr.ProfileStandard)}
|
||||
}
|
||||
// the defaults are those of quic-go, with no keepalive unless asked for, as
|
||||
// in DoH: http3 never closes a connection that is idle or that it dropped
|
||||
// after an error, so only the idle timeout or the end of connCtx ends it
|
||||
// QUIC idle timeout and connCtx bound unused connections.
|
||||
quicConfig := &quic.Config{
|
||||
InitialStreamReceiveWindow: quicParams.InitStreamReceiveWindow,
|
||||
MaxStreamReceiveWindow: quicParams.MaxStreamReceiveWindow,
|
||||
@@ -258,11 +284,16 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
https = &http3.Transport{
|
||||
QUICConfig: quicConfig,
|
||||
Dial: func(ctx context.Context, addr string, _ *gotls.Config, cfg *quic.Config) (*quic.Conn, error) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
stop := context.AfterFunc(connCtx, cancel)
|
||||
defer stop()
|
||||
defer cancel()
|
||||
if connCtx.Err() != nil {
|
||||
cancel()
|
||||
}
|
||||
switch quicParams.Congestion {
|
||||
case "", "bbr", "reno":
|
||||
default:
|
||||
// brutal is for Hysteria servers, not services, and a panic here, in
|
||||
// a goroutine of http3, would end the process
|
||||
return nil, errors.New("unsupported congestion control over h3: ", quicParams.Congestion)
|
||||
}
|
||||
|
||||
@@ -284,8 +315,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
return nil, errors.New("failed to dial to dest: unexpected ", reflect.TypeOf(c))
|
||||
}
|
||||
|
||||
// built for each dial with the host as SNI, as for h2: http3 sets the
|
||||
// SNI on a copy, which a pinned CA and the ECH lookup do not see
|
||||
// Set SNI before certificate pinning and ECH lookup.
|
||||
gotlsConfig := tlsConfig.GetTLSConfig(tls.WithDestination(host))
|
||||
// it is for servers, and ChromeParrot refuses a config that has it
|
||||
gotlsConfig.GetCertificate = nil
|
||||
@@ -299,8 +329,8 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
pktConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
stop := context.AfterFunc(connCtx, func() { qconn.CloseWithError(quic.ApplicationErrorCode(http3.ErrCodeNoError), "") })
|
||||
context.AfterFunc(qconn.Context(), func() { stop(); tr.Close(); pktConn.Close() })
|
||||
stopConn := context.AfterFunc(connCtx, func() { qconn.CloseWithError(quic.ApplicationErrorCode(http3.ErrCodeNoError), "") })
|
||||
context.AfterFunc(qconn.Context(), func() { stopConn(); tr.Close(); pktConn.Close() })
|
||||
if quicParams.Congestion != "reno" {
|
||||
congestion.UseBBR(qconn, bbr.Profile(quicParams.BbrProfile))
|
||||
}
|
||||
@@ -324,8 +354,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
}
|
||||
}
|
||||
|
||||
// ctxConn is a connection that connCtx no longer closes once it is closed,
|
||||
// so that one that ends on its own leaves nothing behind in connCtx
|
||||
// Closing the socket unregisters the owner-context callback.
|
||||
type ctxConn struct {
|
||||
net.Conn
|
||||
stop func() bool
|
||||
@@ -336,9 +365,7 @@ func (c *ctxConn) Close() error {
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// secureTransport keeps a host to one connection, all that h2 needs, as without
|
||||
// a limit parallel requests would each dial their own. A host that answers over
|
||||
// h1 moves to a transport with more, since h1 carries one request at a time
|
||||
// Use one h2 connection per host, but allow parallel h1 connections.
|
||||
type secureTransport struct {
|
||||
h2, h1 http.RoundTripper
|
||||
h1Hosts *sync.Map
|
||||
@@ -355,162 +382,153 @@ func (t *secureTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (t *secureTransport) CloseIdleConnections() {
|
||||
closeIdleTransport(t.h2)
|
||||
closeIdleTransport(t.h1)
|
||||
}
|
||||
|
||||
var errSessionClosed = errors.New("the session is closed")
|
||||
|
||||
// connPool hands the sessions of a storage the connections of XMUX, each a
|
||||
// client of its own made by newClient
|
||||
// XMUX selects a lease once, not repeatedly while looking for a connection.
|
||||
// Running references cover both the session and any response bodies still open.
|
||||
type connPool struct {
|
||||
mu sync.Mutex
|
||||
xmux *splithttp.XmuxManager
|
||||
}
|
||||
|
||||
func newConnPool(config *splithttp.XmuxConfig, newClient func(connCtx context.Context) *http.Client) *connPool {
|
||||
var xmuxConfig splithttp.XmuxConfig
|
||||
if config != nil {
|
||||
xmuxConfig = *config
|
||||
}
|
||||
return &connPool{xmux: splithttp.NewXmuxManager(xmuxConfig, func() splithttp.XmuxConn {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &poolConn{next: newClient(ctx).Transport, cancel: cancel}
|
||||
})}
|
||||
}
|
||||
|
||||
// poolConn is a connection of XMUX, which closes once XMUX drops it and the
|
||||
// requests on it end
|
||||
type poolConn struct {
|
||||
next http.RoundTripper
|
||||
mu sync.Mutex
|
||||
mux *splithttp.XmuxManager
|
||||
media []*splithttp.XmuxManager // Drive-only, one connection per round-robin lane
|
||||
next int
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
mu sync.Mutex
|
||||
inflight int
|
||||
closing bool
|
||||
}
|
||||
|
||||
func (c *poolConn) IsClosed() bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.closing
|
||||
type poolConn struct {
|
||||
transport http.RoundTripper
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
stop func() bool
|
||||
}
|
||||
|
||||
func (c *poolConn) IsClosed() bool { return c.ctx.Err() != nil }
|
||||
|
||||
func (c *poolConn) Close() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.closing = true
|
||||
if c.inflight == 0 {
|
||||
c.cancel()
|
||||
}
|
||||
c.cancel()
|
||||
c.stop()
|
||||
closeIdleTransport(c.transport)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *poolConn) done() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.inflight--
|
||||
if c.closing && c.inflight == 0 {
|
||||
c.cancel()
|
||||
// driveMediaConns is the number of Drive media connections: XMUX
|
||||
// maxConnections when set, else 4. One Google connection carries only a
|
||||
// fraction of a link, so media requests are spread over these.
|
||||
func driveMediaConns(x *splithttp.XmuxConfig) int32 {
|
||||
if x != nil && x.MaxConnections != nil && x.MaxConnections.To > 0 {
|
||||
return x.MaxConnections.To
|
||||
}
|
||||
return 4
|
||||
}
|
||||
|
||||
// Positive conns gives Drive round-robin lanes; other backends keep one manager.
|
||||
func newConnPool(config *splithttp.XmuxConfig, conns int32, newClient func(context.Context) *http.Client) *connPool {
|
||||
if config == nil {
|
||||
config = &splithttp.XmuxConfig{}
|
||||
}
|
||||
maxConns := config.MaxConnections
|
||||
if conns > 0 {
|
||||
maxConns = &splithttp.RangeConfig{From: 1, To: 1}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
p := &connPool{ctx: ctx, cancel: cancel}
|
||||
newConn := func() splithttp.XmuxConn {
|
||||
ctx, cancel := context.WithCancel(p.ctx)
|
||||
c := &poolConn{ctx: ctx, cancel: cancel, transport: newClient(ctx).Transport}
|
||||
c.stop = context.AfterFunc(ctx, func() { closeIdleTransport(c.transport) })
|
||||
return c
|
||||
}
|
||||
newMux := func() *splithttp.XmuxManager {
|
||||
return splithttp.NewXmuxManager(splithttp.XmuxConfig{
|
||||
MaxConnections: maxConns, MaxConcurrency: config.MaxConcurrency,
|
||||
CMaxReuseTimes: config.CMaxReuseTimes, HMaxRequestTimes: config.HMaxRequestTimes,
|
||||
HMaxReusableSecs: config.HMaxReusableSecs, HKeepAlivePeriod: config.HKeepAlivePeriod,
|
||||
}, newConn)
|
||||
}
|
||||
p.mux = newMux()
|
||||
for i := int32(0); i < conns; i++ {
|
||||
mux := p.mux
|
||||
if i > 0 {
|
||||
mux = newMux()
|
||||
}
|
||||
p.media = append(p.media, mux)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *connPool) Close() {
|
||||
if p != nil {
|
||||
p.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// roundTrip sends a request counted in inflight by the caller
|
||||
func (c *poolConn) roundTrip(r *http.Request) (*http.Response, error) {
|
||||
resp, err := c.next.RoundTrip(r)
|
||||
if err != nil {
|
||||
c.done()
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &doneBody{ReadCloser: resp.Body, done: sync.OnceFunc(c.done)}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
type doneBody struct {
|
||||
io.ReadCloser
|
||||
done func()
|
||||
}
|
||||
|
||||
func (b *doneBody) Close() error {
|
||||
err := b.ReadCloser.Close()
|
||||
b.done()
|
||||
return err
|
||||
}
|
||||
|
||||
// a connection that has not answered yet is given this long before its
|
||||
// timeouts retire it, so that a dial or handshake is not cut short again
|
||||
var stalledGrace = 12 * time.Second
|
||||
|
||||
// sessionTransport sends the requests of one session over a connection of
|
||||
// XMUX, and over another once that one has no requests or time left
|
||||
type sessionTransport struct {
|
||||
pool *connPool
|
||||
|
||||
mu sync.Mutex
|
||||
client *splithttp.XmuxClient
|
||||
closed bool
|
||||
slowAt, retiredAt time.Time
|
||||
movedAt time.Time
|
||||
takenAt time.Time
|
||||
served bool
|
||||
pool *connPool
|
||||
client *splithttp.XmuxClient // guarded by pool.mu
|
||||
closed bool
|
||||
// spread selects a pool connection per request instead of pinning one.
|
||||
spread bool
|
||||
}
|
||||
|
||||
func (t *sessionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
t.mu.Lock()
|
||||
if t.closed {
|
||||
t.mu.Unlock()
|
||||
p := t.pool
|
||||
p.mu.Lock()
|
||||
if t.closed || p.ctx.Err() != nil || r.Context().Err() != nil {
|
||||
p.mu.Unlock()
|
||||
if r.Body != nil {
|
||||
r.Body.Close()
|
||||
}
|
||||
if err := r.Context().Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errSessionClosed
|
||||
}
|
||||
client := t.client
|
||||
if client == nil || client.XmuxConn.IsClosed() || client.LeftRequests.Add(-1) < 0 || !client.UnreusableAt.IsZero() && time.Now().After(client.UnreusableAt) {
|
||||
t.pool.mu.Lock()
|
||||
t.client = t.pool.xmux.GetXmuxClient(r.Context())
|
||||
t.pool.mu.Unlock()
|
||||
t.client.AddRunning()
|
||||
t.client.LeftRequests.Add(-1)
|
||||
if client != nil {
|
||||
client.DoneRunning()
|
||||
t.movedAt = time.Now()
|
||||
c := t.client
|
||||
if t.spread {
|
||||
mux := p.mux
|
||||
if len(p.media) != 0 {
|
||||
mux = p.media[p.next]
|
||||
p.next = (p.next + 1) % len(p.media)
|
||||
}
|
||||
client = t.client
|
||||
t.takenAt, t.served = time.Now(), false
|
||||
}
|
||||
// counted under mu, or another request of the session that moves on could
|
||||
// close the connection before this one is sent
|
||||
conn := client.XmuxConn.(*poolConn)
|
||||
conn.mu.Lock()
|
||||
conn.inflight++
|
||||
conn.mu.Unlock()
|
||||
t.mu.Unlock()
|
||||
resp, err := conn.roundTrip(r)
|
||||
if err == nil {
|
||||
t.mu.Lock()
|
||||
if t.client == client {
|
||||
t.served = true
|
||||
c = mux.GetXmuxClient(r.Context())
|
||||
} else if c == nil || c.XmuxConn.IsClosed() || c.LeftRequests.Load() <= 0 || (!c.UnreusableAt.IsZero() && time.Now().After(c.UnreusableAt)) {
|
||||
if c != nil {
|
||||
c.DoneRunning()
|
||||
}
|
||||
t.mu.Unlock()
|
||||
c = p.mux.GetXmuxClient(r.Context())
|
||||
c.AddRunning()
|
||||
t.client = c
|
||||
}
|
||||
return resp, err
|
||||
c.LeftRequests.Add(-1)
|
||||
c.AddRunning()
|
||||
p.mu.Unlock()
|
||||
resp, err := c.XmuxConn.(*poolConn).transport.RoundTrip(r)
|
||||
if err != nil {
|
||||
c.DoneRunning()
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &leasedBody{ReadCloser: resp.Body, release: sync.OnceFunc(c.DoneRunning)}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (t *sessionTransport) stalled(began time.Time) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if began.Before(t.movedAt) {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if !t.served && now.Sub(t.takenAt) < stalledGrace {
|
||||
return
|
||||
}
|
||||
slow := now.Sub(t.slowAt) < 3*time.Second
|
||||
t.slowAt = now
|
||||
if !slow || t.client == nil || now.Sub(t.retiredAt) < 2*time.Second {
|
||||
return
|
||||
}
|
||||
t.retiredAt = now
|
||||
t.client.XmuxConn.(*poolConn).Close()
|
||||
type leasedBody struct {
|
||||
io.ReadCloser
|
||||
release func()
|
||||
}
|
||||
|
||||
func (b *leasedBody) Close() error {
|
||||
defer b.release()
|
||||
return b.ReadCloser.Close()
|
||||
}
|
||||
|
||||
func (t *sessionTransport) Close() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.pool.mu.Lock()
|
||||
defer t.pool.mu.Unlock()
|
||||
t.closed = true
|
||||
if t.client != nil {
|
||||
t.client.DoneRunning()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,21 +15,31 @@ var placeholderAddr = &net.TCPAddr{IP: net.IP{127, 0, 0, 1}, Port: 0}
|
||||
// Conn is a session in segments, walWriter and walReader, or in slots,
|
||||
// slotWriter and slotReader
|
||||
type Conn struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
writer io.WriteCloser
|
||||
writer connWriter
|
||||
reader chunkReader
|
||||
onClose func()
|
||||
|
||||
readMu sync.Mutex
|
||||
readBuf []byte
|
||||
|
||||
deadlineMu sync.Mutex
|
||||
readDeadline time.Time
|
||||
writeDeadline time.Time
|
||||
readDeadline *pipeDeadline
|
||||
writeDeadline *pipeDeadline
|
||||
closing chan struct{}
|
||||
|
||||
publishWG sync.WaitGroup // registered before Dial exposes the connection
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
type connWriter interface {
|
||||
io.WriteCloser
|
||||
// writeUntil returns errWriteStopped, with the bytes it took, once either
|
||||
// channel is closed
|
||||
writeUntil(p []byte, deadline, closing <-chan struct{}) (int, error)
|
||||
}
|
||||
|
||||
type chunkReader interface {
|
||||
// chunks is closed when there are no more, then Err says why
|
||||
chunks() <-chan []byte
|
||||
@@ -37,54 +47,99 @@ type chunkReader interface {
|
||||
Wake()
|
||||
}
|
||||
|
||||
func newConn(ctx context.Context, storage Storage, writePrefix, readPrefix string, p params, onClose func()) *Conn {
|
||||
func newConn(ctx context.Context, storage Storage, writePrefix, readPrefix string, p params, discard bool, onClose func()) *Conn {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
return &Conn{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
writer: newWALWriter(ctx, storage, writePrefix, p),
|
||||
reader: newWALReader(ctx, storage, readPrefix, p),
|
||||
reader: newWALReader(ctx, storage, readPrefix, p, discard),
|
||||
onClose: onClose,
|
||||
|
||||
readDeadline: newPipeDeadline(),
|
||||
writeDeadline: newPipeDeadline(),
|
||||
closing: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func newSlotConn(ctx context.Context, store slotStore, write, read slotTable, p params, first []byte, onClose func()) *Conn {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
ctx, fail := context.WithCancelCause(ctx)
|
||||
closing := make(chan struct{})
|
||||
return &Conn{
|
||||
cancel: cancel,
|
||||
writer: newSlotWriter(ctx, store, write, p),
|
||||
reader: newSlotReader(ctx, store, read, p, first),
|
||||
ctx: ctx,
|
||||
cancel: func() { fail(context.Canceled) },
|
||||
writer: newSlotWriter(ctx, fail, store, write, p),
|
||||
reader: newSlotReader(ctx, fail, store, read, p, first, closing),
|
||||
onClose: onClose,
|
||||
|
||||
readDeadline: newPipeDeadline(),
|
||||
writeDeadline: newPipeDeadline(),
|
||||
closing: closing,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) Read(b []byte) (int, error) {
|
||||
if len(c.readBuf) == 0 {
|
||||
data, err := c.receive()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.readBuf = data
|
||||
c.readMu.Lock()
|
||||
defer c.readMu.Unlock()
|
||||
|
||||
select {
|
||||
case <-c.closing:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-c.readDeadline.wait():
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
if len(b) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if len(c.readBuf) > 0 {
|
||||
// Check state again before consuming buffered bytes: deadline or Close
|
||||
// may have happened after we filled readBuf but before this Read call.
|
||||
select {
|
||||
case <-c.closing:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-c.readDeadline.wait():
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
n := copy(b, c.readBuf)
|
||||
c.readBuf = c.readBuf[n:]
|
||||
if len(c.readBuf) == 0 {
|
||||
c.readBuf = nil
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
data, err := c.receive()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.readBuf = data
|
||||
n := copy(b, c.readBuf)
|
||||
c.readBuf = c.readBuf[n:]
|
||||
if len(c.readBuf) == 0 {
|
||||
c.readBuf = nil
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (c *Conn) receive() ([]byte, error) {
|
||||
deadline := c.getDeadline(true)
|
||||
if deadline.IsZero() {
|
||||
data, ok := <-c.reader.chunks()
|
||||
if !ok {
|
||||
return nil, c.reader.Err()
|
||||
}
|
||||
return data, nil
|
||||
select {
|
||||
case <-c.closing:
|
||||
return nil, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
|
||||
if !time.Now().Before(deadline) {
|
||||
deadline := c.readDeadline.wait()
|
||||
select {
|
||||
case <-deadline:
|
||||
return nil, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
timer := time.NewTimer(time.Until(deadline))
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case data, ok := <-c.reader.chunks():
|
||||
@@ -92,17 +147,36 @@ func (c *Conn) receive() ([]byte, error) {
|
||||
return nil, c.reader.Err()
|
||||
}
|
||||
return data, nil
|
||||
case <-timer.C:
|
||||
case <-deadline:
|
||||
return nil, os.ErrDeadlineExceeded
|
||||
case <-c.closing:
|
||||
return nil, io.ErrClosedPipe
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) Write(b []byte) (int, error) {
|
||||
if deadline := c.getDeadline(false); !deadline.IsZero() && !time.Now().Before(deadline) {
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
select {
|
||||
case <-c.closing:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
n, err := c.writer.Write(b)
|
||||
if err == nil {
|
||||
deadline := c.writeDeadline.wait()
|
||||
select {
|
||||
case <-deadline:
|
||||
return 0, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
|
||||
n, err := c.writer.writeUntil(b, deadline, c.closing)
|
||||
if err == errWriteStopped {
|
||||
select {
|
||||
case <-c.closing:
|
||||
err = io.ErrClosedPipe
|
||||
default:
|
||||
err = os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
c.reader.Wake()
|
||||
}
|
||||
return n, err
|
||||
@@ -110,15 +184,70 @@ func (c *Conn) Write(b []byte) (int, error) {
|
||||
|
||||
func (c *Conn) Close() error {
|
||||
c.closeOnce.Do(func() {
|
||||
c.closeErr = c.writer.Close()
|
||||
c.cancel()
|
||||
if c.onClose != nil {
|
||||
c.onClose()
|
||||
close(c.closing)
|
||||
c.readDeadline.stop()
|
||||
c.writeDeadline.stop()
|
||||
done := make(chan struct{})
|
||||
var result error
|
||||
started := time.Now()
|
||||
progress := func() time.Time { return started }
|
||||
if writer, ok := c.writer.(*slotWriter); ok {
|
||||
writer.markProgress()
|
||||
reader := c.reader.(*slotReader)
|
||||
progress = func() time.Time {
|
||||
last := writer.closeProgress()
|
||||
// Inbound activity must not hide a stalled outbound writer.
|
||||
if credit := reader.drainCredit.Load(); isClosedChan(writer.done) && credit != nil && credit.After(last) {
|
||||
return *credit
|
||||
}
|
||||
return last
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
result = c.closeOrdered(c.writer.Close())
|
||||
close(done)
|
||||
}()
|
||||
c.closeErr = waitCloseProgress(done, progress)
|
||||
if c.closeErr == nil {
|
||||
c.closeErr = result
|
||||
}
|
||||
c.cancel()
|
||||
})
|
||||
return c.closeErr
|
||||
}
|
||||
|
||||
func (c *Conn) closeOrdered(err error) error {
|
||||
c.publishWG.Wait()
|
||||
if err == nil {
|
||||
if writer, ok := c.writer.(interface{ Err() error }); ok {
|
||||
err = writer.Err()
|
||||
}
|
||||
}
|
||||
if reader, ok := c.reader.(*slotReader); ok && err == nil {
|
||||
// Our END says nothing about the peer's outstanding writes. Keep the
|
||||
// discard reader and its ACK worker alive through the peer's END.
|
||||
// The outer watchdog bounds this wait even if the peer never closes.
|
||||
reader.wait()
|
||||
err = context.Cause(c.ctx)
|
||||
}
|
||||
c.cancel()
|
||||
if writer, ok := c.writer.(interface{ wait() }); ok {
|
||||
writer.wait()
|
||||
}
|
||||
if reader, ok := c.reader.(interface{ wait() }); ok {
|
||||
reader.wait()
|
||||
}
|
||||
if c.onClose != nil {
|
||||
c.onClose()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Conn) Interrupt() {
|
||||
c.cancel()
|
||||
c.Close()
|
||||
}
|
||||
|
||||
func (c *Conn) LocalAddr() net.Addr {
|
||||
return placeholderAddr
|
||||
}
|
||||
@@ -127,33 +256,101 @@ func (c *Conn) RemoteAddr() net.Addr {
|
||||
return placeholderAddr
|
||||
}
|
||||
|
||||
func (c *Conn) getDeadline(read bool) time.Time {
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
if read {
|
||||
return c.readDeadline
|
||||
}
|
||||
return c.writeDeadline
|
||||
}
|
||||
|
||||
func (c *Conn) SetDeadline(t time.Time) error {
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.readDeadline = t
|
||||
c.writeDeadline = t
|
||||
c.readDeadline.set(t)
|
||||
c.writeDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) SetReadDeadline(t time.Time) error {
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.readDeadline = t
|
||||
c.readDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) SetWriteDeadline(t time.Time) error {
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.writeDeadline = t
|
||||
c.writeDeadline.set(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
// pipeDeadline is a deadline whose wait channel closes when it passes. Setting
|
||||
// a new time re-arms it, so a call already waiting on the channel sees the
|
||||
// change.
|
||||
type pipeDeadline struct {
|
||||
mu sync.Mutex
|
||||
timer *time.Timer
|
||||
cancel chan struct{}
|
||||
gen uint64
|
||||
stopped bool
|
||||
}
|
||||
|
||||
func newPipeDeadline() *pipeDeadline {
|
||||
return &pipeDeadline{cancel: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (d *pipeDeadline) set(t time.Time) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if d.stopped {
|
||||
return
|
||||
}
|
||||
|
||||
if d.timer != nil {
|
||||
// Stop does not join a callback that has already started; gen makes
|
||||
// that callback skip its close, so a channel is closed at most once.
|
||||
d.timer.Stop()
|
||||
d.timer = nil
|
||||
d.gen++
|
||||
}
|
||||
|
||||
closed := isClosedChan(d.cancel)
|
||||
if t.IsZero() {
|
||||
if closed {
|
||||
d.cancel = make(chan struct{})
|
||||
}
|
||||
return
|
||||
}
|
||||
if dur := time.Until(t); dur > 0 {
|
||||
if closed {
|
||||
d.cancel = make(chan struct{})
|
||||
}
|
||||
cancel, gen := d.cancel, d.gen
|
||||
d.timer = time.AfterFunc(dur, func() {
|
||||
d.mu.Lock()
|
||||
if d.gen == gen {
|
||||
close(cancel)
|
||||
}
|
||||
d.mu.Unlock()
|
||||
})
|
||||
return
|
||||
}
|
||||
if !closed {
|
||||
close(d.cancel)
|
||||
d.gen++
|
||||
}
|
||||
}
|
||||
|
||||
func (d *pipeDeadline) stop() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if d.timer != nil {
|
||||
d.timer.Stop()
|
||||
d.timer = nil
|
||||
}
|
||||
d.gen++ // an in-flight callback must not close a channel reused later
|
||||
d.stopped = true
|
||||
}
|
||||
|
||||
func (d *pipeDeadline) wait() chan struct{} {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.cancel
|
||||
}
|
||||
|
||||
func isClosedChan(c <-chan struct{}) bool {
|
||||
select {
|
||||
case <-c:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
+865
-724
File diff suppressed because it is too large
Load Diff
@@ -1,99 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDecodeRingCaps(t *testing.T) {
|
||||
good := ring{
|
||||
Up: slotTable{Slots: []string{"a", "b"}, Watermark: "w"},
|
||||
Down: slotTable{Slots: []string{"c", "d"}, Watermark: "w"},
|
||||
}
|
||||
b, _ := json.Marshal(good)
|
||||
if _, ok := decodeRing(b); !ok {
|
||||
t.Fatal("a normal ring was rejected")
|
||||
}
|
||||
|
||||
tooMany := good
|
||||
tooMany.Up.Slots = make([]string, maxConcurrency+1)
|
||||
for i := range tooMany.Up.Slots {
|
||||
tooMany.Up.Slots[i] = "s"
|
||||
}
|
||||
b, _ = json.Marshal(tooMany)
|
||||
if _, ok := decodeRing(b); ok {
|
||||
t.Fatalf("a ring with %d slots per table was accepted", maxConcurrency+1)
|
||||
}
|
||||
|
||||
longID := good
|
||||
longID.Up.Slots[0] = strings.Repeat("x", maxSlotIDLen+1)
|
||||
b, _ = json.Marshal(longID)
|
||||
if _, ok := decodeRing(b); ok {
|
||||
t.Fatal("a ring with an over-long slot id was accepted")
|
||||
}
|
||||
|
||||
longWM := good
|
||||
longWM.Down.Watermark = strings.Repeat("w", maxSlotIDLen+1)
|
||||
b, _ = json.Marshal(longWM)
|
||||
if _, ok := decodeRing(b); ok {
|
||||
t.Fatal("a ring with an over-long watermark id was accepted")
|
||||
}
|
||||
|
||||
emptyID := good
|
||||
emptyID.Down.Slots[1] = ""
|
||||
b, _ = json.Marshal(emptyID)
|
||||
if _, ok := decodeRing(b); ok {
|
||||
t.Fatal("a ring with an empty slot id was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func capTestStorage(t *testing.T, body []byte) (*driveStorage, string) {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write(body)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return &driveStorage{
|
||||
driveShared: &driveShared{token: "t", tokenExpiry: time.Now().Add(time.Hour)},
|
||||
client: srv.Client(),
|
||||
inflight: make(chan struct{}, 1),
|
||||
reserved: make(chan struct{}, 1),
|
||||
}, srv.URL
|
||||
}
|
||||
|
||||
func TestDriveResponseBodyCap(t *testing.T) {
|
||||
old := driveMaxResponse
|
||||
driveMaxResponse = 16
|
||||
t.Cleanup(func() { driveMaxResponse = old })
|
||||
s, url := capTestStorage(t, make([]byte, 32))
|
||||
_, _, err := s.do(context.Background(), http.MethodGet, url, "", nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds") {
|
||||
t.Fatalf("an over-cap body returned %v, want a cap error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveAnnouncementBodyCap(t *testing.T) {
|
||||
s, url := capTestStorage(t, make([]byte, 32))
|
||||
ctx := context.WithValue(context.Background(), maxBodyKey{}, int64(8))
|
||||
_, _, err := s.do(ctx, http.MethodGet, url, "", nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds") {
|
||||
t.Fatalf("an over-cap announcement returned %v, want a cap error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveNormal16MiBSegment(t *testing.T) {
|
||||
body := make([]byte, 16<<20)
|
||||
s, url := capTestStorage(t, body)
|
||||
_, payload, err := s.do(context.Background(), http.MethodGet, url, "", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("a normal 16 MiB segment failed: %v", err)
|
||||
}
|
||||
if len(payload) != len(body) {
|
||||
t.Fatalf("read %d bytes, want %d", len(payload), len(body))
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
func livePercentileReport(t *testing.T, label string, samples []time.Duration) {
|
||||
t.Helper()
|
||||
if len(samples) == 0 {
|
||||
t.Logf("%-36s no samples", label)
|
||||
return
|
||||
}
|
||||
sort.Slice(samples, func(i, j int) bool { return samples[i] < samples[j] })
|
||||
q := func(p float64) time.Duration {
|
||||
return samples[min(int(p*float64(len(samples))), len(samples)-1)]
|
||||
}
|
||||
t.Logf("%-36s n=%d p50=%v p95=%v p99=%v max=%v",
|
||||
label, len(samples), q(0.50), q(0.95), q(0.99), samples[len(samples)-1])
|
||||
}
|
||||
|
||||
func TestLiveDrivePercentiles(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
root, err := newDriveStorage(&internet.MemoryStreamConfig{}, config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
store := root.session().(*driveStorage)
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
const n = 60
|
||||
inlineDesc := strings.Repeat("a", 10<<10)
|
||||
body := make([]byte, 256<<10)
|
||||
if _, err := rand.Read(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
inlineID, err := store.makeSlot(ctx, "percentiles/inline")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.deleteID(ctx, flatten("percentiles/inline"), inlineID)
|
||||
mediaID, err := store.makeSlot(ctx, "percentiles/media")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.deleteID(ctx, flatten("percentiles/media"), mediaID)
|
||||
if err := store.setSlot(ctx, mediaID, "media", body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
measure := func(label string, parallelism int, op func() error) {
|
||||
var mu sync.Mutex
|
||||
samples := make([]time.Duration, 0, n)
|
||||
var wg sync.WaitGroup
|
||||
per := n / parallelism
|
||||
for w := 0; w < parallelism; w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < per; i++ {
|
||||
start := time.Now()
|
||||
err := op()
|
||||
elapsed := time.Since(start)
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", label, err)
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
samples = append(samples, elapsed)
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
livePercentileReport(t, fmt.Sprintf("%s (p=%d)", label, parallelism), samples)
|
||||
}
|
||||
|
||||
for _, p := range []int{1, 8} {
|
||||
measure("inline setSlot 10KiB", p, func() error {
|
||||
return store.setSlot(ctx, inlineID, inlineDesc, nil)
|
||||
})
|
||||
measure("media setSlot 256KiB", p, func() error {
|
||||
return store.setSlot(ctx, mediaID, "media", body)
|
||||
})
|
||||
measure("readDescription", p, func() error {
|
||||
_, err := store.readDescription(ctx, mediaID)
|
||||
return err
|
||||
})
|
||||
measure("readBody 256KiB", p, func() error {
|
||||
_, err := store.readBody(ctx, mediaID)
|
||||
return err
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveDriveLatencyUnderLoad(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
config.Concurrency = 64
|
||||
config.FlushIntervalMs = 10
|
||||
config.MaxPollIntervalMs = 200
|
||||
settings := &internet.MemoryStreamConfig{
|
||||
ProtocolName: protocolName,
|
||||
ProtocolSettings: config,
|
||||
}
|
||||
|
||||
run := func(withBulk bool) []time.Duration {
|
||||
client, server, cleanup := pairWith(t, settings)
|
||||
defer cleanup()
|
||||
if err := server.SetReadDeadline(time.Now().Add(10 * time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var writeMu sync.Mutex
|
||||
writeFrame := func(kind byte, payload []byte) error {
|
||||
writeMu.Lock()
|
||||
defer writeMu.Unlock()
|
||||
var header [5]byte
|
||||
header[0] = kind
|
||||
binary.BigEndian.PutUint32(header[1:], uint32(len(payload)))
|
||||
if _, err := client.Write(header[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := client.Write(payload)
|
||||
return err
|
||||
}
|
||||
readFrame := func() (byte, []byte, error) {
|
||||
var header [5]byte
|
||||
if _, err := io.ReadFull(server, header[:]); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
payload := make([]byte, binary.BigEndian.Uint32(header[1:]))
|
||||
if _, err := io.ReadFull(server, payload); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return header[0], payload, nil
|
||||
}
|
||||
|
||||
markers := make(chan time.Duration, 5)
|
||||
bulkTime := make(chan time.Duration, 1)
|
||||
go func() {
|
||||
var bulkRecv int
|
||||
var bulkStart time.Time
|
||||
for {
|
||||
kind, payload, err := readFrame()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if kind == 1 {
|
||||
if bulkRecv == 0 {
|
||||
bulkStart = time.Now()
|
||||
}
|
||||
bulkRecv += len(payload)
|
||||
if bulkRecv == 8<<20 {
|
||||
bulkTime <- time.Since(bulkStart)
|
||||
}
|
||||
}
|
||||
if kind == 2 && len(payload) == 16 {
|
||||
sent := int64(binary.BigEndian.Uint64(payload[:8]))
|
||||
markers <- time.Since(time.Unix(0, sent))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
bulkDone := make(chan struct{})
|
||||
if withBulk {
|
||||
go func() {
|
||||
defer close(bulkDone)
|
||||
chunk := make([]byte, 64<<10)
|
||||
for i := 0; i < 128; i++ {
|
||||
if err := writeFrame(1, chunk); err != nil {
|
||||
t.Errorf("bulk frame: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
var payload [16]byte
|
||||
binary.BigEndian.PutUint64(payload[:8], uint64(time.Now().UnixNano()))
|
||||
if err := writeFrame(2, payload[:]); err != nil {
|
||||
t.Fatalf("marker frame: %v", err)
|
||||
}
|
||||
if i < 4 {
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
if withBulk {
|
||||
<-bulkDone
|
||||
}
|
||||
out := make([]time.Duration, 0, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
select {
|
||||
case d := <-markers:
|
||||
out = append(out, d)
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("marker did not arrive")
|
||||
}
|
||||
}
|
||||
if withBulk {
|
||||
select {
|
||||
case d := <-bulkTime:
|
||||
t.Logf("bulk throughput: %.2f MiB/s", 8/d.Seconds())
|
||||
case <-time.After(60 * time.Second):
|
||||
t.Log("bulk throughput: bulk did not complete")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
t.Log("marker one-way latency with no bulk:")
|
||||
for i, d := range run(false) {
|
||||
t.Logf(" marker %d: %v", i+1, d.Round(time.Millisecond))
|
||||
}
|
||||
t.Log("marker one-way latency under 8MiB bulk:")
|
||||
for i, d := range run(true) {
|
||||
t.Logf(" marker %d: %v", i+1, d.Round(time.Millisecond))
|
||||
}
|
||||
}
|
||||
@@ -1,477 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"net/url"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
const liveSecretsEnv = "XRAY_XDRIVE_DRIVE_SECRETS"
|
||||
|
||||
func liveDriveConfig(t *testing.T) *Config {
|
||||
t.Helper()
|
||||
|
||||
path := os.Getenv(liveSecretsEnv)
|
||||
if path == "" {
|
||||
t.Skipf("set %s to run this test", liveSecretsEnv)
|
||||
}
|
||||
|
||||
payload, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("reading %s: %v", path, err)
|
||||
}
|
||||
var secrets struct {
|
||||
Folder string `json:"folder"`
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret string `json:"client_secret"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &secrets); err != nil {
|
||||
t.Fatalf("parsing %s: %v", path, err)
|
||||
}
|
||||
|
||||
config := &Config{
|
||||
RemoteFolder: secrets.Folder,
|
||||
Service: "google-drive",
|
||||
Secrets: []string{secrets.ClientID, secrets.ClientSecret, secrets.RefreshToken},
|
||||
SegmentBytes: 256 * 1024,
|
||||
FlushIntervalMs: 100,
|
||||
PollIntervalMs: 500,
|
||||
MaxPollIntervalMs: 2000,
|
||||
SessionTtlSeconds: 120,
|
||||
}
|
||||
if raw := os.Getenv("XRAY_XDRIVE_LIVE_SEGMENT"); raw != "" {
|
||||
config.SegmentBytes = uint32(envInt(t, "XRAY_XDRIVE_LIVE_SEGMENT"))
|
||||
}
|
||||
if raw := os.Getenv("XRAY_XDRIVE_LIVE_CONCURRENCY"); raw != "" {
|
||||
config.Concurrency = uint32(envInt(t, "XRAY_XDRIVE_LIVE_CONCURRENCY"))
|
||||
}
|
||||
|
||||
storage, err := newDriveStorage(&internet.MemoryStreamConfig{}, config)
|
||||
if err != nil {
|
||||
t.Fatalf("newDriveStorage: %v", err)
|
||||
}
|
||||
defer storage.Close()
|
||||
for _, dir := range []string{sessionsDir, streamsDir} {
|
||||
if err := storage.Delete(context.Background(), dir); err != nil {
|
||||
t.Fatalf("clearing %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
func envInt(t *testing.T, name string) int {
|
||||
t.Helper()
|
||||
|
||||
parsed, err := strconv.Atoi(os.Getenv(name))
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func TestLiveDriveStorage(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
storage, err := newDriveStorage(&internet.MemoryStreamConfig{}, config)
|
||||
if err != nil {
|
||||
t.Fatalf("newDriveStorage: %v", err)
|
||||
}
|
||||
defer storage.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
name := "streams/livetest/c2s/000000000.seg"
|
||||
payload := []byte("xdrive over a real remote storage service")
|
||||
defer storage.Delete(ctx, "streams/livetest")
|
||||
|
||||
start := time.Now()
|
||||
if err := storage.Put(ctx, name, payload); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
t.Logf("Put took %v", time.Since(start))
|
||||
|
||||
start = time.Now()
|
||||
names, err := storage.List(ctx, "streams/livetest/c2s")
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
t.Logf("List took %v", time.Since(start))
|
||||
if len(names) != 1 || names[0].Name != "000000000.seg" {
|
||||
t.Fatalf("List returned %v, want one segment", names)
|
||||
}
|
||||
|
||||
start = time.Now()
|
||||
got, err := storage.Get(ctx, name)
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
t.Logf("Get took %v", time.Since(start))
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("Get returned %q, want %q", got, payload)
|
||||
}
|
||||
|
||||
if _, err := storage.Get(ctx, "streams/livetest/c2s/000000009.seg"); err != errNotFound {
|
||||
t.Fatalf("Get returned %v, want errNotFound", err)
|
||||
}
|
||||
|
||||
if err := storage.Delete(ctx, "streams/livetest"); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
names, err = storage.List(ctx, "streams/livetest/c2s")
|
||||
if err != nil {
|
||||
t.Fatalf("List after delete: %v", err)
|
||||
}
|
||||
if len(names) != 0 {
|
||||
t.Fatalf("List after delete returned %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveDriveTransport(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
streamSettings := &internet.MemoryStreamConfig{
|
||||
ProtocolName: protocolName,
|
||||
ProtocolSettings: config,
|
||||
}
|
||||
|
||||
client, server, cleanup := pairWith(t, streamSettings)
|
||||
defer cleanup()
|
||||
|
||||
start := time.Now()
|
||||
if _, err := client.Write([]byte("ping")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
expectRead(t, server, "ping")
|
||||
t.Logf("client to server round took %v", time.Since(start))
|
||||
|
||||
start = time.Now()
|
||||
if _, err := server.Write([]byte("pong")); err != nil {
|
||||
t.Fatalf("server write: %v", err)
|
||||
}
|
||||
expectRead(t, client, "pong")
|
||||
t.Logf("server to client round took %v", time.Since(start))
|
||||
|
||||
size := 400000
|
||||
if raw := os.Getenv("XRAY_XDRIVE_LIVE_BYTES"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("XRAY_XDRIVE_LIVE_BYTES: %v", err)
|
||||
}
|
||||
size = parsed
|
||||
}
|
||||
payload := make([]byte, size)
|
||||
if _, err := rand.Read(payload); err != nil {
|
||||
t.Fatalf("rand: %v", err)
|
||||
}
|
||||
|
||||
start = time.Now()
|
||||
go func() {
|
||||
client.Write(payload)
|
||||
}()
|
||||
if err := server.SetReadDeadline(time.Now().Add(5 * time.Minute)); err != nil {
|
||||
t.Fatalf("SetReadDeadline: %v", err)
|
||||
}
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatalf("ReadFull: %v", err)
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("payload mismatch")
|
||||
}
|
||||
t.Logf("%d bytes took %v (%.1f KiB/s)", len(payload), elapsed,
|
||||
float64(len(payload))/1024/elapsed.Seconds())
|
||||
}
|
||||
|
||||
func TestLiveDriveParallelPut(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
storage, err := newDriveStorage(&internet.MemoryStreamConfig{}, config)
|
||||
if err != nil {
|
||||
t.Fatalf("newDriveStorage: %v", err)
|
||||
}
|
||||
defer storage.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
defer storage.Delete(ctx, "streams/benchtest")
|
||||
|
||||
chunk := make([]byte, 256*1024)
|
||||
if _, err := rand.Read(chunk); err != nil {
|
||||
t.Fatalf("rand: %v", err)
|
||||
}
|
||||
|
||||
if err := storage.Put(ctx, "streams/benchtest/warmup", chunk); err != nil {
|
||||
t.Fatalf("warmup: %v", err)
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
for i := 0; i < 4; i++ {
|
||||
if err := storage.Put(ctx, fmt.Sprintf("streams/benchtest/seq%d", i), chunk); err != nil {
|
||||
t.Fatalf("sequential put: %v", err)
|
||||
}
|
||||
}
|
||||
sequential := time.Since(start)
|
||||
t.Logf("4 sequential puts of 256 KiB: %v (%.1f KiB/s)",
|
||||
sequential, float64(4*len(chunk))/1024/sequential.Seconds())
|
||||
|
||||
start = time.Now()
|
||||
var wg sync.WaitGroup
|
||||
failures := make([]error, 8)
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
failures[i] = storage.Put(ctx, fmt.Sprintf("streams/benchtest/par%d", i), chunk)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
parallel := time.Since(start)
|
||||
for _, err := range failures {
|
||||
if err != nil {
|
||||
t.Fatalf("parallel put: %v", err)
|
||||
}
|
||||
}
|
||||
t.Logf("8 parallel puts of 256 KiB: %v (%.1f KiB/s)",
|
||||
parallel, float64(8*len(chunk))/1024/parallel.Seconds())
|
||||
|
||||
start = time.Now()
|
||||
names, err := storage.List(ctx, "streams/benchtest")
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
t.Logf("List of %d objects took %v", len(names), time.Since(start))
|
||||
|
||||
start = time.Now()
|
||||
wg = sync.WaitGroup{}
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
storage.Get(ctx, fmt.Sprintf("streams/benchtest/par%d", i))
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
download := time.Since(start)
|
||||
t.Logf("8 parallel gets of 256 KiB: %v (%.1f KiB/s)",
|
||||
download, float64(8*len(chunk))/1024/download.Seconds())
|
||||
}
|
||||
|
||||
func TestLiveDriveSegmentSweep(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
storage, err := newDriveStorage(&internet.MemoryStreamConfig{}, config)
|
||||
if err != nil {
|
||||
t.Fatalf("newDriveStorage: %v", err)
|
||||
}
|
||||
defer storage.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
defer storage.Delete(ctx, "streams/sweeptest")
|
||||
|
||||
const total = 1024 * 1024
|
||||
for _, size := range []int{64 * 1024, 128 * 1024, 256 * 1024, 512 * 1024} {
|
||||
chunk := make([]byte, size)
|
||||
if _, err := rand.Read(chunk); err != nil {
|
||||
t.Fatalf("rand: %v", err)
|
||||
}
|
||||
count := total / size
|
||||
|
||||
start := time.Now()
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < count; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
storage.Put(ctx, fmt.Sprintf("streams/sweeptest/s%d-%d", size, i), chunk)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
elapsed := time.Since(start)
|
||||
|
||||
t.Logf("%4d KiB x %2d = 1 MiB in %8v -> %6.1f KiB/s",
|
||||
size/1024, count, elapsed.Round(time.Millisecond),
|
||||
float64(total)/1024/elapsed.Seconds())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveDriveListLag(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
storage, err := newDriveStorage(&internet.MemoryStreamConfig{}, config)
|
||||
if err != nil {
|
||||
t.Fatalf("newDriveStorage: %v", err)
|
||||
}
|
||||
defer storage.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
defer storage.Delete(ctx, "streams/lagtest")
|
||||
|
||||
const rounds = 6
|
||||
var worst time.Duration
|
||||
|
||||
for i := 0; i < rounds; i++ {
|
||||
name := fmt.Sprintf("streams/lagtest/round%d/000000000.seg", i)
|
||||
if err := storage.Put(ctx, name, []byte("probe")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
var lag time.Duration
|
||||
for {
|
||||
names, err := storage.List(ctx, fmt.Sprintf("streams/lagtest/round%d", i))
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if len(names) == 1 {
|
||||
lag = time.Since(start)
|
||||
break
|
||||
}
|
||||
if time.Since(start) > 30*time.Second {
|
||||
t.Fatalf("round %d: the object never showed up in a listing", i)
|
||||
}
|
||||
}
|
||||
if lag > worst {
|
||||
worst = lag
|
||||
}
|
||||
t.Logf("round %d: the object became listable after %v", i, lag.Round(time.Millisecond))
|
||||
}
|
||||
t.Logf("worst listing lag: %v", worst.Round(time.Millisecond))
|
||||
}
|
||||
|
||||
func TestLiveDriveLatencyFloor(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
root, err := newDriveStorage(&internet.MemoryStreamConfig{}, config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
store := root.session().(*driveStorage)
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
const probe = "latency-floor/probe"
|
||||
id, err := store.makeSlot(ctx, probe)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.deleteID(ctx, flatten(probe), id)
|
||||
|
||||
small := newSlotFrame(1, slotInline, randomPayload(700)).encode()
|
||||
large := newSlotFrame(1, slotInline, randomPayload(slotInlineLimit)).encode()
|
||||
file := store.filesURL + "/" + url.PathEscape(id)
|
||||
|
||||
type sample struct {
|
||||
total, ttfb time.Duration
|
||||
reused bool
|
||||
}
|
||||
measure := func(label string, op func(context.Context) error) []sample {
|
||||
var out []sample
|
||||
for i := 0; i < 28; i++ {
|
||||
var wrote, first time.Time
|
||||
var reused bool
|
||||
trace := &httptrace.ClientTrace{
|
||||
GotConn: func(info httptrace.GotConnInfo) { reused = info.Reused },
|
||||
WroteRequest: func(httptrace.WroteRequestInfo) { wrote = time.Now() },
|
||||
GotFirstResponseByte: func() { first = time.Now() },
|
||||
}
|
||||
start := time.Now()
|
||||
err := op(httptrace.WithClientTrace(ctx, trace))
|
||||
total := time.Since(start)
|
||||
if err != nil {
|
||||
t.Logf("latency-floor: %s sample failed: %v", label, err)
|
||||
} else if i >= 3 {
|
||||
var ttfb time.Duration
|
||||
if !wrote.IsZero() && !first.IsZero() {
|
||||
ttfb = first.Sub(wrote)
|
||||
}
|
||||
out = append(out, sample{total, ttfb, reused})
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
}
|
||||
return out
|
||||
}
|
||||
report := func(label string, s []sample) time.Duration {
|
||||
if len(s) == 0 {
|
||||
t.Logf("latency-floor: %-30s no samples", label)
|
||||
return 0
|
||||
}
|
||||
totals := make([]time.Duration, len(s))
|
||||
ttfbs := make([]time.Duration, len(s))
|
||||
reused := 0
|
||||
for i, x := range s {
|
||||
totals[i], ttfbs[i] = x.total, x.ttfb
|
||||
if x.reused {
|
||||
reused++
|
||||
}
|
||||
}
|
||||
sort.Slice(totals, func(a, b int) bool { return totals[a] < totals[b] })
|
||||
sort.Slice(ttfbs, func(a, b int) bool { return ttfbs[a] < ttfbs[b] })
|
||||
q := func(v []time.Duration, p float64) time.Duration { return v[min(int(p*float64(len(v))), len(v)-1)] }
|
||||
t.Logf("latency-floor: %-30s n=%d min=%v p50=%v p95=%v ttfb_p50=%v reused=%d/%d",
|
||||
label, len(s), totals[0], q(totals, 0.5), q(totals, 0.95), q(ttfbs, 0.5), reused, len(s))
|
||||
return q(ttfbs, 0.5)
|
||||
}
|
||||
patch := func(target string, doc map[string]any) func(context.Context) error {
|
||||
body, _ := json.Marshal(doc)
|
||||
return func(ctx context.Context) error {
|
||||
status, reply, err := store.do(ctx, http.MethodPatch, target, "application/json; charset=UTF-8", body)
|
||||
if err == nil && status != http.StatusOK {
|
||||
err = fmt.Errorf("status %d: %s", status, reply)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
get := func(target string) func(context.Context) error {
|
||||
return func(ctx context.Context) error {
|
||||
status, reply, err := store.do(ctx, http.MethodGet, target, "", nil)
|
||||
if err == nil && status != http.StatusOK {
|
||||
err = fmt.Errorf("status %d: %s", status, reply)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
proto := ""
|
||||
netFloor := report("net floor (401, no auth)", measure("net", func(ctx context.Context) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.googleapis.com/drive/v3/about?fields=user", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := store.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
proto = resp.Proto
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
return resp.Body.Close()
|
||||
}))
|
||||
t.Logf("latency-floor: negotiated protocol %s", proto)
|
||||
readDesc := report("GET description (prod)", measure("get", func(ctx context.Context) error {
|
||||
_, err := store.readDescription(ctx, id)
|
||||
return err
|
||||
}))
|
||||
report("GET fields=id", measure("getid", get(file+"?fields=id&supportsAllDrives=true")))
|
||||
report("GET description, no allDrives", measure("getnoall", get(file+"?fields=description")))
|
||||
write1k := report("PATCH inline 1 KB (prod)", measure("p1k", func(ctx context.Context) error {
|
||||
return store.setSlot(ctx, id, small, nil)
|
||||
}))
|
||||
write14k := report("PATCH inline 14 KB (prod)", measure("p14k", func(ctx context.Context) error {
|
||||
return store.setSlot(ctx, id, large, nil)
|
||||
}))
|
||||
report("PATCH 1 KB, no allDrives", measure("pnoall", patch(file+"?fields=id", map[string]any{"description": small})))
|
||||
report("PATCH name 200 B", measure("pname", patch(file+"?fields=id&supportsAllDrives=true", map[string]any{"name": strings.Repeat("n", 200)})))
|
||||
report("PATCH appProperties 100 B", measure("pprop", patch(file+"?fields=id&supportsAllDrives=true", map[string]any{"appProperties": map[string]string{"k": strings.Repeat("a", 100)}})))
|
||||
t.Logf("latency-floor: derived: write backend ~ %v, read backend ~ %v, 14 KB payload cost ~ %v",
|
||||
write1k-netFloor, readDesc-netFloor, write14k-write1k)
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
func TestLiveDriveWriteSweep(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
root, err := newDriveStorage(&internet.MemoryStreamConfig{}, config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
store := root.session().(*driveStorage)
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
inlineID, err := store.makeSlot(ctx, "sweep/inline")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.deleteID(ctx, flatten("sweep/inline"), inlineID)
|
||||
mediaID, err := store.makeSlot(ctx, "sweep/media")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.deleteID(ctx, flatten("sweep/media"), mediaID)
|
||||
|
||||
desc := strings.Repeat("a", 10<<10)
|
||||
body := make([]byte, 256<<10)
|
||||
if _, err := rand.Read(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kinds := []struct {
|
||||
name string
|
||||
op func(context.Context) error
|
||||
}{
|
||||
{"inline 10KiB", func(ctx context.Context) error { return store.setSlot(ctx, inlineID, desc, nil) }},
|
||||
{"media 256KiB", func(ctx context.Context) error { return store.setSlot(ctx, mediaID, "media", body) }},
|
||||
}
|
||||
|
||||
for _, p := range []int{1, 2, 3, 4, 6, 8, 12} {
|
||||
for _, kind := range kinds {
|
||||
levelCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
thr0 := store.throttled()
|
||||
var mu sync.Mutex
|
||||
var samples []time.Duration
|
||||
success := 0
|
||||
var wg sync.WaitGroup
|
||||
per := 40 / p
|
||||
levelStart := time.Now()
|
||||
for w := 0; w < p; w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < per; i++ {
|
||||
if levelCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
if err := kind.op(levelCtx); err != nil {
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
samples = append(samples, time.Since(start))
|
||||
success++
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
wall := time.Since(levelStart)
|
||||
cancel()
|
||||
if len(samples) == 0 {
|
||||
t.Logf("sweep p=%-2d %-14s writes=0 wall=%v no samples", p, kind.name, wall.Round(time.Millisecond))
|
||||
continue
|
||||
}
|
||||
sort.Slice(samples, func(i, j int) bool { return samples[i] < samples[j] })
|
||||
q := func(f float64) time.Duration {
|
||||
return samples[min(int(f*float64(len(samples))), len(samples)-1)]
|
||||
}
|
||||
t.Logf("sweep p=%-2d %-14s writes=%d wall=%v writes/s=%.2f p50=%v p95=%v p99=%v max=%v throttled=+%d",
|
||||
p, kind.name, success, wall.Round(time.Millisecond), float64(success)/wall.Seconds(),
|
||||
q(0.50), q(0.95), q(0.99), samples[len(samples)-1], store.throttled()-thr0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveDriveBrowsingExchanges(t *testing.T) {
|
||||
config := liveDriveConfig(t)
|
||||
config.Concurrency = 64
|
||||
config.FlushIntervalMs = 10
|
||||
config.MaxPollIntervalMs = 200
|
||||
settings := &internet.MemoryStreamConfig{
|
||||
ProtocolName: protocolName,
|
||||
ProtocolSettings: config,
|
||||
}
|
||||
|
||||
var slotWrites, ackWrites, announceWrites, reads atomic.Int64
|
||||
testDriveIO = func(method, target string, body []byte) {
|
||||
switch method {
|
||||
case http.MethodGet:
|
||||
reads.Add(1)
|
||||
case http.MethodPatch:
|
||||
var doc struct {
|
||||
Description string `json:"description"`
|
||||
}
|
||||
if json.Unmarshal(body, &doc) != nil {
|
||||
return
|
||||
}
|
||||
if _, ok := decodeSlot(doc.Description); ok {
|
||||
slotWrites.Add(1)
|
||||
return
|
||||
}
|
||||
if _, err := strconv.ParseInt(doc.Description, 10, 64); err == nil && doc.Description != "" {
|
||||
ackWrites.Add(1)
|
||||
return
|
||||
}
|
||||
slotWrites.Add(1)
|
||||
case http.MethodPost, http.MethodPut:
|
||||
if method == http.MethodPut || strings.Contains(target, "/upload") {
|
||||
slotWrites.Add(1)
|
||||
return
|
||||
}
|
||||
var doc struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if json.Unmarshal(body, &doc) == nil && strings.HasPrefix(doc.Name, sessionsDir+flatSeparator) {
|
||||
announceWrites.Add(1)
|
||||
return
|
||||
}
|
||||
slotWrites.Add(1)
|
||||
}
|
||||
}
|
||||
defer func() { testDriveIO = nil }()
|
||||
|
||||
client, server, cleanup := pairWith(t, settings)
|
||||
if err := server.SetReadDeadline(time.Now().Add(10 * time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := client.SetReadDeadline(time.Now().Add(10 * time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer := randomPayload(30 << 10)
|
||||
latencies := make([]time.Duration, 0, 40)
|
||||
for i := 0; i < 40; i++ {
|
||||
start := time.Now()
|
||||
request := randomPayload(500)
|
||||
if _, err := client.Write(request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotRequest := make([]byte, len(request))
|
||||
if _, err := io.ReadFull(server, gotRequest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(gotRequest, request) {
|
||||
t.Fatal("the request came back changed")
|
||||
}
|
||||
if _, err := server.Write(answer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make([]byte, len(answer))
|
||||
if _, err := io.ReadFull(client, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, answer) {
|
||||
t.Fatal("the answer came back changed")
|
||||
}
|
||||
latencies = append(latencies, time.Since(start))
|
||||
if i < 39 {
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
cleanup()
|
||||
|
||||
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
|
||||
q := func(f float64) time.Duration {
|
||||
return latencies[min(int(f*float64(len(latencies))), len(latencies)-1)]
|
||||
}
|
||||
t.Logf("browsing: exchanges=%d p50=%v p95=%v max=%v",
|
||||
len(latencies), q(0.50), q(0.95), latencies[len(latencies)-1])
|
||||
total := slotWrites.Load() + ackWrites.Load() + announceWrites.Load()
|
||||
share := float64(0)
|
||||
if total > 0 {
|
||||
share = 100 * float64(ackWrites.Load()) / float64(total)
|
||||
}
|
||||
t.Logf("browsing writes: slot-data=%d watermark-ack=%d announcement=%d total=%d ack-share=%.1f%% reads=%d",
|
||||
slotWrites.Load(), ackWrites.Load(), announceWrites.Load(), total, share, reads.Load())
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,174 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type tokenServer struct {
|
||||
mu sync.Mutex
|
||||
count int
|
||||
mode int
|
||||
delay time.Duration
|
||||
srv *httptest.Server
|
||||
}
|
||||
|
||||
func newTokenServer(mode int, delay time.Duration) *tokenServer {
|
||||
ts := &tokenServer{mode: mode, delay: delay}
|
||||
ts.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ts.mu.Lock()
|
||||
ts.count++
|
||||
mode, delay := ts.mode, ts.delay
|
||||
ts.mu.Unlock()
|
||||
time.Sleep(delay)
|
||||
if mode != http.StatusOK {
|
||||
w.WriteHeader(mode)
|
||||
w.Write([]byte(`{"error":"temporarily_unavailable"}`))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"access_token":"new-token","expires_in":3600}`))
|
||||
}))
|
||||
return ts
|
||||
}
|
||||
|
||||
func (ts *tokenServer) requests() int {
|
||||
ts.mu.Lock()
|
||||
defer ts.mu.Unlock()
|
||||
return ts.count
|
||||
}
|
||||
|
||||
func (ts *tokenServer) storage() *driveStorage {
|
||||
return &driveStorage{driveShared: &driveShared{
|
||||
tokenClient: ts.srv.Client(),
|
||||
tokenURL: ts.srv.URL + "/token",
|
||||
}}
|
||||
}
|
||||
|
||||
func TestTokenSingleFlightDuringOutage(t *testing.T) {
|
||||
ts := newTokenServer(http.StatusInternalServerError, 200*time.Millisecond)
|
||||
defer ts.srv.Close()
|
||||
s := ts.storage()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 9)
|
||||
start := make(chan struct{})
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); <-start; _, err := s.accessToken(context.Background()); errs <- err }()
|
||||
close(start)
|
||||
// Wait until the single flight is in progress, then pile on waiters.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for ts.requests() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
for i := 0; i < 7; i++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); _, err := s.accessToken(context.Background()); errs <- err }()
|
||||
}
|
||||
cancelledCtx, cancel := context.WithCancel(context.Background())
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
cancel()
|
||||
_, err := s.accessToken(cancelledCtx)
|
||||
errs <- err
|
||||
}()
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
var cancelledSeen bool
|
||||
for err := range errs {
|
||||
if err == nil {
|
||||
t.Fatal("an outage caller succeeded")
|
||||
}
|
||||
if err == context.Canceled {
|
||||
cancelledSeen = true
|
||||
}
|
||||
}
|
||||
if !cancelledSeen {
|
||||
t.Fatal("the cancelled waiter did not return ctx.Err")
|
||||
}
|
||||
if n := ts.requests(); n != 1 {
|
||||
t.Fatalf("N concurrent callers caused %d token fetches, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenBackgroundFailureBacksOff(t *testing.T) {
|
||||
ts := newTokenServer(http.StatusInternalServerError, 0)
|
||||
defer ts.srv.Close()
|
||||
s := ts.storage()
|
||||
s.token = "cached"
|
||||
s.tokenLifetime = 10 * time.Second
|
||||
s.tokenExpiry = time.Now().Add(time.Second) // inside the refresh window
|
||||
|
||||
if tok, err := s.accessToken(context.Background()); err != nil || tok != "cached" {
|
||||
t.Fatalf("accessToken=%q err=%v", tok, err)
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for ts.requests() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if n := ts.requests(); n != 1 {
|
||||
t.Fatalf("background refresh made %d requests, want 1", n)
|
||||
}
|
||||
// A second call inside the backoff must not hit the endpoint again.
|
||||
if _, err := s.accessToken(context.Background()); err != nil {
|
||||
t.Fatalf("cached token should still be returned: %v", err)
|
||||
}
|
||||
if n := ts.requests(); n != 1 {
|
||||
t.Fatalf("a failing endpoint was hit %d times, want 1", n)
|
||||
}
|
||||
s.tokenMu.Lock()
|
||||
backoff := s.tokenBackoff
|
||||
retryAt := s.tokenRetryAt
|
||||
s.tokenMu.Unlock()
|
||||
if backoff < tokenRefreshBackoff {
|
||||
t.Fatalf("backoff %v below the default %v", backoff, tokenRefreshBackoff)
|
||||
}
|
||||
if !retryAt.After(time.Now()) {
|
||||
t.Fatal("tokenRetryAt not set into the future after a background failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestToken401RefetchOnce(t *testing.T) {
|
||||
ts := newTokenServer(http.StatusOK, 0)
|
||||
defer ts.srv.Close()
|
||||
s := ts.storage()
|
||||
s.token = "old"
|
||||
s.tokenLifetime = time.Hour
|
||||
s.tokenExpiry = time.Now().Add(time.Hour)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.invalidateToken("old")
|
||||
if _, err := s.accessToken(context.Background()); err != nil {
|
||||
t.Errorf("accessToken: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if n := ts.requests(); n != 1 {
|
||||
t.Fatalf("many 401 handlers caused %d refetches, want 1", n)
|
||||
}
|
||||
s.tokenMu.Lock()
|
||||
tok := s.token
|
||||
s.tokenMu.Unlock()
|
||||
if tok != "new-token" {
|
||||
t.Fatalf("token=%q, want new-token", tok)
|
||||
}
|
||||
// Invalidating with a stale used token must not clear the fresh one.
|
||||
s.invalidateToken("old")
|
||||
s.tokenMu.Lock()
|
||||
tok = s.token
|
||||
s.tokenMu.Unlock()
|
||||
if tok != "new-token" {
|
||||
t.Fatalf("stale invalidation cleared the fresh token: %q", tok)
|
||||
}
|
||||
}
|
||||
@@ -31,10 +31,14 @@ func (s *localStorage) resolve(name string) (string, error) {
|
||||
if clean == "/" {
|
||||
return "", errors.New("invalid object name: ", name)
|
||||
}
|
||||
if strings.HasPrefix(path.Base(clean), tempPrefix) {
|
||||
local, err := filepath.Localize(clean[1:])
|
||||
if err != nil {
|
||||
return "", errors.New("invalid object name: ", name).Base(err)
|
||||
}
|
||||
if strings.HasPrefix(filepath.Base(local), tempPrefix) {
|
||||
return "", errors.New("reserved object name: ", name)
|
||||
}
|
||||
return filepath.Join(s.root, filepath.FromSlash(clean[1:])), nil
|
||||
return filepath.Join(s.root, local), nil
|
||||
}
|
||||
|
||||
func (s *localStorage) Put(ctx context.Context, name string, data []byte) error {
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func TestLocalSharingViolation(t *testing.T) {
|
||||
storage, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
const name = "streams/session/c2s/000000000.seg"
|
||||
if err := storage.Put(context.Background(), name, []byte("segment")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
full, err := storage.resolve(name)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve: %v", err)
|
||||
}
|
||||
path, err := windows.UTF16PtrFromString(full)
|
||||
if err != nil {
|
||||
t.Fatalf("UTF16PtrFromString: %v", err)
|
||||
}
|
||||
|
||||
// os.Rename holds the file like this until a moment after its new name
|
||||
// appears
|
||||
handle, err := windows.CreateFile(path, windows.DELETE,
|
||||
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
|
||||
nil, windows.OPEN_EXISTING, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateFile: %v", err)
|
||||
}
|
||||
var once sync.Once
|
||||
release := func() { once.Do(func() { windows.CloseHandle(handle) }) }
|
||||
defer release()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, err := storage.Get(ctx, name); !errors.Is(err, windows.ERROR_SHARING_VIOLATION) {
|
||||
t.Fatalf("Get returned %v while the file is held, want a sharing violation", err)
|
||||
}
|
||||
|
||||
time.AfterFunc(100*time.Millisecond, release)
|
||||
data, err := storage.Get(context.Background(), name)
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if string(data) != "segment" {
|
||||
t.Fatalf("Get returned %q, want %q", data, "segment")
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ type params struct {
|
||||
holeTimeout time.Duration
|
||||
sessionTTL time.Duration
|
||||
concurrency int
|
||||
flightBytes int // Drive media bytes in flight per direction
|
||||
}
|
||||
|
||||
func millis(value uint32, fallback time.Duration) time.Duration {
|
||||
@@ -45,7 +46,7 @@ func capped(value uint32, fallback, limit int) int {
|
||||
if value == 0 {
|
||||
return fallback
|
||||
}
|
||||
if int(value) > limit {
|
||||
if uint64(value) > uint64(limit) {
|
||||
return limit
|
||||
}
|
||||
return int(value)
|
||||
@@ -72,18 +73,19 @@ func paramsFromConfig(c *Config) params {
|
||||
// is a slotStore and only to fields the config leaves at 0; wal-based backends
|
||||
// keep the defaults above because their concurrency and flush mean other things
|
||||
func paramsForStorage(c *Config, storage Storage) params {
|
||||
p := paramsFromConfig(c)
|
||||
if _, ok := storage.(slotStore); ok {
|
||||
cc := *c
|
||||
if cc.Concurrency == 0 {
|
||||
cc.Concurrency = 64
|
||||
if c.Concurrency == 0 {
|
||||
p.concurrency = 64
|
||||
}
|
||||
if cc.FlushIntervalMs == 0 {
|
||||
cc.FlushIntervalMs = 10
|
||||
// About one large frame per media connection keeps each one busy.
|
||||
p.flightBytes = int(driveMediaConns(c.Xmux)) * slotMaxFrame
|
||||
if c.FlushIntervalMs == 0 {
|
||||
p.flushInterval = 25 * time.Millisecond
|
||||
}
|
||||
if cc.MaxPollIntervalMs == 0 {
|
||||
cc.MaxPollIntervalMs = 200
|
||||
if c.MaxPollIntervalMs == 0 {
|
||||
p.maxPollInterval = max(200*time.Millisecond, p.minPollInterval)
|
||||
}
|
||||
c = &cc
|
||||
}
|
||||
return paramsFromConfig(c)
|
||||
return p
|
||||
}
|
||||
|
||||
@@ -55,6 +55,9 @@ func ValidateS3Config(c *Config) error {
|
||||
u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" {
|
||||
return errors.New("S3 endpoint must be an http(s) URL without credentials, query or fragment")
|
||||
}
|
||||
if host, err := httpguts.PunycodeHostPort(u.Host); err != nil || !httpguts.ValidHostHeader(host) {
|
||||
return errors.New("invalid S3 endpoint authority")
|
||||
}
|
||||
if !httpguts.ValidHeaderFieldValue(c.S3.Region) || strings.ContainsAny(c.S3.Region, "/, \t") {
|
||||
return errors.New("invalid S3 signing region")
|
||||
}
|
||||
@@ -108,6 +111,8 @@ func newS3Storage(streamSettings *internet.MemoryStreamConfig, c *Config) (*s3St
|
||||
return nil, err
|
||||
}
|
||||
base, _ := url.Parse(c.S3.Endpoint)
|
||||
// Match the ASCII authority net/http transmits before using it in SigV4.
|
||||
base.Host, _ = httpguts.PunycodeHostPort(base.Host)
|
||||
// Encode the endpoint prefix for SigV4 without turning escaped slashes into separators.
|
||||
segments := strings.Split(base.EscapedPath(), "/")
|
||||
for i, segment := range segments {
|
||||
@@ -142,7 +147,7 @@ func newS3Storage(streamSettings *internet.MemoryStreamConfig, c *Config) (*s3St
|
||||
}
|
||||
s := &s3Storage{
|
||||
s3Shared: &s3Shared{
|
||||
conns: newConnPool(c.Xmux, newClient),
|
||||
conns: newConnPool(c.Xmux, 0, newClient),
|
||||
base: *base,
|
||||
prefix: strings.TrimSuffix(c.RemoteFolder, "/") + "/",
|
||||
region: s3Region(c.S3.Region),
|
||||
@@ -278,6 +283,10 @@ func (s *s3Storage) do(ctx context.Context, method, key string, query url.Values
|
||||
case <-ctx.Done():
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-s.inflight
|
||||
return 0, nil, err
|
||||
}
|
||||
status, payload, after, err := s.attempt(ctx, method, key, query, body, payloadHash)
|
||||
<-s.inflight
|
||||
if ctx.Err() != nil {
|
||||
@@ -319,23 +328,29 @@ func (s *s3Storage) attempt(ctx context.Context, method, key string, query url.V
|
||||
s.sign(req, hash, time.Now())
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
if urlErr, ok := err.(*url.Error); ok {
|
||||
err = urlErr.Err
|
||||
}
|
||||
return 0, nil, 0, errors.New("S3 request failed").Base(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
limit := int64(maxSegmentBytes)
|
||||
limit := int64(adapterMaxMetadataBody)
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
limit = 64 << 10
|
||||
limit = adapterMaxErrorBody
|
||||
} else if method == http.MethodGet {
|
||||
if query.Get("list-type") != "" {
|
||||
limit = adapterMaxListResponse
|
||||
} else {
|
||||
limit = adapterObjectLimit(ctx)
|
||||
}
|
||||
}
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||
payload, err := readAdapterBody(resp.Body, limit)
|
||||
if err != nil {
|
||||
return resp.StatusCode, nil, 0, errors.New("failed to read S3 response (HTTP ", resp.StatusCode, ")").Base(err)
|
||||
}
|
||||
if int64(len(payload)) > limit {
|
||||
return 0, nil, 0, errors.New("S3 response exceeds size limit")
|
||||
}
|
||||
var after time.Duration
|
||||
if raw := resp.Header.Get("Retry-After"); raw != "" {
|
||||
if seconds, err := strconv.ParseInt(raw, 10, 32); err == nil && seconds > 0 {
|
||||
|
||||
+708
-900
File diff suppressed because it is too large
Load Diff
@@ -1,77 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// badBodySlots serves a media frame whose body never matches its checksum.
|
||||
type badBodySlots struct{}
|
||||
|
||||
func (badBodySlots) makeSlot(ctx context.Context, name string) (string, error) { return name, nil }
|
||||
func (badBodySlots) setSlot(ctx context.Context, id, description string, body []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (badBodySlots) readDescription(ctx context.Context, id string) (string, error) {
|
||||
return newSlotFrame(0, slotMedia, make([]byte, 64)).encode(), nil
|
||||
}
|
||||
|
||||
func (badBodySlots) readBody(ctx context.Context, id string) ([]byte, error) {
|
||||
return bytes.Repeat([]byte{1}, 64), nil
|
||||
}
|
||||
|
||||
// emptySlots serves an empty description: an idle slot, not a failure.
|
||||
type emptySlots struct{}
|
||||
|
||||
func (emptySlots) makeSlot(ctx context.Context, name string) (string, error) { return name, nil }
|
||||
func (emptySlots) setSlot(ctx context.Context, id, description string, body []byte) error {
|
||||
return nil
|
||||
}
|
||||
func (emptySlots) readDescription(ctx context.Context, id string) (string, error) { return "", nil }
|
||||
func (emptySlots) readBody(ctx context.Context, id string) ([]byte, error) { return nil, nil }
|
||||
|
||||
func shrinkStallClocks(t *testing.T) {
|
||||
t.Helper()
|
||||
// Only the stall timeout is shrunk; readers snapshot it at construction,
|
||||
// so lingering goroutines from other tests never read a mutated global.
|
||||
oldStall := slotStallTimeout
|
||||
slotStallTimeout = 100 * time.Millisecond
|
||||
t.Cleanup(func() { slotStallTimeout = oldStall })
|
||||
}
|
||||
|
||||
func TestHeadBodyChecksumMismatchFails(t *testing.T) {
|
||||
shrinkStallClocks(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
r := newSlotReader(ctx, badBodySlots{}, slotTable{Slots: []string{"id"}, Watermark: "w"},
|
||||
params{concurrency: 1, eagerWindow: 50 * time.Millisecond, maxPollInterval: 5 * time.Millisecond}, nil)
|
||||
select {
|
||||
case _, ok := <-r.chunks():
|
||||
if ok {
|
||||
t.Fatal("a mismatched body was delivered")
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("a persistent checksum mismatch retried forever")
|
||||
}
|
||||
if err := r.Err(); err == nil || !strings.Contains(err.Error(), "no usable body") {
|
||||
t.Fatalf("reader ended with %v, want a clear body error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptySlotStaysIdle(t *testing.T) {
|
||||
shrinkStallClocks(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
r := newSlotReader(ctx, emptySlots{}, slotTable{Slots: []string{"id"}, Watermark: "w"},
|
||||
params{concurrency: 1, eagerWindow: 50 * time.Millisecond, maxPollInterval: 5 * time.Millisecond}, nil)
|
||||
select {
|
||||
case <-r.chunks():
|
||||
t.Fatal("an empty slot failed the reader instead of staying idle")
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
@@ -1,926 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type memSlots struct {
|
||||
mu sync.Mutex
|
||||
next int
|
||||
descs map[string]string
|
||||
bodies map[string][]byte
|
||||
reads int
|
||||
}
|
||||
|
||||
func newMemSlots() *memSlots {
|
||||
return &memSlots{descs: make(map[string]string), bodies: make(map[string][]byte)}
|
||||
}
|
||||
|
||||
func (m *memSlots) makeSlot(ctx context.Context, name string) (string, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.next++
|
||||
id := "slot-" + strconv.Itoa(m.next)
|
||||
m.descs[id] = ""
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (m *memSlots) setSlot(ctx context.Context, id, description string, body []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.descs[id]; !ok {
|
||||
return errNotFound
|
||||
}
|
||||
m.descs[id] = description
|
||||
if body != nil {
|
||||
m.bodies[id] = bytes.Clone(body)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memSlots) readDescription(ctx context.Context, id string) (string, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.reads++
|
||||
d, ok := m.descs[id]
|
||||
if !ok {
|
||||
return "", errNotFound
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (m *memSlots) readBody(ctx context.Context, id string) ([]byte, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.bodies[id], nil
|
||||
}
|
||||
|
||||
// the slots of all tests are asked for often, set once as a goroutine of a
|
||||
// closed Conn may still read them
|
||||
func init() {
|
||||
slotHuntFloor, slotHuntCeiling, slotTailMin, slotTailMax = 2*time.Millisecond, 10*time.Millisecond, 5*time.Millisecond, 20*time.Millisecond
|
||||
slotAckRetry, slotWatermarkTTL = 2*time.Millisecond, 2*time.Millisecond
|
||||
}
|
||||
|
||||
func slotPair(t *testing.T, store slotStore, concurrency, segmentBytes uint32) (*Conn, *Conn) {
|
||||
t.Helper()
|
||||
p := paramsFromConfig(&Config{
|
||||
SegmentBytes: segmentBytes,
|
||||
FlushIntervalMs: 1,
|
||||
PollIntervalMs: 1,
|
||||
MaxPollIntervalMs: 20,
|
||||
EagerWindowMs: 50,
|
||||
Concurrency: concurrency,
|
||||
})
|
||||
r, err := makeRing(context.Background(), store, "session", p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := newSlotConn(context.Background(), store, r.Up, r.Down, p, nil, nil)
|
||||
server := newSlotConn(context.Background(), store, r.Down, r.Up, p, nil, nil)
|
||||
t.Cleanup(func() {
|
||||
client.Close()
|
||||
server.Close()
|
||||
})
|
||||
for _, c := range []*Conn{client, server} {
|
||||
c.SetReadDeadline(time.Now().Add(30 * time.Second))
|
||||
}
|
||||
return client, server
|
||||
}
|
||||
|
||||
// writeAll writes payload in pieces of random size, and closes c if end, the
|
||||
// error goes to errs
|
||||
func writeAll(c *Conn, payload []byte, end bool, errs chan<- error) {
|
||||
go func() {
|
||||
rng := rand.New(rand.NewSource(1))
|
||||
for len(payload) > 0 {
|
||||
n := min(len(payload), 1+rng.Intn(40<<10))
|
||||
if _, err := c.Write(payload[:n]); err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
payload = payload[n:]
|
||||
}
|
||||
var err error
|
||||
if end {
|
||||
err = c.Close()
|
||||
}
|
||||
errs <- err
|
||||
}()
|
||||
}
|
||||
|
||||
func readAll(t *testing.T, c *Conn, want []byte) {
|
||||
t.Helper()
|
||||
got, err := io.ReadAll(c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("got %d bytes, not the %d that were sent", len(got), len(want))
|
||||
}
|
||||
}
|
||||
|
||||
func randomPayload(n int) []byte {
|
||||
payload := make([]byte, n)
|
||||
rand.New(rand.NewSource(int64(n))).Read(payload)
|
||||
return payload
|
||||
}
|
||||
|
||||
func TestSlotFrame(t *testing.T) {
|
||||
data := []byte("hello")
|
||||
f, ok := decodeSlot(newSlotFrame(7, slotInline, data).encode())
|
||||
if !ok || f.seq != 7 || f.mode != slotInline || !bytes.Equal(f.data, data) {
|
||||
t.Fatalf("inline frame came back as %+v %v", f, ok)
|
||||
}
|
||||
|
||||
body := randomPayload(100)
|
||||
f, ok = decodeSlot(newSlotFrame(8, slotMedia, body).encode())
|
||||
if !ok || f.seq != 8 || f.mode != slotMedia || f.data != nil || !f.holds(body) || f.holds(body[1:]) {
|
||||
t.Fatalf("media frame came back as %+v %v", f, ok)
|
||||
}
|
||||
|
||||
corrupt, _ := base64.StdEncoding.DecodeString(newSlotFrame(1, slotInline, data).encode())
|
||||
corrupt[len(corrupt)-1]++
|
||||
for _, broken := range []string{
|
||||
"", "not base64", newSlotFrame(1, slotInline, data).encode()[:20], "WERSVlNMMDE=",
|
||||
base64.StdEncoding.EncodeToString(corrupt),
|
||||
} {
|
||||
if _, ok := decodeSlot(broken); ok {
|
||||
t.Errorf("%q decoded", broken)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// both sides send more segments than the ring has slots at once, small ones
|
||||
// that go in descriptions and large ones that go in bodies, then one closes
|
||||
// and the other reads EOF
|
||||
func TestSlotConnRoundTrip(t *testing.T) {
|
||||
client, server := slotPair(t, newMemSlots(), 4, 64<<10)
|
||||
up, down := randomPayload(1<<20), randomPayload(300<<10)
|
||||
errs := make(chan error, 2)
|
||||
writeAll(client, up, false, errs)
|
||||
writeAll(server, down, false, errs)
|
||||
|
||||
for _, c := range []struct {
|
||||
conn *Conn
|
||||
want []byte
|
||||
}{{server, up}, {client, down}} {
|
||||
got := make([]byte, len(c.want))
|
||||
if _, err := io.ReadFull(c.conn, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, c.want) {
|
||||
t.Fatal("what came is not what was sent")
|
||||
}
|
||||
}
|
||||
for range 2 {
|
||||
if err := <-errs; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := client.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readAll(t, server, nil)
|
||||
}
|
||||
|
||||
// a reader that does not read holds the writer back instead of losing what a
|
||||
// lap of the ring would overwrite
|
||||
func TestSlotConnSlowReader(t *testing.T) {
|
||||
client, server := slotPair(t, newMemSlots(), 2, 16<<10)
|
||||
payload := randomPayload(400 << 10)
|
||||
errs := make(chan error, 1)
|
||||
writeAll(client, payload, true, errs)
|
||||
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
readAll(t, server, payload)
|
||||
if err := <-errs; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// the next segment is asked for at once when it becomes the head, not after
|
||||
// the wait it had as one that was fetched ahead
|
||||
func TestSlotLatency(t *testing.T) {
|
||||
client, server := slotPair(t, newMemSlots(), 8, 64<<10)
|
||||
start := time.Now()
|
||||
for range 10 {
|
||||
for _, c := range [][2]*Conn{{client, server}, {server, client}} {
|
||||
c[0].Write([]byte("ping"))
|
||||
if _, err := io.ReadFull(c[1], make([]byte, 4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if took := time.Since(start); took > 2*time.Second {
|
||||
t.Fatalf("10 round trips took %v", took)
|
||||
}
|
||||
}
|
||||
|
||||
// once nothing comes for the eager window only the heads are asked for, not
|
||||
// the segments that a reader fetches ahead while things come
|
||||
func TestSlotIdle(t *testing.T) {
|
||||
store := newMemSlots()
|
||||
client, server := slotPair(t, store, 8, 64<<10)
|
||||
for _, c := range [][2]*Conn{{client, server}, {server, client}} {
|
||||
c[0].Write([]byte("ping"))
|
||||
if _, err := io.ReadFull(c[1], make([]byte, 4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
store.mu.Lock()
|
||||
before := store.reads
|
||||
store.mu.Unlock()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
store.mu.Lock()
|
||||
reads := store.reads - before
|
||||
store.mu.Unlock()
|
||||
// two heads, each asked for every 20 ms at most
|
||||
if reads > 75 {
|
||||
t.Fatalf("an idle session asked for slots %d times in 500 ms", reads)
|
||||
}
|
||||
}
|
||||
|
||||
type failingSlots struct {
|
||||
*memSlots
|
||||
}
|
||||
|
||||
// setSlot fails for segments, not for the error frame
|
||||
func (f failingSlots) setSlot(ctx context.Context, id, description string, body []byte) error {
|
||||
if frame, ok := decodeSlot(description); ok && (frame.mode == slotInline || frame.mode == slotMedia) {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
return f.memSlots.setSlot(ctx, id, description, body)
|
||||
}
|
||||
|
||||
func TestSlotWriterFailure(t *testing.T) {
|
||||
client, server := slotPair(t, failingSlots{newMemSlots()}, 2, 16<<10)
|
||||
client.Write([]byte("lost"))
|
||||
server.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err := server.Read(make([]byte, 10)); err == nil || err == io.EOF || errors.Is(err, os.ErrDeadlineExceeded) {
|
||||
t.Fatalf("the reader got %v, not the failure of the writer", err)
|
||||
}
|
||||
for start := time.Now(); time.Since(start) < 5*time.Second; time.Sleep(time.Millisecond) {
|
||||
if _, err := client.Write([]byte("more")); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("Write did not fail")
|
||||
}
|
||||
|
||||
type staleSlots struct {
|
||||
*memSlots
|
||||
mu sync.Mutex
|
||||
served map[string]bool
|
||||
}
|
||||
|
||||
// readBody gives what a slot held before once, as a body read right after its
|
||||
// description may
|
||||
func (s *staleSlots) readBody(ctx context.Context, id string) ([]byte, error) {
|
||||
s.mu.Lock()
|
||||
first := !s.served[id]
|
||||
s.served[id] = true
|
||||
s.mu.Unlock()
|
||||
if first {
|
||||
return []byte("stale"), nil
|
||||
}
|
||||
return s.memSlots.readBody(ctx, id)
|
||||
}
|
||||
|
||||
func TestSlotStaleBody(t *testing.T) {
|
||||
client, server := slotPair(t, &staleSlots{memSlots: newMemSlots(), served: make(map[string]bool)}, 2, 64<<10)
|
||||
payload := randomPayload(200 << 10)
|
||||
errs := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := client.Write(payload)
|
||||
if err == nil {
|
||||
err = client.Close()
|
||||
}
|
||||
errs <- err
|
||||
}()
|
||||
readAll(t, server, payload)
|
||||
}
|
||||
|
||||
func TestSlotBurstSplitsInline(t *testing.T) {
|
||||
store := newMemSlots()
|
||||
client, server := slotPair(t, store, 8, 512<<10)
|
||||
payload := randomPayload(90 << 10)
|
||||
errs := make(chan error, 1)
|
||||
writeAll(client, payload, true, errs)
|
||||
readAll(t, server, payload)
|
||||
store.mu.Lock()
|
||||
bodies := len(store.bodies)
|
||||
store.mu.Unlock()
|
||||
if bodies != 0 {
|
||||
t.Fatalf("a burst of 90 KiB went in %d bodies, want none", bodies)
|
||||
}
|
||||
}
|
||||
|
||||
type stuckBodySlots struct {
|
||||
*memSlots
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *stuckBodySlots) readBody(ctx context.Context, id string) ([]byte, error) {
|
||||
if s.calls.Add(1) == 1 {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return s.memSlots.readBody(ctx, id)
|
||||
}
|
||||
|
||||
func TestSlotBodyHedge(t *testing.T) {
|
||||
old := slotBodyHedge
|
||||
slotBodyHedge = 50 * time.Millisecond
|
||||
defer func() { slotBodyHedge = old }()
|
||||
|
||||
store := &stuckBodySlots{memSlots: newMemSlots()}
|
||||
client, server := slotPair(t, store, 2, 64<<10)
|
||||
payload := randomPayload(200 << 10)
|
||||
errs := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := client.Write(payload)
|
||||
if err == nil {
|
||||
err = client.Close()
|
||||
}
|
||||
errs <- err
|
||||
}()
|
||||
readAll(t, server, payload)
|
||||
if store.calls.Load() < 2 {
|
||||
t.Fatalf("the stuck body read was not hedged, %d reads", store.calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
type timedBodySlots struct {
|
||||
*memSlots
|
||||
calls atomic.Int32
|
||||
delay time.Duration
|
||||
stuck atomic.Bool
|
||||
}
|
||||
|
||||
func (s *timedBodySlots) readBody(ctx context.Context, id string) ([]byte, error) {
|
||||
n := s.calls.Add(1)
|
||||
if s.stuck.Load() && n == 1 {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(s.delay):
|
||||
}
|
||||
return make([]byte, 1000), nil
|
||||
}
|
||||
|
||||
func TestSlotBodyHedgeRate(t *testing.T) {
|
||||
old := slotBodyHedge
|
||||
slotBodyHedge = 20 * time.Millisecond
|
||||
t.Cleanup(func() { slotBodyHedge = old })
|
||||
|
||||
store := &timedBodySlots{memSlots: newMemSlots(), delay: 60 * time.Millisecond}
|
||||
r := &slotReader{store: store}
|
||||
ctx := context.Background()
|
||||
if _, err := r.readBodyHedged(ctx, "id", 1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store.calls.Store(0)
|
||||
start := time.Now()
|
||||
if _, err := r.readBodyHedged(ctx, "id", 1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < 60*time.Millisecond {
|
||||
t.Fatalf("the progressing read returned in %v, before its body was ready", elapsed)
|
||||
}
|
||||
if n := store.calls.Load(); n != 1 {
|
||||
t.Fatalf("a progressing read after a learned slow rate hedged, %d reads", n)
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
rate := r.bodyRate
|
||||
r.mu.Unlock()
|
||||
if rate <= 0 {
|
||||
t.Fatal("no body read rate was learned")
|
||||
}
|
||||
expected := max(slotBodyHedge, time.Duration(float64(2*1000)/rate*float64(time.Second)))
|
||||
store.stuck.Store(true)
|
||||
store.calls.Store(0)
|
||||
start = time.Now()
|
||||
if _, err := r.readBodyHedged(ctx, "id", 1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
if n := store.calls.Load(); n < 2 {
|
||||
t.Fatalf("a stuck read after a learned rate was not hedged, %d reads", n)
|
||||
}
|
||||
if elapsed < expected/2 {
|
||||
t.Fatalf("the stuck read hedged after %v, want about %v", elapsed, expected)
|
||||
}
|
||||
|
||||
freshStore := &timedBodySlots{memSlots: newMemSlots()}
|
||||
freshStore.stuck.Store(true)
|
||||
fresh := &slotReader{store: freshStore}
|
||||
store.calls.Store(0)
|
||||
start = time.Now()
|
||||
if _, err := fresh.readBodyHedged(ctx, "id", 1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < slotBodyHedge {
|
||||
t.Fatalf("with no learned rate the hedge came after %v, want at least %v", elapsed, slotBodyHedge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTakeSpareSkipsStale(t *testing.T) {
|
||||
cfg := &Config{}
|
||||
p := params{sessionTTL: 5 * time.Minute}
|
||||
st1, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st2, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
box := spareBoxFor(cfg)
|
||||
box.ch <- spareRing{storage: st1, session: "old", at: time.Now().Add(-time.Hour)}
|
||||
box.ch <- spareRing{storage: st2, session: "new", at: time.Now()}
|
||||
got, ok := takeSpare(cfg, p)
|
||||
if !ok || got.session != "new" {
|
||||
t.Fatalf("takeSpare gave %q, %v, want the fresh one", got.session, ok)
|
||||
}
|
||||
if _, ok := takeSpare(cfg, p); ok {
|
||||
t.Fatal("takeSpare returned a second spare")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropSpareDeletesSession(t *testing.T) {
|
||||
st, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name := sessionPrefix("gone") + "/" + uplinkDir + "/s0"
|
||||
if err := st.Put(context.Background(), name, []byte("x")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dropSpare(spareRing{storage: st, session: "gone"})
|
||||
if got, _ := st.List(context.Background(), sessionPrefix("gone")); len(got) != 0 {
|
||||
t.Fatalf("%d entries left of a dropped spare", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
type stuckHeadSlots struct {
|
||||
*memSlots
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *stuckHeadSlots) readDescription(ctx context.Context, id string) (string, error) {
|
||||
if s.calls.Add(1) == 1 {
|
||||
<-ctx.Done()
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return s.memSlots.readDescription(ctx, id)
|
||||
}
|
||||
|
||||
func TestSlotHeadReadOverlaps(t *testing.T) {
|
||||
client, server := slotPair(t, &stuckHeadSlots{memSlots: newMemSlots()}, 4, 64<<10)
|
||||
for _, c := range [][2]*Conn{{client, server}, {server, client}} {
|
||||
c[0].Write([]byte("ping"))
|
||||
if _, err := io.ReadFull(c[1], make([]byte, 4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlotBurstReadsTogether(t *testing.T) {
|
||||
client, server := slotPair(t, newMemSlots(), 16, 512<<10)
|
||||
payload := randomPayload(8 * slotInlineLimit)
|
||||
go client.Write(payload)
|
||||
start := time.Now()
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("the burst came back changed")
|
||||
}
|
||||
if took := time.Since(start); took > time.Second {
|
||||
t.Fatalf("a burst of 8 segments took %v to read", took)
|
||||
}
|
||||
}
|
||||
|
||||
type lagSlots struct{ *memSlots }
|
||||
|
||||
func (s lagSlots) readDescription(ctx context.Context, id string) (string, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
return s.memSlots.readDescription(ctx, id)
|
||||
}
|
||||
|
||||
func (s lagSlots) setSlot(ctx context.Context, id, description string, body []byte) error {
|
||||
if _, ok := decodeSlot(description); ok {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(600 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
return s.memSlots.setSlot(ctx, id, description, body)
|
||||
}
|
||||
|
||||
func TestSlotReadAheadBurst(t *testing.T) {
|
||||
oldMin, oldMax := slotTailMin, slotTailMax
|
||||
slotTailMin, slotTailMax = 150*time.Millisecond, 800*time.Millisecond
|
||||
t.Cleanup(func() { slotTailMin, slotTailMax = oldMin, oldMax })
|
||||
|
||||
client, server := slotPair(t, lagSlots{newMemSlots()}, 16, 512<<10)
|
||||
payload := randomPayload(8 * slotInlineLimit)
|
||||
go client.Write(payload)
|
||||
start := time.Now()
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("the burst came back changed")
|
||||
}
|
||||
if took := time.Since(start); took > 1700*time.Millisecond {
|
||||
t.Fatalf("a burst of 8 segments took %v to read", took)
|
||||
}
|
||||
client.Close()
|
||||
server.Close()
|
||||
}
|
||||
|
||||
func TestSlotLargeBurstInline(t *testing.T) {
|
||||
store := newMemSlots()
|
||||
client, server := slotPair(t, store, 16, 512<<10)
|
||||
payload := randomPayload(10 * slotInlineLimit)
|
||||
go client.Write(payload)
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("the burst came back changed")
|
||||
}
|
||||
store.mu.Lock()
|
||||
bodies := len(store.bodies)
|
||||
store.mu.Unlock()
|
||||
if bodies != 0 {
|
||||
t.Fatalf("a burst of 140 KiB went in %d bodies, want none", bodies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlotDepthFollowsConcurrency(t *testing.T) {
|
||||
for _, c := range []struct{ set, want int }{{100, 100}, {maxConcurrency, maxConcurrency}, {1 << 20, maxConcurrency}} {
|
||||
p := paramsFromConfig(&Config{Concurrency: uint32(c.set)})
|
||||
r, err := makeRing(context.Background(), newMemSlots(), "session", p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(r.Up.Slots) != c.want || len(r.Down.Slots) != c.want {
|
||||
t.Fatalf("concurrency %d made %d and %d slots, want %d", c.set, len(r.Up.Slots), len(r.Down.Slots), c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlotDeepRingRoundTrip(t *testing.T) {
|
||||
client, server := slotPair(t, newMemSlots(), 64, 64<<10)
|
||||
payload := randomPayload(2 << 20)
|
||||
errs := make(chan error, 1)
|
||||
writeAll(client, payload, true, errs)
|
||||
readAll(t, server, payload)
|
||||
if err := <-errs; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type pollSlots struct {
|
||||
*memSlots
|
||||
pmu sync.Mutex
|
||||
polled map[string]bool
|
||||
}
|
||||
|
||||
func (s *pollSlots) readDescription(ctx context.Context, id string) (string, error) {
|
||||
s.pmu.Lock()
|
||||
s.polled[id] = true
|
||||
s.pmu.Unlock()
|
||||
return s.memSlots.readDescription(ctx, id)
|
||||
}
|
||||
|
||||
func TestSlotReaderReachesPastWindow(t *testing.T) {
|
||||
store := &pollSlots{memSlots: newMemSlots(), polled: make(map[string]bool)}
|
||||
p := paramsFromConfig(&Config{FlushIntervalMs: 1, PollIntervalMs: 1, MaxPollIntervalMs: 20, EagerWindowMs: 50, Concurrency: 64})
|
||||
ring, err := makeRing(context.Background(), store, "session", p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
put := func(seq int64) {
|
||||
slot := ring.Down.Slots[seq%int64(len(ring.Down.Slots))]
|
||||
if err := store.setSlot(ctx, slot, newSlotFrame(seq, slotInline, []byte{byte(seq)}).encode(), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
reader := newSlotReader(ctx, store, ring.Down, p, nil)
|
||||
next := func() []byte {
|
||||
select {
|
||||
case chunk := <-reader.chunks():
|
||||
return chunk
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("no segment came")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
put(0)
|
||||
if got := next(); !bytes.Equal(got, []byte{0}) {
|
||||
t.Fatalf("segment 0 came as %v", got)
|
||||
}
|
||||
for seq := int64(2); seq <= 40; seq++ {
|
||||
put(seq)
|
||||
}
|
||||
last := ring.Down.Slots[40]
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
reader.Wake()
|
||||
store.pmu.Lock()
|
||||
polled := store.polled[last]
|
||||
store.pmu.Unlock()
|
||||
if polled {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("segment 40 was never asked for while segment 1 was missing")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
put(1)
|
||||
for seq := int64(1); seq <= 40; seq++ {
|
||||
if got := next(); !bytes.Equal(got, []byte{byte(seq)}) {
|
||||
t.Fatalf("segment %d came as %v", seq, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type countSlots struct {
|
||||
*memSlots
|
||||
cur atomic.Int32
|
||||
peak atomic.Int32
|
||||
}
|
||||
|
||||
func (s *countSlots) setSlot(ctx context.Context, id, description string, body []byte) error {
|
||||
if _, ok := decodeSlot(description); !ok {
|
||||
return s.memSlots.setSlot(ctx, id, description, body)
|
||||
}
|
||||
n := s.cur.Add(1)
|
||||
for {
|
||||
p := s.peak.Load()
|
||||
if n <= p || s.peak.CompareAndSwap(p, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
s.cur.Add(-1)
|
||||
return s.memSlots.setSlot(ctx, id, description, body)
|
||||
}
|
||||
|
||||
func TestSlotWriteInflightCap(t *testing.T) {
|
||||
store := &countSlots{memSlots: newMemSlots()}
|
||||
client, server := slotPair(t, store, 48, 512<<10)
|
||||
payload := randomPayload(60 * slotInlineLimit)
|
||||
errs := make(chan error, 1)
|
||||
go func() {
|
||||
for off := 0; off < len(payload); off += slotInlineLimit {
|
||||
if _, err := client.Write(payload[off : off+slotInlineLimit]); err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
errs <- nil
|
||||
}()
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-errs; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("the payload came back changed")
|
||||
}
|
||||
if p := int(store.peak.Load()); p > slotWriteInflight {
|
||||
t.Fatalf("%d segments were written at once, want at most %d", p, slotWriteInflight)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlotBurstInlineWaves(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
pieces int
|
||||
media bool
|
||||
}{{20, false}, {30, true}} {
|
||||
store := newMemSlots()
|
||||
client, server := slotPair(t, store, 16, 512<<10)
|
||||
payload := randomPayload(c.pieces * slotInlineLimit)
|
||||
go client.Write(payload)
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("the burst came back changed")
|
||||
}
|
||||
store.mu.Lock()
|
||||
bodies := len(store.bodies)
|
||||
store.mu.Unlock()
|
||||
if (bodies > 0) != c.media {
|
||||
t.Fatalf("a burst of %d pieces went in %d bodies, media wanted %v", c.pieces, bodies, c.media)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type holdSlots struct {
|
||||
*memSlots
|
||||
target string
|
||||
hold chan struct{}
|
||||
}
|
||||
|
||||
func (s *holdSlots) setSlot(ctx context.Context, id, description string, body []byte) error {
|
||||
if id == s.target {
|
||||
select {
|
||||
case <-s.hold:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return s.memSlots.setSlot(ctx, id, description, body)
|
||||
}
|
||||
|
||||
func TestSlotFirstAnnouncement(t *testing.T) {
|
||||
p := params{
|
||||
concurrency: 2,
|
||||
segmentBytes: 4096,
|
||||
flushInterval: time.Millisecond,
|
||||
minPollInterval: time.Millisecond,
|
||||
maxPollInterval: 5 * time.Millisecond,
|
||||
sessionTTL: time.Minute,
|
||||
}
|
||||
store := &holdSlots{memSlots: newMemSlots(), hold: make(chan struct{})}
|
||||
ctx := context.Background()
|
||||
r, err := makeRing(ctx, store, "first", p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store.target = r.Up.Slots[0]
|
||||
client := newSlotConn(ctx, store, r.Up, r.Down, p, nil, nil)
|
||||
defer client.Close()
|
||||
writer := client.writer.(*slotWriter)
|
||||
writer.first = make(chan []byte, 1)
|
||||
|
||||
payload := randomPayload(10000)
|
||||
errs := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := client.Write(payload)
|
||||
if err == nil {
|
||||
err = client.Close()
|
||||
}
|
||||
errs <- err
|
||||
}()
|
||||
var first []byte
|
||||
select {
|
||||
case first = <-writer.first:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the writer never flushed seq 0")
|
||||
}
|
||||
announced := r
|
||||
announced.First = first
|
||||
encoded, err := json.Marshal(announced)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(encoded) > driveInlineLimit {
|
||||
t.Fatalf("the test announcement is %d bytes, want the inline path", len(encoded))
|
||||
}
|
||||
decoded, ok := decodeRing(encoded)
|
||||
if !ok {
|
||||
t.Fatal("the announcement with First did not decode")
|
||||
}
|
||||
server := newSlotConn(ctx, store, decoded.Down, decoded.Up, p, decoded.First, nil)
|
||||
defer server.Close()
|
||||
if err := server.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotFirst := make([]byte, len(first))
|
||||
if _, err := io.ReadFull(server, gotFirst); err != nil {
|
||||
t.Fatalf("the first bytes did not arrive before the ring write: %v", err)
|
||||
}
|
||||
if !bytes.Equal(gotFirst, first) {
|
||||
t.Fatal("the primed first bytes changed")
|
||||
}
|
||||
close(store.hold)
|
||||
rest := make([]byte, len(payload)-len(first))
|
||||
if _, err := io.ReadFull(server, rest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(append(gotFirst, rest...), payload) {
|
||||
t.Fatal("the stream was duplicated or changed")
|
||||
}
|
||||
if err := <-errs; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlotFirstAnnouncementTooLarge(t *testing.T) {
|
||||
p := params{
|
||||
concurrency: 2,
|
||||
segmentBytes: 256 << 10,
|
||||
flushInterval: time.Millisecond,
|
||||
sessionTTL: time.Minute,
|
||||
}
|
||||
store := newMemSlots()
|
||||
ctx := context.Background()
|
||||
r, err := makeRing(ctx, store, "large-first", p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := newSlotConn(ctx, store, r.Up, r.Down, p, nil, nil)
|
||||
defer client.Close()
|
||||
writer := client.writer.(*slotWriter)
|
||||
writer.first = make(chan []byte, 1)
|
||||
go client.Write(randomPayload(300 << 10))
|
||||
var first []byte
|
||||
select {
|
||||
case first = <-writer.first:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the writer never flushed seq 0")
|
||||
}
|
||||
if len(first) <= slotInlineLimit {
|
||||
t.Fatalf("the first segment is %d bytes, want a media segment", len(first))
|
||||
}
|
||||
withFirst := r
|
||||
withFirst.First = first
|
||||
encoded, err := json.Marshal(withFirst)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(encoded) <= driveInlineLimit {
|
||||
t.Fatalf("a %d byte first segment fit the inline announcement", len(first))
|
||||
}
|
||||
plain, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, ok := decodeRing(plain)
|
||||
if !ok || decoded.First != nil {
|
||||
t.Fatal("the announcement without First did not decode cleanly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlotRingFirstCompatibility(t *testing.T) {
|
||||
p := params{concurrency: 2, sessionTTL: time.Minute}
|
||||
store := newMemSlots()
|
||||
r, err := makeRing(context.Background(), store, "compat", p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.First = []byte("hello")
|
||||
encoded, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var oldServer struct {
|
||||
Up slotTable `json:"u"`
|
||||
Down slotTable `json:"d"`
|
||||
}
|
||||
if err := json.Unmarshal(encoded, &oldServer); err != nil {
|
||||
t.Fatalf("an old server could not ignore First: %v", err)
|
||||
}
|
||||
if len(oldServer.Up.Slots) != len(r.Up.Slots) || len(oldServer.Down.Slots) != len(r.Down.Slots) {
|
||||
t.Fatal("an old server lost the ring tables")
|
||||
}
|
||||
r.First = nil
|
||||
plain, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, ok := decodeRing(plain)
|
||||
if !ok || decoded.First != nil {
|
||||
t.Fatal("an old client announcement did not decode")
|
||||
}
|
||||
}
|
||||
@@ -4,21 +4,27 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/splithttp"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
)
|
||||
|
||||
var errNotFound = errors.New("object not found")
|
||||
|
||||
type Entry struct {
|
||||
Name string
|
||||
Inline []byte
|
||||
Name string
|
||||
Inline []byte
|
||||
created time.Time // optional backend-supplied creation time on the local clock
|
||||
}
|
||||
|
||||
// Config.Secrets for clients need only create/update/read/list permissions;
|
||||
// only server credentials need delete permission.
|
||||
type Storage interface {
|
||||
Put(ctx context.Context, name string, data []byte) error
|
||||
Get(ctx context.Context, name string) ([]byte, error)
|
||||
@@ -27,22 +33,18 @@ type Storage interface {
|
||||
Close() error
|
||||
}
|
||||
|
||||
// testStorageFactory lets tests substitute a backend for newStorage; nil in
|
||||
// production so behaviour is unchanged.
|
||||
var testStorageFactory atomic.Pointer[func(config *Config) (Storage, error)]
|
||||
|
||||
func newStorage(streamSettings *internet.MemoryStreamConfig) (Storage, error) {
|
||||
config, err := streamConfig(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f := testStorageFactory.Load(); f != nil {
|
||||
return (*f)(config)
|
||||
}
|
||||
|
||||
switch config.Service {
|
||||
case "local":
|
||||
return newLocalStorage(config.RemoteFolder)
|
||||
storage, err := newLocalStorage(config.RemoteFolder)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ownedStorage(storage), nil
|
||||
case "google-drive", "Google Drive":
|
||||
return sharedStorage(streamSettings, config, func() (Storage, error) {
|
||||
return newDriveStorage(streamSettings, config)
|
||||
@@ -60,10 +62,7 @@ func newStorage(streamSettings *internet.MemoryStreamConfig) (Storage, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// sessionStorage returns the storage of one session, which takes connections
|
||||
// of XMUX until Close, with the token and cache of storage. Local storage has
|
||||
// no connections
|
||||
func sessionStorage(storage Storage) Storage {
|
||||
func rawSessionStorage(storage Storage) Storage {
|
||||
switch s := storage.(type) {
|
||||
case *driveStorage:
|
||||
return s.session()
|
||||
@@ -77,49 +76,68 @@ func sessionStorage(storage Storage) Storage {
|
||||
|
||||
var (
|
||||
sharedMu sync.Mutex
|
||||
shared = make(map[string]Storage)
|
||||
shared = make(map[string]*storageOwner)
|
||||
)
|
||||
|
||||
func shareKey(streamSettings *internet.MemoryStreamConfig, config *Config) string {
|
||||
parts := []string{config.Service, config.RemoteFolder}
|
||||
// Encode only configuration, not protobuf runtime state or transport caches.
|
||||
// JSON provides field/element boundaries (unlike NUL-joined strings), with
|
||||
// deterministic map ordering. These concrete config types contain no funcs.
|
||||
profile := struct {
|
||||
Service, Folder, Template, SecurityType, Destination string
|
||||
Secrets []string
|
||||
S3 *S3Config
|
||||
TLS *tls.Config
|
||||
Socket *internet.SocketConfig
|
||||
QUIC *internet.QuicParams
|
||||
XMUX *splithttp.XmuxConfig
|
||||
}{
|
||||
Service: config.Service, Folder: config.RemoteFolder, Secrets: config.Secrets,
|
||||
Template: config.Template, XMUX: config.Xmux,
|
||||
}
|
||||
if config.S3 != nil {
|
||||
parts = append(parts, config.S3.Endpoint, s3Region(config.S3.Region), config.S3.Bucket)
|
||||
if config.S3.PathStyle {
|
||||
parts = append(parts, "path-style")
|
||||
} else {
|
||||
parts = append(parts, "virtual-hosted-style")
|
||||
profile.S3 = &S3Config{
|
||||
Endpoint: config.S3.Endpoint, Region: s3Region(config.S3.Region),
|
||||
Bucket: config.S3.Bucket, PathStyle: config.S3.PathStyle,
|
||||
}
|
||||
}
|
||||
parts = append(parts, config.Secrets...)
|
||||
if streamSettings != nil {
|
||||
parts = append(parts, streamSettings.SecurityType)
|
||||
profile.SecurityType = streamSettings.SecurityType
|
||||
profile.TLS = tls.ConfigFromStreamSettings(streamSettings)
|
||||
profile.Socket, profile.QUIC = streamSettings.SocketSettings, streamSettings.QuicParams
|
||||
if streamSettings.Destination != nil {
|
||||
parts = append(parts, streamSettings.Destination.NetAddr())
|
||||
profile.Destination = streamSettings.Destination.String()
|
||||
}
|
||||
}
|
||||
sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func resetSharedStorage() {
|
||||
sharedMu.Lock()
|
||||
shared = make(map[string]Storage)
|
||||
sharedMu.Unlock()
|
||||
h := sha256.New()
|
||||
common.Must(json.NewEncoder(h).Encode(profile))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func sharedStorage(streamSettings *internet.MemoryStreamConfig, config *Config, build func() (Storage, error)) (Storage, error) {
|
||||
// Opaque masks have no immutable configuration identity. Isolate their
|
||||
// owners rather than accidentally routing one profile through another.
|
||||
if streamSettings != nil && streamSettings.FinalMask != nil {
|
||||
storage, err := build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ownedStorage(storage), nil
|
||||
}
|
||||
key := shareKey(streamSettings, config)
|
||||
|
||||
sharedMu.Lock()
|
||||
defer sharedMu.Unlock()
|
||||
|
||||
if storage, ok := shared[key]; ok {
|
||||
return storage, nil
|
||||
if owner, ok := shared[key]; ok && !owner.closed {
|
||||
owner.refs++
|
||||
return wrapStorageLease(owner, owner.root, false), nil
|
||||
}
|
||||
storage, err := build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shared[key] = storage
|
||||
return storage, nil
|
||||
owner := &storageOwner{root: storage, key: key, refs: 1}
|
||||
shared[key] = owner
|
||||
return wrapStorageLease(owner, storage, false), nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type storageOwner struct {
|
||||
root Storage
|
||||
key string
|
||||
refs int
|
||||
closed bool
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
type storageLease struct {
|
||||
owner *storageOwner
|
||||
backend Storage
|
||||
session bool
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
closeErr error
|
||||
}
|
||||
|
||||
type (
|
||||
leasedStorage struct{ *storageLease }
|
||||
leasedDriveStorage struct {
|
||||
*driveStorage
|
||||
lease *storageLease
|
||||
}
|
||||
)
|
||||
|
||||
type leasedTemplateStorage struct {
|
||||
*templateStorage
|
||||
lease *storageLease
|
||||
}
|
||||
type leasedS3Storage struct {
|
||||
*s3Storage
|
||||
lease *storageLease
|
||||
}
|
||||
type leasedSlotStorage struct {
|
||||
*leasedStorage
|
||||
slotStore
|
||||
}
|
||||
|
||||
func wrapStorageLease(owner *storageOwner, backend Storage, session bool) Storage {
|
||||
lease := &storageLease{owner: owner, backend: backend, session: session}
|
||||
switch s := backend.(type) {
|
||||
case *driveStorage:
|
||||
return &leasedDriveStorage{driveStorage: s, lease: lease}
|
||||
case *templateStorage:
|
||||
return &leasedTemplateStorage{templateStorage: s, lease: lease}
|
||||
case *s3Storage:
|
||||
return &leasedS3Storage{s3Storage: s, lease: lease}
|
||||
default:
|
||||
storage := &leasedStorage{storageLease: lease}
|
||||
if slots, ok := backend.(slotStore); ok {
|
||||
return &leasedSlotStorage{leasedStorage: storage, slotStore: slots}
|
||||
}
|
||||
return storage
|
||||
}
|
||||
}
|
||||
|
||||
func ownedStorage(storage Storage) Storage {
|
||||
return wrapStorageLease(&storageOwner{root: storage, refs: 1}, storage, false)
|
||||
}
|
||||
|
||||
func (s *storageLease) storageLeaseState() *storageLease { return s }
|
||||
func (s *leasedDriveStorage) storageLeaseState() *storageLease { return s.lease }
|
||||
func (s *leasedTemplateStorage) storageLeaseState() *storageLease { return s.lease }
|
||||
func (s *leasedS3Storage) storageLeaseState() *storageLease { return s.lease }
|
||||
|
||||
func (s *leasedStorage) Put(ctx context.Context, name string, data []byte) error {
|
||||
return s.backend.Put(ctx, name, data)
|
||||
}
|
||||
|
||||
func (s *leasedStorage) Get(ctx context.Context, name string) ([]byte, error) {
|
||||
return s.backend.Get(ctx, name)
|
||||
}
|
||||
|
||||
func (s *leasedStorage) Delete(ctx context.Context, name string) error {
|
||||
return s.backend.Delete(ctx, name)
|
||||
}
|
||||
|
||||
func (s *leasedStorage) List(ctx context.Context, prefix string) ([]Entry, error) {
|
||||
return s.backend.List(ctx, prefix)
|
||||
}
|
||||
func (s *leasedDriveStorage) Close() error { return s.lease.Close() }
|
||||
func (s *leasedTemplateStorage) Close() error { return s.lease.Close() }
|
||||
func (s *leasedS3Storage) Close() error { return s.lease.Close() }
|
||||
|
||||
func (s *storageLease) Close() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return s.closeErr
|
||||
}
|
||||
s.closed = true
|
||||
if s.session && s.backend != s.owner.root {
|
||||
s.closeErr = s.backend.Close()
|
||||
}
|
||||
sharedMu.Lock()
|
||||
s.owner.refs--
|
||||
final := s.owner.refs == 0 && !s.owner.closed
|
||||
if final {
|
||||
s.owner.closed = true
|
||||
if s.owner.key != "" && shared[s.owner.key] == s.owner {
|
||||
delete(shared, s.owner.key)
|
||||
}
|
||||
}
|
||||
sharedMu.Unlock()
|
||||
if final {
|
||||
if err := s.owner.close(); s.closeErr == nil {
|
||||
s.closeErr = err
|
||||
}
|
||||
}
|
||||
return s.closeErr
|
||||
}
|
||||
|
||||
func (o *storageOwner) close() error {
|
||||
o.closeOnce.Do(func() { o.closeErr = closeStorageRoot(o.root) })
|
||||
return o.closeErr
|
||||
}
|
||||
|
||||
func acquireSessionStorage(storage Storage) (Storage, error) {
|
||||
if s, ok := storage.(interface{ storageLeaseState() *storageLease }); ok {
|
||||
lease := s.storageLeaseState()
|
||||
lease.mu.Lock()
|
||||
defer lease.mu.Unlock()
|
||||
sharedMu.Lock()
|
||||
if lease.closed || lease.owner.closed {
|
||||
sharedMu.Unlock()
|
||||
return nil, errSessionClosed
|
||||
}
|
||||
lease.owner.refs++
|
||||
sharedMu.Unlock()
|
||||
return wrapStorageLease(lease.owner, rawSessionStorage(lease.owner.root), true), nil
|
||||
}
|
||||
return rawSessionStorage(storage), nil
|
||||
}
|
||||
|
||||
// Dial and spare construction transfer their acquisition to a session. A
|
||||
// listener instead keeps its acquisition and clones one lease per child.
|
||||
func transferSessionStorage(storage Storage) (Storage, error) {
|
||||
session, err := acquireSessionStorage(storage)
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := storage.(interface{ storageLeaseState() *storageLease }); ok {
|
||||
storage.Close()
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func holdStorageSession(storage Storage, session string) (func(), error) {
|
||||
if s, ok := storage.(interface{ holdSession(string) (func(), error) }); ok {
|
||||
return s.holdSession(session)
|
||||
}
|
||||
return func() {}, nil
|
||||
}
|
||||
|
||||
func closeStorageRoot(storage Storage) error {
|
||||
switch s := storage.(type) {
|
||||
case *templateStorage:
|
||||
s.closeTokenWorkers()
|
||||
closeStoragePool(s.conns)
|
||||
if s.client != nil {
|
||||
s.client.CloseIdleConnections()
|
||||
}
|
||||
if s.tokenClient != nil {
|
||||
s.tokenClient.CloseIdleConnections()
|
||||
}
|
||||
case *s3Storage:
|
||||
closeStoragePool(s.conns)
|
||||
if s.client != nil {
|
||||
s.client.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
return storage.Close()
|
||||
}
|
||||
|
||||
func closeStoragePool(pool *connPool) {
|
||||
if pool != nil {
|
||||
pool.Close()
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,10 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -34,13 +36,17 @@ type opTemplate struct {
|
||||
Body string `json:"body"`
|
||||
NamesRegex string `json:"namesRegex"`
|
||||
|
||||
// NextPagePath extracts a JSON token for the next list URL's query-escaped {pageToken}.
|
||||
NextPagePath string `json:"nextPagePath"`
|
||||
|
||||
// HrefPath makes the operation two-step, as in the Yandex Disk REST API: the first request
|
||||
// answers with a JSON body, the URL found at HrefPath is then called with HrefMethod (GET by
|
||||
// default), carrying the payload. The URL is used as given, with neither auth nor headers.
|
||||
HrefPath string `json:"hrefPath"`
|
||||
HrefMethod string `json:"hrefMethod"`
|
||||
|
||||
presigned bool
|
||||
presigned bool
|
||||
responseLimit int64
|
||||
}
|
||||
|
||||
type retryTemplate struct {
|
||||
@@ -78,8 +84,30 @@ type templateShared struct {
|
||||
secrets []string
|
||||
|
||||
tokenMu sync.Mutex
|
||||
tokenWG sync.WaitGroup
|
||||
tokenClosed bool
|
||||
token string
|
||||
tokenExpiry time.Time
|
||||
tokenFlight *templateTokenFlight
|
||||
}
|
||||
|
||||
type templateTokenFlight struct {
|
||||
done chan struct{}
|
||||
cancel context.CancelFunc
|
||||
waiters int
|
||||
token string
|
||||
err error
|
||||
}
|
||||
|
||||
type adapterPermanentError struct{ error }
|
||||
|
||||
func (e *adapterPermanentError) Unwrap() error { return e.error }
|
||||
|
||||
func permanentAdapterError(err error) error { return &adapterPermanentError{err} }
|
||||
|
||||
func isPermanentAdapterError(err error) bool {
|
||||
var permanent *adapterPermanentError
|
||||
return stderrors.As(err, &permanent)
|
||||
}
|
||||
|
||||
func newTemplateStorage(streamSettings *internet.MemoryStreamConfig, config *Config) (*templateStorage, error) {
|
||||
@@ -93,6 +121,9 @@ func newTemplateStorage(streamSettings *internet.MemoryStreamConfig, config *Con
|
||||
if tmpl.List.NamesRegex == "" {
|
||||
return nil, errors.New("template list needs a namesRegex")
|
||||
}
|
||||
if tmpl.List.NextPagePath != "" && !strings.Contains(tmpl.List.URL, "{pageToken}") {
|
||||
return nil, errors.New("paginated template list URL needs {pageToken}")
|
||||
}
|
||||
re, err := regexp.Compile(tmpl.List.NamesRegex)
|
||||
if err != nil {
|
||||
return nil, errors.New("bad namesRegex").Base(err)
|
||||
@@ -114,7 +145,7 @@ func newTemplateStorage(streamSettings *internet.MemoryStreamConfig, config *Con
|
||||
client := newServiceClient(context.Background(), h1Hosts, streamSettings, driveTimeout, conc)
|
||||
return &templateStorage{
|
||||
templateShared: &templateShared{
|
||||
conns: newConnPool(config.Xmux, func(connCtx context.Context) *http.Client {
|
||||
conns: newConnPool(config.Xmux, 0, func(connCtx context.Context) *http.Client {
|
||||
return newServiceClient(connCtx, h1Hosts, streamSettings, driveTimeout, conc)
|
||||
}),
|
||||
tmpl: tmpl,
|
||||
@@ -139,7 +170,28 @@ func (s *templateStorage) session() Storage {
|
||||
}
|
||||
}
|
||||
|
||||
const maxTemplateConcurrency = 256
|
||||
const (
|
||||
maxTemplateConcurrency = 256
|
||||
adapterMaxListResponse = 32 << 20
|
||||
adapterMaxMetadataBody = 1 << 20
|
||||
adapterMaxErrorBody = 64 << 10
|
||||
)
|
||||
|
||||
func adapterObjectLimit(ctx context.Context) int64 {
|
||||
limit := int64(maxSegmentBytes)
|
||||
if v, ok := ctx.Value(maxBodyKey{}).(int64); ok && v > 0 {
|
||||
limit = min(limit, v)
|
||||
}
|
||||
return limit
|
||||
}
|
||||
|
||||
func readAdapterBody(body io.Reader, limit int64) ([]byte, error) {
|
||||
payload, err := io.ReadAll(io.LimitReader(body, limit+1))
|
||||
if int64(len(payload)) > limit {
|
||||
return nil, permanentAdapterError(errors.New("adapter response exceeds the ", limit, " byte cap"))
|
||||
}
|
||||
return payload, err
|
||||
}
|
||||
|
||||
func (s *templateStorage) baseVars() map[string]string {
|
||||
vars := map[string]string{"folder": s.folder}
|
||||
@@ -218,51 +270,123 @@ func (s *templateStorage) authHeaders(ctx context.Context, vars map[string]strin
|
||||
enc := base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
|
||||
return map[string]string{"Authorization": "Basic " + enc}, nil
|
||||
default:
|
||||
return nil, errors.New("unsupported auth type: ", s.tmpl.Auth.Type)
|
||||
return nil, permanentAdapterError(errors.New("unsupported auth type: ", s.tmpl.Auth.Type))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) accessToken(ctx context.Context) (string, error) {
|
||||
s.tokenMu.Lock()
|
||||
defer s.tokenMu.Unlock()
|
||||
|
||||
if s.token != "" && time.Now().Before(s.tokenExpiry) {
|
||||
return s.token, nil
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
form := make(map[string]string, len(s.tmpl.Auth.Form))
|
||||
vars := s.baseVars()
|
||||
values := strings.Builder{}
|
||||
first := true
|
||||
for k, v := range s.tmpl.Auth.Form {
|
||||
form[k] = subst(v, vars)
|
||||
if !first {
|
||||
values.WriteByte('&')
|
||||
s.tokenMu.Lock()
|
||||
if s.tokenClosed {
|
||||
s.tokenMu.Unlock()
|
||||
return "", context.Canceled
|
||||
}
|
||||
if s.token != "" && time.Now().Before(s.tokenExpiry) {
|
||||
token := s.token
|
||||
s.tokenMu.Unlock()
|
||||
return token, nil
|
||||
}
|
||||
f := s.tokenFlight
|
||||
if f == nil {
|
||||
fetchCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), driveTimeout)
|
||||
f = &templateTokenFlight{done: make(chan struct{}), cancel: cancel}
|
||||
s.tokenFlight = f
|
||||
s.tokenWG.Add(1)
|
||||
go func() {
|
||||
defer s.tokenWG.Done()
|
||||
token, lifetime, err := s.fetchTemplateToken(fetchCtx)
|
||||
cancel()
|
||||
s.tokenMu.Lock()
|
||||
f.token, f.err = token, err
|
||||
if s.tokenFlight == f {
|
||||
s.tokenFlight = nil
|
||||
if err == nil {
|
||||
s.token = token
|
||||
s.tokenExpiry = time.Now().Add(lifetime)
|
||||
}
|
||||
}
|
||||
close(f.done)
|
||||
s.tokenMu.Unlock()
|
||||
}()
|
||||
}
|
||||
f.waiters++
|
||||
s.tokenMu.Unlock()
|
||||
defer func() {
|
||||
s.tokenMu.Lock()
|
||||
f.waiters--
|
||||
if f.waiters == 0 && s.tokenFlight == f {
|
||||
s.tokenFlight = nil
|
||||
f.cancel()
|
||||
}
|
||||
first = false
|
||||
values.WriteString(k)
|
||||
values.WriteByte('=')
|
||||
values.WriteString(form[k])
|
||||
s.tokenMu.Unlock()
|
||||
}()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
case <-f.done:
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return f.token, f.err
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) closeTokenWorkers() {
|
||||
s.tokenMu.Lock()
|
||||
s.tokenClosed = true
|
||||
if f := s.tokenFlight; f != nil {
|
||||
s.tokenFlight = nil
|
||||
f.cancel()
|
||||
}
|
||||
s.tokenMu.Unlock()
|
||||
s.tokenWG.Wait()
|
||||
}
|
||||
|
||||
func (s *templateStorage) fetchTemplateToken(ctx context.Context) (string, time.Duration, error) {
|
||||
form := make(url.Values, len(s.tmpl.Auth.Form))
|
||||
vars := s.baseVars()
|
||||
for k, v := range s.tmpl.Auth.Form {
|
||||
form.Add(k, subst(v, vars))
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.tmpl.Auth.TokenURL,
|
||||
strings.NewReader(values.String()))
|
||||
strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return "", errors.New("failed to build the token request").Base(err)
|
||||
return "", 0, permanentAdapterError(errors.New("failed to build the token request").Base(err))
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" || req.URL.Host == "" {
|
||||
return "", 0, permanentAdapterError(errors.New("token URL must be an http(s) URL with an authority"))
|
||||
}
|
||||
resp, err := s.tokenClient.Do(req)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to fetch the token").Base(err)
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
return "", 0, errors.New("failed to fetch the token").Base(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
limit := int64(adapterMaxMetadataBody)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
limit = adapterMaxErrorBody
|
||||
}
|
||||
payload, err := readAdapterBody(resp.Body, limit)
|
||||
if err != nil {
|
||||
return "", errors.New("failed to read the token response").Base(err)
|
||||
readErr := errors.New("failed to read the token response").Base(err)
|
||||
if resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusRequestTimeout && resp.StatusCode != http.StatusTooManyRequests {
|
||||
return "", 0, permanentAdapterError(readErr)
|
||||
}
|
||||
return "", 0, readErr
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", errors.New("the token endpoint answered ", resp.StatusCode, ": ", string(payload))
|
||||
err := errors.New("the token endpoint answered ", resp.StatusCode)
|
||||
if resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusRequestTimeout && resp.StatusCode != http.StatusTooManyRequests {
|
||||
return "", 0, permanentAdapterError(err)
|
||||
}
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
path := s.tmpl.Auth.TokenPath
|
||||
@@ -271,7 +395,7 @@ func (s *templateStorage) accessToken(ctx context.Context) (string, error) {
|
||||
}
|
||||
token := jsonString(payload, path)
|
||||
if token == "" {
|
||||
return "", errors.New("the token response has no token at ", path)
|
||||
return "", 0, permanentAdapterError(errors.New("the token response has no token at ", path))
|
||||
}
|
||||
|
||||
lifetime := int64(3600)
|
||||
@@ -280,12 +404,11 @@ func (s *templateStorage) accessToken(ctx context.Context) (string, error) {
|
||||
lifetime = n
|
||||
}
|
||||
}
|
||||
lifetime = min(lifetime, int64(365*24*60*60))
|
||||
if lifetime > 60 {
|
||||
lifetime -= 60
|
||||
}
|
||||
s.token = token
|
||||
s.tokenExpiry = time.Now().Add(time.Duration(lifetime) * time.Second)
|
||||
return s.token, nil
|
||||
return token, time.Duration(lifetime) * time.Second, nil
|
||||
}
|
||||
|
||||
func (s *templateStorage) invalidateToken() {
|
||||
@@ -304,6 +427,9 @@ func (s *templateStorage) do(ctx context.Context, op *opTemplate, vars map[strin
|
||||
}
|
||||
|
||||
for attempt := 0; attempt < driveMaxAttempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
if attempt > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -320,6 +446,12 @@ func (s *templateStorage) do(ctx context.Context, op *opTemplate, vars map[strin
|
||||
if !op.presigned {
|
||||
headers, err := s.authHeaders(ctx, vars)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if isPermanentAdapterError(err) {
|
||||
return 0, nil, err
|
||||
}
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
@@ -351,20 +483,50 @@ func (s *templateStorage) do(ctx context.Context, op *opTemplate, vars map[strin
|
||||
case <-ctx.Done():
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-s.inflight
|
||||
return 0, nil, err
|
||||
}
|
||||
resp, err := s.client.Do(req)
|
||||
<-s.inflight
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
<-s.inflight
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
lastErr = errors.New("request failed").Base(err)
|
||||
if errors.Cause(err) == errSessionClosed {
|
||||
return 0, nil, lastErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
payload, err := io.ReadAll(resp.Body)
|
||||
limit := op.responseLimit
|
||||
if limit <= 0 {
|
||||
switch op {
|
||||
case &s.tmpl.Get:
|
||||
limit = adapterObjectLimit(ctx)
|
||||
case &s.tmpl.List:
|
||||
limit = adapterMaxListResponse
|
||||
default:
|
||||
limit = adapterMaxMetadataBody
|
||||
}
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
limit = adapterMaxErrorBody
|
||||
} else if op.HrefPath != "" {
|
||||
limit = adapterMaxMetadataBody
|
||||
}
|
||||
payload, err := readAdapterBody(resp.Body, limit)
|
||||
resp.Body.Close()
|
||||
<-s.inflight
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
if isPermanentAdapterError(err) {
|
||||
return 0, nil, err
|
||||
}
|
||||
lastErr = errors.New("failed to read response").Base(err)
|
||||
continue
|
||||
@@ -397,7 +559,14 @@ func (s *templateStorage) run(ctx context.Context, op *opTemplate, vars map[stri
|
||||
if href == "" {
|
||||
return 0, nil, errors.New("the response has no href at ", op.HrefPath)
|
||||
}
|
||||
return s.do(ctx, &opTemplate{Method: op.HrefMethod, URL: href, presigned: true}, vars, body)
|
||||
limit := int64(adapterMaxMetadataBody)
|
||||
switch op {
|
||||
case &s.tmpl.Get:
|
||||
limit = adapterObjectLimit(ctx)
|
||||
case &s.tmpl.List:
|
||||
limit = adapterMaxListResponse
|
||||
}
|
||||
return s.do(ctx, &opTemplate{Method: op.HrefMethod, URL: href, presigned: true, responseLimit: limit}, vars, body)
|
||||
}
|
||||
|
||||
func (s *templateStorage) Put(ctx context.Context, name string, data []byte) error {
|
||||
@@ -438,10 +607,9 @@ func (s *templateStorage) Get(ctx context.Context, name string) ([]byte, error)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) Delete(ctx context.Context, name string) error {
|
||||
func (s *templateStorage) deleteStoredObject(ctx context.Context, name string) error {
|
||||
vars := s.baseVars()
|
||||
vars["name"] = s.storedName(name)
|
||||
|
||||
vars["name"] = name
|
||||
status, payload, err := s.run(ctx, &s.tmpl.Delete, vars, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -452,53 +620,100 @@ func (s *templateStorage) Delete(ctx context.Context, name string) error {
|
||||
return errors.New("delete of ", name, " answered ", status, ": ", string(payload))
|
||||
}
|
||||
|
||||
func (s *templateStorage) List(ctx context.Context, prefix string) ([]Entry, error) {
|
||||
vars := s.baseVars()
|
||||
flat := s.storedName(prefix)
|
||||
vars["prefix"] = flat
|
||||
|
||||
status, payload, err := s.run(ctx, &s.tmpl.List, vars, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if status == http.StatusNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
if status < 200 || status >= 300 {
|
||||
return nil, errors.New("list of ", prefix, " answered ", status, ": ", string(payload))
|
||||
}
|
||||
|
||||
matches := s.tmpl.names.FindAllStringSubmatch(string(payload), -1)
|
||||
func (s *templateStorage) Delete(ctx context.Context, name string) error {
|
||||
flat := s.storedName(name)
|
||||
if !s.tmpl.Flatten {
|
||||
entries := make([]Entry, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
entries = append(entries, Entry{Name: m[1]})
|
||||
}
|
||||
return entries, nil
|
||||
return s.deleteStoredObject(ctx, flat)
|
||||
}
|
||||
|
||||
want := flat + flatSeparator
|
||||
seen := make(map[string]bool, len(matches))
|
||||
entries := make([]Entry, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
name := m[1]
|
||||
if !strings.HasPrefix(name, want) {
|
||||
continue
|
||||
seen := make(map[string]bool)
|
||||
var descendants []string
|
||||
// Finish pagination before deleting so offset-based listings cannot skip shifted entries.
|
||||
if err := s.listStoredNames(ctx, want, func(name string) {
|
||||
if strings.HasPrefix(name, want) && len(name) > len(want) && !seen[name] {
|
||||
seen[name] = true
|
||||
descendants = append(descendants, name)
|
||||
}
|
||||
rest := strings.TrimPrefix(name, want)
|
||||
if rest == "" {
|
||||
continue
|
||||
}
|
||||
if cut := strings.Index(rest, flatSeparator); cut >= 0 {
|
||||
rest = rest[:cut]
|
||||
}
|
||||
if seen[rest] {
|
||||
continue
|
||||
}
|
||||
seen[rest] = true
|
||||
entries = append(entries, Entry{Name: rest})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return entries, nil
|
||||
for _, name := range descendants {
|
||||
if err := s.deleteStoredObject(ctx, name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.deleteStoredObject(ctx, flat)
|
||||
}
|
||||
|
||||
func (s *templateStorage) listStoredNames(ctx context.Context, prefix string, visit func(string)) error {
|
||||
vars := s.baseVars()
|
||||
vars["prefix"] = prefix
|
||||
vars["pageToken"] = ""
|
||||
seen := make(map[string]bool)
|
||||
for {
|
||||
status, payload, err := s.run(ctx, &s.tmpl.List, vars, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status == http.StatusNotFound && vars["pageToken"] == "" {
|
||||
return nil
|
||||
}
|
||||
if status < 200 || status >= 300 {
|
||||
return errors.New("list of ", prefix, " answered ", status, ": ", string(payload))
|
||||
}
|
||||
var token string
|
||||
if s.tmpl.List.NextPagePath != "" {
|
||||
if !json.Valid(payload) {
|
||||
return permanentAdapterError(errors.New("invalid JSON in paginated template list response"))
|
||||
}
|
||||
if node := jsonWalk(payload, s.tmpl.List.NextPagePath); node != nil {
|
||||
var ok bool
|
||||
token, ok = node.(string)
|
||||
if !ok {
|
||||
return permanentAdapterError(errors.New("template list continuation token must be a string"))
|
||||
}
|
||||
}
|
||||
if token != "" && seen[token] {
|
||||
return permanentAdapterError(errors.New("template list pagination did not advance"))
|
||||
}
|
||||
}
|
||||
for _, match := range s.tmpl.names.FindAllStringSubmatch(string(payload), -1) {
|
||||
visit(match[1])
|
||||
}
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
seen[token] = true
|
||||
vars["pageToken"] = url.QueryEscape(token)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) List(ctx context.Context, prefix string) ([]Entry, error) {
|
||||
flat := s.storedName(prefix)
|
||||
want := flat + flatSeparator
|
||||
seen := make(map[string]bool)
|
||||
var entries []Entry
|
||||
err := s.listStoredNames(ctx, flat, func(name string) {
|
||||
if !s.tmpl.Flatten {
|
||||
entries = append(entries, Entry{Name: name})
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(name, want) {
|
||||
return
|
||||
}
|
||||
name = strings.TrimPrefix(name, want)
|
||||
if name == "" {
|
||||
return
|
||||
}
|
||||
if cut := strings.Index(name, flatSeparator); cut >= 0 {
|
||||
name = name[:cut]
|
||||
}
|
||||
if !seen[name] {
|
||||
seen[name] = true
|
||||
entries = append(entries, Entry{Name: name})
|
||||
}
|
||||
})
|
||||
return entries, err
|
||||
}
|
||||
|
||||
func (s *templateStorage) Close() error {
|
||||
|
||||
@@ -1,424 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
type fakeStore struct {
|
||||
server *httptest.Server
|
||||
|
||||
mu sync.Mutex
|
||||
objects map[string][]byte
|
||||
needAuth string
|
||||
sawAuth string
|
||||
tokens int
|
||||
}
|
||||
|
||||
func newFakeStore(t *testing.T) *fakeStore {
|
||||
t.Helper()
|
||||
|
||||
store := &fakeStore{objects: make(map[string][]byte)}
|
||||
store.server = httptest.NewServer(http.HandlerFunc(store.handle))
|
||||
t.Cleanup(store.server.Close)
|
||||
return store
|
||||
}
|
||||
|
||||
func (s *fakeStore) handle(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/token" {
|
||||
s.mu.Lock()
|
||||
s.tokens++
|
||||
s.mu.Unlock()
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"access_token": "tok-fake", "expires_in": 3600,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if auth := r.Header.Get("Authorization"); auth != "" {
|
||||
s.mu.Lock()
|
||||
s.sawAuth = auth
|
||||
s.mu.Unlock()
|
||||
}
|
||||
if s.needAuth != "" && r.Header.Get("Authorization") != s.needAuth {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
key := strings.TrimPrefix(r.URL.Path, "/folder/")
|
||||
|
||||
switch r.Method {
|
||||
case "PROPFIND":
|
||||
s.mu.Lock()
|
||||
var b strings.Builder
|
||||
for name := range s.objects {
|
||||
fmt.Fprintf(&b, "<d:href>/folder/%s</d:href>\n", name)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
w.Write([]byte(b.String()))
|
||||
case http.MethodPut:
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
s.mu.Lock()
|
||||
s.objects[key] = body
|
||||
s.mu.Unlock()
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
case http.MethodGet:
|
||||
s.mu.Lock()
|
||||
data, ok := s.objects[key]
|
||||
s.mu.Unlock()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
case http.MethodDelete:
|
||||
s.mu.Lock()
|
||||
delete(s.objects, key)
|
||||
s.mu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *fakeStore) count() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return len(s.objects)
|
||||
}
|
||||
|
||||
func (s *fakeStore) seenAuth() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.sawAuth
|
||||
}
|
||||
|
||||
func templateSettings(store *fakeStore, auth map[string]interface{}, secrets []string) *internet.MemoryStreamConfig {
|
||||
base := store.server.URL
|
||||
tmpl := map[string]interface{}{
|
||||
"flatten": true,
|
||||
"auth": auth,
|
||||
"put": map[string]interface{}{"method": "PUT", "url": base + "/folder/{name}"},
|
||||
"get": map[string]interface{}{"method": "GET", "url": base + "/folder/{name}"},
|
||||
"delete": map[string]interface{}{"method": "DELETE", "url": base + "/folder/{name}"},
|
||||
"list": map[string]interface{}{
|
||||
"method": "PROPFIND",
|
||||
"url": base + "/folder/?prefix={prefix}",
|
||||
"namesRegex": `<d:href>/folder/([^<]+)</d:href>`,
|
||||
},
|
||||
"retry": map[string]interface{}{"status": []int{429, 500, 502, 503}},
|
||||
}
|
||||
raw, _ := json.Marshal(tmpl)
|
||||
return &internet.MemoryStreamConfig{
|
||||
ProtocolName: protocolName,
|
||||
ProtocolSettings: &Config{
|
||||
RemoteFolder: "folder",
|
||||
Service: "template",
|
||||
Secrets: secrets,
|
||||
Template: string(raw),
|
||||
FlushIntervalMs: 5,
|
||||
PollIntervalMs: 5,
|
||||
MaxPollIntervalMs: 20,
|
||||
SessionTtlSeconds: 5,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newTemplateBackend(t *testing.T, store *fakeStore, auth map[string]interface{}, secrets []string) *templateStorage {
|
||||
t.Helper()
|
||||
settings := templateSettings(store, auth, secrets)
|
||||
storage, err := newTemplateStorage(settings, settings.ProtocolSettings.(*Config))
|
||||
if err != nil {
|
||||
t.Fatalf("newTemplateStorage: %v", err)
|
||||
}
|
||||
return storage
|
||||
}
|
||||
|
||||
func TestTemplateRoundTrip(t *testing.T) {
|
||||
store := newFakeStore(t)
|
||||
storage := newTemplateBackend(t, store, map[string]interface{}{"type": "none"}, nil)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := storage.Put(ctx, "streams/abc/c2s/000000000.seg", []byte("hello")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
data, err := storage.Get(ctx, "streams/abc/c2s/000000000.seg")
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if string(data) != "hello" {
|
||||
t.Fatalf("Get returned %q, want hello", data)
|
||||
}
|
||||
|
||||
entries, err := storage.List(ctx, "streams/abc/c2s")
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if len(entries) != 1 || entries[0].Name != "000000000.seg" {
|
||||
t.Fatalf("List returned %v, want one segment", entries)
|
||||
}
|
||||
|
||||
if _, err := storage.Get(ctx, "streams/abc/c2s/000000009.seg"); err != errNotFound {
|
||||
t.Fatalf("Get of a missing object returned %v, want errNotFound", err)
|
||||
}
|
||||
|
||||
if err := storage.Delete(ctx, "streams/abc/c2s/000000000.seg"); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
if store.count() != 0 {
|
||||
t.Fatalf("store still holds %d objects", store.count())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplateListReturnsDirectChildren(t *testing.T) {
|
||||
store := newFakeStore(t)
|
||||
storage := newTemplateBackend(t, store, map[string]interface{}{"type": "none"}, nil)
|
||||
ctx := context.Background()
|
||||
|
||||
for _, name := range []string{
|
||||
"streams/one/c2s/000000000.seg",
|
||||
"streams/one/s2c/000000000.seg",
|
||||
"streams/two/c2s/000000000.seg",
|
||||
} {
|
||||
if err := storage.Put(ctx, name, []byte("x")); err != nil {
|
||||
t.Fatalf("Put %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
entries, err := storage.List(ctx, "streams")
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Fatalf("List returned %v, want the two session ids", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplateBasicAuth(t *testing.T) {
|
||||
store := newFakeStore(t)
|
||||
store.needAuth = "Basic dXNlcjpwYXNz"
|
||||
auth := map[string]interface{}{"type": "basic", "username": "{secret0}", "password": "{secret1}"}
|
||||
storage := newTemplateBackend(t, store, auth, []string{"user", "pass"})
|
||||
|
||||
if err := storage.Put(context.Background(), "sessions/a", []byte("x")); err != nil {
|
||||
t.Fatalf("Put with basic auth: %v", err)
|
||||
}
|
||||
if store.seenAuth() != "Basic dXNlcjpwYXNz" {
|
||||
t.Fatalf("server saw auth %q", store.seenAuth())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplateOAuth(t *testing.T) {
|
||||
store := newFakeStore(t)
|
||||
store.needAuth = "Bearer tok-fake"
|
||||
auth := map[string]interface{}{
|
||||
"type": "oauth2",
|
||||
"tokenUrl": store.server.URL + "/token",
|
||||
"form": map[string]interface{}{"grant_type": "refresh_token", "refresh_token": "{secret0}"},
|
||||
"header": map[string]interface{}{"Authorization": "Bearer {token}"},
|
||||
}
|
||||
storage := newTemplateBackend(t, store, auth, []string{"refresh"})
|
||||
ctx := context.Background()
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
if err := storage.Put(ctx, fmt.Sprintf("sessions/s%d", i), nil); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
}
|
||||
if store.tokens != 1 {
|
||||
t.Fatalf("token endpoint was hit %d times, want 1", store.tokens)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplateTransport(t *testing.T) {
|
||||
store := newFakeStore(t)
|
||||
settings := templateSettings(store, map[string]interface{}{"type": "none"}, nil)
|
||||
|
||||
client, server, cleanup := pairWith(t, settings)
|
||||
defer cleanup()
|
||||
|
||||
if _, err := client.Write([]byte("ping")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
expectRead(t, server, "ping")
|
||||
|
||||
if _, err := server.Write([]byte("pong")); err != nil {
|
||||
t.Fatalf("server write: %v", err)
|
||||
}
|
||||
expectRead(t, client, "pong")
|
||||
|
||||
payload := make([]byte, 300000)
|
||||
for i := range payload {
|
||||
payload[i] = byte(i % 251)
|
||||
}
|
||||
go func() { client.Write(payload) }()
|
||||
|
||||
if err := server.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
t.Fatalf("SetReadDeadline: %v", err)
|
||||
}
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatalf("ReadFull: %v", err)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != payload[i] {
|
||||
t.Fatalf("payload mismatch at byte %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplateConcurrency(t *testing.T) {
|
||||
store := newFakeStore(t)
|
||||
settings := templateSettings(store, map[string]interface{}{"type": "none"}, nil)
|
||||
|
||||
var tmpl map[string]interface{}
|
||||
cfg := settings.ProtocolSettings.(*Config)
|
||||
if err := json.Unmarshal([]byte(cfg.Template), &tmpl); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
tmpl["concurrency"] = 4
|
||||
raw, _ := json.Marshal(tmpl)
|
||||
cfg.Template = string(raw)
|
||||
|
||||
storage, err := newTemplateStorage(settings, cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("newTemplateStorage: %v", err)
|
||||
}
|
||||
if cap(storage.inflight) != 4 {
|
||||
t.Fatalf("inflight cap is %d, want 4 from the template", cap(storage.inflight))
|
||||
}
|
||||
// and so has a session, of its own
|
||||
session := storage.session().(*templateStorage)
|
||||
defer session.Close()
|
||||
if session.inflight == storage.inflight || cap(session.inflight) != 4 {
|
||||
t.Fatalf("a session shares inflight or has cap %d, want 4", cap(session.inflight))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplateConcurrencyDefault(t *testing.T) {
|
||||
store := newFakeStore(t)
|
||||
storage := newTemplateBackend(t, store, map[string]interface{}{"type": "none"}, nil)
|
||||
if cap(storage.inflight) != driveMaxInflight {
|
||||
t.Fatalf("default inflight cap is %d, want %d", cap(storage.inflight), driveMaxInflight)
|
||||
}
|
||||
}
|
||||
|
||||
// hrefStore mimics the Yandex Disk REST API: upload and download answer with an href
|
||||
// to a presigned blob URL, which must be called without the API credentials.
|
||||
type hrefStore struct {
|
||||
*fakeStore
|
||||
blobAuth string
|
||||
}
|
||||
|
||||
func newHrefStore(t *testing.T) *hrefStore {
|
||||
t.Helper()
|
||||
|
||||
store := &hrefStore{fakeStore: &fakeStore{objects: make(map[string][]byte)}}
|
||||
store.server = httptest.NewServer(http.HandlerFunc(store.handle))
|
||||
t.Cleanup(store.server.Close)
|
||||
return store
|
||||
}
|
||||
|
||||
func (s *hrefStore) handle(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/blob/") {
|
||||
s.mu.Lock()
|
||||
if auth := r.Header.Get("Authorization"); auth != "" {
|
||||
s.blobAuth = auth
|
||||
}
|
||||
s.mu.Unlock()
|
||||
r.URL.Path = "/folder/" + strings.TrimPrefix(r.URL.Path, "/blob/")
|
||||
s.fakeStore.handle(w, r)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "OAuth tok" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
name := r.URL.Query().Get("path")
|
||||
switch r.URL.Path {
|
||||
case "/upload":
|
||||
case "/download":
|
||||
s.mu.Lock()
|
||||
_, ok := s.objects[name]
|
||||
s.mu.Unlock()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{"href": s.server.URL + "/blob/" + name})
|
||||
}
|
||||
|
||||
func hrefSettings(store *hrefStore) *internet.MemoryStreamConfig {
|
||||
base := store.server.URL
|
||||
settings := templateSettings(store.fakeStore, map[string]interface{}{
|
||||
"type": "static", "header": map[string]interface{}{"Authorization": "OAuth {secret0}"},
|
||||
}, []string{"tok"})
|
||||
cfg := settings.ProtocolSettings.(*Config)
|
||||
var tmpl map[string]interface{}
|
||||
json.Unmarshal([]byte(cfg.Template), &tmpl)
|
||||
tmpl["put"] = map[string]interface{}{"url": base + "/upload?path={name}", "hrefPath": "href", "hrefMethod": "PUT"}
|
||||
tmpl["get"] = map[string]interface{}{"url": base + "/download?path={name}", "hrefPath": "href"}
|
||||
tmpl["list"] = map[string]interface{}{"method": "PROPFIND", "url": base + "/blob/", "namesRegex": `<d:href>/folder/([^<]+)</d:href>`}
|
||||
tmpl["delete"] = map[string]interface{}{"method": "DELETE", "url": base + "/blob/{name}"}
|
||||
raw, _ := json.Marshal(tmpl)
|
||||
cfg.Template = string(raw)
|
||||
return settings
|
||||
}
|
||||
|
||||
func TestTemplateTwoStep(t *testing.T) {
|
||||
store := newHrefStore(t)
|
||||
settings := hrefSettings(store)
|
||||
storage, err := newTemplateStorage(settings, settings.ProtocolSettings.(*Config))
|
||||
if err != nil {
|
||||
t.Fatalf("newTemplateStorage: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
if err := storage.Put(ctx, "streams/abc/c2s/000000000.seg", []byte("hello")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
data, err := storage.Get(ctx, "streams/abc/c2s/000000000.seg")
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if string(data) != "hello" {
|
||||
t.Fatalf("Get returned %q, want hello", data)
|
||||
}
|
||||
if _, err := storage.Get(ctx, "streams/abc/c2s/000000009.seg"); err != errNotFound {
|
||||
t.Fatalf("Get of a missing object returned %v, want errNotFound", err)
|
||||
}
|
||||
if store.blobAuth != "" {
|
||||
t.Fatalf("the presigned href received credentials %q", store.blobAuth)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplateTwoStepTransport(t *testing.T) {
|
||||
store := newHrefStore(t)
|
||||
client, server, cleanup := pairWith(t, hrefSettings(store))
|
||||
defer cleanup()
|
||||
|
||||
if _, err := client.Write([]byte("ping")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
expectRead(t, server, "ping")
|
||||
|
||||
if _, err := server.Write([]byte("pong")); err != nil {
|
||||
t.Fatalf("server write: %v", err)
|
||||
}
|
||||
expectRead(t, client, "pong")
|
||||
}
|
||||
@@ -46,8 +46,13 @@ type walWriter struct {
|
||||
storage Storage
|
||||
prefix string
|
||||
params
|
||||
sem chan struct{}
|
||||
wg sync.WaitGroup
|
||||
sem chan struct{}
|
||||
wg sync.WaitGroup
|
||||
flushDone chan struct{}
|
||||
stop chan struct{}
|
||||
failed chan struct{}
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
|
||||
mu sync.Mutex
|
||||
buf []byte
|
||||
@@ -60,37 +65,65 @@ type walWriter struct {
|
||||
|
||||
func newWALWriter(ctx context.Context, storage Storage, prefix string, p params) *walWriter {
|
||||
w := &walWriter{
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
sem: make(chan struct{}, p.concurrency),
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
sem: make(chan struct{}, p.concurrency),
|
||||
flushDone: make(chan struct{}),
|
||||
stop: make(chan struct{}),
|
||||
failed: make(chan struct{}),
|
||||
}
|
||||
go w.flushLoop()
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *walWriter) Write(p []byte) (int, error) {
|
||||
return w.writeUntil(p, nil, nil)
|
||||
}
|
||||
|
||||
// writeUntil is Write that gives up with errWriteStopped, having returned the
|
||||
// bytes it took into buf, once either channel is closed
|
||||
func (w *walWriter) writeUntil(p []byte, deadline, closing <-chan struct{}) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
if w.err != nil {
|
||||
return 0, w.err
|
||||
}
|
||||
if w.closed {
|
||||
if w.closed || w.ctx.Err() != nil {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if isClosedChan(deadline) || isClosedChan(closing) {
|
||||
return 0, errWriteStopped
|
||||
}
|
||||
|
||||
w.buf = append(w.buf, p...)
|
||||
for len(w.buf) >= w.segmentBytes {
|
||||
if err := w.flushLocked(); err != nil {
|
||||
return 0, err
|
||||
accepted := 0
|
||||
for len(p) > 0 {
|
||||
if w.err != nil {
|
||||
return accepted, w.err
|
||||
}
|
||||
if w.closed || w.ctx.Err() != nil {
|
||||
return accepted, io.ErrClosedPipe
|
||||
}
|
||||
if isClosedChan(deadline) || isClosedChan(closing) {
|
||||
return accepted, errWriteStopped
|
||||
}
|
||||
n := min(len(p), w.segmentBytes-len(w.buf))
|
||||
w.buf = append(w.buf, p[:n]...)
|
||||
accepted += n
|
||||
p = p[n:]
|
||||
for len(w.buf) >= w.segmentBytes {
|
||||
if err := w.flushLocked(deadline, closing); err != nil {
|
||||
return accepted, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return len(p), nil
|
||||
return accepted, nil
|
||||
}
|
||||
|
||||
func (w *walWriter) flushLoop() {
|
||||
defer close(w.flushDone)
|
||||
ticker := time.NewTicker(w.flushInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
@@ -98,10 +131,12 @@ func (w *walWriter) flushLoop() {
|
||||
select {
|
||||
case <-w.ctx.Done():
|
||||
return
|
||||
case <-w.stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
w.mu.Lock()
|
||||
if !w.closed && w.err == nil && len(w.buf) > 0 && w.readyToFlush() {
|
||||
w.flushLocked()
|
||||
w.flushLocked(nil, w.stop)
|
||||
}
|
||||
done := w.closed || w.err != nil
|
||||
w.mu.Unlock()
|
||||
@@ -124,13 +159,67 @@ func (w *walWriter) readyToFlush() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *walWriter) flushLocked() error {
|
||||
// flushLocked takes an upload permit before it cuts a segment, waiting without
|
||||
// w.mu, so a store that falls behind holds Write back instead of piling up
|
||||
// goroutines and chunks. Either stop channel, when closed, ends the wait with
|
||||
// errWriteStopped
|
||||
func (w *walWriter) flushLocked(deadline, closing <-chan struct{}) error {
|
||||
return w.flushLockedMode(deadline, closing, false)
|
||||
}
|
||||
|
||||
func (w *walWriter) flushLockedMode(deadline, closing <-chan struct{}, draining bool) error {
|
||||
if err := w.ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.closed && !draining {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if len(w.buf) == 0 {
|
||||
return nil
|
||||
}
|
||||
if w.err != nil {
|
||||
return w.err
|
||||
}
|
||||
select {
|
||||
case <-deadline:
|
||||
return errWriteStopped
|
||||
case <-closing:
|
||||
return errWriteStopped
|
||||
default:
|
||||
}
|
||||
w.mu.Unlock()
|
||||
select {
|
||||
case w.sem <- struct{}{}:
|
||||
case <-w.failed:
|
||||
w.mu.Lock()
|
||||
return w.err
|
||||
case <-w.ctx.Done():
|
||||
w.mu.Lock()
|
||||
return w.ctx.Err()
|
||||
case <-deadline:
|
||||
w.mu.Lock()
|
||||
return errWriteStopped
|
||||
case <-closing:
|
||||
w.mu.Lock()
|
||||
return errWriteStopped
|
||||
}
|
||||
w.mu.Lock()
|
||||
if err := w.ctx.Err(); err != nil {
|
||||
<-w.sem
|
||||
return err
|
||||
}
|
||||
if w.closed && !draining {
|
||||
<-w.sem
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if isClosedChan(deadline) || isClosedChan(closing) {
|
||||
<-w.sem
|
||||
return errWriteStopped
|
||||
}
|
||||
if w.err != nil || len(w.buf) == 0 {
|
||||
<-w.sem
|
||||
return w.err
|
||||
}
|
||||
|
||||
n := len(w.buf)
|
||||
if n > w.segmentBytes {
|
||||
@@ -157,18 +246,20 @@ func (w *walWriter) flushLocked() error {
|
||||
|
||||
func (w *walWriter) upload(seq int64, chunk []byte) {
|
||||
defer w.wg.Done()
|
||||
|
||||
select {
|
||||
case w.sem <- struct{}{}:
|
||||
case <-w.ctx.Done():
|
||||
defer func() { <-w.sem }()
|
||||
if w.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
defer func() { <-w.sem }()
|
||||
|
||||
if err := w.storage.Put(w.ctx, objectName(w.prefix, seq, segSuffix), chunk); err != nil {
|
||||
err := w.storage.Put(w.ctx, objectName(w.prefix, seq, segSuffix), chunk)
|
||||
if err == nil && requiresWALCommit(w.storage) {
|
||||
err = w.storage.Put(w.ctx, objectName(w.prefix, seq, commitSuffix), encodeWALCommit(chunk))
|
||||
}
|
||||
if err != nil && w.ctx.Err() == nil {
|
||||
w.mu.Lock()
|
||||
if w.err == nil {
|
||||
w.err = errors.New("failed to store segment").Base(err)
|
||||
close(w.failed)
|
||||
}
|
||||
w.mu.Unlock()
|
||||
w.storage.Put(w.ctx, objectName(w.prefix, seq, errSuffix), nil)
|
||||
@@ -176,27 +267,39 @@ func (w *walWriter) upload(seq int64, chunk []byte) {
|
||||
}
|
||||
|
||||
func (w *walWriter) Close() error {
|
||||
w.mu.Lock()
|
||||
if w.closed {
|
||||
w.closeOnce.Do(func() {
|
||||
w.mu.Lock()
|
||||
w.closed = true
|
||||
close(w.stop)
|
||||
w.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
w.closed = true
|
||||
for len(w.buf) > 0 && w.err == nil {
|
||||
w.flushLocked()
|
||||
}
|
||||
w.mu.Unlock()
|
||||
<-w.flushDone
|
||||
|
||||
w.wg.Wait()
|
||||
w.mu.Lock()
|
||||
var flushErr error
|
||||
for len(w.buf) > 0 && w.err == nil {
|
||||
if err := w.flushLockedMode(nil, nil, true); err != nil {
|
||||
flushErr = err
|
||||
break
|
||||
}
|
||||
}
|
||||
w.mu.Unlock()
|
||||
w.wg.Wait()
|
||||
|
||||
w.mu.Lock()
|
||||
err, seq := w.err, w.seq
|
||||
w.mu.Unlock()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return w.storage.Put(w.ctx, objectName(w.prefix, seq, endSuffix), nil)
|
||||
w.mu.Lock()
|
||||
err, seq := w.err, w.seq
|
||||
w.mu.Unlock()
|
||||
switch {
|
||||
case err != nil:
|
||||
w.closeErr = err
|
||||
case w.ctx.Err() != nil:
|
||||
w.closeErr = w.ctx.Err()
|
||||
case flushErr != nil:
|
||||
w.closeErr = flushErr
|
||||
default:
|
||||
w.closeErr = w.storage.Put(w.ctx, objectName(w.prefix, seq, endSuffix), nil)
|
||||
}
|
||||
})
|
||||
return w.closeErr
|
||||
}
|
||||
|
||||
type walReader struct {
|
||||
@@ -207,26 +310,37 @@ type walReader struct {
|
||||
seq int64
|
||||
|
||||
ch chan []byte
|
||||
discard bool
|
||||
discards chan string
|
||||
wake chan struct{}
|
||||
holeSince time.Time
|
||||
|
||||
errMu sync.Mutex
|
||||
err error
|
||||
done chan struct{}
|
||||
work sync.WaitGroup
|
||||
}
|
||||
|
||||
func newWALReader(ctx context.Context, storage Storage, prefix string, p params) *walReader {
|
||||
func newWALReader(ctx context.Context, storage Storage, prefix string, p params, discard bool) *walReader {
|
||||
r := &walReader{
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
ch: make(chan []byte, p.concurrency),
|
||||
discards: make(chan string, 4*p.concurrency),
|
||||
wake: make(chan struct{}, 1),
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
ch: make(chan []byte, p.concurrency),
|
||||
discard: discard,
|
||||
wake: make(chan struct{}, 1),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
if discard {
|
||||
r.discards = make(chan string, 4*p.concurrency)
|
||||
r.work.Add(1)
|
||||
go func() {
|
||||
defer r.work.Done()
|
||||
r.discardLoop()
|
||||
}()
|
||||
}
|
||||
go r.run()
|
||||
go r.discardLoop()
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -241,7 +355,13 @@ func (r *walReader) Wake() {
|
||||
}
|
||||
}
|
||||
|
||||
func (r *walReader) wait() {
|
||||
<-r.done
|
||||
r.work.Wait()
|
||||
}
|
||||
|
||||
func (r *walReader) run() {
|
||||
defer close(r.done)
|
||||
defer close(r.ch)
|
||||
|
||||
delay := r.minPollInterval
|
||||
@@ -297,36 +417,37 @@ func (r *walReader) poll() (advanced, eof bool, err error) {
|
||||
return false, false, err
|
||||
}
|
||||
if len(listed) == 0 {
|
||||
return false, false, nil
|
||||
return false, false, r.pendingError(false)
|
||||
}
|
||||
|
||||
pending := make(map[int64]Entry, len(listed))
|
||||
ahead := false
|
||||
observedThrough := int64(-1)
|
||||
for _, entry := range listed {
|
||||
seq, ok := parseEntry(entry.Name)
|
||||
if !ok {
|
||||
if requiresWALCommit(r.storage) && strings.HasSuffix(entry.Name, commitSuffix) {
|
||||
seq, ok = parseEntry(strings.TrimSuffix(entry.Name, commitSuffix) + segSuffix)
|
||||
if ok {
|
||||
observedThrough = max(observedThrough, seq)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
observedThrough = max(observedThrough, seq)
|
||||
if previous, exists := pending[seq]; exists && strings.HasSuffix(previous.Name, errSuffix) {
|
||||
continue
|
||||
}
|
||||
pending[seq] = entry
|
||||
if seq > r.seq {
|
||||
ahead = true
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := pending[r.seq]; !ok && ahead {
|
||||
if r.holeSince.IsZero() {
|
||||
r.holeSince = time.Now()
|
||||
} else if time.Since(r.holeSince) >= r.holeTimeout {
|
||||
return false, false, errors.New("segment ", r.seq,
|
||||
" never arrived while later ones did, the peer lost it")
|
||||
}
|
||||
} else {
|
||||
r.holeSince = time.Time{}
|
||||
}
|
||||
|
||||
for {
|
||||
if _, ok := pending[r.seq]; !ok {
|
||||
if err := r.pendingError(observedThrough >= r.seq); err != nil {
|
||||
return advanced, false, err
|
||||
}
|
||||
}
|
||||
if entry, ok := pending[r.seq]; ok && strings.HasSuffix(entry.Name, errSuffix) {
|
||||
r.discard(r.prefix + "/" + entry.Name)
|
||||
r.queueDiscard(r.prefix + "/" + entry.Name)
|
||||
return advanced, false, errors.New("the peer could not store segment ", r.seq)
|
||||
}
|
||||
|
||||
@@ -339,9 +460,9 @@ func (r *walReader) poll() (advanced, eof bool, err error) {
|
||||
}
|
||||
|
||||
chunks, err := r.fetch(batch)
|
||||
if err != nil {
|
||||
if err != nil && (err != errNotFound || len(chunks) == 0) {
|
||||
if err == errNotFound {
|
||||
return advanced, false, nil
|
||||
return advanced, false, r.pendingError(true)
|
||||
}
|
||||
return advanced, false, err
|
||||
}
|
||||
@@ -352,13 +473,34 @@ func (r *walReader) poll() (advanced, eof bool, err error) {
|
||||
case <-r.ctx.Done():
|
||||
return advanced, true, nil
|
||||
}
|
||||
seq := r.seq
|
||||
r.seq++
|
||||
r.holeSince = time.Time{}
|
||||
advanced = true
|
||||
r.discard(r.prefix + "/" + batch[i].Name)
|
||||
r.queueDiscard(r.prefix + "/" + batch[i].Name)
|
||||
if requiresWALCommit(r.storage) {
|
||||
r.queueDiscard(objectName(r.prefix, seq, commitSuffix))
|
||||
}
|
||||
}
|
||||
if err == errNotFound {
|
||||
return advanced, false, r.pendingError(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *walReader) pendingError(observed bool) error {
|
||||
if r.holeSince.IsZero() {
|
||||
if observed {
|
||||
r.holeSince = time.Now()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if time.Since(r.holeSince) >= r.holeTimeout {
|
||||
return errors.New("segment ", r.seq, " did not complete before the stream progress timeout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *walReader) nextBatch(pending map[int64]Entry) (batch []Entry, done bool) {
|
||||
for i := 0; i < r.concurrency; i++ {
|
||||
entry, ok := pending[r.seq+int64(i)]
|
||||
@@ -367,7 +509,7 @@ func (r *walReader) nextBatch(pending map[int64]Entry) (batch []Entry, done bool
|
||||
}
|
||||
if !strings.HasSuffix(entry.Name, segSuffix) {
|
||||
if i == 0 && strings.HasSuffix(entry.Name, endSuffix) {
|
||||
r.discard(r.prefix + "/" + entry.Name)
|
||||
r.queueDiscard(r.prefix + "/" + entry.Name)
|
||||
return nil, true
|
||||
}
|
||||
break
|
||||
@@ -395,15 +537,51 @@ func (r *walReader) fetch(batch []Entry) ([][]byte, error) {
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
for i := range batch {
|
||||
if failures[i] != nil {
|
||||
return nil, failures[i]
|
||||
for _, err := range failures {
|
||||
if err != nil && err != errNotFound {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, chunk := range chunks {
|
||||
if len(chunk) > maxSegmentBytes {
|
||||
return nil, errors.New("segment exceeds the maximum size")
|
||||
}
|
||||
}
|
||||
commits := make([][]byte, len(batch))
|
||||
commitFailures := make([]error, len(batch))
|
||||
if requiresWALCommit(r.storage) {
|
||||
for i, entry := range batch {
|
||||
wg.Add(1)
|
||||
go func(i int, name string) {
|
||||
defer wg.Done()
|
||||
seq, _ := parseEntry(name)
|
||||
ctx := context.WithValue(r.ctx, maxBodyKey{}, int64(walCommitBytes))
|
||||
commits[i], commitFailures[i] = r.storage.Get(ctx, objectName(r.prefix, seq, commitSuffix))
|
||||
}(i, entry.Name)
|
||||
}
|
||||
wg.Wait()
|
||||
for _, err := range commitFailures {
|
||||
if err != nil && err != errNotFound {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
for i, err := range failures {
|
||||
if err != nil || len(chunks[i]) == 0 {
|
||||
return chunks[:i], errNotFound
|
||||
}
|
||||
if requiresWALCommit(r.storage) && (commitFailures[i] != nil || !validWALCommit(commits[i], chunks[i])) {
|
||||
return chunks[:i], errNotFound
|
||||
}
|
||||
}
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
func (r *walReader) discard(name string) {
|
||||
func (r *walReader) queueDiscard(name string) {
|
||||
if !r.discard {
|
||||
// Downlink segments stay until the server collects the idle session after sessionTTL.
|
||||
return
|
||||
}
|
||||
select {
|
||||
case r.discards <- name:
|
||||
default:
|
||||
@@ -411,6 +589,9 @@ func (r *walReader) discard(name string) {
|
||||
}
|
||||
|
||||
func (r *walReader) discardLoop() {
|
||||
if !r.discard {
|
||||
return
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
|
||||
@@ -420,7 +601,11 @@ func (r *walReader) discardLoop() {
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
case name := <-r.discards:
|
||||
sem <- struct{}{}
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(name string) {
|
||||
defer wg.Done()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
const (
|
||||
commitSuffix = ".commit"
|
||||
walCommitMagic = "XDWALC01"
|
||||
walCommitBytes = 8 + 8 + sha256.Size
|
||||
)
|
||||
|
||||
func (*templateStorage) requiresWALCommit() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func requiresWALCommit(storage Storage) bool {
|
||||
s, ok := storage.(interface{ requiresWALCommit() bool })
|
||||
return ok && s.requiresWALCommit()
|
||||
}
|
||||
|
||||
func encodeWALCommit(data []byte) []byte {
|
||||
commit := make([]byte, walCommitBytes)
|
||||
copy(commit, walCommitMagic)
|
||||
binary.BigEndian.PutUint64(commit[8:16], uint64(len(data)))
|
||||
sum := sha256.Sum256(data)
|
||||
copy(commit[16:], sum[:])
|
||||
return commit
|
||||
}
|
||||
|
||||
func validWALCommit(commit, data []byte) bool {
|
||||
if len(commit) != walCommitBytes || string(commit[:8]) != walCommitMagic || len(data) == 0 || len(data) > maxSegmentBytes {
|
||||
return false
|
||||
}
|
||||
if binary.BigEndian.Uint64(commit[8:16]) != uint64(len(data)) {
|
||||
return false
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
return bytes.Equal(commit[16:], sum[:])
|
||||
}
|
||||
+377
-224
@@ -6,10 +6,10 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -27,11 +27,6 @@ const (
|
||||
downlinkDir = "s2c"
|
||||
)
|
||||
|
||||
const (
|
||||
spareCount = 2
|
||||
spareIdleStop = 10 * time.Minute
|
||||
)
|
||||
|
||||
func init() {
|
||||
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {
|
||||
return new(Config)
|
||||
@@ -53,6 +48,17 @@ func announceName(session string, at time.Time) string {
|
||||
}
|
||||
|
||||
func parseAnnounce(entry string) (string, time.Time, bool) {
|
||||
session, at, ok := announceParts(entry)
|
||||
if !ok || !safeSessionID(session) {
|
||||
return "", time.Time{}, false
|
||||
}
|
||||
return session, at, true
|
||||
}
|
||||
|
||||
// announceParts splits an announcement entry into its session and its time.
|
||||
// The session is not checked: a caller that turns it into an object name has
|
||||
// to ask safeSessionID first.
|
||||
func announceParts(entry string) (string, time.Time, bool) {
|
||||
dash := strings.IndexByte(entry, '-')
|
||||
if dash <= 0 || dash == len(entry)-1 {
|
||||
return "", time.Time{}, false
|
||||
@@ -64,6 +70,49 @@ func parseAnnounce(entry string) (string, time.Time, bool) {
|
||||
return entry[dash+1:], time.Unix(0, nanos), true
|
||||
}
|
||||
|
||||
// A session id reaches object names, so it must not traverse, must not
|
||||
// collide with another name once a separator is flattened, and must not name
|
||||
// a reserved file.
|
||||
func safeSessionID(session string) bool {
|
||||
return safeNameChars(session) && !reservedName(session)
|
||||
}
|
||||
|
||||
// A listed name becomes a delete target, so it must be safe to build one
|
||||
// from.
|
||||
func safeListedName(name string) bool {
|
||||
return safeNameChars(name) && !reservedName(name)
|
||||
}
|
||||
|
||||
func safeNameChars(name string) bool {
|
||||
if name == "" || len(name) > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range name {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
|
||||
case r == '-' || r == '_' || r == '.':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return name[0] != '.' && name[len(name)-1] != '.'
|
||||
}
|
||||
|
||||
func reservedName(name string) bool {
|
||||
base := name
|
||||
if i := strings.IndexByte(base, '.'); i >= 0 {
|
||||
base = base[:i]
|
||||
}
|
||||
switch strings.ToUpper(base) {
|
||||
case "CON", "PRN", "AUX", "NUL":
|
||||
return true
|
||||
}
|
||||
if len(base) == 4 && base[3] >= '1' && base[3] <= '9' {
|
||||
return strings.EqualFold(base[:3], "COM") || strings.EqualFold(base[:3], "LPT")
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func sessionPrefix(session string) string {
|
||||
return streamsDir + "/" + session
|
||||
}
|
||||
@@ -77,6 +126,9 @@ func downlinkPrefix(session string) string {
|
||||
}
|
||||
|
||||
func streamConfig(streamSettings *internet.MemoryStreamConfig) (*Config, error) {
|
||||
if streamSettings == nil {
|
||||
return nil, errors.New("missing stream settings")
|
||||
}
|
||||
config, ok := streamSettings.ProtocolSettings.(*Config)
|
||||
if !ok || config == nil {
|
||||
return nil, errors.New("invalid protocol settings")
|
||||
@@ -84,185 +136,78 @@ func streamConfig(streamSettings *internet.MemoryStreamConfig) (*Config, error)
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type spareRing struct {
|
||||
storage Storage
|
||||
session string
|
||||
ring ring
|
||||
at time.Time
|
||||
}
|
||||
|
||||
type spareBox struct {
|
||||
ch chan spareRing
|
||||
busy atomic.Bool
|
||||
last atomic.Int64
|
||||
stop atomic.Bool
|
||||
}
|
||||
|
||||
var spareBoxes sync.Map
|
||||
|
||||
func spareBoxFor(config *Config) *spareBox {
|
||||
if b, ok := spareBoxes.Load(config); ok {
|
||||
return b.(*spareBox)
|
||||
}
|
||||
b, _ := spareBoxes.LoadOrStore(config, &spareBox{ch: make(chan spareRing, spareCount)})
|
||||
return b.(*spareBox)
|
||||
}
|
||||
|
||||
func dropSpare(s spareRing) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
s.storage.Delete(ctx, sessionPrefix(s.session))
|
||||
s.storage.Close()
|
||||
}
|
||||
|
||||
func takeSpare(config *Config, p params) (spareRing, bool) {
|
||||
box := spareBoxFor(config)
|
||||
for {
|
||||
select {
|
||||
case s := <-box.ch:
|
||||
if time.Since(s.at) < p.sessionTTL*2/3 {
|
||||
return s, true
|
||||
}
|
||||
go dropSpare(s)
|
||||
default:
|
||||
return spareRing{}, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func warmSpares(streamSettings *internet.MemoryStreamConfig, config *Config, p params) {
|
||||
spareBoxFor(config).last.Store(time.Now().UnixNano())
|
||||
fillSpares(streamSettings, config, p)
|
||||
}
|
||||
|
||||
func fillSpares(streamSettings *internet.MemoryStreamConfig, config *Config, p params) {
|
||||
box := spareBoxFor(config)
|
||||
if !box.busy.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer box.busy.Store(false)
|
||||
for n := len(box.ch); n > 0; n-- {
|
||||
select {
|
||||
case s := <-box.ch:
|
||||
if time.Since(s.at) < p.sessionTTL/3 {
|
||||
box.ch <- s
|
||||
} else {
|
||||
dropSpare(s)
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
for len(box.ch) < cap(box.ch) {
|
||||
for range 40 {
|
||||
if box.stop.Load() {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if box.stop.Load() {
|
||||
return
|
||||
}
|
||||
storage, err := newStorage(streamSettings)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
storage = sessionStorage(storage)
|
||||
slots, ok := storage.(slotStore)
|
||||
if !ok {
|
||||
storage.Close()
|
||||
return
|
||||
}
|
||||
session, err := newSessionID()
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
r, err := makeRing(ctx, slots, session, p)
|
||||
cancel()
|
||||
if err != nil {
|
||||
dropSpare(spareRing{storage: storage, session: session})
|
||||
return
|
||||
}
|
||||
select {
|
||||
case box.ch <- spareRing{storage: storage, session: session, ring: r, at: time.Now()}:
|
||||
default:
|
||||
storage.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
time.AfterFunc(p.sessionTTL/4, func() {
|
||||
if !box.stop.Load() && time.Since(time.Unix(0, box.last.Load())) < spareIdleStop {
|
||||
fillSpares(streamSettings, config, p)
|
||||
}
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config, err := streamConfig(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
p := paramsFromConfig(config)
|
||||
if streamSettings.Destination == nil && dest.Address != nil {
|
||||
front := dest
|
||||
front.Network = net.Network_TCP
|
||||
patched := *streamSettings
|
||||
patched.Destination = &front
|
||||
streamSettings = &patched
|
||||
}
|
||||
|
||||
spare, warm := takeSpare(config, p)
|
||||
storage, session, r := spare.storage, spare.session, spare.ring
|
||||
if !warm {
|
||||
storage, err = newStorage(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storage = sessionStorage(storage)
|
||||
|
||||
session, err = newSessionID()
|
||||
storage, err := newStorage(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storage, err = transferSessionStorage(storage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
session, err := newSessionID()
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
p := paramsForStorage(config, storage)
|
||||
if slots, ok := storage.(slotStore); ok {
|
||||
depth := max(2, p.concurrency)
|
||||
ids, err := slots.takeIDs(ctx, 2*(depth+1)+1)
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
p = paramsForStorage(config, storage)
|
||||
|
||||
slots, ok := storage.(slotStore)
|
||||
if ok && !warm {
|
||||
if r, err = makeRing(ctx, slots, session, p); err != nil {
|
||||
ok = false
|
||||
errors.LogWarningInner(ctx, err, "failed to make the slots of session ", session, ", it goes in segments")
|
||||
}
|
||||
}
|
||||
|
||||
if ok {
|
||||
warmSpares(streamSettings, config, p)
|
||||
r := lazyRing(session, depth, ids[:len(ids)-1])
|
||||
errors.LogInfo(ctx, "opened session ", session, " in ", len(r.Up.Slots), " slots")
|
||||
releaseSession, err := holdStorageSession(storage, session)
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
conn := newSlotConn(context.Background(), slots, r.Up, r.Down, p, nil, func() {
|
||||
storage.Close()
|
||||
releaseSession()
|
||||
})
|
||||
writer := conn.writer.(*slotWriter)
|
||||
writer.first = make(chan []byte, 1)
|
||||
go func() {
|
||||
var first []byte
|
||||
|
||||
conn.publishWG.Go(func() {
|
||||
select {
|
||||
case first = <-writer.first:
|
||||
case <-conn.ctx.Done():
|
||||
return
|
||||
case r.First = <-writer.first:
|
||||
case <-time.After(25 * time.Millisecond):
|
||||
}
|
||||
if conn.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
announce, _ := json.Marshal(r)
|
||||
if len(first) > 0 && len(first) <= slotInlineLimit {
|
||||
withFirst := r
|
||||
withFirst.First = first
|
||||
if encoded, err := json.Marshal(withFirst); err == nil && len(encoded) <= driveInlineLimit {
|
||||
announce = encoded
|
||||
}
|
||||
if len(r.First) != 0 && len(announce) > driveInlineLimit {
|
||||
r.First = nil
|
||||
announce, _ = json.Marshal(r)
|
||||
}
|
||||
// An announce failure surfaces as a connection error on the next Write/Read.
|
||||
if err := storage.Put(context.Background(), announceName(session, time.Now()), announce); err != nil {
|
||||
if err := putDriveObject(conn.ctx, slots, ids[len(ids)-1], announceName(session, time.Now()), announce); err != nil && conn.ctx.Err() == nil {
|
||||
err = errors.New("failed to announce session ", session).Base(err)
|
||||
writer.fail(err)
|
||||
conn.reader.(*slotReader).setErr(err)
|
||||
}
|
||||
}()
|
||||
})
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
@@ -272,7 +217,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me
|
||||
}
|
||||
errors.LogInfo(ctx, "opened session ", session)
|
||||
return newConn(context.Background(), storage,
|
||||
uplinkPrefix(session), downlinkPrefix(session), p, func() {
|
||||
uplinkPrefix(session), downlinkPrefix(session), p, false, func() {
|
||||
storage.Close()
|
||||
}), nil
|
||||
}
|
||||
@@ -288,8 +233,21 @@ type Listener struct {
|
||||
active map[string]bool
|
||||
handled map[string]time.Time
|
||||
idleSince map[string]time.Time
|
||||
collecting map[string]bool
|
||||
announceWarned map[string]bool
|
||||
firstSeen map[string]time.Time
|
||||
lastSeen map[string]time.Time
|
||||
stopping bool
|
||||
cleanupPending map[string]bool
|
||||
cleanupQueue []string
|
||||
cleanupRunning int
|
||||
loopWG sync.WaitGroup
|
||||
cleanupWG sync.WaitGroup
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
|
||||
// collectPause spaces the deletion of two collected sessions.
|
||||
collectPause time.Duration
|
||||
}
|
||||
|
||||
func Serve(ctx context.Context, address net.Address, port net.Port, streamSettings *internet.MemoryStreamConfig, addConn internet.ConnHandler) (internet.Listener, error) {
|
||||
@@ -315,10 +273,19 @@ func Serve(ctx context.Context, address net.Address, port net.Port, streamSettin
|
||||
idleSince: make(map[string]time.Time),
|
||||
announceWarned: make(map[string]bool),
|
||||
firstSeen: make(map[string]time.Time),
|
||||
lastSeen: make(map[string]time.Time),
|
||||
collectPause: cleanupSessionPause,
|
||||
}
|
||||
|
||||
go listener.acceptLoop(ctx)
|
||||
go listener.collectLoop(ctx)
|
||||
listener.loopWG.Add(2)
|
||||
go func() {
|
||||
defer listener.loopWG.Done()
|
||||
listener.acceptLoop(ctx)
|
||||
}()
|
||||
go func() {
|
||||
defer listener.loopWG.Done()
|
||||
listener.collectLoop(ctx)
|
||||
}()
|
||||
|
||||
return listener, nil
|
||||
}
|
||||
@@ -361,20 +328,22 @@ func (l *Listener) acceptPending(logCtx context.Context) (bool, error) {
|
||||
|
||||
accepted := false
|
||||
l.mu.Lock()
|
||||
if l.firstSeen == nil {
|
||||
l.firstSeen = make(map[string]time.Time)
|
||||
}
|
||||
now := time.Now()
|
||||
listedEntries := make(map[string]bool, len(sessions))
|
||||
for _, listed := range sessions {
|
||||
listedEntries[listed.Name] = true
|
||||
l.lastSeen[listed.Name] = now
|
||||
if _, seen := l.firstSeen[listed.Name]; !seen {
|
||||
l.firstSeen[listed.Name] = now
|
||||
first := listed.created
|
||||
if first.IsZero() || first.After(now) {
|
||||
first = now
|
||||
}
|
||||
l.firstSeen[listed.Name] = first
|
||||
}
|
||||
}
|
||||
// Keep first-seen times across brief listing omissions.
|
||||
for entry := range l.firstSeen {
|
||||
if !listedEntries[entry] {
|
||||
if now.Sub(l.lastSeen[entry]) >= 2*l.sessionTTL {
|
||||
delete(l.firstSeen, entry)
|
||||
delete(l.lastSeen, entry)
|
||||
}
|
||||
}
|
||||
l.mu.Unlock()
|
||||
@@ -383,86 +352,225 @@ func (l *Listener) acceptPending(logCtx context.Context) (bool, error) {
|
||||
entry := listed.Name
|
||||
full := sessionsDir + "/" + entry
|
||||
|
||||
session, _, ok := parseAnnounce(entry)
|
||||
session, _, ok := announceParts(entry)
|
||||
if !ok {
|
||||
go l.drop(full)
|
||||
// Never construct a deletion path from an unsafe name.
|
||||
if safeListedName(entry) {
|
||||
l.queueDrop(full)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !safeSessionID(session) {
|
||||
continue
|
||||
}
|
||||
l.mu.Lock()
|
||||
age := now.Sub(l.firstSeen[entry])
|
||||
expires := l.firstSeen[entry].Add(l.sessionTTL)
|
||||
l.mu.Unlock()
|
||||
if age > l.sessionTTL {
|
||||
if !time.Now().Before(expires) {
|
||||
errors.LogInfo(logCtx, "dropping the stale announcement of session ", session)
|
||||
go l.drop(full)
|
||||
l.mu.Lock()
|
||||
protected := l.active[session] || !l.handled[session].IsZero()
|
||||
l.mu.Unlock()
|
||||
if !protected {
|
||||
go l.drop(sessionPrefix(session))
|
||||
}
|
||||
l.queueDrop(full)
|
||||
l.queueSessionDrop(session)
|
||||
continue
|
||||
}
|
||||
if !l.claim(session) {
|
||||
l.mu.Lock()
|
||||
if !l.handled[session].IsZero() {
|
||||
l.queueDropLocked(full)
|
||||
}
|
||||
l.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
admit, cancel := context.WithDeadline(l.ctx, expires)
|
||||
announce := listed.Inline
|
||||
if len(announce) == 0 {
|
||||
if _, ok := sessionStorage(l.storage).(slotStore); ok {
|
||||
announce, err = l.storage.Get(context.WithValue(l.ctx, maxBodyKey{}, int64(driveMaxAnnounce)), full)
|
||||
if err != nil {
|
||||
l.mu.Lock()
|
||||
delete(l.active, session)
|
||||
delete(l.handled, session)
|
||||
warn := !l.announceWarned[session]
|
||||
l.announceWarned[session] = true
|
||||
l.mu.Unlock()
|
||||
if warn {
|
||||
errors.LogWarningInner(logCtx, err, "failed to read the announcement of session ", session)
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
var conn *Conn
|
||||
var loadErr error
|
||||
if _, slots := l.storage.(slotStore); slots && len(announce) == 0 {
|
||||
announce, loadErr = l.storage.Get(context.WithValue(admit, maxBodyKey{}, int64(driveMaxAnnounce)), full)
|
||||
}
|
||||
go l.drop(full)
|
||||
if loadErr == nil && admit.Err() == nil {
|
||||
conn = l.newSessionConn(admit, session, announce)
|
||||
}
|
||||
cancel()
|
||||
if conn == nil {
|
||||
l.mu.Lock()
|
||||
delete(l.active, session)
|
||||
delete(l.handled, session)
|
||||
warn := loadErr != nil && !l.announceWarned[session]
|
||||
if warn {
|
||||
l.announceWarned[session] = true
|
||||
}
|
||||
l.mu.Unlock()
|
||||
if warn {
|
||||
errors.LogWarningInner(logCtx, loadErr, "failed to read the announcement of session ", session)
|
||||
}
|
||||
continue
|
||||
}
|
||||
l.queueDrop(full)
|
||||
accepted = true
|
||||
l.addConn(l.newSessionConn(logCtx, session, announce))
|
||||
l.addConn(conn)
|
||||
}
|
||||
return accepted, nil
|
||||
}
|
||||
|
||||
func (l *Listener) drop(name string) {
|
||||
l.storage.Delete(l.ctx, name)
|
||||
const (
|
||||
listenerCleanupWorkers = 2
|
||||
listenerCleanupQueue = 128
|
||||
)
|
||||
|
||||
func (l *Listener) queueDrop(name string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.queueDropLocked(name)
|
||||
}
|
||||
|
||||
func (l *Listener) queueSessionDrop(session string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.active[session] || !l.handled[session].IsZero() || l.collecting[session] {
|
||||
return
|
||||
}
|
||||
if since := l.idleSince[session]; !since.IsZero() && time.Since(since) < l.sessionTTL {
|
||||
return
|
||||
}
|
||||
if l.collecting == nil {
|
||||
l.collecting = make(map[string]bool)
|
||||
}
|
||||
l.collecting[session] = true
|
||||
if !l.queueDropLocked(sessionPrefix(session)) {
|
||||
delete(l.collecting, session)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Listener) queueDropLocked(name string) bool {
|
||||
if l.stopping || l.ctx.Err() != nil || len(l.cleanupQueue) >= listenerCleanupQueue || l.cleanupPending[name] {
|
||||
return false
|
||||
}
|
||||
if l.cleanupPending == nil {
|
||||
l.cleanupPending = make(map[string]bool)
|
||||
}
|
||||
l.cleanupPending[name] = true
|
||||
l.cleanupQueue = append(l.cleanupQueue, name)
|
||||
if l.cleanupRunning < listenerCleanupWorkers {
|
||||
l.cleanupRunning++
|
||||
l.cleanupWG.Add(1)
|
||||
go l.cleanupWorker()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (l *Listener) cleanupWorker() {
|
||||
defer l.cleanupWG.Done()
|
||||
for {
|
||||
l.mu.Lock()
|
||||
if len(l.cleanupQueue) == 0 {
|
||||
l.cleanupRunning--
|
||||
l.mu.Unlock()
|
||||
return
|
||||
}
|
||||
name := l.cleanupQueue[0]
|
||||
l.cleanupQueue[0] = ""
|
||||
l.cleanupQueue = l.cleanupQueue[1:]
|
||||
l.mu.Unlock()
|
||||
err := l.drop(name)
|
||||
l.finishDrop(name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Listener) finishDrop(name string, err error) {
|
||||
l.mu.Lock()
|
||||
delete(l.cleanupPending, name)
|
||||
if strings.HasPrefix(name, streamsDir+"/") {
|
||||
session := strings.TrimPrefix(name, streamsDir+"/")
|
||||
delete(l.collecting, session)
|
||||
if err == nil || err == errSessionInUse || l.idleSince[session].IsZero() {
|
||||
l.idleSince[session] = time.Now()
|
||||
}
|
||||
}
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
func (l *Listener) drop(name string) error {
|
||||
ctx := context.WithValue(l.ctx, cleanupKey{}, true)
|
||||
var last error
|
||||
for attempt := 0; attempt < cleanupMaxRetries && ctx.Err() == nil; attempt++ {
|
||||
if err := l.storage.Delete(ctx, name); err == nil {
|
||||
return nil
|
||||
} else if err == errSessionInUse {
|
||||
return err
|
||||
} else {
|
||||
last = err
|
||||
errors.LogDebug(ctx, "failed to drop ", name, ": ", err)
|
||||
}
|
||||
if attempt+1 < cleanupMaxRetries && sleepContext(ctx, cleanupRetryDelay+jitter(cleanupRetryDelay)) != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
func (l *Listener) claim(session string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.active[session] || !l.handled[session].IsZero() {
|
||||
if !safeSessionID(session) {
|
||||
return false
|
||||
}
|
||||
if l.stopping || l.ctx.Err() != nil || l.active[session] || !l.handled[session].IsZero() || l.collecting[session] {
|
||||
return false
|
||||
}
|
||||
if l.active == nil {
|
||||
l.active = make(map[string]bool)
|
||||
}
|
||||
if l.handled == nil {
|
||||
l.handled = make(map[string]time.Time)
|
||||
}
|
||||
l.active[session] = true
|
||||
l.handled[session] = time.Now()
|
||||
// The session was accepted, so the inactivity it was listed with is over:
|
||||
// a claim must not hand the session the age it had before it was taken.
|
||||
delete(l.idleSince, session)
|
||||
return true
|
||||
}
|
||||
|
||||
// newSessionConn takes a session in the slots that its announcement has, or
|
||||
// in segments if it has none
|
||||
func (l *Listener) newSessionConn(logCtx context.Context, session string, announce []byte) *Conn {
|
||||
storage := sessionStorage(l.storage)
|
||||
// Drive requires a ring announcement; other backends use the WAL.
|
||||
func (l *Listener) newSessionConn(admit context.Context, session string, announce []byte) *Conn {
|
||||
storage, err := acquireSessionStorage(l.storage)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
releaseSession, err := holdStorageSession(storage, session)
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil
|
||||
}
|
||||
onClose := func() {
|
||||
storage.Close()
|
||||
releaseSession()
|
||||
l.mu.Lock()
|
||||
delete(l.active, session)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
if slots, ok := storage.(slotStore); ok {
|
||||
if r, ok := decodeRing(announce); ok {
|
||||
errors.LogInfo(logCtx, "accepted session ", session, " in ", len(r.Down.Slots), " slots")
|
||||
r.Up.lazy, r.Down.lazy = r.Lazy, r.Lazy
|
||||
r.Up.name, r.Down.name = uplinkPrefix(session), downlinkPrefix(session)
|
||||
deadline, _ := admit.Deadline() // acceptPending always supplies the announcement deadline
|
||||
if scoped, ok := slots.(interface {
|
||||
bindRing(context.Context, ring) error
|
||||
}); (ok && scoped.bindRing(admit, r) != nil) || admit.Err() != nil || !time.Now().Before(deadline) {
|
||||
onClose()
|
||||
return nil
|
||||
}
|
||||
errors.LogInfo(admit, "accepted session ", session, " in ", len(r.Down.Slots), " slots")
|
||||
return newSlotConn(l.ctx, slots, r.Down, r.Up, l.params, r.First, onClose)
|
||||
}
|
||||
onClose()
|
||||
return nil
|
||||
}
|
||||
errors.LogInfo(logCtx, "accepted session ", session)
|
||||
return newConn(l.ctx, storage, downlinkPrefix(session), uplinkPrefix(session), l.params, onClose)
|
||||
errors.LogInfo(admit, "accepted session ", session)
|
||||
return newConn(l.ctx, storage, downlinkPrefix(session), uplinkPrefix(session), l.params, true, onClose)
|
||||
}
|
||||
|
||||
func (l *Listener) collectLoop(logCtx context.Context) {
|
||||
@@ -480,7 +588,12 @@ func (l *Listener) collectLoop(logCtx context.Context) {
|
||||
}
|
||||
|
||||
func (l *Listener) collect() error {
|
||||
sessions, err := l.storage.List(l.ctx, streamsDir)
|
||||
if c, ok := l.storage.(interface{ cooling() bool }); ok && c.cooling() {
|
||||
return nil
|
||||
}
|
||||
ctx := context.WithValue(l.ctx, cleanupKey{}, true)
|
||||
ctx = context.WithValue(ctx, namesOnlyKey{}, true)
|
||||
sessions, err := l.storage.List(ctx, streamsDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -489,40 +602,70 @@ func (l *Listener) collect() error {
|
||||
var expired []string
|
||||
|
||||
l.mu.Lock()
|
||||
if l.collecting == nil {
|
||||
l.collecting = make(map[string]bool)
|
||||
}
|
||||
present := make(map[string]bool, len(sessions))
|
||||
for _, listed := range sessions {
|
||||
session := listed.Name
|
||||
if !safeSessionID(session) {
|
||||
// A listed stream name must never reach an object name.
|
||||
continue
|
||||
}
|
||||
present[session] = true
|
||||
if l.active[session] {
|
||||
delete(l.idleSince, session)
|
||||
continue
|
||||
}
|
||||
if l.collecting[session] || l.stopping {
|
||||
continue
|
||||
}
|
||||
since, seen := l.idleSince[session]
|
||||
if !seen {
|
||||
l.idleSince[session] = now
|
||||
continue
|
||||
}
|
||||
if now.Sub(since) >= l.sessionTTL {
|
||||
l.collecting[session] = true
|
||||
expired = append(expired, session)
|
||||
delete(l.idleSince, session)
|
||||
}
|
||||
}
|
||||
for session := range l.idleSince {
|
||||
if !present[session] {
|
||||
delete(l.idleSince, session)
|
||||
}
|
||||
}
|
||||
for session, at := range l.handled {
|
||||
if !l.active[session] && now.Sub(at) >= l.sessionTTL {
|
||||
delete(l.handled, session)
|
||||
maps.DeleteFunc(l.idleSince, func(id string, _ time.Time) bool { return !present[id] })
|
||||
announced := make(map[string]bool)
|
||||
for entry, seen := range l.lastSeen {
|
||||
if session, _, ok := parseAnnounce(entry); ok && now.Sub(seen) < 2*l.sessionTTL {
|
||||
announced[session] = true
|
||||
}
|
||||
}
|
||||
unused := func(id string) bool { return !l.active[id] && !l.collecting[id] && !announced[id] }
|
||||
maps.DeleteFunc(l.handled, func(id string, at time.Time) bool { return unused(id) && now.Sub(at) >= 2*l.sessionTTL })
|
||||
maps.DeleteFunc(l.announceWarned, func(id string, _ bool) bool { return unused(id) && l.handled[id].IsZero() })
|
||||
l.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
l.mu.Lock()
|
||||
for _, session := range expired {
|
||||
delete(l.collecting, session)
|
||||
}
|
||||
l.mu.Unlock()
|
||||
}()
|
||||
var first error
|
||||
for _, session := range expired {
|
||||
if err := l.storage.Delete(l.ctx, sessionPrefix(session)); err != nil && first == nil {
|
||||
first = err
|
||||
for i, session := range expired {
|
||||
if i > 0 && l.collectPause > 0 && sleepContext(l.ctx, l.collectPause) != nil {
|
||||
return l.ctx.Err()
|
||||
}
|
||||
if err := l.storage.Delete(ctx, sessionPrefix(session)); err != nil && err != errSessionInUse {
|
||||
if first == nil {
|
||||
first = err
|
||||
}
|
||||
} else if err == nil {
|
||||
l.mu.Lock()
|
||||
delete(l.idleSince, session)
|
||||
l.mu.Unlock()
|
||||
} else {
|
||||
l.mu.Lock()
|
||||
l.idleSince[session] = time.Now()
|
||||
l.mu.Unlock()
|
||||
}
|
||||
}
|
||||
return first
|
||||
@@ -533,6 +676,16 @@ func (l *Listener) Addr() net.Addr {
|
||||
}
|
||||
|
||||
func (l *Listener) Close() error {
|
||||
l.cancel()
|
||||
return l.storage.Close()
|
||||
l.closeOnce.Do(func() {
|
||||
l.mu.Lock()
|
||||
l.stopping = true
|
||||
l.mu.Unlock()
|
||||
if l.cancel != nil {
|
||||
l.cancel()
|
||||
}
|
||||
l.loopWG.Wait()
|
||||
l.cleanupWG.Wait()
|
||||
l.closeErr = l.storage.Close()
|
||||
})
|
||||
return l.closeErr
|
||||
}
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
// failPutStore is a slotStore whose Put always fails, to exercise the announce
|
||||
// failure path without any network.
|
||||
type failPutStore struct {
|
||||
*memSlots
|
||||
}
|
||||
|
||||
func (s *failPutStore) Put(ctx context.Context, name string, data []byte) error {
|
||||
return errors.New("put refused")
|
||||
}
|
||||
|
||||
func (s *failPutStore) Close() error { return nil }
|
||||
|
||||
func (s *failPutStore) Get(ctx context.Context, name string) ([]byte, error) {
|
||||
return nil, errNotFound
|
||||
}
|
||||
|
||||
func (s *failPutStore) List(ctx context.Context, prefix string) ([]Entry, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *failPutStore) Delete(ctx context.Context, name string) error { return nil }
|
||||
|
||||
func TestDialAnnounceFailureFailsRead(t *testing.T) {
|
||||
store := &failPutStore{memSlots: newMemSlots()}
|
||||
factory := func(*Config) (Storage, error) { return store, nil }
|
||||
testStorageFactory.Store(&factory)
|
||||
t.Cleanup(func() { testStorageFactory.Store(nil) })
|
||||
|
||||
settings := &internet.MemoryStreamConfig{
|
||||
ProtocolName: protocolName,
|
||||
ProtocolSettings: &Config{
|
||||
Service: "sim",
|
||||
RemoteFolder: "x",
|
||||
Secrets: []string{"a", "b", "c"},
|
||||
Concurrency: 4,
|
||||
FlushIntervalMs: 1,
|
||||
PollIntervalMs: 1,
|
||||
MaxPollIntervalMs: 5,
|
||||
SessionTtlSeconds: 60,
|
||||
},
|
||||
}
|
||||
conn, err := Dial(context.Background(), net.Destination{}, settings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
go conn.Write([]byte("hello"))
|
||||
|
||||
type result struct {
|
||||
n int
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
n, err := conn.Read(make([]byte, 16))
|
||||
done <- result{n, err}
|
||||
}()
|
||||
select {
|
||||
case r := <-done:
|
||||
if r.err == nil || !strings.Contains(r.err.Error(), "failed to announce") {
|
||||
t.Fatalf("Read returned %v, want the announce error", r.err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("Read blocked after the announcement failed")
|
||||
}
|
||||
|
||||
// The reader loop must have exited: it no longer polls the store.
|
||||
store.mu.Lock()
|
||||
before := store.reads
|
||||
store.mu.Unlock()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
store.mu.Lock()
|
||||
after := store.reads
|
||||
store.mu.Unlock()
|
||||
if after != before {
|
||||
t.Fatalf("reader kept polling after the announce failure: %d -> %d", before, after)
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
)
|
||||
|
||||
func announceEntry(name string) string {
|
||||
return strings.TrimPrefix(name, sessionsDir+"/")
|
||||
}
|
||||
|
||||
func TestAcceptPendingClientClockBehind(t *testing.T) {
|
||||
l := newTestListener(t, t.TempDir())
|
||||
var conns int
|
||||
l.addConn = func(c stat.Connection) { conns++; c.Close() }
|
||||
ctx := context.Background()
|
||||
|
||||
session := "clockbehind"
|
||||
ring := sessionPrefix(session) + "/" + uplinkDir + "/s0"
|
||||
if err := l.storage.Put(ctx, ring, []byte("x")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The client's clock is ten minutes behind the server's.
|
||||
name := announceName(session, time.Now().Add(-10*time.Minute))
|
||||
if err := l.storage.Put(ctx, name, []byte("{}")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accepted, err := l.acceptPending(ctx)
|
||||
if err != nil || !accepted {
|
||||
t.Fatalf("a slow client clock must not drop the session: accepted=%v err=%v", accepted, err)
|
||||
}
|
||||
if conns != 1 {
|
||||
t.Fatalf("addConn called %d times, want 1", conns)
|
||||
}
|
||||
if _, err := l.storage.Get(ctx, ring); err != nil {
|
||||
t.Fatalf("the ring of an accepted session was dropped: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptPendingStaleLeftoverProtectsActiveRing(t *testing.T) {
|
||||
l := newTestListener(t, t.TempDir())
|
||||
l.params.sessionTTL = 50 * time.Millisecond
|
||||
var conns int
|
||||
l.addConn = func(c stat.Connection) { conns++; c.Close() }
|
||||
ctx := context.Background()
|
||||
|
||||
session := "active"
|
||||
l.active[session] = true
|
||||
l.handled[session] = time.Now()
|
||||
ring := sessionPrefix(session) + "/" + uplinkDir + "/s0"
|
||||
if err := l.storage.Put(ctx, ring, []byte("x")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name := announceName(session, time.Now())
|
||||
if err := l.storage.Put(ctx, name, []byte("{}")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The listener first saw this leftover entry long ago on its own clock.
|
||||
l.firstSeen = map[string]time.Time{announceEntry(name): time.Now().Add(-time.Hour)}
|
||||
|
||||
accepted, err := l.acceptPending(ctx)
|
||||
if err != nil || accepted {
|
||||
t.Fatalf("a stale leftover must not be accepted: accepted=%v err=%v", accepted, err)
|
||||
}
|
||||
if conns != 0 {
|
||||
t.Fatalf("addConn called %d times, want 0", conns)
|
||||
}
|
||||
waitFor(t, "the leftover announcement file to drop", func() bool {
|
||||
_, err := l.storage.Get(ctx, name)
|
||||
return err == errNotFound
|
||||
})
|
||||
if _, err := l.storage.Get(ctx, ring); err != nil {
|
||||
t.Fatalf("the ring of an active session was dropped: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptPendingTrulyLeftoverDropped(t *testing.T) {
|
||||
l := newTestListener(t, t.TempDir())
|
||||
l.params.sessionTTL = 50 * time.Millisecond
|
||||
var conns int
|
||||
l.addConn = func(c stat.Connection) { conns++; c.Close() }
|
||||
ctx := context.Background()
|
||||
|
||||
session := "leftover"
|
||||
ring := sessionPrefix(session) + "/" + uplinkDir + "/s0"
|
||||
if err := l.storage.Put(ctx, ring, []byte("x")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name := announceName(session, time.Now())
|
||||
if err := l.storage.Put(ctx, name, []byte("{}")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.firstSeen = map[string]time.Time{announceEntry(name): time.Now().Add(-time.Hour)}
|
||||
|
||||
accepted, err := l.acceptPending(ctx)
|
||||
if err != nil || accepted {
|
||||
t.Fatalf("accepted=%v err=%v", accepted, err)
|
||||
}
|
||||
waitFor(t, "the leftover announcement and ring to drop", func() bool {
|
||||
_, e1 := l.storage.Get(ctx, name)
|
||||
_, e2 := l.storage.Get(ctx, ring)
|
||||
return e1 == errNotFound && e2 == errNotFound
|
||||
})
|
||||
}
|
||||
|
||||
func TestAcceptPendingPrunesFirstSeen(t *testing.T) {
|
||||
l := newTestListener(t, t.TempDir())
|
||||
l.addConn = func(c stat.Connection) { c.Close() }
|
||||
ctx := context.Background()
|
||||
l.firstSeen = map[string]time.Time{"gone-entry": time.Now()}
|
||||
if _, err := l.acceptPending(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, still := l.firstSeen["gone-entry"]; still {
|
||||
t.Fatal("firstSeen kept an entry that is no longer listed")
|
||||
}
|
||||
}
|
||||
@@ -1,984 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
gotls "crypto/tls"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
"github.com/xtls/xray-core/transport/internet/splithttp"
|
||||
"github.com/xtls/xray-core/transport/internet/stat"
|
||||
"github.com/xtls/xray-core/transport/internet/tls"
|
||||
)
|
||||
|
||||
const testPatience = 30 * time.Second
|
||||
|
||||
func settings(folder string) *internet.MemoryStreamConfig {
|
||||
return &internet.MemoryStreamConfig{
|
||||
ProtocolName: protocolName,
|
||||
ProtocolSettings: &Config{
|
||||
RemoteFolder: folder,
|
||||
Service: "local",
|
||||
FlushIntervalMs: 5,
|
||||
PollIntervalMs: 5,
|
||||
MaxPollIntervalMs: 20,
|
||||
SessionTtlSeconds: 5,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func pair(t *testing.T) (client, server stat.Connection, cleanup func()) {
|
||||
t.Helper()
|
||||
return pairWith(t, settings(t.TempDir()))
|
||||
}
|
||||
|
||||
func pairWith(t *testing.T, streamSettings *internet.MemoryStreamConfig) (client, server stat.Connection, cleanup func()) {
|
||||
t.Helper()
|
||||
|
||||
accepted := make(chan stat.Connection, 1)
|
||||
|
||||
listener, err := Serve(context.Background(), net.LocalHostIP, net.Port(0), streamSettings, func(conn stat.Connection) {
|
||||
accepted <- conn
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Serve: %v", err)
|
||||
}
|
||||
|
||||
client, err = Dial(context.Background(), net.Destination{}, streamSettings)
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
t.Fatalf("Dial: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case server = <-accepted:
|
||||
case <-time.After(testPatience):
|
||||
client.Close()
|
||||
listener.Close()
|
||||
t.Fatal("listener did not accept the session")
|
||||
}
|
||||
|
||||
return client, server, func() {
|
||||
if config, err := streamConfig(streamSettings); err == nil {
|
||||
box := spareBoxFor(config)
|
||||
box.stop.Store(true)
|
||||
for box.busy.Load() {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
client.Close()
|
||||
server.Close()
|
||||
listener.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func expectRead(t *testing.T, conn stat.Connection, want string) {
|
||||
t.Helper()
|
||||
|
||||
if err := conn.SetReadDeadline(time.Now().Add(testPatience)); err != nil {
|
||||
t.Fatalf("SetReadDeadline: %v", err)
|
||||
}
|
||||
buf := make([]byte, len(want))
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
t.Fatalf("ReadFull: %v", err)
|
||||
}
|
||||
if string(buf) != want {
|
||||
t.Fatalf("read %q, want %q", buf, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
client, server, cleanup := pair(t)
|
||||
defer cleanup()
|
||||
|
||||
if _, err := client.Write([]byte("ping")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
expectRead(t, server, "ping")
|
||||
|
||||
if _, err := server.Write([]byte("pong")); err != nil {
|
||||
t.Fatalf("server write: %v", err)
|
||||
}
|
||||
expectRead(t, client, "pong")
|
||||
}
|
||||
|
||||
func TestInterleaved(t *testing.T) {
|
||||
client, server, cleanup := pair(t)
|
||||
defer cleanup()
|
||||
|
||||
for i := 0; i < 20; i++ {
|
||||
if _, err := client.Write([]byte("up")); err != nil {
|
||||
t.Fatalf("client write %d: %v", i, err)
|
||||
}
|
||||
expectRead(t, server, "up")
|
||||
|
||||
if _, err := server.Write([]byte("down")); err != nil {
|
||||
t.Fatalf("server write %d: %v", i, err)
|
||||
}
|
||||
expectRead(t, client, "down")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiSegmentTransfer(t *testing.T) {
|
||||
client, server, cleanup := pair(t)
|
||||
defer cleanup()
|
||||
|
||||
payload := make([]byte, 3*defaultSegmentBytes+1234)
|
||||
if _, err := rand.Read(payload); err != nil {
|
||||
t.Fatalf("rand: %v", err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
client.Write(payload)
|
||||
}()
|
||||
|
||||
if err := server.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
t.Fatalf("SetReadDeadline: %v", err)
|
||||
}
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatalf("ReadFull: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("payload mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseEOF(t *testing.T) {
|
||||
client, server, cleanup := pair(t)
|
||||
defer cleanup()
|
||||
|
||||
if _, err := client.Write([]byte("bye")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
if err := client.Close(); err != nil {
|
||||
t.Fatalf("client close: %v", err)
|
||||
}
|
||||
|
||||
if err := server.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
t.Fatalf("SetReadDeadline: %v", err)
|
||||
}
|
||||
got, err := io.ReadAll(server)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll: %v", err)
|
||||
}
|
||||
if string(got) != "bye" {
|
||||
t.Fatalf("read %q, want %q", got, "bye")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadDeadline(t *testing.T) {
|
||||
client, _, cleanup := pair(t)
|
||||
defer cleanup()
|
||||
|
||||
if err := client.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil {
|
||||
t.Fatalf("SetReadDeadline: %v", err)
|
||||
}
|
||||
buf := make([]byte, 4)
|
||||
if _, err := client.Read(buf); !os.IsTimeout(err) {
|
||||
t.Fatalf("Read returned %v, want a timeout", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalNameEscape(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
storage, err := newLocalStorage(root)
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
|
||||
if err := storage.Put(context.Background(), "../escaped", []byte("x")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(root + "/escaped"); err != nil {
|
||||
t.Fatalf("name was not clamped inside the root: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalMissingObject(t *testing.T) {
|
||||
storage, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
|
||||
if _, err := storage.Get(context.Background(), "nothing/here"); err != errNotFound {
|
||||
t.Fatalf("Get returned %v, want errNotFound", err)
|
||||
}
|
||||
names, err := storage.List(context.Background(), "nothing")
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if len(names) != 0 {
|
||||
t.Fatalf("List returned %v, want none", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeAfterIdle(t *testing.T) {
|
||||
client, server, cleanup := pair(t)
|
||||
defer cleanup()
|
||||
|
||||
if _, err := client.Write([]byte("first")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
expectRead(t, server, "first")
|
||||
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
if _, err := client.Write([]byte("second")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
expectRead(t, server, "second")
|
||||
}
|
||||
|
||||
func TestParseEntry(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
seq int64
|
||||
ok bool
|
||||
}{
|
||||
{"000000000.seg", 0, true},
|
||||
{"000000042.seg", 42, true},
|
||||
{"000000007.end", 7, true},
|
||||
{"000000001.tmp", 0, false},
|
||||
{"notanumber.seg", 0, false},
|
||||
{"000000001", 0, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
seq, ok := parseEntry(c.name)
|
||||
if ok != c.ok || (ok && seq != c.seq) {
|
||||
t.Fatalf("parseEntry(%q) = %d, %v; want %d, %v", c.name, seq, ok, c.seq, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParamDefaults(t *testing.T) {
|
||||
p := paramsFromConfig(&Config{})
|
||||
if p.segmentBytes != defaultSegmentBytes || p.flushInterval != defaultFlushInterval {
|
||||
t.Fatalf("defaults not applied: %+v", p)
|
||||
}
|
||||
|
||||
p = paramsFromConfig(&Config{SegmentBytes: 1 << 30, PollIntervalMs: 400, MaxPollIntervalMs: 100})
|
||||
if p.segmentBytes != maxSegmentBytes {
|
||||
t.Fatalf("segmentBytes is %d, want %d", p.segmentBytes, maxSegmentBytes)
|
||||
}
|
||||
if p.maxPollInterval < p.minPollInterval {
|
||||
t.Fatalf("maxPollInterval %v below minPollInterval %v", p.maxPollInterval, p.minPollInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, what string, done func() bool) {
|
||||
t.Helper()
|
||||
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if done() {
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("timed out waiting for %s", what)
|
||||
}
|
||||
|
||||
func newTestListener(t *testing.T, folder string) *Listener {
|
||||
t.Helper()
|
||||
|
||||
storage, err := newLocalStorage(folder)
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
return &Listener{
|
||||
ctx: context.Background(),
|
||||
storage: storage,
|
||||
params: paramsFromConfig(&Config{SessionTtlSeconds: 1}),
|
||||
active: make(map[string]bool),
|
||||
handled: make(map[string]time.Time),
|
||||
idleSince: make(map[string]time.Time),
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectAbandoned(t *testing.T) {
|
||||
folder := t.TempDir()
|
||||
listener := newTestListener(t, folder)
|
||||
|
||||
if err := listener.storage.Put(context.Background(), uplinkPrefix("dead")+"/000000000.seg", []byte("x")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
if err := listener.collect(); err != nil {
|
||||
t.Fatalf("collect: %v", err)
|
||||
}
|
||||
names, _ := listener.storage.List(context.Background(), streamsDir)
|
||||
if len(names) != 1 {
|
||||
t.Fatalf("first pass removed the session, got %v", names)
|
||||
}
|
||||
|
||||
listener.idleSince["dead"] = time.Now().Add(-2 * time.Second)
|
||||
if err := listener.collect(); err != nil {
|
||||
t.Fatalf("collect: %v", err)
|
||||
}
|
||||
names, _ = listener.storage.List(context.Background(), streamsDir)
|
||||
if len(names) != 0 {
|
||||
t.Fatalf("abandoned session still there, got %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectKeepsActive(t *testing.T) {
|
||||
folder := t.TempDir()
|
||||
listener := newTestListener(t, folder)
|
||||
listener.active["live"] = true
|
||||
|
||||
if err := listener.storage.Put(context.Background(), uplinkPrefix("live")+"/000000000.seg", []byte("x")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
listener.idleSince["live"] = time.Now().Add(-2 * time.Second)
|
||||
if err := listener.collect(); err != nil {
|
||||
t.Fatalf("collect: %v", err)
|
||||
}
|
||||
names, _ := listener.storage.List(context.Background(), streamsDir)
|
||||
if len(names) != 1 {
|
||||
t.Fatalf("collected an active session, got %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAnnounce(t *testing.T) {
|
||||
session, at, ok := parseAnnounce("1757000000123456789-abc123")
|
||||
if !ok || session != "abc123" || at.UnixNano() != 1757000000123456789 {
|
||||
t.Fatalf("parseAnnounce returned %q, %v, %v", session, at.UnixNano(), ok)
|
||||
}
|
||||
for _, bad := range []string{"abc123", "-abc123", "1757000000-", "notanumber-abc"} {
|
||||
if _, _, ok := parseAnnounce(bad); ok {
|
||||
t.Fatalf("parseAnnounce accepted %q", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleAnnounce(t *testing.T) {
|
||||
folder := t.TempDir()
|
||||
listener := newTestListener(t, folder)
|
||||
|
||||
ctx := context.Background()
|
||||
stale := announceName("ghost", time.Now().Add(-time.Hour))
|
||||
if err := listener.storage.Put(ctx, stale, nil); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
if err := listener.storage.Put(ctx, uplinkPrefix("ghost")+"/000000000.seg", []byte("x")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
// The listener first saw this entry an hour ago on its own clock.
|
||||
listener.firstSeen = map[string]time.Time{
|
||||
strings.TrimPrefix(stale, sessionsDir+"/"): time.Now().Add(-time.Hour),
|
||||
}
|
||||
|
||||
accepted, err := listener.acceptPending(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("acceptPending: %v", err)
|
||||
}
|
||||
if accepted {
|
||||
t.Fatal("accepted a stale announcement")
|
||||
}
|
||||
|
||||
waitFor(t, "the stale announcement to be removed", func() bool {
|
||||
names, _ := listener.storage.List(ctx, sessionsDir)
|
||||
return len(names) == 0
|
||||
})
|
||||
waitFor(t, "the stale session data to be removed", func() bool {
|
||||
names, _ := listener.storage.List(ctx, streamsDir)
|
||||
return len(names) == 0
|
||||
})
|
||||
}
|
||||
|
||||
func TestFreshAnnounce(t *testing.T) {
|
||||
folder := t.TempDir()
|
||||
listener := newTestListener(t, folder)
|
||||
listener.addConn = func(conn stat.Connection) { conn.Close() }
|
||||
|
||||
ctx := context.Background()
|
||||
if err := listener.storage.Put(ctx, announceName("fresh", time.Now()), nil); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
accepted, err := listener.acceptPending(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("acceptPending: %v", err)
|
||||
}
|
||||
if !accepted {
|
||||
t.Fatal("did not accept a fresh announcement")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnouncePrecision(t *testing.T) {
|
||||
at := time.Unix(1757000000, int64(900*time.Millisecond))
|
||||
entry := strings.TrimPrefix(announceName("abc123", at), sessionsDir+"/")
|
||||
|
||||
session, parsed, ok := parseAnnounce(entry)
|
||||
if !ok || session != "abc123" {
|
||||
t.Fatalf("parseAnnounce(%q) returned %q, %v", entry, session, ok)
|
||||
}
|
||||
if !parsed.Equal(at) {
|
||||
t.Fatalf("timestamp came back as %v, want %v", parsed, at)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecentAnnounceTTL(t *testing.T) {
|
||||
folder := t.TempDir()
|
||||
listener := newTestListener(t, folder)
|
||||
listener.addConn = func(conn stat.Connection) { conn.Close() }
|
||||
|
||||
ctx := context.Background()
|
||||
recent := time.Now().Add(-900 * time.Millisecond)
|
||||
if err := listener.storage.Put(ctx, announceName("recent", recent), nil); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
accepted, err := listener.acceptPending(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("acceptPending: %v", err)
|
||||
}
|
||||
if !accepted {
|
||||
t.Fatal("dropped an announcement younger than the TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingSegment(t *testing.T) {
|
||||
storage, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
p := paramsFromConfig(&Config{PollIntervalMs: 5, MaxPollIntervalMs: 20, HoleTimeoutMs: 200})
|
||||
if err := storage.Put(ctx, objectName("hole", 1, segSuffix), []byte("second")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
reader := newWALReader(ctx, storage, "hole", p)
|
||||
select {
|
||||
case _, ok := <-reader.ch:
|
||||
if ok {
|
||||
t.Fatal("delivered data past a missing segment")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("reader did not give up on a missing segment")
|
||||
}
|
||||
|
||||
err = reader.Err()
|
||||
if err == nil || err == io.EOF {
|
||||
t.Fatalf("Err returned %v, want a failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdleStreamWaits(t *testing.T) {
|
||||
storage, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
p := paramsFromConfig(&Config{PollIntervalMs: 5, MaxPollIntervalMs: 20, HoleTimeoutMs: 100})
|
||||
reader := newWALReader(ctx, storage, "idle", p)
|
||||
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
if err := storage.Put(ctx, objectName("idle", 0, segSuffix), []byte("late")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case data, ok := <-reader.ch:
|
||||
if !ok {
|
||||
t.Fatalf("the reader gave up on an idle stream: %v", reader.Err())
|
||||
}
|
||||
if string(data) != "late" {
|
||||
t.Fatalf("read %q, want %q", data, "late")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("reader missed a late segment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailureMarker(t *testing.T) {
|
||||
storage, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
p := paramsFromConfig(&Config{PollIntervalMs: 5, MaxPollIntervalMs: 20})
|
||||
if err := storage.Put(ctx, objectName("broken", 0, segSuffix), []byte("first")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
if err := storage.Put(ctx, objectName("broken", 1, errSuffix), nil); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
|
||||
reader := newWALReader(ctx, storage, "broken", p)
|
||||
|
||||
select {
|
||||
case data, ok := <-reader.ch:
|
||||
if !ok || string(data) != "first" {
|
||||
t.Fatalf("want the segment before the marker, got %q %v", data, ok)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("reader did not deliver the first segment")
|
||||
}
|
||||
|
||||
select {
|
||||
case _, ok := <-reader.ch:
|
||||
if ok {
|
||||
t.Fatal("delivered data past the failure marker")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("reader did not stop on the failure marker")
|
||||
}
|
||||
|
||||
if err := reader.Err(); err == nil || err == io.EOF {
|
||||
t.Fatalf("Err returned %v, want a failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
type inlineOnlyStorage struct {
|
||||
Storage
|
||||
gets int64
|
||||
}
|
||||
|
||||
func (s *inlineOnlyStorage) List(ctx context.Context, prefix string) ([]Entry, error) {
|
||||
return []Entry{{Name: "000000000" + segSuffix, Inline: []byte("carried by the listing")}}, nil
|
||||
}
|
||||
|
||||
func (s *inlineOnlyStorage) Get(ctx context.Context, name string) ([]byte, error) {
|
||||
atomic.AddInt64(&s.gets, 1)
|
||||
return nil, errNotFound
|
||||
}
|
||||
|
||||
func (s *inlineOnlyStorage) Delete(ctx context.Context, name string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestInlinePayload(t *testing.T) {
|
||||
base, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
storage := &inlineOnlyStorage{Storage: base}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
reader := newWALReader(ctx, storage, "inline", paramsFromConfig(&Config{PollIntervalMs: 5}))
|
||||
select {
|
||||
case data, ok := <-reader.ch:
|
||||
if !ok {
|
||||
t.Fatalf("reader stopped: %v", reader.Err())
|
||||
}
|
||||
if string(data) != "carried by the listing" {
|
||||
t.Fatalf("read %q, want the inline payload", data)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("reader did not deliver the inline payload")
|
||||
}
|
||||
|
||||
if got := atomic.LoadInt64(&storage.gets); got != 0 {
|
||||
t.Fatalf("called Get %d times for an inline payload", got)
|
||||
}
|
||||
}
|
||||
|
||||
// runSessions opens n sessions at once, both ends in this process, passes data
|
||||
// both ways over each and closes them
|
||||
func runSessions(t *testing.T, streamSettings *internet.MemoryStreamConfig, n int) {
|
||||
t.Helper()
|
||||
|
||||
accepted := make(chan stat.Connection, 1)
|
||||
listener, err := Serve(context.Background(), net.LocalHostIP, net.Port(0), streamSettings, func(conn stat.Connection) {
|
||||
accepted <- conn
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Serve: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
var ends []stat.Connection
|
||||
defer func() {
|
||||
for _, end := range ends {
|
||||
end.Close()
|
||||
}
|
||||
}()
|
||||
for range n {
|
||||
client, err := Dial(context.Background(), net.Destination{}, streamSettings)
|
||||
if err != nil {
|
||||
t.Fatalf("Dial: %v", err)
|
||||
}
|
||||
ends = append(ends, client)
|
||||
select {
|
||||
case peer := <-accepted:
|
||||
ends = append(ends, peer)
|
||||
case <-time.After(testPatience):
|
||||
t.Fatal("listener did not accept the session")
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(ends); i += 2 {
|
||||
if _, err := ends[i].Write([]byte("ping")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
expectRead(t, ends[i+1], "ping")
|
||||
if _, err := ends[i+1].Write([]byte("pong")); err != nil {
|
||||
t.Fatalf("server write: %v", err)
|
||||
}
|
||||
expectRead(t, ends[i], "pong")
|
||||
}
|
||||
}
|
||||
|
||||
// sessionEnd is the session and end of it that a request to the fake store
|
||||
// comes from, or "" for the listener and the token
|
||||
func sessionEnd(r *http.Request) string {
|
||||
name := strings.TrimPrefix(r.URL.Path, "/folder/")
|
||||
if r.Method == "PROPFIND" {
|
||||
name = r.URL.Query().Get("prefix")
|
||||
}
|
||||
write := r.Method == http.MethodPut
|
||||
parts := strings.Split(name, flatSeparator)
|
||||
switch {
|
||||
case len(parts) > 2 && parts[0] == streamsDir:
|
||||
// each end writes its own direction and reads the other
|
||||
if (parts[2] == uplinkDir) == write {
|
||||
return parts[1] + " client"
|
||||
}
|
||||
return parts[1] + " server"
|
||||
case len(parts) == 2 && parts[0] == sessionsDir && write:
|
||||
_, session, _ := strings.Cut(parts[1], "-")
|
||||
return session + " client"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// with "maxConcurrency" 1 every end of a session has a connection of its own,
|
||||
// with "maxConnections" the ends share that many, and the sessions after them
|
||||
// take the same ones again. The listener and the token use none of them, and
|
||||
// the sessions get the token once
|
||||
func TestXmuxConnections(t *testing.T) {
|
||||
const n = 3
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
xmux *splithttp.XmuxConfig
|
||||
conns int
|
||||
shared bool
|
||||
}{
|
||||
{"maxConcurrency", &splithttp.XmuxConfig{MaxConcurrency: &splithttp.RangeConfig{From: 1, To: 1}}, 2 * n, false},
|
||||
{"maxConnections", &splithttp.XmuxConfig{MaxConnections: &splithttp.RangeConfig{From: 2, To: 2}}, 2, true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
resetSharedStorage()
|
||||
t.Cleanup(resetSharedStorage)
|
||||
|
||||
store := &fakeStore{objects: make(map[string][]byte), needAuth: "Bearer tok-fake"}
|
||||
var (
|
||||
mu sync.Mutex
|
||||
conns = make(map[string]map[string]bool)
|
||||
)
|
||||
server := newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, func(w http.ResponseWriter, r *http.Request) {
|
||||
end := sessionEnd(r)
|
||||
mu.Lock()
|
||||
if conns[end] == nil {
|
||||
conns[end] = make(map[string]bool)
|
||||
}
|
||||
conns[end][r.RemoteAddr] = true
|
||||
mu.Unlock()
|
||||
store.handle(w, r)
|
||||
})
|
||||
store.server = server.Server
|
||||
settings := templateSettings(store, map[string]interface{}{
|
||||
"type": "oauth2",
|
||||
"tokenUrl": server.URL + "/token",
|
||||
"form": map[string]interface{}{"grant_type": "refresh_token", "refresh_token": "{secret0}"},
|
||||
"header": map[string]interface{}{"Authorization": "Bearer {token}"},
|
||||
}, []string{"refresh"})
|
||||
settings.SecuritySettings = server.settings(&tls.Config{}).SecuritySettings
|
||||
settings.ProtocolSettings.(*Config).Xmux = c.xmux
|
||||
|
||||
runSessions(t, settings, n)
|
||||
mu.Lock()
|
||||
first := conns
|
||||
conns = make(map[string]map[string]bool)
|
||||
mu.Unlock()
|
||||
dialed := server.conns.Load()
|
||||
runSessions(t, settings, n)
|
||||
if got := server.conns.Load(); got != dialed {
|
||||
t.Errorf("the next %d sessions dialed %d connections", n, got-dialed)
|
||||
}
|
||||
|
||||
owner := make(map[string]string)
|
||||
for end, addrs := range first {
|
||||
if end == "" {
|
||||
continue
|
||||
}
|
||||
if len(addrs) != 1 {
|
||||
t.Errorf("%s used %d connections", end, len(addrs))
|
||||
}
|
||||
for addr := range addrs {
|
||||
if owner[addr] != "" && !c.shared {
|
||||
t.Errorf("%s and %s shared a connection", end, owner[addr])
|
||||
}
|
||||
owner[addr] = end
|
||||
}
|
||||
}
|
||||
if len(owner) != c.conns {
|
||||
t.Errorf("%d sessions had %d connections, want %d", 2*n, len(owner), c.conns)
|
||||
}
|
||||
for addr := range first[""] {
|
||||
if owner[addr] != "" {
|
||||
t.Errorf("the listener or the token went over the connection of %s", owner[addr])
|
||||
}
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
if store.tokens != 1 {
|
||||
t.Errorf("the sessions got the token %d times", store.tokens)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriveXmuxConnections(t *testing.T) {
|
||||
drive := newFakeDrive(t)
|
||||
server := newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, drive.server.Config.Handler.ServeHTTP)
|
||||
driveTokenURL = server.URL + "/token"
|
||||
driveFilesURL = server.URL + "/files"
|
||||
driveUploadURL = server.URL + "/upload"
|
||||
settings := driveSettings()
|
||||
settings.SecuritySettings = server.settings(&tls.Config{}).SecuritySettings
|
||||
settings.ProtocolSettings.(*Config).Xmux = &splithttp.XmuxConfig{MaxConnections: &splithttp.RangeConfig{From: 3, To: 3}}
|
||||
|
||||
runSessions(t, settings, 3)
|
||||
if got := server.conns.Load(); got != 4 {
|
||||
t.Errorf("6 ends of sessions with 3 connections and the listener took %d connections", got)
|
||||
}
|
||||
|
||||
drive.mu.Lock()
|
||||
defer drive.mu.Unlock()
|
||||
if drive.tokens != 1 {
|
||||
t.Errorf("6 ends of sessions got the token %d times", drive.tokens)
|
||||
}
|
||||
}
|
||||
|
||||
// a session knows the hosts that answered the storage over h1, the polling of
|
||||
// the listener for one, so it sends requests in a row over one connection, not
|
||||
// first over one for h2 that then stays idle, and parallel ones over more
|
||||
func TestSessionKnowsHTTP1Hosts(t *testing.T) {
|
||||
check := func(name string, server *tlsServer, storage Storage) {
|
||||
put := func(s Storage, names ...string) {
|
||||
for _, n := range names {
|
||||
if err := s.Put(context.Background(), "streams/abc/c2s/"+n, []byte("x")); err != nil {
|
||||
t.Errorf("%s: Put: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
put(storage, "a", "b")
|
||||
before := server.conns.Load()
|
||||
session := sessionStorage(storage)
|
||||
defer session.Close()
|
||||
put(session, "c", "d")
|
||||
if n := server.conns.Load() - before; n != 1 {
|
||||
t.Errorf("%s: 2 requests in a row of a session over h1 took %d connections", name, n)
|
||||
}
|
||||
|
||||
before = server.conns.Load()
|
||||
var wg sync.WaitGroup
|
||||
for _, n := range []string{"e", "f", "g", "h"} {
|
||||
wg.Go(func() { put(session, n) })
|
||||
}
|
||||
wg.Wait()
|
||||
if server.conns.Load() == before {
|
||||
t.Errorf("%s: 4 parallel requests of a session over h1 took one connection", name)
|
||||
}
|
||||
}
|
||||
slow := func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
store := &fakeStore{objects: make(map[string][]byte)}
|
||||
server := newTLSServer(t, &gotls.Config{NextProtos: []string{"http/1.1"}}, slow(store.handle))
|
||||
store.server = server.Server
|
||||
settings := templateSettings(store, map[string]interface{}{"type": "none"}, nil)
|
||||
settings.SecuritySettings = server.settings(&tls.Config{}).SecuritySettings
|
||||
template, err := newTemplateStorage(settings, settings.ProtocolSettings.(*Config))
|
||||
if err != nil {
|
||||
t.Fatalf("newTemplateStorage: %v", err)
|
||||
}
|
||||
check("template", server, template)
|
||||
|
||||
drive := newFakeDrive(t)
|
||||
server = newTLSServer(t, &gotls.Config{NextProtos: []string{"http/1.1"}}, slow(drive.server.Config.Handler.ServeHTTP))
|
||||
driveTokenURL = server.URL + "/token"
|
||||
driveFilesURL = server.URL + "/files"
|
||||
settings = driveSettings()
|
||||
settings.SecuritySettings = server.settings(&tls.Config{}).SecuritySettings
|
||||
google, err := newDriveStorage(settings, settings.ProtocolSettings.(*Config))
|
||||
if err != nil {
|
||||
t.Fatalf("newDriveStorage: %v", err)
|
||||
}
|
||||
check("drive", server, google)
|
||||
}
|
||||
|
||||
// with "hMaxRequestTimes" a session moves on to a new connection after that
|
||||
// many requests, and the old one closes once the requests on it end, not before
|
||||
func TestXmuxRequestLimit(t *testing.T) {
|
||||
store := &fakeStore{objects: make(map[string][]byte)}
|
||||
arrived := make(chan struct{}, 1)
|
||||
release := make(chan struct{})
|
||||
server := newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
arrived <- struct{}{}
|
||||
<-release
|
||||
}
|
||||
store.handle(w, r)
|
||||
})
|
||||
store.server = server.Server
|
||||
settings := templateSettings(store, map[string]interface{}{"type": "none"}, nil)
|
||||
settings.SecuritySettings = server.settings(&tls.Config{}).SecuritySettings
|
||||
settings.ProtocolSettings.(*Config).Xmux = &splithttp.XmuxConfig{HMaxRequestTimes: &splithttp.RangeConfig{From: 3, To: 3}}
|
||||
storage, err := newTemplateStorage(settings, settings.ProtocolSettings.(*Config))
|
||||
if err != nil {
|
||||
t.Fatalf("newTemplateStorage: %v", err)
|
||||
}
|
||||
session := sessionStorage(storage)
|
||||
defer session.Close()
|
||||
put := func(names ...string) {
|
||||
for _, name := range names {
|
||||
if err := session.Put(context.Background(), "streams/abc/c2s/"+name, []byte("x")); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
put("a")
|
||||
got := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := session.Get(context.Background(), "streams/abc/c2s/a")
|
||||
got <- err
|
||||
}()
|
||||
<-arrived
|
||||
put("b", "c")
|
||||
if n := server.conns.Load(); n != 2 {
|
||||
t.Errorf("4 requests with 3 to a connection took %d connections", n)
|
||||
}
|
||||
if server.closed.Load() != 0 {
|
||||
t.Error("the first connection closed under a request")
|
||||
}
|
||||
close(release)
|
||||
if err := <-got; err != nil {
|
||||
t.Errorf("Get on the first connection: %v", err)
|
||||
}
|
||||
waitFor(t, "the first connection to close", func() bool { return server.closed.Load() == 1 })
|
||||
|
||||
put("d", "e", "f")
|
||||
if n := server.conns.Load(); n != 3 {
|
||||
t.Errorf("7 requests with 3 to a connection took %d connections", n)
|
||||
}
|
||||
waitFor(t, "the second connection to close", func() bool { return server.closed.Load() == 2 })
|
||||
}
|
||||
|
||||
// a session that fails to announce itself lets go of its connection, which the
|
||||
// next one takes with "maxConcurrency" 1
|
||||
func TestFailedDialReleasesConnection(t *testing.T) {
|
||||
resetSharedStorage()
|
||||
t.Cleanup(resetSharedStorage)
|
||||
|
||||
store := &fakeStore{objects: make(map[string][]byte)}
|
||||
var refuse atomic.Bool
|
||||
refuse.Store(true)
|
||||
server := newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, func(w http.ResponseWriter, r *http.Request) {
|
||||
if refuse.Load() {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
store.handle(w, r)
|
||||
})
|
||||
store.server = server.Server
|
||||
settings := templateSettings(store, map[string]interface{}{"type": "none"}, nil)
|
||||
settings.SecuritySettings = server.settings(&tls.Config{}).SecuritySettings
|
||||
settings.ProtocolSettings.(*Config).Xmux = &splithttp.XmuxConfig{MaxConcurrency: &splithttp.RangeConfig{From: 1, To: 1}}
|
||||
|
||||
if _, err := Dial(context.Background(), net.Destination{}, settings); err == nil {
|
||||
t.Fatal("Dial announced a session that the service refused")
|
||||
}
|
||||
refuse.Store(false)
|
||||
conn, err := Dial(context.Background(), net.Destination{}, settings)
|
||||
if err != nil {
|
||||
t.Fatalf("Dial: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if n := server.conns.Load(); n != 1 {
|
||||
t.Errorf("a failed Dial and the next took %d connections", n)
|
||||
}
|
||||
}
|
||||
|
||||
// a session gets the token over a connection of the storage, not over one of
|
||||
// XMUX
|
||||
func TestSessionTokenConnection(t *testing.T) {
|
||||
check := func(name string, server *tlsServer, storage Storage) {
|
||||
session := sessionStorage(storage)
|
||||
defer session.Close()
|
||||
if err := session.Put(context.Background(), "sessions/abc", nil); err != nil {
|
||||
t.Fatalf("%s: Put: %v", name, err)
|
||||
}
|
||||
if n := server.conns.Load(); n != 2 {
|
||||
t.Errorf("%s: the token and a Put of a session took %d connections, want 2", name, n)
|
||||
}
|
||||
}
|
||||
|
||||
store := &fakeStore{objects: make(map[string][]byte), needAuth: "Bearer tok-fake"}
|
||||
server := newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, store.handle)
|
||||
store.server = server.Server
|
||||
settings := templateSettings(store, map[string]interface{}{
|
||||
"type": "oauth2",
|
||||
"tokenUrl": server.URL + "/token",
|
||||
"header": map[string]interface{}{"Authorization": "Bearer {token}"},
|
||||
}, nil)
|
||||
settings.SecuritySettings = server.settings(&tls.Config{}).SecuritySettings
|
||||
template, err := newTemplateStorage(settings, settings.ProtocolSettings.(*Config))
|
||||
if err != nil {
|
||||
t.Fatalf("newTemplateStorage: %v", err)
|
||||
}
|
||||
check("template", server, template)
|
||||
|
||||
drive := newFakeDrive(t)
|
||||
server = newTLSServer(t, &gotls.Config{NextProtos: chromeALPN}, drive.server.Config.Handler.ServeHTTP)
|
||||
driveTokenURL = server.URL + "/token"
|
||||
driveFilesURL = server.URL + "/files"
|
||||
settings = driveSettings()
|
||||
settings.SecuritySettings = server.settings(&tls.Config{}).SecuritySettings
|
||||
google, err := newDriveStorage(settings, settings.ProtocolSettings.(*Config))
|
||||
if err != nil {
|
||||
t.Fatalf("newDriveStorage: %v", err)
|
||||
}
|
||||
check("drive", server, google)
|
||||
}
|
||||
|
||||
// local storage has no connections to keep apart
|
||||
func TestLocalSessionStorage(t *testing.T) {
|
||||
storage, err := newLocalStorage(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("newLocalStorage: %v", err)
|
||||
}
|
||||
if sessionStorage(storage) != Storage(storage) {
|
||||
t.Fatal("a session of local storage got a storage of its own")
|
||||
}
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package xdrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/transport/internet"
|
||||
)
|
||||
|
||||
const yandexBase = "https://webdav.yandex.ru"
|
||||
|
||||
func envUint(name string, def uint32) uint32 {
|
||||
if v := os.Getenv(name); v != "" {
|
||||
var n uint32
|
||||
fmt.Sscanf(v, "%d", &n)
|
||||
if n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func liveYandexSettings(t *testing.T) (*internet.MemoryStreamConfig, string, func()) {
|
||||
t.Helper()
|
||||
|
||||
user := os.Getenv("XDRIVE_YANDEX_USER")
|
||||
pass := os.Getenv("XDRIVE_YANDEX_PASS")
|
||||
if user == "" || pass == "" {
|
||||
t.Skip("set XDRIVE_YANDEX_USER and XDRIVE_YANDEX_PASS to run this test")
|
||||
}
|
||||
|
||||
folder := fmt.Sprintf("xdrive-live-%d", time.Now().UnixNano())
|
||||
dav := func(method, path string) int {
|
||||
req, _ := http.NewRequest(method, yandexBase+path, nil)
|
||||
req.SetBasicAuth(user, pass)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("%s %s: %v", method, path, err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
if code := dav("MKCOL", "/"+folder); code != 201 && code != 405 {
|
||||
t.Fatalf("MKCOL answered %d", code)
|
||||
}
|
||||
|
||||
tmpl := map[string]interface{}{
|
||||
"flatten": true,
|
||||
"auth": map[string]interface{}{"type": "basic", "username": "{secret0}", "password": "{secret1}"},
|
||||
"put": map[string]interface{}{"method": "PUT", "url": yandexBase + "/{folder}/{name}"},
|
||||
"get": map[string]interface{}{"method": "GET", "url": yandexBase + "/{folder}/{name}"},
|
||||
"delete": map[string]interface{}{"method": "DELETE", "url": yandexBase + "/{folder}/{name}"},
|
||||
"list": map[string]interface{}{
|
||||
"method": "PROPFIND", "url": yandexBase + "/{folder}/",
|
||||
"headers": map[string]interface{}{"Depth": "1"}, "namesRegex": `<d:href>[^<]*/([^/<]+)</d:href>`,
|
||||
},
|
||||
"retry": map[string]interface{}{"status": []int{429, 500, 502, 503}},
|
||||
}
|
||||
raw, _ := json.Marshal(tmpl)
|
||||
settings := &internet.MemoryStreamConfig{
|
||||
ProtocolName: protocolName,
|
||||
ProtocolSettings: &Config{
|
||||
RemoteFolder: folder,
|
||||
Service: "template",
|
||||
Secrets: []string{user, pass},
|
||||
Template: string(raw),
|
||||
SegmentBytes: 262144,
|
||||
FlushIntervalMs: 100,
|
||||
PollIntervalMs: 300,
|
||||
MaxPollIntervalMs: 1500,
|
||||
SessionTtlSeconds: 120,
|
||||
Concurrency: envUint("XDRIVE_LIVE_CONCURRENCY", 8),
|
||||
},
|
||||
}
|
||||
cleanup := func() { dav("DELETE", "/"+folder) }
|
||||
return settings, folder, cleanup
|
||||
}
|
||||
|
||||
func TestLiveYandexStorage(t *testing.T) {
|
||||
settings, _, cleanup := liveYandexSettings(t)
|
||||
defer cleanup()
|
||||
|
||||
storage, err := newTemplateStorage(settings, settings.ProtocolSettings.(*Config))
|
||||
if err != nil {
|
||||
t.Fatalf("newTemplateStorage: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
name := "streams/live/c2s/000000000.seg"
|
||||
payload := []byte("xdrive over real yandex webdav")
|
||||
|
||||
start := time.Now()
|
||||
if err := storage.Put(ctx, name, payload); err != nil {
|
||||
t.Fatalf("Put: %v", err)
|
||||
}
|
||||
t.Logf("Put took %v", time.Since(start))
|
||||
|
||||
start = time.Now()
|
||||
names, err := storage.List(ctx, "streams/live/c2s")
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
t.Logf("List took %v", time.Since(start))
|
||||
if len(names) != 1 || names[0].Name != "000000000.seg" {
|
||||
t.Fatalf("List returned %v, want one segment", names)
|
||||
}
|
||||
|
||||
start = time.Now()
|
||||
got, err := storage.Get(ctx, name)
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
t.Logf("Get took %v", time.Since(start))
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("Get returned %q", got)
|
||||
}
|
||||
|
||||
if _, err := storage.Get(ctx, "streams/live/c2s/000000009.seg"); err != errNotFound {
|
||||
t.Fatalf("Get of a missing object returned %v, want errNotFound", err)
|
||||
}
|
||||
|
||||
if err := storage.Delete(ctx, name); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveYandexTransport(t *testing.T) {
|
||||
settings, _, cleanup := liveYandexSettings(t)
|
||||
defer cleanup()
|
||||
|
||||
client, server, done := pairWith(t, settings)
|
||||
defer done()
|
||||
|
||||
start := time.Now()
|
||||
if _, err := client.Write([]byte("ping")); err != nil {
|
||||
t.Fatalf("client write: %v", err)
|
||||
}
|
||||
expectRead(t, server, "ping")
|
||||
t.Logf("client to server round took %v", time.Since(start))
|
||||
|
||||
size := 1000000
|
||||
if raw := os.Getenv("XDRIVE_LIVE_BYTES"); raw != "" {
|
||||
fmt.Sscanf(raw, "%d", &size)
|
||||
}
|
||||
payload := make([]byte, size)
|
||||
rand.Read(payload)
|
||||
|
||||
start = time.Now()
|
||||
go func() { client.Write(payload) }()
|
||||
if err := server.SetReadDeadline(time.Now().Add(5 * time.Minute)); err != nil {
|
||||
t.Fatalf("SetReadDeadline: %v", err)
|
||||
}
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(server, got); err != nil {
|
||||
t.Fatalf("ReadFull: %v", err)
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatal("payload mismatch")
|
||||
}
|
||||
t.Logf("%d bytes in %v -> %.1f KiB/s", len(payload), elapsed,
|
||||
float64(len(payload))/1024/elapsed.Seconds())
|
||||
}
|
||||
Reference in New Issue
Block a user