From 3e1f922252e2a9b735b0be28733067f3b85bb6f3 Mon Sep 17 00:00:00 2001 From: Eugene Burkov Date: Fri, 6 Nov 2020 12:15:08 +0300 Subject: [PATCH] Pull request:* all: fix all staticcheck simplification and unused warnings Merge in DNS/adguard-home from 2270-fix-s-u-warnings to master Squashed commit of the following: commit 03e0f78bd471057007c2d4042ee26eda2bbc9b29 Merge: 50dc3ef5c 7e16fda57 Author: Eugene Burkov Date: Fri Nov 6 11:54:09 2020 +0300 Merge branch 'master' into 2270-fix-s-u-warnings commit 50dc3ef5c44a5fdc941794c26784b0c44d7b5aa0 Author: Eugene Burkov Date: Thu Nov 5 19:48:54 2020 +0300 * all: improve code quality commit d6d804f759ce3e47154a389b427550e72c4b9090 Author: Eugene Burkov Date: Thu Nov 5 18:03:35 2020 +0300 * all: fix all staticcheck simplification and unused warnings Closes #2270. --- internal/dhcpd/dhcp_http.go | 14 ++++---- internal/dhcpd/dhcpd_test.go | 6 ---- internal/dhcpd/nclient4/client.go | 22 ++++--------- internal/dhcpd/nclient4/client_test.go | 7 ++++ internal/dhcpd/network_utils.go | 3 +- internal/dhcpd/v6.go | 6 ++-- internal/dnsfilter/dnsfilter.go | 25 +++++++-------- internal/dnsfilter/dnsfilter_test.go | 44 +++++++++----------------- internal/dnsfilter/safe_search.go | 3 +- internal/dnsfilter/sb_pc.go | 38 +++++++++++++++------- internal/dnsfilter/sb_pc_test.go | 14 ++++---- internal/home/auth.go | 14 ++++---- internal/home/filter.go | 10 +++--- internal/home/home.go | 8 ++--- internal/home/i18n.go | 24 +++++++------- internal/home/memory.go | 10 ++---- internal/home/rdns.go | 3 +- internal/home/service.go | 13 ++++---- internal/home/tls.go | 4 +-- internal/home/whois.go | 5 ++- internal/stats/stats_test.go | 6 ++-- internal/stats/stats_unit.go | 18 +++++------ internal/util/auto_hosts.go | 34 +++++++++----------- internal/util/helpers.go | 38 ++++++---------------- 24 files changed, 159 insertions(+), 210 deletions(-) diff --git a/internal/dhcpd/dhcp_http.go b/internal/dhcpd/dhcp_http.go index 71defe38..fcb8b715 100644 --- a/internal/dhcpd/dhcp_http.go +++ b/internal/dhcpd/dhcp_http.go @@ -302,17 +302,17 @@ func (s *Server) handleDHCPInterfaces(w http.ResponseWriter, r *http.Request) { func (s *Server) handleDHCPFindActiveServer(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { - errorText := fmt.Sprintf("failed to read request body: %s", err) - log.Error(errorText) - http.Error(w, errorText, http.StatusBadRequest) + msg := fmt.Sprintf("failed to read request body: %s", err) + log.Error(msg) + http.Error(w, msg, http.StatusBadRequest) return } interfaceName := strings.TrimSpace(string(body)) if interfaceName == "" { - errorText := fmt.Sprintf("empty interface name specified") - log.Error(errorText) - http.Error(w, errorText, http.StatusBadRequest) + msg := "empty interface name specified" + log.Error(msg) + http.Error(w, msg, http.StatusBadRequest) return } @@ -370,7 +370,6 @@ func (s *Server) handleDHCPFindActiveServer(w http.ResponseWriter, r *http.Reque } func (s *Server) handleDHCPAddStaticLease(w http.ResponseWriter, r *http.Request) { - lj := staticLeaseJSON{} err := json.NewDecoder(r.Body).Decode(&lj) if err != nil { @@ -424,7 +423,6 @@ func (s *Server) handleDHCPAddStaticLease(w http.ResponseWriter, r *http.Request } func (s *Server) handleDHCPRemoveStaticLease(w http.ResponseWriter, r *http.Request) { - lj := staticLeaseJSON{} err := json.NewDecoder(r.Body).Decode(&lj) if err != nil { diff --git a/internal/dhcpd/dhcpd_test.go b/internal/dhcpd/dhcpd_test.go index 8fd795d1..c57ff36b 100644 --- a/internal/dhcpd/dhcpd_test.go +++ b/internal/dhcpd/dhcpd_test.go @@ -12,12 +12,6 @@ import ( "github.com/stretchr/testify/assert" ) -func check(t *testing.T, result bool, msg string) { - if !result { - t.Fatal(msg) - } -} - func testNotify(flags uint32) { } diff --git a/internal/dhcpd/nclient4/client.go b/internal/dhcpd/nclient4/client.go index 144ab11c..bb0473f1 100644 --- a/internal/dhcpd/nclient4/client.go +++ b/internal/dhcpd/nclient4/client.go @@ -48,14 +48,12 @@ const ( ServerPort = 67 ) -var ( - // DefaultServers is the address of all link-local DHCP servers and - // relay agents. - DefaultServers = &net.UDPAddr{ - IP: net.IPv4bcast, - Port: ServerPort, - } -) +// DefaultServers is the address of all link-local DHCP servers and +// relay agents. +var DefaultServers = &net.UDPAddr{ + IP: net.IPv4bcast, + Port: ServerPort, +} var ( // ErrNoResponse is returned when no response packet is received. @@ -375,14 +373,6 @@ func WithHWAddr(hwAddr net.HardwareAddr) ClientOpt { } } -// nolint -func withBufferCap(n int) ClientOpt { - return func(c *Client) (err error) { - c.bufferCap = n - return - } -} - // WithRetry configures the number of retransmissions to attempt. // // Default is 3. diff --git a/internal/dhcpd/nclient4/client_test.go b/internal/dhcpd/nclient4/client_test.go index ddad1144..79501b28 100644 --- a/internal/dhcpd/nclient4/client_test.go +++ b/internal/dhcpd/nclient4/client_test.go @@ -122,6 +122,13 @@ func newPacket(op dhcpv4.OpcodeType, xid dhcpv4.TransactionID) *dhcpv4.DHCPv4 { return p } +func withBufferCap(n int) ClientOpt { + return func(c *Client) (err error) { + c.bufferCap = n + return + } +} + func TestSendAndRead(t *testing.T) { for _, tt := range []struct { desc string diff --git a/internal/dhcpd/network_utils.go b/internal/dhcpd/network_utils.go index b6e45312..487196cc 100644 --- a/internal/dhcpd/network_utils.go +++ b/internal/dhcpd/network_utils.go @@ -73,7 +73,6 @@ func hasStaticIPDhcpcdConf(dhcpConf, ifaceName string) bool { // we found our interface withinInterfaceCtx = true } - } else { if strings.HasPrefix(line, "interface ") { // we found another interface - reset our state @@ -240,7 +239,7 @@ func getNetworkSetupHardwareReports() map[string]string { return nil } - m := make(map[string]string, 0) + m := make(map[string]string) matches := re.FindAllStringSubmatch(out, -1) for i := range matches { diff --git a/internal/dhcpd/v6.go b/internal/dhcpd/v6.go index 8ea4a576..22505f7a 100644 --- a/internal/dhcpd/v6.go +++ b/internal/dhcpd/v6.go @@ -41,7 +41,7 @@ func (s *v6Server) WriteDiskConfig6(c *V6ServerConf) { // Return TRUE if IP address is within range [start..0xff] // nolint(staticcheck) -func ip6InRange(start net.IP, ip net.IP) bool { +func ip6InRange(start, ip net.IP) bool { if len(start) != 16 { return false } @@ -369,7 +369,7 @@ func (s *v6Server) commitLease(msg *dhcpv6.Message, lease *Lease) time.Duration // case dhcpv6.MessageTypeConfirm: - lifetime = lease.Expiry.Sub(time.Now()) + lifetime = time.Until(lease.Expiry) case dhcpv6.MessageTypeRequest, dhcpv6.MessageTypeRenew, @@ -383,7 +383,7 @@ func (s *v6Server) commitLease(msg *dhcpv6.Message, lease *Lease) time.Duration } // Find a lease associated with MAC and prepare response -func (s *v6Server) process(msg *dhcpv6.Message, req dhcpv6.DHCPv6, resp dhcpv6.DHCPv6) bool { +func (s *v6Server) process(msg *dhcpv6.Message, req, resp dhcpv6.DHCPv6) bool { switch msg.Type() { case dhcpv6.MessageTypeSolicit, dhcpv6.MessageTypeRequest, diff --git a/internal/dnsfilter/dnsfilter.go b/internal/dnsfilter/dnsfilter.go index 10665216..6e733364 100644 --- a/internal/dnsfilter/dnsfilter.go +++ b/internal/dnsfilter/dnsfilter.go @@ -199,7 +199,7 @@ func (d *Dnsfilter) WriteDiskConfig(c *Config) { // SetFilters - set new filters (synchronously or asynchronously) // When filters are set asynchronously, the old filters continue working until the new filters are ready. // In this case the caller must ensure that the old filter files are intact. -func (d *Dnsfilter) SetFilters(blockFilters []Filter, allowFilters []Filter, async bool) error { +func (d *Dnsfilter) SetFilters(blockFilters, allowFilters []Filter, async bool) error { if async { params := filtersInitializerParams{ allowFilters: allowFilters, @@ -481,13 +481,10 @@ func matchBlockedServicesRules(host string, svcs []ServiceEntry) Result { // Adding rule and matching against the rules // -// Return TRUE if file exists +// fileExists returns true if file exists. func fileExists(fn string) bool { _, err := os.Stat(fn) - if err != nil { - return false - } - return true + return err == nil } func createFilteringEngine(filters []Filter) (*filterlist.RuleStorage, *urlfilter.DNSEngine, error) { @@ -508,7 +505,8 @@ func createFilteringEngine(filters []Filter) (*filterlist.RuleStorage, *urlfilte } } else if runtime.GOOS == "windows" { // On Windows we don't pass a file to urlfilter because - // it's difficult to update this file while it's being used. + // it's difficult to update this file while it's being + // used. data, err := ioutil.ReadFile(f.FilePath) if err != nil { return nil, nil, fmt.Errorf("ioutil.ReadFile(): %s: %w", f.FilePath, err) @@ -537,7 +535,7 @@ func createFilteringEngine(filters []Filter) (*filterlist.RuleStorage, *urlfilte return rulesStorage, filteringEngine, nil } -// Initialize urlfilter objects +// Initialize urlfilter objects. func (d *Dnsfilter) initFiltering(allowFilters, blockFilters []Filter) error { rulesStorage, filteringEngine, err := createFilteringEngine(blockFilters) if err != nil { @@ -563,7 +561,8 @@ func (d *Dnsfilter) initFiltering(allowFilters, blockFilters []Filter) error { return nil } -// matchHost is a low-level way to check only if hostname is filtered by rules, skipping expensive safebrowsing and parental lookups +// matchHost is a low-level way to check only if hostname is filtered by rules, +// skipping expensive safebrowsing and parental lookups. func (d *Dnsfilter) matchHost(host string, qtype uint16, setts RequestFilteringSettings) (Result, error) { d.engineLock.RLock() // Keep in mind that this lock must be held no just when calling Match() @@ -664,20 +663,18 @@ func makeResult(rule rules.Rule, reason Reason) Result { return res } -// InitModule() - manually initialize blocked services map +// InitModule manually initializes blocked services map. func InitModule() { initBlockedServices() } -// New creates properly initialized DNS Filter that is ready to be used +// New creates properly initialized DNS Filter that is ready to be used. func New(c *Config, blockFilters []Filter) *Dnsfilter { if c != nil { cacheConf := cache.Config{ EnableLRU: true, } - // initialize objects only once - if gctx.safebrowsingCache == nil { cacheConf.MaxSize = c.SafeBrowsingCacheSize gctx.safebrowsingCache = cache.New(cacheConf) @@ -747,7 +744,7 @@ func (d *Dnsfilter) Start() { // stats // -// GetStats return dns filtering stats since startup +// GetStats return dns filtering stats since startup. func (d *Dnsfilter) GetStats() Stats { return gctx.stats } diff --git a/internal/dnsfilter/dnsfilter_test.go b/internal/dnsfilter/dnsfilter_test.go index 0b669367..f431a1e4 100644 --- a/internal/dnsfilter/dnsfilter_test.go +++ b/internal/dnsfilter/dnsfilter_test.go @@ -3,9 +3,6 @@ package dnsfilter import ( "fmt" "net" - "os" - "path" - "runtime" "testing" "github.com/AdguardTeam/urlfilter/rules" @@ -36,13 +33,6 @@ func purgeCaches() { } } -func _Func() string { - pc := make([]uintptr, 10) // at least 1 entry needed - runtime.Callers(2, pc) - f := runtime.FuncForPC(pc[0]) - return path.Base(f.Name()) -} - func NewForTest(c *Config, filters []Filter) *Dnsfilter { setts = RequestFilteringSettings{} setts.FilteringEnabled = true @@ -71,7 +61,7 @@ func (d *Dnsfilter) checkMatch(t *testing.T, hostname string) { } } -func (d *Dnsfilter) checkMatchIP(t *testing.T, hostname string, ip string, qtype uint16) { +func (d *Dnsfilter) checkMatchIP(t *testing.T, hostname, ip string, qtype uint16) { t.Helper() ret, err := d.CheckHost(hostname, qtype, &setts) if err != nil { @@ -107,7 +97,7 @@ func TestEtcHostsMatching(t *testing.T) { ::1 host2 `, addr, addr6) - filters := []Filter{Filter{ + filters := []Filter{{ ID: 0, Data: []byte(text), }} d := NewForTest(nil, filters) @@ -351,11 +341,15 @@ func TestParentalControl(t *testing.T) { // FILTERING -var blockingRules = "||example.org^\n" -var whitelistRules = "||example.org^\n@@||test.example.org\n" -var importantRules = "@@||example.org^\n||test.example.org^$important\n" -var regexRules = "/example\\.org/\n@@||test.example.org^\n" -var maskRules = "test*.example.org^\nexam*.com\n" +const nl = "\n" + +const ( + blockingRules = `||example.org^` + nl + whitelistRules = `||example.org^` + nl + `@@||test.example.org` + nl + importantRules = `@@||example.org^` + nl + `||test.example.org^$important` + nl + regexRules = `/example\.org/` + nl + `@@||test.example.org^` + nl + maskRules = `test*.example.org^` + nl + `exam*.com` + nl +) var tests = []struct { testname string @@ -406,7 +400,7 @@ var tests = []struct { func TestMatching(t *testing.T) { for _, test := range tests { t.Run(fmt.Sprintf("%s-%s", test.testname, test.hostname), func(t *testing.T) { - filters := []Filter{Filter{ + filters := []Filter{{ ID: 0, Data: []byte(test.rules), }} d := NewForTest(nil, filters) @@ -430,14 +424,14 @@ func TestWhitelist(t *testing.T) { rules := `||host1^ ||host2^ ` - filters := []Filter{Filter{ + filters := []Filter{{ ID: 0, Data: []byte(rules), }} whiteRules := `||host1^ ||host3^ ` - whiteFilters := []Filter{Filter{ + whiteFilters := []Filter{{ ID: 0, Data: []byte(whiteRules), }} d := NewForTest(nil, filters) @@ -455,7 +449,6 @@ func TestWhitelist(t *testing.T) { assert.True(t, err == nil) assert.True(t, ret.IsFiltered && ret.Reason == FilteredBlackList) assert.True(t, ret.Rule == "||host2^") - } // CLIENT SETTINGS @@ -476,7 +469,7 @@ func applyClientSettings(setts *RequestFilteringSettings) { // then apply per-client settings and check behaviour once again func TestClientSettings(t *testing.T) { var r Result - filters := []Filter{Filter{ + filters := []Filter{{ ID: 0, Data: []byte("||example.org^\n"), }} d := NewForTest(&Config{ParentalEnabled: true, SafeBrowsingEnabled: false}, filters) @@ -532,13 +525,6 @@ func TestClientSettings(t *testing.T) { assert.True(t, r.IsFiltered && r.Reason == FilteredBlockedService) } -func prepareTestDir() string { - const dir = "./agh-test" - _ = os.RemoveAll(dir) - _ = os.MkdirAll(dir, 0755) - return dir -} - // BENCHMARKS func BenchmarkSafeBrowsing(b *testing.B) { diff --git a/internal/dnsfilter/safe_search.go b/internal/dnsfilter/safe_search.go index fb1358d5..6bd6bc94 100644 --- a/internal/dnsfilter/safe_search.go +++ b/internal/dnsfilter/safe_search.go @@ -22,8 +22,7 @@ func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) i var buf bytes.Buffer expire := uint(time.Now().Unix()) + d.Config.CacheTime*60 - var exp []byte - exp = make([]byte, 4) + exp := make([]byte, 4) binary.BigEndian.PutUint32(exp, uint32(expire)) _, _ = buf.Write(exp) diff --git a/internal/dnsfilter/sb_pc.go b/internal/dnsfilter/sb_pc.go index bf8e8a46..eb5457a6 100644 --- a/internal/dnsfilter/sb_pc.go +++ b/internal/dnsfilter/sb_pc.go @@ -22,11 +22,13 @@ import ( "golang.org/x/net/publicsuffix" ) -const dnsTimeout = 3 * time.Second -const defaultSafebrowsingServer = "https://dns-family.adguard.com/dns-query" -const defaultParentalServer = "https://dns-family.adguard.com/dns-query" -const sbTXTSuffix = "sb.dns.adguard.com." -const pcTXTSuffix = "pc.dns.adguard.com." +const ( + dnsTimeout = 3 * time.Second + defaultSafebrowsingServer = `https://dns-family.adguard.com/dns-query` + defaultParentalServer = `https://dns-family.adguard.com/dns-query` + sbTXTSuffix = `sb.dns.adguard.com.` + pcTXTSuffix = `pc.dns.adguard.com.` +) func (d *Dnsfilter) initSecurityServices() error { var err error @@ -60,7 +62,7 @@ expire byte[4] hash byte[32] ... */ -func (c *sbCtx) setCache(prefix []byte, hashes []byte) { +func (c *sbCtx) setCache(prefix, hashes []byte) { d := make([]byte, 4+len(hashes)) expire := uint(time.Now().Unix()) + c.cacheTime*60 binary.BigEndian.PutUint32(d[:4], uint32(expire)) @@ -158,16 +160,28 @@ func hostnameToHashes(host string) map[[32]byte]string { // convert hash array to string func (c *sbCtx) getQuestion() string { - q := "" + b := &strings.Builder{} + encoder := hex.NewEncoder(b) + for hash := range c.hashToHost { - q += fmt.Sprintf("%s.", hex.EncodeToString(hash[0:2])) + // Ignore errors, since strings.(*Buffer).Write never returns + // errors. + // + // TODO(e.burkov, a.garipov): Find out and document why exactly + // this slice. + _, _ = encoder.Write(hash[0:2]) + _, _ = b.WriteRune('.') } + if c.svc == "SafeBrowsing" { - q += sbTXTSuffix - } else { - q += pcTXTSuffix + // See comment above. + _, _ = b.WriteString(sbTXTSuffix) + return b.String() } - return q + + // See comment above. + _, _ = b.WriteString(pcTXTSuffix) + return b.String() } // Find the target hash in TXT response diff --git a/internal/dnsfilter/sb_pc_test.go b/internal/dnsfilter/sb_pc_test.go index 4d4d4d04..93746363 100644 --- a/internal/dnsfilter/sb_pc_test.go +++ b/internal/dnsfilter/sb_pc_test.go @@ -23,16 +23,16 @@ func TestSafeBrowsingHash(t *testing.T) { assert.False(t, ok) c := &sbCtx{ - svc: "SafeBrowsing", + svc: "SafeBrowsing", + hashToHost: hashes, } - // test getQuestion() - c.hashToHost = hashes q := c.getQuestion() - assert.True(t, strings.Index(q, "7a1b.") >= 0) - assert.True(t, strings.Index(q, "af5a.") >= 0) - assert.True(t, strings.Index(q, "eb11.") >= 0) - assert.True(t, strings.Index(q, "sb.dns.adguard.com.") > 0) + + assert.True(t, strings.Contains(q, "7a1b.")) + assert.True(t, strings.Contains(q, "af5a.")) + assert.True(t, strings.Contains(q, "eb11.")) + assert.True(t, strings.HasSuffix(q, "sb.dns.adguard.com.")) } func TestSafeBrowsingCache(t *testing.T) { diff --git a/internal/home/auth.go b/internal/home/auth.go index a7888e31..ca3f653a 100644 --- a/internal/home/auth.go +++ b/internal/home/auth.go @@ -27,14 +27,12 @@ type session struct { expire uint32 // expiration time (in seconds) } -/* -expire byte[4] -name_len byte[2] -name byte[] -*/ func (s *session) serialize() []byte { - var data []byte - data = make([]byte, 4+2+len(s.userName)) + const ( + expireLen = 4 + nameLen = 2 + ) + data := make([]byte, expireLen+nameLen+len(s.userName)) binary.BigEndian.PutUint32(data[0:4], s.expire) binary.BigEndian.PutUint16(data[4:6], uint16(len(s.userName))) copy(data[6:], []byte(s.userName)) @@ -474,7 +472,7 @@ func (a *Auth) UserAdd(u *User, password string) { } // UserFind - find a user -func (a *Auth) UserFind(login string, password string) User { +func (a *Auth) UserFind(login, password string) User { a.lock.Lock() defer a.lock.Unlock() for _, u := range a.users { diff --git a/internal/home/filter.go b/internal/home/filter.go index 93801a0b..5c6b0fa6 100644 --- a/internal/home/filter.go +++ b/internal/home/filter.go @@ -16,7 +16,6 @@ import ( "time" "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter" - "github.com/AdguardTeam/AdGuardHome/internal/util" "github.com/AdguardTeam/golibs/log" ) @@ -548,8 +547,10 @@ func (f *Filtering) updateIntl(filter *filter) (bool, error) { total += n if htmlTest { - // gather full buffer firstChunk and perform its data tests - num := util.MinInt(n, len(firstChunk)-firstChunkLen) + num := len(firstChunk) - firstChunkLen + if n < num { + num = n + } copied := copy(firstChunk[firstChunkLen:], buf[:num]) firstChunkLen += copied @@ -559,8 +560,7 @@ func (f *Filtering) updateIntl(filter *filter) (bool, error) { } s := strings.ToLower(string(firstChunk)) - if strings.Index(s, "= 0 || - strings.Index(s, "= 0 { + if strings.Contains(s, "= a[j].Count { - return true - } - return false + return a[j].Count < a[i].Count } sort.Slice(a, less) if max > len(a) { @@ -297,15 +294,17 @@ func convertArrayToMap(a []countPair) map[string]uint64 { func serialize(u *unit) *unitDB { udb := unitDB{} udb.NTotal = u.nTotal - for _, it := range u.nResult { - udb.NResult = append(udb.NResult, it) - } + + udb.NResult = append(udb.NResult, u.nResult...) + if u.nTotal != 0 { udb.TimeAvg = uint32(u.timeSum / u.nTotal) } + udb.Domains = convertMapToArray(u.domains, maxDomains) udb.BlockedDomains = convertMapToArray(u.blockedDomains, maxDomains) udb.Clients = convertMapToArray(u.clients, maxClients) + return &udb } @@ -499,7 +498,8 @@ func (s *statsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) { curID := s.unit.id s.unitLock.Unlock() - units := []*unitDB{} //per-hour units + // Per-hour units. + units := []*unitDB{} firstID := curID - limit + 1 for i := firstID; i != curID; i++ { u := s.loadUnitFromDB(tx, i) diff --git a/internal/util/auto_hosts.go b/internal/util/auto_hosts.go index 1cec9c1a..4230eae0 100644 --- a/internal/util/auto_hosts.go +++ b/internal/util/auto_hosts.go @@ -59,7 +59,7 @@ func (a *AutoHosts) Init(hostsFn string) { a.hostsFn = hostsFn } - if IsOpenWrt() { + if IsOpenWRT() { a.hostsDirs = append(a.hostsDirs, "/tmp/hosts") // OpenWRT: "/tmp/hosts/dhcp.cfg01411c" } @@ -106,8 +106,8 @@ func (a *AutoHosts) Close() { } } -// Process - get the list of IP addresses for the hostname -// Return nil if not found +// Process returns the list of IP addresses for the hostname or nil if nothing +// found. func (a *AutoHosts) Process(host string, qtype uint16) []net.IP { if qtype == dns.TypePTR { return nil @@ -115,11 +115,12 @@ func (a *AutoHosts) Process(host string, qtype uint16) []net.IP { var ipsCopy []net.IP a.lock.Lock() - ips, _ := a.table[host] - if len(ips) != 0 { + + if ips, ok := a.table[host]; ok { ipsCopy = make([]net.IP, len(ips)) copy(ipsCopy, ips) } + a.lock.Unlock() log.Debug("AutoHosts: answer: %s -> %v", host, ipsCopy) @@ -256,18 +257,16 @@ func (a *AutoHosts) load(table map[string][]net.IP, tableRev map[string]string, func (a *AutoHosts) watcherLoop() { for { select { - case event, ok := <-a.watcher.Events: if !ok { return } - // skip duplicate events repeat := true for repeat { select { - case _ = <-a.watcher.Events: - // skip this event + case <-a.watcher.Events: + // Skip this duplicating event default: repeat = false } @@ -292,18 +291,15 @@ func (a *AutoHosts) watcherLoop() { } } -// updateLoop - read static hosts from system files +// updateLoop reads static hosts from system files. func (a *AutoHosts) updateLoop() { - for { - select { - case ok := <-a.updateChan: - if !ok { - log.Debug("Finished AutoHosts update loop") - return - } - - a.updateHosts() + for ok := range a.updateChan { + if !ok { + log.Debug("Finished AutoHosts update loop") + return } + + a.updateHosts() } } diff --git a/internal/util/helpers.go b/internal/util/helpers.go index 08afa3f1..4b38746e 100644 --- a/internal/util/helpers.go +++ b/internal/util/helpers.go @@ -10,26 +10,23 @@ import ( "strings" ) -// ContainsString checks if "v" is in the array "arr" -func ContainsString(arr []string, v string) bool { - for _, i := range arr { - if i == v { +// ContainsString checks if string is in the slice of strings. +func ContainsString(strs []string, str string) bool { + for _, s := range strs { + if s == str { return true } } return false } -// fileExists returns TRUE if file exists +// FileExists returns true if file exists. func FileExists(fn string) bool { _, err := os.Stat(fn) - if err != nil { - return false - } - return true + return err == nil } -// runCommand runs shell command +// RunCommand runs shell command. func RunCommand(command string, arguments ...string) (int, string, error) { cmd := exec.Command(command, arguments...) out, err := cmd.Output() @@ -71,16 +68,8 @@ func SplitNext(str *string, splitBy byte) string { return strings.TrimSpace(s) } -// MinInt - return the minimum value -func MinInt(a, b int) int { - if a < b { - return a - } - return b -} - -// IsOpenWrt checks if OS is OpenWRT -func IsOpenWrt() bool { +// IsOpenWRT checks if OS is OpenWRT. +func IsOpenWRT() bool { if runtime.GOOS != "linux" { return false } @@ -92,12 +81,3 @@ func IsOpenWrt() bool { return strings.Contains(string(body), "OpenWrt") } - -// IsFreeBSD checks if OS is FreeBSD -func IsFreeBSD() bool { - if runtime.GOOS == "freebsd" { - return true - } - - return false -}