adguard_querylog.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // adguard_querylog.go — lectura del query log de AdGuard Home (#2078).
  2. //
  3. // El query log es la única fuente que atribuye dominios a dispositivos. Se lee
  4. // de forma incremental (older_than) y se agrega en el servidor: nunca se guarda
  5. // el log crudo. Este fichero solo normaliza la API a un contrato interno.
  6. package adapters
  7. import (
  8. "context"
  9. "encoding/json"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. // DNSQuery es una entrada del query log normalizada.
  16. type DNSQuery struct {
  17. Time time.Time
  18. ClientIP string
  19. ClientName string
  20. Domain string
  21. QType string
  22. Status string
  23. Reason string
  24. ServiceName string
  25. Rule string
  26. Proto string
  27. }
  28. // BlockedByFilter distingue un bloqueo real de una reescritura: Rewrite y
  29. // FilteredSafeSearch reescriben la respuesta, no la deniegan.
  30. func (q DNSQuery) BlockedByFilter() bool {
  31. switch q.Reason {
  32. case "FilteredBlackList", "FilteredSafeBrowsing", "FilteredParental", "FilteredBlockedService":
  33. return true
  34. }
  35. return false
  36. }
  37. // QueryLogPage es una página del log, de la más reciente a la más antigua.
  38. type QueryLogPage struct {
  39. Oldest time.Time
  40. Queries []DNSQuery
  41. }
  42. // QueryLogConfig es la configuración del log que cambia su utilidad:
  43. // deshabilitado o con IPs anonimizadas no hay atribución posible.
  44. type QueryLogConfig struct {
  45. Enabled bool
  46. AnonymizeClientIP bool
  47. IntervalMS float64
  48. }
  49. // agQueryLogRaw es la forma JSON de /control/querylog.
  50. type agQueryLogRaw struct {
  51. Oldest string `json:"oldest"`
  52. Data []struct {
  53. Time string `json:"time"`
  54. Client string `json:"client"`
  55. ClientProto string `json:"client_proto"`
  56. ClientInfo struct {
  57. Name string `json:"name"`
  58. } `json:"client_info"`
  59. Question struct {
  60. Name string `json:"name"`
  61. Type string `json:"type"`
  62. } `json:"question"`
  63. Status string `json:"status"`
  64. Reason string `json:"reason"`
  65. ServiceName string `json:"service_name"`
  66. Rules []struct {
  67. Text string `json:"text"`
  68. } `json:"rules"`
  69. } `json:"data"`
  70. }
  71. // parseQueryLog normaliza una respuesta cruda. Entradas sin dominio se
  72. // descartan: no aportan nada a una vista por dominio.
  73. func parseQueryLog(raw *agQueryLogRaw) *QueryLogPage {
  74. page := &QueryLogPage{Queries: []DNSQuery{}}
  75. if raw == nil {
  76. return page
  77. }
  78. if ts, err := time.Parse(time.RFC3339, raw.Oldest); err == nil {
  79. page.Oldest = ts
  80. }
  81. for _, e := range raw.Data {
  82. domain := normalizeDomain(e.Question.Name)
  83. if domain == "" {
  84. continue
  85. }
  86. ts, err := time.Parse(time.RFC3339, e.Time)
  87. if err != nil {
  88. continue
  89. }
  90. q := DNSQuery{
  91. Time: ts,
  92. ClientIP: strings.TrimSpace(e.Client),
  93. ClientName: e.ClientInfo.Name,
  94. Domain: domain,
  95. QType: e.Question.Type,
  96. Status: e.Status,
  97. Reason: e.Reason,
  98. ServiceName: e.ServiceName,
  99. Proto: e.ClientProto,
  100. }
  101. if len(e.Rules) > 0 {
  102. q.Rule = e.Rules[0].Text
  103. }
  104. page.Queries = append(page.Queries, q)
  105. }
  106. return page
  107. }
  108. // normalizeDomain pasa a minúsculas y quita el punto final de la raíz.
  109. func normalizeDomain(s string) string {
  110. return strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
  111. }
  112. // QueryLog lee una página del log, opcionalmente más antigua que olderThan.
  113. func (c *AdGuardClient) QueryLog(ctx context.Context, olderThan string, limit int) (*QueryLogPage, error) {
  114. if limit <= 0 || limit > 1000 {
  115. limit = 1000
  116. }
  117. q := url.Values{}
  118. q.Set("limit", strconv.Itoa(limit))
  119. if olderThan != "" {
  120. q.Set("older_than", olderThan)
  121. }
  122. ctx, cancel := context.WithTimeout(ctx, adguardHTTPTimeout)
  123. defer cancel()
  124. var raw agQueryLogRaw
  125. if err := c.get(ctx, "/control/querylog?"+q.Encode(), &raw); err != nil {
  126. return nil, err
  127. }
  128. return parseQueryLog(&raw), nil
  129. }
  130. // QueryLogConfig lee la configuración del query log.
  131. func (c *AdGuardClient) QueryLogConfig(ctx context.Context) (*QueryLogConfig, error) {
  132. ctx, cancel := context.WithTimeout(ctx, adguardHTTPTimeout)
  133. defer cancel()
  134. var cfg struct {
  135. Enabled bool `json:"enabled"`
  136. AnonymizeClientIP bool `json:"anonymize_client_ip"`
  137. Interval float64 `json:"interval"`
  138. }
  139. if err := c.get(ctx, "/control/querylog/config", &cfg); err != nil {
  140. return nil, err
  141. }
  142. return &QueryLogConfig{Enabled: cfg.Enabled, AnonymizeClientIP: cfg.AnonymizeClientIP, IntervalMS: cfg.Interval}, nil
  143. }
  144. // QueryLog lee una página del log con login GL y re-login ante 401.
  145. func (c *AdGuardGlinetClient) QueryLog(ctx context.Context, olderThan string, limit int) (*QueryLogPage, error) {
  146. if limit <= 0 || limit > 1000 {
  147. limit = 1000
  148. }
  149. q := url.Values{}
  150. q.Set("limit", strconv.Itoa(limit))
  151. if olderThan != "" {
  152. q.Set("older_than", olderThan)
  153. }
  154. ctx, cancel := context.WithTimeout(ctx, glHTTPTimeout+glSSHTimeout)
  155. defer cancel()
  156. var raw agQueryLogRaw
  157. if err := c.glGetWithLogin(ctx, "querylog?"+q.Encode(), &raw); err != nil {
  158. return nil, err
  159. }
  160. return parseQueryLog(&raw), nil
  161. }
  162. // QueryLogConfig lee la configuración del log con login GL. En firmwares GL
  163. // antiguos el endpoint no existe: el caller lo trata como "desconocida".
  164. func (c *AdGuardGlinetClient) QueryLogConfig(ctx context.Context) (*QueryLogConfig, error) {
  165. ctx, cancel := context.WithTimeout(ctx, glHTTPTimeout+glSSHTimeout)
  166. defer cancel()
  167. var cfg struct {
  168. Enabled bool `json:"enabled"`
  169. AnonymizeClientIP bool `json:"anonymize_client_ip"`
  170. Interval float64 `json:"interval"`
  171. }
  172. if err := c.glGetWithLogin(ctx, "querylog/config", &cfg); err != nil {
  173. return nil, err
  174. }
  175. return &QueryLogConfig{Enabled: cfg.Enabled, AnonymizeClientIP: cfg.AnonymizeClientIP, IntervalMS: cfg.Interval}, nil
  176. }
  177. // glGetWithLogin ejecuta glGet con el sid actual y re-login ante 401 (mismo
  178. // patrón que GetStats y QueryClients).
  179. func (c *AdGuardGlinetClient) glGetWithLogin(ctx context.Context, path string, dst any) error {
  180. c.mu.Lock()
  181. hasSid := c.sid != ""
  182. c.mu.Unlock()
  183. if !hasSid {
  184. if _, err := c.Login(); err != nil {
  185. return err
  186. }
  187. }
  188. err := c.glGet(ctx, path, dst)
  189. if err != errGL401 {
  190. return err
  191. }
  192. c.mu.Lock()
  193. c.sid = ""
  194. c.mu.Unlock()
  195. if _, lerr := c.Login(); lerr != nil {
  196. return lerr
  197. }
  198. return c.glGet(ctx, path, dst)
  199. }
  200. // AdGuardSource implementa la lectura del query log sobre el cliente que haya
  201. // configurado (estándar o GL), sin que el ingestor conozca las dos variantes.
  202. type AdGuardSource struct {
  203. Std *AdGuardClient
  204. GL *AdGuardGlinetClient
  205. }
  206. // QueryLog delega en el cliente configurado.
  207. func (s AdGuardSource) QueryLog(ctx context.Context, olderThan string, limit int) (*QueryLogPage, error) {
  208. if s.Std != nil {
  209. return s.Std.QueryLog(ctx, olderThan, limit)
  210. }
  211. if s.GL != nil {
  212. return s.GL.QueryLog(ctx, olderThan, limit)
  213. }
  214. return nil, ErrNoAdguard
  215. }
  216. // QueryLogConfig delega en el cliente configurado.
  217. func (s AdGuardSource) QueryLogConfig(ctx context.Context) (*QueryLogConfig, error) {
  218. if s.Std != nil {
  219. return s.Std.QueryLogConfig(ctx)
  220. }
  221. if s.GL != nil {
  222. return s.GL.QueryLogConfig(ctx)
  223. }
  224. return nil, ErrNoAdguard
  225. }
  226. // ErrNoAdguard: no hay integración configurada.
  227. var ErrNoAdguard = errNoAdguard()
  228. type errNoAdguardType struct{}
  229. func (errNoAdguardType) Error() string { return "AdGuard no configurado" }
  230. func errNoAdguard() error { return errNoAdguardType{} }
  231. // parseQueryLogJSON se mantiene exportado para tests: decodifica un cuerpo
  232. // crudo sin pasar por HTTP.
  233. func parseQueryLogJSON(body []byte) (*QueryLogPage, error) {
  234. var raw agQueryLogRaw
  235. if err := json.Unmarshal(body, &raw); err != nil {
  236. return nil, err
  237. }
  238. return parseQueryLog(&raw), nil
  239. }