dnsconfig

package module
v0.0.0-...-d9705e4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 13 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

dnsconfig

A Go library for configuring system DNS on macOS and Windows. It routes queries to your nameservers through OS settings; your application supplies the resolver and keeps it reachable. dnsconfig does not resolve or forward queries itself.

API reference | Examples | Design notes | FAQ | Contributing

go get github.com/DefinedNet/dnsconfig

Requires Go 1.26 or newer. The public API may change before v1.0.

Platform Configuration mechanism
macOS Synthetic SCDynamicStore keys and owned /etc/resolver/ files.
Windows NRPT rules and DNS settings on a caller-controlled adapter.

Both support split DNS. Unsupported platforms refuse Set unless you explicitly select BackendNoop.

Quickstart: split DNS

Send corp.example and its subdomains to your resolver, leaving unrelated names with the host's DNS. SearchDomains adds short-name expansion; each search domain must equal or sit below a match domain in a split configuration.

Replace 192.0.2.53 with an already-running resolver. On Windows, replace myvpn0 with an existing adapter whose DNS settings you exclusively control; macOS ignores the adapter name. This excerpt matches the complete Go example.

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()

m, err := dnsconfig.New(ctx, dnsconfig.Options{
	Identity:        "myapp",
	Logger:          slog.New(slog.NewTextHandler(os.Stderr, nil)),
	InterfaceName:   "myvpn0",
	ShutdownTimeout: 10 * time.Second,
})
if err != nil {
	log.Print(err)
	return
}
defer func() {
	if err := m.Close(); err != nil {
		log.Printf("DNS cleanup incomplete; recover with Clear under this identity: %v", err)
	}
}()

cfg := dnsconfig.Config{
	Nameservers:   []netip.Addr{netip.MustParseAddr("192.0.2.53")},
	MatchDomains:  []string{"corp.example"},
	SearchDomains: []string{"corp.example"},
}
// Set records the goal; the Manager applies, retries, and repairs it in
// the background. Status reports progress.
if err := m.Set(cfg); err != nil {
	log.Print(err)
	return
}

// Keep the resolver and its network path available through DNS cleanup.
<-ctx.Done()

Applying and cleaning up

New starts a worker without changing DNS. Set records a complete configuration, then returns. The worker applies it, retries host failures, and repairs drift. Poll Status: Converged describes the latest installation check, and LastError reports failures. It does not test application queries.

  • Choose a stable Identity across restarts and distinct identities for independent instances. Exact domain or catch-all conflicts with another identity are refused before writes and retried. Unequal priority is not supported.
  • Set replaces its goal without merging or reordering nameservers. A zero Config is invalid. Use Clear to remove this identity's settings and wait for GoalClear and Converged before treating cleanup as complete. The error Close returns reports Close as a whole. After Close, Converged is false for a Set goal and reports whether the cleanup succeeded for a Clear goal.
  • Failed attempts do not roll back, so an error can accompany partial writes.
  • Call Close during shutdown. If cleanup fails, recover with a fresh Manager's Clear under the same identity. ShutdownTimeout sets the cancellation deadline for final cleanup, including the host-lock wait; synchronous Windows API calls can exceed it. It does not bound all of Close; zero selects DefaultShutdownTimeout. See the lifecycle examples.

Limits

  • Privileges: root is required on macOS. Windows consumers are expected to run as LocalSystem. Elevated Administrator operation falls back to a policy refresh that can leave removed rules effective after successful cleanup, so stopping the resolver can break DNS. See Windows execution requirements.
  • Roaming and captive portals: prefer split DNS. A catch-all needs a resolver that can answer every name and consumer-managed recovery when it becomes unreachable. dnsconfig does not discover upstreams or detect portal sign-in; on Windows, a catch-all exempts the default connectivity probe hosts so Windows can still detect a portal. See catch-all recovery.
  • Windows adapter ownership: the caller provides and controls the adapter. Cleanup clears its DNS settings without restoring older values. Global and policy search lists remain unchanged and may suppress adapter suffixes; short names can also depend on adapter preference.
  • Windows Group Policy: foreign policy can require using the policy NRPT store; rules then also keep a local copy that takes over when that policy leaves. Applying while a policy container exists requires a live policy watcher. Windows activates and removes policy rules on its own schedule, and valid rules remain installed while activation is uncertain. See Windows behavior.
  • Application resolvers: private resolvers and encrypted-DNS policy can bypass these settings.

See the documentation index for integration and testing guides.

License

MIT. See LICENSE.

Documentation

Overview

Package dnsconfig configures the operating system's DNS resolver on macOS and Windows. It does not resolve, forward, or cache DNS queries.

Configuration model

