diff --git a/go.mod b/go.mod index fe03acd7..71fbe5c6 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,6 @@ require ( github.com/gobuffalo/packr v1.30.1 github.com/hugelgupf/socketpair v0.0.0-20190730060125-05d35a94e714 github.com/insomniacslk/dhcp v0.0.0-20200621044212-d74cd86ad5b8 - github.com/joomcode/errorx v1.0.3 github.com/kardianos/service v1.1.0 github.com/mdlayher/ethernet v0.0.0-20190606142754-0394541c37b7 github.com/mdlayher/raw v0.0.0-20191009151244-50f2db8cc065 diff --git a/go.sum b/go.sum index acefe4a0..09d11e64 100644 --- a/go.sum +++ b/go.sum @@ -136,8 +136,6 @@ github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= github.com/joomcode/errorx v1.0.1 h1:CalpDWz14ZHd68fIqluJasJosAewpz2TFaJALrUxjrk= github.com/joomcode/errorx v1.0.1/go.mod h1:kgco15ekB6cs+4Xjzo7SPeXzx38PbJzBwbnu9qfVNHQ= -github.com/joomcode/errorx v1.0.3 h1:3e1mi0u7/HTPNdg6d6DYyKGBhA5l9XpsfuVE29NxnWw= -github.com/joomcode/errorx v1.0.3/go.mod h1:eQzdtdlNyN7etw6YCS4W4+lu442waxZYw5yvz0ULrRo= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/kardianos/service v1.1.0 h1:QV2SiEeWK42P0aEmGcsAgjApw/lRxkwopvT+Gu6t1/0= diff --git a/internal/agherr/agherr.go b/internal/agherr/agherr.go new file mode 100644 index 00000000..4ef3b9c4 --- /dev/null +++ b/internal/agherr/agherr.go @@ -0,0 +1,59 @@ +// Package agherr contains the extended error type, and the function for +// wrapping several errors. +package agherr + +import ( + "fmt" + "strings" +) + +// manyError is an error containing several wrapped errors. It is created to be +// a simpler version of the API provided by github.com/joomcode/errorx. +type manyError struct { + message string + underlying []error +} + +// Many wraps several errors and returns a single error. +func Many(message string, underlying ...error) error { + err := &manyError{ + message: message, + underlying: underlying, + } + + return err +} + +// Error implements the error interface for *manyError. +func (e *manyError) Error() string { + switch len(e.underlying) { + case 0: + return e.message + case 1: + return fmt.Sprintf("%s: %s", e.message, e.underlying[0]) + default: + b := &strings.Builder{} + + // Ignore errors, since strings.(*Buffer).Write never returns + // errors. + _, _ = fmt.Fprintf(b, "%s: %s (hidden: %s", e.message, e.underlying[0], e.underlying[1]) + for _, u := range e.underlying[2:] { + // See comment above. + _, _ = fmt.Fprintf(b, ", %s", u) + } + + // See comment above. + _, _ = b.WriteString(")") + + return b.String() + } +} + +// Unwrap implements the hidden errors.wrapper interface for *manyError. +func (e *manyError) Unwrap() error { + if len(e.underlying) == 0 { + return nil + } + + return e.underlying[0] +} diff --git a/internal/agherr/agherr_test.go b/internal/agherr/agherr_test.go new file mode 100644 index 00000000..21e3af79 --- /dev/null +++ b/internal/agherr/agherr_test.go @@ -0,0 +1,73 @@ +package agherr + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestError_Error(t *testing.T) { + testCases := []struct { + name string + want string + err error + }{{ + name: "simple", + want: "a", + err: Many("a"), + }, { + name: "wrapping", + want: "a: b", + err: Many("a", errors.New("b")), + }, { + name: "wrapping several", + want: "a: b (hidden: c, d)", + err: Many("a", errors.New("b"), errors.New("c"), errors.New("d")), + }, { + name: "wrapping wrapper", + want: "a: b: c (hidden: d)", + err: Many("a", Many("b", errors.New("c"), errors.New("d"))), + }} + for _, tc := range testCases { + assert.Equal(t, tc.want, tc.err.Error(), tc.name) + } +} + +func TestError_Unwrap(t *testing.T) { + const ( + errSimple = iota + errWrapped + errNil + ) + errs := []error{ + errSimple: errors.New("a"), + errWrapped: fmt.Errorf("%w", errors.New("nested")), + errNil: nil, + } + testCases := []struct { + name string + want error + wrapped error + }{{ + name: "simple", + want: errs[errSimple], + wrapped: Many("a", errs[errSimple]), + }, { + name: "nested", + want: errs[errWrapped], + wrapped: Many("b", errs[errWrapped]), + }, { + name: "nil passed", + want: errs[errNil], + wrapped: Many("c", errs[errNil]), + }, { + name: "nil not passed", + want: nil, + wrapped: Many("d"), + }} + for _, tc := range testCases { + assert.Equal(t, tc.want, errors.Unwrap(tc.wrapped), tc.name) + } +} diff --git a/internal/dhcpd/check_other_dhcp.go b/internal/dhcpd/check_other_dhcp.go index 38471e48..bf3ff1cc 100644 --- a/internal/dhcpd/check_other_dhcp.go +++ b/internal/dhcpd/check_other_dhcp.go @@ -23,7 +23,7 @@ import ( func CheckIfOtherDHCPServersPresentV4(ifaceName string) (bool, error) { iface, err := net.InterfaceByName(ifaceName) if err != nil { - return false, wrapErrPrint(err, "Couldn't find interface by name %s", ifaceName) + return false, fmt.Errorf("couldn't find interface by name %s: %w", ifaceName, err) } // get ipv4 address of an interface @@ -44,7 +44,7 @@ func CheckIfOtherDHCPServersPresentV4(ifaceName string) (bool, error) { req, err := dhcpv4.NewDiscovery(iface.HardwareAddr) if err != nil { - return false, fmt.Errorf("dhcpv4.NewDiscovery: %s", err) + return false, fmt.Errorf("dhcpv4.NewDiscovery: %w", err) } req.Options.Update(dhcpv4.OptClientIdentifier(iface.HardwareAddr)) req.Options.Update(dhcpv4.OptHostName(hostname)) @@ -52,24 +52,24 @@ func CheckIfOtherDHCPServersPresentV4(ifaceName string) (bool, error) { // resolve 0.0.0.0:68 udpAddr, err := net.ResolveUDPAddr("udp4", src) if err != nil { - return false, wrapErrPrint(err, "Couldn't resolve UDP address %s", src) + return false, fmt.Errorf("couldn't resolve UDP address %s: %w", src, err) } if !udpAddr.IP.To4().Equal(srcIP) { - return false, wrapErrPrint(err, "Resolved UDP address is not %s", src) + return false, fmt.Errorf("resolved UDP address is not %s: %w", src, err) } // resolve 255.255.255.255:67 dstAddr, err := net.ResolveUDPAddr("udp4", dst) if err != nil { - return false, wrapErrPrint(err, "Couldn't resolve UDP address %s", dst) + return false, fmt.Errorf("couldn't resolve UDP address %s: %w", dst, err) } // bind to 0.0.0.0:68 log.Tracef("Listening to udp4 %+v", udpAddr) c, err := nclient4.NewRawUDPConn(ifaceName, 68) if err != nil { - return false, wrapErrPrint(err, "Couldn't listen on :68") + return false, fmt.Errorf("couldn't listen on :68: %w", err) } if c != nil { defer c.Close() @@ -78,7 +78,7 @@ func CheckIfOtherDHCPServersPresentV4(ifaceName string) (bool, error) { // send to 255.255.255.255:67 _, err = c.WriteTo(req.ToBytes(), dstAddr) if err != nil { - return false, wrapErrPrint(err, "Couldn't send a packet to %s", dst) + return false, fmt.Errorf("couldn't send a packet to %s: %w", dst, err) } for { @@ -94,7 +94,7 @@ func CheckIfOtherDHCPServersPresentV4(ifaceName string) (bool, error) { return false, nil } if err != nil { - return false, wrapErrPrint(err, "Couldn't receive packet") + return false, fmt.Errorf("couldn't receive packet: %w", err) } log.Tracef("Received packet (%v bytes)", n) @@ -127,12 +127,12 @@ func CheckIfOtherDHCPServersPresentV4(ifaceName string) (bool, error) { func CheckIfOtherDHCPServersPresentV6(ifaceName string) (bool, error) { iface, err := net.InterfaceByName(ifaceName) if err != nil { - return false, fmt.Errorf("DHCPv6: net.InterfaceByName: %s: %s", ifaceName, err) + return false, fmt.Errorf("dhcpv6: net.InterfaceByName: %s: %w", ifaceName, err) } ifaceIPNet := getIfaceIPv6(*iface) if len(ifaceIPNet) == 0 { - return false, fmt.Errorf("DHCPv6: couldn't find IPv6 address of interface %s %+v", ifaceName, iface) + return false, fmt.Errorf("dhcpv6: couldn't find IPv6 address of interface %s %+v", ifaceName, iface) } srcIP := ifaceIPNet[0] @@ -141,27 +141,27 @@ func CheckIfOtherDHCPServersPresentV6(ifaceName string) (bool, error) { req, err := dhcpv6.NewSolicit(iface.HardwareAddr) if err != nil { - return false, fmt.Errorf("DHCPv6: dhcpv6.NewSolicit: %s", err) + return false, fmt.Errorf("dhcpv6: dhcpv6.NewSolicit: %w", err) } udpAddr, err := net.ResolveUDPAddr("udp6", src) if err != nil { - return false, wrapErrPrint(err, "DHCPv6: Couldn't resolve UDP address %s", src) + return false, fmt.Errorf("dhcpv6: Couldn't resolve UDP address %s: %w", src, err) } if !udpAddr.IP.To16().Equal(srcIP) { - return false, wrapErrPrint(err, "DHCPv6: Resolved UDP address is not %s", src) + return false, fmt.Errorf("dhcpv6: Resolved UDP address is not %s: %w", src, err) } dstAddr, err := net.ResolveUDPAddr("udp6", dst) if err != nil { - return false, fmt.Errorf("DHCPv6: Couldn't resolve UDP address %s: %s", dst, err) + return false, fmt.Errorf("dhcpv6: Couldn't resolve UDP address %s: %w", dst, err) } log.Debug("DHCPv6: Listening to udp6 %+v", udpAddr) c, err := nclient6.NewIPv6UDPConn(ifaceName, dhcpv6.DefaultClientPort) if err != nil { - return false, fmt.Errorf("DHCPv6: Couldn't listen on :546: %s", err) + return false, fmt.Errorf("dhcpv6: Couldn't listen on :546: %w", err) } if c != nil { defer c.Close() @@ -169,7 +169,7 @@ func CheckIfOtherDHCPServersPresentV6(ifaceName string) (bool, error) { _, err = c.WriteTo(req.ToBytes(), dstAddr) if err != nil { - return false, fmt.Errorf("DHCPv6: Couldn't send a packet to %s: %s", dst, err) + return false, fmt.Errorf("dhcpv6: Couldn't send a packet to %s: %w", dst, err) } for { @@ -182,7 +182,7 @@ func CheckIfOtherDHCPServersPresentV6(ifaceName string) (bool, error) { return false, nil } if err != nil { - return false, wrapErrPrint(err, "Couldn't receive packet") + return false, fmt.Errorf("couldn't receive packet: %w", err) } log.Debug("DHCPv6: Received packet (%v bytes)", n) diff --git a/internal/dhcpd/helpers.go b/internal/dhcpd/helpers.go index 6c02110f..cb7cf013 100644 --- a/internal/dhcpd/helpers.go +++ b/internal/dhcpd/helpers.go @@ -4,9 +4,6 @@ import ( "encoding/binary" "fmt" "net" - - "github.com/AdguardTeam/golibs/log" - "github.com/joomcode/errorx" ) func isTimeout(err error) bool { @@ -37,17 +34,6 @@ func getIfaceIPv4(iface net.Interface) []net.IP { return res } -func wrapErrPrint(err error, message string, args ...interface{}) error { - var errx error - if err == nil { - errx = fmt.Errorf(message, args...) - } else { - errx = errorx.Decorate(err, message, args...) - } - log.Println(errx.Error()) - return errx -} - func parseIPv4(text string) (net.IP, error) { result := net.ParseIP(text) if result == nil { diff --git a/internal/dhcpd/router_adv.go b/internal/dhcpd/router_adv.go index f4ecae19..e3d386f0 100644 --- a/internal/dhcpd/router_adv.go +++ b/internal/dhcpd/router_adv.go @@ -163,7 +163,7 @@ func (ra *raCtx) Init() error { return nil } - log.Debug("DHCPv6 RA: source IP address: %s DNS IP address: %s", + log.Debug("dhcpv6 ra: source IP address: %s DNS IP address: %s", ra.ipAddr, ra.dnsIPAddr) params := icmpv6RA{ @@ -183,7 +183,7 @@ func (ra *raCtx) Init() error { ipAndScope := ra.ipAddr.String() + "%" + ra.ifaceName ra.conn, err = icmp.ListenPacket("ip6:ipv6-icmp", ipAndScope) if err != nil { - return fmt.Errorf("DHCPv6 RA: icmp.ListenPacket: %s", err) + return fmt.Errorf("dhcpv6 ra: icmp.ListenPacket: %w", err) } success := false defer func() { @@ -195,11 +195,11 @@ func (ra *raCtx) Init() error { con6 := ra.conn.IPv6PacketConn() if err := con6.SetHopLimit(255); err != nil { - return fmt.Errorf("DHCPv6 RA: SetHopLimit: %s", err) + return fmt.Errorf("dhcpv6 ra: SetHopLimit: %w", err) } if err := con6.SetMulticastHopLimit(255); err != nil { - return fmt.Errorf("DHCPv6 RA: SetMulticastHopLimit: %s", err) + return fmt.Errorf("dhcpv6 ra: SetMulticastHopLimit: %w", err) } msg := &ipv6.ControlMessage{ @@ -212,15 +212,15 @@ func (ra *raCtx) Init() error { } go func() { - log.Debug("DHCPv6 RA: starting to send periodic RouterAdvertisement packets") + log.Debug("dhcpv6 ra: starting to send periodic RouterAdvertisement packets") for ra.stop.Load() == 0 { _, err = con6.WriteTo(data, msg, addr) if err != nil { - log.Error("DHCPv6 RA: WriteTo: %s", err) + log.Error("dhcpv6 ra: WriteTo: %s", err) } time.Sleep(ra.packetSendPeriod) } - log.Debug("DHCPv6 RA: loop exit") + log.Debug("dhcpv6 ra: loop exit") }() success = true @@ -229,7 +229,7 @@ func (ra *raCtx) Init() error { // Close - close module func (ra *raCtx) Close() { - log.Debug("DHCPv6 RA: closing") + log.Debug("dhcpv6 ra: closing") ra.stop.Store(1) diff --git a/internal/dhcpd/v4.go b/internal/dhcpd/v4.go index e820b0da..e0acdad0 100644 --- a/internal/dhcpd/v4.go +++ b/internal/dhcpd/v4.go @@ -55,7 +55,7 @@ func (s *v4Server) ResetLeases(leases []*Lease) { if l.Expiry.Unix() != leaseExpireStatic && !ip4InRange(s.conf.ipStart, s.conf.ipEnd, l.IP) { - log.Debug("DHCPv4: skipping a lease with IP %v: not within current IP range", l.IP) + log.Debug("dhcpv4: skipping a lease with IP %v: not within current IP range", l.IP) continue } @@ -124,7 +124,7 @@ func (s *v4Server) blacklistLease(lease *Lease) { // Remove (swap) lease by index func (s *v4Server) leaseRemoveSwapByIndex(i int) { s.ipAddrs[s.leases[i].IP[3]] = 0 - log.Debug("DHCPv4: removed lease %s", s.leases[i].HWAddr) + log.Debug("dhcpv4: removed lease %s", s.leases[i].HWAddr) n := len(s.leases) if i != n-1 { @@ -168,7 +168,7 @@ func (s *v4Server) rmDynamicLease(lease Lease) error { func (s *v4Server) addLease(l *Lease) { s.leases = append(s.leases, l) s.ipAddrs[l.IP[3]] = 1 - log.Debug("DHCPv4: added lease %s <-> %s", l.IP, l.HWAddr) + log.Debug("dhcpv4: added lease %s <-> %s", l.IP, l.HWAddr) } // Remove a lease with the same properties @@ -178,8 +178,7 @@ func (s *v4Server) rmLease(lease Lease) error { if !bytes.Equal(l.HWAddr, lease.HWAddr) || l.Hostname != lease.Hostname { - - return fmt.Errorf("Lease not found") + return fmt.Errorf("lease not found") } s.leaseRemoveSwapByIndex(i) @@ -238,7 +237,6 @@ func (s *v4Server) RemoveStaticLease(l Lease) error { // Send ICMP to the specified machine // Return TRUE if it doesn't reply, which probably means that the IP is available func (s *v4Server) addrAvailable(target net.IP) bool { - if s.conf.ICMPTimeout == 0 { return true } @@ -256,15 +254,15 @@ func (s *v4Server) addrAvailable(target net.IP) bool { pinger.OnRecv = func(pkt *ping.Packet) { reply = true } - log.Debug("DHCPv4: Sending ICMP Echo to %v", target) + log.Debug("dhcpv4: Sending ICMP Echo to %v", target) pinger.Run() if reply { - log.Info("DHCPv4: IP conflict: %v is already used by another device", target) + log.Info("dhcpv4: IP conflict: %v is already used by another device", target) return false } - log.Debug("DHCPv4: ICMP procedure is complete: %v", target) + log.Debug("dhcpv4: ICMP procedure is complete: %v", target) return true } @@ -349,7 +347,7 @@ func (s *v4Server) processDiscover(req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4) *Lea for lease == nil { lease = s.reserveLease(mac) if lease == nil { - log.Debug("DHCPv4: No more IP addresses") + log.Debug("dhcpv4: No more IP addresses") if toStore { s.conf.notify(LeaseChangedDBStore) } @@ -372,7 +370,7 @@ func (s *v4Server) processDiscover(req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4) *Lea reqIP := req.Options.Get(dhcpv4.OptionRequestedIPAddress) if len(reqIP) != 0 && !bytes.Equal(reqIP, lease.IP) { - log.Debug("DHCPv4: different RequestedIP: %v != %v", reqIP, lease.IP) + log.Debug("dhcpv4: different RequestedIP: %v != %v", reqIP, lease.IP) } } @@ -407,7 +405,6 @@ func (o *optFQDN) ToBytes() []byte { copy(b[i:], []byte(o.name)) return b - } // Process Request request and return lease @@ -424,12 +421,12 @@ func (s *v4Server) processRequest(req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4) (*Lea sid := req.Options.Get(dhcpv4.OptionServerIdentifier) if len(sid) != 0 && !bytes.Equal(sid, s.conf.dnsIPAddrs[0]) { - log.Debug("DHCPv4: Bad OptionServerIdentifier in Request message for %s", mac) + log.Debug("dhcpv4: Bad OptionServerIdentifier in Request message for %s", mac) return nil, false } if len(reqIP) != 4 { - log.Debug("DHCPv4: Bad OptionRequestedIPAddress in Request message for %s", mac) + log.Debug("dhcpv4: Bad OptionRequestedIPAddress in Request message for %s", mac) return nil, false } @@ -438,7 +435,7 @@ func (s *v4Server) processRequest(req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4) (*Lea if bytes.Equal(l.HWAddr, mac) { if !bytes.Equal(l.IP, reqIP) { s.leasesLock.Unlock() - log.Debug("DHCPv4: Mismatched OptionRequestedIPAddress in Request message for %s", mac) + log.Debug("dhcpv4: Mismatched OptionRequestedIPAddress in Request message for %s", mac) return nil, true } @@ -449,7 +446,7 @@ func (s *v4Server) processRequest(req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4) (*Lea s.leasesLock.Unlock() if lease == nil { - log.Debug("DHCPv4: No lease for %s", mac) + log.Debug("dhcpv4: No lease for %s", mac) return nil, true } @@ -476,7 +473,6 @@ func (s *v4Server) processRequest(req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4) (*Lea // Return 0: error; reply with Nak // Return -1: error; don't reply func (s *v4Server) process(req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4) int { - var lease *Lease resp.UpdateOption(dhcpv4.OptServerIdentifier(s.conf.dnsIPAddrs[0])) @@ -519,7 +515,7 @@ func (s *v4Server) process(req *dhcpv4.DHCPv4, resp *dhcpv4.DHCPv4) int { // client(0.0.0.0:68) -> (Request:ClientMAC,Type=Request,ClientID,ReqIP||ClientIP,HostName,ServerID,ParamReqList) -> server(255.255.255.255:67) // client(255.255.255.255:68) <- (Reply:YourIP,ClientMAC,Type=ACK,ServerID,SubnetMask,LeaseTime) <- server(:67) func (s *v4Server) packetHandler(conn net.PacketConn, peer net.Addr, req *dhcpv4.DHCPv4) { - log.Debug("DHCPv4: received message: %s", req.Summary()) + log.Debug("dhcpv4: received message: %s", req.Summary()) switch req.MessageType() { case dhcpv4.MessageTypeDiscover, @@ -527,18 +523,18 @@ func (s *v4Server) packetHandler(conn net.PacketConn, peer net.Addr, req *dhcpv4 // default: - log.Debug("DHCPv4: unsupported message type %d", req.MessageType()) + log.Debug("dhcpv4: unsupported message type %d", req.MessageType()) return } resp, err := dhcpv4.NewReplyFromRequest(req) if err != nil { - log.Debug("DHCPv4: dhcpv4.New: %s", err) + log.Debug("dhcpv4: dhcpv4.New: %s", err) return } if len(req.ClientHWAddr) != 6 { - log.Debug("DHCPv4: Invalid ClientHWAddr") + log.Debug("dhcpv4: Invalid ClientHWAddr") return } @@ -549,11 +545,11 @@ func (s *v4Server) packetHandler(conn net.PacketConn, peer net.Addr, req *dhcpv4 resp.Options.Update(dhcpv4.OptMessageType(dhcpv4.MessageTypeNak)) } - log.Debug("DHCPv4: sending: %s", resp.Summary()) + log.Debug("dhcpv4: sending: %s", resp.Summary()) _, err = conn.WriteTo(resp.ToBytes(), peer) if err != nil { - log.Error("DHCPv4: conn.Write to %s failed: %s", peer, err) + log.Error("dhcpv4: conn.Write to %s failed: %s", peer, err) return } } @@ -566,13 +562,13 @@ func (s *v4Server) Start() error { iface, err := net.InterfaceByName(s.conf.InterfaceName) if err != nil { - return fmt.Errorf("DHCPv4: Couldn't find interface by name %s: %s", s.conf.InterfaceName, err) + return fmt.Errorf("dhcpv4: Couldn't find interface by name %s: %w", s.conf.InterfaceName, err) } - log.Debug("DHCPv4: starting...") + log.Debug("dhcpv4: starting...") s.conf.dnsIPAddrs = getIfaceIPv4(*iface) if len(s.conf.dnsIPAddrs) == 0 { - log.Debug("DHCPv4: no IPv6 address for interface %s", iface.Name) + log.Debug("dhcpv4: no IPv6 address for interface %s", iface.Name) return nil } @@ -585,11 +581,11 @@ func (s *v4Server) Start() error { return err } - log.Info("DHCPv4: listening") + log.Info("dhcpv4: listening") go func() { err = s.srv.Serve() - log.Debug("DHCPv4: srv.Serve: %s", err) + log.Debug("dhcpv4: srv.Serve: %s", err) }() return nil } @@ -600,10 +596,10 @@ func (s *v4Server) Stop() { return } - log.Debug("DHCPv4: stopping") + log.Debug("dhcpv4: stopping") err := s.srv.Close() if err != nil { - log.Error("DHCPv4: srv.Close: %s", err) + log.Error("dhcpv4: srv.Close: %s", err) } // now s.srv.Serve() will return s.srv = nil @@ -621,31 +617,31 @@ func v4Create(conf V4ServerConf) (DHCPServer, error) { var err error s.conf.routerIP, err = parseIPv4(s.conf.GatewayIP) if err != nil { - return s, fmt.Errorf("DHCPv4: %s", err) + return s, fmt.Errorf("dhcpv4: %w", err) } subnet, err := parseIPv4(s.conf.SubnetMask) if err != nil || !isValidSubnetMask(subnet) { - return s, fmt.Errorf("DHCPv4: invalid subnet mask: %s", s.conf.SubnetMask) + return s, fmt.Errorf("dhcpv4: invalid subnet mask: %s", s.conf.SubnetMask) } s.conf.subnetMask = make([]byte, 4) copy(s.conf.subnetMask, subnet) s.conf.ipStart, err = parseIPv4(conf.RangeStart) if s.conf.ipStart == nil { - return s, fmt.Errorf("DHCPv4: %s", err) + return s, fmt.Errorf("dhcpv4: %w", err) } if s.conf.ipStart[0] == 0 { - return s, fmt.Errorf("DHCPv4: invalid range start IP") + return s, fmt.Errorf("dhcpv4: invalid range start IP") } s.conf.ipEnd, err = parseIPv4(conf.RangeEnd) if s.conf.ipEnd == nil { - return s, fmt.Errorf("DHCPv4: %s", err) + return s, fmt.Errorf("dhcpv4: %w", err) } if !net.IP.Equal(s.conf.ipStart[:3], s.conf.ipEnd[:3]) || s.conf.ipStart[3] > s.conf.ipEnd[3] { - return s, fmt.Errorf("DHCPv4: range end IP should match range start IP") + return s, fmt.Errorf("dhcpv4: range end IP should match range start IP") } if conf.LeaseDuration == 0 { @@ -658,7 +654,7 @@ func v4Create(conf V4ServerConf) (DHCPServer, error) { for _, o := range conf.Options { code, val := parseOptionString(o) if code == 0 { - log.Debug("DHCPv4: bad option string: %s", o) + log.Debug("dhcpv4: bad option string: %s", o) continue } diff --git a/internal/dhcpd/v6.go b/internal/dhcpd/v6.go index e9ad0193..8ea4a576 100644 --- a/internal/dhcpd/v6.go +++ b/internal/dhcpd/v6.go @@ -73,12 +73,10 @@ func (s *v6Server) GetLeases(flags int) []Lease { var result []Lease s.leasesLock.Lock() for _, lease := range s.leases { - if lease.Expiry.Unix() == leaseExpireStatic { if (flags & LeasesStatic) != 0 { result = append(result, *lease) } - } else { if (flags & LeasesDynamic) != 0 { result = append(result, *lease) @@ -215,8 +213,7 @@ func (s *v6Server) rmLease(lease Lease) error { if !bytes.Equal(l.HWAddr, lease.HWAddr) || l.Hostname != lease.Hostname { - - return fmt.Errorf("Lease not found") + return fmt.Errorf("lease not found") } s.leaseRemoveSwapByIndex(i) @@ -303,7 +300,7 @@ func (s *v6Server) commitDynamicLease(l *Lease) { // Check Client ID func (s *v6Server) checkCID(msg *dhcpv6.Message) error { if msg.Options.ClientID() == nil { - return fmt.Errorf("DHCPv6: no ClientID option in request") + return fmt.Errorf("dhcpv6: no ClientID option in request") } return nil } @@ -318,7 +315,7 @@ func (s *v6Server) checkSID(msg *dhcpv6.Message) error { dhcpv6.MessageTypeRebind: if sid != nil { - return fmt.Errorf("DHCPv6: drop packet: ServerID option in message %s", msg.Type().String()) + return fmt.Errorf("dhcpv6: drop packet: ServerID option in message %s", msg.Type().String()) } case dhcpv6.MessageTypeRequest, @@ -327,10 +324,10 @@ func (s *v6Server) checkSID(msg *dhcpv6.Message) error { dhcpv6.MessageTypeDecline: if sid == nil { - return fmt.Errorf("DHCPv6: drop packet: no ServerID option in message %s", msg.Type().String()) + return fmt.Errorf("dhcpv6: drop packet: no ServerID option in message %s", msg.Type().String()) } if !sid.Equal(s.sid) { - return fmt.Errorf("DHCPv6: drop packet: mismatched ServerID option in message %s: %s", + return fmt.Errorf("dhcpv6: drop packet: mismatched ServerID option in message %s: %s", msg.Type().String(), sid.String()) } } @@ -589,7 +586,7 @@ func (s *v6Server) Start() error { iface, err := net.InterfaceByName(s.conf.InterfaceName) if err != nil { - return wrapErrPrint(err, "Couldn't find interface by name %s", s.conf.InterfaceName) + return fmt.Errorf("couldn't find interface by name %s: %w", s.conf.InterfaceName, err) } s.conf.dnsIPAddrs = getIfaceIPv6(*iface) @@ -612,7 +609,7 @@ func (s *v6Server) Start() error { log.Debug("DHCPv6: starting...") if len(iface.HardwareAddr) != 6 { - return fmt.Errorf("DHCPv6: invalid MAC %s", iface.HardwareAddr) + return fmt.Errorf("dhcpv6: invalid MAC %s", iface.HardwareAddr) } s.sid = dhcpv6.Duid{ Type: dhcpv6.DUID_LLT, @@ -667,7 +664,7 @@ func v6Create(conf V6ServerConf) (DHCPServer, error) { s.conf.ipStart = net.ParseIP(conf.RangeStart) if s.conf.ipStart == nil || s.conf.ipStart.To16() == nil { - return s, fmt.Errorf("DHCPv6: invalid range-start IP: %s", conf.RangeStart) + return s, fmt.Errorf("dhcpv6: invalid range-start IP: %s", conf.RangeStart) } if conf.LeaseDuration == 0 { diff --git a/internal/dnsfilter/README.md b/internal/dnsfilter/README.md index 3b90e004..218ba7a7 100644 --- a/internal/dnsfilter/README.md +++ b/internal/dnsfilter/README.md @@ -22,12 +22,12 @@ func main() { res, err := filter.CheckHost(host) if err != nil { // temporary failure - log.Fatalf("Failed to check host '%s': %s", host, err) + log.Fatalf("Failed to check host %q: %s", host, err) } if res.IsFiltered { - log.Printf("Host %s is filtered, reason - '%s', matched rule: '%s'", host, res.Reason, res.Rule) + log.Printf("Host %s is filtered, reason - %q, matched rule: %q", host, res.Reason, res.Rule) } else { - log.Printf("Host %s is not filtered, reason - '%s'", host, res.Reason) + log.Printf("Host %s is not filtered, reason - %q", host, res.Reason) } } ``` @@ -59,12 +59,12 @@ func main() { res, err := filter.CheckHost(host) if err != nil { // temporary failure - log.Fatalf("Failed to check host '%s': %s", host, err) + log.Fatalf("Failed to check host %q: %s", host, err) } if res.IsFiltered { - log.Printf("Host %s is filtered, reason - '%s', matched rule: '%s'", host, res.Reason, res.Rule) + log.Printf("Host %s is filtered, reason - %q, matched rule: %q", host, res.Reason, res.Rule) } else { - log.Printf("Host %s is not filtered, reason - '%s'", host, res.Reason) + log.Printf("Host %s is not filtered, reason - %q", host, res.Reason) } } ``` diff --git a/internal/dnsfilter/dnsfilter.go b/internal/dnsfilter/dnsfilter.go index 81ec3d63..10665216 100644 --- a/internal/dnsfilter/dnsfilter.go +++ b/internal/dnsfilter/dnsfilter.go @@ -501,19 +501,17 @@ func createFilteringEngine(filters []Filter) (*filterlist.RuleStorage, *urlfilte RulesText: string(f.Data), IgnoreCosmetic: true, } - } else if !fileExists(f.FilePath) { list = &filterlist.StringRuleList{ ID: int(f.ID), IgnoreCosmetic: true, } - } 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. data, err := ioutil.ReadFile(f.FilePath) if err != nil { - return nil, nil, fmt.Errorf("ioutil.ReadFile(): %s: %s", f.FilePath, err) + return nil, nil, fmt.Errorf("ioutil.ReadFile(): %s: %w", f.FilePath, err) } list = &filterlist.StringRuleList{ ID: int(f.ID), @@ -525,7 +523,7 @@ func createFilteringEngine(filters []Filter) (*filterlist.RuleStorage, *urlfilte var err error list, err = filterlist.NewFileRuleList(int(f.ID), f.FilePath, true) if err != nil { - return nil, nil, fmt.Errorf("filterlist.NewFileRuleList(): %s: %s", f.FilePath, err) + return nil, nil, fmt.Errorf("filterlist.NewFileRuleList(): %s: %w", f.FilePath, err) } } listArray = append(listArray, list) @@ -533,7 +531,7 @@ func createFilteringEngine(filters []Filter) (*filterlist.RuleStorage, *urlfilte rulesStorage, err := filterlist.NewRuleStorage(listArray) if err != nil { - return nil, nil, fmt.Errorf("filterlist.NewRuleStorage(): %s", err) + return nil, nil, fmt.Errorf("filterlist.NewRuleStorage(): %w", err) } filteringEngine := urlfilter.NewDNSEngine(rulesStorage) return rulesStorage, filteringEngine, nil @@ -590,7 +588,7 @@ func (d *Dnsfilter) matchHost(host string, qtype uint16, setts RequestFilteringS rule = rr.HostRulesV6[0] } - log.Debug("Filtering: found whitelist rule for host '%s': '%s' list_id: %d", + log.Debug("Filtering: found whitelist rule for host %q: %q list_id: %d", host, rule.Text(), rule.GetFilterListID()) res := makeResult(rule, NotFilteredWhiteList) return res, nil @@ -607,7 +605,7 @@ func (d *Dnsfilter) matchHost(host string, qtype uint16, setts RequestFilteringS } if rr.NetworkRule != nil { - log.Debug("Filtering: found rule for host '%s': '%s' list_id: %d", + log.Debug("Filtering: found rule for host %q: %q list_id: %d", host, rr.NetworkRule.Text(), rr.NetworkRule.GetFilterListID()) reason := FilteredBlackList if rr.NetworkRule.Whitelist { @@ -619,7 +617,7 @@ func (d *Dnsfilter) matchHost(host string, qtype uint16, setts RequestFilteringS if qtype == dns.TypeA && rr.HostRulesV4 != nil { rule := rr.HostRulesV4[0] // note that we process only 1 matched rule - log.Debug("Filtering: found rule for host '%s': '%s' list_id: %d", + log.Debug("Filtering: found rule for host %q: %q list_id: %d", host, rule.Text(), rule.GetFilterListID()) res := makeResult(rule, FilteredBlackList) res.IP = rule.IP.To4() @@ -628,7 +626,7 @@ func (d *Dnsfilter) matchHost(host string, qtype uint16, setts RequestFilteringS if qtype == dns.TypeAAAA && rr.HostRulesV6 != nil { rule := rr.HostRulesV6[0] // note that we process only 1 matched rule - log.Debug("Filtering: found rule for host '%s': '%s' list_id: %d", + log.Debug("Filtering: found rule for host %q: %q list_id: %d", host, rule.Text(), rule.GetFilterListID()) res := makeResult(rule, FilteredBlackList) res.IP = rule.IP @@ -644,7 +642,7 @@ func (d *Dnsfilter) matchHost(host string, qtype uint16, setts RequestFilteringS } else if rr.HostRulesV6 != nil { rule = rr.HostRulesV6[0] } - log.Debug("Filtering: found rule for host '%s': '%s' list_id: %d", + log.Debug("Filtering: found rule for host %q: %q list_id: %d", host, rule.Text(), rule.GetFilterListID()) res := makeResult(rule, FilteredBlackList) res.IP = net.IP{} @@ -673,7 +671,6 @@ func InitModule() { // 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, @@ -713,7 +710,7 @@ func New(c *Config, blockFilters []Filter) *Dnsfilter { bsvcs := []string{} for _, s := range d.BlockedServices { if !BlockedSvcKnown(s) { - log.Debug("skipping unknown blocked-service '%s'", s) + log.Debug("skipping unknown blocked-service %q", s) continue } bsvcs = append(bsvcs, s) diff --git a/internal/dnsforward/access.go b/internal/dnsforward/access.go index dbe60de5..5038a89a 100644 --- a/internal/dnsforward/access.go +++ b/internal/dnsforward/access.go @@ -51,7 +51,7 @@ func (a *accessCtx) Init(allowedClients, disallowedClients, blockedHosts []strin listArray = append(listArray, list) rulesStorage, err := filterlist.NewRuleStorage(listArray) if err != nil { - return fmt.Errorf("filterlist.NewRuleStorage(): %s", err) + return fmt.Errorf("filterlist.NewRuleStorage(): %w", err) } a.blockedHostsEngine = urlfilter.NewDNSEngine(rulesStorage) diff --git a/internal/dnsforward/config.go b/internal/dnsforward/config.go index c673252b..93aa312b 100644 --- a/internal/dnsforward/config.go +++ b/internal/dnsforward/config.go @@ -15,7 +15,6 @@ import ( "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/golibs/log" - "github.com/joomcode/errorx" ) // FilteringConfig represents the DNS filtering configuration of AdGuard Home @@ -252,14 +251,14 @@ func (s *Server) prepareUpstreamSettings() error { upstreams = filterOutComments(upstreams) upstreamConfig, err := proxy.ParseUpstreamsConfig(upstreams, s.conf.BootstrapDNS, DefaultTimeout) if err != nil { - return fmt.Errorf("DNS: proxy.ParseUpstreamsConfig: %s", err) + return fmt.Errorf("dns: proxy.ParseUpstreamsConfig: %w", err) } if len(upstreamConfig.Upstreams) == 0 { log.Info("Warning: no default upstream servers specified, using %v", defaultDNS) uc, err := proxy.ParseUpstreamsConfig(defaultDNS, s.conf.BootstrapDNS, DefaultTimeout) if err != nil { - return fmt.Errorf("DNS: failed to parse default upstreams: %v", err) + return fmt.Errorf("dns: failed to parse default upstreams: %v", err) } upstreamConfig.Upstreams = uc.Upstreams } @@ -300,13 +299,13 @@ func (s *Server) prepareTLS(proxyConfig *proxy.Config) error { var err error s.conf.cert, err = tls.X509KeyPair(s.conf.CertificateChainData, s.conf.PrivateKeyData) if err != nil { - return errorx.Decorate(err, "Failed to parse TLS keypair") + return fmt.Errorf("failed to parse TLS keypair: %w", err) } if s.conf.StrictSNICheck { x, err := x509.ParseCertificate(s.conf.cert.Certificate[0]) if err != nil { - return errorx.Decorate(err, "x509.ParseCertificate(): %s", err) + return fmt.Errorf("x509.ParseCertificate(): %w", err) } if len(x.DNSNames) != 0 { s.conf.dnsNames = x.DNSNames diff --git a/internal/dnsforward/dnsforward.go b/internal/dnsforward/dnsforward.go index cf39a5c0..05d2eab9 100644 --- a/internal/dnsforward/dnsforward.go +++ b/internal/dnsforward/dnsforward.go @@ -15,7 +15,6 @@ import ( "github.com/AdguardTeam/AdGuardHome/internal/stats" "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/golibs/log" - "github.com/joomcode/errorx" "github.com/miekg/dns" ) @@ -182,7 +181,7 @@ func (s *Server) Prepare(config *ServerConfig) error { s.conf.BlockingIPAddrv4 = net.ParseIP(s.conf.BlockingIPv4) s.conf.BlockingIPAddrv6 = net.ParseIP(s.conf.BlockingIPv6) if s.conf.BlockingIPAddrv4 == nil || s.conf.BlockingIPAddrv6 == nil { - return fmt.Errorf("DNS: invalid custom blocking IP address specified") + return fmt.Errorf("dns: invalid custom blocking IP address specified") } } if s.conf.MaxGoroutines == 0 { @@ -250,7 +249,7 @@ func (s *Server) stopInternal() error { if s.dnsProxy != nil { err := s.dnsProxy.Stop() if err != nil { - return errorx.Decorate(err, "could not stop the DNS server properly") + return fmt.Errorf("could not stop the DNS server properly: %w", err) } } @@ -273,7 +272,7 @@ func (s *Server) Reconfigure(config *ServerConfig) error { log.Print("Start reconfiguring the server") err := s.stopInternal() if err != nil { - return errorx.Decorate(err, "could not reconfigure the server") + return fmt.Errorf("could not reconfigure the server: %w", err) } // It seems that net.Listener.Close() doesn't close file descriptors right away. @@ -282,12 +281,12 @@ func (s *Server) Reconfigure(config *ServerConfig) error { err = s.Prepare(config) if err != nil { - return errorx.Decorate(err, "could not reconfigure the server") + return fmt.Errorf("could not reconfigure the server: %w", err) } err = s.startInternal() if err != nil { - return errorx.Decorate(err, "could not reconfigure the server") + return fmt.Errorf("could not reconfigure the server: %w", err) } return nil diff --git a/internal/dnsforward/dnsforward_http.go b/internal/dnsforward/dnsforward_http.go index 56a173ba..1e156c50 100644 --- a/internal/dnsforward/dnsforward_http.go +++ b/internal/dnsforward/dnsforward_http.go @@ -17,7 +17,7 @@ import ( func httpError(r *http.Request, w http.ResponseWriter, code int, format string, args ...interface{}) { text := fmt.Sprintf(format, args...) - log.Info("DNS: %s %s: %s", r.Method, r.URL, text) + log.Info("dns: %s %s: %s", r.Method, r.URL, text) http.Error(w, text, code) } @@ -102,7 +102,7 @@ func checkBootstrap(addr string) error { } _, err := upstream.NewResolver(addr, 0) if err != nil { - return fmt.Errorf("invalid bootstrap server address: %s", err) + return fmt.Errorf("invalid bootstrap server address: %w", err) } return nil } @@ -322,7 +322,7 @@ func separateUpstream(upstream string) (string, bool, error) { // split domains and upstream string domainsAndUpstream := strings.Split(strings.TrimPrefix(upstream, "[/"), "/]") if len(domainsAndUpstream) != 2 { - return "", defaultUpstream, fmt.Errorf("wrong DNS upstream per domain specification: %s", upstream) + return "", defaultUpstream, fmt.Errorf("wrong dns upstream per domain specification: %s", upstream) } // split domains list and validate each one @@ -357,7 +357,7 @@ func checkPlainDNS(upstream string) error { _, err = strconv.ParseInt(port, 0, 64) if err != nil { - return fmt.Errorf("%s is not a valid port: %s", port, err) + return fmt.Errorf("%s is not a valid port: %w", port, err) } return nil @@ -405,7 +405,7 @@ func checkDNS(input string, bootstrap []string) error { // separate upstream from domains list input, defaultUpstream, err := separateUpstream(input) if err != nil { - return fmt.Errorf("wrong upstream format: %s", err) + return fmt.Errorf("wrong upstream format: %w", err) } // No need to check this DNS server @@ -414,17 +414,17 @@ func checkDNS(input string, bootstrap []string) error { } if _, err := validateUpstream(input); err != nil { - return fmt.Errorf("wrong upstream format: %s", err) + return fmt.Errorf("wrong upstream format: %w", err) } if len(bootstrap) == 0 { bootstrap = defaultBootstrap } - log.Debug("Checking if DNS %s works...", input) + log.Debug("checking if dns %s works...", input) u, err := upstream.AddressToUpstream(input, upstream.Options{Bootstrap: bootstrap, Timeout: DefaultTimeout}) if err != nil { - return fmt.Errorf("failed to choose upstream for %s: %s", input, err) + return fmt.Errorf("failed to choose upstream for %s: %w", input, err) } req := dns.Msg{} @@ -435,18 +435,18 @@ func checkDNS(input string, bootstrap []string) error { } reply, err := u.Exchange(&req) if err != nil { - return fmt.Errorf("couldn't communicate with DNS server %s: %s", input, err) + return fmt.Errorf("couldn't communicate with dns server %s: %w", input, err) } if len(reply.Answer) != 1 { - return fmt.Errorf("DNS server %s returned wrong answer", input) + return fmt.Errorf("dns server %s returned wrong answer", input) } if t, ok := reply.Answer[0].(*dns.A); ok { if !net.IPv4(8, 8, 8, 8).Equal(t.A) { - return fmt.Errorf("DNS server %s returned wrong answer: %v", input, t.A) + return fmt.Errorf("dns server %s returned wrong answer: %v", input, t.A) } } - log.Debug("DNS %s works OK", input) + log.Debug("dns %s works OK", input) return nil } @@ -462,7 +462,7 @@ func (s *Server) handleDOH(w http.ResponseWriter, r *http.Request) { } if !s.IsRunning() { - httpError(r, w, http.StatusInternalServerError, "DNS server is not running") + httpError(r, w, http.StatusInternalServerError, "dns server is not running") return } diff --git a/internal/dnsforward/filter.go b/internal/dnsforward/filter.go index 0d325624..d2990360 100644 --- a/internal/dnsforward/filter.go +++ b/internal/dnsforward/filter.go @@ -1,12 +1,13 @@ package dnsforward import ( + "fmt" "strings" "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter" "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/golibs/log" - "github.com/joomcode/errorx" + "github.com/miekg/dns" ) @@ -49,10 +50,9 @@ func (s *Server) filterDNSRequest(ctx *dnsContext) (*dnsfilter.Result, error) { res, err := s.dnsFilter.CheckHost(host, d.Req.Question[0].Qtype, ctx.setts) if err != nil { // Return immediately if there's an error - return nil, errorx.Decorate(err, "dnsfilter failed to check host '%s'", host) - + return nil, fmt.Errorf("dnsfilter failed to check host %q: %w", host, err) } else if res.IsFiltered { - log.Tracef("Host %s is filtered, reason - '%s', matched rule: '%s'", host, res.Reason, res.Rule) + log.Tracef("Host %s is filtered, reason - %q, matched rule: %q", host, res.Reason, res.Rule) d.Res = s.genDNSFilterMessage(d, &res) } else if res.Reason == dnsfilter.ReasonRewrite && len(res.CanonName) != 0 && len(res.IPList) == 0 { @@ -136,7 +136,6 @@ func (s *Server) filterDNSResponse(ctx *dnsContext) (*dnsfilter.Result, error) { if err != nil { return nil, err - } else if res.IsFiltered { d.Res = s.genDNSFilterMessage(d, &res) log.Debug("DNSFwd: Matched %s by response: %s", d.Req.Question[0].Name, host) diff --git a/internal/dnsforward/ipset.go b/internal/dnsforward/ipset.go index eeea4608..74a8ecd8 100644 --- a/internal/dnsforward/ipset.go +++ b/internal/dnsforward/ipset.go @@ -31,13 +31,13 @@ func (c *ipsetCtx) init(ipsetConfig []string) { it = strings.TrimSpace(it) hostsAndNames := strings.Split(it, "/") if len(hostsAndNames) != 2 { - log.Debug("IPSET: invalid value '%s'", it) + log.Debug("IPSET: invalid value %q", it) continue } ipsetNames := strings.Split(hostsAndNames[1], ",") if len(ipsetNames) == 0 { - log.Debug("IPSET: invalid value '%s'", it) + log.Debug("IPSET: invalid value %q", it) continue } bad := false @@ -49,7 +49,7 @@ func (c *ipsetCtx) init(ipsetConfig []string) { } } if bad { - log.Debug("IPSET: invalid value '%s'", it) + log.Debug("IPSET: invalid value %q", it) continue } @@ -58,7 +58,7 @@ func (c *ipsetCtx) init(ipsetConfig []string) { host = strings.TrimSpace(host) host = strings.ToLower(host) if len(host) == 0 { - log.Debug("IPSET: invalid value '%s'", it) + log.Debug("IPSET: invalid value %q", it) continue } c.ipsetList[host] = ipsetNames @@ -131,7 +131,7 @@ func (c *ipsetCtx) process(ctx *dnsContext) int { continue } if code != 0 { - log.Info("IPSET: ipset add: code:%d output:'%s'", code, out) + log.Info("IPSET: ipset add: code:%d output:%q", code, out) continue } log.Debug("IPSET: added %s(%s) -> %s", host, ipStr, name) diff --git a/internal/dnsforward/msg.go b/internal/dnsforward/msg.go index 7b295b31..d0811df4 100644 --- a/internal/dnsforward/msg.go +++ b/internal/dnsforward/msg.go @@ -46,7 +46,6 @@ func (s *Server) genDNSFilterMessage(d *proxy.DNSContext, result *dnsfilter.Resu if s.conf.BlockingMode == "null_ip" { // it means that we should return 0.0.0.0 or :: for any blocked request return s.makeResponseNullIP(m) - } else if s.conf.BlockingMode == "custom_ip" { // means that we should return custom IP for any blocked request @@ -56,12 +55,10 @@ func (s *Server) genDNSFilterMessage(d *proxy.DNSContext, result *dnsfilter.Resu case dns.TypeAAAA: return s.genAAAARecord(m, s.conf.BlockingIPAddrv6) } - } else if s.conf.BlockingMode == "nxdomain" { // means that we should return NXDOMAIN for any blocked request return s.genNXDomain(m) - } else if s.conf.BlockingMode == "refused" { // means that we should return NXDOMAIN for any blocked request @@ -148,7 +145,6 @@ func (s *Server) makeResponseNullIP(req *dns.Msg) *dns.Msg { } func (s *Server) genBlockedHost(request *dns.Msg, newAddr string, d *proxy.DNSContext) *dns.Msg { - ip := net.ParseIP(newAddr) if ip != nil { return s.genResponseWithIP(request, ip) @@ -168,7 +164,7 @@ func (s *Server) genBlockedHost(request *dns.Msg, newAddr string, d *proxy.DNSCo err := s.dnsProxy.Resolve(newContext) if err != nil { - log.Printf("Couldn't look up replacement host '%s': %s", newAddr, err) + log.Printf("Couldn't look up replacement host %q: %s", newAddr, err) return s.genServerFailure(request) } diff --git a/internal/home/auth.go b/internal/home/auth.go index ce8eb055..a7888e31 100644 --- a/internal/home/auth.go +++ b/internal/home/auth.go @@ -17,8 +17,10 @@ import ( "golang.org/x/crypto/bcrypt" ) -const cookieTTL = 365 * 24 // in hours -const sessionCookieName = "agh_session" +const ( + cookieTTL = 365 * 24 // in hours + sessionCookieName = "agh_session" +) type session struct { userName string @@ -78,7 +80,7 @@ func InitAuth(dbFilename string, users []User, sessionTTL uint32) *Auth { a.sessions = make(map[string]*session) rand.Seed(time.Now().UTC().Unix()) var err error - a.db, err = bbolt.Open(dbFilename, 0644, nil) + a.db, err = bbolt.Open(dbFilename, 0o644, nil) if err != nil { log.Error("Auth: open DB: %s: %s", dbFilename, err) if err.Error() == "invalid argument" { @@ -318,7 +320,7 @@ func handleLogin(w http.ResponseWriter, r *http.Request) { cookie := Context.auth.httpCookie(req) if len(cookie) == 0 { - log.Info("Auth: invalid user name or password: name='%s'", req.Name) + log.Info("Auth: invalid user name or password: name=%q", req.Name) time.Sleep(1 * time.Second) http.Error(w, "invalid user name or password", http.StatusBadRequest) return @@ -372,7 +374,6 @@ func parseCookie(cookie string) string { // nolint(gocyclo) func optionalAuth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/login.html" { // redirect to dashboard if already authenticated authRequired := Context.auth != nil && Context.auth.AuthRequired() @@ -424,7 +425,6 @@ func optionalAuth(handler func(http.ResponseWriter, *http.Request)) func(http.Re if r.URL.Path == "/" || r.URL.Path == "/index.html" { if glProcessRedirect(w, r) { log.Debug("Auth: redirected to login page by GL-Inet submodule") - } else { w.Header().Set("Location", "/login.html") w.WriteHeader(http.StatusFound) diff --git a/internal/home/clients.go b/internal/home/clients.go index 06333bd8..03a69db3 100644 --- a/internal/home/clients.go +++ b/internal/home/clients.go @@ -126,7 +126,6 @@ func (clients *clientsContainer) Start() { } go clients.periodicUpdate() } - } // Reload - reload auto-clients @@ -173,7 +172,7 @@ func (clients *clientsContainer) addFromConfig(objects []clientObject) { for _, s := range cy.BlockedServices { if !dnsfilter.BlockedSvcKnown(s) { - log.Debug("Clients: skipping unknown blocked-service '%s'", s) + log.Debug("Clients: skipping unknown blocked-service %q", s) continue } cli.BlockedServices = append(cli.BlockedServices, s) @@ -181,7 +180,7 @@ func (clients *clientsContainer) addFromConfig(objects []clientObject) { for _, t := range cy.Tags { if !clients.tagKnown(t) { - log.Debug("Clients: skipping unknown tag '%s'", t) + log.Debug("Clients: skipping unknown tag %q", t) continue } cli.Tags = append(cli.Tags, t) @@ -377,7 +376,7 @@ func (clients *clientsContainer) check(c *Client) error { } if len(c.IDs) == 0 { - return fmt.Errorf("ID required") + return fmt.Errorf("id required") } for i, id := range c.IDs { @@ -409,7 +408,7 @@ func (clients *clientsContainer) check(c *Client) error { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { - return fmt.Errorf("invalid upstream servers: %s", err) + return fmt.Errorf("invalid upstream servers: %w", err) } return nil @@ -448,7 +447,7 @@ func (clients *clientsContainer) Add(c Client) (bool, error) { clients.idIndex[id] = &c } - log.Debug("Clients: added '%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) + log.Debug("Clients: added %q: ID:%v [%d]", c.Name, c.IDs, len(clients.list)) return true, nil } @@ -590,7 +589,7 @@ func (clients *clientsContainer) addHost(ip, host string, source clientSource) ( } clients.ipHost[ip] = ch } - log.Debug("Clients: added '%s' -> '%s' [%d]", ip, host, len(clients.ipHost)) + log.Debug("Clients: added %q -> %q [%d]", ip, host, len(clients.ipHost)) return true, nil } diff --git a/internal/home/control_install.go b/internal/home/control_install.go index 47437e59..fcb8fcea 100644 --- a/internal/home/control_install.go +++ b/internal/home/control_install.go @@ -71,6 +71,7 @@ type checkConfigReqEnt struct { IP string `json:"ip"` Autofix bool `json:"autofix"` } + type checkConfigReq struct { Web checkConfigReqEnt `json:"web"` DNS checkConfigReqEnt `json:"dns"` @@ -81,11 +82,13 @@ type checkConfigRespEnt struct { Status string `json:"status"` CanAutofix bool `json:"can_autofix"` } + type staticIPJSON struct { Static string `json:"static"` IP string `json:"ip"` Error string `json:"error"` } + type checkConfigResp struct { Web checkConfigRespEnt `json:"web"` DNS checkConfigRespEnt `json:"dns"` @@ -214,31 +217,33 @@ func checkDNSStubListener() bool { return true } -const resolvedConfPath = "/etc/systemd/resolved.conf.d/adguardhome.conf" -const resolvedConfData = `[Resolve] +const ( + resolvedConfPath = "/etc/systemd/resolved.conf.d/adguardhome.conf" + resolvedConfData = `[Resolve] DNS=127.0.0.1 DNSStubListener=no ` +) const resolvConfPath = "/etc/resolv.conf" // Deactivate DNSStubListener func disableDNSStubListener() error { dir := filepath.Dir(resolvedConfPath) - err := os.MkdirAll(dir, 0755) + err := os.MkdirAll(dir, 0o755) if err != nil { - return fmt.Errorf("os.MkdirAll: %s: %s", dir, err) + return fmt.Errorf("os.MkdirAll: %s: %w", dir, err) } - err = ioutil.WriteFile(resolvedConfPath, []byte(resolvedConfData), 0644) + err = ioutil.WriteFile(resolvedConfPath, []byte(resolvedConfData), 0o644) if err != nil { - return fmt.Errorf("ioutil.WriteFile: %s: %s", resolvedConfPath, err) + return fmt.Errorf("ioutil.WriteFile: %s: %w", resolvedConfPath, err) } _ = os.Rename(resolvConfPath, resolvConfPath+".backup") err = os.Symlink("/run/systemd/resolve/resolv.conf", resolvConfPath) if err != nil { _ = os.Remove(resolvedConfPath) // remove the file we've just created - return fmt.Errorf("os.Symlink: %s: %s", resolvConfPath, err) + return fmt.Errorf("os.Symlink: %s: %w", resolvConfPath, err) } cmd := exec.Command("systemctl", "reload-or-restart", "systemd-resolved") @@ -259,6 +264,7 @@ type applyConfigReqEnt struct { IP string `json:"ip"` Port int `json:"port"` } + type applyConfigReq struct { Web applyConfigReqEnt `json:"web"` DNS applyConfigReqEnt `json:"dns"` diff --git a/internal/home/dns.go b/internal/home/dns.go index 418a0837..a93bc307 100644 --- a/internal/home/dns.go +++ b/internal/home/dns.go @@ -12,7 +12,6 @@ import ( "github.com/AdguardTeam/AdGuardHome/internal/util" "github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/golibs/log" - "github.com/joomcode/errorx" ) // Called by other modules when configuration is changed @@ -75,7 +74,7 @@ func initDNSServer() error { err = Context.dnsServer.Prepare(&dnsConfig) if err != nil { closeDNSServer() - return fmt.Errorf("dnsServer.Prepare: %s", err) + return fmt.Errorf("dnsServer.Prepare: %w", err) } Context.rdns = InitRDNS(Context.dnsServer, &Context.clients) @@ -96,41 +95,41 @@ func isPublicIP(ip net.IP) bool { if ip4 != nil { switch ip4[0] { case 0: - return false //software + return false // software case 10: - return false //private network + return false // private network case 127: - return false //loopback + return false // loopback case 169: if ip4[1] == 254 { - return false //link-local + return false // link-local } case 172: if ip4[1] >= 16 && ip4[1] <= 31 { - return false //private network + return false // private network } case 192: - if (ip4[1] == 0 && ip4[2] == 0) || //private network - (ip4[1] == 0 && ip4[2] == 2) || //documentation - (ip4[1] == 88 && ip4[2] == 99) || //reserved - (ip4[1] == 168) { //private network + if (ip4[1] == 0 && ip4[2] == 0) || // private network + (ip4[1] == 0 && ip4[2] == 2) || // documentation + (ip4[1] == 88 && ip4[2] == 99) || // reserved + (ip4[1] == 168) { // private network return false } case 198: - if (ip4[1] == 18 || ip4[2] == 19) || //private network - (ip4[1] == 51 || ip4[2] == 100) { //documentation + if (ip4[1] == 18 || ip4[2] == 19) || // private network + (ip4[1] == 51 || ip4[2] == 100) { // documentation return false } case 203: - if ip4[1] == 0 && ip4[2] == 113 { //documentation + if ip4[1] == 0 && ip4[2] == 113 { // documentation return false } case 224: - if ip4[1] == 0 && ip4[2] == 0 { //multicast + if ip4[1] == 0 && ip4[2] == 0 { // multicast return false } case 255: - if ip4[1] == 255 && ip4[2] == 255 && ip4[3] == 255 { //subnet + if ip4[1] == 255 && ip4[2] == 255 && ip4[3] == 255 { // subnet return false } } @@ -313,7 +312,7 @@ func startDNSServer() error { err := Context.dnsServer.Start() if err != nil { - return errorx.Decorate(err, "Couldn't start forwarding DNS server") + return fmt.Errorf("couldn't start forwarding DNS server: %w", err) } Context.dnsFilter.Start() @@ -340,7 +339,7 @@ func reconfigureDNSServer() error { newconfig := generateServerConfig() err := Context.dnsServer.Reconfigure(&newconfig) if err != nil { - return errorx.Decorate(err, "Couldn't start forwarding DNS server") + return fmt.Errorf("couldn't start forwarding DNS server: %w", err) } return nil @@ -353,7 +352,7 @@ func stopDNSServer() error { err := Context.dnsServer.Stop() if err != nil { - return errorx.Decorate(err, "Couldn't stop forwarding DNS server") + return fmt.Errorf("couldn't stop forwarding DNS server: %w", err) } closeDNSServer() diff --git a/internal/home/filter.go b/internal/home/filter.go index 6bcb831c..93801a0b 100644 --- a/internal/home/filter.go +++ b/internal/home/filter.go @@ -20,9 +20,7 @@ import ( "github.com/AdguardTeam/golibs/log" ) -var ( - nextFilterID = time.Now().Unix() // semi-stable way to generate an unique ID -) +var nextFilterID = time.Now().Unix() // semi-stable way to generate an unique ID // Filtering - module object type Filtering struct { @@ -35,7 +33,7 @@ type Filtering struct { // Init - initialize the module func (f *Filtering) Init() { f.filterTitleRegexp = regexp.MustCompile(`^! Title: +(.*)$`) - _ = os.MkdirAll(filepath.Join(Context.getDataDir(), filterDir), 0755) + _ = os.MkdirAll(filepath.Join(Context.getDataDir(), filterDir), 0o755) f.loadFilters(config.Filters) f.loadFilters(config.WhitelistFilters) deduplicateFilters() @@ -466,7 +464,6 @@ func (f *Filtering) parseFilterContents(file io.Reader) (int, uint32, string) { line = strings.TrimSpace(line) if len(line) == 0 { // - } else if line[0] == '!' { m := f.filterTitleRegexp.FindAllStringSubmatch(line, -1) if len(m) > 0 && len(m[0]) >= 2 && !seenTitle { @@ -476,7 +473,6 @@ func (f *Filtering) parseFilterContents(file io.Reader) (int, uint32, string) { } else if line[0] == '#' { // - } else { rulesCount++ } @@ -521,7 +517,7 @@ func (f *Filtering) updateIntl(filter *filter) (bool, error) { if filepath.IsAbs(filter.URL) { f, err := os.Open(filter.URL) if err != nil { - return false, fmt.Errorf("open file: %s", err) + return false, fmt.Errorf("open file: %w", err) } defer f.Close() reader = f diff --git a/internal/home/home.go b/internal/home/home.go index 8dd3115e..8474d552 100644 --- a/internal/home/home.go +++ b/internal/home/home.go @@ -22,11 +22,10 @@ import ( "gopkg.in/natefinch/lumberjack.v2" + "github.com/AdguardTeam/AdGuardHome/internal/agherr" "github.com/AdguardTeam/AdGuardHome/internal/update" "github.com/AdguardTeam/AdGuardHome/internal/util" - "github.com/joomcode/errorx" - "github.com/AdguardTeam/AdGuardHome/internal/isdelve" "github.com/AdguardTeam/AdGuardHome/internal/dhcpd" @@ -113,7 +112,7 @@ func Main(version string, channel string, armVer string) { go func() { for { sig := <-Context.appSignalChannel - log.Info("Received signal '%s'", sig) + log.Info("Received signal %q", sig) switch sig { case syscall.SIGHUP: Context.clients.Reload() @@ -279,7 +278,7 @@ func run(args options) { } } - err := os.MkdirAll(Context.getDataDir(), 0755) + err := os.MkdirAll(Context.getDataDir(), 0o755) if err != nil { log.Fatalf("Cannot create DNS data dir at %s: %s", Context.getDataDir(), err) } @@ -358,7 +357,7 @@ func checkPermissions() { // On Windows we need to have admin rights to run properly admin, _ := util.HaveAdminRights() - if //noinspection ALL + if // noinspection ALL admin || isdelve.Enabled { // Don't forget that for this to work you need to add "delve" tag explicitly // https://stackoverflow.com/questions/47879070/how-can-i-see-if-the-goland-debugger-is-running-in-the-program @@ -404,7 +403,7 @@ Please note, that this is crucial for a DNS server to be able to use that port.` // Write PID to a file func writePIDFile(fn string) bool { data := fmt.Sprintf("%d", os.Getpid()) - err := ioutil.WriteFile(fn, []byte(data), 0644) + err := ioutil.WriteFile(fn, []byte(data), 0o644) if err != nil { log.Error("Couldn't write PID to file %s: %v", fn, err) return false @@ -487,7 +486,7 @@ func configureLogger(args options) { logFilePath = ls.LogFile } - _, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + _, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644) if err != nil { log.Fatalf("cannot create a log file: %s", err) } @@ -498,7 +497,7 @@ func configureLogger(args options) { LocalTime: ls.LogLocalTime, MaxBackups: ls.LogMaxBackups, MaxSize: ls.LogMaxSize, // megabytes - MaxAge: ls.LogMaxAge, //days + MaxAge: ls.LogMaxAge, // days }) } } @@ -662,7 +661,7 @@ func customDialContext(ctx context.Context, network, addr string) (net.Conn, err } return con, err } - return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...) + return nil, agherr.Many(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...) } func getHTTPProxy(req *http.Request) (*url.URL, error) { diff --git a/internal/home/options.go b/internal/home/options.go index 1d8a8a4e..514ed3a1 100644 --- a/internal/home/options.go +++ b/internal/home/options.go @@ -106,7 +106,7 @@ var portArg = arg{ var p int minPort, maxPort := 0, 1<<16-1 if p, err = strconv.Atoi(v); err != nil { - err = fmt.Errorf("port '%s' is not a number", v) + err = fmt.Errorf("port %q is not a number", v) } else if p < minPort || p > maxPort { err = fmt.Errorf("port %d not in range %d - %d", p, minPort, maxPort) } else { diff --git a/internal/home/tls.go b/internal/home/tls.go index a6a90aaf..62c29922 100644 --- a/internal/home/tls.go +++ b/internal/home/tls.go @@ -20,7 +20,6 @@ import ( "time" "github.com/AdguardTeam/golibs/log" - "github.com/joomcode/errorx" ) var tlsWebHandlersRegistered = false @@ -484,13 +483,13 @@ func unmarshalTLS(r *http.Request) (tlsConfigSettings, error) { data := tlsConfigSettings{} err := json.NewDecoder(r.Body).Decode(&data) if err != nil { - return data, errorx.Decorate(err, "Failed to parse new TLS config json") + return data, fmt.Errorf("failed to parse new TLS config json: %w", err) } if data.CertificateChain != "" { certPEM, err := base64.StdEncoding.DecodeString(data.CertificateChain) if err != nil { - return data, errorx.Decorate(err, "Failed to base64-decode certificate chain") + return data, fmt.Errorf("failed to base64-decode certificate chain: %w", err) } data.CertificateChain = string(certPEM) if data.CertificatePath != "" { @@ -501,7 +500,7 @@ func unmarshalTLS(r *http.Request) (tlsConfigSettings, error) { if data.PrivateKey != "" { keyPEM, err := base64.StdEncoding.DecodeString(data.PrivateKey) if err != nil { - return data, errorx.Decorate(err, "Failed to base64-decode private key") + return data, fmt.Errorf("failed to base64-decode private key: %w", err) } data.PrivateKey = string(keyPEM) diff --git a/internal/home/upgrade.go b/internal/home/upgrade.go index bf9e5b51..42fd83d6 100644 --- a/internal/home/upgrade.go +++ b/internal/home/upgrade.go @@ -184,7 +184,7 @@ func upgradeSchema2to3(diskConfig *map[string]interface{}) error { newDNSConfig[fmt.Sprint(k)] = v } default: - return fmt.Errorf("DNS configuration is not a map") + return fmt.Errorf("dns configuration is not a map") } // Replace bootstrap_dns value filed with new array contains old bootstrap_dns inside @@ -217,7 +217,6 @@ func upgradeSchema3to4(diskConfig *map[string]interface{}) error { case []interface{}: for i := range arr { - switch c := arr[i].(type) { case map[interface{}]interface{}: @@ -309,7 +308,6 @@ func upgradeSchema5to6(diskConfig *map[string]interface{}) error { case []interface{}: for i := range arr { - switch c := arr[i].(type) { case map[interface{}]interface{}: diff --git a/internal/home/whois.go b/internal/home/whois.go index ecd76a7b..c7eaac8f 100644 --- a/internal/home/whois.go +++ b/internal/home/whois.go @@ -168,7 +168,7 @@ func (w *Whois) queryAll(target string) (string, error) { log.Debug("Whois: redirected to %s IP:%s", redir, target) } - return "", fmt.Errorf("Whois: redirect loop") + return "", fmt.Errorf("whois: redirect loop") } // Request WHOIS information diff --git a/internal/querylog/qlog_reader.go b/internal/querylog/qlog_reader.go index ee2f617d..d376119d 100644 --- a/internal/querylog/qlog_reader.go +++ b/internal/querylog/qlog_reader.go @@ -3,7 +3,7 @@ package querylog import ( "io" - "github.com/joomcode/errorx" + "github.com/AdguardTeam/AdGuardHome/internal/agherr" ) // QLogReader allows reading from multiple query log files in the reverse order. @@ -132,7 +132,7 @@ func closeQFiles(qFiles []*QLogFile) error { } if len(errs) > 0 { - return errorx.DecorateMany("Error while closing QLogReader", errs...) + return agherr.Many("Error while closing QLogReader", errs...) } return nil diff --git a/internal/update/check.go b/internal/update/check.go index fc6f1203..b10cec73 100644 --- a/internal/update/check.go +++ b/internal/update/check.go @@ -32,12 +32,12 @@ func (u *Updater) GetVersionResponse(forceRecheck bool) (VersionInfo, error) { } if err != nil { - return VersionInfo{}, fmt.Errorf("updater: HTTP GET %s: %s", u.VersionURL, err) + return VersionInfo{}, fmt.Errorf("updater: HTTP GET %s: %w", u.VersionURL, err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { - return VersionInfo{}, fmt.Errorf("updater: HTTP GET %s: %s", u.VersionURL, err) + return VersionInfo{}, fmt.Errorf("updater: HTTP GET %s: %w", u.VersionURL, err) } u.versionJSON = body @@ -51,7 +51,7 @@ func (u *Updater) parseVersionResponse(data []byte) (VersionInfo, error) { versionJSON := make(map[string]interface{}) err := json.Unmarshal(data, &versionJSON) if err != nil { - return info, fmt.Errorf("version.json: %s", err) + return info, fmt.Errorf("version.json: %w", err) } var ok1, ok2, ok3, ok4 bool diff --git a/internal/update/updater.go b/internal/update/updater.go index 31fc9c72..f78f85c5 100644 --- a/internal/update/updater.go +++ b/internal/update/updater.go @@ -138,13 +138,13 @@ func (u *Updater) unpack() error { if strings.HasSuffix(pkgNameOnly, ".zip") { u.unpackedFiles, err = zipFileUnpack(u.packageName, u.updateDir) if err != nil { - return fmt.Errorf(".zip unpack failed: %s", err) + return fmt.Errorf(".zip unpack failed: %w", err) } } else if strings.HasSuffix(pkgNameOnly, ".tar.gz") { u.unpackedFiles, err = tarGzFileUnpack(u.packageName, u.updateDir) if err != nil { - return fmt.Errorf(".tar.gz unpack failed: %s", err) + return fmt.Errorf(".tar.gz unpack failed: %w", err) } } else { @@ -158,7 +158,7 @@ func (u *Updater) check() error { log.Debug("updater: checking configuration") err := copyFile(u.ConfigName, filepath.Join(u.updateDir, "AdGuardHome.yaml")) if err != nil { - return fmt.Errorf("copyFile() failed: %s", err) + return fmt.Errorf("copyFile() failed: %w", err) } cmd := exec.Command(u.updateExeName, "--check-config") err = cmd.Run() @@ -170,10 +170,10 @@ func (u *Updater) check() error { func (u *Updater) backup() error { log.Debug("updater: backing up the current configuration") - _ = os.Mkdir(u.backupDir, 0755) + _ = os.Mkdir(u.backupDir, 0o755) err := copyFile(u.ConfigName, filepath.Join(u.backupDir, "AdGuardHome.yaml")) if err != nil { - return fmt.Errorf("copyFile() failed: %s", err) + return fmt.Errorf("copyFile() failed: %w", err) } // workdir/README.md -> backup/README.md @@ -221,7 +221,7 @@ func (u *Updater) clean() { func (u *Updater) downloadPackageFile(url string, filename string) error { resp, err := u.Client.Get(url) if err != nil { - return fmt.Errorf("HTTP request failed: %s", err) + return fmt.Errorf("http request failed: %w", err) } if resp != nil && resp.Body != nil { defer resp.Body.Close() @@ -230,15 +230,15 @@ func (u *Updater) downloadPackageFile(url string, filename string) error { log.Debug("updater: reading HTTP body") body, err := ioutil.ReadAll(resp.Body) if err != nil { - return fmt.Errorf("ioutil.ReadAll() failed: %s", err) + return fmt.Errorf("ioutil.ReadAll() failed: %w", err) } - _ = os.Mkdir(u.updateDir, 0755) + _ = os.Mkdir(u.updateDir, 0o755) log.Debug("updater: saving package to file") - err = ioutil.WriteFile(filename, body, 0644) + err = ioutil.WriteFile(filename, body, 0o644) if err != nil { - return fmt.Errorf("ioutil.WriteFile() failed: %s", err) + return fmt.Errorf("ioutil.WriteFile() failed: %w", err) } return nil } @@ -250,7 +250,7 @@ func (u *Updater) downloadPackageFile(url string, filename string) error { func tarGzFileUnpack(tarfile, outdir string) ([]string, error) { f, err := os.Open(tarfile) if err != nil { - return nil, fmt.Errorf("os.Open(): %s", err) + return nil, fmt.Errorf("os.Open(): %w", err) } defer func() { _ = f.Close() @@ -258,7 +258,7 @@ func tarGzFileUnpack(tarfile, outdir string) ([]string, error) { gzReader, err := gzip.NewReader(f) if err != nil { - return nil, fmt.Errorf("gzip.NewReader(): %s", err) + return nil, fmt.Errorf("gzip.NewReader(): %w", err) } var files []string @@ -271,7 +271,7 @@ func tarGzFileUnpack(tarfile, outdir string) ([]string, error) { break } if err != nil { - err2 = fmt.Errorf("tarReader.Next(): %s", err) + err2 = fmt.Errorf("tarReader.Next(): %w", err) break } @@ -283,9 +283,9 @@ func tarGzFileUnpack(tarfile, outdir string) ([]string, error) { outputName := filepath.Join(outdir, inputNameOnly) if header.Typeflag == tar.TypeDir { - err = os.Mkdir(outputName, os.FileMode(header.Mode&0777)) + err = os.Mkdir(outputName, os.FileMode(header.Mode&0o777)) if err != nil && !os.IsExist(err) { - err2 = fmt.Errorf("os.Mkdir(%s): %s", outputName, err) + err2 = fmt.Errorf("os.Mkdir(%s): %w", outputName, err) break } log.Debug("updater: created directory %s", outputName) @@ -295,20 +295,20 @@ func tarGzFileUnpack(tarfile, outdir string) ([]string, error) { continue } - f, err := os.OpenFile(outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode&0777)) + f, err := os.OpenFile(outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode&0o777)) if err != nil { - err2 = fmt.Errorf("os.OpenFile(%s): %s", outputName, err) + err2 = fmt.Errorf("os.OpenFile(%s): %w", outputName, err) break } _, err = io.Copy(f, tarReader) if err != nil { _ = f.Close() - err2 = fmt.Errorf("io.Copy(): %s", err) + err2 = fmt.Errorf("io.Copy(): %w", err) break } err = f.Close() if err != nil { - err2 = fmt.Errorf("f.Close(): %s", err) + err2 = fmt.Errorf("f.Close(): %w", err) break } @@ -327,7 +327,7 @@ func tarGzFileUnpack(tarfile, outdir string) ([]string, error) { func zipFileUnpack(zipfile, outdir string) ([]string, error) { r, err := zip.OpenReader(zipfile) if err != nil { - return nil, fmt.Errorf("zip.OpenReader(): %s", err) + return nil, fmt.Errorf("zip.OpenReader(): %w", err) } defer r.Close() @@ -337,7 +337,7 @@ func zipFileUnpack(zipfile, outdir string) ([]string, error) { for _, zf := range r.File { zr, err = zf.Open() if err != nil { - err2 = fmt.Errorf("zip file Open(): %s", err) + err2 = fmt.Errorf("zip file Open(): %w", err) break } @@ -352,7 +352,7 @@ func zipFileUnpack(zipfile, outdir string) ([]string, error) { if fi.IsDir() { err = os.Mkdir(outputName, fi.Mode()) if err != nil && !os.IsExist(err) { - err2 = fmt.Errorf("os.Mkdir(): %s", err) + err2 = fmt.Errorf("os.Mkdir(): %w", err) break } log.Tracef("created directory %s", outputName) @@ -361,18 +361,18 @@ func zipFileUnpack(zipfile, outdir string) ([]string, error) { f, err := os.OpenFile(outputName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fi.Mode()) if err != nil { - err2 = fmt.Errorf("os.OpenFile(): %s", err) + err2 = fmt.Errorf("os.OpenFile(): %w", err) break } _, err = io.Copy(f, zr) if err != nil { _ = f.Close() - err2 = fmt.Errorf("io.Copy(): %s", err) + err2 = fmt.Errorf("io.Copy(): %w", err) break } err = f.Close() if err != nil { - err2 = fmt.Errorf("f.Close(): %s", err) + err2 = fmt.Errorf("f.Close(): %w", err) break } @@ -390,7 +390,7 @@ func copyFile(src, dst string) error { if e != nil { return e } - e = ioutil.WriteFile(dst, d, 0644) + e = ioutil.WriteFile(dst, d, 0o644) if e != nil { return e } diff --git a/internal/util/network_utils.go b/internal/util/network_utils.go index c4c61594..3aafecff 100644 --- a/internal/util/network_utils.go +++ b/internal/util/network_utils.go @@ -11,8 +11,6 @@ import ( "time" "github.com/AdguardTeam/golibs/log" - - "github.com/joomcode/errorx" ) // NetInterface represents a list of network interfaces @@ -30,7 +28,7 @@ type NetInterface struct { func GetValidNetInterfaces() ([]net.Interface, error) { ifaces, err := net.Interfaces() if err != nil { - return nil, fmt.Errorf("couldn't get list of interfaces: %s", err) + return nil, fmt.Errorf("couldn't get list of interfaces: %w", err) } netIfaces := []net.Interface{} @@ -48,7 +46,7 @@ func GetValidNetInterfaces() ([]net.Interface, error) { func GetValidNetInterfacesForWeb() ([]NetInterface, error) { ifaces, err := GetValidNetInterfaces() if err != nil { - return nil, errorx.Decorate(err, "Couldn't get interfaces") + return nil, fmt.Errorf("couldn't get interfaces: %w", err) } if len(ifaces) == 0 { return nil, errors.New("couldn't find any legible interface") @@ -57,9 +55,9 @@ func GetValidNetInterfacesForWeb() ([]NetInterface, error) { var netInterfaces []NetInterface for _, iface := range ifaces { - addrs, e := iface.Addrs() - if e != nil { - return nil, errorx.Decorate(e, "Failed to get addresses for interface %s", iface.Name) + addrs, err := iface.Addrs() + if err != nil { + return nil, fmt.Errorf("failed to get addresses for interface %s: %w", iface.Name, err) } netIface := NetInterface{