Skip to content

Commit

Permalink
cmd: hosts files paths
Browse files Browse the repository at this point in the history
  • Loading branch information
schzhn committed Dec 24, 2024
1 parent d80a8e3 commit ee07eda
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion internal/cmd/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import (
"context"
"crypto/tls"
"fmt"
"io/fs"
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"

Expand Down Expand Up @@ -514,7 +517,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 conf.HostsFiles, nil
return prepareHostsFilesPaths(conf.HostsFiles)
}

paths, err = hostsfile.DefaultHostsPaths()
Expand All @@ -526,3 +529,40 @@ 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
}

0 comments on commit ee07eda

Please sign in to comment.