New selects the native backend unless Options specifies ForceBackend. macOS uses synthetic SCDynamicStore keys and owned /etc/resolver files; Windows uses NRPT rules and a caller-controlled adapter's DNS settings. Applying and removing configuration requires root on macOS. Windows consumers are expected to run as LocalSystem so Group Policy changes can be notified directly; elevated Administrator operation falls back to a full policy refresh; see "Convergence and repair". On macOS, New declines DNS management for a process that is not root: it logs one Info line through Options.Logger, Set returns ErrConfigurationDeclined, and Clear converges without touching the host. Status.LastError keeps that refusal for the Manager's life, so a converged Clear does not read as a verified clean host. On Windows, the first attempt that writes to the host logs a warning when the process is not LocalSystem or its identity cannot be checked; the attempt proceeds. The OS tools the backends invoke are resolved by absolute path and never through PATH. Unsupported platforms select BackendNoop, which refuses Manager.Set unless explicitly forced.

Config describes a replacement configuration. In split DNS, MatchDomains selects routed suffixes. Each SearchDomains entry must equal or be a subdomain of a MatchDomains entry. Empty MatchDomains selects catch-all routing and requires a nameserver that can answer every name, often a caller-run forwarder. Appending the host's nameservers does not compose namespaces: a negative answer can end resolution before another server is tried.

On Windows, every catch-all also publishes an NRPT exemption with no servers for the default Network Connectivity Status Indicator (NCSI) probe hosts. Their exact names use the interfaces' DNS instead of the catch-all. NCSI cannot detect a captive portal if its probe lookup fails, so an unreachable catch-all resolver would otherwise hide the portal. The exemption is always on, and the interfaces' resolvers see those lookups. A portal served from its own hostname still needs the catch-all removed or a forwarder that can reach the local network's DNS.

Ownership and lifecycle

Options requires an Identity that is stable across restarts and distinct for independent application instances. It scopes native artifacts and recovery. The caller owns the resolver, its network path, and, on Windows, the adapter's DNS settings. Keep them available until cleanup completes, including any resolver a replaced Config named, since a failed attempt can leave it configured. The library does not create interfaces or manage addresses, routes, or metrics.

New neither applies nor reverts DNS; it starts one worker goroutine per Manager. Manager.Set records a Config as the goal and Manager.Clear records removal of this identity's configuration, including a crashed predecessor's artifacts. Both return at once. The worker applies the latest goal, retries failures with backoff, and repairs drift while a Set goal is live. Manager.Status reports the goal and the worker's progress toward it. There is no completion barrier and no callback; poll Status.

Set returns only failures that retrying cannot fix: validation and platform-limit errors, ErrClosed, ErrConfigurationDeclined, and ErrInterfaceRequired. The host's answers, including ErrConflict and ErrManagerAlreadyRunning, appear in Status.LastError and are retried. A failed attempt does not roll back, so between attempts the host can hold parts of the previous and new configurations.

Manager.Close is the shutdown cleanup. It cancels an in-flight attempt, stops the worker, and, if a goal was recorded and no Clear converged since, attempts removal with a cancellation deadline of ShutdownTimeout, or DefaultShutdownTimeout when that is zero, before releasing resources. Synchronous Windows API calls can exceed that deadline; Close keeps the locks until cleanup returns. It is one-shot; a failed cleanup needs a fresh Manager's Clear. Recovery needs the same identity but no saved snapshot or Windows adapter name.

Methods are safe for concurrent use and none waits for a converge, except that Close waits for an in-flight attempt to return. The worker takes an OS-released identity lock before its first attempt and keeps it until a Clear converges or Close finishes; when a goal is still owed and the worker does not hold the lock, Close tries for it once without waiting. While another live Manager holds that identity, attempts report ErrManagerAlreadyRunning and Close leaves its configuration in place without returning an error for it. Each attempt runs under a host lock shared by every dnsconfig process, which serializes conflict checks with the writes they admit. New and Status take neither lock. The no-op backend takes no host locks.

Independent identities have equal standing. Claiming an exact routing domain or catch-all already published by another identity is refused with ErrConflict before mutation and retried, so ownership of a contended namespace goes to whichever identity publishes it first, with one macOS exception below: a later match domain takes routing for an exact domain that another identity only searches.

macOS also publishes every search domain as an exact routing domain. A match domain's resolver file answers that exact domain ahead of any search entry, so a search domain does not conflict with another identity's match domain. Two identities may both search a domain only when one of those two has it as a match domain; a third identity's match domain does not count.

Windows claims MatchDomains and the InterfaceName adapter. Parent/child suffixes are allowed; the DNS Client routes each name by its longest matching suffix.

Each identity normally removes only its own artifacts. On Windows, a Group Policy NRPT container holding only dnsconfig rules is retired by rename and removed whole when every peer's rule is unstaged and has an identical local copy. A peer's staged rule blocks retirement even if it has a local copy. The retiring identity's own rules, staged or not, never block retirement: they are its own to remove. If foreign rules or values arrive during retirement, a Set attempt fails and the next one places rules for that policy, while a Clear goes on removing its own rules. The retired key is restored unless a new container exists; then it is deleted with those foreign rules and values, with a Warn naming them.

