Skip to content

Commit

Permalink
all: imp code
Browse files Browse the repository at this point in the history
  • Loading branch information
schzhn committed Dec 25, 2024
1 parent ee07eda commit b96522a
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 75 deletions.
51 changes: 8 additions & 43 deletions internal/cmd/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@ import (
"context"
"crypto/tls"
"fmt"
"io/fs"
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"

Expand Down Expand Up @@ -43,13 +40,18 @@ func createProxyConfig(
return nil, err
}

hosts, err := handler.ReadHosts(hostsFiles)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return nil, err
}

reqHdlr, err := handler.NewDefault(&handler.DefaultConfig{
Logger: l.With(slogutil.KeyPrefix, "default_handler"),
// TODO(e.burkov): Use the configured message constructor.
MessageConstructor: dnsmsg.DefaultMessageConstructor{},
HaltIPv6: conf.IPv6Disabled,
HostsFiles: hostsFiles,
FileSystem: osutil.RootDirFS(),
HostsFiles: hosts,
})
if err != nil {
return nil, fmt.Errorf("creating default handler: %w", err)
Expand Down Expand Up @@ -517,7 +519,7 @@ func (conf *configuration) hostsFiles(ctx context.Context, l *slog.Logger) (path
l.DebugContext(ctx, "hosts files are enabled")

if len(conf.HostsFiles) > 0 {
return prepareHostsFilesPaths(conf.HostsFiles)
return conf.HostsFiles, nil
}

paths, err = hostsfile.DefaultHostsPaths()
Expand All @@ -529,40 +531,3 @@ func (conf *configuration) hostsFiles(ctx context.Context, l *slog.Logger) (path

return paths, nil
}

func prepareHostsFilesPaths(paths []string) (res []string, err error) {
defer func() { err = errors.Annotate(err, "preparing hosts files paths: %w") }()

execPath, err := os.Executable()
if err != nil {
// Don't wrap the error, as it will get annotated.
return nil, err
}

execDir := filepath.Dir(execPath)

var errs []error
for _, p := range paths {
if strings.HasPrefix(p, "./") {
p = path.Join(execDir, p)
}

p = strings.TrimPrefix(p, "/")

if !fs.ValidPath(p) {
errs = append(errs, fmt.Errorf("invalid path: %q", p))

continue
}

res = append(res, p)
}

err = errors.Join(errs...)
if err != nil {
// Don't wrap the error, as it will get annotated.
return nil, err
}

return res, nil
}
19 changes: 3 additions & 16 deletions internal/handler/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package handler

import (
"context"
"io/fs"
"log/slog"

"github.com/AdguardTeam/dnsproxy/proxy"
Expand All @@ -16,18 +15,11 @@ type DefaultConfig struct {
// MessageConstructor constructs DNS messages. It must not be nil.
MessageConstructor proxy.MessageConstructor

// FileSystem is the file system for reading files from. It must not be
// nil.
FileSystem fs.FS

// Logger is the logger. It must not be nil.
Logger *slog.Logger

// HostsFiles is the list of paths to the hosts files. The hosts files
// aren't used if the list is empty.
//
// TODO(e.burkov): Consider passing just a [hostsfile.Storage].
HostsFiles []string
// HostsFiles is the index containing the records of the hosts files.
HostsFiles hostsfile.Storage

// HaltIPv6 halts the processing of AAAA requests and makes the handler
// reply with NODATA to them.
Expand All @@ -44,11 +36,6 @@ type Default struct {

// NewDefault creates a new [Default] handler.
func NewDefault(conf *DefaultConfig) (d *Default, err error) {
hosts, err := readHosts(conf.FileSystem, conf.HostsFiles)
if err != nil {
return nil, err
}

mc, ok := conf.MessageConstructor.(messageConstructor)
if !ok {
mc = defaultConstructor{
Expand All @@ -60,7 +47,7 @@ func NewDefault(conf *DefaultConfig) (d *Default, err error) {
logger: conf.Logger,
isIPv6Halted: conf.HaltIPv6,
messages: mc,
hosts: hosts,
hosts: conf.HostsFiles,
}, nil
}

Expand Down
12 changes: 4 additions & 8 deletions internal/handler/default_internal_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"io/fs"
"net"
"net/netip"
"os"
Expand Down Expand Up @@ -33,9 +32,6 @@ func TestMain(m *testing.M) {
// defaultTimeout is a default timeout for tests and contexts.
const defaultTimeout = 1 * time.Second

// testdata is the file system for test data.
var testdata fs.FS = os.DirFS("testdata")

func TestDefault_haltAAAA(t *testing.T) {
t.Parallel()

Expand All @@ -56,7 +52,6 @@ func TestDefault_haltAAAA(t *testing.T) {
Logger: slogutil.NewDiscardLogger(),
MessageConstructor: messages,
HaltIPv6: false,
FileSystem: testdata,
})
require.NoError(t, err)

Expand All @@ -73,7 +68,6 @@ func TestDefault_haltAAAA(t *testing.T) {
Logger: slogutil.NewDiscardLogger(),
MessageConstructor: messages,
HaltIPv6: true,
FileSystem: testdata,
})
require.NoError(t, err)

Expand All @@ -90,11 +84,13 @@ func TestDefault_resolveFromHosts(t *testing.T) {
// TODO(e.burkov): Use the one from [dnsproxytest].
messages := dnsmsg.DefaultMessageConstructor{}

strg, err := ReadHosts([]string{path.Join("testdata", t.Name(), "hosts")})
require.NoError(t, err)

hdlr, err := NewDefault(&DefaultConfig{
MessageConstructor: messages,
FileSystem: testdata,
Logger: slogutil.NewDiscardLogger(),
HostsFiles: []string{path.Join(t.Name(), "hosts")},
HostsFiles: strg,
HaltIPv6: true,
})
require.NoError(t, err)
Expand Down
23 changes: 15 additions & 8 deletions internal/handler/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package handler
import (
"context"
"fmt"
"io/fs"
"net/netip"
"os"
"path/filepath"
"slices"
"strings"

Expand Down Expand Up @@ -33,15 +34,15 @@ func (emptyStorage) ByName(_ string) (addrs []netip.Addr) {
return nil
}

// readHosts reads the hosts files from the file system and returns a storage
// ReadHosts reads the hosts files from the file system and returns a storage
// with parsed records. strg is always usable even if an error occurred.
func readHosts(fsys fs.FS, paths []string) (strg hostsfile.Storage, err error) {
func ReadHosts(paths []string) (strg hostsfile.Storage, err error) {
// Don't check the error since it may only appear when any readers used.
defaultStrg, _ := hostsfile.NewDefaultStorage()

var errs []error
for _, path := range paths {
err = readHostsFile(defaultStrg, fsys, path)
err = readHostsFile(defaultStrg, path)
if err != nil {
// Don't wrap the error since it's informative enough as is.
errs = append(errs, err)
Expand All @@ -63,13 +64,19 @@ func readHosts(fsys fs.FS, paths []string) (strg hostsfile.Storage, err error) {
return defaultStrg, errors.Join(errs...)
}

// readHostsFile reads the hosts file at path from fsys and parses it into strg.
func readHostsFile(strg *hostsfile.DefaultStorage, fsys fs.FS, path string) (err error) {
f, err := fsys.Open(path)
// readHostsFile reads the hosts file at path and parses it into strg.
func readHostsFile(strg *hostsfile.DefaultStorage, path string) (err error) {
absPath, err := filepath.Abs(path)
if err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}

// #nosec G304 -- Trust the file path from the configuration file.
f, err := os.Open(absPath)
if err != nil {
return err
}

defer func() { err = errors.WithDeferred(err, f.Close()) }()

err = hostsfile.Parse(strg, f, nil)
Expand Down

0 comments on commit b96522a

Please sign in to comment.