| 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 |
"io" |
| 19 |
"net" |
| 20 |
"os" |
| 21 |
"path/filepath" |
| 22 |
"strings" |
| 23 |
|
| 24 |
"codeberg.org/miekg/dns/cmd/atomdns/internal/dnsreverse" |
| 25 |
) |
| 26 |
|
| 27 |
// Parse parses the input just enough to group tokens, in order, by server block. No further parsing is performed. |
| 28 |
// Handler blocks are returned in the order in which they appear. |
| 29 |
func Parse(filename string, input io.Reader) ([]HandlerBlock, error) { |
| 30 |
p := parser{Dispenser: newDispenser(filename, input)} |
| 31 |
return p.parseAll() |
| 32 |
} |
| 33 |
|
| 34 |
// AllTokens lexes the entire input, but does not parse it. It returns all the tokens from the input, unstructured |
| 35 |
// and in order. |
| 36 |
func allTokens(input io.Reader) ([]Token, error) { |
| 37 |
l := new(lexer) |
| 38 |
err := l.load(input) |
| 39 |
if err != nil { |
| 40 |
return nil, err |
| 41 |
} |
| 42 |
var tokens []Token |
| 43 |
for l.next() { |
| 44 |
tokens = append(tokens, l.token) |
| 45 |
} |
| 46 |
return tokens, nil |
| 47 |
} |
| 48 |
|
| 49 |
type parser struct { |
| 50 |
Dispenser |
| 51 |
block HandlerBlock // current server block being parsed |
| 52 |
eof bool // if we encounter a valid EOF in a hard place |
| 53 |
definedSnippets map[string][]Token |
| 54 |
expansions int // max number of expansions, either snippits or files |
| 55 |
} |
| 56 |
|
| 57 |
func (p *parser) parseAll() ([]HandlerBlock, error) { |
| 58 |
var blocks []HandlerBlock |
| 59 |
|
| 60 |
for p.Next() { |
| 61 |
err := p.parseOne() |
| 62 |
if err != nil { |
| 63 |
return blocks, err |
| 64 |
} |
| 65 |
// block with no keys is a global block, there can only be one of those |
| 66 |
if len(p.block.Keys) == 0 && len(p.block.Tokens) > 0 { |
| 67 |
for i := range blocks { |
| 68 |
if len(blocks[i].Keys) == 0 { |
| 69 |
return nil, p.Errf("redeclaration of global block") |
| 70 |
} |
| 71 |
} |
| 72 |
} |
| 73 |
if len(p.block.Tokens) > 0 { |
| 74 |
blocks = append(blocks, p.block) |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
return blocks, nil |
| 79 |
} |
| 80 |
|
| 81 |
func (p *parser) parseOne() error { |
| 82 |
p.block = HandlerBlock{Tokens: make(map[string][]Token)} |
| 83 |
|
| 84 |
return p.begin() |
| 85 |
} |
| 86 |
|
| 87 |
func (p *parser) begin() error { |
| 88 |
if len(p.tokens) == 0 { |
| 89 |
return nil |
| 90 |
} |
| 91 |
|
| 92 |
err := p.addresses() |
| 93 |
if err != nil { |
| 94 |
return err |
| 95 |
} |
| 96 |
|
| 97 |
if p.eof { |
| 98 |
// this happens if the Caddyfile consists of only |
| 99 |
// a line of addresses and nothing else |
| 100 |
return nil |
| 101 |
} |
| 102 |
|
| 103 |
if ok, name := p.isSnippet(); ok { |
| 104 |
if p.definedSnippets == nil { |
| 105 |
p.definedSnippets = map[string][]Token{} |
| 106 |
} |
| 107 |
if _, found := p.definedSnippets[name]; found { |
| 108 |
return p.Errf("redeclaration of previously declared snippet %s", name) |
| 109 |
} |
| 110 |
// consume all tokens til matched close brace |
| 111 |
tokens, err := p.snippetTokens() |
| 112 |
if err != nil { |
| 113 |
return err |
| 114 |
} |
| 115 |
p.definedSnippets[name] = tokens |
| 116 |
// empty block keys so we don't save this block as a real server. |
| 117 |
p.block.Keys = nil |
| 118 |
return nil |
| 119 |
} |
| 120 |
|
| 121 |
return p.blockContents() |
| 122 |
} |
| 123 |
|
| 124 |
func (p *parser) addresses() error { |
| 125 |
var expectingAnother bool |
| 126 |
|
| 127 |
for { |
| 128 |
tkn := replaceEnvVars(p.Val()) |
| 129 |
|
| 130 |
// special case: import directive replaces tokens during parse-time |
| 131 |
if tkn == "import" && p.isNewLine() { |
| 132 |
err := p.doImport() |
| 133 |
if err != nil { |
| 134 |
return err |
| 135 |
} |
| 136 |
continue |
| 137 |
} |
| 138 |
|
| 139 |
// Open brace definitely indicates end of addresses |
| 140 |
if tkn == "{" { |
| 141 |
if expectingAnother { |
| 142 |
return p.Errf("expected another address but had %s - check for extra comma", tkn) |
| 143 |
} |
| 144 |
break |
| 145 |
} |
| 146 |
|
| 147 |
if tkn != "" { // empty token possible if user typed "" |
| 148 |
// Trailing comma indicates another address will follow, which |
| 149 |
// may possibly be on the next line |
| 150 |
if tkn[len(tkn)-1] == ',' { |
| 151 |
tkn = tkn[:len(tkn)-1] |
| 152 |
expectingAnother = true |
| 153 |
} else { |
| 154 |
expectingAnother = false // but we may still see another one on this line |
| 155 |
} |
| 156 |
|
| 157 |
// If tkn parses a CIDR e.g 192.168.0.0/16 is a reverse zone syntax we we want to expand that for |
| 158 |
// user convience. |
| 159 |
_, ipnet, err := net.ParseCIDR(tkn) |
| 160 |
if err != nil { |
| 161 |
p.block.Keys = append(p.block.Keys, tkn) |
| 162 |
} else { |
| 163 |
p.block.Keys = append(p.block.Keys, dnsreverse.Zones(ipnet)...) |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
// Advance token and possibly break out of loop or return error |
| 168 |
hasNext := p.Next() |
| 169 |
if expectingAnother && !hasNext { |
| 170 |
return p.EOFErr() |
| 171 |
} |
| 172 |
if !hasNext { |
| 173 |
p.eof = true |
| 174 |
break // EOF |
| 175 |
} |
| 176 |
if !expectingAnother && p.isNewLine() { |
| 177 |
break |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
return nil |
| 182 |
} |
| 183 |
|
| 184 |
func (p *parser) blockContents() error { |
| 185 |
errOpenCurlyBrace := p.openCurlyBrace() |
| 186 |
if errOpenCurlyBrace != nil { |
| 187 |
// single-server configs don't need curly braces |
| 188 |
p.cursor-- |
| 189 |
} |
| 190 |
|
| 191 |
err := p.directives() |
| 192 |
if err != nil { |
| 193 |
return err |
| 194 |
} |
| 195 |
|
| 196 |
// Only look for close curly brace if there was an opening |
| 197 |
if errOpenCurlyBrace == nil { |
| 198 |
err = p.closeCurlyBrace() |
| 199 |
if err != nil { |
| 200 |
return err |
| 201 |
} |
| 202 |
} |
| 203 |
|
| 204 |
return nil |
| 205 |
} |
| 206 |
|
| 207 |
// directives parses through all the lines for directives |
| 208 |
// and it expects the next token to be the first |
| 209 |
// directive. It goes until EOF or closing curly brace |
| 210 |
// which ends the server block. |
| 211 |
func (p *parser) directives() error { |
| 212 |
for p.Next() { |
| 213 |
// end of server block |
| 214 |
if p.Val() == "}" { |
| 215 |
break |
| 216 |
} |
| 217 |
|
| 218 |
// special case: import directive replaces tokens during parse-time |
| 219 |
if p.Val() == "import" { |
| 220 |
err := p.doImport() |
| 221 |
if err != nil { |
| 222 |
return err |
| 223 |
} |
| 224 |
p.cursor-- // cursor is advanced when we continue, so roll back one more |
| 225 |
continue |
| 226 |
} |
| 227 |
|
| 228 |
// normal case: parse a directive on this line |
| 229 |
if err := p.directive(); err != nil { |
| 230 |
return err |
| 231 |
} |
| 232 |
} |
| 233 |
return nil |
| 234 |
} |
| 235 |
|
| 236 |
// doImport swaps out the import directive and its argument |
| 237 |
// (a total of 2 tokens) with the tokens in the specified file |
| 238 |
// or globbing pattern. When the function returns, the cursor |
| 239 |
// is on the token before where the import directive was. In |
| 240 |
// other words, call Next() to access the first token that was |
| 241 |
// imported. |
| 242 |
func (p *parser) doImport() error { |
| 243 |
// syntax checks |
| 244 |
if !p.NextArg() { |
| 245 |
return p.ArgErr() |
| 246 |
} |
| 247 |
importPattern := replaceEnvVars(p.Val()) |
| 248 |
if importPattern == "" { |
| 249 |
return p.Errf("import requires a non-empty filepath") |
| 250 |
} |
| 251 |
if p.NextArg() { |
| 252 |
return p.Errf("import takes only one argument (glob pattern or file)") |
| 253 |
} |
| 254 |
// splice out the import directive and its argument (2 tokens total) |
| 255 |
tokensBefore := p.tokens[:p.cursor-1] |
| 256 |
tokensAfter := p.tokens[p.cursor+1:] |
| 257 |
var importedTokens []Token |
| 258 |
|
| 259 |
// first check snippets. That is a simple, non-recursive replacement |
| 260 |
if p.definedSnippets != nil && p.definedSnippets[importPattern] != nil { |
| 261 |
p.expansions++ |
| 262 |
importedTokens = p.definedSnippets[importPattern] |
| 263 |
} else { |
| 264 |
p.expansions++ |
| 265 |
// make path relative to the file of the _token_ being processed rather |
| 266 |
// than current working directory (issue #867) and then use glob to get |
| 267 |
// list of matching filenames |
| 268 |
absFile, err := filepath.Abs(p.File()) |
| 269 |
if err != nil { |
| 270 |
return p.Errf("failed to get absolute path of file: %s: %v", p.filename, err) |
| 271 |
} |
| 272 |
|
| 273 |
var matches []string |
| 274 |
var globPattern string |
| 275 |
if !filepath.IsAbs(importPattern) { |
| 276 |
globPattern = filepath.Join(filepath.Dir(absFile), importPattern) |
| 277 |
} else { |
| 278 |
globPattern = importPattern |
| 279 |
} |
| 280 |
if strings.Count(globPattern, "*") > 1 || strings.Count(globPattern, "?") > 1 || |
| 281 |
(strings.Contains(globPattern, "[") && strings.Contains(globPattern, "]")) { |
| 282 |
// See issue #2096 - a pattern with many glob expansions can hang for too long |
| 283 |
return p.Errf("glob pattern may only contain one wildcard (*), but has others: %s", globPattern) |
| 284 |
} |
| 285 |
matches, err = filepath.Glob(globPattern) |
| 286 |
if err != nil { |
| 287 |
return p.Errf("failed to use import pattern %s: %v", importPattern, err) |
| 288 |
} |
| 289 |
if len(matches) == 0 { |
| 290 |
return p.Errf("file to import not found: %s", importPattern) |
| 291 |
} |
| 292 |
|
| 293 |
// collect all the imported tokens |
| 294 |
|
| 295 |
for _, importFile := range matches { |
| 296 |
newTokens, err := p.doSingleImport(importFile) |
| 297 |
if err != nil { |
| 298 |
return err |
| 299 |
} |
| 300 |
importedTokens = append(importedTokens, newTokens...) |
| 301 |
} |
| 302 |
} |
| 303 |
if p.expansions > 1000 { |
| 304 |
return p.Errf("maximum snippet import depth (%d) exceeded", 1000) |
| 305 |
} |
| 306 |
|
| 307 |
// splice the imported tokens in the place of the import statement |
| 308 |
// and rewind cursor so Next() will land on first imported token |
| 309 |
p.tokens = append(tokensBefore, append(importedTokens, tokensAfter...)...) |
| 310 |
p.cursor-- |
| 311 |
|
| 312 |
return nil |
| 313 |
} |
| 314 |
|
| 315 |
// doSingleImport lexes the individual file at importFile and returns |
| 316 |
// its tokens or an error, if any. |
| 317 |
func (p *parser) doSingleImport(importFile string) ([]Token, error) { |
| 318 |
file, err := os.Open(importFile) |
| 319 |
if err != nil { |
| 320 |
return nil, p.Errf("could not import %s: %v", importFile, err) |
| 321 |
} |
| 322 |
defer file.Close() |
| 323 |
|
| 324 |
if info, err := file.Stat(); err != nil { |
| 325 |
return nil, p.Errf("could not import %s: %v", importFile, err) |
| 326 |
} else if info.IsDir() { |
| 327 |
return nil, p.Errf("could not import %s: is a directory", importFile) |
| 328 |
} |
| 329 |
|
| 330 |
importedTokens, err := allTokens(file) |
| 331 |
if err != nil { |
| 332 |
return nil, p.Errf("could not read tokens while importing %s: %v", importFile, err) |
| 333 |
} |
| 334 |
|
| 335 |
// Tack the file path onto these tokens so errors show the imported file's name |
| 336 |
// (we use full, absolute path to avoid bugs: issue #1892) |
| 337 |
filename, err := filepath.Abs(importFile) |
| 338 |
if err != nil { |
| 339 |
return nil, p.Errf("failed to get absolute path of file: %s: %v", p.filename, err) |
| 340 |
} |
| 341 |
for i := range importedTokens { |
| 342 |
importedTokens[i].File = filename |
| 343 |
} |
| 344 |
|
| 345 |
return importedTokens, nil |
| 346 |
} |
| 347 |
|
| 348 |
// directive collects tokens until the directive's scope |
| 349 |
// closes (either end of line or end of curly brace block). |
| 350 |
// It expects the currently-loaded token to be a directive |
| 351 |
// (or } that ends a server block). The collected tokens |
| 352 |
// are loaded into the current server block for later use |
| 353 |
// by directive setup functions. |
| 354 |
func (p *parser) directive() error { |
| 355 |
dir := replaceEnvVars(p.Val()) |
| 356 |
nesting := 0 |
| 357 |
|
| 358 |
// The directive itself is appended as a relevant token |
| 359 |
p.block.Tokens[dir] = append(p.block.Tokens[dir], p.tokens[p.cursor]) |
| 360 |
p.block.Directives = append(p.block.Directives, dir) |
| 361 |
|
| 362 |
for p.Next() { |
| 363 |
if p.Val() == "{" { |
| 364 |
nesting++ |
| 365 |
} else if p.isNewLine() && nesting == 0 { |
| 366 |
p.cursor-- // read too far |
| 367 |
break |
| 368 |
} else if p.Val() == "}" && nesting > 0 { |
| 369 |
nesting-- |
| 370 |
} else if p.Val() == "}" && nesting == 0 { |
| 371 |
return p.Errf("unexpected '}' because no matching opening brace") |
| 372 |
} else if p.Val() == "import" && p.isNewLine() { |
| 373 |
if err := p.doImport(); err != nil { |
| 374 |
return err |
| 375 |
} |
| 376 |
p.cursor-- // cursor is advanced when we continue, so roll back one more |
| 377 |
continue |
| 378 |
} |
| 379 |
p.tokens[p.cursor].Text = replaceEnvVars(p.tokens[p.cursor].Text) |
| 380 |
p.block.Tokens[dir] = append(p.block.Tokens[dir], p.tokens[p.cursor]) |
| 381 |
} |
| 382 |
|
| 383 |
if nesting > 0 { |
| 384 |
return p.EOFErr() |
| 385 |
} |
| 386 |
return nil |
| 387 |
} |
| 388 |
|
| 389 |
// openCurlyBrace expects the current token to be an |
| 390 |
// opening curly brace. This acts like an assertion |
| 391 |
// because it returns an error if the token is not |
| 392 |
// a opening curly brace. It does NOT advance the token. |
| 393 |
func (p *parser) openCurlyBrace() error { |
| 394 |
if p.Val() != "{" { |
| 395 |
return p.SyntaxErr("{") |
| 396 |
} |
| 397 |
return nil |
| 398 |
} |
| 399 |
|
| 400 |
// closeCurlyBrace expects the current token to be |
| 401 |
// a closing curly brace. This acts like an assertion |
| 402 |
// because it returns an error if the token is not |
| 403 |
// a closing curly brace. It does NOT advance the token. |
| 404 |
func (p *parser) closeCurlyBrace() error { |
| 405 |
if p.Val() != "}" { |
| 406 |
return p.SyntaxErr("}") |
| 407 |
} |
| 408 |
return nil |
| 409 |
} |
| 410 |
|
| 411 |
// replaceEnvVars replaces environment variables that appear in the token |
| 412 |
// and understands both the $UNIX and %WINDOWS% syntaxes. |
| 413 |
func replaceEnvVars(s string) string { |
| 414 |
s = replaceEnvReferences(s, "{%", "%}") |
| 415 |
s = replaceEnvReferences(s, "{$", "}") |
| 416 |
return s |
| 417 |
} |
| 418 |
|
| 419 |
// replaceEnvReferences performs the actual replacement of env variables |
| 420 |
// in s, given the placeholder start and placeholder end strings. |
| 421 |
func replaceEnvReferences(s, refStart, refEnd string) string { |
| 422 |
index := strings.Index(s, refStart) |
| 423 |
for index != -1 { |
| 424 |
endIndex := strings.Index(s[index:], refEnd) |
| 425 |
if endIndex == -1 { |
| 426 |
break |
| 427 |
} |
| 428 |
|
| 429 |
endIndex += index |
| 430 |
if endIndex > index+len(refStart) { |
| 431 |
ref := s[index : endIndex+len(refEnd)] |
| 432 |
s = strings.ReplaceAll(s, ref, os.Getenv(ref[len(refStart):len(ref)-len(refEnd)])) |
| 433 |
} else { |
| 434 |
return s |
| 435 |
} |
| 436 |
index = strings.Index(s, refStart) |
| 437 |
} |
| 438 |
return s |
| 439 |
} |
| 440 |
|
| 441 |
// HandlerBlock associates any number of keys (usually addresses |
| 442 |
// of some sort) with tokens (grouped by directive name). |
| 443 |
type HandlerBlock struct { |
| 444 |
Keys []string |
| 445 |
Tokens map[string][]Token |
| 446 |
Directives []string // Directives tracks the original order of the directives. |
| 447 |
} |
| 448 |
|
| 449 |
type Directives struct { |
| 450 |
Name string |
| 451 |
Tokens []Token |
| 452 |
} |
| 453 |
|
| 454 |
func (p *parser) isSnippet() (bool, string) { |
| 455 |
keys := p.block.Keys |
| 456 |
// A snippet block is a single key with parens. Nothing else qualifies. |
| 457 |
if len(keys) == 1 && strings.HasPrefix(keys[0], "(") && strings.HasSuffix(keys[0], ")") { |
| 458 |
return true, strings.TrimSuffix(keys[0][1:], ")") |
| 459 |
} |
| 460 |
return false, "" |
| 461 |
} |
| 462 |
|
| 463 |
// read and store everything in a block for later replay. |
| 464 |
func (p *parser) snippetTokens() ([]Token, error) { |
| 465 |
// TODO: disallow imports in snippets for simplicity at import time |
| 466 |
// snippet must have curlies. |
| 467 |
err := p.openCurlyBrace() |
| 468 |
if err != nil { |
| 469 |
return nil, err |
| 470 |
} |
| 471 |
count := 1 |
| 472 |
tokens := []Token{} |
| 473 |
for p.Next() { |
| 474 |
if p.Val() == "}" { |
| 475 |
count-- |
| 476 |
if count == 0 { |
| 477 |
break |
| 478 |
} |
| 479 |
} |
| 480 |
if p.Val() == "{" { |
| 481 |
count++ |
| 482 |
} |
| 483 |
tokens = append(tokens, p.tokens[p.cursor]) |
| 484 |
} |
| 485 |
// make sure we're matched up |
| 486 |
if count != 0 { |
| 487 |
return nil, p.SyntaxErr("}") |
| 488 |
} |
| 489 |
return tokens, nil |
| 490 |
} |