AdGuardHome/internal/filtering/http.go

588 lines
15 KiB
Go
Raw Normal View History

2022-09-29 15:36:01 +01:00
package filtering
import (
"encoding/json"
"fmt"
"net/http"
2023-09-07 15:13:48 +01:00
"net/netip"
"net/url"
"os"
"path/filepath"
2024-03-12 14:45:11 +00:00
"slices"
2023-06-07 18:04:01 +01:00
"sync"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
2024-04-02 18:22:19 +01:00
"github.com/AdguardTeam/AdGuardHome/internal/filtering/rulelist"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns"
)
// validateFilterURL validates the filter list URL or file name.
func validateFilterURL(urlStr string) (err error) {
2023-04-12 12:48:42 +01:00
defer func() { err = errors.Annotate(err, "checking filter: %w") }()
if filepath.IsAbs(urlStr) {
_, err = os.Stat(urlStr)
2024-01-30 15:43:51 +00:00
// Don't wrap the error since it's informative enough as is.
return err
}
2023-04-12 12:48:42 +01:00
u, err := url.ParseRequestURI(urlStr)
if err != nil {
2023-04-12 12:48:42 +01:00
// Don't wrap the error since it's informative enough as is.
return err
2024-01-30 15:43:51 +00:00
}
if s := u.Scheme; s != aghhttp.SchemeHTTP && s != aghhttp.SchemeHTTPS {
2023-04-12 12:48:42 +01:00
return &url.Error{
Op: "Check scheme",
URL: urlStr,
2024-01-30 15:43:51 +00:00
Err: fmt.Errorf("only %v allowed", []string{
aghhttp.SchemeHTTP,
aghhttp.SchemeHTTPS,
}),
2023-04-12 12:48:42 +01:00
}
}
return nil
}
type filterAddJSON struct {
Name string `json:"name"`
URL string `json:"url"`
Whitelist bool `json:"whitelist"`
}
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) handleFilteringAddURL(w http.ResponseWriter, r *http.Request) {
fj := filterAddJSON{}
err := json.NewDecoder(r.Body).Decode(&fj)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "Failed to parse request body json: %s", err)
return
}
err = validateFilterURL(fj.URL)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)
return
}
// Check for duplicates
2022-09-29 15:36:01 +01:00
if d.filterExists(fj.URL) {
2023-04-12 12:48:42 +01:00
err = errFilterExists
aghhttp.Error(r, w, http.StatusBadRequest, "Filter with URL %q: %s", fj.URL, err)
return
}
// Set necessary properties
2022-09-29 15:36:01 +01:00
filt := FilterYAML{
Enabled: true,
URL: fj.URL,
Name: fj.Name,
white: fj.Whitelist,
2022-11-02 13:18:02 +00:00
Filter: Filter{
2024-04-02 18:22:19 +01:00
ID: d.idGen.next(),
2022-11-02 13:18:02 +00:00
},
}
// Download the filter contents
2022-09-29 15:36:01 +01:00
ok, err := d.update(&filt)
if err != nil {
aghhttp.Error(
r,
w,
http.StatusBadRequest,
2023-07-12 13:13:31 +01:00
"Couldn't fetch filter from URL %q: %s",
filt.URL,
err,
)
return
}
if !ok {
aghhttp.Error(
r,
w,
http.StatusBadRequest,
2023-04-12 12:48:42 +01:00
"Filter with URL %q is invalid (maybe it points to blank page?)",
filt.URL,
)
return
}
// URL is assumed valid so append it to filters, update config, write new
// file and reload it to engines.
2023-04-12 12:48:42 +01:00
err = d.filterAdd(filt)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "Filter with URL %q: %s", filt.URL, err)
return
}
2023-09-07 15:13:48 +01:00
d.conf.ConfigModified()
2022-09-29 15:36:01 +01:00
d.EnableFilters(true)
_, err = fmt.Fprintf(w, "OK %d rules\n", filt.RulesCount)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "Couldn't write body: %s", err)
}
}
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) handleFilteringRemoveURL(w http.ResponseWriter, r *http.Request) {
type request struct {
URL string `json:"url"`
Whitelist bool `json:"whitelist"`
}
req := request{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "failed to parse request body json: %s", err)
return
}
2022-09-29 15:36:01 +01:00
var deleted FilterYAML
2023-04-12 12:48:42 +01:00
func() {
2023-09-07 15:13:48 +01:00
d.conf.filtersMu.Lock()
defer d.conf.filtersMu.Unlock()
2023-09-07 15:13:48 +01:00
filters := &d.conf.Filters
2023-04-12 12:48:42 +01:00
if req.Whitelist {
2023-09-07 15:13:48 +01:00
filters = &d.conf.WhitelistFilters
}
2023-04-12 12:48:42 +01:00
delIdx := slices.IndexFunc(*filters, func(flt FilterYAML) bool {
return flt.URL == req.URL
})
if delIdx == -1 {
log.Error("deleting filter with url %q: %s", req.URL, errFilterNotExist)
return
}
deleted = (*filters)[delIdx]
2023-09-07 15:13:48 +01:00
p := deleted.Path(d.conf.DataDir)
2023-04-12 12:48:42 +01:00
err = os.Rename(p, p+".old")
2023-07-03 12:10:40 +01:00
if err != nil && !errors.Is(err, os.ErrNotExist) {
2023-04-12 12:48:42 +01:00
log.Error("deleting filter %d: renaming file %q: %s", deleted.ID, p, err)
return
}
2023-04-12 12:48:42 +01:00
*filters = slices.Delete(*filters, delIdx, delIdx+1)
log.Info("deleted filter %d", deleted.ID)
}()
2023-09-07 15:13:48 +01:00
d.conf.ConfigModified()
2022-09-29 15:36:01 +01:00
d.EnableFilters(true)
// NOTE: The old files "filter.txt.old" aren't deleted. It's not really
// necessary, but will require the additional complicated code to run
// after enableFilters is done.
//
// TODO(a.garipov): Make sure the above comment is true.
_, err = fmt.Fprintf(w, "OK %d rules\n", deleted.RulesCount)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "couldn't write body: %s", err)
}
}
type filterURLReqData struct {
Name string `json:"name"`
URL string `json:"url"`
Enabled bool `json:"enabled"`
}
type filterURLReq struct {
Data *filterURLReqData `json:"data"`
URL string `json:"url"`
Whitelist bool `json:"whitelist"`
}
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) handleFilteringSetURL(w http.ResponseWriter, r *http.Request) {
fj := filterURLReq{}
err := json.NewDecoder(r.Body).Decode(&fj)
if err != nil {
2022-09-29 15:36:01 +01:00
aghhttp.Error(r, w, http.StatusBadRequest, "decoding request: %s", err)
return
}
if fj.Data == nil {
2022-09-29 15:36:01 +01:00
aghhttp.Error(r, w, http.StatusBadRequest, "%s", errors.Error("data is absent"))
return
}
err = validateFilterURL(fj.Data.URL)
if err != nil {
2022-09-29 15:36:01 +01:00
aghhttp.Error(r, w, http.StatusBadRequest, "invalid url: %s", err)
return
}
2022-09-29 15:36:01 +01:00
filt := FilterYAML{
Enabled: fj.Data.Enabled,
Name: fj.Data.Name,
URL: fj.Data.URL,
}
2022-09-29 15:36:01 +01:00
2022-11-02 13:18:02 +00:00
restart, err := d.filterSetProperties(fj.URL, filt, fj.Whitelist)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, err.Error())
2022-09-29 15:36:01 +01:00
return
}
2023-09-07 15:13:48 +01:00
d.conf.ConfigModified()
if restart {
2022-09-29 15:36:01 +01:00
d.EnableFilters(true)
}
}
2022-09-29 17:10:03 +01:00
// filteringRulesReq is the JSON structure for settings custom filtering rules.
type filteringRulesReq struct {
Rules []string `json:"rules"`
}
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) handleFilteringSetRules(w http.ResponseWriter, r *http.Request) {
2022-09-29 17:10:03 +01:00
if aghhttp.WriteTextPlainDeprecated(w, r) {
return
}
req := &filteringRulesReq{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
2022-09-29 17:10:03 +01:00
aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err)
return
}
2023-09-07 15:13:48 +01:00
d.conf.UserRules = req.Rules
d.conf.ConfigModified()
2022-09-29 15:36:01 +01:00
d.EnableFilters(true)
}
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) handleFilteringRefresh(w http.ResponseWriter, r *http.Request) {
type Req struct {
White bool `json:"whitelist"`
}
var err error
req := Req{}
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err)
return
}
2022-09-29 15:36:01 +01:00
var ok bool
2023-04-12 12:48:42 +01:00
resp := struct {
Updated int `json:"updated"`
}{}
2022-09-29 15:36:01 +01:00
resp.Updated, _, ok = d.tryRefreshFilters(!req.White, req.White, true)
if !ok {
aghhttp.Error(
r,
w,
http.StatusInternalServerError,
"filters update procedure is already running",
)
return
}
2023-09-07 15:13:48 +01:00
aghhttp.WriteJSONResponseOK(w, r, resp)
}
type filterJSON struct {
2024-04-02 18:22:19 +01:00
URL string `json:"url"`
Name string `json:"name"`
LastUpdated string `json:"last_updated,omitempty"`
ID rulelist.URLFilterID `json:"id"`
RulesCount uint32 `json:"rules_count"`
Enabled bool `json:"enabled"`
}
type filteringConfig struct {
Filters []filterJSON `json:"filters"`
WhitelistFilters []filterJSON `json:"whitelist_filters"`
UserRules []string `json:"user_rules"`
Interval uint32 `json:"interval"` // in hours
Enabled bool `json:"enabled"`
}
2022-09-29 15:36:01 +01:00
func filterToJSON(f FilterYAML) filterJSON {
fj := filterJSON{
ID: f.ID,
Enabled: f.Enabled,
URL: f.URL,
Name: f.Name,
RulesCount: uint32(f.RulesCount),
}
if !f.LastUpdated.IsZero() {
fj.LastUpdated = f.LastUpdated.Format(time.RFC3339)
}
return fj
}
// Get filtering configuration
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) handleFilteringStatus(w http.ResponseWriter, r *http.Request) {
resp := filteringConfig{}
2023-09-07 15:13:48 +01:00
d.conf.filtersMu.RLock()
resp.Enabled = d.conf.FilteringEnabled
resp.Interval = d.conf.FiltersUpdateIntervalHours
for _, f := range d.conf.Filters {
fj := filterToJSON(f)
resp.Filters = append(resp.Filters, fj)
}
2023-09-07 15:13:48 +01:00
for _, f := range d.conf.WhitelistFilters {
fj := filterToJSON(f)
resp.WhitelistFilters = append(resp.WhitelistFilters, fj)
}
2023-09-07 15:13:48 +01:00
resp.UserRules = d.conf.UserRules
d.conf.filtersMu.RUnlock()
2023-09-07 15:13:48 +01:00
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// Set filtering configuration
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) handleFilteringConfig(w http.ResponseWriter, r *http.Request) {
req := filteringConfig{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err)
return
}
2022-09-29 15:36:01 +01:00
if !ValidateUpdateIvl(req.Interval) {
aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval")
return
}
func() {
2023-09-07 15:13:48 +01:00
d.conf.filtersMu.Lock()
defer d.conf.filtersMu.Unlock()
2023-09-07 15:13:48 +01:00
d.conf.FilteringEnabled = req.Enabled
d.conf.FiltersUpdateIntervalHours = req.Interval
}()
2023-09-07 15:13:48 +01:00
d.conf.ConfigModified()
2022-09-29 15:36:01 +01:00
d.EnableFilters(true)
}
type checkHostRespRule struct {
2024-04-02 18:22:19 +01:00
Text string `json:"text"`
FilterListID rulelist.URLFilterID `json:"filter_list_id"`
}
type checkHostResp struct {
Reason string `json:"reason"`
// Rule is the text of the matched rule.
//
// Deprecated: Use Rules[*].Text.
Rule string `json:"rule"`
Rules []*checkHostRespRule `json:"rules"`
// for FilteredBlockedService:
SvcName string `json:"service_name"`
// for Rewrite:
2023-09-07 15:13:48 +01:00
CanonName string `json:"cname"` // CNAME value
IPList []netip.Addr `json:"ip_addrs"` // list of IP addresses
// FilterID is the ID of the rule's filter list.
//
// Deprecated: Use Rules[*].FilterListID.
2024-04-02 18:22:19 +01:00
FilterID rulelist.URLFilterID `json:"filter_id"`
}
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) handleCheckHost(w http.ResponseWriter, r *http.Request) {
host := r.URL.Query().Get("name")
2023-07-03 12:10:40 +01:00
setts := d.Settings()
setts.FilteringEnabled = true
setts.ProtectionEnabled = true
2022-09-29 15:36:01 +01:00
2023-07-03 12:10:40 +01:00
d.ApplyBlockedServices(setts)
result, err := d.CheckHost(host, dns.TypeA, setts)
if err != nil {
aghhttp.Error(
r,
w,
http.StatusInternalServerError,
"couldn't apply filtering: %s: %s",
host,
err,
)
return
}
2022-09-29 15:36:01 +01:00
rulesLen := len(result.Rules)
resp := checkHostResp{
Reason: result.Reason.String(),
SvcName: result.ServiceName,
CanonName: result.CanonName,
IPList: result.IPList,
Rules: make([]*checkHostRespRule, len(result.Rules)),
}
2022-09-29 15:36:01 +01:00
if rulesLen > 0 {
resp.FilterID = result.Rules[0].FilterListID
resp.Rule = result.Rules[0].Text
}
for i, r := range result.Rules {
resp.Rules[i] = &checkHostRespRule{
FilterListID: r.FilterListID,
Text: r.Text,
}
}
2023-09-07 15:13:48 +01:00
aghhttp.WriteJSONResponseOK(w, r, resp)
}
2023-06-07 18:04:01 +01:00
// setProtectedBool sets the value of a boolean pointer under a lock. l must
// protect the value under ptr.
//
// TODO(e.burkov): Make it generic?
func setProtectedBool(mu *sync.RWMutex, ptr *bool, val bool) {
mu.Lock()
defer mu.Unlock()
*ptr = val
}
// protectedBool gets the value of a boolean pointer under a read lock. l must
// protect the value under ptr.
//
// TODO(e.burkov): Make it generic?
func protectedBool(mu *sync.RWMutex, ptr *bool) (val bool) {
mu.RLock()
defer mu.RUnlock()
return *ptr
}
// handleSafeBrowsingEnable is the handler for the POST
// /control/safebrowsing/enable HTTP API.
func (d *DNSFilter) handleSafeBrowsingEnable(w http.ResponseWriter, r *http.Request) {
2023-09-07 15:13:48 +01:00
setProtectedBool(d.confMu, &d.conf.SafeBrowsingEnabled, true)
d.conf.ConfigModified()
2023-06-07 18:04:01 +01:00
}
// handleSafeBrowsingDisable is the handler for the POST
// /control/safebrowsing/disable HTTP API.
func (d *DNSFilter) handleSafeBrowsingDisable(w http.ResponseWriter, r *http.Request) {
2023-09-07 15:13:48 +01:00
setProtectedBool(d.confMu, &d.conf.SafeBrowsingEnabled, false)
d.conf.ConfigModified()
2023-06-07 18:04:01 +01:00
}
// handleSafeBrowsingStatus is the handler for the GET
// /control/safebrowsing/status HTTP API.
func (d *DNSFilter) handleSafeBrowsingStatus(w http.ResponseWriter, r *http.Request) {
resp := &struct {
Enabled bool `json:"enabled"`
}{
2023-09-07 15:13:48 +01:00
Enabled: protectedBool(d.confMu, &d.conf.SafeBrowsingEnabled),
2023-06-07 18:04:01 +01:00
}
2023-09-07 15:13:48 +01:00
aghhttp.WriteJSONResponseOK(w, r, resp)
2023-06-07 18:04:01 +01:00
}
// handleParentalEnable is the handler for the POST /control/parental/enable
// HTTP API.
func (d *DNSFilter) handleParentalEnable(w http.ResponseWriter, r *http.Request) {
2023-09-07 15:13:48 +01:00
setProtectedBool(d.confMu, &d.conf.ParentalEnabled, true)
d.conf.ConfigModified()
2023-06-07 18:04:01 +01:00
}
// handleParentalDisable is the handler for the POST /control/parental/disable
// HTTP API.
func (d *DNSFilter) handleParentalDisable(w http.ResponseWriter, r *http.Request) {
2023-09-07 15:13:48 +01:00
setProtectedBool(d.confMu, &d.conf.ParentalEnabled, false)
d.conf.ConfigModified()
2023-06-07 18:04:01 +01:00
}
// handleParentalStatus is the handler for the GET /control/parental/status
// HTTP API.
func (d *DNSFilter) handleParentalStatus(w http.ResponseWriter, r *http.Request) {
resp := &struct {
Enabled bool `json:"enabled"`
}{
2023-09-07 15:13:48 +01:00
Enabled: protectedBool(d.confMu, &d.conf.ParentalEnabled),
2023-06-07 18:04:01 +01:00
}
2023-09-07 15:13:48 +01:00
aghhttp.WriteJSONResponseOK(w, r, resp)
2023-06-07 18:04:01 +01:00
}
// RegisterFilteringHandlers - register handlers
2022-09-29 15:36:01 +01:00
func (d *DNSFilter) RegisterFilteringHandlers() {
2023-09-07 15:13:48 +01:00
registerHTTP := d.conf.HTTPRegister
2022-09-29 15:36:01 +01:00
if registerHTTP == nil {
return
}
registerHTTP(http.MethodPost, "/control/safebrowsing/enable", d.handleSafeBrowsingEnable)
registerHTTP(http.MethodPost, "/control/safebrowsing/disable", d.handleSafeBrowsingDisable)
registerHTTP(http.MethodGet, "/control/safebrowsing/status", d.handleSafeBrowsingStatus)
registerHTTP(http.MethodPost, "/control/parental/enable", d.handleParentalEnable)
registerHTTP(http.MethodPost, "/control/parental/disable", d.handleParentalDisable)
registerHTTP(http.MethodGet, "/control/parental/status", d.handleParentalStatus)
registerHTTP(http.MethodPost, "/control/safesearch/enable", d.handleSafeSearchEnable)
registerHTTP(http.MethodPost, "/control/safesearch/disable", d.handleSafeSearchDisable)
registerHTTP(http.MethodGet, "/control/safesearch/status", d.handleSafeSearchStatus)
2023-04-12 12:48:42 +01:00
registerHTTP(http.MethodPut, "/control/safesearch/settings", d.handleSafeSearchSettings)
2022-09-29 15:36:01 +01:00
registerHTTP(http.MethodGet, "/control/rewrite/list", d.handleRewriteList)
registerHTTP(http.MethodPost, "/control/rewrite/add", d.handleRewriteAdd)
2023-07-03 12:10:40 +01:00
registerHTTP(http.MethodPut, "/control/rewrite/update", d.handleRewriteUpdate)
2022-09-29 15:36:01 +01:00
registerHTTP(http.MethodPost, "/control/rewrite/delete", d.handleRewriteDelete)
2022-11-02 13:18:02 +00:00
registerHTTP(http.MethodGet, "/control/blocked_services/services", d.handleBlockedServicesIDs)
registerHTTP(http.MethodGet, "/control/blocked_services/all", d.handleBlockedServicesAll)
2023-09-07 15:13:48 +01:00
// Deprecated handlers.
2022-09-29 15:36:01 +01:00
registerHTTP(http.MethodGet, "/control/blocked_services/list", d.handleBlockedServicesList)
registerHTTP(http.MethodPost, "/control/blocked_services/set", d.handleBlockedServicesSet)
2023-09-07 15:13:48 +01:00
registerHTTP(http.MethodGet, "/control/blocked_services/get", d.handleBlockedServicesGet)
registerHTTP(http.MethodPut, "/control/blocked_services/update", d.handleBlockedServicesUpdate)
2022-09-29 15:36:01 +01:00
registerHTTP(http.MethodGet, "/control/filtering/status", d.handleFilteringStatus)
registerHTTP(http.MethodPost, "/control/filtering/config", d.handleFilteringConfig)
registerHTTP(http.MethodPost, "/control/filtering/add_url", d.handleFilteringAddURL)
registerHTTP(http.MethodPost, "/control/filtering/remove_url", d.handleFilteringRemoveURL)
registerHTTP(http.MethodPost, "/control/filtering/set_url", d.handleFilteringSetURL)
registerHTTP(http.MethodPost, "/control/filtering/refresh", d.handleFilteringRefresh)
registerHTTP(http.MethodPost, "/control/filtering/set_rules", d.handleFilteringSetRules)
registerHTTP(http.MethodGet, "/control/filtering/check_host", d.handleCheckHost)
}
2022-09-29 15:36:01 +01:00
// ValidateUpdateIvl returns false if i is not a valid filters update interval.
func ValidateUpdateIvl(i uint32) bool {
return i == 0 || i == 1 || i == 12 || i == 1*24 || i == 3*24 || i == 7*24
}