From 6ca03f5a902c2064bba4cdb91b8dcf80be03a66e Mon Sep 17 00:00:00 2001 From: gVisor bot Date: Tue, 25 Aug 2020 22:19:59 +0800 Subject: [PATCH] Chore: pass staticcheck --- adapters/outbound/base.go | 4 --- adapters/outbound/parser.go | 10 ++++--- adapters/outboundgroup/parser.go | 5 +++- adapters/outboundgroup/relay.go | 2 +- adapters/outboundgroup/selector.go | 2 +- adapters/provider/provider.go | 6 ++-- common/pool/alloc.go | 2 ++ common/pool/alloc_test.go | 8 +++--- common/singledo/singledo.go | 2 ++ component/dialer/dialer.go | 37 ++++++++++++------------- component/snell/snell.go | 2 +- component/ssr/obfs/tls12_ticket_auth.go | 1 - component/ssr/protocol/auth_chain_a.go | 1 - component/vmess/aead.go | 2 +- component/vmess/chunk.go | 2 +- component/vmess/vmess.go | 9 +----- component/vmess/websocket.go | 4 +-- config/config.go | 18 ++++++------ config/initial.go | 12 ++++---- config/utils.go | 11 +------- dns/middleware.go | 3 -- dns/resolver.go | 4 +-- hub/executor/executor.go | 4 +-- log/log.go | 1 - main.go | 5 ++-- proxy/http/server.go | 3 +- proxy/listener.go | 6 ---- proxy/redir/utils.go | 1 - proxy/socks/utils.go | 1 - rules/base.go | 1 - tunnel/connection.go | 2 +- 31 files changed, 72 insertions(+), 99 deletions(-) diff --git a/adapters/outbound/base.go b/adapters/outbound/base.go index d51a26dd..26fa5d56 100644 --- a/adapters/outbound/base.go +++ b/adapters/outbound/base.go @@ -13,10 +13,6 @@ import ( C "github.com/Dreamacro/clash/constant" ) -var ( - defaultURLTestTimeout = time.Second * 5 -) - type Base struct { name string addr string diff --git a/adapters/outbound/parser.go b/adapters/outbound/parser.go index 19a779ee..f0f894da 100644 --- a/adapters/outbound/parser.go +++ b/adapters/outbound/parser.go @@ -11,11 +11,13 @@ func ParseProxy(mapping map[string]interface{}) (C.Proxy, error) { decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true}) proxyType, existType := mapping["type"].(string) if !existType { - return nil, fmt.Errorf("Missing type") + return nil, fmt.Errorf("missing type") } - var proxy C.ProxyAdapter - err := fmt.Errorf("Cannot parse") + var ( + proxy C.ProxyAdapter + err error + ) switch proxyType { case "ss": ssOption := &ShadowSocksOption{} @@ -72,7 +74,7 @@ func ParseProxy(mapping map[string]interface{}) (C.Proxy, error) { } proxy, err = NewTrojan(*trojanOption) default: - return nil, fmt.Errorf("Unsupport proxy type: %s", proxyType) + return nil, fmt.Errorf("unsupport proxy type: %s", proxyType) } if err != nil { diff --git a/adapters/outboundgroup/parser.go b/adapters/outboundgroup/parser.go index 0a33b94e..f0fa54c9 100644 --- a/adapters/outboundgroup/parser.go +++ b/adapters/outboundgroup/parser.go @@ -12,7 +12,6 @@ import ( var ( errFormat = errors.New("format error") errType = errors.New("unsupport type") - errMissUse = errors.New("`use` field should not be empty") errMissProxy = errors.New("`use` or `proxies` missing") errMissHealthCheck = errors.New("`url` or `interval` missing") errDuplicateProvider = errors.New("`duplicate provider name") @@ -63,6 +62,10 @@ func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy, providers = append(providers, pd) } else { + if _, ok := providersMap[groupName]; ok { + return nil, errDuplicateProvider + } + // select don't need health check if groupOption.Type == "select" || groupOption.Type == "relay" { hc := provider.NewHealthCheck(ps, "", 0) diff --git a/adapters/outboundgroup/relay.go b/adapters/outboundgroup/relay.go index eb9b8eb8..e27df09b 100644 --- a/adapters/outboundgroup/relay.go +++ b/adapters/outboundgroup/relay.go @@ -22,7 +22,7 @@ type Relay struct { func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) { proxies := r.proxies(metadata) if len(proxies) == 0 { - return nil, errors.New("Proxy does not exist") + return nil, errors.New("proxy does not exist") } first := proxies[0] last := proxies[len(proxies)-1] diff --git a/adapters/outboundgroup/selector.go b/adapters/outboundgroup/selector.go index 239abcf7..e253cb3e 100644 --- a/adapters/outboundgroup/selector.go +++ b/adapters/outboundgroup/selector.go @@ -64,7 +64,7 @@ func (s *Selector) Set(name string) error { } } - return errors.New("Proxy does not exist") + return errors.New("proxy not exist") } func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy { diff --git a/adapters/provider/provider.go b/adapters/provider/provider.go index f5321e73..09d05430 100644 --- a/adapters/provider/provider.go +++ b/adapters/provider/provider.go @@ -120,20 +120,20 @@ func proxiesParse(buf []byte) (interface{}, error) { } if schema.Proxies == nil { - return nil, errors.New("File must have a `proxies` field") + return nil, errors.New("file must have a `proxies` field") } proxies := []C.Proxy{} for idx, mapping := range schema.Proxies { proxy, err := outbound.ParseProxy(mapping) if err != nil { - return nil, fmt.Errorf("Proxy %d error: %w", idx, err) + return nil, fmt.Errorf("proxy %d error: %w", idx, err) } proxies = append(proxies, proxy) } if len(proxies) == 0 { - return nil, errors.New("File doesn't have any valid proxy") + return nil, errors.New("file doesn't have any valid proxy") } return proxies, nil diff --git a/common/pool/alloc.go b/common/pool/alloc.go index e9a7d52c..4f26c036 100644 --- a/common/pool/alloc.go +++ b/common/pool/alloc.go @@ -55,6 +55,8 @@ func (alloc *Allocator) Put(buf []byte) error { if cap(buf) == 0 || cap(buf) > 65536 || cap(buf) != 1< maxSize { - return 0, errors.New("Buffer is larger than standard") + return 0, errors.New("buffer is larger than standard") } buf := pool.Get(size) diff --git a/component/vmess/chunk.go b/component/vmess/chunk.go index cd7ea57b..ab1adb6d 100644 --- a/component/vmess/chunk.go +++ b/component/vmess/chunk.go @@ -47,7 +47,7 @@ func (cr *chunkReader) Read(b []byte) (int, error) { size := int(binary.BigEndian.Uint16(cr.sizeBuf)) if size > maxSize { - return 0, errors.New("Buffer is larger than standard") + return 0, errors.New("buffer is larger than standard") } if len(b) >= size { diff --git a/component/vmess/vmess.go b/component/vmess/vmess.go index 9b7ef906..5b538f7e 100644 --- a/component/vmess/vmess.go +++ b/component/vmess/vmess.go @@ -1,12 +1,10 @@ package vmess import ( - "crypto/tls" "fmt" "math/rand" "net" "runtime" - "sync" "github.com/gofrs/uuid" ) @@ -37,11 +35,6 @@ var CipherMapping = map[string]byte{ "chacha20-poly1305": SecurityCHACHA20POLY1305, } -var ( - clientSessionCache tls.ClientSessionCache - once sync.Once -) - // Command types const ( CommandTCP byte = 1 @@ -106,7 +99,7 @@ func NewClient(config Config) (*Client, error) { security = SecurityAES128GCM } default: - return nil, fmt.Errorf("Unknown security type: %s", config.Security) + return nil, fmt.Errorf("unknown security type: %s", config.Security) } return &Client{ diff --git a/component/vmess/websocket.go b/component/vmess/websocket.go index 499f15c8..980add13 100644 --- a/component/vmess/websocket.go +++ b/component/vmess/websocket.go @@ -73,7 +73,7 @@ func (wsc *websocketConn) Close() error { errors = append(errors, err.Error()) } if len(errors) > 0 { - return fmt.Errorf("Failed to close connection: %s", strings.Join(errors, ",")) + return fmt.Errorf("failed to close connection: %s", strings.Join(errors, ",")) } return nil } @@ -159,7 +159,7 @@ func StreamWebsocketConn(conn net.Conn, c *WebsocketConfig) (net.Conn, error) { if resp != nil { reason = resp.Status } - return nil, fmt.Errorf("Dial %s error: %s", uri.Host, reason) + return nil, fmt.Errorf("dial %s error: %s", uri.Host, reason) } return &websocketConn{ diff --git a/config/config.go b/config/config.go index c853cbd5..cf6a7670 100644 --- a/config/config.go +++ b/config/config.go @@ -264,11 +264,11 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[ for idx, mapping := range proxiesConfig { proxy, err := outbound.ParseProxy(mapping) if err != nil { - return nil, nil, fmt.Errorf("Proxy %d: %w", idx, err) + return nil, nil, fmt.Errorf("proxy %d: %w", idx, err) } if _, exist := proxies[proxy.Name()]; exist { - return nil, nil, fmt.Errorf("Proxy %s is the duplicate name", proxy.Name()) + return nil, nil, fmt.Errorf("proxy %s is the duplicate name", proxy.Name()) } proxies[proxy.Name()] = proxy proxyList = append(proxyList, proxy.Name()) @@ -278,7 +278,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[ for idx, mapping := range groupsConfig { groupName, existName := mapping["name"].(string) if !existName { - return nil, nil, fmt.Errorf("ProxyGroup %d: missing name", idx) + return nil, nil, fmt.Errorf("proxy group %d: missing name", idx) } proxyList = append(proxyList, groupName) } @@ -313,12 +313,12 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[ for idx, mapping := range groupsConfig { group, err := outboundgroup.ParseProxyGroup(mapping, proxies, providersMap) if err != nil { - return nil, nil, fmt.Errorf("ProxyGroup[%d]: %w", idx, err) + return nil, nil, fmt.Errorf("proxy group[%d]: %w", idx, err) } groupName := group.Name() if _, exist := proxies[groupName]; exist { - return nil, nil, fmt.Errorf("ProxyGroup %s: the duplicate name", groupName) + return nil, nil, fmt.Errorf("proxy group %s: the duplicate name", groupName) } proxies[groupName] = outbound.NewProxy(group) @@ -373,11 +373,11 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) { target = rule[2] params = rule[3:] default: - return nil, fmt.Errorf("Rules[%d] [%s] error: format invalid", idx, line) + return nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line) } if _, ok := proxies[target]; !ok { - return nil, fmt.Errorf("Rules[%d] [%s] error: proxy [%s] not found", idx, line, target) + return nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target) } rule = trimArr(rule) @@ -389,7 +389,7 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) { log.Warnln("Rules[%d] [%s] don't support current OS, skip", idx, line) continue } - return nil, fmt.Errorf("Rules[%d] [%s] error: %s", idx, line, parseErr.Error()) + return nil, fmt.Errorf("rules[%d] [%s] error: %s", idx, line, parseErr.Error()) } rules = append(rules, parsed) @@ -499,7 +499,7 @@ func parseFallbackIPCIDR(ips []string) ([]*net.IPNet, error) { func parseDNS(cfg RawDNS, hosts *trie.DomainTrie) (*DNS, error) { if cfg.Enable && len(cfg.NameServer) == 0 { - return nil, fmt.Errorf("If DNS configuration is turned on, NameServer cannot be empty") + return nil, fmt.Errorf("if DNS configuration is turned on, NameServer cannot be empty") } dnsCfg := &DNS{ diff --git a/config/initial.go b/config/initial.go index 26421f68..7c876162 100644 --- a/config/initial.go +++ b/config/initial.go @@ -32,18 +32,18 @@ func initMMDB() error { if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) { log.Infoln("Can't find MMDB, start download") if err := downloadMMDB(C.Path.MMDB()); err != nil { - return fmt.Errorf("Can't download MMDB: %s", err.Error()) + return fmt.Errorf("can't download MMDB: %s", err.Error()) } } if !mmdb.Verify() { log.Warnln("MMDB invalid, remove and download") if err := os.Remove(C.Path.MMDB()); err != nil { - return fmt.Errorf("Can't remove invalid MMDB: %s", err.Error()) + return fmt.Errorf("can't remove invalid MMDB: %s", err.Error()) } if err := downloadMMDB(C.Path.MMDB()); err != nil { - return fmt.Errorf("Can't download MMDB: %s", err.Error()) + return fmt.Errorf("can't download MMDB: %s", err.Error()) } } @@ -55,7 +55,7 @@ func Init(dir string) error { // initial homedir if _, err := os.Stat(dir); os.IsNotExist(err) { if err := os.MkdirAll(dir, 0777); err != nil { - return fmt.Errorf("Can't create config directory %s: %s", dir, err.Error()) + return fmt.Errorf("can't create config directory %s: %s", dir, err.Error()) } } @@ -64,7 +64,7 @@ func Init(dir string) error { log.Infoln("Can't find config, create a initial config file") f, err := os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644) if err != nil { - return fmt.Errorf("Can't create file %s: %s", C.Path.Config(), err.Error()) + return fmt.Errorf("can't create file %s: %s", C.Path.Config(), err.Error()) } f.Write([]byte(`port: 7890`)) f.Close() @@ -72,7 +72,7 @@ func Init(dir string) error { // initial mmdb if err := initMMDB(); err != nil { - return fmt.Errorf("Can't initial MMDB: %w", err) + return fmt.Errorf("can't initial MMDB: %w", err) } return nil } diff --git a/config/utils.go b/config/utils.go index 79fae6c9..74af4a64 100644 --- a/config/utils.go +++ b/config/utils.go @@ -15,15 +15,6 @@ func trimArr(arr []string) (r []string) { return } -func or(pointers ...*int) *int { - for _, p := range pointers { - if p != nil { - return p - } - } - return pointers[len(pointers)-1] -} - // Check if ProxyGroups form DAG(Directed Acyclic Graph), and sort all ProxyGroups by dependency order. // Meanwhile, record the original index in the config file. // If loop is detected, return an error with location of loop. @@ -153,5 +144,5 @@ func proxyGroupsDagSort(groupsConfig []map[string]interface{}) error { loopElements = append(loopElements, name) delete(graph, name) } - return fmt.Errorf("Loop is detected in ProxyGroup, please check following ProxyGroups: %v", loopElements) + return fmt.Errorf("loop is detected in ProxyGroup, please check following ProxyGroups: %v", loopElements) } diff --git a/dns/middleware.go b/dns/middleware.go index ad04b856..cc58c001 100644 --- a/dns/middleware.go +++ b/dns/middleware.go @@ -55,7 +55,6 @@ func withHosts(hosts *trie.DomainTrie) middleware { msg.RecursionAvailable = true w.WriteMsg(msg) - return } } } @@ -99,7 +98,6 @@ func withFakeIP(fakePool *fakeip.Pool) middleware { msg.RecursionAvailable = true w.WriteMsg(msg) - return } } } @@ -130,7 +128,6 @@ func withResolver(resolver *Resolver) handler { msg.SetRcode(r, msg.Rcode) msg.Authoritative = true w.WriteMsg(msg) - return } } diff --git a/dns/resolver.go b/dns/resolver.go index dd3e2f47..04ea41bb 100644 --- a/dns/resolver.go +++ b/dns/resolver.go @@ -106,7 +106,7 @@ func (r *Resolver) Exchange(m *D.Msg) (msg *D.Msg, err error) { setMsgTTL(msg, uint32(1)) // Continue fetch go r.exchangeWithoutCache(m) } else { - setMsgTTL(msg, uint32(expireTime.Sub(time.Now()).Seconds())) + setMsgTTL(msg, uint32(time.Until(expireTime).Seconds())) } return } @@ -203,7 +203,7 @@ func (r *Resolver) batchExchange(clients []dnsClient, m *D.Msg) (msg *D.Msg, err elm := fast.Wait() if elm == nil { - err := errors.New("All DNS requests failed") + err := errors.New("all DNS requests failed") if fErr := fast.Error(); fErr != nil { err = fmt.Errorf("%w, first error: %s", err, fErr.Error()) } diff --git a/hub/executor/executor.go b/hub/executor/executor.go index d2085a7b..3bb29f57 100644 --- a/hub/executor/executor.go +++ b/hub/executor/executor.go @@ -34,7 +34,7 @@ func readConfig(path string) ([]byte, error) { } if len(data) == 0 { - return nil, fmt.Errorf("Configuration file %s is empty", path) + return nil, fmt.Errorf("configuration file %s is empty", path) } return data, err @@ -101,7 +101,7 @@ func GetGeneral() *config.General { func updateExperimental(c *config.Config) {} func updateDNS(c *config.DNS) { - if c.Enable == false { + if !c.Enable { resolver.DefaultResolver = nil tunnel.SetResolver(nil) dns.ReCreateServer("", nil) diff --git a/log/log.go b/log/log.go index 7190cc89..73ff0b9e 100644 --- a/log/log.go +++ b/log/log.go @@ -64,7 +64,6 @@ func Subscribe() observable.Subscription { func UnSubscribe(sub observable.Subscription) { source.UnSubscribe(sub) - return } func Level() LogLevel { diff --git a/main.go b/main.go index 28229bfb..d612fcb4 100644 --- a/main.go +++ b/main.go @@ -10,7 +10,6 @@ import ( "syscall" "github.com/Dreamacro/clash/config" - "github.com/Dreamacro/clash/constant" C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/hub" "github.com/Dreamacro/clash/hub/executor" @@ -76,10 +75,10 @@ func main() { if testConfig { if _, err := executor.Parse(); err != nil { log.Errorln(err.Error()) - fmt.Printf("configuration file %s test failed\n", constant.Path.Config()) + fmt.Printf("configuration file %s test failed\n", C.Path.Config()) os.Exit(1) } - fmt.Printf("configuration file %s test is successful\n", constant.Path.Config()) + fmt.Printf("configuration file %s test is successful\n", C.Path.Config()) return } diff --git a/proxy/http/server.go b/proxy/http/server.go index 1791f62e..8eecf1e7 100644 --- a/proxy/http/server.go +++ b/proxy/http/server.go @@ -60,6 +60,7 @@ func (l *HttpListener) Address() string { func canActivate(loginStr string, authenticator auth.Authenticator, cache *cache.Cache) (ret bool) { if result := cache.Get(loginStr); result != nil { ret = result.(bool) + return } loginData, err := base64.StdEncoding.DecodeString(loginStr) login := strings.Split(string(loginData), ":") @@ -80,7 +81,7 @@ func HandleConn(conn net.Conn, cache *cache.Cache) { authenticator := authStore.Authenticator() if authenticator != nil { if authStrings := strings.Split(request.Header.Get("Proxy-Authorization"), " "); len(authStrings) != 2 { - _, err = conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic\r\n\r\n")) + conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic\r\n\r\n")) conn.Close() return } else if !canActivate(authStrings[1], authenticator, cache) { diff --git a/proxy/listener.go b/proxy/listener.go index 88d0f522..d1414b5a 100644 --- a/proxy/listener.go +++ b/proxy/listener.go @@ -30,14 +30,8 @@ var ( httpMux sync.Mutex redirMux sync.Mutex mixedMux sync.Mutex - tunMux sync.Mutex ) -type listener interface { - Close() - Address() string -} - type Ports struct { Port int `json:"port"` SocksPort int `json:"socks-port"` diff --git a/proxy/redir/utils.go b/proxy/redir/utils.go index e78563f4..46e39b8a 100644 --- a/proxy/redir/utils.go +++ b/proxy/redir/utils.go @@ -34,5 +34,4 @@ func (c *packet) LocalAddr() net.Addr { func (c *packet) Drop() { pool.Put(c.buf) - return } diff --git a/proxy/socks/utils.go b/proxy/socks/utils.go index 6b77a40f..d3ab3b78 100644 --- a/proxy/socks/utils.go +++ b/proxy/socks/utils.go @@ -34,5 +34,4 @@ func (c *packet) LocalAddr() net.Addr { func (c *packet) Drop() { pool.Put(c.bufRef) - return } diff --git a/rules/base.go b/rules/base.go index 9fa5e6ea..2db3558c 100644 --- a/rules/base.go +++ b/rules/base.go @@ -6,7 +6,6 @@ import ( var ( errPayload = errors.New("payload error") - errParams = errors.New("params error") ErrPlatformNotSupport = errors.New("not support on this platform") ErrInvalidNetwork = errors.New("invalid network") diff --git a/tunnel/connection.go b/tunnel/connection.go index bdba863a..13f7875a 100644 --- a/tunnel/connection.go +++ b/tunnel/connection.go @@ -121,7 +121,7 @@ func handleUDPToLocal(packet C.UDPPacket, pc net.PacketConn, key string, fAddr n from = fAddr } - n, err = packet.WriteBack(buf[:n], from) + _, err = packet.WriteBack(buf[:n], from) if err != nil { return }