Convergence and repair

Each attempt reads the host, writes only artifacts that differ from the goal, removes obsolete owned artifacts, and verifies installation. Matching artifacts with no owed side effects cause no writes, cache flushes, or policy notifications. On Windows, the first attempt with an adapter after taking the identity owes a reload and a subsequent cache flush even if values match: a predecessor may have exited between its adapter write and its reload.

Repair is another attempt at the current goal. While a Set goal is live, backend change signals trigger repair after a short debounce, and a periodic check covers losses the signals miss. While the worker is backing off after a failure, signals wait and the periodic check is skipped until the retry runs, with one exception: a signal can end backoff after a failed Set attempt that wrote no artifact. This includes conflicts and Windows attempts that find local rules in place behind an empty Group Policy NRPT container. No artifact write of ours can have raised that signal. A completed side effect can raise one, but is not repeated, so it can end backoff at most once. When repeat attempts keep rewriting the host, the worker paces signal-driven attempts and logs each rewrite.

Failed attempts retain owed cache flushes, adapter reloads, and policy notifications for retry. A failed adapter reload does not stop a Windows Clear from removing its rules, and once they are gone only a retry in the same process can finish the reload.

macOS signals come from a scutil notification child watching configd's DNS keys. Windows signals come from machine-policy notifications and registry change notifications on both NRPT stores and the controlled adapter.

Windows notifies Group Policy subscribers after an attempt changes Group Policy NRPT rules. LocalSystem uses GenerateGPNotification directly. Elevated Administrator callers fall back to RefreshPolicyEx, which requests a refresh of all machine policy. That request can succeed without delivering the change on a workgroup host or when a domain controller is unreachable. Removed rules can remain effective after Clear converges or Close returns nil, leaving DNS broken if the caller stops their resolver. A failed request is retried on backoff; an accepted one is not repeated. The worker's pacing is the only bound on how often repeat attempts request one.

Installed settings affect only queries that use the OS resolver; applications with private resolvers or encrypted-DNS policy can bypass them. Status reports the worker's bookkeeping, not live query results or effective-policy readback. macOS retains intact settings when another resolver takes precedence.

Change-signal source failures and Windows policy-delivery warnings are logged at Warn through Options.Logger. Converged and a nil Close confirm the library's artifact checks and accepted notification requests. Neither shows that the DNS Client has finished activating or removing the rules, even under LocalSystem. No fixed grace period makes the resolver safe to stop. Valid rules remain installed while activation is uncertain.

Global and policy search lists remain unchanged and may shadow adapter suffixes. Short-name resolution may also depend on caller-managed adapter preference.

Index

Examples

Constants

View Source
const DefaultShutdownTimeout = 15 * time.Second

DefaultShutdownTimeout is Close's final-cleanup cancellation budget when Options.ShutdownTimeout is zero. It exceeds the worker's attempt budget to allow time for cleanup after waiting behind a peer.

Variables

View Source
var (
	// ErrInterfaceRequired is returned by [Manager.Set] when the Windows
	// backend is selected and Options.InterfaceName is empty. Set records no
	// goal and also records the refusal in Status.LastError.
	ErrInterfaceRequired = errors.New("interface required for this backend")

	// ErrManagerAlreadyRunning reports, through Status.LastError, that
	// another live Manager, in this or another process, holds this
	// Options.Identity. From the worker it means the attempt changed nothing
	// and retries with backoff. After Close it means the final cleanup for a
	// recorded goal was not run because the holder's configuration stays;
	// Close itself does not return it.
	ErrManagerAlreadyRunning = errors.New("another Manager holds this identity")

	// ErrConflict reports, through Status.LastError, that another identity
	// already publishes one of the requested domains or a catch-all, or on
	// Windows records the Options.InterfaceName adapter. The attempt changed
	// nothing; for a domain or catch-all, errors.As yields a *ConflictError
	// naming it and the holder. The worker retries with backoff, so the goal
	// converges once the holder leaves.
	ErrConflict = backend.ErrConflict

	// ErrEmptyConfig is returned by Config.Validate (and so by Set) when the
	// Config is the zero value. Use Clear to remove managed configuration.
	ErrEmptyConfig = errors.New("dnsconfig: empty Config; call Clear to remove configuration")

	// ErrInvalidOptions is returned by Options.Validate, which New calls
	// first, and by New inside *Error when the forced backend is absent on
	// this OS.
	ErrInvalidOptions = errors.New("dnsconfig: invalid Options")

	// ErrClosed is returned by Set and Clear after Close.
	ErrClosed = errors.New("manager closed")

	// ErrGroupPolicyContainerEmpty reports, through Status.LastError, a
	// Windows Group Policy NRPT container with no rules or values. Its
	// presence makes the DNS Client ignore the local NRPT table, and nothing
	// attributes it to dnsconfig, so it is left in place. Each Set attempt
	// keeps the local copies written and fails with this error, or fails
	// before writing when Group Policy cannot be monitored. The goal
	// converges once the key is removed; after a manual deletion, reboot so
	// the DNS Client drops its cached policy table.
	ErrGroupPolicyContainerEmpty = backend.ErrGroupPolicyContainerEmpty

	// ErrConfigurationDeclined is returned by Set when the active backend
	// applies nothing and the caller did not ask for that. Detection answers
	// BackendNoop on unsupported platforms, and New declines the macOS backend
	// for a process that is not root, since every write it would attempt
	// needs root. A declined macOS Manager names BackendDarwin in its errors,
	// its refusal says why, and its Clear converges without touching the host or
	// taking locks. Set records no goal. Status.LastError holds this error
	// from New on and LastConvergedCleared stays false, since a converged
	// Clear checked nothing. Explicitly selecting BackendNoop
	// through Options.ForceBackend permits a goal that converges without
	// touching the host.
	//
	// Retrying on the same Manager cannot change this condition.
	ErrConfigurationDeclined = errors.New("backend applies no DNS configuration")
)

