diff --git a/cluster/state.go b/cluster/state.go index 32beb9ae..ea05f1cf 100644 --- a/cluster/state.go +++ b/cluster/state.go @@ -11,6 +11,8 @@ import ( "path/filepath" "strings" "sync" + + "dnsplane/internal/atomicfile" ) // PersistedState is stored next to dnsplane.json as cluster_state.json. @@ -90,11 +92,7 @@ func (s *stateManager) saveLocked() error { if err != nil { return err } - tmp := s.path + ".tmp" - if err := os.WriteFile(tmp, data, 0o600); err != nil { - return err - } - return os.Rename(tmp, s.path) + return atomicfile.Write(s.path, data, 0o600) } func (s *stateManager) NodeID() string { diff --git a/config/config.go b/config/config.go index bc69d459..da3dbf44 100644 --- a/config/config.go +++ b/config/config.go @@ -12,10 +12,14 @@ import ( ) const ( - // FileName is the canonical name of the configuration file. - FileName = "dnsplane.json" - // systemConfigPath is the location checked last when resolving the config. - systemConfigPath = "/etc/" + FileName + // FileName is the canonical name of new configuration files (YAML). + FileName = "dnsplane.yaml" + // FileNameYML is an alternate YAML extension. + FileNameYML = "dnsplane.yml" + // FileNameJSON is the legacy JSON configuration file name. + FileNameJSON = "dnsplane.json" + // systemConfigDir is the packaged system config directory. + systemConfigDir = "/etc/dnsplane" ) // RecordsSourceType is how the DNS records file is provided: local file, HTTP(S) URL, git repo, or BIND zone directory. @@ -230,27 +234,46 @@ type Config struct { // Loaded contains the configuration together with metadata about the source file. type Loaded struct { - Path string - Created bool - Config Config + Path string // file read for this session + WritePath string // file used for Save (always YAML once present or migrated) + Created bool + Config Config +} + +// WriteConfigPath returns the path settings and saves should use. +func (l *Loaded) WriteConfigPath() string { + if l == nil { + return "" + } + if l.WritePath != "" { + return l.WritePath + } + return l.Path } // Load resolves the dnsplane configuration file, creating a default one if // necessary, and returns the parsed configuration alongside metadata. func Load() (*Loaded, error) { - candidates, err := candidatePaths() + dirs, err := candidateSearchPaths() if err != nil { return nil, err } - - for _, path := range candidates { - cfg, err := readConfig(path) + for _, dir := range dirs { + loaded, err := resolveLoadedConfig(dir, "") + if err == nil { + return loaded, nil + } + if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + } + if fileExists(legacyEtcConfig()) { + loaded, err := tryLoadFromResolvedPath(legacyEtcConfig()) if err == nil { - cfg.applyDefaults(filepath.Dir(path)) - return &Loaded{Path: path, Config: *cfg}, nil + return loaded, nil } if !errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("config: failed to read %s: %w", path, err) + return nil, err } } @@ -258,69 +281,79 @@ func Load() (*Loaded, error) { if err != nil { return nil, fmt.Errorf("config: determine working directory: %w", err) } - - defaultPath := filepath.Join(defaultDir, FileName) - cfg := defaultConfig(defaultDir) - if err := writeConfig(defaultPath, cfg); err != nil { - return nil, err - } - cfg.applyDefaults(defaultDir) - return &Loaded{Path: defaultPath, Created: true, Config: *cfg}, nil + return createDefaultInDir(defaultDir) } -// resolveConfigPath returns the config file path. If path is a directory (ends -// with /, exists as dir, or path has no extension), returns path/FileName; -// otherwise returns path as the config file path. -func resolveConfigPath(path string) (string, error) { +// resolveConfigInput returns the directory or explicit config file path. +func resolveConfigInput(path string) (resolved string, isDir bool, err error) { path = filepath.Clean(strings.TrimSpace(path)) if path == "" || path == "." { - return "", fmt.Errorf("config: path is empty") + return "", false, fmt.Errorf("config: path is empty") } - isDir := strings.HasSuffix(path, string(filepath.Separator)) + isDir = strings.HasSuffix(path, string(filepath.Separator)) if !isDir { - if info, err := os.Stat(path); err == nil && info.IsDir() { + if info, statErr := os.Stat(path); statErr == nil && info.IsDir() { isDir = true } else if !strings.Contains(filepath.Base(path), ".") { isDir = true } } if isDir { - path = strings.TrimSuffix(path, string(filepath.Separator)) - return filepath.Join(path, FileName), nil + return strings.TrimSuffix(path, string(filepath.Separator)), true, nil + } + return path, false, nil +} + +func isStandardConfigName(p string) bool { + switch filepath.Base(p) { + case FileName, FileNameYML, FileNameJSON: + return true + default: + return false } - return path, nil } // LoadFromPath loads configuration from the given path, or creates a default // config at that path if the file does not exist. Path may be a directory -// (then config is path/dnsplane.json) or a file path (then that file is used). +// (then config is path/dnsplane.yaml) or a file path (then that file is used). func LoadFromPath(path string) (*Loaded, error) { path = strings.TrimSpace(path) if path == "" { return nil, fmt.Errorf("config: path is empty") } - configPath, err := resolveConfigPath(path) + resolved, isDir, err := resolveConfigInput(path) if err != nil { return nil, err } - cfg, err := readConfig(configPath) - if err == nil { - cfg.applyDefaults(filepath.Dir(configPath)) - return &Loaded{Path: configPath, Config: *cfg}, nil + if isDir { + loaded, loadErr := resolveLoadedConfig(resolved, "") + if loadErr == nil { + return loaded, nil + } + if !errors.Is(loadErr, os.ErrNotExist) { + return nil, loadErr + } + return createDefaultInDir(resolved) } - if !errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("config: failed to read %s: %w", configPath, err) + dir := filepath.Dir(resolved) + if isStandardConfigName(resolved) { + loaded, loadErr := resolveLoadedConfig(dir, resolved) + if loadErr == nil { + return loaded, nil + } + if !errors.Is(loadErr, os.ErrNotExist) { + return nil, loadErr + } + return createDefaultInDir(dir) } - dir := filepath.Dir(configPath) - if err := os.MkdirAll(dir, 0o750); err != nil { - return nil, fmt.Errorf("config: ensure config directory %s: %w", dir, err) + loaded, err := tryLoadFromResolvedPath(resolved) + if err == nil { + return loaded, nil } - defaultCfg := defaultConfig(dir) - if err := writeConfig(configPath, defaultCfg); err != nil { + if !errors.Is(err, os.ErrNotExist) { return nil, err } - defaultCfg.applyDefaults(dir) - return &Loaded{Path: configPath, Created: true, Config: *defaultCfg}, nil + return createDefaultInDir(dir) } // Read loads and normalises configuration from the specified path without @@ -350,63 +383,6 @@ func (c *Config) Normalize(configDir string) { c.applyDefaults(configDir) } -func candidatePaths() ([]string, error) { - execPath, err := os.Executable() - if err != nil { - return nil, fmt.Errorf("config: determine executable path: %w", err) - } - execDir := filepath.Dir(execPath) - - var paths []string - paths = appendIfMissing(paths, filepath.Join(execDir, FileName)) - - if userPath, err := userConfigPath(); err == nil && userPath != "" { - paths = appendIfMissing(paths, userPath) - } - - paths = appendIfMissing(paths, systemConfigPath) - return paths, nil -} - -func userConfigPath() (string, error) { - dir, err := os.UserConfigDir() - if err != nil { - return "", fmt.Errorf("config: determine user config dir: %w", err) - } - return filepath.Join(dir, "dnsplane", FileName), nil -} - -func readConfig(path string) (*Config, error) { - data, err := os.ReadFile(path) // #nosec G304 -- path from operator (config file) - if err != nil { - return nil, err - } - if len(strings.TrimSpace(string(data))) == 0 { - return nil, fmt.Errorf("config: file %s is empty", path) - } - - var cfg Config - if err := json.Unmarshal(data, &cfg); err != nil { - return nil, fmt.Errorf("config: parse %s: %w", path, err) - } - - if legacy := extractLegacyRecordSettings(data); legacy != nil { - cfg.DNSRecordSettings = *legacy - } - return &cfg, nil -} - -func writeConfig(path string, cfg *Config) error { - payload, err := json.MarshalIndent(cfg, "", " ") - if err != nil { - return fmt.Errorf("config: marshal config: %w", err) - } - if err := os.WriteFile(path, payload, 0o600); err != nil { - return fmt.Errorf("config: write %s: %w", path, err) - } - return nil -} - func defaultConfig(baseDir string) *Config { logDir := "/var/log/dnsplane" if !isSystemConfigDir(baseDir) { diff --git a/config/format.go b/config/format.go new file mode 100644 index 00000000..3de9198b --- /dev/null +++ b/config/format.go @@ -0,0 +1,84 @@ +// Copyright 2024-2026 George (earentir) Pantazis (https://earentir.dev) +// SPDX-License-Identifier: GPL-2.0-only + +package config + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + + "dnsplane/internal/atomicfile" + + "gopkg.in/yaml.v3" +) + +func decodeConfigBytes(path string, data []byte) (*Config, error) { + if len(strings.TrimSpace(string(data))) == 0 { + return nil, fmt.Errorf("config: file %s is empty", path) + } + ext := strings.ToLower(filepath.Ext(path)) + jsonData := data + if ext == ".yaml" || ext == ".yml" { + var v any + if err := yaml.Unmarshal(data, &v); err != nil { + return nil, fmt.Errorf("config: parse %s: %w", path, err) + } + var err error + jsonData, err = json.Marshal(v) + if err != nil { + return nil, fmt.Errorf("config: parse %s: %w", path, err) + } + } + + var cfg Config + if err := json.Unmarshal(jsonData, &cfg); err != nil { + return nil, fmt.Errorf("config: parse %s: %w", path, err) + } + if legacy := extractLegacyRecordSettings(jsonData); legacy != nil { + cfg.DNSRecordSettings = *legacy + } + return &cfg, nil +} + +func readConfig(path string) (*Config, error) { + data, err := os.ReadFile(path) // #nosec G304 -- path from operator (config file) + if err != nil { + return nil, err + } + return decodeConfigBytes(path, data) +} + +func writeConfig(path string, cfg *Config) error { + ext := strings.ToLower(filepath.Ext(path)) + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o750); err != nil { + return fmt.Errorf("config: ensure config directory %s: %w", dir, err) + } + cfg.applyDefaults(dir) + var payload []byte + var err error + switch ext { + case ".yaml", ".yml": + j, mErr := json.Marshal(cfg) + if mErr != nil { + return fmt.Errorf("config: marshal config: %w", mErr) + } + var v any + if err = json.Unmarshal(j, &v); err != nil { + return fmt.Errorf("config: marshal config: %w", err) + } + payload, err = yaml.Marshal(v) + default: + payload, err = json.MarshalIndent(cfg, "", " ") + } + if err != nil { + return fmt.Errorf("config: marshal config: %w", err) + } + if err := atomicfile.Write(path, payload, 0o600); err != nil { + return fmt.Errorf("config: write %s: %w", path, err) + } + return nil +} diff --git a/config/resolve.go b/config/resolve.go new file mode 100644 index 00000000..4e463725 --- /dev/null +++ b/config/resolve.go @@ -0,0 +1,164 @@ +// Copyright 2024-2026 George (earentir) Pantazis (https://earentir.dev) +// SPDX-License-Identifier: GPL-2.0-only + +package config + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +func configPathsInDir(dir string) (yaml, yml, json string) { + dir = filepath.Clean(dir) + return filepath.Join(dir, FileName), filepath.Join(dir, FileNameYML), filepath.Join(dir, FileNameJSON) +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +func nagf(format string, args ...any) { + _, _ = fmt.Fprintf(os.Stderr, "dnsplane: "+format+"\n", args...) +} + +// resolveLoadedConfig picks read/write paths in dir, handles JSON→YAML migration and startup nags. +// userPath is the path the operator passed (--config) or the candidate file path from search; empty when probing a dir only. +func resolveLoadedConfig(dir, userPath string) (*Loaded, error) { + dir = filepath.Clean(dir) + yamlPath, ymlPath, jsonPath := configPathsInDir(dir) + writePath := yamlPath + + yamlExists := fileExists(yamlPath) + ymlExists := fileExists(ymlPath) + jsonExists := fileExists(jsonPath) + readYAML := "" + if yamlExists { + readYAML = yamlPath + } else if ymlExists { + readYAML = ymlPath + } + + userPath = strings.TrimSpace(userPath) + userJSON := strings.HasSuffix(strings.ToLower(userPath), ".json") + + if readYAML != "" { + if jsonExists { + nagf("config: using %s; leftover %s is ignored (remove it or pass --config %s)", readYAML, jsonPath, readYAML) + } + if userJSON && filepath.Clean(userPath) == jsonPath { + nagf("config: --config points at %s; using %s. Pass --config %s", jsonPath, readYAML, readYAML) + } + cfg, err := readConfig(readYAML) + if err != nil { + return nil, fmt.Errorf("config: failed to read %s: %w", readYAML, err) + } + cfg.applyDefaults(dir) + return &Loaded{Path: readYAML, WritePath: writePath, Config: *cfg}, nil + } + + if jsonExists { + cfg, err := readConfig(jsonPath) + if err != nil { + return nil, fmt.Errorf("config: failed to read %s: %w", jsonPath, err) + } + cfg.applyDefaults(dir) + if err := writeConfig(writePath, cfg); err != nil { + return nil, err + } + nagf("config: migrated %s -> %s (JSON kept; settings saves go to YAML)", jsonPath, writePath) + if userJSON && filepath.Clean(userPath) == jsonPath { + nagf("config: pass --config %s to silence this message", writePath) + } + return &Loaded{Path: writePath, WritePath: writePath, Config: *cfg}, nil + } + + return nil, os.ErrNotExist +} + +func createDefaultInDir(dir string) (*Loaded, error) { + if err := os.MkdirAll(dir, 0o750); err != nil { + return nil, fmt.Errorf("config: ensure config directory %s: %w", dir, err) + } + yamlPath, _, _ := configPathsInDir(dir) + defaultCfg := defaultConfig(dir) + if err := writeConfig(yamlPath, defaultCfg); err != nil { + return nil, err + } + defaultCfg.applyDefaults(dir) + return &Loaded{Path: yamlPath, WritePath: yamlPath, Created: true, Config: *defaultCfg}, nil +} + +func tryLoadFromResolvedPath(configPath string) (*Loaded, error) { + configPath = filepath.Clean(strings.TrimSpace(configPath)) + dir := filepath.Dir(configPath) + loaded, err := resolveLoadedConfig(dir, configPath) + if err == nil { + return loaded, nil + } + if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + // Explicit single file that is not part of standard trio (e.g. custom name) + if fileExists(configPath) { + cfg, rErr := readConfig(configPath) + if rErr != nil { + return nil, fmt.Errorf("config: failed to read %s: %w", configPath, rErr) + } + cfg.applyDefaults(dir) + wp := configPath + ext := strings.ToLower(filepath.Ext(configPath)) + if ext == ".json" { + yamlPath, _, _ := configPathsInDir(dir) + if fileExists(yamlPath) { + wp = yamlPath + nagf("config: using %s instead of %s", yamlPath, configPath) + } + } + return &Loaded{Path: configPath, WritePath: wp, Config: *cfg}, nil + } + return nil, os.ErrNotExist +} + +func candidateSearchPaths() ([]string, error) { + execPath, err := os.Executable() + if err != nil { + return nil, fmt.Errorf("config: determine executable path: %w", err) + } + execDir := filepath.Dir(execPath) + + var dirs []string + dirs = appendIfMissingDir(dirs, execDir) + if userPath, err := userConfigDir(); err == nil && userPath != "" { + dirs = appendIfMissingDir(dirs, userPath) + } + dirs = appendIfMissingDir(dirs, systemConfigDir) + dirs = appendIfMissingDir(dirs, filepath.Dir(systemConfigDir)) // /etc for legacy /etc/dnsplane.json + return dirs, nil +} + +func appendIfMissingDir(list []string, dir string) []string { + dir = filepath.Clean(dir) + for _, existing := range list { + if existing == dir { + return list + } + } + return append(list, dir) +} + +func userConfigDir() (string, error) { + dir, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(dir, "dnsplane"), nil +} + +// legacy paths beside /etc/dnsplane.json +func legacyEtcConfig() string { + return filepath.Join("/etc", FileNameJSON) +} diff --git a/config/yaml_test.go b/config/yaml_test.go new file mode 100644 index 00000000..632275a8 --- /dev/null +++ b/config/yaml_test.go @@ -0,0 +1,75 @@ +// Copyright 2024-2026 George (earentir) Pantazis (https://earentir.dev) +// SPDX-License-Identifier: GPL-2.0-only + +package config + +import ( + "os" + "path/filepath" + "testing" +) + +func TestLoadFromPathMigratesJSONToYAML(t *testing.T) { + dir := t.TempDir() + jsonPath := filepath.Join(dir, FileNameJSON) + raw := []byte(`{"port":"5353","apiport":"8080","file_locations":{"dnsservers":"a.json","cache":"b.json","records_source":{"type":"file","location":"r.json"}},"DNSRecordSettings":{"auto_build_ptr_from_a":true,"forward_ptr_queries":false},"log":{"log_dir":"./l","log_severity":"none","log_rotation":"size","log_rotation_size_mb":100,"log_rotation_time_days":7}}`) + if err := os.WriteFile(jsonPath, raw, 0o600); err != nil { + t.Fatal(err) + } + loaded, err := LoadFromPath(dir) + if err != nil { + t.Fatal(err) + } + yamlPath := filepath.Join(dir, FileName) + if loaded.WritePath != yamlPath { + t.Fatalf("WritePath = %q, want %q", loaded.WritePath, yamlPath) + } + if _, err := os.Stat(yamlPath); err != nil { + t.Fatalf("yaml not created: %v", err) + } + if _, err := os.Stat(jsonPath); err != nil { + t.Fatal("json should remain after migration") + } + if loaded.Config.DNSPort != "5353" { + t.Fatalf("DNSPort = %q", loaded.Config.DNSPort) + } +} + +func TestLoadPrefersYAMLWhenBothExist(t *testing.T) { + dir := t.TempDir() + jsonPath := filepath.Join(dir, FileNameJSON) + yamlPath := filepath.Join(dir, FileName) + _ = os.WriteFile(jsonPath, []byte(`{"port":"1111","apiport":"8080","file_locations":{"dnsservers":"a.json","cache":"b.json","records_source":{"type":"file","location":"r.json"}},"DNSRecordSettings":{"auto_build_ptr_from_a":true,"forward_ptr_queries":false},"log":{"log_dir":"./l","log_severity":"none","log_rotation":"size","log_rotation_size_mb":100,"log_rotation_time_days":7}}`), 0o600) + _ = os.WriteFile(yamlPath, []byte("port: \"2222\"\napiport: \"8080\"\nfile_locations:\n dnsservers: a.json\n cache: b.json\n records_source:\n type: file\n location: r.json\nDNSRecordSettings:\n auto_build_ptr_from_a: true\n forward_ptr_queries: false\nlog:\n log_dir: ./l\n log_severity: none\n log_rotation: size\n log_rotation_size_mb: 100\n log_rotation_time_days: 7\n"), 0o600) + + loaded, err := LoadFromPath(jsonPath) + if err != nil { + t.Fatal(err) + } + if loaded.Config.DNSPort != "2222" { + t.Fatalf("expected yaml port 2222, got %q", loaded.Config.DNSPort) + } +} + +func TestSaveWritesYAMLNotJSON(t *testing.T) { + dir := t.TempDir() + jsonPath := filepath.Join(dir, FileNameJSON) + yamlPath := filepath.Join(dir, FileName) + _ = os.WriteFile(jsonPath, []byte(`{"port":"53","apiport":"8080","file_locations":{"dnsservers":"a.json","cache":"b.json","records_source":{"type":"file","location":"r.json"}},"DNSRecordSettings":{"auto_build_ptr_from_a":true,"forward_ptr_queries":false},"log":{"log_dir":"./l","log_severity":"none","log_rotation":"size","log_rotation_size_mb":100,"log_rotation_time_days":7}}`), 0o600) + loaded, err := LoadFromPath(jsonPath) + if err != nil { + t.Fatal(err) + } + loaded.Config.DNSPort = "9999" + if err := Save(loaded.WritePath, loaded.Config); err != nil { + t.Fatal(err) + } + cfg, err := readConfig(yamlPath) + if err != nil || cfg.DNSPort != "9999" { + t.Fatalf("yaml save: port=%q err=%v", cfg.DNSPort, err) + } + cfg2, err := readConfig(jsonPath) + if err != nil || cfg2.DNSPort != "53" { + t.Fatalf("json should be untouched, port=%q", cfg2.DNSPort) + } +} diff --git a/data/cache_corrupt_test.go b/data/cache_corrupt_test.go new file mode 100644 index 00000000..cd42d288 --- /dev/null +++ b/data/cache_corrupt_test.go @@ -0,0 +1,38 @@ +// Copyright 2024-2026 George (earentir) Pantazis (https://earentir.dev) +// SPDX-License-Identifier: GPL-2.0-only + +package data + +import ( + "os" + "path/filepath" + "testing" + + "dnsplane/config" +) + +func TestLoadCacheRecordsCorruptStartsEmpty(t *testing.T) { + dir := t.TempDir() + cachePath := filepath.Join(dir, "dnscache.json") + if err := os.WriteFile(cachePath, []byte(`{"cache":`), 0o600); err != nil { + t.Fatal(err) + } + SetConfig(&config.Loaded{ + Path: filepath.Join(dir, "dnsplane.yaml"), + WritePath: filepath.Join(dir, "dnsplane.yaml"), + Config: config.Config{ + FileLocations: config.FileLocations{ + DNSServerFile: filepath.Join(dir, "dnsservers.json"), + CacheFile: cachePath, + RecordsSource: &config.RecordsSourceConfig{Type: config.RecordsSourceFile, Location: filepath.Join(dir, "dnsrecords.json")}, + }, + }, + }) + rec, err := LoadCacheRecords() + if err != nil { + t.Fatalf("corrupt cache should not error: %v", err) + } + if rec != nil && len(rec) != 0 { + t.Fatalf("expected nil or empty cache, got %d", len(rec)) + } +} diff --git a/data/data.go b/data/data.go index eaea9993..f56e75d9 100644 --- a/data/data.go +++ b/data/data.go @@ -5,11 +5,13 @@ package data import ( + "bytes" "dnsplane/adblock" "dnsplane/config" "dnsplane/dnsrecordcache" "dnsplane/dnsrecords" "dnsplane/dnsservers" + "dnsplane/internal/atomicfile" "encoding/json" "errors" "fmt" @@ -169,15 +171,19 @@ func (d *DNSResolverData) Initialize() error { servers, err := LoadDNSServers() if err != nil { - return fmt.Errorf("load dns servers: %w", err) + return fmt.Errorf("load dns servers from %s: %w", cfg.Config.FileLocations.DNSServerFile, err) } records, err := LoadDNSRecords() if err != nil { - return fmt.Errorf("load dns records: %w", err) + loc := "" + if rs := cfg.Config.FileLocations.RecordsSource; rs != nil { + loc = rs.Location + } + return fmt.Errorf("load dns records from %s: %w", loc, err) } cache, err := LoadCacheRecords() if err != nil { - return fmt.Errorf("load cache records: %w", err) + return fmt.Errorf("load cache records from %s: %w", cfg.Config.FileLocations.CacheFile, err) } d.DNSServers = servers @@ -502,20 +508,15 @@ func SaveToJSON[T any](filePath string, data T) error { // writeJSONFile writes JSON to path. indent=false avoids SetIndent for large machine-written files (e.g. dnscache.json). func writeJSONFile[T any](filePath string, data T, indent bool) error { - if err := os.MkdirAll(filepath.Dir(filePath), 0o750); err != nil { - return err - } - file, err := os.Create(filePath) // #nosec G304 -- path from operator/config - if err != nil { - return err - } - defer func() { _ = file.Close() }() - - encoder := json.NewEncoder(file) + var buf bytes.Buffer + encoder := json.NewEncoder(&buf) if indent { encoder.SetIndent("", " ") } - return encoder.Encode(data) + if err := encoder.Encode(data); err != nil { + return err + } + return atomicfile.Write(filePath, buf.Bytes(), 0o600) } // LoadDNSServers reads the dnsservers.json file and returns the list of DNS servers @@ -618,9 +619,15 @@ func LoadCacheRecords() ([]dnsrecordcache.CacheRecord, error) { Cache []dnsrecordcache.CacheRecord `json:"cache"` } paths := currentConfig().Config.FileLocations - cache, err := LoadFromJSON[cacheType](paths.CacheFile) + path := paths.CacheFile + cache, err := LoadFromJSON[cacheType](path) if err != nil { - return nil, err + if errors.Is(err, os.ErrNotExist) { + return nil, err + } + resolverSlog().Error("cache file unreadable or corrupt; starting with empty cache", "path", path, "error", err) + _, _ = fmt.Fprintf(os.Stderr, "dnsplane: cache file %s is corrupt (%v); starting with empty cache\n", path, err) + return nil, nil } return cache.Cache, nil } @@ -729,7 +736,7 @@ func CreateFileIfNotExists(filename, content string) { if err := os.MkdirAll(filepath.Dir(filename), 0o750); err != nil { fatalResolver("failed to create directory for data file", "path", filename, "error", err) } - if err := os.WriteFile(filename, []byte(content), 0o600); err != nil { + if err := atomicfile.Write(filename, []byte(content), 0o600); err != nil { fatalResolver("failed to create data file", "path", filename, "error", err) } } @@ -748,7 +755,7 @@ func LoadSettings() DNSResolverSettings { // SaveSettings saves the DNS server settings to the dnsplane.json file func SaveSettings(settings DNSResolverSettings) { info := currentConfig() - if err := config.Save(info.Path, settings); err != nil { + if err := config.Save(info.WriteConfigPath(), settings); err != nil { fatalResolver("failed to save settings", "error", err) } updateStoredConfig(info.Path, settings) diff --git a/data/resolver_log.go b/data/resolver_log.go index 4bf3b2ec..fd47bccf 100644 --- a/data/resolver_log.go +++ b/data/resolver_log.go @@ -4,6 +4,7 @@ package data import ( + "fmt" "log/slog" "os" "sync/atomic" @@ -25,6 +26,11 @@ func resolverSlog() *slog.Logger { } func fatalResolver(msg string, args ...any) { + _, _ = fmt.Fprintf(os.Stderr, "FATAL: %s", msg) + for i := 0; i+1 < len(args); i += 2 { + _, _ = fmt.Fprintf(os.Stderr, " %v=%v", args[i], args[i+1]) + } + _, _ = fmt.Fprintln(os.Stderr) resolverSlog().Error(msg, args...) os.Exit(1) } diff --git a/docs/config-files.md b/docs/config-files.md index 1b85a768..f9c546f0 100644 --- a/docs/config-files.md +++ b/docs/config-files.md @@ -1,6 +1,6 @@ # Config files and API reference -JSON data files, `dnsplane.json` keys, REST paths, and curl samples. For resolution order and the diagram see [resolution.md](resolution.md). For CLI paths and the TUI see [usage.md](usage.md). For logging options see [logging.md](logging.md). **RPM/Debian packages** and version strings (`BASE-SHORTSHA`): [packaging/README.md](../packaging/README.md). +`dnsplane.yaml` (canonical; `dnsplane.json` still loads with startup nags), JSON data files, REST paths, and curl samples. For resolution order and the diagram see [resolution.md](resolution.md). For CLI paths and the TUI see [usage.md](usage.md). For logging options see [logging.md](logging.md). **RPM/Debian packages** and version strings (`BASE-SHORTSHA`): [packaging/README.md](../packaging/README.md). ## Config Files @@ -9,7 +9,7 @@ JSON data files, `dnsplane.json` keys, REST paths, and curl samples. For resolut | dnsrecords.json | holds dns records | | dnsservers.json | holds the dns servers used for queries (see [Upstream servers and domain whitelist](#upstream-servers-dnsserversjson-and-domain-whitelist)) | | dnscache.json | Cached answers while still valid (TTL not expired), when caching is enabled | -| dnsplane.json | the app config | +| dnsplane.yaml | the app config (YAML; legacy `dnsplane.json` is migrated to YAML on first start; saves go to YAML) | Starter copies in the repo: **[examples/dnsplane-example.json](../examples/dnsplane-example.json)** and **[examples/dnsservers-example.json](../examples/dnsservers-example.json)** (point `file_locations.dnsservers` at your real path, e.g. `./dnsservers.json`). diff --git a/docs/usage.md b/docs/usage.md index 808ac310..d2a50143 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -41,15 +41,15 @@ The daemon keeps the resolver running, exposes a UNIX control socket for the TUI ## config and data file paths -When you do not pass any path flags, dnsplane looks for an existing `dnsplane.json` in the executable directory, then the user config dir (e.g. `~/.config/dnsplane/`), then `/etc/dnsplane.json`. If none is found, it creates the config and data files in the **current directory only** (never in `/etc` or elsewhere). You can override the config file and the JSON data files with server flags: +When you do not pass any path flags, dnsplane looks for `dnsplane.yaml` (then `dnsplane.yml`, then legacy `dnsplane.json`) in the executable directory, then `~/.config/dnsplane/`, then `/etc/dnsplane/`. If none is found, it creates YAML config and JSON data files in the **current directory only** (never in `/etc` or elsewhere). Legacy JSON-only configs are copied to YAML on startup; settings saves always write YAML. You can override paths with server flags: ```bash -./dnsplane server --config ./myconfig.json --dnsrecords ./records.json --cache ./cache.json --dnsservers ./servers.json +./dnsplane server --config ./myconfig.yaml --dnsrecords ./records.json --cache ./cache.json --dnsservers ./servers.json ``` | Flag | Purpose | | --- | --- | -| `--config` | Path to config file; if the file does not exist, a default config is created there (server only) | +| `--config` | Path to config file or directory; if missing, default `dnsplane.yaml` is created there (server only). Passing `dnsplane.json` still works but prefers YAML when both exist. | | `--dnsservers` | Path to dnsservers.json (overrides config) | | `--dnsrecords` | Path to dnsrecords.json (overrides config) | | `--cache` | Path to dnscache.json (overrides config) | diff --git a/go.mod b/go.mod index 5230f122..44eab5d0 100644 --- a/go.mod +++ b/go.mod @@ -38,4 +38,5 @@ require ( golang.org/x/net v0.57.0 // indirect golang.org/x/sys v0.49.0 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/internal/atomicfile/atomicfile.go b/internal/atomicfile/atomicfile.go new file mode 100644 index 00000000..d22c5b95 --- /dev/null +++ b/internal/atomicfile/atomicfile.go @@ -0,0 +1,59 @@ +// Copyright 2024-2026 George (earentir) Pantazis (https://earentir.dev) +// SPDX-License-Identifier: GPL-2.0-only + +// Package atomicfile writes file contents with temp+fsync+rename so the previous file survives a crash mid-write. +package atomicfile + +import ( + "fmt" + "os" + "path/filepath" +) + +// Write replaces path with data using a same-directory temp file, fsync, and atomic rename. +func Write(path string, data []byte, perm os.FileMode) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o750); err != nil { + return fmt.Errorf("atomicfile: mkdir %s: %w", dir, err) + } + tmp, err := os.CreateTemp(dir, "."+filepath.Base(path)+".") + if err != nil { + return fmt.Errorf("atomicfile: create temp in %s: %w", dir, err) + } + tmpName := tmp.Name() + cleanup := true + defer func() { + if cleanup { + _ = os.Remove(tmpName) + } + }() + if err := tmp.Chmod(perm); err != nil { + return fmt.Errorf("atomicfile: chmod temp: %w", err) + } + if _, err := tmp.Write(data); err != nil { + return fmt.Errorf("atomicfile: write temp: %w", err) + } + if err := tmp.Sync(); err != nil { + return fmt.Errorf("atomicfile: sync temp: %w", err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("atomicfile: close temp: %w", err) + } + if err := os.Rename(tmpName, path); err != nil { + return fmt.Errorf("atomicfile: rename %s -> %s: %w", tmpName, path, err) + } + cleanup = false + if err := syncDir(dir); err != nil { + return fmt.Errorf("atomicfile: sync dir %s: %w", dir, err) + } + return nil +} + +func syncDir(dir string) error { + d, err := os.Open(dir) // #nosec G304 -- directory from config path parent + if err != nil { + return err + } + defer func() { _ = d.Close() }() + return d.Sync() +} diff --git a/internal/atomicfile/atomicfile_test.go b/internal/atomicfile/atomicfile_test.go new file mode 100644 index 00000000..16ebc5c1 --- /dev/null +++ b/internal/atomicfile/atomicfile_test.go @@ -0,0 +1,38 @@ +// Copyright 2024-2026 George (earentir) Pantazis (https://earentir.dev) +// SPDX-License-Identifier: GPL-2.0-only + +package atomicfile + +import ( + "bytes" + "os" + "path/filepath" + "testing" +) + +func TestWriteReplacesContent(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "test.json") + orig := []byte(`{"cache":[]}`) + if err := Write(path, orig, 0o600); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, orig) { + t.Fatalf("content mismatch: %q", got) + } + next := []byte(`{"cache":[{"x":1}]}`) + if err := Write(path, next, 0o600); err != nil { + t.Fatal(err) + } + got, err = os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, next) { + t.Fatalf("after replace: %q", got) + } +} diff --git a/logger/logger.go b/logger/logger.go index c597c8c7..dbff85ca 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -3,6 +3,7 @@ package logger import ( + "context" "fmt" "io" "log/slog" @@ -17,6 +18,31 @@ import ( lj "gopkg.in/natefinch/lumberjack.v2" ) +// stderrTeeHandler duplicates Error and above to stderr while still writing through primary. +type stderrTeeHandler struct { + primary slog.Handler + stderr slog.Handler +} + +func (h *stderrTeeHandler) Enabled(ctx context.Context, level slog.Level) bool { + return h.primary.Enabled(ctx, level) || (level >= slog.LevelError && h.stderr.Enabled(ctx, level)) +} + +func (h *stderrTeeHandler) Handle(ctx context.Context, r slog.Record) error { + if r.Level >= slog.LevelError { + _ = h.stderr.Handle(ctx, r.Clone()) + } + return h.primary.Handle(ctx, r) +} + +func (h *stderrTeeHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return &stderrTeeHandler{primary: h.primary.WithAttrs(attrs), stderr: h.stderr} +} + +func (h *stderrTeeHandler) WithGroup(name string) slog.Handler { + return &stderrTeeHandler{primary: h.primary.WithGroup(name), stderr: h.stderr} +} + const defaultAsyncLogQueueSize = 10000 const ( @@ -150,9 +176,9 @@ func newFileWriter(logPath string, logCfg config.LogConfig) (io.Writer, error) { // If severity is "none", no files are created and all log output is discarded. // If the file cannot be created or written (and severity is not "none"), logs are written to stderr instead. func NewServerLogger(serviceLogName, logDir string, logCfg config.LogConfig) *slog.Logger { + stderrErr := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}) if isSeverityNone(logCfg.Severity) { - h := slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError + 1000}) - return slog.New(h) + return slog.New(stderrErr) } logPath := filepath.Join(logDir, serviceLogName) wr, err := newFileWriter(logPath, logCfg) @@ -161,7 +187,8 @@ func NewServerLogger(serviceLogName, logDir string, logCfg config.LogConfig) *sl wr = os.Stderr } level := levelFromSeverity(logCfg.Severity) - h := slog.NewTextHandler(wr, &slog.HandlerOptions{Level: level}) + primary := slog.NewTextHandler(wr, &slog.HandlerOptions{Level: level}) + h := &stderrTeeHandler{primary: primary, stderr: stderrErr} return slog.New(h) } diff --git a/logger/stderr_tee_test.go b/logger/stderr_tee_test.go new file mode 100644 index 00000000..a19a24f3 --- /dev/null +++ b/logger/stderr_tee_test.go @@ -0,0 +1,56 @@ +// Copyright 2024-2026 George (earentir) Pantazis (https://earentir.dev) +// SPDX-License-Identifier: GPL-2.0-only + +package logger + +import ( + "bytes" + "io" + "log/slog" + "os" + "sync" + "testing" + + "dnsplane/config" +) + +func TestNewServerLogger_SeverityNoneErrorsToStderr(t *testing.T) { + old := os.Stderr + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stderr = w + + var wg sync.WaitGroup + wg.Add(1) + buf := bytes.Buffer{} + go func() { + defer wg.Done() + _, _ = io.Copy(&buf, r) + }() + + log := NewServerLogger(DNSServerLog, t.TempDir(), config.LogConfig{Severity: "none"}) + log.Error("startup failed", "reason", "test") + + _ = w.Close() + os.Stderr = old + wg.Wait() + + if !bytes.Contains(buf.Bytes(), []byte("startup failed")) { + t.Fatalf("stderr missing error: %q", buf.Bytes()) + } +} + +func TestStderrTeeHandlerDuplicatesErrors(t *testing.T) { + var fileBuf bytes.Buffer + primary := slog.NewTextHandler(&fileBuf, &slog.HandlerOptions{Level: slog.LevelDebug}) + stderrErr := slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError}) + // use a real tee with stderr to pipe in integration test above; here only check primary gets info + log := slog.New(&stderrTeeHandler{primary: primary, stderr: stderrErr}) + log.Info("hello") + log.Error("boom") + if !bytes.Contains(fileBuf.Bytes(), []byte("boom")) { + t.Fatalf("primary should log error: %q", fileBuf.Bytes()) + } +} diff --git a/main.go b/main.go index 7be39f08..3b6d03f9 100644 --- a/main.go +++ b/main.go @@ -15,6 +15,11 @@ import ( "syscall" "time" + "github.com/chzyer/readline" + "github.com/inconshreveable/mousetrap" + tui "github.com/network-plane/planetui" + "github.com/spf13/cobra" + "dnsplane/api" "dnsplane/cluster" "dnsplane/commandhandler" @@ -26,11 +31,6 @@ import ( "dnsplane/logger" "dnsplane/ratelimit" "dnsplane/resolver" - - "github.com/chzyer/readline" - "github.com/inconshreveable/mousetrap" - tui "github.com/network-plane/planetui" - "github.com/spf13/cobra" ) const ( @@ -43,7 +43,7 @@ const ( ) // Default release string for normal builds; RPM/DEB may override with -ldflags "-X main.appVersion=..." (see packaging/version.sh). -var appVersion = "1.4.193" +var appVersion = "1.4.201" var ( appState = daemon.NewState() @@ -463,7 +463,7 @@ func runServer(cmd *cobra.Command, args []string) error { } clusterCtx, clusterCancel := context.WithCancel(context.Background()) - clusterMgr := cluster.NewManager(loadedCfg.Path, dnsData, dnsLogger) + clusterMgr := cluster.NewManager(loadedCfg.WriteConfigPath(), dnsData, dnsLogger) cluster.SetGlobalManager(clusterMgr) sCluster := dnsData.GetResolverSettings() if err := clusterMgr.Start(clusterCtx, sCluster); err != nil && dnsLogger != nil { diff --git a/systemd/dnsplane.service b/systemd/dnsplane.service index eda64d8c..2ebfd531 100644 --- a/systemd/dnsplane.service +++ b/systemd/dnsplane.service @@ -9,7 +9,7 @@ # 3. Add StateDirectory=dnsplane (creates /var/lib/dnsplane, owned by dnsplane) # 4. Use data paths under /var/lib/dnsplane so the service can write without root. # Example ExecStart for non-root (config in /etc, data in /var/lib/dnsplane): -# ExecStart=/usr/local/dnsplane/dnsplane server --config /etc/dnsplane/dnsplane.json --server-socket /run/dnsplane/dnsplane.socket --dnsservers /var/lib/dnsplane/dnsservers.json --dnsrecords /var/lib/dnsplane/dnsrecords.json --cache /var/lib/dnsplane/dnscache.json +# ExecStart=/usr/local/dnsplane/dnsplane server --config /etc/dnsplane/dnsplane.yaml --server-socket /run/dnsplane/dnsplane.socket --dnsservers /var/lib/dnsplane/dnsservers.json --dnsrecords /var/lib/dnsplane/dnsrecords.json --cache /var/lib/dnsplane/dnscache.json # Ensure /etc/dnsplane (and dnsplane.json) is readable by dnsplane. [Unit] @@ -21,7 +21,7 @@ Wants=network-online.target [Service] Type=simple RuntimeDirectory=dnsplane -ExecStart=/usr/local/dnsplane/dnsplane server --config /etc/dnsplane/dnsplane.json --server-socket /run/dnsplane/dnsplane.socket --dnsservers /etc/dnsplane/dnsservers.json --dnsrecords /etc/dnsplane/dnsrecords.json --cache /etc/dnsplane/dnscache.json +ExecStart=/usr/local/dnsplane/dnsplane server --config /etc/dnsplane/dnsplane.yaml --server-socket /run/dnsplane/dnsplane.socket --dnsservers /etc/dnsplane/dnsservers.json --dnsrecords /etc/dnsplane/dnsrecords.json --cache /etc/dnsplane/dnscache.json Restart=on-failure RestartSec=5 TimeoutStopSec=30 diff --git a/systemd/dnsplane.service.packaged b/systemd/dnsplane.service.packaged index f95af565..b17fe78b 100644 --- a/systemd/dnsplane.service.packaged +++ b/systemd/dnsplane.service.packaged @@ -15,7 +15,7 @@ Wants=network-online.target [Service] Type=simple RuntimeDirectory=dnsplane -ExecStart=/usr/bin/dnsplane server --config /etc/dnsplane/dnsplane.json --server-socket /run/dnsplane/dnsplane.socket --dnsservers /etc/dnsplane/dnsservers.json --dnsrecords /etc/dnsplane/dnsrecords.json --cache /etc/dnsplane/dnscache.json +ExecStart=/usr/bin/dnsplane server --config /etc/dnsplane/dnsplane.yaml --server-socket /run/dnsplane/dnsplane.socket --dnsservers /etc/dnsplane/dnsservers.json --dnsrecords /etc/dnsplane/dnsrecords.json --cache /etc/dnsplane/dnscache.json Restart=on-failure RestartSec=5 TimeoutStopSec=30