obsdconf

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 12 Imported by: 0

README

obsdconf

A Go package for configuration files in the style of OpenBSD daemons (pf.conf, httpd.conf, relayd.conf):

include "/etc/bridge.secrets"           # defines $mqtt_password

broker = "ssl://localhost:8883"

log level info

mqtt $broker {
	client id "e3dc-1"
	username e3dc
	password $mqtt_password
	keepalive 30s
}

no sandbox

obsdconf does the parts that are the same in every such file — lexing, macros, include, lists, blocks, values, error reporting and recovery — and leaves the grammar to you. You write it as plain recursive descent:

p := obsdconf.New("bridge.conf", src, obsdconf.Options{
	Keywords: []string{"mqtt", "client", "keepalive"},
})
err := p.Parse(func() bool {
	if !p.Expect("mqtt") {
		return false
	}
	url, ok := p.Text("broker URL")
	if !ok {
		return false
	}
	return p.Block("mqtt", func() bool {
		switch {
		case p.Accept("client", "id"):
			cfg.ClientID, ok = p.Text("client id")
		case p.Accept("keepalive"):
			cfg.Keepalive, ok = p.Duration(time.Second, time.Hour)
		default:
			p.Errorf(p.Tok().Pos, "unknown mqtt option %q", p.Tok().Text)
			ok = false
		}
		return ok
	})
})

A statement function is called with the first word of a statement as the current token. It consumes the statement and returns false after reporting an error. The parser then skips to the end of the statement and goes on, so one run reports every error:

bridge.conf:4: expected log level, got "loud"
bridge.conf:9: duration "2h" out of range (1s-3600s)

See the package documentation for the full API.