Sentinel errors. Library callers should compare with errors.Is rather than equality so wrapping via *Error works. Sentinels that backends also report are defined once in the backend contract and re-exported here.

Functions

func ValidateIdentity

func ValidateIdentity(s string) error

ValidateIdentity reports whether s is an acceptable Options.Identity: 1 to 63 characters of lowercase letters, digits, '.', '_', or '-', starting with a letter or digit.

Types

type BackendKind

type BackendKind string

BackendKind names a DNS-configuration backend. The zero value, BackendAuto, requests detection.

const (
	// BackendAuto is the zero value; it requests backend detection.
	BackendAuto BackendKind = ""
	// BackendDarwin uses /etc/resolver files and SCDynamicStore keys on macOS.
	BackendDarwin BackendKind = "darwin"
	// BackendWindows uses NRPT rules and controlled-adapter DNS settings on Windows.
	BackendWindows BackendKind = "windows"
	// BackendNoop applies nothing. Detection selects it on unsupported platforms,
	// where Set returns ErrConfigurationDeclined. Explicitly forcing it permits
	// Set goals that converge without touching the host.
	BackendNoop BackendKind = "noop"
)

func Detect

func Detect() BackendKind

Detect reports the native backend without initializing it. It returns BackendDarwin on macOS, BackendWindows on Windows, and BackendNoop on unsupported platforms. New uses this backend unless Options.ForceBackend is set.

func (BackendKind) IsValid

func (k BackendKind) IsValid() bool

IsValid reports whether k is one of the declared BackendKind constants. It says nothing about whether that backend exists on the current OS or can be initialized; New answers those.

type Config

type Config struct {
	// Nameservers is the list of DNS server addresses queries should be
	// sent to. Must be non-empty for a non-zero Config.
	//
	// The list is applied in order and is not deduplicated. [Manager.Set]
	// rejects a list that exceeds the OS mechanism's hard limit; it never
	// silently truncates. macOS split DNS accepts at most three nameservers. Entries are IP addresses
	// without ports; a non-53 upstream port requires a caller-provided forwarder
	// on port 53.
	//
	// Unspecified (0.0.0.0, ::), multicast, and limited broadcast
	// (255.255.255.255) addresses are rejected, including their IPv4-mapped
	// IPv6 forms.
	//
	// IPv6 link-local addresses may carry a zone (e.g. fe80::1%en0).
	// macOS preserves it; Windows rejects it because NRPT scoped-address
	// support is undocumented.
	Nameservers []netip.Addr

	// SearchDomains is the list of domain suffixes appended to single-label
	// names during resolution. May be empty; entries must not be the root
	// domain. Entries keep their configured order. In a split configuration
	// each entry must sit under a MatchDomains entry.
	//
	// macOS publishes every entry, in configured order, in one dynamic-store
	// key ahead of the primary service's search domains, so requested
	// suffixes take precedence for short names; the relative order of
	// different identities' suffixes is unspecified. [Manager.Set] rejects a
	// list that does not fit one scutil command line (2047 bytes, at most 99
	// entries). An
	// entry the primary service lists in the same spelling moves to the
	// front; one it lists in a different case appears twice; its other
	// domains keep their order. Each entry also routes that exact domain to
	// Nameservers unless an identity's MatchDomains entry for that exact
	// domain exists, since the resolver file wins over every search entry.
	// Another identity's search entry for it causes [ErrConflict] unless
	// this identity or that one has it in MatchDomains; then the two share
	// the suffix, which appears once in the search list. As an exact domain it can outrank another
	// resolver more specific than MatchDomains or a catch-all. [Manager.Clear] removes what this identity published. Windows
	// sets suffixes on the controlled adapter and allows the same suffix on
	// other identities' adapters; routing comes from MatchDomains alone. Global
	// and policy search lists remain unchanged and can suppress adapter suffixes.
	SearchDomains []string

	// MatchDomains, when non-empty, requests split DNS: queries whose names
	// end in one of these suffixes route to Nameservers. Empty MatchDomains
	// means Nameservers handles everything (catch-all). Entries must not be
	// the root domain; express catch-all with an empty list.
	//
	// Reverse-lookup zones belong here too. A split configuration listing
	// only forward suffixes sends PTR queries to the host's other resolvers,
	// potentially disclosing private addresses. List the covering zones
	// alongside the forward suffixes: "2.0.192.in-addr.arpa." for
	// 192.0.2.0/24, "8.b.d.0.1.0.0.2.ip6.arpa." for 2001:db8::/32. Name the
	// zone that covers the prefix, not the whole "in-addr.arpa." or
	// "ip6.arpa." tree, which would capture every reverse lookup on the host.
	MatchDomains []string
}

