From e286cdcaa820f8e892f27d3586dfadea9e57d437 Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Tue, 19 Oct 2021 12:57:14 -0400 Subject: [PATCH] Style: format code by gofumpt (#761) --- app/dispatcher/default.go | 4 +- app/dns/dns_test.go | 3 +- app/dns/dnscommon.go | 4 +- app/dns/dnscommon_test.go | 20 +++-- app/dns/fakedns/fake.go | 4 +- app/dns/fakedns/fakedns_test.go | 4 +- app/dns/nameserver_local.go | 3 +- app/dns/nameserver_local_test.go | 3 +- app/dns/nameserver_quic_test.go | 3 +- app/log/log_creator.go | 4 +- app/proxyman/inbound/worker.go | 1 + app/router/balancing.go | 3 +- app/router/condition_geoip.go | 4 +- app/router/condition_geoip_test.go | 3 +- app/router/config.go | 1 - app/router/router.go | 1 - app/router/router_test.go | 3 +- common/buf/buffer_test.go | 1 + common/buf/io.go | 2 +- common/common.go | 6 +- common/crypto/auth.go | 1 - common/crypto/chacha20_test.go | 2 +- .../crypto/internal/chacha_core.generated.go | 2 +- common/crypto/internal/chacha_core_gen.go | 2 +- common/crypto/io.go | 4 +- common/errors/errorgen/main.go | 2 +- common/log/log.go | 4 +- common/log/logger.go | 4 +- common/mux/client.go | 7 +- common/net/system.go | 82 ++++++++++++------- common/ocsp/ocsp.go | 3 - common/platform/filesystem/file.go | 2 +- common/protocol/bittorrent/bittorrent.go | 3 +- common/protocol/tls/cert/cert_test.go | 2 + common/protocol/tls/sniff.go | 6 +- common/retry/retry.go | 4 +- common/retry/retry_test.go | 4 +- common/strmatcher/ac_automaton_matcher.go | 20 ++--- common/strmatcher/mph_matcher.go | 7 +- common/strmatcher/strmatcher_test.go | 6 +- common/type.go | 4 +- common/type_test.go | 2 +- common/uuid/uuid.go | 4 +- core/xray.go | 4 +- infra/conf/blackhole.go | 16 ++-- infra/conf/dns_test.go | 3 +- infra/conf/http.go | 1 + infra/conf/json/reader_test.go | 3 +- infra/conf/mtproto.go | 3 +- infra/conf/router.go | 4 +- infra/conf/serial/builder.go | 5 +- infra/conf/socks.go | 1 + infra/conf/transport_internet.go | 2 +- infra/conf/vmess.go | 1 + infra/conf/xray_test.go | 45 ++++++---- main/commands/all/commands.go | 2 +- main/commands/all/tls/ping.go | 4 +- main/commands/base/command.go | 6 +- main/confloader/confloader.go | 6 +- main/main.go | 18 ++-- main/run.go | 6 +- proxy/dns/dns_test.go | 3 +- proxy/http/client.go | 2 +- proxy/http/server.go | 2 +- proxy/mtproto/auth.go | 12 ++- proxy/mtproto/client.go | 5 +- proxy/mtproto/server.go | 24 +++--- proxy/shadowsocks/client.go | 4 +- proxy/shadowsocks/protocol.go | 1 - proxy/shadowsocks/server.go | 2 +- proxy/socks/client.go | 2 +- proxy/socks/server.go | 3 +- proxy/trojan/client.go | 2 +- proxy/trojan/protocol.go | 2 +- proxy/trojan/server.go | 2 +- proxy/vless/encoding/encoding.go | 2 +- proxy/vless/inbound/inbound.go | 4 +- proxy/vless/outbound/outbound.go | 4 +- proxy/vmess/aead/encrypt.go | 6 +- proxy/vmess/aead/encrypt_test.go | 8 +- proxy/vmess/encoding/auth.go | 3 +- proxy/vmess/encoding/commands.go | 3 +- proxy/vmess/inbound/inbound.go | 4 +- proxy/vmess/outbound/outbound.go | 2 +- testing/mocks/dns.go | 5 +- testing/mocks/io.go | 3 +- testing/mocks/log.go | 3 +- testing/mocks/mux.go | 3 +- testing/mocks/outbound.go | 3 +- testing/scenarios/vmess_test.go | 6 +- testing/servers/tcp/tcp.go | 1 - transport/internet/dialer.go | 6 +- transport/internet/domainsocket/config.go | 6 +- transport/internet/grpc/dial.go | 3 +- transport/internet/grpc/encoding/multiconn.go | 2 +- transport/internet/kcp/dialer.go | 4 +- transport/internet/quic/hub.go | 1 - transport/internet/quic/quic.go | 6 +- transport/internet/sockopt_freebsd.go | 1 + transport/internet/sockopt_windows.go | 1 - transport/internet/system_dialer.go | 4 +- transport/internet/system_listener.go | 4 +- transport/internet/tcp/hub.go | 2 +- transport/internet/tcp_hub.go | 5 +- transport/internet/tls/config.go | 4 +- transport/internet/tls/tls.go | 4 +- transport/internet/websocket/connection.go | 4 +- transport/internet/websocket/dialer.go | 1 + transport/internet/websocket/hub.go | 6 +- transport/internet/xtls/config.go | 4 +- transport/pipe/impl.go | 6 +- 111 files changed, 293 insertions(+), 291 deletions(-) diff --git a/app/dispatcher/default.go b/app/dispatcher/default.go index 2d513eb6..026c5f27 100644 --- a/app/dispatcher/default.go +++ b/app/dispatcher/default.go @@ -25,9 +25,7 @@ import ( "github.com/xtls/xray-core/transport/pipe" ) -var ( - errSniffingTimeout = newError("timeout on sniffing") -) +var errSniffingTimeout = newError("timeout on sniffing") type cachedReader struct { sync.Mutex diff --git a/app/dns/dns_test.go b/app/dns/dns_test.go index 8468e653..b3a8def8 100644 --- a/app/dns/dns_test.go +++ b/app/dns/dns_test.go @@ -21,8 +21,7 @@ import ( "github.com/xtls/xray-core/testing/servers/udp" ) -type staticHandler struct { -} +type staticHandler struct{} func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { ans := new(dns.Msg) diff --git a/app/dns/dnscommon.go b/app/dns/dnscommon.go index bead44b7..c48045ce 100644 --- a/app/dns/dnscommon.go +++ b/app/dns/dnscommon.go @@ -54,9 +54,7 @@ func isNewer(baseRec *IPRecord, newRec *IPRecord) bool { return baseRec.Expire.Before(newRec.Expire) } -var ( - errRecordNotFound = errors.New("record not found") -) +var errRecordNotFound = errors.New("record not found") type dnsRequest struct { reqType dnsmessage.Type diff --git a/app/dns/dnscommon_test.go b/app/dns/dnscommon_test.go index f089f306..76e89688 100644 --- a/app/dns/dnscommon_test.go +++ b/app/dns/dnscommon_test.go @@ -50,20 +50,28 @@ func Test_parseResponse(t *testing.T) { want *IPRecord wantErr bool }{ - {"empty", + { + "empty", &IPRecord{0, []net.Address(nil), time.Time{}, dnsmessage.RCodeSuccess}, false, }, - {"error", + { + "error", nil, true, }, - {"a record", - &IPRecord{1, []net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")}, - time.Time{}, dnsmessage.RCodeSuccess}, + { + "a record", + &IPRecord{ + 1, + []net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")}, + time.Time{}, + dnsmessage.RCodeSuccess, + }, false, }, - {"aaaa record", + { + "aaaa record", &IPRecord{2, []net.Address{net.ParseAddress("2001::123:8888"), net.ParseAddress("2001::123:8844")}, time.Time{}, dnsmessage.RCodeSuccess}, false, }, diff --git a/app/dns/fakedns/fake.go b/app/dns/fakedns/fake.go index 5d3965e4..1b5ec7d4 100644 --- a/app/dns/fakedns/fake.go +++ b/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 { 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() rooms := bits - ones if rooms < 64 { 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)) var ip net.Address for { diff --git a/app/dns/fakedns/fakedns_test.go b/app/dns/fakedns/fakedns_test.go index 74106171..434c4451 100644 --- a/app/dns/fakedns/fakedns_test.go +++ b/app/dns/fakedns/fakedns_test.go @@ -11,9 +11,7 @@ import ( "github.com/xtls/xray-core/features/dns" ) -var ( - ipPrefix = "198.18." -) +var ipPrefix = "198.18." func TestNewFakeDnsHolder(_ *testing.T) { _, err := NewFakeDNSHolder() diff --git a/app/dns/nameserver_local.go b/app/dns/nameserver_local.go index 87c70b82..6b0f1319 100644 --- a/app/dns/nameserver_local.go +++ b/app/dns/nameserver_local.go @@ -2,9 +2,10 @@ package dns import ( "context" - "github.com/xtls/xray-core/features/dns" "strings" + "github.com/xtls/xray-core/features/dns" + "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/features/dns/localdns" ) diff --git a/app/dns/nameserver_local_test.go b/app/dns/nameserver_local_test.go index b3d9678c..c27692e5 100644 --- a/app/dns/nameserver_local_test.go +++ b/app/dns/nameserver_local_test.go @@ -2,10 +2,11 @@ package dns_test import ( "context" - "github.com/xtls/xray-core/common/net" "testing" "time" + "github.com/xtls/xray-core/common/net" + . "github.com/xtls/xray-core/app/dns" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/features/dns" diff --git a/app/dns/nameserver_quic_test.go b/app/dns/nameserver_quic_test.go index 9ed33484..2c4710a9 100644 --- a/app/dns/nameserver_quic_test.go +++ b/app/dns/nameserver_quic_test.go @@ -2,11 +2,12 @@ package dns_test import ( "context" - "github.com/xtls/xray-core/features/dns" "net/url" "testing" "time" + "github.com/xtls/xray-core/features/dns" + "github.com/google/go-cmp/cmp" . "github.com/xtls/xray-core/app/dns" diff --git a/app/log/log_creator.go b/app/log/log_creator.go index b154168f..af4cb210 100644 --- a/app/log/log_creator.go +++ b/app/log/log_creator.go @@ -11,9 +11,7 @@ type HandlerCreatorOptions struct { type HandlerCreator func(LogType, HandlerCreatorOptions) (log.Handler, error) -var ( - handlerCreatorMap = make(map[LogType]HandlerCreator) -) +var handlerCreatorMap = make(map[LogType]HandlerCreator) func RegisterHandlerCreator(logType LogType, f HandlerCreator) error { if f == nil { diff --git a/app/proxyman/inbound/worker.go b/app/proxyman/inbound/worker.go index 806a59fe..913c69cc 100644 --- a/app/proxyman/inbound/worker.go +++ b/app/proxyman/inbound/worker.go @@ -482,6 +482,7 @@ func (w *dsWorker) Proxy() proxy.Inbound { func (w *dsWorker) Port() net.Port { return net.Port(0) } + func (w *dsWorker) Start() error { ctx := context.Background() hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn stat.Connection) { diff --git a/app/router/balancing.go b/app/router/balancing.go index 0f80230b..d4642bd9 100644 --- a/app/router/balancing.go +++ b/app/router/balancing.go @@ -9,8 +9,7 @@ type BalancingStrategy interface { PickOutbound([]string) string } -type RandomStrategy struct { -} +type RandomStrategy struct{} func (s *RandomStrategy) PickOutbound(tags []string) string { n := len(tags) diff --git a/app/router/condition_geoip.go b/app/router/condition_geoip.go index 90ad7da7..99a591e0 100644 --- a/app/router/condition_geoip.go +++ b/app/router/condition_geoip.go @@ -186,6 +186,4 @@ func (c *GeoIPMatcherContainer) Add(geoip *GeoIP) (*GeoIPMatcher, error) { return m, nil } -var ( - globalGeoIPContainer GeoIPMatcherContainer -) +var globalGeoIPContainer GeoIPMatcherContainer diff --git a/app/router/condition_geoip_test.go b/app/router/condition_geoip_test.go index 3332be3c..8579f2f4 100644 --- a/app/router/condition_geoip_test.go +++ b/app/router/condition_geoip_test.go @@ -89,7 +89,8 @@ func TestGeoIPMatcher(t *testing.T) { { Input: "192.0.1.0", Output: false, - }, { + }, + { Input: "0.1.0.0", Output: true, }, diff --git a/app/router/config.go b/app/router/config.go index f7ce0911..780ff10e 100644 --- a/app/router/config.go +++ b/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() conds.Add(matcher) } - } if len(rr.UserEmail) > 0 { diff --git a/app/router/router.go b/app/router/router.go index 8c8b32e4..2a2482a6 100644 --- a/app/router/router.go +++ b/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) { - // SkipDNSResolve is set from DNS module. // the DOH remote server maybe a domain name, // this prevents cycle resolving dead loop diff --git a/app/router/router_test.go b/app/router/router_test.go index c980e238..93b5fb19 100644 --- a/app/router/router_test.go +++ b/app/router/router_test.go @@ -2,9 +2,10 @@ package router_test import ( "context" - "github.com/xtls/xray-core/features/dns" "testing" + "github.com/xtls/xray-core/features/dns" + "github.com/golang/mock/gomock" . "github.com/xtls/xray-core/app/router" diff --git a/common/buf/buffer_test.go b/common/buf/buffer_test.go index 7b0a7924..3a49d55f 100644 --- a/common/buf/buffer_test.go +++ b/common/buf/buffer_test.go @@ -78,6 +78,7 @@ func TestBufferByte(t *testing.T) { buffer.Release() } } + func TestBufferResize(t *testing.T) { buffer := New() defer buffer.Release() diff --git a/common/buf/io.go b/common/buf/io.go index b2d80ba2..f0b7689c 100644 --- a/common/buf/io.go +++ b/common/buf/io.go @@ -121,7 +121,7 @@ func NewWriter(writer io.Writer) Writer { return mw } - var iConn = writer + iConn := writer if statConn, ok := writer.(*stat.CounterConnection); ok { iConn = statConn.Connection } diff --git a/common/common.go b/common/common.go index eab19aa5..cada9973 100644 --- a/common/common.go +++ b/common/common.go @@ -14,10 +14,8 @@ import ( //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 = errors.New("not enough information for making a decision") -) +// 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. +var ErrNoClue = errors.New("not enough information for making a decision") // Must panics if err is not nil. func Must(err error) { diff --git a/common/crypto/auth.go b/common/crypto/auth.go index fc72405f..355e5bc3 100644 --- a/common/crypto/auth.go +++ b/common/crypto/auth.go @@ -290,7 +290,6 @@ func (w *AuthenticationWriter) writeStream(mb buf.MultiBuffer) error { mb = nb eb, err := w.seal(rawBytes[:nBytes]) - if err != nil { buf.ReleaseMulti(mb2Write) return err diff --git a/common/crypto/chacha20_test.go b/common/crypto/chacha20_test.go index e1237da4..4a51ea75 100644 --- a/common/crypto/chacha20_test.go +++ b/common/crypto/chacha20_test.go @@ -18,7 +18,7 @@ func mustDecodeHex(s string) []byte { } func TestChaCha20Stream(t *testing.T) { - var cases = []struct { + cases := []struct { key []byte iv []byte output []byte diff --git a/common/crypto/internal/chacha_core.generated.go b/common/crypto/internal/chacha_core.generated.go index a0b59788..65458776 100644 --- a/common/crypto/internal/chacha_core.generated.go +++ b/common/crypto/internal/chacha_core.generated.go @@ -3,7 +3,7 @@ package internal import "encoding/binary" 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 { var x uint32 diff --git a/common/crypto/internal/chacha_core_gen.go b/common/crypto/internal/chacha_core_gen.go index a77a9250..5a285172 100644 --- a/common/crypto/internal/chacha_core_gen.go +++ b/common/crypto/internal/chacha_core_gen.go @@ -56,7 +56,7 @@ func ChaCha20Block(s *[16]uint32, out []byte, rounds int) { } 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 { log.Fatalf("Failed to generate chacha_core.go: %v", err) } diff --git a/common/crypto/io.go b/common/crypto/io.go index 59e16660..acf9e0f6 100644 --- a/common/crypto/io.go +++ b/common/crypto/io.go @@ -27,9 +27,7 @@ func (r *CryptionReader) Read(data []byte) (int, error) { return nBytes, err } -var ( - _ buf.Writer = (*CryptionWriter)(nil) -) +var _ buf.Writer = (*CryptionWriter)(nil) type CryptionWriter struct { stream cipher.Stream diff --git a/common/errors/errorgen/main.go b/common/errors/errorgen/main.go index 6accc7a4..4532fd8d 100644 --- a/common/errors/errorgen/main.go +++ b/common/errors/errorgen/main.go @@ -17,7 +17,7 @@ func main() { 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 { fmt.Printf("Failed to generate errors.generated.go: %v", err) os.Exit(1) diff --git a/common/log/log.go b/common/log/log.go index 3d478755..e67e11ec 100644 --- a/common/log/log.go +++ b/common/log/log.go @@ -32,9 +32,7 @@ func Record(msg Message) { logHandler.Handle(msg) } -var ( - logHandler syncHandler -) +var logHandler syncHandler // RegisterHandler register a new handler as current log handler. Previous registered handler will be discarded. func RegisterHandler(handler Handler) { diff --git a/common/log/logger.go b/common/log/logger.go index 6899fef5..79507964 100644 --- a/common/log/logger.go +++ b/common/log/logger.go @@ -130,13 +130,13 @@ func CreateStderrLogWriter() WriterCreator { // CreateFileLogWriter returns a LogWriterCreator that creates LogWriter for the given file. 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 { return nil, err } file.Close() 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 { return nil } diff --git a/common/mux/client.go b/common/mux/client.go index 3d6807f0..ccf05cb2 100644 --- a/common/mux/client.go +++ b/common/mux/client.go @@ -142,7 +142,6 @@ func (f *DialingWorkerFactory) Create() (*ClientWorker, error) { Reader: downlinkReader, Writer: upLinkWriter, }, f.Strategy) - if err != nil { return nil, err } @@ -175,8 +174,10 @@ type ClientWorker struct { strategy ClientStrategy } -var muxCoolAddress = net.DomainAddress("v1.mux.cool") -var muxCoolPort = net.Port(9527) +var ( + muxCoolAddress = net.DomainAddress("v1.mux.cool") + muxCoolPort = net.Port(9527) +) // NewClientWorker creates a new mux.Client. func NewClientWorker(stream transport.Link, s ClientStrategy) (*ClientWorker, error) { diff --git a/common/net/system.go b/common/net/system.go index 19468794..e5bded04 100644 --- a/common/net/system.go +++ b/common/net/system.go @@ -3,17 +3,21 @@ package net import "net" // DialTCP is an alias of net.DialTCP. -var DialTCP = net.DialTCP -var DialUDP = net.DialUDP -var DialUnix = net.DialUnix -var Dial = net.Dial +var ( + DialTCP = net.DialTCP + DialUDP = net.DialUDP + DialUnix = net.DialUnix + Dial = net.Dial +) type ListenConfig = net.ListenConfig -var Listen = net.Listen -var ListenTCP = net.ListenTCP -var ListenUDP = net.ListenUDP -var ListenUnix = net.ListenUnix +var ( + Listen = net.Listen + ListenTCP = net.ListenTCP + ListenUDP = net.ListenUDP + ListenUnix = net.ListenUnix +) var LookupIP = net.LookupIP @@ -26,36 +30,54 @@ var SplitHostPort = net.SplitHostPort var CIDRMask = net.CIDRMask -type Addr = net.Addr -type Conn = net.Conn -type PacketConn = net.PacketConn +type ( + Addr = net.Addr + Conn = net.Conn + PacketConn = net.PacketConn +) -type TCPAddr = net.TCPAddr -type TCPConn = net.TCPConn +type ( + TCPAddr = net.TCPAddr + TCPConn = net.TCPConn +) -type UDPAddr = net.UDPAddr -type UDPConn = net.UDPConn +type ( + UDPAddr = net.UDPAddr + UDPConn = net.UDPConn +) -type UnixAddr = net.UnixAddr -type UnixConn = net.UnixConn +type ( + UnixAddr = net.UnixAddr + UnixConn = net.UnixConn +) // IP is an alias for net.IP. -type IP = net.IP -type IPMask = net.IPMask -type IPNet = net.IPNet +type ( + IP = net.IP + IPMask = net.IPMask + IPNet = net.IPNet +) -const IPv4len = net.IPv4len -const IPv6len = net.IPv6len +const ( + IPv4len = net.IPv4len + IPv6len = net.IPv6len +) -type Error = net.Error -type AddrError = net.AddrError +type ( + Error = net.Error + AddrError = net.AddrError +) -type Dialer = net.Dialer -type Listener = net.Listener -type TCPListener = net.TCPListener -type UnixListener = net.UnixListener +type ( + Dialer = net.Dialer + Listener = net.Listener + TCPListener = net.TCPListener + UnixListener = net.UnixListener +) -var ResolveUnixAddr = net.ResolveUnixAddr -var ResolveUDPAddr = net.ResolveUDPAddr +var ( + ResolveUnixAddr = net.ResolveUnixAddr + ResolveUDPAddr = net.ResolveUDPAddr +) type Resolver = net.Resolver diff --git a/common/ocsp/ocsp.go b/common/ocsp/ocsp.go index 9a9fa5a4..7aadf3ef 100644 --- a/common/ocsp/ocsp.go +++ b/common/ocsp/ocsp.go @@ -56,7 +56,6 @@ func GetOCSPForCert(cert [][]byte) ([]byte, error) { pemBundle := bundle.Bytes() certificates, err := parsePEMBundle(pemBundle) - if err != nil { return nil, err } @@ -99,12 +98,10 @@ func GetOCSPForCert(cert [][]byte) ([]byte, error) { } defer req.Body.Close() ocspResBytes, err := io.ReadAll(req.Body) - if err != nil { return nil, newError(err) } return ocspResBytes, nil - } // parsePEMBundle parses a certificate bundle from top to bottom and returns diff --git a/common/platform/filesystem/file.go b/common/platform/filesystem/file.go index 632694a8..e10bfc11 100644 --- a/common/platform/filesystem/file.go +++ b/common/platform/filesystem/file.go @@ -33,7 +33,7 @@ func CopyFile(dst string, src string) error { if err != nil { 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 { return err } diff --git a/common/protocol/bittorrent/bittorrent.go b/common/protocol/bittorrent/bittorrent.go index 0ffc56a3..17958a3a 100644 --- a/common/protocol/bittorrent/bittorrent.go +++ b/common/protocol/bittorrent/bittorrent.go @@ -6,8 +6,7 @@ import ( "github.com/xtls/xray-core/common" ) -type SniffHeader struct { -} +type SniffHeader struct{} func (h *SniffHeader) Protocol() string { return "bittorrent" diff --git a/common/protocol/tls/cert/cert_test.go b/common/protocol/tls/cert/cert_test.go index 3a1ef8ff..f4bfe090 100644 --- a/common/protocol/tls/cert/cert_test.go +++ b/common/protocol/tls/cert/cert_test.go @@ -73,6 +73,7 @@ func printJSON(certificate *Certificate) { os.Stdout.Write(content) os.Stdout.WriteString("\n") } + func printFile(certificate *Certificate, name string) error { certPEM, keyPEM := certificate.ToPEM() return task.Run(context.Background(), func() error { @@ -81,6 +82,7 @@ func printFile(certificate *Certificate, name string) error { return writeFile(keyPEM, name+"_key.pem") }) } + func writeFile(content []byte, name string) error { f, err := os.Create(name) if err != nil { diff --git a/common/protocol/tls/sniff.go b/common/protocol/tls/sniff.go index a8fec15f..e7661fa7 100644 --- a/common/protocol/tls/sniff.go +++ b/common/protocol/tls/sniff.go @@ -20,8 +20,10 @@ func (h *SniffHeader) Domain() string { return h.domain } -var errNotTLS = errors.New("not TLS header") -var errNotClientHello = errors.New("not client hello") +var ( + errNotTLS = errors.New("not TLS header") + errNotClientHello = errors.New("not client hello") +) func IsValidTLSVersion(major, minor byte) bool { return major == 3 diff --git a/common/retry/retry.go b/common/retry/retry.go index 594e10e9..ec1ad696 100644 --- a/common/retry/retry.go +++ b/common/retry/retry.go @@ -6,9 +6,7 @@ import ( "time" ) -var ( - ErrRetryFailed = newError("all retry attempts failed") -) +var ErrRetryFailed = newError("all retry attempts failed") // Strategy is a way to retry on a specific function. type Strategy interface { diff --git a/common/retry/retry_test.go b/common/retry/retry_test.go index 38a38872..52755a8d 100644 --- a/common/retry/retry_test.go +++ b/common/retry/retry_test.go @@ -9,9 +9,7 @@ import ( . "github.com/xtls/xray-core/common/retry" ) -var ( - errorTestOnly = errors.New("this is a fake error") -) +var errorTestOnly = errors.New("this is a fake error") func TestNoRetry(t *testing.T) { startTime := time.Now().Unix() diff --git a/common/strmatcher/ac_automaton_matcher.go b/common/strmatcher/ac_automaton_matcher.go index e21364ec..ab7c09bd 100644 --- a/common/strmatcher/ac_automaton_matcher.go +++ b/common/strmatcher/ac_automaton_matcher.go @@ -122,7 +122,7 @@ var char2Index = []int{ } func NewACAutomaton() *ACAutomaton { - var ac = new(ACAutomaton) + ac := new(ACAutomaton) ac.trie = append(ac.trie, newNode()) ac.fail = append(ac.fail, 0) ac.exists = append(ac.exists, MatchType{ @@ -133,9 +133,9 @@ func NewACAutomaton() *ACAutomaton { } func (ac *ACAutomaton) Add(domain string, t Type) { - var node = 0 + node := 0 for i := len(domain) - 1; i >= 0; i-- { - var idx = char2Index[domain[i]] + idx := char2Index[domain[i]] if ac.trie[node][idx].nextNode == 0 { ac.count++ if len(ac.trie) < ac.count+1 { @@ -163,7 +163,7 @@ func (ac *ACAutomaton) Add(domain string, t Type) { matchType: Full, exist: true, } - var idx = char2Index['.'] + idx := char2Index['.'] if ac.trie[node][idx].nextNode == 0 { ac.count++ if len(ac.trie) < ac.count+1 { @@ -190,18 +190,18 @@ func (ac *ACAutomaton) Add(domain string, t Type) { } func (ac *ACAutomaton) Build() { - var queue = list.New() + queue := list.New() for i := 0; i < validCharCount; i++ { if ac.trie[0][i].nextNode != 0 { queue.PushBack(ac.trie[0][i]) } } for { - var front = queue.Front() + front := queue.Front() if front == nil { break } else { - var node = front.Value.(Edge).nextNode + node := front.Value.(Edge).nextNode queue.Remove(front) for i := 0; i < validCharCount; i++ { if ac.trie[node][i].nextNode != 0 { @@ -219,13 +219,13 @@ func (ac *ACAutomaton) Build() { } func (ac *ACAutomaton) Match(s string) bool { - var node = 0 - var fullMatch = true + node := 0 + fullMatch := true // 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.1 Through a fail edge, but there exists a valid node. SUBSTR for i := len(s) - 1; i >= 0; i-- { - var idx = char2Index[s[i]] + idx := char2Index[s[i]] fullMatch = fullMatch && ac.trie[node][idx].edgeType node = ac.trie[node][idx].nextNode switch ac.exists[node].matchType { diff --git a/common/strmatcher/mph_matcher.go b/common/strmatcher/mph_matcher.go index 21b98e76..3c10cb49 100644 --- a/common/strmatcher/mph_matcher.go +++ b/common/strmatcher/mph_matcher.go @@ -102,7 +102,7 @@ func (g *MphMatcherGroup) Build() { g.level0Mask = len(g.level0) - 1 g.level1 = make([]uint32, nextPow2(keyLen)) g.level1Mask = len(g.level1) - 1 - var sparseBuckets = make([][]int, len(g.level0)) + sparseBuckets := make([][]int, len(g.level0)) var ruleIdx int for rule, hash := range *g.ruleMap { n := int(hash) & g.level0Mask @@ -122,7 +122,7 @@ func (g *MphMatcherGroup) Build() { occ := make([]bool, len(g.level1)) var tmpOcc []int for _, bucket := range buckets { - var seed = uint32(0) + seed := uint32(0) for { findSeed := true tmpOcc = tmpOcc[:0] @@ -284,9 +284,11 @@ tail: h ^= h >> 32 return uintptr(h) } + func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { return unsafe.Pointer(uintptr(p) + x) } + func readUnaligned32(p unsafe.Pointer) uint32 { q := (*[4]byte)(p) 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 { return (x << 31) | (x >> (64 - 31)) } + func readUnaligned64(p unsafe.Pointer) uint64 { 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 diff --git a/common/strmatcher/strmatcher_test.go b/common/strmatcher/strmatcher_test.go index ec87ce5c..2e48c1b7 100644 --- a/common/strmatcher/strmatcher_test.go +++ b/common/strmatcher/strmatcher_test.go @@ -143,7 +143,7 @@ func TestACAutomaton(t *testing.T) { }, } for _, test := range cases1 { - var ac = NewACAutomaton() + ac := NewACAutomaton() ac.Add(test.pattern, test.mType) ac.Build() if m := ac.Match(test.input); m != test.output { @@ -176,7 +176,7 @@ func TestACAutomaton(t *testing.T) { mType: Substr, }, } - var ac = NewACAutomaton() + ac := NewACAutomaton() for _, test := range cases2Input { ac.Add(test.pattern, test.mType) } @@ -239,7 +239,7 @@ func TestACAutomaton(t *testing.T) { mType: Domain, }, } - var ac = NewACAutomaton() + ac := NewACAutomaton() for _, test := range cases3Input { ac.Add(test.pattern, test.mType) } diff --git a/common/type.go b/common/type.go index 2cda62e9..1f85b4ef 100644 --- a/common/type.go +++ b/common/type.go @@ -8,9 +8,7 @@ import ( // ConfigCreator is a function to create an object by a config. type ConfigCreator func(ctx context.Context, config interface{}) (interface{}, error) -var ( - typeCreatorRegistry = make(map[reflect.Type]ConfigCreator) -) +var typeCreatorRegistry = make(map[reflect.Type]ConfigCreator) // RegisterConfig registers a global config creator. The config can be nil but must have a type. func RegisterConfig(config interface{}, configCreator ConfigCreator) error { diff --git a/common/type_test.go b/common/type_test.go index d074a391..6a8b920f 100644 --- a/common/type_test.go +++ b/common/type_test.go @@ -16,7 +16,7 @@ type YConfig struct { } 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 t.(*TConfig).value }, nil diff --git a/common/uuid/uuid.go b/common/uuid/uuid.go index 0086f06b..4ede12e6 100644 --- a/common/uuid/uuid.go +++ b/common/uuid/uuid.go @@ -10,9 +10,7 @@ import ( "github.com/xtls/xray-core/common/errors" ) -var ( - byteGroups = []int{8, 4, 4, 4, 12} -) +var byteGroups = []int{8, 4, 4, 4, 12} type UUID [16]byte diff --git a/core/xray.go b/core/xray.go index c18a3101..5c7518f9 100644 --- a/core/xray.go +++ b/core/xray.go @@ -159,7 +159,7 @@ func RequireFeatures(ctx context.Context, callback interface{}) error { // 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. func New(config *Config) (*Instance, error) { - var server = &Instance{ctx: context.Background()} + server := &Instance{ctx: context.Background()} done, err := initInstanceWithConfig(config, server) if done { @@ -170,7 +170,7 @@ func New(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) if done { diff --git a/infra/conf/blackhole.go b/infra/conf/blackhole.go index 6c4f692c..e2fdeedc 100644 --- a/infra/conf/blackhole.go +++ b/infra/conf/blackhole.go @@ -42,12 +42,10 @@ func (v *BlackholeConfig) Build() (proto.Message, error) { return config, nil } -var ( - configLoader = NewJSONConfigLoader( - ConfigCreatorCache{ - "none": func() interface{} { return new(NoneResponse) }, - "http": func() interface{} { return new(HTTPResponse) }, - }, - "type", - "") -) +var configLoader = NewJSONConfigLoader( + ConfigCreatorCache{ + "none": func() interface{} { return new(NoneResponse) }, + "http": func() interface{} { return new(HTTPResponse) }, + }, + "type", + "") diff --git a/infra/conf/dns_test.go b/infra/conf/dns_test.go index 8c583a51..cbd5d672 100644 --- a/infra/conf/dns_test.go +++ b/infra/conf/dns_test.go @@ -27,7 +27,7 @@ func init() { geositeFilePath := filepath.Join(wd, "geosite.dat") 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) defer geositeFile.Close() @@ -46,6 +46,7 @@ func init() { common.Must(err) common.Must2(geositeFile.Write(listBytes)) } + func TestDNSConfigParsing(t *testing.T) { geositePath := platform.GetAssetLocation("geosite.dat") defer func() { diff --git a/infra/conf/http.go b/infra/conf/http.go index d3d944f6..54cf178b 100644 --- a/infra/conf/http.go +++ b/infra/conf/http.go @@ -51,6 +51,7 @@ type HTTPRemoteConfig struct { Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } + type HTTPClientConfig struct { Servers []*HTTPRemoteConfig `json:"servers"` } diff --git a/infra/conf/json/reader_test.go b/infra/conf/json/reader_test.go index 6999c245..145157a0 100644 --- a/infra/conf/json/reader_test.go +++ b/infra/conf/json/reader_test.go @@ -24,7 +24,8 @@ content 2`, ` content -content 2`}, +content 2`, + }, {`content`, `content`}, {" ", " "}, {`con/*abcd*/tent`, "content"}, diff --git a/infra/conf/mtproto.go b/infra/conf/mtproto.go index a9bc8eec..4cd5972e 100644 --- a/infra/conf/mtproto.go +++ b/infra/conf/mtproto.go @@ -60,8 +60,7 @@ func (c *MTProtoServerConfig) Build() (proto.Message, error) { return config, nil } -type MTProtoClientConfig struct { -} +type MTProtoClientConfig struct{} func (c *MTProtoClientConfig) Build() (proto.Message, error) { config := new(mtproto.ClientConfig) diff --git a/infra/conf/router.go b/infra/conf/router.go index ed0b488c..c920e5e8 100644 --- a/infra/conf/router.go +++ b/infra/conf/router.go @@ -338,7 +338,7 @@ func parseDomainRule(domain string) ([]*router.Domain, error) { } return domains, nil } - var isExtDatFile = 0 + isExtDatFile := 0 { const prefix = "ext:" if strings.HasPrefix(domain, prefix) { @@ -417,7 +417,7 @@ func toCidrList(ips StringList) ([]*router.GeoIP, error) { }) continue } - var isExtDatFile = 0 + isExtDatFile := 0 { const prefix = "ext:" if strings.HasPrefix(ip, prefix) { diff --git a/infra/conf/serial/builder.go b/infra/conf/serial/builder.go index a1de8b84..443dbdb0 100644 --- a/infra/conf/serial/builder.go +++ b/infra/conf/serial/builder.go @@ -9,7 +9,6 @@ import ( ) func BuildConfig(files []string, formats []string) (*core.Config, error) { - cf := &conf.Config{} for i, file := range files { 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) -var ( - ReaderDecoderByFormat = make(map[string]readerDecoder) -) +var ReaderDecoderByFormat = make(map[string]readerDecoder) func init() { ReaderDecoderByFormat["json"] = DecodeJSONConfig diff --git a/infra/conf/socks.go b/infra/conf/socks.go index 794b60d4..b86dfae1 100644 --- a/infra/conf/socks.go +++ b/infra/conf/socks.go @@ -70,6 +70,7 @@ type SocksRemoteConfig struct { Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } + type SocksClientConfig struct { Servers []*SocksRemoteConfig `json:"servers"` } diff --git a/infra/conf/transport_internet.go b/infra/conf/transport_internet.go index 5983a8d5..cac20522 100644 --- a/infra/conf/transport_internet.go +++ b/infra/conf/transport_internet.go @@ -540,7 +540,7 @@ func (c *SocketConfig) Build() (*internet.SocketConfig, error) { tproxy = internet.SocketConfig_Off } - var dStrategy = internet.DomainStrategy_AS_IS + dStrategy := internet.DomainStrategy_AS_IS switch strings.ToLower(c.DomainStrategy) { case "useip", "use_ip": dStrategy = internet.DomainStrategy_USE_IP diff --git a/infra/conf/vmess.go b/infra/conf/vmess.go index 1200be07..37557c17 100644 --- a/infra/conf/vmess.go +++ b/infra/conf/vmess.go @@ -127,6 +127,7 @@ type VMessOutboundTarget struct { Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } + type VMessOutboundConfig struct { Receivers []*VMessOutboundTarget `json:"vnext"` } diff --git a/infra/conf/xray_test.go b/infra/conf/xray_test.go index db930dd6..289850ea 100644 --- a/infra/conf/xray_test.go +++ b/infra/conf/xray_test.go @@ -380,7 +380,8 @@ func TestConfig_Override(t *testing.T) { fn string want *Config }{ - {"combine/empty", + { + "combine/empty", &Config{}, &Config{ LogConfig: &LogConfig{}, @@ -404,40 +405,54 @@ func TestConfig_Override(t *testing.T) { Reverse: &ReverseConfig{}, }, }, - {"combine/newattr", + { + "combine/newattr", &Config{InboundConfigs: []InboundDetourConfig{{Tag: "old"}}}, &Config{LogConfig: &LogConfig{}}, "", - &Config{LogConfig: &LogConfig{}, InboundConfigs: []InboundDetourConfig{{Tag: "old"}}}}, - {"replace/inbounds", + &Config{LogConfig: &LogConfig{}, InboundConfigs: []InboundDetourConfig{{Tag: "old"}}}, + }, + { + "replace/inbounds", &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, "", - &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}}, - {"replace/inbounds-replaceall", + &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}, + }, + { + "replace/inbounds-replaceall", &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"}}}}, - {"replace/notag-append", + &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}, + }, + { + "replace/notag-append", &Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}}}, &Config{InboundConfigs: []InboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, "", - &Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}, {Tag: "pos1", Protocol: "kcp"}}}}, - {"replace/outbounds", + &Config{InboundConfigs: []InboundDetourConfig{{}, {Protocol: "vmess"}, {Tag: "pos1", Protocol: "kcp"}}}, + }, + { + "replace/outbounds", &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}}}, "", - &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}}, - {"replace/outbounds-prepend", + &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Tag: "pos1", Protocol: "kcp"}}}, + }, + { + "replace/outbounds-prepend", &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}, "config.json", - &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}}, - {"replace/outbounds-append", + &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos1", Protocol: "kcp"}, {Tag: "pos2", Protocol: "kcp"}}}, + }, + { + "replace/outbounds-append", &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos0"}, {Protocol: "vmess", Tag: "pos1"}}}, &Config{OutboundConfigs: []OutboundDetourConfig{{Tag: "pos2", Protocol: "kcp"}}}, "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 { t.Run(tt.name, func(t *testing.T) { diff --git a/main/commands/all/commands.go b/main/commands/all/commands.go index a4945c8e..da50a845 100644 --- a/main/commands/all/commands.go +++ b/main/commands/all/commands.go @@ -12,7 +12,7 @@ func init() { base.RootCommand.Commands = append( base.RootCommand.Commands, api.CmdAPI, - //cmdConvert, + // cmdConvert, tls.CmdTLS, cmdUUID, ) diff --git a/main/commands/all/tls/ping.go b/main/commands/all/tls/ping.go index a3697d28..0f096cac 100644 --- a/main/commands/all/tls/ping.go +++ b/main/commands/all/tls/ping.go @@ -27,9 +27,7 @@ func init() { cmdPing.Run = executePing // break init loop } -var ( - pingIPStr = cmdPing.Flag.String("ip", "", "") -) +var pingIPStr = cmdPing.Flag.String("ip", "", "") func executePing(cmd *base.Command, args []string) { if cmdPing.Flag.NArg() < 1 { diff --git a/main/commands/base/command.go b/main/commands/base/command.go index 98237595..165a1c62 100644 --- a/main/commands/base/command.go +++ b/main/commands/base/command.go @@ -113,8 +113,10 @@ func ExitIfErrors() { } } -var exitStatus = 0 -var exitMu sync.Mutex +var ( + exitStatus = 0 + exitMu sync.Mutex +) // SetExitStatus set exit status code func SetExitStatus(n int) { diff --git a/main/confloader/confloader.go b/main/confloader/confloader.go index c0e4d62f..80b3b306 100644 --- a/main/confloader/confloader.go +++ b/main/confloader/confloader.go @@ -5,8 +5,10 @@ import ( "os" ) -type configFileLoader func(string) (io.Reader, error) -type extconfigLoader func([]string, io.Reader) (io.Reader, error) +type ( + configFileLoader func(string) (io.Reader, error) + extconfigLoader func([]string, io.Reader) (io.Reader, error) +) var ( EffectiveConfigFileLoader configFileLoader diff --git a/main/main.go b/main/main.go index 22d60bdf..e8824e6f 100644 --- a/main/main.go +++ b/main/main.go @@ -37,20 +37,20 @@ func getArgsV4Compatible() []string { fs.SetOutput(&null{}) err := fs.Parse(os.Args[1:]) if err == flag.ErrHelp { - //fmt.Println("DEPRECATED: -h, WILL BE REMOVED IN V5.") - //fmt.Println("PLEASE USE: xray help") - //fmt.Println() + // fmt.Println("DEPRECATED: -h, WILL BE REMOVED IN V5.") + // fmt.Println("PLEASE USE: xray help") + // fmt.Println() return []string{os.Args[0], "help"} } if version { - //fmt.Println("DEPRECATED: -version, WILL BE REMOVED IN V5.") - //fmt.Println("PLEASE USE: xray version") - //fmt.Println() + // fmt.Println("DEPRECATED: -version, WILL BE REMOVED IN V5.") + // fmt.Println("PLEASE USE: xray version") + // fmt.Println() return []string{os.Args[0], "version"} } - //fmt.Println("COMPATIBLE MODE, DEPRECATED.") - //fmt.Println("PLEASE USE: xray run [arguments] INSTEAD.") - //fmt.Println() + // fmt.Println("COMPATIBLE MODE, DEPRECATED.") + // fmt.Println("PLEASE USE: xray run [arguments] INSTEAD.") + // fmt.Println() return append([]string{os.Args[0], "run"}, os.Args[1:]...) } diff --git a/main/run.go b/main/run.go index e12d6beb..97967700 100644 --- a/main/run.go +++ b/main/run.go @@ -39,7 +39,7 @@ without launching the server } func init() { - cmdRun.Run = executeRun //break init loop + cmdRun.Run = executeRun // break init loop } var ( @@ -52,7 +52,6 @@ var ( * main func in this file is run. */ _ = func() bool { - cmdRun.Flag.Var(&configFiles, "config", "Config path for Xray.") cmdRun.Flag.Var(&configFiles, "c", "Short alias of -config") cmdRun.Flag.StringVar(&configDir, "confdir", "", "A dir with multiple json config") @@ -181,10 +180,9 @@ func getConfigFormat() string { func startXray() (core.Server, error) { configFiles := getConfigFilePath() - //config, err := core.LoadConfig(getConfigFormat(), configFiles[0], configFiles) + // config, err := core.LoadConfig(getConfigFormat(), configFiles[0], configFiles) c, err := core.LoadConfig(getConfigFormat(), configFiles) - if err != nil { return nil, newError("failed to load config files: [", configFiles.String(), "]").Base(err) } diff --git a/proxy/dns/dns_test.go b/proxy/dns/dns_test.go index cc43c251..7d73a08d 100644 --- a/proxy/dns/dns_test.go +++ b/proxy/dns/dns_test.go @@ -24,8 +24,7 @@ import ( "github.com/xtls/xray-core/testing/servers/udp" ) -type staticHandler struct { -} +type staticHandler struct{} func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { ans := new(dns.Msg) diff --git a/proxy/http/client.go b/proxy/http/client.go index 21247985..ab0b420c 100644 --- a/proxy/http/client.go +++ b/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)) } - 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 { return newError("connection ends").Base(err) } diff --git a/proxy/http/server.go b/proxy/http/server.go index 414eb2bc..67f82976 100644 --- a/proxy/http/server.go +++ b/proxy/http/server.go @@ -206,7 +206,7 @@ func (s *Server) handleConnect(ctx context.Context, _ *http.Request, reader *buf 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 { common.Interrupt(link.Reader) common.Interrupt(link.Writer) diff --git a/proxy/mtproto/auth.go b/proxy/mtproto/auth.go index 00857d73..cdd66d6f 100644 --- a/proxy/mtproto/auth.go +++ b/proxy/mtproto/auth.go @@ -133,13 +133,11 @@ func Inverse(b []byte) []byte { return b2 } -var ( - authPool = sync.Pool{ - New: func() interface{} { - return new(Authentication) - }, - } -) +var authPool = sync.Pool{ + New: func() interface{} { + return new(Authentication) + }, +} func getAuthenticationObject() *Authentication { return authPool.Get().(*Authentication) diff --git a/proxy/mtproto/client.go b/proxy/mtproto/client.go index ee4e7a8e..6825fdae 100644 --- a/proxy/mtproto/client.go +++ b/proxy/mtproto/client.go @@ -13,8 +13,7 @@ import ( "github.com/xtls/xray-core/transport/internet" ) -type Client struct { -} +type Client struct{} func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { 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) } - 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 { return newError("connection ends").Base(err) } diff --git a/proxy/mtproto/server.go b/proxy/mtproto/server.go index c6c7b7ce..45096d33 100644 --- a/proxy/mtproto/server.go +++ b/proxy/mtproto/server.go @@ -20,15 +20,13 @@ import ( "github.com/xtls/xray-core/features/routing" ) -var ( - dcList = []net.Address{ - net.ParseAddress("149.154.175.50"), - net.ParseAddress("149.154.167.51"), - net.ParseAddress("149.154.175.100"), - net.ParseAddress("149.154.167.91"), - net.ParseAddress("149.154.171.5"), - } -) +var dcList = []net.Address{ + net.ParseAddress("149.154.175.50"), + net.ParseAddress("149.154.167.51"), + net.ParseAddress("149.154.175.100"), + net.ParseAddress("149.154.167.91"), + net.ParseAddress("149.154.171.5"), +} type Server struct { user *protocol.User @@ -64,8 +62,10 @@ func (s *Server) Network() []net.Network { return []net.Network{net.Network_TCP} } -var ctype1 = []byte{0xef, 0xef, 0xef, 0xef} -var ctype2 = []byte{0xee, 0xee, 0xee, 0xee} +var ( + ctype1 = []byte{0xef, 0xef, 0xef, 0xef} + ctype2 = []byte{0xee, 0xee, 0xee, 0xee} +) func isValidConnectionType(c [4]byte) bool { 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)) } - 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 { common.Interrupt(link.Reader) common.Interrupt(link.Writer) diff --git a/proxy/shadowsocks/client.go b/proxy/shadowsocks/client.go index 6b362d33..5e45852a 100644 --- a/proxy/shadowsocks/client.go +++ b/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)) } - 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 { return newError("connection ends").Base(err) } @@ -170,7 +170,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter 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 { return newError("connection ends").Base(err) } diff --git a/proxy/shadowsocks/protocol.go b/proxy/shadowsocks/protocol.go index f09e5bd2..c465476c 100644 --- a/proxy/shadowsocks/protocol.go +++ b/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. func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) { - hashkdf := hmac.New(sha256.New, []byte("SSBSKDF")) behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil)) diff --git a/proxy/shadowsocks/server.go b/proxy/shadowsocks/server.go index 523bac9f..430a5688 100644 --- a/proxy/shadowsocks/server.go +++ b/proxy/shadowsocks/server.go @@ -271,7 +271,7 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis 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 { common.Interrupt(link.Reader) common.Interrupt(link.Writer) diff --git a/proxy/socks/client.go b/proxy/socks/client.go index 22eb3650..409113ac 100644 --- a/proxy/socks/client.go +++ b/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 { return newError("connection ends").Base(err) } diff --git a/proxy/socks/server.go b/proxy/socks/server.go index 0225c79c..966c3ac2 100644 --- a/proxy/socks/server.go +++ b/proxy/socks/server.go @@ -182,7 +182,7 @@ func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writ 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 { common.Interrupt(link.Reader) common.Interrupt(link.Writer) @@ -237,7 +237,6 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis for _, payload := range mpayload { request, err := DecodeUDPPacket(payload) - if err != nil { newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx)) payload.Release() diff --git a/proxy/trojan/client.go b/proxy/trojan/client.go index cc674d83..bc5b96bf 100644 --- a/proxy/trojan/client.go +++ b/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)) } - 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 { return newError("connection ends").Base(err) } diff --git a/proxy/trojan/protocol.go b/proxy/trojan/protocol.go index 0befb927..34b6b267 100644 --- a/proxy/trojan/protocol.go +++ b/proxy/trojan/protocol.go @@ -323,7 +323,7 @@ func ReadV(reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, c panic("XTLS Splice: not TCP inbound") } } else { - //panic("XTLS Splice: nil inbound or nil inbound.Conn") + // panic("XTLS Splice: nil inbound or nil inbound.Conn") } } reader = buf.NewReadVReader(conn.Connection, rawConn, nil) diff --git a/proxy/trojan/server.go b/proxy/trojan/server.go index 0642b764..7c965097 100644 --- a/proxy/trojan/server.go +++ b/proxy/trojan/server.go @@ -382,7 +382,7 @@ func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Sess 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 { common.Must(common.Interrupt(link.Reader)) common.Must(common.Interrupt(link.Writer)) diff --git a/proxy/vless/encoding/encoding.go b/proxy/vless/encoding/encoding.go index eb7999ce..a5ee0690 100644 --- a/proxy/vless/encoding/encoding.go +++ b/proxy/vless/encoding/encoding.go @@ -210,7 +210,7 @@ func ReadV(reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, c panic("XTLS Splice: not TCP inbound") } } else { - //panic("XTLS Splice: nil inbound or nil inbound.Conn") + // panic("XTLS Splice: nil inbound or nil inbound.Conn") } } reader = buf.NewReadVReader(conn.Connection, rawConn, nil) diff --git a/proxy/vless/inbound/inbound.go b/proxy/vless/inbound/inbound.go index 5b21a109..d78782c0 100644 --- a/proxy/vless/inbound/inbound.go +++ b/proxy/vless/inbound/inbound.go @@ -35,9 +35,7 @@ import ( "github.com/xtls/xray-core/transport/internet/xtls" ) -var ( - xtls_show = false -) +var xtls_show = false func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { diff --git a/proxy/vless/outbound/outbound.go b/proxy/vless/outbound/outbound.go index ffb36837..87dd9caf 100644 --- a/proxy/vless/outbound/outbound.go +++ b/proxy/vless/outbound/outbound.go @@ -29,9 +29,7 @@ import ( "github.com/xtls/xray-core/transport/internet/xtls" ) -var ( - xtls_show = false -) +var xtls_show = false func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { diff --git a/proxy/vmess/aead/encrypt.go b/proxy/vmess/aead/encrypt.go index bd7df0ec..8995f2ea 100644 --- a/proxy/vmess/aead/encrypt.go +++ b/proxy/vmess/aead/encrypt.go @@ -40,7 +40,6 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte { } payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderLengthAEADAESBlock) - if err != nil { panic(err.Error()) } @@ -61,7 +60,6 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte { } payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) - if err != nil { panic(err.Error()) } @@ -69,7 +67,7 @@ func SealVMessAEADHeader(key [16]byte, data []byte) []byte { 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(payloadHeaderLengthAEADEncrypted)) // 2+16 @@ -112,7 +110,6 @@ func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte, } payloadHeaderLengthAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) - if err != nil { panic(err.Error()) } @@ -154,7 +151,6 @@ func OpenVMessAEADHeader(key [16]byte, authid [16]byte, data io.Reader) ([]byte, } payloadHeaderAEAD, err := cipher.NewGCM(payloadHeaderAEADAESBlock) - if err != nil { panic(err.Error()) } diff --git a/proxy/vmess/aead/encrypt_test.go b/proxy/vmess/aead/encrypt_test.go index b18cfcce..5f8e33cf 100644 --- a/proxy/vmess/aead/encrypt_test.go +++ b/proxy/vmess/aead/encrypt_test.go @@ -16,7 +16,7 @@ func TestOpenVMessAEADHeader(t *testing.T) { copy(keyw[:], key) sealed := SealVMessAEADHeader(keyw, TestHeader) - var AEADR = bytes.NewReader(sealed) + AEADR := bytes.NewReader(sealed) var authid [16]byte @@ -35,7 +35,7 @@ func TestOpenVMessAEADHeader2(t *testing.T) { copy(keyw[:], key) sealed := SealVMessAEADHeader(keyw, TestHeader) - var AEADR = bytes.NewReader(sealed) + AEADR := bytes.NewReader(sealed) var authid [16]byte @@ -57,7 +57,7 @@ func TestOpenVMessAEADHeader4(t *testing.T) { var sealedm [16]byte copy(sealedm[:], sealed) sealed[i] ^= 0xff - var AEADR = bytes.NewReader(sealed) + AEADR := bytes.NewReader(sealed) var authid [16]byte @@ -85,7 +85,7 @@ func TestOpenVMessAEADHeader4Massive(t *testing.T) { var sealedm [16]byte copy(sealedm[:], sealed) sealed[i] ^= 0xff - var AEADR = bytes.NewReader(sealed) + AEADR := bytes.NewReader(sealed) var authid [16]byte diff --git a/proxy/vmess/encoding/auth.go b/proxy/vmess/encoding/auth.go index 1761238c..6233643f 100644 --- a/proxy/vmess/encoding/auth.go +++ b/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. -type FnvAuthenticator struct { -} +type FnvAuthenticator struct{} // NonceSize implements AEAD.NonceSize(). func (*FnvAuthenticator) NonceSize() int { diff --git a/proxy/vmess/encoding/commands.go b/proxy/vmess/encoding/commands.go index c71d6460..de2e0253 100644 --- a/proxy/vmess/encoding/commands.go +++ b/proxy/vmess/encoding/commands.go @@ -77,8 +77,7 @@ type CommandFactory interface { Unmarshal(data []byte) (interface{}, error) } -type CommandSwitchAccountFactory struct { -} +type CommandSwitchAccountFactory struct{} func (f *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error { cmd, ok := command.(*protocol.CommandSwitchAccount) diff --git a/proxy/vmess/inbound/inbound.go b/proxy/vmess/inbound/inbound.go index 7c1a2e50..ec508adb 100644 --- a/proxy/vmess/inbound/inbound.go +++ b/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) } - 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 { common.Interrupt(link.Reader) common.Interrupt(link.Writer) @@ -370,7 +370,7 @@ func init() { return New(ctx, config.(*Config)) })) - var defaultFlagValue = "NOT_DEFINED_AT_ALL" + defaultFlagValue := "NOT_DEFINED_AT_ALL" if time.Now().Year() >= 2022 { defaultFlagValue = "true_by_default_2022" diff --git a/proxy/vmess/outbound/outbound.go b/proxy/vmess/outbound/outbound.go index fbdca3c5..7265e9f3 100644 --- a/proxy/vmess/outbound/outbound.go +++ b/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)) } - var responseDonePost = task.OnSuccess(responseDone, task.Close(output)) + responseDonePost := task.OnSuccess(responseDone, task.Close(output)) if err := task.Run(ctx, requestDone, responseDonePost); err != nil { return newError("connection ends").Base(err) } diff --git a/testing/mocks/dns.go b/testing/mocks/dns.go index 73a219ed..15ddfbf4 100644 --- a/testing/mocks/dns.go +++ b/testing/mocks/dns.go @@ -5,10 +5,11 @@ package mocks import ( - gomock "github.com/golang/mock/gomock" - dns "github.com/xtls/xray-core/features/dns" net "net" reflect "reflect" + + gomock "github.com/golang/mock/gomock" + dns "github.com/xtls/xray-core/features/dns" ) // DNSClient is a mock of Client interface diff --git a/testing/mocks/io.go b/testing/mocks/io.go index d1f92cea..e1b72c0f 100644 --- a/testing/mocks/io.go +++ b/testing/mocks/io.go @@ -5,8 +5,9 @@ package mocks import ( - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" ) // Reader is a mock of Reader interface diff --git a/testing/mocks/log.go b/testing/mocks/log.go index 77c821f5..2014714a 100644 --- a/testing/mocks/log.go +++ b/testing/mocks/log.go @@ -5,9 +5,10 @@ package mocks import ( + reflect "reflect" + gomock "github.com/golang/mock/gomock" log "github.com/xtls/xray-core/common/log" - reflect "reflect" ) // LogHandler is a mock of Handler interface diff --git a/testing/mocks/mux.go b/testing/mocks/mux.go index 07d4c4ad..99690896 100644 --- a/testing/mocks/mux.go +++ b/testing/mocks/mux.go @@ -5,9 +5,10 @@ package mocks import ( + reflect "reflect" + gomock "github.com/golang/mock/gomock" mux "github.com/xtls/xray-core/common/mux" - reflect "reflect" ) // MuxClientWorkerFactory is a mock of ClientWorkerFactory interface diff --git a/testing/mocks/outbound.go b/testing/mocks/outbound.go index 9cab8c34..4f1083cf 100644 --- a/testing/mocks/outbound.go +++ b/testing/mocks/outbound.go @@ -6,9 +6,10 @@ package mocks import ( context "context" + reflect "reflect" + gomock "github.com/golang/mock/gomock" outbound "github.com/xtls/xray-core/features/outbound" - reflect "reflect" ) // OutboundManager is a mock of Manager interface diff --git a/testing/scenarios/vmess_test.go b/testing/scenarios/vmess_test.go index c7ddaf67..45641deb 100644 --- a/testing/scenarios/vmess_test.go +++ b/testing/scenarios/vmess_test.go @@ -108,12 +108,12 @@ func TestVMessDynamicPort(t *testing.T) { } server, _ := InitializeServerConfig(serverConfig) - if server != nil && tcpConnAvailableAtPort(t, serverPort + 100) { + if server != nil && tcpConnAvailableAtPort(t, serverPort+100) { defer CloseServer(server) break } retry += 1 - if (retry > 5) { + if retry > 5 { t.Fatal("All attempts failed to start server") } serverPort = tcp.PickPort() @@ -174,7 +174,7 @@ func TestVMessDynamicPort(t *testing.T) { func tcpConnAvailableAtPort(t *testing.T, port net.Port) bool { for i := 1; ; i++ { - if (i > 10) { + if i > 10 { t.Log("All attempts failed to test tcp conn") return false } diff --git a/testing/servers/tcp/tcp.go b/testing/servers/tcp/tcp.go index 484f2d76..7fffecf6 100644 --- a/testing/servers/tcp/tcp.go +++ b/testing/servers/tcp/tcp.go @@ -97,7 +97,6 @@ func (server *Server) handleConnection(conn net.Conn) { } } }) - if err != nil { fmt.Println("failed to transfer data: ", err.Error()) } diff --git a/transport/internet/dialer.go b/transport/internet/dialer.go index 7ba1f285..fe676b3b 100644 --- a/transport/internet/dialer.go +++ b/transport/internet/dialer.go @@ -28,9 +28,7 @@ type Dialer interface { // 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) -var ( - transportDialerCache = make(map[string]dialFunc) -) +var transportDialerCache = make(map[string]dialFunc) // RegisterTransportDialer registers a Dialer with given name. func RegisterTransportDialer(protocol string, dialer dialFunc) error { @@ -81,7 +79,7 @@ func lookupIP(domain string, strategy DomainStrategy, localAddr net.Address) ([] return nil, nil } - var option = dns.IPOption{ + option := dns.IPOption{ IPv4Enable: true, IPv6Enable: true, FakeEnable: false, diff --git a/transport/internet/domainsocket/config.go b/transport/internet/domainsocket/config.go index 54e3eabe..7dfb5ec4 100644 --- a/transport/internet/domainsocket/config.go +++ b/transport/internet/domainsocket/config.go @@ -6,8 +6,10 @@ import ( "github.com/xtls/xray-core/transport/internet" ) -const protocolName = "domainsocket" -const sizeofSunPath = 108 +const ( + protocolName = "domainsocket" + sizeofSunPath = 108 +) func (c *Config) GetUnixAddr() (*net.UnixAddr, error) { path := c.Path diff --git a/transport/internet/grpc/dial.go b/transport/internet/grpc/dial.go index c0a789e3..e4b942d5 100644 --- a/transport/internet/grpc/dial.go +++ b/transport/internet/grpc/dial.go @@ -49,7 +49,6 @@ func dialgRPC(ctx context.Context, dest net.Destination, streamSettings *interne grpcSettings := streamSettings.ProtocolSettings.(*Config) conn, err := getGrpcClient(ctx, dest, streamSettings) - if err != nil { 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 } - var dialOptions = []grpc.DialOption{ + dialOptions := []grpc.DialOption{ grpc.WithConnectParams(grpc.ConnectParams{ Backoff: backoff.Config{ BaseDelay: 500 * time.Millisecond, diff --git a/transport/internet/grpc/encoding/multiconn.go b/transport/internet/grpc/encoding/multiconn.go index 13a7eb2c..750268ef 100644 --- a/transport/internet/grpc/encoding/multiconn.go +++ b/transport/internet/grpc/encoding/multiconn.go @@ -92,7 +92,7 @@ func (h *MultiHunkReaderWriter) ReadMultiBuffer() (buf.MultiBuffer, error) { 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 { if len(b) == 0 { continue diff --git a/transport/internet/kcp/dialer.go b/transport/internet/kcp/dialer.go index cd30b6ff..9df28c99 100644 --- a/transport/internet/kcp/dialer.go +++ b/transport/internet/kcp/dialer.go @@ -16,9 +16,7 @@ import ( "github.com/xtls/xray-core/transport/internet/xtls" ) -var ( - globalConv = uint32(dice.RollUint16()) -) +var globalConv = uint32(dice.RollUint16()) func fetchInput(_ context.Context, input io.Reader, reader PacketReader, conn *Connection) { cache := make(chan *buf.Buffer, 1024) diff --git a/transport/internet/quic/hub.go b/transport/internet/quic/hub.go index 49ca1f7e..ee3cf053 100644 --- a/transport/internet/quic/hub.go +++ b/transport/internet/quic/hub.go @@ -97,7 +97,6 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti IP: address.IP(), Port: int(port), }, streamSettings.SocketSettings) - if err != nil { return nil, err } diff --git a/transport/internet/quic/quic.go b/transport/internet/quic/quic.go index db1d85b1..fe462139 100644 --- a/transport/internet/quic/quic.go +++ b/transport/internet/quic/quic.go @@ -13,8 +13,10 @@ import ( // // -const protocolName = "quic" -const internalDomain = "quic.internal.example.com" +const ( + protocolName = "quic" + internalDomain = "quic.internal.example.com" +) func init() { common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} { diff --git a/transport/internet/sockopt_freebsd.go b/transport/internet/sockopt_freebsd.go index 29c19de5..1f10e08b 100644 --- a/transport/internet/sockopt_freebsd.go +++ b/transport/internet/sockopt_freebsd.go @@ -45,6 +45,7 @@ func ioctl(s uintptr, ioc int, b []byte) error { } return nil } + func (nl *pfiocNatlook) rdPort() int { return int(binary.BigEndian.Uint16((*[2]byte)(unsafe.Pointer(&nl.Rdport))[:])) } diff --git a/transport/internet/sockopt_windows.go b/transport/internet/sockopt_windows.go index 840834b6..d2ce9ff7 100644 --- a/transport/internet/sockopt_windows.go +++ b/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 { return err } - } return nil diff --git a/transport/internet/system_dialer.go b/transport/internet/system_dialer.go index 9932300b..fa8b656c 100644 --- a/transport/internet/system_dialer.go +++ b/transport/internet/system_dialer.go @@ -11,9 +11,7 @@ import ( "github.com/xtls/xray-core/features/outbound" ) -var ( - effectiveSystemDialer SystemDialer = &DefaultSystemDialer{} -) +var effectiveSystemDialer SystemDialer = &DefaultSystemDialer{} type SystemDialer interface { Dial(ctx context.Context, source net.Address, destination net.Destination, sockopt *SocketConfig) (net.Conn, error) diff --git a/transport/internet/system_listener.go b/transport/internet/system_listener.go index ef758e0b..4a1df9fe 100644 --- a/transport/internet/system_listener.go +++ b/transport/internet/system_listener.go @@ -11,9 +11,7 @@ import ( "github.com/xtls/xray-core/common/session" ) -var ( - effectiveListener = DefaultListener{} -) +var effectiveListener = DefaultListener{} type controller func(network, address string, fd uintptr) error diff --git a/transport/internet/tcp/hub.go b/transport/internet/tcp/hub.go index 841638a8..3aee41a2 100644 --- a/transport/internet/tcp/hub.go +++ b/transport/internet/tcp/hub.go @@ -45,7 +45,7 @@ func ListenTCP(ctx context.Context, address net.Address, port net.Port, streamSe } var listener net.Listener var err error - if port == net.Port(0) { //unix + if port == net.Port(0) { // unix listener, err = internet.ListenSystem(ctx, &net.UnixAddr{ Name: address.Domain(), Net: "unix", diff --git a/transport/internet/tcp_hub.go b/transport/internet/tcp_hub.go index ffb81e95..cbb1ca99 100644 --- a/transport/internet/tcp_hub.go +++ b/transport/internet/tcp_hub.go @@ -8,9 +8,7 @@ import ( "github.com/xtls/xray-core/common/net" ) -var ( - transportListenerCache = make(map[string]ListenFunc) -) +var transportListenerCache = make(map[string]ListenFunc) func RegisterTransportListener(protocol string, listener ListenFunc) error { if _, found := transportListenerCache[protocol]; found { @@ -50,6 +48,7 @@ func ListenUnix(ctx context.Context, address net.Address, settings *MemoryStream } return listener, nil } + func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error) { if settings == nil { s, err := ToMemoryStreamConfig(nil) diff --git a/transport/internet/tls/config.go b/transport/internet/tls/config.go index 219fbaaf..e1d84959 100644 --- a/transport/internet/tls/config.go +++ b/transport/internet/tls/config.go @@ -14,9 +14,7 @@ import ( "github.com/xtls/xray-core/transport/internet" ) -var ( - globalSessionCache = tls.NewLRUClientSessionCache(128) -) +var globalSessionCache = tls.NewLRUClientSessionCache(128) // ParseCertificate converts a cert.Certificate to Certificate. func ParseCertificate(c *cert.Certificate) *Certificate { diff --git a/transport/internet/tls/tls.go b/transport/internet/tls/tls.go index b33eaf69..8ea2ce0f 100644 --- a/transport/internet/tls/tls.go +++ b/transport/internet/tls/tls.go @@ -11,9 +11,7 @@ import ( //go:generate go run github.com/xtls/xray-core/common/errors/errorgen -var ( - _ buf.Writer = (*Conn)(nil) -) +var _ buf.Writer = (*Conn)(nil) type Conn struct { *tls.Conn diff --git a/transport/internet/websocket/connection.go b/transport/internet/websocket/connection.go index 563ed242..d5dd7419 100644 --- a/transport/internet/websocket/connection.go +++ b/transport/internet/websocket/connection.go @@ -12,9 +12,7 @@ import ( "github.com/xtls/xray-core/common/serial" ) -var ( - _ buf.Writer = (*connection)(nil) -) +var _ buf.Writer = (*connection)(nil) // connection is a wrapper for net.Conn over WebSocket connection. type connection struct { diff --git a/transport/internet/websocket/dialer.go b/transport/internet/websocket/dialer.go index fd23177d..67f159b1 100644 --- a/transport/internet/websocket/dialer.go +++ b/transport/internet/websocket/dialer.go @@ -23,6 +23,7 @@ import ( //go:embed dialer.html var webpage []byte + var conns chan *websocket.Conn func init() { diff --git a/transport/internet/websocket/hub.go b/transport/internet/websocket/hub.go index 06ca2d28..4f377ebe 100644 --- a/transport/internet/websocket/hub.go +++ b/transport/internet/websocket/hub.go @@ -44,7 +44,7 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req } var extraReader io.Reader - var responseHeader = http.Header{} + responseHeader := http.Header{} if str := request.Header.Get("Sec-WebSocket-Protocol"); str != "" { if ed, err := base64.RawURLEncoding.DecodeString(replacer.Replace(str)); err == nil && len(ed) > 0 { extraReader = bytes.NewReader(ed) @@ -94,7 +94,7 @@ func ListenWS(ctx context.Context, address net.Address, port net.Port, streamSet } var listener net.Listener var err error - if port == net.Port(0) { //unix + if port == net.Port(0) { // unix listener, err = internet.ListenSystem(ctx, &net.UnixAddr{ Name: address.Domain(), Net: "unix", @@ -107,7 +107,7 @@ func ListenWS(ctx context.Context, address net.Address, port net.Port, streamSet if locker != nil { l.locker = locker.(*internet.FileLocker) } - } else { //tcp + } else { // tcp listener, err = internet.ListenSystem(ctx, &net.TCPAddr{ IP: address.IP(), Port: int(port), diff --git a/transport/internet/xtls/config.go b/transport/internet/xtls/config.go index 8a631eb8..fd1f3471 100644 --- a/transport/internet/xtls/config.go +++ b/transport/internet/xtls/config.go @@ -15,9 +15,7 @@ import ( "github.com/xtls/xray-core/transport/internet" ) -var ( - globalSessionCache = xtls.NewLRUClientSessionCache(128) -) +var globalSessionCache = xtls.NewLRUClientSessionCache(128) // ParseCertificate converts a cert.Certificate to Certificate. func ParseCertificate(c *cert.Certificate) *Certificate { diff --git a/transport/pipe/impl.go b/transport/pipe/impl.go index 4d0929f8..903c5fdf 100644 --- a/transport/pipe/impl.go +++ b/transport/pipe/impl.go @@ -40,8 +40,10 @@ type pipe struct { state state } -var errBufferFull = errors.New("buffer full") -var errSlowDown = errors.New("slow down") +var ( + errBufferFull = errors.New("buffer full") + errSlowDown = errors.New("slow down") +) func (p *pipe) getState(forRead bool) error { switch p.state {