AdGuardHome/internal/querylog/http.go
Stanislav Chzhen aac36a2d2f Pull request 1907: 951-blocked-services-schedule-api
Updates #951.

Squashed commit of the following:

commit 6b840fd516f5a87fde0420e3aceb9c239b22c974
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Tue Aug 29 19:53:03 2023 +0300

    client: imp docs more

commit 7fc8f0363fbe4c4266cb0f67428fe4d18c351d2d
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Tue Aug 29 19:40:00 2023 +0300

    client: imp docs

commit 00bc14d5760614f2797714cdc2c4c19b1a94b86e
Author: Ildar Kamalov <ik@adguard.com>
Date:   Mon Aug 28 18:43:49 2023 +0300

    try to fix lock file

commit d749df74b576091e0b58928d86ea8b3b49f919da
Merge: c69f9230b e1f6229e5
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Mon Aug 28 18:14:02 2023 +0300

    Merge branch 'master' into 951-blocked-services-schedule-api

commit c69f9230b12f7c983db06b74324b3df77d74b32b
Author: Ildar Kamalov <ik@adguard.com>
Date:   Mon Aug 28 17:16:20 2023 +0300

    revert eslintrc

commit b37916c2dff0ddea5293d87570bb58e3443d2d21
Author: Ildar Kamalov <ik@adguard.com>
Date:   Mon Aug 28 12:02:39 2023 +0300

    fix translations

commit f5bb67d81506c687d0abd580049a3eee0af808e0
Author: Ildar Kamalov <ik@adguard.com>
Date:   Mon Aug 28 11:43:57 2023 +0300

    fix helpers

commit 13ec6a8b3a0acfb62762ae7e46c6e98eb7c82212
Author: Ildar Kamalov <ik@adguard.com>
Date:   Mon Aug 28 11:24:57 2023 +0300

    remove todo

commit 23724ec2fd683ed17b9f1cee841ad9aaf4c9d04f
Author: Ildar Kamalov <ik@adguard.com>
Date:   Mon Aug 28 09:56:56 2023 +0300

    add clients schedule form

commit 84d29e558a329068e64e7a95ee183946aa4515b5
Author: Ildar Kamalov <ik@adguard.com>
Date:   Fri Aug 25 17:44:40 2023 +0300

    fix schedule form

commit 83e4017688082e9eb670091d5a24d98157050502
Author: Ildar Kamalov <ik@adguard.com>
Date:   Fri Aug 18 12:58:16 2023 +0300

    remove unused

commit ef2b68e138da382e3cf42586ae604e12d9493504
Author: Ildar Kamalov <ik@adguard.com>
Date:   Fri Aug 18 12:57:37 2023 +0300

    client: fix translation string

commit 32ea80c968f52f18adbc811b2f06874644cdfe20
Author: Ildar Kamalov <ik@adguard.com>
Date:   Fri Aug 18 12:26:26 2023 +0300

    wip schedule

commit 9b770873859186c9424c8d108812e32ddff33bad
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Fri Jul 21 14:29:50 2023 +0300

    all: imp naming

commit ea4e9514ea3b264bcce7f2a301db817de4e87059
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Wed Jul 19 18:09:27 2023 +0300

    all: imp code

commit 98a705bdaa5c1e79394c73e5d75af2416fe9f297
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Tue Jul 18 18:23:26 2023 +0300

    all: imp naming

commit 4f84b55c7bfc9f7b680feac0ec45f5ea9189299a
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Fri Jul 14 15:01:17 2023 +0300

    all: add global schedule api

commit 87cf1646869ee9138964b47a27b7493674c8854a
Merge: cabb80ac1 2adc8624c
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Fri Jul 14 12:09:29 2023 +0300

    Merge branch 'master' into 951-blocked-services-schedule-api

commit cabb80ac16de437a8118bb0166479574379c97a3
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Thu Jul 13 13:37:23 2023 +0300

    openapi: fix typo

commit 2279b03acbcfc3d76216f8aaf30ae1c7894127bc
Author: Stanislav Chzhen <s.chzhen@adguard.com>
Date:   Thu Jul 13 12:26:19 2023 +0300

    all: imp docs

... and 3 more commits
2023-08-29 20:03:40 +03:00

387 lines
10 KiB
Go

