diff --git a/.github/linters/.golangci.yml b/.github/linters/.golangci.yml index 9e4dcdf33f..74b60dcb98 100644 --- a/.github/linters/.golangci.yml +++ b/.github/linters/.golangci.yml @@ -5,6 +5,10 @@ run: issues: new: true + exclude-rules: + - path: _test\.go + linters: + - scopelint linters: enable: @@ -20,8 +24,6 @@ linters: - ineffassign - misspell - nakedret - - noctx - - nolintlint - rowserrcheck - scopelint - staticcheck diff --git a/app/router/command/command.go b/app/router/command/command.go index fc467fa767..6d777829dd 100644 --- a/app/router/command/command.go +++ b/app/router/command/command.go @@ -9,7 +9,6 @@ import ( "time" "google.golang.org/grpc" - "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/features/routing" @@ -39,7 +38,7 @@ func (s *routingServer) TestRoute(ctx context.Context, request *TestRouteRequest return nil, err } if request.PublishResult && s.routingStats != nil { - ctx, _ := context.WithTimeout(context.Background(), 4*time.Second) + ctx, _ := context.WithTimeout(context.Background(), 4*time.Second) // nolint: govet s.routingStats.Publish(ctx, route) } return AsProtobufMessage(request.FieldSelectors)(route), nil diff --git a/app/router/condition.go b/app/router/condition.go index c77fc657e3..ac6984febc 100644 --- a/app/router/condition.go +++ b/app/router/condition.go @@ -7,7 +7,6 @@ import ( "go.starlark.net/starlark" "go.starlark.net/syntax" - "v2ray.com/core/common/net" "v2ray.com/core/common/strmatcher" "v2ray.com/core/features/routing" @@ -154,9 +153,8 @@ func NewPortMatcher(list *net.PortList, onSource bool) *PortMatcher { func (v *PortMatcher) Apply(ctx routing.Context) bool { if v.onSource { return v.port.Contains(ctx.GetSourcePort()) - } else { - return v.port.Contains(ctx.GetTargetPort()) } + return v.port.Contains(ctx.GetTargetPort()) } type NetworkMatcher struct { diff --git a/common/buf/buffer.go b/common/buf/buffer.go index a6cd4bbb57..83db8ea334 100644 --- a/common/buf/buffer.go +++ b/common/buf/buffer.go @@ -46,7 +46,7 @@ func (b *Buffer) Release() { p := b.v b.v = nil b.Clear() - pool.Put(p) + pool.Put(p) // nolint: staticcheck } // Clear clears the content of the buffer, results an empty buffer with diff --git a/common/bytespool/pool.go b/common/bytespool/pool.go index 9b0e710e55..a94935b19a 100644 --- a/common/bytespool/pool.go +++ b/common/bytespool/pool.go @@ -65,7 +65,7 @@ func Free(b []byte) { b = b[0:cap(b)] for i := numPools - 1; i >= 0; i-- { if size >= poolSize[i] { - pool[i].Put(b) + pool[i].Put(b) // nolint: staticcheck return } } diff --git a/common/net/destination.go b/common/net/destination.go index 055395e9d2..7ced9979dc 100644 --- a/common/net/destination.go +++ b/common/net/destination.go @@ -32,13 +32,15 @@ func ParseDestination(dest string) (Destination, error) { Address: AnyIP, Port: Port(0), } - if strings.HasPrefix(dest, "tcp:") { + + switch { + case strings.HasPrefix(dest, "tcp:"): d.Network = Network_TCP dest = dest[4:] - } else if strings.HasPrefix(dest, "udp:") { + case strings.HasPrefix(dest, "udp:"): d.Network = Network_UDP dest = dest[4:] - } else if strings.HasPrefix(dest, "unix:") { + case strings.HasPrefix(dest, "unix:"): d = UnixDestination(DomainAddress(dest[5:])) return d, nil } diff --git a/functions.go b/functions.go index ee4fab81e0..a2fc42f06f 100644 --- a/functions.go +++ b/functions.go @@ -14,9 +14,9 @@ import ( // CreateObject creates a new object based on the given V2Ray instance and config. The V2Ray instance may be nil. func CreateObject(v *Instance, config interface{}) (interface{}, error) { - ctx := v.ctx + var ctx context.Context if v != nil { - ctx = context.WithValue(ctx, v2rayKey, v) + ctx = context.WithValue(v.ctx, v2rayKey, v) } return common.CreateObject(ctx, config) } diff --git a/infra/conf/dns.go b/infra/conf/dns.go index 1487f3fd75..dc2b68ba5c 100644 --- a/infra/conf/dns.go +++ b/infra/conf/dns.go @@ -119,10 +119,9 @@ func getHostMapping(addr *Address) *dns.Config_HostMapping { return &dns.Config_HostMapping{ Ip: [][]byte{[]byte(addr.IP())}, } - } else { - return &dns.Config_HostMapping{ - ProxiedDomain: addr.Domain(), - } + } + return &dns.Config_HostMapping{ + ProxiedDomain: addr.Domain(), } } diff --git a/infra/conf/v2ray.go b/infra/conf/v2ray.go index 576e504376..5ae3aa3bb9 100644 --- a/infra/conf/v2ray.go +++ b/infra/conf/v2ray.go @@ -166,19 +166,20 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) { receiverSettings.Listen = c.ListenOn.Build() listenDS := c.ListenOn.Family().IsDomain() && (c.ListenOn.Domain()[0] == '/' || c.ListenOn.Domain()[0] == '@') listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost") - if listenIP { + switch { + case listenIP: // Listen on specific IP, must set PortRange if c.PortRange == nil { return nil, newError("Listen on specific ip without port in InboundDetour.") } // Listen on IP:Port receiverSettings.PortRange = c.PortRange.Build() - } else if listenDS { + case listenDS: if c.PortRange != nil { // Listen on Unix Domain Socket, PortRange should be nil receiverSettings.PortRange = nil } - } else { + default: return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain()) } } diff --git a/main/main.go b/main/main.go index de6f3890da..d25ae6647d 100644 --- a/main/main.go +++ b/main/main.go @@ -31,8 +31,7 @@ var ( /* We have to do this here because Golang's Test will also need to parse flag, before * main func in this file is run. */ - _ = func() error { - + _ = func() error { // nolint: unparam flag.Var(&configFiles, "config", "Config file for V2Ray. Multiple assign is accepted (only json). Latter ones overrides the former ones.") flag.Var(&configFiles, "c", "Short alias of -config") flag.StringVar(&configDir, "confdir", "", "A dir with multiple json config") @@ -66,7 +65,7 @@ func readConfDir(dirPath string) { } } -func getConfigFilePath() (cmdarg.Arg, error) { +func getConfigFilePath() cmdarg.Arg { if dirExists(configDir) { log.Println("Using confdir from arg:", configDir) readConfDir(configDir) @@ -76,24 +75,24 @@ func getConfigFilePath() (cmdarg.Arg, error) { } if len(configFiles) > 0 { - return configFiles, nil + return configFiles } if workingDir, err := os.Getwd(); err == nil { configFile := filepath.Join(workingDir, "config.json") if fileExists(configFile) { log.Println("Using default config: ", configFile) - return cmdarg.Arg{configFile}, nil + return cmdarg.Arg{configFile} } } if configFile := platform.GetConfigurationPath(); fileExists(configFile) { log.Println("Using config from env: ", configFile) - return cmdarg.Arg{configFile}, nil + return cmdarg.Arg{configFile} } log.Println("Using config from STDIN") - return cmdarg.Arg{"stdin:"}, nil + return cmdarg.Arg{"stdin:"} } func GetConfigFormat() string { @@ -106,10 +105,7 @@ func GetConfigFormat() string { } func startV2Ray() (core.Server, error) { - configFiles, err := getConfigFilePath() - if err != nil { - return nil, err - } + configFiles := getConfigFilePath() config, err := core.LoadConfig(GetConfigFormat(), configFiles[0], configFiles) if err != nil { diff --git a/proxy/blackhole/config_test.go b/proxy/blackhole/config_test.go index d67ac87fe3..42bf0f0dcb 100644 --- a/proxy/blackhole/config_test.go +++ b/proxy/blackhole/config_test.go @@ -19,6 +19,7 @@ func TestHTTPResponse(t *testing.T) { reader := bufio.NewReader(buffer) response, err := http.ReadResponse(reader, nil) common.Must(err) + defer response.Body.Close() if response.StatusCode != 403 { t.Error("expected status code 403, but got ", response.StatusCode) diff --git a/proxy/dns/dns_test.go b/proxy/dns/dns_test.go index 95833d6819..aebfb01c58 100644 --- a/proxy/dns/dns_test.go +++ b/proxy/dns/dns_test.go @@ -7,7 +7,6 @@ import ( "github.com/google/go-cmp/cmp" "github.com/miekg/dns" - "v2ray.com/core" "v2ray.com/core/app/dispatcher" dnsapp "v2ray.com/core/app/dns" diff --git a/proxy/dokodemo/dokodemo.go b/proxy/dokodemo/dokodemo.go index 9185a597fe..a124924e4f 100644 --- a/proxy/dokodemo/dokodemo.go +++ b/proxy/dokodemo/dokodemo.go @@ -25,7 +25,7 @@ import ( func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { - d := new(DokodemoDoor) + d := new(Door) err := core.RequireFeatures(ctx, func(pm policy.Manager) error { return d.Init(config.(*Config), pm, session.SockoptFromContext(ctx)) }) @@ -33,7 +33,7 @@ func init() { })) } -type DokodemoDoor struct { +type Door struct { policyManager policy.Manager config *Config address net.Address @@ -41,8 +41,8 @@ type DokodemoDoor struct { sockopt *session.Sockopt } -// Init initializes the DokodemoDoor instance with necessary parameters. -func (d *DokodemoDoor) Init(config *Config, pm policy.Manager, sockopt *session.Sockopt) error { +// Init initializes the Door instance with necessary parameters. +func (d *Door) Init(config *Config, pm policy.Manager, sockopt *session.Sockopt) error { if (config.NetworkList == nil || len(config.NetworkList.Network) == 0) && len(config.Networks) == 0 { return newError("no network specified") } @@ -56,7 +56,7 @@ func (d *DokodemoDoor) Init(config *Config, pm policy.Manager, sockopt *session. } // Network implements proxy.Inbound. -func (d *DokodemoDoor) Network() []net.Network { +func (d *Door) Network() []net.Network { if len(d.config.Networks) > 0 { return d.config.Networks } @@ -64,7 +64,7 @@ func (d *DokodemoDoor) Network() []net.Network { return d.config.NetworkList.Network } -func (d *DokodemoDoor) policy() policy.Session { +func (d *Door) policy() policy.Session { config := d.config p := d.policyManager.ForLevel(config.UserLevel) if config.Timeout > 0 && config.UserLevel == 0 { @@ -78,7 +78,7 @@ type hasHandshakeAddress interface { } // Process implements proxy.Inbound. -func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error { +func (d *Door) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error { newError("processing connection from: ", conn.RemoteAddr()).AtDebug().WriteToLog(session.ExportIDToError(ctx)) dest := net.Destination{ Network: network, diff --git a/proxy/http/client.go b/proxy/http/client.go index 79a2bd608e..51a2b6de49 100644 --- a/proxy/http/client.go +++ b/proxy/http/client.go @@ -12,7 +12,6 @@ import ( "sync" "golang.org/x/net/http2" - "v2ray.com/core" "v2ray.com/core/common" "v2ray.com/core/common/buf" @@ -165,7 +164,7 @@ func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, u return nil, err } - resp, err := http.ReadResponse(bufio.NewReader(rawConn), req) + resp, err := http.ReadResponse(bufio.NewReader(rawConn), req) // nolint: bodyclose if err != nil { rawConn.Close() return nil, err @@ -191,7 +190,7 @@ func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, u wg.Done() }() - resp, err := h2clientConn.RoundTrip(req) + resp, err := h2clientConn.RoundTrip(req) // nolint: bodyclose if err != nil { rawConn.Close() return nil, err diff --git a/proxy/http/server.go b/proxy/http/server.go index 9f6b88590b..5cf5c5ed4d 100644 --- a/proxy/http/server.go +++ b/proxy/http/server.go @@ -279,7 +279,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri responseDone := func() error { responseReader := bufio.NewReaderSize(&buf.BufferedReader{Reader: link.Reader}, buf.Size) - response, err := http.ReadResponse(responseReader, request) + response, err := http.ReadResponse(responseReader, request) // nolint: bodyclose if err == nil { http_proto.RemoveHopByHopHeaders(response.Header) if response.ContentLength >= 0 { diff --git a/proxy/trojan/protocol.go b/proxy/trojan/protocol.go index 0c5386d422..3b21975d52 100644 --- a/proxy/trojan/protocol.go +++ b/proxy/trojan/protocol.go @@ -128,7 +128,7 @@ func (w *PacketWriter) WriteMultiBufferWithMetadata(mb buf.MultiBuffer, dest net return nil } -func (w *PacketWriter) writePacket(payload []byte, dest net.Destination) (int, error) { +func (w *PacketWriter) writePacket(payload []byte, dest net.Destination) (int, error) { // nolint: unparam buffer := buf.StackNew() defer buffer.Release() diff --git a/proxy/trojan/trojan.go b/proxy/trojan/trojan.go index 4639b7d9b5..73b3154fb1 100644 --- a/proxy/trojan/trojan.go +++ b/proxy/trojan/trojan.go @@ -1,5 +1 @@ package trojan - -const ( - muxCoolAddress = "v1.mux.cool" -) diff --git a/proxy/vless/encoding/addons.go b/proxy/vless/encoding/addons.go index b37b275f80..266fa51f2e 100644 --- a/proxy/vless/encoding/addons.go +++ b/proxy/vless/encoding/addons.go @@ -6,20 +6,15 @@ import ( "io" "github.com/golang/protobuf/proto" - "v2ray.com/core/common/buf" "v2ray.com/core/common/protocol" ) // EncodeHeaderAddons Add addons byte to the header func EncodeHeaderAddons(buffer *buf.Buffer, addons *Addons) error { - switch addons.Flow { - default: - if err := buffer.WriteByte(0); err != nil { - return newError("failed to write addons protobuf length").Base(err) - } + if err := buffer.WriteByte(0); err != nil { + return newError("failed to write addons protobuf length").Base(err) } - return nil } @@ -39,11 +34,6 @@ func DecodeHeaderAddons(buffer *buf.Buffer, reader io.Reader) (*Addons, error) { if err := proto.Unmarshal(buffer.Bytes(), addons); err != nil { return nil, newError("failed to unmarshal addons protobuf value").Base(err) } - - // Verification. - switch addons.Flow { - default: - } } return addons, nil @@ -51,22 +41,16 @@ func DecodeHeaderAddons(buffer *buf.Buffer, reader io.Reader) (*Addons, error) { // EncodeBodyAddons returns a Writer that auto-encrypt content written by caller. func EncodeBodyAddons(writer io.Writer, request *protocol.RequestHeader, addons *Addons) buf.Writer { - switch addons.Flow { - default: - if request.Command == protocol.RequestCommandUDP { - return NewMultiLengthPacketWriter(writer.(buf.Writer)) - } + if request.Command == protocol.RequestCommandUDP { + return NewMultiLengthPacketWriter(writer.(buf.Writer)) } return buf.NewWriter(writer) } // DecodeBodyAddons returns a Reader from which caller can fetch decrypted body. func DecodeBodyAddons(reader io.Reader, request *protocol.RequestHeader, addons *Addons) buf.Reader { - switch addons.Flow { - default: - if request.Command == protocol.RequestCommandUDP { - return NewLengthPacketReader(reader) - } + if request.Command == protocol.RequestCommandUDP { + return NewLengthPacketReader(reader) } return buf.NewReader(reader) } diff --git a/proxy/vless/encoding/encoding.go b/proxy/vless/encoding/encoding.go index 3d09c5b207..81a8d512ae 100644 --- a/proxy/vless/encoding/encoding.go +++ b/proxy/vless/encoding/encoding.go @@ -6,6 +6,7 @@ package encoding import ( "io" + "v2ray.com/core/common/buf" "v2ray.com/core/common/net" "v2ray.com/core/common/protocol" diff --git a/proxy/vless/encoding/encoding_test.go b/proxy/vless/encoding/encoding_test.go index 5366b84d21..496112af55 100644 --- a/proxy/vless/encoding/encoding_test.go +++ b/proxy/vless/encoding/encoding_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "v2ray.com/core/common" "v2ray.com/core/common/buf" "v2ray.com/core/common/net" diff --git a/proxy/vless/inbound/inbound.go b/proxy/vless/inbound/inbound.go index 4534b3bd2d..d293c5ce31 100644 --- a/proxy/vless/inbound/inbound.go +++ b/proxy/vless/inbound/inbound.go @@ -421,11 +421,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection i return newError("failed to transfer response payload").Base(err).AtInfo() } - // Indicates the end of response payload. - switch responseAddons.Flow { - default: - } - return nil } diff --git a/proxy/vless/outbound/outbound.go b/proxy/vless/outbound/outbound.go index d331702ff8..aee8f1c286 100644 --- a/proxy/vless/outbound/outbound.go +++ b/proxy/vless/outbound/outbound.go @@ -7,7 +7,6 @@ package outbound import ( "context" "time" - "v2ray.com/core/proxy/vless" "v2ray.com/core" "v2ray.com/core/common" @@ -19,6 +18,7 @@ import ( "v2ray.com/core/common/signal" "v2ray.com/core/common/task" "v2ray.com/core/features/policy" + "v2ray.com/core/proxy/vless" "v2ray.com/core/proxy/vless/encoding" "v2ray.com/core/transport" "v2ray.com/core/transport/internet" @@ -76,12 +76,6 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } defer conn.Close() - iConn := conn - statConn, ok := iConn.(*internet.StatCouterConnection) - if ok { - iConn = statConn.Connection - } - outbound := session.OutboundFromContext(ctx) if outbound == nil || !outbound.Target.IsValid() { return newError("target not specified").AtError() @@ -143,11 +137,6 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte return newError("failed to transfer request payload").Base(err).AtInfo() } - // Indicates the end of request payload. - switch requestAddons.Flow { - default: - } - return nil } diff --git a/proxy/vmess/encoding/client.go b/proxy/vmess/encoding/client.go index 3e4ad04743..133ea2d17a 100644 --- a/proxy/vmess/encoding/client.go +++ b/proxy/vmess/encoding/client.go @@ -207,7 +207,7 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon } if decryptedResponseHeaderLengthBinaryBuffer, err := aeadResponseHeaderLengthEncryptionAEAD.Open(nil, aeadResponseHeaderLengthEncryptionIV, aeadEncryptedResponseHeaderLength[:], nil); err != nil { return nil, newError("Failed To Decrypt Length").Base(err) - } else { + } else { // nolint: golint common.Must(binary.Read(bytes.NewReader(decryptedResponseHeaderLengthBinaryBuffer), binary.BigEndian, &decryptedResponseHeaderLengthBinaryDeserializeBuffer)) decryptedResponseHeaderLength = int(decryptedResponseHeaderLengthBinaryDeserializeBuffer) } @@ -226,7 +226,7 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon if decryptedResponseHeaderBuffer, err := aeadResponseHeaderPayloadEncryptionAEAD.Open(nil, aeadResponseHeaderPayloadEncryptionIV, encryptedResponseHeaderBuffer, nil); err != nil { return nil, newError("Failed To Decrypt Payload").Base(err) - } else { + } else { // nolint: golint c.responseReader = bytes.NewReader(decryptedResponseHeaderBuffer) } } diff --git a/proxy/vmess/encoding/server.go b/proxy/vmess/encoding/server.go index 88876625ea..c33dff982d 100644 --- a/proxy/vmess/encoding/server.go +++ b/proxy/vmess/encoding/server.go @@ -179,9 +179,8 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.Request if shouldDrain { readSizeRemain -= bytesRead return nil, drainConnection(newError("AEAD read failed").Base(errorReason)) - } else { - return nil, drainConnection(newError("AEAD read failed, drain skipped").Base(errorReason)) } + return nil, drainConnection(newError("AEAD read failed, drain skipped").Base(errorReason)) } decryptor = bytes.NewReader(aeadData) s.isAEADRequest = true @@ -226,9 +225,8 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.Request return nil, drainConnection(newError("duplicated session id, possibly under replay attack, and failed to taint userHash").Base(drainErr)) } return nil, drainConnection(newError("duplicated session id, possibly under replay attack, userHash tainted")) - } else { - return nil, newError("duplicated session id, possibly under replay attack, but this is a AEAD request") } + return nil, newError("duplicated session id, possibly under replay attack, but this is a AEAD request") } s.responseHeader = buffer.Byte(33) // 1 byte @@ -288,9 +286,8 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.Request } // It is possible that we are under attack described in https://github.com/v2ray/v2ray-core/issues/2523 return nil, drainConnection(Autherr) - } else { - return nil, newError("invalid auth, but this is a AEAD request") } + return nil, newError("invalid auth, but this is a AEAD request") } if request.Address == nil { diff --git a/testing/scenarios/command_test.go b/testing/scenarios/command_test.go index daf48244c6..ed67295fc1 100644 --- a/testing/scenarios/command_test.go +++ b/testing/scenarios/command_test.go @@ -11,7 +11,6 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "google.golang.org/grpc" - "v2ray.com/core" "v2ray.com/core/app/commander" "v2ray.com/core/app/policy" diff --git a/testing/scenarios/common.go b/testing/scenarios/common.go index d3ba1e863e..9ae6a788b6 100644 --- a/testing/scenarios/common.go +++ b/testing/scenarios/common.go @@ -164,7 +164,7 @@ func testTCPConn(port net.Port, payloadSize int, timeout time.Duration) func() e } } -func testUDPConn(port net.Port, payloadSize int, timeout time.Duration) func() error { +func testUDPConn(port net.Port, payloadSize int, timeout time.Duration) func() error { // nolint: unparam return func() error { conn, err := net.DialUDP("udp", nil, &net.UDPAddr{ IP: []byte{127, 0, 0, 1}, diff --git a/testing/scenarios/dokodemo_test.go b/testing/scenarios/dokodemo_test.go index e48117ea7f..5031b49c4c 100644 --- a/testing/scenarios/dokodemo_test.go +++ b/testing/scenarios/dokodemo_test.go @@ -5,7 +5,6 @@ import ( "time" "golang.org/x/sync/errgroup" - "v2ray.com/core" "v2ray.com/core/app/log" "v2ray.com/core/app/proxyman" diff --git a/testing/scenarios/feature_test.go b/testing/scenarios/feature_test.go index 5b09eb806b..a03593f423 100644 --- a/testing/scenarios/feature_test.go +++ b/testing/scenarios/feature_test.go @@ -638,6 +638,7 @@ func TestDomainSniffing(t *testing.T) { resp, err := client.Get("https://www.github.com/") common.Must(err) + defer resp.Body.Close() if resp.StatusCode != 200 { t.Error("unexpected status code: ", resp.StatusCode) } diff --git a/testing/scenarios/http_test.go b/testing/scenarios/http_test.go index aca61c41fd..17b21a5271 100644 --- a/testing/scenarios/http_test.go +++ b/testing/scenarios/http_test.go @@ -12,7 +12,6 @@ import ( "time" "github.com/google/go-cmp/cmp" - "v2ray.com/core" "v2ray.com/core/app/proxyman" "v2ray.com/core/common" @@ -70,6 +69,7 @@ func TestHttpConformance(t *testing.T) { resp, err := client.Get("http://127.0.0.1:" + httpServerPort.String()) common.Must(err) + defer resp.Body.Close() if resp.StatusCode != 200 { t.Fatal("status: ", resp.StatusCode) } @@ -129,8 +129,9 @@ func TestHttpError(t *testing.T) { Transport: transport, } - resp, err := client.Get("http://127.0.0.1:" + dest.Port.String()) + resp, err := client.Get("http://127.0.0.1:" + dest.Port.String()) // nolint: bodyclose common.Must(err) + defer resp.Body.Close() if resp.StatusCode != 503 { t.Error("status: ", resp.StatusCode) } @@ -189,6 +190,7 @@ func TestHTTPConnectMethod(t *testing.T) { resp, err := client.Do(req) common.Must(err) + defer resp.Body.Close() if resp.StatusCode != 200 { t.Fatal("status: ", resp.StatusCode) } @@ -263,6 +265,7 @@ func TestHttpPost(t *testing.T) { resp, err := client.Post("http://127.0.0.1:"+httpServerPort.String()+"/testpost", "application/x-www-form-urlencoded", bytes.NewReader(payload)) common.Must(err) + defer resp.Body.Close() if resp.StatusCode != 200 { t.Fatal("status: ", resp.StatusCode) } @@ -331,6 +334,7 @@ func TestHttpBasicAuth(t *testing.T) { { resp, err := client.Get("http://127.0.0.1:" + httpServerPort.String()) common.Must(err) + defer resp.Body.Close() if resp.StatusCode != 407 { t.Fatal("status: ", resp.StatusCode) } @@ -344,6 +348,7 @@ func TestHttpBasicAuth(t *testing.T) { setProxyBasicAuth(req, "a", "c") resp, err := client.Do(req) common.Must(err) + defer resp.Body.Close() if resp.StatusCode != 407 { t.Fatal("status: ", resp.StatusCode) } @@ -357,6 +362,7 @@ func TestHttpBasicAuth(t *testing.T) { setProxyBasicAuth(req, "a", "b") resp, err := client.Do(req) common.Must(err) + defer resp.Body.Close() if resp.StatusCode != 200 { t.Fatal("status: ", resp.StatusCode) } diff --git a/transport/internet/headers/http/http.go b/transport/internet/headers/http/http.go index f00e11b946..e50495ad5f 100644 --- a/transport/internet/headers/http/http.go +++ b/transport/internet/headers/http/http.go @@ -112,7 +112,7 @@ func (h *HeaderReader) Read(reader io.Reader) (*buf.Buffer, error) { // Parse the request if req, err := readRequest(bufio.NewReader(bytes.NewReader(headerBuf.Bytes())), false); err != nil { return nil, err - } else { + } else { // nolint: golint h.req = req } diff --git a/transport/internet/headers/noop/noop.go b/transport/internet/headers/noop/noop.go index e622b35efe..eb5cd1110f 100644 --- a/transport/internet/headers/noop/noop.go +++ b/transport/internet/headers/noop/noop.go @@ -7,34 +7,34 @@ import ( "v2ray.com/core/common" ) -type NoOpHeader struct{} +type Header struct{} -func (NoOpHeader) Size() int32 { +func (Header) Size() int32 { return 0 } // Serialize implements PacketHeader. -func (NoOpHeader) Serialize([]byte) {} +func (Header) Serialize([]byte) {} -func NewNoOpHeader(context.Context, interface{}) (interface{}, error) { - return NoOpHeader{}, nil +func NewHeader(context.Context, interface{}) (interface{}, error) { + return Header{}, nil } -type NoOpConnectionHeader struct{} +type ConnectionHeader struct{} -func (NoOpConnectionHeader) Client(conn net.Conn) net.Conn { +func (ConnectionHeader) Client(conn net.Conn) net.Conn { return conn } -func (NoOpConnectionHeader) Server(conn net.Conn) net.Conn { +func (ConnectionHeader) Server(conn net.Conn) net.Conn { return conn } -func NewNoOpConnectionHeader(context.Context, interface{}) (interface{}, error) { - return NoOpConnectionHeader{}, nil +func NewConnectionHeader(context.Context, interface{}) (interface{}, error) { + return ConnectionHeader{}, nil } func init() { - common.Must(common.RegisterConfig((*Config)(nil), NewNoOpHeader)) - common.Must(common.RegisterConfig((*ConnectionConfig)(nil), NewNoOpConnectionHeader)) + common.Must(common.RegisterConfig((*Config)(nil), NewHeader)) + common.Must(common.RegisterConfig((*ConnectionConfig)(nil), NewConnectionHeader)) } diff --git a/transport/internet/http/dialer.go b/transport/internet/http/dialer.go index 4a32b9fe3d..48269fcdd6 100644 --- a/transport/internet/http/dialer.go +++ b/transport/internet/http/dialer.go @@ -23,7 +23,7 @@ var ( globalDialerAccess sync.Mutex ) -func getHTTPClient(_ context.Context, dest net.Destination, tlsSettings *tls.Config) (*http.Client, error) { +func getHTTPClient(_ context.Context, dest net.Destination, tlsSettings *tls.Config) *http.Client { globalDialerAccess.Lock() defer globalDialerAccess.Unlock() @@ -32,7 +32,7 @@ func getHTTPClient(_ context.Context, dest net.Destination, tlsSettings *tls.Con } if client, found := globalDialerMap[dest]; found { - return client, nil + return client } transport := &http2.Transport{ @@ -81,7 +81,7 @@ func getHTTPClient(_ context.Context, dest net.Destination, tlsSettings *tls.Con } globalDialerMap[dest] = client - return client, nil + return client } // Dial dials a new TCP connection to the given destination. @@ -91,10 +91,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me if tlsConfig == nil { return nil, newError("TLS must be enabled for http transport.").AtWarning() } - client, err := getHTTPClient(ctx, dest, tlsConfig) - if err != nil { - return nil, err - } + client := getHTTPClient(ctx, dest, tlsConfig) opts := pipe.OptionsFromContext(ctx) preader, pwriter := pipe.New(opts...) @@ -116,7 +113,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me // Disable any compression method from server. request.Header.Set("Accept-Encoding", "identity") - response, err := client.Do(request) + response, err := client.Do(request) // nolint: bodyclose if err != nil { return nil, newError("failed to dial to ", dest).Base(err).AtWarning() } diff --git a/transport/internet/kcp/io.go b/transport/internet/kcp/io.go index a4cb8ed5f9..58f657ca02 100644 --- a/transport/internet/kcp/io.go +++ b/transport/internet/kcp/io.go @@ -21,7 +21,7 @@ type PacketWriter interface { io.Writer } -type KCPPacketReader struct { +type KCPPacketReader struct { // nolint: golint Security cipher.AEAD Header internet.PacketHeader } @@ -57,7 +57,7 @@ func (r *KCPPacketReader) Read(b []byte) []Segment { return result } -type KCPPacketWriter struct { +type KCPPacketWriter struct { // nolint: golint Header internet.PacketHeader Security cipher.AEAD Writer io.Writer diff --git a/transport/internet/quic/pool.go b/transport/internet/quic/pool.go index 2e2032da40..935a450681 100644 --- a/transport/internet/quic/pool.go +++ b/transport/internet/quic/pool.go @@ -19,5 +19,5 @@ func getBuffer() []byte { } func putBuffer(p []byte) { - pool.Put(p) + pool.Put(p) // nolint: staticcheck } diff --git a/transport/internet/sockopt_darwin.go b/transport/internet/sockopt_darwin.go index e6281923da..c4b2e8deb3 100644 --- a/transport/internet/sockopt_darwin.go +++ b/transport/internet/sockopt_darwin.go @@ -6,11 +6,11 @@ import ( const ( // TCP_FASTOPEN is the socket option on darwin for TCP fast open. - TCP_FASTOPEN = 0x105 + TCP_FASTOPEN = 0x105 // nolint: golint,stylecheck // TCP_FASTOPEN_SERVER is the value to enable TCP fast open on darwin for server connections. - TCP_FASTOPEN_SERVER = 0x01 + TCP_FASTOPEN_SERVER = 0x01 // nolint: golint,stylecheck // TCP_FASTOPEN_CLIENT is the value to enable TCP fast open on darwin for client connections. - TCP_FASTOPEN_CLIENT = 0x02 + TCP_FASTOPEN_CLIENT = 0x02 // nolint: golint,stylecheck ) func applyOutboundSocketOptions(network string, address string, fd uintptr, config *SocketConfig) error { diff --git a/transport/internet/system_listener.go b/transport/internet/system_listener.go index d867914eaa..e5426b781a 100644 --- a/transport/internet/system_listener.go +++ b/transport/internet/system_listener.go @@ -29,7 +29,7 @@ func getControlFunc(ctx context.Context, sockopt *SocketConfig, controllers []co } } - setReusePort(fd) + setReusePort(fd) // nolint: staticcheck for _, controller := range controllers { if err := controller(network, address, fd); err != nil { @@ -71,7 +71,7 @@ func (dl *DefaultListener) Listen(ctx context.Context, addr net.Addr, sockopt *S if err != nil { return nil, err } - ctx = context.WithValue(ctx, address, locker) + ctx = context.WithValue(ctx, address, locker) // nolint: golint,staticcheck } } diff --git a/transport/internet/tcp/hub.go b/transport/internet/tcp/hub.go index 7cfb69436b..eff9bf4b29 100644 --- a/transport/internet/tcp/hub.go +++ b/transport/internet/tcp/hub.go @@ -40,7 +40,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/tls/config.go b/transport/internet/tls/config.go index 2d55998b6b..f210f673d3 100644 --- a/transport/internet/tls/config.go +++ b/transport/internet/tls/config.go @@ -117,8 +117,9 @@ func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.Cli access.Lock() for _, certificate := range c.Certificates { - if !isCertificateExpired(&certificate) { - newCerts = append(newCerts, certificate) + cert := certificate + if !isCertificateExpired(&cert) { + newCerts = append(newCerts, cert) } } diff --git a/transport/internet/websocket/hub.go b/transport/internet/websocket/hub.go index 834a9edb8d..0439a05d70 100644 --- a/transport/internet/websocket/hub.go +++ b/transport/internet/websocket/hub.go @@ -10,7 +10,6 @@ import ( "time" "github.com/gorilla/websocket" - "v2ray.com/core/common" "v2ray.com/core/common/net" http_proto "v2ray.com/core/common/protocol/http" @@ -79,7 +78,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", @@ -92,7 +91,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),