Skip to content

Commit

Permalink
Fix lint according to golangci-lint (#439)
Browse files Browse the repository at this point in the history
  • Loading branch information
Loyalsoldier committed Nov 21, 2020
1 parent f41286a commit b68f943
Show file tree
Hide file tree
Showing 39 changed files with 96 additions and 137 deletions.
6 changes: 4 additions & 2 deletions .github/linters/.golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ run:

issues:
new: true
exclude-rules:
- path: _test\.go
linters:
- scopelint

linters:
enable:
Expand All @@ -20,8 +24,6 @@ linters:
- ineffassign
- misspell
- nakedret
- noctx
- nolintlint
- rowserrcheck
- scopelint
- staticcheck
Expand Down
3 changes: 1 addition & 2 deletions app/router/command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"time"

"google.golang.org/grpc"

"v2ray.com/core"
"v2ray.com/core/common"
"v2ray.com/core/features/routing"
Expand Down Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions app/router/condition.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion common/buf/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion common/bytespool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
8 changes: 5 additions & 3 deletions common/net/destination.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
7 changes: 3 additions & 4 deletions infra/conf/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
}

Expand Down
7 changes: 4 additions & 3 deletions infra/conf/v2ray.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
Expand Down
18 changes: 7 additions & 11 deletions main/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions proxy/blackhole/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion proxy/dns/dns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
14 changes: 7 additions & 7 deletions proxy/dokodemo/dokodemo.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,24 +25,24 @@ 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))
})
return d, err
}))
}

type DokodemoDoor struct {
type Door struct {
policyManager policy.Manager
config *Config
address net.Address
port net.Port
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")
}
Expand All @@ -56,15 +56,15 @@ 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
}

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 {
Expand All @@ -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,
Expand Down
5 changes: 2 additions & 3 deletions proxy/http/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"sync"

"golang.org/x/net/http2"

"v2ray.com/core"
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion proxy/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion proxy/trojan/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
4 changes: 0 additions & 4 deletions proxy/trojan/trojan.go
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
package trojan

const (
muxCoolAddress = "v1.mux.cool"
)
28 changes: 6 additions & 22 deletions proxy/vless/encoding/addons.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -39,34 +34,23 @@ 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
}

// 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)
}
Expand Down
1 change: 1 addition & 0 deletions proxy/vless/encoding/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package encoding

import (
"io"

"v2ray.com/core/common/buf"
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
Expand Down
Loading

0 comments on commit b68f943

Please sign in to comment.