package querylog
import (
"encoding/json"
"fmt"
"math"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/stringutil"
"github.com/AdguardTeam/golibs/timeutil"
"golang.org/x/exp/slices"
"golang.org/x/net/idna"
)
// configJSON is the JSON structure for the querylog configuration.
type configJSON struct {
// Interval is the querylog rotation interval. Use float64 here to support
// fractional numbers and not mess the API users by changing the units.
Interval float64 `json:"interval"`
// Enabled shows if the querylog is enabled. It is an aghalg.NullBool to
// be able to tell when it's set without using pointers.
Enabled aghalg.NullBool `json:"enabled"`
// AnonymizeClientIP shows if the clients' IP addresses must be anonymized.
// It is an [aghalg.NullBool] to be able to tell when it's set without using
// pointers.
AnonymizeClientIP aghalg.NullBool `json:"anonymize_client_ip"`
}
// getConfigResp is the JSON structure for the querylog configuration.
type getConfigResp struct {
// Ignored is the list of host names, which should not be written to log.
Ignored []string `json:"ignored"`
// Interval is the querylog rotation interval in milliseconds.
Interval float64 `json:"interval"`
// Enabled shows if the querylog is enabled. It is an aghalg.NullBool to
// be able to tell when it's set without using pointers.
Enabled aghalg.NullBool `json:"enabled"`
// AnonymizeClientIP shows if the clients' IP addresses must be anonymized.
// It is an aghalg.NullBool to be able to tell when it's set without using
// pointers.
//
// TODO(a.garipov): Consider using separate setting for statistics.
AnonymizeClientIP aghalg.NullBool `json:"anonymize_client_ip"`
}
// Register web handlers
func (l *queryLog) initWeb() {
l.conf.HTTPRegister(http.MethodGet, "/control/querylog", l.handleQueryLog)
l.conf.HTTPRegister(http.MethodPost, "/control/querylog_clear", l.handleQueryLogClear)
l.conf.HTTPRegister(http.MethodGet, "/control/querylog/config", l.handleGetQueryLogConfig)
l.conf.HTTPRegister(
http.MethodPut,
"/control/querylog/config/update",
l.handlePutQueryLogConfig,
)
// Deprecated handlers.
l.conf.HTTPRegister(http.MethodGet, "/control/querylog_info", l.handleQueryLogInfo)
l.conf.HTTPRegister(http.MethodPost, "/control/querylog_config", l.handleQueryLogConfig)
}
// handleQueryLog is the handler for the GET /control/querylog HTTP API.
func (l *queryLog) handleQueryLog(w http.ResponseWriter, r *http.Request) {
params, err := parseSearchParams(r)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "parsing params: %s", err)
return
}
var entries []*logEntry
var oldest time.Time
func() {
l.confMu.RLock()
defer l.confMu.RUnlock()
entries, oldest = l.search(params)
}()
resp := entriesToJSON(entries, oldest, l.anonymizer.Load())
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// handleQueryLogClear is the handler for the POST /control/querylog/clear HTTP
// API.
func (l *queryLog) handleQueryLogClear(_ http.ResponseWriter, _ *http.Request) {
l.clear()
}
// handleQueryLogInfo is the handler for the GET /control/querylog_info HTTP
// API.
//
// Deprecated: Remove it when migration to the new API is over.
func (l *queryLog) handleQueryLogInfo(w http.ResponseWriter, r *http.Request) {
l.confMu.RLock()
defer l.confMu.RUnlock()
ivl := l.conf.RotationIvl
if !checkInterval(ivl) {
// NOTE: If interval is custom we set it to 90 days for compatibility
// with old API.
ivl = timeutil.Day * 90
}
aghhttp.WriteJSONResponseOK(w, r, configJSON{
Enabled: aghalg.BoolToNullBool(l.conf.Enabled),
Interval: ivl.Hours() / 24,
AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP),
})
}
// handleGetQueryLogConfig is the handler for the GET /control/querylog/config
// HTTP API.
func (l *queryLog) handleGetQueryLogConfig(w http.ResponseWriter, r *http.Request) {
var resp *getConfigResp
func() {
l.confMu.RLock()
defer l.confMu.RUnlock()
resp = &getConfigResp{
Interval: float64(l.conf.RotationIvl.Milliseconds()),
Enabled: aghalg.BoolToNullBool(l.conf.Enabled),
AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP),
Ignored: l.conf.Ignored.Values(),
}
}()
slices.Sort(resp.Ignored)
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// AnonymizeIP masks ip to anonymize the client if the ip is a valid one.
func AnonymizeIP(ip net.IP) {
// zeroes is a slice of zero bytes from which the IP address tail is copied.
// Using constant string as source of copying is more efficient than byte
// slice, see https://github.com/golang/go/issues/49997.
const zeroes = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
if ip4 := ip.To4(); ip4 != nil {
copy(ip4[net.IPv4len-2:net.IPv4len], zeroes)
} else if len(ip) == net.IPv6len {
copy(ip[net.IPv6len-10:net.IPv6len], zeroes)
}
}
// handleQueryLogConfig is the handler for the POST /control/querylog_config
// HTTP API.
//
// Deprecated: Remove it when migration to the new API is over.
func (l *queryLog) handleQueryLogConfig(w http.ResponseWriter, r *http.Request) {
// Set NaN as initial value to be able to know if it changed later by
// comparing it to NaN.
newConf := &configJSON{
Interval: math.NaN(),
}
err := json.NewDecoder(r.Body).Decode(newConf)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)
return
}
ivl := time.Duration(float64(timeutil.Day) * newConf.Interval)
hasIvl := !math.IsNaN(newConf.Interval)
if hasIvl && !checkInterval(ivl) {
aghhttp.Error(r, w, http.StatusBadRequest, "unsupported interval")
return
}
defer l.conf.ConfigModified()
l.confMu.Lock()
defer l.confMu.Unlock()
conf := *l.conf
if newConf.Enabled != aghalg.NBNull {
conf.Enabled = newConf.Enabled == aghalg.NBTrue
}
if hasIvl {
conf.RotationIvl = ivl
}
if newConf.AnonymizeClientIP != aghalg.NBNull {
conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue
if conf.AnonymizeClientIP {
l.anonymizer.Store(AnonymizeIP)
} else {
l.anonymizer.Store(nil)
}
}
l.conf = &conf
}
// handlePutQueryLogConfig is the handler for the PUT
// /control/querylog/config/update HTTP API.
func (l *queryLog) handlePutQueryLogConfig(w http.ResponseWriter, r *http.Request) {
newConf := &getConfigResp{}
err := json.NewDecoder(r.Body).Decode(newConf)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)
return
}
set, err := aghnet.NewDomainNameSet(newConf.Ignored)
if err != nil {
aghhttp.Error(r, w, http.StatusUnprocessableEntity, "ignored: %s", err)
return
}
ivl := time.Duration(newConf.Interval) * time.Millisecond
err = validateIvl(ivl)
if err != nil {
aghhttp.Error(r, w, http.StatusUnprocessableEntity, "unsupported interval: %s", err)
return
}
if newConf.Enabled == aghalg.NBNull {
aghhttp.Error(r, w, http.StatusUnprocessableEntity, "enabled is null")
return
}
if newConf.AnonymizeClientIP == aghalg.NBNull {
aghhttp.Error(r, w, http.StatusUnprocessableEntity, "anonymize_client_ip is null")
return
}
defer l.conf.ConfigModified()
l.confMu.Lock()
defer l.confMu.Unlock()
conf := *l.conf
conf.Ignored = set
conf.RotationIvl = ivl
conf.Enabled = newConf.Enabled == aghalg.NBTrue
conf.AnonymizeClientIP = newConf.AnonymizeClientIP == aghalg.NBTrue
if conf.AnonymizeClientIP {
l.anonymizer.Store(AnonymizeIP)
} else {
l.anonymizer.Store(nil)
}
l.conf = &conf
}
// "value" -> value, return TRUE
func getDoubleQuotesEnclosedValue(s *string) bool {
t := *s
if len(t) >= 2 && t[0] == '"' && t[len(t)-1] == '"' {
*s = t[1 : len(t)-1]
return true
}
return false
}
// parseSearchCriterion parses a search criterion from the query parameter.
func parseSearchCriterion(q url.Values, name string, ct criterionType) (
ok bool,
sc searchCriterion,
err error,
) {
val := q.Get(name)
if val == "" {
return false, sc, nil
}
strict := getDoubleQuotesEnclosedValue(&val)
var asciiVal string
switch ct {
case ctTerm:
// Decode lowercased value from punycode to make EqualFold and
// friends work properly with IDNAs.
//
// TODO(e.burkov): Make it work with parts of IDNAs somehow.
loweredVal := strings.ToLower(val)
if asciiVal, err = idna.ToASCII(loweredVal); err != nil {
log.Debug("can't convert %q to ascii: %s", val, err)
} else if asciiVal == loweredVal {
// Purge asciiVal to prevent checking the same value
// twice.
asciiVal = ""
}
case ctFilteringStatus:
if !stringutil.InSlice(filteringStatusValues, val) {
return false, sc, fmt.Errorf("invalid value %s", val)
}
default:
return false, sc, fmt.Errorf(
"invalid criterion type %v: should be one of %v",
ct,
[]criterionType{ctTerm, ctFilteringStatus},
)
}
sc = searchCriterion{
criterionType: ct,
value: val,
asciiVal: asciiVal,
strict: strict,
}
return true, sc, nil
}
// parseSearchParams parses search parameters from the HTTP request's query
// string.
func parseSearchParams(r *http.Request) (p *searchParams, err error) {
p = newSearchParams()
q := r.URL.Query()
olderThan := q.Get("older_than")
if len(olderThan) != 0 {
p.olderThan, err = time.Parse(time.RFC3339Nano, olderThan)
if err != nil {
return nil, err
}
}
var limit64 int64
if limit64, err = strconv.ParseInt(q.Get("limit"), 10, 64); err == nil {
p.limit = int(limit64)
}
var offset64 int64
if offset64, err = strconv.ParseInt(q.Get("offset"), 10, 64); err == nil {
p.offset = int(offset64)
// If we don't use "olderThan" and use offset/limit instead, we should change the default behavior
// and scan all log records until we found enough log entries
p.maxFileScanEntries = 0
}
for _, v := range []struct {
urlField string
ct criterionType
}{{
urlField: "search",
ct: ctTerm,
}, {
urlField: "response_status",
ct: ctFilteringStatus,
}} {
var ok bool
var c searchCriterion
ok, c, err = parseSearchCriterion(q, v.urlField, v.ct)
if err != nil {
return nil, err
}
if ok {
p.searchCriteria = append(p.searchCriteria, c)
}
}
return p, nil
}