Skip to content

Commit

Permalink
Fixed a bug when PI-Hole is not protected by a password (fixes #1)
Browse files Browse the repository at this point in the history
  • Loading branch information
eko committed May 10, 2019
1 parent cc6acaf commit 4298f91
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions internal/pihole/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ var (

// Client struct is a PI-Hole client to request an instance of a PI-Hole ad blocker.
type Client struct {
httpClient http.Client
interval time.Duration
hostname string
password string
interval time.Duration
httpClient http.Client
sessionID string
}

// NewClient method initializes a new PI-Hole client.
Expand All @@ -46,13 +47,11 @@ func NewClient(hostname, password string, interval time.Duration) *Client {
// and then pass them as Prometheus metrics.
func (c *Client) Scrape() {
for range time.Tick(c.interval) {
sessionID := c.getPHPSessionID()
if sessionID == nil {
log.Println("Unable to retrieve session identifier")
return
if c.isAuthenticated() {
c.sessionID = c.getPHPSessionID()
}

stats := c.getStatistics(*sessionID)
stats := c.getStatistics()
c.setMetrics(stats)

log.Printf("New tick of statistics: %s", stats.ToString())
Expand Down Expand Up @@ -103,9 +102,7 @@ func (c *Client) setMetrics(stats *Stats) {
}
}

func (c *Client) getPHPSessionID() *string {
var sessionID string

func (c *Client) getPHPSessionID() (sessionID string) {
loginURL := fmt.Sprintf(loginURLPattern, c.hostname)
values := url.Values{"pw": []string{c.password}}

Expand Down Expand Up @@ -134,10 +131,10 @@ func (c *Client) getPHPSessionID() *string {
}
}

return &sessionID
return
}

func (c *Client) getStatistics(sessionID string) *Stats {
func (c *Client) getStatistics() *Stats {
var stats Stats

statsURL := fmt.Sprintf(statsURLPattern, c.hostname)
Expand All @@ -147,8 +144,9 @@ func (c *Client) getStatistics(sessionID string) *Stats {
log.Fatal("An error has occured when creating HTTP statistics request", err)
}

cookie := http.Cookie{Name: "PHPSESSID", Value: sessionID}
req.AddCookie(&cookie)
if c.isAuthenticated() {
c.authenticateRequest(req)
}

resp, err := c.httpClient.Do(req)
if err != nil {
Expand All @@ -167,3 +165,12 @@ func (c *Client) getStatistics(sessionID string) *Stats {

return &stats
}

func (c *Client) isAuthenticated() bool {
return len(c.password) > 0
}

func (c *Client) authenticateRequest(req *http.Request) {
cookie := http.Cookie{Name: "PHPSESSID", Value: c.sessionID}
req.AddCookie(&cookie)
}

0 comments on commit 4298f91

Please sign in to comment.