github.com/netdata/go.d.plugin@v0.58.1/modules/pihole/init.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package pihole 4 5 import ( 6 "bufio" 7 "errors" 8 "fmt" 9 "net/http" 10 "os" 11 "strings" 12 13 "github.com/netdata/go.d.plugin/pkg/web" 14 ) 15 16 func (p *Pihole) validateConfig() error { 17 if p.URL == "" { 18 return errors.New("url not set") 19 } 20 return nil 21 } 22 23 func (p *Pihole) initHTTPClient() (*http.Client, error) { 24 return web.NewHTTPClient(p.Client) 25 } 26 27 func (p *Pihole) getWebPassword() string { 28 // do no read setupVarsPath is password is set in the configuration file 29 if p.Password != "" { 30 return p.Password 31 } 32 if !isLocalHost(p.URL) { 33 p.Info("abort web password auto detection, host is not localhost") 34 return "" 35 } 36 37 p.Infof("starting web password auto detection, reading : %s", p.SetupVarsPath) 38 pass, err := getWebPassword(p.SetupVarsPath) 39 if err != nil { 40 p.Warningf("error during reading '%s' : %v", p.SetupVarsPath, err) 41 } 42 43 return pass 44 } 45 46 func getWebPassword(path string) (string, error) { 47 f, err := os.Open(path) 48 if err != nil { 49 return "", err 50 } 51 defer func() { _ = f.Close() }() 52 53 s := bufio.NewScanner(f) 54 var password string 55 56 for s.Scan() && password == "" { 57 if strings.HasPrefix(s.Text(), "WEBPASSWORD") { 58 parts := strings.Split(s.Text(), "=") 59 if len(parts) != 2 { 60 return "", fmt.Errorf("unparsable line : %s", s.Text()) 61 } 62 password = parts[1] 63 } 64 } 65 66 return password, nil 67 } 68 69 func isLocalHost(u string) bool { 70 if strings.Contains(u, "127.0.0.1") { 71 return true 72 } 73 if strings.Contains(u, "localhost") { 74 return true 75 } 76 77 return false 78 }