diff --git a/app/dispatcher/default.go b/app/dispatcher/default.go index ef00f533e..f61dad717 100644 --- a/app/dispatcher/default.go +++ b/app/dispatcher/default.go @@ -26,9 +26,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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 e0fe494eb..d317233dc 100644 --- a/app/dns/dns_test.go +++ b/app/dns/dns_test.go @@ -22,8 +22,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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 4cd64e8d2..239e04c21 100644 --- a/app/dns/dnscommon.go +++ b/app/dns/dnscommon.go @@ -56,9 +56,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 72ff54fba..2d5dbc6cc 100644 --- a/app/dns/dnscommon_test.go +++ b/app/dns/dnscommon_test.go @@ -52,20 +52,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/log/log_creator.go b/app/log/log_creator.go index ceb5fd532..f52e65103 100644 --- a/app/log/log_creator.go +++ b/app/log/log_creator.go @@ -13,9 +13,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 30f82c20d..09574a976 100644 --- a/app/proxyman/inbound/worker.go +++ b/app/proxyman/inbound/worker.go @@ -465,6 +465,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 internet.Connection) { diff --git a/app/router/balancing.go b/app/router/balancing.go index 6b313eb09..86b11bca0 100644 --- a/app/router/balancing.go +++ b/app/router/balancing.go @@ -14,8 +14,7 @@ type BalancingStrategy interface { PickOutbound([]string) string } -type RandomStrategy struct { -} +type RandomStrategy struct{} func (s *RandomStrategy) PickOutbound(tags []string) string { n := len(tags) @@ -47,6 +46,7 @@ func (b *Balancer) PickOutbound() (string, error) { } return tag, nil } + func (b *Balancer) InjectContext(ctx context.Context) { if contextReceiver, ok := b.strategy.(extension.ContextReceiver); ok { contextReceiver.InjectContext(ctx) diff --git a/app/router/condition_geoip.go b/app/router/condition_geoip.go index ffa526acb..ca518153a 100644 --- a/app/router/condition_geoip.go +++ b/app/router/condition_geoip.go @@ -203,6 +203,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 1d4ed45c2..9a2f957a2 100644 --- a/app/router/condition_geoip_test.go +++ b/app/router/condition_geoip_test.go @@ -28,7 +28,7 @@ func init() { os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) @@ -98,7 +98,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/condition_test.go b/app/router/condition_test.go index 3a9ded4ba..1c5a59ac5 100644 --- a/app/router/condition_test.go +++ b/app/router/condition_test.go @@ -38,13 +38,13 @@ func init() { os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) } if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geositeBytes, err := common.FetchHTTPContent(geositeURL) common.Must(err) common.Must(filesystem.WriteFile(geositePath, geositeBytes)) @@ -369,6 +369,7 @@ func loadGeoSite(country string) ([]*router.Domain, error) { return nil, errors.New("country not found: " + country) } + func TestChinaSites(t *testing.T) { domains, err := loadGeoSite("CN") common.Must(err) diff --git a/common/buf/buffer_test.go b/common/buf/buffer_test.go index 7c7488652..a9fc09643 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/common.go b/common/common.go index 87db4b74d..c73d8f145 100644 --- a/common/common.go +++ b/common/common.go @@ -18,10 +18,8 @@ import ( //go:generate go run github.com/v2fly/v2ray-core/v4/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 69117ae93..da30d7454 100644 --- a/common/crypto/auth.go +++ b/common/crypto/auth.go @@ -295,7 +295,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 1303364c6..3dd841b7b 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 a0b59788e..654587768 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 0058bd439..a26d36828 100644 --- a/common/crypto/internal/chacha_core_gen.go +++ b/common/crypto/internal/chacha_core_gen.go @@ -55,7 +55,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 46d8f0912..871cb8c28 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 e41dda328..fc64a5237 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 56e7168b6..effc55863 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 72be4f40f..e15dffc04 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 714ba6de1..1e0bfdf12 100644 --- a/common/mux/client.go +++ b/common/mux/client.go @@ -143,6 +143,7 @@ func NewDialingWorkerFactory(ctx context.Context, proxy proxy.Outbound, dialer i ctx: ctx, } } + func (f *DialingWorkerFactory) Create() (*ClientWorker, error) { opts := []pipe.Option{pipe.WithSizeLimit(64 * 1024)} uplinkReader, upLinkWriter := pipe.New(opts...) @@ -152,7 +153,6 @@ func (f *DialingWorkerFactory) Create() (*ClientWorker, error) { Reader: downlinkReader, Writer: upLinkWriter, }, f.Strategy) - if err != nil { return nil, err } @@ -185,8 +185,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 19468794d..84dd952e0 100644 --- a/common/net/system.go +++ b/common/net/system.go @@ -2,60 +2,48 @@ 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 +const ( + IPv4len = net.IPv4len + IPv6len = net.IPv6len +) -type ListenConfig = net.ListenConfig +var ( + CIDRMask = net.CIDRMask + Dial = net.Dial + DialTCP = net.DialTCP + DialUDP = net.DialUDP + DialUnix = net.DialUnix + FileConn = net.FileConn + Listen = net.Listen + ListenTCP = net.ListenTCP + ListenUDP = net.ListenUDP + ListenUnix = net.ListenUnix + LookupIP = net.LookupIP + ParseIP = net.ParseIP + ResolveUDPAddr = net.ResolveUDPAddr + ResolveUnixAddr = net.ResolveUnixAddr + SplitHostPort = net.SplitHostPort +) -var Listen = net.Listen -var ListenTCP = net.ListenTCP -var ListenUDP = net.ListenUDP -var ListenUnix = net.ListenUnix - -var LookupIP = net.LookupIP - -var FileConn = net.FileConn - -// ParseIP is an alias of net.ParseIP -var ParseIP = net.ParseIP - -var SplitHostPort = net.SplitHostPort - -var CIDRMask = net.CIDRMask - -type Addr = net.Addr -type Conn = net.Conn -type PacketConn = net.PacketConn - -type TCPAddr = net.TCPAddr -type TCPConn = net.TCPConn - -type UDPAddr = net.UDPAddr -type UDPConn = net.UDPConn - -type UnixAddr = net.UnixAddr -type UnixConn = net.UnixConn - -// IP is an alias for net.IP. -type IP = net.IP -type IPMask = net.IPMask -type IPNet = net.IPNet - -const IPv4len = net.IPv4len -const IPv6len = net.IPv6len - -type Error = net.Error -type AddrError = net.AddrError - -type Dialer = net.Dialer -type Listener = net.Listener -type TCPListener = net.TCPListener -type UnixListener = net.UnixListener - -var ResolveUnixAddr = net.ResolveUnixAddr -var ResolveUDPAddr = net.ResolveUDPAddr - -type Resolver = net.Resolver +type ( + Addr = net.Addr + AddrError = net.AddrError + Conn = net.Conn + Dialer = net.Dialer + Error = net.Error + IP = net.IP + IPMask = net.IPMask + IPNet = net.IPNet + ListenConfig = net.ListenConfig + Listener = net.Listener + PacketConn = net.PacketConn + Resolver = net.Resolver + TCPAddr = net.TCPAddr + TCPConn = net.TCPConn + TCPListener = net.TCPListener + UDPAddr = net.UDPAddr + UDPConn = net.UDPConn + UnixAddr = net.UnixAddr + UnixConn = net.UnixConn + UnixListener = net.UnixListener +) diff --git a/common/platform/filesystem/file.go b/common/platform/filesystem/file.go index d171019d9..c3cfc989e 100644 --- a/common/platform/filesystem/file.go +++ b/common/platform/filesystem/file.go @@ -55,7 +55,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 c7a2184c7..248c10f67 100644 --- a/common/protocol/bittorrent/bittorrent.go +++ b/common/protocol/bittorrent/bittorrent.go @@ -6,8 +6,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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 a2ce82883..91271c6d0 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 2e3cd2b70..832e53df8 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 31cf07ec2..45e987254 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 a684f4309..2575e945e 100644 --- a/common/retry/retry_test.go +++ b/common/retry/retry_test.go @@ -9,9 +9,7 @@ import ( . "github.com/v2fly/v2ray-core/v4/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 e21364ecc..ab7c09bdd 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/matchers_test.go b/common/strmatcher/matchers_test.go index 03ae644de..8e549eae4 100644 --- a/common/strmatcher/matchers_test.go +++ b/common/strmatcher/matchers_test.go @@ -71,6 +71,7 @@ func TestMatcher(t *testing.T) { } } } + func TestACAutomaton(t *testing.T) { cases1 := []struct { pattern string @@ -122,7 +123,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 { @@ -155,7 +156,7 @@ func TestACAutomaton(t *testing.T) { mType: Substr, }, } - var ac = NewACAutomaton() + ac := NewACAutomaton() for _, test := range cases2Input { ac.Add(test.pattern, test.mType) } @@ -218,7 +219,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/strmatcher/mph_matcher.go b/common/strmatcher/mph_matcher.go index 21b98e764..3c10cb492 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/type.go b/common/type.go index 2cda62e9a..1f85b4ef1 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 64caba438..702dbef59 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 23413d3da..58497ec7e 100644 --- a/common/uuid/uuid.go +++ b/common/uuid/uuid.go @@ -9,9 +9,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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/infra/conf/blackhole.go b/infra/conf/blackhole.go index c1dd314c1..12223cdcc 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 29f4335a8..ef7b7c953 100644 --- a/infra/conf/dns_test.go +++ b/infra/conf/dns_test.go @@ -34,13 +34,13 @@ func init() { os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) } if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geositeBytes, err := common.FetchHTTPContent(geositeURL) common.Must(err) common.Must(filesystem.WriteFile(geositePath, geositeBytes)) diff --git a/infra/conf/geodata/geodata_test.go b/infra/conf/geodata/geodata_test.go index 74e515e8d..796b11eb9 100644 --- a/infra/conf/geodata/geodata_test.go +++ b/infra/conf/geodata/geodata_test.go @@ -31,13 +31,13 @@ func init() { os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) } if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geositeBytes, err := common.FetchHTTPContent(geositeURL) common.Must(err) common.Must(filesystem.WriteFile(geositePath, geositeBytes)) diff --git a/infra/conf/geodata/memconservative/decode_test.go b/infra/conf/geodata/memconservative/decode_test.go index 7f7031a40..64e66fb0e 100644 --- a/infra/conf/geodata/memconservative/decode_test.go +++ b/infra/conf/geodata/memconservative/decode_test.go @@ -29,13 +29,13 @@ func init() { os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) } if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geositeBytes, err := common.FetchHTTPContent(geositeURL) common.Must(err) common.Must(filesystem.WriteFile(geositePath, geositeBytes)) diff --git a/infra/conf/geodata/standard/standard.go b/infra/conf/geodata/standard/standard.go index 42e5894b6..566199ba5 100644 --- a/infra/conf/geodata/standard/standard.go +++ b/infra/conf/geodata/standard/standard.go @@ -50,8 +50,7 @@ func loadSite(filename, list string) ([]*router.Domain, error) { return nil, newError("list not found in ", filename, ": ", list) } -type standardLoader struct { -} +type standardLoader struct{} func (d standardLoader) LoadSite(filename, list string) ([]*router.Domain, error) { return loadSite(filename, list) diff --git a/infra/conf/http.go b/infra/conf/http.go index bdbaefdb5..27683b847 100644 --- a/infra/conf/http.go +++ b/infra/conf/http.go @@ -52,6 +52,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 cda56cfa6..74210c443 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 ab16800ff..9bacd23ca 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/rule/rule.go b/infra/conf/rule/rule.go index 4770b2c2a..f0cc2ef28 100644 --- a/infra/conf/rule/rule.go +++ b/infra/conf/rule/rule.go @@ -30,7 +30,7 @@ func parseDomainRule(ctx context.Context, domain string) ([]*router.Domain, erro return domains, nil } - var isExtDatFile = 0 + isExtDatFile := 0 { const prefix = "ext:" if strings.HasPrefix(domain, prefix) { @@ -141,7 +141,7 @@ func toCidrList(ctx context.Context, ips cfgcommon.StringList) ([]*router.GeoIP, continue } - var isExtDatFile = 0 + isExtDatFile := 0 { const prefix = "ext:" if strings.HasPrefix(ip, prefix) { diff --git a/infra/conf/rule/rule_test.go b/infra/conf/rule/rule_test.go index 671917255..c7dbab14b 100644 --- a/infra/conf/rule/rule_test.go +++ b/infra/conf/rule/rule_test.go @@ -29,7 +29,7 @@ func init() { os.Setenv("v2ray.location.asset", tempPath) if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) { - common.Must(os.MkdirAll(tempPath, 0755)) + common.Must(os.MkdirAll(tempPath, 0o755)) geoipBytes, err := common.FetchHTTPContent(geoipURL) common.Must(err) common.Must(filesystem.WriteFile(geoipPath, geoipBytes)) diff --git a/infra/conf/socks.go b/infra/conf/socks.go index ccf8d0825..5c3e3e5c6 100644 --- a/infra/conf/socks.go +++ b/infra/conf/socks.go @@ -71,6 +71,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/v2ray_test.go b/infra/conf/v2ray_test.go index 161d39c7e..ce358cfeb 100644 --- a/infra/conf/v2ray_test.go +++ b/infra/conf/v2ray_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/infra/conf/vmess.go b/infra/conf/vmess.go index c6a607fed..1f180182b 100644 --- a/infra/conf/vmess.go +++ b/infra/conf/vmess.go @@ -120,6 +120,7 @@ type VMessOutboundTarget struct { Port uint16 `json:"port"` Users []json.RawMessage `json:"users"` } + type VMessOutboundConfig struct { Receivers []*VMessOutboundTarget `json:"vnext"` } diff --git a/infra/control/cert.go b/infra/control/cert.go index 0690af850..9e0308106 100644 --- a/infra/control/cert.go +++ b/infra/control/cert.go @@ -33,8 +33,7 @@ type jsonCert struct { Key []string `json:"key"` } -type CertificateCommand struct { -} +type CertificateCommand struct{} func (c *CertificateCommand) Name() string { return "cert" diff --git a/infra/control/certchainhash.go b/infra/control/certchainhash.go index e30b7df27..1726ecc28 100644 --- a/infra/control/certchainhash.go +++ b/infra/control/certchainhash.go @@ -8,8 +8,7 @@ import ( v2tls "github.com/v2fly/v2ray-core/v4/transport/internet/tls" ) -type CertificateChainHashCommand struct { -} +type CertificateChainHashCommand struct{} func (c CertificateChainHashCommand) Name() string { return "certChainHash" diff --git a/main/confloader/confloader.go b/main/confloader/confloader.go index 24da1a0cb..01cb92339 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/proxy/blackhole/blackhole_test.go b/proxy/blackhole/blackhole_test.go index 0f48b3b36..c6b222868 100644 --- a/proxy/blackhole/blackhole_test.go +++ b/proxy/blackhole/blackhole_test.go @@ -20,7 +20,7 @@ func TestBlackHoleHTTPResponse(t *testing.T) { reader, writer := pipe.New(pipe.WithoutSizeLimit()) - var readerError = make(chan error) + readerError := make(chan error) var mb buf.MultiBuffer go func() { b, e := reader.ReadMultiBuffer() diff --git a/proxy/dns/dns_test.go b/proxy/dns/dns_test.go index 67f8c1e35..7b7a565fb 100644 --- a/proxy/dns/dns_test.go +++ b/proxy/dns/dns_test.go @@ -24,8 +24,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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 ae0085f37..30df032c6 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 dc4b9ece4..99b138d54 100644 --- a/proxy/http/server.go +++ b/proxy/http/server.go @@ -203,7 +203,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 707f7f606..b7347e158 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 bbd28451a..fabee92ee 100644 --- a/proxy/mtproto/client.go +++ b/proxy/mtproto/client.go @@ -13,8 +13,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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 8a3b7161b..252523f06 100644 --- a/proxy/mtproto/server.go +++ b/proxy/mtproto/server.go @@ -21,15 +21,13 @@ import ( "github.com/v2fly/v2ray-core/v4/transport/internet" ) -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 @@ -65,8 +63,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) { @@ -145,7 +145,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn internet 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 04f51b0d4..a0f3f1b51 100644 --- a/proxy/shadowsocks/client.go +++ b/proxy/shadowsocks/client.go @@ -127,7 +127,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) } @@ -164,7 +164,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/server.go b/proxy/shadowsocks/server.go index 86905c1cd..983c91b88 100644 --- a/proxy/shadowsocks/server.go +++ b/proxy/shadowsocks/server.go @@ -222,7 +222,7 @@ func (s *Server) handleConnection(ctx context.Context, conn internet.Connection, 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 69b568f35..ae2915cf5 100644 --- a/proxy/socks/client.go +++ b/proxy/socks/client.go @@ -149,7 +149,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 9c45219c5..ec6d25ccb 100644 --- a/proxy/socks/server.go +++ b/proxy/socks/server.go @@ -177,7 +177,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) @@ -220,7 +220,6 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn internet.Connection, 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 8be3b93f2..5805310ba 100644 --- a/proxy/trojan/client.go +++ b/proxy/trojan/client.go @@ -131,7 +131,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/server.go b/proxy/trojan/server.go index eae605c19..88ca9c913 100644 --- a/proxy/trojan/server.go +++ b/proxy/trojan/server.go @@ -275,7 +275,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/vmess/aead/encrypt.go b/proxy/vmess/aead/encrypt.go index e31e52f9c..84b982f93 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 b18cfcce2..5f8e33cfe 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 d57a31be7..da02c3d7a 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 ea59401ef..f1f228f06 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 8883f9d80..da9e5f29f 100644 --- a/proxy/vmess/inbound/inbound.go +++ b/proxy/vmess/inbound/inbound.go @@ -306,7 +306,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection i 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) @@ -352,15 +352,17 @@ func (h *Handler) generateCommand(ctx context.Context, request *protocol.Request return nil } -var aeadForced = false -var aeadForced2022 = false +var ( + aeadForced = false + aeadForced2022 = false +) func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 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 c41f767ce..c4d26a6a8 100644 --- a/proxy/vmess/outbound/outbound.go +++ b/proxy/vmess/outbound/outbound.go @@ -175,7 +175,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/servers/tcp/tcp.go b/testing/servers/tcp/tcp.go index f841d6e79..c04fcfac7 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 aa2f900bb..16d1e2ec0 100644 --- a/transport/internet/dialer.go +++ b/transport/internet/dialer.go @@ -20,9 +20,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) (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 { diff --git a/transport/internet/domainsocket/config.go b/transport/internet/domainsocket/config.go index 97ca05745..8e77f2b45 100644 --- a/transport/internet/domainsocket/config.go +++ b/transport/internet/domainsocket/config.go @@ -8,8 +8,10 @@ import ( "github.com/v2fly/v2ray-core/v4/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 17d543127..ae89176b5 100644 --- a/transport/internet/grpc/dial.go +++ b/transport/internet/grpc/dial.go @@ -44,14 +44,13 @@ func dialgRPC(ctx context.Context, dest net.Destination, streamSettings *interne grpcSettings := streamSettings.ProtocolSettings.(*Config) config := tls.ConfigFromStreamSettings(streamSettings) - var dialOption = grpc.WithInsecure() + dialOption := grpc.WithInsecure() if config != nil { dialOption = grpc.WithTransportCredentials(credentials.NewTLS(config.GetTLSConfig())) } conn, err := getGrpcClient(ctx, dest, dialOption) - if err != nil { return nil, newError("Cannot dial grpc").Base(err) } diff --git a/transport/internet/kcp/dialer.go b/transport/internet/kcp/dialer.go index 1abcae402..b843b5664 100644 --- a/transport/internet/kcp/dialer.go +++ b/transport/internet/kcp/dialer.go @@ -15,9 +15,7 @@ import ( "github.com/v2fly/v2ray-core/v4/transport/internet/tls" ) -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 f686ec015..567f68231 100644 --- a/transport/internet/quic/hub.go +++ b/transport/internet/quic/hub.go @@ -99,7 +99,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 00d2e0ac7..fcb7bae4e 100644 --- a/transport/internet/quic/quic.go +++ b/transport/internet/quic/quic.go @@ -15,8 +15,10 @@ import ( // // -const protocolName = "quic" -const internalDomain = "quic.internal.v2fly.org" +const ( + protocolName = "quic" + internalDomain = "quic.internal.v2fly.org" +) func init() { common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} { diff --git a/transport/internet/sockopt_freebsd.go b/transport/internet/sockopt_freebsd.go index 48c5eda69..50834cdd2 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 f84900892..0f8d475d8 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.Tfo); err != nil { return err } - } return nil diff --git a/transport/internet/system_dialer.go b/transport/internet/system_dialer.go index bb187dfb3..eb6ffffa7 100644 --- a/transport/internet/system_dialer.go +++ b/transport/internet/system_dialer.go @@ -9,9 +9,7 @@ import ( "github.com/v2fly/v2ray-core/v4/common/session" ) -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 4aff71758..a13a36768 100644 --- a/transport/internet/system_listener.go +++ b/transport/internet/system_listener.go @@ -11,9 +11,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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 3231f288e..478a6a819 100644 --- a/transport/internet/tcp_hub.go +++ b/transport/internet/tcp_hub.go @@ -6,9 +6,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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 { @@ -48,6 +46,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 aa30a2c53..f11ba8d13 100644 --- a/transport/internet/tls/config.go +++ b/transport/internet/tls/config.go @@ -16,9 +16,7 @@ import ( "github.com/v2fly/v2ray-core/v4/transport/internet" ) -var ( - globalSessionCache = tls.NewLRUClientSessionCache(128) -) +var globalSessionCache = tls.NewLRUClientSessionCache(128) const exp8357 = "experiment:8357" diff --git a/transport/internet/tls/tls.go b/transport/internet/tls/tls.go index 9b62600c7..14c5c616d 100644 --- a/transport/internet/tls/tls.go +++ b/transport/internet/tls/tls.go @@ -11,9 +11,7 @@ import ( //go:generate go run github.com/v2fly/v2ray-core/v4/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 d150c8d52..1ed28292e 100644 --- a/transport/internet/websocket/connection.go +++ b/transport/internet/websocket/connection.go @@ -15,9 +15,7 @@ import ( "github.com/v2fly/v2ray-core/v4/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/hub.go b/transport/internet/websocket/hub.go index 2472ab539..a2822144c 100644 --- a/transport/internet/websocket/hub.go +++ b/transport/internet/websocket/hub.go @@ -142,8 +142,8 @@ func ListenWS(ctx context.Context, address net.Address, port net.Port, streamSet } l.listener = listener - var useEarlyData = false - var earlyDataHeaderName = "" + useEarlyData := false + earlyDataHeaderName := "" if wsSettings.MaxEarlyData != 0 { useEarlyData = true earlyDataHeaderName = wsSettings.EarlyDataHeaderName diff --git a/transport/pipe/impl.go b/transport/pipe/impl.go index 4d711f045..797b3b968 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 { diff --git a/v2ray.go b/v2ray.go index 6a0278f08..51ba874f5 100644 --- a/v2ray.go +++ b/v2ray.go @@ -159,7 +159,7 @@ func RequireFeatures(ctx context.Context, callback interface{}) error { // The instance is not started at this point. // To ensure V2Ray 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 {