Features

  • Words, quoted strings (\" and \\ escapes, UTF-8), # comments, \ continuation lines.
  • Macros: name = value at top level, used as $name. A quoted value is split into tokens again, as in pf.conf, so lan = "{ a b }" defines a list. Options.Macros predefines macros, like pfctl -D.
  • include "file", relative to the including file, with loop detection.
  • Lists { a b } (commas optional, may span lines) and blocks.
  • Values: Word, Text, Number, Port, Duration (500ms, 90, 1h30m, 2w), Bool, Enum, Addr, Prefix.
  • Multi-word keywords: p.Accept("client", "id"); negated options: p.Accept("no").
  • UnusedMacros lists the macros that are defined but never used, which pfctl warns about since they are often typing errors.
  • Options.Secret rejects files that are not owned by root or the current user, or that are group writable or accessible by others — the rules of check_file_secrecy() in OpenBSD daemons. It applies to included files too, so passwords can live in a separate file with mode 0600.

Users

The API is not stable before v1.0.0. It is meant to grow with the projects that use it; planned users are e3dc-mqtt, mygekko-mqtt and weft. Their configurations need, among other things, sub-second durations, multi-word keywords, secrets in included files, repeated blocks with arguments (attribute ou { … }), UTF-8 labels and listen on ADDRESS port N.

License

MIT, see LICENSE.

Documentation

Overview

Package obsdconf parses configuration files in the style of OpenBSD daemons such as pf.conf(5), httpd.conf(5) and relayd.conf(5): one statement per line, keywords instead of punctuation, curly braces for blocks and lists, macros and include.

The package handles everything that is the same in every such file and leaves the grammar to the caller, who writes it as plain recursive descent with the helpers of Parser:

  • Lexing: words, quoted strings, # comments, \ at the end of a line.
  • Macros: name = value at top level, used as $name. As in pf.conf, a quoted value is split into tokens again, so lan = "{ a b }" defines a list. Options.Macros predefines macros, like pfctl -D.
  • include "file", relative to the including file, with loop detection.
  • Lists ({ a b }, { a, b }, spanning lines) and blocks ({ on its own line ... }).
  • Values: Word, Text, Number, Port, Duration, Bool, Enum, Addr, Prefix.
  • Multi-word keywords with Accept("client", "id"); negated options with Accept("no").
  • UnusedMacros reports macros that are defined but never used.
  • Errors as file:line: message. After an error the parser skips to the end of the statement and goes on, so one run reports all errors.
  • Options.Secret checks file permissions like check_file_secrecy() for configurations with passwords.
Example
package main

import (
	"fmt"
	"time"

	"github.com/isnogudus/obsdconf"
)

func main() {
	src := `
broker = "ssl://localhost:8883"

mqtt $broker {
	client id "e3dc-1"
	keepalive 30s
}
`
	var url, clientID string
	var keepalive time.Duration

	p := obsdconf.New("bridge.conf", []byte(src), obsdconf.Options{
		Keywords: []string{"mqtt", "client", "keepalive"},
	})
	err := p.Parse(func() bool {
		if !p.Expect("mqtt") {
			return false
		}
		var ok bool
		if url, ok = p.Text("broker URL"); !ok {
			return false
		}
		return p.Block("mqtt", func() bool {
			switch {
			case p.Accept("client", "id"):
				clientID, ok = p.Text("client id")
			case p.Accept("keepalive"):
				keepalive, ok = p.Duration(time.Second, time.Hour)
			default:
				p.Errorf(p.Tok().Pos, "unknown mqtt option %q", p.Tok().Text)
				ok = false
			}
			return ok
		})
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(url, clientID, keepalive)
}
Output:
ssl://localhost:8883 e3dc-1 30s

Index

Examples

Constants

View Source
const DefaultMaxIncludeDepth = 16

DefaultMaxIncludeDepth limits how deeply include statements may nest if Options.MaxIncludeDepth is zero.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {
	Pos Pos
	Msg string
}

Error is a problem found at a position in the configuration.

func (*Error) Error

func (e *Error) Error() string

type ErrorList

type ErrorList []*Error

ErrorList holds all errors of a parse, in the order they were found.

func (ErrorList) Error

func (l ErrorList) Error() string

type Kind

type Kind int

Kind is the kind of a token.

const (
	EOF Kind = iota
	Newline
	Word
	String
	LBrace
	RBrace
	Equals
	Comma
	// Illegal carries a lexical error message in Text. The parser reports
	// it as soon as the token is read.
	Illegal
)

type Macro added in v0.2.0

type Macro struct {
	Name string
	Pos  Pos
}

Macro is a macro defined in the configuration.

type Options

type Options struct {
	// Keywords of the grammar. They cannot be used as macro names.
	Keywords []string
	// Macros predefines macros, like pfctl -D name=value. Values are split
	// into tokens like quoted macro values.
	Macros map[string]string
	// Secret requires every file read, including included ones, to be
	// owned by root or the current user and not to be group writable or
	// accessible by others, like check_file_secrecy() in OpenBSD daemons.
	// Use it for configurations that hold passwords or keys. Standard
	// input is not checked.
	Secret bool
	// MaxIncludeDepth limits nested includes; 0 means
	// DefaultMaxIncludeDepth.
	MaxIncludeDepth int
}

Options configure a Parser.

type Parser

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

Parser reads a configuration as a sequence of statements. It handles macros, include, lists, blocks and recovery after errors; the grammar of the statements is up to the caller.

A statement function is called with the first word of a statement as the current token. It consumes the statement, but not the newline that ends it, and returns false after reporting an error with Errorf or Expected. The parser then skips the rest of the statement and goes on, so that one run reports every error.

func New

func New(name string, src []byte, opts Options) *Parser

New returns a parser for src. name is used in error messages and as the base for relative include paths.

func NewFile

func NewFile(path string, opts Options) (*Parser, error)

NewFile returns a parser for the file at path. A path of "-" reads standard input.

func (*Parser) Accept

func (p *Parser) Accept(words ...string) bool

Accept consumes the given words if they come next, as in p.Accept("client", "id"), and reports whether it did.

func (*Parser) Addr

func (p *Parser) Addr() (netip.Addr, bool)

Addr consumes an IPv4 or IPv6 address without zone.

func (*Parser) Block

func (p *Parser) Block(what string, stmt func() bool) bool

Block parses the statements of a brace-enclosed block; the opening brace is the current token. As in httpd.conf(5), the block may stand on one line if it holds one statement, as in { user x }; it may also be empty, {} or { }. Otherwise the statements start on the line after the brace. stmt is called like the statement function of Parse. what names the block in the error for a missing closing brace.

func (*Parser) Bool

func (p *Parser) Bool() (bool, bool)

Bool consumes "yes" or "no". Grammars in the style of OpenBSD usually prefer a "no" prefix for negated options, written as p.Accept("no").

func (*Parser) Duration

func (p *Parser) Duration(min, max time.Duration) (time.Duration, bool)

Duration consumes a duration in the range min to max: a plain number of seconds, or numbers with the units ms, s, m, h, d and w, as in 1h30m.

func (*Parser) Enum

func (p *Parser) Enum(what string, values ...string) (string, bool)

Enum consumes one of the given words. what describes the choice in the error message.

func (*Parser) Errorf

func (p *Parser) Errorf(pos Pos, format string, args ...any)

Errorf reports an error at pos.

func (*Parser) Errors

func (p *Parser) Errors() ErrorList

Errors returns the errors reported so far.

func (*Parser) Expect

func (p *Parser) Expect(words ...string) bool

Expect is Accept, but reports an error if the words do not come next.

func (*Parser) Expected

func (p *Parser) Expected(what string) bool

Expected reports that the current token is not what is expected here. Lexical errors have already been reported when the token was read. It always returns false.

func (*Parser) Is

func (p *Parser) Is(words ...string) bool

Is reports whether the next tokens are the given words, starting with the current token.

func (*Parser) List

func (p *Parser) List(item func() bool) bool

List parses a single item or a brace-enclosed list of items. Newlines and commas between items are ignored. item is called with the current token at the item and consumes it.

func (*Parser) Next

func (p *Parser) Next()

Next moves to the next token.

func (*Parser) Number

func (p *Parser) Number(min, max uint64) (uint64, bool)

Number consumes a decimal number in the range min to max.

func (*Parser) Parse

func (p *Parser) Parse(stmt func() bool) error

Parse reads the whole input. Macro definitions and include statements are handled by the parser; every other statement is passed to stmt. It returns an ErrorList if any error was reported.

func (*Parser) Peek

func (p *Parser) Peek(n int) Token

Peek returns the token n positions after the current one; Peek(1) is the next token.

func (*Parser) Port

func (p *Parser) Port() (uint16, bool)

Port consumes a port number from 1 to 65535.

func (*Parser) Prefix

func (p *Parser) Prefix() (netip.Prefix, bool)

Prefix consumes a network in CIDR notation. Host bits must be zero.

func (*Parser) Text

func (p *Parser) Text(what string) (string, bool)

Text consumes a word or a quoted string and returns its text. A quoted string is never taken as a keyword, so it can hold any value, including spaces, braces and UTF-8. Empty strings are rejected.

func (*Parser) Tok

func (p *Parser) Tok() Token

Tok returns the current token.

func (*Parser) UnusedMacros added in v0.2.0

func (p *Parser) UnusedMacros() []Macro

UnusedMacros returns the macros defined in the configuration, after Parse, that no statement or other macro references, in the order of their definitions. Predefined macros from Options.Macros are not included. pfctl(8) warns about these, since a macro that is defined but never used is often a typing error.

func (*Parser) Word

func (p *Parser) Word(what string) (string, bool)

Word consumes a word and returns it. what describes the expected value in the error message.

type Pos

type Pos struct {
	File string
	Line int
}

Pos is a position in a configuration file.

func (Pos) String

func (p Pos) String() string

type Token

type Token struct {
	Kind Kind
	Text string
	Pos  Pos
}

Token is a lexical token. Text is the word, the unquoted string, or the punctuation character.

func (Token) String

func (t Token) String() string

String describes the token for error messages: "end of line", "end of file", or the quoted text.

Jump to

Keyboard shortcuts

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