text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```go
package home
import (
"bytes"
"encoding/binary"
"io"
"net"
"net/http"
"os"
"time"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/AdguardTeam/golibs/log"
"github.com/josharian/native"
)
// GLMode - enable GL-Inet compatibility mode
var GLMode bool
var glFilePrefix = "/tmp/gl_token_"
const (
glTokenTimeoutSeconds = 3600
glCookieName = "Admin-Token"
)
func glProcessRedirect(w http.ResponseWriter, r *http.Request) bool {
if !GLMode {
return false
}
// redirect to gl-inet login
host, _, _ := net.SplitHostPort(r.Host)
url := "http://" + host
log.Debug("Auth: redirecting to %s", url)
http.Redirect(w, r, url, http.StatusFound)
return true
}
func glProcessCookie(r *http.Request) bool {
if !GLMode {
return false
}
glCookie, glerr := r.Cookie(glCookieName)
if glerr != nil {
return false
}
log.Debug("Auth: GL cookie value: %s", glCookie.Value)
if glCheckToken(glCookie.Value) {
return true
}
log.Info("Auth: invalid GL cookie value: %s", glCookie)
return false
}
func glCheckToken(sess string) bool {
tokenName := glFilePrefix + sess
_, err := os.Stat(tokenName)
if err != nil {
log.Error("os.Stat: %s", err)
return false
}
tokenDate := glGetTokenDate(tokenName)
now := uint32(time.Now().UTC().Unix())
return now <= (tokenDate + glTokenTimeoutSeconds)
}
// MaxFileSize is a maximum file length in bytes.
const MaxFileSize = 1024 * 1024
func glGetTokenDate(file string) uint32 {
f, err := os.Open(file)
if err != nil {
log.Error("os.Open: %s", err)
return 0
}
defer func() {
derr := f.Close()
if derr != nil {
log.Error("glinet: closing file: %s", err)
}
}()
fileReader := ioutil.LimitReader(f, MaxFileSize)
var dateToken uint32
// This use of ReadAll is now safe, because we limited reader.
bs, err := io.ReadAll(fileReader)
if err != nil {
log.Error("reading token: %s", err)
return 0
}
buf := bytes.NewBuffer(bs)
// TODO(a.garipov): Get rid of github.com/josharian/native dependency.
err = binary.Read(buf, native.Endian, &dateToken)
if err != nil {
log.Error("decoding token: %s", err)
return 0
}
return dateToken
}
``` | /content/code_sandbox/internal/home/authglinet.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 617 |
```go
//go:build openbsd
package home
import (
"cmp"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"text/template"
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/kardianos/service"
)
// OpenBSD Service Implementation
//
// The file contains OpenBSD implementations for service.System and
// service.Service interfaces. It uses the default approach for RunCom-based
// services systems, e.g. rc.d script. It's written as if it was in a separate
// package and has only one internal dependency.
//
// TODO(e.burkov): Perhaps, file a PR to github.com/kardianos/service.
// sysVersion is the version of local service.System interface implementation.
const sysVersion = "openbsd-runcom"
// chooseSystem checks the current system detected and substitutes it with local
// implementation if needed.
func chooseSystem() {
service.ChooseSystem(openbsdSystem{})
}
// openbsdSystem is the service.System to be used on the OpenBSD.
type openbsdSystem struct{}
// String implements service.System interface for openbsdSystem.
func (openbsdSystem) String() string {
return sysVersion
}
// Detect implements service.System interface for openbsdSystem.
func (openbsdSystem) Detect() (ok bool) {
return true
}
// Interactive implements service.System interface for openbsdSystem.
func (openbsdSystem) Interactive() (ok bool) {
return os.Getppid() != 1
}
// New implements service.System interface for openbsdSystem.
func (openbsdSystem) New(i service.Interface, c *service.Config) (s service.Service, err error) {
return &openbsdRunComService{
i: i,
cfg: c,
}, nil
}
// openbsdRunComService is the RunCom-based service.Service to be used on the
// OpenBSD.
type openbsdRunComService struct {
i service.Interface
cfg *service.Config
}
// Platform implements service.Service interface for *openbsdRunComService.
func (*openbsdRunComService) Platform() (p string) {
return "openbsd"
}
// String implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) String() string {
return cmp.Or(s.cfg.DisplayName, s.cfg.Name)
}
// getBool returns the value of the given name from kv, assuming the value is a
// boolean. If the value isn't found or is not of the type, the defaultValue is
// returned.
func getBool(kv service.KeyValue, name string, defaultValue bool) (val bool) {
var ok bool
if val, ok = kv[name].(bool); ok {
return val
}
return defaultValue
}
// getString returns the value of the given name from kv, assuming the value is
// a string. If the value isn't found or is not of the type, the defaultValue
// is returned.
func getString(kv service.KeyValue, name, defaultValue string) (val string) {
var ok bool
if val, ok = kv[name].(string); ok {
return val
}
return defaultValue
}
// getFuncNiladic returns the value of the given name from kv, assuming the
// value is a func(). If the value isn't found or is not of the type, the
// defaultValue is returned.
func getFuncNiladic(kv service.KeyValue, name string, defaultValue func()) (val func()) {
var ok bool
if val, ok = kv[name].(func()); ok {
return val
}
return defaultValue
}
const (
// optionUserService is the UserService option name.
optionUserService = "UserService"
// optionUserServiceDefault is the UserService option default value.
optionUserServiceDefault = false
// errNoUserServiceRunCom is returned when the service uses some custom
// path to script.
errNoUserServiceRunCom errors.Error = "user services are not supported on " + sysVersion
)
// scriptPath returns the absolute path to the script. It's commonly used to
// send commands to the service.
func (s *openbsdRunComService) scriptPath() (cp string, err error) {
if getBool(s.cfg.Option, optionUserService, optionUserServiceDefault) {
return "", errNoUserServiceRunCom
}
const scriptPathPref = "/etc/rc.d"
return filepath.Join(scriptPathPref, s.cfg.Name), nil
}
const (
// optionRunComScript is the RunCom script option name.
optionRunComScript = "RunComScript"
// runComScript is the default RunCom script.
runComScript = `#!/bin/sh
#
# $OpenBSD: {{ .SvcInfo }}
daemon="{{.Path}}"
daemon_flags={{ .Arguments | args }}
. /etc/rc.d/rc.subr
rc_bg=YES
rc_cmd $1
`
)
// template returns the script template to put into rc.d.
func (s *openbsdRunComService) template() (t *template.Template) {
tf := map[string]any{
"args": func(sl []string) string {
return `"` + strings.Join(sl, " ") + `"`
},
}
return template.Must(template.New("").Funcs(tf).Parse(getString(
s.cfg.Option,
optionRunComScript,
runComScript,
)))
}
// execPath returns the absolute path to the executable to be run as a service.
func (s *openbsdRunComService) execPath() (path string, err error) {
if c := s.cfg; c != nil && len(c.Executable) != 0 {
return filepath.Abs(c.Executable)
}
if path, err = os.Executable(); err != nil {
return "", err
}
return filepath.Abs(path)
}
// annotate wraps errors.Annotate applying a common error format.
func (s *openbsdRunComService) annotate(action string, err error) (annotated error) {
return errors.Annotate(err, "%s %s %s service: %w", action, sysVersion, s.cfg.Name)
}
// Install implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) Install() (err error) {
defer func() { err = s.annotate("installing", err) }()
if err = s.writeScript(); err != nil {
return err
}
return s.configureSysStartup(true)
}
// configureSysStartup adds s into the group of packages started with system.
func (s *openbsdRunComService) configureSysStartup(enable bool) (err error) {
cmd := "enable"
if !enable {
cmd = "disable"
}
var code int
code, _, err = aghos.RunCommand("rcctl", cmd, s.cfg.Name)
if err != nil {
return err
} else if code != 0 {
return fmt.Errorf("rcctl finished with code %d", code)
}
return nil
}
// writeScript tries to write the script for the service.
func (s *openbsdRunComService) writeScript() (err error) {
var scriptPath string
if scriptPath, err = s.scriptPath(); err != nil {
return err
}
if _, err = os.Stat(scriptPath); !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("script already exists at %s", scriptPath)
}
var execPath string
if execPath, err = s.execPath(); err != nil {
return err
}
t := s.template()
f, err := os.Create(scriptPath)
if err != nil {
return fmt.Errorf("creating rc.d script file: %w", err)
}
defer f.Close()
err = t.Execute(f, &struct {
*service.Config
Path string
SvcInfo string
}{
Config: s.cfg,
Path: execPath,
SvcInfo: getString(s.cfg.Option, "SvcInfo", s.String()),
})
if err != nil {
return err
}
return errors.Annotate(
os.Chmod(scriptPath, 0o755),
"changing rc.d script file permissions: %w",
)
}
// Uninstall implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) Uninstall() (err error) {
defer func() { err = s.annotate("uninstalling", err) }()
if err = s.configureSysStartup(false); err != nil {
return err
}
var scriptPath string
if scriptPath, err = s.scriptPath(); err != nil {
return err
}
if err = os.Remove(scriptPath); errors.Is(err, os.ErrNotExist) {
return service.ErrNotInstalled
}
return errors.Annotate(err, "removing rc.d script: %w")
}
// optionRunWait is the name of the option associated with function which waits
// for the service to be stopped.
const optionRunWait = "RunWait"
// runWait is the default function to wait for service to be stopped.
func runWait() {
sigChan := make(chan os.Signal, 3)
signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt)
<-sigChan
}
// Run implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) Run() (err error) {
if err = s.i.Start(s); err != nil {
return err
}
getFuncNiladic(s.cfg.Option, optionRunWait, runWait)()
return s.i.Stop(s)
}
// runCom calls the script with the specified cmd.
func (s *openbsdRunComService) runCom(cmd string) (out string, err error) {
var scriptPath string
if scriptPath, err = s.scriptPath(); err != nil {
return "", err
}
// TODO(e.burkov): It's possible that os.ErrNotExist is caused by
// something different than the service script's non-existence. Keep it
// in mind, when replace the aghos.RunCommand.
var outData []byte
_, outData, err = aghos.RunCommand(scriptPath, cmd)
if errors.Is(err, os.ErrNotExist) {
return "", service.ErrNotInstalled
}
return string(outData), err
}
// Status implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) Status() (status service.Status, err error) {
defer func() { err = s.annotate("getting status of", err) }()
var out string
if out, err = s.runCom("check"); err != nil {
return service.StatusUnknown, err
}
name := s.cfg.Name
switch out {
case fmt.Sprintf("%s(ok)\n", name):
return service.StatusRunning, nil
case fmt.Sprintf("%s(failed)\n", name):
return service.StatusStopped, nil
default:
return service.StatusUnknown, service.ErrNotInstalled
}
}
// Start implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) Start() (err error) {
_, err = s.runCom("start")
return s.annotate("starting", err)
}
// Stop implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) Stop() (err error) {
_, err = s.runCom("stop")
return s.annotate("stopping", err)
}
// Restart implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) Restart() (err error) {
if err = s.Stop(); err != nil {
return err
}
return s.Start()
}
// Logger implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) Logger(errs chan<- error) (l service.Logger, err error) {
if service.ChosenSystem().Interactive() {
return service.ConsoleLogger, nil
}
return s.SystemLogger(errs)
}
// SystemLogger implements service.Service interface for *openbsdRunComService.
func (s *openbsdRunComService) SystemLogger(errs chan<- error) (l service.Logger, err error) {
return newSysLogger(s.cfg.Name, errs)
}
// newSysLogger returns a stub service.Logger implementation.
func newSysLogger(_ string, _ chan<- error) (service.Logger, error) {
return sysLogger{}, nil
}
// sysLogger wraps calls of the logging functions understandable for service
// interfaces.
type sysLogger struct{}
// Error implements service.Logger interface for sysLogger.
func (sysLogger) Error(v ...any) error {
log.Error(fmt.Sprint(v...))
return nil
}
// Warning implements service.Logger interface for sysLogger.
func (sysLogger) Warning(v ...any) error {
log.Info("warning: %s", fmt.Sprint(v...))
return nil
}
// Info implements service.Logger interface for sysLogger.
func (sysLogger) Info(v ...any) error {
log.Info(fmt.Sprint(v...))
return nil
}
// Errorf implements service.Logger interface for sysLogger.
func (sysLogger) Errorf(format string, a ...any) error {
log.Error(format, a...)
return nil
}
// Warningf implements service.Logger interface for sysLogger.
func (sysLogger) Warningf(format string, a ...any) error {
log.Info("warning: %s", fmt.Sprintf(format, a...))
return nil
}
// Infof implements service.Logger interface for sysLogger.
func (sysLogger) Infof(format string, a ...any) error {
log.Info(format, a...)
return nil
}
``` | /content/code_sandbox/internal/home/service_openbsd.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 2,930 |
```go
package home
import (
"cmp"
"fmt"
"log/slog"
"path/filepath"
"runtime"
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/yaml.v3"
)
// configSyslog is used to indicate that syslog or eventlog (win) should be used
// for logger output.
const configSyslog = "syslog"
// newSlogLogger returns new [*slog.Logger] configured with the given settings.
func newSlogLogger(ls *logSettings) (l *slog.Logger) {
if !ls.Enabled {
return slogutil.NewDiscardLogger()
}
return slogutil.New(&slogutil.Config{
Format: slogutil.FormatAdGuardLegacy,
AddTimestamp: true,
Verbose: ls.Verbose,
})
}
// configureLogger configures logger level and output.
func configureLogger(ls *logSettings) (err error) {
// Configure logger level.
if !ls.Enabled {
log.SetLevel(log.OFF)
} else if ls.Verbose {
log.SetLevel(log.DEBUG)
}
// Make sure that we see the microseconds in logs, as networking stuff can
// happen pretty quickly.
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
// Write logs to stdout by default.
if ls.File == "" {
return nil
}
if ls.File == configSyslog {
// Use syslog where it is possible and eventlog on Windows.
err = aghos.ConfigureSyslog(serviceName)
if err != nil {
return fmt.Errorf("cannot initialize syslog: %w", err)
}
return nil
}
logFilePath := ls.File
if !filepath.IsAbs(logFilePath) {
logFilePath = filepath.Join(Context.workDir, logFilePath)
}
log.SetOutput(&lumberjack.Logger{
Filename: logFilePath,
Compress: ls.Compress,
LocalTime: ls.LocalTime,
MaxBackups: ls.MaxBackups,
MaxSize: ls.MaxSize,
MaxAge: ls.MaxAge,
})
return err
}
// getLogSettings returns a log settings object properly initialized from opts.
func getLogSettings(opts options) (ls *logSettings) {
configLogSettings := config.Log
ls = readLogSettings()
if ls == nil {
// Use default log settings.
ls = &configLogSettings
}
// Command-line arguments can override config settings.
if opts.verbose {
ls.Verbose = true
}
ls.File = cmp.Or(opts.logFile, ls.File)
if opts.runningAsService && ls.File == "" && runtime.GOOS == "windows" {
// When running as a Windows service, use eventlog by default if
// nothing else is configured. Otherwise, we'll lose the log output.
ls.File = configSyslog
}
return ls
}
// readLogSettings reads logging settings from the config file. We do it in a
// separate method in order to configure logger before the actual configuration
// is parsed and applied.
func readLogSettings() (ls *logSettings) {
// TODO(s.chzhen): Add a helper function that returns default parameters
// for this structure and for the global configuration structure [config].
conf := &configuration{
Log: logSettings{
// By default, it is true if the property does not exist.
Enabled: true,
},
}
yamlFile, err := readConfigFile()
if err != nil {
return nil
}
err = yaml.Unmarshal(yamlFile, conf)
if err != nil {
log.Error("Couldn't get logging settings from the configuration: %s", err)
}
return &conf.Log
}
``` | /content/code_sandbox/internal/home/log.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 859 |
```go
package home
import (
"net/http"
"net/netip"
"net/textproto"
"net/url"
"path/filepath"
"testing"
"github.com/AdguardTeam/golibs/httphdr"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// implements http.ResponseWriter
type testResponseWriter struct {
hdr http.Header
statusCode int
}
func (w *testResponseWriter) Header() http.Header {
return w.hdr
}
func (w *testResponseWriter) Write([]byte) (int, error) {
return 0, nil
}
func (w *testResponseWriter) WriteHeader(statusCode int) {
w.statusCode = statusCode
}
func TestAuthHTTP(t *testing.T) {
dir := t.TempDir()
fn := filepath.Join(dir, "sessions.db")
users := []webUser{
{Name: "name", PasswordHash: "$2y$05$..vyzAECIhJPfaQiOK17IukcQnqEgKJHy0iETyYqxn3YXJl8yZuo2"},
}
Context.auth = InitAuth(fn, users, 60, nil, nil)
handlerCalled := false
handler := func(_ http.ResponseWriter, _ *http.Request) {
handlerCalled = true
}
handler2 := optionalAuth(handler)
w := testResponseWriter{}
w.hdr = make(http.Header)
r := http.Request{}
r.Header = make(http.Header)
r.Method = http.MethodGet
// get / - we're redirected to login page
r.URL = &url.URL{Path: "/"}
handlerCalled = false
handler2(&w, &r)
assert.Equal(t, http.StatusFound, w.statusCode)
assert.NotEmpty(t, w.hdr.Get(httphdr.Location))
assert.False(t, handlerCalled)
// go to login page
loginURL := w.hdr.Get(httphdr.Location)
r.URL = &url.URL{Path: loginURL}
handlerCalled = false
handler2(&w, &r)
assert.True(t, handlerCalled)
// perform login
cookie, err := Context.auth.newCookie(loginJSON{Name: "name", Password: "password"}, "")
require.NoError(t, err)
require.NotNil(t, cookie)
// get /
handler2 = optionalAuth(handler)
w.hdr = make(http.Header)
r.Header.Set(httphdr.Cookie, cookie.String())
r.URL = &url.URL{Path: "/"}
handlerCalled = false
handler2(&w, &r)
assert.True(t, handlerCalled)
r.Header.Del(httphdr.Cookie)
// get / with basic auth
handler2 = optionalAuth(handler)
w.hdr = make(http.Header)
r.URL = &url.URL{Path: "/"}
r.SetBasicAuth("name", "password")
handlerCalled = false
handler2(&w, &r)
assert.True(t, handlerCalled)
r.Header.Del(httphdr.Authorization)
// get login page with a valid cookie - we're redirected to /
handler2 = optionalAuth(handler)
w.hdr = make(http.Header)
r.Header.Set(httphdr.Cookie, cookie.String())
r.URL = &url.URL{Path: loginURL}
handlerCalled = false
handler2(&w, &r)
assert.NotEmpty(t, w.hdr.Get(httphdr.Location))
assert.False(t, handlerCalled)
r.Header.Del(httphdr.Cookie)
// get login page with an invalid cookie
handler2 = optionalAuth(handler)
w.hdr = make(http.Header)
r.Header.Set(httphdr.Cookie, "bad")
r.URL = &url.URL{Path: loginURL}
handlerCalled = false
handler2(&w, &r)
assert.True(t, handlerCalled)
r.Header.Del(httphdr.Cookie)
Context.auth.Close()
}
func TestRealIP(t *testing.T) {
const remoteAddr = "1.2.3.4:5678"
testCases := []struct {
name string
header http.Header
remoteAddr string
wantErrMsg string
wantIP netip.Addr
}{{
name: "success_no_proxy",
header: nil,
remoteAddr: remoteAddr,
wantErrMsg: "",
wantIP: netip.MustParseAddr("1.2.3.4"),
}, {
name: "success_proxy",
header: http.Header{
textproto.CanonicalMIMEHeaderKey(httphdr.XRealIP): []string{"1.2.3.5"},
},
remoteAddr: remoteAddr,
wantErrMsg: "",
wantIP: netip.MustParseAddr("1.2.3.5"),
}, {
name: "success_proxy_multiple",
header: http.Header{
textproto.CanonicalMIMEHeaderKey(httphdr.XForwardedFor): []string{
"1.2.3.6, 1.2.3.5",
},
},
remoteAddr: remoteAddr,
wantErrMsg: "",
wantIP: netip.MustParseAddr("1.2.3.6"),
}, {
name: "error_no_proxy",
header: nil,
remoteAddr: "1:::2",
wantErrMsg: `getting ip from client addr: address 1:::2: ` +
`too many colons in address`,
wantIP: netip.Addr{},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
r := &http.Request{
Header: tc.header,
RemoteAddr: tc.remoteAddr,
}
ip, err := realIP(r)
assert.Equal(t, tc.wantIP, ip)
testutil.AssertErrorMsg(t, tc.wantErrMsg, err)
})
}
}
``` | /content/code_sandbox/internal/home/authhttp_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,265 |
```go
package home
import (
"encoding/json"
"fmt"
"net/http"
"net/netip"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/client"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/AdGuardHome/internal/schedule"
"github.com/AdguardTeam/AdGuardHome/internal/whois"
)
// clientJSON is a common structure used by several handlers to deal with
// clients. Some of the fields are only necessary in one or two handlers and
// are thus made pointers with an omitempty tag.
//
// TODO(a.garipov): Consider using nullbool and an optional string here? Or
// split into several structs?
type clientJSON struct {
// Disallowed, if non-nil and false, means that the client's IP is
// allowed. Otherwise, the IP is blocked.
Disallowed *bool `json:"disallowed,omitempty"`
// DisallowedRule is the rule due to which the client is disallowed.
// If Disallowed is true and this string is empty, the client IP is
// disallowed by the "allowed IP list", that is it is not included in
// the allowlist.
DisallowedRule *string `json:"disallowed_rule,omitempty"`
// WHOIS is the filtered WHOIS data of a client.
WHOIS *whois.Info `json:"whois_info,omitempty"`
SafeSearchConf *filtering.SafeSearchConfig `json:"safe_search"`
// Schedule is blocked services schedule for every day of the week.
Schedule *schedule.Weekly `json:"blocked_services_schedule"`
Name string `json:"name"`
// BlockedServices is the names of blocked services.
BlockedServices []string `json:"blocked_services"`
IDs []string `json:"ids"`
Tags []string `json:"tags"`
Upstreams []string `json:"upstreams"`
FilteringEnabled bool `json:"filtering_enabled"`
ParentalEnabled bool `json:"parental_enabled"`
SafeBrowsingEnabled bool `json:"safebrowsing_enabled"`
// Deprecated: use safeSearchConf.
SafeSearchEnabled bool `json:"safesearch_enabled"`
UseGlobalBlockedServices bool `json:"use_global_blocked_services"`
UseGlobalSettings bool `json:"use_global_settings"`
IgnoreQueryLog aghalg.NullBool `json:"ignore_querylog"`
IgnoreStatistics aghalg.NullBool `json:"ignore_statistics"`
UpstreamsCacheSize uint32 `json:"upstreams_cache_size"`
UpstreamsCacheEnabled aghalg.NullBool `json:"upstreams_cache_enabled"`
}
// runtimeClientJSON is a JSON representation of the [client.Runtime].
type runtimeClientJSON struct {
WHOIS *whois.Info `json:"whois_info"`
IP netip.Addr `json:"ip"`
Name string `json:"name"`
Source client.Source `json:"source"`
}
// clientListJSON contains lists of persistent clients, runtime clients and also
// supported tags.
type clientListJSON struct {
Clients []*clientJSON `json:"clients"`
RuntimeClients []runtimeClientJSON `json:"auto_clients"`
Tags []string `json:"supported_tags"`
}
// whoisOrEmpty returns a WHOIS client information or a pointer to an empty
// struct. Frontend expects a non-nil value.
func whoisOrEmpty(r *client.Runtime) (info *whois.Info) {
info = r.WHOIS()
if info != nil {
return info
}
return &whois.Info{}
}
// handleGetClients is the handler for GET /control/clients HTTP API.
func (clients *clientsContainer) handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
clients.lock.Lock()
defer clients.lock.Unlock()
clients.storage.RangeByName(func(c *client.Persistent) (cont bool) {
cj := clientToJSON(c)
data.Clients = append(data.Clients, cj)
return true
})
clients.storage.RangeRuntime(func(rc *client.Runtime) (cont bool) {
src, host := rc.Info()
cj := runtimeClientJSON{
WHOIS: whoisOrEmpty(rc),
Name: host,
Source: src,
IP: rc.Addr(),
}
data.RuntimeClients = append(data.RuntimeClients, cj)
return true
})
for _, l := range clients.dhcp.Leases() {
cj := runtimeClientJSON{
Name: l.Hostname,
Source: client.SourceDHCP,
IP: l.IP,
WHOIS: &whois.Info{},
}
data.RuntimeClients = append(data.RuntimeClients, cj)
}
data.Tags = clientTags
aghhttp.WriteJSONResponseOK(w, r, data)
}
// initPrev initializes the persistent client with the default or previous
// client properties.
func initPrev(cj clientJSON, prev *client.Persistent) (c *client.Persistent, err error) {
var (
uid client.UID
ignoreQueryLog bool
ignoreStatistics bool
upsCacheEnabled bool
upsCacheSize uint32
)
if prev != nil {
uid = prev.UID
ignoreQueryLog = prev.IgnoreQueryLog
ignoreStatistics = prev.IgnoreStatistics
upsCacheEnabled = prev.UpstreamsCacheEnabled
upsCacheSize = prev.UpstreamsCacheSize
}
if cj.IgnoreQueryLog != aghalg.NBNull {
ignoreQueryLog = cj.IgnoreQueryLog == aghalg.NBTrue
}
if cj.IgnoreStatistics != aghalg.NBNull {
ignoreStatistics = cj.IgnoreStatistics == aghalg.NBTrue
}
if cj.UpstreamsCacheEnabled != aghalg.NBNull {
upsCacheEnabled = cj.UpstreamsCacheEnabled == aghalg.NBTrue
upsCacheSize = cj.UpstreamsCacheSize
}
svcs, err := copyBlockedServices(cj.Schedule, cj.BlockedServices, prev)
if err != nil {
return nil, fmt.Errorf("invalid blocked services: %w", err)
}
if (uid == client.UID{}) {
uid, err = client.NewUID()
if err != nil {
return nil, fmt.Errorf("generating uid: %w", err)
}
}
return &client.Persistent{
BlockedServices: svcs,
UID: uid,
IgnoreQueryLog: ignoreQueryLog,
IgnoreStatistics: ignoreStatistics,
UpstreamsCacheEnabled: upsCacheEnabled,
UpstreamsCacheSize: upsCacheSize,
}, nil
}
// jsonToClient converts JSON object to persistent client object if there are no
// errors.
func (clients *clientsContainer) jsonToClient(
cj clientJSON,
prev *client.Persistent,
) (c *client.Persistent, err error) {
c, err = initPrev(cj, prev)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
}
err = c.SetIDs(cj.IDs)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
}
c.SafeSearchConf = copySafeSearch(cj.SafeSearchConf, cj.SafeSearchEnabled)
c.Name = cj.Name
c.Tags = cj.Tags
c.Upstreams = cj.Upstreams
c.UseOwnSettings = !cj.UseGlobalSettings
c.FilteringEnabled = cj.FilteringEnabled
c.ParentalEnabled = cj.ParentalEnabled
c.SafeBrowsingEnabled = cj.SafeBrowsingEnabled
c.UseOwnBlockedServices = !cj.UseGlobalBlockedServices
if c.SafeSearchConf.Enabled {
err = c.SetSafeSearch(
c.SafeSearchConf,
clients.safeSearchCacheSize,
clients.safeSearchCacheTTL,
)
if err != nil {
return nil, fmt.Errorf("creating safesearch for client %q: %w", c.Name, err)
}
}
return c, nil
}
// copySafeSearch returns safe search config created from provided parameters.
func copySafeSearch(
jsonConf *filtering.SafeSearchConfig,
enabled bool,
) (conf filtering.SafeSearchConfig) {
if jsonConf != nil {
return *jsonConf
}
// TODO(d.kolyshev): Remove after cleaning the deprecated
// [clientJSON.SafeSearchEnabled] field.
conf = filtering.SafeSearchConfig{
Enabled: enabled,
}
// Set default service flags for enabled safesearch.
if conf.Enabled {
conf.Bing = true
conf.DuckDuckGo = true
conf.Ecosia = true
conf.Google = true
conf.Pixabay = true
conf.Yandex = true
conf.YouTube = true
}
return conf
}
// copyBlockedServices converts a json blocked services to an internal blocked
// services.
func copyBlockedServices(
sch *schedule.Weekly,
svcStrs []string,
prev *client.Persistent,
) (svcs *filtering.BlockedServices, err error) {
var weekly *schedule.Weekly
if sch != nil {
weekly = sch.Clone()
} else if prev != nil {
weekly = prev.BlockedServices.Schedule.Clone()
} else {
weekly = schedule.EmptyWeekly()
}
svcs = &filtering.BlockedServices{
Schedule: weekly,
IDs: svcStrs,
}
err = svcs.Validate()
if err != nil {
return nil, fmt.Errorf("validating blocked services: %w", err)
}
return svcs, nil
}
// clientToJSON converts persistent client object to JSON object.
func clientToJSON(c *client.Persistent) (cj *clientJSON) {
// TODO(d.kolyshev): Remove after cleaning the deprecated
// [clientJSON.SafeSearchEnabled] field.
cloneVal := c.SafeSearchConf
safeSearchConf := &cloneVal
return &clientJSON{
Name: c.Name,
IDs: c.IDs(),
Tags: c.Tags,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: safeSearchConf.Enabled,
SafeSearchConf: safeSearchConf,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
Schedule: c.BlockedServices.Schedule,
BlockedServices: c.BlockedServices.IDs,
Upstreams: c.Upstreams,
IgnoreQueryLog: aghalg.BoolToNullBool(c.IgnoreQueryLog),
IgnoreStatistics: aghalg.BoolToNullBool(c.IgnoreStatistics),
UpstreamsCacheSize: c.UpstreamsCacheSize,
UpstreamsCacheEnabled: aghalg.BoolToNullBool(c.UpstreamsCacheEnabled),
}
}
// handleAddClient is the handler for POST /control/clients/add HTTP API.
func (clients *clientsContainer) handleAddClient(w http.ResponseWriter, r *http.Request) {
cj := clientJSON{}
err := json.NewDecoder(r.Body).Decode(&cj)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "failed to process request body: %s", err)
return
}
c, err := clients.jsonToClient(cj, nil)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)
return
}
err = clients.storage.Add(c)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)
return
}
if !clients.testing {
onConfigModified()
}
}
// handleDelClient is the handler for POST /control/clients/delete HTTP API.
func (clients *clientsContainer) handleDelClient(w http.ResponseWriter, r *http.Request) {
cj := clientJSON{}
err := json.NewDecoder(r.Body).Decode(&cj)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "failed to process request body: %s", err)
return
}
if len(cj.Name) == 0 {
aghhttp.Error(r, w, http.StatusBadRequest, "client's name must be non-empty")
return
}
if !clients.storage.RemoveByName(cj.Name) {
aghhttp.Error(r, w, http.StatusBadRequest, "Client not found")
return
}
if !clients.testing {
onConfigModified()
}
}
// updateJSON contains the name and data of the updated persistent client.
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// handleUpdateClient is the handler for POST /control/clients/update HTTP API.
//
// TODO(s.chzhen): Accept updated parameters instead of whole structure.
func (clients *clientsContainer) handleUpdateClient(w http.ResponseWriter, r *http.Request) {
dj := updateJSON{}
err := json.NewDecoder(r.Body).Decode(&dj)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "failed to process request body: %s", err)
return
}
if len(dj.Name) == 0 {
aghhttp.Error(r, w, http.StatusBadRequest, "Invalid request")
return
}
c, err := clients.jsonToClient(dj.Data, nil)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)
return
}
err = clients.storage.Update(dj.Name, c)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "%s", err)
return
}
if !clients.testing {
onConfigModified()
}
}
// handleFindClient is the handler for GET /control/clients/find HTTP API.
func (clients *clientsContainer) handleFindClient(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
data := []map[string]*clientJSON{}
for i := range len(q) {
idStr := q.Get(fmt.Sprintf("ip%d", i))
if idStr == "" {
break
}
ip, _ := netip.ParseAddr(idStr)
c, ok := clients.find(idStr)
var cj *clientJSON
if !ok {
cj = clients.findRuntime(ip, idStr)
} else {
cj = clientToJSON(c)
disallowed, rule := clients.clientChecker.IsBlockedClient(ip, idStr)
cj.Disallowed, cj.DisallowedRule = &disallowed, &rule
}
data = append(data, map[string]*clientJSON{
idStr: cj,
})
}
aghhttp.WriteJSONResponseOK(w, r, data)
}
// findRuntime looks up the IP in runtime and temporary storages, like
// /etc/hosts tables, DHCP leases, or blocklists. cj is guaranteed to be
// non-nil.
func (clients *clientsContainer) findRuntime(ip netip.Addr, idStr string) (cj *clientJSON) {
rc := clients.findRuntimeClient(ip)
if rc == nil {
// It is still possible that the IP used to be in the runtime clients
// list, but then the server was reloaded. So, check the DNS server's
// blocked IP list.
//
// See path_to_url
disallowed, rule := clients.clientChecker.IsBlockedClient(ip, idStr)
cj = &clientJSON{
IDs: []string{idStr},
Disallowed: &disallowed,
DisallowedRule: &rule,
WHOIS: &whois.Info{},
}
return cj
}
_, host := rc.Info()
cj = &clientJSON{
Name: host,
IDs: []string{idStr},
WHOIS: whoisOrEmpty(rc),
}
disallowed, rule := clients.clientChecker.IsBlockedClient(ip, idStr)
cj.Disallowed, cj.DisallowedRule = &disallowed, &rule
return cj
}
// RegisterClientsHandlers registers HTTP handlers
func (clients *clientsContainer) registerWebHandlers() {
httpRegister(http.MethodGet, "/control/clients", clients.handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", clients.handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", clients.handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", clients.handleUpdateClient)
httpRegister(http.MethodGet, "/control/clients/find", clients.handleFindClient)
}
``` | /content/code_sandbox/internal/home/clientshttp.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 3,656 |
```go
package home
import (
"encoding/json"
"net/http"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/golibs/container"
"github.com/AdguardTeam/golibs/log"
)
// TODO(a.garipov): Get rid of a global or generate from .twosky.json.
var allowedLanguages = container.NewMapSet(
"ar",
"be",
"bg",
"cs",
"da",
"de",
"en",
"es",
"fa",
"fi",
"fr",
"hr",
"hu",
"id",
"it",
"ja",
"ko",
"nl",
"no",
"pl",
"pt-br",
"pt-pt",
"ro",
"ru",
"si-lk",
"sk",
"sl",
"sr-cs",
"sv",
"th",
"tr",
"uk",
"vi",
"zh-cn",
"zh-hk",
"zh-tw",
)
// languageJSON is the JSON structure for language requests and responses.
type languageJSON struct {
Language string `json:"language"`
}
// TODO(d.kolyshev): Deprecated, remove it later.
func handleI18nCurrentLanguage(w http.ResponseWriter, r *http.Request) {
log.Printf("home: language is %s", config.Language)
aghhttp.WriteJSONResponseOK(w, r, &languageJSON{
Language: config.Language,
})
}
// TODO(d.kolyshev): Deprecated, remove it later.
func handleI18nChangeLanguage(w http.ResponseWriter, r *http.Request) {
if aghhttp.WriteTextPlainDeprecated(w, r) {
return
}
langReq := &languageJSON{}
err := json.NewDecoder(r.Body).Decode(langReq)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "reading req: %s", err)
return
}
lang := langReq.Language
if !allowedLanguages.Has(lang) {
aghhttp.Error(r, w, http.StatusBadRequest, "unknown language: %q", lang)
return
}
func() {
config.Lock()
defer config.Unlock()
config.Language = lang
log.Printf("home: language is set to %s", lang)
}()
onConfigModified()
aghhttp.OK(w)
}
``` | /content/code_sandbox/internal/home/i18n.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 523 |
```go
package home
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLimitRequestBody(t *testing.T) {
errReqLimitReached := &ioutil.LimitError{
Limit: defaultReqBodySzLim.Bytes(),
}
testCases := []struct {
wantErr error
name string
body string
want []byte
}{{
wantErr: nil,
name: "not_so_big",
body: "somestr",
want: []byte("somestr"),
}, {
wantErr: errReqLimitReached,
name: "so_big",
body: string(make([]byte, defaultReqBodySzLim+1)),
want: make([]byte, defaultReqBodySzLim),
}, {
wantErr: nil,
name: "empty",
body: "",
want: []byte(nil),
}}
makeHandler := func(t *testing.T, err *error) http.HandlerFunc {
t.Helper()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var b []byte
b, *err = io.ReadAll(r.Body)
_, werr := w.Write(b)
require.NoError(t, werr)
})
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
var err error
handler := makeHandler(t, &err)
lim := limitRequestBody(handler)
req := httptest.NewRequest(http.MethodPost, "path_to_url", strings.NewReader(tc.body))
res := httptest.NewRecorder()
lim.ServeHTTP(res, req)
assert.Equal(t, tc.wantErr, err)
assert.Equal(t, tc.want, res.Body.Bytes())
})
}
}
``` | /content/code_sandbox/internal/home/middlewares_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 419 |
```go
package home
import (
"bytes"
"crypto/rand"
"encoding/hex"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewSessionToken(t *testing.T) {
// Successful case.
token, err := newSessionToken()
require.NoError(t, err)
assert.Len(t, token, sessionTokenSize)
// Break the rand.Reader.
prevReader := rand.Reader
t.Cleanup(func() { rand.Reader = prevReader })
rand.Reader = &bytes.Buffer{}
// Unsuccessful case.
token, err = newSessionToken()
require.Error(t, err)
assert.Empty(t, token)
}
func TestAuth(t *testing.T) {
dir := t.TempDir()
fn := filepath.Join(dir, "sessions.db")
users := []webUser{{
Name: "name",
PasswordHash: "$2y$05$..vyzAECIhJPfaQiOK17IukcQnqEgKJHy0iETyYqxn3YXJl8yZuo2",
}}
a := InitAuth(fn, nil, 60, nil, nil)
s := session{}
user := webUser{Name: "name"}
err := a.addUser(&user, "password")
require.NoError(t, err)
assert.Equal(t, checkSessionNotFound, a.checkSession("notfound"))
a.removeSession("notfound")
sess, err := newSessionToken()
require.NoError(t, err)
sessStr := hex.EncodeToString(sess)
now := time.Now().UTC().Unix()
// check expiration
s.expire = uint32(now)
a.addSession(sess, &s)
assert.Equal(t, checkSessionExpired, a.checkSession(sessStr))
// add session with TTL = 2 sec
s = session{}
s.expire = uint32(time.Now().UTC().Unix() + 2)
a.addSession(sess, &s)
assert.Equal(t, checkSessionOK, a.checkSession(sessStr))
a.Close()
// load saved session
a = InitAuth(fn, users, 60, nil, nil)
// the session is still alive
assert.Equal(t, checkSessionOK, a.checkSession(sessStr))
// reset our expiration time because checkSession() has just updated it
s.expire = uint32(time.Now().UTC().Unix() + 2)
a.storeSession(sess, &s)
a.Close()
u, ok := a.findUser("name", "password")
assert.True(t, ok)
assert.NotEmpty(t, u.Name)
time.Sleep(3 * time.Second)
// load and remove expired sessions
a = InitAuth(fn, users, 60, nil, nil)
assert.Equal(t, checkSessionNotFound, a.checkSession(sessStr))
a.Close()
}
``` | /content/code_sandbox/internal/home/auth_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 591 |
```go
package home
import (
"fmt"
"net/netip"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testParseOK(t *testing.T, ss ...string) options {
t.Helper()
o, _, err := parseCmdOpts("", ss)
require.NoError(t, err)
return o
}
func testParseErr(t *testing.T, descr string, ss ...string) {
t.Helper()
_, _, err := parseCmdOpts("", ss)
require.Error(t, err)
}
func testParseParamMissing(t *testing.T, param string) {
t.Helper()
testParseErr(t, fmt.Sprintf("%s parameter missing", param), param)
}
func TestParseVerbose(t *testing.T) {
assert.False(t, testParseOK(t).verbose, "empty is not verbose")
assert.True(t, testParseOK(t, "-v").verbose, "-v is verbose")
assert.True(t, testParseOK(t, "--verbose").verbose, "--verbose is verbose")
}
func TestParseConfigFilename(t *testing.T) {
assert.Equal(t, "", testParseOK(t).confFilename, "empty is no config filename")
assert.Equal(t, "path", testParseOK(t, "-c", "path").confFilename, "-c is config filename")
testParseParamMissing(t, "-c")
assert.Equal(t, "path", testParseOK(t, "--config", "path").confFilename, "--config is config filename")
testParseParamMissing(t, "--config")
}
func TestParseWorkDir(t *testing.T) {
assert.Equal(t, "", testParseOK(t).workDir, "empty is no work dir")
assert.Equal(t, "path", testParseOK(t, "-w", "path").workDir, "-w is work dir")
testParseParamMissing(t, "-w")
assert.Equal(t, "path", testParseOK(t, "--work-dir", "path").workDir, "--work-dir is work dir")
testParseParamMissing(t, "--work-dir")
}
func TestParseBindHost(t *testing.T) {
wantAddr := netip.MustParseAddr("1.2.3.4")
assert.Zero(t, testParseOK(t).bindHost, "empty is not host")
assert.Equal(t, wantAddr, testParseOK(t, "-h", "1.2.3.4").bindHost, "-h is host")
testParseParamMissing(t, "-h")
assert.Equal(t, wantAddr, testParseOK(t, "--host", "1.2.3.4").bindHost, "--host is host")
testParseParamMissing(t, "--host")
}
func TestParseBindPort(t *testing.T) {
assert.Equal(t, uint16(0), testParseOK(t).bindPort, "empty is port 0")
assert.Equal(t, uint16(65535), testParseOK(t, "-p", "65535").bindPort, "-p is port")
testParseParamMissing(t, "-p")
assert.Equal(t, uint16(65535), testParseOK(t, "--port", "65535").bindPort, "--port is port")
testParseParamMissing(t, "--port")
testParseErr(t, "not an int", "-p", "x")
testParseErr(t, "hex not supported", "-p", "0x100")
testParseErr(t, "port negative", "-p", "-1")
testParseErr(t, "port too high", "-p", "65536")
testParseErr(t, "port too high", "-p", "4294967297") // 2^32 + 1
testParseErr(t, "port too high", "-p", "18446744073709551617") // 2^64 + 1
}
func TestParseBindAddr(t *testing.T) {
wantAddrPort := netip.MustParseAddrPort("1.2.3.4:8089")
assert.Zero(t, testParseOK(t).bindAddr, "empty is not web-addr")
assert.Equal(t, wantAddrPort, testParseOK(t, "--web-addr", "1.2.3.4:8089").bindAddr)
assert.Equal(t, netip.MustParseAddrPort("1.2.3.4:0"), testParseOK(t, "--web-addr", "1.2.3.4:0").bindAddr)
testParseParamMissing(t, "-web-addr")
testParseErr(t, "not an int", "--web-addr", "1.2.3.4:x")
testParseErr(t, "hex not supported", "--web-addr", "1.2.3.4:0x100")
testParseErr(t, "port negative", "--web-addr", "1.2.3.4:-1")
testParseErr(t, "port too high", "--web-addr", "1.2.3.4:65536")
testParseErr(t, "port too high", "--web-addr", "1.2.3.4:4294967297") // 2^32 + 1
testParseErr(t, "port too high", "--web-addr", "1.2.3.4:18446744073709551617") // 2^64 + 1
}
func TestParseLogfile(t *testing.T) {
assert.Equal(t, "", testParseOK(t).logFile, "empty is no log file")
assert.Equal(t, "path", testParseOK(t, "-l", "path").logFile, "-l is log file")
assert.Equal(t, "path", testParseOK(t, "--logfile", "path").logFile, "--logfile is log file")
}
func TestParsePidfile(t *testing.T) {
assert.Equal(t, "", testParseOK(t).pidFile, "empty is no pid file")
assert.Equal(t, "path", testParseOK(t, "--pidfile", "path").pidFile, "--pidfile is pid file")
}
func TestParseCheckConfig(t *testing.T) {
assert.False(t, testParseOK(t).checkConfig, "empty is not check config")
assert.True(t, testParseOK(t, "--check-config").checkConfig, "--check-config is check config")
}
func TestParseDisableUpdate(t *testing.T) {
assert.False(t, testParseOK(t).disableUpdate, "empty is not disable update")
assert.True(t, testParseOK(t, "--no-check-update").disableUpdate, "--no-check-update is disable update")
}
func TestParsePerformUpdate(t *testing.T) {
assert.False(t, testParseOK(t).performUpdate, "empty is not perform update")
assert.True(t, testParseOK(t, "--update").performUpdate, "--update is perform update")
}
// TODO(e.burkov): Remove after v0.108.0.
func TestParseDisableMemoryOptimization(t *testing.T) {
o, eff, err := parseCmdOpts("", []string{"--no-mem-optimization"})
require.NoError(t, err)
assert.Nil(t, eff)
assert.Zero(t, o)
}
func TestParseService(t *testing.T) {
assert.Equal(t, "", testParseOK(t).serviceControlAction, "empty is not service cmd")
assert.Equal(t, "cmd", testParseOK(t, "-s", "cmd").serviceControlAction, "-s is service cmd")
assert.Equal(t, "cmd", testParseOK(t, "--service", "cmd").serviceControlAction, "--service is service cmd")
}
func TestParseGLInet(t *testing.T) {
assert.False(t, testParseOK(t).glinetMode, "empty is not GL-Inet mode")
assert.True(t, testParseOK(t, "--glinet").glinetMode, "--glinet is GL-Inet mode")
}
func TestParseUnknown(t *testing.T) {
testParseErr(t, "unknown word", "x")
testParseErr(t, "unknown short", "-x")
testParseErr(t, "unknown long", "--x")
testParseErr(t, "unknown triple", "---x")
testParseErr(t, "unknown plus", "+x")
testParseErr(t, "unknown dash", "-")
}
func TestOptsToArgs(t *testing.T) {
testCases := []struct {
name string
args []string
opts options
}{{
name: "empty",
args: []string{},
opts: options{},
}, {
name: "config_filename",
args: []string{"-c", "path"},
opts: options{confFilename: "path"},
}, {
name: "work_dir",
args: []string{"-w", "path"},
opts: options{workDir: "path"},
}, {
name: "bind_host",
opts: options{bindHost: netip.MustParseAddr("1.2.3.4")},
args: []string{"-h", "1.2.3.4"},
}, {
name: "bind_port",
args: []string{"-p", "666"},
opts: options{bindPort: 666},
}, {
name: "web-addr",
args: []string{"--web-addr", "1.2.3.4:8080"},
opts: options{bindAddr: netip.MustParseAddrPort("1.2.3.4:8080")},
}, {
name: "log_file",
args: []string{"-l", "path"},
opts: options{logFile: "path"},
}, {
name: "pid_file",
args: []string{"--pidfile", "path"},
opts: options{pidFile: "path"},
}, {
name: "disable_update",
args: []string{"--no-check-update"},
opts: options{disableUpdate: true},
}, {
name: "perform_update",
args: []string{"--update"},
opts: options{performUpdate: true},
}, {
name: "control_action",
args: []string{"-s", "run"},
opts: options{serviceControlAction: "run"},
}, {
name: "glinet_mode",
args: []string{"--glinet"},
opts: options{glinetMode: true},
}, {
name: "multiple",
args: []string{
"-c", "config",
"-w", "work",
"-s", "run",
"--pidfile", "pid",
"--no-check-update",
},
opts: options{
serviceControlAction: "run",
confFilename: "config",
workDir: "work",
pidFile: "pid",
disableUpdate: true,
},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := optsToArgs(tc.opts)
assert.ElementsMatch(t, tc.args, result)
})
}
}
``` | /content/code_sandbox/internal/home/options_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 2,342 |
```go
package home
import (
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/netip"
"path"
"strconv"
"strings"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/httphdr"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/timeutil"
)
// cookieTTL is the time-to-live of the session cookie.
const cookieTTL = 365 * timeutil.Day
// sessionCookieName is the name of the session cookie.
const sessionCookieName = "agh_session"
// loginJSON is the JSON structure for authentication.
type loginJSON struct {
Name string `json:"name"`
Password string `json:"password"`
}
// newCookie creates a new authentication cookie.
func (a *Auth) newCookie(req loginJSON, addr string) (c *http.Cookie, err error) {
rateLimiter := a.rateLimiter
u, ok := a.findUser(req.Name, req.Password)
if !ok {
if rateLimiter != nil {
rateLimiter.inc(addr)
}
return nil, errors.Error("invalid username or password")
}
if rateLimiter != nil {
rateLimiter.remove(addr)
}
sess, err := newSessionToken()
if err != nil {
return nil, fmt.Errorf("generating token: %w", err)
}
now := time.Now().UTC()
a.addSession(sess, &session{
userName: u.Name,
expire: uint32(now.Unix()) + a.sessionTTL,
})
return &http.Cookie{
Name: sessionCookieName,
Value: hex.EncodeToString(sess),
Path: "/",
Expires: now.Add(cookieTTL),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}, nil
}
// realIP extracts the real IP address of the client from an HTTP request using
// the known HTTP headers.
//
// TODO(a.garipov): Currently, this is basically a copy of a similar function in
// module dnsproxy. This should really become a part of module golibs and be
// replaced both here and there. Or be replaced in both places by
// a well-maintained third-party module.
//
// TODO(a.garipov): Support header Forwarded from RFC 7329.
func realIP(r *http.Request) (ip netip.Addr, err error) {
proxyHeaders := []string{
httphdr.CFConnectingIP,
httphdr.TrueClientIP,
httphdr.XRealIP,
}
for _, h := range proxyHeaders {
v := r.Header.Get(h)
ip, err = netip.ParseAddr(v)
if err == nil {
return ip, nil
}
}
// If none of the above yielded any results, get the leftmost IP address
// from the X-Forwarded-For header.
s := r.Header.Get(httphdr.XForwardedFor)
ipStr, _, _ := strings.Cut(s, ",")
ip, err = netip.ParseAddr(ipStr)
if err == nil {
return ip, nil
}
// When everything else fails, just return the remote address as understood
// by the stdlib.
ipStr, err = netutil.SplitHost(r.RemoteAddr)
if err != nil {
return netip.Addr{}, fmt.Errorf("getting ip from client addr: %w", err)
}
return netip.ParseAddr(ipStr)
}
// writeErrorWithIP is like [aghhttp.Error], but includes the remote IP address
// when it writes to the log.
func writeErrorWithIP(
r *http.Request,
w http.ResponseWriter,
code int,
remoteIP string,
format string,
args ...any,
) {
text := fmt.Sprintf(format, args...)
log.Error("%s %s %s: from ip %s: %s", r.Method, r.Host, r.URL, remoteIP, text)
http.Error(w, text, code)
}
// handleLogin is the handler for the POST /control/login HTTP API.
func handleLogin(w http.ResponseWriter, r *http.Request) {
req := loginJSON{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err)
return
}
var remoteIP string
// realIP cannot be used here without taking TrustedProxies into account due
// to security issues.
//
// See path_to_url
if remoteIP, err = netutil.SplitHost(r.RemoteAddr); err != nil {
writeErrorWithIP(
r,
w,
http.StatusBadRequest,
r.RemoteAddr,
"auth: getting remote address: %s",
err,
)
return
}
if rateLimiter := Context.auth.rateLimiter; rateLimiter != nil {
if left := rateLimiter.check(remoteIP); left > 0 {
w.Header().Set(httphdr.RetryAfter, strconv.Itoa(int(left.Seconds())))
writeErrorWithIP(
r,
w,
http.StatusTooManyRequests,
remoteIP,
"auth: blocked for %s",
left,
)
return
}
}
ip, err := realIP(r)
if err != nil {
log.Error("auth: getting real ip from request with remote ip %s: %s", remoteIP, err)
}
cookie, err := Context.auth.newCookie(req, remoteIP)
if err != nil {
logIP := remoteIP
if Context.auth.trustedProxies.Contains(ip.Unmap()) {
logIP = ip.String()
}
writeErrorWithIP(r, w, http.StatusForbidden, logIP, "%s", err)
return
}
log.Info("auth: user %q successfully logged in from ip %s", req.Name, ip)
http.SetCookie(w, cookie)
h := w.Header()
h.Set(httphdr.CacheControl, "no-store, no-cache, must-revalidate, proxy-revalidate")
h.Set(httphdr.Pragma, "no-cache")
h.Set(httphdr.Expires, "0")
aghhttp.OK(w)
}
// handleLogout is the handler for the GET /control/logout HTTP API.
func handleLogout(w http.ResponseWriter, r *http.Request) {
respHdr := w.Header()
c, err := r.Cookie(sessionCookieName)
if err != nil {
// The only error that is returned from r.Cookie is [http.ErrNoCookie].
// The user is already logged out.
respHdr.Set(httphdr.Location, "/login.html")
w.WriteHeader(http.StatusFound)
return
}
Context.auth.removeSession(c.Value)
c = &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: "/",
Expires: time.Unix(0, 0),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
respHdr.Set(httphdr.Location, "/login.html")
respHdr.Set(httphdr.SetCookie, c.String())
w.WriteHeader(http.StatusFound)
}
// RegisterAuthHandlers - register handlers
func RegisterAuthHandlers() {
Context.mux.Handle("/control/login", postInstallHandler(ensureHandler(http.MethodPost, handleLogin)))
httpRegister(http.MethodGet, "/control/logout", handleLogout)
}
// optionalAuthThird returns true if a user should authenticate first.
func optionalAuthThird(w http.ResponseWriter, r *http.Request) (mustAuth bool) {
pref := fmt.Sprintf("auth: raddr %s", r.RemoteAddr)
if glProcessCookie(r) {
log.Debug("%s: authentication is handled by gl-inet submodule", pref)
return false
}
// redirect to login page if not authenticated
isAuthenticated := false
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
// The only error that is returned from r.Cookie is [http.ErrNoCookie].
// Check Basic authentication.
user, pass, hasBasic := r.BasicAuth()
if hasBasic {
_, isAuthenticated = Context.auth.findUser(user, pass)
if !isAuthenticated {
log.Info("%s: invalid basic authorization value", pref)
}
}
} else {
res := Context.auth.checkSession(cookie.Value)
isAuthenticated = res == checkSessionOK
if !isAuthenticated {
log.Debug("%s: invalid cookie value: %q", pref, cookie)
}
}
if isAuthenticated {
return false
}
if p := r.URL.Path; p == "/" || p == "/index.html" {
if glProcessRedirect(w, r) {
log.Debug("%s: redirected to login page by gl-inet submodule", pref)
} else {
log.Debug("%s: redirected to login page", pref)
http.Redirect(w, r, "login.html", http.StatusFound)
}
} else {
log.Debug("%s: responded with forbidden to %s %s", pref, r.Method, p)
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte("Forbidden"))
}
return true
}
// TODO(a.garipov): Use [http.Handler] consistently everywhere throughout the
// project.
func optionalAuth(
h func(http.ResponseWriter, *http.Request),
) (wrapped func(http.ResponseWriter, *http.Request)) {
return func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path
authRequired := Context.auth != nil && Context.auth.authRequired()
if p == "/login.html" {
cookie, err := r.Cookie(sessionCookieName)
if authRequired && err == nil {
// Redirect to the dashboard if already authenticated.
res := Context.auth.checkSession(cookie.Value)
if res == checkSessionOK {
http.Redirect(w, r, "", http.StatusFound)
return
}
log.Debug("auth: raddr %s: invalid cookie value: %q", r.RemoteAddr, cookie)
}
} else if isPublicResource(p) {
// Process as usual, no additional auth requirements.
} else if authRequired {
if optionalAuthThird(w, r) {
return
}
}
h(w, r)
}
}
// isPublicResource returns true if p is a path to a public resource.
func isPublicResource(p string) (ok bool) {
isAsset, err := path.Match("/assets/*", p)
if err != nil {
// The only error that is returned from path.Match is
// [path.ErrBadPattern]. This is a programmer error.
panic(fmt.Errorf("bad asset pattern: %w", err))
}
isLogin, err := path.Match("/login.*", p)
if err != nil {
// Same as above.
panic(fmt.Errorf("bad login pattern: %w", err))
}
return isAsset || isLogin
}
// authHandler is a helper structure that implements [http.Handler].
type authHandler struct {
handler http.Handler
}
// ServeHTTP implements the [http.Handler] interface for *authHandler.
func (a *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
optionalAuth(a.handler.ServeHTTP)(w, r)
}
// optionalAuthHandler returns a authentication handler.
func optionalAuthHandler(handler http.Handler) http.Handler {
return &authHandler{handler}
}
``` | /content/code_sandbox/internal/home/authhttp.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 2,514 |
```go
package home
import (
"encoding/json"
"fmt"
"net/http"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/golibs/log"
)
// Theme is an enum of all allowed UI themes.
type Theme string
// Allowed [Theme] values.
//
// Keep in sync with client/src/helpers/constants.ts.
const (
ThemeAuto Theme = "auto"
ThemeLight Theme = "light"
ThemeDark Theme = "dark"
)
// UnmarshalText implements [encoding.TextUnmarshaler] interface for *Theme.
func (t *Theme) UnmarshalText(b []byte) (err error) {
switch string(b) {
case "auto":
*t = ThemeAuto
case "dark":
*t = ThemeDark
case "light":
*t = ThemeLight
default:
return fmt.Errorf("invalid theme %q, supported: %q, %q, %q", b, ThemeAuto, ThemeDark, ThemeLight)
}
return nil
}
// profileJSON is an object for /control/profile and /control/profile/update
// endpoints.
type profileJSON struct {
Name string `json:"name"`
Language string `json:"language"`
Theme Theme `json:"theme"`
}
// handleGetProfile is the handler for GET /control/profile endpoint.
func handleGetProfile(w http.ResponseWriter, r *http.Request) {
u := Context.auth.getCurrentUser(r)
var resp profileJSON
func() {
config.RLock()
defer config.RUnlock()
resp = profileJSON{
Name: u.Name,
Language: config.Language,
Theme: config.Theme,
}
}()
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// handlePutProfile is the handler for PUT /control/profile/update endpoint.
func handlePutProfile(w http.ResponseWriter, r *http.Request) {
if aghhttp.WriteTextPlainDeprecated(w, r) {
return
}
profileReq := &profileJSON{}
err := json.NewDecoder(r.Body).Decode(profileReq)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "reading req: %s", err)
return
}
lang := profileReq.Language
if !allowedLanguages.Has(lang) {
aghhttp.Error(r, w, http.StatusBadRequest, "unknown language: %q", lang)
return
}
theme := profileReq.Theme
func() {
config.Lock()
defer config.Unlock()
config.Language = lang
config.Theme = theme
log.Printf("home: language is set to %s", lang)
log.Printf("home: theme is set to %s", theme)
}()
onConfigModified()
aghhttp.OK(w)
}
``` | /content/code_sandbox/internal/home/profilehttp.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 587 |
```go
package home
import (
"fmt"
"net/http"
"net/netip"
"net/url"
"runtime"
"strings"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/dnsforward"
"github.com/AdguardTeam/AdGuardHome/internal/version"
"github.com/AdguardTeam/golibs/httphdr"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
"github.com/NYTimes/gziphandler"
)
// appendDNSAddrs is a convenient helper for appending a formatted form of DNS
// addresses to a slice of strings.
func appendDNSAddrs(dst []string, addrs ...netip.Addr) (res []string) {
for _, addr := range addrs {
hostport := addr.String()
if p := config.DNS.Port; p != defaultPortDNS {
hostport = netutil.JoinHostPort(hostport, p)
}
dst = append(dst, hostport)
}
return dst
}
// appendDNSAddrsWithIfaces formats and appends all DNS addresses from src to
// dst. It also adds the IP addresses of all network interfaces if src contains
// an unspecified IP address.
func appendDNSAddrsWithIfaces(dst []string, src []netip.Addr) (res []string, err error) {
ifacesAdded := false
for _, h := range src {
if !h.IsUnspecified() {
dst = appendDNSAddrs(dst, h)
continue
} else if ifacesAdded {
continue
}
// Add addresses of all network interfaces for addresses like
// "0.0.0.0" and "::".
var ifaces []*aghnet.NetInterface
ifaces, err = aghnet.GetValidNetInterfacesForWeb()
if err != nil {
return nil, fmt.Errorf("cannot get network interfaces: %w", err)
}
for _, iface := range ifaces {
dst = appendDNSAddrs(dst, iface.Addresses...)
}
ifacesAdded = true
}
return dst, nil
}
// collectDNSAddresses returns the list of DNS addresses the server is listening
// on, including the addresses on all interfaces in cases of unspecified IPs.
func collectDNSAddresses() (addrs []string, err error) {
if hosts := config.DNS.BindHosts; len(hosts) == 0 {
addrs = appendDNSAddrs(addrs, netutil.IPv4Localhost())
} else {
addrs, err = appendDNSAddrsWithIfaces(addrs, hosts)
if err != nil {
return nil, fmt.Errorf("collecting dns addresses: %w", err)
}
}
de := getDNSEncryption()
if de.https != "" {
addrs = append(addrs, de.https)
}
if de.tls != "" {
addrs = append(addrs, de.tls)
}
if de.quic != "" {
addrs = append(addrs, de.quic)
}
return addrs, nil
}
// statusResponse is a response for /control/status endpoint.
type statusResponse struct {
Version string `json:"version"`
Language string `json:"language"`
DNSAddrs []string `json:"dns_addresses"`
DNSPort uint16 `json:"dns_port"`
HTTPPort uint16 `json:"http_port"`
// ProtectionDisabledDuration is the duration of the protection pause in
// milliseconds.
ProtectionDisabledDuration int64 `json:"protection_disabled_duration"`
ProtectionEnabled bool `json:"protection_enabled"`
// TODO(e.burkov): Inspect if front-end doesn't requires this field as
// openapi.yaml declares.
IsDHCPAvailable bool `json:"dhcp_available"`
IsRunning bool `json:"running"`
}
func handleStatus(w http.ResponseWriter, r *http.Request) {
dnsAddrs, err := collectDNSAddresses()
if err != nil {
// Don't add a lot of formatting, since the error is already
// wrapped by collectDNSAddresses.
aghhttp.Error(r, w, http.StatusInternalServerError, "%s", err)
return
}
var (
fltConf *dnsforward.Config
protectionDisabledUntil *time.Time
protectionEnabled bool
)
if Context.dnsServer != nil {
fltConf = &dnsforward.Config{}
Context.dnsServer.WriteDiskConfig(fltConf)
protectionEnabled, protectionDisabledUntil = Context.dnsServer.UpdatedProtectionStatus()
}
var resp statusResponse
func() {
config.RLock()
defer config.RUnlock()
var protectionDisabledDuration int64
if protectionDisabledUntil != nil {
// Make sure that we don't send negative numbers to the frontend,
// since enough time might have passed to make the difference less
// than zero.
protectionDisabledDuration = max(0, time.Until(*protectionDisabledUntil).Milliseconds())
}
resp = statusResponse{
Version: version.Version(),
Language: config.Language,
DNSAddrs: dnsAddrs,
DNSPort: config.DNS.Port,
HTTPPort: config.HTTPConfig.Address.Port(),
ProtectionDisabledDuration: protectionDisabledDuration,
ProtectionEnabled: protectionEnabled,
IsRunning: isRunning(),
}
}()
// IsDHCPAvailable field is now false by default for Windows.
if runtime.GOOS != "windows" {
resp.IsDHCPAvailable = Context.dhcpServer != nil
}
aghhttp.WriteJSONResponseOK(w, r, resp)
}
// ------------------------
// registration of handlers
// ------------------------
func registerControlHandlers(web *webAPI) {
Context.mux.HandleFunc(
"/control/version.json",
postInstall(optionalAuth(web.handleVersionJSON)),
)
httpRegister(http.MethodPost, "/control/update", web.handleUpdate)
httpRegister(http.MethodGet, "/control/status", handleStatus)
httpRegister(http.MethodPost, "/control/i18n/change_language", handleI18nChangeLanguage)
httpRegister(http.MethodGet, "/control/i18n/current_language", handleI18nCurrentLanguage)
httpRegister(http.MethodGet, "/control/profile", handleGetProfile)
httpRegister(http.MethodPut, "/control/profile/update", handlePutProfile)
// No auth is necessary for DoH/DoT configurations
Context.mux.HandleFunc("/apple/doh.mobileconfig", postInstall(handleMobileConfigDoH))
Context.mux.HandleFunc("/apple/dot.mobileconfig", postInstall(handleMobileConfigDoT))
RegisterAuthHandlers()
}
func httpRegister(method, url string, handler http.HandlerFunc) {
if method == "" {
// "/dns-query" handler doesn't need auth, gzip and isn't restricted by 1 HTTP method
Context.mux.HandleFunc(url, postInstall(handler))
return
}
Context.mux.Handle(url, postInstallHandler(optionalAuthHandler(gziphandler.GzipHandler(ensureHandler(method, handler)))))
}
// ensure returns a wrapped handler that makes sure that the request has the
// correct method as well as additional method and header checks.
func ensure(
method string,
handler func(http.ResponseWriter, *http.Request),
) (wrapped func(http.ResponseWriter, *http.Request)) {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
m, u := r.Method, r.URL
log.Debug("started %s %s %s", m, r.Host, u)
defer func() { log.Debug("finished %s %s %s in %s", m, r.Host, u, time.Since(start)) }()
if m != method {
aghhttp.Error(r, w, http.StatusMethodNotAllowed, "only method %s is allowed", method)
return
}
if modifiesData(m) {
if !ensureContentType(w, r) {
return
}
Context.controlLock.Lock()
defer Context.controlLock.Unlock()
}
handler(w, r)
}
}
// modifiesData returns true if m is an HTTP method that can modify data.
func modifiesData(m string) (ok bool) {
return m == http.MethodPost || m == http.MethodPut || m == http.MethodDelete
}
// ensureContentType makes sure that the content type of a data-modifying
// request is set correctly. If it is not, ensureContentType writes a response
// to w, and ok is false.
func ensureContentType(w http.ResponseWriter, r *http.Request) (ok bool) {
const statusUnsup = http.StatusUnsupportedMediaType
cType := r.Header.Get(httphdr.ContentType)
if r.ContentLength == 0 {
if cType == "" {
return true
}
// Assume that browsers always send a content type when submitting HTML
// forms and require no content type for requests with no body to make
// sure that the request comes from JavaScript.
aghhttp.Error(r, w, statusUnsup, "empty body with content-type %q not allowed", cType)
return false
}
const wantCType = aghhttp.HdrValApplicationJSON
if cType == wantCType {
return true
}
aghhttp.Error(r, w, statusUnsup, "only content-type %s is allowed", wantCType)
return false
}
func ensurePOST(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return ensure(http.MethodPost, handler)
}
func ensureGET(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return ensure(http.MethodGet, handler)
}
// Bridge between http.Handler object and Go function
type httpHandler struct {
handler func(http.ResponseWriter, *http.Request)
}
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.handler(w, r)
}
func ensureHandler(method string, handler func(http.ResponseWriter, *http.Request)) http.Handler {
h := httpHandler{}
h.handler = ensure(method, handler)
return &h
}
// preInstall lets the handler run only if firstRun is true, no redirects
func preInstall(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if !Context.firstRun {
// if it's not first run, don't let users access it (for example /install.html when configuration is done)
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
handler(w, r)
}
}
// preInstallStruct wraps preInstall into a struct that can be returned as an interface where necessary
type preInstallHandlerStruct struct {
handler http.Handler
}
func (p *preInstallHandlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
preInstall(p.handler.ServeHTTP)(w, r)
}
// preInstallHandler returns http.Handler interface for preInstall wrapper
func preInstallHandler(handler http.Handler) http.Handler {
return &preInstallHandlerStruct{handler}
}
// handleHTTPSRedirect redirects the request to HTTPS, if needed, and adds some
// HTTPS-related headers. If proceed is true, the middleware must continue
// handling the request.
func handleHTTPSRedirect(w http.ResponseWriter, r *http.Request) (proceed bool) {
web := Context.web
if web.httpsServer.server == nil {
return true
}
host, err := netutil.SplitHost(r.Host)
if err != nil {
aghhttp.Error(r, w, http.StatusBadRequest, "bad host: %s", err)
return false
}
var (
forceHTTPS bool
serveHTTP3 bool
portHTTPS uint16
)
func() {
config.RLock()
defer config.RUnlock()
serveHTTP3, portHTTPS = config.DNS.ServeHTTP3, config.TLS.PortHTTPS
forceHTTPS = config.TLS.ForceHTTPS && config.TLS.Enabled && config.TLS.PortHTTPS != 0
}()
respHdr := w.Header()
// Let the browser know that server supports HTTP/3.
//
// See path_to_url
//
// TODO(a.garipov): Consider adding a configurable max-age. Currently, the
// default is 24 hours.
if serveHTTP3 {
altSvc := fmt.Sprintf(`h3=":%d"`, portHTTPS)
respHdr.Set(httphdr.AltSvc, altSvc)
}
if forceHTTPS {
if r.TLS == nil {
u := httpsURL(r.URL, host, portHTTPS)
http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect)
return false
}
// TODO(a.garipov): Consider adding a configurable max-age. Currently,
// the default is 365 days.
respHdr.Set(httphdr.StrictTransportSecurity, aghhttp.HdrValStrictTransportSecurity)
}
// Allow the frontend from the HTTP origin to send requests to the HTTPS
// server. This can happen when the user has just set up HTTPS with
// redirects. Prevent cache-related errors by setting the Vary header.
//
// See path_to_url
originURL := &url.URL{
Scheme: aghhttp.SchemeHTTP,
Host: r.Host,
}
respHdr.Set(httphdr.AccessControlAllowOrigin, originURL.String())
respHdr.Set(httphdr.Vary, httphdr.Origin)
return true
}
// httpsURL returns a copy of u for redirection to the HTTPS version, taking the
// hostname and the HTTPS port into account.
func httpsURL(u *url.URL, host string, portHTTPS uint16) (redirectURL *url.URL) {
hostPort := host
if portHTTPS != defaultPortHTTPS {
hostPort = netutil.JoinHostPort(host, portHTTPS)
}
return &url.URL{
Scheme: aghhttp.SchemeHTTPS,
Host: hostPort,
Path: u.Path,
RawQuery: u.RawQuery,
}
}
// postInstall lets the handler to run only if firstRun is false. Otherwise, it
// redirects to /install.html. It also enforces HTTPS if it is enabled and
// configured and sets appropriate access control headers.
func postInstall(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if Context.firstRun && !strings.HasPrefix(path, "/install.") &&
!strings.HasPrefix(path, "/assets/") {
http.Redirect(w, r, "install.html", http.StatusFound)
return
}
proceed := handleHTTPSRedirect(w, r)
if proceed {
handler(w, r)
}
}
}
type postInstallHandlerStruct struct {
handler http.Handler
}
func (p *postInstallHandlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
postInstall(p.handler.ServeHTTP)(w, r)
}
func postInstallHandler(handler http.Handler) http.Handler {
return &postInstallHandlerStruct{handler}
}
``` | /content/code_sandbox/internal/home/control.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 3,299 |
```go
package home
import (
"io"
"net/http"
"github.com/AdguardTeam/golibs/ioutil"
"github.com/c2h5oh/datasize"
)
// middlerware is a wrapper function signature.
type middleware func(http.Handler) http.Handler
// withMiddlewares consequently wraps h with all the middlewares.
//
// TODO(e.burkov): Use [httputil.Wrap].
func withMiddlewares(h http.Handler, middlewares ...middleware) (wrapped http.Handler) {
wrapped = h
for _, mw := range middlewares {
wrapped = mw(wrapped)
}
return wrapped
}
const (
// defaultReqBodySzLim is the default maximum request body size.
defaultReqBodySzLim datasize.ByteSize = 64 * datasize.KB
// largerReqBodySzLim is the maximum request body size for APIs expecting
// larger requests.
largerReqBodySzLim datasize.ByteSize = 4 * datasize.MB
)
// expectsLargerRequests shows if this request should use a larger body size
// limit. These are exceptions for poorly designed current APIs as well as APIs
// that are designed to expect large files and requests. Remove once the new,
// better APIs are up.
//
// See path_to_url and
// path_to_url
func expectsLargerRequests(r *http.Request) (ok bool) {
if r.Method != http.MethodPost {
return false
}
switch r.URL.Path {
case "/control/access/set", "/control/filtering/set_rules":
return true
default:
return false
}
}
// limitRequestBody wraps underlying handler h, making it's request's body Read
// method limited.
func limitRequestBody(h http.Handler) (limited http.Handler) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
szLim := defaultReqBodySzLim
if expectsLargerRequests(r) {
szLim = largerReqBodySzLim
}
reader := ioutil.LimitReader(r.Body, szLim.Bytes())
// HTTP handlers aren't supposed to call r.Body.Close(), so just
// replace the body in a clone.
rr := r.Clone(r.Context())
rr.Body = io.NopCloser(reader)
h.ServeHTTP(w, rr)
})
}
``` | /content/code_sandbox/internal/home/middlewares.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 492 |
```go
package home
import (
"bytes"
"fmt"
"net/netip"
"os"
"path/filepath"
"sync"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghtls"
"github.com/AdguardTeam/AdGuardHome/internal/configmigrate"
"github.com/AdguardTeam/AdGuardHome/internal/dhcpd"
"github.com/AdguardTeam/AdGuardHome/internal/dnsforward"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/AdGuardHome/internal/querylog"
"github.com/AdguardTeam/AdGuardHome/internal/schedule"
"github.com/AdguardTeam/AdGuardHome/internal/stats"
"github.com/AdguardTeam/dnsproxy/fastip"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/timeutil"
"github.com/google/renameio/v2/maybe"
yaml "gopkg.in/yaml.v3"
)
// dataDir is the name of a directory under the working one to store some
// persistent data.
const dataDir = "data"
// logSettings are the logging settings part of the configuration file.
type logSettings struct {
// Enabled indicates whether logging is enabled.
Enabled bool `yaml:"enabled"`
// File is the path to the log file. If empty, logs are written to stdout.
// If "syslog", logs are written to syslog.
File string `yaml:"file"`
// MaxBackups is the maximum number of old log files to retain.
//
// NOTE: MaxAge may still cause them to get deleted.
MaxBackups int `yaml:"max_backups"`
// MaxSize is the maximum size of the log file before it gets rotated, in
// megabytes. The default value is 100 MB.
MaxSize int `yaml:"max_size"`
// MaxAge is the maximum duration for retaining old log files, in days.
MaxAge int `yaml:"max_age"`
// Compress determines, if the rotated log files should be compressed using
// gzip.
Compress bool `yaml:"compress"`
// LocalTime determines, if the time used for formatting the timestamps in
// is the computer's local time.
LocalTime bool `yaml:"local_time"`
// Verbose determines, if verbose (aka debug) logging is enabled.
Verbose bool `yaml:"verbose"`
}
// osConfig contains OS-related configuration.
type osConfig struct {
// Group is the name of the group which AdGuard Home must switch to on
// startup. Empty string means no switching.
Group string `yaml:"group"`
// User is the name of the user which AdGuard Home must switch to on
// startup. Empty string means no switching.
User string `yaml:"user"`
// RlimitNoFile is the maximum number of opened fd's per process. Zero
// means use the default value.
RlimitNoFile uint64 `yaml:"rlimit_nofile"`
}
type clientsConfig struct {
// Sources defines the set of sources to fetch the runtime clients from.
Sources *clientSourcesConfig `yaml:"runtime_sources"`
// Persistent are the configured clients.
Persistent []*clientObject `yaml:"persistent"`
}
// clientSourceConfig is used to configure where the runtime clients will be
// obtained from.
type clientSourcesConfig struct {
WHOIS bool `yaml:"whois"`
ARP bool `yaml:"arp"`
RDNS bool `yaml:"rdns"`
DHCP bool `yaml:"dhcp"`
HostsFile bool `yaml:"hosts"`
}
// configuration is loaded from YAML.
//
// Field ordering is important, YAML fields better not to be reordered, if it's
// not absolutely necessary.
type configuration struct {
// Raw file data to avoid re-reading of configuration file
// It's reset after config is parsed
fileData []byte
// HTTPConfig is the block with http conf.
HTTPConfig httpConfig `yaml:"http"`
// Users are the clients capable for accessing the web interface.
Users []webUser `yaml:"users"`
// AuthAttempts is the maximum number of failed login attempts a user
// can do before being blocked.
AuthAttempts uint `yaml:"auth_attempts"`
// AuthBlockMin is the duration, in minutes, of the block of new login
// attempts after AuthAttempts unsuccessful login attempts.
AuthBlockMin uint `yaml:"block_auth_min"`
// ProxyURL is the address of proxy server for the internal HTTP client.
ProxyURL string `yaml:"http_proxy"`
// Language is a two-letter ISO 639-1 language code.
Language string `yaml:"language"`
// Theme is a UI theme for current user.
Theme Theme `yaml:"theme"`
// TODO(a.garipov): Make DNS and the fields below pointers and validate
// and/or reset on explicit nulling.
DNS dnsConfig `yaml:"dns"`
TLS tlsConfigSettings `yaml:"tls"`
QueryLog queryLogConfig `yaml:"querylog"`
Stats statsConfig `yaml:"statistics"`
// Filters reflects the filters from [filtering.Config]. It's cloned to the
// config used in the filtering module at the startup. Afterwards it's
// cloned from the filtering module back here.
//
// TODO(e.burkov): Move all the filtering configuration fields into the
// only configuration subsection covering the changes with a single
// migration. Also keep the blocked services in mind.
Filters []filtering.FilterYAML `yaml:"filters"`
WhitelistFilters []filtering.FilterYAML `yaml:"whitelist_filters"`
UserRules []string `yaml:"user_rules"`
DHCP *dhcpd.ServerConfig `yaml:"dhcp"`
Filtering *filtering.Config `yaml:"filtering"`
// Clients contains the YAML representations of the persistent clients.
// This field is only used for reading and writing persistent client data.
// Keep this field sorted to ensure consistent ordering.
Clients *clientsConfig `yaml:"clients"`
// Log is a block with log configuration settings.
Log logSettings `yaml:"log"`
OSConfig *osConfig `yaml:"os"`
sync.RWMutex `yaml:"-"`
// SchemaVersion is the version of the configuration schema. See
// [configmigrate.LastSchemaVersion].
SchemaVersion uint `yaml:"schema_version"`
}
// httpConfig is a block with HTTP configuration params.
//
// Field ordering is important, YAML fields better not to be reordered, if it's
// not absolutely necessary.
type httpConfig struct {
// Pprof defines the profiling HTTP handler.
Pprof *httpPprofConfig `yaml:"pprof"`
// Address is the address to serve the web UI on.
Address netip.AddrPort
// SessionTTL for a web session.
// An active session is automatically refreshed once a day.
SessionTTL timeutil.Duration `yaml:"session_ttl"`
}
// httpPprofConfig is the block with pprof HTTP configuration.
type httpPprofConfig struct {
// Port for the profiling handler.
Port uint16 `yaml:"port"`
// Enabled defines if the profiling handler is enabled.
Enabled bool `yaml:"enabled"`
}
// dnsConfig is a block with DNS configuration params.
//
// Field ordering is important, YAML fields better not to be reordered, if it's
// not absolutely necessary.
type dnsConfig struct {
BindHosts []netip.Addr `yaml:"bind_hosts"`
Port uint16 `yaml:"port"`
// AnonymizeClientIP defines if clients' IP addresses should be anonymized
// in query log and statistics.
AnonymizeClientIP bool `yaml:"anonymize_client_ip"`
// Config is the embed configuration with DNS params.
//
// TODO(a.garipov): Remove embed.
dnsforward.Config `yaml:",inline"`
// UpstreamTimeout is the timeout for querying upstream servers.
UpstreamTimeout timeutil.Duration `yaml:"upstream_timeout"`
// PrivateNets is the set of IP networks for which the private reverse DNS
// resolver should be used.
PrivateNets []netutil.Prefix `yaml:"private_networks"`
// UsePrivateRDNS enables resolving requests containing a private IP address
// using private reverse DNS resolvers. See PrivateRDNSResolvers.
//
// TODO(e.burkov): Rename in YAML.
UsePrivateRDNS bool `yaml:"use_private_ptr_resolvers"`
// PrivateRDNSResolvers is the slice of addresses to be used as upstreams
// for private requests. It's only used for PTR, SOA, and NS queries,
// containing an ARPA subdomain, came from the the client with private
// address. The address considered private according to PrivateNets.
//
// If empty, the OS-provided resolvers are used for private requests.
PrivateRDNSResolvers []string `yaml:"local_ptr_upstreams"`
// UseDNS64 defines if DNS64 should be used for incoming requests. Requests
// of type PTR for addresses within the configured prefixes will be resolved
// via [PrivateRDNSResolvers], so those should be valid and UsePrivateRDNS
// be set to true.
UseDNS64 bool `yaml:"use_dns64"`
// DNS64Prefixes is the list of NAT64 prefixes to be used for DNS64.
DNS64Prefixes []netip.Prefix `yaml:"dns64_prefixes"`
// ServeHTTP3 defines if HTTP/3 is allowed for incoming requests.
//
// TODO(a.garipov): Add to the UI when HTTP/3 support is no longer
// experimental.
ServeHTTP3 bool `yaml:"serve_http3"`
// UseHTTP3Upstreams defines if HTTP/3 is allowed for DNS-over-HTTPS
// upstreams.
//
// TODO(a.garipov): Add to the UI when HTTP/3 support is no longer
// experimental.
UseHTTP3Upstreams bool `yaml:"use_http3_upstreams"`
// ServePlainDNS defines if plain DNS is allowed for incoming requests.
ServePlainDNS bool `yaml:"serve_plain_dns"`
// HostsFileEnabled defines whether to use information from the system hosts
// file to resolve queries.
HostsFileEnabled bool `yaml:"hostsfile_enabled"`
}
type tlsConfigSettings struct {
Enabled bool `yaml:"enabled" json:"enabled"` // Enabled is the encryption (DoT/DoH/HTTPS) status
ServerName string `yaml:"server_name" json:"server_name,omitempty"` // ServerName is the hostname of your HTTPS/TLS server
ForceHTTPS bool `yaml:"force_https" json:"force_https"` // ForceHTTPS: if true, forces HTTP->HTTPS redirect
PortHTTPS uint16 `yaml:"port_https" json:"port_https,omitempty"` // HTTPS port. If 0, HTTPS will be disabled
PortDNSOverTLS uint16 `yaml:"port_dns_over_tls" json:"port_dns_over_tls,omitempty"` // DNS-over-TLS port. If 0, DoT will be disabled
PortDNSOverQUIC uint16 `yaml:"port_dns_over_quic" json:"port_dns_over_quic,omitempty"` // DNS-over-QUIC port. If 0, DoQ will be disabled
// PortDNSCrypt is the port for DNSCrypt requests. If it's zero,
// DNSCrypt is disabled.
PortDNSCrypt uint16 `yaml:"port_dnscrypt" json:"port_dnscrypt"`
// DNSCryptConfigFile is the path to the DNSCrypt config file. Must be
// set if PortDNSCrypt is not zero.
//
// See path_to_url and
// path_to_url
DNSCryptConfigFile string `yaml:"dnscrypt_config_file" json:"dnscrypt_config_file"`
// Allow DoH queries via unencrypted HTTP (e.g. for reverse proxying)
AllowUnencryptedDoH bool `yaml:"allow_unencrypted_doh" json:"allow_unencrypted_doh"`
dnsforward.TLSConfig `yaml:",inline" json:",inline"`
}
type queryLogConfig struct {
// DirPath is the custom directory for logs. If it's empty the default
// directory will be used. See [homeContext.getDataDir].
DirPath string `yaml:"dir_path"`
// Ignored is the list of host names, which should not be written to log.
// "." is considered to be the root domain.
Ignored []string `yaml:"ignored"`
// Interval is the interval for query log's files rotation.
Interval timeutil.Duration `yaml:"interval"`
// MemSize is the number of entries kept in memory before they are flushed
// to disk.
MemSize uint `yaml:"size_memory"`
// Enabled defines if the query log is enabled.
Enabled bool `yaml:"enabled"`
// FileEnabled defines, if the query log is written to the file.
FileEnabled bool `yaml:"file_enabled"`
}
type statsConfig struct {
// DirPath is the custom directory for statistics. If it's empty the
// default directory is used. See [homeContext.getDataDir].
DirPath string `yaml:"dir_path"`
// Ignored is the list of host names, which should not be counted.
Ignored []string `yaml:"ignored"`
// Interval is the retention interval for statistics.
Interval timeutil.Duration `yaml:"interval"`
// Enabled defines if the statistics are enabled.
Enabled bool `yaml:"enabled"`
}
// Default block host constants.
const (
defaultSafeBrowsingBlockHost = "standard-block.dns.adguard.com"
defaultParentalBlockHost = "family-block.dns.adguard.com"
)
// config is the global configuration structure.
//
// TODO(a.garipov, e.burkov): This global is awful and must be removed.
var config = &configuration{
AuthAttempts: 5,
AuthBlockMin: 15,
HTTPConfig: httpConfig{
Address: netip.AddrPortFrom(netip.IPv4Unspecified(), 3000),
SessionTTL: timeutil.Duration{Duration: 30 * timeutil.Day},
Pprof: &httpPprofConfig{
Enabled: false,
Port: 6060,
},
},
DNS: dnsConfig{
BindHosts: []netip.Addr{netip.IPv4Unspecified()},
Port: defaultPortDNS,
Config: dnsforward.Config{
Ratelimit: 20,
RatelimitSubnetLenIPv4: 24,
RatelimitSubnetLenIPv6: 56,
RefuseAny: true,
UpstreamMode: dnsforward.UpstreamModeLoadBalance,
HandleDDR: true,
FastestTimeout: timeutil.Duration{
Duration: fastip.DefaultPingWaitTimeout,
},
TrustedProxies: []netutil.Prefix{{
Prefix: netip.MustParsePrefix("127.0.0.0/8"),
}, {
Prefix: netip.MustParsePrefix("::1/128"),
}},
CacheSize: 4 * 1024 * 1024,
EDNSClientSubnet: &dnsforward.EDNSClientSubnet{
CustomIP: netip.Addr{},
Enabled: false,
UseCustom: false,
},
// set default maximum concurrent queries to 300
// we introduced a default limit due to this:
// path_to_url#issuecomment-674041912
// was later increased to 300 due to path_to_url
MaxGoroutines: 300,
},
UpstreamTimeout: timeutil.Duration{Duration: dnsforward.DefaultTimeout},
UsePrivateRDNS: true,
ServePlainDNS: true,
HostsFileEnabled: true,
},
TLS: tlsConfigSettings{
PortHTTPS: defaultPortHTTPS,
PortDNSOverTLS: defaultPortTLS, // needs to be passed through to dnsproxy
PortDNSOverQUIC: defaultPortQUIC,
},
QueryLog: queryLogConfig{
Enabled: true,
FileEnabled: true,
Interval: timeutil.Duration{Duration: 90 * timeutil.Day},
MemSize: 1000,
Ignored: []string{},
},
Stats: statsConfig{
Enabled: true,
Interval: timeutil.Duration{Duration: 1 * timeutil.Day},
Ignored: []string{},
},
// NOTE: Keep these parameters in sync with the one put into
// client/src/helpers/filters/filters.ts by scripts/vetted-filters.
//
// TODO(a.garipov): Think of a way to make scripts/vetted-filters update
// these as well if necessary.
Filters: []filtering.FilterYAML{{
Filter: filtering.Filter{ID: 1},
Enabled: true,
URL: "path_to_url",
Name: "AdGuard DNS filter",
}, {
Filter: filtering.Filter{ID: 2},
Enabled: false,
URL: "path_to_url",
Name: "AdAway Default Blocklist",
}},
Filtering: &filtering.Config{
ProtectionEnabled: true,
BlockingMode: filtering.BlockingModeDefault,
BlockedResponseTTL: 10, // in seconds
FilteringEnabled: true,
FiltersUpdateIntervalHours: 24,
ParentalEnabled: false,
SafeBrowsingEnabled: false,
SafeBrowsingCacheSize: 1 * 1024 * 1024,
SafeSearchCacheSize: 1 * 1024 * 1024,
ParentalCacheSize: 1 * 1024 * 1024,
CacheTime: 30,
SafeSearchConf: filtering.SafeSearchConfig{
Enabled: false,
Bing: true,
DuckDuckGo: true,
Ecosia: true,
Google: true,
Pixabay: true,
Yandex: true,
YouTube: true,
},
BlockedServices: &filtering.BlockedServices{
Schedule: schedule.EmptyWeekly(),
IDs: []string{},
},
ParentalBlockHost: defaultParentalBlockHost,
SafeBrowsingBlockHost: defaultSafeBrowsingBlockHost,
},
DHCP: &dhcpd.ServerConfig{
LocalDomainName: "lan",
Conf4: dhcpd.V4ServerConf{
LeaseDuration: dhcpd.DefaultDHCPLeaseTTL,
ICMPTimeout: dhcpd.DefaultDHCPTimeoutICMP,
},
Conf6: dhcpd.V6ServerConf{
LeaseDuration: dhcpd.DefaultDHCPLeaseTTL,
},
},
Clients: &clientsConfig{
Sources: &clientSourcesConfig{
WHOIS: true,
ARP: true,
RDNS: true,
DHCP: true,
HostsFile: true,
},
},
Log: logSettings{
Enabled: true,
File: "",
MaxBackups: 0,
MaxSize: 100,
MaxAge: 3,
Compress: false,
LocalTime: false,
Verbose: false,
},
OSConfig: &osConfig{},
SchemaVersion: configmigrate.LastSchemaVersion,
Theme: ThemeAuto,
}
// configFilePath returns the absolute path to the symlink-evaluated path to the
// current config file.
func configFilePath() (confPath string) {
confPath, err := filepath.EvalSymlinks(Context.confFilePath)
if err != nil {
confPath = Context.confFilePath
logFunc := log.Error
if errors.Is(err, os.ErrNotExist) {
logFunc = log.Debug
}
logFunc("evaluating config path: %s; using %q", err, confPath)
}
if !filepath.IsAbs(confPath) {
confPath = filepath.Join(Context.workDir, confPath)
}
return confPath
}
// validateBindHosts returns error if any of binding hosts from configuration is
// not a valid IP address.
func validateBindHosts(conf *configuration) (err error) {
if !conf.HTTPConfig.Address.IsValid() {
return errors.Error("http.address is not a valid ip address")
}
for i, addr := range conf.DNS.BindHosts {
if !addr.IsValid() {
return fmt.Errorf("dns.bind_hosts at index %d is not a valid ip address", i)
}
}
return nil
}
// parseConfig loads configuration from the YAML file, upgrading it if
// necessary.
func parseConfig() (err error) {
// Do the upgrade if necessary.
config.fileData, err = readConfigFile()
if err != nil {
return err
}
migrator := configmigrate.New(&configmigrate.Config{
WorkingDir: Context.workDir,
})
var upgraded bool
config.fileData, upgraded, err = migrator.Migrate(
config.fileData,
configmigrate.LastSchemaVersion,
)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return err
} else if upgraded {
confPath := configFilePath()
log.Debug("writing config file %q after config upgrade", confPath)
err = maybe.WriteFile(confPath, config.fileData, 0o644)
if err != nil {
return fmt.Errorf("writing new config: %w", err)
}
}
err = yaml.Unmarshal(config.fileData, &config)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
err = validateConfig()
if err != nil {
return err
}
if config.DNS.UpstreamTimeout.Duration == 0 {
config.DNS.UpstreamTimeout = timeutil.Duration{Duration: dnsforward.DefaultTimeout}
}
// Do not wrap the error because it's informative enough as is.
return setContextTLSCipherIDs()
}
// validateConfig returns error if the configuration is invalid.
func validateConfig() (err error) {
err = validateBindHosts(config)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
tcpPorts := aghalg.UniqChecker[tcpPort]{}
addPorts(tcpPorts, tcpPort(config.HTTPConfig.Address.Port()))
udpPorts := aghalg.UniqChecker[udpPort]{}
addPorts(udpPorts, udpPort(config.DNS.Port))
if config.TLS.Enabled {
addPorts(
tcpPorts,
tcpPort(config.TLS.PortHTTPS),
tcpPort(config.TLS.PortDNSOverTLS),
tcpPort(config.TLS.PortDNSCrypt),
)
// TODO(e.burkov): Consider adding a udpPort with the same value when
// we add support for HTTP/3 for web admin interface.
addPorts(udpPorts, udpPort(config.TLS.PortDNSOverQUIC))
}
if err = tcpPorts.Validate(); err != nil {
return fmt.Errorf("validating tcp ports: %w", err)
} else if err = udpPorts.Validate(); err != nil {
return fmt.Errorf("validating udp ports: %w", err)
}
if !filtering.ValidateUpdateIvl(config.Filtering.FiltersUpdateIntervalHours) {
config.Filtering.FiltersUpdateIntervalHours = 24
}
return nil
}
// udpPort is the port number for UDP protocol.
type udpPort uint16
// tcpPort is the port number for TCP protocol.
type tcpPort uint16
// addPorts is a helper for ports validation that skips zero ports.
func addPorts[T tcpPort | udpPort](uc aghalg.UniqChecker[T], ports ...T) {
for _, p := range ports {
if p != 0 {
uc.Add(p)
}
}
}
// readConfigFile reads configuration file contents.
func readConfigFile() (fileData []byte, err error) {
if len(config.fileData) > 0 {
return config.fileData, nil
}
confPath := configFilePath()
log.Debug("reading config file %q", confPath)
// Do not wrap the error because it's informative enough as is.
return os.ReadFile(confPath)
}
// Saves configuration to the YAML file and also saves the user filter contents to a file
func (c *configuration) write() (err error) {
c.Lock()
defer c.Unlock()
if Context.auth != nil {
config.Users = Context.auth.usersList()
}
if Context.tls != nil {
tlsConf := tlsConfigSettings{}
Context.tls.WriteDiskConfig(&tlsConf)
config.TLS = tlsConf
}
if Context.stats != nil {
statsConf := stats.Config{}
Context.stats.WriteDiskConfig(&statsConf)
config.Stats.Interval = timeutil.Duration{Duration: statsConf.Limit}
config.Stats.Enabled = statsConf.Enabled
config.Stats.Ignored = statsConf.Ignored.Values()
}
if Context.queryLog != nil {
dc := querylog.Config{}
Context.queryLog.WriteDiskConfig(&dc)
config.DNS.AnonymizeClientIP = dc.AnonymizeClientIP
config.QueryLog.Enabled = dc.Enabled
config.QueryLog.FileEnabled = dc.FileEnabled
config.QueryLog.Interval = timeutil.Duration{Duration: dc.RotationIvl}
config.QueryLog.MemSize = dc.MemSize
config.QueryLog.Ignored = dc.Ignored.Values()
}
if Context.filters != nil {
Context.filters.WriteDiskConfig(config.Filtering)
config.Filters = config.Filtering.Filters
config.WhitelistFilters = config.Filtering.WhitelistFilters
config.UserRules = config.Filtering.UserRules
}
if s := Context.dnsServer; s != nil {
c := dnsforward.Config{}
s.WriteDiskConfig(&c)
dns := &config.DNS
dns.Config = c
dns.PrivateRDNSResolvers = s.LocalPTRResolvers()
addrProcConf := s.AddrProcConfig()
config.Clients.Sources.RDNS = addrProcConf.UseRDNS
config.Clients.Sources.WHOIS = addrProcConf.UseWHOIS
dns.UsePrivateRDNS = addrProcConf.UsePrivateRDNS
}
if Context.dhcpServer != nil {
Context.dhcpServer.WriteDiskConfig(config.DHCP)
}
config.Clients.Persistent = Context.clients.forConfig()
confPath := configFilePath()
log.Debug("writing config file %q", confPath)
buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
err = enc.Encode(config)
if err != nil {
return fmt.Errorf("generating config file: %w", err)
}
err = maybe.WriteFile(confPath, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err)
}
return nil
}
// setContextTLSCipherIDs sets the TLS cipher suite IDs to use.
func setContextTLSCipherIDs() (err error) {
if len(config.TLS.OverrideTLSCiphers) == 0 {
log.Info("tls: using default ciphers")
Context.tlsCipherIDs = aghtls.SaferCipherSuites()
return nil
}
log.Info("tls: overriding ciphers: %s", config.TLS.OverrideTLSCiphers)
Context.tlsCipherIDs, err = aghtls.ParseCiphers(config.TLS.OverrideTLSCiphers)
if err != nil {
return fmt.Errorf("parsing override ciphers: %w", err)
}
return nil
}
``` | /content/code_sandbox/internal/home/config.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 6,129 |
```go
package home
import (
"net"
"net/netip"
"runtime"
"testing"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/client"
"github.com/AdguardTeam/AdGuardHome/internal/dhcpd"
"github.com/AdguardTeam/AdGuardHome/internal/dhcpsvc"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/AdGuardHome/internal/whois"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type testDHCP struct {
OnLeases func() (leases []*dhcpsvc.Lease)
OnHostBy func(ip netip.Addr) (host string)
OnMACBy func(ip netip.Addr) (mac net.HardwareAddr)
}
// Lease implements the [DHCP] interface for testDHCP.
func (t *testDHCP) Leases() (leases []*dhcpsvc.Lease) { return t.OnLeases() }
// HostByIP implements the [DHCP] interface for testDHCP.
func (t *testDHCP) HostByIP(ip netip.Addr) (host string) { return t.OnHostBy(ip) }
// MACByIP implements the [DHCP] interface for testDHCP.
func (t *testDHCP) MACByIP(ip netip.Addr) (mac net.HardwareAddr) { return t.OnMACBy(ip) }
// newClientsContainer is a helper that creates a new clients container for
// tests.
func newClientsContainer(t *testing.T) (c *clientsContainer) {
t.Helper()
c = &clientsContainer{
testing: true,
}
dhcp := &testDHCP{
OnLeases: func() (leases []*dhcpsvc.Lease) { return nil },
OnHostBy: func(ip netip.Addr) (host string) { return "" },
OnMACBy: func(ip netip.Addr) (mac net.HardwareAddr) { return nil },
}
require.NoError(t, c.Init(nil, dhcp, nil, nil, &filtering.Config{}))
return c
}
func TestClients(t *testing.T) {
clients := newClientsContainer(t)
t.Run("add_success", func(t *testing.T) {
var (
cliNone = "1.2.3.4"
cli1 = "1.1.1.1"
cli2 = "2.2.2.2"
cli1IP = netip.MustParseAddr(cli1)
cli2IP = netip.MustParseAddr(cli2)
cliIPv6 = netip.MustParseAddr("1:2:3::4")
)
c := &client.Persistent{
Name: "client1",
UID: client.MustNewUID(),
IPs: []netip.Addr{cli1IP, cliIPv6},
}
err := clients.storage.Add(c)
require.NoError(t, err)
c = &client.Persistent{
Name: "client2",
UID: client.MustNewUID(),
IPs: []netip.Addr{cli2IP},
}
err = clients.storage.Add(c)
require.NoError(t, err)
c, ok := clients.find(cli1)
require.True(t, ok)
assert.Equal(t, "client1", c.Name)
c, ok = clients.find("1:2:3::4")
require.True(t, ok)
assert.Equal(t, "client1", c.Name)
c, ok = clients.find(cli2)
require.True(t, ok)
assert.Equal(t, "client2", c.Name)
_, ok = clients.find(cliNone)
assert.False(t, ok)
assert.Equal(t, clients.clientSource(cli1IP), client.SourcePersistent)
assert.Equal(t, clients.clientSource(cli2IP), client.SourcePersistent)
})
t.Run("add_fail_name", func(t *testing.T) {
err := clients.storage.Add(&client.Persistent{
Name: "client1",
UID: client.MustNewUID(),
IPs: []netip.Addr{netip.MustParseAddr("1.2.3.5")},
})
require.Error(t, err)
})
t.Run("add_fail_ip", func(t *testing.T) {
err := clients.storage.Add(&client.Persistent{
Name: "client3",
UID: client.MustNewUID(),
})
require.Error(t, err)
})
t.Run("update_fail_ip", func(t *testing.T) {
err := clients.storage.Update("client1", &client.Persistent{
Name: "client1",
UID: client.MustNewUID(),
})
assert.Error(t, err)
})
t.Run("update_success", func(t *testing.T) {
var (
cliOld = "1.1.1.1"
cliNew = "1.1.1.2"
cliNewIP = netip.MustParseAddr(cliNew)
)
prev, ok := clients.storage.FindByName("client1")
require.True(t, ok)
require.NotNil(t, prev)
err := clients.storage.Update("client1", &client.Persistent{
Name: "client1",
UID: prev.UID,
IPs: []netip.Addr{cliNewIP},
})
require.NoError(t, err)
_, ok = clients.find(cliOld)
assert.False(t, ok)
assert.Equal(t, clients.clientSource(cliNewIP), client.SourcePersistent)
prev, ok = clients.storage.FindByName("client1")
require.True(t, ok)
require.NotNil(t, prev)
err = clients.storage.Update("client1", &client.Persistent{
Name: "client1-renamed",
UID: prev.UID,
IPs: []netip.Addr{cliNewIP},
UseOwnSettings: true,
})
require.NoError(t, err)
c, ok := clients.find(cliNew)
require.True(t, ok)
assert.Equal(t, "client1-renamed", c.Name)
assert.True(t, c.UseOwnSettings)
nilCli, ok := clients.storage.FindByName("client1")
require.False(t, ok)
assert.Nil(t, nilCli)
require.Len(t, c.IDs(), 1)
assert.Equal(t, cliNewIP, c.IPs[0])
})
t.Run("del_success", func(t *testing.T) {
ok := clients.storage.RemoveByName("client1-renamed")
require.True(t, ok)
_, ok = clients.find("1.1.1.2")
assert.False(t, ok)
})
t.Run("del_fail", func(t *testing.T) {
ok := clients.storage.RemoveByName("client3")
assert.False(t, ok)
})
t.Run("addhost_success", func(t *testing.T) {
ip := netip.MustParseAddr("1.1.1.1")
ok := clients.addHost(ip, "host", client.SourceARP)
assert.True(t, ok)
ok = clients.addHost(ip, "host2", client.SourceARP)
assert.True(t, ok)
ok = clients.addHost(ip, "host3", client.SourceHostsFile)
assert.True(t, ok)
assert.Equal(t, clients.clientSource(ip), client.SourceHostsFile)
})
t.Run("dhcp_replaces_arp", func(t *testing.T) {
ip := netip.MustParseAddr("1.2.3.4")
ok := clients.addHost(ip, "from_arp", client.SourceARP)
assert.True(t, ok)
assert.Equal(t, clients.clientSource(ip), client.SourceARP)
ok = clients.addHost(ip, "from_dhcp", client.SourceDHCP)
assert.True(t, ok)
assert.Equal(t, clients.clientSource(ip), client.SourceDHCP)
})
t.Run("addhost_priority", func(t *testing.T) {
ip := netip.MustParseAddr("1.1.1.1")
ok := clients.addHost(ip, "host1", client.SourceRDNS)
assert.True(t, ok)
assert.Equal(t, client.SourceHostsFile, clients.clientSource(ip))
})
}
func TestClientsWHOIS(t *testing.T) {
clients := newClientsContainer(t)
whois := &whois.Info{
Country: "AU",
Orgname: "Example Org",
}
t.Run("new_client", func(t *testing.T) {
ip := netip.MustParseAddr("1.1.1.255")
clients.setWHOISInfo(ip, whois)
rc := clients.storage.ClientRuntime(ip)
require.NotNil(t, rc)
assert.Equal(t, whois, rc.WHOIS())
})
t.Run("existing_auto-client", func(t *testing.T) {
ip := netip.MustParseAddr("1.1.1.1")
ok := clients.addHost(ip, "host", client.SourceRDNS)
assert.True(t, ok)
clients.setWHOISInfo(ip, whois)
rc := clients.storage.ClientRuntime(ip)
require.NotNil(t, rc)
assert.Equal(t, whois, rc.WHOIS())
})
t.Run("can't_set_manually-added", func(t *testing.T) {
ip := netip.MustParseAddr("1.1.1.2")
err := clients.storage.Add(&client.Persistent{
Name: "client1",
UID: client.MustNewUID(),
IPs: []netip.Addr{netip.MustParseAddr("1.1.1.2")},
})
require.NoError(t, err)
clients.setWHOISInfo(ip, whois)
rc := clients.storage.ClientRuntime(ip)
require.Nil(t, rc)
assert.True(t, clients.storage.RemoveByName("client1"))
})
}
func TestClientsAddExisting(t *testing.T) {
clients := newClientsContainer(t)
t.Run("simple", func(t *testing.T) {
ip := netip.MustParseAddr("1.1.1.1")
// Add a client.
err := clients.storage.Add(&client.Persistent{
Name: "client1",
UID: client.MustNewUID(),
IPs: []netip.Addr{ip, netip.MustParseAddr("1:2:3::4")},
Subnets: []netip.Prefix{netip.MustParsePrefix("2.2.2.0/24")},
MACs: []net.HardwareAddr{{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}},
})
require.NoError(t, err)
// Now add an auto-client with the same IP.
ok := clients.addHost(ip, "test", client.SourceRDNS)
assert.True(t, ok)
})
t.Run("complicated", func(t *testing.T) {
// TODO(a.garipov): Properly decouple the DHCP server from the client
// storage.
if runtime.GOOS == "windows" {
t.Skip("skipping dhcp test on windows")
}
ip := netip.MustParseAddr("1.2.3.4")
// First, init a DHCP server with a single static lease.
config := &dhcpd.ServerConfig{
Enabled: true,
DataDir: t.TempDir(),
Conf4: dhcpd.V4ServerConf{
Enabled: true,
GatewayIP: netip.MustParseAddr("1.2.3.1"),
SubnetMask: netip.MustParseAddr("255.255.255.0"),
RangeStart: netip.MustParseAddr("1.2.3.2"),
RangeEnd: netip.MustParseAddr("1.2.3.10"),
},
}
dhcpServer, err := dhcpd.Create(config)
require.NoError(t, err)
clients.dhcp = dhcpServer
err = dhcpServer.AddStaticLease(&dhcpsvc.Lease{
HWAddr: net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA},
IP: ip,
Hostname: "testhost",
Expiry: time.Now().Add(time.Hour),
})
require.NoError(t, err)
// Add a new client with the same IP as for a client with MAC.
err = clients.storage.Add(&client.Persistent{
Name: "client2",
UID: client.MustNewUID(),
IPs: []netip.Addr{ip},
})
require.NoError(t, err)
// Add a new client with the IP from the first client's IP range.
err = clients.storage.Add(&client.Persistent{
Name: "client3",
UID: client.MustNewUID(),
IPs: []netip.Addr{netip.MustParseAddr("2.2.2.2")},
})
require.NoError(t, err)
})
}
func TestClientsCustomUpstream(t *testing.T) {
clients := newClientsContainer(t)
// Add client with upstreams.
err := clients.storage.Add(&client.Persistent{
Name: "client1",
UID: client.MustNewUID(),
IPs: []netip.Addr{netip.MustParseAddr("1.1.1.1"), netip.MustParseAddr("1:2:3::4")},
Upstreams: []string{
"1.1.1.1",
"[/example.org/]8.8.8.8",
},
})
require.NoError(t, err)
upsConf, err := clients.UpstreamConfigByID("1.2.3.4", net.DefaultResolver)
assert.Nil(t, upsConf)
assert.NoError(t, err)
upsConf, err = clients.UpstreamConfigByID("1.1.1.1", net.DefaultResolver)
require.NotNil(t, upsConf)
assert.NoError(t, err)
}
``` | /content/code_sandbox/internal/home/clients_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 3,062 |
```go
// Package version contains AdGuard Home version information.
package version
import (
"fmt"
"runtime"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/AdguardTeam/golibs/stringutil"
)
// Channel constants.
const (
ChannelBeta = "beta"
ChannelCandidate = "candidate"
ChannelDevelopment = "development"
ChannelEdge = "edge"
ChannelRelease = "release"
)
// These are set by the linker. Unfortunately we cannot set constants during
// linking, and Go doesn't have a concept of immutable variables, so to be
// thorough we have to only export them through getters.
//
// TODO(a.garipov): Find out if we can get GOARM and GOMIPS values the same way
// we can GOARCH and GOOS.
var (
channel string = ChannelDevelopment
goarm string
gomips string
version string
committime string
)
// Channel returns the current AdGuard Home release channel.
func Channel() (v string) {
return channel
}
// vFmtFull defines the format of full version output.
const vFmtFull = "AdGuard Home, version %s"
// Full returns the full current version of AdGuard Home.
func Full() (v string) {
return fmt.Sprintf(vFmtFull, version)
}
// GOARM returns the GOARM value used to build the current AdGuard Home release.
func GOARM() (v string) {
return goarm
}
// GOMIPS returns the GOMIPS value used to build the current AdGuard Home
// release.
func GOMIPS() (v string) {
return gomips
}
// Version returns the AdGuard Home build version.
func Version() (v string) {
return version
}
// fmtModule returns formatted information about module. The result looks like:
//
// github.com/Username/module@v1.2.3 (sum: someHASHSUM=)
func fmtModule(m *debug.Module) (formatted string) {
if m == nil {
return ""
}
if repl := m.Replace; repl != nil {
return fmtModule(repl)
}
b := &strings.Builder{}
stringutil.WriteToBuilder(b, m.Path)
if ver := m.Version; ver != "" {
sep := "@"
if ver == "(devel)" {
sep = " "
}
stringutil.WriteToBuilder(b, sep, ver)
}
if sum := m.Sum; sum != "" {
stringutil.WriteToBuilder(b, "(sum: ", sum, ")")
}
return b.String()
}
// Constants defining the headers of build information message.
const (
vFmtAGHHdr = "AdGuard Home"
vFmtVerHdr = "Version: "
vFmtSchemaVerHdr = "Schema version: "
vFmtChanHdr = "Channel: "
vFmtGoHdr = "Go version: "
vFmtTimeHdr = "Commit time: "
vFmtRaceHdr = "Race: "
vFmtGOOSHdr = "GOOS: " + runtime.GOOS
vFmtGOARCHHdr = "GOARCH: " + runtime.GOARCH
vFmtGOARMHdr = "GOARM: "
vFmtGOMIPSHdr = "GOMIPS: "
vFmtDepsHdr = "Dependencies:"
)
// Verbose returns formatted build information. Output example:
//
// AdGuard Home
// Version: v0.105.3
// Schema version: 27
// Channel: development
// Go version: go1.15.3
// Build time: 2021-03-30T16:26:08Z+0300
// GOOS: darwin
// GOARCH: amd64
// Race: false
// Main module:
// ...
// Dependencies:
// ...
//
// TODO(e.burkov): Make it write into passed io.Writer.
func Verbose(schemaVersion uint) (v string) {
b := &strings.Builder{}
const nl = "\n"
stringutil.WriteToBuilder(b, vFmtAGHHdr, nl)
stringutil.WriteToBuilder(b, vFmtVerHdr, version, nl)
schemaVerStr := strconv.FormatUint(uint64(schemaVersion), 10)
stringutil.WriteToBuilder(b, vFmtSchemaVerHdr, schemaVerStr, nl)
stringutil.WriteToBuilder(b, vFmtChanHdr, channel, nl)
stringutil.WriteToBuilder(b, vFmtGoHdr, runtime.Version(), nl)
writeCommitTime(b)
stringutil.WriteToBuilder(b, vFmtGOOSHdr, nl)
stringutil.WriteToBuilder(b, vFmtGOARCHHdr, nl)
if goarm != "" {
stringutil.WriteToBuilder(b, vFmtGOARMHdr, "v", goarm, nl)
} else if gomips != "" {
stringutil.WriteToBuilder(b, vFmtGOMIPSHdr, gomips, nl)
}
stringutil.WriteToBuilder(b, vFmtRaceHdr, strconv.FormatBool(isRace), nl)
info, ok := debug.ReadBuildInfo()
if !ok {
return b.String()
}
if len(info.Deps) == 0 {
return b.String()
}
stringutil.WriteToBuilder(b, vFmtDepsHdr, nl)
for _, dep := range info.Deps {
if depStr := fmtModule(dep); depStr != "" {
stringutil.WriteToBuilder(b, "\t", depStr, nl)
}
}
return b.String()
}
func writeCommitTime(b *strings.Builder) {
if committime == "" {
return
}
commitTimeUnix, err := strconv.ParseInt(committime, 10, 64)
if err != nil {
stringutil.WriteToBuilder(b, vFmtTimeHdr, fmt.Sprintf("parse error: %s", err), "\n")
} else {
stringutil.WriteToBuilder(b, vFmtTimeHdr, time.Unix(commitTimeUnix, 0).String(), "\n")
}
}
``` | /content/code_sandbox/internal/version/version.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,294 |
```go
//go:build race
package version
const isRace = true
``` | /content/code_sandbox/internal/version/race.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 16 |
```go
//go:build !race
package version
const isRace = false
``` | /content/code_sandbox/internal/version/norace.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 17 |
```go
package configmigrate
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
// migrateTo5 performs the following changes:
//
// # BEFORE:
// 'schema_version': 4
// 'auth_name':
// 'auth_pass':
// #
//
// # AFTER:
// 'schema_version': 5
// 'users':
// - 'name':
// 'password': <hashed>
// #
func migrateTo5(diskConf yobj) (err error) {
diskConf["schema_version"] = 5
user := yobj{}
if err = moveVal[string](diskConf, user, "auth_name", "name"); err != nil {
return err
}
pass, ok, err := fieldVal[string](diskConf, "auth_pass")
if !ok {
return err
}
delete(diskConf, "auth_pass")
hash, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("generating password hash: %w", err)
}
user["password"] = string(hash)
diskConf["users"] = yarr{user}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v5.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 260 |
```go
package configmigrate
import (
"os"
"path/filepath"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
)
// migrateTo2 performs the following changes:
//
// # BEFORE:
// 'schema_version': 1
// 'coredns':
// #
//
// # AFTER:
// 'schema_version': 2
// 'dns':
// #
//
// It also deletes the Corefile file, since it isn't used anymore.
func (m *Migrator) migrateTo2(diskConf yobj) (err error) {
diskConf["schema_version"] = 2
coreFilePath := filepath.Join(m.workingDir, "Corefile")
log.Printf("deleting %s as we don't need it anymore", coreFilePath)
err = os.Remove(coreFilePath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Info("warning: %s", err)
// Go on.
}
return moveVal[any](diskConf, diskConf, "coredns", "dns")
}
``` | /content/code_sandbox/internal/configmigrate/v2.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 241 |
```go
package configmigrate
import (
"fmt"
"net/url"
"strconv"
"strings"
"github.com/AdguardTeam/golibs/netutil"
)
// migrateTo10 performs the following changes:
//
// # BEFORE:
// 'schema_version': 9
// 'dns':
// 'upstream_dns':
// - 'quic://some-upstream.com'
// 'local_ptr_upstreams':
// - 'quic://some-upstream.com'
// #
// #
//
// # AFTER:
// 'schema_version': 10
// 'dns':
// 'upstream_dns':
// - 'quic://some-upstream.com:784'
// 'local_ptr_upstreams':
// - 'quic://some-upstream.com:784'
// #
// #
func migrateTo10(diskConf yobj) (err error) {
diskConf["schema_version"] = 10
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
const quicPort = 784
ups, ok, err := fieldVal[yarr](dns, "upstream_dns")
if err != nil {
return err
} else if ok {
if err = addQUICPorts(ups, quicPort); err != nil {
return err
}
dns["upstream_dns"] = ups
}
ups, ok, err = fieldVal[yarr](dns, "local_ptr_upstreams")
if err != nil {
return err
} else if ok {
if err = addQUICPorts(ups, quicPort); err != nil {
return err
}
dns["local_ptr_upstreams"] = ups
}
return nil
}
// addQUICPorts inserts a port into each QUIC upstream's hostname in ups if
// those are missing.
func addQUICPorts(ups yarr, port int) (err error) {
for i, uVal := range ups {
u, ok := uVal.(string)
if !ok {
return fmt.Errorf("unexpected type of upstream field: %T", uVal)
}
ups[i] = addQUICPort(u, port)
}
return nil
}
// addQUICPort inserts a port into QUIC upstream's hostname if it is missing.
func addQUICPort(ups string, port int) (withPort string) {
if ups == "" || ups[0] == '#' {
return ups
}
var doms string
withPort = ups
if strings.HasPrefix(ups, "[/") {
domsAndUps := strings.Split(strings.TrimPrefix(ups, "[/"), "/]")
if len(domsAndUps) != 2 {
return ups
}
doms, withPort = "[/"+domsAndUps[0]+"/]", domsAndUps[1]
}
if !strings.Contains(withPort, "://") {
return ups
}
upsURL, err := url.Parse(withPort)
if err != nil || upsURL.Scheme != "quic" {
return ups
}
var host string
host, err = netutil.SplitHost(upsURL.Host)
if err != nil || host != upsURL.Host {
return ups
}
upsURL.Host = strings.Join([]string{host, strconv.Itoa(port)}, ":")
return doms + upsURL.String()
}
``` | /content/code_sandbox/internal/configmigrate/v10.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 750 |
```go
package configmigrate
import (
"fmt"
)
type (
// yarr is the convenience alias for YAML array.
yarr = []any
// yobj is the convenience alias for YAML key-value object.
yobj = map[string]any
)
// fieldVal returns the value of type T for key from obj. Use [any] if the
// field's type doesn't matter.
func fieldVal[T any](obj yobj, key string) (v T, ok bool, err error) {
val, ok := obj[key]
if !ok {
return v, false, nil
}
if val == nil {
return v, true, nil
}
v, ok = val.(T)
if !ok {
return v, false, fmt.Errorf("unexpected type of %q: %T", key, val)
}
return v, true, nil
}
// moveVal copies the value for srcKey from src into dst for dstKey and deletes
// it from src.
func moveVal[T any](src, dst yobj, srcKey, dstKey string) (err error) {
newVal, ok, err := fieldVal[T](src, srcKey)
if !ok {
return err
}
dst[dstKey] = newVal
delete(src, srcKey)
return nil
}
// moveSameVal moves the value for key from src into dst.
func moveSameVal[T any](src, dst yobj, key string) (err error) {
return moveVal[T](src, dst, key, key)
}
``` | /content/code_sandbox/internal/configmigrate/yaml.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 330 |
```go
package configmigrate
// migrateTo11 performs the following changes:
//
// # BEFORE:
// 'schema_version': 10
// 'rlimit_nofile': 42
// #
//
// # AFTER:
// 'schema_version': 11
// 'os':
// 'group': ''
// 'rlimit_nofile': 42
// 'user': ''
// #
func migrateTo11(diskConf yobj) (err error) {
diskConf["schema_version"] = 11
rlimit, _, err := fieldVal[int](diskConf, "rlimit_nofile")
if err != nil {
return err
}
delete(diskConf, "rlimit_nofile")
diskConf["os"] = yobj{
"group": "",
"rlimit_nofile": rlimit,
"user": "",
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v11.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 199 |
```go
package configmigrate
import (
"bytes"
"fmt"
"github.com/AdguardTeam/golibs/log"
yaml "gopkg.in/yaml.v3"
)
// Config is a the configuration for initializing a [Migrator].
type Config struct {
// WorkingDir is an absolute path to the working directory of AdGuardHome.
WorkingDir string
}
// Migrator performs the YAML configuration file migrations.
type Migrator struct {
// workingDir is an absolute path to the working directory of AdGuardHome.
workingDir string
}
// New creates a new Migrator.
func New(cfg *Config) (m *Migrator) {
return &Migrator{
workingDir: cfg.WorkingDir,
}
}
// Migrate preforms necessary upgrade operations to upgrade file to target
// schema version, if needed. It returns the body of the upgraded config file,
// whether the file was upgraded, and an error, if any. If upgraded is false,
// the body is the same as the input.
func (m *Migrator) Migrate(body []byte, target uint) (newBody []byte, upgraded bool, err error) {
diskConf := yobj{}
err = yaml.Unmarshal(body, &diskConf)
if err != nil {
return body, false, fmt.Errorf("parsing config file for upgrade: %w", err)
}
currentInt, _, err := fieldVal[int](diskConf, "schema_version")
if err != nil {
// Don't wrap the error, since it's informative enough as is.
return body, false, err
}
current := uint(currentInt)
log.Debug("got schema version %v", current)
if err = validateVersion(current, target); err != nil {
// Don't wrap the error, since it's informative enough as is.
return body, false, err
} else if current == target {
return body, false, nil
}
if err = m.upgradeConfigSchema(current, target, diskConf); err != nil {
// Don't wrap the error, since it's informative enough as is.
return body, false, err
}
buf := bytes.NewBuffer(newBody)
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
if err = enc.Encode(diskConf); err != nil {
return body, false, fmt.Errorf("generating new config: %w", err)
}
return buf.Bytes(), true, nil
}
// validateVersion validates the current and desired schema versions.
func validateVersion(current, target uint) (err error) {
switch {
case current > target:
return fmt.Errorf("unknown current schema version %d", current)
case target > LastSchemaVersion:
return fmt.Errorf("unknown target schema version %d", target)
case target < current:
return fmt.Errorf("target schema version %d lower than current %d", target, current)
default:
return nil
}
}
// migrateFunc is a function that upgrades a config and returns an error.
type migrateFunc = func(diskConf yobj) (err error)
// upgradeConfigSchema upgrades the configuration schema in diskConf from
// current to target version. current must be less than target, and both must
// be non-negative and less or equal to [LastSchemaVersion].
func (m *Migrator) upgradeConfigSchema(current, target uint, diskConf yobj) (err error) {
upgrades := [LastSchemaVersion]migrateFunc{
0: m.migrateTo1,
1: m.migrateTo2,
2: migrateTo3,
3: migrateTo4,
4: migrateTo5,
5: migrateTo6,
6: migrateTo7,
7: migrateTo8,
8: migrateTo9,
9: migrateTo10,
10: migrateTo11,
11: migrateTo12,
12: migrateTo13,
13: migrateTo14,
14: migrateTo15,
15: migrateTo16,
16: migrateTo17,
17: migrateTo18,
18: migrateTo19,
19: migrateTo20,
20: migrateTo21,
21: migrateTo22,
22: migrateTo23,
23: migrateTo24,
24: migrateTo25,
25: migrateTo26,
26: migrateTo27,
27: migrateTo28,
}
for i, migrate := range upgrades[current:target] {
cur := current + uint(i)
next := current + uint(i) + 1
log.Printf("Upgrade yaml: %d to %d", cur, next)
if err = migrate(diskConf); err != nil {
return fmt.Errorf("migrating schema %d to %d: %w", cur, next, err)
}
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/migrator.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,081 |
```go
package configmigrate
// migrateTo25 performs the following changes:
//
// # BEFORE:
// 'schema_version': 24
// 'debug_pprof': true
// #
//
// # AFTER:
// 'schema_version': 25
// 'http':
// 'pprof':
// 'enabled': true
// 'port': 6060
// #
func migrateTo25(diskConf yobj) (err error) {
diskConf["schema_version"] = 25
httpObj, ok, err := fieldVal[yobj](diskConf, "http")
if !ok {
return err
}
pprofObj := yobj{
"enabled": false,
"port": 6060,
}
err = moveVal[bool](diskConf, pprofObj, "debug_pprof", "enabled")
if err != nil {
return err
}
httpObj["pprof"] = pprofObj
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v25.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 217 |
```go
package configmigrate
// migrateTo18 performs the following changes:
//
// # BEFORE:
// 'schema_version': 17
// 'dns':
// 'safesearch_enabled': true
// #
// #
//
// # AFTER:
// 'schema_version': 18
// 'dns':
// 'safe_search':
// 'enabled': true
// 'bing': true
// 'duckduckgo': true
// 'google': true
// 'pixabay': true
// 'yandex': true
// 'youtube': true
// #
// #
func migrateTo18(diskConf yobj) (err error) {
diskConf["schema_version"] = 18
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
safeSearch := yobj{
"enabled": true,
"bing": true,
"duckduckgo": true,
"google": true,
"pixabay": true,
"yandex": true,
"youtube": true,
}
dns["safe_search"] = safeSearch
return moveVal[bool](dns, safeSearch, "safesearch_enabled", "enabled")
}
``` | /content/code_sandbox/internal/configmigrate/v18.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 295 |
```go
package configmigrate
// migrateTo17 performs the following changes:
//
// # BEFORE:
// 'schema_version': 16
// 'dns':
// 'edns_client_subnet': false
// #
// #
//
// # AFTER:
// 'schema_version': 17
// 'dns':
// 'edns_client_subnet':
// 'enabled': false
// 'use_custom': false
// 'custom_ip': ""
// #
// #
func migrateTo17(diskConf yobj) (err error) {
diskConf["schema_version"] = 17
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
const field = "edns_client_subnet"
enabled, _, _ := fieldVal[bool](dns, field)
dns[field] = yobj{
"enabled": enabled,
"use_custom": false,
"custom_ip": "",
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v17.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 226 |
```go
package configmigrate
import "fmt"
// migrateTo6 performs the following changes:
//
// # BEFORE:
// 'schema_version': 5
// 'clients':
// - #
// 'ip': '127.0.0.1'
// 'mac': 'AA:AA:AA:AA:AA:AA'
// #
// #
//
// # AFTER:
// 'schema_version': 6
// 'clients':
// - #
// 'ip': '127.0.0.1'
// 'mac': 'AA:AA:AA:AA:AA:AA'
// 'ids':
// - '127.0.0.1'
// - 'AA:AA:AA:AA:AA:AA'
// #
// #
func migrateTo6(diskConf yobj) (err error) {
diskConf["schema_version"] = 6
clients, ok, err := fieldVal[yarr](diskConf, "clients")
if !ok {
return err
}
for i, client := range clients {
var c yobj
c, ok = client.(yobj)
if !ok {
return fmt.Errorf("unexpected type of client at index %d: %T", i, client)
}
ids := yarr{}
for _, id := range []string{"ip", "mac"} {
val, _, valErr := fieldVal[string](c, id)
if valErr != nil {
return fmt.Errorf("client at index %d: %w", i, valErr)
} else if val != "" {
ids = append(ids, val)
}
}
c["ids"] = ids
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v6.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 390 |
```go
package configmigrate
import (
"fmt"
)
// migrateTo22 performs the following changes:
//
// # BEFORE:
// 'schema_version': 21
// 'persistent':
// - 'name': 'client_name'
// 'blocked_services':
// - 'svc_name'
// - #
// #
// #
// #
//
// # AFTER:
// 'schema_version': 22
// 'persistent':
// - 'name': 'client_name'
// 'blocked_services':
// 'ids':
// - 'svc_name'
// - #
// 'schedule':
// 'time_zone': 'Local'
// #
// #
// #
func migrateTo22(diskConf yobj) (err error) {
diskConf["schema_version"] = 22
const field = "blocked_services"
clients, ok, err := fieldVal[yobj](diskConf, "clients")
if !ok {
return err
}
persistent, ok, err := fieldVal[yarr](clients, "persistent")
if !ok {
return err
}
for i, p := range persistent {
var c yobj
c, ok = p.(yobj)
if !ok {
return fmt.Errorf("persistent client at index %d: unexpected type %T", i, p)
}
var services yarr
services, ok, err = fieldVal[yarr](c, field)
if err != nil {
return fmt.Errorf("persistent client at index %d: %w", i, err)
} else if !ok {
continue
}
c[field] = yobj{
"ids": services,
"schedule": yobj{
"time_zone": "Local",
},
}
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v22.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 406 |
```go
package configmigrate_test
import (
"io/fs"
"os"
"path"
"testing"
"github.com/AdguardTeam/AdGuardHome/internal/configmigrate"
"github.com/AdguardTeam/golibs/testutil"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
yaml "gopkg.in/yaml.v3"
)
func TestMain(m *testing.M) {
testutil.DiscardLogOutput(m)
}
// testdata is a virtual filesystem containing test data.
var testdata = os.DirFS("testdata")
// getField returns the value located at the given indexes in the given object.
// It fails the test if the value is not found or of the expected type. The
// indexes can be either strings or integers, and are interpreted as map keys or
// array indexes, respectively.
func getField[T any](t require.TestingT, obj any, indexes ...any) (val T) {
for _, index := range indexes {
switch index := index.(type) {
case string:
require.IsType(t, map[string]any(nil), obj)
typedObj := obj.(map[string]any)
require.Contains(t, typedObj, index)
obj = typedObj[index]
case int:
require.IsType(t, []any(nil), obj)
typedObj := obj.([]any)
require.Less(t, index, len(typedObj))
obj = typedObj[index]
default:
t.Errorf("unexpected index type: %T", index)
t.FailNow()
}
}
require.IsType(t, val, obj)
return obj.(T)
}
func TestMigrateConfig_Migrate(t *testing.T) {
const (
inputFileName = "input.yml"
outputFileName = "output.yml"
)
testCases := []struct {
yamlEqFunc func(t require.TestingT, expected, actual string, msgAndArgs ...any)
name string
targetVersion uint
}{{
yamlEqFunc: require.YAMLEq,
name: "v1",
targetVersion: 1,
}, {
yamlEqFunc: require.YAMLEq,
name: "v2",
targetVersion: 2,
}, {
yamlEqFunc: require.YAMLEq,
name: "v3",
targetVersion: 3,
}, {
yamlEqFunc: require.YAMLEq,
name: "v4",
targetVersion: 4,
}, {
// Compare passwords separately because bcrypt hashes those with a
// different salt every time.
yamlEqFunc: func(t require.TestingT, expected, actual string, msgAndArgs ...any) {
if h, ok := t.(interface{ Helper() }); ok {
h.Helper()
}
var want, got map[string]any
err := yaml.Unmarshal([]byte(expected), &want)
require.NoError(t, err)
err = yaml.Unmarshal([]byte(actual), &got)
require.NoError(t, err)
gotPass := getField[string](t, got, "users", 0, "password")
wantPass := getField[string](t, want, "users", 0, "password")
require.NoError(t, bcrypt.CompareHashAndPassword([]byte(gotPass), []byte(wantPass)))
delete(getField[map[string]any](t, got, "users", 0), "password")
delete(getField[map[string]any](t, want, "users", 0), "password")
require.Equal(t, want, got, msgAndArgs...)
},
name: "v5",
targetVersion: 5,
}, {
yamlEqFunc: require.YAMLEq,
name: "v6",
targetVersion: 6,
}, {
yamlEqFunc: require.YAMLEq,
name: "v7",
targetVersion: 7,
}, {
yamlEqFunc: require.YAMLEq,
name: "v8",
targetVersion: 8,
}, {
yamlEqFunc: require.YAMLEq,
name: "v9",
targetVersion: 9,
}, {
yamlEqFunc: require.YAMLEq,
name: "v10",
targetVersion: 10,
}, {
yamlEqFunc: require.YAMLEq,
name: "v11",
targetVersion: 11,
}, {
yamlEqFunc: require.YAMLEq,
name: "v12",
targetVersion: 12,
}, {
yamlEqFunc: require.YAMLEq,
name: "v13",
targetVersion: 13,
}, {
yamlEqFunc: require.YAMLEq,
name: "v14",
targetVersion: 14,
}, {
yamlEqFunc: require.YAMLEq,
name: "v15",
targetVersion: 15,
}, {
yamlEqFunc: require.YAMLEq,
name: "v16",
targetVersion: 16,
}, {
yamlEqFunc: require.YAMLEq,
name: "v17",
targetVersion: 17,
}, {
yamlEqFunc: require.YAMLEq,
name: "v18",
targetVersion: 18,
}, {
yamlEqFunc: require.YAMLEq,
name: "v19",
targetVersion: 19,
}, {
yamlEqFunc: require.YAMLEq,
name: "v20",
targetVersion: 20,
}, {
yamlEqFunc: require.YAMLEq,
name: "v21",
targetVersion: 21,
}, {
yamlEqFunc: require.YAMLEq,
name: "v22",
targetVersion: 22,
}, {
yamlEqFunc: require.YAMLEq,
name: "v23",
targetVersion: 23,
}, {
yamlEqFunc: require.YAMLEq,
name: "v24",
targetVersion: 24,
}, {
yamlEqFunc: require.YAMLEq,
name: "v25",
targetVersion: 25,
}, {
yamlEqFunc: require.YAMLEq,
name: "v26",
targetVersion: 26,
}, {
yamlEqFunc: require.YAMLEq,
name: "v27",
targetVersion: 27,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
body, err := fs.ReadFile(testdata, path.Join(t.Name(), inputFileName))
require.NoError(t, err)
wantBody, err := fs.ReadFile(testdata, path.Join(t.Name(), outputFileName))
require.NoError(t, err)
migrator := configmigrate.New(&configmigrate.Config{
WorkingDir: t.Name(),
})
newBody, upgraded, err := migrator.Migrate(body, tc.targetVersion)
require.NoError(t, err)
require.True(t, upgraded)
tc.yamlEqFunc(t, string(wantBody), string(newBody))
})
}
}
``` | /content/code_sandbox/internal/configmigrate/migrator_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,643 |
```go
package configmigrate
// migrateTo3 performs the following changes:
//
// # BEFORE:
// 'schema_version': 2
// 'dns':
// 'bootstrap_dns': '1.1.1.1'
// #
//
// # AFTER:
// 'schema_version': 3
// 'dns':
// 'bootstrap_dns':
// - '1.1.1.1'
// #
func migrateTo3(diskConf yobj) (err error) {
diskConf["schema_version"] = 3
dnsConfig, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
bootstrapDNS, ok, err := fieldVal[any](dnsConfig, "bootstrap_dns")
if ok {
dnsConfig["bootstrap_dns"] = yarr{bootstrapDNS}
}
return err
}
``` | /content/code_sandbox/internal/configmigrate/v3.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 195 |
```go
package configmigrate
// migrateTo27 performs the following changes:
//
// # BEFORE:
// 'querylog':
// 'ignored':
// - '.'
// - #
// #
// 'statistics':
// 'ignored':
// - '.'
// - #
// #
// #
//
// # AFTER:
// 'querylog':
// 'ignored':
// - '|.^'
// - #
// #
// 'statistics':
// 'ignored':
// - '|.^'
// - #
// #
// #
func migrateTo27(diskConf yobj) (err error) {
diskConf["schema_version"] = 27
keys := []string{"querylog", "statistics"}
for _, k := range keys {
err = replaceDot(diskConf, k)
if err != nil {
return err
}
}
return nil
}
// replaceDot replaces rules blocking root domain "." with AdBlock style syntax
// "|.^".
func replaceDot(diskConf yobj, key string) (err error) {
var obj yobj
var ok bool
obj, ok, err = fieldVal[yobj](diskConf, key)
if err != nil {
return err
} else if !ok {
return nil
}
var ignored yarr
ignored, ok, err = fieldVal[yarr](obj, "ignored")
if err != nil {
return err
} else if !ok {
return nil
}
for i, hostVal := range ignored {
var host string
host, ok = hostVal.(string)
if !ok {
continue
}
if host == "." {
ignored[i] = "|.^"
}
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v27.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 397 |
```go
package configmigrate
// migrateTo13 performs the following changes:
//
// # BEFORE:
// 'schema_version': 12
// 'dns':
// 'local_domain_name': 'lan'
// #
// #
//
// # AFTER:
// 'schema_version': 13
// 'dhcp':
// 'local_domain_name': 'lan'
// #
// #
func migrateTo13(diskConf yobj) (err error) {
diskConf["schema_version"] = 13
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
dhcp, ok, err := fieldVal[yobj](diskConf, "dhcp")
if !ok {
return err
}
return moveSameVal[string](dns, dhcp, "local_domain_name")
}
``` | /content/code_sandbox/internal/configmigrate/v13.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 189 |
```go
package configmigrate
import "github.com/AdguardTeam/golibs/errors"
// migrateTo24 performs the following changes:
//
// # BEFORE:
// 'schema_version': 23
// 'log_file': ""
// 'log_max_backups': 0
// 'log_max_size': 100
// 'log_max_age': 3
// 'log_compress': false
// 'log_localtime': false
// 'verbose': false
// #
//
// # AFTER:
// 'schema_version': 24
// 'log':
// 'file': ""
// 'max_backups': 0
// 'max_size': 100
// 'max_age': 3
// 'compress': false
// 'local_time': false
// 'verbose': false
// #
func migrateTo24(diskConf yobj) (err error) {
diskConf["schema_version"] = 24
logObj := yobj{}
err = errors.Join(
moveVal[string](diskConf, logObj, "log_file", "file"),
moveVal[int](diskConf, logObj, "log_max_backups", "max_backups"),
moveVal[int](diskConf, logObj, "log_max_size", "max_size"),
moveVal[int](diskConf, logObj, "log_max_age", "max_age"),
moveVal[bool](diskConf, logObj, "log_compress", "compress"),
moveVal[bool](diskConf, logObj, "log_localtime", "local_time"),
moveVal[bool](diskConf, logObj, "verbose", "verbose"),
)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return err
}
if len(logObj) != 0 {
diskConf["log"] = logObj
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v24.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 421 |
```go
package configmigrate
// migrateTo14 performs the following changes:
//
// # BEFORE:
// 'schema_version': 13
// 'dns':
// 'resolve_clients': true
// #
// 'clients':
// - 'name': 'client-name'
// #
// #
//
// # AFTER:
// 'schema_version': 14
// 'dns':
// #
// 'clients':
// 'persistent':
// - 'name': 'client-name'
// #
// 'runtime_sources':
// 'whois': true
// 'arp': true
// 'rdns': true
// 'dhcp': true
// 'hosts': true
// #
func migrateTo14(diskConf yobj) (err error) {
diskConf["schema_version"] = 14
persistent, ok, err := fieldVal[yarr](diskConf, "clients")
if !ok {
if err != nil {
return err
}
persistent = yarr{}
}
runtimeClients := yobj{
"whois": true,
"arp": true,
"rdns": false,
"dhcp": true,
"hosts": true,
}
diskConf["clients"] = yobj{
"persistent": persistent,
"runtime_sources": runtimeClients,
}
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if err != nil {
return err
} else if !ok {
return nil
}
return moveVal[bool](dns, runtimeClients, "resolve_clients", "rdns")
}
``` | /content/code_sandbox/internal/configmigrate/v14.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 373 |
```go
package configmigrate
import "github.com/AdguardTeam/golibs/errors"
// migrateTo15 performs the following changes:
//
// # BEFORE:
// 'schema_version': 14
// 'dns':
// #
// 'querylog_enabled': true
// 'querylog_file_enabled': true
// 'querylog_interval': '2160h'
// 'querylog_size_memory': 1000
// 'querylog':
// #
// #
//
// # AFTER:
// 'schema_version': 15
// 'dns':
// #
// 'querylog':
// 'enabled': true
// 'file_enabled': true
// 'interval': '2160h'
// 'size_memory': 1000
// 'ignored': []
// #
// #
func migrateTo15(diskConf yobj) (err error) {
diskConf["schema_version"] = 15
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
qlog := map[string]any{
"ignored": yarr{},
"enabled": true,
"file_enabled": true,
"interval": "2160h",
"size_memory": 1000,
}
diskConf["querylog"] = qlog
return errors.Join(
moveVal[bool](dns, qlog, "querylog_enabled", "enabled"),
moveVal[bool](dns, qlog, "querylog_file_enabled", "file_enabled"),
moveVal[any](dns, qlog, "querylog_interval", "interval"),
moveVal[int](dns, qlog, "querylog_size_memory", "size_memory"),
)
}
``` | /content/code_sandbox/internal/configmigrate/v15.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 396 |
```go
package configmigrate
import (
"os"
"path/filepath"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
)
// migrateTo1 performs the following changes:
//
// # BEFORE:
// #
//
// # AFTER:
// 'schema_version': 1
// #
//
// It also deletes the unused dnsfilter.txt file, since the following versions
// store filters in data/filters/.
func (m *Migrator) migrateTo1(diskConf yobj) (err error) {
diskConf["schema_version"] = 1
dnsFilterPath := filepath.Join(m.workingDir, "dnsfilter.txt")
log.Printf("deleting %s as we don't need it anymore", dnsFilterPath)
err = os.Remove(dnsFilterPath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Info("warning: %s", err)
// Go on.
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v1.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 219 |
```go
package configmigrate
import (
"github.com/AdguardTeam/AdGuardHome/internal/dnsforward"
)
// migrateTo28 performs the following changes:
//
// # BEFORE:
// 'dns':
// 'all_servers': true
// 'fastest_addr': true
// #
// #
//
// # AFTER:
// 'dns':
// 'upstream_mode': 'parallel'
// #
// #
func migrateTo28(diskConf yobj) (err error) {
diskConf["schema_version"] = 28
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
allServers, _, _ := fieldVal[bool](dns, "all_servers")
fastestAddr, _, _ := fieldVal[bool](dns, "fastest_addr")
var upstreamModeType dnsforward.UpstreamMode
if allServers {
upstreamModeType = dnsforward.UpstreamModeParallel
} else if fastestAddr {
upstreamModeType = dnsforward.UpstreamModeFastestAddr
} else {
upstreamModeType = dnsforward.UpstreamModeLoadBalance
}
dns["upstream_mode"] = upstreamModeType
delete(dns, "all_servers")
delete(dns, "fastest_addr")
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v28.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 292 |
```go
package configmigrate
// migrateTo21 performs the following changes:
//
// # BEFORE:
// 'schema_version': 20
// 'dns':
// 'blocked_services':
// - 'svc_name'
// - #
// #
// #
//
// # AFTER:
// 'schema_version': 21
// 'dns':
// 'blocked_services':
// 'ids':
// - 'svc_name'
// - #
// 'schedule':
// 'time_zone': 'Local'
// #
// #
func migrateTo21(diskConf yobj) (err error) {
diskConf["schema_version"] = 21
const field = "blocked_services"
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
svcs := yobj{
"schedule": yobj{
"time_zone": "Local",
},
}
err = moveVal[yarr](dns, svcs, field, "ids")
if err != nil {
return err
}
dns[field] = svcs
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v21.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 255 |
```go
package configmigrate
// migrateTo16 performs the following changes:
//
// # BEFORE:
// 'schema_version': 15
// 'dns':
// #
// 'statistics_interval': 1
// 'statistics':
// #
// #
//
// # AFTER:
// 'schema_version': 16
// 'dns':
// #
// 'statistics':
// 'enabled': true
// 'interval': 1
// 'ignored': []
// #
// #
//
// If statistics were disabled:
//
// # BEFORE:
// 'schema_version': 15
// 'dns':
// #
// 'statistics_interval': 0
// 'statistics':
// #
// #
//
// # AFTER:
// 'schema_version': 16
// 'dns':
// #
// 'statistics':
// 'enabled': false
// 'interval': 1
// 'ignored': []
// #
// #
func migrateTo16(diskConf yobj) (err error) {
diskConf["schema_version"] = 16
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
stats := yobj{
"enabled": true,
"interval": 1,
"ignored": yarr{},
}
diskConf["statistics"] = stats
const field = "statistics_interval"
statsIvl, ok, err := fieldVal[int](dns, field)
if !ok {
return err
}
if statsIvl == 0 {
// Set the interval to the default value of one day to make sure
// that it passes the validations.
stats["enabled"] = false
} else {
stats["interval"] = statsIvl
}
delete(dns, field)
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v16.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 430 |
```go
package configmigrate
import (
"time"
"github.com/AdguardTeam/golibs/timeutil"
)
// migrateTo20 performs the following changes:
//
// # BEFORE:
// 'schema_version': 19
// 'statistics':
// 'interval': 1
// #
// #
//
// # AFTER:
// 'schema_version': 20
// 'statistics':
// 'interval': 24h
// #
// #
func migrateTo20(diskConf yobj) (err error) {
diskConf["schema_version"] = 20
stats, ok, err := fieldVal[yobj](diskConf, "statistics")
if !ok {
return err
}
const field = "interval"
ivl, ok, err := fieldVal[int](stats, field)
if err != nil {
return err
} else if !ok || ivl == 0 {
ivl = 1
}
stats[field] = timeutil.Duration{Duration: time.Duration(ivl) * timeutil.Day}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v20.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 240 |
```go
package configmigrate
// migrateTo9 performs the following changes:
//
// # BEFORE:
// 'schema_version': 8
// 'dns':
// 'autohost_tld': 'lan'
// #
// #
//
// # AFTER:
// 'schema_version': 9
// 'dns':
// 'local_domain_name': 'lan'
// #
// #
func migrateTo9(diskConf yobj) (err error) {
diskConf["schema_version"] = 9
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
return moveVal[string](dns, dns, "autohost_tld", "local_domain_name")
}
``` | /content/code_sandbox/internal/configmigrate/v9.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 167 |
```go
package configmigrate
import (
"fmt"
"net/netip"
"time"
"github.com/AdguardTeam/golibs/timeutil"
)
// migrateTo23 performs the following changes:
//
// # BEFORE:
// 'schema_version': 22
// 'bind_host': '1.2.3.4'
// 'bind_port': 8080
// 'web_session_ttl': 720
// #
//
// # AFTER:
// 'schema_version': 23
// 'http':
// 'address': '1.2.3.4:8080'
// 'session_ttl': '720h'
// #
func migrateTo23(diskConf yobj) (err error) {
diskConf["schema_version"] = 23
bindHost, ok, err := fieldVal[string](diskConf, "bind_host")
if !ok {
return err
}
bindHostAddr, err := netip.ParseAddr(bindHost)
if err != nil {
return fmt.Errorf("invalid bind_host value: %s", bindHost)
}
bindPort, _, err := fieldVal[int](diskConf, "bind_port")
if err != nil {
return err
}
sessionTTL, _, err := fieldVal[int](diskConf, "web_session_ttl")
if err != nil {
return err
}
diskConf["http"] = yobj{
"address": netip.AddrPortFrom(bindHostAddr, uint16(bindPort)).String(),
"session_ttl": timeutil.Duration{Duration: time.Duration(sessionTTL) * time.Hour}.String(),
}
delete(diskConf, "bind_host")
delete(diskConf, "bind_port")
delete(diskConf, "web_session_ttl")
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v23.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 387 |
```go
package configmigrate
// migrateTo4 performs the following changes:
//
// # BEFORE:
// 'schema_version': 3
// 'clients':
// - #
// #
//
// # AFTER:
// 'schema_version': 4
// 'clients':
// - 'use_global_blocked_services': true
// #
// #
func migrateTo4(diskConf yobj) (err error) {
diskConf["schema_version"] = 4
clients, ok, _ := fieldVal[yarr](diskConf, "clients")
if ok {
for i := range clients {
if c, isYobj := clients[i].(yobj); isYobj {
c["use_global_blocked_services"] = true
}
}
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v4.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 179 |
```go
package configmigrate
import "github.com/AdguardTeam/golibs/errors"
// migrateTo26 performs the following changes:
//
// # BEFORE:
// 'schema_version': 25
// 'dns':
// 'filtering_enabled': true
// 'filters_update_interval': 24
// 'parental_enabled': false
// 'safebrowsing_enabled': false
// 'safebrowsing_cache_size': 1048576
// 'safesearch_cache_size': 1048576
// 'parental_cache_size': 1048576
// 'safe_search':
// 'enabled': false
// 'bing': true
// 'duckduckgo': true
// 'google': true
// 'pixabay': true
// 'yandex': true
// 'youtube': true
// 'rewrites': []
// 'blocked_services':
// 'schedule':
// 'time_zone': 'Local'
// 'ids': []
// 'protection_enabled': true,
// 'blocking_mode': 'custom_ip',
// 'blocking_ipv4': '1.2.3.4',
// 'blocking_ipv6': '1:2:3::4',
// 'blocked_response_ttl': 10,
// 'protection_disabled_until': 'null',
// 'parental_block_host': 'p.dns.adguard.com',
// 'safebrowsing_block_host': 's.dns.adguard.com',
// #
//
// # AFTER:
// 'schema_version': 26
// 'filtering':
// 'filtering_enabled': true
// 'filters_update_interval': 24
// 'parental_enabled': false
// 'safebrowsing_enabled': false
// 'safebrowsing_cache_size': 1048576
// 'safesearch_cache_size': 1048576
// 'parental_cache_size': 1048576
// 'safe_search':
// 'enabled': false
// 'bing': true
// 'duckduckgo': true
// 'google': true
// 'pixabay': true
// 'yandex': true
// 'youtube': true
// 'rewrites': []
// 'blocked_services':
// 'schedule':
// 'time_zone': 'Local'
// 'ids': []
// 'protection_enabled': true,
// 'blocking_mode': 'custom_ip',
// 'blocking_ipv4': '1.2.3.4',
// 'blocking_ipv6': '1:2:3::4',
// 'blocked_response_ttl': 10,
// 'protection_disabled_until': 'null',
// 'parental_block_host': 'p.dns.adguard.com',
// 'safebrowsing_block_host': 's.dns.adguard.com',
// 'dns'
// #
// #
func migrateTo26(diskConf yobj) (err error) {
diskConf["schema_version"] = 26
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
filteringObj := yobj{}
err = errors.Join(
moveSameVal[bool](dns, filteringObj, "filtering_enabled"),
moveSameVal[int](dns, filteringObj, "filters_update_interval"),
moveSameVal[bool](dns, filteringObj, "parental_enabled"),
moveSameVal[bool](dns, filteringObj, "safebrowsing_enabled"),
moveSameVal[int](dns, filteringObj, "safebrowsing_cache_size"),
moveSameVal[int](dns, filteringObj, "safesearch_cache_size"),
moveSameVal[int](dns, filteringObj, "parental_cache_size"),
moveSameVal[yobj](dns, filteringObj, "safe_search"),
moveSameVal[yarr](dns, filteringObj, "rewrites"),
moveSameVal[yobj](dns, filteringObj, "blocked_services"),
moveSameVal[bool](dns, filteringObj, "protection_enabled"),
moveSameVal[string](dns, filteringObj, "blocking_mode"),
moveSameVal[string](dns, filteringObj, "blocking_ipv4"),
moveSameVal[string](dns, filteringObj, "blocking_ipv6"),
moveSameVal[int](dns, filteringObj, "blocked_response_ttl"),
moveSameVal[any](dns, filteringObj, "protection_disabled_until"),
moveSameVal[string](dns, filteringObj, "parental_block_host"),
moveSameVal[string](dns, filteringObj, "safebrowsing_block_host"),
)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return err
}
if len(filteringObj) != 0 {
diskConf["filtering"] = filteringObj
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v26.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 1,081 |
```go
// Package configmigrate provides a way to upgrade the YAML configuration file.
package configmigrate
// LastSchemaVersion is the most recent schema version.
const LastSchemaVersion uint = 28
``` | /content/code_sandbox/internal/configmigrate/configmigrate.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 41 |
```go
package configmigrate
import "github.com/AdguardTeam/golibs/log"
// migrateTo19 performs the following changes:
//
// # BEFORE:
// 'schema_version': 18
// 'clients':
// 'persistent':
// - 'name': 'client-name'
// 'safesearch_enabled': true
// #
// #
// #
//
// # AFTER:
// 'schema_version': 19
// 'clients':
// 'persistent':
// - 'name': 'client-name'
// 'safe_search':
// 'enabled': true
// 'bing': true
// 'duckduckgo': true
// 'google': true
// 'pixabay': true
// 'yandex': true
// 'youtube': true
// #
// #
// #
func migrateTo19(diskConf yobj) (err error) {
diskConf["schema_version"] = 19
clients, ok, err := fieldVal[yobj](diskConf, "clients")
if !ok {
return err
}
persistent, ok, _ := fieldVal[yarr](clients, "persistent")
if !ok {
return nil
}
for _, p := range persistent {
var c yobj
c, ok = p.(yobj)
if !ok {
continue
}
safeSearch := yobj{
"enabled": true,
"bing": true,
"duckduckgo": true,
"google": true,
"pixabay": true,
"yandex": true,
"youtube": true,
}
err = moveVal[bool](c, safeSearch, "safesearch_enabled", "enabled")
if err != nil {
log.Debug("migrating to version 19: %s", err)
}
c["safe_search"] = safeSearch
}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v19.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 442 |
```go
package configmigrate
import "github.com/AdguardTeam/golibs/errors"
// migrateTo7 performs the following changes:
//
// # BEFORE:
// 'schema_version': 6
// 'dhcp':
// 'enabled': false
// 'interface_name': vboxnet0
// 'gateway_ip': '192.168.56.1'
// 'subnet_mask': '255.255.255.0'
// 'range_start': '192.168.56.10'
// 'range_end': '192.168.56.240'
// 'lease_duration': 86400
// 'icmp_timeout_msec': 1000
// #
//
// # AFTER:
// 'schema_version': 7
// 'dhcp':
// 'enabled': false
// 'interface_name': vboxnet0
// 'dhcpv4':
// 'gateway_ip': '192.168.56.1'
// 'subnet_mask': '255.255.255.0'
// 'range_start': '192.168.56.10'
// 'range_end': '192.168.56.240'
// 'lease_duration': 86400
// 'icmp_timeout_msec': 1000
// #
func migrateTo7(diskConf yobj) (err error) {
diskConf["schema_version"] = 7
dhcp, ok, _ := fieldVal[yobj](diskConf, "dhcp")
if !ok {
return nil
}
dhcpv4 := yobj{}
err = errors.Join(
moveSameVal[string](dhcp, dhcpv4, "gateway_ip"),
moveSameVal[string](dhcp, dhcpv4, "subnet_mask"),
moveSameVal[string](dhcp, dhcpv4, "range_start"),
moveSameVal[string](dhcp, dhcpv4, "range_end"),
moveSameVal[int](dhcp, dhcpv4, "lease_duration"),
moveSameVal[int](dhcp, dhcpv4, "icmp_timeout_msec"),
)
if err != nil {
return err
}
dhcp["dhcpv4"] = dhcpv4
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v7.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 475 |
```go
package configmigrate
// migrateTo8 performs the following changes:
//
// # BEFORE:
// 'schema_version': 7
// 'dns':
// 'bind_host': '127.0.0.1'
// #
// #
//
// # AFTER:
// 'schema_version': 8
// 'dns':
// 'bind_hosts':
// - '127.0.0.1'
// #
// #
func migrateTo8(diskConf yobj) (err error) {
diskConf["schema_version"] = 8
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
bindHost, ok, err := fieldVal[string](dns, "bind_host")
if !ok {
return err
}
delete(dns, "bind_host")
dns["bind_hosts"] = yarr{bindHost}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v8.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 211 |
```go
package configmigrate
import (
"time"
"github.com/AdguardTeam/golibs/timeutil"
)
// migrateTo12 performs the following changes:
//
// # BEFORE:
// 'schema_version': 11
// 'querylog_interval': 90
// #
//
// # AFTER:
// 'schema_version': 12
// 'querylog_interval': '2160h'
// #
func migrateTo12(diskConf yobj) (err error) {
diskConf["schema_version"] = 12
dns, ok, err := fieldVal[yobj](diskConf, "dns")
if !ok {
return err
}
const field = "querylog_interval"
qlogIvl, ok, err := fieldVal[int](dns, field)
if !ok {
if err != nil {
return err
}
// Set the initial value from home.initConfig function.
qlogIvl = 90
}
dns[field] = timeutil.Duration{Duration: time.Duration(qlogIvl) * timeutil.Day}
return nil
}
``` | /content/code_sandbox/internal/configmigrate/v12.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 241 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 20
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v21/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 662 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 21
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v21/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 674 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
auth_name: testuser
auth_pass: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ip: 127.0.0.1
mac: ""
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
schema_version: 4
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v5/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 303 |
```go
package configmigrate
import (
"testing"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/dnsforward"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/golibs/testutil"
"github.com/AdguardTeam/golibs/timeutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TODO(e.burkov): Cover all migrations, use a testdata/ dir.
func TestUpgradeSchema1to2(t *testing.T) {
diskConf := testDiskConf(1)
m := New(&Config{
WorkingDir: "",
})
err := m.migrateTo2(diskConf)
require.NoError(t, err)
require.Equal(t, diskConf["schema_version"], 2)
_, ok := diskConf["coredns"]
require.False(t, ok)
newDNSConf, ok := diskConf["dns"]
require.True(t, ok)
oldDNSConf := testDNSConf(1)
assert.Equal(t, oldDNSConf, newDNSConf)
oldExcludedEntries := []string{"coredns", "schema_version"}
newExcludedEntries := []string{"dns", "schema_version"}
oldDiskConf := testDiskConf(1)
assertEqualExcept(t, oldDiskConf, diskConf, oldExcludedEntries, newExcludedEntries)
}
func TestUpgradeSchema2to3(t *testing.T) {
diskConf := testDiskConf(2)
err := migrateTo3(diskConf)
require.NoError(t, err)
require.Equal(t, diskConf["schema_version"], 3)
dnsMap, ok := diskConf["dns"]
require.True(t, ok)
newDNSConf, ok := dnsMap.(yobj)
require.True(t, ok)
bootstrapDNS := newDNSConf["bootstrap_dns"]
switch v := bootstrapDNS.(type) {
case yarr:
require.Len(t, v, 1)
require.Equal(t, "8.8.8.8:53", v[0])
default:
t.Fatalf("wrong type for bootstrap dns: %T", v)
}
excludedEntries := []string{"bootstrap_dns"}
oldDNSConf := testDNSConf(2)
assertEqualExcept(t, oldDNSConf, newDNSConf, excludedEntries, excludedEntries)
excludedEntries = []string{"dns", "schema_version"}
oldDiskConf := testDiskConf(2)
assertEqualExcept(t, oldDiskConf, diskConf, excludedEntries, excludedEntries)
}
func TestUpgradeSchema5to6(t *testing.T) {
const newSchemaVer = 6
testCases := []struct {
in yobj
want yobj
wantErr string
name string
}{{
in: yobj{
"clients": yarr{},
},
want: yobj{
"clients": yarr{},
"schema_version": newSchemaVer,
},
wantErr: "",
name: "no_clients",
}, {
in: yobj{
"clients": yarr{yobj{"ip": "127.0.0.1"}},
},
want: yobj{
"clients": yarr{yobj{
"ids": yarr{"127.0.0.1"},
"ip": "127.0.0.1",
}},
"schema_version": newSchemaVer,
},
wantErr: "",
name: "client_ip",
}, {
in: yobj{
"clients": yarr{yobj{"mac": "mac"}},
},
want: yobj{
"clients": yarr{yobj{
"ids": yarr{"mac"},
"mac": "mac",
}},
"schema_version": newSchemaVer,
},
wantErr: "",
name: "client_mac",
}, {
in: yobj{
"clients": yarr{yobj{"ip": "127.0.0.1", "mac": "mac"}},
},
want: yobj{
"clients": yarr{yobj{
"ids": yarr{"127.0.0.1", "mac"},
"ip": "127.0.0.1",
"mac": "mac",
}},
"schema_version": newSchemaVer,
},
wantErr: "",
name: "client_ip_mac",
}, {
in: yobj{
"clients": yarr{yobj{"ip": 1, "mac": "mac"}},
},
want: yobj{
"clients": yarr{yobj{"ip": 1, "mac": "mac"}},
"schema_version": newSchemaVer,
},
wantErr: `client at index 0: unexpected type of "ip": int`,
name: "inv_client_ip",
}, {
in: yobj{
"clients": yarr{yobj{"ip": "127.0.0.1", "mac": 1}},
},
want: yobj{
"clients": yarr{yobj{"ip": "127.0.0.1", "mac": 1}},
"schema_version": newSchemaVer,
},
wantErr: `client at index 0: unexpected type of "mac": int`,
name: "inv_client_mac",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo6(tc.in)
testutil.AssertErrorMsg(t, tc.wantErr, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema7to8(t *testing.T) {
const host = "1.2.3.4"
oldConf := yobj{
"dns": yobj{
"bind_host": host,
},
"schema_version": 7,
}
err := migrateTo8(oldConf)
require.NoError(t, err)
require.Equal(t, oldConf["schema_version"], 8)
dnsVal, ok := oldConf["dns"]
require.True(t, ok)
newDNSConf, ok := dnsVal.(yobj)
require.True(t, ok)
newBindHosts, ok := newDNSConf["bind_hosts"].(yarr)
require.True(t, ok)
require.Len(t, newBindHosts, 1)
assert.Equal(t, host, newBindHosts[0])
}
func TestUpgradeSchema8to9(t *testing.T) {
const tld = "foo"
t.Run("with_autohost_tld", func(t *testing.T) {
oldConf := yobj{
"dns": yobj{
"autohost_tld": tld,
},
"schema_version": 8,
}
err := migrateTo9(oldConf)
require.NoError(t, err)
require.Equal(t, oldConf["schema_version"], 9)
dnsVal, ok := oldConf["dns"]
require.True(t, ok)
newDNSConf, ok := dnsVal.(yobj)
require.True(t, ok)
localDomainName, ok := newDNSConf["local_domain_name"].(string)
require.True(t, ok)
assert.Equal(t, tld, localDomainName)
})
t.Run("without_autohost_tld", func(t *testing.T) {
oldConf := yobj{
"dns": yobj{},
"schema_version": 8,
}
err := migrateTo9(oldConf)
require.NoError(t, err)
require.Equal(t, oldConf["schema_version"], 9)
dnsVal, ok := oldConf["dns"]
require.True(t, ok)
newDNSConf, ok := dnsVal.(yobj)
require.True(t, ok)
// Should be nil in order to be set to the default value by the
// following config rewrite.
_, ok = newDNSConf["local_domain_name"]
require.False(t, ok)
})
}
// assertEqualExcept removes entries from configs and compares them.
func assertEqualExcept(t *testing.T, oldConf, newConf yobj, oldKeys, newKeys []string) {
t.Helper()
for _, k := range oldKeys {
delete(oldConf, k)
}
for _, k := range newKeys {
delete(newConf, k)
}
assert.Equal(t, oldConf, newConf)
}
func testDiskConf(schemaVersion int) (diskConf yobj) {
filters := []filtering.FilterYAML{{
URL: "path_to_url",
Name: "Latvian filter",
RulesCount: 100,
}, {
URL: "path_to_url",
Name: "Germany filter",
RulesCount: 200,
}}
diskConf = yobj{
"language": "en",
"filters": filters,
"user_rules": []string{},
"schema_version": schemaVersion,
"bind_host": "0.0.0.0",
"bind_port": 80,
"auth_name": "name",
"auth_pass": "pass",
}
dnsConf := testDNSConf(schemaVersion)
if schemaVersion > 1 {
diskConf["dns"] = dnsConf
} else {
diskConf["coredns"] = dnsConf
}
return diskConf
}
// testDNSConf creates a DNS config for test the way gopkg.in/yaml.v3 would
// unmarshal it. In YAML, keys aren't guaranteed to always only be strings.
func testDNSConf(schemaVersion int) (dnsConf yobj) {
dnsConf = yobj{
"port": 53,
"blocked_response_ttl": 10,
"querylog_enabled": true,
"ratelimit": 20,
"bootstrap_dns": "8.8.8.8:53",
"parental_sensitivity": 13,
"ratelimit_whitelist": []string{},
"upstream_dns": []string{"tls://1.1.1.1", "tls://1.0.0.1", "8.8.8.8"},
"filtering_enabled": true,
"refuse_any": true,
"parental_enabled": true,
"bind_host": "0.0.0.0",
"protection_enabled": true,
"safesearch_enabled": true,
"safebrowsing_enabled": true,
}
if schemaVersion > 2 {
dnsConf["bootstrap_dns"] = []string{"8.8.8.8:53"}
}
return dnsConf
}
func TestAddQUICPort(t *testing.T) {
testCases := []struct {
name string
ups string
want string
}{{
name: "simple_ip",
ups: "8.8.8.8",
want: "8.8.8.8",
}, {
name: "url_ipv4",
ups: "quic://8.8.8.8",
want: "quic://8.8.8.8:784",
}, {
name: "url_ipv4_with_port",
ups: "quic://8.8.8.8:25565",
want: "quic://8.8.8.8:25565",
}, {
name: "url_ipv6",
ups: "quic://[::1]",
want: "quic://[::1]:784",
}, {
name: "url_ipv6_invalid",
ups: "quic://::1",
want: "quic://::1",
}, {
name: "url_ipv6_with_port",
ups: "quic://[::1]:25565",
want: "quic://[::1]:25565",
}, {
name: "url_hostname",
ups: "quic://example.com",
want: "quic://example.com:784",
}, {
name: "url_hostname_with_port",
ups: "quic://example.com:25565",
want: "quic://example.com:25565",
}, {
name: "url_hostname_with_endpoint",
ups: "quic://example.com/some-endpoint",
want: "quic://example.com:784/some-endpoint",
}, {
name: "url_hostname_with_port_endpoint",
ups: "quic://example.com:25565/some-endpoint",
want: "quic://example.com:25565/some-endpoint",
}, {
name: "non-quic_proto",
ups: "tls://example.com",
want: "tls://example.com",
}, {
name: "comment",
ups: "# comment",
want: "# comment",
}, {
name: "blank",
ups: "",
want: "",
}, {
name: "with_domain_ip",
ups: "[/example.domain/]8.8.8.8",
want: "[/example.domain/]8.8.8.8",
}, {
name: "with_domain_url",
ups: "[/example.domain/]quic://example.com",
want: "[/example.domain/]quic://example.com:784",
}, {
name: "invalid_domain",
ups: "[/exmaple.domain]quic://example.com",
want: "[/exmaple.domain]quic://example.com",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
withPort := addQUICPort(tc.ups, 784)
assert.Equal(t, tc.want, withPort)
})
}
}
func TestUpgradeSchema9to10(t *testing.T) {
const ultimateAns = 42
testCases := []struct {
ups any
want any
wantErr string
name string
}{{
ups: yarr{"quic://8.8.8.8"},
want: yarr{"quic://8.8.8.8:784"},
wantErr: "",
name: "success",
}, {
ups: ultimateAns,
want: nil,
wantErr: `unexpected type of "upstream_dns": int`,
name: "bad_yarr_type",
}, {
ups: yarr{ultimateAns},
want: nil,
wantErr: `unexpected type of upstream field: int`,
name: "bad_upstream_type",
}}
for _, tc := range testCases {
conf := yobj{
"dns": yobj{
"upstream_dns": tc.ups,
},
"schema_version": 9,
}
t.Run(tc.name, func(t *testing.T) {
err := migrateTo10(conf)
if tc.wantErr != "" {
testutil.AssertErrorMsg(t, tc.wantErr, err)
return
}
require.NoError(t, err)
require.Equal(t, conf["schema_version"], 10)
dnsVal, ok := conf["dns"]
require.True(t, ok)
newDNSConf, ok := dnsVal.(yobj)
require.True(t, ok)
fixedUps, ok := newDNSConf["upstream_dns"].(yarr)
require.True(t, ok)
assert.Equal(t, tc.want, fixedUps)
})
}
t.Run("no_dns", func(t *testing.T) {
err := migrateTo10(yobj{})
assert.NoError(t, err)
})
t.Run("bad_dns", func(t *testing.T) {
err := migrateTo10(yobj{
"dns": ultimateAns,
})
testutil.AssertErrorMsg(t, `unexpected type of "dns": int`, err)
})
}
func TestUpgradeSchema10to11(t *testing.T) {
check := func(t *testing.T, conf yobj) {
rlimit, _ := conf["rlimit_nofile"].(int)
err := migrateTo11(conf)
require.NoError(t, err)
require.Equal(t, conf["schema_version"], 11)
_, ok := conf["rlimit_nofile"]
assert.False(t, ok)
osVal, ok := conf["os"]
require.True(t, ok)
newOSConf, ok := osVal.(yobj)
require.True(t, ok)
_, ok = newOSConf["group"]
assert.True(t, ok)
_, ok = newOSConf["user"]
assert.True(t, ok)
rlimitVal, ok := newOSConf["rlimit_nofile"].(int)
require.True(t, ok)
assert.Equal(t, rlimit, rlimitVal)
}
const rlimit = 42
t.Run("with_rlimit", func(t *testing.T) {
conf := yobj{
"rlimit_nofile": rlimit,
"schema_version": 10,
}
check(t, conf)
})
t.Run("without_rlimit", func(t *testing.T) {
conf := yobj{
"schema_version": 10,
}
check(t, conf)
})
}
func TestUpgradeSchema11to12(t *testing.T) {
testCases := []struct {
ivl any
want any
wantErr string
name string
}{{
ivl: 1,
want: timeutil.Duration{Duration: timeutil.Day},
wantErr: "",
name: "success",
}, {
ivl: 0.25,
want: 0,
wantErr: `unexpected type of "querylog_interval": float64`,
name: "fail",
}}
for _, tc := range testCases {
conf := yobj{
"dns": yobj{
"querylog_interval": tc.ivl,
},
"schema_version": 11,
}
t.Run(tc.name, func(t *testing.T) {
err := migrateTo12(conf)
if tc.wantErr != "" {
require.Error(t, err)
assert.Equal(t, tc.wantErr, err.Error())
return
}
require.NoError(t, err)
require.Equal(t, conf["schema_version"], 12)
dnsVal, ok := conf["dns"]
require.True(t, ok)
var newDNSConf yobj
newDNSConf, ok = dnsVal.(yobj)
require.True(t, ok)
var newIvl timeutil.Duration
newIvl, ok = newDNSConf["querylog_interval"].(timeutil.Duration)
require.True(t, ok)
assert.Equal(t, tc.want, newIvl)
})
}
t.Run("no_dns", func(t *testing.T) {
err := migrateTo12(yobj{})
assert.NoError(t, err)
})
t.Run("bad_dns", func(t *testing.T) {
err := migrateTo12(yobj{
"dns": 0,
})
testutil.AssertErrorMsg(t, `unexpected type of "dns": int`, err)
})
t.Run("no_field", func(t *testing.T) {
conf := yobj{
"dns": yobj{},
}
err := migrateTo12(conf)
require.NoError(t, err)
dns, ok := conf["dns"]
require.True(t, ok)
var dnsVal yobj
dnsVal, ok = dns.(yobj)
require.True(t, ok)
var ivl any
ivl, ok = dnsVal["querylog_interval"]
require.True(t, ok)
var ivlVal timeutil.Duration
ivlVal, ok = ivl.(timeutil.Duration)
require.True(t, ok)
assert.Equal(t, 90*24*time.Hour, ivlVal.Duration)
})
}
func TestUpgradeSchema12to13(t *testing.T) {
const newSchemaVer = 13
testCases := []struct {
in yobj
want yobj
name string
}{{
in: yobj{},
want: yobj{"schema_version": newSchemaVer},
name: "no_dns",
}, {
in: yobj{"dns": yobj{}},
want: yobj{
"dns": yobj{},
"schema_version": newSchemaVer,
},
name: "no_dhcp",
}, {
in: yobj{
"dns": yobj{
"local_domain_name": "lan",
},
"dhcp": yobj{},
"schema_version": newSchemaVer - 1,
},
want: yobj{
"dns": yobj{},
"dhcp": yobj{
"local_domain_name": "lan",
},
"schema_version": newSchemaVer,
},
name: "good",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo13(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema13to14(t *testing.T) {
const newSchemaVer = 14
testClient := yobj{
"name": "agh-client",
"ids": []string{"id1"},
"use_global_settings": true,
}
testCases := []struct {
in yobj
want yobj
name string
}{{
in: yobj{},
want: yobj{
"schema_version": newSchemaVer,
// The clients field will be added anyway.
"clients": yobj{
"persistent": yarr{},
"runtime_sources": yobj{
"whois": true,
"arp": true,
"rdns": false,
"dhcp": true,
"hosts": true,
},
},
},
name: "no_clients",
}, {
in: yobj{
"clients": yarr{testClient},
},
want: yobj{
"schema_version": newSchemaVer,
"clients": yobj{
"persistent": yarr{testClient},
"runtime_sources": yobj{
"whois": true,
"arp": true,
"rdns": false,
"dhcp": true,
"hosts": true,
},
},
},
name: "no_dns",
}, {
in: yobj{
"clients": yarr{testClient},
"dns": yobj{
"resolve_clients": true,
},
},
want: yobj{
"schema_version": newSchemaVer,
"clients": yobj{
"persistent": yarr{testClient},
"runtime_sources": yobj{
"whois": true,
"arp": true,
"rdns": true,
"dhcp": true,
"hosts": true,
},
},
"dns": yobj{},
},
name: "good",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo14(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema14to15(t *testing.T) {
const newSchemaVer = 15
defaultWantObj := yobj{
"querylog": map[string]any{
"enabled": true,
"file_enabled": true,
"interval": "2160h",
"size_memory": 1000,
"ignored": []any{},
},
"dns": map[string]any{},
"schema_version": newSchemaVer,
}
testCases := []struct {
in yobj
want yobj
name string
}{{
in: yobj{
"dns": map[string]any{
"querylog_enabled": true,
"querylog_file_enabled": true,
"querylog_interval": "2160h",
"querylog_size_memory": 1000,
},
},
want: defaultWantObj,
name: "basic",
}, {
in: yobj{
"dns": map[string]any{},
},
want: defaultWantObj,
name: "default_values",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo15(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema15to16(t *testing.T) {
const newSchemaVer = 16
defaultWantObj := yobj{
"statistics": map[string]any{
"enabled": true,
"interval": 1,
"ignored": []any{},
},
"dns": map[string]any{},
"schema_version": newSchemaVer,
}
testCases := []struct {
in yobj
want yobj
name string
}{{
in: yobj{
"dns": map[string]any{
"statistics_interval": 1,
},
},
want: defaultWantObj,
name: "basic",
}, {
in: yobj{
"dns": map[string]any{},
},
want: defaultWantObj,
name: "default_values",
}, {
in: yobj{
"dns": map[string]any{
"statistics_interval": 0,
},
},
want: yobj{
"statistics": map[string]any{
"enabled": false,
"interval": 1,
"ignored": []any{},
},
"dns": map[string]any{},
"schema_version": newSchemaVer,
},
name: "stats_disabled",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo16(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema16to17(t *testing.T) {
const newSchemaVer = 17
defaultWantObj := yobj{
"dns": map[string]any{
"edns_client_subnet": map[string]any{
"enabled": false,
"use_custom": false,
"custom_ip": "",
},
},
"schema_version": newSchemaVer,
}
testCases := []struct {
in yobj
want yobj
name string
}{{
in: yobj{
"dns": map[string]any{
"edns_client_subnet": false,
},
},
want: defaultWantObj,
name: "basic",
}, {
in: yobj{
"dns": map[string]any{},
},
want: defaultWantObj,
name: "default_values",
}, {
in: yobj{
"dns": map[string]any{
"edns_client_subnet": true,
},
},
want: yobj{
"dns": map[string]any{
"edns_client_subnet": map[string]any{
"enabled": true,
"use_custom": false,
"custom_ip": "",
},
},
"schema_version": newSchemaVer,
},
name: "is_true",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo17(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema17to18(t *testing.T) {
const newSchemaVer = 18
defaultWantObj := yobj{
"dns": yobj{
"safe_search": yobj{
"enabled": true,
"bing": true,
"duckduckgo": true,
"google": true,
"pixabay": true,
"yandex": true,
"youtube": true,
},
},
"schema_version": newSchemaVer,
}
testCases := []struct {
in yobj
want yobj
name string
}{{
in: yobj{"dns": yobj{}},
want: defaultWantObj,
name: "default_values",
}, {
in: yobj{"dns": yobj{"safesearch_enabled": true}},
want: defaultWantObj,
name: "enabled",
}, {
in: yobj{"dns": yobj{"safesearch_enabled": false}},
want: yobj{
"dns": yobj{
"safe_search": map[string]any{
"enabled": false,
"bing": true,
"duckduckgo": true,
"google": true,
"pixabay": true,
"yandex": true,
"youtube": true,
},
},
"schema_version": newSchemaVer,
},
name: "disabled",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo18(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema18to19(t *testing.T) {
const newSchemaVer = 19
defaultWantObj := yobj{
"clients": yobj{
"persistent": yarr{yobj{
"name": "localhost",
"safe_search": yobj{
"enabled": true,
"bing": true,
"duckduckgo": true,
"google": true,
"pixabay": true,
"yandex": true,
"youtube": true,
},
}},
},
"schema_version": newSchemaVer,
}
testCases := []struct {
in yobj
want yobj
name string
}{{
in: yobj{
"clients": yobj{},
},
want: yobj{
"clients": yobj{},
"schema_version": newSchemaVer,
},
name: "no_clients",
}, {
in: yobj{
"clients": yobj{
"persistent": yarr{yobj{"name": "localhost"}},
},
},
want: defaultWantObj,
name: "default_values",
}, {
in: yobj{
"clients": yobj{
"persistent": yarr{yobj{"name": "localhost", "safesearch_enabled": true}},
},
},
want: defaultWantObj,
name: "enabled",
}, {
in: yobj{
"clients": yobj{
"persistent": yarr{yobj{"name": "localhost", "safesearch_enabled": false}},
},
},
want: yobj{
"clients": yobj{"persistent": yarr{yobj{
"name": "localhost",
"safe_search": yobj{
"enabled": false,
"bing": true,
"duckduckgo": true,
"google": true,
"pixabay": true,
"yandex": true,
"youtube": true,
},
}}},
"schema_version": newSchemaVer,
},
name: "disabled",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo19(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema19to20(t *testing.T) {
testCases := []struct {
ivl any
want any
wantErr string
name string
}{{
ivl: 1,
want: timeutil.Duration{Duration: timeutil.Day},
wantErr: "",
name: "success",
}, {
ivl: 0,
want: timeutil.Duration{Duration: timeutil.Day},
wantErr: "",
name: "success",
}, {
ivl: 0.25,
want: 0,
wantErr: `unexpected type of "interval": float64`,
name: "fail",
}}
for _, tc := range testCases {
conf := yobj{
"statistics": yobj{
"interval": tc.ivl,
},
"schema_version": 19,
}
t.Run(tc.name, func(t *testing.T) {
err := migrateTo20(conf)
if tc.wantErr != "" {
require.Error(t, err)
assert.Equal(t, tc.wantErr, err.Error())
return
}
require.NoError(t, err)
require.Equal(t, conf["schema_version"], 20)
statsVal, ok := conf["statistics"]
require.True(t, ok)
var stats yobj
stats, ok = statsVal.(yobj)
require.True(t, ok)
var newIvl timeutil.Duration
newIvl, ok = stats["interval"].(timeutil.Duration)
require.True(t, ok)
assert.Equal(t, tc.want, newIvl)
})
}
t.Run("no_stats", func(t *testing.T) {
err := migrateTo20(yobj{})
assert.NoError(t, err)
})
t.Run("bad_stats", func(t *testing.T) {
err := migrateTo20(yobj{
"statistics": 0,
})
testutil.AssertErrorMsg(t, `unexpected type of "statistics": int`, err)
})
t.Run("no_field", func(t *testing.T) {
conf := yobj{
"statistics": yobj{},
}
err := migrateTo20(conf)
require.NoError(t, err)
statsVal, ok := conf["statistics"]
require.True(t, ok)
var stats yobj
stats, ok = statsVal.(yobj)
require.True(t, ok)
var ivl any
ivl, ok = stats["interval"]
require.True(t, ok)
var ivlVal timeutil.Duration
ivlVal, ok = ivl.(timeutil.Duration)
require.True(t, ok)
assert.Equal(t, 24*time.Hour, ivlVal.Duration)
})
}
func TestUpgradeSchema20to21(t *testing.T) {
const newSchemaVer = 21
testCases := []struct {
in yobj
want yobj
name string
}{{
name: "nothing",
in: yobj{},
want: yobj{
"schema_version": newSchemaVer,
},
}, {
name: "no_clients",
in: yobj{
"dns": yobj{
"blocked_services": yarr{"ok"},
},
},
want: yobj{
"dns": yobj{
"blocked_services": yobj{
"ids": yarr{"ok"},
"schedule": yobj{
"time_zone": "Local",
},
},
},
"schema_version": newSchemaVer,
},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo21(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema21to22(t *testing.T) {
const newSchemaVer = 22
testCases := []struct {
in yobj
want yobj
name string
}{{
in: yobj{
"clients": yobj{},
},
want: yobj{
"clients": yobj{},
"schema_version": newSchemaVer,
},
name: "nothing",
}, {
in: yobj{
"clients": yobj{
"persistent": []any{yobj{"name": "localhost", "blocked_services": yarr{}}},
},
},
want: yobj{
"clients": yobj{
"persistent": []any{yobj{
"name": "localhost",
"blocked_services": yobj{
"ids": yarr{},
"schedule": yobj{
"time_zone": "Local",
},
},
}},
},
"schema_version": newSchemaVer,
},
name: "no_services",
}, {
in: yobj{
"clients": yobj{
"persistent": []any{yobj{"name": "localhost", "blocked_services": yarr{"ok"}}},
},
},
want: yobj{
"clients": yobj{
"persistent": []any{yobj{
"name": "localhost",
"blocked_services": yobj{
"ids": yarr{"ok"},
"schedule": yobj{
"time_zone": "Local",
},
},
}},
},
"schema_version": newSchemaVer,
},
name: "services",
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo22(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema22to23(t *testing.T) {
const newSchemaVer = 23
testCases := []struct {
in yobj
want yobj
name string
}{{
name: "empty",
in: yobj{},
want: yobj{
"schema_version": newSchemaVer,
},
}, {
name: "ok",
in: yobj{
"bind_host": "1.2.3.4",
"bind_port": 8081,
"web_session_ttl": 720,
},
want: yobj{
"http": yobj{
"address": "1.2.3.4:8081",
"session_ttl": "720h",
},
"schema_version": newSchemaVer,
},
}, {
name: "v6_address",
in: yobj{
"bind_host": "2001:db8::1",
"bind_port": 8081,
"web_session_ttl": 720,
},
want: yobj{
"http": yobj{
"address": "[2001:db8::1]:8081",
"session_ttl": "720h",
},
"schema_version": newSchemaVer,
},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo23(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema23to24(t *testing.T) {
const newSchemaVer = 24
testCases := []struct {
in yobj
want yobj
name string
wantErrMsg string
}{{
name: "empty",
in: yobj{},
want: yobj{
"schema_version": newSchemaVer,
},
wantErrMsg: "",
}, {
name: "ok",
in: yobj{
"log_file": "/test/path.log",
"log_max_backups": 1,
"log_max_size": 2,
"log_max_age": 3,
"log_compress": true,
"log_localtime": true,
"verbose": true,
},
want: yobj{
"log": yobj{
"file": "/test/path.log",
"max_backups": 1,
"max_size": 2,
"max_age": 3,
"compress": true,
"local_time": true,
"verbose": true,
},
"schema_version": newSchemaVer,
},
wantErrMsg: "",
}, {
name: "invalid",
in: yobj{
"log_file": "/test/path.log",
"log_max_backups": 1,
"log_max_size": 2,
"log_max_age": 3,
"log_compress": "",
"log_localtime": true,
"verbose": true,
},
want: yobj{
"log_compress": "",
"schema_version": newSchemaVer,
},
wantErrMsg: `unexpected type of "log_compress": string`,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo24(tc.in)
testutil.AssertErrorMsg(t, tc.wantErrMsg, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema24to25(t *testing.T) {
const newSchemaVer = 25
testCases := []struct {
in yobj
want yobj
name string
wantErrMsg string
}{{
name: "empty",
in: yobj{},
want: yobj{
"schema_version": newSchemaVer,
},
wantErrMsg: "",
}, {
name: "ok",
in: yobj{
"http": yobj{
"address": "0.0.0.0:3000",
"session_ttl": "720h",
},
"debug_pprof": true,
},
want: yobj{
"http": yobj{
"address": "0.0.0.0:3000",
"session_ttl": "720h",
"pprof": yobj{
"enabled": true,
"port": 6060,
},
},
"schema_version": newSchemaVer,
},
wantErrMsg: "",
}, {
name: "ok_disabled",
in: yobj{
"http": yobj{
"address": "0.0.0.0:3000",
"session_ttl": "720h",
},
"debug_pprof": false,
},
want: yobj{
"http": yobj{
"address": "0.0.0.0:3000",
"session_ttl": "720h",
"pprof": yobj{
"enabled": false,
"port": 6060,
},
},
"schema_version": newSchemaVer,
},
wantErrMsg: "",
}, {
name: "invalid",
in: yobj{
"http": yobj{
"address": "0.0.0.0:3000",
"session_ttl": "720h",
},
"debug_pprof": 1,
},
want: yobj{
"http": yobj{
"address": "0.0.0.0:3000",
"session_ttl": "720h",
},
"debug_pprof": 1,
"schema_version": newSchemaVer,
},
wantErrMsg: `unexpected type of "debug_pprof": int`,
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo25(tc.in)
testutil.AssertErrorMsg(t, tc.wantErrMsg, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema25to26(t *testing.T) {
const newSchemaVer = 26
testCases := []struct {
in yobj
want yobj
name string
}{{
name: "empty",
in: yobj{},
want: yobj{
"schema_version": newSchemaVer,
},
}, {
name: "ok",
in: yobj{
"dns": yobj{
"filtering_enabled": true,
"filters_update_interval": 24,
"parental_enabled": false,
"safebrowsing_enabled": false,
"safebrowsing_cache_size": 1048576,
"safesearch_cache_size": 1048576,
"parental_cache_size": 1048576,
"safe_search": yobj{
"enabled": false,
"bing": true,
"duckduckgo": true,
"google": true,
"pixabay": true,
"yandex": true,
"youtube": true,
},
"rewrites": yarr{},
"blocked_services": yobj{
"schedule": yobj{
"time_zone": "Local",
},
"ids": yarr{},
},
"protection_enabled": true,
"blocking_mode": "custom_ip",
"blocking_ipv4": "1.2.3.4",
"blocking_ipv6": "1:2:3::4",
"blocked_response_ttl": 10,
"protection_disabled_until": nil,
"parental_block_host": "p.dns.adguard.com",
"safebrowsing_block_host": "s.dns.adguard.com",
},
},
want: yobj{
"dns": yobj{},
"filtering": yobj{
"filtering_enabled": true,
"filters_update_interval": 24,
"parental_enabled": false,
"safebrowsing_enabled": false,
"safebrowsing_cache_size": 1048576,
"safesearch_cache_size": 1048576,
"parental_cache_size": 1048576,
"safe_search": yobj{
"enabled": false,
"bing": true,
"duckduckgo": true,
"google": true,
"pixabay": true,
"yandex": true,
"youtube": true,
},
"rewrites": yarr{},
"blocked_services": yobj{
"schedule": yobj{
"time_zone": "Local",
},
"ids": yarr{},
},
"protection_enabled": true,
"blocking_mode": "custom_ip",
"blocking_ipv4": "1.2.3.4",
"blocking_ipv6": "1:2:3::4",
"blocked_response_ttl": 10,
"protection_disabled_until": nil,
"parental_block_host": "p.dns.adguard.com",
"safebrowsing_block_host": "s.dns.adguard.com",
},
"schema_version": newSchemaVer,
},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo26(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema26to27(t *testing.T) {
const newSchemaVer = 27
testCases := []struct {
in yobj
want yobj
name string
}{{
name: "empty",
in: yobj{},
want: yobj{
"schema_version": newSchemaVer,
},
}, {
name: "single_dot",
in: yobj{
"querylog": yobj{
"ignored": yarr{
".",
},
},
"statistics": yobj{
"ignored": yarr{
".",
},
},
},
want: yobj{
"querylog": yobj{
"ignored": yarr{
"|.^",
},
},
"statistics": yobj{
"ignored": yarr{
"|.^",
},
},
"schema_version": newSchemaVer,
},
}, {
name: "mixed",
in: yobj{
"querylog": yobj{
"ignored": yarr{
".",
"example.com",
},
},
"statistics": yobj{
"ignored": yarr{
".",
"example.org",
},
},
},
want: yobj{
"querylog": yobj{
"ignored": yarr{
"|.^",
"example.com",
},
},
"statistics": yobj{
"ignored": yarr{
"|.^",
"example.org",
},
},
"schema_version": newSchemaVer,
},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo27(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
func TestUpgradeSchema27to28(t *testing.T) {
const newSchemaVer = 28
testCases := []struct {
in yobj
want yobj
name string
}{{
name: "empty",
in: yobj{},
want: yobj{
"schema_version": newSchemaVer,
},
}, {
name: "load_balance",
in: yobj{
"dns": yobj{
"all_servers": false,
"fastest_addr": false,
},
},
want: yobj{
"dns": yobj{
"upstream_mode": dnsforward.UpstreamModeLoadBalance,
},
"schema_version": newSchemaVer,
},
}, {
name: "parallel",
in: yobj{
"dns": yobj{
"all_servers": true,
"fastest_addr": false,
},
},
want: yobj{
"dns": yobj{
"upstream_mode": dnsforward.UpstreamModeParallel,
},
"schema_version": newSchemaVer,
},
}, {
name: "parallel_fastest",
in: yobj{
"dns": yobj{
"all_servers": true,
"fastest_addr": true,
},
},
want: yobj{
"dns": yobj{
"upstream_mode": dnsforward.UpstreamModeParallel,
},
"schema_version": newSchemaVer,
},
}, {
name: "load_balance",
in: yobj{
"dns": yobj{
"all_servers": false,
"fastest_addr": true,
},
},
want: yobj{
"dns": yobj{
"upstream_mode": dnsforward.UpstreamModeFastestAddr,
},
"schema_version": newSchemaVer,
},
}}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := migrateTo28(tc.in)
require.NoError(t, err)
assert.Equal(t, tc.want, tc.in)
})
}
}
``` | /content/code_sandbox/internal/configmigrate/migrations_internal_test.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 11,767 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ip: 127.0.0.1
mac: ""
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
schema_version: 5
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v5/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 305 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
querylog_file_enabled: true
querylog_interval: 720h
querylog_size_memory: 1000
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 14
user_rules: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v15/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 527 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 15
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v15/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 526 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
local_domain_name: local
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 10
user_rules: []
rlimit_nofile: 123
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v11/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 451 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
local_domain_name: local
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 11
user_rules: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v11/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 462 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
autohost_tld: local
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 8
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v9/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 429 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
local_domain_name: local
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 9
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v9/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 428 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
local_domain_name: local
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
querylog_interval: 30
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 11
user_rules: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v12/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 470 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
local_domain_name: local
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
querylog_interval: 720h
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 12
user_rules: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v12/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 471 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: true
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 18
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 10
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v19/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 609 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 19
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 10
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v19/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 651 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 21
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v22/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 684 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
auth_name: testuser
auth_pass: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns: 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
schema_version: 2
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v3/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 235 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 22
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v22/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 696 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
auth_name: testuser
auth_pass: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
schema_version: 3
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v3/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 237 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 6
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v7/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 388 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 7
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v7/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 393 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
local_domain_name: local
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 9
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v10/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 441 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
local_domain_name: local
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 10
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v10/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 443 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
auth_name: testuser
auth_pass: testpassword
coredns:
bind_host: 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns: 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
schema_version: 1
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v2/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 249 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
auth_name: testuser
auth_pass: testpassword
dns:
bind_host: 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns: 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
schema_version: 2
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v2/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 248 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet: true
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 16
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 10
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v17/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 551 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 17
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 10
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v17/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 567 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
auth_name: testuser
auth_pass: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ip: 127.0.0.1
mac: ""
use_global_settings: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
schema_version: 3
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v4/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 295 |
```yaml
http:
address: 127.0.0.1:3000
session_ttl: 3h
debug_pprof: true
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 24
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
log:
file: ""
max_backups: 0
max_size: 100
max_age: 3
compress: true
local_time: false
verbose: true
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v25/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 752 |
```yaml
http:
address: 127.0.0.1:3000
session_ttl: 3h
pprof:
enabled: true
port: 6060
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 25
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
log:
file: ""
max_backups: 0
max_size: 100
max_age: 3
compress: true
local_time: false
verbose: true
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v25/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 762 |
```yaml
http:
address: 127.0.0.1:3000
session_ttl: 3h
pprof:
enabled: true
port: 6060
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
parental_sensitivity: 0
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
filtering:
filtering_enabled: true
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
protection_enabled: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
blocked_response_ttl: 10
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 27
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored:
- '|.^'
statistics:
enabled: true
interval: 240h
ignored:
- '|.^'
os:
group: ''
rlimit_nofile: 123
user: ''
log:
file: ""
max_backups: 0
max_size: 100
max_age: 3
compress: true
local_time: false
verbose: true
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v27/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 773 |
```yaml
http:
address: 127.0.0.1:3000
session_ttl: 3h
pprof:
enabled: true
port: 6060
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
parental_sensitivity: 0
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
filtering:
filtering_enabled: true
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
protection_enabled: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
blocked_response_ttl: 10
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 26
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored:
- '.'
statistics:
enabled: true
interval: 240h
ignored:
- '.'
os:
group: ''
rlimit_nofile: 123
user: ''
log:
file: ""
max_backups: 0
max_size: 100
max_age: 3
compress: true
local_time: false
verbose: true
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v27/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 771 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
querylog_interval: 720h
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
resolve_clients: true
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 13
user_rules: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v14/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 477 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
querylog_interval: 720h
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 14
user_rules: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v14/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 509 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ip: 127.0.0.1
mac: aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
schema_version: 5
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v6/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 316 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 18
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 10
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v18/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 609 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
ip: 127.0.0.1
mac: aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
schema_version: 6
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v6/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 344 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_host: 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 7
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v8/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 419 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 8
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v8/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 421 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
web_session_ttl: 3
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 22
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v23/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 703 |
```yaml
http:
address: 127.0.0.1:3000
session_ttl: 3h
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 23
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v23/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 702 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 20
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v20/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 652 |
```yaml
http:
address: 127.0.0.1:3000
session_ttl: 3h
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 23
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ""
rlimit_nofile: 123
user: ""
log_file: ""
log_max_backups: 0
log_max_size: 100
log_max_age: 3
log_compress: true
log_localtime: false
verbose: true
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v24/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 743 |
```yaml
http:
address: 127.0.0.1:3000
session_ttl: 3h
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safe_search:
enabled: false
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
edns_client_subnet:
enabled: true
use_custom: false
custom_ip: ""
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safe_search:
enabled: true
bing: true
duckduckgo: true
google: true
pixabay: true
yandex: true
youtube: true
blocked_services:
schedule:
time_zone: Local
ids:
- 500px
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 24
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 240h
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
log:
file: ""
max_backups: 0
max_size: 100
max_age: 3
compress: true
local_time: false
verbose: true
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v24/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 746 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
auth_name: testuser
auth_pass: testpassword
coredns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v1/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 215 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
auth_name: testuser
auth_pass: testpassword
coredns:
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
schema_version: 1
user_rules: []
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v1/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 221 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 16
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
statistics:
enabled: true
interval: 10
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v16/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 543 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
statistics_interval: 10
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
persistent:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
runtime_sources:
whois: true
arp: true
rdns: true
dhcp: true
hosts: true
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 15
user_rules: []
querylog:
enabled: true
file_enabled: true
interval: 720h
size_memory: 1000
ignored: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v16/input.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 533 |
```yaml
bind_host: 127.0.0.1
bind_port: 3000
users:
- name: testuser
password: testpassword
dns:
bind_hosts:
- 127.0.0.1
port: 53
protection_enabled: true
filtering_enabled: true
safebrowsing_enabled: false
safesearch_enabled: false
parental_enabled: false
parental_sensitivity: 0
blocked_response_ttl: 10
querylog_enabled: true
querylog_interval: 720h
upstream_dns:
- tls://1.1.1.1
- tls://1.0.0.1
- quic://8.8.8.8:784
bootstrap_dns:
- 8.8.8.8:53
filters:
- url: path_to_url
name: ""
enabled: true
- url: path_to_url
name: AdAway
enabled: false
- url: path_to_url
name: hpHosts - Ad and Tracking servers only
enabled: false
- url: path_to_url
name: MalwareDomainList.com Hosts List
enabled: false
clients:
- name: localhost
ids:
- 127.0.0.1
- aa:aa:aa:aa:aa:aa
use_global_settings: true
use_global_blocked_services: true
filtering_enabled: false
parental_enabled: false
safebrowsing_enabled: false
safesearch_enabled: false
dhcp:
enabled: false
interface_name: vboxnet0
local_domain_name: local
dhcpv4:
gateway_ip: 192.168.0.1
subnet_mask: 255.255.255.0
range_start: 192.168.0.10
range_end: 192.168.0.250
lease_duration: 1234
icmp_timeout_msec: 10
schema_version: 13
user_rules: []
os:
group: ''
rlimit_nofile: 123
user: ''
``` | /content/code_sandbox/internal/configmigrate/testdata/TestMigrateConfig_Migrate/v13/output.yml | yaml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 471 |
```go
// Package ipset provides ipset functionality.
package ipset
import (
"net"
)
// Manager is the ipset manager interface.
//
// TODO(a.garipov): Perhaps generalize this into some kind of a NetFilter type,
// since ipset is exclusive to Linux?
type Manager interface {
Add(host string, ip4s, ip6s []net.IP) (n int, err error)
Close() (err error)
}
// NewManager returns a new ipset manager. IPv4 addresses are added to an
// ipset with an ipv4 family; IPv6 addresses, to an ipv6 ipset. ipset must
// exist.
//
// The syntax of the ipsetConf is:
//
// DOMAIN[,DOMAIN].../IPSET_NAME[,IPSET_NAME]...
//
// If ipsetConf is empty, msg and err are nil. The error's chain contains
// [errors.ErrUnsupported] if current OS is not supported.
func NewManager(ipsetConf []string) (mgr Manager, err error) {
if len(ipsetConf) == 0 {
return nil, nil
}
return newManager(ipsetConf)
}
``` | /content/code_sandbox/internal/ipset/ipset.go | go | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 247 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.