The job store is to keep its database in the directory that holds the ntfy subscriptions' state files, so the directory moves to a section of its own: [state] dir, or UBERBRINGER_STATE_DIR, in place of [ntfy] state_dir. For now only the subscriptions use it. It still has no default and is still required with a subscription, and the checks at start name state.dir in their errors. install.sh writes [state] dir into new configs, and the Docker image sets UBERBRINGER_STATE_DIR. ntfy.state_dir has never been in a release, so its CHANGELOG entry changes in place and there is no fallback: a config that still sets it fails to load with an unknown key until the line moves to [state]. The image itself was not built, since the workstation has no Docker. Part of stage 1b of docs/plans/job-store.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1122 lines
39 KiB
Go
1122 lines
39 KiB
Go
// Package config loads and validates the Überbringer daemon configuration
|
|
// from a TOML file and UBERBRINGER_* environment variables.
|
|
package config
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"net/netip"
|
|
"net/url"
|
|
"os"
|
|
"reflect"
|
|
"regexp"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/go-viper/mapstructure/v2"
|
|
"github.com/pelletier/go-toml/v2"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
// EnvPrefix starts the environment variables that set config keys: a key
|
|
// section.name is read from UBERBRINGER_SECTION_NAME, e.g.
|
|
// UBERBRINGER_PRINTER_ADDRESS. An environment variable wins over the file.
|
|
const EnvPrefix = "UBERBRINGER"
|
|
|
|
// MinSecretLength is the minimum API secret length in bytes. HS256 keys
|
|
// shorter than the 256-bit hash output weaken the signature (RFC 7518 §3.2).
|
|
const MinSecretLength = 32
|
|
|
|
// MaxLineSpacing is the largest printer.box_line_spacing, the most ESC 3
|
|
// takes.
|
|
const MaxLineSpacing = 255
|
|
|
|
// MaxCutFeed is the largest printer.cut_feed, the most ESC d feeds at once.
|
|
const MaxCutFeed = 255
|
|
|
|
// Log formats accepted by [LogConfig.Format].
|
|
const (
|
|
LogFormatText = "text"
|
|
LogFormatJSON = "json"
|
|
)
|
|
|
|
// Config is the root daemon configuration.
|
|
type Config struct {
|
|
WebServer WebServerConfig `mapstructure:"webserver"`
|
|
API APIConfig `mapstructure:"api"`
|
|
Printer PrinterConfig `mapstructure:"printer"`
|
|
Format FormatConfig `mapstructure:"format"`
|
|
Ntfy NtfyConfig `mapstructure:"ntfy"`
|
|
Queue QueueConfig `mapstructure:"queue"`
|
|
State StateConfig `mapstructure:"state"`
|
|
Images ImagesConfig `mapstructure:"images"`
|
|
Sentry SentryConfig `mapstructure:"sentry"`
|
|
Log LogConfig `mapstructure:"log"`
|
|
}
|
|
|
|
// WebServerConfig configures the HTTP listener.
|
|
type WebServerConfig struct {
|
|
BindIP string `mapstructure:"bind_ip"`
|
|
Port int `mapstructure:"port"`
|
|
|
|
// RateLimit is the number of API requests one client may make per
|
|
// RateWindow.
|
|
RateLimit int `mapstructure:"rate_limit"`
|
|
RateWindow time.Duration `mapstructure:"rate_window"`
|
|
|
|
// TrustedProxies lists proxy IPs or CIDR ranges whose ProxyHeader is
|
|
// trusted to carry the real client IP.
|
|
TrustedProxies []string `mapstructure:"trusted_proxies"`
|
|
ProxyHeader string `mapstructure:"proxy_header"`
|
|
|
|
// BodyLimit is the maximum request body size in bytes.
|
|
BodyLimit int `mapstructure:"body_limit"`
|
|
|
|
ReadTimeout time.Duration `mapstructure:"read_timeout"`
|
|
WriteTimeout time.Duration `mapstructure:"write_timeout"`
|
|
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
|
|
}
|
|
|
|
// APIConfig configures API authentication.
|
|
type APIConfig struct {
|
|
// Secret is the HS256 key used to verify bearer tokens.
|
|
Secret string `mapstructure:"secret"`
|
|
}
|
|
|
|
// PrinterConfig configures the network receipt printer.
|
|
type PrinterConfig struct {
|
|
Address string `mapstructure:"address"`
|
|
Port int `mapstructure:"port"`
|
|
|
|
// Model selects a printer profile, e.g. "tm-t88" or "generic-58mm".
|
|
Model string `mapstructure:"model"`
|
|
|
|
// CodePage is the character table text is transcoded to, e.g. "cp437".
|
|
CodePage string `mapstructure:"codepage"`
|
|
|
|
// PaperWidth overrides the profile's printable width in dots. Zero keeps
|
|
// the profile default.
|
|
PaperWidth int `mapstructure:"paper_width"`
|
|
|
|
// Columns overrides the number of Font A characters per line used for
|
|
// word wrapping. Zero derives it from the paper width.
|
|
Columns int `mapstructure:"columns"`
|
|
|
|
// BoxLineSpacing is the line spacing, in motion units (ESC 3), used
|
|
// while a box prints, to close the gaps in its vertical borders. Zero
|
|
// keeps the printer's default spacing.
|
|
BoxLineSpacing int `mapstructure:"box_line_spacing"`
|
|
|
|
// CutFeed is how many blank lines feed before each cut, so that the
|
|
// last printed line does not sit right at the cut.
|
|
CutFeed int `mapstructure:"cut_feed"`
|
|
|
|
DialTimeout time.Duration `mapstructure:"dial_timeout"`
|
|
WriteTimeout time.Duration `mapstructure:"write_timeout"`
|
|
|
|
// Retries is how many times a failed send is retried before the job is
|
|
// marked failed.
|
|
Retries int `mapstructure:"retries"`
|
|
RetryDelay time.Duration `mapstructure:"retry_delay"`
|
|
}
|
|
|
|
// FormatConfig configures how receipts are laid out.
|
|
type FormatConfig struct {
|
|
// MaxLines fails a job that would print more lines, all copies
|
|
// counted. It is a backstop against runaway text.
|
|
MaxLines int `mapstructure:"max_lines"`
|
|
|
|
// Timezone is the zone the times modules print are in: an IANA name
|
|
// such as "Europe/London", "UTC", or "Local" for the host's zone.
|
|
Timezone string `mapstructure:"timezone"`
|
|
|
|
// TimeLayout is the Go time layout those times are printed in.
|
|
TimeLayout string `mapstructure:"time_layout"`
|
|
}
|
|
|
|
// Values of the ntfy settings.
|
|
var (
|
|
NtfyStyles = []string{"auto", "box", "compact"}
|
|
NtfyQRModes = []string{"all", "first", "none"}
|
|
NtfyUpdateModes = []string{"print", "skip"}
|
|
NtfyQuietActions = []string{"digest", "drop"}
|
|
NtfyDays = []string{"mon", "tue", "wed", "thu", "fri", "sat", "sun"}
|
|
)
|
|
|
|
// Limits of the ntfy settings.
|
|
const (
|
|
// MaxNtfyLines is the largest ntfy.format.max_lines.
|
|
MaxNtfyLines = 400
|
|
|
|
// MaxMarker is the most characters in a marker.
|
|
MaxMarker = 16
|
|
|
|
// MaxNtfyTopics is how many topics one subscription may name, as many
|
|
// as ntfy serves on one connection.
|
|
MaxNtfyTopics = 150
|
|
|
|
// MaxNtfyBacklog is the longest max_backlog: ntfy keeps messages for
|
|
// 12 hours by default.
|
|
MaxNtfyBacklog = 12 * time.Hour
|
|
|
|
// MaxNtfyRateLimit is the largest rate_limit.
|
|
MaxNtfyRateLimit = 1000
|
|
|
|
// MinNtfyKeepalive and MaxNtfyKeepalive bound keepalive.
|
|
MinNtfyKeepalive = 5 * time.Second
|
|
MaxNtfyKeepalive = time.Hour
|
|
)
|
|
|
|
// NtfyConfig configures how notifications print, from the notify and ntfy
|
|
// modules and from the subscriptions.
|
|
type NtfyConfig struct {
|
|
Format NtfyFormatConfig `mapstructure:"format"`
|
|
|
|
// Markers override the markers printed for tags, by tag: an empty
|
|
// marker hides the tag.
|
|
Markers map[string]string `mapstructure:"markers"`
|
|
|
|
// Subscriptions are the ntfy servers and topics whose messages print.
|
|
// They come from the file only: a list of tables has no environment
|
|
// variable.
|
|
Subscriptions []NtfySubscription `mapstructure:"subscriptions"`
|
|
}
|
|
|
|
// NtfySubscription is one connection to an ntfy server, for one or more
|
|
// topics.
|
|
type NtfySubscription struct {
|
|
// Name names the subscription in /healthz, in logs, in job sources
|
|
// (ntfy:<name>) and in its state file.
|
|
Name string `mapstructure:"name"`
|
|
|
|
// Server is the ntfy server's base URL, e.g. https://ntfy.sh.
|
|
Server string `mapstructure:"server"`
|
|
|
|
// Topics are the topics to print.
|
|
Topics []string `mapstructure:"topics"`
|
|
|
|
// Token, TokenFile, or User with PasswordFile authenticate the
|
|
// subscription; at most one of them is set. A file holds the secret
|
|
// alone, and spaces around it are ignored.
|
|
Token string `mapstructure:"token"`
|
|
TokenFile string `mapstructure:"token_file"`
|
|
User string `mapstructure:"user"`
|
|
PasswordFile string `mapstructure:"password_file"`
|
|
|
|
// AllowInsecure allows a server URL that is http rather than https.
|
|
AllowInsecure bool `mapstructure:"allow_insecure"`
|
|
|
|
// MinPriority is the lowest priority that prints, 1-5.
|
|
MinPriority int `mapstructure:"min_priority"`
|
|
|
|
// MaxBacklog is how far back missed messages are printed after a
|
|
// restart or an outage.
|
|
MaxBacklog time.Duration `mapstructure:"max_backlog"`
|
|
|
|
// RateLimit receipts print per RateWindow at most; messages over it
|
|
// are held and print together on one digest receipt.
|
|
RateLimit int `mapstructure:"rate_limit"`
|
|
RateWindow time.Duration `mapstructure:"rate_window"`
|
|
|
|
// BypassPriority is the lowest priority that prints at once, outside
|
|
// the rate limit, 1-5.
|
|
BypassPriority int `mapstructure:"bypass_priority"`
|
|
|
|
// Keepalive is the server's keepalive interval. A connection that
|
|
// sends nothing for twice this, plus 15 seconds, is reconnected.
|
|
Keepalive time.Duration `mapstructure:"keepalive"`
|
|
|
|
// Quiet sets quiet hours; nil leaves them off.
|
|
Quiet *NtfyQuiet `mapstructure:"quiet"`
|
|
}
|
|
|
|
// NtfyQuiet configures a subscription's quiet hours: a daily window in
|
|
// which only urgent messages print.
|
|
type NtfyQuiet struct {
|
|
// Start and End are the window's times of day, HH:MM. An End before
|
|
// Start ends the window on the next day.
|
|
Start string `mapstructure:"start"`
|
|
End string `mapstructure:"end"`
|
|
|
|
// Days are the days the window starts on: mon, tue, wed, thu, fri,
|
|
// sat or sun.
|
|
Days []string `mapstructure:"days"`
|
|
|
|
// Timezone is the zone Start and End are in; "" means format.timezone.
|
|
Timezone string `mapstructure:"timezone"`
|
|
|
|
// MinPriority is the lowest priority that prints during the window.
|
|
MinPriority int `mapstructure:"min_priority"`
|
|
|
|
// Action is digest, to print the held messages on one receipt when the
|
|
// window ends, or drop.
|
|
Action string `mapstructure:"action"`
|
|
}
|
|
|
|
// DefaultSubscription returns a subscription with every optional setting
|
|
// at its default. Name, Server and Topics have no defaults.
|
|
func DefaultSubscription() NtfySubscription {
|
|
return NtfySubscription{
|
|
MinPriority: 1,
|
|
MaxBacklog: time.Hour,
|
|
RateLimit: 5,
|
|
RateWindow: 10 * time.Minute,
|
|
BypassPriority: 5,
|
|
Keepalive: 45 * time.Second,
|
|
}
|
|
}
|
|
|
|
// DefaultQuiet returns quiet hours with every setting at its default.
|
|
func DefaultQuiet() NtfyQuiet {
|
|
return NtfyQuiet{
|
|
Start: "22:00",
|
|
End: "07:00",
|
|
Days: slices.Clone(NtfyDays),
|
|
MinPriority: 5,
|
|
Action: "digest",
|
|
}
|
|
}
|
|
|
|
// NtfyFormatConfig configures the layout of a notification.
|
|
type NtfyFormatConfig struct {
|
|
// Style is auto, which picks the form from the priority, box or
|
|
// compact.
|
|
Style string `mapstructure:"style"`
|
|
|
|
// MaxLines is how many lines of a message print, as written.
|
|
MaxLines int `mapstructure:"max_lines"`
|
|
|
|
// QR is all, first or none: which links print as QR codes.
|
|
QR string `mapstructure:"qr"`
|
|
|
|
// Images prints attached images.
|
|
Images bool `mapstructure:"images"`
|
|
|
|
// Markdown lays out markdown messages.
|
|
Markdown bool `mapstructure:"markdown"`
|
|
|
|
// Updates says what a subscription does with a message that replaces
|
|
// one it printed: print marks its title "(updated)", skip leaves it
|
|
// out. The module routes print every message plain.
|
|
Updates string `mapstructure:"updates"`
|
|
}
|
|
|
|
// QueueConfig configures the print queue.
|
|
type QueueConfig struct {
|
|
// Size is the number of jobs that may wait to be printed.
|
|
Size int `mapstructure:"size"`
|
|
|
|
// History is the number of finished jobs whose status is kept.
|
|
History int `mapstructure:"history"`
|
|
}
|
|
|
|
// StateConfig configures where the daemon keeps what must survive a
|
|
// restart.
|
|
type StateConfig struct {
|
|
// Dir is the directory each ntfy subscription keeps its state in: its
|
|
// cursor, the IDs it has seen and the messages it holds. It has no
|
|
// default, and is required when a subscription is configured.
|
|
Dir string `mapstructure:"dir"`
|
|
}
|
|
|
|
// ImagesConfig configures image elements.
|
|
type ImagesConfig struct {
|
|
Timeout time.Duration `mapstructure:"timeout"`
|
|
MaxBytes int64 `mapstructure:"max_bytes"`
|
|
|
|
// MaxPixels caps the decoded image size to guard against decompression
|
|
// bombs.
|
|
MaxPixels int `mapstructure:"max_pixels"`
|
|
|
|
// MaxHeight caps the printed image height in dots after scaling.
|
|
MaxHeight int `mapstructure:"max_height"`
|
|
|
|
// AllowPrivateNetworks permits fetching from loopback, private and
|
|
// link-local addresses.
|
|
AllowPrivateNetworks bool `mapstructure:"allow_private_networks"`
|
|
|
|
// AllowedHosts, when non-empty, restricts fetching to these hosts. Listed
|
|
// hosts may resolve to private addresses.
|
|
AllowedHosts []string `mapstructure:"allowed_hosts"`
|
|
}
|
|
|
|
// SentryConfig configures error reporting.
|
|
type SentryConfig struct {
|
|
DSN string `mapstructure:"dsn"`
|
|
Environment string `mapstructure:"environment"`
|
|
Debug bool `mapstructure:"debug"`
|
|
}
|
|
|
|
// LogConfig configures structured logging.
|
|
type LogConfig struct {
|
|
Level string `mapstructure:"level"`
|
|
Format string `mapstructure:"format"`
|
|
}
|
|
|
|
// Default returns a configuration with every optional setting at its
|
|
// default. API.Secret and Printer.Address have no defaults.
|
|
func Default() Config {
|
|
return Config{
|
|
WebServer: WebServerConfig{
|
|
BindIP: "127.0.0.1",
|
|
Port: 8080,
|
|
RateLimit: 60,
|
|
RateWindow: time.Minute,
|
|
TrustedProxies: []string{"127.0.0.1", "::1"},
|
|
ProxyHeader: "X-Real-IP",
|
|
BodyLimit: 4 << 20,
|
|
ReadTimeout: 15 * time.Second,
|
|
WriteTimeout: 15 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
},
|
|
Printer: PrinterConfig{
|
|
Port: 9100,
|
|
// The narrower 512-dot profile is the safe default: on a wider
|
|
// printer lines are just shorter, while a profile wider than the
|
|
// printer makes it break words at the right edge.
|
|
Model: "tm-t88",
|
|
CodePage: "cp437",
|
|
CutFeed: 3,
|
|
DialTimeout: 5 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
Retries: 3,
|
|
RetryDelay: time.Second,
|
|
},
|
|
Format: FormatConfig{
|
|
MaxLines: 2000,
|
|
Timezone: "Local",
|
|
TimeLayout: "02 Jan 15:04",
|
|
},
|
|
Ntfy: NtfyConfig{
|
|
Format: NtfyFormatConfig{
|
|
Style: "auto",
|
|
MaxLines: 40,
|
|
QR: "all",
|
|
Images: true,
|
|
Markdown: true,
|
|
Updates: "print",
|
|
},
|
|
},
|
|
Queue: QueueConfig{
|
|
Size: 100,
|
|
History: 1000,
|
|
},
|
|
Images: ImagesConfig{
|
|
Timeout: 10 * time.Second,
|
|
MaxBytes: 10 << 20,
|
|
MaxPixels: 25_000_000,
|
|
MaxHeight: 4000,
|
|
},
|
|
Sentry: SentryConfig{
|
|
Environment: "production",
|
|
},
|
|
Log: LogConfig{
|
|
Level: "info",
|
|
Format: LogFormatText,
|
|
},
|
|
}
|
|
}
|
|
|
|
// Load builds the configuration from [Default], the TOML file at path and
|
|
// UBERBRINGER_* environment variables, in rising order of precedence, and
|
|
// validates the result. An empty path reads no file, for configuration by
|
|
// environment alone. Keys in the file that Config does not have are errors,
|
|
// so typos do not silently fall back to defaults. When sentry.dsn is unset,
|
|
// the SENTRY_DSN environment variable is used.
|
|
func Load(path string) (*Config, error) {
|
|
v := viper.New()
|
|
keys := make(map[string]keyKind)
|
|
registerDefaults(v, "", reflect.ValueOf(Default()), keys)
|
|
|
|
// Each setting is bound to its own variable. Viper's automatic lookup
|
|
// would also read a variable named after a section, such as
|
|
// UBERBRINGER_PRINTER, and let it hide every setting in that section.
|
|
var envSet []string
|
|
bound := map[string]bool{PathEnvVar: true}
|
|
for _, key := range slices.Sorted(maps.Keys(keys)) {
|
|
if kind := keys[key]; kind != setting && kind != tableSetting {
|
|
continue
|
|
}
|
|
name := envVar(key)
|
|
bound[name] = true
|
|
if err := v.BindEnv(key, name); err != nil {
|
|
return nil, fmt.Errorf("binding %s: %w", name, err)
|
|
}
|
|
// Viper treats an empty variable as unset. One that holds only
|
|
// spaces is refused: for a list it would clear the file's list.
|
|
value := os.Getenv(name)
|
|
if value != "" && strings.TrimSpace(value) == "" {
|
|
return nil, fmt.Errorf("config: %s holds only spaces; unset it or give it a value", name)
|
|
}
|
|
if value != "" {
|
|
envSet = append(envSet, name)
|
|
}
|
|
}
|
|
|
|
if path != "" {
|
|
table, err := readFile(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
unknown, clashes := checkKeys(table, "", "", keys)
|
|
if len(clashes) > 0 {
|
|
slices.Sort(clashes)
|
|
return nil, fmt.Errorf("config %s: keys that differ only in case: %s", path, strings.Join(clashes, "; "))
|
|
}
|
|
if len(unknown) > 0 {
|
|
slices.Sort(unknown)
|
|
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(unknown, ", "))
|
|
}
|
|
if err := v.MergeConfigMap(table); err != nil {
|
|
return nil, fmt.Errorf("config %s: %w", path, err)
|
|
}
|
|
}
|
|
|
|
// The names of the variables that were set, never their values, so a
|
|
// bad value can be traced to the file or the environment.
|
|
source := strings.Join(slices.Concat(slices.DeleteFunc([]string{path}, isEmpty), envSet), ", ")
|
|
if source == "" {
|
|
source = "(no file and no " + EnvPrefix + "_* settings)"
|
|
}
|
|
|
|
var cfg Config
|
|
err := v.Unmarshal(&cfg,
|
|
viper.DecodeHook(decodeHooks()),
|
|
// Values are taken as written, apart from the strings that hooks
|
|
// above parse: environment variables are strings.
|
|
func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false },
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("config %s: %w%s", source, err, unusedVariables(bound))
|
|
}
|
|
if cfg.Sentry.DSN == "" {
|
|
cfg.Sentry.DSN = os.Getenv("SENTRY_DSN")
|
|
}
|
|
if err := cfg.Validate(); err != nil {
|
|
return nil, fmt.Errorf("config %s: %w%s", source, err, unusedVariables(bound))
|
|
}
|
|
return &cfg, nil
|
|
}
|
|
|
|
// PathEnvVar names the config file for the command line's --config. Load
|
|
// does not read it, but does not count it as a misspelt setting either.
|
|
const PathEnvVar = EnvPrefix + "_CONFIG"
|
|
|
|
// envVar returns the environment variable that sets the dotted config key,
|
|
// e.g. UBERBRINGER_PRINTER_ADDRESS for printer.address.
|
|
func envVar(key string) string {
|
|
return EnvPrefix + "_" + strings.ToUpper(strings.ReplaceAll(key, ".", "_"))
|
|
}
|
|
|
|
// unusedVariables returns a note naming the set UBERBRINGER_* variables
|
|
// that match no setting, which are likely misspelt, or "" when there are
|
|
// none. Only names are given, never values.
|
|
func unusedVariables(bound map[string]bool) string {
|
|
var unused []string
|
|
for _, entry := range os.Environ() {
|
|
name, value, _ := strings.Cut(entry, "=")
|
|
if strings.HasPrefix(name, EnvPrefix+"_") && value != "" && !bound[name] {
|
|
unused = append(unused, name)
|
|
}
|
|
}
|
|
if len(unused) == 0 {
|
|
return ""
|
|
}
|
|
slices.Sort(unused)
|
|
return "\n" + EnvPrefix + "_* variables that set nothing: " + strings.Join(unused, ", ")
|
|
}
|
|
|
|
func isEmpty(s string) bool { return s == "" }
|
|
|
|
// readFile parses the TOML file at path into a table.
|
|
func readFile(path string) (map[string]any, error) {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("reading config %s: %w", path, err)
|
|
}
|
|
if bytes.HasPrefix(data, []byte("\xff\xfe")) || bytes.HasPrefix(data, []byte("\xfe\xff")) {
|
|
return nil, fmt.Errorf("config %s: the file is UTF-16; save it as UTF-8", path)
|
|
}
|
|
// A byte order mark, which some Windows editors write at the start of a
|
|
// UTF-8 file, is not part of the TOML.
|
|
data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
|
|
var table map[string]any
|
|
if err := toml.Unmarshal(data, &table); err != nil {
|
|
var decodeErr *toml.DecodeError
|
|
if errors.As(err, &decodeErr) {
|
|
row, col := decodeErr.Position()
|
|
return nil, fmt.Errorf("config %s: line %d, column %d: %w", path, row, col, err)
|
|
}
|
|
return nil, fmt.Errorf("config %s: %w", path, err)
|
|
}
|
|
return table, nil
|
|
}
|
|
|
|
// keyKind tells a setting from a section that holds settings, from a
|
|
// table setting, whose keys are the user's own, and from a list of tables.
|
|
type keyKind int
|
|
|
|
const (
|
|
setting keyKind = iota + 1
|
|
section
|
|
tableSetting
|
|
|
|
// tableList is a list of tables, such as ntfy.subscriptions, which only
|
|
// the file sets. listSetting and listSection are the keys of its
|
|
// entries.
|
|
tableList
|
|
listSetting
|
|
listSection
|
|
)
|
|
|
|
// registerDefaults sets every field of the config struct rv as a Viper
|
|
// default under its dotted mapstructure key, and records each key in keys.
|
|
func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[string]keyKind) {
|
|
rt := rv.Type()
|
|
for i := range rt.NumField() {
|
|
tag := rt.Field(i).Tag.Get("mapstructure")
|
|
if tag == "" {
|
|
continue
|
|
}
|
|
key := tag
|
|
if prefix != "" {
|
|
key = prefix + "." + tag
|
|
}
|
|
field := rv.Field(i)
|
|
switch field.Kind() {
|
|
case reflect.Struct:
|
|
keys[key] = section
|
|
registerDefaults(v, key, field, keys)
|
|
case reflect.Map:
|
|
// A default table would merge with the file's instead of
|
|
// giving way to it; the table settings default to empty.
|
|
keys[key] = tableSetting
|
|
case reflect.Slice:
|
|
if elem := field.Type().Elem(); elem.Kind() == reflect.Struct {
|
|
keys[key] = tableList
|
|
registerListKeys(key, elem, keys)
|
|
continue
|
|
}
|
|
v.SetDefault(key, field.Interface())
|
|
keys[key] = setting
|
|
default:
|
|
v.SetDefault(key, field.Interface())
|
|
keys[key] = setting
|
|
}
|
|
}
|
|
}
|
|
|
|
// registerListKeys records the keys of an entry of a list of tables, a
|
|
// struct of type t, under prefix. They have no Viper defaults: decodeHooks
|
|
// starts each entry from its own defaults.
|
|
func registerListKeys(prefix string, t reflect.Type, keys map[string]keyKind) {
|
|
for i := range t.NumField() {
|
|
tag := t.Field(i).Tag.Get("mapstructure")
|
|
if tag == "" {
|
|
continue
|
|
}
|
|
key := prefix + "." + tag
|
|
ft := t.Field(i).Type
|
|
if ft.Kind() == reflect.Pointer {
|
|
ft = ft.Elem()
|
|
}
|
|
if ft.Kind() == reflect.Struct {
|
|
keys[key] = listSection
|
|
registerListKeys(key, ft, keys)
|
|
continue
|
|
}
|
|
keys[key] = listSetting
|
|
}
|
|
}
|
|
|
|
// checkKeys walks the file's table under prefix. It returns the keys Config
|
|
// does not have (unknown names, empty tables included, a setting written as
|
|
// a table, a section written as a value, and a quoted name with a dot, which
|
|
// is one key rather than a path) and the names in one table that differ only
|
|
// in case. Names match case-insensitively, as Viper reads them, and Viper
|
|
// would keep only one of two such names. lookup is the lowercase dotted path
|
|
// of prefix, which names it as written.
|
|
func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyKind) (unknown, clashes []string) {
|
|
names := slices.Sorted(maps.Keys(table))
|
|
seen := make(map[string]string, len(names))
|
|
for _, name := range names {
|
|
path := displayKey(name)
|
|
key := strings.ToLower(name)
|
|
if prefix != "" {
|
|
path = prefix + "." + path
|
|
key = lookup + "." + key
|
|
}
|
|
if other, ok := seen[key]; ok {
|
|
clashes = append(clashes, other+" and "+path)
|
|
continue
|
|
}
|
|
seen[key] = path
|
|
|
|
sub, isTable := table[name].(map[string]any)
|
|
kind := keys[key]
|
|
if strings.Contains(name, ".") {
|
|
kind = 0
|
|
}
|
|
switch {
|
|
case isTable && (kind == section || kind == listSection):
|
|
u, c := checkKeys(sub, path, key, keys)
|
|
unknown = append(unknown, u...)
|
|
clashes = append(clashes, c...)
|
|
case isTable && kind == tableSetting:
|
|
u, c := checkTable(sub, path)
|
|
unknown = append(unknown, u...)
|
|
clashes = append(clashes, c...)
|
|
case kind == tableList:
|
|
u, c := checkList(table[name], path, key, keys)
|
|
unknown = append(unknown, u...)
|
|
clashes = append(clashes, c...)
|
|
case !isTable && (kind == setting || kind == listSetting):
|
|
default:
|
|
unknown = append(unknown, path)
|
|
}
|
|
}
|
|
return unknown, clashes
|
|
}
|
|
|
|
// checkList checks the entries of a list of tables at path, whose dotted
|
|
// lowercase key is lookup. Each entry must be a table, whose keys are
|
|
// checked as a section's; an entry is named by its index, as
|
|
// ntfy.subscriptions[0].name. A list given as anything else is unknown.
|
|
func checkList(value any, path, lookup string, keys map[string]keyKind) (unknown, clashes []string) {
|
|
var entries []map[string]any
|
|
switch list := value.(type) {
|
|
case []map[string]any:
|
|
entries = list
|
|
case []any:
|
|
for i, item := range list {
|
|
entry, ok := item.(map[string]any)
|
|
if !ok {
|
|
unknown = append(unknown, fmt.Sprintf("%s[%d]", path, i))
|
|
continue
|
|
}
|
|
entries = append(entries, entry)
|
|
}
|
|
if len(unknown) > 0 {
|
|
return unknown, nil
|
|
}
|
|
default:
|
|
return []string{path}, nil
|
|
}
|
|
for i, entry := range entries {
|
|
u, c := checkKeys(entry, fmt.Sprintf("%s[%d]", path, i), lookup, keys)
|
|
unknown = append(unknown, u...)
|
|
clashes = append(clashes, c...)
|
|
}
|
|
return unknown, clashes
|
|
}
|
|
|
|
// checkTable checks the entries of a table setting at path, whose names are
|
|
// the user's own. Like checkKeys, it returns as unknown a name with a dot
|
|
// and an entry that is itself a table, and the names that differ only in
|
|
// case.
|
|
func checkTable(entries map[string]any, path string) (unknown, clashes []string) {
|
|
seen := make(map[string]string, len(entries))
|
|
for _, name := range slices.Sorted(maps.Keys(entries)) {
|
|
entry := path + "." + displayKey(name)
|
|
if other, ok := seen[strings.ToLower(name)]; ok {
|
|
clashes = append(clashes, other+" and "+entry)
|
|
continue
|
|
}
|
|
seen[strings.ToLower(name)] = entry
|
|
if _, isTable := entries[name].(map[string]any); isTable || strings.Contains(name, ".") {
|
|
unknown = append(unknown, entry)
|
|
}
|
|
}
|
|
return unknown, clashes
|
|
}
|
|
|
|
// displayKey quotes a key name that TOML would need quoted, so that spaces,
|
|
// dots and empty names show in messages.
|
|
func displayKey(name string) string {
|
|
if name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == "" {
|
|
return name
|
|
}
|
|
return strconv.Quote(name)
|
|
}
|
|
|
|
// decodeHooks are the hooks that decode the config: values from strings,
|
|
// and the entries of the lists of tables from their own defaults.
|
|
func decodeHooks() mapstructure.DecodeHookFunc {
|
|
values := []mapstructure.DecodeHookFunc{
|
|
durations(),
|
|
stringToList(),
|
|
stringToTable(),
|
|
refuseFractions(),
|
|
stringToNumberOrFlag(),
|
|
}
|
|
quiet := entryDefaults(DefaultQuiet, values)
|
|
subscription := entryDefaults(DefaultSubscription, append(slices.Clone(values), quiet))
|
|
return mapstructure.ComposeDecodeHookFunc(append(values, subscription, quiet)...)
|
|
}
|
|
|
|
// entryDefaults decodes a table into a T, an entry of a list of tables or
|
|
// a table inside one, starting from defaults(): the keys the table leaves
|
|
// out keep their defaults, which Viper cannot give the entries of a list.
|
|
// hooks decode the entry's values.
|
|
func entryDefaults[T any](defaults func() T, hooks []mapstructure.DecodeHookFunc) mapstructure.DecodeHookFunc {
|
|
target := reflect.TypeFor[T]()
|
|
return func(_, to reflect.Type, data any) (any, error) {
|
|
table, ok := data.(map[string]any)
|
|
if to != target || !ok {
|
|
return data, nil
|
|
}
|
|
entry := defaults()
|
|
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
|
|
DecodeHook: mapstructure.ComposeDecodeHookFunc(hooks...),
|
|
// A list the table gives replaces the default list rather than
|
|
// overwriting its first items.
|
|
ZeroFields: true,
|
|
Result: &entry,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := dec.Decode(table); err != nil {
|
|
return nil, err
|
|
}
|
|
return entry, nil
|
|
}
|
|
}
|
|
|
|
// durations decodes a duration from a string such as "1m30s". A bare number
|
|
// is refused, since the decoder would read it as nanoseconds.
|
|
func durations() mapstructure.DecodeHookFunc {
|
|
durationType := reflect.TypeFor[time.Duration]()
|
|
return func(from, to reflect.Type, data any) (any, error) {
|
|
if to != durationType || from == durationType {
|
|
return data, nil
|
|
}
|
|
s, ok := data.(string)
|
|
if !ok {
|
|
return nil, errors.New(`expected a duration as a string, such as "5s"`)
|
|
}
|
|
d, err := time.ParseDuration(strings.TrimSpace(s))
|
|
if err != nil {
|
|
return nil, errors.New(`expected a duration such as "5s" or "1m30s"`)
|
|
}
|
|
return d, nil
|
|
}
|
|
}
|
|
|
|
// refuseFractions refuses a number with a fraction for an integer setting,
|
|
// which the decoder would otherwise truncate.
|
|
func refuseFractions() mapstructure.DecodeHookFunc {
|
|
return func(from, to reflect.Type, data any) (any, error) {
|
|
if from.Kind() != reflect.Float32 && from.Kind() != reflect.Float64 {
|
|
return data, nil
|
|
}
|
|
switch to.Kind() {
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
|
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
return nil, errors.New("expected a whole number")
|
|
}
|
|
return data, nil
|
|
}
|
|
}
|
|
|
|
// stringToNumberOrFlag parses a string, such as an environment variable, for
|
|
// a number or flag setting: decimal digits for a number, true or false for a
|
|
// flag. Spaces around the value are ignored.
|
|
func stringToNumberOrFlag() mapstructure.DecodeHookFunc {
|
|
return func(from, to reflect.Type, data any) (any, error) {
|
|
if from.Kind() != reflect.String {
|
|
return data, nil
|
|
}
|
|
s := strings.TrimSpace(data.(string))
|
|
switch to.Kind() {
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
n, err := strconv.ParseInt(s, 10, to.Bits())
|
|
if err != nil {
|
|
return nil, numberError(err)
|
|
}
|
|
return reflect.ValueOf(n).Convert(to).Interface(), nil
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
n, err := strconv.ParseUint(s, 10, to.Bits())
|
|
if err != nil {
|
|
return nil, numberError(err)
|
|
}
|
|
return reflect.ValueOf(n).Convert(to).Interface(), nil
|
|
case reflect.Bool:
|
|
switch s {
|
|
case "true":
|
|
return true, nil
|
|
case "false":
|
|
return false, nil
|
|
}
|
|
return nil, errors.New("expected true or false")
|
|
}
|
|
return data, nil
|
|
}
|
|
}
|
|
|
|
func numberError(err error) error {
|
|
if errors.Is(err, strconv.ErrRange) {
|
|
return errors.New("number out of range")
|
|
}
|
|
return errors.New("expected a whole number in decimal digits")
|
|
}
|
|
|
|
// stringToList splits a string, such as an environment variable, into a list
|
|
// at commas and trims the spaces around each item, so "a, b" and "a,b" give
|
|
// the same list. An empty item, from a doubled or trailing comma, is refused.
|
|
func stringToList() mapstructure.DecodeHookFunc {
|
|
return func(from, to reflect.Type, data any) (any, error) {
|
|
if from.Kind() != reflect.String || to.Kind() != reflect.Slice {
|
|
return data, nil
|
|
}
|
|
raw := strings.TrimSpace(data.(string))
|
|
if raw == "" {
|
|
return []string{}, nil
|
|
}
|
|
items := strings.Split(raw, ",")
|
|
for i := range items {
|
|
items[i] = strings.TrimSpace(items[i])
|
|
if items[i] == "" {
|
|
return nil, errors.New("a list item is empty; check for a doubled or trailing comma")
|
|
}
|
|
}
|
|
return items, nil
|
|
}
|
|
}
|
|
|
|
// stringToTable reads a table setting from a string, such as an
|
|
// environment variable: entries name=value, separated by commas, with the
|
|
// spaces around each trimmed, so "a=[A], b=" sets a to "[A]" and b to "". A
|
|
// value cannot hold a comma.
|
|
func stringToTable() mapstructure.DecodeHookFunc {
|
|
return func(from, to reflect.Type, data any) (any, error) {
|
|
if from.Kind() != reflect.String || to.Kind() != reflect.Map {
|
|
return data, nil
|
|
}
|
|
entries := make(map[string]string)
|
|
raw := strings.TrimSpace(data.(string))
|
|
if raw == "" {
|
|
return entries, nil
|
|
}
|
|
for item := range strings.SplitSeq(raw, ",") {
|
|
name, value, ok := strings.Cut(item, "=")
|
|
name = strings.ToLower(strings.TrimSpace(name))
|
|
if !ok || name == "" {
|
|
return nil, errors.New("expected entries name=value separated by commas, e.g. backup=[B],skull=")
|
|
}
|
|
if _, dup := entries[name]; dup {
|
|
return nil, fmt.Errorf("%q is given twice", name)
|
|
}
|
|
entries[name] = strings.TrimSpace(value)
|
|
}
|
|
return entries, nil
|
|
}
|
|
}
|
|
|
|
// Validate reports every problem with the configuration.
|
|
func (c *Config) Validate() error {
|
|
var errs []error
|
|
check := func(ok bool, format string, args ...any) {
|
|
if !ok {
|
|
errs = append(errs, fmt.Errorf(format, args...))
|
|
}
|
|
}
|
|
|
|
ws := c.WebServer
|
|
_, ipErr := netip.ParseAddr(ws.BindIP)
|
|
check(ipErr == nil, "webserver.bind_ip: %q is not an IP address", ws.BindIP)
|
|
check(validPort(ws.Port), "webserver.port: %d is out of range 1-65535", ws.Port)
|
|
check(ws.RateLimit > 0, "webserver.rate_limit must be positive")
|
|
check(ws.RateWindow > 0, "webserver.rate_window must be positive")
|
|
check(ws.BodyLimit > 0, "webserver.body_limit must be positive")
|
|
check(ws.ReadTimeout > 0 && ws.WriteTimeout > 0 && ws.IdleTimeout > 0,
|
|
"webserver read/write/idle timeouts must be positive")
|
|
for _, proxy := range ws.TrustedProxies {
|
|
check(validIPOrPrefix(proxy), "webserver.trusted_proxies: %q is not an IP or CIDR", proxy)
|
|
}
|
|
|
|
check(len(c.API.Secret) >= MinSecretLength,
|
|
"api.secret must be at least %d bytes (generate one with `uberbringer secret`)", MinSecretLength)
|
|
|
|
p := c.Printer
|
|
check(strings.TrimSpace(p.Address) != "", "printer.address is required")
|
|
check(validPort(p.Port), "printer.port: %d is out of range 1-65535", p.Port)
|
|
check(p.PaperWidth >= 0, "printer.paper_width must not be negative")
|
|
check(p.Columns >= 0, "printer.columns must not be negative")
|
|
check(p.BoxLineSpacing >= 0 && p.BoxLineSpacing <= MaxLineSpacing,
|
|
"printer.box_line_spacing must be 0-%d", MaxLineSpacing)
|
|
check(p.CutFeed >= 0 && p.CutFeed <= MaxCutFeed, "printer.cut_feed must be 0-%d", MaxCutFeed)
|
|
check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive")
|
|
check(p.Retries >= 0, "printer.retries must not be negative")
|
|
check(p.RetryDelay > 0, "printer.retry_delay must be positive")
|
|
|
|
check(c.Format.MaxLines > 0, "format.max_lines must be positive")
|
|
if c.Format.Timezone == "" {
|
|
errs = append(errs, errors.New(`format.timezone is required: an IANA name such as "Europe/London", "UTC" or "Local"`))
|
|
} else if _, err := time.LoadLocation(c.Format.Timezone); err != nil {
|
|
errs = append(errs, fmt.Errorf(`format.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, c.Format.Timezone))
|
|
}
|
|
check(showsTime(c.Format.TimeLayout),
|
|
`format.time_layout: %q shows no date or time; write it in Go's layout, such as "02 Jan 15:04"`, c.Format.TimeLayout)
|
|
|
|
nf := c.Ntfy.Format
|
|
check(slices.Contains(NtfyStyles, nf.Style), "ntfy.format.style: %q must be one of %s", nf.Style, strings.Join(NtfyStyles, ", "))
|
|
check(nf.MaxLines >= 1 && nf.MaxLines <= MaxNtfyLines, "ntfy.format.max_lines must be 1-%d", MaxNtfyLines)
|
|
check(slices.Contains(NtfyQRModes, nf.QR), "ntfy.format.qr: %q must be one of %s", nf.QR, strings.Join(NtfyQRModes, ", "))
|
|
for _, tag := range slices.Sorted(maps.Keys(c.Ntfy.Markers)) {
|
|
check(strings.TrimSpace(tag) != "", "ntfy.markers: a tag name is empty")
|
|
check(utf8.RuneCountInString(c.Ntfy.Markers[tag]) <= MaxMarker,
|
|
"ntfy.markers.%s: %q is longer than %d characters", tag, c.Ntfy.Markers[tag], MaxMarker)
|
|
}
|
|
check(slices.Contains(NtfyUpdateModes, nf.Updates), "ntfy.format.updates: %q must be one of %s", nf.Updates, strings.Join(NtfyUpdateModes, ", "))
|
|
errs = append(errs, validateSubscriptions(c.Ntfy)...)
|
|
|
|
check(c.Queue.Size > 0, "queue.size must be positive")
|
|
check(c.Queue.History >= 0, "queue.history must not be negative")
|
|
|
|
check(len(c.Ntfy.Subscriptions) == 0 || strings.TrimSpace(c.State.Dir) != "",
|
|
`state.dir is required when an ntfy subscription is configured, e.g. "/var/lib/uberbringer"`)
|
|
|
|
img := c.Images
|
|
check(img.Timeout > 0, "images.timeout must be positive")
|
|
check(img.MaxBytes > 0, "images.max_bytes must be positive")
|
|
check(img.MaxPixels > 0, "images.max_pixels must be positive")
|
|
check(img.MaxHeight > 0, "images.max_height must be positive")
|
|
|
|
check(slices.Contains([]string{"debug", "info", "warn", "error"}, c.Log.Level),
|
|
"log.level: %q must be one of debug, info, warn, error", c.Log.Level)
|
|
check(c.Log.Format == LogFormatText || c.Log.Format == LogFormatJSON,
|
|
"log.format: %q must be %q or %q", c.Log.Format, LogFormatText, LogFormatJSON)
|
|
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
var (
|
|
// subscriptionName is the form of a subscription's name, which appears
|
|
// in job sources and in a file name.
|
|
subscriptionName = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
|
|
|
|
// ntfyTopic is the form of an ntfy topic name.
|
|
ntfyTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
|
|
|
|
// clock is a time of day, HH:MM.
|
|
clock = regexp.MustCompile(`^([01][0-9]|2[0-3]):[0-5][0-9]$`)
|
|
)
|
|
|
|
// validateSubscriptions reports every problem with the ntfy subscriptions.
|
|
// The server URL is never quoted, since it could hold a password.
|
|
func validateSubscriptions(n NtfyConfig) []error {
|
|
var errs []error
|
|
names := make(map[string]int)
|
|
for i, s := range n.Subscriptions {
|
|
at := fmt.Sprintf("ntfy.subscriptions[%d]", i)
|
|
check := func(ok bool, format string, args ...any) {
|
|
if !ok {
|
|
errs = append(errs, fmt.Errorf(at+"."+format, args...))
|
|
}
|
|
}
|
|
|
|
switch other, dup := names[s.Name]; {
|
|
case s.Name == "":
|
|
check(false, "name is required")
|
|
case !subscriptionName.MatchString(s.Name):
|
|
check(false, "name: %q must be 1-32 lowercase letters, digits, - and _, starting with a letter or digit", s.Name)
|
|
case dup:
|
|
check(false, "name: %q is also the name of ntfy.subscriptions[%d]", s.Name, other)
|
|
default:
|
|
names[s.Name] = i
|
|
}
|
|
|
|
u, err := url.Parse(s.Server)
|
|
switch {
|
|
case s.Server == "":
|
|
check(false, "server is required, e.g. \"https://ntfy.sh\"")
|
|
case err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http"):
|
|
check(false, "server is not an http or https URL")
|
|
case u.User != nil:
|
|
check(false, "server holds credentials; set token, token_file, or user and password_file instead")
|
|
case u.RawQuery != "" || u.Fragment != "":
|
|
check(false, "server must have no query or fragment")
|
|
case u.Scheme == "http" && !s.AllowInsecure:
|
|
check(false, "server is not https; set allow_insecure = true to allow plain http")
|
|
}
|
|
|
|
// A topic is named by its index, never quoted: on a public server
|
|
// its name can be all that keeps others from publishing to it.
|
|
check(len(s.Topics) >= 1 && len(s.Topics) <= MaxNtfyTopics, "topics: name 1-%d topics", MaxNtfyTopics)
|
|
seen := make(map[string]int, len(s.Topics))
|
|
for j, topic := range s.Topics {
|
|
check(ntfyTopic.MatchString(topic), "topics[%d] must be 1-64 letters, digits, - and _", j)
|
|
if first, dup := seen[topic]; dup {
|
|
check(false, "topics[%d] repeats topics[%d]", j, first)
|
|
continue
|
|
}
|
|
seen[topic] = j
|
|
}
|
|
|
|
methods := 0
|
|
for _, set := range []bool{s.Token != "", s.TokenFile != "", s.User != "" || s.PasswordFile != ""} {
|
|
if set {
|
|
methods++
|
|
}
|
|
}
|
|
check(methods <= 1, "set at most one of token, token_file, or user with password_file")
|
|
check((s.User == "") == (s.PasswordFile == ""), "user and password_file go together")
|
|
|
|
check(s.MinPriority >= 1 && s.MinPriority <= 5, "min_priority must be 1-5")
|
|
check(s.BypassPriority >= 1 && s.BypassPriority <= 5, "bypass_priority must be 1-5")
|
|
check(s.MaxBacklog > 0 && s.MaxBacklog <= MaxNtfyBacklog, "max_backlog must be more than 0 and at most %s", MaxNtfyBacklog)
|
|
check(s.RateLimit >= 1 && s.RateLimit <= MaxNtfyRateLimit, "rate_limit must be 1-%d", MaxNtfyRateLimit)
|
|
check(s.RateWindow > 0, "rate_window must be positive")
|
|
check(s.Keepalive >= MinNtfyKeepalive && s.Keepalive <= MaxNtfyKeepalive,
|
|
"keepalive must be %s-%s", MinNtfyKeepalive, MaxNtfyKeepalive)
|
|
|
|
if q := s.Quiet; q != nil {
|
|
check(clock.MatchString(q.Start), "quiet.start: %q is not a time of day HH:MM", q.Start)
|
|
check(clock.MatchString(q.End), "quiet.end: %q is not a time of day HH:MM", q.End)
|
|
check(q.Start != q.End, "quiet: start and end are both %q; the window would be empty", q.Start)
|
|
check(len(q.Days) > 0, "quiet.days: name at least one day")
|
|
days := make(map[string]bool, len(q.Days))
|
|
for _, day := range q.Days {
|
|
check(slices.Contains(NtfyDays, day), "quiet.days: %q must be one of %s", day, strings.Join(NtfyDays, ", "))
|
|
check(!days[day], "quiet.days: %q is given twice", day)
|
|
days[day] = true
|
|
}
|
|
if q.Timezone != "" {
|
|
_, err := time.LoadLocation(q.Timezone)
|
|
check(err == nil, `quiet.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, q.Timezone)
|
|
}
|
|
check(q.MinPriority >= 1 && q.MinPriority <= 5, "quiet.min_priority must be 1-5")
|
|
check(slices.Contains(NtfyQuietActions, q.Action), "quiet.action: %q must be one of %s", q.Action, strings.Join(NtfyQuietActions, ", "))
|
|
}
|
|
}
|
|
return errs
|
|
}
|
|
|
|
// showsTime reports whether layout prints something of the time it
|
|
// formats: two times that differ in every field format differently. A
|
|
// layout with none of Go's reference values, such as "HH:MM", prints
|
|
// itself.
|
|
func showsTime(layout string) bool {
|
|
a := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC)
|
|
b := time.Date(2012, 11, 22, 16, 47, 58, 0, time.FixedZone("X", 3600))
|
|
return a.Format(layout) != b.Format(layout)
|
|
}
|
|
|
|
func validPort(port int) bool {
|
|
return port >= 1 && port <= 65535
|
|
}
|
|
|
|
func validIPOrPrefix(s string) bool {
|
|
if _, err := netip.ParseAddr(s); err == nil {
|
|
return true
|
|
}
|
|
_, err := netip.ParsePrefix(s)
|
|
return err == nil
|
|
}
|