Compare commits

...
1 Commits
Author SHA1 Message Date
Fangliding 09e988e457 Stop transport after removing user or inbound 2026-12-02 14:03:23 +08:00
31 changed files with 248 additions and 101 deletions
+31 -3
View File
@@ -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 {
+12
View File
@@ -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
}
+3 -11
View File
@@ -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.
+1 -1
View File
@@ -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)
}
+29 -17
View File
@@ -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
})
+6 -1
View File
@@ -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()
}
}
+6
View File
@@ -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
}
+1 -1
View File
@@ -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{
+3 -1
View File
@@ -369,10 +369,12 @@ func (d *closingDispatcher) DispatchLink(_ context.Context, _ net.Destination, l
func TestServerKeepsConnectionOpenWhenWriterCloses(t *testing.T) {
conn := &stackConn{}
dispatcher := &closingDispatcher{conn: conn}
userCtx, userCancel := context.WithCancel(context.Background())
defer userCancel()
s := &Server{
ctx: context.Background(),
dispatcher: dispatcher,
tunnels: map[netip.Addr]*serverTunnel{netip.MustParseAddr("10.13.0.2"): newServerTunnel(nil, &protocol.MemoryUser{})},
tunnels: map[netip.Addr]*serverTunnel{netip.MustParseAddr("10.13.0.2"): newServerTunnel(nil, &protocol.MemoryUser{Account: &MemoryAccount{Ctx: userCtx, Cancel: userCancel}})},
}
s.HandleConnection(conn, net.TCPDestination(net.ParseAddress("192.0.2.1"), 443))
+4
View File
@@ -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")
+12
View File
@@ -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(),
+5
View File
@@ -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
}
}
+4
View File
@@ -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.
+12 -3
View File
@@ -11,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"
@@ -75,8 +76,8 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
networks: networks,
method: method,
masterPSK: masterPSK,
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
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),
@@ -121,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 != "" {
@@ -146,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
}
@@ -243,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,
+1 -1
View File
@@ -131,7 +131,7 @@ type UDPSessionManager struct {
func NewUDPSessionManager(timeout time.Duration) *UDPSessionManager {
return &UDPSessionManager{
sessions: utils.NewTypedSyncMap[uint64, *ServerUDPSession](),
sessions: &utils.TypedSyncMap[uint64, *ServerUDPSession]{},
timeout: timeout,
}
}
+8 -1
View File
@@ -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"
@@ -65,7 +66,13 @@ func (s *ServerUDPSession) EnsureLink(
// UDP Session might travel across multiple connections
// don't bind its lifetime to a parent context
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
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 {
newInbound := *inbound
+4
View File
@@ -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.
+5
View File
@@ -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
View File
@@ -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
})
+5
View File
@@ -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().
+3 -2
View File
@@ -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)
}
+5
View File
@@ -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
View File
@@ -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
})
+4
View File
@@ -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.
+3 -2
View File
@@ -5,6 +5,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"
@@ -58,7 +59,7 @@ func TestRequestSerialization(t *testing.T) {
actualRequest, err := server.DecodeRequestHeader(buffer, false)
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(vmess.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
t.Error(r)
}
@@ -147,7 +148,7 @@ func TestMuxRequest(t *testing.T) {
actualRequest, err := server.DecodeRequestHeader(buffer, false)
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(vmess.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
t.Error(r)
}
}
+5
View File
@@ -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)
+5 -1
View File
@@ -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
}
}
+4
View File
@@ -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
View File
@@ -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",
+10 -4
View File
@@ -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))
+2 -2
View File
@@ -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.