Compare commits

..
1 Commits
Author SHA1 Message Date
Fangliding 96dbfda86d Fix many panic 2026-12-04 14:56:33 +08:00
46 changed files with 252 additions and 380 deletions
+3 -31
View File
@@ -48,8 +48,7 @@ type tcpWorker struct {
hub internet.Listener
ctx context.Context
cancel context.CancelFunc
ctx context.Context
}
func getTProxyType(s *internet.MemoryStreamConfig) internet.SocketConfig_TProxyMode {
@@ -133,11 +132,6 @@ 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 {
@@ -155,9 +149,6 @@ 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 {
@@ -282,8 +273,7 @@ type udpWorker struct {
checker *task.Periodic
activeConn map[connID]*udpConn
ctx context.Context
cancel context.CancelFunc
ctx context.Context
}
func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
@@ -417,11 +407,6 @@ 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))
@@ -443,10 +428,6 @@ func (w *udpWorker) Close() error {
w.Lock()
defer w.Unlock()
if w.cancel != nil {
w.cancel()
}
var errs []interface{}
if w.hub != nil {
@@ -491,8 +472,7 @@ type dsWorker struct {
hub internet.Listener
ctx context.Context
cancel context.CancelFunc
ctx context.Context
}
func (w *dsWorker) callback(conn stat.Connection) {
@@ -537,11 +517,6 @@ 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)
@@ -554,9 +529,6 @@ 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,15 +23,3 @@ 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
}
+4
View File
@@ -1,6 +1,7 @@
package protocol
import (
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
)
@@ -17,6 +18,9 @@ func NewServerSpec(dest net.Destination, user *MemoryUser) *ServerSpec {
}
func NewServerSpecFromPB(spec *ServerEndpoint) (*ServerSpec, error) {
if spec == nil || spec.Address == nil {
return nil, errors.New("server address is not set")
}
dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
var dUser *MemoryUser
if spec.User != nil {
+11 -3
View File
@@ -6,11 +6,19 @@ 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
// 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 returned nil, it will return the zero value of the type V.
type TypedSyncMap[K, V any] struct {
syncMap sync.Map
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{},
}
}
// Clear deletes all the entries, resulting in an empty Map.
+6
View File
@@ -47,6 +47,9 @@ type Address struct {
// MarshalJSON implements encoding/json.Marshaler.MarshalJSON
func (v *Address) MarshalJSON() ([]byte, error) {
if v.Address == nil {
return json.Marshal(net.AnyIP.String())
}
return json.Marshal(v.Address.String())
}
@@ -68,6 +71,9 @@ func (v *Address) Build() *net.IPOrDomain {
if v == nil {
return nil
}
if v.Address == nil {
return net.NewIPOrDomain(net.AnyIP)
}
return net.NewIPOrDomain(v.Address)
}
+1 -1
View File
@@ -47,7 +47,7 @@ func (c *HTTPServerConfig) Build() (proto.Message, error) {
}
type HTTPClientConfig struct {
Address *Address `json:"address"`
Address Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
+3 -3
View File
@@ -11,9 +11,9 @@ import (
)
type HysteriaClientConfig struct {
Version int32 `json:"version"`
Address *Address `json:"address"`
Port uint16 `json:"port"`
Version int32 `json:"version"`
Address Address `json:"address"`
Port uint16 `json:"port"`
}
func (c *HysteriaClientConfig) Build() (proto.Message, error) {
+1 -4
View File
@@ -12,15 +12,12 @@ import (
)
type MasqueClientConfig struct {
Address *Address `json:"address"`
Address Address `json:"address"`
Port uint16 `json:"port"`
RemoteDNS []string `json:"remoteDNS"`
}
func (c *MasqueClientConfig) Build() (proto.Message, error) {
if c.Address == nil {
return nil, errors.New(`MASQUE: "address" is not set`)
}
if c.Port == 0 {
return nil, errors.New(`MASQUE: "port" is not set`)
}
+6 -9
View File
@@ -178,20 +178,17 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
}
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"`
Address Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Cipher string `json:"method"`
Password string `json:"password"`
}
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
errors.PrintNonRemovalDeprecatedFeatureWarning("Shadowsocks (with no Forward Secrecy, etc.)", "VLESS Encryption")
if v.Address == nil {
return nil, errors.New("Shadowsocks server address is not set.")
}
if v.Port == 0 {
return nil, errors.New("Invalid Shadowsocks port.")
}
+6 -6
View File
@@ -65,12 +65,12 @@ func (v *SocksServerConfig) Build() (proto.Message, error) {
}
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"`
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) {
+3
View File
@@ -929,6 +929,9 @@ func (c *XDNS) Build() (proto.Message, error) {
return nil, err
}
quicConfig = proto.(*internet.QuicParams)
if quicConfig.Congestion == "brutal" {
return nil, errors.New(`XDNS: "brutal" is for Hysteria, use "force-brutal", "bbr" or "reno"`)
}
}
for j := range c.Resolvers[i].Addrs {
var u *url.URL
+3
View File
@@ -277,6 +277,9 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
return nil, errors.New(`XDRIVE: brutal is for Hysteria servers, over h3 "congestion" is "bbr" or "reno", not "`, config.QuicParams.Congestion, `"`)
}
}
if config.ProtocolName == "splithttp" && config.QuicParams != nil && config.QuicParams.Congestion == "brutal" {
return nil, errors.New(`XHTTP: "brutal" is for Hysteria, use "force-brutal", "bbr" or "reno"`)
}
return config, nil
}
+3
View File
@@ -455,6 +455,9 @@ func (c *SplitHTTPConfig) Build() (proto.Message, error) {
if c.ServerMaxHeaderBytes < 0 {
return nil, errors.New("invalid negative value of maxHeaderBytes")
}
if c.ScMaxEachPostBytes.From < 0 || c.ScMaxEachPostBytes.To < 0 || (c.ScMaxEachPostBytes.To > 0 && c.ScMaxEachPostBytes.From <= 0) {
return nil, errors.New("`scMaxEachPostBytes` must be greater than 0")
}
if c.Xmux.MaxConnections.To > 0 && c.Xmux.MaxConcurrency.To > 0 {
return nil, errors.New("maxConnections cannot be specified together with maxConcurrency")
+5 -8
View File
@@ -19,11 +19,11 @@ import (
// 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"`
Address Address `json:"address"`
Port uint16 `json:"port"`
Level byte `json:"level"`
Email string `json:"email"`
Password string `json:"password"`
}
// Build implements Buildable
@@ -32,9 +32,6 @@ func (c *TrojanClientConfig) Build() (proto.Message, error) {
config := &trojan.ClientConfig{}
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.")
}
+100 -95
View File
@@ -104,56 +104,15 @@ func (c *VLessInboundConfig) Build() (proto.Message, error) {
return nil, err
}
config.Decryption = c.Decryption
if !func() bool {
s := strings.Split(config.Decryption, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return false
}
switch s[1] {
case "native":
case "xorpub":
config.XorMode = 1
case "random":
config.XorMode = 2
default:
return false
}
t := strings.SplitN(strings.TrimSuffix(s[2], "s"), "-", 2)
i, err := strconv.Atoi(t[0])
if err != nil {
return false
}
config.SecondsFrom = int64(i)
if len(t) == 2 {
i, err := strconv.Atoi(t[1])
if err != nil {
return false
}
config.SecondsTo = int64(i)
}
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) != 64 {
return false
}
}
config.Decryption = config.Decryption[27+len(s[2]):]
if padding > 0 {
config.Padding = config.Decryption[:padding-1]
config.Decryption = config.Decryption[padding:]
}
return true
}() && config.Decryption != "none" {
if config.Decryption == "" {
return nil, errors.New(`VLESS settings: please add/set "decryption":"none" to every settings`)
}
return nil, errors.New(`VLESS settings: unsupported "decryption": ` + config.Decryption)
dec, err := parseVLESSEncryption(c.Decryption, false)
if err != nil {
return nil, err
}
config.Decryption = dec.key
config.Padding = dec.padding
config.XorMode = dec.xorMode
config.SecondsFrom = dec.secondsFrom
config.SecondsTo = dec.secondsTo
if config.Decryption != "none" && c.Fallbacks != nil {
return nil, errors.New(`VLESS settings: "fallbacks" can not be used together with "decryption"`)
@@ -257,7 +216,7 @@ func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
}
type VLessOutboundConfig struct {
Address *Address `json:"address"`
Address Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
@@ -279,9 +238,6 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
}
config := &outbound.Config{Multiplex: multiplex}
if c.Address == nil {
return nil, errors.New(`VLESS: "address" is not set`)
}
uid, err := uuid.ParseString(c.Id)
if err != nil {
return nil, err
@@ -318,49 +274,14 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
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)
enc, err := parseVLESSEncryption(account.Encryption, true)
if err != nil {
return nil, err
}
account.Encryption = enc.key
account.Padding = enc.padding
account.XorMode = enc.xorMode
account.Seconds = enc.seconds
user.Account = serial.ToTypedMessage(account)
spec.User = user
@@ -368,3 +289,87 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
config.Vnext = spec
return config, nil
}
type parsedVLESSEncryption struct {
key string
padding string
xorMode uint32
seconds uint32
secondsFrom int64
secondsTo int64
}
func parseVLESSEncryption(raw string, isOutbound bool) (parsedVLESSEncryption, error) {
field, scope := "decryption", "settings"
if isOutbound {
field, scope = "encryption", "users"
}
if raw == "" {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: please add/set "`, field, `":"none"`)
}
if raw == "none" {
return parsedVLESSEncryption{key: "none"}, nil
}
s := strings.Split(raw, ".")
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `": `, raw)
}
var out parsedVLESSEncryption
switch s[1] {
case "native":
case "xorpub":
out.xorMode = 1
case "random":
out.xorMode = 2
default:
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `" mode: `, s[1])
}
if isOutbound {
switch s[2] {
case "1rtt":
case "0rtt":
out.seconds = 1
default:
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `" rtt: `, s[2])
}
} else {
t := strings.SplitN(strings.TrimSuffix(s[2], "s"), "-", 2)
i, err := strconv.Atoi(t[0])
if err != nil {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" seconds: `, s[2]).Base(err)
}
out.secondsFrom = int64(i)
if len(t) == 2 {
i, err := strconv.Atoi(t[1])
if err != nil {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" seconds: `, s[2]).Base(err)
}
out.secondsTo = int64(i)
}
}
altKeyLen := 64
if isOutbound {
altKeyLen = 1184
}
padding := 0
for i, r := range s[3:] {
if len(r) < 20 {
padding += len(r) + 1
continue
}
for _, r := range s[3+i:] {
b, err := base64.RawURLEncoding.DecodeString(r)
if err != nil || (len(b) != 32 && len(b) != altKeyLen) {
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" key segment`)
}
}
rest := raw[27+len(s[2]):]
if padding > 0 {
out.padding = rest[:padding-1]
rest = rest[padding:]
}
out.key = rest
return out, nil
}
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: missing "`, field, `" key segment`)
}
+1 -4
View File
@@ -103,7 +103,7 @@ func (c *VMessInboundConfig) Build() (proto.Message, error) {
}
type VMessOutboundConfig struct {
Address *Address `json:"address"`
Address Address `json:"address"`
Port uint16 `json:"port"`
Level uint32 `json:"level"`
Email string `json:"email"`
@@ -123,9 +123,6 @@ func (c *VMessOutboundConfig) Build() (proto.Message, error) {
}
config := &outbound.Config{Multiplex: multiplex}
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
+7
View File
@@ -3,6 +3,7 @@ package conf
import (
"encoding/base64"
"encoding/hex"
"net/netip"
"strconv"
"strings"
@@ -124,6 +125,12 @@ func (c *WireGuardConfig) Build() (proto.Message, error) {
}
config.Reserved = c.Reserved
for _, s := range c.DNS {
if _, err := netip.ParseAddr(s); err != nil {
return nil, errors.New(`WireGuard: invalid "remoteDNS" `, s).Base(err)
}
}
config.IsClient = c.IsClient
config.NoKernelTun = c.NoKernelTun
config.DNS = c.DNS
+2 -2
View File
@@ -232,13 +232,13 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
if vlessCfg.Encryption != "" && vlessCfg.Encryption != "none" {
return nil
}
if requiresTransportSecurity(vlessCfg.Address) {
if requiresTransportSecurity(&vlessCfg.Address) {
return errors.New("vless without TLS or other encryption is prohibited unless the server address is a private IP or domain")
}
}
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
if requiresTransportSecurity(tjCfg.Address) {
if requiresTransportSecurity(&tjCfg.Address) {
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
}
}
+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.TypedSyncMap[string, net.Address]{}
resolvedUDPAddr := utils.NewTypedSyncMap[string, net.Address]()
if DialDest.Address.Family().IsDomain() {
resolvedUDPAddr.Store(DialDest.Address.Domain(), net.DestinationFromAddr(conn.RemoteAddr()).Address)
}
+17 -29
View File
@@ -1,12 +1,10 @@
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"
@@ -26,9 +24,6 @@ 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 {
@@ -45,8 +40,8 @@ func (a *MemoryAccount) ToProto() proto.Message {
}
type Validator struct {
users utils.TypedSyncMap[string, *protocol.MemoryUser]
ids utils.TypedSyncMap[uuid.UUID, *protocol.MemoryUser]
users sync.Map
ids sync.Map
mu sync.Mutex
}
@@ -56,10 +51,8 @@ func NewValidator() *Validator {
func (v *Validator) Add(user *protocol.MemoryUser) (err error) {
v.mu.Lock()
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 {
v.users.Store(user.Account.(*MemoryAccount).Auth, user)
if id, err := uuid.Parse(user.Account.(*MemoryAccount).Auth); err == nil {
id[6] = 0
id[7] = 0
v.ids.Store(id, user)
@@ -71,15 +64,13 @@ 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 {
a := user.Account.(*MemoryAccount)
auth := a.Auth
auth := user.Account.(*MemoryAccount).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
@@ -89,16 +80,13 @@ 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])
orig := user.Account.(*MemoryAccount)
if orig.VR != VR {
if user.Account.(*MemoryAccount).VR != VR {
user = &protocol.MemoryUser{
Email: user.Email,
Level: user.Level,
Account: &MemoryAccount{
Auth: auth,
VR: VR,
Ctx: orig.Ctx,
Cancel: orig.Cancel,
Auth: auth,
VR: VR,
},
}
}
@@ -106,7 +94,7 @@ func (v *Validator) Get(auth string) (user *protocol.MemoryUser) {
return
}
if value, ok := v.users.Load(auth); ok {
user = value
user = value.(*protocol.MemoryUser)
}
return
}
@@ -115,15 +103,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
user = value.(*protocol.MemoryUser)
}
return
}
func (v *Validator) GetByEmail(email string) (user *protocol.MemoryUser) {
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
if value.Email == email {
user = value
v.users.Range(func(key, value any) bool {
if value.(*protocol.MemoryUser).Email == email {
user = value.(*protocol.MemoryUser)
return false
}
return true
@@ -132,15 +120,15 @@ func (v *Validator) GetByEmail(email string) (user *protocol.MemoryUser) {
}
func (v *Validator) GetAll() (users []*protocol.MemoryUser) {
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
users = append(users, value)
v.users.Range(func(key, value any) bool {
users = append(users, value.(*protocol.MemoryUser))
return true
})
return
}
func (v *Validator) GetCount() (count int64) {
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
v.users.Range(func(key, value any) bool {
count++
return true
})
@@ -148,7 +136,7 @@ func (v *Validator) GetCount() (count int64) {
}
func (v *Validator) NotEmpty() (not_empty bool) {
v.users.Range(func(key string, value *protocol.MemoryUser) bool {
v.users.Range(func(key, value any) bool {
not_empty = true
return false
})
+1 -6
View File
@@ -6,7 +6,6 @@ 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"
@@ -96,11 +95,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con
user := v.User()
if user != nil {
inbound.User = user
a := user.Account.(*account.MemoryAccount)
inbound.VlessRoute = a.VR
var cancel context.CancelFunc
ctx, cancel = c.ContextWithParents(ctx, a.Ctx)
defer cancel()
inbound.VlessRoute = user.Account.(*account.MemoryAccount).VR
}
}
-6
View File
@@ -1,7 +1,6 @@
package masque
import (
"context"
"crypto/subtle"
"strings"
"sync"
@@ -17,9 +16,6 @@ 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 {
@@ -57,7 +53,6 @@ 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
}
@@ -71,7 +66,6 @@ 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 := c.ContextWithParents(s.ctx, t.user.Account.(*MemoryAccount).Ctx)
ctx, cancel := context.WithCancel(s.ctx)
defer cancel()
ctx = c.ContextWithID(ctx, session.NewID())
inbound := session.Inbound{
+1 -3
View File
@@ -369,12 +369,10 @@ 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{Account: &MemoryAccount{Ctx: userCtx, Cancel: userCancel}})},
tunnels: map[netip.Addr]*serverTunnel{netip.MustParseAddr("10.13.0.2"): newServerTunnel(nil, &protocol.MemoryUser{})},
}
s.HandleConnection(conn, net.TCPDestination(net.ParseAddress("192.0.2.1"), 443))
-4
View File
@@ -2,7 +2,6 @@ package shadowsocks
import (
"bytes"
"context"
"crypto/cipher"
"crypto/md5"
"crypto/sha1"
@@ -25,9 +24,6 @@ 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,7 +6,6 @@ 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"
@@ -131,12 +130,6 @@ 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()
@@ -157,7 +150,6 @@ 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)
}
}
@@ -228,10 +220,6 @@ 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,7 +1,6 @@
package shadowsocks
import (
"context"
"crypto/cipher"
"crypto/hmac"
"crypto/sha256"
@@ -34,9 +33,6 @@ 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 {
@@ -62,7 +58,6 @@ 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,7 +2,6 @@ package shadowsocks_2022
import (
"bytes"
"context"
"encoding/base64"
"google.golang.org/protobuf/proto"
@@ -13,9 +12,6 @@ import (
// MemoryAccount is an account type converted from Account.
type MemoryAccount struct {
Key []byte
Ctx context.Context
Cancel context.CancelFunc
}
// AsAccount implements protocol.AsAccount.
+3 -12
View File
@@ -11,7 +11,6 @@ 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"
@@ -76,8 +75,8 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
networks: networks,
method: method,
masterPSK: masterPSK,
usersByHash: &utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]{},
usersByEmail: &utils.TypedSyncMap[string, *protocol.MemoryUser]{},
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
saltFilter: antireplay.NewMapFilter[[32]byte](60),
udpCodec: udpCodec,
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
@@ -122,8 +121,6 @@ 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 != "" {
@@ -149,11 +146,9 @@ func (i *MultiUserInbound) RemoveUser(ctx context.Context, email string) error {
return errors.New("user ", email, " not found")
}
a := u.Account.(*MemoryAccount)
pskHash := DeriveUserPSKHash(a.Key)
pskHash := DeriveUserPSKHash(u.Account.(*MemoryAccount).Key)
i.usersByHash.Delete(pskHash)
i.userCount.Add(-1)
a.Cancel()
return nil
}
@@ -248,10 +243,6 @@ 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.TypedSyncMap[uint64, *ServerUDPSession]{},
sessions: utils.NewTypedSyncMap[uint64, *ServerUDPSession](),
timeout: timeout,
}
}
+1 -8
View File
@@ -5,7 +5,6 @@ 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"
@@ -66,13 +65,7 @@ func (s *ServerUDPSession) EnsureLink(
// 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))
}
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
inbound := session.InboundFromContext(sessCtx)
if inbound != nil {
newInbound := *inbound
-4
View File
@@ -1,7 +1,6 @@
package trojan
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
@@ -16,9 +15,6 @@ import (
type MemoryAccount struct {
Password string
Key []byte
Ctx context.Context
Cancel context.CancelFunc
}
// AsAccount implements protocol.AsAccount.
-5
View File
@@ -9,7 +9,6 @@ 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"
@@ -227,10 +226,6 @@ 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)
}
+18 -16
View File
@@ -1,32 +1,29 @@
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 utils.TypedSyncMap[string, *protocol.MemoryUser]
users utils.TypedSyncMap[string, *protocol.MemoryUser]
email sync.Map
users sync.Map
}
// 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(a.Key), u)
v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u)
return nil
}
@@ -41,29 +38,34 @@ func (v *Validator) Del(e string) error {
return errors.New("User ", e, " not found.")
}
v.email.Delete(le)
a := u.Account.(*MemoryAccount)
v.users.Delete(hexString(a.Key))
a.Cancel()
v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key))
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)
return u
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
// Get a trojan user with hashed key, nil if user doesn't exist.
func (v *Validator) GetByEmail(email string) *protocol.MemoryUser {
u, _ := v.email.Load(strings.ToLower(email))
return u
email = strings.ToLower(email)
u, _ := v.email.Load(email)
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
// Get all users
func (v *Validator) GetAll() []*protocol.MemoryUser {
u := make([]*protocol.MemoryUser, 0, 100)
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
u = append(u, value)
v.email.Range(func(key, value interface{}) bool {
u = append(u, value.(*protocol.MemoryUser))
return true
})
return u
@@ -72,7 +74,7 @@ func (v *Validator) GetAll() []*protocol.MemoryUser {
// Get users count
func (v *Validator) GetCount() int64 {
var c int64 = 0
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
v.email.Range(func(key, value interface{}) bool {
c++
return true
})
-5
View File
@@ -1,8 +1,6 @@
package vless
import (
"context"
"google.golang.org/protobuf/proto"
"github.com/xtls/xray-core/common/errors"
@@ -45,9 +43,6 @@ type MemoryAccount struct {
Testpre uint32
Testseed []uint32
Ctx context.Context
Cancel context.CancelFunc
}
// Equals implements protocol.Account.Equals().
+2 -3
View File
@@ -4,7 +4,6 @@ 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"
@@ -49,7 +48,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{}), cmpopts.IgnoreFields(vless.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
@@ -121,7 +120,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{}), cmpopts.IgnoreFields(vless.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
-5
View File
@@ -13,7 +13,6 @@ 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"
@@ -542,10 +541,6 @@ 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")
}
+18 -16
View File
@@ -1,12 +1,11 @@
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"
)
@@ -28,21 +27,19 @@ 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 utils.TypedSyncMap[string, *protocol.MemoryUser]
users utils.TypedSyncMap[[16]byte, *protocol.MemoryUser]
email sync.Map
users sync.Map
}
// 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(a.ID.UUID()), u)
v.users.Store(ProcessUUID(u.Account.(*MemoryAccount).ID.UUID()), u)
return nil
}
@@ -57,29 +54,34 @@ func (v *MemoryValidator) Del(e string) error {
return errors.New("User ", e, " not found.")
}
v.email.Delete(le)
a := u.Account.(*MemoryAccount)
v.users.Delete(ProcessUUID(a.ID.UUID()))
a.Cancel()
v.users.Delete(ProcessUUID(u.(*protocol.MemoryUser).Account.(*MemoryAccount).ID.UUID()))
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))
return u
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
// Get a VLESS user with email, nil if user doesn't exist.
func (v *MemoryValidator) GetByEmail(email string) *protocol.MemoryUser {
u, _ := v.email.Load(strings.ToLower(email))
return u
email = strings.ToLower(email)
u, _ := v.email.Load(email)
if u != nil {
return u.(*protocol.MemoryUser)
}
return nil
}
// Get all users
func (v *MemoryValidator) GetAll() []*protocol.MemoryUser {
u := make([]*protocol.MemoryUser, 0, 100)
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
u = append(u, value)
v.email.Range(func(key, value interface{}) bool {
u = append(u, value.(*protocol.MemoryUser))
return true
})
return u
@@ -88,7 +90,7 @@ func (v *MemoryValidator) GetAll() []*protocol.MemoryUser {
// Get users count
func (v *MemoryValidator) GetCount() int64 {
var c int64 = 0
v.email.Range(func(key string, value *protocol.MemoryUser) bool {
v.email.Range(func(key, value interface{}) bool {
c++
return true
})
-4
View File
@@ -1,7 +1,6 @@
package vmess
import (
"context"
"strings"
"google.golang.org/protobuf/proto"
@@ -20,9 +19,6 @@ type MemoryAccount struct {
AuthenticatedLengthExperiment bool
NoTerminationSignal bool
Ctx context.Context
Cancel context.CancelFunc
}
// Equals implements protocol.Account.
+2 -3
View File
@@ -5,7 +5,6 @@ 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"
@@ -59,7 +58,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{}), cmpopts.IgnoreFields(vmess.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
@@ -148,7 +147,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{}), cmpopts.IgnoreFields(vmess.MemoryAccount{}, "Ctx", "Cancel")); r != "" {
if r := cmp.Diff(actualRequest, expectedRequest, cmp.AllowUnexported(protocol.ID{})); r != "" {
t.Error(r)
}
}
-5
View File
@@ -9,7 +9,6 @@ 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"
@@ -236,10 +235,6 @@ 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 -5
View File
@@ -1,7 +1,6 @@
package vmess
import (
"context"
"crypto/hmac"
"crypto/sha256"
"hash/crc64"
@@ -44,7 +43,6 @@ 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())
@@ -95,11 +93,9 @@ 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[:], a.ID.CmdKey())
copy(cmdkeyfl[:], u.Account.(*MemoryAccount).ID.CmdKey())
v.aeadDecoderHolder.RemoveUser(cmdkeyfl)
a.Cancel()
break
}
}
-4
View File
@@ -1,7 +1,6 @@
package wireguard
import (
"context"
"encoding/hex"
"net/netip"
@@ -37,9 +36,6 @@ type MemoryAccount struct {
AllowedIPs []netip.Prefix
PreSharedKey string
KeepAlive string
Ctx context.Context
Cancel context.CancelFunc
}
func (a *MemoryAccount) Equals(other protocol.Account) bool {
+14 -23
View File
@@ -17,7 +17,6 @@ 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"
@@ -49,7 +48,7 @@ type Server struct {
mu sync.Mutex
pub [32]byte
users *utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]
users *sync.Map
}
func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
@@ -99,15 +98,13 @@ func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) {
var pub [32]byte
curve25519.ScalarBaseMult(&pub, pri)
users := &utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]{}
users := &sync.Map{}
for _, u := range conf.Users {
user, err := u.ToMemoryUser()
if err != nil {
return nil, err
}
peer := user.Account.(*MemoryAccount)
peer.Ctx, peer.Cancel = context.WithCancel(context.Background())
users.Store(peer.Pub, user)
users.Store(user.Account.(*MemoryAccount).Pub, user)
}
s := &Server{
@@ -161,7 +158,6 @@ 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
}
@@ -179,15 +175,14 @@ 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 [32]byte, value *protocol.MemoryUser) bool {
if value.Email == email {
user = value
s.users.Range(func(key, value any) bool {
if value.(*protocol.MemoryUser).Email == email {
user = value.(*protocol.MemoryUser)
return false
}
return true
@@ -196,11 +191,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 [32]byte, value *protocol.MemoryUser) bool {
peer := value.Account.(*MemoryAccount)
s.users.Range(func(key, value any) bool {
peer := value.(*protocol.MemoryUser).Account.(*MemoryAccount)
for i := range peer.AllowedIPs {
if peer.AllowedIPs[i].Contains(addr) {
user = value
user = value.(*protocol.MemoryUser)
return false
}
}
@@ -210,15 +205,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 [32]byte, value *protocol.MemoryUser) bool {
users = append(users, value)
s.users.Range(func(key, value interface{}) bool {
users = append(users, value.(*protocol.MemoryUser))
return true
})
return
}
func (s *Server) GetUsersCount(context.Context) (count int64) {
s.users.Range(func(key [32]byte, value *protocol.MemoryUser) bool {
s.users.Range(func(key, value interface{}) bool {
count++
return true
})
@@ -300,8 +295,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 [32]byte, value *protocol.MemoryUser) bool {
peer := value.Account.(*MemoryAccount)
s.users.Range(func(key, value any) bool {
peer := value.(*protocol.MemoryUser).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")
@@ -355,10 +350,6 @@ 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 -10
View File
@@ -4,6 +4,7 @@ import (
"context"
"io"
"net/netip"
"sync"
"sync/atomic"
"testing"
@@ -11,7 +12,6 @@ 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,16 +54,10 @@ func (d *closingDispatcher) DispatchLink(_ context.Context, _ net.Destination, l
func TestServerKeepsConnectionOpenWhenWriterCloses(t *testing.T) {
conn := &stackConn{}
dispatcher := &closingDispatcher{conn: conn}
users := &utils.TypedSyncMap[[32]byte, *protocol.MemoryUser]{}
userCtx, userCancel := context.WithCancel(context.Background())
defer userCancel()
users := &sync.Map{}
users.Store([32]byte{1}, &protocol.MemoryUser{
Email: "love@xray.com",
Account: &MemoryAccount{
AllowedIPs: []netip.Prefix{netip.MustParsePrefix("10.0.0.2/32")},
Ctx: userCtx,
Cancel: userCancel,
},
Email: "love@xray.com",
Account: &MemoryAccount{AllowedIPs: []netip.Prefix{netip.MustParsePrefix("10.0.0.2/32")}},
})
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.TypedSyncMap[string, *ECHConfigCache]{}
clientForECHDOH = &utils.TypedSyncMap[string, *http.Client]{}
GlobalECHConfigCache = utils.NewTypedSyncMap[string, *ECHConfigCache]()
clientForECHDOH = utils.NewTypedSyncMap[string, *http.Client]()
)
// sockopt can be nil if not specified.