mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-12-01 22:29:03 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0a4ddc35c | ||
|
|
919d0ae8eb | ||
|
|
8eac7b41b3 | ||
|
|
ded8443fee | ||
|
|
5780f0df90 | ||
|
|
4d0bfb4d0d | ||
|
|
db6664bd68 | ||
|
|
67756b3674 | ||
|
|
9576662b8e | ||
|
|
c5ccb356aa |
@@ -48,7 +48,8 @@ type tcpWorker struct {
|
||||
|
||||
hub internet.Listener
|
||||
|
||||
ctx context.Context
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func getTProxyType(s *internet.MemoryStreamConfig) internet.SocketConfig_TProxyMode {
|
||||
@@ -132,6 +133,11 @@ func (w *tcpWorker) Proxy() proxy.Inbound {
|
||||
}
|
||||
|
||||
func (w *tcpWorker) Start() error {
|
||||
if w.ctx == nil {
|
||||
w.ctx = context.Background()
|
||||
}
|
||||
w.ctx, w.cancel = context.WithCancel(w.ctx)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
if v, ok := w.proxy.(*hysteria_proxy.Server); ok {
|
||||
@@ -149,6 +155,9 @@ func (w *tcpWorker) Start() error {
|
||||
}
|
||||
|
||||
func (w *tcpWorker) Close() error {
|
||||
if w.cancel != nil {
|
||||
w.cancel()
|
||||
}
|
||||
var errs []interface{}
|
||||
if w.hub != nil {
|
||||
if err := common.Close(w.hub); err != nil {
|
||||
@@ -273,7 +282,8 @@ type udpWorker struct {
|
||||
checker *task.Periodic
|
||||
activeConn map[connID]*udpConn
|
||||
|
||||
ctx context.Context
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
|
||||
@@ -407,6 +417,11 @@ func (w *udpWorker) clean() error {
|
||||
}
|
||||
|
||||
func (w *udpWorker) Start() error {
|
||||
if w.ctx == nil {
|
||||
w.ctx = context.Background()
|
||||
}
|
||||
w.ctx, w.cancel = context.WithCancel(w.ctx)
|
||||
|
||||
w.activeConn = make(map[connID]*udpConn, 16)
|
||||
ctx := context.Background()
|
||||
h, err := udp.ListenUDP(ctx, w.address, w.port, w.stream, udp.HubCapacity(256))
|
||||
@@ -428,6 +443,10 @@ func (w *udpWorker) Close() error {
|
||||
w.Lock()
|
||||
defer w.Unlock()
|
||||
|
||||
if w.cancel != nil {
|
||||
w.cancel()
|
||||
}
|
||||
|
||||
var errs []interface{}
|
||||
|
||||
if w.hub != nil {
|
||||
@@ -472,7 +491,8 @@ type dsWorker struct {
|
||||
|
||||
hub internet.Listener
|
||||
|
||||
ctx context.Context
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (w *dsWorker) callback(conn stat.Connection) {
|
||||
@@ -517,6 +537,11 @@ func (w *dsWorker) Port() net.Port {
|
||||
}
|
||||
|
||||
func (w *dsWorker) Start() error {
|
||||
if w.ctx == nil {
|
||||
w.ctx = context.Background()
|
||||
}
|
||||
w.ctx, w.cancel = context.WithCancel(w.ctx)
|
||||
|
||||
ctx := context.Background()
|
||||
hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn stat.Connection) {
|
||||
go w.callback(conn)
|
||||
@@ -529,6 +554,9 @@ func (w *dsWorker) Start() error {
|
||||
}
|
||||
|
||||
func (w *dsWorker) Close() error {
|
||||
if w.cancel != nil {
|
||||
w.cancel()
|
||||
}
|
||||
var errs []interface{}
|
||||
if w.hub != nil {
|
||||
if err := common.Close(w.hub); err != nil {
|
||||
|
||||
+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]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,3 +23,15 @@ func IDFromContext(ctx context.Context) ID {
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// ContextWithParents returns a new context derived from the father
|
||||
// but also cancels when the mother is done.
|
||||
func ContextWithParents(father, mother context.Context) (context.Context, context.CancelFunc) {
|
||||
child, cancel := context.WithCancel(father)
|
||||
stop := context.AfterFunc(mother, cancel)
|
||||
newCancel := func() {
|
||||
stop()
|
||||
cancel()
|
||||
}
|
||||
return child, newCancel
|
||||
}
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -6,19 +6,11 @@ import (
|
||||
|
||||
// TypedSyncMap is a wrapper of sync.Map that provides type-safe for keys and values.
|
||||
// No need to use type assertions every time, so you can have more time to enjoy other things like GochiUsa
|
||||
// If sync.Map methods returned nil, it will return the zero value of the type V.
|
||||
type TypedSyncMap[K, V any] struct {
|
||||
syncMap *sync.Map
|
||||
}
|
||||
|
||||
// NewTypedSyncMap creates a new TypedSyncMap
|
||||
// K is key type, V is value type
|
||||
// It is recommended to use pointer types for V because sync.Map might return nil
|
||||
// If sync.Map methods really returned nil, it will return the zero value of the type V
|
||||
func NewTypedSyncMap[K any, V any]() *TypedSyncMap[K, V] {
|
||||
return &TypedSyncMap[K, V]{
|
||||
syncMap: &sync.Map{},
|
||||
}
|
||||
// If sync.Map methods returned nil, it will return the zero value of the type V.
|
||||
type TypedSyncMap[K, V any] struct {
|
||||
syncMap sync.Map
|
||||
}
|
||||
|
||||
// Clear deletes all the entries, resulting in an empty Map.
|
||||
|
||||
@@ -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
|
||||
@@ -36,7 +36,7 @@ require (
|
||||
google.golang.org/protobuf v1.36.12
|
||||
h12.io/socks v1.0.3
|
||||
layeh.com/gopher-luar v1.0.11
|
||||
lukechampine.com/blake3 v1.5.1
|
||||
lukechampine.com/blake3 v1.5.3
|
||||
mvdan.cc/gofumpt v0.12.0
|
||||
)
|
||||
|
||||
|
||||
@@ -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=
|
||||
@@ -168,7 +168,7 @@ h12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo=
|
||||
h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck=
|
||||
layeh.com/gopher-luar v1.0.11 h1:8zJudpKI6HWkoh9eyyNFaTM79PY6CAPcIr6X/KTiliw=
|
||||
layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk=
|
||||
lukechampine.com/blake3 v1.5.1 h1:ITRyxe0LlLZcPUWOZ3Taz8mbug/ptn7jbbeeij5ZiPo=
|
||||
lukechampine.com/blake3 v1.5.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
lukechampine.com/blake3 v1.5.3 h1:q4Ru9Zisjt/knP3KQYuk63VDPnREbSOA6cuL6UwrDlI=
|
||||
lukechampine.com/blake3 v1.5.3/go.mod h1:+mObCTICmKFFJzAZ+4qqw23+LrWOuO+Zfj3DQiNQFXs=
|
||||
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
|
||||
mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
|
||||
|
||||
+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",
|
||||
|
||||
@@ -975,6 +975,17 @@ type XMC struct {
|
||||
// NoPadding disables padding. An explicit empty "paddings" array means the
|
||||
// same; an absent one keeps the built-in preset.
|
||||
NoPadding bool `json:"noPadding,omitempty"`
|
||||
// Custom payload channels that carry the tunnel byte stream and the startup
|
||||
// padding. Both ends must use the same pair; empty keeps the defaults
|
||||
// (xmc:data / xmc:pad). Vanilla's "minecraft" namespace is rejected.
|
||||
DataChannel string `json:"dataChannel,omitempty"`
|
||||
PaddingChannel string `json:"paddingChannel,omitempty"`
|
||||
// Minecraft network protocol number the client advertises, for example 777
|
||||
// for 26.3. Zero detects it from the peer's status response (cached per
|
||||
// destination) and falls back to the newest version the mask knows. Set it to
|
||||
// skip detection or to pin a version; the server follows whatever the client
|
||||
// names.
|
||||
ProtocolVersion uint32 `json:"protocolVersion,omitempty"`
|
||||
}
|
||||
|
||||
type XMCPaddingTurn struct {
|
||||
@@ -1040,7 +1051,21 @@ func (c *XMC) Build() (proto.Message, error) {
|
||||
if noPadding && len(c.Paddings) > 0 {
|
||||
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
|
||||
}
|
||||
config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding}
|
||||
if err := xmc.ValidateProtocolVersion(c.ProtocolVersion); err != nil {
|
||||
return nil, fmt.Errorf("minecraft protocolVersion: %w", err)
|
||||
}
|
||||
config := &xmc.Config{
|
||||
Hostname: c.Hostname,
|
||||
NoPadding: noPadding,
|
||||
DataChannel: c.DataChannel,
|
||||
PaddingChannel: c.PaddingChannel,
|
||||
ProtocolVersion: c.ProtocolVersion,
|
||||
}
|
||||
dataChannel, paddingChannel, channelErr := config.ChannelIDs()
|
||||
if channelErr != nil {
|
||||
return nil, fmt.Errorf("minecraft channels: %w", channelErr)
|
||||
}
|
||||
config.DataChannel, config.PaddingChannel = dataChannel, paddingChannel
|
||||
for i, turn := range c.Paddings {
|
||||
minimum, maximum, err := ParseRangeString(turn.Length)
|
||||
if err != nil {
|
||||
|
||||
@@ -242,3 +242,93 @@ func TestXMCBuildDisablesPadding(t *testing.T) {
|
||||
t.Fatalf("expected an exclusive padding error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func xmcTestProfiles() []XMCProfile {
|
||||
return []XMCProfile{{
|
||||
Username: "TestUser",
|
||||
UUID: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
TexturesValue: "textures-value",
|
||||
TexturesSignature: "textures-signature",
|
||||
}}
|
||||
}
|
||||
|
||||
func TestXMCBuildChannels(t *testing.T) {
|
||||
built, err := (&XMC{
|
||||
Password: "test-password",
|
||||
Profiles: xmcTestProfiles(),
|
||||
DataChannel: "myxmc:stream",
|
||||
PaddingChannel: "myxmc:noise",
|
||||
}).Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build XMC config: %v", err)
|
||||
}
|
||||
config := built.(*xmc.Config)
|
||||
if config.DataChannel != "myxmc:stream" || config.PaddingChannel != "myxmc:noise" {
|
||||
t.Fatalf("channels = %q, %q", config.DataChannel, config.PaddingChannel)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildChannelDefaults(t *testing.T) {
|
||||
built, err := (&XMC{Password: "test-password", Profiles: xmcTestProfiles()}).Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build XMC config: %v", err)
|
||||
}
|
||||
config := built.(*xmc.Config)
|
||||
if config.DataChannel != xmc.DefaultDataChannel || config.PaddingChannel != xmc.DefaultPaddingChannel {
|
||||
t.Fatalf("default channels = %q, %q", config.DataChannel, config.PaddingChannel)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildRejectsChannels(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
data string
|
||||
padding string
|
||||
}{
|
||||
"vanilla_namespace": {"minecraft:data", ""},
|
||||
"no_colon": {"xmcdata", ""},
|
||||
"empty_path": {"xmc:", ""},
|
||||
"uppercase": {"Xmc:data", ""},
|
||||
"same_channel": {"xmc:same", "xmc:same"},
|
||||
"too_long": {strings.Repeat("a", 129) + ":b", ""},
|
||||
}
|
||||
for name, test := range cases {
|
||||
_, err := (&XMC{
|
||||
Password: "test-password",
|
||||
Profiles: xmcTestProfiles(),
|
||||
DataChannel: test.data,
|
||||
PaddingChannel: test.padding,
|
||||
}).Build()
|
||||
if err == nil || !strings.Contains(err.Error(), "channel") {
|
||||
t.Fatalf("%s: expected a channel error, got %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMCBuildProtocolVersion(t *testing.T) {
|
||||
profile := XMCProfile{
|
||||
Username: "TestUser",
|
||||
UUID: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
TexturesValue: "textures-value",
|
||||
TexturesSignature: "textures-signature",
|
||||
}
|
||||
|
||||
built, err := (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}}).Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build default XMC config: %v", err)
|
||||
}
|
||||
if got := built.(*xmc.Config).ProtocolVersion; got != 0 {
|
||||
t.Fatalf("default protocol version = %d, want 0 (newest)", got)
|
||||
}
|
||||
|
||||
built, err = (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}, ProtocolVersion: 775}).Build()
|
||||
if err != nil {
|
||||
t.Fatalf("build XMC config with a protocol version: %v", err)
|
||||
}
|
||||
if got := built.(*xmc.Config).ProtocolVersion; got != 775 {
|
||||
t.Fatalf("protocol version = %d, want 775", got)
|
||||
}
|
||||
|
||||
if _, err = (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}, ProtocolVersion: 778}).Build(); err == nil || !strings.Contains(err.Error(), "unsupported protocol version 778") {
|
||||
t.Fatalf("expected an unknown protocol version to be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -606,7 +606,7 @@ func NewPacketWriter(conn net.Conn, h *Handler, defaultRule *Firewall, UDPOverri
|
||||
if c, ok := iConn.(*net.PacketConnWrapper); ok {
|
||||
// If DialDest is a domain, it will be resolved in dialer
|
||||
// check this behavior and add it to map
|
||||
resolvedUDPAddr := utils.NewTypedSyncMap[string, net.Address]()
|
||||
resolvedUDPAddr := &utils.TypedSyncMap[string, net.Address]{}
|
||||
if DialDest.Address.Family().IsDomain() {
|
||||
resolvedUDPAddr.Store(DialDest.Address.Domain(), net.DestinationFromAddr(conn.RemoteAddr()).Address)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/utils"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -24,6 +26,9 @@ func (a *Account) AsAccount() (protocol.Account, error) {
|
||||
type MemoryAccount struct {
|
||||
Auth string
|
||||
VR net.Port
|
||||
|
||||
Ctx context.Context
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (a *MemoryAccount) Equals(other protocol.Account) bool {
|
||||
@@ -40,8 +45,8 @@ func (a *MemoryAccount) ToProto() proto.Message {
|
||||
}
|
||||
|
||||
type Validator struct {
|
||||
users sync.Map
|
||||
ids sync.Map
|
||||
users utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
ids utils.TypedSyncMap[uuid.UUID, *protocol.MemoryUser]
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
@@ -51,8 +56,10 @@ func NewValidator() *Validator {
|
||||
|
||||
func (v *Validator) Add(user *protocol.MemoryUser) (err error) {
|
||||
v.mu.Lock()
|
||||
v.users.Store(user.Account.(*MemoryAccount).Auth, user)
|
||||
if id, err := uuid.Parse(user.Account.(*MemoryAccount).Auth); err == nil {
|
||||
a := user.Account.(*MemoryAccount)
|
||||
a.Ctx, a.Cancel = context.WithCancel(context.Background())
|
||||
v.users.Store(a.Auth, user)
|
||||
if id, err := uuid.Parse(a.Auth); err == nil {
|
||||
id[6] = 0
|
||||
id[7] = 0
|
||||
v.ids.Store(id, user)
|
||||
@@ -64,13 +71,15 @@ func (v *Validator) Add(user *protocol.MemoryUser) (err error) {
|
||||
func (v *Validator) DelByEmail(email string) (err error) {
|
||||
v.mu.Lock()
|
||||
if user := v.GetByEmail(email); user != nil {
|
||||
auth := user.Account.(*MemoryAccount).Auth
|
||||
a := user.Account.(*MemoryAccount)
|
||||
auth := a.Auth
|
||||
v.users.Delete(auth)
|
||||
if id, err := uuid.Parse(auth); err == nil {
|
||||
id[6] = 0
|
||||
id[7] = 0
|
||||
v.ids.Delete(id)
|
||||
}
|
||||
a.Cancel()
|
||||
}
|
||||
v.mu.Unlock()
|
||||
return
|
||||
@@ -80,13 +89,16 @@ func (v *Validator) Get(auth string) (user *protocol.MemoryUser) {
|
||||
if id, err := uuid.Parse(auth); err == nil {
|
||||
if user = v.GetByID(id); user != nil {
|
||||
VR := net.PortFromBytes(id[6:8])
|
||||
if user.Account.(*MemoryAccount).VR != VR {
|
||||
orig := user.Account.(*MemoryAccount)
|
||||
if orig.VR != VR {
|
||||
user = &protocol.MemoryUser{
|
||||
Email: user.Email,
|
||||
Level: user.Level,
|
||||
Account: &MemoryAccount{
|
||||
Auth: auth,
|
||||
VR: VR,
|
||||
Auth: auth,
|
||||
VR: VR,
|
||||
Ctx: orig.Ctx,
|
||||
Cancel: orig.Cancel,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -94,7 +106,7 @@ func (v *Validator) Get(auth string) (user *protocol.MemoryUser) {
|
||||
return
|
||||
}
|
||||
if value, ok := v.users.Load(auth); ok {
|
||||
user = value.(*protocol.MemoryUser)
|
||||
user = value
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -103,15 +115,15 @@ func (v *Validator) GetByID(id uuid.UUID) (user *protocol.MemoryUser) {
|
||||
id[6] = 0
|
||||
id[7] = 0
|
||||
if value, ok := v.ids.Load(id); ok {
|
||||
user = value.(*protocol.MemoryUser)
|
||||
user = value
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (v *Validator) GetByEmail(email string) (user *protocol.MemoryUser) {
|
||||
v.users.Range(func(key, value any) bool {
|
||||
if value.(*protocol.MemoryUser).Email == email {
|
||||
user = value.(*protocol.MemoryUser)
|
||||
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
|
||||
if value.Email == email {
|
||||
user = value
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -120,15 +132,15 @@ func (v *Validator) GetByEmail(email string) (user *protocol.MemoryUser) {
|
||||
}
|
||||
|
||||
func (v *Validator) GetAll() (users []*protocol.MemoryUser) {
|
||||
v.users.Range(func(key, value any) bool {
|
||||
users = append(users, value.(*protocol.MemoryUser))
|
||||
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
|
||||
users = append(users, value)
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func (v *Validator) GetCount() (count int64) {
|
||||
v.users.Range(func(key, value any) bool {
|
||||
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
|
||||
count++
|
||||
return true
|
||||
})
|
||||
@@ -136,7 +148,7 @@ func (v *Validator) GetCount() (count int64) {
|
||||
}
|
||||
|
||||
func (v *Validator) NotEmpty() (not_empty bool) {
|
||||
v.users.Range(func(key, value any) bool {
|
||||
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
|
||||
not_empty = true
|
||||
return false
|
||||
})
|
||||
|
||||
+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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
c "github.com/xtls/xray-core/common/ctx"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -95,7 +96,11 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con
|
||||
user := v.User()
|
||||
if user != nil {
|
||||
inbound.User = user
|
||||
inbound.VlessRoute = user.Account.(*account.MemoryAccount).VR
|
||||
a := user.Account.(*account.MemoryAccount)
|
||||
inbound.VlessRoute = a.VR
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = c.ContextWithParents(ctx, a.Ctx)
|
||||
defer cancel()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package masque
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -16,6 +17,9 @@ func (a *Account) AsAccount() (protocol.Account, error) {
|
||||
|
||||
type MemoryAccount struct {
|
||||
Password string
|
||||
|
||||
Ctx context.Context
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (a *MemoryAccount) Equals(other protocol.Account) bool {
|
||||
@@ -53,6 +57,7 @@ func (v *validator) add(user *protocol.MemoryUser) error {
|
||||
if _, found := v.users[email]; found {
|
||||
return errors.New("user ", user.Email, " already exists")
|
||||
}
|
||||
account.Ctx, account.Cancel = context.WithCancel(context.Background())
|
||||
v.users[email] = user
|
||||
return nil
|
||||
}
|
||||
@@ -66,6 +71,7 @@ func (v *validator) delByEmail(email string) (*protocol.MemoryUser, error) {
|
||||
return nil, errors.New("user ", email, " not found")
|
||||
}
|
||||
delete(v.users, key)
|
||||
user.Account.(*MemoryAccount).Cancel()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -511,7 +511,7 @@ func (s *Server) HandleConnection(conn net.Conn, dest net.Destination) {
|
||||
}
|
||||
defer t.untrack(conn)
|
||||
|
||||
ctx, cancel := context.WithCancel(s.ctx)
|
||||
ctx, cancel := c.ContextWithParents(s.ctx, t.user.Account.(*MemoryAccount).Ctx)
|
||||
defer cancel()
|
||||
ctx = c.ContextWithID(ctx, session.NewID())
|
||||
inbound := session.Inbound{
|
||||
|
||||
@@ -2,6 +2,7 @@ package shadowsocks
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/cipher"
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
@@ -24,6 +25,9 @@ type MemoryAccount struct {
|
||||
CipherType CipherType
|
||||
Key []byte
|
||||
Password string
|
||||
|
||||
Ctx context.Context
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
var ErrIVNotUnique = errors.New("IV is not unique")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
c "github.com/xtls/xray-core/common/ctx"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -130,6 +131,12 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
|
||||
|
||||
inbound := session.InboundFromContext(ctx)
|
||||
var dest *net.Destination
|
||||
var userCancel context.CancelFunc
|
||||
defer func() {
|
||||
if userCancel != nil {
|
||||
userCancel()
|
||||
}
|
||||
}()
|
||||
reader := buf.NewPacketReader(conn)
|
||||
for {
|
||||
mpayload, err := reader.ReadMultiBuffer()
|
||||
@@ -150,6 +157,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
|
||||
request, data, err = DecodeUDPPacket(s.validator, payload)
|
||||
if err == nil {
|
||||
inbound.User = request.User
|
||||
ctx, userCancel = c.ContextWithParents(ctx, request.User.Account.(*MemoryAccount).Ctx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,6 +228,10 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis
|
||||
}
|
||||
inbound.User = request.User
|
||||
|
||||
var userCancel context.CancelFunc
|
||||
ctx, userCancel = c.ContextWithParents(ctx, request.User.Account.(*MemoryAccount).Ctx)
|
||||
defer userCancel()
|
||||
|
||||
dest := request.Destination()
|
||||
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
|
||||
From: conn.RemoteAddr(),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package shadowsocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
@@ -33,6 +34,9 @@ func (v *Validator) Add(u *protocol.MemoryUser) error {
|
||||
if !account.Cipher.IsAEAD() && len(v.users) > 0 {
|
||||
return errors.New("The cipher is not support Single-port Multi-user")
|
||||
}
|
||||
if account.Ctx == nil {
|
||||
account.Ctx, account.Cancel = context.WithCancel(context.Background())
|
||||
}
|
||||
v.users = append(v.users, u)
|
||||
|
||||
if !v.behaviorFused {
|
||||
@@ -58,6 +62,7 @@ func (v *Validator) Del(email string) error {
|
||||
for i, u := range v.users {
|
||||
if strings.EqualFold(u.Email, email) {
|
||||
idx = i
|
||||
u.Account.(*MemoryAccount).Cancel()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package shadowsocks_2022
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -12,6 +13,9 @@ import (
|
||||
// MemoryAccount is an account type converted from Account.
|
||||
type MemoryAccount struct {
|
||||
Key []byte
|
||||
|
||||
Ctx context.Context
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// AsAccount implements protocol.AsAccount.
|
||||
|
||||
@@ -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"
|
||||
@@ -13,6 +11,7 @@ import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/antireplay"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
c "github.com/xtls/xray-core/common/ctx"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -34,16 +33,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 +66,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.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]{},
|
||||
usersByEmail: &utils.TypedSyncMap[string, *protocol.MemoryUser]{},
|
||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||
udpCodec: udpCodec,
|
||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||
}
|
||||
|
||||
for idx, user := range config.Users {
|
||||
@@ -125,6 +122,8 @@ func (i *MultiUserInbound) AddUser(ctx context.Context, u *protocol.MemoryUser)
|
||||
return ErrBadKey
|
||||
}
|
||||
|
||||
memAcc.Ctx, memAcc.Cancel = context.WithCancel(context.Background())
|
||||
|
||||
pskHash := DeriveUserPSKHash(memAcc.Key)
|
||||
i.usersByHash.Store(pskHash, u)
|
||||
if emailKey != "" {
|
||||
@@ -150,9 +149,11 @@ func (i *MultiUserInbound) RemoveUser(ctx context.Context, email string) error {
|
||||
return errors.New("user ", email, " not found")
|
||||
}
|
||||
|
||||
pskHash := DeriveUserPSKHash(u.Account.(*MemoryAccount).Key)
|
||||
a := u.Account.(*MemoryAccount)
|
||||
pskHash := DeriveUserPSKHash(a.Key)
|
||||
i.usersByHash.Delete(pskHash)
|
||||
i.userCount.Add(-1)
|
||||
a.Cancel()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -247,6 +248,10 @@ func (i *MultiUserInbound) processTCP(ctx context.Context, conn net.Conn, dispat
|
||||
inbound := session.InboundFromContext(ctx)
|
||||
inbound.User = user
|
||||
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = c.ContextWithParents(ctx, user.Account.(*MemoryAccount).Ctx)
|
||||
defer cancel()
|
||||
|
||||
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
|
||||
From: conn.RemoteAddr(),
|
||||
To: dest,
|
||||
@@ -281,68 +286,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 +319,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 {
|
||||
@@ -123,11 +131,18 @@ type UDPSessionManager struct {
|
||||
|
||||
func NewUDPSessionManager(timeout time.Duration) *UDPSessionManager {
|
||||
return &UDPSessionManager{
|
||||
sessions: utils.NewTypedSyncMap[uint64, *ServerUDPSession](),
|
||||
sessions: &utils.TypedSyncMap[uint64, *ServerUDPSession]{},
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
c "github.com/xtls/xray-core/common/ctx"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -63,10 +64,22 @@ 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
|
||||
var sessCtx context.Context
|
||||
var cancel context.CancelFunc
|
||||
if s.User != nil && s.User.Account != nil {
|
||||
sessCtx, cancel = c.ContextWithParents(context.WithoutCancel(ctx), s.User.Account.(*MemoryAccount).Ctx)
|
||||
} else {
|
||||
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()
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package trojan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
@@ -15,6 +16,9 @@ import (
|
||||
type MemoryAccount struct {
|
||||
Password string
|
||||
Key []byte
|
||||
|
||||
Ctx context.Context
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// AsAccount implements protocol.AsAccount.
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
c "github.com/xtls/xray-core/common/ctx"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -226,6 +227,10 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con
|
||||
inbound.User = user
|
||||
sessionPolicy = s.policyManager.ForLevel(user.Level)
|
||||
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = c.ContextWithParents(ctx, user.Account.(*MemoryAccount).Ctx)
|
||||
defer cancel()
|
||||
|
||||
if destination.Network == net.Network_UDP { // handle udp request
|
||||
return s.handleUDPPayload(ctx, sessionPolicy, &PacketReader{Reader: clientReader}, &PacketWriter{Writer: conn}, dispatcher)
|
||||
}
|
||||
|
||||
+16
-18
@@ -1,29 +1,32 @@
|
||||
package trojan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/utils"
|
||||
)
|
||||
|
||||
// Validator stores valid trojan users.
|
||||
type Validator struct {
|
||||
// Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
|
||||
email sync.Map
|
||||
users sync.Map
|
||||
email utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
users utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
}
|
||||
|
||||
// Add a trojan user, Email must be empty or unique.
|
||||
func (v *Validator) Add(u *protocol.MemoryUser) error {
|
||||
a := u.Account.(*MemoryAccount)
|
||||
a.Ctx, a.Cancel = context.WithCancel(context.Background())
|
||||
if u.Email != "" {
|
||||
_, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
|
||||
if loaded {
|
||||
return errors.New("User ", u.Email, " already exists.")
|
||||
}
|
||||
}
|
||||
v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u)
|
||||
v.users.Store(hexString(a.Key), u)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -38,34 +41,29 @@ func (v *Validator) Del(e string) error {
|
||||
return errors.New("User ", e, " not found.")
|
||||
}
|
||||
v.email.Delete(le)
|
||||
v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key))
|
||||
a := u.Account.(*MemoryAccount)
|
||||
v.users.Delete(hexString(a.Key))
|
||||
a.Cancel()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get a trojan user with hashed key, nil if user doesn't exist.
|
||||
func (v *Validator) Get(hash string) *protocol.MemoryUser {
|
||||
u, _ := v.users.Load(hash)
|
||||
if u != nil {
|
||||
return u.(*protocol.MemoryUser)
|
||||
}
|
||||
return nil
|
||||
return u
|
||||
}
|
||||
|
||||
// Get a trojan user with hashed key, nil if user doesn't exist.
|
||||
func (v *Validator) GetByEmail(email string) *protocol.MemoryUser {
|
||||
email = strings.ToLower(email)
|
||||
u, _ := v.email.Load(email)
|
||||
if u != nil {
|
||||
return u.(*protocol.MemoryUser)
|
||||
}
|
||||
return nil
|
||||
u, _ := v.email.Load(strings.ToLower(email))
|
||||
return u
|
||||
}
|
||||
|
||||
// Get all users
|
||||
func (v *Validator) GetAll() []*protocol.MemoryUser {
|
||||
u := make([]*protocol.MemoryUser, 0, 100)
|
||||
v.email.Range(func(key, value interface{}) bool {
|
||||
u = append(u, value.(*protocol.MemoryUser))
|
||||
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
|
||||
u = append(u, value)
|
||||
return true
|
||||
})
|
||||
return u
|
||||
@@ -74,7 +72,7 @@ func (v *Validator) GetAll() []*protocol.MemoryUser {
|
||||
// Get users count
|
||||
func (v *Validator) GetCount() int64 {
|
||||
var c int64 = 0
|
||||
v.email.Range(func(key, value interface{}) bool {
|
||||
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
|
||||
c++
|
||||
return true
|
||||
})
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package vless
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
@@ -43,6 +45,9 @@ type MemoryAccount struct {
|
||||
|
||||
Testpre uint32
|
||||
Testseed []uint32
|
||||
|
||||
Ctx context.Context
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// Equals implements protocol.Account.Equals().
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -48,7 +49,7 @@ func TestRequestSerialization(t *testing.T) {
|
||||
_, actualRequest, actualAddons, _, err := DecodeRequestHeader(false, nil, &buffer, Validator)
|
||||
common.Must(err)
|
||||
|
||||
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
|
||||
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{}), cmpopts.IgnoreFields(vless.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
|
||||
t.Error(r)
|
||||
}
|
||||
|
||||
@@ -120,7 +121,7 @@ func TestMuxRequest(t *testing.T) {
|
||||
_, actualRequest, actualAddons, _, err := DecodeRequestHeader(false, nil, &buffer, Validator)
|
||||
common.Must(err)
|
||||
|
||||
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
|
||||
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{}), cmpopts.IgnoreFields(vless.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
|
||||
t.Error(r)
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/xtls/xray-core/app/dispatcher"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
c "github.com/xtls/xray-core/common/ctx"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -541,6 +542,10 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
|
||||
account := request.User.Account.(*vless.MemoryAccount)
|
||||
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = c.ContextWithParents(ctx, account.Ctx)
|
||||
defer cancel()
|
||||
|
||||
if account.Reverse != nil && request.Command != protocol.RequestCommandRvs {
|
||||
return errors.New("for safety reasons, user " + account.ID.String() + " is not allowed to use forward proxy")
|
||||
}
|
||||
|
||||
+16
-18
@@ -1,11 +1,12 @@
|
||||
package vless
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/utils"
|
||||
"github.com/xtls/xray-core/common/uuid"
|
||||
)
|
||||
|
||||
@@ -27,19 +28,21 @@ func ProcessUUID(id [16]byte) [16]byte {
|
||||
// MemoryValidator stores valid VLESS users.
|
||||
type MemoryValidator struct {
|
||||
// Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
|
||||
email sync.Map
|
||||
users sync.Map
|
||||
email utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||
users utils.TypedSyncMap[[16]byte, *protocol.MemoryUser]
|
||||
}
|
||||
|
||||
// Add a VLESS user, Email must be empty or unique.
|
||||
func (v *MemoryValidator) Add(u *protocol.MemoryUser) error {
|
||||
a := u.Account.(*MemoryAccount)
|
||||
a.Ctx, a.Cancel = context.WithCancel(context.Background())
|
||||
if u.Email != "" {
|
||||
_, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
|
||||
if loaded {
|
||||
return errors.New("User ", u.Email, " already exists.")
|
||||
}
|
||||
}
|
||||
v.users.Store(ProcessUUID(u.Account.(*MemoryAccount).ID.UUID()), u)
|
||||
v.users.Store(ProcessUUID(a.ID.UUID()), u)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -54,34 +57,29 @@ func (v *MemoryValidator) Del(e string) error {
|
||||
return errors.New("User ", e, " not found.")
|
||||
}
|
||||
v.email.Delete(le)
|
||||
v.users.Delete(ProcessUUID(u.(*protocol.MemoryUser).Account.(*MemoryAccount).ID.UUID()))
|
||||
a := u.Account.(*MemoryAccount)
|
||||
v.users.Delete(ProcessUUID(a.ID.UUID()))
|
||||
a.Cancel()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get a VLESS user with UUID, nil if user doesn't exist.
|
||||
func (v *MemoryValidator) Get(id uuid.UUID) *protocol.MemoryUser {
|
||||
u, _ := v.users.Load(ProcessUUID(id))
|
||||
if u != nil {
|
||||
return u.(*protocol.MemoryUser)
|
||||
}
|
||||
return nil
|
||||
return u
|
||||
}
|
||||
|
||||
// Get a VLESS user with email, nil if user doesn't exist.
|
||||
func (v *MemoryValidator) GetByEmail(email string) *protocol.MemoryUser {
|
||||
email = strings.ToLower(email)
|
||||
u, _ := v.email.Load(email)
|
||||
if u != nil {
|
||||
return u.(*protocol.MemoryUser)
|
||||
}
|
||||
return nil
|
||||
u, _ := v.email.Load(strings.ToLower(email))
|
||||
return u
|
||||
}
|
||||
|
||||
// Get all users
|
||||
func (v *MemoryValidator) GetAll() []*protocol.MemoryUser {
|
||||
u := make([]*protocol.MemoryUser, 0, 100)
|
||||
v.email.Range(func(key, value interface{}) bool {
|
||||
u = append(u, value.(*protocol.MemoryUser))
|
||||
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
|
||||
u = append(u, value)
|
||||
return true
|
||||
})
|
||||
return u
|
||||
@@ -90,7 +88,7 @@ func (v *MemoryValidator) GetAll() []*protocol.MemoryUser {
|
||||
// Get users count
|
||||
func (v *MemoryValidator) GetCount() int64 {
|
||||
var c int64 = 0
|
||||
v.email.Range(func(key, value interface{}) bool {
|
||||
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
|
||||
c++
|
||||
return true
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package vmess
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -19,6 +20,9 @@ type MemoryAccount struct {
|
||||
|
||||
AuthenticatedLengthExperiment bool
|
||||
NoTerminationSignal bool
|
||||
|
||||
Ctx context.Context
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// Equals implements protocol.Account.
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
c "github.com/xtls/xray-core/common/ctx"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
@@ -235,6 +236,10 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
||||
inbound.CanSpliceCopy = 3
|
||||
inbound.User = request.User
|
||||
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = c.ContextWithParents(ctx, request.User.Account.(*vmess.MemoryAccount).Ctx)
|
||||
defer cancel()
|
||||
|
||||
bodyReader, err := svrSession.DecodeRequestBody(request, reader)
|
||||
if err != nil {
|
||||
return errors.New("failed to start decoding").Base(err)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package vmess
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"hash/crc64"
|
||||
@@ -43,6 +44,7 @@ func (v *TimedUserValidator) Add(u *protocol.MemoryUser) error {
|
||||
if !ok {
|
||||
return errors.New("account type is incorrect")
|
||||
}
|
||||
account.Ctx, account.Cancel = context.WithCancel(context.Background())
|
||||
if !v.behaviorFused {
|
||||
hashkdf := hmac.New(sha256.New, []byte("VMESSBSKDF"))
|
||||
hashkdf.Write(account.ID.Bytes())
|
||||
@@ -93,9 +95,11 @@ func (v *TimedUserValidator) Remove(email string) bool {
|
||||
for i, u := range v.users {
|
||||
if strings.EqualFold(u.Email, email) {
|
||||
idx = i
|
||||
a := u.Account.(*MemoryAccount)
|
||||
var cmdkeyfl [16]byte
|
||||
copy(cmdkeyfl[:], u.Account.(*MemoryAccount).ID.CmdKey())
|
||||
copy(cmdkeyfl[:], a.ID.CmdKey())
|
||||
v.aeadDecoderHolder.RemoveUser(cmdkeyfl)
|
||||
a.Cancel()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"net/netip"
|
||||
|
||||
@@ -36,6 +37,9 @@ type MemoryAccount struct {
|
||||
AllowedIPs []netip.Prefix
|
||||
PreSharedKey string
|
||||
KeepAlive string
|
||||
|
||||
Ctx context.Context
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (a *MemoryAccount) Equals(other protocol.Account) bool {
|
||||
|
||||
+23
-14
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/utils"
|
||||
"github.com/xtls/xray-core/core"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
@@ -48,7 +49,7 @@ type Server struct {
|
||||
mu sync.Mutex
|
||||
|
||||
pub [32]byte
|
||||
users *sync.Map
|
||||
users *utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]
|
||||
}
|
||||
|
||||
func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
|
||||
@@ -98,13 +99,15 @@ func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
|
||||
var pub [32]byte
|
||||
curve25519.ScalarBaseMult(&pub, pri)
|
||||
|
||||
users := &sync.Map{}
|
||||
users := &utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]{}
|
||||
for _, u := range conf.Users {
|
||||
user, err := u.ToMemoryUser()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
users.Store(user.Account.(*MemoryAccount).Pub, user)
|
||||
peer := user.Account.(*MemoryAccount)
|
||||
peer.Ctx, peer.Cancel = context.WithCancel(context.Background())
|
||||
users.Store(peer.Pub, user)
|
||||
}
|
||||
|
||||
s := &Server{
|
||||
@@ -158,6 +161,7 @@ func (s *Server) AddUser(ctx context.Context, user *protocol.MemoryUser) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
peer.Ctx, peer.Cancel = context.WithCancel(context.Background())
|
||||
s.users.Store(peer.Pub, user)
|
||||
return nil
|
||||
}
|
||||
@@ -175,14 +179,15 @@ func (s *Server) RemoveUser(ctx context.Context, email string) error {
|
||||
return err
|
||||
}
|
||||
s.users.Delete(peer.Pub)
|
||||
peer.Cancel()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) GetUser(ctx context.Context, email string) (user *protocol.MemoryUser) {
|
||||
s.users.Range(func(key, value any) bool {
|
||||
if value.(*protocol.MemoryUser).Email == email {
|
||||
user = value.(*protocol.MemoryUser)
|
||||
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
|
||||
if value.Email == email {
|
||||
user = value
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -191,11 +196,11 @@ func (s *Server) GetUser(ctx context.Context, email string) (user *protocol.Memo
|
||||
}
|
||||
|
||||
func (s *Server) GetUserByAddr(ctx context.Context, addr netip.Addr) (user *protocol.MemoryUser) {
|
||||
s.users.Range(func(key, value any) bool {
|
||||
peer := value.(*protocol.MemoryUser).Account.(*MemoryAccount)
|
||||
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
|
||||
peer := value.Account.(*MemoryAccount)
|
||||
for i := range peer.AllowedIPs {
|
||||
if peer.AllowedIPs[i].Contains(addr) {
|
||||
user = value.(*protocol.MemoryUser)
|
||||
user = value
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -205,15 +210,15 @@ func (s *Server) GetUserByAddr(ctx context.Context, addr netip.Addr) (user *prot
|
||||
}
|
||||
|
||||
func (s *Server) GetUsers(ctx context.Context) (users []*protocol.MemoryUser) {
|
||||
s.users.Range(func(key, value interface{}) bool {
|
||||
users = append(users, value.(*protocol.MemoryUser))
|
||||
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
|
||||
users = append(users, value)
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Server) GetUsersCount(context.Context) (count int64) {
|
||||
s.users.Range(func(key, value interface{}) bool {
|
||||
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
|
||||
count++
|
||||
return true
|
||||
})
|
||||
@@ -295,8 +300,8 @@ func (s *Server) Start() error {
|
||||
dev := device.NewDevice(s.tun, bind, logger)
|
||||
var cfg strings.Builder
|
||||
cfg.WriteString("private_key=" + s.conf.SecretKey + "\n")
|
||||
s.users.Range(func(key, value any) bool {
|
||||
peer := value.(*protocol.MemoryUser).Account.(*MemoryAccount)
|
||||
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
|
||||
peer := value.Account.(*MemoryAccount)
|
||||
cfg.WriteString("public_key=" + hex.EncodeToString(peer.Pub[:]) + "\n")
|
||||
for i := range peer.AllowedIPs {
|
||||
cfg.WriteString("allowed_ip=" + peer.AllowedIPs[i].String() + "\n")
|
||||
@@ -350,6 +355,10 @@ func (s *Server) HandleConnection(conn net.Conn, dest net.Destination) {
|
||||
return
|
||||
}
|
||||
|
||||
var userCancel context.CancelFunc
|
||||
ctx, userCancel = c.ContextWithParents(ctx, user.Account.(*MemoryAccount).Ctx)
|
||||
defer userCancel()
|
||||
|
||||
source := net.DestinationFromAddr(remote)
|
||||
inbound := session.Inbound{
|
||||
Name: "wireguard",
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"io"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
@@ -12,6 +11,7 @@ import (
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/protocol"
|
||||
"github.com/xtls/xray-core/common/utils"
|
||||
"github.com/xtls/xray-core/features/routing"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
@@ -54,10 +54,16 @@ func (d *closingDispatcher) DispatchLink(_ context.Context, _ net.Destination, l
|
||||
func TestServerKeepsConnectionOpenWhenWriterCloses(t *testing.T) {
|
||||
conn := &stackConn{}
|
||||
dispatcher := &closingDispatcher{conn: conn}
|
||||
users := &sync.Map{}
|
||||
users := &utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]{}
|
||||
userCtx, userCancel := context.WithCancel(context.Background())
|
||||
defer userCancel()
|
||||
users.Store([32]byte{1}, &protocol.MemoryUser{
|
||||
Email: "love@xray.com",
|
||||
Account: &MemoryAccount{AllowedIPs: []netip.Prefix{netip.MustParsePrefix("10.0.0.2/32")}},
|
||||
Email: "love@xray.com",
|
||||
Account: &MemoryAccount{
|
||||
AllowedIPs: []netip.Prefix{netip.MustParsePrefix("10.0.0.2/32")},
|
||||
Ctx: userCtx,
|
||||
Cancel: userCancel,
|
||||
},
|
||||
})
|
||||
s := &Server{ctx: context.Background(), dispatcher: dispatcher, users: users}
|
||||
s.HandleConnection(conn, net.TCPDestination(net.ParseAddress("192.0.2.1"), 443))
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultDataChannel carries the tunnel byte stream and DefaultPaddingChannel
|
||||
// carries the startup padding. Both ends must agree on the pair, and the
|
||||
// defaults are public constants, so a deployment that wants a different
|
||||
// fingerprint renames them on both sides.
|
||||
DefaultDataChannel = "xmc:data"
|
||||
DefaultPaddingChannel = "xmc:pad"
|
||||
|
||||
// MaxChannelIDLength bounds a channel id. The id travels in every custom
|
||||
// payload header, so a long one is pure overhead; vanilla itself has no
|
||||
// limit beyond the string encoding.
|
||||
MaxChannelIDLength = 128
|
||||
)
|
||||
|
||||
var (
|
||||
channelNamespacePattern = regexp.MustCompile(`^[a-z0-9_.-]+$`)
|
||||
channelPathPattern = regexp.MustCompile(`^[a-z0-9/._-]+$`)
|
||||
)
|
||||
|
||||
// ChannelIDs returns the two configured custom payload channels, filling in the
|
||||
// defaults for empty fields. Both are validated because both ends have to
|
||||
// register them as Minecraft resource locations.
|
||||
func (c *Config) ChannelIDs() (dataChannel, paddingChannel string, err error) {
|
||||
dataChannel = c.DataChannel
|
||||
if dataChannel == "" {
|
||||
dataChannel = DefaultDataChannel
|
||||
}
|
||||
paddingChannel = c.PaddingChannel
|
||||
if paddingChannel == "" {
|
||||
paddingChannel = DefaultPaddingChannel
|
||||
}
|
||||
if err = ValidateChannelID(dataChannel); err != nil {
|
||||
return "", "", fmt.Errorf("data channel: %w", err)
|
||||
}
|
||||
if err = ValidateChannelID(paddingChannel); err != nil {
|
||||
return "", "", fmt.Errorf("padding channel: %w", err)
|
||||
}
|
||||
if dataChannel == paddingChannel {
|
||||
return "", "", fmt.Errorf("data and padding channels must differ: %q", dataChannel)
|
||||
}
|
||||
return dataChannel, paddingChannel, nil
|
||||
}
|
||||
|
||||
// ValidateChannelID checks one custom payload id as a Minecraft resource
|
||||
// location: namespace:path with vanilla's character rules. The "minecraft"
|
||||
// namespace is reserved, because every vanilla custom payload id lives there and
|
||||
// reusing one would make the tunnel collide with the game.
|
||||
func ValidateChannelID(id string) error {
|
||||
if id == "" {
|
||||
return fmt.Errorf("empty channel id")
|
||||
}
|
||||
if len(id) > MaxChannelIDLength {
|
||||
return fmt.Errorf("channel id %q is longer than %d bytes", id, MaxChannelIDLength)
|
||||
}
|
||||
namespace, path, found := strings.Cut(id, ":")
|
||||
if !found || strings.Contains(path, ":") {
|
||||
return fmt.Errorf("channel id %q is not namespace:path", id)
|
||||
}
|
||||
if namespace == "" || namespace == ".." || !channelNamespacePattern.MatchString(namespace) {
|
||||
return fmt.Errorf("channel id %q has an invalid namespace: only a-z, 0-9, '_', '.' and '-' are allowed, and it cannot be \"..\"", id)
|
||||
}
|
||||
if namespace == "minecraft" {
|
||||
return fmt.Errorf("channel id %q uses the vanilla \"minecraft\" namespace; vanilla custom payload ids belong to the game", id)
|
||||
}
|
||||
if path == "" || !channelPathPattern.MatchString(path) {
|
||||
return fmt.Errorf("channel id %q has an invalid path: only a-z, 0-9, '_', '-', '.' and '/' are allowed", id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestChannelIDsDefaults(t *testing.T) {
|
||||
dataChannel, paddingChannel, err := (&Config{}).ChannelIDs()
|
||||
if err != nil {
|
||||
t.Fatalf("default channels: %v", err)
|
||||
}
|
||||
if dataChannel != DefaultDataChannel || paddingChannel != DefaultPaddingChannel {
|
||||
t.Fatalf("defaults = %q, %q", dataChannel, paddingChannel)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelIDsConfigured(t *testing.T) {
|
||||
config := &Config{DataChannel: "myxmc:stream", PaddingChannel: "myxmc:noise"}
|
||||
dataChannel, paddingChannel, err := config.ChannelIDs()
|
||||
if err != nil {
|
||||
t.Fatalf("configured channels: %v", err)
|
||||
}
|
||||
if dataChannel != "myxmc:stream" || paddingChannel != "myxmc:noise" {
|
||||
t.Fatalf("channels = %q, %q", dataChannel, paddingChannel)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelIDsRejectEqualChannels(t *testing.T) {
|
||||
config := &Config{DataChannel: "myxmc:same", PaddingChannel: "myxmc:same"}
|
||||
if _, _, err := config.ChannelIDs(); err == nil {
|
||||
t.Fatal("expected an error for one channel used twice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateChannelID(t *testing.T) {
|
||||
tests := []struct {
|
||||
id string
|
||||
ok bool
|
||||
}{
|
||||
{"xmc:data", true},
|
||||
{"a:b", true},
|
||||
{"my-xmc:v1/main.data", true},
|
||||
{strings.Repeat("a", 126) + ":b", true}, // exactly 128 bytes
|
||||
{"", false},
|
||||
{"xmcdata", false},
|
||||
{"xmc:data:extra", false},
|
||||
{":data", false},
|
||||
{"xmc:", false},
|
||||
{"Xmc:data", false},
|
||||
{"xmc:Data", false},
|
||||
{"..:data", false},
|
||||
{"xmc:data space", false},
|
||||
{"xmc:data!", false},
|
||||
{"minecraft:data", false},
|
||||
{"minecraft:brand", false},
|
||||
{strings.Repeat("a", 127) + ":b", false}, // 129 bytes
|
||||
}
|
||||
for _, test := range tests {
|
||||
err := ValidateChannelID(test.id)
|
||||
if test.ok && err != nil {
|
||||
t.Fatalf("%q: unexpected error %v", test.id, err)
|
||||
}
|
||||
if !test.ok && err == nil {
|
||||
t.Fatalf("%q: expected an error", test.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPaddingFramingDependsOnChannelLength pins that the exact frame lengths of
|
||||
// a captured preset follow the configured channel name instead of the default.
|
||||
func TestPaddingFramingDependsOnChannelLength(t *testing.T) {
|
||||
const channel = "my-long-namespace:padding-channel"
|
||||
framing := newPaddingFraming(channel)
|
||||
if got, want := framing.overhead(), defaultPaddingFraming.overhead()+len(channel)-len(DefaultPaddingChannel); got != want {
|
||||
t.Fatalf("overhead = %d, want %d", got, want)
|
||||
}
|
||||
for _, length := range []int{1024, 48 * 1024, 1024 * 1024} {
|
||||
plan, err := framing.plan(length)
|
||||
if err != nil {
|
||||
t.Fatalf("plan %d: %v", length, err)
|
||||
}
|
||||
total := 0
|
||||
for _, frameLength := range plan {
|
||||
if _, ok := framing.frameDataLength(frameLength); !ok {
|
||||
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
|
||||
}
|
||||
total += frameLength
|
||||
}
|
||||
if total != length {
|
||||
t.Fatalf("plan %d totals %d", length, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPaddingChannelIsConfigurable checks that the startup-padding reader drains
|
||||
// exactly the configured channel and leaves every other payload alone.
|
||||
func TestPaddingChannelIsConfigurable(t *testing.T) {
|
||||
const paddingChannel = "myxmc:noise"
|
||||
packetID := paddingFramePacketID(configurationPacketIDs121, false)
|
||||
|
||||
build := func() []byte {
|
||||
var wire bytes.Buffer
|
||||
channel := String(paddingChannel)
|
||||
padding := RestBytes(make([]byte, 64))
|
||||
if err := writePacket(&wire, packetID, &channel, &padding); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
following := String(DefaultDataChannel)
|
||||
payload := RestBytes("tunnel bytes")
|
||||
if err := writePacket(&wire, packetID, &following, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return wire.Bytes()
|
||||
}
|
||||
|
||||
channelOf := func(frame []byte) string {
|
||||
t.Helper()
|
||||
packet, err := readPacket(bytes.NewReader(frame))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var channel String
|
||||
if err := channel.readFrom(bytes.NewReader(packet.data)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(channel)
|
||||
}
|
||||
|
||||
frame, err := readPastPadding(bytes.NewReader(build()), packetID, paddingChannel)
|
||||
if err != nil {
|
||||
t.Fatalf("readPastPadding: %v", err)
|
||||
}
|
||||
if got := channelOf(frame); got != DefaultDataChannel {
|
||||
t.Fatalf("drained past the configured padding channel, got %q", got)
|
||||
}
|
||||
|
||||
// A different configured name must not silently drop the frame.
|
||||
frame, err = readPastPadding(bytes.NewReader(build()), packetID, "other:pad")
|
||||
if err != nil {
|
||||
t.Fatalf("readPastPadding with another channel: %v", err)
|
||||
}
|
||||
if got := channelOf(frame); got != paddingChannel {
|
||||
t.Fatalf("expected the unrecognized frame back, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTickStreamUsesConfiguredChannels checks that a configured pair reaches the
|
||||
// wire: data payloads on the data channel, idle ticks on the padding channel.
|
||||
func TestTickStreamUsesConfiguredChannels(t *testing.T) {
|
||||
const (
|
||||
dataChannel = "myxmc:stream"
|
||||
paddingChannel = "myxmc:noise"
|
||||
)
|
||||
writer := &tickTestWriter{}
|
||||
stream := newTickStream(nil, writer, true, configurationPacketIDs121, dataChannel, paddingChannel)
|
||||
defer stream.Stop()
|
||||
|
||||
if _, err := stream.Write([]byte("hello")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(120 * time.Millisecond)
|
||||
stream.Stop()
|
||||
_ = stream.Flush()
|
||||
|
||||
seenData, seenPadding := false, false
|
||||
for _, batch := range writer.snapshot() {
|
||||
for _, packet := range readTickBatch(t, batch) {
|
||||
channel, payload := tickPacketChannelAndPayload(t, packet)
|
||||
switch channel {
|
||||
case dataChannel:
|
||||
seenData = true
|
||||
if !bytes.Equal(payload, []byte("hello")) {
|
||||
t.Fatalf("data payload = %q", payload)
|
||||
}
|
||||
case paddingChannel:
|
||||
seenPadding = true
|
||||
default:
|
||||
t.Fatalf("unexpected channel %q", channel)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !seenData || !seenPadding {
|
||||
t.Fatalf("configured channels not used: data=%v padding=%v", seenData, seenPadding)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,11 @@ type clientConn struct {
|
||||
|
||||
state clientState
|
||||
|
||||
// protocol selects the packet ids and field shapes of the login the client
|
||||
// performs. The server picks its own row from the handshake, so both ends
|
||||
// agree without a negotiation round trip.
|
||||
protocol protocolVersion
|
||||
|
||||
handshakeLock sync.Mutex
|
||||
lifecycleMu sync.Mutex
|
||||
closed bool
|
||||
@@ -30,9 +35,11 @@ type clientConn struct {
|
||||
password string
|
||||
rsaPublicKey []byte
|
||||
hostname string
|
||||
dataChannel string
|
||||
paddingChannel string
|
||||
yggdrasil *yggdrasilAuth
|
||||
paddingSchedule []paddingTurn
|
||||
packet *packetStream
|
||||
packet *tickStream
|
||||
deadlines *connectionDeadlines
|
||||
|
||||
done chan struct{}
|
||||
@@ -46,7 +53,7 @@ var (
|
||||
clientStateProxy clientState = 2
|
||||
)
|
||||
|
||||
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth) (*clientConn, error) {
|
||||
func newClientConn(c net.Conn, protocol protocolVersion, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth, dataChannel, paddingChannel string) (*clientConn, error) {
|
||||
if len(rsaPublicKey) == 0 && yggdrasil == nil {
|
||||
return nil, fmt.Errorf("empty rsa public key")
|
||||
}
|
||||
@@ -61,11 +68,14 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
|
||||
writer: c,
|
||||
c: c,
|
||||
state: clientStateHandshake,
|
||||
protocol: protocol,
|
||||
handshakeLock: sync.Mutex{},
|
||||
profiles: profiles,
|
||||
password: password,
|
||||
rsaPublicKey: rsaPublicKey,
|
||||
hostname: hostname,
|
||||
dataChannel: dataChannel,
|
||||
paddingChannel: paddingChannel,
|
||||
yggdrasil: yggdrasil,
|
||||
paddingSchedule: paddingSchedule,
|
||||
deadlines: newConnectionDeadlines(c),
|
||||
@@ -92,10 +102,10 @@ func (c *clientConn) handshake() error {
|
||||
defer func() { _ = c.deadlines.endHandshake() }()
|
||||
|
||||
var (
|
||||
protocolVersion Varint = Varint(775)
|
||||
serverAddress String = String(c.hostname)
|
||||
serverPort UnsignedShort = UnsignedShort(25565)
|
||||
nextState Varint = Varint(2)
|
||||
protocolNumber Varint = c.protocol.number
|
||||
serverAddress String = String(c.hostname)
|
||||
serverPort UnsignedShort = UnsignedShort(25565)
|
||||
nextState Varint = Varint(2)
|
||||
)
|
||||
|
||||
host, portString, err := net.SplitHostPort(c.c.RemoteAddr().String())
|
||||
@@ -110,11 +120,37 @@ func (c *clientConn) handshake() error {
|
||||
}
|
||||
}
|
||||
|
||||
err = writePacket(c.writer, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState)
|
||||
err = writePacket(c.writer, handshakeServerboundIntention, &protocolNumber, &serverAddress, &serverPort, &nextState)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write handshake packet: %w", err)
|
||||
}
|
||||
|
||||
// The session server keeps a single server id per profile: only the last
|
||||
// /join answers hasJoined. One account is therefore one login at a time, so
|
||||
// the whole exchange is serialized per account until the server has verified
|
||||
// the player and answered with Login Finished. Releasing the lock after
|
||||
// /join alone is not enough: a second login would overwrite the session
|
||||
// while the first server is still polling hasJoined, and that server would
|
||||
// disconnect with unverified_username.
|
||||
//
|
||||
// The lock is released as soon as the login is verified, before the startup
|
||||
// padding (which takes time on purpose) so a queue of connections still
|
||||
// logs in at the API's pace rather than at the peer's padding pace. A peer
|
||||
// that never answers holds this account's logins until the handshake
|
||||
// deadline, which is the same wait its own connection would have.
|
||||
releaseLogin := func() {}
|
||||
if c.yggdrasil != nil {
|
||||
c.yggdrasil.loginMu.Lock()
|
||||
released := false
|
||||
releaseLogin = func() {
|
||||
if !released {
|
||||
released = true
|
||||
c.yggdrasil.loginMu.Unlock()
|
||||
}
|
||||
}
|
||||
defer releaseLogin()
|
||||
}
|
||||
|
||||
// Login Start
|
||||
var selectedProfile loginProfile
|
||||
if c.yggdrasil != nil {
|
||||
@@ -139,57 +175,156 @@ func (c *clientConn) handshake() error {
|
||||
}
|
||||
username := String(selectedProfile.Username)
|
||||
|
||||
err = writePacket(c.writer, 0x00, &username, &selectedProfile.UUID)
|
||||
err = writePacket(c.writer, c.protocol.login.serverboundLoginStart, &username, &selectedProfile.UUID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write login start: %w", err)
|
||||
}
|
||||
|
||||
// Encryption Request
|
||||
pkt, err := readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encryption request: %w", err)
|
||||
}
|
||||
// From here the server drives the login: Encryption Request, then optionally
|
||||
// Set Compression, then Login Finished; queries and cookie requests can
|
||||
// appear at any point between them, so the client loops over the login
|
||||
// packets like a vanilla one instead of expecting a fixed sequence.
|
||||
//
|
||||
// The encryption exchange is mandatory. XMC exists to look like a licensed
|
||||
// player joining an online-mode server (with a third-party API in Yggdrasil
|
||||
// mode), and an offline-mode login skips the encryption request entirely, so
|
||||
// there is nothing to reproduce and nothing to authenticate.
|
||||
handledEncryption := false
|
||||
joinedSession := false
|
||||
for {
|
||||
pkt, readErr := readPacket(c.reader)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("read login packet: %w", readErr)
|
||||
}
|
||||
|
||||
if pkt.packetID != 0x01 {
|
||||
return fmt.Errorf("bad encrypt request packet id")
|
||||
}
|
||||
switch pkt.packetID {
|
||||
case c.protocol.login.clientboundHello:
|
||||
if handledEncryption {
|
||||
return fmt.Errorf("duplicate encryption request")
|
||||
}
|
||||
handledEncryption = true
|
||||
updatedProfile, joined, helloErr := c.handleEncryptionRequest(pkt, selectedProfile)
|
||||
if helloErr != nil {
|
||||
return helloErr
|
||||
}
|
||||
selectedProfile = updatedProfile
|
||||
joinedSession = joined
|
||||
|
||||
case c.protocol.login.clientboundLoginCompression:
|
||||
// Set Compression is not compressed itself and must be handled before
|
||||
// the packet that follows it, which already uses the compressed
|
||||
// framing. The threshold only decides whether the framing applies:
|
||||
// this writer never compresses, so a server-side threshold does not
|
||||
// shrink padding turns.
|
||||
var threshold Varint
|
||||
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
|
||||
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
|
||||
}
|
||||
if threshold >= 0 {
|
||||
c.reader = newCompressionReader(c.reader)
|
||||
c.writer = newCompressionWriter(c.writer)
|
||||
}
|
||||
|
||||
case c.protocol.login.clientboundCustomQuery:
|
||||
// A vanilla 26.x client answers a login query with a null payload: the
|
||||
// server-driven login extensions of older versions are gone, and a
|
||||
// server that still asks gets an explicit "no answer".
|
||||
if answerErr := c.answerCustomQuery(pkt); answerErr != nil {
|
||||
return answerErr
|
||||
}
|
||||
|
||||
case c.protocol.login.clientboundCookieRequest:
|
||||
if answerErr := c.answerCookieRequest(pkt); answerErr != nil {
|
||||
return answerErr
|
||||
}
|
||||
|
||||
case c.protocol.login.clientboundLoginDisconnect:
|
||||
var reason String
|
||||
if readErr := pkt.readFields(&reason); readErr != nil {
|
||||
return fmt.Errorf("authentication rejected")
|
||||
}
|
||||
if isProtocolVersionReject(string(reason)) {
|
||||
forgetProbedVersions()
|
||||
}
|
||||
return fmt.Errorf("authentication rejected: %s", reason)
|
||||
|
||||
case c.protocol.login.clientboundLoginFinished:
|
||||
if !handledEncryption {
|
||||
return fmt.Errorf("server finished the login without an encryption request: offline-mode servers are not supported")
|
||||
}
|
||||
receivedProfile, finishErr := c.readLoginFinished(pkt)
|
||||
if finishErr != nil {
|
||||
return fmt.Errorf("read login finished fields: %w", finishErr)
|
||||
}
|
||||
// Login Finished is written only after the server's hasJoined
|
||||
// succeeded, so the session is verified and the next login for this
|
||||
// account may join.
|
||||
releaseLogin()
|
||||
if verifyErr := c.verifyLoginProfile(receivedProfile, selectedProfile, joinedSession); verifyErr != nil {
|
||||
return verifyErr
|
||||
}
|
||||
selectedProfile = receivedProfile
|
||||
|
||||
loginAcknowledgedLength, writeErr := writePacketWithLength(c.writer, c.protocol.login.serverboundLoginAcknowledged)
|
||||
if writeErr != nil {
|
||||
return fmt.Errorf("write login acknowledged: %w", writeErr)
|
||||
}
|
||||
return c.startProxy(loginAcknowledgedLength)
|
||||
|
||||
default:
|
||||
return fmt.Errorf("unexpected login packet: 0x%02x", pkt.packetID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleEncryptionRequest performs the shared-secret exchange and reports the
|
||||
// session profile plus whether the session server was joined, which decides how
|
||||
// strictly the returned game profile can be checked.
|
||||
func (c *clientConn) handleEncryptionRequest(pkt *mcPacket, profile loginProfile) (loginProfile, bool, error) {
|
||||
var (
|
||||
serverId String
|
||||
publicKey Bytes
|
||||
verifyToken Bytes
|
||||
serverId String
|
||||
publicKey Bytes
|
||||
verifyToken Bytes
|
||||
shouldAuthenticate Boolean
|
||||
)
|
||||
|
||||
err = pkt.readFields(&serverId, &publicKey, &verifyToken)
|
||||
err := pkt.readFields(&serverId, &publicKey, &verifyToken, &shouldAuthenticate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encryption request fields: %w", err)
|
||||
return profile, false, fmt.Errorf("read encryption request fields: %w", err)
|
||||
}
|
||||
|
||||
// shouldAuthenticate is false for an offline-mode server that still encrypts.
|
||||
// XMC only reproduces the online-mode login, so the client does not pretend
|
||||
// to authenticate against it.
|
||||
if c.yggdrasil != nil && !shouldAuthenticate {
|
||||
return profile, false, fmt.Errorf("server asked the client not to authenticate: offline-mode servers are not supported")
|
||||
}
|
||||
|
||||
if c.yggdrasil == nil && !bytes.Equal(publicKey, c.rsaPublicKey) {
|
||||
return fmt.Errorf("server public key mismatch")
|
||||
return profile, false, fmt.Errorf("server public key mismatch")
|
||||
}
|
||||
|
||||
k, err := x509.ParsePKIXPublicKey(publicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse server public key: %w", err)
|
||||
return profile, false, fmt.Errorf("parse server public key: %w", err)
|
||||
}
|
||||
|
||||
rsaPublicKey, ok := k.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return fmt.Errorf("parse server public key: not rsa")
|
||||
return profile, false, fmt.Errorf("parse server public key: not rsa")
|
||||
}
|
||||
if rsaPublicKey.N.BitLen() < 1024 {
|
||||
return fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen())
|
||||
return profile, false, fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen())
|
||||
}
|
||||
|
||||
sharedSecret := make([]byte, 16)
|
||||
if _, err = rand.Read(sharedSecret); err != nil {
|
||||
return fmt.Errorf("generate shared secret: %w", err)
|
||||
return profile, false, fmt.Errorf("generate shared secret: %w", err)
|
||||
}
|
||||
|
||||
encryptedSharedSecret, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encrypt shared secret: %w", err)
|
||||
return profile, false, fmt.Errorf("encrypt shared secret: %w", err)
|
||||
}
|
||||
|
||||
if c.yggdrasil == nil {
|
||||
@@ -198,107 +333,132 @@ func (c *clientConn) handshake() error {
|
||||
|
||||
encryptedVerifyToken, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, verifyToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encrypt verify token: %w", err)
|
||||
return profile, false, fmt.Errorf("encrypt verify token: %w", err)
|
||||
}
|
||||
|
||||
// Send Encryption Response
|
||||
// Send Encryption Response, then switch the ciphers on: vanilla starts
|
||||
// encrypting only after the response itself has been written.
|
||||
err = writePacket(
|
||||
c.writer,
|
||||
0x01,
|
||||
c.protocol.login.serverboundKey,
|
||||
(*Bytes)(&encryptedSharedSecret),
|
||||
(*Bytes)(&encryptedVerifyToken),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write encryption response: %w", err)
|
||||
return profile, false, fmt.Errorf("write encryption response: %w", err)
|
||||
}
|
||||
|
||||
// Enable encryption
|
||||
c.reader, err = newCryptoReader(c.reader, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new crypto reader: %w", err)
|
||||
return profile, false, fmt.Errorf("new crypto reader: %w", err)
|
||||
}
|
||||
|
||||
c.writer, err = newCryptoWriter(c.writer, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new crypto writer: %w", err)
|
||||
return profile, false, fmt.Errorf("new crypto writer: %w", err)
|
||||
}
|
||||
|
||||
if c.yggdrasil != nil {
|
||||
// Standard online-mode login: join the session with the hash of the
|
||||
// handshake data, the server verifies it through hasJoined.
|
||||
serverID := minecraftServerID(string(serverId), sharedSecret, publicKey)
|
||||
token, joinErr := c.yggdrasil.join(context.Background(), serverID)
|
||||
if joinErr != nil {
|
||||
return fmt.Errorf("yggdrasil session join: %w", joinErr)
|
||||
}
|
||||
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
|
||||
if uuidErr != nil {
|
||||
return fmt.Errorf("yggdrasil session join: %w", uuidErr)
|
||||
}
|
||||
selectedProfile = loginProfile{
|
||||
Username: token.profile.Name,
|
||||
UUID: profileUUID,
|
||||
}
|
||||
// Online mode: join the session with the digest of the handshake data so the
|
||||
// server can verify it through hasJoined. The password mode has no session
|
||||
// server; its login is authenticated by the pre-shared password instead.
|
||||
if c.yggdrasil == nil {
|
||||
return profile, false, nil
|
||||
}
|
||||
|
||||
pkt, err = readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login finished: %w", err)
|
||||
serverID := minecraftServerID(string(serverId), sharedSecret, publicKey)
|
||||
token, joinErr := c.yggdrasil.join(context.Background(), serverID)
|
||||
if joinErr != nil {
|
||||
return profile, false, fmt.Errorf("yggdrasil session join: %w", joinErr)
|
||||
}
|
||||
// Set Compression is not compressed itself and must be handled before the
|
||||
// packet that follows it, which already uses the compressed framing. The
|
||||
// threshold only decides whether the framing applies: this writer never
|
||||
// compresses, so a server-side threshold does not shrink padding turns.
|
||||
if pkt.packetID == 0x03 {
|
||||
var threshold Varint
|
||||
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
|
||||
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
|
||||
}
|
||||
if threshold >= 0 {
|
||||
c.reader = newCompressionReader(c.reader)
|
||||
c.writer = newCompressionWriter(c.writer)
|
||||
}
|
||||
pkt, err = readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login finished: %w", err)
|
||||
}
|
||||
}
|
||||
if pkt.packetID == 0x00 {
|
||||
var reason String
|
||||
if readErr := pkt.readFields(&reason); readErr != nil {
|
||||
return fmt.Errorf("authentication rejected")
|
||||
}
|
||||
return fmt.Errorf("authentication rejected: %s", reason)
|
||||
}
|
||||
if pkt.packetID != 0x02 {
|
||||
return fmt.Errorf("bad login finished packet id: %d", pkt.packetID)
|
||||
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
|
||||
if uuidErr != nil {
|
||||
return profile, false, fmt.Errorf("yggdrasil session join: %w", uuidErr)
|
||||
}
|
||||
return loginProfile{Username: token.profile.Name, UUID: profileUUID}, true, nil
|
||||
}
|
||||
|
||||
receivedProfile, err := readLoginSuccess(pkt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login finished fields: %w", err)
|
||||
// answerCustomQuery replies to a login query with a null payload, which is what
|
||||
// a vanilla 26.x client sends.
|
||||
func (c *clientConn) answerCustomQuery(pkt *mcPacket) error {
|
||||
var transactionID Varint
|
||||
if err := pkt.readFields(&transactionID); err != nil {
|
||||
return fmt.Errorf("read login query: %w", err)
|
||||
}
|
||||
if c.yggdrasil != nil {
|
||||
if !sameProfileIdentity(receivedProfile, selectedProfile) {
|
||||
// The answer payload is nullable; a vanilla 26.x client leaves it absent.
|
||||
answered := Boolean(false)
|
||||
if err := writePacket(c.writer, c.protocol.login.serverboundCustomQueryAnswer, &transactionID, &answered); err != nil {
|
||||
return fmt.Errorf("write login query answer: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// answerCookieRequest replies with an absent cookie, like a client that has
|
||||
// never received a cookie for the key.
|
||||
func (c *clientConn) answerCookieRequest(pkt *mcPacket) error {
|
||||
var key String
|
||||
if err := pkt.readFields(&key); err != nil {
|
||||
return fmt.Errorf("read login cookie request: %w", err)
|
||||
}
|
||||
// The cookie is nullable; an absent value means "no cookie for this key".
|
||||
answered := Boolean(false)
|
||||
if err := writePacket(c.writer, c.protocol.login.serverboundCookieResponse, &key, &answered); err != nil {
|
||||
return fmt.Errorf("write login cookie response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readLoginFinished reads the game profile and, from 26.2 on, the connection
|
||||
// session id that follows it. Trailing bytes are ignored on purpose: Mojang has
|
||||
// appended a field to this packet before, and a client that needs an exact
|
||||
// length would stop pairing on the next release.
|
||||
func (c *clientConn) readLoginFinished(pkt *mcPacket) (loginProfile, error) {
|
||||
var (
|
||||
profile loginProfile
|
||||
username String
|
||||
)
|
||||
fields := []field{&profile.UUID, &username, &profile.Properties}
|
||||
if c.protocol.loginFinishedSessionID {
|
||||
var sessionID UUID
|
||||
fields = append(fields, &sessionID)
|
||||
}
|
||||
if err := pkt.readFields(fields...); err != nil {
|
||||
return loginProfile{}, err
|
||||
}
|
||||
profile.Username = string(username)
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
// verifyLoginProfile checks the profile the server returned. A session join
|
||||
// pins the identity to the Yggdrasil account and its signed textures; the
|
||||
// pre-shared password mode compares the configured profile; an offline-mode
|
||||
// server derives the profile from the name, so it is accepted as it is.
|
||||
func (c *clientConn) verifyLoginProfile(received, selected loginProfile, joinedSession bool) error {
|
||||
switch {
|
||||
case joinedSession:
|
||||
if !sameProfileIdentity(received, selected) {
|
||||
return fmt.Errorf("login profile mismatch")
|
||||
}
|
||||
if verifyErr := c.yggdrasil.verifyLoginProfile(receivedProfile); verifyErr != nil {
|
||||
return fmt.Errorf("verify login profile: %w", verifyErr)
|
||||
if err := c.yggdrasil.verifyLoginProfile(received); err != nil {
|
||||
return fmt.Errorf("verify login profile: %w", err)
|
||||
}
|
||||
case c.yggdrasil == nil:
|
||||
if !sameLoginProfile(received, selected) {
|
||||
return fmt.Errorf("login profile mismatch")
|
||||
}
|
||||
} else if !sameLoginProfile(receivedProfile, selectedProfile) {
|
||||
return fmt.Errorf("login profile mismatch")
|
||||
}
|
||||
loginAcknowledgedLength, err := writePacketWithLength(c.writer, 0x03)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write login acknowledged: %w", err)
|
||||
}
|
||||
c.reader = newPaddingReader(c.reader, true)
|
||||
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// startProxy runs the startup padding and hands the connection to the tick
|
||||
// stream. It is called once the login reached the configuration state.
|
||||
func (c *clientConn) startProxy(loginAcknowledgedLength int) error {
|
||||
c.reader = newPaddingReader(c.reader, true, c.paddingChannel, c.protocol.configuration)
|
||||
if err := runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause, c.paddingChannel, c.protocol.configuration); err != nil {
|
||||
_ = c.Close() // Unblock the startup reader if writing failed.
|
||||
return fmt.Errorf("run startup padding: %w", err)
|
||||
}
|
||||
|
||||
packet := newPacketStream(c.reader, c.writer, true)
|
||||
packet := newTickStream(c.reader, c.writer, true, c.protocol.configuration, c.dataChannel, c.paddingChannel)
|
||||
c.lifecycleMu.Lock()
|
||||
if c.closed {
|
||||
c.lifecycleMu.Unlock()
|
||||
@@ -339,6 +499,10 @@ func (c *clientConn) Close() error {
|
||||
c.lifecycleMu.Unlock()
|
||||
c.closeOnce.Do(func() { close(c.done) })
|
||||
if packet != nil {
|
||||
// Write returns once data is queued for the next tick, so a graceful
|
||||
// close has to flush the last tick instead of dropping it.
|
||||
_ = c.c.SetWriteDeadline(time.Now().Add(time.Second))
|
||||
_ = packet.Flush()
|
||||
packet.Stop()
|
||||
}
|
||||
return c.c.Close()
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask"
|
||||
)
|
||||
@@ -30,6 +32,49 @@ func (c *Config) wrapClientAuth() (*yggdrasilAuth, error) {
|
||||
)
|
||||
}
|
||||
|
||||
// gameVersion resolves an explicitly configured protocol row. A configured
|
||||
// value has to be a known row, because a guessed packet id breaks the login in a
|
||||
// way that looks like a network failure.
|
||||
func (c *Config) gameVersion() (protocolVersion, error) {
|
||||
if err := ValidateProtocolVersion(c.ProtocolVersion); err != nil {
|
||||
return protocolVersion{}, err
|
||||
}
|
||||
if c.ProtocolVersion == 0 {
|
||||
return latestProtocolVersion, nil
|
||||
}
|
||||
version, _ := protocolVersionByNumber(Varint(c.ProtocolVersion))
|
||||
return version, nil
|
||||
}
|
||||
|
||||
// clientProtocol resolves the row the client advertises in its handshake. A
|
||||
// configured protocol_version is used as-is; zero asks the peer for its status,
|
||||
// because a vanilla server rejects a client that names another version, and the
|
||||
// status response carries the version its login expects.
|
||||
//
|
||||
// The probe is cached per destination, so a normal connection pays it once in a
|
||||
// while rather than on every dial. A peer that does not answer status (or is
|
||||
// behind another transport) falls back to the newest row, which is what a
|
||||
// client of the newest release sends.
|
||||
func (c *Config) clientProtocol(dest *net.Destination, dialer *finalmask.Dialer) (protocolVersion, error) {
|
||||
if err := ValidateProtocolVersion(c.ProtocolVersion); err != nil {
|
||||
return protocolVersion{}, err
|
||||
}
|
||||
if c.ProtocolVersion != 0 {
|
||||
return c.gameVersion()
|
||||
}
|
||||
|
||||
number, name, err := detectProtocolVersion(dest, c.Hostname, dialer)
|
||||
if err != nil {
|
||||
errors.LogWarning(context.Background(), "XMC: cannot detect the peer's protocol version (", err, "), advertising ", latestProtocolVersion.name, " (", latestProtocolVersion.number, "); set protocolVersion to pin it")
|
||||
return latestProtocolVersion, nil
|
||||
}
|
||||
version, ok := protocolVersionByNumber(number)
|
||||
if !ok {
|
||||
return protocolVersion{}, fmt.Errorf("the peer reports Minecraft %q (protocol %d), which is not in the supported table (%s); set protocolVersion to override the detection", name, number, protocolVersionRange())
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
|
||||
profiles, err := profilesFromConfig(c.Profiles)
|
||||
if err != nil {
|
||||
@@ -39,6 +84,14 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
dataChannel, paddingChannel, err := c.ChannelIDs()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
protocol, err := c.clientProtocol(dest, dialer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
|
||||
auth, err := c.wrapClientAuth()
|
||||
if err != nil {
|
||||
@@ -56,7 +109,7 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
|
||||
rsaPublicKey = c.RsaPublicKey
|
||||
}
|
||||
|
||||
cc, err := newClientConn(conn, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth)
|
||||
cc, err := newClientConn(conn, protocol, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth, dataChannel, paddingChannel)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
@@ -73,6 +126,10 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
dataChannel, paddingChannel, err := c.ChannelIDs()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
|
||||
var verifier *yggdrasilVerifier
|
||||
if c.Yggdrasil != nil {
|
||||
@@ -85,7 +142,7 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
|
||||
return nil, fmt.Errorf("minecraft finalmask: empty profiles")
|
||||
}
|
||||
|
||||
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier)
|
||||
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier, dataChannel, paddingChannel)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||
}
|
||||
|
||||
@@ -189,9 +189,24 @@ type Config struct {
|
||||
Yggdrasil *Yggdrasil `protobuf:"bytes,13,opt,name=yggdrasil,proto3" json:"yggdrasil,omitempty"`
|
||||
// Disables startup padding. The configuration sets this for an explicit
|
||||
// empty "paddings" array, which an unset repeated field cannot express.
|
||||
NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"`
|
||||
// Custom payload channel that carries the tunnel byte stream, and the one
|
||||
// that carries startup padding. Both ends must use the same pair; empty
|
||||
// keeps the built-in default. Both are namespace:path resource locations,
|
||||
// so vanilla's "minecraft" namespace is rejected: those ids belong to the
|
||||
// game, and reusing one would collide with a vanilla payload.
|
||||
DataChannel string `protobuf:"bytes,15,opt,name=data_channel,json=dataChannel,proto3" json:"data_channel,omitempty"`
|
||||
PaddingChannel string `protobuf:"bytes,16,opt,name=padding_channel,json=paddingChannel,proto3" json:"padding_channel,omitempty"`
|
||||
// Minecraft release the client advertises in its handshake, as a network
|
||||
// protocol number (for example 777 for 26.3). Zero probes the peer: the
|
||||
// client asks for its status and advertises the protocol the peer reports,
|
||||
// falling back to the newest version the mask knows when the peer does not
|
||||
// answer (the probe result is cached per destination). Set it to skip the
|
||||
// probe or to pin a version; the server always follows the version the
|
||||
// client names.
|
||||
ProtocolVersion uint32 `protobuf:"varint,17,opt,name=protocol_version,json=protocolVersion,proto3" json:"protocol_version,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Config) Reset() {
|
||||
@@ -280,6 +295,27 @@ func (x *Config) GetNoPadding() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *Config) GetDataChannel() string {
|
||||
if x != nil {
|
||||
return x.DataChannel
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Config) GetPaddingChannel() string {
|
||||
if x != nil {
|
||||
return x.PaddingChannel
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Config) GetProtocolVersion() uint32 {
|
||||
if x != nil {
|
||||
return x.ProtocolVersion
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type Padding struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"`
|
||||
@@ -379,7 +415,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
|
||||
"\x03api\x18\x01 \x01(\tR\x03api\x12\x1a\n" +
|
||||
"\busername\x18\x02 \x01(\tR\busername\x12\x1a\n" +
|
||||
"\bpassword\x18\x03 \x01(\tR\bpassword\x12\x16\n" +
|
||||
"\x06player\x18\x04 \x01(\tR\x06player\"\x9b\x03\n" +
|
||||
"\x06player\x18\x04 \x01(\tR\x06player\"\x92\x04\n" +
|
||||
"\x06Config\x12\x1a\n" +
|
||||
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
|
||||
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
|
||||
@@ -390,7 +426,10 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
|
||||
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddings\x12N\n" +
|
||||
"\tyggdrasil\x18\r \x01(\v20.xray.transport.internet.finalmask.xmc.YggdrasilR\tyggdrasil\x12\x1d\n" +
|
||||
"\n" +
|
||||
"no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
|
||||
"no_padding\x18\x0e \x01(\bR\tnoPadding\x12!\n" +
|
||||
"\fdata_channel\x18\x0f \x01(\tR\vdataChannel\x12'\n" +
|
||||
"\x0fpadding_channel\x18\x10 \x01(\tR\x0epaddingChannel\x12)\n" +
|
||||
"\x10protocol_version\x18\x11 \x01(\rR\x0fprotocolVersionJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
|
||||
"\aPadding\x12\x1d\n" +
|
||||
"\n" +
|
||||
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
|
||||
|
||||
@@ -53,6 +53,21 @@ message Config {
|
||||
// Disables startup padding. The configuration sets this for an explicit
|
||||
// empty "paddings" array, which an unset repeated field cannot express.
|
||||
bool no_padding = 14;
|
||||
// Custom payload channel that carries the tunnel byte stream, and the one
|
||||
// that carries startup padding. Both ends must use the same pair; empty
|
||||
// keeps the built-in default. Both are namespace:path resource locations,
|
||||
// so vanilla's "minecraft" namespace is rejected: those ids belong to the
|
||||
// game, and reusing one would collide with a vanilla payload.
|
||||
string data_channel = 15;
|
||||
string padding_channel = 16;
|
||||
// Minecraft release the client advertises in its handshake, as a network
|
||||
// protocol number (for example 777 for 26.3). Zero probes the peer: the
|
||||
// client asks for its status and advertises the protocol the peer reports,
|
||||
// falling back to the newest version the mask knows when the peer does not
|
||||
// answer (the probe result is cached per destination). Set it to skip the
|
||||
// probe or to pin a version; the server always follows the version the
|
||||
// client names.
|
||||
uint32 protocol_version = 17;
|
||||
}
|
||||
|
||||
message Padding {
|
||||
|
||||
@@ -16,10 +16,10 @@ func TestClientRejectsLongLegacyPassword(t *testing.T) {
|
||||
profiles := []loginProfile{{Username: "TestUser"}}
|
||||
publicKey := []byte{0x01}
|
||||
|
||||
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil); err != nil {
|
||||
if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err != nil {
|
||||
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
|
||||
}
|
||||
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil); err == nil {
|
||||
if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err == nil {
|
||||
t.Fatal("expected the long password to be rejected")
|
||||
}
|
||||
}
|
||||
@@ -130,7 +130,7 @@ func TestCloseCancelsPaddingPause(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer server.Close()
|
||||
|
||||
conn, err := newClientConn(client, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil)
|
||||
conn, err := newClientConn(client, latestProtocolVersion, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
@@ -13,9 +14,16 @@ type sha256Stream struct {
|
||||
buf []byte
|
||||
}
|
||||
|
||||
// newSHA256Stream returns a stream seeded with a private copy of seed. The
|
||||
// seed is hashed lazily on every refill, so retaining the caller's slice lets a
|
||||
// later append on the same base array rewrite an already-created stream.
|
||||
// DeriveRSAKey builds "<password>-p-prime" and "<password>-q-prime" from one
|
||||
// password buffer: with a shared array the second append overwrote the first
|
||||
// stream's seed, both primes then came from the "-q-prime" stream, and the
|
||||
// resulting N factored at the first step of Fermat's method.
|
||||
func newSHA256Stream(seed []byte) *sha256Stream {
|
||||
return &sha256Stream{
|
||||
seed: seed,
|
||||
seed: bytes.Clone(seed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +64,8 @@ func derivePrime(stream *sha256Stream) *big.Int {
|
||||
func DeriveRSAKey(password string) (*rsa.PrivateKey, error) {
|
||||
seed := []byte(password)
|
||||
|
||||
// Both appends may write into seed's spare capacity; that is harmless
|
||||
// because each stream keeps its own copy of the bytes it was given.
|
||||
pStream := newSHA256Stream(append(seed, []byte("-p-prime")...))
|
||||
qStream := newSHA256Stream(append(seed, []byte("-q-prime")...))
|
||||
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fermatFactorsInOneStep reports whether the public modulus alone discloses the
|
||||
// private key. One iteration of Fermat's method yields a square exactly when N
|
||||
// is the product of two primes with a small gap, which is what happens when p
|
||||
// and q are derived from the same stream (p == q repaired by stepping q to the
|
||||
// next prime).
|
||||
func fermatFactorsInOneStep(n *big.Int) bool {
|
||||
a := new(big.Int).Sqrt(n)
|
||||
a.Add(a, big.NewInt(1))
|
||||
b2 := new(big.Int).Sub(new(big.Int).Mul(a, a), n)
|
||||
if b2.Sign() < 0 {
|
||||
return false
|
||||
}
|
||||
b := new(big.Int).Sqrt(b2)
|
||||
return new(big.Int).Mul(b, b).Cmp(b2) == 0
|
||||
}
|
||||
|
||||
func requireUsableKey(t *testing.T, password string) *rsa.PrivateKey {
|
||||
t.Helper()
|
||||
key, err := DeriveRSAKey(password)
|
||||
if err != nil {
|
||||
t.Fatalf("DeriveRSAKey(%q): %v", password, err)
|
||||
}
|
||||
if key.N.BitLen() != 1024 {
|
||||
t.Fatalf("%q: N is %d bits, want 1024", password, key.N.BitLen())
|
||||
}
|
||||
if key.E != 65537 {
|
||||
t.Fatalf("%q: E is %d, want 65537", password, key.E)
|
||||
}
|
||||
if len(key.Primes) != 2 {
|
||||
t.Fatalf("%q: got %d primes, want 2", password, len(key.Primes))
|
||||
}
|
||||
if key.Primes[0].Cmp(key.Primes[1]) == 0 {
|
||||
t.Fatalf("%q (%d bytes): p == q", password, len(password))
|
||||
}
|
||||
if fermatFactorsInOneStep(key.N) {
|
||||
t.Fatalf("%q (%d bytes): N factors at the first Fermat step, p and q are neighbouring primes", password, len(password))
|
||||
}
|
||||
if got := new(big.Int).Mul(key.Primes[0], key.Primes[1]); got.Cmp(key.N) != 0 {
|
||||
t.Fatalf("%q: p*q != N", password)
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// TestNewSHA256StreamOwnsItsSeed is the direct regression test for the aliasing
|
||||
// defect: the stream hashes its seed on every refill, so it must not retain a
|
||||
// slice whose backing array a caller may still append to.
|
||||
func TestNewSHA256StreamOwnsItsSeed(t *testing.T) {
|
||||
password := []byte(strings.Repeat("k", 100))
|
||||
// Mimic []byte(password) handing out a buffer with spare capacity, which is
|
||||
// what made the two DeriveRSAKey appends overlap in the first place.
|
||||
shared := make([]byte, len(password), len(password)+2*32)
|
||||
copy(shared, password)
|
||||
|
||||
pStream := newSHA256Stream(append(shared, []byte("-p-prime")...))
|
||||
qStream := newSHA256Stream(append(shared, []byte("-q-prime")...))
|
||||
|
||||
if bytes.HasSuffix(pStream.seed, []byte("-q-prime")) {
|
||||
t.Fatalf("p stream seed was rewritten by the q stream's append: %q", pStream.seed)
|
||||
}
|
||||
if !bytes.HasPrefix(pStream.seed, password) || !bytes.HasSuffix(pStream.seed, []byte("-p-prime")) {
|
||||
t.Fatalf("p stream seed = %q, want <password>-p-prime", pStream.seed)
|
||||
}
|
||||
if !bytes.HasPrefix(qStream.seed, password) || !bytes.HasSuffix(qStream.seed, []byte("-q-prime")) {
|
||||
t.Fatalf("q stream seed = %q, want <password>-q-prime", qStream.seed)
|
||||
}
|
||||
if &pStream.seed[0] == &qStream.seed[0] {
|
||||
t.Fatal("both streams share one backing array")
|
||||
}
|
||||
|
||||
// Whatever happens to the caller's buffer afterwards, the streams are fixed.
|
||||
for i := range shared {
|
||||
shared[i] = 'z'
|
||||
}
|
||||
if !bytes.HasPrefix(pStream.seed, password) || !bytes.HasPrefix(qStream.seed, password) {
|
||||
t.Fatal("stream seed follows the caller's buffer after construction")
|
||||
}
|
||||
}
|
||||
|
||||
func referenceStreamBytes(seed string, blocks int) []byte {
|
||||
out := make([]byte, 0, blocks*sha256.Size)
|
||||
for i := 0; i < blocks; i++ {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(seed))
|
||||
fmt.Fprintf(h, "-%d", i)
|
||||
out = append(out, h.Sum(nil)...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSHA256StreamMatchesReference(t *testing.T) {
|
||||
for _, seed := range []string{
|
||||
"",
|
||||
"password",
|
||||
strings.Repeat("a", 113),
|
||||
"00000000-0000-0000-0000-000000000000-p-prime",
|
||||
} {
|
||||
got := make([]byte, 3*sha256.Size)
|
||||
if _, err := newSHA256Stream([]byte(seed)).Read(got); err != nil {
|
||||
t.Fatalf("seed %q: %v", seed, err)
|
||||
}
|
||||
want := referenceStreamBytes(seed, 3)
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("seed %q: keystream mismatch", seed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeriveRSAKeyAllPasswordLengths sweeps every password length the login
|
||||
// accepts. Lengths whose allocation rounded up left spare capacity for the
|
||||
// "-p-prime"/"-q-prime" appends (33-40, 49-56, 65-72, 81-88, 97-104, 113 at the
|
||||
// time of the fix), but the whole range is checked so a change in allocator size
|
||||
// classes or escape analysis cannot reintroduce the defect unnoticed.
|
||||
func TestDeriveRSAKeyAllPasswordLengths(t *testing.T) {
|
||||
for n := 1; n <= MaxLegacyPasswordLength; n++ {
|
||||
n := n
|
||||
t.Run(fmt.Sprintf("len-%03d", n), func(t *testing.T) {
|
||||
requireUsableKey(t, strings.Repeat("a", n))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeriveRSAKeyBoundaryLengths pins the lengths next to the capacity
|
||||
// boundaries where the pre-fix code switched between aliasing and reallocating.
|
||||
func TestDeriveRSAKeyBoundaryLengths(t *testing.T) {
|
||||
for _, n := range []int{15, 16, 17, 23, 24, 25, 31, 32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57, 63, 64, 65, 71, 72, 73, 79, 80, 81, 87, 88, 89, 95, 96, 97, 103, 104, 105, 111, 112, 113} {
|
||||
n := n
|
||||
t.Run(fmt.Sprintf("len-%03d", n), func(t *testing.T) {
|
||||
requireUsableKey(t, strings.Repeat("b", n))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeriveRSAKeyNonASCIIPasswords covers multi-byte passwords: the affected
|
||||
// ranges are byte lengths, so a 12-character CJK password is a 36-byte one.
|
||||
func TestDeriveRSAKeyNonASCIIPasswords(t *testing.T) {
|
||||
passwords := map[string]string{
|
||||
"cjk-33-bytes": strings.Repeat("密", 11),
|
||||
"cjk-36-bytes": strings.Repeat("密", 12),
|
||||
"emoji-36-bytes": strings.Repeat("🔒", 9),
|
||||
"mixed-utf8": "密码-Password-密码-0123456789-密码-0123",
|
||||
"embedded-nul": "abc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
|
||||
"all-high-bytes": strings.Repeat("\xff", 40),
|
||||
"surrogate-ish-41": strings.Repeat("é", 20) + "x",
|
||||
}
|
||||
for name, password := range passwords {
|
||||
password := password
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Logf("password is %d bytes", len(password))
|
||||
requireUsableKey(t, password)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeriveRSAKeyExtremeInputs keeps the derivation total over sizes far
|
||||
// outside what the login accepts: it is called from configuration building, so
|
||||
// it must not panic or depend on a particular capacity.
|
||||
func TestDeriveRSAKeyExtremeInputs(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"empty": "",
|
||||
"one-byte": "x",
|
||||
"max-accepted": strings.Repeat("m", MaxLegacyPasswordLength),
|
||||
"just-over-max": strings.Repeat("m", MaxLegacyPasswordLength+1),
|
||||
"four-kibibytes": strings.Repeat("m", 4096),
|
||||
}
|
||||
for name, password := range cases {
|
||||
password := password
|
||||
t.Run(name, func(t *testing.T) {
|
||||
requireUsableKey(t, password)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeriveRSAKeyDeterministic checks that both ends of a connection derive the
|
||||
// same key, including when several goroutines build configurations at once.
|
||||
func TestDeriveRSAKeyDeterministic(t *testing.T) {
|
||||
const password = "00000000-0000-0000-0000-000000000000"
|
||||
want := requireUsableKey(t, password).N
|
||||
|
||||
const workers = 8
|
||||
results := make([]*big.Int, workers)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
key, err := DeriveRSAKey(password)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
results[i] = key.N
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
for i, n := range results {
|
||||
if n.Cmp(want) != 0 {
|
||||
t.Fatalf("worker %d derived a different modulus", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeriveRSAKeyKnownAnswers pins the derivation. The key is a wire-level
|
||||
// shared secret: changing it for an unaffected password would break every
|
||||
// existing deployment, so the digests below must only ever change on purpose.
|
||||
// The 8-, 18- and 32-byte entries are byte-identical to what the aliasing code
|
||||
// derived, which is the compatibility promise of the fix; the 36- and 113-byte
|
||||
// entries were the ones whose key had to change.
|
||||
func TestDeriveRSAKeyKnownAnswers(t *testing.T) {
|
||||
cases := []struct {
|
||||
password string
|
||||
nDigest string
|
||||
}{
|
||||
{"password", "cf683eb5c302ca70"},
|
||||
{"padding-regression", "b9e1f7f9b936fb8d"},
|
||||
{strings.Repeat("a", 32), "6692488374c0e7aa"},
|
||||
{"00000000-0000-0000-0000-000000000000", "6d971fd64a5c0981"},
|
||||
{strings.Repeat("m", MaxLegacyPasswordLength), "45b0e2f0dd483585"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
key := requireUsableKey(t, c.password)
|
||||
digest := sha256.Sum256(key.N.Bytes())
|
||||
got := hex.EncodeToString(digest[:8])
|
||||
if got != c.nDigest {
|
||||
t.Fatalf("%d-byte password: N digest %s, want %s (wire-compatibility break)", len(c.password), got, c.nDigest)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,647 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The Encryption Response is the one place where a peer can get an answer out of
|
||||
// the mask before it holds any secret, so every check on it has to be
|
||||
// indistinguishable from every other. These tests drive the real serverConn.login
|
||||
// over a scripted stream, so what the peer writes and what the server answers are
|
||||
// both exact and no socket timing is involved.
|
||||
|
||||
// scriptedServer is one XMC server whose login a test drives packet by packet.
|
||||
type scriptedServer struct {
|
||||
t *testing.T
|
||||
|
||||
key *rsa.PrivateKey
|
||||
conn *serverConn
|
||||
reader *feedReader
|
||||
writer *syncWriter
|
||||
|
||||
challenge []byte
|
||||
|
||||
// requestLength is how many bytes the Encryption Request occupied, so the
|
||||
// answer (everything after it) can be decrypted on its own.
|
||||
requestLength int
|
||||
|
||||
// respond feeds one Encryption Response and returns the server's answer.
|
||||
respond func(sharedSecret, verifyToken []byte) loginOutcome
|
||||
}
|
||||
|
||||
// loginOutcome is what a peer observes after it wrote one Encryption Response:
|
||||
// the bytes the server sent back and the error login() ended with.
|
||||
type loginOutcome struct {
|
||||
answer []byte
|
||||
err error
|
||||
}
|
||||
|
||||
// newScriptedServer runs login() up to the Encryption Response. The peer sends
|
||||
// the Login Start a client would and reads the Encryption Request back.
|
||||
func newScriptedServer(t *testing.T, password string, profiles []loginProfile) *scriptedServer {
|
||||
t.Helper()
|
||||
return newScriptedServerAs(t, password, profiles, profiles[0].Username, profiles[0].UUID)
|
||||
}
|
||||
|
||||
// newScriptedServerAs is newScriptedServer for a peer that logs in as a name the
|
||||
// profile list does not contain, which is how the whitelist rejection is reached.
|
||||
func newScriptedServerAs(t *testing.T, password string, profiles []loginProfile, loginName string, loginUUID UUID) *scriptedServer {
|
||||
t.Helper()
|
||||
|
||||
key, err := DeriveRSAKey("oracle-test-password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var inbound bytes.Buffer
|
||||
if err := writePacket(&inbound, latestProtocolVersion.login.serverboundLoginStart, new(String(loginName)), &loginUUID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := &scriptedServer{
|
||||
t: t,
|
||||
key: key,
|
||||
reader: newFeedReader(inbound.Bytes()),
|
||||
writer: &syncWriter{},
|
||||
}
|
||||
s.conn = &serverConn{
|
||||
reader: s.reader,
|
||||
c: &discardConn{},
|
||||
state: serverStateHandshake,
|
||||
protocol: latestProtocolVersion,
|
||||
profiles: profiles,
|
||||
password: password,
|
||||
rsaPrivateKey: key,
|
||||
rsaPublicKey: publicKey,
|
||||
dataChannel: DefaultDataChannel,
|
||||
paddingChannel: DefaultPaddingChannel,
|
||||
deadlines: newConnectionDeadlines(&discardConn{}),
|
||||
done: make(chan struct{}),
|
||||
yggdrasil: nil,
|
||||
paddingSchedule: nil,
|
||||
}
|
||||
// The Encryption Request goes straight to the peer's socket, so it lands in
|
||||
// the same buffer the encrypted answer will.
|
||||
s.conn.writer = s.writer
|
||||
|
||||
loginDone := make(chan error, 1)
|
||||
go func() { loginDone <- s.conn.login() }()
|
||||
|
||||
// The Encryption Request is one packet and the server writes it as it goes;
|
||||
// wait until it is fully there instead of reading a writer that is still
|
||||
// being filled.
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
// A frame that decoded fully is the only reliable signal that the
|
||||
// server has written all of it; counting frames would accept a
|
||||
// half-written one.
|
||||
if frames, ok := decodeAllPackets(s.writer.snapshot()); ok && frames == 1 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
select {
|
||||
case loginErr := <-loginDone:
|
||||
t.Fatalf("login returned before the encryption request: %v (wrote % x)", loginErr, s.writer.snapshot())
|
||||
default:
|
||||
}
|
||||
t.Fatalf("the server did not write the encryption request: % x", s.writer.snapshot())
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
|
||||
// Parse the Encryption Request from a snapshot: the buffer keeps every byte
|
||||
// the server writes, later answers included.
|
||||
written := s.writer.snapshot()
|
||||
s.requestLength = countFrameBytes(written)
|
||||
request, err := readPacket(bytes.NewReader(written))
|
||||
if err != nil {
|
||||
t.Fatalf("read encryption request: %v", err)
|
||||
}
|
||||
if request.packetID != latestProtocolVersion.login.clientboundHello {
|
||||
t.Fatalf("login packet id = 0x%02x, want the encryption request", request.packetID)
|
||||
}
|
||||
var (
|
||||
serverID String
|
||||
publicKeyField Bytes
|
||||
verifyToken Bytes
|
||||
shouldAuthenticate Boolean
|
||||
)
|
||||
if err := request.readFields(&serverID, &publicKeyField, &verifyToken, &shouldAuthenticate); err != nil {
|
||||
t.Fatalf("read encryption request fields: %v", err)
|
||||
}
|
||||
s.challenge = verifyToken
|
||||
|
||||
// Feed the Encryption Response when the peer answers, and collect the
|
||||
// server's reply afterwards.
|
||||
s.respond = func(sharedSecret, verifyToken []byte) loginOutcome {
|
||||
sharedField := Bytes(append([]byte(nil), sharedSecret...))
|
||||
tokenField := Bytes(append([]byte(nil), verifyToken...))
|
||||
frame, err := encodePacket(latestProtocolVersion.login.serverboundKey, &sharedField, &tokenField)
|
||||
if err != nil {
|
||||
t.Fatalf("encode encryption response: %v", err)
|
||||
}
|
||||
s.reader.feed(frame)
|
||||
return s.await(loginDone)
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// await waits for login() to return and returns everything the server wrote.
|
||||
func (s *scriptedServer) await(done <-chan error) loginOutcome {
|
||||
s.t.Helper()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
return loginOutcome{answer: s.answer(), err: err}
|
||||
case <-time.After(20 * time.Second):
|
||||
s.t.Fatal("login did not return")
|
||||
return loginOutcome{}
|
||||
}
|
||||
}
|
||||
|
||||
// validToken builds the second block a password-mode client sends: the challenge
|
||||
// followed by the password, encrypted with the server's public key.
|
||||
func (s *scriptedServer) validToken(password string) []byte {
|
||||
s.t.Helper()
|
||||
plaintext := append(append([]byte(nil), s.challenge...), []byte(password)...)
|
||||
return s.encrypt(plaintext)
|
||||
}
|
||||
|
||||
// encrypt builds one PKCS#1 v1.5 block with the public key, exactly as a client
|
||||
// does with Cipher.getInstance("RSA"). The ciphertext is emitted in its shortest
|
||||
// form, so the tests also cover a peer whose implementation does not write the
|
||||
// full modulus width.
|
||||
func (s *scriptedServer) encrypt(plaintext []byte) []byte {
|
||||
s.t.Helper()
|
||||
|
||||
k := s.key.Size()
|
||||
if len(plaintext) > k-11 {
|
||||
s.t.Fatalf("plaintext of %d bytes does not fit a %d-byte block", len(plaintext), k)
|
||||
}
|
||||
|
||||
em := make([]byte, k)
|
||||
em[1] = 0x02
|
||||
padding := em[2 : k-1-len(plaintext)]
|
||||
if _, err := io.ReadFull(rand.Reader, padding); err != nil {
|
||||
s.t.Fatal(err)
|
||||
}
|
||||
for i := range padding {
|
||||
for padding[i] == 0 {
|
||||
if _, err := io.ReadFull(rand.Reader, padding[i:i+1]); err != nil {
|
||||
s.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
copy(em[k-len(plaintext):], plaintext)
|
||||
|
||||
m := new(big.Int).SetBytes(em)
|
||||
c := new(big.Int).Exp(m, big.NewInt(int64(s.key.E)), s.key.N)
|
||||
return c.Bytes()
|
||||
}
|
||||
|
||||
// answer returns everything the server wrote after the Encryption Request.
|
||||
func (s *scriptedServer) answer() []byte {
|
||||
written := s.writer.snapshot()
|
||||
if s.requestLength > len(written) {
|
||||
return nil
|
||||
}
|
||||
return append([]byte(nil), written[s.requestLength:]...)
|
||||
}
|
||||
|
||||
// decryptDisconnect decrypts the answer with the session key the test chose and
|
||||
// returns the reason of the Login Disconnect inside it. Every server in these
|
||||
// tests closes with that packet, so a peer that holds the key sees exactly this.
|
||||
func (s *scriptedServer) decryptDisconnect(answer, sessionKey []byte) string {
|
||||
s.t.Helper()
|
||||
|
||||
block, err := newAESCipher(sessionKey)
|
||||
if err != nil {
|
||||
s.t.Fatal(err)
|
||||
}
|
||||
plaintext := make([]byte, len(answer))
|
||||
newCFB8Decrypt(block, sessionKey).XORKeyStream(plaintext, answer)
|
||||
|
||||
packet, err := readPacket(bytes.NewReader(plaintext))
|
||||
if err != nil {
|
||||
s.t.Fatalf("decrypt answer: %v (plaintext % x)", err, plaintext)
|
||||
}
|
||||
if packet.packetID != latestProtocolVersion.login.clientboundLoginDisconnect {
|
||||
s.t.Fatalf("packet id in the encrypted answer = 0x%02x, want a login disconnect", packet.packetID)
|
||||
}
|
||||
var reason String
|
||||
if err := packet.readFields(&reason); err != nil {
|
||||
s.t.Fatalf("read disconnect reason: %v", err)
|
||||
}
|
||||
return string(reason)
|
||||
}
|
||||
|
||||
// decodeAllPackets counts the packets a byte stream holds and reports whether
|
||||
// the stream ended on a packet boundary and every packet decoded. A single
|
||||
// frame that grows while it is being written therefore reports ok == false.
|
||||
func decodeAllPackets(data []byte) (int, bool) {
|
||||
frames := 0
|
||||
rest := data
|
||||
for len(rest) > 0 {
|
||||
var length int
|
||||
size := 0
|
||||
for {
|
||||
if size >= len(rest) {
|
||||
return frames, false
|
||||
}
|
||||
b := rest[size]
|
||||
length |= int(b&0x7f) << (7 * size)
|
||||
size++
|
||||
if b&0x80 == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if size+length > len(rest) {
|
||||
return frames, false
|
||||
}
|
||||
if _, err := readPacket(bytes.NewReader(rest[:size+length])); err != nil {
|
||||
return frames, false
|
||||
}
|
||||
rest = rest[size+length:]
|
||||
frames++
|
||||
}
|
||||
return frames, true
|
||||
}
|
||||
|
||||
// syncWriter is the peer's socket: login() writes to it from its own goroutine
|
||||
// while the test reads, so every access is under one lock.
|
||||
type syncWriter struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (w *syncWriter) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.buf.Write(p)
|
||||
}
|
||||
|
||||
func (w *syncWriter) snapshot() []byte {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return append([]byte(nil), w.buf.Bytes()...)
|
||||
}
|
||||
|
||||
// feedReader hands a running login() the bytes the peer writes, one feed at a
|
||||
// time, which a bytes.Reader cannot do once login() holds it.
|
||||
type feedReader struct {
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
pending []byte
|
||||
closed bool
|
||||
}
|
||||
|
||||
func newFeedReader(initial []byte) *feedReader {
|
||||
r := &feedReader{pending: append([]byte(nil), initial...)}
|
||||
r.cond = sync.NewCond(&r.mu)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *feedReader) feed(data []byte) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.pending = append(r.pending, data...)
|
||||
r.cond.Broadcast()
|
||||
}
|
||||
|
||||
func (r *feedReader) Read(p []byte) (int, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for len(r.pending) == 0 && !r.closed {
|
||||
r.cond.Wait()
|
||||
}
|
||||
if len(r.pending) == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, r.pending)
|
||||
r.pending = r.pending[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// discardConn satisfies net.Conn for a scripted server that never blocks.
|
||||
type discardConn struct{}
|
||||
|
||||
func (discardConn) Read([]byte) (int, error) { return 0, io.EOF }
|
||||
func (discardConn) Write(p []byte) (int, error) { return len(p), nil }
|
||||
func (discardConn) Close() error { return nil }
|
||||
func (discardConn) LocalAddr() net.Addr { return nil }
|
||||
func (discardConn) RemoteAddr() net.Addr { return nil }
|
||||
func (discardConn) SetDeadline(time.Time) error { return nil }
|
||||
func (discardConn) SetReadDeadline(time.Time) error { return nil }
|
||||
func (discardConn) SetWriteDeadline(time.Time) error { return nil }
|
||||
|
||||
// TestEncryptionResponseBadSecretIsRandom checks the fallback itself: a block
|
||||
// that does not unpad to exactly sixteen bytes must leave a random secret, not a
|
||||
// truncated one and not the bytes the peer sent.
|
||||
func TestEncryptionResponseBadSecretIsRandom(t *testing.T) {
|
||||
s := newScriptedServer(t, "right-password", []loginProfile{{Username: "TestUser"}})
|
||||
|
||||
bad := s.encrypt(make([]byte, aesKeyLength))
|
||||
bad[0] ^= 0xff
|
||||
|
||||
seen := make(map[string]bool)
|
||||
for range 8 {
|
||||
secret, block, ok := s.conn.decryptSharedSecret(bad)
|
||||
if !ok || block == nil {
|
||||
t.Fatal("a bad block must still yield a session key to carry on with")
|
||||
}
|
||||
seen[string(secret)] = true
|
||||
}
|
||||
if len(seen) < 2 {
|
||||
t.Fatal("every bad block produced the same session key; the fallback is not random")
|
||||
}
|
||||
|
||||
// A block that unpads to the wrong length must take the same fallback. The
|
||||
// plaintext is not a session key, so it must not be used as one.
|
||||
for _, length := range []int{0, 1, 15, 17, 117} {
|
||||
short := s.encrypt(make([]byte, length))
|
||||
first, _, ok := s.conn.decryptSharedSecret(short)
|
||||
if !ok {
|
||||
t.Fatalf("%d-byte message: no session key", length)
|
||||
}
|
||||
second, _, ok := s.conn.decryptSharedSecret(short)
|
||||
if !ok {
|
||||
t.Fatalf("%d-byte message: no session key", length)
|
||||
}
|
||||
if bytes.Equal(first, second) {
|
||||
t.Fatalf("%d-byte message: the fallback secret repeats", length)
|
||||
}
|
||||
if len(first) != aesKeyLength {
|
||||
t.Fatalf("%d-byte message: secret is %d bytes", length, len(first))
|
||||
}
|
||||
}
|
||||
|
||||
secret, _, ok := s.conn.decryptSharedSecret(s.encrypt(make([]byte, aesKeyLength)))
|
||||
if !ok || !bytes.Equal(secret, make([]byte, aesKeyLength)) {
|
||||
t.Fatalf("a valid block did not yield its plaintext: %x", secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEncryptionResponseDoesNotRevealPadding is the regression test for
|
||||
// GHSA-ggm8-658p-x4mr. The pre-fix server called rsa.DecryptPKCS1v15 and
|
||||
// returned before installing CFB8 when the padding or the plaintext length was
|
||||
// wrong, so an invalid block closed the connection with no answer while a valid
|
||||
// one got an encrypted Login Disconnect: one oracle bit per attempt against a
|
||||
// static, public RSA key. The fixed server carries on with a random secret, so
|
||||
// every one of these blocks must produce an answer of exactly the same length as
|
||||
// the block a peer can verify, and none of them may be rejected before the
|
||||
// cipher is installed.
|
||||
func TestEncryptionResponseDoesNotRevealPadding(t *testing.T) {
|
||||
profiles := []loginProfile{{Username: "TestUser"}}
|
||||
password := "right-password"
|
||||
|
||||
// Baseline: a well-formed block the peer chose the plaintext of, so it can
|
||||
// decrypt the answer. The password is wrong, which is what an oracle query
|
||||
// uses to make the server reach its single rejection.
|
||||
baselineServer := newScriptedServer(t, password, profiles)
|
||||
baseline := baselineServer.respond(baselineServer.encrypt(make([]byte, aesKeyLength)), baselineServer.validToken("wrong-password"))
|
||||
if baseline.err == nil {
|
||||
t.Fatal("the encryption response with a wrong password was accepted")
|
||||
}
|
||||
if len(baseline.answer) == 0 {
|
||||
t.Fatal("a valid block with a wrong password was not answered inside the encrypted stream")
|
||||
}
|
||||
if reason := baselineServer.decryptDisconnect(baseline.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "authservers_down") {
|
||||
t.Fatalf("baseline disconnect reason = %s", reason)
|
||||
}
|
||||
want := len(baseline.answer)
|
||||
|
||||
blocks := []struct {
|
||||
name string
|
||||
make func(*scriptedServer) []byte
|
||||
}{
|
||||
{"valid padding, empty message", func(s *scriptedServer) []byte { return s.encrypt(nil) }},
|
||||
{"valid padding, one-byte message", func(s *scriptedServer) []byte { return s.encrypt([]byte{1}) }},
|
||||
{"valid padding, fifteen-byte message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, 15)) }},
|
||||
{"valid padding, seventeen-byte message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, 17)) }},
|
||||
{"valid padding, longest message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, s.key.Size()-11)) }},
|
||||
{"ciphertext zero", func(s *scriptedServer) []byte { return make([]byte, s.key.Size()) }},
|
||||
{"ciphertext one", func(s *scriptedServer) []byte {
|
||||
block := make([]byte, s.key.Size())
|
||||
block[len(block)-1] = 1
|
||||
return block
|
||||
}},
|
||||
{"ciphertext equal to the modulus", func(s *scriptedServer) []byte {
|
||||
return s.key.N.FillBytes(make([]byte, s.key.Size()))
|
||||
}},
|
||||
{"empty field", func(*scriptedServer) []byte { return nil }},
|
||||
{"field longer than the modulus", func(*scriptedServer) []byte {
|
||||
block := make([]byte, 1023)
|
||||
if _, err := rand.Read(block); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return block
|
||||
}},
|
||||
}
|
||||
|
||||
var fallbackCiphertexts [][]byte
|
||||
for _, tc := range blocks {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := newScriptedServer(t, password, profiles)
|
||||
out := s.respond(tc.make(s), s.validToken("wrong-password"))
|
||||
if out.err == nil {
|
||||
t.Fatal("the encryption response was accepted")
|
||||
}
|
||||
if strings.Contains(out.err.Error(), "verify token mismatch") {
|
||||
t.Fatalf("the block was rejected before the cipher was installed: %v", out.err)
|
||||
}
|
||||
if len(out.answer) != want {
|
||||
t.Fatalf("answer is %d bytes, want %d: the response depends on the shared-secret block", len(out.answer), want)
|
||||
}
|
||||
fallbackCiphertexts = append(fallbackCiphertexts, out.answer)
|
||||
})
|
||||
}
|
||||
|
||||
// The fallback secret is random per connection, so two runs of the same
|
||||
// invalid block must not produce the same answer bytes.
|
||||
t.Run("fallback is fresh per connection", func(t *testing.T) {
|
||||
if len(fallbackCiphertexts) < 2 {
|
||||
t.Fatal("not enough answers collected")
|
||||
}
|
||||
if bytes.Equal(fallbackCiphertexts[0], fallbackCiphertexts[1]) {
|
||||
t.Fatal("the same ciphertext was sent for two random session keys")
|
||||
}
|
||||
})
|
||||
|
||||
// The shape of an adaptive query: take a ciphertext that decrypts to a
|
||||
// session key and perturb it one bit at a time. Whatever padding each
|
||||
// perturbation happens to produce, the answer must keep the same length.
|
||||
t.Run("modified captured ciphertexts", func(t *testing.T) {
|
||||
s := newScriptedServer(t, password, profiles)
|
||||
captured := s.encrypt(make([]byte, aesKeyLength))
|
||||
for i := range 16 {
|
||||
modified := append([]byte(nil), captured...)
|
||||
modified[i%len(modified)] ^= 1 << (i % 8)
|
||||
|
||||
query := newScriptedServer(t, password, profiles)
|
||||
out := query.respond(modified, query.validToken("wrong-password"))
|
||||
if out.err == nil {
|
||||
t.Fatal("the modified ciphertext was accepted")
|
||||
}
|
||||
if len(out.answer) != want {
|
||||
t.Fatalf("query %d answered %d bytes, want %d", i, len(out.answer), want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestEncryptionResponseChallengeIsPubliclyCheckable pins the one difference the
|
||||
// server keeps on purpose: vanilla validates the challenge before it installs
|
||||
// the cipher, so a wrong challenge closes the connection unencrypted. The
|
||||
// challenge is four random bytes the server sent a moment ago, so that shape
|
||||
// discloses nothing.
|
||||
func TestEncryptionResponseChallengeIsPubliclyCheckable(t *testing.T) {
|
||||
profiles := []loginProfile{{Username: "TestUser"}}
|
||||
|
||||
s := newScriptedServer(t, "right-password", profiles)
|
||||
wrongChallenge := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.encrypt([]byte{1, 2, 3, 4}))
|
||||
if wrongChallenge.err == nil || !strings.Contains(wrongChallenge.err.Error(), "verify token mismatch") {
|
||||
t.Fatalf("a wrong challenge was not rejected: %v", wrongChallenge.err)
|
||||
}
|
||||
if len(wrongChallenge.answer) != 0 {
|
||||
t.Fatalf("a bad challenge got %d bytes back, want an unencrypted close", len(wrongChallenge.answer))
|
||||
}
|
||||
|
||||
s = newScriptedServer(t, "right-password", profiles)
|
||||
goodChallenge := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("wrong-password"))
|
||||
if goodChallenge.err == nil {
|
||||
t.Fatal("a wrong password was accepted")
|
||||
}
|
||||
if len(goodChallenge.answer) == 0 {
|
||||
t.Fatal("a good challenge with a wrong password was not answered inside the encrypted stream")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEncryptionResponseRejectionsAreInsideTheStream checks what a peer that
|
||||
// holds the session key actually receives: a Login Disconnect, with the reason
|
||||
// vanilla uses. The whitelist answer is only reachable after the password
|
||||
// matched, so a guesser never sees it.
|
||||
func TestEncryptionResponseRejectionsAreInsideTheStream(t *testing.T) {
|
||||
t.Run("wrong password", func(t *testing.T) {
|
||||
s := newScriptedServer(t, "right-password", []loginProfile{{Username: "TestUser"}})
|
||||
out := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("wrong-password"))
|
||||
if out.err == nil {
|
||||
t.Fatal("a wrong password was accepted")
|
||||
}
|
||||
if reason := s.decryptDisconnect(out.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "multiplayer.disconnect.authservers_down") {
|
||||
t.Fatalf("disconnect reason = %s", reason)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unknown profile", func(t *testing.T) {
|
||||
profiles := []loginProfile{{Username: "Known", UUID: UUID{9, 9, 9}}}
|
||||
|
||||
s := newScriptedServerAs(t, "right-password", profiles, "TestUser", UUID{1, 2, 3})
|
||||
out := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("right-password"))
|
||||
if out.err == nil {
|
||||
t.Fatal("an unknown profile was accepted")
|
||||
}
|
||||
if reason := s.decryptDisconnect(out.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "not white-listed") {
|
||||
t.Fatalf("disconnect reason = %s", reason)
|
||||
}
|
||||
|
||||
// The same answer, from a peer that sent a block it cannot use, must be
|
||||
// the same length: the whitelist rejection cannot become an oracle for
|
||||
// the block either.
|
||||
bad := newScriptedServerAs(t, "right-password", profiles, "TestUser", UUID{1, 2, 3})
|
||||
badOut := bad.respond(make([]byte, bad.key.Size()), bad.validToken("right-password"))
|
||||
if badOut.err == nil {
|
||||
t.Fatal("an unknown profile with an invalid shared secret was accepted")
|
||||
}
|
||||
if len(badOut.answer) != len(out.answer) {
|
||||
t.Fatalf("invalid shared secret answered %d bytes, valid one %d", len(badOut.answer), len(out.answer))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestEncryptionResponseExtremeFields checks the shapes at the edges of the two
|
||||
// fields: they must fail cleanly, without a panic and without a different shape
|
||||
// than any other failure, and the field-length limit itself is the only place
|
||||
// where the packet is refused before decryption - which is public framing the
|
||||
// peer chose.
|
||||
func TestEncryptionResponseExtremeFields(t *testing.T) {
|
||||
profiles := []loginProfile{{Username: "TestUser"}}
|
||||
|
||||
baseline := func(t *testing.T, shared, token []byte) loginOutcome {
|
||||
t.Helper()
|
||||
s := newScriptedServer(t, "right-password", profiles)
|
||||
return s.respond(shared, token)
|
||||
}
|
||||
|
||||
t.Run("empty token field", func(t *testing.T) {
|
||||
out := baseline(t, make([]byte, 128), nil)
|
||||
if out.err == nil || !strings.Contains(out.err.Error(), "verify token mismatch") {
|
||||
t.Fatalf("empty token: %v", out.err)
|
||||
}
|
||||
if len(out.answer) != 0 {
|
||||
t.Fatalf("empty token got %d bytes", len(out.answer))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("token field one byte under the packet field limit", func(t *testing.T) {
|
||||
out := baseline(t, make([]byte, 128), make([]byte, 1023))
|
||||
if out.err == nil || !strings.Contains(out.err.Error(), "verify token mismatch") {
|
||||
t.Fatalf("oversized token: %v", out.err)
|
||||
}
|
||||
if len(out.answer) != 0 {
|
||||
t.Fatalf("oversized token got %d bytes", len(out.answer))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("token field at the packet field limit", func(t *testing.T) {
|
||||
out := baseline(t, make([]byte, 128), make([]byte, 1024))
|
||||
if out.err == nil || !strings.Contains(out.err.Error(), "read encrypt response") {
|
||||
t.Fatalf("token field at the limit: %v", out.err)
|
||||
}
|
||||
if len(out.answer) != 0 {
|
||||
t.Fatalf("token field at the limit got %d bytes", len(out.answer))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("shared secret field at the packet field limit", func(t *testing.T) {
|
||||
out := baseline(t, make([]byte, 1024), nil)
|
||||
if out.err == nil || !strings.Contains(out.err.Error(), "read encrypt response") {
|
||||
t.Fatalf("shared secret field at the limit: %v", out.err)
|
||||
}
|
||||
if len(out.answer) != 0 {
|
||||
t.Fatalf("shared secret field at the limit got %d bytes", len(out.answer))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// countFrameBytes returns the byte length of the first frame in data.
|
||||
func countFrameBytes(data []byte) int {
|
||||
var length int
|
||||
size := 0
|
||||
for {
|
||||
if size >= len(data) {
|
||||
return len(data)
|
||||
}
|
||||
b := data[size]
|
||||
length |= int(b&0x7f) << (7 * size)
|
||||
size++
|
||||
if b&0x80 == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return size + length
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/subtle"
|
||||
)
|
||||
|
||||
const (
|
||||
// aesKeyLength is the shared secret length vanilla's Crypt counts its
|
||||
// cipher on, and the length an XMC client encrypts.
|
||||
aesKeyLength = 16
|
||||
)
|
||||
|
||||
// decryptSharedSecret recovers the AES shared secret and builds its cipher block
|
||||
// without turning the Encryption Response into a Bleichenbacher oracle.
|
||||
//
|
||||
// The wire format is a bare RSA / PKCS#1 v1.5 block, because that is what a
|
||||
// vanilla client writes (Crypt.encryptUsingKey -> Cipher.getInstance("RSA") ->
|
||||
// doFinal) and a mask that answered anything else would stop pairing with one.
|
||||
// Reading it with rsa.DecryptPKCS1v15 and acting on the error - which is what
|
||||
// this server used to do - lets a peer tell a valid block from an invalid one
|
||||
// without knowing the key. The key is static (derived from the password) and
|
||||
// public, so a captured shared secret could then be attacked offline forever.
|
||||
//
|
||||
// rsa.DecryptPKCS1v15SessionKey is the RFC 3218 countermeasure, and the one the
|
||||
// advisory names: a random sixteen-byte secret is chosen first, the block is
|
||||
// decrypted into it, and the random value survives unless the plaintext is
|
||||
// exactly sixteen bytes. The padding verdict and the length verdict are folded
|
||||
// into one constant-time copy, so neither is reported; the private-key operation
|
||||
// runs on the constant-time FIPS module and the padding scan is branch-free.
|
||||
// Nothing downstream can branch on the padding either, because a peer that did
|
||||
// not send a valid block does not learn the secret the server carries on with.
|
||||
//
|
||||
// The challenge block is the opposite case and keeps vanilla's behaviour; see
|
||||
// decryptVerifyToken.
|
||||
func (c *serverConn) decryptSharedSecret(encryptedSharedSecret []byte) ([]byte, cipher.Block, bool) {
|
||||
secret := make([]byte, aesKeyLength)
|
||||
if _, err := rand.Read(secret); err != nil {
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// An error here means the field did not decode to a number below the
|
||||
// modulus: it was longer than the modulus, or equal to or above N. Both are
|
||||
// properties of the peer's own bytes, not a padding verdict, and the random
|
||||
// secret stands either way, so the error is dropped on purpose.
|
||||
_ = rsa.DecryptPKCS1v15SessionKey(nil, c.rsaPrivateKey, encryptedSharedSecret, secret)
|
||||
|
||||
// A secret the AES layer cannot use cannot happen here - the buffer is
|
||||
// sixteen bytes either way - but the caller must not be able to reach a
|
||||
// panic through it, so it folds into the same boolean.
|
||||
block, err := newAESCipher(secret)
|
||||
if err != nil {
|
||||
return nil, nil, false
|
||||
}
|
||||
return secret, block, true
|
||||
}
|
||||
|
||||
// decryptVerifyToken recovers the challenge block. It is not a secret-bearing
|
||||
// plaintext: the challenge is the four random bytes the server sent a moment
|
||||
// ago, so a failed padding here discloses nothing that is not already public.
|
||||
// Vanilla treats it the same way (ServerboundKeyPacket.isChallengeValid turns
|
||||
// bad padding into the same protocol error a wrong challenge produces), and the
|
||||
// outcome is the one difference vanilla draws too: a bad token closes the
|
||||
// connection before the cipher is installed, a good one fails inside it.
|
||||
//
|
||||
// Unlike the shared secret this must return the whole message, because password
|
||||
// mode carries the password after the challenge in the same block, so
|
||||
// rsa.DecryptPKCS1v15 is the right call: its error is the public padding
|
||||
// verdict vanilla already draws, and its length is not secret.
|
||||
func decryptVerifyToken(key *rsa.PrivateKey, encryptedVerifyToken []byte) ([]byte, bool) {
|
||||
plaintext, err := rsa.DecryptPKCS1v15(nil, key, encryptedVerifyToken)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return plaintext, true
|
||||
}
|
||||
|
||||
// challengesEqual compares the challenge the server sent with the plaintext the
|
||||
// peer returned. In password mode the password follows the challenge in the same
|
||||
// block, so a longer plaintext that starts with the challenge is a match;
|
||||
// vanilla compares the whole plaintext, which works there because its client
|
||||
// sends the challenge alone. The comparison is constant time, and only the
|
||||
// length check is not, which is public data deciding a public question.
|
||||
func challengesEqual(want, got []byte) bool {
|
||||
if len(got) < len(want) {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare(want, got[:len(want)]) == 1
|
||||
}
|
||||
@@ -9,10 +9,22 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestHandshakeWithBidirectionalPadding performs the whole login for the oldest
|
||||
// and the newest row: 1.21.1 has no Login Finished session id, 26.3 does, so the
|
||||
// test covers both packet shapes end to end.
|
||||
func TestHandshakeWithBidirectionalPadding(t *testing.T) {
|
||||
for _, version := range []protocolVersion{protocolVersions[0], latestProtocolVersion} {
|
||||
t.Run(version.name, func(t *testing.T) {
|
||||
testHandshakeVersions(t, version)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testHandshakeVersions(t *testing.T, version protocolVersion) {
|
||||
t.Helper()
|
||||
t.Run("pipe", func(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
testHandshakeWithPadding(t, client, server, 64*1024)
|
||||
testHandshakeWithPadding(t, version, client, server, 64*1024)
|
||||
})
|
||||
t.Run("tcp", func(t *testing.T) {
|
||||
listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
@@ -38,11 +50,11 @@ func TestHandshakeWithBidirectionalPadding(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
testHandshakeWithPadding(t, client, server, maxPaddingTurnLength)
|
||||
testHandshakeWithPadding(t, version, client, server, maxPaddingTurnLength)
|
||||
})
|
||||
}
|
||||
|
||||
func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, length int64) {
|
||||
func testHandshakeWithPadding(t *testing.T, version protocolVersion, clientRaw, serverRaw net.Conn, length int64) {
|
||||
t.Helper()
|
||||
defer clientRaw.Close()
|
||||
defer serverRaw.Close()
|
||||
@@ -72,12 +84,12 @@ func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, lengt
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule, nil)
|
||||
client, err := newClientConn(clientRaw, version, profiles, "password", publicKey, "localhost", paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil)
|
||||
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/x509"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newLoginTestClient(t *testing.T, conn net.Conn, version protocolVersion) *clientConn {
|
||||
t.Helper()
|
||||
key, err := DeriveRSAKey("login-flow")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, err := newClientConn(conn, version, []loginProfile{{Username: "TestUser"}}, "password", publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
// TestClientHandshakeAdvertisesConfiguredVersion checks that the handshake
|
||||
// carries the row selected in the configuration, which is what lets one binary
|
||||
// pair with servers of different releases.
|
||||
func TestClientHandshakeAdvertisesConfiguredVersion(t *testing.T) {
|
||||
for _, number := range []Varint{767, 775, 777} {
|
||||
version, ok := protocolVersionByNumber(number)
|
||||
if !ok {
|
||||
t.Fatalf("protocol %d is missing from the table", number)
|
||||
}
|
||||
clientRaw, serverRaw := net.Pipe()
|
||||
client := newLoginTestClient(t, clientRaw, version)
|
||||
go func() { _ = client.handshake() }()
|
||||
|
||||
if err := serverRaw.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
packet, err := readPacket(serverRaw)
|
||||
if err != nil {
|
||||
t.Fatalf("protocol %d: read handshake: %v", number, err)
|
||||
}
|
||||
if packet.packetID != handshakeServerboundIntention {
|
||||
t.Fatalf("protocol %d: handshake packet id = 0x%02x", number, packet.packetID)
|
||||
}
|
||||
var (
|
||||
gotNumber Varint
|
||||
address String
|
||||
port UnsignedShort
|
||||
nextState Varint
|
||||
)
|
||||
if err := packet.readFields(&gotNumber, &address, &port, &nextState); err != nil {
|
||||
t.Fatalf("protocol %d: read handshake fields: %v", number, err)
|
||||
}
|
||||
if gotNumber != number {
|
||||
t.Fatalf("handshake advertised %d, want %d", gotNumber, number)
|
||||
}
|
||||
if nextState != 2 {
|
||||
t.Fatalf("handshake intent = %d, want login (2)", nextState)
|
||||
}
|
||||
|
||||
_ = clientRaw.Close()
|
||||
_ = serverRaw.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientLoginAnswers checks the two optional login exchanges a vanilla 26.x
|
||||
// client answers: a custom query gets a null payload, a cookie request gets an
|
||||
// absent cookie. Both use the ids of the selected version.
|
||||
func TestClientLoginAnswers(t *testing.T) {
|
||||
version := latestProtocolVersion
|
||||
|
||||
t.Run("custom query", func(t *testing.T) {
|
||||
var wire, out bytes.Buffer
|
||||
transactionID := Varint(7)
|
||||
if err := writePacket(&wire, version.login.clientboundCustomQuery, &transactionID, new(String("test:query"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request, err := readPacket(&wire)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &clientConn{protocol: version, writer: &out}
|
||||
if err := client.answerCustomQuery(request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer, err := readPacket(&out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if answer.packetID != version.login.serverboundCustomQueryAnswer {
|
||||
t.Fatalf("answer packet id = 0x%02x", answer.packetID)
|
||||
}
|
||||
// transaction id 7, then the nullable payload marker for "no payload".
|
||||
if !bytes.Equal(answer.data, []byte{0x07, 0x00}) {
|
||||
t.Fatalf("answer body = %x", answer.data)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cookie request", func(t *testing.T) {
|
||||
var wire, out bytes.Buffer
|
||||
if err := writePacket(&wire, version.login.clientboundCookieRequest, new(String("test:cookie"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request, err := readPacket(&wire)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &clientConn{protocol: version, writer: &out}
|
||||
if err := client.answerCookieRequest(request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer, err := readPacket(&out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if answer.packetID != version.login.serverboundCookieResponse {
|
||||
t.Fatalf("answer packet id = 0x%02x", answer.packetID)
|
||||
}
|
||||
var key String
|
||||
if err := answer.readFields(&key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(key) != "test:cookie" {
|
||||
t.Fatalf("cookie key = %q", string(key))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestReadLoginFinished checks both shapes of the packet: before 26.2 the body
|
||||
// ends after the game profile, from 26.2 on a session id follows it. Trailing
|
||||
// bytes are ignored, because Mojang has appended a field to this packet before.
|
||||
func TestReadLoginFinished(t *testing.T) {
|
||||
for _, version := range []protocolVersion{protocolVersions[0], latestProtocolVersion} {
|
||||
var (
|
||||
wire bytes.Buffer
|
||||
profile = loginProfile{Username: "TestUser", UUID: UUID{1, 2, 3}}
|
||||
name = String("TestUser")
|
||||
)
|
||||
fields := []field{&profile.UUID, &name, &profile.Properties}
|
||||
if version.loginFinishedSessionID {
|
||||
sessionID := UUID{9, 9, 9}
|
||||
fields = append(fields, &sessionID)
|
||||
}
|
||||
if err := writePacket(&wire, version.login.clientboundLoginFinished, fields...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
packet, err := readPacket(&wire)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
client := &clientConn{protocol: version}
|
||||
got, err := client.readLoginFinished(packet)
|
||||
if err != nil {
|
||||
t.Fatalf("%s (%d): read login finished: %v", version.name, version.number, err)
|
||||
}
|
||||
if got.Username != "TestUser" || got.UUID != profile.UUID {
|
||||
t.Fatalf("%s (%d): profile = %q %x", version.name, version.number, got.Username, got.UUID)
|
||||
}
|
||||
|
||||
// One missing session id must fail, so the flag cannot silently rot.
|
||||
if version.loginFinishedSessionID {
|
||||
var short bytes.Buffer
|
||||
username := String("TestUser")
|
||||
if err := writePacket(&short, version.login.clientboundLoginFinished, &profile.UUID, &username, &profile.Properties); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
packet, err := readPacket(&short)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.readLoginFinished(packet); err == nil {
|
||||
t.Fatalf("%s: login finished without a session id was accepted", version.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerRejectsUnknownProtocolVersion checks the server answers a version
|
||||
// outside the table with the same Login Disconnect a vanilla server sends,
|
||||
// instead of guessing packet ids.
|
||||
func TestServerRejectsUnknownProtocolVersion(t *testing.T) {
|
||||
key, err := DeriveRSAKey("login-flow")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
clientRaw, serverRaw := net.Pipe()
|
||||
defer clientRaw.Close()
|
||||
defer serverRaw.Close()
|
||||
|
||||
server, err := wrapConnServer(serverRaw, []loginProfile{{Username: "TestUser"}}, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, nil, nil, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handshakeResult := make(chan error, 1)
|
||||
go func() { handshakeResult <- server.handshake() }()
|
||||
|
||||
if err := clientRaw.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var (
|
||||
protocolNumber Varint = 999
|
||||
address String = "localhost"
|
||||
port UnsignedShort = 25565
|
||||
nextState Varint = 2
|
||||
)
|
||||
if err := writePacket(clientRaw, handshakeServerboundIntention, &protocolNumber, &address, &port, &nextState); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
packet, err := readPacket(clientRaw)
|
||||
if err != nil {
|
||||
t.Fatalf("read login disconnect: %v", err)
|
||||
}
|
||||
if packet.packetID != latestProtocolVersion.login.clientboundLoginDisconnect {
|
||||
t.Fatalf("disconnect packet id = 0x%02x", packet.packetID)
|
||||
}
|
||||
var reason String
|
||||
if err := packet.readFields(&reason); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(reason), "multiplayer.disconnect.incompatible") {
|
||||
t.Fatalf("disconnect reason = %s", string(reason))
|
||||
}
|
||||
|
||||
if err := <-handshakeResult; err == nil || !strings.Contains(err.Error(), "unsupported protocol version") {
|
||||
t.Fatalf("handshake error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientRejectsOfflineLogin checks the client refuses a login that never
|
||||
// asks for encryption: XMC reproduces the online-mode login, and an offline
|
||||
// server has none of it.
|
||||
func TestClientRejectsOfflineLogin(t *testing.T) {
|
||||
version := latestProtocolVersion
|
||||
clientRaw, serverRaw := net.Pipe()
|
||||
defer clientRaw.Close()
|
||||
defer serverRaw.Close()
|
||||
|
||||
client := newLoginTestClient(t, clientRaw, version)
|
||||
handshakeResult := make(chan error, 1)
|
||||
go func() { handshakeResult <- client.handshake() }()
|
||||
|
||||
if err := serverRaw.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := readPacket(serverRaw); err != nil {
|
||||
t.Fatalf("read handshake: %v", err)
|
||||
}
|
||||
if _, err := readPacket(serverRaw); err != nil {
|
||||
t.Fatalf("read login start: %v", err)
|
||||
}
|
||||
|
||||
// An offline-mode server answers Login Start with Login Finished directly.
|
||||
var (
|
||||
profile = loginProfile{Username: "TestUser", UUID: UUID{1}}
|
||||
username = String("TestUser")
|
||||
session = UUID{9}
|
||||
)
|
||||
if err := writePacket(serverRaw, version.login.clientboundLoginFinished, &profile.UUID, &username, &profile.Properties, &session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := <-handshakeResult
|
||||
if err == nil || !strings.Contains(err.Error(), "offline-mode servers are not supported") {
|
||||
t.Fatalf("handshake error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientRejectsUnauthenticatedServer checks that a server which still
|
||||
// encrypts but tells the client not to authenticate is refused in Yggdrasil
|
||||
// mode: that flag is an offline-mode server.
|
||||
func TestClientRejectsUnauthenticatedServer(t *testing.T) {
|
||||
version := latestProtocolVersion
|
||||
|
||||
var wire bytes.Buffer
|
||||
var (
|
||||
serverID String
|
||||
publicKey Bytes = Bytes{1, 2, 3}
|
||||
challenge Bytes = Bytes{4, 5, 6, 7}
|
||||
shouldAuthenticate Boolean
|
||||
)
|
||||
if err := writePacket(&wire, version.login.clientboundHello, &serverID, &publicKey, &challenge, &shouldAuthenticate); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request, err := readPacket(&wire)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
client := &clientConn{protocol: version, writer: io.Discard, yggdrasil: &yggdrasilAuth{}}
|
||||
if _, _, err := client.handleEncryptionRequest(request, loginProfile{}); err == nil || !strings.Contains(err.Error(), "offline-mode servers are not supported") {
|
||||
t.Fatalf("handle encryption request error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -4,52 +4,173 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
configurationClientboundCustomPayload = 0x01
|
||||
configurationServerboundCustomPayload = 0x02
|
||||
configurationKeepAlive = 0x04
|
||||
|
||||
packetChannel = "xmc:data"
|
||||
maxPacketData = 24 * 1024
|
||||
keepAlivePeriod = 15 * time.Second
|
||||
|
||||
// tickInterval is one Minecraft game tick. After the handshake the proxy
|
||||
// stream is emitted in one batch per tick so that the connection keeps the
|
||||
// 20 Hz shape of a real client instead of turning into a bulk TCP stream.
|
||||
tickInterval = 50 * time.Millisecond
|
||||
// maxQueuedData bounds proxy data waiting for the next tick. Write blocks
|
||||
// once the queue is full, so a slow peer pushes back to the proxy instead
|
||||
// of growing memory without bound.
|
||||
maxQueuedData = 4 * 1024 * 1024
|
||||
// tickPaddingSize keeps every tick non-empty in both directions, like the
|
||||
// small per-tick packets a real client and server keep sending while idle.
|
||||
tickPaddingSize = 1
|
||||
)
|
||||
|
||||
// packetStream carries the raw proxy byte stream in Minecraft configuration
|
||||
// tickStream carries the raw proxy byte stream in Minecraft configuration
|
||||
// custom payload packets. The configuration state provides bidirectional
|
||||
// payload packets and keep-alives without requiring version-specific world data.
|
||||
type packetStream struct {
|
||||
//
|
||||
// Proxy writes are queued and flushed once per game tick (50 ms). Each tick
|
||||
// always emits at least one small padding frame, so an idle connection keeps
|
||||
// the same 20 Hz cadence as a real client. Data that does not fit in one
|
||||
// payload is split over several payloads in the same tick, which keeps the
|
||||
// per-tick burst shape without an artificial bandwidth cap.
|
||||
type tickStream struct {
|
||||
reader io.Reader
|
||||
writer io.Writer
|
||||
isClient bool
|
||||
|
||||
// packetIDs are the configuration-state ids of the negotiated version: the
|
||||
// custom payload pair that carries the tunnel plus the keep-alives, pings,
|
||||
// cookies and disconnects a peer may send before the tunnel starts.
|
||||
packetIDs configurationPacketIDs
|
||||
|
||||
// Configured custom payload channels: the data one carries proxy bytes, the
|
||||
// padding one keeps an idle tick non-empty. Both ends must use the same pair.
|
||||
dataChannel string
|
||||
paddingChannel string
|
||||
|
||||
readMu sync.Mutex
|
||||
writeMu sync.Mutex
|
||||
pending []byte
|
||||
|
||||
writeMu sync.Mutex
|
||||
|
||||
queueMu sync.Mutex
|
||||
queueCond *sync.Cond
|
||||
queue []byte
|
||||
closed bool
|
||||
|
||||
keepAliveID atomic.Int64
|
||||
done chan struct{}
|
||||
stopOnce sync.Once
|
||||
}
|
||||
|
||||
func newPacketStream(reader io.Reader, writer io.Writer, isClient bool) *packetStream {
|
||||
s := &packetStream{
|
||||
reader: reader,
|
||||
writer: writer,
|
||||
isClient: isClient,
|
||||
done: make(chan struct{}),
|
||||
func newTickStream(reader io.Reader, writer io.Writer, isClient bool, packetIDs configurationPacketIDs, dataChannel, paddingChannel string) *tickStream {
|
||||
s := &tickStream{
|
||||
reader: reader,
|
||||
writer: writer,
|
||||
isClient: isClient,
|
||||
packetIDs: packetIDs,
|
||||
dataChannel: dataChannel,
|
||||
paddingChannel: paddingChannel,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
s.queueCond = sync.NewCond(&s.queueMu)
|
||||
go s.tickLoop()
|
||||
if !isClient {
|
||||
go s.keepAliveLoop()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *packetStream) Read(p []byte) (int, error) {
|
||||
func (s *tickStream) tickLoop() {
|
||||
ticker := time.NewTicker(tickInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if err := s.flushTick(); err != nil {
|
||||
s.Stop()
|
||||
return
|
||||
}
|
||||
case <-s.done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// flushTick writes one game tick worth of packets in a single network write:
|
||||
// queued proxy data first, then one small padding frame. Data is split into
|
||||
// payloads of at most maxPacketData bytes, but every payload stays in this
|
||||
// tick's batch, so a busy connection looks like Minecraft chunk bursts rather
|
||||
// than a continuous stream.
|
||||
func (s *tickStream) flushTick() error {
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
|
||||
data := s.takeQueue()
|
||||
|
||||
var batch bytes.Buffer
|
||||
if err := s.writeDataPackets(&batch, data); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeCustomPayload(&batch, s.localCustomPayloadID(), s.paddingChannel, make([]byte, tickPaddingSize)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := s.writer.Write(batch.Bytes()); err != nil {
|
||||
return fmt.Errorf("write minecraft tick: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Flush writes queued proxy data immediately instead of waiting for the next
|
||||
// tick. Close uses it so the last bytes are not dropped after Write returned.
|
||||
func (s *tickStream) Flush() error {
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
|
||||
data := s.takeQueue()
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var batch bytes.Buffer
|
||||
if err := s.writeDataPackets(&batch, data); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.writer.Write(batch.Bytes())
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *tickStream) takeQueue() []byte {
|
||||
s.queueMu.Lock()
|
||||
defer s.queueMu.Unlock()
|
||||
data := s.queue
|
||||
s.queue = nil
|
||||
s.queueCond.Broadcast()
|
||||
return data
|
||||
}
|
||||
|
||||
func (s *tickStream) writeDataPackets(batch *bytes.Buffer, data []byte) error {
|
||||
for len(data) > 0 {
|
||||
n := min(len(data), maxPacketData)
|
||||
if err := writeCustomPayload(batch, s.localCustomPayloadID(), s.dataChannel, data[:n]); err != nil {
|
||||
return err
|
||||
}
|
||||
data = data[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeCustomPayload(w io.Writer, packetID int, channel string, payload []byte) error {
|
||||
name := String(channel)
|
||||
data := RestBytes(payload)
|
||||
return writePacket(w, packetID, &name, &data)
|
||||
}
|
||||
|
||||
func (s *tickStream) Read(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -70,7 +191,7 @@ func (s *packetStream) Read(p []byte) (int, error) {
|
||||
}
|
||||
|
||||
if packet.packetID == s.remoteCustomPayloadID() {
|
||||
payload, ok, err := parseCustomPayload(packet)
|
||||
payload, ok, err := parseCustomPayload(packet, s.dataChannel)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -85,70 +206,99 @@ func (s *packetStream) Read(p []byte) (int, error) {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
if packet.packetID == configurationKeepAlive {
|
||||
// Everything else in this state is server chatter: the client answers
|
||||
// what a vanilla client answers and skips the rest (registry data, tags,
|
||||
// dialogs...), which is what keeps it working across releases. The server
|
||||
// side only reads tunnel data, so it skips all of it.
|
||||
if !s.isClient {
|
||||
continue
|
||||
}
|
||||
|
||||
switch packet.packetID {
|
||||
case s.packetIDs.clientboundKeepAlive:
|
||||
var id Long
|
||||
if err := packet.readFields(&id); err != nil {
|
||||
return 0, fmt.Errorf("read minecraft keep-alive: %w", err)
|
||||
}
|
||||
if s.isClient {
|
||||
if err := s.writeKeepAlive(id); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := s.writeKeepAlive(s.packetIDs.serverboundKeepAlive, id); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
case s.packetIDs.clientboundPing:
|
||||
// Configuration Ping is answered with Pong, like a real client. The
|
||||
// id is a plain 32-bit integer here, not a varint.
|
||||
var id Int
|
||||
if err := packet.readFields(&id); err != nil {
|
||||
return 0, fmt.Errorf("read minecraft ping: %w", err)
|
||||
}
|
||||
if err := s.writePong(id); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
case s.packetIDs.clientboundCookieRequest:
|
||||
if err := s.writeCookieResponse(packet); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
case s.packetIDs.clientboundDisconnect:
|
||||
var reason String
|
||||
_ = packet.readFields(&reason)
|
||||
return 0, fmt.Errorf("minecraft disconnected: %s", string(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *packetStream) Write(p []byte) (int, error) {
|
||||
func (s *tickStream) Write(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
|
||||
written := 0
|
||||
for written < len(p) {
|
||||
end := written + maxPacketData
|
||||
if end > len(p) {
|
||||
end = len(p)
|
||||
}
|
||||
channel := String(packetChannel)
|
||||
payload := RestBytes(p[written:end])
|
||||
if err := writePacket(s.writer, s.localCustomPayloadID(), &channel, &payload); err != nil {
|
||||
return written, fmt.Errorf("write minecraft custom payload: %w", err)
|
||||
}
|
||||
written = end
|
||||
s.queueMu.Lock()
|
||||
for len(s.queue) >= maxQueuedData && !s.closed {
|
||||
s.queueCond.Wait()
|
||||
}
|
||||
if s.closed {
|
||||
s.queueMu.Unlock()
|
||||
return 0, net.ErrClosed
|
||||
}
|
||||
s.queue = append(s.queue, p...)
|
||||
s.queueMu.Unlock()
|
||||
|
||||
return written, nil
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (s *packetStream) Stop() {
|
||||
s.stopOnce.Do(func() { close(s.done) })
|
||||
func (s *tickStream) Stop() {
|
||||
s.stopOnce.Do(func() {
|
||||
s.queueMu.Lock()
|
||||
s.closed = true
|
||||
s.queue = nil
|
||||
s.queueCond.Broadcast()
|
||||
s.queueMu.Unlock()
|
||||
close(s.done)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *packetStream) localCustomPayloadID() int {
|
||||
func (s *tickStream) localCustomPayloadID() int {
|
||||
if s.isClient {
|
||||
return configurationServerboundCustomPayload
|
||||
return s.packetIDs.serverboundCustomPayload
|
||||
}
|
||||
return configurationClientboundCustomPayload
|
||||
return s.packetIDs.clientboundCustomPayload
|
||||
}
|
||||
|
||||
func (s *packetStream) remoteCustomPayloadID() int {
|
||||
func (s *tickStream) remoteCustomPayloadID() int {
|
||||
if s.isClient {
|
||||
return configurationClientboundCustomPayload
|
||||
return s.packetIDs.clientboundCustomPayload
|
||||
}
|
||||
return configurationServerboundCustomPayload
|
||||
return s.packetIDs.serverboundCustomPayload
|
||||
}
|
||||
|
||||
func parseCustomPayload(packet *mcPacket) ([]byte, bool, error) {
|
||||
func parseCustomPayload(packet *mcPacket, dataChannel string) ([]byte, bool, error) {
|
||||
r := bytes.NewReader(packet.data)
|
||||
var channel String
|
||||
if err := channel.readFrom(r); err != nil {
|
||||
return nil, false, fmt.Errorf("read minecraft custom payload channel: %w", err)
|
||||
}
|
||||
if string(channel) != packetChannel {
|
||||
if string(channel) != dataChannel {
|
||||
return nil, false, nil
|
||||
}
|
||||
payload := make([]byte, r.Len())
|
||||
@@ -158,23 +308,49 @@ func parseCustomPayload(packet *mcPacket) ([]byte, bool, error) {
|
||||
return payload, true, nil
|
||||
}
|
||||
|
||||
func (s *packetStream) writeKeepAlive(id Long) error {
|
||||
func (s *tickStream) writeKeepAlive(packetID int, id Long) error {
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
if err := writePacket(s.writer, configurationKeepAlive, &id); err != nil {
|
||||
if err := writePacket(s.writer, packetID, &id); err != nil {
|
||||
return fmt.Errorf("write minecraft keep-alive: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *packetStream) keepAliveLoop() {
|
||||
// writePong answers a configuration Ping, which a vanilla client always does.
|
||||
func (s *tickStream) writePong(id Int) error {
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
if err := writePacket(s.writer, s.packetIDs.serverboundPong, &id); err != nil {
|
||||
return fmt.Errorf("write minecraft pong: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeCookieResponse answers a cookie request with an absent cookie, which is
|
||||
// what a client that never received one sends.
|
||||
func (s *tickStream) writeCookieResponse(request *mcPacket) error {
|
||||
var key String
|
||||
if err := request.readFields(&key); err != nil {
|
||||
return fmt.Errorf("read minecraft cookie request: %w", err)
|
||||
}
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
answered := Boolean(false)
|
||||
if err := writePacket(s.writer, s.packetIDs.serverboundCookieResponse, &key, &answered); err != nil {
|
||||
return fmt.Errorf("write minecraft cookie response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *tickStream) keepAliveLoop() {
|
||||
ticker := time.NewTicker(keepAlivePeriod)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
id := Long(s.keepAliveID.Add(1))
|
||||
if err := s.writeKeepAlive(id); err != nil {
|
||||
if err := s.writeKeepAlive(s.packetIDs.clientboundKeepAlive, id); err != nil {
|
||||
return
|
||||
}
|
||||
case <-s.done:
|
||||
|
||||
@@ -29,19 +29,97 @@ const (
|
||||
// every connection, so it is rejected when the configuration is built.
|
||||
maxPaddingScheduleDelay = handshakeTimeout - 10*time.Second
|
||||
|
||||
// Frame padding carries the startup padding in ordinary Minecraft custom
|
||||
// payload packets so that a vanilla server can parse the whole connection
|
||||
// without taking the pipeline over. The channel is deliberately different
|
||||
// from the packet stream channel: both ends drop unknown payloads.
|
||||
paddingFrameChannel = "xmc:pad"
|
||||
// Serverbound custom payload data is capped at 32767 bytes by
|
||||
// ServerboundCustomPayloadPacket; keep the same budget in both directions.
|
||||
maxPaddingFrameDataLength = 32767
|
||||
// Length varint, packet id, channel length varint and the channel itself.
|
||||
paddingFrameOverhead = 1 + 1 + 1 + len(paddingFrameChannel)
|
||||
)
|
||||
|
||||
var maxPaddingFrameLength = paddingFrameLength(maxPaddingFrameDataLength)
|
||||
// defaultPaddingFraming is the framing of the built-in padding channel. A
|
||||
// configured channel name changes the frame overhead, so the framing travels
|
||||
// with the channel instead of being a package constant.
|
||||
var defaultPaddingFraming = newPaddingFraming(DefaultPaddingChannel)
|
||||
|
||||
// paddingFraming is the custom payload framing of one channel. Frame padding
|
||||
// carries the startup padding in ordinary Minecraft custom payload packets so
|
||||
// that a vanilla server can parse the whole connection without taking the
|
||||
// pipeline over; the channel name decides the frame overhead, so every exact
|
||||
// frame length the captured presets ask for depends on it.
|
||||
type paddingFraming struct {
|
||||
channel string
|
||||
}
|
||||
|
||||
func newPaddingFraming(channel string) paddingFraming {
|
||||
return paddingFraming{channel: channel}
|
||||
}
|
||||
|
||||
// overhead is the length varint, the packet id, the channel length varint and
|
||||
// the channel itself, for the smallest length varint.
|
||||
func (f paddingFraming) overhead() int {
|
||||
return 1 + 1 + 1 + len(f.channel)
|
||||
}
|
||||
|
||||
func (f paddingFraming) maxFrameLength() int {
|
||||
return f.frameLength(maxPaddingFrameDataLength)
|
||||
}
|
||||
|
||||
// frameLength is the wire size of a custom payload frame whose payload body is
|
||||
// dataLength bytes long.
|
||||
func (f paddingFraming) frameLength(dataLength int) int {
|
||||
bodyLength := 1 + 1 + len(f.channel) + dataLength
|
||||
return varintSize(Varint(bodyLength)) + bodyLength
|
||||
}
|
||||
|
||||
// frameDataLength is the payload body that makes a frame exactly frameLength
|
||||
// bytes long. Some lengths are unreachable because the length varint grows in
|
||||
// steps.
|
||||
func (f paddingFraming) frameDataLength(frameLength int) (int, bool) {
|
||||
for overhead := f.overhead(); overhead <= f.overhead()+2; overhead++ {
|
||||
dataLength := frameLength - overhead
|
||||
if dataLength < 0 || dataLength > maxPaddingFrameDataLength {
|
||||
continue
|
||||
}
|
||||
if f.frameLength(dataLength) == frameLength {
|
||||
return dataLength, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// plan splits length bytes into reachable frame sizes. The result is exact
|
||||
// whenever a partition exists; a length below the smallest frame (the captured
|
||||
// 2-byte turns) is rounded up to that frame.
|
||||
func (f paddingFraming) plan(length int) ([]int, error) {
|
||||
if length <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
overhead := f.overhead()
|
||||
if length < overhead {
|
||||
return []int{overhead}, nil
|
||||
}
|
||||
maxFrameLength := f.maxFrameLength()
|
||||
frameLengths := make([]int, 0, length/paddingBufferLength+1)
|
||||
for remaining := length; remaining > 0; {
|
||||
candidate := min(remaining, maxFrameLength)
|
||||
picked := 0
|
||||
for ; candidate >= overhead; candidate-- {
|
||||
if _, ok := f.frameDataLength(candidate); !ok {
|
||||
continue
|
||||
}
|
||||
rest := remaining - candidate
|
||||
if rest > 0 && rest < overhead {
|
||||
continue
|
||||
}
|
||||
picked = candidate
|
||||
break
|
||||
}
|
||||
if picked == 0 {
|
||||
return nil, fmt.Errorf("cannot frame %d padding bytes", length)
|
||||
}
|
||||
frameLengths = append(frameLengths, picked)
|
||||
remaining -= picked
|
||||
}
|
||||
return frameLengths, nil
|
||||
}
|
||||
|
||||
type paddingVariant struct {
|
||||
chunks []int
|
||||
@@ -97,13 +175,14 @@ func pausePadding(done <-chan struct{}, d time.Duration) error {
|
||||
// Minecraft packets that carry nothing to compare an early arrival against, and
|
||||
// the startup reader drains them on its own while this schedule writes. A peer
|
||||
// that stalls is bounded by maxPaddingScheduleDelay instead.
|
||||
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error) error {
|
||||
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error, paddingChannel string, packetIDs configurationPacketIDs) error {
|
||||
if len(schedule) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
|
||||
return err
|
||||
}
|
||||
framing := newPaddingFraming(paddingChannel)
|
||||
|
||||
for i, turn := range schedule {
|
||||
prefixLength := 0
|
||||
@@ -128,7 +207,7 @@ func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength i
|
||||
if err := sleep(delay); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
|
||||
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(packetIDs, isClient), framing); err != nil {
|
||||
return fmt.Errorf("write padding turn %d: %w", i, err)
|
||||
}
|
||||
}
|
||||
@@ -195,18 +274,19 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
|
||||
|
||||
// paddingFramePacketID returns the configuration-state custom payload packet id
|
||||
// used by the side that sends the padding bytes; both values come from the
|
||||
// vanilla configuration protocol, so no proxy-specific id ever reaches the wire.
|
||||
func paddingFramePacketID(isClient bool) int {
|
||||
// negotiated version's configuration protocol, so no proxy-specific id ever
|
||||
// reaches the wire.
|
||||
func paddingFramePacketID(packetIDs configurationPacketIDs, isClient bool) int {
|
||||
if isClient {
|
||||
return configurationServerboundCustomPayload
|
||||
return packetIDs.serverboundCustomPayload
|
||||
}
|
||||
return configurationClientboundCustomPayload
|
||||
return packetIDs.clientboundCustomPayload
|
||||
}
|
||||
|
||||
// writePaddingTurnFrames writes one padding turn as a sequence of valid
|
||||
// Minecraft custom payload frames. Only the framing is native: payload bodies
|
||||
// stay zero-filled, so the captured traffic shape is kept.
|
||||
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int) (int, error) {
|
||||
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int, framing paddingFraming) (int, error) {
|
||||
startDelay, err := randomPaddingDelay(turn.startDelay)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("select padding start delay: %w", err)
|
||||
@@ -241,7 +321,7 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
|
||||
}
|
||||
|
||||
zeros := make([]byte, maxPaddingFrameDataLength)
|
||||
channel := String(paddingFrameChannel)
|
||||
channel := String(framing.channel)
|
||||
written := 0
|
||||
for i, chunkLength := range chunks {
|
||||
if i < len(delays) {
|
||||
@@ -253,12 +333,12 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
|
||||
return written, delayErr
|
||||
}
|
||||
}
|
||||
frameLengths, planErr := paddingFramePlan(chunkLength)
|
||||
frameLengths, planErr := framing.plan(chunkLength)
|
||||
if planErr != nil {
|
||||
return written, planErr
|
||||
}
|
||||
for _, frameLength := range frameLengths {
|
||||
dataLength, ok := paddingFrameDataLength(frameLength)
|
||||
dataLength, ok := framing.frameDataLength(frameLength)
|
||||
if !ok {
|
||||
return written, fmt.Errorf("unframed padding length %d", frameLength)
|
||||
}
|
||||
@@ -272,63 +352,6 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
|
||||
return written, nil
|
||||
}
|
||||
|
||||
// paddingFrameLength is the wire size of a custom payload frame whose payload
|
||||
// body is dataLength bytes long.
|
||||
func paddingFrameLength(dataLength int) int {
|
||||
bodyLength := 1 + 1 + len(paddingFrameChannel) + dataLength
|
||||
return varintSize(Varint(bodyLength)) + bodyLength
|
||||
}
|
||||
|
||||
// paddingFrameDataLength is the payload body that makes a frame exactly
|
||||
// frameLength bytes long. Some lengths are unreachable because the length
|
||||
// varint grows in steps.
|
||||
func paddingFrameDataLength(frameLength int) (int, bool) {
|
||||
for overhead := paddingFrameOverhead; overhead <= paddingFrameOverhead+2; overhead++ {
|
||||
dataLength := frameLength - overhead
|
||||
if dataLength < 0 || dataLength > maxPaddingFrameDataLength {
|
||||
continue
|
||||
}
|
||||
if paddingFrameLength(dataLength) == frameLength {
|
||||
return dataLength, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// paddingFramePlan splits length bytes into reachable frame sizes. The result is
|
||||
// exact whenever a partition exists; a length below the smallest frame (the
|
||||
// captured 2-byte turns) is rounded up to that frame.
|
||||
func paddingFramePlan(length int) ([]int, error) {
|
||||
if length <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if length < paddingFrameOverhead {
|
||||
return []int{paddingFrameOverhead}, nil
|
||||
}
|
||||
frameLengths := make([]int, 0, length/paddingBufferLength+1)
|
||||
for remaining := length; remaining > 0; {
|
||||
candidate := min(remaining, maxPaddingFrameLength)
|
||||
picked := 0
|
||||
for ; candidate >= paddingFrameOverhead; candidate-- {
|
||||
if _, ok := paddingFrameDataLength(candidate); !ok {
|
||||
continue
|
||||
}
|
||||
rest := remaining - candidate
|
||||
if rest > 0 && rest < paddingFrameOverhead {
|
||||
continue
|
||||
}
|
||||
picked = candidate
|
||||
break
|
||||
}
|
||||
if picked == 0 {
|
||||
return nil, fmt.Errorf("cannot frame %d padding bytes", length)
|
||||
}
|
||||
frameLengths = append(frameLengths, picked)
|
||||
remaining -= picked
|
||||
}
|
||||
return frameLengths, nil
|
||||
}
|
||||
|
||||
func selectPaddingVariant(turn paddingTurn, prefixLength int) (int, []int, []paddingDelayRange, error) {
|
||||
if len(turn.variants) == 0 {
|
||||
minimum, maximum := turn.minLength, turn.maxLength
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
|
||||
func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
|
||||
for dataLength := 0; dataLength <= maxPaddingFrameDataLength; dataLength++ {
|
||||
frameLength := paddingFrameLength(dataLength)
|
||||
got, ok := paddingFrameDataLength(frameLength)
|
||||
frameLength := defaultPaddingFraming.frameLength(dataLength)
|
||||
got, ok := defaultPaddingFraming.frameDataLength(frameLength)
|
||||
if !ok || got != dataLength {
|
||||
t.Fatalf("data length %d -> frame %d -> data %d (ok=%v)", dataLength, frameLength, got, ok)
|
||||
}
|
||||
@@ -21,18 +21,18 @@ func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPaddingFramePlanTotals(t *testing.T) {
|
||||
lengths := []int{paddingFrameOverhead, paddingFrameOverhead + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, maxPaddingFrameLength - 1, maxPaddingFrameLength, maxPaddingFrameLength + 1, 3 * maxPaddingFrameLength, 1024 * 1024}
|
||||
lengths := []int{defaultPaddingFraming.overhead(), defaultPaddingFraming.overhead() + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, defaultPaddingFraming.maxFrameLength() - 1, defaultPaddingFraming.maxFrameLength(), defaultPaddingFraming.maxFrameLength() + 1, 3 * defaultPaddingFraming.maxFrameLength(), 1024 * 1024}
|
||||
for _, length := range lengths {
|
||||
plan, err := paddingFramePlan(length)
|
||||
plan, err := defaultPaddingFraming.plan(length)
|
||||
if err != nil {
|
||||
t.Fatalf("plan %d: %v", length, err)
|
||||
}
|
||||
total := 0
|
||||
for _, frameLength := range plan {
|
||||
if _, ok := paddingFrameDataLength(frameLength); !ok {
|
||||
if _, ok := defaultPaddingFraming.frameDataLength(frameLength); !ok {
|
||||
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
|
||||
}
|
||||
if frameLength > maxPaddingFrameLength {
|
||||
if frameLength > defaultPaddingFraming.maxFrameLength() {
|
||||
t.Fatalf("plan %d contains oversized frame %d", length, frameLength)
|
||||
}
|
||||
total += frameLength
|
||||
@@ -44,11 +44,11 @@ func TestPaddingFramePlanTotals(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPaddingFramePlanRoundsUpShortTurn(t *testing.T) {
|
||||
plan, err := paddingFramePlan(2)
|
||||
plan, err := defaultPaddingFraming.plan(2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(plan) != 1 || plan[0] != paddingFrameOverhead {
|
||||
if len(plan) != 1 || plan[0] != defaultPaddingFraming.overhead() {
|
||||
t.Fatalf("short turn plan = %v", plan)
|
||||
}
|
||||
}
|
||||
@@ -57,12 +57,12 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
|
||||
turns := []paddingTurn{
|
||||
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
|
||||
{direction: paddingClientToServer, minLength: 2, maxLength: 2},
|
||||
{direction: paddingClientToServer, minLength: maxPaddingFrameLength, maxLength: maxPaddingFrameLength},
|
||||
{direction: paddingClientToServer, minLength: 3*maxPaddingFrameLength + 7, maxLength: 3*maxPaddingFrameLength + 7},
|
||||
{direction: paddingClientToServer, minLength: defaultPaddingFraming.maxFrameLength(), maxLength: defaultPaddingFraming.maxFrameLength()},
|
||||
{direction: paddingClientToServer, minLength: 3*defaultPaddingFraming.maxFrameLength() + 7, maxLength: 3*defaultPaddingFraming.maxFrameLength() + 7},
|
||||
}
|
||||
for i, turn := range turns {
|
||||
var buffer bytes.Buffer
|
||||
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationServerboundCustomPayload)
|
||||
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationPacketIDs121.serverboundCustomPayload, defaultPaddingFraming)
|
||||
if err != nil {
|
||||
t.Fatalf("turn %d: %v", i, err)
|
||||
}
|
||||
@@ -81,10 +81,10 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("turn %d frame %d is not a valid packet: %v", i, frames, err)
|
||||
}
|
||||
if packet.packetID != configurationServerboundCustomPayload {
|
||||
if packet.packetID != configurationPacketIDs121.serverboundCustomPayload {
|
||||
t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID)
|
||||
}
|
||||
_, ok, err := parseCustomPayload(packet)
|
||||
_, ok, err := parseCustomPayload(packet, DefaultDataChannel)
|
||||
if err != nil {
|
||||
t.Fatalf("turn %d frame %d: %v", i, frames, err)
|
||||
}
|
||||
@@ -107,7 +107,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause); err != nil {
|
||||
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("padding stream is not a valid packet stream: %v", err)
|
||||
}
|
||||
if packet.packetID != configurationServerboundCustomPayload {
|
||||
if packet.packetID != configurationPacketIDs121.serverboundCustomPayload {
|
||||
t.Fatalf("unexpected packet id %d in padding stream", packet.packetID)
|
||||
}
|
||||
total += before - reader.Len()
|
||||
@@ -135,7 +135,7 @@ func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) {
|
||||
schedule := []paddingTurn{
|
||||
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
|
||||
}
|
||||
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause); err == nil {
|
||||
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err == nil {
|
||||
t.Fatal("expected an error for a prefixed server-to-client first turn")
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,7 @@ func noPaddingPause(time.Duration) error { return nil }
|
||||
|
||||
func TestRunPaddingScheduleWithoutTurns(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause); err != nil {
|
||||
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Len() != 0 {
|
||||
@@ -167,7 +167,7 @@ func TestRunPaddingScheduleStopsWhenClosed(t *testing.T) {
|
||||
pauses++
|
||||
return net.ErrClosed
|
||||
}
|
||||
err := runPaddingSchedule(&out, true, 2, schedule, sleep)
|
||||
err := runPaddingSchedule(&out, true, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121)
|
||||
if !errors.Is(err, net.ErrClosed) {
|
||||
t.Fatalf("expected net.ErrClosed, got %v", err)
|
||||
}
|
||||
@@ -208,7 +208,7 @@ func TestPaddingDelayLeadsIntoTheTurn(t *testing.T) {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep); err != nil {
|
||||
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return events
|
||||
@@ -246,7 +246,7 @@ func TestPaddingDelayRangeJittersOnlyTheSender(t *testing.T) {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep); err != nil {
|
||||
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pauses
|
||||
|
||||
@@ -19,16 +19,16 @@ type paddingReader struct {
|
||||
// writing. Buffer only the first non-padding packet, then let the caller resume
|
||||
// reading the underlying stream. This keeps memory bounded without requiring
|
||||
// matching padding lengths or an extra end-of-padding packet on the wire.
|
||||
func newPaddingReader(reader io.Reader, isClient bool) io.Reader {
|
||||
func newPaddingReader(reader io.Reader, isClient bool, paddingChannel string, packetIDs configurationPacketIDs) io.Reader {
|
||||
first := make(chan paddingReadResult, 1)
|
||||
go func() {
|
||||
frame, err := readPastPadding(reader, paddingFramePacketID(!isClient))
|
||||
frame, err := readPastPadding(reader, paddingFramePacketID(packetIDs, !isClient), paddingChannel)
|
||||
first <- paddingReadResult{frame: frame, err: err}
|
||||
}()
|
||||
return &paddingReader{reader: reader, first: first}
|
||||
}
|
||||
|
||||
func readPastPadding(reader io.Reader, packetID int) ([]byte, error) {
|
||||
func readPastPadding(reader io.Reader, packetID int, paddingChannel string) ([]byte, error) {
|
||||
for {
|
||||
packet, err := readPacket(reader)
|
||||
if err != nil {
|
||||
@@ -36,7 +36,7 @@ func readPastPadding(reader io.Reader, packetID int) ([]byte, error) {
|
||||
}
|
||||
if packet.packetID == packetID {
|
||||
var channel String
|
||||
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && channel == paddingFrameChannel {
|
||||
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && string(channel) == paddingChannel {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
|
||||
func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
|
||||
for _, isClient := range []bool{true, false} {
|
||||
packetID := paddingFramePacketID(!isClient)
|
||||
packetID := paddingFramePacketID(configurationPacketIDs121, !isClient)
|
||||
var wire bytes.Buffer
|
||||
paddingChannel := String(paddingFrameChannel)
|
||||
paddingChannel := String(DefaultPaddingChannel)
|
||||
padding := RestBytes(make([]byte, 1024))
|
||||
if err := writePacket(&wire, packetID, &paddingChannel, &padding); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -24,15 +24,15 @@ func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := Long(42)
|
||||
if err := writePacket(&want, configurationKeepAlive, &id); err != nil {
|
||||
if err := writePacket(&want, configurationPacketIDs121.clientboundKeepAlive, &id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
channel := String(packetChannel)
|
||||
channel := String(DefaultDataChannel)
|
||||
if err := writePacket(&want, packetID, &channel, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wire.Write(want.Bytes())
|
||||
got, err := io.ReadAll(newPaddingReader(&wire, isClient))
|
||||
got, err := io.ReadAll(newPaddingReader(&wire, isClient, DefaultPaddingChannel, configurationPacketIDs121))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func TestPaddingReaderReadErrors(t *testing.T) {
|
||||
{name: "truncated", wire: []byte{2, 1}, err: io.ErrUnexpectedEOF},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
reader := newPaddingReader(bytes.NewReader(test.wire), true)
|
||||
reader := newPaddingReader(bytes.NewReader(test.wire), true, DefaultPaddingChannel, configurationPacketIDs121)
|
||||
if _, err := reader.Read(make([]byte, 1)); !errors.Is(err, test.err) {
|
||||
t.Fatalf("got %v, want %v", err, test.err)
|
||||
}
|
||||
@@ -63,7 +63,7 @@ func TestPaddingReaderReadErrors(t *testing.T) {
|
||||
func TestPaddingReaderUnblocksOnClose(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer server.Close()
|
||||
reader := newPaddingReader(client, true)
|
||||
reader := newPaddingReader(client, true, DefaultPaddingChannel, configurationPacketIDs121)
|
||||
if n, err := reader.Read(nil); n != 0 || err != nil {
|
||||
t.Fatalf("empty read = %d, %v", n, err)
|
||||
}
|
||||
|
||||
@@ -184,19 +184,18 @@ func propertyListFromYggdrasil(properties []yggdrasilProperty) loginProperties {
|
||||
return result
|
||||
}
|
||||
|
||||
func readLoginSuccess(packet *mcPacket) (loginProfile, error) {
|
||||
var (
|
||||
profile loginProfile
|
||||
username String
|
||||
)
|
||||
if err := packet.readFields(&profile.UUID, &username, &profile.Properties); err != nil {
|
||||
return loginProfile{}, err
|
||||
}
|
||||
profile.Username = string(username)
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
func writeLoginSuccess(w io.Writer, profile loginProfile) error {
|
||||
// writeLoginFinished writes the Login Finished packet. From 26.2 on the packet
|
||||
// also carries the connection session id, which the client only uses for its
|
||||
// own telemetry, so one value per process is enough.
|
||||
func writeLoginFinished(w io.Writer, version protocolVersion, profile loginProfile) error {
|
||||
username := String(profile.Username)
|
||||
return writePacket(w, 0x02, &profile.UUID, &username, &profile.Properties)
|
||||
fields := []field{&profile.UUID, &username, &profile.Properties}
|
||||
if version.loginFinishedSessionID {
|
||||
sessionID, err := serverSessionID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fields = append(fields, &sessionID)
|
||||
}
|
||||
return writePacket(w, version.login.clientboundLoginFinished, fields...)
|
||||
}
|
||||
|
||||
@@ -238,6 +238,29 @@ func (v *UnsignedShort) writeTo(w io.Writer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Int is a big-endian 32-bit integer, which is how vanilla encodes packet ids
|
||||
// that are not counting up from zero (Ping, Pong). It is not a Varint: using the
|
||||
// wrong one decodes as a valid-looking packet and fails later with a decoder
|
||||
// exception on the peer.
|
||||
type Int int32
|
||||
|
||||
func (v *Int) readFrom(r io.Reader) error {
|
||||
var buf [4]byte
|
||||
if _, err := io.ReadFull(r, buf[:]); err != nil {
|
||||
return fmt.Errorf("read int: %w", err)
|
||||
}
|
||||
*v = Int(int32(buf[0])<<24 | int32(buf[1])<<16 | int32(buf[2])<<8 | int32(buf[3]))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *Int) writeTo(w io.Writer) error {
|
||||
buf := []byte{byte(*v >> 24), byte(*v >> 16), byte(*v >> 8), byte(*v)}
|
||||
if _, err := w.Write(buf); err != nil {
|
||||
return fmt.Errorf("write int: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Long int64
|
||||
|
||||
func (v *Long) readFrom(r io.Reader) error {
|
||||
@@ -443,6 +466,6 @@ func writeFull(w io.Writer, p []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeDisconnectPacket(w io.Writer, reason string) error {
|
||||
return writePacket(w, 0x00, new(String(reason)))
|
||||
func writeDisconnectPacket(w io.Writer, packetID int, reason string) error {
|
||||
return writePacket(w, packetID, new(String(reason)))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// Status probe used to pick the protocol version of the peer.
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask"
|
||||
)
|
||||
|
||||
const (
|
||||
// protocolProbeTimeout bounds one status round trip. A peer that cannot
|
||||
// answer status in this time is not going to answer the login either.
|
||||
protocolProbeTimeout = 5 * time.Second
|
||||
// protocolProbeTTL keeps detection off the connection path: a real client
|
||||
// refreshes a server's status in its server list, not once per join.
|
||||
protocolProbeTTL = 10 * time.Minute
|
||||
// maxProtocolProbeEntries bounds the cache. A proxy can dial many different
|
||||
// destinations, and each entry is three words.
|
||||
maxProtocolProbeEntries = 256
|
||||
)
|
||||
|
||||
// statusVersion is the part of the status JSON the probe reads. Vanilla reports
|
||||
// its own protocol version there, and the login it accepts is that version.
|
||||
type statusVersion struct {
|
||||
Version struct {
|
||||
Name string `json:"name"`
|
||||
Protocol int32 `json:"protocol"`
|
||||
} `json:"version"`
|
||||
}
|
||||
|
||||
type protocolProbeEntry struct {
|
||||
number Varint
|
||||
name string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
var protocolProbeCache = struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]protocolProbeEntry
|
||||
}{entries: make(map[string]protocolProbeEntry)}
|
||||
|
||||
// probeProtocolVersion asks the peer for its status and returns the protocol
|
||||
// number and release name it reports.
|
||||
//
|
||||
// The probe is a second TCP connection to the same destination, exactly what a
|
||||
// client does when it refreshes a server in its list, so the peer sees nothing
|
||||
// unusual. It only works when the destination speaks plain Minecraft: for a
|
||||
// destination behind another transport, set protocol_version instead.
|
||||
func probeProtocolVersion(dest *xnet.Destination, hostname string, dialer *finalmask.Dialer) (Varint, string, error) {
|
||||
if dest == nil {
|
||||
return 0, "", fmt.Errorf("status probe: no destination")
|
||||
}
|
||||
if dialer == nil || dialer.DialTCP == nil {
|
||||
return 0, "", fmt.Errorf("status probe: no TCP dialer")
|
||||
}
|
||||
|
||||
conn, err := dialer.DialTCP(*dest)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("status probe: dial: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if err := conn.SetDeadline(time.Now().Add(protocolProbeTimeout)); err != nil {
|
||||
return 0, "", fmt.Errorf("status probe: set deadline: %w", err)
|
||||
}
|
||||
|
||||
address := String(hostname)
|
||||
if address == "" {
|
||||
address = String(dest.Address.String())
|
||||
}
|
||||
var (
|
||||
protocolNumber Varint = latestProtocolVersion.number
|
||||
port UnsignedShort = UnsignedShort(dest.Port.Value())
|
||||
nextState Varint = 1 // status
|
||||
)
|
||||
if err := writePacket(conn, handshakeServerboundIntention, &protocolNumber, &address, &port, &nextState); err != nil {
|
||||
return 0, "", fmt.Errorf("status probe: write handshake: %w", err)
|
||||
}
|
||||
if err := writePacket(conn, statusServerboundRequest); err != nil {
|
||||
return 0, "", fmt.Errorf("status probe: write status request: %w", err)
|
||||
}
|
||||
|
||||
packet, err := readPacket(conn)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("status probe: read status response: %w", err)
|
||||
}
|
||||
if packet.packetID != statusClientboundResponse {
|
||||
return 0, "", fmt.Errorf("status probe: unexpected status packet id: 0x%02x", packet.packetID)
|
||||
}
|
||||
var payload String
|
||||
if err := packet.readFields(&payload); err != nil {
|
||||
return 0, "", fmt.Errorf("status probe: read status payload: %w", err)
|
||||
}
|
||||
var status statusVersion
|
||||
if err := json.Unmarshal([]byte(payload), &status); err != nil {
|
||||
return 0, "", fmt.Errorf("status probe: decode status response: %w", err)
|
||||
}
|
||||
if status.Version.Protocol <= 0 {
|
||||
return 0, "", fmt.Errorf("status probe: status response has no version")
|
||||
}
|
||||
return Varint(status.Version.Protocol), status.Version.Name, nil
|
||||
}
|
||||
|
||||
// detectProtocolVersion returns the peer's protocol version, reusing a recent
|
||||
// probe for the same destination.
|
||||
func detectProtocolVersion(dest *xnet.Destination, hostname string, dialer *finalmask.Dialer) (Varint, string, error) {
|
||||
key := protocolProbeKey(dest)
|
||||
now := time.Now()
|
||||
|
||||
protocolProbeCache.mu.Lock()
|
||||
if entry, ok := protocolProbeCache.entries[key]; ok && entry.expires.After(now) {
|
||||
protocolProbeCache.mu.Unlock()
|
||||
return entry.number, entry.name, nil
|
||||
}
|
||||
protocolProbeCache.mu.Unlock()
|
||||
|
||||
number, name, err := probeProtocolVersion(dest, hostname, dialer)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
protocolProbeCache.mu.Lock()
|
||||
if len(protocolProbeCache.entries) >= maxProtocolProbeEntries {
|
||||
for cachedKey, entry := range protocolProbeCache.entries {
|
||||
if entry.expires.Before(now) {
|
||||
delete(protocolProbeCache.entries, cachedKey)
|
||||
}
|
||||
}
|
||||
if len(protocolProbeCache.entries) >= maxProtocolProbeEntries {
|
||||
clear(protocolProbeCache.entries)
|
||||
}
|
||||
}
|
||||
protocolProbeCache.entries[key] = protocolProbeEntry{number: number, name: name, expires: now.Add(protocolProbeTTL)}
|
||||
protocolProbeCache.mu.Unlock()
|
||||
return number, name, nil
|
||||
}
|
||||
|
||||
// forgetProbedVersions drops every cached detection. A login rejected with a
|
||||
// version mismatch means the cached row is stale (the peer was upgraded, or the
|
||||
// detection was wrong), so the next attempt has to ask again instead of waiting
|
||||
// for the TTL.
|
||||
func forgetProbedVersions() {
|
||||
protocolProbeCache.mu.Lock()
|
||||
clear(protocolProbeCache.entries)
|
||||
protocolProbeCache.mu.Unlock()
|
||||
}
|
||||
|
||||
func protocolProbeKey(dest *xnet.Destination) string {
|
||||
return dest.Network.String() + "|" + dest.Address.String() + "|" + strconv.Itoa(int(dest.Port.Value()))
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/transport/internet/finalmask"
|
||||
)
|
||||
|
||||
// statusTestServer answers exactly one status exchange with the given version.
|
||||
func statusTestServer(t *testing.T, listener net.Listener, protocol int32, name string) {
|
||||
t.Helper()
|
||||
go func() {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
if _, err := readPacket(conn); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := readPacket(conn); err != nil {
|
||||
return
|
||||
}
|
||||
payload := String(fmt.Sprintf(`{"description":"test","players":{"max":0,"online":0},"version":{"name":%q,"protocol":%d}}`, name, protocol))
|
||||
_ = writePacket(conn, statusClientboundResponse, &payload)
|
||||
}()
|
||||
}
|
||||
|
||||
func statusTestDestination(t *testing.T, listener net.Listener) xnet.Destination {
|
||||
t.Helper()
|
||||
dest, err := xnet.ParseDestination("tcp:" + listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return dest
|
||||
}
|
||||
|
||||
func statusTestDialer(dialErr error) *finalmask.Dialer {
|
||||
return &finalmask.Dialer{DialTCP: func(dest xnet.Destination) (net.Conn, error) {
|
||||
if dialErr != nil {
|
||||
return nil, dialErr
|
||||
}
|
||||
return net.Dial("tcp", net.JoinHostPort(dest.Address.String(), strconv.Itoa(int(dest.Port.Value()))))
|
||||
}}
|
||||
}
|
||||
|
||||
// TestProbeProtocolVersion reads the version out of the status response, which
|
||||
// is the version the peer's login expects.
|
||||
func TestProbeProtocolVersion(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
statusTestServer(t, listener, 767, "1.21.1")
|
||||
|
||||
dest := statusTestDestination(t, listener)
|
||||
number, name, err := probeProtocolVersion(&dest, "localhost", statusTestDialer(nil))
|
||||
if err != nil {
|
||||
t.Fatalf("probe: %v", err)
|
||||
}
|
||||
if number != 767 || name != "1.21.1" {
|
||||
t.Fatalf("probe = %d %q, want 767 \"1.21.1\"", number, name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbeProtocolVersionRejectsBrokenPeer(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
go func() {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
_, _ = readPacket(conn)
|
||||
_, _ = readPacket(conn)
|
||||
payload := String(`{"description":"no version here"}`)
|
||||
_ = writePacket(conn, statusClientboundResponse, &payload)
|
||||
}()
|
||||
|
||||
dest := statusTestDestination(t, listener)
|
||||
if _, _, err := probeProtocolVersion(&dest, "localhost", statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "no version") {
|
||||
t.Fatalf("probe error = %v", err)
|
||||
}
|
||||
|
||||
if _, _, err := probeProtocolVersion(&dest, "localhost", nil); err == nil || !strings.Contains(err.Error(), "no TCP dialer") {
|
||||
t.Fatalf("nil dialer error = %v", err)
|
||||
}
|
||||
if _, _, err := probeProtocolVersion(nil, "localhost", statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "no destination") {
|
||||
t.Fatalf("nil destination error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDetectProtocolVersionCaches checks a destination is probed once per TTL:
|
||||
// the second call must answer from the cache even though dialing now fails.
|
||||
func TestDetectProtocolVersionCaches(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
statusTestServer(t, listener, 776, "26.2")
|
||||
dest := statusTestDestination(t, listener)
|
||||
|
||||
number, name, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(nil))
|
||||
if err != nil {
|
||||
t.Fatalf("detect: %v", err)
|
||||
}
|
||||
if number != 776 || name != "26.2" {
|
||||
t.Fatalf("detect = %d %q", number, name)
|
||||
}
|
||||
if err := listener.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
number, _, err = detectProtocolVersion(&dest, "localhost", statusTestDialer(fmt.Errorf("must not dial")))
|
||||
if err != nil {
|
||||
t.Fatalf("cached detect: %v", err)
|
||||
}
|
||||
if number != 776 {
|
||||
t.Fatalf("cached detect = %d", number)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientProtocol covers the three ways the client picks its row: a
|
||||
// configured version, a detected one, and the fallback when the peer does not
|
||||
// answer status.
|
||||
func TestClientProtocol(t *testing.T) {
|
||||
t.Run("configured", func(t *testing.T) {
|
||||
// No destination and no dialer: a configured version must not probe.
|
||||
version, err := (&Config{ProtocolVersion: 775}).clientProtocol(nil, nil)
|
||||
if err != nil || version.number != 775 {
|
||||
t.Fatalf("configured = %v, %v", version.number, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("detected", func(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
statusTestServer(t, listener, 767, "1.21.1")
|
||||
dest := statusTestDestination(t, listener)
|
||||
|
||||
version, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil))
|
||||
if err != nil || version.number != 767 || version.name != "1.21.1" {
|
||||
t.Fatalf("detected = %v %q, %v", version.number, version.name, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unknown", func(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
statusTestServer(t, listener, 999, "999")
|
||||
dest := statusTestDestination(t, listener)
|
||||
|
||||
if _, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "not in the supported table") {
|
||||
t.Fatalf("unknown version error = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("probe failure falls back to the newest row", func(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address := listener.Addr().String()
|
||||
if err := listener.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dest, err := xnet.ParseDestination("tcp:" + address)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
version, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil))
|
||||
if err != nil {
|
||||
t.Fatalf("fallback: %v", err)
|
||||
}
|
||||
if version.number != latestProtocolVersion.number {
|
||||
t.Fatalf("fallback version = %d, want %d", version.number, latestProtocolVersion.number)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestForgetProbedVersions covers a stale detection: after a version mismatch
|
||||
// the cache is dropped, so the next connection probes again instead of reusing
|
||||
// the row the peer no longer speaks.
|
||||
func TestForgetProbedVersions(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
statusTestServer(t, listener, 767, "1.21.1")
|
||||
dest := statusTestDestination(t, listener)
|
||||
|
||||
if number, _, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(nil)); err != nil || number != 767 {
|
||||
t.Fatalf("detect = %v, %v", number, err)
|
||||
}
|
||||
forgetProbedVersions()
|
||||
|
||||
// The peer now reports another version; a cached answer would hide it.
|
||||
listener2, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener2.Close()
|
||||
statusTestServer(t, listener2, 775, "26.1")
|
||||
dest2 := statusTestDestination(t, listener2)
|
||||
|
||||
// A dialer that fails proves the cache was consulted; after forgetting, the
|
||||
// same destination must probe again.
|
||||
if err := listener.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if number, _, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(fmt.Errorf("must probe again"))); err == nil {
|
||||
t.Fatalf("stale cache was reused: %v", number)
|
||||
}
|
||||
if number, _, err := detectProtocolVersion(&dest2, "localhost", statusTestDialer(nil)); err != nil || number != 775 {
|
||||
t.Fatalf("fresh detect = %v, %v", number, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsProtocolVersionReject(t *testing.T) {
|
||||
for _, reason := range []string{
|
||||
`{"translate":"multiplayer.disconnect.incompatible","with":["26.3"]}`,
|
||||
`{"translate":"multiplayer.disconnect.outdated_client","with":["26.3"]}`,
|
||||
} {
|
||||
if !isProtocolVersionReject(reason) {
|
||||
t.Fatalf("%s should be a version reject", reason)
|
||||
}
|
||||
}
|
||||
if isProtocolVersionReject(`{"translate":"multiplayer.disconnect.not_whitelisted"}`) {
|
||||
t.Fatal("a whitelist reject is not a version reject")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// Minecraft protocol table.
|
||||
//
|
||||
// Every packet id XMC writes or matches is the registration order of the packet
|
||||
// type in that version's protocol builder, not a value observed in a capture:
|
||||
// LoginProtocols and ConfigurationProtocols call addPacket in source order and
|
||||
// both ends dispatch on that index. The table keeps those ids in one place and
|
||||
// per version, so a new release is a row instead of an edit spread over the
|
||||
// login, configuration and padding code.
|
||||
//
|
||||
// Rows come from two independent sources, and neither is a packet capture:
|
||||
//
|
||||
// - 767..775 (1.21.1 .. 26.1): minecraft-data's per-version protocol.json
|
||||
// (data/pc/<version>/protocol.json), which stores the same registration
|
||||
// order as a {hex id: packet name} mapping;
|
||||
// - 776..777 (26.2, 26.3): the official jars, LoginProtocols and
|
||||
// ConfigurationProtocols.
|
||||
//
|
||||
// 26.3 is the reason this table exists. It inserts ClientboundPostEffectsPacket
|
||||
// into the configuration clientbound list at 0x0a, after the keep-alive and
|
||||
// before store_cookie, so every id behind it moves by one. Every id XMC uses
|
||||
// stayed put, which is luck rather than design: the list grows by one or two
|
||||
// packets per release (17 clientbound configuration packets in 1.21.1, 21 in
|
||||
// 26.3), and an insertion in front of 0x04 would silently break the tunnel.
|
||||
// Adding a version means adding a row here and an expectation in
|
||||
// protocol_table_test.go, after diffing the two registration lists.
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// handshaking and status packet ids. These have not moved since 1.7 and are
|
||||
// fixed for every version the table covers.
|
||||
const (
|
||||
handshakeServerboundIntention = 0x00
|
||||
statusServerboundRequest = 0x00
|
||||
statusServerboundPing = 0x01
|
||||
statusClientboundResponse = 0x00
|
||||
statusClientboundPong = 0x01
|
||||
)
|
||||
|
||||
// loginPacketIDs is the login state of one version.
|
||||
type loginPacketIDs struct {
|
||||
// Serverbound (client to server).
|
||||
serverboundLoginStart int
|
||||
serverboundKey int
|
||||
serverboundCustomQueryAnswer int
|
||||
serverboundLoginAcknowledged int
|
||||
serverboundCookieResponse int
|
||||
|
||||
// Clientbound (server to client).
|
||||
clientboundLoginDisconnect int
|
||||
clientboundHello int
|
||||
clientboundLoginFinished int
|
||||
clientboundLoginCompression int
|
||||
clientboundCustomQuery int
|
||||
clientboundCookieRequest int
|
||||
}
|
||||
|
||||
// configurationPacketIDs is the part of the configuration state XMC uses: the
|
||||
// custom payload pair that carries the tunnel, the keep-alive and ping that
|
||||
// keep the connection alive like a real one, and the packets that a peer can
|
||||
// send before the tunnel starts, so that they are recognised instead of being
|
||||
// mistaken for tunnel data.
|
||||
type configurationPacketIDs struct {
|
||||
// Serverbound (client to server).
|
||||
serverboundClientInformation int
|
||||
serverboundCookieResponse int
|
||||
serverboundCustomPayload int
|
||||
serverboundKeepAlive int
|
||||
serverboundPong int
|
||||
|
||||
// Clientbound (server to client).
|
||||
clientboundCookieRequest int
|
||||
clientboundCustomPayload int
|
||||
clientboundDisconnect int
|
||||
clientboundKeepAlive int
|
||||
clientboundPing int
|
||||
}
|
||||
|
||||
// protocolVersion describes one Minecraft release for the part of the protocol
|
||||
// the finalmask depends on.
|
||||
type protocolVersion struct {
|
||||
// number is the network protocol version advertised in the handshake and
|
||||
// reported by the status response.
|
||||
number Varint
|
||||
// name is the release name, for example "26.3", as the status response
|
||||
// reports it.
|
||||
name string
|
||||
|
||||
login loginPacketIDs
|
||||
configuration configurationPacketIDs
|
||||
|
||||
// loginFinishedSessionID is set from 26.2 (776) on: Login Finished appends
|
||||
// the connection session id after the game profile, so the client has to
|
||||
// read it and the server has to write it.
|
||||
loginFinishedSessionID bool
|
||||
}
|
||||
|
||||
// The login and configuration ids that 767..777 share. 26.2 added the session
|
||||
// id field, and 26.3 inserted a clientbound configuration packet, but none of
|
||||
// the ids below moved between 1.21.1 and 26.3.
|
||||
var (
|
||||
loginPacketIDs121 = loginPacketIDs{
|
||||
serverboundLoginStart: 0x00,
|
||||
serverboundKey: 0x01,
|
||||
serverboundCustomQueryAnswer: 0x02,
|
||||
serverboundLoginAcknowledged: 0x03,
|
||||
serverboundCookieResponse: 0x04,
|
||||
|
||||
clientboundLoginDisconnect: 0x00,
|
||||
clientboundHello: 0x01,
|
||||
clientboundLoginFinished: 0x02,
|
||||
clientboundLoginCompression: 0x03,
|
||||
clientboundCustomQuery: 0x04,
|
||||
clientboundCookieRequest: 0x05,
|
||||
}
|
||||
|
||||
configurationPacketIDs121 = configurationPacketIDs{
|
||||
serverboundClientInformation: 0x00,
|
||||
serverboundCookieResponse: 0x01,
|
||||
serverboundCustomPayload: 0x02,
|
||||
serverboundKeepAlive: 0x04,
|
||||
serverboundPong: 0x05,
|
||||
|
||||
clientboundCookieRequest: 0x00,
|
||||
clientboundCustomPayload: 0x01,
|
||||
clientboundDisconnect: 0x02,
|
||||
clientboundKeepAlive: 0x04,
|
||||
clientboundPing: 0x05,
|
||||
}
|
||||
)
|
||||
|
||||
// protocolVersions is ordered by protocol number, oldest first. Only releases
|
||||
// the mod's branches target are listed: the configuration state starts at 1.20.5
|
||||
// (766), and XMC is only useful from 1.21 on, so 767 is the oldest row.
|
||||
//
|
||||
// Releases that share a protocol number share a row and cannot be told apart on
|
||||
// the wire; the name is the one the mod's branches use (1.21.2 is 768 like
|
||||
// 1.21.3, 1.21.7 is 772 like 1.21.8, 1.21.10 is 773 like 1.21.9, and 26.1.1 /
|
||||
// 26.1.2 are 775 like 26.1).
|
||||
var protocolVersions = []protocolVersion{
|
||||
{number: 767, name: "1.21.1", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 768, name: "1.21.3", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 769, name: "1.21.4", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 770, name: "1.21.5", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 771, name: "1.21.6", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 772, name: "1.21.8", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 773, name: "1.21.9", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 774, name: "1.21.11", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 775, name: "26.1", login: loginPacketIDs121, configuration: configurationPacketIDs121},
|
||||
{number: 776, name: "26.2", login: loginPacketIDs121, configuration: configurationPacketIDs121, loginFinishedSessionID: true},
|
||||
{number: 777, name: "26.3", login: loginPacketIDs121, configuration: configurationPacketIDs121, loginFinishedSessionID: true},
|
||||
}
|
||||
|
||||
// latestProtocolVersion is the newest row. It is what the client advertises
|
||||
// unless a version is configured, and what the server reports in its status
|
||||
// response.
|
||||
var latestProtocolVersion = protocolVersions[len(protocolVersions)-1]
|
||||
|
||||
// protocolVersionByNumber finds a row. An unknown number is an error rather
|
||||
// than a guess: a wrong packet id breaks the login in a way that looks like a
|
||||
// network failure, so the configuration has to name a version the table knows.
|
||||
func protocolVersionByNumber(number Varint) (protocolVersion, bool) {
|
||||
for _, version := range protocolVersions {
|
||||
if version.number == number {
|
||||
return version, true
|
||||
}
|
||||
}
|
||||
return protocolVersion{}, false
|
||||
}
|
||||
|
||||
// ValidateProtocolVersion checks a configured network protocol number. Zero is
|
||||
// valid and selects the newest row. Configuration is validated when it is built,
|
||||
// so a version that is not in the table fails before a connection is attempted.
|
||||
func ValidateProtocolVersion(number uint32) error {
|
||||
if number == 0 {
|
||||
return nil
|
||||
}
|
||||
if _, ok := protocolVersionByNumber(Varint(number)); !ok {
|
||||
return fmt.Errorf("unsupported protocol version %d (supported: %s)", number, protocolVersionRange())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// protocolVersionRange describes the supported versions for error messages.
|
||||
func protocolVersionRange() string {
|
||||
first, last := protocolVersions[0], protocolVersions[len(protocolVersions)-1]
|
||||
return fmt.Sprintf("%d (%s) to %d (%s)", first.number, first.name, last.number, last.name)
|
||||
}
|
||||
|
||||
// isProtocolVersionReject recognises the Login Disconnect reasons vanilla sends
|
||||
// when the client named another protocol version, so the cached detection can be
|
||||
// dropped.
|
||||
func isProtocolVersionReject(reason string) bool {
|
||||
return strings.Contains(reason, "multiplayer.disconnect.incompatible") ||
|
||||
strings.Contains(reason, "multiplayer.disconnect.outdated_client")
|
||||
}
|
||||
|
||||
// loginRejectReason is the Login Disconnect reason a vanilla server sends for a
|
||||
// protocol version it does not speak. Vanilla splits the message at 1.20.5
|
||||
// (754): older clients are told to update, newer ones that the server is
|
||||
// incompatible.
|
||||
func loginRejectReason(number Varint) string {
|
||||
if number < 754 {
|
||||
return fmt.Sprintf(`{"translate":"multiplayer.disconnect.outdated_client","with":[%q]}`, latestProtocolVersion.name)
|
||||
}
|
||||
return fmt.Sprintf(`{"translate":"multiplayer.disconnect.incompatible","with":[%q]}`, latestProtocolVersion.name)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestProtocolTablePinsRegistrationOrder pins every id XMC uses against the
|
||||
// source it came from, so that changing a row is a conscious edit and not a
|
||||
// side effect of a refactor:
|
||||
//
|
||||
// - 767..775: minecraft-data data/pc/<version>/protocol.json, keyed by the
|
||||
// packet name in the same order LoginProtocols and ConfigurationProtocols
|
||||
// register them;
|
||||
// - 776..777: the official 26.2 and 26.3 jars.
|
||||
func TestProtocolTablePinsRegistrationOrder(t *testing.T) {
|
||||
wantLogin := loginPacketIDs{
|
||||
serverboundLoginStart: 0x00,
|
||||
serverboundKey: 0x01,
|
||||
serverboundCustomQueryAnswer: 0x02,
|
||||
serverboundLoginAcknowledged: 0x03,
|
||||
serverboundCookieResponse: 0x04,
|
||||
|
||||
clientboundLoginDisconnect: 0x00,
|
||||
clientboundHello: 0x01,
|
||||
clientboundLoginFinished: 0x02,
|
||||
clientboundLoginCompression: 0x03,
|
||||
clientboundCustomQuery: 0x04,
|
||||
clientboundCookieRequest: 0x05,
|
||||
}
|
||||
wantConfiguration := configurationPacketIDs{
|
||||
serverboundClientInformation: 0x00,
|
||||
serverboundCookieResponse: 0x01,
|
||||
serverboundCustomPayload: 0x02,
|
||||
serverboundKeepAlive: 0x04,
|
||||
serverboundPong: 0x05,
|
||||
|
||||
clientboundCookieRequest: 0x00,
|
||||
clientboundCustomPayload: 0x01,
|
||||
clientboundDisconnect: 0x02,
|
||||
clientboundKeepAlive: 0x04,
|
||||
clientboundPing: 0x05,
|
||||
}
|
||||
|
||||
for _, version := range protocolVersions {
|
||||
if version.login != wantLogin {
|
||||
t.Fatalf("%s (%d): login ids = %+v, want %+v", version.name, version.number, version.login, wantLogin)
|
||||
}
|
||||
if version.configuration != wantConfiguration {
|
||||
t.Fatalf("%s (%d): configuration ids = %+v, want %+v", version.name, version.number, version.configuration, wantConfiguration)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestProtocolTableCoverage checks the table is a contiguous, ordered run of
|
||||
// the releases XMC supports, and that the newest row is the default.
|
||||
func TestProtocolTableCoverage(t *testing.T) {
|
||||
if len(protocolVersions) == 0 {
|
||||
t.Fatal("empty protocol table")
|
||||
}
|
||||
for i, version := range protocolVersions {
|
||||
want := Varint(767 + i)
|
||||
if version.number != want {
|
||||
t.Fatalf("row %d is protocol %d, want %d", i, version.number, want)
|
||||
}
|
||||
if version.name == "" {
|
||||
t.Fatalf("row %d (%d) has no release name", i, version.number)
|
||||
}
|
||||
if version.loginFinishedSessionID != (version.number >= 776) {
|
||||
t.Fatalf("%s (%d): loginFinishedSessionID = %v", version.name, version.number, version.loginFinishedSessionID)
|
||||
}
|
||||
}
|
||||
|
||||
if latestProtocolVersion.number != 777 || latestProtocolVersion.name != "26.3" {
|
||||
t.Fatalf("latest row = %s (%d), want 26.3 (777)", latestProtocolVersion.name, latestProtocolVersion.number)
|
||||
}
|
||||
if !latestProtocolVersion.loginFinishedSessionID {
|
||||
t.Fatal("26.3 must carry the Login Finished session id")
|
||||
}
|
||||
if _, ok := protocolVersionByNumber(776); !ok {
|
||||
t.Fatal("26.2 row is missing")
|
||||
}
|
||||
if _, ok := protocolVersionByNumber(775); !ok {
|
||||
t.Fatal("26.1 row is missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolVersionByNumberRejectsUnknown(t *testing.T) {
|
||||
for _, number := range []Varint{0, 1, 766, 778, 9999} {
|
||||
if _, ok := protocolVersionByNumber(number); ok {
|
||||
t.Fatalf("protocol %d should not be in the table", number)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolVersionRange(t *testing.T) {
|
||||
got := protocolVersionRange()
|
||||
for _, want := range []string{"767 (1.21.1)", "777 (26.3)"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("range %q does not contain %q", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginRejectReason checks the vanilla split at 1.20.5 (754): older clients
|
||||
// are told to update, newer ones that the server is incompatible.
|
||||
func TestLoginRejectReason(t *testing.T) {
|
||||
if got := loginRejectReason(700); !strings.Contains(got, "multiplayer.disconnect.outdated_client") {
|
||||
t.Fatalf("old client reason = %s", got)
|
||||
}
|
||||
for _, number := range []Varint{754, 775, 778} {
|
||||
got := loginRejectReason(number)
|
||||
if !strings.Contains(got, "multiplayer.disconnect.incompatible") {
|
||||
t.Fatalf("protocol %d reason = %s", number, got)
|
||||
}
|
||||
if !strings.Contains(got, `"with":["26.3"]`) {
|
||||
t.Fatalf("protocol %d reason has no version argument: %s", number, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatusResponse pins the status JSON shape a vanilla server builds: a
|
||||
// collapsed literal description, player counts with an empty sample, and the
|
||||
// version it speaks.
|
||||
func TestStatusResponse(t *testing.T) {
|
||||
got := statusResponse(latestProtocolVersion)
|
||||
want := `{"description":"A Minecraft Server","players":{"max":20,"online":0,"sample":[]},"version":{"name":"26.3","protocol":777},"enforcesSecureChat":true}`
|
||||
if got != want {
|
||||
t.Fatalf("status = %s\nwant %s", got, want)
|
||||
}
|
||||
if got := statusResponse(protocolVersions[0]); !strings.Contains(got, `"version":{"name":"1.21.1","protocol":767}`) {
|
||||
t.Fatalf("1.21.1 status = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidPlayerName(t *testing.T) {
|
||||
for _, name := range []string{"Notch", "a", "Player_123", "Player.Name-1", strings.Repeat("a", 16)} {
|
||||
if !validPlayerName(name) {
|
||||
t.Fatalf("%q should be a valid 26.x player name", name)
|
||||
}
|
||||
}
|
||||
// 26.x only rejects lengths above sixteen and bytes outside printable ASCII:
|
||||
// spaces and the old "letters, digits, underscore" restriction are gone.
|
||||
for _, name := range []string{strings.Repeat("a", 17), "name with space", "tab\tname", "high\x7f", "unicode\u00e9"} {
|
||||
if validPlayerName(name) {
|
||||
t.Fatalf("%q should be rejected", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGameVersion(t *testing.T) {
|
||||
version, err := (&Config{}).gameVersion()
|
||||
if err != nil || version.number != latestProtocolVersion.number {
|
||||
t.Fatalf("default version = %v, %v", version.number, err)
|
||||
}
|
||||
|
||||
version, err = (&Config{ProtocolVersion: 775}).gameVersion()
|
||||
if err != nil || version.number != 775 {
|
||||
t.Fatalf("configured version = %v, %v", version.number, err)
|
||||
}
|
||||
|
||||
if _, err = (&Config{ProtocolVersion: 778}).gameVersion(); err == nil || !strings.Contains(err.Error(), "unsupported protocol version 778") {
|
||||
t.Fatalf("unknown version error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package xmc
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
@@ -24,12 +23,22 @@ const (
|
||||
// still missing, instead of making every login wait a fixed interval.
|
||||
yggdrasilVerifyFirstPoll = 10 * time.Millisecond
|
||||
yggdrasilVerifyMaxPoll = 200 * time.Millisecond
|
||||
// maxPlayerNameLength is vanilla's Login Start limit (readUtf(16)).
|
||||
maxPlayerNameLength = 16
|
||||
)
|
||||
|
||||
var errYggdrasilNotJoined = errors.New("player did not join the minecraft session")
|
||||
|
||||
// Response by vanilla 26.1.2 server.
|
||||
var statusResponse = `{"description":"A Minecraft Server","players":{"max":20,"online":0},"version":{"name":"26.1.2","protocol":775},"enforcesSecureChat":true}`
|
||||
// serverSessionID is the connection session id that Login Finished carries from
|
||||
// 26.2 on. Vanilla generates it once per server rather than per connection, so
|
||||
// one value for the process has the same shape.
|
||||
var serverSessionID = sync.OnceValues(func() (UUID, error) {
|
||||
var sessionID UUID
|
||||
if _, err := rand.Read(sessionID[:]); err != nil {
|
||||
return UUID{}, fmt.Errorf("generate session id: %w", err)
|
||||
}
|
||||
return sessionID, nil
|
||||
})
|
||||
|
||||
type serverState int
|
||||
|
||||
@@ -45,6 +54,10 @@ type serverConn struct {
|
||||
|
||||
state serverState
|
||||
|
||||
// protocol is the row selected from the client's handshake. Both ends have
|
||||
// to use the same ids, and the client is the side that names the version.
|
||||
protocol protocolVersion
|
||||
|
||||
handshakeLock sync.Mutex
|
||||
lifecycleMu sync.Mutex
|
||||
closed bool
|
||||
@@ -52,9 +65,11 @@ type serverConn struct {
|
||||
password string
|
||||
rsaPrivateKey *rsa.PrivateKey
|
||||
rsaPublicKey []byte
|
||||
dataChannel string
|
||||
paddingChannel string
|
||||
yggdrasil *yggdrasilVerifier
|
||||
paddingSchedule []paddingTurn
|
||||
packet *packetStream
|
||||
packet *tickStream
|
||||
deadlines *connectionDeadlines
|
||||
|
||||
done chan struct{}
|
||||
@@ -75,10 +90,10 @@ func (c *serverConn) handshake() error {
|
||||
defer func() { _ = c.deadlines.endHandshake() }()
|
||||
|
||||
var (
|
||||
protocolVersion Varint
|
||||
serverAddress String
|
||||
serverPort UnsignedShort
|
||||
nextState Varint
|
||||
protocolNumber Varint
|
||||
serverAddress String
|
||||
serverPort UnsignedShort
|
||||
nextState Varint
|
||||
)
|
||||
|
||||
// handshake packet
|
||||
@@ -88,11 +103,11 @@ func (c *serverConn) handshake() error {
|
||||
return fmt.Errorf("read handshake packet: %w", err)
|
||||
}
|
||||
|
||||
if pkt.packetID != 0 {
|
||||
if pkt.packetID != handshakeServerboundIntention {
|
||||
return fmt.Errorf("bad handshake packet id")
|
||||
}
|
||||
|
||||
err = pkt.readFields(&protocolVersion, &serverAddress, &serverPort, &nextState)
|
||||
err = pkt.readFields(&protocolNumber, &serverAddress, &serverPort, &nextState)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read handshake packet: %w", err)
|
||||
}
|
||||
@@ -110,14 +125,14 @@ func (c *serverConn) handshake() error {
|
||||
}
|
||||
|
||||
switch pkt.packetID {
|
||||
case 0: // Status Request
|
||||
case statusServerboundRequest: // Status Request
|
||||
|
||||
err = writePacket(c.writer, 0, new(String(statusResponse)))
|
||||
err = writePacket(c.writer, statusClientboundResponse, new(String(statusResponse(latestProtocolVersion))))
|
||||
if err != nil {
|
||||
return fmt.Errorf("write status response: %w", err)
|
||||
}
|
||||
|
||||
case 1: // Ping
|
||||
case statusServerboundPing: // Ping
|
||||
|
||||
var payload Long
|
||||
err = pkt.readFields(&payload)
|
||||
@@ -125,7 +140,7 @@ func (c *serverConn) handshake() error {
|
||||
return fmt.Errorf("read ping packet: %w", err)
|
||||
}
|
||||
|
||||
err = writePacket(c.writer, 1, &payload)
|
||||
err = writePacket(c.writer, statusClientboundPong, &payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write ping response: %w", err)
|
||||
}
|
||||
@@ -136,167 +151,34 @@ func (c *serverConn) handshake() error {
|
||||
|
||||
return fmt.Errorf("ping")
|
||||
|
||||
case 2:
|
||||
case 2, 3:
|
||||
|
||||
// Login
|
||||
|
||||
// login start
|
||||
|
||||
pkt, err := readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login start packet: %w", err)
|
||||
// Login. A vanilla server starts the login protocol, checks the version
|
||||
// against its own, and only then reads Login Start; TRANSFER shares the
|
||||
// login but is only accepted when the server allows transfers, which the
|
||||
// mask does not.
|
||||
if nextState == 3 {
|
||||
reason := `{"translate":"multiplayer.disconnect.transfers_disabled"}`
|
||||
_ = writePacket(c.writer, latestProtocolVersion.login.clientboundLoginDisconnect, new(String(reason)))
|
||||
return fmt.Errorf("transfers are disabled")
|
||||
}
|
||||
|
||||
if pkt.packetID != 0 {
|
||||
return fmt.Errorf("bad login start packet id")
|
||||
// The version picks the row, not the other way around: the ids are the
|
||||
// registration order of the peer's own protocol, so the client decides.
|
||||
// An unknown version is rejected with the same Login Disconnect a vanilla
|
||||
// server sends for it. The disconnect id is taken from the newest row
|
||||
// because no row matches, and no release has ever moved it.
|
||||
protocol, known := protocolVersionByNumber(protocolNumber)
|
||||
if !known {
|
||||
reason := String(loginRejectReason(protocolNumber))
|
||||
_ = writePacket(c.writer, latestProtocolVersion.login.clientboundLoginDisconnect, &reason)
|
||||
return fmt.Errorf("unsupported protocol version: %d", protocolNumber)
|
||||
}
|
||||
c.protocol = protocol
|
||||
|
||||
var (
|
||||
username String
|
||||
uuid UUID
|
||||
)
|
||||
|
||||
err = pkt.readFields(&username, &uuid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login start packet: %w", err)
|
||||
}
|
||||
profile, found := findProfile(c.profiles, string(username), uuid)
|
||||
|
||||
// encrypt request
|
||||
|
||||
var (
|
||||
serverId String = String("")
|
||||
publicKey Bytes = Bytes(c.rsaPublicKey)
|
||||
verifyToken Bytes = Bytes(make([]byte, 4))
|
||||
shouldAuthenticate Boolean = true
|
||||
)
|
||||
|
||||
if _, err = rand.Read(verifyToken); err != nil {
|
||||
return fmt.Errorf("generate verify token: %w", err)
|
||||
}
|
||||
|
||||
err = writePacket(c.writer, 0x01, &serverId, &publicKey, &verifyToken, &shouldAuthenticate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write encryption request: %w", err)
|
||||
}
|
||||
|
||||
// encrypt response
|
||||
|
||||
var (
|
||||
encryptedSharedSecret Bytes
|
||||
encryptedVerifyToken Bytes
|
||||
|
||||
sharedSecret []byte
|
||||
decryptedVerifyToken []byte
|
||||
)
|
||||
|
||||
pkt, err = readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encrypt response: %w", err)
|
||||
}
|
||||
|
||||
if pkt.packetID != 0x01 {
|
||||
return fmt.Errorf("bad encrypt response packet id")
|
||||
}
|
||||
|
||||
err = pkt.readFields(&encryptedSharedSecret, &encryptedVerifyToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encrypt response: %w", err)
|
||||
}
|
||||
|
||||
sharedSecret, err = rsa.DecryptPKCS1v15(rand.Reader, c.rsaPrivateKey, encryptedSharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt shared secret: %w", err)
|
||||
}
|
||||
if len(sharedSecret) != 16 {
|
||||
return fmt.Errorf("bad shared secret length: %d", len(sharedSecret))
|
||||
}
|
||||
|
||||
decryptedVerifyToken, err = rsa.DecryptPKCS1v15(rand.Reader, c.rsaPrivateKey, encryptedVerifyToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt verify token: %w", err)
|
||||
}
|
||||
|
||||
if len(decryptedVerifyToken) < 4 || !bytes.Equal(verifyToken, decryptedVerifyToken[:4]) {
|
||||
return fmt.Errorf("verify token mismatch")
|
||||
}
|
||||
|
||||
c.reader, err = newCryptoReader(c.reader, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new crypto reader: %w", err)
|
||||
}
|
||||
|
||||
c.writer, err = newCryptoWriter(c.writer, sharedSecret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("new crypto writer: %w", err)
|
||||
}
|
||||
|
||||
if c.yggdrasil != nil {
|
||||
// Online-mode login: verify the player through the session server
|
||||
// instead of the pre-shared password and the static profile list.
|
||||
if !bytes.Equal(decryptedVerifyToken, verifyToken) {
|
||||
return fmt.Errorf("verify token mismatch")
|
||||
}
|
||||
|
||||
serverID := minecraftServerID(string(serverId), sharedSecret, c.rsaPublicKey)
|
||||
profile, err = c.verifyYggdrasilLogin(string(username), uuid, serverID)
|
||||
if err != nil {
|
||||
reason := `{"type":"translatable","translate":"multiplayer.disconnect.unverified_username"}`
|
||||
if !errors.Is(err, errYggdrasilNotJoined) {
|
||||
reason = `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}`
|
||||
}
|
||||
if writeErr := writeDisconnectPacket(c.writer, reason); writeErr != nil {
|
||||
return fmt.Errorf("write yggdrasil disconnect: %w", writeErr)
|
||||
}
|
||||
return fmt.Errorf("verify yggdrasil login: %w", err)
|
||||
}
|
||||
} else {
|
||||
// verify password
|
||||
receivedPassword := decryptedVerifyToken[4:]
|
||||
|
||||
if subtle.ConstantTimeCompare(receivedPassword, []byte(c.password)) != 1 {
|
||||
_ = writeDisconnectPacket(c.writer, `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}`)
|
||||
return fmt.Errorf("bad password")
|
||||
}
|
||||
if !found {
|
||||
if err = writeDisconnectPacket(c.writer, `{"text":"You are not white-listed on this server!"}`); err != nil {
|
||||
return fmt.Errorf("write unknown login profile disconnect: %w", err)
|
||||
}
|
||||
return fmt.Errorf("unknown login profile")
|
||||
}
|
||||
}
|
||||
|
||||
if err = writeLoginSuccess(c.writer, profile); err != nil {
|
||||
return fmt.Errorf("write login finished: %w", err)
|
||||
}
|
||||
|
||||
var loginAcknowledgedLength int
|
||||
pkt, loginAcknowledgedLength, err = readPacketWithLength(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login acknowledged: %w", err)
|
||||
}
|
||||
if err = validateLoginAcknowledgedPacket(pkt); err != nil {
|
||||
if err = c.login(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.reader = newPaddingReader(c.reader, false)
|
||||
if err = runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil {
|
||||
_ = c.Close() // Unblock the startup reader if writing failed.
|
||||
return fmt.Errorf("run startup padding: %w", err)
|
||||
}
|
||||
|
||||
packet := newPacketStream(c.reader, c.writer, false)
|
||||
c.lifecycleMu.Lock()
|
||||
if c.closed {
|
||||
c.lifecycleMu.Unlock()
|
||||
packet.Stop()
|
||||
return net.ErrClosed
|
||||
}
|
||||
c.packet = packet
|
||||
c.reader = packet
|
||||
c.writer = packet
|
||||
c.state = serverStateProxy
|
||||
c.lifecycleMu.Unlock()
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
@@ -304,6 +186,222 @@ func (c *serverConn) handshake() error {
|
||||
}
|
||||
}
|
||||
|
||||
// login runs the login state once the protocol version is known.
|
||||
func (c *serverConn) login() error {
|
||||
// login start
|
||||
|
||||
pkt, err := readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login start packet: %w", err)
|
||||
}
|
||||
|
||||
if pkt.packetID != c.protocol.login.serverboundLoginStart {
|
||||
return fmt.Errorf("bad login start packet id")
|
||||
}
|
||||
|
||||
var (
|
||||
username String
|
||||
uuid UUID
|
||||
)
|
||||
|
||||
err = pkt.readFields(&username, &uuid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login start packet: %w", err)
|
||||
}
|
||||
if !validPlayerName(string(username)) {
|
||||
return fmt.Errorf("invalid player name: %q", string(username))
|
||||
}
|
||||
profile, found := findProfile(c.profiles, string(username), uuid)
|
||||
|
||||
// encrypt request
|
||||
|
||||
var (
|
||||
serverId String = String("")
|
||||
publicKey Bytes = Bytes(c.rsaPublicKey)
|
||||
verifyToken Bytes = Bytes(make([]byte, 4))
|
||||
shouldAuthenticate Boolean = true
|
||||
)
|
||||
|
||||
if _, err = rand.Read(verifyToken); err != nil {
|
||||
return fmt.Errorf("generate verify token: %w", err)
|
||||
}
|
||||
|
||||
err = writePacket(c.writer, c.protocol.login.clientboundHello, &serverId, &publicKey, &verifyToken, &shouldAuthenticate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write encryption request: %w", err)
|
||||
}
|
||||
|
||||
// encrypt response
|
||||
|
||||
var (
|
||||
encryptedSharedSecret Bytes
|
||||
encryptedVerifyToken Bytes
|
||||
|
||||
sharedSecret []byte
|
||||
decryptedVerifyToken []byte
|
||||
)
|
||||
|
||||
pkt, err = readPacket(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encrypt response: %w", err)
|
||||
}
|
||||
|
||||
if pkt.packetID != c.protocol.login.serverboundKey {
|
||||
return fmt.Errorf("bad encrypt response packet id")
|
||||
}
|
||||
|
||||
err = pkt.readFields(&encryptedSharedSecret, &encryptedVerifyToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read encrypt response: %w", err)
|
||||
}
|
||||
|
||||
// The order is vanilla's: handleKey runs ServerboundKeyPacket.isChallengeValid
|
||||
// and turns a bad challenge into java.lang.IllegalStateException: Protocol
|
||||
// error before it ever touches the secret key, so a bad challenge closes the
|
||||
// connection unencrypted and a good one fails inside the CFB8 stream. That
|
||||
// difference is drawn by vanilla too and the mask keeps it. The challenge is
|
||||
// the 4 random bytes this server sent moments ago, so an oracle on it
|
||||
// discloses nothing.
|
||||
//
|
||||
// The shared secret is the opposite case: it is the only secret on the wire,
|
||||
// so it is decrypted with the session-key countermeasure and never branched
|
||||
// on. See decryptSharedSecret.
|
||||
decryptedVerifyToken, verifyTokenOK := decryptVerifyToken(c.rsaPrivateKey, encryptedVerifyToken)
|
||||
if !verifyTokenOK || !challengesEqual(verifyToken, decryptedVerifyToken) {
|
||||
return fmt.Errorf("verify token mismatch")
|
||||
}
|
||||
|
||||
sharedSecret, blockCipher, sharedSecretOK := c.decryptSharedSecret(encryptedSharedSecret)
|
||||
if !sharedSecretOK {
|
||||
return fmt.Errorf("decrypt shared secret")
|
||||
}
|
||||
|
||||
c.reader = newCryptoReaderWithBlock(c.reader, blockCipher, sharedSecret)
|
||||
c.writer = newCryptoWriterWithBlock(c.writer, blockCipher, sharedSecret)
|
||||
|
||||
// From here the connection is encrypted and every rejection is a Login
|
||||
// Disconnect inside it, exactly like the rejections vanilla sends after a
|
||||
// successful challenge. Nothing below branches on padding validity and the
|
||||
// password comparison is constant time. A peer that did not send a valid
|
||||
// secret cannot read this answer at all: it is encrypted under a random key
|
||||
// the peer never saw.
|
||||
var reason string
|
||||
if c.yggdrasil != nil {
|
||||
// Online-mode login: verify the player through the session server
|
||||
// instead of the pre-shared password and the static profile list.
|
||||
// Vanilla's client sends the bare challenge back, and this reports an
|
||||
// unknown player to the client rather than the API outage a second
|
||||
// session server round trip would guess at.
|
||||
if len(decryptedVerifyToken) != len(verifyToken) {
|
||||
return fmt.Errorf("verify token mismatch")
|
||||
}
|
||||
|
||||
serverID := minecraftServerID(string(serverId), sharedSecret, c.rsaPublicKey)
|
||||
profile, err = c.verifyYggdrasilLogin(string(username), uuid, serverID)
|
||||
if err != nil {
|
||||
reason = `{"translate":"multiplayer.disconnect.unverified_username"}`
|
||||
if !errors.Is(err, errYggdrasilNotJoined) {
|
||||
reason = `{"translate":"multiplayer.disconnect.authservers_down"}`
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// verify password
|
||||
receivedPassword := decryptedVerifyToken[len(verifyToken):]
|
||||
|
||||
if subtle.ConstantTimeCompare(receivedPassword, []byte(c.password)) != 1 {
|
||||
// A wrong password is reported as an outage, the answer vanilla
|
||||
// gives when the session check that would have authorised the
|
||||
// player fails. Only a peer that already sent the right password can
|
||||
// reach the profile check below, so the whitelist answer is never
|
||||
// visible to a guesser.
|
||||
reason = `{"translate":"multiplayer.disconnect.authservers_down"}`
|
||||
} else if !found {
|
||||
// The password is shared, the profile list is not: only a holder of
|
||||
// the password can ever see this answer.
|
||||
reason = `{"text":"You are not white-listed on this server!"}`
|
||||
}
|
||||
}
|
||||
|
||||
if reason != "" {
|
||||
if writeErr := writeDisconnectPacket(c.writer, c.protocol.login.clientboundLoginDisconnect, reason); writeErr != nil {
|
||||
return fmt.Errorf("write login disconnect: %w", writeErr)
|
||||
}
|
||||
return fmt.Errorf("authentication rejected")
|
||||
}
|
||||
|
||||
// No Set Compression, which is the same wire as a vanilla server with
|
||||
// network-compression-threshold=-1: the startup padding preset reproduces a
|
||||
// login that ran without it, and the tunnel payloads are already compressed
|
||||
// or encrypted by whoever produced them. The client still negotiates the
|
||||
// compressed framing when the peer is a real server that enables it.
|
||||
if err = writeLoginFinished(c.writer, c.protocol, profile); err != nil {
|
||||
return fmt.Errorf("write login finished: %w", err)
|
||||
}
|
||||
|
||||
var loginAcknowledgedLength int
|
||||
pkt, loginAcknowledgedLength, err = readPacketWithLength(c.reader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read login acknowledged: %w", err)
|
||||
}
|
||||
if err = validateLoginAcknowledgedPacket(pkt, c.protocol.login.serverboundLoginAcknowledged); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.startProxy(loginAcknowledgedLength)
|
||||
}
|
||||
|
||||
// startProxy runs the startup padding and hands the connection to the tick
|
||||
// stream. It is called once the login reached the configuration state.
|
||||
func (c *serverConn) startProxy(loginAcknowledgedLength int) error {
|
||||
c.reader = newPaddingReader(c.reader, false, c.paddingChannel, c.protocol.configuration)
|
||||
if err := runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause, c.paddingChannel, c.protocol.configuration); err != nil {
|
||||
_ = c.Close() // Unblock the startup reader if writing failed.
|
||||
return fmt.Errorf("run startup padding: %w", err)
|
||||
}
|
||||
|
||||
packet := newTickStream(c.reader, c.writer, false, c.protocol.configuration, c.dataChannel, c.paddingChannel)
|
||||
c.lifecycleMu.Lock()
|
||||
if c.closed {
|
||||
c.lifecycleMu.Unlock()
|
||||
packet.Stop()
|
||||
return net.ErrClosed
|
||||
}
|
||||
c.packet = packet
|
||||
c.reader = packet
|
||||
c.writer = packet
|
||||
c.state = serverStateProxy
|
||||
c.lifecycleMu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validPlayerName mirrors vanilla's Login Start check in 26.x: at most sixteen
|
||||
// bytes, all printable ASCII. The older "letters, digits and underscore"
|
||||
// restriction was dropped, so filtering it here would reject players a vanilla
|
||||
// server accepts.
|
||||
func validPlayerName(name string) bool {
|
||||
if len(name) > maxPlayerNameLength {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(name); i++ {
|
||||
if name[i] <= 32 || name[i] >= 127 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// statusResponse is the status JSON a vanilla server of this version builds:
|
||||
// a collapsed literal description, the player counts with an empty sample, and
|
||||
// the version the server speaks.
|
||||
func statusResponse(version protocolVersion) string {
|
||||
return fmt.Sprintf(
|
||||
`{"description":"A Minecraft Server","players":{"max":20,"online":0,"sample":[]},"version":{"name":%q,"protocol":%d},"enforcesSecureChat":true}`,
|
||||
version.name,
|
||||
version.number,
|
||||
)
|
||||
}
|
||||
|
||||
func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID string) (loginProfile, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), yggdrasilVerifyTimeout)
|
||||
defer cancel()
|
||||
@@ -348,8 +446,8 @@ func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID s
|
||||
}
|
||||
}
|
||||
|
||||
func validateLoginAcknowledgedPacket(pkt *mcPacket) error {
|
||||
if pkt.packetID != 0x03 {
|
||||
func validateLoginAcknowledgedPacket(pkt *mcPacket, packetID int) error {
|
||||
if pkt.packetID != packetID {
|
||||
return fmt.Errorf("bad login acknowledged packet id: %d", pkt.packetID)
|
||||
}
|
||||
if len(pkt.data) != 0 {
|
||||
@@ -383,6 +481,10 @@ func (c *serverConn) Close() error {
|
||||
c.lifecycleMu.Unlock()
|
||||
c.closeOnce.Do(func() { close(c.done) })
|
||||
if packet != nil {
|
||||
// Write returns once data is queued for the next tick, so a graceful
|
||||
// close has to flush the last tick instead of dropping it.
|
||||
_ = c.c.SetWriteDeadline(time.Now().Add(time.Second))
|
||||
_ = packet.Flush()
|
||||
packet.Stop()
|
||||
}
|
||||
return c.c.Close()
|
||||
@@ -413,7 +515,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
|
||||
return c.deadlines.setWriteDeadline(t)
|
||||
}
|
||||
|
||||
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier) (*serverConn, error) {
|
||||
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier, dataChannel, paddingChannel string) (*serverConn, error) {
|
||||
if len(profiles) == 0 && yggdrasil == nil {
|
||||
return nil, fmt.Errorf("empty profiles")
|
||||
}
|
||||
@@ -437,6 +539,8 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
|
||||
password: password,
|
||||
rsaPrivateKey: rsaPrivateKey,
|
||||
rsaPublicKey: rsaPublicKey,
|
||||
dataChannel: dataChannel,
|
||||
paddingChannel: paddingChannel,
|
||||
yggdrasil: yggdrasil,
|
||||
paddingSchedule: paddingSchedule,
|
||||
deadlines: newConnectionDeadlines(c),
|
||||
|
||||
@@ -17,9 +17,9 @@ type cryptoStream struct {
|
||||
}
|
||||
|
||||
func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) {
|
||||
blockCipher, err := aes.NewCipher(sharedSecret)
|
||||
blockCipher, err := newAESCipher(sharedSecret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new aes cipher: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stream := newCFB8Decrypt(blockCipher, sharedSecret)
|
||||
@@ -27,6 +27,27 @@ func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) {
|
||||
return &cryptoStream{stream: stream, r: r}, nil
|
||||
}
|
||||
|
||||
func newAESCipher(sharedSecret []byte) (cipher.Block, error) {
|
||||
blockCipher, err := aes.NewCipher(sharedSecret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new aes cipher: %w", err)
|
||||
}
|
||||
return blockCipher, nil
|
||||
}
|
||||
|
||||
// newCryptoReaderWithBlock is newCryptoReader for a caller that already holds
|
||||
// the cipher block, so the key stays in the caller's hands until it installs the
|
||||
// stream.
|
||||
func newCryptoReaderWithBlock(r io.Reader, blockCipher cipher.Block, sharedSecret []byte) *cryptoStream {
|
||||
return &cryptoStream{stream: newCFB8Decrypt(blockCipher, sharedSecret), r: r}
|
||||
}
|
||||
|
||||
// newCryptoWriterWithBlock is newCryptoWriter for a caller that already holds
|
||||
// the cipher block.
|
||||
func newCryptoWriterWithBlock(w io.Writer, blockCipher cipher.Block, sharedSecret []byte) *cryptoStream {
|
||||
return &cryptoStream{stream: newCFB8Encrypt(blockCipher, sharedSecret), w: w}
|
||||
}
|
||||
|
||||
func (c *cryptoStream) Read(b []byte) (int, error) {
|
||||
if c.r == nil {
|
||||
panic("read on a write-only crypto stream")
|
||||
@@ -50,9 +71,9 @@ func (c *cryptoStream) Read(b []byte) (int, error) {
|
||||
}
|
||||
|
||||
func newCryptoWriter(w io.Writer, sharedSecret []byte) (*cryptoStream, error) {
|
||||
blockCipher, err := aes.NewCipher(sharedSecret)
|
||||
blockCipher, err := newAESCipher(sharedSecret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("new aes cipher: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stream := newCFB8Encrypt(blockCipher, sharedSecret)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package xmc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// tickTestWriter records every batch the tick stream writes to the network.
|
||||
type tickTestWriter struct {
|
||||
mu sync.Mutex
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *tickTestWriter) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.writes = append(w.writes, append([]byte(nil), p...))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (w *tickTestWriter) snapshot() [][]byte {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return append([][]byte(nil), w.writes...)
|
||||
}
|
||||
|
||||
func readTickBatch(t *testing.T, batch []byte) []*mcPacket {
|
||||
t.Helper()
|
||||
r := bytes.NewReader(batch)
|
||||
var packets []*mcPacket
|
||||
for r.Len() > 0 {
|
||||
packet, err := readPacket(r)
|
||||
if err != nil {
|
||||
t.Fatalf("parse tick batch: %v", err)
|
||||
}
|
||||
packets = append(packets, packet)
|
||||
}
|
||||
return packets
|
||||
}
|
||||
|
||||
// tickPacketChannelAndPayload splits one custom payload into its channel name
|
||||
// and the raw payload bytes that follow it.
|
||||
func tickPacketChannelAndPayload(t *testing.T, packet *mcPacket) (string, []byte) {
|
||||
t.Helper()
|
||||
r := bytes.NewReader(packet.data)
|
||||
var channel String
|
||||
if err := channel.readFrom(r); err != nil {
|
||||
t.Fatalf("read tick packet channel: %v", err)
|
||||
}
|
||||
payload, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
t.Fatalf("read tick packet payload: %v", err)
|
||||
}
|
||||
return string(channel), payload
|
||||
}
|
||||
|
||||
func collectTickData(t *testing.T, batches [][]byte) (data []byte, dataPackets, padding int) {
|
||||
t.Helper()
|
||||
for _, batch := range batches {
|
||||
for _, packet := range readTickBatch(t, batch) {
|
||||
channel, payload := tickPacketChannelAndPayload(t, packet)
|
||||
switch channel {
|
||||
case DefaultDataChannel:
|
||||
data = append(data, payload...)
|
||||
dataPackets++
|
||||
case DefaultPaddingChannel:
|
||||
padding++
|
||||
}
|
||||
}
|
||||
}
|
||||
return data, dataPackets, padding
|
||||
}
|
||||
|
||||
// TestTickStreamIdleCadence pins the 20 Hz shape: an idle connection still
|
||||
// emits one small padding frame per tick in both directions.
|
||||
func TestTickStreamIdleCadence(t *testing.T) {
|
||||
writer := &tickTestWriter{}
|
||||
stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel)
|
||||
defer stream.Stop()
|
||||
|
||||
time.Sleep(180 * time.Millisecond)
|
||||
stream.Stop()
|
||||
// Wait for an in-flight tick so the recorded batches are complete.
|
||||
_ = stream.Flush()
|
||||
|
||||
batches := writer.snapshot()
|
||||
if len(batches) < 2 || len(batches) > 6 {
|
||||
t.Fatalf("got %d tick batches in 180ms, want about 3", len(batches))
|
||||
}
|
||||
for i, batch := range batches {
|
||||
packets := readTickBatch(t, batch)
|
||||
if len(packets) != 1 {
|
||||
t.Fatalf("idle tick %d wrote %d packets, want 1", i, len(packets))
|
||||
}
|
||||
if packets[0].packetID != configurationPacketIDs121.serverboundCustomPayload {
|
||||
t.Fatalf("idle tick %d packet id = %d", i, packets[0].packetID)
|
||||
}
|
||||
channel, _ := tickPacketChannelAndPayload(t, packets[0])
|
||||
if channel != DefaultPaddingChannel {
|
||||
t.Fatalf("idle tick %d channel = %q", i, channel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTickStreamSendsQueuedDataInOneTick checks that proxy data is queued and
|
||||
// then emitted as one per-tick batch, split at maxPacketData boundaries.
|
||||
func TestTickStreamSendsQueuedDataInOneTick(t *testing.T) {
|
||||
writer := &tickTestWriter{}
|
||||
stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel)
|
||||
defer stream.Stop()
|
||||
|
||||
payload := bytes.Repeat([]byte("0123456789abcdef"), 4096)
|
||||
if _, err := stream.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(time.Second)
|
||||
var (
|
||||
data []byte
|
||||
dataPackets int
|
||||
padding int
|
||||
)
|
||||
for time.Now().Before(deadline) {
|
||||
batches := writer.snapshot()
|
||||
if len(batches) > 0 {
|
||||
data, dataPackets, padding = collectTickData(t, batches)
|
||||
if len(data) >= len(payload) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
|
||||
if !bytes.Equal(data, payload) {
|
||||
t.Fatalf("got %d payload bytes, want %d", len(data), len(payload))
|
||||
}
|
||||
wantPackets := (len(payload) + maxPacketData - 1) / maxPacketData
|
||||
if dataPackets != wantPackets {
|
||||
t.Fatalf("got %d data packets, want %d", dataPackets, wantPackets)
|
||||
}
|
||||
if padding < 1 {
|
||||
t.Fatal("the tick that carried data did not carry a padding frame")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTickStreamFlushWritesQueuedDataImmediately covers graceful close: data
|
||||
// already accepted by Write must not wait for the next tick.
|
||||
func TestTickStreamFlushWritesQueuedDataImmediately(t *testing.T) {
|
||||
writer := &tickTestWriter{}
|
||||
stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel)
|
||||
defer stream.Stop()
|
||||
|
||||
payload := []byte("flush me")
|
||||
if _, err := stream.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := stream.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, _, _ := collectTickData(t, writer.snapshot())
|
||||
if !bytes.Equal(data, payload) {
|
||||
t.Fatalf("flush delivered %q, want %q", data, payload)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPingPongEncoding pins the configuration ping/pong form: the id is a plain
|
||||
// 32-bit integer, not a varint. Vanilla rejected a varint pong with "Failed to
|
||||
// decode packet 'serverbound/minecraft:pong'", which is why this is tested
|
||||
// separately from the rest of the stream.
|
||||
func TestPingPongEncoding(t *testing.T) {
|
||||
packetIDs := configurationPacketIDs121
|
||||
|
||||
var wire bytes.Buffer
|
||||
pingID := Int(0x01020304)
|
||||
if err := writePacket(&wire, packetIDs.clientboundPing, &pingID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
packet, err := readPacket(&wire)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var received Int
|
||||
if err := packet.readFields(&received); err != nil {
|
||||
t.Fatalf("read ping id as int: %v", err)
|
||||
}
|
||||
if received != pingID {
|
||||
t.Fatalf("ping id = %#x, want %#x", received, pingID)
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
stream := &tickStream{writer: &out, isClient: true, packetIDs: packetIDs}
|
||||
if err := stream.writePong(received); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer, err := readPacket(&out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if answer.packetID != packetIDs.serverboundPong {
|
||||
t.Fatalf("pong packet id = 0x%02x", answer.packetID)
|
||||
}
|
||||
if !bytes.Equal(answer.data, []byte{1, 2, 3, 4}) {
|
||||
t.Fatalf("pong body = %x, want 01020304", answer.data)
|
||||
}
|
||||
}
|
||||
@@ -468,6 +468,14 @@ type yggdrasilAuth struct {
|
||||
|
||||
keyMu sync.Mutex
|
||||
signatureKey *rsa.PublicKey
|
||||
|
||||
// loginMu serializes the login exchange of one account, from Login Start to
|
||||
// the peer's Login Finished. The session server keeps one server id per
|
||||
// profile, so only the most recent /join answers hasJoined; a second login
|
||||
// that started while the first server was still polling would overwrite
|
||||
// that session and the first server would reject it with
|
||||
// unverified_username.
|
||||
loginMu sync.Mutex
|
||||
}
|
||||
|
||||
func newYggdrasilAuth(config *yggdrasilConfig) *yggdrasilAuth {
|
||||
|
||||
@@ -58,6 +58,15 @@ type fakeYggdrasil struct {
|
||||
|
||||
boundProfile string
|
||||
joined map[string]string // serverId -> profile name
|
||||
|
||||
// latestServerID is the server id of the most recent join. A real session
|
||||
// server keeps one id per profile, so with singleSession set only that id
|
||||
// answers hasJoined.
|
||||
latestServerID string
|
||||
singleSession bool
|
||||
// hasJoinedDelay widens the window in which a concurrent join can replace
|
||||
// the session under test.
|
||||
hasJoinedDelay time.Duration
|
||||
}
|
||||
|
||||
func writeFakeYggdrasilJSON(w http.ResponseWriter, status int, body string) {
|
||||
@@ -124,15 +133,30 @@ func newFakeYggdrasilHandler(state *fakeYggdrasil) http.Handler {
|
||||
state.joinCalls++
|
||||
state.boundProfile = request.SelectedProfile
|
||||
state.joined[request.ServerID] = state.profile.Name
|
||||
state.latestServerID = request.ServerID
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
|
||||
mux.HandleFunc(prefix+"/sessionserver/session/minecraft/hasJoined", func(w http.ResponseWriter, r *http.Request) {
|
||||
serverID := r.URL.Query().Get("serverId")
|
||||
username := r.URL.Query().Get("username")
|
||||
|
||||
state.mu.Lock()
|
||||
delay := state.hasJoinedDelay
|
||||
state.mu.Unlock()
|
||||
if delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
|
||||
name, found := state.joined[r.URL.Query().Get("serverId")]
|
||||
if !found || name != r.URL.Query().Get("username") {
|
||||
if state.singleSession && state.latestServerID != serverID {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
name, found := state.joined[serverID]
|
||||
if !found || name != username {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
@@ -358,11 +382,14 @@ func TestHandshakeWithYggdrasil(t *testing.T) {
|
||||
t.Errorf("new verifier: %v", err)
|
||||
return
|
||||
}
|
||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier)
|
||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Errorf("wrap server: %v", err)
|
||||
return
|
||||
}
|
||||
// Write queues the payload for the next tick, so Close has to flush it
|
||||
// before the raw connection is torn down.
|
||||
defer server.Close()
|
||||
|
||||
buf := make([]byte, 1024)
|
||||
n, err := server.Read(buf)
|
||||
@@ -387,7 +414,7 @@ func TestHandshakeWithYggdrasil(t *testing.T) {
|
||||
|
||||
// The client intentionally has no pinned server key: Yggdrasil mode accepts
|
||||
// the key sent by the server and binds it through the session hash.
|
||||
client, err := newClientConn(rawClient, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser"))
|
||||
client, err := newClientConn(rawClient, latestProtocolVersion, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser"), DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatalf("new client: %v", err)
|
||||
}
|
||||
@@ -421,6 +448,128 @@ func TestHandshakeWithYggdrasil(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestYggdrasilConcurrentLoginsSerialized checks that one account never runs two
|
||||
// logins at once. The session server keeps a single server id per profile, so a
|
||||
// concurrent login would overwrite the session of a server that is still polling
|
||||
// hasJoined, and that server would answer unverified_username. The fake API here
|
||||
// behaves like the real one (only the most recent /join answers hasJoined) and
|
||||
// adds latency to make the overwrite window wide.
|
||||
func TestYggdrasilConcurrentLoginsSerialized(t *testing.T) {
|
||||
state, api := newFakeYggdrasilServer(t)
|
||||
state.singleSession = true
|
||||
state.hasJoinedDelay = 25 * time.Millisecond
|
||||
|
||||
const logins = 4
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
password := "yggdrasil-rsa-seed"
|
||||
privateKey, publicKey := deriveTestRSAKey(t, password)
|
||||
|
||||
var servers sync.WaitGroup
|
||||
servers.Add(logins)
|
||||
go func() {
|
||||
for i := 0; i < logins; i++ {
|
||||
rawConn, err := ln.Accept()
|
||||
if err != nil {
|
||||
t.Errorf("accept: %v", err)
|
||||
servers.Done()
|
||||
continue
|
||||
}
|
||||
go func(conn net.Conn) {
|
||||
defer servers.Done()
|
||||
defer conn.Close()
|
||||
|
||||
verifier, err := newYggdrasilVerifier(api)
|
||||
if err != nil {
|
||||
t.Errorf("new verifier: %v", err)
|
||||
return
|
||||
}
|
||||
server, err := wrapConnServer(conn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Errorf("wrap server: %v", err)
|
||||
return
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
buf := make([]byte, 64)
|
||||
n, err := server.Read(buf)
|
||||
if err != nil {
|
||||
t.Errorf("server read: %v", err)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(buf[:n], []byte("ping")) {
|
||||
t.Errorf("unexpected payload: %q", buf[:n])
|
||||
return
|
||||
}
|
||||
if _, err := server.Write([]byte("ok")); err != nil {
|
||||
t.Errorf("server write: %v", err)
|
||||
}
|
||||
}(rawConn)
|
||||
}
|
||||
}()
|
||||
|
||||
// One auth value for all connections, like one Xray process and one account.
|
||||
auth := newTestYggdrasilAuth(t, api, "SkinUser")
|
||||
|
||||
var clients sync.WaitGroup
|
||||
errs := make(chan error, logins)
|
||||
for i := 0; i < logins; i++ {
|
||||
clients.Add(1)
|
||||
go func() {
|
||||
defer clients.Done()
|
||||
|
||||
rawConn, err := net.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
errs <- fmt.Errorf("dial: %w", err)
|
||||
return
|
||||
}
|
||||
defer rawConn.Close()
|
||||
|
||||
client, err := newClientConn(rawConn, latestProtocolVersion, nil, "", nil, "localhost", nil, auth, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
errs <- fmt.Errorf("new client: %w", err)
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
if _, err := client.Write([]byte("ping")); err != nil {
|
||||
errs <- fmt.Errorf("client write: %w", err)
|
||||
return
|
||||
}
|
||||
reply := make([]byte, 2)
|
||||
if err := client.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
if _, err := io.ReadFull(client, reply); err != nil {
|
||||
errs <- fmt.Errorf("client read: %w", err)
|
||||
return
|
||||
}
|
||||
if string(reply) != "ok" {
|
||||
errs <- fmt.Errorf("unexpected reply: %q", reply)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
clients.Wait()
|
||||
servers.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
state.mu.Lock()
|
||||
defer state.mu.Unlock()
|
||||
if state.joinCalls != logins {
|
||||
t.Errorf("join calls = %d, want %d", state.joinCalls, logins)
|
||||
}
|
||||
}
|
||||
|
||||
func TestYggdrasilVerifiesTexturesSignature(t *testing.T) {
|
||||
state, api := newFakeYggdrasilServer(t)
|
||||
auth := newTestYggdrasilAuth(t, api, "SkinUser")
|
||||
@@ -554,7 +703,7 @@ func TestYggdrasilLoginFailure(t *testing.T) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier)
|
||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -568,7 +717,7 @@ func TestYggdrasilLoginFailure(t *testing.T) {
|
||||
}
|
||||
defer rawClient.Close()
|
||||
|
||||
client, err := newClientConn(rawClient, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, ""))
|
||||
client, err := newClientConn(rawClient, latestProtocolVersion, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, ""), DefaultDataChannel, DefaultPaddingChannel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -99,8 +99,8 @@ type echConfigRecord struct {
|
||||
|
||||
var (
|
||||
// The keys for both maps must be generated by ECHCacheKey().
|
||||
GlobalECHConfigCache = utils.NewTypedSyncMap[string, *ECHConfigCache]()
|
||||
clientForECHDOH = utils.NewTypedSyncMap[string, *http.Client]()
|
||||
GlobalECHConfigCache = &utils.TypedSyncMap[string, *ECHConfigCache]{}
|
||||
clientForECHDOH = &utils.TypedSyncMap[string, *http.Client]{}
|
||||
)
|
||||
|
||||
// sockopt can be nil if not specified.
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user