Pull request:* all: remove github.com/joomcode/errorx dependency

Merge in DNS/adguard-home from 2240-removing-errorx-dependency to master

Squashed commit of the following:

commit 5bbe0567356f06e3b9ee5b3dc38d357b472cacb1
Merge: a6040850d 02d16a0b4
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Thu Nov 5 14:32:22 2020 +0300

    Merge branch 'master' into 2240-removing-errorx-dependency

commit a6040850da3cefb131208097477b0956e80063fb
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Thu Nov 5 14:23:36 2020 +0300

    * dhcpd: convert some abbreviations to lowercase.

commit d05bd51b994906b0ff52c5a8e779bd1f512f4bb7
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Thu Nov 5 12:47:20 2020 +0300

    * agherr: last final fixes

commit 164bca55035ff44e50b0abb33e129a0d24ffe87c
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Nov 3 19:11:10 2020 +0300

    * all: final fixes again

commit a0ac26f409c0b28a176cf2861d52c2f471b59484
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Nov 3 18:51:39 2020 +0300

    * all: final fixes

commit 6147b02d402b513323b07e85856b348884f3a088
Merge: 9fd3af1a3 62cc334f4
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Nov 3 18:26:03 2020 +0300

    Merge branch 'master' into 2240-removing-errorx-dependency

commit 9fd3af1a39a3189b5c41315a8ad1568ae5cb4fc9
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Nov 3 18:23:08 2020 +0300

    * all: remove useless helper

commit 7cd9aeae639762b28b25f354d69c5cf74f670211
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Nov 3 17:19:26 2020 +0300

    * agherr: improved code tidiness

commit a74a49236e9aaace070646dac710de9201105262
Merge: dc9dedbf2 df34ee5c0
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Nov 3 16:54:29 2020 +0300

    Merge branch 'master' into 2240-removing-errorx-dependency

commit dc9dedbf205756e3adaa3bc776d349bf3d8c69a5
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Nov 3 16:40:08 2020 +0300

    * agherr: improve and cover by tests

commit fd6bfe9e282156cc60e006cb7cd46cce4d3a07a8
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Nov 3 14:06:27 2020 +0300

    * all: improve code quality

commit ea00c2f8c5060e9611f9a80cfd0e4a039526d0c4
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Nov 3 13:03:57 2020 +0300

    * all: fix linter style warnings

commit 8e75e1a681a7218c2b4c69adfa2b7e1e2966f9ac
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Nov 3 12:29:26 2020 +0300

    * all: remove github.com/joomcode/errorx dependency

    Closes #2240.
This commit is contained in:
Eugene Burkov
2020-11-05 15:20:57 +03:00
parent 02d16a0b40
commit 2baa33fb1f
32 changed files with 342 additions and 250 deletions

View File

@@ -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)

View File

@@ -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
}

View File

@@ -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"`

View File

@@ -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()

View File

@@ -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

View File

@@ -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) {

View File

@@ -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 {

View File

@@ -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)

View File

@@ -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{}:

View File

@@ -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