adguard.go 5.7 KB

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