Browse Source

Style: format code by gofumpt (#761)

pull/777/head
yuhan6665 3 years ago committed by GitHub
parent
commit
e286cdcaa8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      app/dispatcher/default.go
  2. 3
      app/dns/dns_test.go
  3. 4
      app/dns/dnscommon.go
  4. 20
      app/dns/dnscommon_test.go
  5. 4
      app/dns/fakedns/fake.go
  6. 4
      app/dns/fakedns/fakedns_test.go
  7. 3
      app/dns/nameserver_local.go
  8. 3
      app/dns/nameserver_local_test.go
  9. 3
      app/dns/nameserver_quic_test.go
  10. 4
      app/log/log_creator.go
  11. 1
      app/proxyman/inbound/worker.go
  12. 3
      app/router/balancing.go
  13. 4
      app/router/condition_geoip.go
  14. 3
      app/router/condition_geoip_test.go
  15. 1
      app/router/config.go
  16. 1
      app/router/router.go
  17. 3
      app/router/router_test.go
  18. 1
      common/buf/buffer_test.go
  19. 2
      common/buf/io.go
  20. 4
      common/common.go
  21. 1
      common/crypto/auth.go
  22. 2
      common/crypto/chacha20_test.go
  23. 2
      common/crypto/internal/chacha_core.generated.go
  24. 2
      common/crypto/internal/chacha_core_gen.go
  25. 4
      common/crypto/io.go
  26. 2
      common/errors/errorgen/main.go
  27. 4
      common/log/log.go
  28. 4
      common/log/logger.go
  29. 7
      common/mux/client.go
  30. 90
      common/net/system.go
  31. 3
      common/ocsp/ocsp.go
  32. 2
      common/platform/filesystem/file.go
  33. 3
      common/protocol/bittorrent/bittorrent.go
  34. 2
      common/protocol/tls/cert/cert_test.go
  35. 6
      common/protocol/tls/sniff.go
  36. 4
      common/retry/retry.go
  37. 4
      common/retry/retry_test.go
  38. 20
      common/strmatcher/ac_automaton_matcher.go
  39. 7
      common/strmatcher/mph_matcher.go
  40. 6
      common/strmatcher/strmatcher_test.go
  41. 4
      common/type.go
  42. 2
      common/type_test.go
  43. 4
      common/uuid/uuid.go
  44. 4
      core/xray.go
  45. 4
      infra/conf/blackhole.go
  46. 3
      infra/conf/dns_test.go
  47. 1
      infra/conf/http.go
  48. 3
      infra/conf/json/reader_test.go
  49. 3
      infra/conf/mtproto.go
  50. 4
      infra/conf/router.go
  51. 5
      infra/conf/serial/builder.go
  52. 1
      infra/conf/socks.go
  53. 2
      infra/conf/transport_internet.go
  54. 1
      infra/conf/vmess.go
  55. 45
      infra/conf/xray_test.go
  56. 4
      main/commands/all/tls/ping.go
  57. 6
      main/commands/base/command.go
  58. 6
      main/confloader/confloader.go
  59. 2
      main/run.go
  60. 3
      proxy/dns/dns_test.go
  61. 2
      proxy/http/client.go
  62. 2
      proxy/http/server.go
  63. 4
      proxy/mtproto/auth.go
  64. 5
      proxy/mtproto/client.go
  65. 12
      proxy/mtproto/server.go
  66. 4
      proxy/shadowsocks/client.go
  67. 1
      proxy/shadowsocks/protocol.go
  68. 2
      proxy/shadowsocks/server.go
  69. 2
      proxy/socks/client.go
  70. 3
      proxy/socks/server.go
  71. 2
      proxy/trojan/client.go
  72. 2
      proxy/trojan/server.go
  73. 4
      proxy/vless/inbound/inbound.go
  74. 4
      proxy/vless/outbound/outbound.go
  75. 6
      proxy/vmess/aead/encrypt.go
  76. 8
      proxy/vmess/aead/encrypt_test.go
  77. 3
      proxy/vmess/encoding/auth.go
  78. 3
      proxy/vmess/encoding/commands.go
  79. 4
      proxy/vmess/inbound/inbound.go
  80. 2
      proxy/vmess/outbound/outbound.go
  81. 5
      testing/mocks/dns.go
  82. 3
      testing/mocks/io.go
  83. 3
      testing/mocks/log.go
  84. 3
      testing/mocks/mux.go
  85. 3
      testing/mocks/outbound.go
  86. 4
      testing/scenarios/vmess_test.go
  87. 1
      testing/servers/tcp/tcp.go
  88. 6
      transport/internet/dialer.go
  89. 6
      transport/internet/domainsocket/config.go
  90. 3
      transport/internet/grpc/dial.go
  91. 2
      transport/internet/grpc/encoding/multiconn.go
  92. 4
      transport/internet/kcp/dialer.go
  93. 1
      transport/internet/quic/hub.go
  94. 6
      transport/internet/quic/quic.go
  95. 1
      transport/internet/sockopt_freebsd.go
  96. 1
      transport/internet/sockopt_windows.go
  97. 4
      transport/internet/system_dialer.go
  98. 4
      transport/internet/system_listener.go
  99. 5
      transport/internet/tcp_hub.go
  100. 4
      transport/internet/tls/config.go
  101. Some files were not shown because too many files have changed in this diff Show More

4
app/dispatcher/default.go

@ -25,9 +25,7 @@ import (
"github.com/xtls/xray-core/transport/pipe" "github.com/xtls/xray-core/transport/pipe"
) )
var ( var errSniffingTimeout = newError("timeout on sniffing")
errSniffingTimeout = newError("timeout on sniffing")
)
type cachedReader struct { type cachedReader struct {
sync.Mutex sync.Mutex

3
app/dns/dns_test.go

@ -21,8 +21,7 @@ import (
"github.com/xtls/xray-core/testing/servers/udp" "github.com/xtls/xray-core/testing/servers/udp"
) )
type staticHandler struct { type staticHandler struct{}
}
func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
ans := new(dns.Msg) ans := new(dns.Msg)

4
app/dns/dnscommon.go

@ -54,9 +54,7 @@ func isNewer(baseRec *IPRecord, newRec *IPRecord) bool {
return baseRec.Expire.Before(newRec.Expire) return baseRec.Expire.Before(newRec.Expire)
} }
var ( var errRecordNotFound = errors.New("record not found")
errRecordNotFound = errors.New("record not found")
)
type dnsRequest struct { type dnsRequest struct {
reqType dnsmessage.Type reqType dnsmessage.Type

20
app/dns/dnscommon_test.go

@ -50,20 +50,28 @@ func Test_parseResponse(t *testing.T) {
want *IPRecord want *IPRecord
wantErr bool wantErr bool
}{ }{
{"empty", {
"empty",
&IPRecord{0, []net.Address(nil), time.Time{}, dnsmessage.RCodeSuccess}, &IPRecord{0, []net.Address(nil), time.Time{}, dnsmessage.RCodeSuccess},
false, false,
}, },
{"error", {
"error",
nil, nil,
true, true,
}, },
{"a record", {
&IPRecord{1, []net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")}, "a record",
time.Time{}, dnsmessage.RCodeSuccess}, &IPRecord{
1,
[]net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")},
time.Time{},
dnsmessage.RCodeSuccess,
},
false, false,
}, },
{"aaaa record", {
"aaaa record",
&IPRecord{2, []net.Address{net.ParseAddress("2001::123:8888"), net.ParseAddress("2001::123:8844")}, time.Time{}, dnsmessage.RCodeSuccess}, &IPRecord{2, []net.Address{net.ParseAddress("2001::123:8888"), net.ParseAddress("2001::123:8844")}, time.Time{}, dnsmessage.RCodeSuccess},
false, false,
}, },

4
app/dns/fakedns/fake.go

@ -79,13 +79,13 @@ func (fkdns *Holder) GetFakeIPForDomain(domain string) []net.Address {
if v, ok := fkdns.domainToIP.Get(domain); ok { if v, ok := fkdns.domainToIP.Get(domain); ok {
return []net.Address{v.(net.Address)} return []net.Address{v.(net.Address)}
} }
var currentTimeMillis = uint64(time.Now().UnixNano() / 1e6) currentTimeMillis := uint64(time.Now().UnixNano() / 1e6)
ones, bits := fkdns.ipRange.Mask.Size() ones, bits := fkdns.ipRange.Mask.Size()
rooms := bits - ones rooms := bits - ones
if rooms < 64 { if rooms < 64 {
currentTimeMillis %= (uint64(1) << rooms) currentTimeMillis %= (uint64(1) << rooms)
} }
var bigIntIP = big.NewInt(0).SetBytes(fkdns.ipRange.IP) bigIntIP := big.NewInt(0).SetBytes(fkdns.ipRange.IP)
bigIntIP = bigIntIP.Add(bigIntIP, new(big.Int).SetUint64(currentTimeMillis)) bigIntIP = bigIntIP.Add(bigIntIP, new(big.Int).SetUint64(currentTimeMillis))
var ip net.Address var ip net.Address
for { for {

4
app/dns/fakedns/fakedns_test.go

@ -11,9 +11,7 @@ import (
"github.com/xtls/xray-core/features/dns" "github.com/xtls/xray-core/features/dns"
) )
var ( var ipPrefix = "198.18."
ipPrefix = "198.18."
)
func TestNewFakeDnsHolder(_ *testing.T) { func TestNewFakeDnsHolder(_ *testing.T) {
_, err := NewFakeDNSHolder() _, err := NewFakeDNSHolder()

3
app/dns/nameserver_local.go

@ -2,9 +2,10 @@ package dns
import ( import (
"context" "context"
"github.com/xtls/xray-core/features/dns"
"strings" "strings"
"github.com/xtls/xray-core/features/dns"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/features/dns/localdns" "github.com/xtls/xray-core/features/dns/localdns"
) )

3
app/dns/nameserver_local_test.go

@ -2,10 +2,11 @@ package dns_test
import ( import (
"context" "context"
"github.com/xtls/xray-core/common/net"
"testing" "testing"
"time" "time"
"github.com/xtls/xray-core/common/net"
. "github.com/xtls/xray-core/app/dns" . "github.com/xtls/xray-core/app/dns"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/features/dns" "github.com/xtls/xray-core/features/dns"

3
app/dns/nameserver_quic_test.go

@ -2,11 +2,12 @@ package dns_test
import ( import (
"context" "context"
"github.com/xtls/xray-core/features/dns"
"net/url" "net/url"
"testing" "testing"
"time" "time"
"github.com/xtls/xray-core/features/dns"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
. "github.com/xtls/xray-core/app/dns" . "github.com/xtls/xray-core/app/dns"

4
app/log/log_creator.go

@ -11,9 +11,7 @@ type HandlerCreatorOptions struct {
type HandlerCreator func(LogType, HandlerCreatorOptions) (log.Handler, error) type HandlerCreator func(LogType, HandlerCreatorOptions) (log.Handler, error)
var ( var handlerCreatorMap = make(map[LogType]HandlerCreator)
handlerCreatorMap = make(map[LogType]HandlerCreator)
)
func RegisterHandlerCreator(logType LogType, f HandlerCreator) error { func RegisterHandlerCreator(logType LogType, f HandlerCreator) error {
if f == nil { if f == nil {

1
app/proxyman/inbound/worker.go

@ -482,6 +482,7 @@ func (w *dsWorker) Proxy() proxy.Inbound {
func (w *dsWorker) Port() net.Port { func (w *dsWorker) Port() net.Port {
return net.Port(0) return net.Port(0)
} }
func (w *dsWorker) Start() error { func (w *dsWorker) Start() error {
ctx := context.Background() ctx := context.Background()
hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn stat.Connection) { hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn stat.Connection) {

3
app/router/balancing.go

@ -9,8 +9,7 @@ type BalancingStrategy interface {
PickOutbound([]string) string PickOutbound([]string) string
} }
type RandomStrategy struct { type RandomStrategy struct{}
}
func (s *RandomStrategy) PickOutbound(tags []string) string { func (s *RandomStrategy) PickOutbound(tags []string) string {
n := len(tags) n := len(tags)

4
app/router/condition_geoip.go

@ -186,6 +186,4 @@ func (c *GeoIPMatcherContainer) Add(geoip *GeoIP) (*GeoIPMatcher, error) {
return m, nil return m, nil
} }
var ( var globalGeoIPContainer GeoIPMatcherContainer
globalGeoIPContainer GeoIPMatcherContainer
)

3
app/router/condition_geoip_test.go

@ -89,7 +89,8 @@ func TestGeoIPMatcher(t *testing.T) {
{ {
Input: "192.0.1.0", Input: "192.0.1.0",
Output: false, Output: false,
}, { },
{
Input: "0.1.0.0", Input: "0.1.0.0",
Output: true, Output: true,
}, },

1
app/router/config.go

@ -84,7 +84,6 @@ func (rr *RoutingRule) BuildCondition() (Condition, error) {
newError("MphDomainMatcher is enabled for ", len(rr.Domain), " domain rule(s)").AtDebug().WriteToLog() newError("MphDomainMatcher is enabled for ", len(rr.Domain), " domain rule(s)").AtDebug().WriteToLog()
conds.Add(matcher) conds.Add(matcher)
} }
} }
if len(rr.UserEmail) > 0 { if len(rr.UserEmail) > 0 {

1
app/router/router.go

@ -80,7 +80,6 @@ func (r *Router) PickRoute(ctx routing.Context) (routing.Route, error) {
} }
func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context, error) { func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context, error) {
// SkipDNSResolve is set from DNS module. // SkipDNSResolve is set from DNS module.
// the DOH remote server maybe a domain name, // the DOH remote server maybe a domain name,
// this prevents cycle resolving dead loop // this prevents cycle resolving dead loop

3
app/router/router_test.go

@ -2,9 +2,10 @@ package router_test
import ( import (
"context" "context"
"github.com/xtls/xray-core/features/dns"
"testing" "testing"
"github.com/xtls/xray-core/features/dns"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
. "github.com/xtls/xray-core/app/router" . "github.com/xtls/xray-core/app/router"

1
common/buf/buffer_test.go

@ -78,6 +78,7 @@ func TestBufferByte(t *testing.T) {
buffer.Release() buffer.Release()
} }
} }
func TestBufferResize(t *testing.T) { func TestBufferResize(t *testing.T) {
buffer := New() buffer := New()
defer buffer.Release() defer buffer.Release()

2
common/buf/io.go

@ -121,7 +121,7 @@ func NewWriter(writer io.Writer) Writer {
return mw return mw
} }
var iConn = writer iConn := writer
if statConn, ok := writer.(*stat.CounterConnection); ok { if statConn, ok := writer.(*stat.CounterConnection); ok {
iConn = statConn.Connection iConn = statConn.Connection
} }

4
common/common.go

@ -14,10 +14,8 @@ import (
//go:generate go run github.com/xtls/xray-core/common/errors/errorgen //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
var (
// ErrNoClue is for the situation that existing information is not enough to make a decision. For example, Router may return this error when there is no suitable route. // ErrNoClue is for the situation that existing information is not enough to make a decision. For example, Router may return this error when there is no suitable route.
ErrNoClue = errors.New("not enough information for making a decision") var ErrNoClue = errors.New("not enough information for making a decision")
)
// Must panics if err is not nil. // Must panics if err is not nil.
func Must(err error) { func Must(err error) {

1
common/crypto/auth.go

@ -290,7 +290,6 @@ func (w *AuthenticationWriter) writeStream(mb buf.MultiBuffer) error {
mb = nb mb = nb
eb, err := w.seal(rawBytes[:nBytes]) eb, err := w.seal(rawBytes[:nBytes])
if err != nil { if err != nil {
buf.ReleaseMulti(mb2Write) buf.ReleaseMulti(mb2Write)
return err return err

2
common/crypto/chacha20_test.go

@ -18,7 +18,7 @@ func mustDecodeHex(s string) []byte {
} }
func TestChaCha20Stream(t *testing.T) { func TestChaCha20Stream(t *testing.T) {
var cases = []struct { cases := []struct {
key []byte key []byte
iv []byte iv []byte
output []byte output []byte

2
common/crypto/internal/chacha_core.generated.go

@ -3,7 +3,7 @@ package internal
import "encoding/binary" import "encoding/binary"
func ChaCha20Block(s *[16]uint32, out []byte, rounds int) { func ChaCha20Block(s *[16]uint32, out []byte, rounds int) {
var x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 = s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15] x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 := s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], s[12], s[13], s[14], s[15]
for i := 0; i < rounds; i += 2 { for i := 0; i < rounds; i += 2 {
var x uint32 var x uint32

2
common/crypto/internal/chacha_core_gen.go

@ -56,7 +56,7 @@ func ChaCha20Block(s *[16]uint32, out []byte, rounds int) {
} }
func main() { func main() {
file, err := os.OpenFile("chacha_core.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) file, err := os.OpenFile("chacha_core.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644)
if err != nil { if err != nil {
log.Fatalf("Failed to generate chacha_core.go: %v", err) log.Fatalf("Failed to generate chacha_core.go: %v", err)
} }

4
common/crypto/io.go

@ -27,9 +27,7 @@ func (r *CryptionReader) Read(data []byte) (int, error) {
return nBytes, err return nBytes, err
} }
var ( var _ buf.Writer = (*CryptionWriter)(nil)
_ buf.Writer = (*CryptionWriter)(nil)
)
type CryptionWriter struct { type CryptionWriter struct {
stream cipher.Stream stream cipher.Stream

2
common/errors/errorgen/main.go

@ -17,7 +17,7 @@ func main() {
pkg = "core" pkg = "core"
} }
file, err := os.OpenFile("errors.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) file, err := os.OpenFile("errors.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644)
if err != nil { if err != nil {
fmt.Printf("Failed to generate errors.generated.go: %v", err) fmt.Printf("Failed to generate errors.generated.go: %v", err)
os.Exit(1) os.Exit(1)

4
common/log/log.go

@ -32,9 +32,7 @@ func Record(msg Message) {
logHandler.Handle(msg) logHandler.Handle(msg)
} }
var ( var logHandler syncHandler
logHandler syncHandler
)
// RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded. // RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded.
func RegisterHandler(handler Handler) { func RegisterHandler(handler Handler) {

4
common/log/logger.go

@ -130,13 +130,13 @@ func CreateStderrLogWriter() WriterCreator {
// CreateFileLogWriter returns a LogWriterCreator that creates LogWriter for the given file. // CreateFileLogWriter returns a LogWriterCreator that creates LogWriter for the given file.
func CreateFileLogWriter(path string) (WriterCreator, error) { func CreateFileLogWriter(path string) (WriterCreator, error) {
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil { if err != nil {
return nil, err return nil, err
} }
file.Close() file.Close()
return func() Writer { return func() Writer {
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil { if err != nil {
return nil return nil
} }

7
common/mux/client.go

@ -142,7 +142,6 @@ func (f *DialingWorkerFactory) Create() (*ClientWorker, error) {
Reader: downlinkReader, Reader: downlinkReader,
Writer: upLinkWriter, Writer: upLinkWriter,
}, f.Strategy) }, f.Strategy)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -175,8 +174,10 @@ type ClientWorker struct {
strategy ClientStrategy strategy ClientStrategy
} }
var muxCoolAddress = net.DomainAddress("v1.mux.cool") var (
var muxCoolPort = net.Port(9527) muxCoolAddress = net.DomainAddress("v1.mux.cool")
muxCoolPort = net.Port(9527)
)
// NewClientWorker creates a new mux.Client. // NewClientWorker creates a new mux.Client.
func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) { func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) {

90
common/net/system.go

@ -3,17 +3,21 @@ package net
import "net" import "net"
// DialTCP is an alias of net.DialTCP. // DialTCP is an alias of net.DialTCP.
var DialTCP = net.DialTCP var (
var DialUDP = net.DialUDP DialTCP = net.DialTCP
var DialUnix = net.DialUnix DialUDP = net.DialUDP
var Dial = net.Dial DialUnix = net.DialUnix
Dial = net.Dial
)
type ListenConfig = net.ListenConfig type ListenConfig = net.ListenConfig
var Listen = net.Listen var (
var ListenTCP = net.ListenTCP Listen = net.Listen
var ListenUDP = net.ListenUDP ListenTCP = net.ListenTCP
var ListenUnix = net.ListenUnix ListenUDP = net.ListenUDP
ListenUnix = net.ListenUnix
)
var LookupIP = net.LookupIP var LookupIP = net.LookupIP
@ -26,36 +30,54 @@ var SplitHostPort = net.SplitHostPort
var CIDRMask = net.CIDRMask var CIDRMask = net.CIDRMask
type Addr = net.Addr type (
type Conn = net.Conn Addr = net.Addr
type PacketConn = net.PacketConn Conn = net.Conn
PacketConn = net.PacketConn
)
type TCPAddr = net.TCPAddr type (
type TCPConn = net.TCPConn TCPAddr = net.TCPAddr
TCPConn = net.TCPConn
)
type UDPAddr = net.UDPAddr type (
type UDPConn = net.UDPConn UDPAddr = net.UDPAddr
UDPConn = net.UDPConn
)
type UnixAddr = net.UnixAddr type (
type UnixConn = net.UnixConn UnixAddr = net.UnixAddr
UnixConn = net.UnixConn
)
// IP is an alias for net.IP. // IP is an alias for net.IP.
type IP = net.IP type (
type IPMask = net.IPMask IP = net.IP
type IPNet = net.IPNet IPMask = net.IPMask
IPNet = net.IPNet
const IPv4len = net.IPv4len )
const IPv6len = net.IPv6len
const (
type Error = net.Error IPv4len = net.IPv4len
type AddrError = net.AddrError IPv6len = net.IPv6len
)
type Dialer = net.Dialer
type Listener = net.Listener type (
type TCPListener = net.TCPListener Error = net.Error
type UnixListener = net.UnixListener AddrError = net.AddrError
)
var ResolveUnixAddr = net.ResolveUnixAddr
var ResolveUDPAddr = net.ResolveUDPAddr type (
Dialer = net.Dialer
Listener = net.Listener
TCPListener = net.TCPListener
UnixListener = net.UnixListener
)
var (
ResolveUnixAddr = net.ResolveUnixAddr
ResolveUDPAddr = net.ResolveUDPAddr
)
type Resolver = net.Resolver type Resolver = net.Resolver

3
common/ocsp/ocsp.go

@ -56,7 +56,6 @@ func GetOCSPForCert(cert [][]byte) ([]byte, error) {
pemBundle := bundle.Bytes() pemBundle := bundle.Bytes()
certificates, err := parsePEMBundle(pemBundle) certificates, err := parsePEMBundle(pemBundle)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -99,12 +98,10 @@ func GetOCSPForCert(cert [][]byte) ([]byte, error) {
} }
defer req.Body.Close() defer req.Body.Close()
ocspResBytes, err := io.ReadAll(req.Body) ocspResBytes, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
return nil, newError(err) return nil, newError(err)
} }
return ocspResBytes, nil return ocspResBytes, nil
} }
// parsePEMBundle parses a certificate bundle from top to bottom and returns // parsePEMBundle parses a certificate bundle from top to bottom and returns

2
common/platform/filesystem/file.go

@ -33,7 +33,7 @@ func CopyFile(dst string, src string) error {
if err != nil { if err != nil {
return err return err
} }
f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil { if err != nil {
return err return err
} }

3
common/protocol/bittorrent/bittorrent.go

@ -6,8 +6,7 @@ import (
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
) )
type SniffHeader struct { type SniffHeader struct{}
}
func (h *SniffHeader) Protocol() string { func (h *SniffHeader) Protocol() string {
return "bittorrent" return "bittorrent"

2
common/protocol/tls/cert/cert_test.go

@ -73,6 +73,7 @@ func printJSON(certificate *Certificate) {
os.Stdout.Write(content) os.Stdout.Write(content)
os.Stdout.WriteString("\n") os.Stdout.WriteString("\n")
} }
func printFile(certificate *Certificate, name string) error { func printFile(certificate *Certificate, name string) error {
certPEM, keyPEM := certificate.ToPEM() certPEM, keyPEM := certificate.ToPEM()
return task.Run(context.Background(), func() error { return task.Run(context.Background(), func() error {
@ -81,6 +82,7 @@ func printFile(certificate *Certificate, name string) error {
return writeFile(keyPEM, name+"_key.pem") return writeFile(keyPEM, name+"_key.pem")
}) })
} }
func writeFile(content []byte, name string) error { func writeFile(content []byte, name string) error {
f, err := os.Create(name) f, err := os.Create(name)
if err != nil { if err != nil {

6
common/protocol/tls/sniff.go

@ -20,8 +20,10 @@ func (h *SniffHeader) Domain() string {
return h.domain return h.domain
} }
var errNotTLS = errors.New("not TLS header") var (
var errNotClientHello = errors.New("not client hello") errNotTLS = errors.New("not TLS header")
errNotClientHello = errors.New("not client hello")
)
func IsValidTLSVersion(major, minor byte) bool { func IsValidTLSVersion(major, minor byte) bool {
return major == 3 return major == 3

4
common/retry/retry.go

@ -6,9 +6,7 @@ import (
"time" "time"
) )
var ( var ErrRetryFailed = newError("all retry attempts failed")
ErrRetryFailed = newError("all retry attempts failed")
)
// Strategy is a way to retry on a specific function. // Strategy is a way to retry on a specific function.
type Strategy interface { type Strategy interface {

4
common/retry/retry_test.go

@ -9,9 +9,7 @@ import (
. "github.com/xtls/xray-core/common/retry" . "github.com/xtls/xray-core/common/retry"
) )
var ( var errorTestOnly = errors.New("this is a fake error")
errorTestOnly = errors.New("this is a fake error")
)
func TestNoRetry(t *testing.T) { func TestNoRetry(t *testing.T) {
startTime := time.Now().Unix() startTime := time.Now().Unix()

20
common/strmatcher/ac_automaton_matcher.go

@ -122,7 +122,7 @@ var char2Index = []int{
} }
func NewACAutomaton() *ACAutomaton { func NewACAutomaton() *ACAutomaton {
var ac = new(ACAutomaton) ac := new(ACAutomaton)
ac.trie = append(ac.trie, newNode()) ac.trie = append(ac.trie, newNode())
ac.fail = append(ac.fail, 0) ac.fail = append(ac.fail, 0)
ac.exists = append(ac.exists, MatchType{ ac.exists = append(ac.exists, MatchType{
@ -133,9 +133,9 @@ func NewACAutomaton() *ACAutomaton {
} }
func (ac *ACAutomaton) Add(domain string, t Type) { func (ac *ACAutomaton) Add(domain string, t Type) {
var node = 0 node := 0
for i := len(domain) - 1; i >= 0; i-- { for i := len(domain) - 1; i >= 0; i-- {
var idx = char2Index[domain[i]] idx := char2Index[domain[i]]
if ac.trie[node][idx].nextNode == 0 { if ac.trie[node][idx].nextNode == 0 {
ac.count++ ac.count++
if len(ac.trie) < ac.count+1 { if len(ac.trie) < ac.count+1 {
@ -163,7 +163,7 @@ func (ac *ACAutomaton) Add(domain string, t Type) {
matchType: Full, matchType: Full,
exist: true, exist: true,
} }
var idx = char2Index['.'] idx := char2Index['.']
if ac.trie[node][idx].nextNode == 0 { if ac.trie[node][idx].nextNode == 0 {
ac.count++ ac.count++
if len(ac.trie) < ac.count+1 { if len(ac.trie) < ac.count+1 {
@ -190,18 +190,18 @@ func (ac *ACAutomaton) Add(domain string, t Type) {
} }
func (ac *ACAutomaton) Build() { func (ac *ACAutomaton) Build() {
var queue = list.New() queue := list.New()
for i := 0; i < validCharCount; i++ { for i := 0; i < validCharCount; i++ {
if ac.trie[0][i].nextNode != 0 { if ac.trie[0][i].nextNode != 0 {
queue.PushBack(ac.trie[0][i]) queue.PushBack(ac.trie[0][i])
} }
} }
for { for {
var front = queue.Front() front := queue.Front()
if front == nil { if front == nil {
break break
} else { } else {
var node = front.Value.(Edge).nextNode node := front.Value.(Edge).nextNode
queue.Remove(front) queue.Remove(front)
for i := 0; i < validCharCount; i++ { for i := 0; i < validCharCount; i++ {
if ac.trie[node][i].nextNode != 0 { if ac.trie[node][i].nextNode != 0 {
@ -219,13 +219,13 @@ func (ac *ACAutomaton) Build() {
} }
func (ac *ACAutomaton) Match(s string) bool { func (ac *ACAutomaton) Match(s string) bool {
var node = 0 node := 0
var fullMatch = true fullMatch := true
// 1. the match string is all through trie edge. FULL MATCH or DOMAIN // 1. the match string is all through trie edge. FULL MATCH or DOMAIN
// 2. the match string is through a fail edge. NOT FULL MATCH // 2. the match string is through a fail edge. NOT FULL MATCH
// 2.1 Through a fail edge, but there exists a valid node. SUBSTR // 2.1 Through a fail edge, but there exists a valid node. SUBSTR
for i := len(s) - 1; i >= 0; i-- { for i := len(s) - 1; i >= 0; i-- {
var idx = char2Index[s[i]] idx := char2Index[s[i]]
fullMatch = fullMatch && ac.trie[node][idx].edgeType fullMatch = fullMatch && ac.trie[node][idx].edgeType
node = ac.trie[node][idx].nextNode node = ac.trie[node][idx].nextNode
switch ac.exists[node].matchType { switch ac.exists[node].matchType {

7
common/strmatcher/mph_matcher.go

@ -102,7 +102,7 @@ func (g *MphMatcherGroup) Build() {
g.level0Mask = len(g.level0) - 1 g.level0Mask = len(g.level0) - 1
g.level1 = make([]uint32, nextPow2(keyLen)) g.level1 = make([]uint32, nextPow2(keyLen))
g.level1Mask = len(g.level1) - 1 g.level1Mask = len(g.level1) - 1
var sparseBuckets = make([][]int, len(g.level0)) sparseBuckets := make([][]int, len(g.level0))
var ruleIdx int var ruleIdx int
for rule, hash := range *g.ruleMap { for rule, hash := range *g.ruleMap {
n := int(hash) & g.level0Mask n := int(hash) & g.level0Mask
@ -122,7 +122,7 @@ func (g *MphMatcherGroup) Build() {
occ := make([]bool, len(g.level1)) occ := make([]bool, len(g.level1))
var tmpOcc []int var tmpOcc []int
for _, bucket := range buckets { for _, bucket := range buckets {
var seed = uint32(0) seed := uint32(0)
for { for {
findSeed := true findSeed := true
tmpOcc = tmpOcc[:0] tmpOcc = tmpOcc[:0]
@ -284,9 +284,11 @@ tail:
h ^= h >> 32 h ^= h >> 32
return uintptr(h) return uintptr(h)
} }
func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { func add(p unsafe.Pointer, x uintptr) unsafe.Pointer {
return unsafe.Pointer(uintptr(p) + x) return unsafe.Pointer(uintptr(p) + x)
} }
func readUnaligned32(p unsafe.Pointer) uint32 { func readUnaligned32(p unsafe.Pointer) uint32 {
q := (*[4]byte)(p) q := (*[4]byte)(p)
return uint32(q[0]) | uint32(q[1])<<8 | uint32(q[2])<<16 | uint32(q[3])<<24 return uint32(q[0]) | uint32(q[1])<<8 | uint32(q[2])<<16 | uint32(q[3])<<24
@ -295,6 +297,7 @@ func readUnaligned32(p unsafe.Pointer) uint32 {
func rotl31(x uint64) uint64 { func rotl31(x uint64) uint64 {
return (x << 31) | (x >> (64 - 31)) return (x << 31) | (x >> (64 - 31))
} }
func readUnaligned64(p unsafe.Pointer) uint64 { func readUnaligned64(p unsafe.Pointer) uint64 {
q := (*[8]byte)(p) q := (*[8]byte)(p)
return uint64(q[0]) | uint64(q[1])<<8 | uint64(q[2])<<16 | uint64(q[3])<<24 | uint64(q[4])<<32 | uint64(q[5])<<40 | uint64(q[6])<<48 | uint64(q[7])<<56 return uint64(q[0]) | uint64(q[1])<<8 | uint64(q[2])<<16 | uint64(q[3])<<24 | uint64(q[4])<<32 | uint64(q[5])<<40 | uint64(q[6])<<48 | uint64(q[7])<<56

6
common/strmatcher/strmatcher_test.go

@ -143,7 +143,7 @@ func TestACAutomaton(t *testing.T) {
}, },
} }
for _, test := range cases1 { for _, test := range cases1 {
var ac = NewACAutomaton() ac := NewACAutomaton()
ac.Add(test.pattern, test.mType) ac.Add(test.pattern, test.mType)
ac.Build() ac.Build()
if m := ac.Match(test.input); m != test.output { if m := ac.Match(test.input); m != test.output {
@ -176,7 +176,7 @@ func TestACAutomaton(t *testing.T) {
mType: Substr, mType: Substr,
}, },
} }
var ac = NewACAutomaton() ac := NewACAutomaton()
for _, test := range cases2Input { for _, test := range cases2Input {
ac.Add(test.pattern, test.mType) ac.Add(test.pattern, test.mType)
} }
@ -239,7 +239,7 @@ func TestACAutomaton(t *testing.T) {
mType: Domain, mType: Domain,
}, },
} }
var ac = NewACAutomaton() ac := NewACAutomaton()
for _, test := range cases3Input { for _, test := range cases3Input {
ac.Add(test.pattern, test.mType) ac.Add(test.pattern, test.mType)
} }

4
common/type.go

@ -8,9 +8,7 @@ import (
// ConfigCreator is a function to create an object by a config. // ConfigCreator is a function to create an object by a config.
type ConfigCreator func(ctx context.Context, config interface{}) (interface{}, error) type ConfigCreator func(ctx context.Context, config interface{}) (interface{}, error)
var ( var typeCreatorRegistry = make(map[reflect.Type]ConfigCreator)
typeCreatorRegistry = make(map[reflect.Type]ConfigCreator)
)
// RegisterConfig registers a global config creator. The config can be nil but must have a type. // RegisterConfig registers a global config creator. The config can be nil but must have a type.
func RegisterConfig(config interface{}, configCreator ConfigCreator) error { func RegisterConfig(config interface{}, configCreator ConfigCreator) error {

2
common/type_test.go

@ -16,7 +16,7 @@ type YConfig struct {
} }
func TestObjectCreation(t *testing.T) { func TestObjectCreation(t *testing.T) {
var f = func(ctx context.Context, t interface{}) (interface{}, error) { f := func(ctx context.Context, t interface{}) (interface{}, error) {
return func() int { return func() int {
return t.(*TConfig).value return t.(*TConfig).value
}, nil }, nil

4
common/uuid/uuid.go

@ -10,9 +10,7 @@ import (
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
) )
var ( var byteGroups = []int{8, 4, 4, 4, 12}
byteGroups = []int{8, 4, 4, 4, 12}
)
type UUID [16]byte type UUID [16]byte

4
core/xray.go

@ -159,7 +159,7 @@ func RequireFeatures(ctx context.Context, callback interface{}) error {
// The instance is not started at this point. // The instance is not started at this point.
// To ensure Xray instance works properly, the config must contain one Dispatcher, one InboundHandlerManager and one OutboundHandlerManager. Other features are optional. // To ensure Xray instance works properly, the config must contain one Dispatcher, one InboundHandlerManager and one OutboundHandlerManager. Other features are optional.
func New(config *Config) (*Instance, error) { func New(config *Config) (*Instance, error) {
var server = &Instance{ctx: context.Background()} server := &Instance{ctx: context.Background()}
done, err := initInstanceWithConfig(config, server) done, err := initInstanceWithConfig(config, server)
if done { if done {
@ -170,7 +170,7 @@ func New(config *Config) (*Instance, error) {
} }
func NewWithContext(ctx context.Context, config *Config) (*Instance, error) { func NewWithContext(ctx context.Context, config *Config) (*Instance, error) {
var server = &Instance{ctx: ctx} server := &Instance{ctx: ctx}
done, err := initInstanceWithConfig(config, server) done, err := initInstanceWithConfig(config, server)
if done { if done {

4
infra/conf/blackhole.go

@ -42,12 +42,10 @@ func (v *BlackholeConfig) Build() (proto.Message, error) {
return config, nil return config, nil
} }
var ( var configLoader = NewJSONConfigLoader(
configLoader = NewJSONConfigLoader(
ConfigCreatorCache{ ConfigCreatorCache{
"none": func() interface{} { return new(NoneResponse) }, "none": func() interface{} { return new(NoneResponse) },
"http": func() interface{} { return new(HTTPResponse) }, "http": func() interface{} { return new(HTTPResponse) },
}, },
"type", "type",
"") "")
)

3
infra/conf/dns_test.go

@ -27,7 +27,7 @@ func init() {
geositeFilePath := filepath.Join(wd, "geosite.dat") geositeFilePath := filepath.Join(wd, "geosite.dat")
os.Setenv("xray.location.asset", wd) os.Setenv("xray.location.asset", wd)
geositeFile, err := os.OpenFile(geositeFilePath, os.O_CREATE|os.O_WRONLY, 0600) geositeFile, err := os.OpenFile(geositeFilePath, os.O_CREATE|os.O_WRONLY, 0o600)
common.Must(err) common.Must(err)
defer geositeFile.Close() defer geositeFile.Close()
@ -46,6 +46,7 @@ func init() {
common.Must(err) common.Must(err)
common.Must2(geositeFile.Write(listBytes)) common.Must2(geositeFile.Write(listBytes))
} }
func TestDNSConfigParsing(t *testing.T) { func TestDNSConfigParsing(t *testing.T) {
geositePath := platform.GetAssetLocation("geosite.dat") geositePath := platform.GetAssetLocation("geosite.dat")
defer func() { defer func() {

1
infra/conf/http.go

@ -51,6 +51,7 @@ type HTTPRemoteConfig struct {
Port uint16 `json:"port"` Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"` Users []json.RawMessage `json:"users"`
} }
type HTTPClientConfig struct { type HTTPClientConfig struct {
Servers []*HTTPRemoteConfig `json:"servers"` Servers []*HTTPRemoteConfig `json:"servers"`
} }

3
infra/conf/json/reader_test.go

@ -24,7 +24,8 @@ content 2`,
` `
content content
content 2`}, content 2`,
},
{`content`, `content`}, {`content`, `content`},
{" ", " "}, {" ", " "},
{`con/*abcd*/tent`, "content"}, {`con/*abcd*/tent`, "content"},

3
infra/conf/mtproto.go

@ -60,8 +60,7 @@ func (c *MTProtoServerConfig) Build() (proto.Message, error) {
return config, nil return config, nil
} }
type MTProtoClientConfig struct { type MTProtoClientConfig struct{}
}
func (c *MTProtoClientConfig) Build() (proto.Message, error) { func (c *MTProtoClientConfig) Build() (proto.Message, error) {
config := new(mtproto.ClientConfig) config := new(mtproto.ClientConfig)

4
infra/conf/router.go

@ -338,7 +338,7 @@ func parseDomainRule(domain string) ([]*router.Domain, error) {
} }
return domains, nil return domains, nil
} }
var isExtDatFile = 0 isExtDatFile := 0
{ {
const prefix = "ext:" const prefix = "ext:"
if strings.HasPrefix(domain, prefix) { if strings.HasPrefix(domain, prefix) {
@ -417,7 +417,7 @@ func toCidrList(ips StringList) ([]*router.GeoIP, error) {
}) })
continue continue
} }
var isExtDatFile = 0 isExtDatFile := 0
{ {
const prefix = "ext:" const prefix = "ext:"
if strings.HasPrefix(ip, prefix) { if strings.HasPrefix(ip, prefix) {

5
infra/conf/serial/builder.go

@ -9,7 +9,6 @@ import (
) )
func BuildConfig(files []string, formats []string) (*core.Config, error) { func BuildConfig(files []string, formats []string) (*core.Config, error) {
cf := &conf.Config{} cf := &conf.Config{}
for i, file := range files { for i, file := range files {
newError("Reading config: ", file).AtInfo().WriteToLog() newError("Reading config: ", file).AtInfo().WriteToLog()
@ -32,9 +31,7 @@ func BuildConfig(files []string, formats []string) (*core.Config, error) {
type readerDecoder func(io.Reader) (*conf.Config, error) type readerDecoder func(io.Reader) (*conf.Config, error)
var ( var ReaderDecoderByFormat = make(map[string]readerDecoder)
ReaderDecoderByFormat = make(map[string]readerDecoder)
)
func init() { func init() {
ReaderDecoderByFormat["json"] = DecodeJSONConfig ReaderDecoderByFormat["json"] = DecodeJSONConfig

1
infra/conf/socks.go

@ -70,6 +70,7 @@ type SocksRemoteConfig struct {
Port uint16 `json:"port"` Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"` Users []json.RawMessage `json:"users"`
} }
type SocksClientConfig struct { type SocksClientConfig struct {
Servers []*SocksRemoteConfig `json:"servers"` Servers []*SocksRemoteConfig `json:"servers"`
} }

2
infra/conf/transport_internet.go

@ -540,7 +540,7 @@ func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
tproxy = internet.SocketConfig_Off tproxy = internet.SocketConfig_Off
} }
var dStrategy = internet.DomainStrategy_AS_IS dStrategy := internet.DomainStrategy_AS_IS
switch strings.ToLower(c.DomainStrategy) { switch strings.ToLower(c.DomainStrategy) {
case "useip", "use_ip": case "useip", "use_ip":
dStrategy = internet.DomainStrategy_USE_IP dStrategy = internet.DomainStrategy_USE_IP

1
infra/conf/vmess.go

@ -127,6 +127,7 @@ type VMessOutboundTarget struct {
Port uint16 `json:"port"` Port uint16 `json:"port"`
Users []json.RawMessage `json:"users"` Users []json.RawMessage `json:"users"`
} }
type VMessOutboundConfig struct { type VMessOutboundConfig struct {
Receivers []*VMessOutboundTarget `json:"vnext"` Receivers []*VMessOutboundTarget `json:"vnext"`
} }

45
infra/conf/xray_test.go

@ -380,7 +380,8 @@ func TestConfig_Override(t *testing.T) {
fn string fn string
want *Config want *Config
}{ }{
{"combine/empty", {
"combine/empty",
&Config{}, &Config{},
&Config{ &Config{
LogConfig: &LogConfig{}, LogConfig: &LogConfig{},
@ -404,40 +405,54 @@ func TestConfig_Override(t *testing.T) {
Reverse: &ReverseConfig{}, Reverse: &ReverseConfig{},
}, },
}, },
{"combine/newattr", {
"combine/newattr",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "old"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "old"}}},
&Config{LogConfig: &LogConfig{}}, "", &Config{LogConfig: &LogConfig{}}, "",
&Config{LogConfig: &LogConfig{}, InboundConfigs: []InboundDetourConfig{{Tag: "old"}}}}, &Config{LogConfig: &LogConfig{}, InboundConfigs: []InboundDetourConfig{{Tag: "old"}}},
{"replace/inbounds", },
{
"replace/inbounds",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"", "",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}},
{"replace/inbounds-replaceall", },
{
"replace/inbounds-replaceall",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
"", "",
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
{"replace/notag-append", },
{
"replace/notag-append",
&Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}}}, &Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}}},
&Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"", "",
&Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}, {Tag: "pos1", Protocol: "kcp"}}}}, &Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}, {Tag: "pos1", Protocol: "kcp"}}},
{"replace/outbounds", },
{
"replace/outbounds",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}},
"", "",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}},
{"replace/outbounds-prepend", },
{
"replace/outbounds-prepend",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
"config.json", "config.json",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}},
{"replace/outbounds-append", },
{
"replace/outbounds-append",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}},
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos2", Protocol: "kcp"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos2", Protocol: "kcp"}}},
"config_tail.json", "config_tail.json",
&Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}, {Tag: "pos2", Protocol: "kcp"}}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}, {Tag: "pos2", Protocol: "kcp"}}},
},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {

4
main/commands/all/tls/ping.go

@ -27,9 +27,7 @@ func init() {
cmdPing.Run = executePing // break init loop cmdPing.Run = executePing // break init loop
} }
var ( var pingIPStr = cmdPing.Flag.String("ip", "", "")
pingIPStr = cmdPing.Flag.String("ip", "", "")
)
func executePing(cmd *base.Command, args []string) { func executePing(cmd *base.Command, args []string) {
if cmdPing.Flag.NArg() < 1 { if cmdPing.Flag.NArg() < 1 {

6
main/commands/base/command.go

@ -113,8 +113,10 @@ func ExitIfErrors() {
} }
} }
var exitStatus = 0 var (
var exitMu sync.Mutex exitStatus = 0
exitMu sync.Mutex
)
// SetExitStatus set exit status code // SetExitStatus set exit status code
func SetExitStatus(n int) { func SetExitStatus(n int) {

6
main/confloader/confloader.go

@ -5,8 +5,10 @@ import (
"os" "os"
) )
type configFileLoader func(string) (io.Reader, error) type (
type extconfigLoader func([]string, io.Reader) (io.Reader, error) configFileLoader func(string) (io.Reader, error)
extconfigLoader func([]string, io.Reader) (io.Reader, error)
)
var ( var (
EffectiveConfigFileLoader configFileLoader EffectiveConfigFileLoader configFileLoader

2
main/run.go

@ -52,7 +52,6 @@ var (
* main func in this file is run. * main func in this file is run.
*/ */
_ = func() bool { _ = func() bool {
cmdRun.Flag.Var(&configFiles, "config", "Config path for Xray.") cmdRun.Flag.Var(&configFiles, "config", "Config path for Xray.")
cmdRun.Flag.Var(&configFiles, "c", "Short alias of -config") cmdRun.Flag.Var(&configFiles, "c", "Short alias of -config")
cmdRun.Flag.StringVar(&configDir, "confdir", "", "A dir with multiple json config") cmdRun.Flag.StringVar(&configDir, "confdir", "", "A dir with multiple json config")
@ -184,7 +183,6 @@ func startXray() (core.Server, error) {
// config, err := core.LoadConfig(getConfigFormat(), configFiles[0], configFiles) // config, err := core.LoadConfig(getConfigFormat(), configFiles[0], configFiles)
c, err := core.LoadConfig(getConfigFormat(), configFiles) c, err := core.LoadConfig(getConfigFormat(), configFiles)
if err != nil { if err != nil {
return nil, newError("failed to load config files: [", configFiles.String(), "]").Base(err) return nil, newError("failed to load config files: [", configFiles.String(), "]").Base(err)
} }

3
proxy/dns/dns_test.go

@ -24,8 +24,7 @@ import (
"github.com/xtls/xray-core/testing/servers/udp" "github.com/xtls/xray-core/testing/servers/udp"
) )
type staticHandler struct { type staticHandler struct{}
}
func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
ans := new(dns.Msg) ans := new(dns.Msg)

2
proxy/http/client.go

@ -133,7 +133,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)) return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer))
} }
var responseDonePost = task.OnSuccess(responseFunc, task.Close(link.Writer)) responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

2
proxy/http/server.go

@ -206,7 +206,7 @@ func (s *Server) handleConnect(ctx context.Context, _ *http.Request, reader *buf
return nil return nil
} }
var closeWriter = task.OnSuccess(requestDone, task.Close(link.Writer)) closeWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, closeWriter, responseDone); err != nil { if err := task.Run(ctx, closeWriter, responseDone); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)

4
proxy/mtproto/auth.go

@ -133,13 +133,11 @@ func Inverse(b []byte) []byte {
return b2 return b2
} }
var ( var authPool = sync.Pool{
authPool = sync.Pool{
New: func() interface{} { New: func() interface{} {
return new(Authentication) return new(Authentication)
}, },
} }
)
func getAuthenticationObject() *Authentication { func getAuthenticationObject() *Authentication {
return authPool.Get().(*Authentication) return authPool.Get().(*Authentication)

5
proxy/mtproto/client.go

@ -13,8 +13,7 @@ import (
"github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet"
) )
type Client struct { type Client struct{}
}
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
return &Client{}, nil return &Client{}, nil
@ -62,7 +61,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return buf.Copy(connReader, link.Writer) return buf.Copy(connReader, link.Writer)
} }
var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(response, task.Close(link.Writer))
if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

12
proxy/mtproto/server.go

@ -20,15 +20,13 @@ import (
"github.com/xtls/xray-core/features/routing" "github.com/xtls/xray-core/features/routing"
) )
var ( var dcList = []net.Address{
dcList = []net.Address{
net.ParseAddress("149.154.175.50"), net.ParseAddress("149.154.175.50"),
net.ParseAddress("149.154.167.51"), net.ParseAddress("149.154.167.51"),
net.ParseAddress("149.154.175.100"), net.ParseAddress("149.154.175.100"),
net.ParseAddress("149.154.167.91"), net.ParseAddress("149.154.167.91"),
net.ParseAddress("149.154.171.5"), net.ParseAddress("149.154.171.5"),
} }
)
type Server struct { type Server struct {
user *protocol.User user *protocol.User
@ -64,8 +62,10 @@ func (s *Server) Network() []net.Network {
return []net.Network{net.Network_TCP} return []net.Network{net.Network_TCP}
} }
var ctype1 = []byte{0xef, 0xef, 0xef, 0xef} var (
var ctype2 = []byte{0xee, 0xee, 0xee, 0xee} ctype1 = []byte{0xef, 0xef, 0xef, 0xef}
ctype2 = []byte{0xee, 0xee, 0xee, 0xee}
)
func isValidConnectionType(c [4]byte) bool { func isValidConnectionType(c [4]byte) bool {
if bytes.Equal(c[:], ctype1) { if bytes.Equal(c[:], ctype1) {
@ -144,7 +144,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con
return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)) return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
} }
var responseDoneAndCloseWriter = task.OnSuccess(response, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(response, task.Close(link.Writer))
if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, request, responseDoneAndCloseWriter); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)

4
proxy/shadowsocks/client.go

@ -132,7 +132,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer)) return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
} }
var responseDoneAndCloseWriter = task.OnSuccess(responseDone, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }
@ -170,7 +170,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return nil return nil
} }
var responseDoneAndCloseWriter = task.OnSuccess(responseDone, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

1
proxy/shadowsocks/protocol.go

@ -54,7 +54,6 @@ func (r *FullReader) Read(p []byte) (n int, err error) {
// ReadTCPSession reads a Shadowsocks TCP session from the given reader, returns its header and remaining parts. // ReadTCPSession reads a Shadowsocks TCP session from the given reader, returns its header and remaining parts.
func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) { func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) {
hashkdf := hmac.New(sha256.New, []byte("SSBSKDF")) hashkdf := hmac.New(sha256.New, []byte("SSBSKDF"))
behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil)) behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil))

2
proxy/shadowsocks/server.go

@ -271,7 +271,7 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis
return nil return nil
} }
var requestDoneAndCloseWriter = task.OnSuccess(requestDone, task.Close(link.Writer)) requestDoneAndCloseWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil { if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)

2
proxy/socks/client.go

@ -150,7 +150,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
} }
} }
var responseDonePost = task.OnSuccess(responseFunc, task.Close(link.Writer)) responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer))
if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { if err := task.Run(ctx, requestFunc, responseDonePost); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

3
proxy/socks/server.go

@ -182,7 +182,7 @@ func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writ
return nil return nil
} }
var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer)) requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil { if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)
@ -237,7 +237,6 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis
for _, payload := range mpayload { for _, payload := range mpayload {
request, err := DecodeUDPPacket(payload) request, err := DecodeUDPPacket(payload)
if err != nil { if err != nil {
newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx)) newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx))
payload.Release() payload.Release()

2
proxy/trojan/client.go

@ -204,7 +204,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter
return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)) return buf.Copy(reader, link.Writer, buf.UpdateActivity(timer))
} }
var responseDoneAndCloseWriter = task.OnSuccess(getResponse, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil { if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

2
proxy/trojan/server.go

@ -382,7 +382,7 @@ func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Sess
return nil return nil
} }
var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer)) requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil { if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Must(common.Interrupt(link.Reader)) common.Must(common.Interrupt(link.Reader))
common.Must(common.Interrupt(link.Writer)) common.Must(common.Interrupt(link.Writer))

4
proxy/vless/inbound/inbound.go

@ -35,9 +35,7 @@ import (
"github.com/xtls/xray-core/transport/internet/xtls" "github.com/xtls/xray-core/transport/internet/xtls"
) )
var ( var xtls_show = false
xtls_show = false
)
func init() { func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {

4
proxy/vless/outbound/outbound.go

@ -29,9 +29,7 @@ import (
"github.com/xtls/xray-core/transport/internet/xtls" "github.com/xtls/xray-core/transport/internet/xtls"
) )
var ( var xtls_show = false
xtls_show = false
)
func init() { func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {

6
proxy/vmess/aead/encrypt.go

@ -40,7 +40,6 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte {
} }
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderLengthAEADAESBlock) payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderLengthAEADAESBlock)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }
@ -61,7 +60,6 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte {
} }
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }
@ -69,7 +67,7 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte {
payloadHeaderAEADEncrypted = payloadHeaderAEAD.Seal(nil, payloadHeaderAEADNonce, data, generatedAuthID[:]) payloadHeaderAEADEncrypted = payloadHeaderAEAD.Seal(nil, payloadHeaderAEADNonce, data, generatedAuthID[:])
} }
var outputBuffer = bytes.NewBuffer(nil) outputBuffer := bytes.NewBuffer(nil)
common.Must2(outputBuffer.Write(generatedAuthID[:])) // 16 common.Must2(outputBuffer.Write(generatedAuthID[:])) // 16
common.Must2(outputBuffer.Write(payloadHeaderLengthAEADEncrypted)) // 2+16 common.Must2(outputBuffer.Write(payloadHeaderLengthAEADEncrypted)) // 2+16
@ -112,7 +110,6 @@ func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte,
} }
payloadHeaderLengthAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) payloadHeaderLengthAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }
@ -154,7 +151,6 @@ func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte,
} }
payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock)
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
} }

8
proxy/vmess/aead/encrypt_test.go

@ -16,7 +16,7 @@ func TestOpenVMessAEADHeader(t *testing.T) {
copy(keyw[:], key) copy(keyw[:], key)
sealed := SealVMessAEADHeader(keyw, TestHeader) sealed := SealVMessAEADHeader(keyw, TestHeader)
var AEADR = bytes.NewReader(sealed) AEADR := bytes.NewReader(sealed)
var authid [16]byte var authid [16]byte
@ -35,7 +35,7 @@ func TestOpenVMessAEADHeader2(t *testing.T) {
copy(keyw[:], key) copy(keyw[:], key)
sealed := SealVMessAEADHeader(keyw, TestHeader) sealed := SealVMessAEADHeader(keyw, TestHeader)
var AEADR = bytes.NewReader(sealed) AEADR := bytes.NewReader(sealed)
var authid [16]byte var authid [16]byte
@ -57,7 +57,7 @@ func TestOpenVMessAEADHeader4(t *testing.T) {
var sealedm [16]byte var sealedm [16]byte
copy(sealedm[:], sealed) copy(sealedm[:], sealed)
sealed[i] ^= 0xff sealed[i] ^= 0xff
var AEADR = bytes.NewReader(sealed) AEADR := bytes.NewReader(sealed)
var authid [16]byte var authid [16]byte
@ -85,7 +85,7 @@ func TestOpenVMessAEADHeader4Massive(t *testing.T) {
var sealedm [16]byte var sealedm [16]byte
copy(sealedm[:], sealed) copy(sealedm[:], sealed)
sealed[i] ^= 0xff sealed[i] ^= 0xff
var AEADR = bytes.NewReader(sealed) AEADR := bytes.NewReader(sealed)
var authid [16]byte var authid [16]byte

3
proxy/vmess/encoding/auth.go

@ -38,8 +38,7 @@ func (NoOpAuthenticator) Open(dst, nonce, ciphertext, additionalData []byte) ([]
} }
// FnvAuthenticator is an AEAD based on Fnv hash. // FnvAuthenticator is an AEAD based on Fnv hash.
type FnvAuthenticator struct { type FnvAuthenticator struct{}
}
// NonceSize implements AEAD.NonceSize(). // NonceSize implements AEAD.NonceSize().
func (*FnvAuthenticator) NonceSize() int { func (*FnvAuthenticator) NonceSize() int {

3
proxy/vmess/encoding/commands.go

@ -77,8 +77,7 @@ type CommandFactory interface {
Unmarshal(data []byte) (interface{}, error) Unmarshal(data []byte) (interface{}, error)
} }
type CommandSwitchAccountFactory struct { type CommandSwitchAccountFactory struct{}
}
func (f *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error { func (f *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error {
cmd, ok := command.(*protocol.CommandSwitchAccount) cmd, ok := command.(*protocol.CommandSwitchAccount)

4
proxy/vmess/inbound/inbound.go

@ -319,7 +319,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
return transferResponse(timer, svrSession, request, response, link.Reader, writer) return transferResponse(timer, svrSession, request, response, link.Reader, writer)
} }
var requestDonePost = task.OnSuccess(requestDone, task.Close(link.Writer)) requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDonePost, responseDone); err != nil { if err := task.Run(ctx, requestDonePost, responseDone); err != nil {
common.Interrupt(link.Reader) common.Interrupt(link.Reader)
common.Interrupt(link.Writer) common.Interrupt(link.Writer)
@ -370,7 +370,7 @@ func init() {
return New(ctx, config.(*Config)) return New(ctx, config.(*Config))
})) }))
var defaultFlagValue = "NOT_DEFINED_AT_ALL" defaultFlagValue := "NOT_DEFINED_AT_ALL"
if time.Now().Year() >= 2022 { if time.Now().Year() >= 2022 {
defaultFlagValue = "true_by_default_2022" defaultFlagValue = "true_by_default_2022"

2
proxy/vmess/outbound/outbound.go

@ -191,7 +191,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
return buf.Copy(bodyReader, output, buf.UpdateActivity(timer)) return buf.Copy(bodyReader, output, buf.UpdateActivity(timer))
} }
var responseDonePost = task.OnSuccess(responseDone, task.Close(output)) responseDonePost := task.OnSuccess(responseDone, task.Close(output))
if err := task.Run(ctx, requestDone, responseDonePost); err != nil { if err := task.Run(ctx, requestDone, responseDonePost); err != nil {
return newError("connection ends").Base(err) return newError("connection ends").Base(err)
} }

5
testing/mocks/dns.go

@ -5,10 +5,11 @@
package mocks package mocks
import ( import (
gomock "github.com/golang/mock/gomock"
dns "github.com/xtls/xray-core/features/dns"
net "net" net "net"
reflect "reflect" reflect "reflect"
gomock "github.com/golang/mock/gomock"
dns "github.com/xtls/xray-core/features/dns"
) )
// DNSClient is a mock of Client interface // DNSClient is a mock of Client interface

3
testing/mocks/io.go

@ -5,8 +5,9 @@
package mocks package mocks
import ( import (
gomock "github.com/golang/mock/gomock"
reflect "reflect" reflect "reflect"
gomock "github.com/golang/mock/gomock"
) )
// Reader is a mock of Reader interface // Reader is a mock of Reader interface

3
testing/mocks/log.go

@ -5,9 +5,10 @@
package mocks package mocks
import ( import (
reflect "reflect"
gomock "github.com/golang/mock/gomock" gomock "github.com/golang/mock/gomock"
log "github.com/xtls/xray-core/common/log" log "github.com/xtls/xray-core/common/log"
reflect "reflect"
) )
// LogHandler is a mock of Handler interface // LogHandler is a mock of Handler interface

3
testing/mocks/mux.go

@ -5,9 +5,10 @@
package mocks package mocks
import ( import (
reflect "reflect"
gomock "github.com/golang/mock/gomock" gomock "github.com/golang/mock/gomock"
mux "github.com/xtls/xray-core/common/mux" mux "github.com/xtls/xray-core/common/mux"
reflect "reflect"
) )
// MuxClientWorkerFactory is a mock of ClientWorkerFactory interface // MuxClientWorkerFactory is a mock of ClientWorkerFactory interface

3
testing/mocks/outbound.go

@ -6,9 +6,10 @@ package mocks
import ( import (
context "context" context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock" gomock "github.com/golang/mock/gomock"
outbound "github.com/xtls/xray-core/features/outbound" outbound "github.com/xtls/xray-core/features/outbound"
reflect "reflect"
) )
// OutboundManager is a mock of Manager interface // OutboundManager is a mock of Manager interface

4
testing/scenarios/vmess_test.go

@ -113,7 +113,7 @@ func TestVMessDynamicPort(t *testing.T) {
break break
} }
retry += 1 retry += 1
if (retry > 5) { if retry > 5 {
t.Fatal("All attempts failed to start server") t.Fatal("All attempts failed to start server")
} }
serverPort = tcp.PickPort() serverPort = tcp.PickPort()
@ -174,7 +174,7 @@ func TestVMessDynamicPort(t *testing.T) {
func tcpConnAvailableAtPort(t *testing.T, port net.Port) bool { func tcpConnAvailableAtPort(t *testing.T, port net.Port) bool {
for i := 1; ; i++ { for i := 1; ; i++ {
if (i > 10) { if i > 10 {
t.Log("All attempts failed to test tcp conn") t.Log("All attempts failed to test tcp conn")
return false return false
} }

1
testing/servers/tcp/tcp.go

@ -97,7 +97,6 @@ func (server *Server) handleConnection(conn net.Conn) {
} }
} }
}) })
if err != nil { if err != nil {
fmt.Println("failed to transfer data: ", err.Error()) fmt.Println("failed to transfer data: ", err.Error())
} }

6
transport/internet/dialer.go

@ -28,9 +28,7 @@ type Dialer interface {
// dialFunc is an interface to dial network connection to a specific destination. // dialFunc is an interface to dial network connection to a specific destination.
type dialFunc func(ctx context.Context, dest net.Destination, streamSettings *MemoryStreamConfig) (stat.Connection, error) type dialFunc func(ctx context.Context, dest net.Destination, streamSettings *MemoryStreamConfig) (stat.Connection, error)
var ( var transportDialerCache = make(map[string]dialFunc)
transportDialerCache = make(map[string]dialFunc)
)
// RegisterTransportDialer registers a Dialer with given name. // RegisterTransportDialer registers a Dialer with given name.
func RegisterTransportDialer(protocol string, dialer dialFunc) error { func RegisterTransportDialer(protocol string, dialer dialFunc) error {
@ -81,7 +79,7 @@ func lookupIP(domain string, strategy DomainStrategy, localAddr net.Address) ([]
return nil, nil return nil, nil
} }
var option = dns.IPOption{ option := dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,

6
transport/internet/domainsocket/config.go

@ -6,8 +6,10 @@ import (
"github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet"
) )
const protocolName = "domainsocket" const (
const sizeofSunPath = 108 protocolName = "domainsocket"
sizeofSunPath = 108
)
func (c *Config) GetUnixAddr() (*net.UnixAddr, error) { func (c *Config) GetUnixAddr() (*net.UnixAddr, error) {
path := c.Path path := c.Path

3
transport/internet/grpc/dial.go

@ -49,7 +49,6 @@ func dialgRPC(ctx context.Context, dest net.Destination, streamSettings *interne
grpcSettings := streamSettings.ProtocolSettings.(*Config) grpcSettings := streamSettings.ProtocolSettings.(*Config)
conn, err := getGrpcClient(ctx, dest, streamSettings) conn, err := getGrpcClient(ctx, dest, streamSettings)
if err != nil { if err != nil {
return nil, newError("Cannot dial gRPC").Base(err) return nil, newError("Cannot dial gRPC").Base(err)
} }
@ -86,7 +85,7 @@ func getGrpcClient(ctx context.Context, dest net.Destination, streamSettings *in
return client, nil return client, nil
} }
var dialOptions = []grpc.DialOption{ dialOptions := []grpc.DialOption{
grpc.WithConnectParams(grpc.ConnectParams{ grpc.WithConnectParams(grpc.ConnectParams{
Backoff: backoff.Config{ Backoff: backoff.Config{
BaseDelay: 500 * time.Millisecond, BaseDelay: 500 * time.Millisecond,

2
transport/internet/grpc/encoding/multiconn.go

@ -92,7 +92,7 @@ func (h *MultiHunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) {
return nil, err return nil, err
} }
var mb = make(buf.MultiBuffer, 0, len(h.buf)) mb := make(buf.MultiBuffer, 0, len(h.buf))
for _, b := range h.buf { for _, b := range h.buf {
if len(b) == 0 { if len(b) == 0 {
continue continue

4
transport/internet/kcp/dialer.go

@ -16,9 +16,7 @@ import (
"github.com/xtls/xray-core/transport/internet/xtls" "github.com/xtls/xray-core/transport/internet/xtls"
) )
var ( var globalConv = uint32(dice.RollUint16())
globalConv = uint32(dice.RollUint16())
)
func fetchInput(_ context.Context, input io.Reader, reader PacketReader, conn *Connection) { func fetchInput(_ context.Context, input io.Reader, reader PacketReader, conn *Connection) {
cache := make(chan *buf.Buffer, 1024) cache := make(chan *buf.Buffer, 1024)

1
transport/internet/quic/hub.go

@ -97,7 +97,6 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti
IP: address.IP(), IP: address.IP(),
Port: int(port), Port: int(port),
}, streamSettings.SocketSettings) }, streamSettings.SocketSettings)
if err != nil { if err != nil {
return nil, err return nil, err
} }

6
transport/internet/quic/quic.go

@ -13,8 +13,10 @@ import (
// //
// //
const protocolName = "quic" const (
const internalDomain = "quic.internal.example.com" protocolName = "quic"
internalDomain = "quic.internal.example.com"
)
func init() { func init() {
common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} { common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {

1
transport/internet/sockopt_freebsd.go

@ -45,6 +45,7 @@ func ioctl(s uintptr, ioc int, b []byte) error {
} }
return nil return nil
} }
func (nl *pfiocNatlook) rdPort() int { func (nl *pfiocNatlook) rdPort() int {
return int(binary.BigEndian.Uint16((*[2]byte)(unsafe.Pointer(&nl.Rdport))[:])) return int(binary.BigEndian.Uint16((*[2]byte)(unsafe.Pointer(&nl.Rdport))[:]))
} }

1
transport/internet/sockopt_windows.go

@ -25,7 +25,6 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
if err := setTFO(syscall.Handle(fd), config.ParseTFOValue()); err != nil { if err := setTFO(syscall.Handle(fd), config.ParseTFOValue()); err != nil {
return err return err
} }
} }
return nil return nil

4
transport/internet/system_dialer.go

@ -11,9 +11,7 @@ import (
"github.com/xtls/xray-core/features/outbound" "github.com/xtls/xray-core/features/outbound"
) )
var ( var effectiveSystemDialer SystemDialer = &DefaultSystemDialer{}
effectiveSystemDialer SystemDialer = &DefaultSystemDialer{}
)
type SystemDialer interface { type SystemDialer interface {
Dial(ctx context.Context, source net.Address, destination net.Destination, sockopt *SocketConfig) (net.Conn, error) Dial(ctx context.Context, source net.Address, destination net.Destination, sockopt *SocketConfig) (net.Conn, error)

4
transport/internet/system_listener.go

@ -11,9 +11,7 @@ import (
"github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/session"
) )
var ( var effectiveListener = DefaultListener{}
effectiveListener = DefaultListener{}
)
type controller func(network, address string, fd uintptr) error type controller func(network, address string, fd uintptr) error

5
transport/internet/tcp_hub.go

@ -8,9 +8,7 @@ import (
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
) )
var ( var transportListenerCache = make(map[string]ListenFunc)
transportListenerCache = make(map[string]ListenFunc)
)
func RegisterTransportListener(protocol string, listener ListenFunc) error { func RegisterTransportListener(protocol string, listener ListenFunc) error {
if _, found := transportListenerCache[protocol]; found { if _, found := transportListenerCache[protocol]; found {
@ -50,6 +48,7 @@ func ListenUnix(ctx context.Context, address net.Address, settings *MemoryStream
} }
return listener, nil return listener, nil
} }
func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error) { func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error) {
if settings == nil { if settings == nil {
s, err := ToMemoryStreamConfig(nil) s, err := ToMemoryStreamConfig(nil)

4
transport/internet/tls/config.go

@ -14,9 +14,7 @@ import (
"github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet"
) )
var ( var globalSessionCache = tls.NewLRUClientSessionCache(128)
globalSessionCache = tls.NewLRUClientSessionCache(128)
)
// ParseCertificate converts a cert.Certificate to Certificate. // ParseCertificate converts a cert.Certificate to Certificate.
func ParseCertificate(c *cert.Certificate) *Certificate { func ParseCertificate(c *cert.Certificate) *Certificate {

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save