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.
- Macro references inside words: as in yylex() of OpenBSD's parse.y, the name ends at the first character that is not a letter, digit or underscore, and the rest of the word is kept, so with movies = "/export/movies" the word $movies/plex is /export/movies/plex. OpenBSD cannot do this for $x/y, since / ends an unquoted word there; obsdconf allows / in words. ${name} delimits the name, as in the shell, so that a letter, digit or underscore may follow it, as in ${base}_old; OpenBSD has no such form. A word may hold several references, as in $host:$port, and text before them. Each must expand to a single word: $lan/x is an error if lan is a list, while $lan alone still stands for the list. In an unquoted word every $ starts a reference and a $ without a name is an error, so values with a literal $ must be quoted. Quoted strings are never expanded.
- 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 ¶
- Constants
- type Error
- type ErrorList
- type Kind
- type Macro
- type Options
- type Parser
- func (p *Parser) Accept(words ...string) bool
- func (p *Parser) Addr() (netip.Addr, bool)
- func (p *Parser) Block(what string, stmt func() bool) bool
- func (p *Parser) Bool() (bool, bool)
- func (p *Parser) Duration(min, max time.Duration) (time.Duration, bool)
- func (p *Parser) Enum(what string, values ...string) (string, bool)
- func (p *Parser) Errorf(pos Pos, format string, args ...any)
- func (p *Parser) Errors() ErrorList
- func (p *Parser) Expect(words ...string) bool
- func (p *Parser) Expected(what string) bool
- func (p *Parser) Is(words ...string) bool
- func (p *Parser) List(item func() bool) bool
- func (p *Parser) Next()
- func (p *Parser) Number(min, max uint64) (uint64, bool)
- func (p *Parser) Parse(stmt func() bool) error
- func (p *Parser) Peek(n int) Token
- func (p *Parser) Port() (uint16, bool)
- func (p *Parser) Prefix() (netip.Prefix, bool)
- func (p *Parser) Text(what string) (string, bool)
- func (p *Parser) Tok() Token
- func (p *Parser) UnusedMacros() []Macro
- func (p *Parser) Word(what string) (string, bool)
- type Pos
- type Token
Examples ¶
Constants ¶
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 ErrorList ¶
type ErrorList []*Error
ErrorList holds all errors of a parse, in the order they were found.
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 ¶
New returns a parser for src. name is used in error messages and as the base for relative include paths.
func (*Parser) Accept ¶
Accept consumes the given words if they come next, as in p.Accept("client", "id"), and reports whether it did.
func (*Parser) Block ¶
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 ¶
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 ¶
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 ¶
Enum consumes one of the given words. what describes the choice in the error message.
func (*Parser) Expected ¶
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 ¶
Is reports whether the next tokens are the given words, starting with the current token.
func (*Parser) List ¶
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) Parse ¶
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 ¶
Peek returns the token n positions after the current one; Peek(1) is the next token.
func (*Parser) Text ¶
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) UnusedMacros ¶ added in v0.2.0
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.