adguard.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // adguard.go — Cliente AdGuard Home estándar (API HTTP /control con Basic
  2. // auth; port de src/adapters/adguard.js, SPEC §7.3). Timeout corto y errores
  3. // controlados: si AdGuard no responde, el caller degrada y el poller sigue.
  4. package adapters
  5. import (
  6. "context"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "math"
  12. "net/http"
  13. "net/url"
  14. "strconv"
  15. "time"
  16. )
  17. const adguardHTTPTimeout = 4 * time.Second
  18. // AdGuardClient es el cliente estándar (ADGUARD_URL/USER/PASS).
  19. type AdGuardClient struct {
  20. url string // sin barra final
  21. auth string // "Basic …"
  22. hc *http.Client
  23. }
  24. // NewAdGuardClient crea el cliente estándar.
  25. func NewAdGuardClient(rawURL, user, pass string) *AdGuardClient {
  26. return &AdGuardClient{
  27. url: rawURL,
  28. auth: "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass)),
  29. hc: &http.Client{Timeout: adguardHTTPTimeout},
  30. }
  31. }
  32. func (c *AdGuardClient) get(ctx context.Context, path string, dst any) error {
  33. req, err := http.NewRequestWithContext(ctx, "GET", c.url+path, nil)
  34. if err != nil {
  35. return err
  36. }
  37. req.Header.Set("Authorization", c.auth)
  38. req.Header.Set("Accept", "application/json")
  39. res, err := c.hc.Do(req)
  40. if err != nil {
  41. return err
  42. }
  43. defer res.Body.Close()
  44. if res.StatusCode != 200 {
  45. return fmt.Errorf("AdGuard %s → HTTP %d", path, res.StatusCode)
  46. }
  47. return json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(dst)
  48. }
  49. // adGuardStatus: /control/status
  50. type adGuardStatus struct {
  51. ProtectionEnabled bool `json:"protection_enabled"`
  52. Running bool `json:"running"`
  53. }
  54. // adGuardStatsRaw: /control/stats (top_blocked_domains acepta los dos
  55. // formatos: [{domain:count}] o [["domain",count]]).
  56. type adGuardStatsRaw struct {
  57. NumDNSQueries int64 `json:"num_dns_queries"`
  58. NumBlockedFiltering int64 `json:"num_blocked_filtering"`
  59. NumReplacedSafebrows *int64 `json:"num_replaced_safebrowsing"`
  60. NumReplacedParental int64 `json:"num_replaced_parental"`
  61. AvgProcessingTime float64 `json:"avg_processing_time"`
  62. NumClients int64 `json:"num_clients"`
  63. TopBlockedDomains json.RawMessage `json:"top_blocked_domains"`
  64. }
  65. // GetStats devuelve AdGuardStats (shape del contrato). Error si caído.
  66. func (c *AdGuardClient) GetStats(ctx context.Context) (*AdGuardStats, error) {
  67. ctx, cancel := context.WithTimeout(ctx, adguardHTTPTimeout)
  68. defer cancel()
  69. var status adGuardStatus
  70. if err := c.get(ctx, "/control/status", &status); err != nil {
  71. return nil, err
  72. }
  73. var stats adGuardStatsRaw
  74. if err := c.get(ctx, "/control/stats", &stats); err != nil {
  75. return nil, err
  76. }
  77. var filtering struct {
  78. Filters []struct {
  79. Enabled bool `json:"enabled"`
  80. RulesCount int `json:"rules_count"`
  81. } `json:"filters"`
  82. }
  83. _ = c.get(ctx, "/control/filtering/status", &filtering) // best-effort (null en JS)
  84. queries := stats.NumDNSQueries
  85. blocked := stats.NumBlockedFiltering
  86. u, _ := url.Parse(c.url)
  87. host := u.Hostname()
  88. port := 80
  89. if p := u.Port(); p != "" {
  90. if n, err := strconv.Atoi(p); err == nil {
  91. port = n
  92. }
  93. }
  94. blockedPct := 0.0
  95. if queries > 0 {
  96. blockedPct = math.Round(float64(blocked)/float64(queries)*100*10) / 10
  97. }
  98. trackers := blocked
  99. if stats.NumReplacedSafebrows != nil {
  100. trackers = blocked - (*stats.NumReplacedSafebrows + stats.NumReplacedParental)
  101. }
  102. status2 := "inactive"
  103. if status.ProtectionEnabled && status.Running {
  104. status2 = "active"
  105. }
  106. filterLists := 0
  107. rules := 0
  108. for _, f := range filtering.Filters {
  109. if f.Enabled {
  110. filterLists++
  111. rules += f.RulesCount
  112. }
  113. }
  114. return &AdGuardStats{
  115. Host: host, Port: port, Status: status2,
  116. Queries24h: queries, Blocked24h: blocked, BlockedPct: blockedPct,
  117. TrackersBlocked: trackers,
  118. DNSLatencyMs: int(math.Round(stats.AvgProcessingTime * 1000)),
  119. ClientsUsing: int(stats.NumClients), ClientsTotal: int(stats.NumClients),
  120. TopBlocked: parseTopBlocked(stats.TopBlockedDomains, 5),
  121. FilterLists: filterLists, Rules: rules,
  122. }, nil
  123. }
  124. // parseTopBlocked: top 5; acepta [{domain: count}] y [["domain", count]].
  125. func parseTopBlocked(raw json.RawMessage, limit int) []TopBlocked {
  126. out := []TopBlocked{}
  127. if len(raw) == 0 {
  128. return out
  129. }
  130. var arr []json.RawMessage
  131. if err := json.Unmarshal(raw, &arr); err != nil {
  132. return out
  133. }
  134. for i, item := range arr {
  135. if i >= limit {
  136. break
  137. }
  138. // Formato viejo: ["domain", count]
  139. var pair []json.RawMessage
  140. if err := json.Unmarshal(item, &pair); err == nil && len(pair) == 2 {
  141. var domain string
  142. var count int64
  143. if json.Unmarshal(pair[0], &domain) == nil && json.Unmarshal(pair[1], &count) == nil {
  144. out = append(out, TopBlocked{Domain: domain, Count: count})
  145. continue
  146. }
  147. }
  148. // Formato nuevo: {domain: count}
  149. var m map[string]int64
  150. if err := json.Unmarshal(item, &m); err == nil {
  151. for k, v := range m { // una sola clave por objeto
  152. out = append(out, TopBlocked{Domain: k, Count: v})
  153. break
  154. }
  155. }
  156. }
  157. return out
  158. }