Config is the DNS configuration a caller asks the OS to apply.

Manager.Set makes it the goal the Manager converges the host toward. Static per-name host overrides are outside this API.

Domains are case-insensitive and may omit the trailing dot: "Corp.Example" and "corp.example." name the same domain. Labels may contain ASCII letters, digits, hyphens, and underscores. Configs that Manager.Set accepts and Status reports back use the canonical form, lowercase with a trailing dot.

func (Config) Equal

func (c Config) Equal(other Config) bool

Equal reports whether c and other hold the same nameservers, search domains, and match domains in the same order. Domains compare in canonical form, so case and a trailing dot do not matter. Order matters because Set neither deduplicates nor reorders. Addresses compare as given, so an IPv4-mapped IPv6 address differs from its IPv4 form although Set installs both the same way.

func (Config) IsSplit

func (c Config) IsSplit() bool

IsSplit reports whether c requests split DNS (non-empty MatchDomains).

func (Config) IsZero

func (c Config) IsZero() bool

IsZero reports whether c is the zero value (no nameservers, no domains). A zero Config is rejected by Validate with ErrEmptyConfig: it is not a request to revert. Callers remove configuration with Manager.Clear.

func (Config) Validate

func (c Config) Validate() error

Validate reports whether c is internally consistent. It does not check whether c can be applied by any particular backend; Manager.Set also checks the platform's limits before recording c as its goal.

Each domain must be a valid name, neither list may contain the root domain or the same domain twice in any spelling, and in a split configuration each search domain must equal or sit under a MatchDomains entry. Validate does not modify c.

type ConflictError

type ConflictError = backend.ConflictError

ConflictError reports, inside Status.LastError, that another identity already publishes a requested domain. Domain is that domain in canonical form, lowercase with a trailing dot, or "." for a catch-all; Holder is the identity. It matches ErrConflict through errors.Is.

type Error

type Error struct {
	// Op names the operation: "New", "Set", "Clear", or "Close", or
	// "Converge" for a worker attempt recorded in Status.LastError.
	Op string
	// Backend identifies the selected backend, or is empty before selection.
	Backend BackendKind
	// Err is the underlying cause.
	Err error
}

Error is the structured error type returned by Manager operations. Use errors.Is to compare against sentinels; use errors.As to inspect Op and Backend.

func (*Error) Error

func (e *Error) Error() string

Error describes the failed operation and its cause.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause.

type Goal

type Goal string

Goal names what a Manager's worker is converging the host toward.

const (
	// GoalNone means neither Set nor Clear has been called.
	GoalNone Goal = ""
	// GoalSet means the worker installs and repairs Status.Desired.
	GoalSet Goal = "set"
	// GoalClear means the worker removes this identity's configuration.
	GoalClear Goal = "clear"
)

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager owns one application instance's DNS configuration and resources. Construct one with New, record a goal with Manager.Set or Manager.Clear, observe progress through Manager.Status, and call Manager.Close when done.

A Manager runs one worker goroutine for goals and retries. Close joins it before final cleanup. All methods are safe for concurrent use. Set, Clear, and Status do not wait for a converge to finish.

func New

func New(ctx context.Context, opts Options) (*Manager, error)

New constructs a Manager and starts its worker without applying or reverting DNS configuration. It validates opts, selects the native backend unless ForceBackend is set, and initializes that backend. ctx bounds construction only; Close uses ShutdownTimeout, or DefaultShutdownTimeout when it is zero.

Invalid Options are returned as-is. Construction failures are wrapped in *Error, with ErrInvalidOptions for a backend absent on this OS. No backend touches the host at construction or needs Options.InterfaceName; Windows checks it at Set. A host this process cannot manage, such as macOS without root, gets a declined Manager instead of an error; see ErrConfigurationDeclined.

func (*Manager) Clear

func (m *Manager) Clear() error

