Skip to content

Commit

Permalink
Refine code according to golangci-lint results
Browse files Browse the repository at this point in the history
  • Loading branch information
Loyalsoldier committed Oct 11, 2020
1 parent ff6bb51 commit 784775f
Show file tree
Hide file tree
Showing 118 changed files with 515 additions and 532 deletions.
6 changes: 3 additions & 3 deletions app/commander/outbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ func (l *OutboundListener) add(conn net.Conn) {
select {
case l.buffer <- conn:
case <-l.done.Wait():
conn.Close() // nolint: errcheck
conn.Close()
default:
conn.Close() // nolint: errcheck
conn.Close()
}
}

Expand All @@ -45,7 +45,7 @@ L:
for {
select {
case c := <-l.buffer:
c.Close() // nolint: errcheck
c.Close()
default:
break L
}
Expand Down
1 change: 0 additions & 1 deletion app/dns/dnscommon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ func Test_parseResponse(t *testing.T) {
}

func Test_buildReqMsgs(t *testing.T) {

stubID := func() uint16 {
return uint16(rand.Uint32())
}
Expand Down
2 changes: 0 additions & 2 deletions app/dns/dohdns.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ type DoHNameServer struct {

// NewDoHNameServer creates DOH client object for remote resolving
func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher, clientIP net.IP) (*DoHNameServer, error) {

newError("DNS: created Remote DOH client for ", url.String()).AtInfo().WriteToLog()
s := baseDOHNameServer(url, "DOH", clientIP)

Expand Down Expand Up @@ -112,7 +111,6 @@ func NewDoHLocalNameServer(url *url.URL, clientIP net.IP) *DoHNameServer {
}

func baseDOHNameServer(url *url.URL, prefix string, clientIP net.IP) *DoHNameServer {

s := &DoHNameServer{
ips: make(map[string]record),
clientIP: clientIP,
Expand Down
9 changes: 6 additions & 3 deletions app/dns/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,20 @@ func NewStaticHosts(hosts []*Config_HostMapping, legacy map[string]*net.IPOrDoma
}
id := g.Add(matcher)
ips := make([]net.Address, 0, len(mapping.Ip)+1)
if len(mapping.Ip) > 0 {
switch {
case len(mapping.Ip) > 0:
for _, ip := range mapping.Ip {
addr := net.IPAddress(ip)
if addr == nil {
return nil, newError("invalid IP address in static hosts: ", ip).AtWarning()
}
ips = append(ips, addr)
}
} else if len(mapping.ProxiedDomain) > 0 {

case len(mapping.ProxiedDomain) > 0:
ips = append(ips, net.DomainAddress(mapping.ProxiedDomain))
} else {

default:
return nil, newError("neither IP address nor proxied domain specified for domain: ", mapping.Domain).AtWarning()
}

Expand Down
10 changes: 5 additions & 5 deletions app/dns/nameserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ type Client interface {
QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error)
}

type localNameServer struct {
type LocalNameServer struct {
client *localdns.Client
}

func (s *localNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
func (s *LocalNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
if option.IPv4Enable && option.IPv6Enable {
return s.client.LookupIP(domain)
}
Expand All @@ -44,13 +44,13 @@ func (s *localNameServer) QueryIP(ctx context.Context, domain string, option IPO
return nil, newError("neither IPv4 nor IPv6 is enabled")
}

func (s *localNameServer) Name() string {
func (s *LocalNameServer) Name() string {
return "localhost"
}

func NewLocalNameServer() *localNameServer {
func NewLocalNameServer() *LocalNameServer {
newError("DNS: created localhost client").AtInfo().WriteToLog()
return &localNameServer{
return &LocalNameServer{
client: localdns.New(),
}
}
13 changes: 9 additions & 4 deletions app/dns/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ func New(ctx context.Context, config *Config) (*Server, error) {
addNameServer := func(ns *NameServer) int {
endpoint := ns.Address
address := endpoint.Address.AsAddress()
if address.Family().IsDomain() && address.Domain() == "localhost" {

switch {
case address.Family().IsDomain() && address.Domain() == "localhost":
server.clients = append(server.clients, NewLocalNameServer())
// Priotize local domains with specific TLDs or without any dot to local DNS
// References:
Expand All @@ -115,15 +117,17 @@ func New(ctx context.Context, config *Config) (*Server, error) {
{Type: DomainMatchingType_Subdomain, Domain: "test"},
}
ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
} else if address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https+local://") {

case address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https+local://"):
// URI schemed string treated as domain
// DOH Local mode
u, err := url.Parse(address.Domain())
if err != nil {
log.Fatalln(newError("DNS config error").Base(err))
}
server.clients = append(server.clients, NewDoHLocalNameServer(u, server.clientIP))
} else if address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https://") {

case address.Family().IsDomain() && strings.HasPrefix(address.Domain(), "https://"):
// DOH Remote mode
u, err := url.Parse(address.Domain())
if err != nil {
Expand All @@ -140,7 +144,8 @@ func New(ctx context.Context, config *Config) (*Server, error) {
}
server.clients[idx] = c
}))
} else {

default:
// UDP classic DNS mode
dest := endpoint.AsDestination()
if dest.Network == net.Network_Unknown {
Expand Down
42 changes: 28 additions & 14 deletions app/dns/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,52 +42,66 @@ func (*staticHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
}

for _, q := range r.Question {
if q.Name == "google.com." && q.Qtype == dns.TypeA {
switch {
case q.Name == "google.com." && q.Qtype == dns.TypeA:
if clientIP == nil {
rr, _ := dns.NewRR("google.com. IN A 8.8.8.8")
ans.Answer = append(ans.Answer, rr)
} else {
rr, _ := dns.NewRR("google.com. IN A 8.8.4.4")
ans.Answer = append(ans.Answer, rr)
}
} else if q.Name == "api.google.com." && q.Qtype == dns.TypeA {

case q.Name == "api.google.com." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("api.google.com. IN A 8.8.7.7")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "v2.api.google.com." && q.Qtype == dns.TypeA {

case q.Name == "v2.api.google.com." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("v2.api.google.com. IN A 8.8.7.8")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "facebook.com." && q.Qtype == dns.TypeA {

case q.Name == "facebook.com." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("facebook.com. IN A 9.9.9.9")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "ipv6.google.com." && q.Qtype == dns.TypeA {

case q.Name == "ipv6.google.com." && q.Qtype == dns.TypeA:
rr, err := dns.NewRR("ipv6.google.com. IN A 8.8.8.7")
common.Must(err)
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "ipv6.google.com." && q.Qtype == dns.TypeAAAA {

case q.Name == "ipv6.google.com." && q.Qtype == dns.TypeAAAA:
rr, err := dns.NewRR("ipv6.google.com. IN AAAA 2001:4860:4860::8888")
common.Must(err)
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "notexist.google.com." && q.Qtype == dns.TypeAAAA {

case q.Name == "notexist.google.com." && q.Qtype == dns.TypeAAAA:
ans.MsgHdr.Rcode = dns.RcodeNameError
} else if q.Name == "hostname." && q.Qtype == dns.TypeA {

case q.Name == "hostname." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("hostname. IN A 127.0.0.1")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "hostname.local." && q.Qtype == dns.TypeA {

case q.Name == "hostname.local." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("hostname.local. IN A 127.0.0.1")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "hostname.localdomain." && q.Qtype == dns.TypeA {

case q.Name == "hostname.localdomain." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("hostname.localdomain. IN A 127.0.0.1")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "localhost." && q.Qtype == dns.TypeA {

case q.Name == "localhost." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("localhost. IN A 127.0.0.2")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "localhost-a." && q.Qtype == dns.TypeA {

case q.Name == "localhost-a." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("localhost-a. IN A 127.0.0.3")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "localhost-b." && q.Qtype == dns.TypeA {

case q.Name == "localhost-b." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("localhost-b. IN A 127.0.0.4")
ans.Answer = append(ans.Answer, rr)
} else if q.Name == "Mijia\\ Cloud." && q.Qtype == dns.TypeA {

case q.Name == "Mijia\\ Cloud." && q.Qtype == dns.TypeA:
rr, _ := dns.NewRR("Mijia\\ Cloud. IN A 127.0.0.1")
ans.Answer = append(ans.Answer, rr)
}
Expand Down
3 changes: 0 additions & 3 deletions app/dns/udpns.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ type ClassicNameServer struct {
}

func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher, clientIP net.IP) *ClassicNameServer {

// default to 53 if unspecific
if address.Port == 0 {
address.Port = net.Port(53)
Expand Down Expand Up @@ -105,7 +104,6 @@ func (s *ClassicNameServer) Cleanup() error {
}

func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_proto.Packet) {

ipRec, err := parseResponse(packet.Payload.Bytes())
if err != nil {
newError(s.name, " fail to parse responded DNS udp").AtError().WriteToLog()
Expand Down Expand Up @@ -240,7 +238,6 @@ func (s *ClassicNameServer) findIPsForDomain(domain string, option IPOption) ([]
}

func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {

fqdn := Fqdn(domain)

ips, err := s.findIPsForDomain(fqdn, option)
Expand Down
4 changes: 2 additions & 2 deletions app/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,10 @@ func (g *Instance) Close() error {

g.active = false

common.Close(g.accessLogger) // nolint: errcheck
common.Close(g.accessLogger)
g.accessLogger = nil

common.Close(g.errorLogger) // nolint: errcheck
common.Close(g.errorLogger)
g.errorLogger = nil

return nil
Expand Down
8 changes: 4 additions & 4 deletions app/proxyman/inbound/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest
conn, existing := w.getConnection(id)

// payload will be discarded in pipe is full.
conn.writer.WriteMultiBuffer(buf.MultiBuffer{b}) // nolint: errcheck
conn.writer.WriteMultiBuffer(buf.MultiBuffer{b})

if !existing {
common.Must(w.checker.Start())
Expand All @@ -303,7 +303,7 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest
if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil {
newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx))
}
conn.Close() // nolint: errcheck
conn.Close()
w.removeConn(id)
}()
}
Expand Down Expand Up @@ -332,9 +332,9 @@ func (w *udpWorker) clean() error {
}

for addr, conn := range w.activeConn {
if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 { //TODO Timeout too small
if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 { // TODO Timeout too small
delete(w.activeConn, addr)
conn.Close() // nolint: errcheck
conn.Close()
}
}

Expand Down
4 changes: 2 additions & 2 deletions app/router/command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,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) // nolint: govet
ctx, _ := context.WithTimeout(context.Background(), 4*time.Second)
s.routingStats.Publish(ctx, route)
}
return AsProtobufMessage(request.FieldSelectors)(route), nil
Expand All @@ -54,7 +54,7 @@ func (s *routingServer) SubscribeRoutingStats(request *SubscribeRoutingStatsRequ
if err != nil {
return err
}
defer stats.UnsubscribeClosableChannel(s.routingStats, subscriber) // nolint: errcheck
defer stats.UnsubscribeClosableChannel(s.routingStats, subscriber)
for {
select {
case value, ok := <-subscriber:
Expand Down
24 changes: 12 additions & 12 deletions app/router/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ func TestSimpleRouter(t *testing.T) {
mockCtl := gomock.NewController(t)
defer mockCtl.Finish()

mockDns := mocks.NewDNSClient(mockCtl)
mockDNS := mocks.NewDNSClient(mockCtl)
mockOhm := mocks.NewOutboundManager(mockCtl)
mockHs := mocks.NewOutboundHandlerSelector(mockCtl)

r := new(Router)
common.Must(r.Init(config, mockDns, &mockOutboundManager{
common.Must(r.Init(config, mockDNS, &mockOutboundManager{
Manager: mockOhm,
HandlerSelector: mockHs,
}))
Expand Down Expand Up @@ -73,14 +73,14 @@ func TestSimpleBalancer(t *testing.T) {
mockCtl := gomock.NewController(t)
defer mockCtl.Finish()

mockDns := mocks.NewDNSClient(mockCtl)
mockDNS := mocks.NewDNSClient(mockCtl)
mockOhm := mocks.NewOutboundManager(mockCtl)
mockHs := mocks.NewOutboundHandlerSelector(mockCtl)

mockHs.EXPECT().Select(gomock.Eq([]string{"test-"})).Return([]string{"test"})

r := new(Router)
common.Must(r.Init(config, mockDns, &mockOutboundManager{
common.Must(r.Init(config, mockDNS, &mockOutboundManager{
Manager: mockOhm,
HandlerSelector: mockHs,
}))
Expand Down Expand Up @@ -114,11 +114,11 @@ func TestIPOnDemand(t *testing.T) {
mockCtl := gomock.NewController(t)
defer mockCtl.Finish()

mockDns := mocks.NewDNSClient(mockCtl)
mockDns.EXPECT().LookupIP(gomock.Eq("v2ray.com")).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes()
mockDNS := mocks.NewDNSClient(mockCtl)
mockDNS.EXPECT().LookupIP(gomock.Eq("v2ray.com")).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes()

r := new(Router)
common.Must(r.Init(config, mockDns, nil))
common.Must(r.Init(config, mockDNS, nil))

ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2ray.com"), 80)})
route, err := r.PickRoute(routing_session.AsRoutingContext(ctx))
Expand Down Expand Up @@ -149,11 +149,11 @@ func TestIPIfNonMatchDomain(t *testing.T) {
mockCtl := gomock.NewController(t)
defer mockCtl.Finish()

mockDns := mocks.NewDNSClient(mockCtl)
mockDns.EXPECT().LookupIP(gomock.Eq("v2ray.com")).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes()
mockDNS := mocks.NewDNSClient(mockCtl)
mockDNS.EXPECT().LookupIP(gomock.Eq("v2ray.com")).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes()

r := new(Router)
common.Must(r.Init(config, mockDns, nil))
common.Must(r.Init(config, mockDNS, nil))

ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.DomainAddress("v2ray.com"), 80)})
route, err := r.PickRoute(routing_session.AsRoutingContext(ctx))
Expand Down Expand Up @@ -184,10 +184,10 @@ func TestIPIfNonMatchIP(t *testing.T) {
mockCtl := gomock.NewController(t)
defer mockCtl.Finish()

mockDns := mocks.NewDNSClient(mockCtl)
mockDNS := mocks.NewDNSClient(mockCtl)

r := new(Router)
common.Must(r.Init(config, mockDns, nil))
common.Must(r.Init(config, mockDNS, nil))

ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{Target: net.TCPDestination(net.LocalHostIP, 80)})
route, err := r.PickRoute(routing_session.AsRoutingContext(ctx))
Expand Down
2 changes: 1 addition & 1 deletion app/stats/channel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ func TestStatsChannelConcurrency(t *testing.T) {
if ok {
errCh <- fmt.Sprint("unexpected receiving: ", v)
} else {
errCh <- fmt.Sprint("unexpected closing of channel")
errCh <- "unexpected closing of channel"
}
default:
}
Expand Down
Loading

0 comments on commit 784775f

Please sign in to comment.