mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-30 13:48:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e6feeb12f | ||
|
|
ded8443fee | ||
|
|
5780f0df90 | ||
|
|
4d0bfb4d0d | ||
|
|
db6664bd68 | ||
|
|
67756b3674 | ||
|
|
9576662b8e | ||
|
|
c5ccb356aa |
+3
-23
@@ -15,8 +15,6 @@ const (
|
||||
|
||||
var ErrBufferFull = errors.New("buffer is full")
|
||||
|
||||
var pool = bytespool.GetPool(Size)
|
||||
|
||||
// ownership represents the data owner of the buffer.
|
||||
type ownership uint8
|
||||
|
||||
@@ -39,16 +37,7 @@ type Buffer struct {
|
||||
|
||||
// New creates a Buffer with 0 length and 8K capacity, managed.
|
||||
func New() *Buffer {
|
||||
buf := pool.Get().([]byte)
|
||||
if cap(buf) >= Size {
|
||||
buf = buf[:Size]
|
||||
} else {
|
||||
buf = make([]byte, Size)
|
||||
}
|
||||
|
||||
return &Buffer{
|
||||
v: buf,
|
||||
}
|
||||
return &Buffer{v: bytespool.Alloc(Size)}
|
||||
}
|
||||
|
||||
// NewExisted creates a standard size Buffer with an existed bytearray, managed.
|
||||
@@ -80,16 +69,7 @@ func FromBytes(b []byte) *Buffer {
|
||||
// StackNew creates a new Buffer object on stack, managed.
|
||||
// This method is for buffers that is released in the same function.
|
||||
func StackNew() Buffer {
|
||||
buf := pool.Get().([]byte)
|
||||
if cap(buf) >= Size {
|
||||
buf = buf[:Size]
|
||||
} else {
|
||||
buf = make([]byte, Size)
|
||||
}
|
||||
|
||||
return Buffer{
|
||||
v: buf,
|
||||
}
|
||||
return Buffer{v: bytespool.Alloc(Size)}
|
||||
}
|
||||
|
||||
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
|
||||
@@ -113,7 +93,7 @@ func (b *Buffer) Release() {
|
||||
switch b.ownership {
|
||||
case managed:
|
||||
if cap(p) == Size {
|
||||
pool.Put(p)
|
||||
bytespool.Free(p)
|
||||
}
|
||||
case bytespools:
|
||||
bytespool.Free(p)
|
||||
|
||||
+64
-52
@@ -1,72 +1,84 @@
|
||||
package bytespool
|
||||
|
||||
import "sync"
|
||||
import (
|
||||
"math/bits"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func createAllocFunc(size int32) func() interface{} {
|
||||
return func() interface{} {
|
||||
return make([]byte, size)
|
||||
}
|
||||
}
|
||||
|
||||
// The following parameters controls the size of buffer pools.
|
||||
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
|
||||
// Package buf is guaranteed to not use buffers larger than the largest pool.
|
||||
// Other packets may use larger buffers.
|
||||
const (
|
||||
numPools = 4
|
||||
sizeMulti = 4
|
||||
minShift = 10 // 1KB
|
||||
maxShift = 16 // 64KB
|
||||
numPools = maxShift - minShift + 1
|
||||
minSize = 1 << minShift
|
||||
maxSize = 1 << maxShift
|
||||
)
|
||||
|
||||
var (
|
||||
pool [numPools]sync.Pool
|
||||
poolSize [numPools]int32
|
||||
)
|
||||
|
||||
func init() {
|
||||
size := int32(2048)
|
||||
for i := 0; i < numPools; i++ {
|
||||
pool[i] = sync.Pool{
|
||||
New: createAllocFunc(size),
|
||||
}
|
||||
poolSize[i] = size
|
||||
size *= sizeMulti
|
||||
}
|
||||
// pools hold array pointers (*[N]byte) to avoid interface boxing allocations on Put.
|
||||
var pools = [numPools]sync.Pool{
|
||||
{New: func() any { return new([1 << 10]byte) }},
|
||||
{New: func() any { return new([1 << 11]byte) }},
|
||||
{New: func() any { return new([1 << 12]byte) }},
|
||||
{New: func() any { return new([1 << 13]byte) }},
|
||||
{New: func() any { return new([1 << 14]byte) }},
|
||||
{New: func() any { return new([1 << 15]byte) }},
|
||||
{New: func() any { return new([1 << 16]byte) }},
|
||||
}
|
||||
|
||||
// GetPool returns a sync.Pool that generates bytes array with at least the given size.
|
||||
// It may return nil if no such pool exists.
|
||||
//
|
||||
// xray:api:stable
|
||||
func GetPool(size int32) *sync.Pool {
|
||||
for idx, ps := range poolSize {
|
||||
if size <= ps {
|
||||
return &pool[idx]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
|
||||
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024.
|
||||
//
|
||||
// xray:api:stable
|
||||
func Alloc(size int32) []byte {
|
||||
pool := GetPool(size)
|
||||
if pool != nil {
|
||||
return pool.Get().([]byte)
|
||||
if size > maxSize {
|
||||
return make([]byte, size)
|
||||
}
|
||||
index := 0
|
||||
if size > minSize {
|
||||
index = bits.Len32(uint32(size-1)) - minShift
|
||||
}
|
||||
p := pools[index].Get()
|
||||
switch index {
|
||||
case 0:
|
||||
return p.(*[1 << 10]byte)[:]
|
||||
case 1:
|
||||
return p.(*[1 << 11]byte)[:]
|
||||
case 2:
|
||||
return p.(*[1 << 12]byte)[:]
|
||||
case 3:
|
||||
return p.(*[1 << 13]byte)[:]
|
||||
case 4:
|
||||
return p.(*[1 << 14]byte)[:]
|
||||
case 5:
|
||||
return p.(*[1 << 15]byte)[:]
|
||||
case 6:
|
||||
return p.(*[1 << 16]byte)[:]
|
||||
default:
|
||||
panic("invalid pool index")
|
||||
}
|
||||
return make([]byte, size)
|
||||
}
|
||||
|
||||
// Free puts a byte slice into the internal pool.
|
||||
//
|
||||
// xray:api:stable
|
||||
func Free(b []byte) {
|
||||
size := int32(cap(b))
|
||||
b = b[0:cap(b)]
|
||||
for i := numPools - 1; i >= 0; i-- {
|
||||
if size >= poolSize[i] {
|
||||
pool[i].Put(b)
|
||||
return
|
||||
}
|
||||
c := cap(b)
|
||||
if c < minSize || c > maxSize {
|
||||
return
|
||||
}
|
||||
index := bits.Len(uint(c)) - 1 - minShift
|
||||
switch index {
|
||||
case 0:
|
||||
pools[0].Put((*[1 << 10]byte)(b[:1<<10]))
|
||||
case 1:
|
||||
pools[1].Put((*[1 << 11]byte)(b[:1<<11]))
|
||||
case 2:
|
||||
pools[2].Put((*[1 << 12]byte)(b[:1<<12]))
|
||||
case 3:
|
||||
pools[3].Put((*[1 << 13]byte)(b[:1<<13]))
|
||||
case 4:
|
||||
pools[4].Put((*[1 << 14]byte)(b[:1<<14]))
|
||||
case 5:
|
||||
pools[5].Put((*[1 << 15]byte)(b[:1<<15]))
|
||||
case 6:
|
||||
pools[6].Put((*[1 << 16]byte)(b[:1<<16]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,18 +191,10 @@ func getConfig() string {
|
||||
{
|
||||
"protocol": "vless",
|
||||
"settings": {
|
||||
"vnext": [
|
||||
{
|
||||
"address": "1.2.3.4",
|
||||
"port": 1234,
|
||||
"users": [
|
||||
{
|
||||
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
|
||||
"encryption": "none"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
"address": "1.2.3.4",
|
||||
"port": 1234,
|
||||
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
|
||||
"encryption": "none"
|
||||
},
|
||||
"tag": "XHTTP_IN",
|
||||
"streamSettings": {
|
||||
|
||||
@@ -70,6 +70,10 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
|
||||
Execute: t.check,
|
||||
}
|
||||
common.CloseIfExists(t.checkTask)
|
||||
select {
|
||||
case <-t.updated:
|
||||
default:
|
||||
}
|
||||
t.checkTask = newCheckTask
|
||||
common.Must(newCheckTask.Start())
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
|
||||
github.com/bufbuild/protocompile v0.14.1
|
||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
|
||||
github.com/golang/mock v1.7.0-rc.1
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a h1:uCIlOCbXUtBkFk47HxIkQieCkV+zKv5VCDawLtj3Pkc=
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
||||
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
|
||||
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
|
||||
+24
-63
@@ -1,9 +1,6 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/proxy/http"
|
||||
@@ -49,73 +46,37 @@ func (c *HTTPServerConfig) Build() (proto.Message, error) {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type HTTPRemoteConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Users []json.RawMessage `json:"users"`
|
||||
}
|
||||
|
||||
type HTTPClientConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"user"`
|
||||
Password string `json:"pass"`
|
||||
Servers []*HTTPRemoteConfig `json:"servers"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"user"`
|
||||
Password string `json:"pass"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
}
|
||||
|
||||
func (v *HTTPClientConfig) Build() (proto.Message, error) {
|
||||
config := new(http.ClientConfig)
|
||||
if v.Address != nil {
|
||||
v.Servers = []*HTTPRemoteConfig{
|
||||
{
|
||||
Address: v.Address,
|
||||
Port: v.Port,
|
||||
},
|
||||
}
|
||||
if len(v.Username) > 0 {
|
||||
v.Servers[0].Users = []json.RawMessage{{}}
|
||||
}
|
||||
|
||||
server := &protocol.ServerEndpoint{
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
}
|
||||
if len(v.Servers) != 1 {
|
||||
return nil, errors.New(`HTTP settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple HTTP outbounds and routing balancer instead`)
|
||||
}
|
||||
for _, serverConfig := range v.Servers {
|
||||
if len(serverConfig.Users) > 1 {
|
||||
return nil, errors.New(`HTTP servers: "users" should have one member at most. Multiple members in "users" should use multiple HTTP outbounds and routing balancer instead`)
|
||||
}
|
||||
server := &protocol.ServerEndpoint{
|
||||
Address: serverConfig.Address.Build(),
|
||||
Port: uint32(serverConfig.Port),
|
||||
}
|
||||
for _, rawUser := range serverConfig.Users {
|
||||
user := new(protocol.User)
|
||||
if v.Address != nil {
|
||||
user.Level = v.Level
|
||||
user.Email = v.Email
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, user); err != nil {
|
||||
return nil, errors.New("failed to parse HTTP user").Base(err)
|
||||
}
|
||||
}
|
||||
account := new(HTTPAccount)
|
||||
if v.Address != nil {
|
||||
account.Username = v.Username
|
||||
account.Password = v.Password
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, account); err != nil {
|
||||
return nil, errors.New("failed to parse HTTP account").Base(err)
|
||||
}
|
||||
}
|
||||
user.Account = serial.ToTypedMessage(account.Build())
|
||||
server.User = user
|
||||
break
|
||||
}
|
||||
config.Server = server
|
||||
break
|
||||
if len(v.Username) > 0 {
|
||||
account := &HTTPAccount{
|
||||
Username: v.Username,
|
||||
Password: v.Password,
|
||||
}
|
||||
user := &protocol.User{
|
||||
Level: v.Level,
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(account.Build()),
|
||||
}
|
||||
server.User = user
|
||||
}
|
||||
|
||||
config.Server = server
|
||||
config.Header = make([]*http.Header, 0, 32)
|
||||
for key, value := range v.Headers {
|
||||
config.Header = append(config.Header, &http.Header{
|
||||
|
||||
+22
-48
@@ -177,7 +177,7 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type ShadowsocksServerTarget struct {
|
||||
type ShadowsocksClientConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level byte `json:"level"`
|
||||
@@ -186,69 +186,43 @@ type ShadowsocksServerTarget struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type ShadowsocksClientConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level byte `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Cipher string `json:"method"`
|
||||
Password string `json:"password"`
|
||||
Servers []*ShadowsocksServerTarget `json:"servers"`
|
||||
}
|
||||
|
||||
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
|
||||
errors.PrintNonRemovalDeprecatedFeatureWarning("Shadowsocks (with no Forward Secrecy, etc.)", "VLESS Encryption")
|
||||
|
||||
if v.Address != nil {
|
||||
v.Servers = []*ShadowsocksServerTarget{
|
||||
{
|
||||
Address: v.Address,
|
||||
Port: v.Port,
|
||||
Level: v.Level,
|
||||
Email: v.Email,
|
||||
Cipher: v.Cipher,
|
||||
Password: v.Password,
|
||||
},
|
||||
}
|
||||
}
|
||||
if len(v.Servers) != 1 {
|
||||
return nil, errors.New(`Shadowsocks settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Shadowsocks outbounds and routing balancer instead`)
|
||||
}
|
||||
|
||||
server := v.Servers[0]
|
||||
if server.Address == nil {
|
||||
if v.Address == nil {
|
||||
return nil, errors.New("Shadowsocks server address is not set.")
|
||||
}
|
||||
if server.Port == 0 {
|
||||
if v.Port == 0 {
|
||||
return nil, errors.New("Invalid Shadowsocks port.")
|
||||
}
|
||||
if server.Password == "" {
|
||||
if v.Password == "" {
|
||||
return nil, errors.New("Shadowsocks password is not specified.")
|
||||
}
|
||||
|
||||
if _, err := shadowsocks_2022.GetCipherMethod(server.Cipher); err == nil {
|
||||
config := new(shadowsocks_2022.ClientConfig)
|
||||
config.Address = server.Address.Build()
|
||||
config.Port = uint32(server.Port)
|
||||
config.Method = server.Cipher
|
||||
config.Key = server.Password
|
||||
if _, err := shadowsocks_2022.GetCipherMethod(v.Cipher); err == nil {
|
||||
config := &shadowsocks_2022.ClientConfig{
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
Method: v.Cipher,
|
||||
Key: v.Password,
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
config := new(shadowsocks.ClientConfig)
|
||||
account := &shadowsocks.Account{
|
||||
Password: server.Password,
|
||||
}
|
||||
account.CipherType = cipherFromString(server.Cipher)
|
||||
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
|
||||
return nil, errors.New("unknown cipher method: ", server.Cipher)
|
||||
if cipherFromString(v.Cipher) == shadowsocks.CipherType_UNKNOWN {
|
||||
return nil, errors.New("unknown cipher method: ", v.Cipher)
|
||||
}
|
||||
ss := &protocol.ServerEndpoint{
|
||||
Address: server.Address.Build(),
|
||||
Port: uint32(server.Port),
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
User: &protocol.User{
|
||||
Level: uint32(server.Level),
|
||||
Email: server.Email,
|
||||
Account: serial.ToTypedMessage(account),
|
||||
Level: uint32(v.Level),
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(&shadowsocks.Account{
|
||||
Password: v.Password,
|
||||
CipherType: cipherFromString(v.Cipher),
|
||||
}),
|
||||
},
|
||||
}
|
||||
config.Server = ss
|
||||
|
||||
+23
-62
@@ -1,9 +1,6 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
"github.com/xtls/xray-core/proxy/socks"
|
||||
@@ -67,71 +64,35 @@ func (v *SocksServerConfig) Build() (proto.Message, error) {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type SocksRemoteConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Users []json.RawMessage `json:"users"`
|
||||
}
|
||||
|
||||
type SocksClientConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"user"`
|
||||
Password string `json:"pass"`
|
||||
Servers []*SocksRemoteConfig `json:"servers"`
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"user"`
|
||||
Password string `json:"pass"`
|
||||
}
|
||||
|
||||
func (v *SocksClientConfig) Build() (proto.Message, error) {
|
||||
config := new(socks.ClientConfig)
|
||||
if v.Address != nil {
|
||||
v.Servers = []*SocksRemoteConfig{
|
||||
{
|
||||
Address: v.Address,
|
||||
Port: v.Port,
|
||||
},
|
||||
}
|
||||
if len(v.Username) > 0 {
|
||||
v.Servers[0].Users = []json.RawMessage{{}}
|
||||
}
|
||||
|
||||
server := &protocol.ServerEndpoint{
|
||||
Address: v.Address.Build(),
|
||||
Port: uint32(v.Port),
|
||||
}
|
||||
if len(v.Servers) != 1 {
|
||||
return nil, errors.New(`SOCKS settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple SOCKS outbounds and routing balancer instead`)
|
||||
}
|
||||
for _, serverConfig := range v.Servers {
|
||||
if len(serverConfig.Users) > 1 {
|
||||
return nil, errors.New(`SOCKS servers: "users" should have one member at most. Multiple members in "users" should use multiple SOCKS outbounds and routing balancer instead`)
|
||||
}
|
||||
server := &protocol.ServerEndpoint{
|
||||
Address: serverConfig.Address.Build(),
|
||||
Port: uint32(serverConfig.Port),
|
||||
}
|
||||
for _, rawUser := range serverConfig.Users {
|
||||
user := new(protocol.User)
|
||||
if v.Address != nil {
|
||||
user.Level = v.Level
|
||||
user.Email = v.Email
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, user); err != nil {
|
||||
return nil, errors.New("failed to parse Socks user").Base(err)
|
||||
}
|
||||
}
|
||||
account := new(SocksAccount)
|
||||
if v.Address != nil {
|
||||
account.Username = v.Username
|
||||
account.Password = v.Password
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, account); err != nil {
|
||||
return nil, errors.New("failed to parse socks account").Base(err)
|
||||
}
|
||||
}
|
||||
user.Account = serial.ToTypedMessage(account.Build())
|
||||
server.User = user
|
||||
break
|
||||
}
|
||||
config.Server = server
|
||||
break
|
||||
if len(v.Username) > 0 {
|
||||
account := &SocksAccount{
|
||||
Username: v.Username,
|
||||
Password: v.Password,
|
||||
}
|
||||
user := &protocol.User{
|
||||
Level: v.Level,
|
||||
Email: v.Email,
|
||||
Account: serial.ToTypedMessage(account.Build()),
|
||||
}
|
||||
server.User = user
|
||||
}
|
||||
|
||||
config.Server = server
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -53,35 +53,6 @@ func TestSocksOutboundConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{
|
||||
"servers": [{
|
||||
"address": "127.0.0.1",
|
||||
"port": 1234,
|
||||
"users": [
|
||||
{"user": "test user", "pass": "test pass", "email": "test@email.com"}
|
||||
]
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &socks.ClientConfig{
|
||||
Server: &protocol.ServerEndpoint{
|
||||
Address: &net.IPOrDomain{
|
||||
Address: &net.IPOrDomain_Ip{
|
||||
Ip: []byte{127, 0, 0, 1},
|
||||
},
|
||||
},
|
||||
Port: 1234,
|
||||
User: &protocol.User{
|
||||
Email: "test@email.com",
|
||||
Account: serial.ToTypedMessage(&socks.Account{
|
||||
Username: "test user",
|
||||
Password: "test pass",
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
"address": "127.0.0.1",
|
||||
|
||||
@@ -532,7 +532,7 @@ func TestXDriveOutboundConfig(t *testing.T) {
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||
} {
|
||||
if err := build(input); err != nil {
|
||||
t.Errorf("%s: %v", input, err)
|
||||
@@ -543,7 +543,7 @@ func TestXDriveOutboundConfig(t *testing.T) {
|
||||
{`{"protocol": "vless", "settings": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
|
||||
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||
|
||||
+21
-60
@@ -17,76 +17,41 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// TrojanServerTarget is configuration of a single trojan server
|
||||
type TrojanServerTarget struct {
|
||||
// TrojanClientConfig is configuration of trojan servers
|
||||
type TrojanClientConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level byte `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Flow string `json:"flow"`
|
||||
}
|
||||
|
||||
// TrojanClientConfig is configuration of trojan servers
|
||||
type TrojanClientConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level byte `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Flow string `json:"flow"`
|
||||
Servers []*TrojanServerTarget `json:"servers"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
func (c *TrojanClientConfig) Build() (proto.Message, error) {
|
||||
errors.PrintNonRemovalDeprecatedFeatureWarning("Trojan (with no Flow, etc.)", "VLESS with Flow & Seed")
|
||||
|
||||
if c.Address != nil {
|
||||
c.Servers = []*TrojanServerTarget{
|
||||
{
|
||||
Address: c.Address,
|
||||
Port: c.Port,
|
||||
Level: c.Level,
|
||||
Email: c.Email,
|
||||
Password: c.Password,
|
||||
Flow: c.Flow,
|
||||
},
|
||||
}
|
||||
}
|
||||
if len(c.Servers) != 1 {
|
||||
return nil, errors.New(`Trojan settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Trojan outbounds and routing balancer instead`)
|
||||
}
|
||||
|
||||
config := &trojan.ClientConfig{}
|
||||
|
||||
for _, rec := range c.Servers {
|
||||
if rec.Address == nil {
|
||||
return nil, errors.New("Trojan server address is not set.")
|
||||
}
|
||||
if rec.Port == 0 {
|
||||
return nil, errors.New("Invalid Trojan port.")
|
||||
}
|
||||
if rec.Password == "" {
|
||||
return nil, errors.New("Trojan password is not specified.")
|
||||
}
|
||||
if rec.Flow != "" {
|
||||
return nil, errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
|
||||
}
|
||||
if c.Address == nil {
|
||||
return nil, errors.New("Trojan server address is not set.")
|
||||
}
|
||||
if c.Port == 0 {
|
||||
return nil, errors.New("Invalid Trojan port.")
|
||||
}
|
||||
if c.Password == "" {
|
||||
return nil, errors.New("Trojan password is not specified.")
|
||||
}
|
||||
|
||||
config.Server = &protocol.ServerEndpoint{
|
||||
Address: rec.Address.Build(),
|
||||
Port: uint32(rec.Port),
|
||||
User: &protocol.User{
|
||||
Level: uint32(rec.Level),
|
||||
Email: rec.Email,
|
||||
Account: serial.ToTypedMessage(&trojan.Account{
|
||||
Password: rec.Password,
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
break
|
||||
config.Server = &protocol.ServerEndpoint{
|
||||
Address: c.Address.Build(),
|
||||
Port: uint32(c.Port),
|
||||
User: &protocol.User{
|
||||
Level: uint32(c.Level),
|
||||
Email: c.Email,
|
||||
Account: serial.ToTypedMessage(&trojan.Account{
|
||||
Password: c.Password,
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
return config, nil
|
||||
@@ -107,7 +72,6 @@ type TrojanUserConfig struct {
|
||||
Password string `json:"password"`
|
||||
Level byte `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Flow string `json:"flow"`
|
||||
}
|
||||
|
||||
// TrojanServerConfig is Inbound configuration
|
||||
@@ -131,9 +95,6 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
|
||||
|
||||
processClient := func(idx int) error {
|
||||
rawUser := c.Users[idx]
|
||||
if rawUser.Flow != "" {
|
||||
return errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
|
||||
}
|
||||
|
||||
config.Users[idx] = &protocol.User{
|
||||
Level: uint32(rawUser.Level),
|
||||
|
||||
+96
-141
@@ -256,26 +256,19 @@ func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
|
||||
})
|
||||
}
|
||||
|
||||
type VLessOutboundVnext struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Users []json.RawMessage `json:"users"`
|
||||
}
|
||||
|
||||
type VLessOutboundConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Id string `json:"id"`
|
||||
Flow string `json:"flow"`
|
||||
Seed string `json:"seed"`
|
||||
Encryption string `json:"encryption"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
Reverse *VLessReverseConfig `json:"reverse"`
|
||||
Testpre uint32 `json:"testpre"`
|
||||
Testseed []uint32 `json:"testseed"`
|
||||
Vnext []*VLessOutboundVnext `json:"vnext"`
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
Id string `json:"id"`
|
||||
Flow string `json:"flow"`
|
||||
Seed string `json:"seed"`
|
||||
Encryption string `json:"encryption"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
Reverse *VLessReverseConfig `json:"reverse"`
|
||||
Testpre uint32 `json:"testpre"`
|
||||
Testseed []uint32 `json:"testseed"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
@@ -286,130 +279,92 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
|
||||
if c.Address != nil {
|
||||
c.Vnext = []*VLessOutboundVnext{
|
||||
{
|
||||
Address: c.Address,
|
||||
Port: c.Port,
|
||||
Users: []json.RawMessage{{}},
|
||||
},
|
||||
}
|
||||
if c.Address == nil {
|
||||
return nil, errors.New(`VLESS: "address" is not set`)
|
||||
}
|
||||
if len(c.Vnext) != 1 {
|
||||
return nil, errors.New(`VLESS settings: "vnext" should have one and only one member. Multiple endpoints in "vnext" should use multiple VLESS outbounds and routing balancer instead`)
|
||||
}
|
||||
for _, rec := range c.Vnext {
|
||||
if rec.Address == nil {
|
||||
return nil, errors.New(`VLESS vnext: "address" is not set`)
|
||||
}
|
||||
if len(rec.Users) != 1 {
|
||||
return nil, errors.New(`VLESS vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VLESS outbounds and routing balancer instead`)
|
||||
}
|
||||
spec := &protocol.ServerEndpoint{
|
||||
Address: rec.Address.Build(),
|
||||
Port: uint32(rec.Port),
|
||||
}
|
||||
for _, rawUser := range rec.Users {
|
||||
user := new(protocol.User)
|
||||
if c.Address != nil {
|
||||
user.Level = c.Level
|
||||
user.Email = c.Email
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, user); err != nil {
|
||||
return nil, errors.New(`VLESS users: invalid user`).Base(err)
|
||||
}
|
||||
}
|
||||
account := new(vless.Account)
|
||||
if c.Address != nil {
|
||||
account.Id = c.Id
|
||||
account.Flow = c.Flow
|
||||
//account.Seed = c.Seed
|
||||
account.Encryption = c.Encryption
|
||||
if c.Reverse != nil {
|
||||
rvs, err := c.Reverse.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.Reverse = rvs
|
||||
}
|
||||
account.Testpre = c.Testpre
|
||||
account.Testseed = c.Testseed
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, account); err != nil {
|
||||
return nil, errors.New(`VLESS users: invalid user`).Base(err)
|
||||
}
|
||||
// validateOutboundTransportSecurity needs to see these
|
||||
c.Encryption = account.Encryption
|
||||
c.Address = rec.Address
|
||||
if account.Reverse != nil { // may not be reached: error json unmarshal
|
||||
return nil, errors.New(`VLESS users: please use simplified outbound's config style to use "reverse"`)
|
||||
}
|
||||
}
|
||||
|
||||
u, err := uuid.ParseString(account.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.Id = u.String()
|
||||
|
||||
switch account.Flow {
|
||||
case "":
|
||||
case vless.XRV, vless.XRV + "-udp443":
|
||||
default:
|
||||
return nil, errors.New(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
|
||||
}
|
||||
|
||||
if !func() bool {
|
||||
s := strings.Split(account.Encryption, ".")
|
||||
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
|
||||
return false
|
||||
}
|
||||
switch s[1] {
|
||||
case "native":
|
||||
case "xorpub":
|
||||
account.XorMode = 1
|
||||
case "random":
|
||||
account.XorMode = 2
|
||||
default:
|
||||
return false
|
||||
}
|
||||
switch s[2] {
|
||||
case "1rtt":
|
||||
case "0rtt":
|
||||
account.Seconds = 1
|
||||
default:
|
||||
return false
|
||||
}
|
||||
padding := 0
|
||||
for _, r := range s[3:] {
|
||||
if len(r) < 20 {
|
||||
padding += len(r) + 1
|
||||
continue
|
||||
}
|
||||
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
account.Encryption = account.Encryption[27+len(s[2]):]
|
||||
if padding > 0 {
|
||||
account.Padding = account.Encryption[:padding-1]
|
||||
account.Encryption = account.Encryption[padding:]
|
||||
}
|
||||
return true
|
||||
}() && account.Encryption != "none" {
|
||||
if account.Encryption == "" {
|
||||
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
|
||||
}
|
||||
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
|
||||
}
|
||||
|
||||
user.Account = serial.ToTypedMessage(account)
|
||||
spec.User = user
|
||||
break
|
||||
}
|
||||
config.Vnext = spec
|
||||
break
|
||||
uid, err := uuid.ParseString(c.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch c.Flow {
|
||||
case "":
|
||||
case vless.XRV, vless.XRV + "-udp443":
|
||||
default:
|
||||
return nil, errors.New(`VLESS users: "flow" doesn't support "` + c.Flow + `" in this version`)
|
||||
}
|
||||
|
||||
spec := &protocol.ServerEndpoint{
|
||||
Address: c.Address.Build(),
|
||||
Port: uint32(c.Port),
|
||||
}
|
||||
user := &protocol.User{
|
||||
Level: c.Level,
|
||||
Email: c.Email,
|
||||
}
|
||||
account := &vless.Account{
|
||||
Id: uid.String(),
|
||||
Flow: c.Flow,
|
||||
// Seed: c.Seed,
|
||||
Encryption: c.Encryption,
|
||||
Testpre: c.Testpre,
|
||||
Testseed: c.Testseed,
|
||||
}
|
||||
if c.Reverse != nil {
|
||||
rvs, err := c.Reverse.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.Reverse = rvs
|
||||
}
|
||||
|
||||
if !func() bool {
|
||||
s := strings.Split(account.Encryption, ".")
|
||||
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
|
||||
return false
|
||||
}
|
||||
switch s[1] {
|
||||
case "native":
|
||||
case "xorpub":
|
||||
account.XorMode = 1
|
||||
case "random":
|
||||
account.XorMode = 2
|
||||
default:
|
||||
return false
|
||||
}
|
||||
switch s[2] {
|
||||
case "1rtt":
|
||||
case "0rtt":
|
||||
account.Seconds = 1
|
||||
default:
|
||||
return false
|
||||
}
|
||||
padding := 0
|
||||
for _, r := range s[3:] {
|
||||
if len(r) < 20 {
|
||||
padding += len(r) + 1
|
||||
continue
|
||||
}
|
||||
if b, _ := base64.RawURLEncoding.DecodeString(r); len(b) != 32 && len(b) != 1184 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
account.Encryption = account.Encryption[27+len(s[2]):]
|
||||
if padding > 0 {
|
||||
account.Padding = account.Encryption[:padding-1]
|
||||
account.Encryption = account.Encryption[padding:]
|
||||
}
|
||||
return true
|
||||
}() && account.Encryption != "none" {
|
||||
if account.Encryption == "" {
|
||||
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
|
||||
}
|
||||
return nil, errors.New(`VLESS users: unsupported "encryption": ` + account.Encryption)
|
||||
}
|
||||
|
||||
user.Account = serial.ToTypedMessage(account)
|
||||
spec.User = user
|
||||
|
||||
config.Vnext = spec
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -18,41 +18,6 @@ func TestVLessOutbound(t *testing.T) {
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{
|
||||
"vnext": [{
|
||||
"address": "example.com",
|
||||
"port": 443,
|
||||
"users": [
|
||||
{
|
||||
"id": "27848739-7e62-4138-9fd3-098a63964b6b",
|
||||
"flow": "xtls-rprx-vision-udp443",
|
||||
"encryption": "none",
|
||||
"level": 0
|
||||
}
|
||||
]
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &outbound.Config{
|
||||
Vnext: &protocol.ServerEndpoint{
|
||||
Address: &net.IPOrDomain{
|
||||
Address: &net.IPOrDomain_Domain{
|
||||
Domain: "example.com",
|
||||
},
|
||||
},
|
||||
Port: 443,
|
||||
User: &protocol.User{
|
||||
Account: serial.ToTypedMessage(&vless.Account{
|
||||
Id: "27848739-7e62-4138-9fd3-098a63964b6b",
|
||||
Flow: "xtls-rprx-vision-udp443",
|
||||
Encryption: "none",
|
||||
}),
|
||||
Level: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
"address": "example.com",
|
||||
|
||||
+31
-70
@@ -102,22 +102,15 @@ func (c *VMessInboundConfig) Build() (proto.Message, error) {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type VMessOutboundTarget struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Users []json.RawMessage `json:"users"`
|
||||
}
|
||||
|
||||
type VMessOutboundConfig struct {
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
ID string `json:"id"`
|
||||
Security string `json:"security"`
|
||||
Experiments string `json:"experiments"`
|
||||
Receivers []*VMessOutboundTarget `json:"vnext"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
Address *Address `json:"address"`
|
||||
Port uint16 `json:"port"`
|
||||
Level uint32 `json:"level"`
|
||||
Email string `json:"email"`
|
||||
ID string `json:"id"`
|
||||
Security string `json:"security"`
|
||||
Experiments string `json:"experiments"`
|
||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||
}
|
||||
|
||||
// Build implements Buildable
|
||||
@@ -129,62 +122,30 @@ func (c *VMessOutboundConfig) Build() (proto.Message, error) {
|
||||
return nil, err
|
||||
}
|
||||
config := &outbound.Config{Multiplex: multiplex}
|
||||
if c.Address != nil {
|
||||
c.Receivers = []*VMessOutboundTarget{
|
||||
{
|
||||
Address: c.Address,
|
||||
Port: c.Port,
|
||||
Users: []json.RawMessage{{}},
|
||||
},
|
||||
}
|
||||
}
|
||||
if len(c.Receivers) != 1 {
|
||||
return nil, errors.New(`VMess settings: "vnext" should have one and only one member. Multiple endpoints in "vnext" should use multiple VMess outbounds and routing balancer instead`)
|
||||
}
|
||||
for _, rec := range c.Receivers {
|
||||
if len(rec.Users) != 1 {
|
||||
return nil, errors.New(`VMess vnext: "users" should have one and only one member. Multiple members in "users" should use multiple VMess outbounds and routing balancer instead`)
|
||||
}
|
||||
if rec.Address == nil {
|
||||
return nil, errors.New(`VMess vnext: "address" is not set`)
|
||||
}
|
||||
spec := &protocol.ServerEndpoint{
|
||||
Address: rec.Address.Build(),
|
||||
Port: uint32(rec.Port),
|
||||
}
|
||||
for _, rawUser := range rec.Users {
|
||||
user := new(protocol.User)
|
||||
if c.Address != nil {
|
||||
user.Level = c.Level
|
||||
user.Email = c.Email
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, user); err != nil {
|
||||
return nil, errors.New("invalid VMess user").Base(err)
|
||||
}
|
||||
}
|
||||
account := new(VMessAccount)
|
||||
if c.Address != nil {
|
||||
account.ID = c.ID
|
||||
account.Security = c.Security
|
||||
account.Experiments = c.Experiments
|
||||
} else {
|
||||
if err := json.Unmarshal(rawUser, account); err != nil {
|
||||
return nil, errors.New("invalid VMess user").Base(err)
|
||||
}
|
||||
}
|
||||
|
||||
u, err := uuid.ParseString(account.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.ID = u.String()
|
||||
|
||||
user.Account = serial.ToTypedMessage(account.Build())
|
||||
spec.User = user
|
||||
break
|
||||
}
|
||||
config.Receiver = spec
|
||||
break
|
||||
if c.Address == nil {
|
||||
return nil, errors.New(`VMess: "address" is not set`)
|
||||
}
|
||||
uid, err := uuid.ParseString(c.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
account := &VMessAccount{
|
||||
ID: uid.String(),
|
||||
Security: c.Security,
|
||||
Experiments: c.Experiments,
|
||||
}
|
||||
spec := &protocol.ServerEndpoint{
|
||||
Address: c.Address.Build(),
|
||||
Port: uint32(c.Port),
|
||||
User: &protocol.User{
|
||||
Level: c.Level,
|
||||
Email: c.Email,
|
||||
Account: serial.ToTypedMessage(account.Build()),
|
||||
},
|
||||
}
|
||||
|
||||
config.Receiver = spec
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -18,42 +18,6 @@ func TestVMessOutbound(t *testing.T) {
|
||||
}
|
||||
|
||||
runMultiTestCase(t, []TestCase{
|
||||
{
|
||||
Input: `{
|
||||
"vnext": [{
|
||||
"address": "127.0.0.1",
|
||||
"port": 80,
|
||||
"users": [
|
||||
{
|
||||
"id": "e641f5ad-9397-41e3-bf1a-e8740dfed019",
|
||||
"email": "love@example.com",
|
||||
"level": 255
|
||||
}
|
||||
]
|
||||
}]
|
||||
}`,
|
||||
Parser: loadJSON(creator),
|
||||
Output: &outbound.Config{
|
||||
Receiver: &protocol.ServerEndpoint{
|
||||
Address: &net.IPOrDomain{
|
||||
Address: &net.IPOrDomain_Ip{
|
||||
Ip: []byte{127, 0, 0, 1},
|
||||
},
|
||||
},
|
||||
Port: 80,
|
||||
User: &protocol.User{
|
||||
Email: "love@example.com",
|
||||
Level: 255,
|
||||
Account: serial.ToTypedMessage(&vmess.Account{
|
||||
Id: "e641f5ad-9397-41e3-bf1a-e8740dfed019",
|
||||
SecuritySettings: &protocol.SecurityConfig{
|
||||
Type: protocol.SecurityType_AUTO,
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Input: `{
|
||||
"address": "127.0.0.1",
|
||||
|
||||
+1
-1
@@ -238,7 +238,7 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
||||
}
|
||||
|
||||
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
|
||||
if requiresTransportSecurity(tjCfg.Servers[0].Address) {
|
||||
if requiresTransportSecurity(tjCfg.Address) {
|
||||
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
|
||||
}
|
||||
}
|
||||
|
||||
+39
-14
@@ -5,6 +5,7 @@ import (
|
||||
go_errors "errors"
|
||||
"io"
|
||||
"math/rand"
|
||||
"slices"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -174,10 +175,15 @@ func init() {
|
||||
}))
|
||||
}
|
||||
|
||||
// UDPWriter is not safe for concurrent writes.
|
||||
type UDPWriter struct {
|
||||
writer io.Writer
|
||||
addr string
|
||||
buf [buf.Size]byte
|
||||
|
||||
// Last b.UDP and its NetAddr, which allocates on every call.
|
||||
lastUDP net.Destination
|
||||
lastUDPAddr string
|
||||
}
|
||||
|
||||
func (w *UDPWriter) SendMessage(msg *UDPMessage) error {
|
||||
@@ -193,21 +199,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
for i, b := range mb {
|
||||
addr := w.addr
|
||||
if b.UDP != nil {
|
||||
addr = b.UDP.NetAddr()
|
||||
if *b.UDP != w.lastUDP {
|
||||
w.lastUDP = *b.UDP
|
||||
w.lastUDPAddr = b.UDP.NetAddr()
|
||||
}
|
||||
addr = w.lastUDPAddr
|
||||
}
|
||||
|
||||
msg := &UDPMessage{
|
||||
SessionID: 0,
|
||||
PacketID: 0,
|
||||
FragID: 0,
|
||||
FragCount: 1,
|
||||
Addr: addr,
|
||||
Data: b.Bytes(),
|
||||
}
|
||||
|
||||
err := w.SendMessage(msg)
|
||||
var errTooLarge *quic.DatagramTooLargeError
|
||||
if go_errors.As(err, &errTooLarge) {
|
||||
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
|
||||
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
|
||||
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
|
||||
for _, fMsg := range fMsgs {
|
||||
@@ -228,40 +234,59 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UDPReader is not safe for concurrent reads.
|
||||
type UDPReader struct {
|
||||
reader io.Reader
|
||||
df *Defragger
|
||||
firstBuf *buf.Buffer
|
||||
|
||||
// Last message address and its parsed destination.
|
||||
lastAddr string
|
||||
lastDest net.Destination
|
||||
|
||||
packet [1500]byte
|
||||
msg UDPMessage
|
||||
}
|
||||
|
||||
func (r *UDPReader) ReadFrom(p []byte) (n int, addr *net.Destination, err error) {
|
||||
for {
|
||||
var packet [1500]byte
|
||||
|
||||
n, err := r.reader.Read(packet[:])
|
||||
n, err := r.reader.Read(r.packet[:])
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
msg, err := ParseUDPMessage(packet[:n])
|
||||
if err != nil {
|
||||
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
msg := &r.msg
|
||||
if msg.FragCount > 1 {
|
||||
// The defragger keeps fragments between calls, so they must not alias packet.
|
||||
frag := *msg
|
||||
frag.Data = slices.Clone(msg.Data)
|
||||
msg = &frag
|
||||
}
|
||||
|
||||
dfMsg := r.df.Feed(msg)
|
||||
if dfMsg == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||
if err != nil {
|
||||
continue
|
||||
if dfMsg.Addr != r.lastAddr {
|
||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
r.lastAddr = dfMsg.Addr
|
||||
r.lastDest = dest
|
||||
}
|
||||
|
||||
if len(p) < len(dfMsg.Data) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Callers can rewrite the packet destination in place.
|
||||
dest := r.lastDest
|
||||
return copy(p, dfMsg.Data), &dest, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// datagramReader returns one datagram per Read, like a QUIC datagram stream.
|
||||
type datagramReader struct {
|
||||
msgs [][]byte
|
||||
}
|
||||
|
||||
func (r *datagramReader) Read(p []byte) (int, error) {
|
||||
if len(r.msgs) == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, r.msgs[0])
|
||||
r.msgs = r.msgs[1:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func newTestReader(msgs []UDPMessage) *UDPReader {
|
||||
datagrams := make([][]byte, len(msgs))
|
||||
for i := range msgs {
|
||||
datagrams[i] = make([]byte, msgs[i].Size())
|
||||
msgs[i].Serialize(datagrams[i])
|
||||
}
|
||||
return &UDPReader{reader: &datagramReader{msgs: datagrams}, df: &Defragger{}}
|
||||
}
|
||||
|
||||
func TestUDPReaderFragments(t *testing.T) {
|
||||
want := &UDPMessage{PacketID: 1, Addr: "example.com:443", Data: bytes.Repeat([]byte("0123456789"), 20)}
|
||||
frags := FragUDPMessage(want, 100)
|
||||
if len(frags) < 2 {
|
||||
t.Fatalf("got %d fragments, want at least 2", len(frags))
|
||||
}
|
||||
|
||||
p := make([]byte, buf.Size)
|
||||
n, dest, err := newTestReader(frags).ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, want.Data, want.Addr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUDPReaderDestinations(t *testing.T) {
|
||||
msgs := []UDPMessage{
|
||||
{Addr: "203.0.113.1:53", Data: []byte("first")},
|
||||
{Addr: "203.0.113.1:53", Data: []byte("second")},
|
||||
{Addr: "203.0.113.2:53", Data: []byte("third")},
|
||||
}
|
||||
r := newTestReader(msgs)
|
||||
p := make([]byte, buf.Size)
|
||||
for i, want := range msgs {
|
||||
n, dest, err := r.ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
||||
t.Errorf("packet %d: got %q to %v, want %q to %s", i, p[:n], dest, want.Data, want.Addr)
|
||||
}
|
||||
// Callers rewrite the destination in place, the next packet must not see it.
|
||||
dest.Port = 5353
|
||||
}
|
||||
}
|
||||
|
||||
type captureWriter struct {
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *captureWriter) Write(p []byte) (int, error) {
|
||||
w.writes = append(w.writes, bytes.Clone(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestUDPWriterAddress(t *testing.T) {
|
||||
ip := xnet.UDPDestination(xnet.ParseAddress("203.0.113.1"), 53)
|
||||
domain := xnet.UDPDestination(xnet.DomainAddress("example.com"), 53)
|
||||
|
||||
cw := &captureWriter{}
|
||||
w := &UDPWriter{writer: cw, addr: "198.51.100.1:1"}
|
||||
for _, tc := range []struct {
|
||||
udp *xnet.Destination
|
||||
want string
|
||||
}{
|
||||
{&ip, "203.0.113.1:53"},
|
||||
{&domain, "example.com:53"},
|
||||
{nil, "198.51.100.1:1"},
|
||||
{&ip, "203.0.113.1:53"},
|
||||
} {
|
||||
b := buf.FromBytes([]byte("data"))
|
||||
b.UDP = tc.udp
|
||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg, err := ParseUDPMessage(cw.writes[len(cw.writes)-1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg.Addr != tc.want {
|
||||
t.Errorf("address = %q, want %q", msg.Addr, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fragmentingWriter rejects datagrams larger than max, like a QUIC connection.
|
||||
type fragmentingWriter struct {
|
||||
max int
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *fragmentingWriter) Write(p []byte) (int, error) {
|
||||
if len(p) > w.max {
|
||||
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(w.max)}
|
||||
}
|
||||
w.writes = append(w.writes, bytes.Clone(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestUDPWriterFragmentation(t *testing.T) {
|
||||
data := bytes.Repeat([]byte("0123456789"), 20)
|
||||
fw := &fragmentingWriter{max: 100}
|
||||
w := &UDPWriter{writer: fw, addr: "example.com:443"}
|
||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(data)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fw.writes) < 2 {
|
||||
t.Fatalf("got %d datagrams, want at least 2", len(fw.writes))
|
||||
}
|
||||
|
||||
r := &UDPReader{reader: &datagramReader{msgs: fw.writes}, df: &Defragger{}}
|
||||
p := make([]byte, buf.Size)
|
||||
n, dest, err := r.ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != w.addr || !bytes.Equal(p[:n], data) {
|
||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, data, w.addr)
|
||||
}
|
||||
}
|
||||
+28
-20
@@ -1,7 +1,6 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -183,35 +182,44 @@ func (m *UDPMessage) Serialize(buf []byte) int {
|
||||
}
|
||||
|
||||
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
|
||||
m := &UDPMessage{}
|
||||
buf := bytes.NewBuffer(msg)
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
|
||||
m := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, "", m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); err != nil {
|
||||
return nil, err
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// parseUDPMessage parses msg into m. m.Data aliases msg; m.Addr is lastAddr
|
||||
// when they are equal, so an unchanged address is not allocated again.
|
||||
func parseUDPMessage(msg []byte, lastAddr string, m *UDPMessage) error {
|
||||
if len(msg) < 8 {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.FragID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.FragCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lAddr, err := quicvarint.Read(buf)
|
||||
lAddr, n, err := quicvarint.Parse(msg[8:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
if lAddr == 0 || lAddr > MaxMessageLength {
|
||||
return nil, errors.New("invalid address length")
|
||||
return errors.New("invalid address length")
|
||||
}
|
||||
bs := buf.Bytes()
|
||||
bs := msg[8+n:]
|
||||
if len(bs) <= int(lAddr) {
|
||||
// We use <= instead of < here as we expect at least one byte of data after the address
|
||||
return nil, errors.New("invalid message length")
|
||||
return errors.New("invalid message length")
|
||||
}
|
||||
m.Addr = string(bs[:lAddr])
|
||||
m.Data = bs[lAddr:]
|
||||
return m, nil
|
||||
*m = UDPMessage{
|
||||
SessionID: binary.BigEndian.Uint32(msg),
|
||||
PacketID: binary.BigEndian.Uint16(msg[4:]),
|
||||
FragID: msg[6],
|
||||
FragCount: msg[7],
|
||||
Data: bs[lAddr:],
|
||||
}
|
||||
if string(bs[:lAddr]) == lastAddr {
|
||||
m.Addr = lastAddr
|
||||
} else {
|
||||
m.Addr = string(bs[:lAddr])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// varintPut is like quicvarint.Append, but instead of appending to a slice,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseUDPMessage(t *testing.T) {
|
||||
want := &UDPMessage{PacketID: 1, FragID: 2, FragCount: 3, Addr: "example.com:443", Data: []byte("hello")}
|
||||
msg := make([]byte, want.Size())
|
||||
want.Serialize(msg)
|
||||
|
||||
for _, lastAddr := range []string{"", want.Addr, "other:1"} {
|
||||
got := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, lastAddr, got); err != nil {
|
||||
t.Fatalf("lastAddr %q: %v", lastAddr, err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("lastAddr %q: got %+v, want %+v", lastAddr, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseUDPMessageInvalid(t *testing.T) {
|
||||
msg := &UDPMessage{Addr: "example.com:443", Data: []byte("hello")}
|
||||
buf := make([]byte, msg.Size())
|
||||
msg.Serialize(buf)
|
||||
|
||||
zeroAddrLen := bytes.Clone(buf)
|
||||
zeroAddrLen[8] = 0 // Address length varint follows the 8-byte header
|
||||
|
||||
noData := &UDPMessage{Addr: msg.Addr}
|
||||
noDataBuf := make([]byte, noData.Size())
|
||||
noData.Serialize(noDataBuf)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
msg []byte
|
||||
}{
|
||||
{"short header", buf[:7]},
|
||||
{"zero address length", zeroAddrLen},
|
||||
{"no data after address", noDataBuf},
|
||||
} {
|
||||
if _, err := ParseUDPMessage(tc.msg); err == nil {
|
||||
t.Errorf("%s: expected error", tc.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,21 +53,23 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
udpCodec, err := NewUDPServerCodec(method, psk, 500*time.Second)
|
||||
user := &protocol.MemoryUser{
|
||||
Email: config.Email,
|
||||
Level: uint32(config.Level),
|
||||
}
|
||||
|
||||
udpCodec, err := NewUDPServerCodec(method, psk, user, 500*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
return &Inbound{
|
||||
networks: networks,
|
||||
method: method,
|
||||
psk: psk,
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
user: &protocol.MemoryUser{
|
||||
Email: config.Email,
|
||||
Level: uint32(config.Level),
|
||||
},
|
||||
networks: networks,
|
||||
method: method,
|
||||
psk: psk,
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
user: user,
|
||||
udpCodec: udpCodec,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}, nil
|
||||
@@ -155,20 +157,12 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
|
||||
}
|
||||
|
||||
for _, b := range mb {
|
||||
decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
||||
sessionItem, decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
||||
b.Release()
|
||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
||||
continue
|
||||
}
|
||||
|
||||
sessionItem := i.udpCodec.GetSession(decoded.SessionID)
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = i.user
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
|
||||
@@ -2,8 +2,6 @@ package shadowsocks_2022
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -34,16 +32,15 @@ func init() {
|
||||
|
||||
type MultiUserInbound struct {
|
||||
sync.Mutex
|
||||
networks []net.Network
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
|
||||
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
userCount atomic.Int64
|
||||
saltFilter *antireplay.ReplayFilter[[32]byte]
|
||||
udpSessions *UDPSessionManager
|
||||
udpMasterCipher cipher.Block
|
||||
policyManager policy.Manager
|
||||
networks []net.Network
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
|
||||
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
userCount atomic.Int64
|
||||
saltFilter *antireplay.ReplayFilter[[32]byte]
|
||||
udpCodec *UDPMultiServerCodec
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) {
|
||||
@@ -68,22 +65,21 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
|
||||
return nil, err
|
||||
}
|
||||
|
||||
masterBlock, err := method.NewBlock(masterPSK)
|
||||
udpCodec, err := NewUDPMultiServerCodec(method, masterPSK, 500*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
i := &MultiUserInbound{
|
||||
networks: networks,
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
|
||||
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
udpSessions: NewUDPSessionManager(500 * time.Second),
|
||||
udpMasterCipher: masterBlock,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
networks: networks,
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
|
||||
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
udpCodec: udpCodec,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
|
||||
for idx, user := range config.Users {
|
||||
@@ -281,68 +277,26 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
|
||||
for _, b := range mb {
|
||||
// In multi-user UDP:
|
||||
// Packet header is 16 bytes: Encrypted(SessionID + PacketID)
|
||||
// Followed by 16 bytes EIH
|
||||
packetBytes := b.Bytes()
|
||||
if len(packetBytes) < 32+1+8+2 {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
var rawHeader [16]byte
|
||||
i.udpMasterCipher.Decrypt(rawHeader[:], packetBytes[:16])
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := i.udpSessions.GetOrCreate(sessionID)
|
||||
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
b.Release()
|
||||
continue
|
||||
}
|
||||
|
||||
var userPSK []byte
|
||||
var currentUser *protocol.MemoryUser
|
||||
sessionItem.Lock()
|
||||
currentUser = sessionItem.User
|
||||
userPSK = sessionItem.UserPSK
|
||||
sessionItem.Unlock()
|
||||
|
||||
if currentUser == nil {
|
||||
// Decrypt EIH
|
||||
decryptedHash := DecryptUDPEIH(i.udpMasterCipher, rawHeader[:], packetBytes[16:32])
|
||||
|
||||
user, ok := i.usersByHash.Load(decryptedHash)
|
||||
sessionItem, decoded, user, err := i.udpCodec.DecodePacket(b.Bytes(), func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool) {
|
||||
u, ok := i.usersByHash.Load(hash)
|
||||
if !ok {
|
||||
b.Release()
|
||||
continue
|
||||
return nil, nil, false
|
||||
}
|
||||
currentUser = user
|
||||
userPSK = user.Account.(*MemoryAccount).Key
|
||||
}
|
||||
|
||||
decoded, err := sessionItem.DecryptAESPayload(i.method, userPSK, sessionID, packetID, rawHeader[:], packetBytes[32:])
|
||||
return u, u.Account.(*MemoryAccount).Key, true
|
||||
})
|
||||
b.Release()
|
||||
if err != nil {
|
||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
||||
continue
|
||||
}
|
||||
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = currentUser
|
||||
sessionItem.UserPSK = userPSK
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
} else {
|
||||
userPSK := user.Account.(*MemoryAccount).Key
|
||||
var err error
|
||||
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
|
||||
return i.udpCodec.EncodeServerPacket(decoded.SessionID, userPSK, replyDest, payload)
|
||||
})
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -356,7 +310,3 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (i *MultiUserInbound) encodeServerUDPPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return i.udpSessions.EncodeServerPacket(i.method, userPSK, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
@@ -243,16 +243,14 @@ func (i *RelayInbound) processUDP(ctx context.Context, conn stat.Connection, dis
|
||||
dest.Network = net.Network_UDP
|
||||
|
||||
sessionItem := i.udpSessions.GetOrCreate(sessionID)
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.Lock()
|
||||
if sessionItem.User == nil {
|
||||
sessionItem.User = &protocol.MemoryUser{
|
||||
Email: targetDest.email,
|
||||
Level: targetDest.level,
|
||||
}
|
||||
sessionItem.User = &protocol.MemoryUser{
|
||||
Email: targetDest.email,
|
||||
Level: targetDest.level,
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
sessionItem.Unlock()
|
||||
link := sessionItem.link.Load()
|
||||
if link != nil {
|
||||
sessionItem.UpdateConn(conn)
|
||||
|
||||
@@ -30,7 +30,7 @@ type Outbound struct {
|
||||
method *CipherMethod
|
||||
pskList [][]byte
|
||||
finalPSK []byte
|
||||
udpCodec *UDPPacketCodec
|
||||
udpCodec *UDPClientCodec
|
||||
policyManager policy.Manager
|
||||
}
|
||||
|
||||
@@ -50,9 +50,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Outbound, error) {
|
||||
}
|
||||
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
udpCodec, err := NewUDPPacketCodec(method, pskList)
|
||||
udpCodec, err := NewUDPClientCodec(method, pskList)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to create udp packet codec").Base(err)
|
||||
return nil, errors.New("failed to create udp client codec").Base(err)
|
||||
}
|
||||
|
||||
v := core.MustFromContext(ctx)
|
||||
|
||||
+292
-147
@@ -7,33 +7,78 @@ import (
|
||||
"io"
|
||||
"math"
|
||||
mrand "math/rand/v2"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
)
|
||||
|
||||
type UDPCodec struct {
|
||||
type UDPClientCodec struct {
|
||||
method *CipherMethod
|
||||
pskList [][]byte
|
||||
psk []byte
|
||||
blockCipher cipher.Block
|
||||
blockCiphers []cipher.Block
|
||||
chachaCipher cipher.AEAD
|
||||
}
|
||||
|
||||
func NewUDPClientCodec(method *CipherMethod, pskList [][]byte) (*UDPClientCodec, error) {
|
||||
if len(pskList) == 0 {
|
||||
return nil, errors.New("empty psk list")
|
||||
}
|
||||
if method.IsChaCha && len(pskList) > 1 {
|
||||
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
|
||||
}
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
c := &UDPClientCodec{
|
||||
method: method,
|
||||
pskList: pskList,
|
||||
psk: finalPSK,
|
||||
}
|
||||
var err error
|
||||
if method.IsChaCha {
|
||||
c.chachaCipher, err = method.NewUDPCipher(finalPSK)
|
||||
} else {
|
||||
c.blockCipher, err = method.NewBlock(finalPSK)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(pskList) > 1 {
|
||||
c.blockCiphers = make([]cipher.Block, len(pskList))
|
||||
for i, psk := range pskList {
|
||||
c.blockCiphers[i], err = method.NewBlock(psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPClientCodec, error) {
|
||||
return NewUDPClientCodec(method, pskList)
|
||||
}
|
||||
|
||||
type UDPServerCodec struct {
|
||||
method *CipherMethod
|
||||
psk []byte
|
||||
user *protocol.MemoryUser
|
||||
blockCipher cipher.Block
|
||||
chachaCipher cipher.AEAD
|
||||
sessions *UDPSessionManager
|
||||
}
|
||||
|
||||
type (
|
||||
UDPPacketCodec = UDPCodec
|
||||
UDPServerCodec = UDPCodec
|
||||
)
|
||||
|
||||
func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
|
||||
c := &UDPCodec{
|
||||
method: method,
|
||||
psk: psk,
|
||||
func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUser, sessionTimeout time.Duration) (*UDPServerCodec, error) {
|
||||
c := &UDPServerCodec{
|
||||
method: method,
|
||||
psk: psk,
|
||||
user: user,
|
||||
sessions: NewUDPSessionManager(sessionTimeout),
|
||||
}
|
||||
var err error
|
||||
if method.IsChaCha {
|
||||
@@ -47,46 +92,129 @@ func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPCodec, error) {
|
||||
if method.IsChaCha && len(pskList) > 1 {
|
||||
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
|
||||
}
|
||||
finalPSK := pskList[len(pskList)-1]
|
||||
c, err := newUDPCodec(method, finalPSK)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.pskList = pskList
|
||||
if len(pskList) > 1 {
|
||||
c.blockCiphers = make([]cipher.Block, len(pskList))
|
||||
for i, psk := range pskList {
|
||||
c.blockCiphers[i], err = method.NewBlock(psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewUDPServerCodec(method *CipherMethod, psk []byte, sessionTimeout time.Duration) (*UDPCodec, error) {
|
||||
c, err := newUDPCodec(method, psk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.sessions = NewUDPSessionManager(sessionTimeout)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) Sessions() *UDPSessionManager {
|
||||
func (c *UDPServerCodec) Sessions() *UDPSessionManager {
|
||||
return c.sessions
|
||||
}
|
||||
|
||||
func (c *UDPCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
func (c *UDPServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
if c.sessions == nil {
|
||||
return nil
|
||||
}
|
||||
return c.sessions.GetOrCreate(sessionID)
|
||||
return c.sessions.Get(sessionID)
|
||||
}
|
||||
|
||||
type UDPMultiServerCodec struct {
|
||||
method *CipherMethod
|
||||
masterPSK []byte
|
||||
masterBlock cipher.Block
|
||||
sessions *UDPSessionManager
|
||||
}
|
||||
|
||||
func NewUDPMultiServerCodec(method *CipherMethod, masterPSK []byte, sessionTimeout time.Duration) (*UDPMultiServerCodec, error) {
|
||||
if method.IsChaCha {
|
||||
return nil, errors.New("multi-user is not supported for chacha20-poly1305")
|
||||
}
|
||||
masterBlock, err := method.NewBlock(masterPSK)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UDPMultiServerCodec{
|
||||
method: method,
|
||||
masterPSK: masterPSK,
|
||||
masterBlock: masterBlock,
|
||||
sessions: NewUDPSessionManager(sessionTimeout),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) Sessions() *UDPSessionManager {
|
||||
return c.sessions
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||
if c.sessions == nil {
|
||||
return nil
|
||||
}
|
||||
return c.sessions.Get(sessionID)
|
||||
}
|
||||
|
||||
type UserLookupFunc func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool)
|
||||
|
||||
func (c *UDPMultiServerCodec) DecodePacket(data []byte, userLookup UserLookupFunc) (*ServerUDPSession, DecodedUDPPacket, *protocol.MemoryUser, error) {
|
||||
if len(data) < 2*AESBlockSize+AEADTagSize+RequestHeaderFixedChunkLength {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketTooShort
|
||||
}
|
||||
|
||||
var rawHeader [16]byte
|
||||
c.masterBlock.Decrypt(rawHeader[:], data[:16])
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := c.sessions.Get(sessionID)
|
||||
var currentUser *protocol.MemoryUser
|
||||
var userPSK []byte
|
||||
var bodyAead cipher.AEAD
|
||||
|
||||
if sessionItem != nil {
|
||||
sessionItem.Lock()
|
||||
currentUser = sessionItem.User
|
||||
userPSK = sessionItem.UserPSK
|
||||
bodyAead = sessionItem.clientBodyCipher
|
||||
sessionItem.Unlock()
|
||||
|
||||
if currentUser != nil {
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketIdNotUnique
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if currentUser == nil {
|
||||
decryptedHash := DecryptUDPEIH(c.masterBlock, rawHeader[:], data[16:32])
|
||||
user, psk, ok := userLookup(decryptedHash)
|
||||
if !ok {
|
||||
return nil, DecodedUDPPacket{}, nil, errors.New("user not found")
|
||||
}
|
||||
currentUser = user
|
||||
userPSK = psk
|
||||
}
|
||||
|
||||
if bodyAead == nil {
|
||||
bodyKey := DeriveSessionSubKey(userPSK, rawHeader[:8], c.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = c.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[32:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
||||
if err != nil {
|
||||
return nil, DecodedUDPPacket{}, nil, err
|
||||
}
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrBadHeaderType
|
||||
}
|
||||
|
||||
if sessionItem == nil {
|
||||
sessionItem = c.sessions.GetOrCreate(sessionID)
|
||||
}
|
||||
if !sessionItem.Commit(packetID, bodyAead, currentUser, userPSK) {
|
||||
return nil, DecodedUDPPacket{}, nil, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return sessionItem, decoded, currentUser, nil
|
||||
}
|
||||
|
||||
func (c *UDPMultiServerCodec) EncodeServerPacket(clientSessionID uint64, userPSK []byte, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return c.sessions.EncodeServerPacket(c.method, userPSK, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
type DecodedUDPPacket struct {
|
||||
@@ -193,44 +321,42 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUDPPacket, error) {
|
||||
if len(data) < PacketMinimalHeaderSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
if c.method.IsChaCha {
|
||||
if len(data) < PacketNonceSize+AEADTagSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
nonce := data[:PacketNonceSize]
|
||||
ciphertext := data[PacketNonceSize:]
|
||||
plain, err := c.chachaCipher.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||
}
|
||||
if len(plain) < 16+1+8+2 {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
sessionID := binary.BigEndian.Uint64(plain[:8])
|
||||
packetID := binary.BigEndian.Uint64(plain[8:16])
|
||||
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
|
||||
sessionItem.AddPacketID(packetID)
|
||||
return decoded, nil
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.Commit(packetID, nil, c.user, c.psk) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
return sessionItem, decoded, nil
|
||||
}
|
||||
|
||||
// AES mode
|
||||
@@ -239,49 +365,48 @@ func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
sessionItem := c.sessions.Get(sessionID)
|
||||
var bodyAead cipher.AEAD
|
||||
if sessionItem != nil {
|
||||
if !sessionItem.CheckPacketID(packetID) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
sessionItem.Lock()
|
||||
bodyAead = sessionItem.clientBodyCipher
|
||||
sessionItem.Unlock()
|
||||
}
|
||||
|
||||
return sessionItem.DecryptAESPayload(c.method, c.psk, sessionID, packetID, rawHeader[:], data[16:])
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) DecryptAESPayload(method *CipherMethod, psk []byte, sessionID, packetID uint64, rawHeader, bodyCipher []byte) (DecodedUDPPacket, error) {
|
||||
bodyAead := s.clientBodyCipher
|
||||
isNewCipher := false
|
||||
if bodyAead == nil {
|
||||
bodyKey := DeriveSessionSubKey(psk, rawHeader[:8], method.KeySaltLength)
|
||||
bodyKey := DeriveSessionSubKey(c.psk, rawHeader[:8], c.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = method.NewAEAD(bodyKey)
|
||||
bodyAead, err = c.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
isNewCipher = true
|
||||
}
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[16:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
return nil, DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
|
||||
s.AddPacketID(packetID)
|
||||
|
||||
if isNewCipher {
|
||||
s.clientBodyCipher = bodyAead
|
||||
if sessionItem == nil {
|
||||
sessionItem = c.sessions.GetOrCreate(sessionID)
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
if !sessionItem.Commit(packetID, bodyAead, c.user, c.psk) {
|
||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
return sessionItem, decoded, nil
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error {
|
||||
@@ -303,6 +428,9 @@ func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) e
|
||||
if method.IsChaCha {
|
||||
var err error
|
||||
s.serverChaCha, err = method.NewUDPCipher(psk)
|
||||
if err != nil {
|
||||
s.ServerSessionID = 0
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -387,11 +515,12 @@ func (s *ServerUDPSession) EncodeServerPacket(method *CipherMethod, clientSessio
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *UDPCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
func (c *UDPServerCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||
return c.sessions.EncodeServerPacket(c.method, c.psk, clientSessionID, dest, payload)
|
||||
}
|
||||
|
||||
type serverSessionState struct {
|
||||
sync.Mutex
|
||||
sessionID uint64
|
||||
window *SlidingWindow
|
||||
cipher cipher.AEAD
|
||||
@@ -399,21 +528,24 @@ type serverSessionState struct {
|
||||
}
|
||||
|
||||
func (st *serverSessionState) check(packetID uint64) bool {
|
||||
if st.window == nil {
|
||||
st.window = new(SlidingWindow)
|
||||
}
|
||||
st.Lock()
|
||||
defer st.Unlock()
|
||||
return st.window.Check(packetID)
|
||||
}
|
||||
|
||||
func (st *serverSessionState) add(packetID uint64) {
|
||||
if st.window == nil {
|
||||
st.window = new(SlidingWindow)
|
||||
func (st *serverSessionState) commit(packetID uint64, now int64) bool {
|
||||
st.Lock()
|
||||
defer st.Unlock()
|
||||
if !st.window.CheckAndAdd(packetID) {
|
||||
return false
|
||||
}
|
||||
st.window.Add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
return true
|
||||
}
|
||||
|
||||
type ClientUDPSession struct {
|
||||
codec *UDPCodec
|
||||
mu sync.Mutex
|
||||
codec *UDPClientCodec
|
||||
clientSessionID uint64
|
||||
nextPacketID atomic.Uint64
|
||||
clientBodyCipher cipher.AEAD
|
||||
@@ -421,7 +553,7 @@ type ClientUDPSession struct {
|
||||
old atomic.Pointer[serverSessionState]
|
||||
}
|
||||
|
||||
func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
var sessID [8]byte
|
||||
if _, err := io.ReadFull(rand.Reader, sessID[:]); err != nil {
|
||||
return nil, err
|
||||
@@ -446,51 +578,43 @@ func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ClientUDPSession) getServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||
cur := s.current.Load()
|
||||
if cur != nil && cur.sessionID == sessionID {
|
||||
func (s *ClientUDPSession) findServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||
if cur := s.current.Load(); cur != nil && cur.sessionID == sessionID {
|
||||
return cur, nil
|
||||
}
|
||||
|
||||
old := s.old.Load()
|
||||
if old != nil && old.sessionID == sessionID {
|
||||
if now-old.lastSeen.Load() > 60 {
|
||||
s.old.CompareAndSwap(old, nil)
|
||||
return nil, errors.New("old server session expired")
|
||||
if old := s.old.Load(); old != nil {
|
||||
if old.sessionID == sessionID {
|
||||
if now-old.lastSeen.Load() > 60 {
|
||||
return nil, errors.New("old server session expired")
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
|
||||
// New server session:
|
||||
// Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
|
||||
if old != nil && now-old.lastSeen.Load() < 60 {
|
||||
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
|
||||
}
|
||||
|
||||
var bodyAead cipher.AEAD
|
||||
if !s.codec.method.IsChaCha {
|
||||
var sessBytes [8]byte
|
||||
binary.BigEndian.PutUint64(sessBytes[:], sessionID)
|
||||
bodyKey := DeriveSessionSubKey(s.codec.psk, sessBytes[:], s.codec.method.KeySaltLength)
|
||||
var err error
|
||||
bodyAead, err = s.codec.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
|
||||
if now-old.lastSeen.Load() < 60 {
|
||||
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *ClientUDPSession) transitionServerSession(sessionID uint64, cipher cipher.AEAD, now int64) (*serverSessionState, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if st, err := s.findServerSession(sessionID, now); st != nil || err != nil {
|
||||
return st, err
|
||||
}
|
||||
|
||||
newState := &serverSessionState{
|
||||
sessionID: sessionID,
|
||||
cipher: bodyAead,
|
||||
window: new(SlidingWindow),
|
||||
cipher: cipher,
|
||||
}
|
||||
newState.lastSeen.Store(now)
|
||||
|
||||
if cur == nil {
|
||||
s.current.CompareAndSwap(nil, newState)
|
||||
return s.current.Load(), nil
|
||||
if cur := s.current.Load(); cur != nil {
|
||||
s.old.Store(cur)
|
||||
}
|
||||
|
||||
s.old.Store(cur)
|
||||
s.current.Store(newState)
|
||||
return newState, nil
|
||||
}
|
||||
@@ -505,7 +629,7 @@ func (s *ClientUDPSession) EncodePacket(dest net.Destination, payload []byte) (*
|
||||
|
||||
var paddingLen int
|
||||
if dest.Port == 53 && len(payload) < MaxPaddingLength {
|
||||
paddingLen = mrand.IntN(MaxPaddingLength) + 1
|
||||
paddingLen = mrand.IntN(MaxPaddingLength-len(payload)) + 1
|
||||
}
|
||||
|
||||
addrPortLen := AddrPortLength(dest)
|
||||
@@ -620,6 +744,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
||||
if s.codec.method.IsChaCha {
|
||||
if len(data) < PacketNonceSize+AEADTagSize {
|
||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||
@@ -637,20 +763,10 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(plain[:8])
|
||||
packetID := binary.BigEndian.Uint64(plain[8:16])
|
||||
|
||||
now := time.Now().Unix()
|
||||
st, err := s.getServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeServer {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
@@ -658,8 +774,20 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||
}
|
||||
|
||||
st.add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
st, err := s.findServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if st == nil {
|
||||
st, err = s.transitionServerSession(sessionID, nil, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if !st.commit(packetID, now) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
@@ -670,19 +798,29 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||
|
||||
now := time.Now().Unix()
|
||||
st, err := s.getServerSession(sessionID, now)
|
||||
st, err := s.findServerSession(sessionID, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
|
||||
var bodyAead cipher.AEAD
|
||||
if st != nil {
|
||||
if !st.check(packetID) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
bodyAead = st.cipher
|
||||
} else {
|
||||
var sessBytes [8]byte
|
||||
binary.BigEndian.PutUint64(sessBytes[:], sessionID)
|
||||
bodyKey := DeriveSessionSubKey(s.codec.psk, sessBytes[:], s.codec.method.KeySaltLength)
|
||||
bodyAead, err = s.codec.method.NewAEAD(bodyKey)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
bodyAead := st.cipher
|
||||
|
||||
bodyNonce := rawHeader[4:16]
|
||||
bodyCipher := data[16:]
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, data[16:], nil)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||
}
|
||||
@@ -691,7 +829,6 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
|
||||
if decoded.HeaderType != HeaderTypeServer {
|
||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||
}
|
||||
@@ -699,8 +836,16 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||
}
|
||||
|
||||
st.add(packetID)
|
||||
st.lastSeen.Store(now)
|
||||
if st == nil {
|
||||
st, err = s.transitionServerSession(sessionID, bodyAead, now)
|
||||
if err != nil {
|
||||
return DecodedUDPPacket{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if !st.commit(packetID, now) {
|
||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||
}
|
||||
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
// Verify downstream destination can decode both packets
|
||||
method, err := GetCipherMethod(MethodAES128GCM)
|
||||
common.Must(err)
|
||||
destCodec, err := NewUDPServerCodec(method, destKey, 300*time.Second)
|
||||
destCodec, err := NewUDPServerCodec(method, destKey, nil, 300*time.Second)
|
||||
common.Must(err)
|
||||
|
||||
mu.Lock()
|
||||
@@ -202,7 +202,8 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
t.Fatalf("expected 2 received packets at destination, got %d", len(pkts))
|
||||
}
|
||||
|
||||
dec1, err := destCodec.DecodePacket(pkts[0])
|
||||
dec1, dec2 := DecodedUDPPacket{}, DecodedUDPPacket{}
|
||||
_, dec1, err = destCodec.DecodePacket(pkts[0])
|
||||
if err != nil {
|
||||
t.Fatalf("dest failed to decode packet 1: %v", err)
|
||||
}
|
||||
@@ -210,7 +211,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
||||
t.Fatalf("dec1 mismatch: sess=%x, pktID=%d, payload=%s", dec1.SessionID, dec1.PacketID, string(dec1.Payload))
|
||||
}
|
||||
|
||||
dec2, err := destCodec.DecodePacket(pkts[1])
|
||||
_, dec2, err = destCodec.DecodePacket(pkts[1])
|
||||
if err != nil {
|
||||
t.Fatalf("dest failed to decode packet 2: %v", err)
|
||||
}
|
||||
|
||||
@@ -100,19 +100,27 @@ type ServerUDPSession struct {
|
||||
func (s *ServerUDPSession) CheckPacketID(packetID uint64) bool {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.Window == nil {
|
||||
s.Window = new(SlidingWindow)
|
||||
}
|
||||
return s.Window.Check(packetID)
|
||||
}
|
||||
|
||||
func (s *ServerUDPSession) AddPacketID(packetID uint64) {
|
||||
func (s *ServerUDPSession) Commit(packetID uint64, bodyAead cipher.AEAD, user *protocol.MemoryUser, userPSK []byte) bool {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.Window == nil {
|
||||
s.Window = new(SlidingWindow)
|
||||
if s.User != nil && user != nil && s.User != user {
|
||||
return false
|
||||
}
|
||||
s.Window.Add(packetID)
|
||||
if !s.Window.CheckAndAdd(packetID) {
|
||||
return false
|
||||
}
|
||||
if s.clientBodyCipher == nil && bodyAead != nil {
|
||||
s.clientBodyCipher = bodyAead
|
||||
}
|
||||
if s.User == nil && user != nil {
|
||||
s.User = user
|
||||
s.UserPSK = userPSK
|
||||
}
|
||||
s.LastActive.Store(time.Now().Unix())
|
||||
return true
|
||||
}
|
||||
|
||||
type UDPSessionManager struct {
|
||||
@@ -128,6 +136,13 @@ func NewUDPSessionManager(timeout time.Duration) *UDPSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
func (m *UDPSessionManager) Get(sessionID uint64) *ServerUDPSession {
|
||||
if s, ok := m.sessions.Load(sessionID); ok {
|
||||
return s
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||
now := time.Now().Unix()
|
||||
if s, ok := m.sessions.Load(sessionID); ok {
|
||||
@@ -137,6 +152,7 @@ func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||
|
||||
s := &ServerUDPSession{
|
||||
SessionID: sessionID,
|
||||
Window: new(SlidingWindow),
|
||||
manager: m,
|
||||
}
|
||||
s.LastActive.Store(now)
|
||||
|
||||
@@ -63,10 +63,16 @@ func (s *ServerUDPSession) EnsureLink(
|
||||
|
||||
s.currentConn.Store(conn)
|
||||
|
||||
sessCtx, cancel := context.WithCancel(ctx)
|
||||
// UDP Session might travel across multiple connections
|
||||
// don't bind its lifetime to a parent context
|
||||
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
inbound := session.InboundFromContext(sessCtx)
|
||||
if inbound != nil && s.User != nil {
|
||||
inbound.User = s.User
|
||||
if inbound != nil {
|
||||
newInbound := *inbound
|
||||
if s.User != nil {
|
||||
newInbound.User = s.User
|
||||
}
|
||||
sessCtx = session.ContextWithInbound(sessCtx, &newInbound)
|
||||
}
|
||||
var email string
|
||||
var level uint32
|
||||
|
||||
@@ -265,7 +265,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
|
||||
clientCodec, err := NewUDPPacketCodec(method, [][]byte{psk})
|
||||
common.Must(err)
|
||||
serverCodec, err := NewUDPServerCodec(method, psk, time.Minute)
|
||||
serverCodec, err := NewUDPServerCodec(method, psk, nil, time.Minute)
|
||||
common.Must(err)
|
||||
|
||||
session, err := clientCodec.NewClientSession()
|
||||
@@ -277,7 +277,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
rawCopy := make([]byte, pktBuf.Len())
|
||||
copy(rawCopy, pktBuf.Bytes())
|
||||
|
||||
decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
|
||||
_, decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
|
||||
common.Must(err)
|
||||
|
||||
if decoded.HeaderType != HeaderTypeClient {
|
||||
@@ -291,7 +291,7 @@ func TestUDPCodec(t *testing.T) {
|
||||
}
|
||||
|
||||
// Replay same packet wire bytes should fail with ErrPacketIdNotUnique
|
||||
_, err = serverCodec.DecodePacket(rawCopy)
|
||||
_, _, err = serverCodec.DecodePacket(rawCopy)
|
||||
if err != ErrPacketIdNotUnique {
|
||||
t.Fatalf("expected ErrPacketIdNotUnique on replay, got: %v", err)
|
||||
}
|
||||
@@ -427,7 +427,7 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
|
||||
|
||||
clientCodec, err := NewUDPPacketCodec(method, [][]byte{rawKey})
|
||||
common.Must(err)
|
||||
serverCodec, err := NewUDPServerCodec(method, rawKey, time.Minute)
|
||||
serverCodec, err := NewUDPServerCodec(method, rawKey, nil, time.Minute)
|
||||
common.Must(err)
|
||||
|
||||
session, err := clientCodec.NewClientSession()
|
||||
@@ -448,9 +448,9 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
|
||||
defer pkt2.Release()
|
||||
|
||||
// Server decodes both
|
||||
dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
|
||||
_, dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
|
||||
common.Must(err)
|
||||
dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
|
||||
_, dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
|
||||
common.Must(err)
|
||||
|
||||
if dec1.SessionID != session.ClientSessionID() || dec2.SessionID != session.ClientSessionID() {
|
||||
|
||||
@@ -337,7 +337,7 @@ func WriteTCPRequest(w io.Writer, method *CipherMethod, pskList [][]byte, dest n
|
||||
addrPortLen := AddrPortLength(dest)
|
||||
varHeaderLen := addrPortLen + 2 + paddingLen + payloadLen
|
||||
|
||||
totalHandshakeLen := int32(method.KeySaltLength + len(pskList)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||
totalHandshakeLen := int32(method.KeySaltLength + (len(pskList)-1)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||
handshakeBuf := buf.NewWithSize(totalHandshakeLen)
|
||||
defer handshakeBuf.Release()
|
||||
|
||||
|
||||
@@ -255,10 +255,11 @@ func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig
|
||||
}
|
||||
ips, err := LookupForIP(dest.Address.Domain(), finalStrategy, src)
|
||||
if err != nil {
|
||||
errors.LogErrorInner(ctx, err, "failed to resolve ip")
|
||||
if sockopt.DomainStrategy.ForceIP() {
|
||||
errors.LogErrorInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain())
|
||||
return nil, err
|
||||
}
|
||||
errors.LogInfoInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain(), ", but continue due to USEIP* strategy")
|
||||
} else if sockopt.HappyEyeballs == nil || sockopt.HappyEyeballs.TryDelayMs == 0 || sockopt.HappyEyeballs.MaxConcurrentTry == 0 || len(ips) < 2 || len(sockopt.DialerProxy) > 0 || dest.Network != net.Network_TCP {
|
||||
dest.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
||||
errors.LogInfo(ctx, "replace destination with "+dest.String())
|
||||
|
||||
@@ -175,7 +175,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
c.decref(msg, addr)
|
||||
return
|
||||
}
|
||||
if TypeMap_[decoded[0]&3] != uint16(msg.Questions[0].Type) || (decoded[8]&0x3F != 3 && decoded[8]&0x3F != 8) || (decoded[8]&0x3F == 3 && n < 9+3+1) || (decoded[8]&0x3F == 8 && n != 9+8) {
|
||||
kind := decoded[8] & 0x3F
|
||||
fragmented := decoded[8]&0xC0 == 0xC0
|
||||
dataOffset := 9 + 3
|
||||
if fragmented {
|
||||
dataOffset += 3
|
||||
}
|
||||
if TypeMap_[decoded[0]&3] != uint16(msg.Questions[0].Type) ||
|
||||
(kind != 3 && kind != 8) || (kind == 3 && n <= dataOffset) || (kind == 8 && n != 9+8) {
|
||||
msg.Header.Response = true
|
||||
msg.Header.Authoritative = true
|
||||
msg.Header.RCode = dnsmessage.RCodeSuccess
|
||||
@@ -201,14 +208,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
c.decref(msg, addr)
|
||||
}
|
||||
|
||||
if decoded[8]&0x3F == 8 {
|
||||
if kind == 8 {
|
||||
return
|
||||
}
|
||||
p := pool4K.Get().([]byte)
|
||||
p = p[:0]
|
||||
if decoded[8]&0xC0 == 0xC0 {
|
||||
if fragmented {
|
||||
out := pool4K.Get().([]byte)
|
||||
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[15:n])
|
||||
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[dataOffset:n])
|
||||
pool4K.Put(p[:cap(p)])
|
||||
if n > 0 {
|
||||
p = out[:n]
|
||||
@@ -217,7 +224,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
p = append(p, decoded[12:n]...)
|
||||
p = append(p, decoded[dataOffset:n]...)
|
||||
}
|
||||
select {
|
||||
case <-c.closeCh:
|
||||
|
||||
@@ -28,7 +28,11 @@ func (s *Proxy) Proxy(w http.ResponseWriter, r *ProxyRequest) (*Conn, error) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
if ok {
|
||||
return newProxiedConn(streamer.HTTPStream()), nil
|
||||
str, err := streamer.HTTPStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newProxiedConn(str), nil
|
||||
}
|
||||
controller := http.NewResponseController(w)
|
||||
if err := controller.Flush(); err != nil {
|
||||
|
||||
@@ -231,7 +231,11 @@ func TestDialWarpHTTP3(t *testing.T) {
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
str := w.(http3.HTTPStreamer).HTTPStream()
|
||||
str, err := w.(http3.HTTPStreamer).HTTPStream()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
go func() { capsules <- readCapsuleTypes(str, nil) }()
|
||||
b, err := str.ReceiveDatagram(r.Context())
|
||||
if err != nil {
|
||||
|
||||
@@ -1,266 +0,0 @@
|
||||
# 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** |
|
||||
+183
-201
@@ -32,7 +32,10 @@ type serviceTransport struct {
|
||||
stall time.Duration
|
||||
}
|
||||
|
||||
// Cancel stalled requests, not long transfers that continue to make progress.
|
||||
// RoundTrip ends a request that stands still for t.stall, with no answer that
|
||||
// long after its body went out or no byte of either body, but not one that just
|
||||
// runs long: a large object on a slow link takes minutes and is fine as long as
|
||||
// its bytes move
|
||||
func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
next := t.plain
|
||||
if r.URL.Scheme == "https" {
|
||||
@@ -40,46 +43,29 @@ func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancelCause(r.Context())
|
||||
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)
|
||||
}
|
||||
}
|
||||
timer := time.AfterFunc(t.stall, func() { cancel(errStalled) })
|
||||
alive := func() { timer.Reset(t.stall) }
|
||||
end := func() {
|
||||
timerMu.Lock()
|
||||
ended = true
|
||||
timer.Stop()
|
||||
timerMu.Unlock()
|
||||
cancel(nil)
|
||||
}
|
||||
r = r.WithContext(ctx)
|
||||
// Clone before setting defaults: the caller owns the original headers.
|
||||
// the headers of chrome as with XHTTP and DoH, net/http and http3 would send
|
||||
// their own user agent after a hello of chrome
|
||||
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, upload: true}
|
||||
r.Body = &progressBody{ReadCloser: r.Body, alive: alive}
|
||||
}
|
||||
// Rewinds performed by the transport must also reset the stall timer.
|
||||
// a body sent again by the transport itself, after a GOAWAY or on a reused
|
||||
// connection that failed, moves just the same
|
||||
if getBody := r.GetBody; getBody != nil {
|
||||
r.GetBody = func() (io.ReadCloser, error) {
|
||||
body, err := getBody()
|
||||
if err != nil || body == http.NoBody {
|
||||
return body, err
|
||||
}
|
||||
return &progressBody{ReadCloser: body, alive: alive, upload: true}, nil
|
||||
return &progressBody{ReadCloser: body, alive: alive}, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,18 +80,8 @@ func (t *serviceTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
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.
|
||||
// stalled returns errStalled for an error that the stall gave, which http2 reports
|
||||
// as a plain cancel
|
||||
func stalled(ctx context.Context, err error) error {
|
||||
if context.Cause(ctx) == errStalled {
|
||||
return errStalled
|
||||
@@ -115,19 +91,16 @@ func stalled(ctx context.Context, err error) error {
|
||||
|
||||
type progressBody struct {
|
||||
io.ReadCloser
|
||||
alive func()
|
||||
end func()
|
||||
upload bool
|
||||
alive func()
|
||||
end func()
|
||||
// ctx is that of the request, for the body of its response
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (b *progressBody) Read(p []byte) (int, error) {
|
||||
// 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)
|
||||
// http2 reads a request body up to 512 KiB at a time and sends it all before
|
||||
// the next read, which on a slow link could look like no progress
|
||||
n, err := b.ReadCloser.Read(p[:min(len(p), 16<<10)])
|
||||
if n > 0 {
|
||||
b.alive()
|
||||
}
|
||||
@@ -145,27 +118,29 @@ func (b *progressBody) Close() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// connCtx owns sockets; h1Hosts shares ALPN observations between clients.
|
||||
// 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
|
||||
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
|
||||
// Detect silent h2 loss unless XMUX supplies an explicit keepalive.
|
||||
h2Idle, h2PingWait = 1500 * time.Millisecond, 2500 * time.Millisecond
|
||||
h3KeepAlive time.Duration
|
||||
keepAlive = net.ChromeH2KeepAlivePeriod
|
||||
// h3 keeps alive only when asked to, see below
|
||||
h3KeepAlive time.Duration
|
||||
)
|
||||
if streamSettings != nil {
|
||||
tlsConfig = tls.ConfigFromStreamSettings(streamSettings)
|
||||
sockopt = streamSettings.SocketSettings
|
||||
fronting = streamSettings.Destination
|
||||
if config, ok := streamSettings.ProtocolSettings.(*Config); ok && config != nil && config.Xmux != nil {
|
||||
if config, ok := streamSettings.ProtocolSettings.(*Config); ok && config.Xmux != nil {
|
||||
switch period := config.Xmux.HKeepAlivePeriod; {
|
||||
case period > 0:
|
||||
h3KeepAlive = time.Duration(period) * time.Second
|
||||
h2Idle, h2PingWait = h3KeepAlive, 0
|
||||
keepAlive = time.Duration(period) * time.Second
|
||||
h3KeepAlive = keepAlive
|
||||
case period < 0:
|
||||
h2Idle, h2PingWait = 0, 0
|
||||
keepAlive = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -174,15 +149,9 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
}
|
||||
fingerprint := tls.GetFingerprint(tlsConfig.Fingerprint)
|
||||
|
||||
// A configured front replaces the address, not the transport network.
|
||||
// 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
|
||||
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)
|
||||
@@ -198,7 +167,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
|
||||
var conn net.Conn
|
||||
switch {
|
||||
case streamSettings == nil || streamSettings.FinalMask == nil:
|
||||
case streamSettings.FinalMask == nil:
|
||||
conn, err = internet.DialSystem(ctx, target, sockopt)
|
||||
case target.Network == net.Network_UDP:
|
||||
conn, err = streamSettings.FinalMask.DialUDP(ctx, target)
|
||||
@@ -208,13 +177,15 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
if err != nil {
|
||||
return nil, host, errors.New("failed to dial to dest").Base(err)
|
||||
}
|
||||
// HTTP/3 must close QUIC itself as well as its UDP socket.
|
||||
// h3 closes its QUIC connection instead, as the server never hears of a UDP
|
||||
// socket that closes
|
||||
if network == "udp" {
|
||||
return conn, 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
|
||||
// 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
|
||||
}
|
||||
|
||||
dialPlain := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
@@ -236,7 +207,8 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
} else {
|
||||
tlsConn = tls.UClient(conn, gotlsConfig, fingerprint)
|
||||
}
|
||||
// Bound the handshake independently of connection reuse.
|
||||
// the dial outlives the request that started it, and a handshake that hangs
|
||||
// would keep the one connection of the host to itself
|
||||
ctx, cancel := context.WithTimeout(ctx, stall)
|
||||
defer cancel()
|
||||
if err := tlsConn.(tls.Interface).HandshakeContext(ctx); err != nil {
|
||||
@@ -254,7 +226,7 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
MaxIdleConns: maxConns,
|
||||
MaxIdleConnsPerHost: maxConns,
|
||||
MaxConnsPerHost: connsPerHost,
|
||||
HTTP2: &http.HTTP2Config{SendPingTimeout: h2Idle, PingTimeout: h2PingWait},
|
||||
HTTP2: &http.HTTP2Config{SendPingTimeout: keepAlive},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,7 +237,9 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
if quicParams == nil {
|
||||
quicParams = &internet.QuicParams{BbrProfile: string(bbr.ProfileStandard)}
|
||||
}
|
||||
// QUIC idle timeout and connCtx bound unused connections.
|
||||
// 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
|
||||
quicConfig := &quic.Config{
|
||||
InitialStreamReceiveWindow: quicParams.InitStreamReceiveWindow,
|
||||
MaxStreamReceiveWindow: quicParams.MaxStreamReceiveWindow,
|
||||
@@ -284,16 +258,11 @@ 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)
|
||||
}
|
||||
|
||||
@@ -315,7 +284,8 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
return nil, errors.New("failed to dial to dest: unexpected ", reflect.TypeOf(c))
|
||||
}
|
||||
|
||||
// Set SNI before certificate pinning and ECH lookup.
|
||||
// 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
|
||||
gotlsConfig := tlsConfig.GetTLSConfig(tls.WithDestination(host))
|
||||
// it is for servers, and ChromeParrot refuses a config that has it
|
||||
gotlsConfig.GetCertificate = nil
|
||||
@@ -329,8 +299,8 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
pktConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
stopConn := context.AfterFunc(connCtx, func() { qconn.CloseWithError(quic.ApplicationErrorCode(http3.ErrCodeNoError), "") })
|
||||
context.AfterFunc(qconn.Context(), func() { stopConn(); tr.Close(); pktConn.Close() })
|
||||
stop := context.AfterFunc(connCtx, func() { qconn.CloseWithError(quic.ApplicationErrorCode(http3.ErrCodeNoError), "") })
|
||||
context.AfterFunc(qconn.Context(), func() { stop(); tr.Close(); pktConn.Close() })
|
||||
if quicParams.Congestion != "reno" {
|
||||
congestion.UseBBR(qconn, bbr.Profile(quicParams.BbrProfile))
|
||||
}
|
||||
@@ -354,7 +324,8 @@ func newServiceClient(connCtx context.Context, h1Hosts *sync.Map, streamSettings
|
||||
}
|
||||
}
|
||||
|
||||
// Closing the socket unregisters the owner-context callback.
|
||||
// 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
|
||||
type ctxConn struct {
|
||||
net.Conn
|
||||
stop func() bool
|
||||
@@ -365,7 +336,9 @@ func (c *ctxConn) Close() error {
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// Use one h2 connection per host, but allow parallel h1 connections.
|
||||
// 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
|
||||
type secureTransport struct {
|
||||
h2, h1 http.RoundTripper
|
||||
h1Hosts *sync.Map
|
||||
@@ -382,153 +355,162 @@ 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")
|
||||
|
||||
// XMUX selects a lease once, not repeatedly while looking for a connection.
|
||||
// Running references cover both the session and any response bodies still open.
|
||||
// connPool hands the sessions of a storage the connections of XMUX, each a
|
||||
// client of its own made by newClient
|
||||
type connPool struct {
|
||||
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
|
||||
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 {
|
||||
transport http.RoundTripper
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
stop func() bool
|
||||
next http.RoundTripper
|
||||
cancel context.CancelFunc
|
||||
|
||||
mu sync.Mutex
|
||||
inflight int
|
||||
closing bool
|
||||
}
|
||||
|
||||
func (c *poolConn) IsClosed() bool { return c.ctx.Err() != nil }
|
||||
func (c *poolConn) IsClosed() bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.closing
|
||||
}
|
||||
|
||||
func (c *poolConn) Close() error {
|
||||
c.cancel()
|
||||
c.stop()
|
||||
closeIdleTransport(c.transport)
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.closing = true
|
||||
if c.inflight == 0 {
|
||||
c.cancel()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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()
|
||||
func (c *poolConn) done() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.inflight--
|
||||
if c.closing && c.inflight == 0 {
|
||||
c.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
type sessionTransport struct {
|
||||
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) {
|
||||
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
|
||||
}
|
||||
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)
|
||||
}
|
||||
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()
|
||||
}
|
||||
c = p.mux.GetXmuxClient(r.Context())
|
||||
c.AddRunning()
|
||||
t.client = c
|
||||
}
|
||||
c.LeftRequests.Add(-1)
|
||||
c.AddRunning()
|
||||
p.mu.Unlock()
|
||||
resp, err := c.XmuxConn.(*poolConn).transport.RoundTrip(r)
|
||||
// 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.DoneRunning()
|
||||
c.done()
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &leasedBody{ReadCloser: resp.Body, release: sync.OnceFunc(c.DoneRunning)}
|
||||
resp.Body = &doneBody{ReadCloser: resp.Body, done: sync.OnceFunc(c.done)}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
type leasedBody struct {
|
||||
type doneBody struct {
|
||||
io.ReadCloser
|
||||
release func()
|
||||
done func()
|
||||
}
|
||||
|
||||
func (b *leasedBody) Close() error {
|
||||
defer b.release()
|
||||
return b.ReadCloser.Close()
|
||||
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
|
||||
}
|
||||
|
||||
func (t *sessionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
t.mu.Lock()
|
||||
if t.closed {
|
||||
t.mu.Unlock()
|
||||
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()
|
||||
}
|
||||
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
|
||||
}
|
||||
t.mu.Unlock()
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
func (t *sessionTransport) Close() {
|
||||
t.pool.mu.Lock()
|
||||
defer t.pool.mu.Unlock()
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.closed = true
|
||||
if t.client != nil {
|
||||
t.client.DoneRunning()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,31 +15,21 @@ 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 connWriter
|
||||
writer io.WriteCloser
|
||||
reader chunkReader
|
||||
onClose func()
|
||||
|
||||
readMu sync.Mutex
|
||||
readBuf []byte
|
||||
|
||||
readDeadline *pipeDeadline
|
||||
writeDeadline *pipeDeadline
|
||||
closing chan struct{}
|
||||
deadlineMu sync.Mutex
|
||||
readDeadline time.Time
|
||||
writeDeadline time.Time
|
||||
|
||||
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
|
||||
@@ -47,99 +37,54 @@ type chunkReader interface {
|
||||
Wake()
|
||||
}
|
||||
|
||||
func newConn(ctx context.Context, storage Storage, writePrefix, readPrefix string, p params, discard bool, onClose func()) *Conn {
|
||||
func newConn(ctx context.Context, storage Storage, writePrefix, readPrefix string, p params, 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, discard),
|
||||
reader: newWALReader(ctx, storage, readPrefix, p),
|
||||
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, fail := context.WithCancelCause(ctx)
|
||||
closing := make(chan struct{})
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
return &Conn{
|
||||
ctx: ctx,
|
||||
cancel: func() { fail(context.Canceled) },
|
||||
writer: newSlotWriter(ctx, fail, store, write, p),
|
||||
reader: newSlotReader(ctx, fail, store, read, p, first, closing),
|
||||
cancel: cancel,
|
||||
writer: newSlotWriter(ctx, store, write, p),
|
||||
reader: newSlotReader(ctx, store, read, p, first),
|
||||
onClose: onClose,
|
||||
|
||||
readDeadline: newPipeDeadline(),
|
||||
writeDeadline: newPipeDeadline(),
|
||||
closing: closing,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) Read(b []byte) (int, error) {
|
||||
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:
|
||||
if len(c.readBuf) == 0 {
|
||||
data, err := c.receive()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
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
|
||||
c.readBuf = data
|
||||
}
|
||||
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) {
|
||||
select {
|
||||
case <-c.closing:
|
||||
return nil, io.ErrClosedPipe
|
||||
default:
|
||||
deadline := c.getDeadline(true)
|
||||
if deadline.IsZero() {
|
||||
data, ok := <-c.reader.chunks()
|
||||
if !ok {
|
||||
return nil, c.reader.Err()
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
deadline := c.readDeadline.wait()
|
||||
select {
|
||||
case <-deadline:
|
||||
|
||||
if !time.Now().Before(deadline) {
|
||||
return nil, os.ErrDeadlineExceeded
|
||||
default:
|
||||
}
|
||||
timer := time.NewTimer(time.Until(deadline))
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case data, ok := <-c.reader.chunks():
|
||||
@@ -147,36 +92,17 @@ func (c *Conn) receive() ([]byte, error) {
|
||||
return nil, c.reader.Err()
|
||||
}
|
||||
return data, nil
|
||||
case <-deadline:
|
||||
case <-timer.C:
|
||||
return nil, os.ErrDeadlineExceeded
|
||||
case <-c.closing:
|
||||
return nil, io.ErrClosedPipe
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) Write(b []byte) (int, error) {
|
||||
select {
|
||||
case <-c.closing:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
}
|
||||
deadline := c.writeDeadline.wait()
|
||||
select {
|
||||
case <-deadline:
|
||||
if deadline := c.getDeadline(false); !deadline.IsZero() && !time.Now().Before(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 {
|
||||
n, err := c.writer.Write(b)
|
||||
if err == nil {
|
||||
c.reader.Wake()
|
||||
}
|
||||
return n, err
|
||||
@@ -184,70 +110,15 @@ func (c *Conn) Write(b []byte) (int, error) {
|
||||
|
||||
func (c *Conn) Close() error {
|
||||
c.closeOnce.Do(func() {
|
||||
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.closeErr = c.writer.Close()
|
||||
c.cancel()
|
||||
if c.onClose != nil {
|
||||
c.onClose()
|
||||
}
|
||||
})
|
||||
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
|
||||
}
|
||||
@@ -256,101 +127,33 @@ 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.readDeadline.set(t)
|
||||
c.writeDeadline.set(t)
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.readDeadline = t
|
||||
c.writeDeadline = t
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) SetReadDeadline(t time.Time) error {
|
||||
c.readDeadline.set(t)
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.readDeadline = t
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) SetWriteDeadline(t time.Time) error {
|
||||
c.writeDeadline.set(t)
|
||||
c.deadlineMu.Lock()
|
||||
defer c.deadlineMu.Unlock()
|
||||
c.writeDeadline = 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
|
||||
}
|
||||
}
|
||||
|
||||
+744
-885
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,99 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
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
@@ -0,0 +1,174 @@
|
||||
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,14 +31,10 @@ func (s *localStorage) resolve(name string) (string, error) {
|
||||
if clean == "/" {
|
||||
return "", errors.New("invalid object name: ", name)
|
||||
}
|
||||
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) {
|
||||
if strings.HasPrefix(path.Base(clean), tempPrefix) {
|
||||
return "", errors.New("reserved object name: ", name)
|
||||
}
|
||||
return filepath.Join(s.root, local), nil
|
||||
return filepath.Join(s.root, filepath.FromSlash(clean[1:])), nil
|
||||
}
|
||||
|
||||
func (s *localStorage) Put(ctx context.Context, name string, data []byte) error {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
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,7 +25,6 @@ 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 {
|
||||
@@ -46,7 +45,7 @@ func capped(value uint32, fallback, limit int) int {
|
||||
if value == 0 {
|
||||
return fallback
|
||||
}
|
||||
if uint64(value) > uint64(limit) {
|
||||
if int(value) > limit {
|
||||
return limit
|
||||
}
|
||||
return int(value)
|
||||
@@ -73,19 +72,18 @@ 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 {
|
||||
if c.Concurrency == 0 {
|
||||
p.concurrency = 64
|
||||
cc := *c
|
||||
if cc.Concurrency == 0 {
|
||||
cc.Concurrency = 64
|
||||
}
|
||||
// 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.FlushIntervalMs == 0 {
|
||||
cc.FlushIntervalMs = 10
|
||||
}
|
||||
if c.MaxPollIntervalMs == 0 {
|
||||
p.maxPollInterval = max(200*time.Millisecond, p.minPollInterval)
|
||||
if cc.MaxPollIntervalMs == 0 {
|
||||
cc.MaxPollIntervalMs = 200
|
||||
}
|
||||
c = &cc
|
||||
}
|
||||
return p
|
||||
return paramsFromConfig(c)
|
||||
}
|
||||
|
||||
@@ -55,9 +55,6 @@ 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")
|
||||
}
|
||||
@@ -111,8 +108,6 @@ 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 {
|
||||
@@ -147,7 +142,7 @@ func newS3Storage(streamSettings *internet.MemoryStreamConfig, c *Config) (*s3St
|
||||
}
|
||||
s := &s3Storage{
|
||||
s3Shared: &s3Shared{
|
||||
conns: newConnPool(c.Xmux, 0, newClient),
|
||||
conns: newConnPool(c.Xmux, newClient),
|
||||
base: *base,
|
||||
prefix: strings.TrimSuffix(c.RemoteFolder, "/") + "/",
|
||||
region: s3Region(c.S3.Region),
|
||||
@@ -283,10 +278,6 @@ 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 {
|
||||
@@ -328,29 +319,23 @@ 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(adapterMaxMetadataBody)
|
||||
limit := int64(maxSegmentBytes)
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
limit = adapterMaxErrorBody
|
||||
} else if method == http.MethodGet {
|
||||
if query.Get("list-type") != "" {
|
||||
limit = adapterMaxListResponse
|
||||
} else {
|
||||
limit = adapterObjectLimit(ctx)
|
||||
}
|
||||
limit = 64 << 10
|
||||
}
|
||||
payload, err := readAdapterBody(resp.Body, limit)
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
|
||||
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 {
|
||||
|
||||
+880
-688
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,77 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,926 @@
|
||||
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,27 +4,21 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"sync/atomic"
|
||||
|
||||
"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
|
||||
created time.Time // optional backend-supplied creation time on the local clock
|
||||
Name string
|
||||
Inline []byte
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -33,18 +27,22 @@ 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":
|
||||
storage, err := newLocalStorage(config.RemoteFolder)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ownedStorage(storage), nil
|
||||
return newLocalStorage(config.RemoteFolder)
|
||||
case "google-drive", "Google Drive":
|
||||
return sharedStorage(streamSettings, config, func() (Storage, error) {
|
||||
return newDriveStorage(streamSettings, config)
|
||||
@@ -62,7 +60,10 @@ func newStorage(streamSettings *internet.MemoryStreamConfig) (Storage, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func rawSessionStorage(storage Storage) Storage {
|
||||
// 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 {
|
||||
switch s := storage.(type) {
|
||||
case *driveStorage:
|
||||
return s.session()
|
||||
@@ -76,68 +77,49 @@ func rawSessionStorage(storage Storage) Storage {
|
||||
|
||||
var (
|
||||
sharedMu sync.Mutex
|
||||
shared = make(map[string]*storageOwner)
|
||||
shared = make(map[string]Storage)
|
||||
)
|
||||
|
||||
func shareKey(streamSettings *internet.MemoryStreamConfig, config *Config) string {
|
||||
// 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,
|
||||
}
|
||||
parts := []string{config.Service, config.RemoteFolder}
|
||||
if config.S3 != nil {
|
||||
profile.S3 = &S3Config{
|
||||
Endpoint: config.S3.Endpoint, Region: s3Region(config.S3.Region),
|
||||
Bucket: config.S3.Bucket, PathStyle: config.S3.PathStyle,
|
||||
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")
|
||||
}
|
||||
}
|
||||
parts = append(parts, config.Secrets...)
|
||||
if streamSettings != nil {
|
||||
profile.SecurityType = streamSettings.SecurityType
|
||||
profile.TLS = tls.ConfigFromStreamSettings(streamSettings)
|
||||
profile.Socket, profile.QUIC = streamSettings.SocketSettings, streamSettings.QuicParams
|
||||
parts = append(parts, streamSettings.SecurityType)
|
||||
if streamSettings.Destination != nil {
|
||||
profile.Destination = streamSettings.Destination.String()
|
||||
parts = append(parts, streamSettings.Destination.NetAddr())
|
||||
}
|
||||
}
|
||||
h := sha256.New()
|
||||
common.Must(json.NewEncoder(h).Encode(profile))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func resetSharedStorage() {
|
||||
sharedMu.Lock()
|
||||
shared = make(map[string]Storage)
|
||||
sharedMu.Unlock()
|
||||
}
|
||||
|
||||
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 owner, ok := shared[key]; ok && !owner.closed {
|
||||
owner.refs++
|
||||
return wrapStorageLease(owner, owner.root, false), nil
|
||||
if storage, ok := shared[key]; ok {
|
||||
return storage, nil
|
||||
}
|
||||
storage, err := build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner := &storageOwner{root: storage, key: key, refs: 1}
|
||||
shared[key] = owner
|
||||
return wrapStorageLease(owner, storage, false), nil
|
||||
shared[key] = storage
|
||||
return storage, nil
|
||||
}
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
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,10 +5,8 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -36,17 +34,13 @@ 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
|
||||
responseLimit int64
|
||||
presigned bool
|
||||
}
|
||||
|
||||
type retryTemplate struct {
|
||||
@@ -84,30 +78,8 @@ 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) {
|
||||
@@ -121,9 +93,6 @@ 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)
|
||||
@@ -145,7 +114,7 @@ func newTemplateStorage(streamSettings *internet.MemoryStreamConfig, config *Con
|
||||
client := newServiceClient(context.Background(), h1Hosts, streamSettings, driveTimeout, conc)
|
||||
return &templateStorage{
|
||||
templateShared: &templateShared{
|
||||
conns: newConnPool(config.Xmux, 0, func(connCtx context.Context) *http.Client {
|
||||
conns: newConnPool(config.Xmux, func(connCtx context.Context) *http.Client {
|
||||
return newServiceClient(connCtx, h1Hosts, streamSettings, driveTimeout, conc)
|
||||
}),
|
||||
tmpl: tmpl,
|
||||
@@ -170,28 +139,7 @@ func (s *templateStorage) session() Storage {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
const maxTemplateConcurrency = 256
|
||||
|
||||
func (s *templateStorage) baseVars() map[string]string {
|
||||
vars := map[string]string{"folder": s.folder}
|
||||
@@ -270,123 +218,51 @@ 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, permanentAdapterError(errors.New("unsupported auth type: ", s.tmpl.Auth.Type))
|
||||
return nil, errors.New("unsupported auth type: ", s.tmpl.Auth.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) accessToken(ctx context.Context) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
s.tokenMu.Lock()
|
||||
if s.tokenClosed {
|
||||
s.tokenMu.Unlock()
|
||||
return "", context.Canceled
|
||||
}
|
||||
defer s.tokenMu.Unlock()
|
||||
|
||||
if s.token != "" && time.Now().Before(s.tokenExpiry) {
|
||||
token := s.token
|
||||
s.tokenMu.Unlock()
|
||||
return token, nil
|
||||
return s.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()
|
||||
}
|
||||
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))
|
||||
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.Add(k, subst(v, vars))
|
||||
form[k] = subst(v, vars)
|
||||
if !first {
|
||||
values.WriteByte('&')
|
||||
}
|
||||
first = false
|
||||
values.WriteString(k)
|
||||
values.WriteByte('=')
|
||||
values.WriteString(form[k])
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.tmpl.Auth.TokenURL,
|
||||
strings.NewReader(form.Encode()))
|
||||
strings.NewReader(values.String()))
|
||||
if err != nil {
|
||||
return "", 0, permanentAdapterError(errors.New("failed to build the token request").Base(err))
|
||||
return "", 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 {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
return "", 0, errors.New("failed to fetch the token").Base(err)
|
||||
return "", errors.New("failed to fetch the token").Base(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
limit := int64(adapterMaxMetadataBody)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
limit = adapterMaxErrorBody
|
||||
}
|
||||
payload, err := readAdapterBody(resp.Body, limit)
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
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
|
||||
return "", errors.New("failed to read the token response").Base(err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
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
|
||||
return "", errors.New("the token endpoint answered ", resp.StatusCode, ": ", string(payload))
|
||||
}
|
||||
|
||||
path := s.tmpl.Auth.TokenPath
|
||||
@@ -395,7 +271,7 @@ func (s *templateStorage) fetchTemplateToken(ctx context.Context) (string, time.
|
||||
}
|
||||
token := jsonString(payload, path)
|
||||
if token == "" {
|
||||
return "", 0, permanentAdapterError(errors.New("the token response has no token at ", path))
|
||||
return "", errors.New("the token response has no token at ", path)
|
||||
}
|
||||
|
||||
lifetime := int64(3600)
|
||||
@@ -404,11 +280,12 @@ func (s *templateStorage) fetchTemplateToken(ctx context.Context) (string, time.
|
||||
lifetime = n
|
||||
}
|
||||
}
|
||||
lifetime = min(lifetime, int64(365*24*60*60))
|
||||
if lifetime > 60 {
|
||||
lifetime -= 60
|
||||
}
|
||||
return token, time.Duration(lifetime) * time.Second, nil
|
||||
s.token = token
|
||||
s.tokenExpiry = time.Now().Add(time.Duration(lifetime) * time.Second)
|
||||
return s.token, nil
|
||||
}
|
||||
|
||||
func (s *templateStorage) invalidateToken() {
|
||||
@@ -427,9 +304,6 @@ 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():
|
||||
@@ -446,12 +320,6 @@ 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
|
||||
}
|
||||
@@ -483,50 +351,20 @@ 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
|
||||
}
|
||||
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)
|
||||
payload, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
<-s.inflight
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
if isPermanentAdapterError(err) {
|
||||
return 0, nil, err
|
||||
if ctx.Err() != nil {
|
||||
return 0, nil, ctx.Err()
|
||||
}
|
||||
lastErr = errors.New("failed to read response").Base(err)
|
||||
continue
|
||||
@@ -559,14 +397,7 @@ 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)
|
||||
}
|
||||
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)
|
||||
return s.do(ctx, &opTemplate{Method: op.HrefMethod, URL: href, presigned: true}, vars, body)
|
||||
}
|
||||
|
||||
func (s *templateStorage) Put(ctx context.Context, name string, data []byte) error {
|
||||
@@ -607,9 +438,10 @@ func (s *templateStorage) Get(ctx context.Context, name string) ([]byte, error)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *templateStorage) deleteStoredObject(ctx context.Context, name string) error {
|
||||
func (s *templateStorage) Delete(ctx context.Context, name string) error {
|
||||
vars := s.baseVars()
|
||||
vars["name"] = name
|
||||
vars["name"] = s.storedName(name)
|
||||
|
||||
status, payload, err := s.run(ctx, &s.tmpl.Delete, vars, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -620,100 +452,53 @@ func (s *templateStorage) deleteStoredObject(ctx context.Context, name string) e
|
||||
return errors.New("delete of ", name, " answered ", status, ": ", string(payload))
|
||||
}
|
||||
|
||||
func (s *templateStorage) Delete(ctx context.Context, name string) error {
|
||||
flat := s.storedName(name)
|
||||
if !s.tmpl.Flatten {
|
||||
return s.deleteStoredObject(ctx, flat)
|
||||
}
|
||||
want := flat + flatSeparator
|
||||
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)
|
||||
}
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
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) {
|
||||
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)
|
||||
if !s.tmpl.Flatten {
|
||||
entries := make([]Entry, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
entries = append(entries, Entry{Name: m[1]})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
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) {
|
||||
return
|
||||
continue
|
||||
}
|
||||
name = strings.TrimPrefix(name, want)
|
||||
if name == "" {
|
||||
return
|
||||
rest := strings.TrimPrefix(name, want)
|
||||
if rest == "" {
|
||||
continue
|
||||
}
|
||||
if cut := strings.Index(name, flatSeparator); cut >= 0 {
|
||||
name = name[:cut]
|
||||
if cut := strings.Index(rest, flatSeparator); cut >= 0 {
|
||||
rest = rest[:cut]
|
||||
}
|
||||
if !seen[name] {
|
||||
seen[name] = true
|
||||
entries = append(entries, Entry{Name: name})
|
||||
if seen[rest] {
|
||||
continue
|
||||
}
|
||||
})
|
||||
return entries, err
|
||||
seen[rest] = true
|
||||
entries = append(entries, Entry{Name: rest})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func (s *templateStorage) Close() error {
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
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,13 +46,8 @@ type walWriter struct {
|
||||
storage Storage
|
||||
prefix string
|
||||
params
|
||||
sem chan struct{}
|
||||
wg sync.WaitGroup
|
||||
flushDone chan struct{}
|
||||
stop chan struct{}
|
||||
failed chan struct{}
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
sem chan struct{}
|
||||
wg sync.WaitGroup
|
||||
|
||||
mu sync.Mutex
|
||||
buf []byte
|
||||
@@ -65,65 +60,37 @@ 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),
|
||||
flushDone: make(chan struct{}),
|
||||
stop: make(chan struct{}),
|
||||
failed: make(chan struct{}),
|
||||
ctx: ctx,
|
||||
storage: storage,
|
||||
prefix: prefix,
|
||||
params: p,
|
||||
sem: make(chan struct{}, p.concurrency),
|
||||
}
|
||||
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 || w.ctx.Err() != nil {
|
||||
if w.closed {
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
if isClosedChan(deadline) || isClosedChan(closing) {
|
||||
return 0, errWriteStopped
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
w.buf = append(w.buf, p...)
|
||||
for len(w.buf) >= w.segmentBytes {
|
||||
if err := w.flushLocked(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return accepted, nil
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (w *walWriter) flushLoop() {
|
||||
defer close(w.flushDone)
|
||||
ticker := time.NewTicker(w.flushInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
@@ -131,12 +98,10 @@ 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(nil, w.stop)
|
||||
w.flushLocked()
|
||||
}
|
||||
done := w.closed || w.err != nil
|
||||
w.mu.Unlock()
|
||||
@@ -159,67 +124,13 @@ func (w *walWriter) readyToFlush() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
func (w *walWriter) flushLocked() error {
|
||||
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 {
|
||||
@@ -246,20 +157,18 @@ func (w *walWriter) flushLockedMode(deadline, closing <-chan struct{}, draining
|
||||
|
||||
func (w *walWriter) upload(seq int64, chunk []byte) {
|
||||
defer w.wg.Done()
|
||||
defer func() { <-w.sem }()
|
||||
if w.ctx.Err() != nil {
|
||||
|
||||
select {
|
||||
case w.sem <- struct{}{}:
|
||||
case <-w.ctx.Done():
|
||||
return
|
||||
}
|
||||
defer func() { <-w.sem }()
|
||||
|
||||
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 {
|
||||
if err := w.storage.Put(w.ctx, objectName(w.prefix, seq, segSuffix), chunk); 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)
|
||||
@@ -267,39 +176,27 @@ func (w *walWriter) upload(seq int64, chunk []byte) {
|
||||
}
|
||||
|
||||
func (w *walWriter) Close() error {
|
||||
w.closeOnce.Do(func() {
|
||||
w.mu.Lock()
|
||||
w.closed = true
|
||||
close(w.stop)
|
||||
w.mu.Lock()
|
||||
if w.closed {
|
||||
w.mu.Unlock()
|
||||
<-w.flushDone
|
||||
return nil
|
||||
}
|
||||
w.closed = true
|
||||
for len(w.buf) > 0 && w.err == nil {
|
||||
w.flushLocked()
|
||||
}
|
||||
w.mu.Unlock()
|
||||
|
||||
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.wg.Wait()
|
||||
|
||||
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
|
||||
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)
|
||||
}
|
||||
|
||||
type walReader struct {
|
||||
@@ -310,37 +207,26 @@ 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, discard bool) *walReader {
|
||||
func newWALReader(ctx context.Context, storage Storage, prefix string, p params) *walReader {
|
||||
r := &walReader{
|
||||
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()
|
||||
}()
|
||||
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),
|
||||
}
|
||||
go r.run()
|
||||
go r.discardLoop()
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -355,13 +241,7 @@ 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
|
||||
@@ -417,37 +297,36 @@ func (r *walReader) poll() (advanced, eof bool, err error) {
|
||||
return false, false, err
|
||||
}
|
||||
if len(listed) == 0 {
|
||||
return false, false, r.pendingError(false)
|
||||
return false, false, nil
|
||||
}
|
||||
|
||||
pending := make(map[int64]Entry, len(listed))
|
||||
observedThrough := int64(-1)
|
||||
ahead := false
|
||||
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.queueDiscard(r.prefix + "/" + entry.Name)
|
||||
r.discard(r.prefix + "/" + entry.Name)
|
||||
return advanced, false, errors.New("the peer could not store segment ", r.seq)
|
||||
}
|
||||
|
||||
@@ -460,9 +339,9 @@ func (r *walReader) poll() (advanced, eof bool, err error) {
|
||||
}
|
||||
|
||||
chunks, err := r.fetch(batch)
|
||||
if err != nil && (err != errNotFound || len(chunks) == 0) {
|
||||
if err != nil {
|
||||
if err == errNotFound {
|
||||
return advanced, false, r.pendingError(true)
|
||||
return advanced, false, nil
|
||||
}
|
||||
return advanced, false, err
|
||||
}
|
||||
@@ -473,34 +352,13 @@ 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.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)
|
||||
r.discard(r.prefix + "/" + batch[i].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)]
|
||||
@@ -509,7 +367,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.queueDiscard(r.prefix + "/" + entry.Name)
|
||||
r.discard(r.prefix + "/" + entry.Name)
|
||||
return nil, true
|
||||
}
|
||||
break
|
||||
@@ -537,51 +395,15 @@ func (r *walReader) fetch(batch []Entry) ([][]byte, error) {
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
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
|
||||
for i := range batch {
|
||||
if failures[i] != nil {
|
||||
return nil, failures[i]
|
||||
}
|
||||
}
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
func (r *walReader) queueDiscard(name string) {
|
||||
if !r.discard {
|
||||
// Downlink segments stay until the server collects the idle session after sessionTTL.
|
||||
return
|
||||
}
|
||||
func (r *walReader) discard(name string) {
|
||||
select {
|
||||
case r.discards <- name:
|
||||
default:
|
||||
@@ -589,9 +411,6 @@ func (r *walReader) queueDiscard(name string) {
|
||||
}
|
||||
|
||||
func (r *walReader) discardLoop() {
|
||||
if !r.discard {
|
||||
return
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
|
||||
@@ -601,11 +420,7 @@ func (r *walReader) discardLoop() {
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
case name := <-r.discards:
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
}
|
||||
sem <- struct{}{}
|
||||
wg.Add(1)
|
||||
go func(name string) {
|
||||
defer wg.Done()
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
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[:])
|
||||
}
|
||||
+225
-378
@@ -6,10 +6,10 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -27,6 +27,11 @@ const (
|
||||
downlinkDir = "s2c"
|
||||
)
|
||||
|
||||
const (
|
||||
spareCount = 2
|
||||
spareIdleStop = 10 * time.Minute
|
||||
)
|
||||
|
||||
func init() {
|
||||
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {
|
||||
return new(Config)
|
||||
@@ -48,17 +53,6 @@ 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
|
||||
@@ -70,49 +64,6 @@ func announceParts(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
|
||||
}
|
||||
@@ -126,9 +77,6 @@ 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")
|
||||
@@ -136,78 +84,185 @@ func streamConfig(streamSettings *internet.MemoryStreamConfig) (*Config, error)
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
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) {
|
||||
config, err := streamConfig(streamSettings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if streamSettings.Destination == nil && dest.Address != nil {
|
||||
front := dest
|
||||
front.Network = net.Network_TCP
|
||||
patched := *streamSettings
|
||||
patched.Destination = &front
|
||||
streamSettings = &patched
|
||||
p := paramsFromConfig(config)
|
||||
|
||||
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()
|
||||
if err != nil {
|
||||
storage.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
r := lazyRing(session, depth, ids[:len(ids)-1])
|
||||
}
|
||||
|
||||
if ok {
|
||||
warmSpares(streamSettings, config, p)
|
||||
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)
|
||||
|
||||
conn.publishWG.Go(func() {
|
||||
writer.first = make(chan []byte, 1)
|
||||
go func() {
|
||||
var first []byte
|
||||
select {
|
||||
case <-conn.ctx.Done():
|
||||
return
|
||||
case r.First = <-writer.first:
|
||||
case first = <-writer.first:
|
||||
case <-time.After(25 * time.Millisecond):
|
||||
}
|
||||
if conn.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
announce, _ := json.Marshal(r)
|
||||
if len(r.First) != 0 && len(announce) > driveInlineLimit {
|
||||
r.First = nil
|
||||
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
|
||||
}
|
||||
}
|
||||
// An announce failure surfaces as a connection error on the next Write/Read.
|
||||
if err := putDriveObject(conn.ctx, slots, ids[len(ids)-1], announceName(session, time.Now()), announce); err != nil && conn.ctx.Err() == nil {
|
||||
if err := storage.Put(context.Background(), announceName(session, time.Now()), announce); err != nil {
|
||||
err = errors.New("failed to announce session ", session).Base(err)
|
||||
writer.fail(err)
|
||||
conn.reader.(*slotReader).setErr(err)
|
||||
}
|
||||
})
|
||||
}()
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
@@ -217,7 +272,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, false, func() {
|
||||
uplinkPrefix(session), downlinkPrefix(session), p, func() {
|
||||
storage.Close()
|
||||
}), nil
|
||||
}
|
||||
@@ -233,21 +288,8 @@ 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) {
|
||||
@@ -273,19 +315,10 @@ 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,
|
||||
}
|
||||
|
||||
listener.loopWG.Add(2)
|
||||
go func() {
|
||||
defer listener.loopWG.Done()
|
||||
listener.acceptLoop(ctx)
|
||||
}()
|
||||
go func() {
|
||||
defer listener.loopWG.Done()
|
||||
listener.collectLoop(ctx)
|
||||
}()
|
||||
go listener.acceptLoop(ctx)
|
||||
go listener.collectLoop(ctx)
|
||||
|
||||
return listener, nil
|
||||
}
|
||||
@@ -328,22 +361,20 @@ 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 {
|
||||
l.lastSeen[listed.Name] = now
|
||||
listedEntries[listed.Name] = true
|
||||
if _, seen := l.firstSeen[listed.Name]; !seen {
|
||||
first := listed.created
|
||||
if first.IsZero() || first.After(now) {
|
||||
first = now
|
||||
}
|
||||
l.firstSeen[listed.Name] = first
|
||||
l.firstSeen[listed.Name] = now
|
||||
}
|
||||
}
|
||||
// Keep first-seen times across brief listing omissions.
|
||||
for entry := range l.firstSeen {
|
||||
if now.Sub(l.lastSeen[entry]) >= 2*l.sessionTTL {
|
||||
if !listedEntries[entry] {
|
||||
delete(l.firstSeen, entry)
|
||||
delete(l.lastSeen, entry)
|
||||
}
|
||||
}
|
||||
l.mu.Unlock()
|
||||
@@ -352,225 +383,86 @@ func (l *Listener) acceptPending(logCtx context.Context) (bool, error) {
|
||||
entry := listed.Name
|
||||
full := sessionsDir + "/" + entry
|
||||
|
||||
session, _, ok := announceParts(entry)
|
||||
session, _, ok := parseAnnounce(entry)
|
||||
if !ok {
|
||||
// Never construct a deletion path from an unsafe name.
|
||||
if safeListedName(entry) {
|
||||
l.queueDrop(full)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !safeSessionID(session) {
|
||||
go l.drop(full)
|
||||
continue
|
||||
}
|
||||
l.mu.Lock()
|
||||
expires := l.firstSeen[entry].Add(l.sessionTTL)
|
||||
age := now.Sub(l.firstSeen[entry])
|
||||
l.mu.Unlock()
|
||||
if !time.Now().Before(expires) {
|
||||
if age > l.sessionTTL {
|
||||
errors.LogInfo(logCtx, "dropping the stale announcement of session ", session)
|
||||
l.queueDrop(full)
|
||||
l.queueSessionDrop(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))
|
||||
}
|
||||
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
|
||||
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)
|
||||
}
|
||||
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
|
||||
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
|
||||
}
|
||||
}
|
||||
l.mu.Unlock()
|
||||
if warn {
|
||||
errors.LogWarningInner(logCtx, loadErr, "failed to read the announcement of session ", session)
|
||||
}
|
||||
continue
|
||||
}
|
||||
l.queueDrop(full)
|
||||
go l.drop(full)
|
||||
accepted = true
|
||||
l.addConn(conn)
|
||||
l.addConn(l.newSessionConn(logCtx, session, announce))
|
||||
}
|
||||
return accepted, nil
|
||||
}
|
||||
|
||||
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) drop(name string) {
|
||||
l.storage.Delete(l.ctx, name)
|
||||
}
|
||||
|
||||
func (l *Listener) claim(session string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if !safeSessionID(session) {
|
||||
if l.active[session] || !l.handled[session].IsZero() {
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
// 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)
|
||||
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 {
|
||||
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")
|
||||
errors.LogInfo(logCtx, "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(admit, "accepted session ", session)
|
||||
return newConn(l.ctx, storage, downlinkPrefix(session), uplinkPrefix(session), l.params, true, onClose)
|
||||
errors.LogInfo(logCtx, "accepted session ", session)
|
||||
return newConn(l.ctx, storage, downlinkPrefix(session), uplinkPrefix(session), l.params, onClose)
|
||||
}
|
||||
|
||||
func (l *Listener) collectLoop(logCtx context.Context) {
|
||||
@@ -588,12 +480,7 @@ func (l *Listener) collectLoop(logCtx context.Context) {
|
||||
}
|
||||
|
||||
func (l *Listener) collect() error {
|
||||
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)
|
||||
sessions, err := l.storage.List(l.ctx, streamsDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -602,70 +489,40 @@ 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)
|
||||
}
|
||||
}
|
||||
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
|
||||
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)
|
||||
}
|
||||
}
|
||||
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 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()
|
||||
for _, session := range expired {
|
||||
if err := l.storage.Delete(l.ctx, sessionPrefix(session)); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
return first
|
||||
@@ -676,16 +533,6 @@ func (l *Listener) Addr() net.Addr {
|
||||
}
|
||||
|
||||
func (l *Listener) Close() error {
|
||||
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
|
||||
l.cancel()
|
||||
return l.storage.Close()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,984 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
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