Clear records removal of this identity's DNS configuration as the goal and returns without waiting. The worker removes discoverable artifacts, including a crashed predecessor's, and completes owed cache flushes, Windows adapter reloads, and policy notifications, retrying with backoff until an attempt succeeds, which leaves nothing pending. Once the Clear converges, the worker releases the identity lock so another Manager can use the identity; Status.Goal is GoalClear and Status.Converged is true.

macOS discovers prefixed State keys and owned resolver and staging files. Windows discovers NRPT records naming the controlled adapter's GUID, so recovery does not need InterfaceName or a saved snapshot, and clears that adapter's DNS values rather than restoring older ones. Discovering nothing attributable is a successful Clear, so a setting whose ownership evidence was lost stays in place. A Manager that declined DNS management converges a Clear without touching the host; Status keeps ErrConfigurationDeclined in LastError and LastConvergedCleared false.

Clear returns ErrClosed after Close and otherwise nil. Calling it while Clear is already the goal is a no-op.

Example (Recovery)

A recovery process uses the predecessor's identity. Windows discovers the adapter from recovery records, so InterfaceName is unnecessary here.

package main

import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/DefinedNet/dnsconfig"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	m, err := dnsconfig.New(ctx, dnsconfig.Options{
		Identity:        "myapp",
		ShutdownTimeout: 10 * time.Second,
	})
	if err != nil {
		log.Print(err)
		return
	}
	defer func() {
		if err := m.Close(); err != nil {
			log.Printf("DNS cleanup remains incomplete: %v", err)
		}
	}()

	if err := m.Clear(); err != nil {
		log.Print(err)
		return
	}
	ticker := time.NewTicker(250 * time.Millisecond)
	defer ticker.Stop()
	for {
		s := m.Status()
		switch {
		case errors.Is(s.LastError, dnsconfig.ErrConfigurationDeclined):
			log.Printf("DNS management declined; nothing was checked: %v", s.LastError)
			return
		case s.Converged && s.LastChangedAt.IsZero():
			log.Print("no DNS configuration attributable to myapp was found")
			return
		case s.Converged:
			log.Print("managed DNS configuration removed")
			return
		case errors.Is(s.LastError, dnsconfig.ErrManagerAlreadyRunning):
			log.Print("myapp is still running; leave its DNS configuration in place")
			return
		}
		select {
		case <-ctx.Done():
			log.Printf("DNS recovery incomplete; keep the resolver available and retry: %v", s.LastError)
			return
		case <-ticker.C:
		}
	}
}

func (*Manager) Close

func (m *Manager) Close() error

Close stops the worker, removes this identity's DNS configuration, and releases backend resources and the identity lock. Cleanup, teardown, and lock failures are joined in an Error with Op "Close" and recorded in Status.LastError. Cleanup that still owes a cache flush, adapter reload, or policy notification is a failure too.

Close cancels an in-flight attempt and waits for the worker to exit. If a goal was recorded and no Clear converged since, Close then makes one final Clear under the host lock. The worker holds the identity lock from its first attempt at a goal until a Clear converges; when it does not hold the lock, because it never attempted the goal or every attempt failed to take it, Close takes the lock itself without waiting. While another live Manager holds the identity, Close changes nothing and does not report it: that holder's configuration is meant to stay, so no recovery is needed. Teardown failures are still returned. Status.LastError then includes ErrManagerAlreadyRunning and Converged stays false. Like Manager.Clear, the cleanup removes every artifact attributable to the identity. A Manager that was never given a goal changes nothing.

Close is one-shot: the first call returns any cleanup error; later calls do nothing and return nil. Manager.Status remains callable. Recover a failed cleanup with a fresh New followed by Clear. The identity lock is released after backend teardown even when cleanup fails, so that Manager can recover.

Options.ShutdownTimeout, or DefaultShutdownTimeout when it is zero, sets the cancellation deadline for the host-wide lock wait and final cleanup together. Lock waits and subprocesses observe cancellation. Windows cleanup checks cancellation between operations, but cannot interrupt a synchronous API call. It finishes the empty-container check after deleting policy rules and requests any owed policy notification even after cancellation. Close keeps the locks until cleanup returns. The deadline does not bound waiting for the canceled worker to return or resource teardown. Keep the resolver and its network path available until Close returns. The package documentation describes what a nil error means on Windows, where consumers are expected to run as LocalSystem.

func (*Manager) Set

func (m *Manager) Set(cfg Config) error

Set records cfg as this Manager's goal and returns without waiting for the host to change. The worker converges toward it, retries failures, and repairs drift until another goal replaces it or Close. Observe progress through Manager.Status; Set provides no completion barrier. Nameserver ordering, split routing, and search-domain behavior are defined by Config.

Set returns only failures that retrying cannot fix. Config.Validate errors, including ErrEmptyConfig for a zero Config, and a config that exceeds a limit of the platform's DNS mechanism, judged from the Config alone, are returned directly without an Error wrapper. The other refusals record no goal: ErrClosed after Close, ErrConfigurationDeclined when detection selected the no-op backend or the process lacks the privilege the backend needs, and ErrInterfaceRequired on Windows without Options.InterfaceName. The last two are also recorded in Status.LastError.

