Debian Codegraph @

cmd/atomdns/internal/conffile/dispenser.go

raw
1 // Copyright 2015 Light Code Labs, LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package conffile
16
17 import (
18 "errors"
19 "fmt"
20 "io"
21 "net"
22 "os"
23 "path/filepath"
24 "strings"
25 "time"
26
27 "codeberg.org/miekg/dns/cmd/atomdns/internal/iface"
28 )
29
30 // Dispenser is a type that dispenses tokens, similarly to a lexer, except that it can do so with some
31 // notion of structure and has some really convenient methods.
32 type Dispenser struct {
33 filename string
34 keys []string
35 tokens []Token
36 cursor int
37 nesting int
38 handlers []string // previous handlers seen by this handler
39 }
40
41 func NewTestDispenser(input string) Dispenser {
42 tokens, _ := allTokens(strings.NewReader(input))
43 return Dispenser{
44 filename: "Testfile",
45 tokens: tokens,
46 cursor: -1,
47 }
48 }
49
50 // newDispenser returns a Dispenser, ready to use for parsing the given input.
51 func newDispenser(filename string, input io.Reader) Dispenser {
52 tokens, _ := allTokens(input)
53 return Dispenser{
54 filename: filename,
55 tokens: tokens,
56 cursor: -1,
57 }
58 }
59
60 // NewDispenser returns a Dispenser filled with the given tokens.
61 func NewDispenser(filename string, keys []string, tokens []Token, handlers []string) Dispenser {
62 return Dispenser{
63 filename: filename,
64 keys: keys,
65 tokens: tokens,
66 cursor: -1,
67 handlers: handlers,
68 }
69 }
70
71 // Handlers returns all previous handlers seen up until the parsing of this handler. The current handler's
72 // name is included in the list.
73 func (d *Dispenser) Handlers() []string { return d.handlers }
74
75 // Next loads the next token. Returns true if a token was loaded; false otherwise. If false, all tokens
76 // have been consumed.
77 func (d *Dispenser) Next() bool {
78 if d.cursor < len(d.tokens)-1 {
79 d.cursor++
80 return true
81 }
82 return false
83 }
84
85 // NextArg loads the next token if it is on the same line. Returns true if a token was loaded; false
86 // otherwise. If false, all tokens on the line have been consumed. It handles imported tokens correctly.
87 func (d *Dispenser) NextArg() bool {
88 if d.cursor < 0 {
89 d.cursor++
90 return true
91 }
92 if d.cursor >= len(d.tokens) {
93 return false
94 }
95 if d.cursor < len(d.tokens)-1 &&
96 d.tokens[d.cursor].File == d.tokens[d.cursor+1].File &&
97 d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) == d.tokens[d.cursor+1].Line {
98 d.cursor++
99 return true
100 }
101 return false
102 }
103
104 // nextOnSameLine advances the cursor if the next token is on the same line of the same file.
105 func (d *Dispenser) nextOnSameLine() bool {
106 if d.cursor < 0 {
107 d.cursor++
108 return true
109 }
110 if d.cursor >= len(d.tokens)-1 {
111 return false
112 }
113 curr := d.tokens[d.cursor]
114 next := d.tokens[d.cursor+1]
115 if !isNextOnNewLine(curr, next) {
116 d.cursor++
117 return true
118 }
119 return false
120 }
121
122 // NextLine loads the next token only if it is not on the same line as the current token, and returns true if a token was
123 // loaded; false otherwise. If false, there is not another token or it is on the same line. It handles imported tokens correctly.
124 func (d *Dispenser) NextLine() bool {
125 if d.cursor < 0 {
126 d.cursor++
127 return true
128 }
129 if d.cursor >= len(d.tokens) {
130 return false
131 }
132 if d.cursor < len(d.tokens)-1 &&
133 (d.tokens[d.cursor].File != d.tokens[d.cursor+1].File ||
134 d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) < d.tokens[d.cursor+1].Line) {
135 d.cursor++
136 return true
137 }
138 return false
139 }
140
141 // NextBlock can be used as the condition of a for loop to load the next token as long as it opens a block or
142 // is already in a block. It returns true if a token was loaded, or false when the block's closing curly brace
143 // was loaded and thus the block ended. Nested blocks are not supported.
144 func (d *Dispenser) NextBlock(initialNestingLevel int) bool {
145 if d.nesting > initialNestingLevel {
146 if !d.Next() {
147 return false // should be EOF error
148 }
149 if d.Val() == "}" && !d.nextOnSameLine() {
150 d.nesting--
151 } else if d.Val() == "{" && !d.nextOnSameLine() {
152 d.nesting++
153 }
154 return d.nesting > initialNestingLevel
155 }
156 if !d.nextOnSameLine() { // block must open on same line
157 return false
158 }
159 if d.Val() != "{" {
160 d.cursor-- // roll back if not opening brace
161 return false
162 }
163 if !d.Next() {
164 return false
165 }
166 if d.Val() == "}" {
167 // Open and then closed right away
168 return false
169 }
170 d.nesting++
171 return true
172 }
173
174 // Nesting returns the current nesting level. Necessary if using NextBlock()
175 func (d *Dispenser) Nesting() int {
176 return d.nesting
177 }
178
179 // Val gets the text of the current token. If there is no token loaded, it returns empty string.
180 func (d *Dispenser) Val() string {
181 if d.cursor < 0 || d.cursor >= len(d.tokens) {
182 return ""
183 }
184 return d.tokens[d.cursor].Text
185 }
186
187 // Line gets the line number of the current token. If there is no token loaded, it returns 0.
188 func (d *Dispenser) Line() int {
189 if d.cursor < 0 || d.cursor >= len(d.tokens) {
190 return 0
191 }
192 return d.tokens[d.cursor].Line
193 }
194
195 // File gets the filename of the current token. If there is no token loaded,
196 // it returns the filename originally given when parsing started.
197 func (d *Dispenser) File() string {
198 if d.cursor < 0 || d.cursor >= len(d.tokens) {
199 return d.filename
200 }
201 if tokenFilename := d.tokens[d.cursor].File; tokenFilename != "" {
202 return tokenFilename
203 }
204 return d.filename
205 }
206
207 // Keys returns the keys of the block we are parsing right now.
208 func (d *Dispenser) Keys() []string { return d.keys }
209
210 // Args is a convenience function that loads the next arguments (tokens on the same line) into an arbitrary number of strings
211 // pointed to in targets. If there are fewer tokens available than string pointers, the remaining strings will not be changed
212 // and false will be returned. If there were enough tokens available to fill the arguments, then true will be returned.
213 func (d *Dispenser) Args(targets ...*string) bool {
214 enough := true
215 for i := range len(targets) {
216 if !d.NextArg() {
217 enough = false
218 break
219 }
220 *targets[i] = d.Val()
221 }
222 return enough
223 }
224
225 // RemainingArgs loads any more arguments (tokens on the same line) into a slice and returns them. Open curly brace tokens also indicate
226 // the end of arguments, and the curly brace is not included in the return value nor is it loaded.
227 func (d *Dispenser) RemainingArgs() []string {
228 var args []string
229
230 for d.NextArg() {
231 if d.Val() == "{" {
232 d.cursor--
233 break
234 }
235 args = append(args, d.Val())
236 }
237
238 return args
239 }
240
241 // ArgErr returns an argument error, meaning that another argument was expected but not found. In other words,
242 // a line break or open curly brace was encountered instead of an argument.
243 func (d *Dispenser) ArgErr() error {
244 if d.Val() == "{" {
245 return d.Errf("unexpected token '{', expecting argument")
246 }
247 return d.Errf("wrong argument count or unexpected line ending after '%s'", d.Val())
248 }
249
250 // PropErr return a property error, meaning that x was expect but we got y.
251 func (d *Dispenser) PropErr(err ...error) error {
252 if len(err) > 0 {
253 return d.Errf("unexpected property: '%s': %s", d.Val(), err[0].Error())
254 }
255 return d.Errf("unexpected property: %s", d.Val())
256 }
257
258 // SyntaxErr creates a generic syntax error which explains what was found and what was expected.
259 func (d *Dispenser) SyntaxErr(expected string) error {
260 msg := fmt.Sprintf("%s:%d - syntax error: unexpected token '%s', expecting '%s'", d.File(), d.Line(), d.Val(), expected)
261 return errors.New(msg)
262 }
263
264 // PropEmptyErr create a error that a property was not defined or still empty after parsing.
265 func (d *Dispenser) PropEmptyErr(prop string) error {
266 msg := fmt.Sprintf("property: '%s' can not be empty", prop)
267 return errors.New(msg)
268 }
269
270 // EOFErr returns an error indicating that the dispenser reached the end of the input when searching for the next token.
271 func (d *Dispenser) EOFErr() error {
272 return d.Errf("unexpected EOF")
273 }
274
275 // Err generates a custom parse-time error with a message of msg.
276 func (d *Dispenser) Err(err error) error {
277 return fmt.Errorf("%s:%d - error parsing or initializing: %w", d.File(), d.Line(), err)
278 }
279
280 // Errf is like Err, but for formatted error messages
281 func (d *Dispenser) Errf(format string, args ...any) error { return d.Err(fmt.Errorf(format, args...)) }
282
283 // numLineBreaks counts how many line breaks are in the token value given by the token index tknIdx. It returns 0 if the
284 // token does not exist or there are no line breaks.
285 func (d *Dispenser) numLineBreaks(tknIdx int) int {
286 if tknIdx < 0 || tknIdx >= len(d.tokens) {
287 return 0
288 }
289 return strings.Count(d.tokens[tknIdx].Text, "\n")
290 }
291
292 // isNewLine determines whether the current token is on a different line (higher line number) than the
293 // previous token. It handles imported tokens correctly. If there isn't a previous token, it returns true.
294 func (d *Dispenser) isNewLine() bool {
295 if d.cursor < 1 {
296 return true
297 }
298 if d.cursor > len(d.tokens)-1 {
299 return false
300 }
301
302 prev := d.tokens[d.cursor-1]
303 curr := d.tokens[d.cursor]
304 return isNextOnNewLine(prev, curr)
305 }
306
307 // Addr parses the host and port in the current token, i.e. 127.0.0.0:53 is parsed and returned, same for
308 // IPv6 addresses [2004:32]:53. If there is no port the default port will be added (53).
309 func (d *Dispenser) Addr() (string, error) { return addr(d.Val()) }
310
311 // RemainingAddrs calls RemainingArgs and return each actual address. If the address does not have
312 // port :53 is added.
313 func (d *Dispenser) RemainingAddrs() ([]string, error) {
314 args := d.RemainingArgs()
315 for i := range args {
316 addr, err := addr(args[i])
317 if err != nil {
318 return nil, err
319 }
320 args[i] = addr
321 }
322 return args, nil
323 }
324
325 func addr(s string) (string, error) {
326 addr, port, err := net.SplitHostPort(s)
327 if err != nil {
328 if net.ParseIP(s) == nil {
329 return "", fmt.Errorf("failed to parse '%s' as IP", s)
330 }
331 return net.JoinHostPort(s, "53"), nil
332 }
333 return net.JoinHostPort(addr, port), nil
334 }
335
336 // RemainingIPs calls RemainingArgs and return all IPs. If a arg does not look like an IP, it is assume to be
337 // a interface name.
338 func (d *Dispenser) RemainingIPs() ([]string, error) {
339 args := d.RemainingArgs()
340 ips := []string{}
341 for i := range args {
342 x := net.ParseIP(args[i])
343 if x != nil {
344 ips = append(ips, args[i])
345 continue
346 }
347 ifips := iface.List(args[i])
348 if len(ifips) == 0 {
349 return nil, fmt.Errorf("failed to find routable IPs on '%s' interface", args[i])
350 }
351 ips = append(ips, ifips...)
352 }
353 return ips, nil
354 }
355
356 // RemainingDurations calls RemainingArgs and returns all arguments as parsed time.Durations or an error.
357 func (d *Dispenser) RemainingDurations() ([]time.Duration, error) {
358 args := d.RemainingArgs()
359 durs := []time.Duration{}
360 for i := range args {
361 x, err := time.ParseDuration(args[i])
362 if err != nil {
363 return durs, err
364 }
365 durs = append(durs, x)
366 }
367 return durs, nil
368 }
369
370 // Tilde will replace "~" as the first path element with the home directory of the user running us.
371 func Tilde(s string) string {
372 if !strings.HasPrefix(s, "~") {
373 return s
374 }
375 home, err := os.UserHomeDir()
376 if err != nil {
377 return s
378 }
379 return filepath.Join(home, strings.TrimPrefix(s, "~"))
380 }