Everything the host decides is reported through Status.LastError and retried with backoff, including ErrConflict and ErrManagerAlreadyRunning. A failed attempt does not roll back what it wrote, so the host can hold parts of the previous and new configurations until an attempt succeeds.

A cfg Config.Equal to the current goal is a no-op: it neither restarts backoff nor starts an attempt.

Example (SplitDNS)

This example assumes the resolver is already serving and the application owns the existing myvpn0 adapter's DNS settings. It runs until interrupted.

package main

import (
	"context"
	"log"
	"log/slog"
	"net/netip"
	"os"
	"os/signal"
	"time"

	"github.com/DefinedNet/dnsconfig"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	m, err := dnsconfig.New(ctx, dnsconfig.Options{
		Identity:        "myapp",
		Logger:          slog.New(slog.NewTextHandler(os.Stderr, nil)),
		InterfaceName:   "myvpn0",
		ShutdownTimeout: 10 * time.Second,
	})
	if err != nil {
		log.Print(err)
		return
	}
	defer func() {
		if err := m.Close(); err != nil {
			log.Printf("DNS cleanup incomplete; recover with Clear under this identity: %v", err)
		}
	}()

	cfg := dnsconfig.Config{
		Nameservers:   []netip.Addr{netip.MustParseAddr("192.0.2.53")},
		MatchDomains:  []string{"corp.example"},
		SearchDomains: []string{"corp.example"},
	}
	// Set records the goal; the Manager applies, retries, and repairs it in
	// the background. Status reports progress.
	if err := m.Set(cfg); err != nil {
		log.Print(err)
		return
	}

	// Keep the resolver and its network path available through DNS cleanup.
	<-ctx.Done()
}

func (*Manager) Status

func (m *Manager) Status() Status

Status returns a snapshot of the Manager's goal and the worker's progress toward it. It never waits for an in-flight converge and never probes the OS. The returned value is a copy.

Example

Set returns only failures that retrying cannot fix. Everything the host decides, such as another identity holding the namespace, appears in Status and is retried. In an application, retain the Manager for its lifetime.

package main

import (
	"context"
	"errors"
	"log"
	"net/netip"
	"time"

	"github.com/DefinedNet/dnsconfig"
)

func main() {
	ctx := context.Background()
	m, err := dnsconfig.New(ctx, dnsconfig.Options{
		Identity:        "myapp",
		InterfaceName:   "myvpn0",
		ShutdownTimeout: 10 * time.Second,
	})
	if err != nil {
		log.Print(err)
		return
	}
	defer m.Close()

	cfg := dnsconfig.Config{
		Nameservers:  []netip.Addr{netip.MustParseAddr("192.0.2.53")},
		MatchDomains: []string{"corp.example"},
	}
	if err := m.Set(cfg); err != nil {
		log.Printf("DNS configuration refused: %v", err)
		return
	}

	time.Sleep(5 * time.Second)
	s := m.Status()
	var conflict *dnsconfig.ConflictError
	switch {
	case s.Converged:
		log.Print("DNS configuration installed")
	case errors.As(s.LastError, &conflict):
		log.Printf("%s is held by %s; retrying until it leaves", conflict.Domain, conflict.Holder)
	case s.LastError != nil:
		log.Printf("attempt failed, possibly after partial changes; retrying: %v", s.LastError)
	default:
		log.Print("first attempt still running")
	}
}

type Options

type Options struct {
	// Identity is required and names the application instance that owns this
	// Manager's DNS artifacts, so Clear and Close remove only its work. Reuse
	// it across restarts and give independent instances different identities.
	// It must pass [ValidateIdentity], which rejects uppercase.
	Identity string

	// Logger is the slog logger used for warnings and debug output.
	// Nil discards output independently of slog.Default(). The library logs
	// while holding internal locks, so the handler must not call back into
	// the Manager.
	Logger *slog.Logger

	// ForceBackend selects a specific backend; the zero value requests
	// detection. New never falls back to a different backend: an undeclared
	// kind fails Validate, and a kind with no implementation on this OS fails
	// New with ErrInvalidOptions. The exception is a declined host, such as
	// BackendDarwin in a process that is not root, which gets a Manager that
	// refuses Set with [ErrConfigurationDeclined]. See [BackendNoop] for
	// forcing the no-op one.
	ForceBackend BackendKind

	// InterfaceName is the friendly name of a Windows adapter, such as a
	// tunnel adapter, whose DNS settings the caller controls through cleanup.
	// Windows Set requires it. It is resolved to the adapter's GUID at each
	// converge, so a recreated adapter needs no new Manager but a renamed one
	// does. An adapter belongs to one identity at a time: another identity's
	// Set naming it is refused with [ErrConflict] until that identity clears.
	// Turn off its dynamic DNS registration with RegistrationEnabled=0,
	// DisableDynamicUpdate=1, and MaxNumberOfAddressesToRegister=0 under both
	// its Tcpip and Tcpip6 interface keys. The darwin and noop backends
	// ignore it.
	InterfaceName string

	// ShutdownTimeout sets the cancellation deadline for Close's final cleanup,
	// including the host-wide lock wait. Synchronous Windows API calls can
	// exceed the deadline. Zero selects [DefaultShutdownTimeout]; a negative
	// value fails Validate. [Manager.Close] describes cancellation and teardown.
	ShutdownTimeout time.Duration
}

Options configures a Manager. Identity is required; other zero values select the native backend and discard log output. Windows Set requires InterfaceName. Options are fixed for a Manager's life; changing them requires a new Manager.

func (Options) Validate

func (o Options) Validate() error

Validate reports ErrInvalidOptions for an unknown ForceBackend, an invalid or missing Identity, or a negative ShutdownTimeout. New calls it before initializing the backend.

type Status

type Status struct {
	// Goal is the most recent goal the caller recorded with Set or Clear.
	Goal Goal

	// Desired is the configuration the worker converges toward when Goal is
	// GoalSet, and the zero Config otherwise. Close leaves Goal and Desired
	// as recorded.
	Desired Config

	// Converged reports that the most recent attempt at the current goal
	// passed its artifact checks and completed every owed side-effect
	// request, and no newer goal has been recorded since. A declined
	// Manager checks nothing; see LastError. Later drift is
	// found by a change signal or periodic check. Close's final cleanup,
	// when it runs, counts as an attempt: afterwards Converged is false for
	// a Set goal and reports whether that cleanup succeeded for a Clear goal.
	Converged bool

	// LastError is the failure of the most recent attempt, as an [Error] with
	// Op "Converge", or of Close, or a Set refusal that Set also returned.
	// After a Close that left a live holder's configuration in place it
	// includes [ErrManagerAlreadyRunning] with Op "Close", which Close
	// itself does not return. It is nil after a successful attempt, except
	// on a Manager that declined DNS management: from New on it holds
	// [ErrConfigurationDeclined], as Op "New" or a Set refusal, because
	// nothing on the host was checked. errors.Is and errors.As reach the
	// cause.
	// Before Close the worker retries a failed attempt with backoff; Set
	// refusals and Close's failure are not retried.
	LastError error

	// LastChangedAt is when an attempt last changed or may have changed the
	// host, including a partially failed write, or zero if none has. A change
	// after the goal had converged means something else undid this Manager's
	// configuration.
	LastChangedAt time.Time

	// LastConvergedCleared reports that the most recent successful attempt,
	// including Close's final cleanup, was a Clear. It is false before any
	// attempt succeeds and always false on a Manager that declined DNS
	// management, which removes nothing.
	LastConvergedCleared bool
}

Status is a snapshot of a Manager's goal and its worker's progress toward it. Reading it neither probes the OS nor waits for an in-flight converge, so it can lag the host by one attempt.

Status has no per-request completion barrier: a converge records what it achieved, not which Set asked for it.

Directories

Path Synopsis
internal
backend
Package backend defines the contract between the dnsconfig.Manager worker and the per-OS backends it drives.
Package backend defines the contract between the dnsconfig.Manager worker and the per-OS backends it drives.
backend/backendtest
Package backendtest checks the shared converge contract of backend.Backend implementations using backend-specific fakes.
Package backendtest checks the shared converge contract of backend.Backend implementations using backend-specific fakes.
backend/darwin
Package darwin implements the dnsconfig backend for macOS.
Package darwin implements the dnsconfig backend for macOS.
backend/noop
Package noop is the fallback backend used on unsupported platforms or when explicitly requested by a caller.
Package noop is the fallback backend used on unsupported platforms or when explicitly requested by a caller.
backend/windows
Package windows implements the dnsconfig backend for Windows.
Package windows implements the dnsconfig backend for Windows.
cmd/dnsconfigctl command
Command dnsconfigctl is test scaffolding that exercises the dnsconfig library for the smoke-test harness and diagnostic probe scripts.
Command dnsconfigctl is test scaffolding that exercises the dnsconfig library for the smoke-test harness and diagnostic probe scripts.
cmd/smoketest command
Command smoketest runs macOS and Windows DNS smoke scenarios on the host.
Command smoketest runs macOS and Windows DNS smoke scenarios on the host.
hostlock
Package hostlock provides named advisory locks shared by every process on a host and released by the operating system when the holder exits.
Package hostlock provides named advisory locks shared by every process on a host and released by the operating system when the holder exits.
runner
Package runner abstracts backend subprocess execution for testability.
Package runner abstracts backend subprocess execution for testability.
runner/runnertest
Package runnertest provides a recording fake runner.Runner for backend tests.
Package runnertest provides a recording fake runner.Runner for backend tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL