Debian Codegraph @

caddyconfig/caddyfile/parse.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
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 caddyfile
16
17 import (
18 "bytes"
19 "fmt"
20 "io"
21 "os"
22 "path/filepath"
23 "strings"
24
25 "go.uber.org/zap"
26
27 "github.com/caddyserver/caddy/v2"
28 )
29
30 // Parse parses the input just enough to group tokens, in
31 // order, by server block. No further parsing is performed.
32 // Server blocks are returned in the order in which they appear.
33 // Directives that do not appear in validDirectives will cause
34 // an error. If you do not want to check for valid directives,
35 // pass in nil instead.
36 //
37 // Environment variables in {$ENVIRONMENT_VARIABLE} notation
38 // will be replaced before parsing begins.
39 func Parse(filename string, input []byte) ([]ServerBlock, error) {
40 // unfortunately, we must copy the input because parsing must
41 // remain a read-only operation, but we have to expand environment
42 // variables before we parse, which changes the underlying array (#4422)
43 inputCopy := make([]byte, len(input))
44 copy(inputCopy, input)
45
46 tokens, err := allTokens(filename, inputCopy)
47 if err != nil {
48 return nil, err
49 }
50 p := parser{
51 Dispenser: NewDispenser(tokens),
52 importGraph: importGraph{
53 nodes: make(map[string]struct{}),
54 edges: make(adjacency),
55 },
56 }
57 return p.parseAll()
58 }
59
60 // allTokens lexes the entire input, but does not parse it.
61 // It returns all the tokens from the input, unstructured
62 // and in order. It may mutate input as it expands env vars.
63 func allTokens(filename string, input []byte) ([]Token, error) {
64 return Tokenize(replaceEnvVars(input), filename)
65 }
66
67 // replaceEnvVars replaces all occurrences of environment variables.
68 // It mutates the underlying array and returns the updated slice.
69 func replaceEnvVars(input []byte) []byte {
70 var offset int
71 for {
72 begin := bytes.Index(input[offset:], spanOpen)
73 if begin < 0 {
74 break
75 }
76 begin += offset // make beginning relative to input, not offset
77 end := bytes.Index(input[begin+len(spanOpen):], spanClose)
78 if end < 0 {
79 break
80 }
81 end += begin + len(spanOpen) // make end relative to input, not begin
82
83 // get the name; if there is no name, skip it
84 envString := input[begin+len(spanOpen) : end]
85 if len(envString) == 0 {
86 offset = end + len(spanClose)
87 continue
88 }
89
90 // split the string into a key and an optional default
91 envParts := strings.SplitN(string(envString), envVarDefaultDelimiter, 2)
92
93 // do a lookup for the env var, replace with the default if not found
94 envVarValue, found := os.LookupEnv(envParts[0])
95 if !found && len(envParts) == 2 {
96 envVarValue = envParts[1]
97 }
98
99 // get the value of the environment variable
100 // note that this causes one-level deep chaining
101 envVarBytes := []byte(envVarValue)
102
103 // splice in the value
104 input = append(input[:begin],
105 append(envVarBytes, input[end+len(spanClose):]...)...)
106
107 // continue at the end of the replacement
108 offset = begin + len(envVarBytes)
109 }
110 return input
111 }
112
113 type parser struct {
114 *Dispenser
115 block ServerBlock // current server block being parsed
116 eof bool // if we encounter a valid EOF in a hard place
117 definedSnippets map[string][]Token
118 nesting int
119 importGraph importGraph
120 }
121
122 func (p *parser) parseAll() ([]ServerBlock, error) {
123 var blocks []ServerBlock
124
125 for p.Next() {
126 err := p.parseOne()
127 if err != nil {
128 return blocks, err
129 }
130 if len(p.block.Keys) > 0 || len(p.block.Segments) > 0 {
131 blocks = append(blocks, p.block)
132 }
133 if p.nesting > 0 {
134 return blocks, p.EOFErr()
135 }
136 }
137
138 return blocks, nil
139 }
140
141 func (p *parser) parseOne() error {
142 p.block = ServerBlock{}
143 return p.begin()
144 }
145
146 func (p *parser) begin() error {
147 if len(p.tokens) == 0 {
148 return nil
149 }
150
151 err := p.addresses()
152 if err != nil {
153 return err
154 }
155
156 if p.eof {
157 // this happens if the Caddyfile consists of only
158 // a line of addresses and nothing else
159 return nil
160 }
161
162 if ok, name := p.isNamedRoute(); ok {
163 // we just need a dummy leading token to ease parsing later
164 nameToken := p.Token()
165 nameToken.Text = name
166
167 // named routes only have one key, the route name
168 p.block.Keys = []Token{nameToken}
169 p.block.IsNamedRoute = true
170
171 // get all the tokens from the block, including the braces
172 tokens, err := p.blockTokens(true)
173 if err != nil {
174 return err
175 }
176 tokens = append([]Token{nameToken}, tokens...)
177 p.block.Segments = []Segment{tokens}
178 return nil
179 }
180
181 if ok, name := p.isSnippet(); ok {
182 if p.definedSnippets == nil {
183 p.definedSnippets = map[string][]Token{}
184 }
185 if _, found := p.definedSnippets[name]; found {
186 return p.Errf("redeclaration of previously declared snippet %s", name)
187 }
188 // consume all tokens til matched close brace
189 tokens, err := p.blockTokens(false)
190 if err != nil {
191 return err
192 }
193 // Just as we need to track which file the token comes from, we need to
194 // keep track of which snippet the token comes from. This is helpful
195 // in tracking import cycles across files/snippets by namespacing them.
196 // Without this, we end up with false-positives in cycle-detection.
197 for k, v := range tokens {
198 v.snippetName = name
199 tokens[k] = v
200 }
201 p.definedSnippets[name] = tokens
202 // empty block keys so we don't save this block as a real server.
203 p.block.Keys = nil
204 return nil
205 }
206
207 return p.blockContents()
208 }
209
210 func (p *parser) addresses() error {
211 var expectingAnother bool
212
213 for {
214 value := p.Val()
215 token := p.Token()
216
217 // Reject request matchers if trying to define them globally
218 if strings.HasPrefix(value, "@") {
219 return p.Errf("request matchers may not be defined globally, they must be in a site block; found %s", value)
220 }
221
222 // Special case: import directive replaces tokens during parse-time
223 if value == "import" && p.isNewLine() {
224 err := p.doImport(0)
225 if err != nil {
226 return err
227 }
228 continue
229 }
230
231 // Open brace definitely indicates end of addresses
232 if value == "{" {
233 if expectingAnother {
234 return p.Errf("Expected another address but had '%s' - check for extra comma", value)
235 }
236 // Mark this server block as being defined with braces.
237 // This is used to provide a better error message when
238 // the user may have tried to define two server blocks
239 // without having used braces, which are required in
240 // that case.
241 p.block.HasBraces = true
242 break
243 }
244
245 // Users commonly forget to place a space between the address and the '{'
246 if strings.HasSuffix(value, "{") {
247 return p.Errf("Site addresses cannot end with a curly brace: '%s' - put a space between the token and the brace", value)
248 }
249
250 if value != "" { // empty token possible if user typed ""
251 // Trailing comma indicates another address will follow, which
252 // may possibly be on the next line
253 if value[len(value)-1] == ',' {
254 value = value[:len(value)-1]
255 expectingAnother = true
256 } else {
257 expectingAnother = false // but we may still see another one on this line
258 }
259
260 // If there's a comma here, it's probably because they didn't use a space
261 // between their two domains, e.g. "foo.com,bar.com", which would not be
262 // parsed as two separate site addresses.
263 if strings.Contains(value, ",") {
264 return p.Errf("Site addresses cannot contain a comma ',': '%s' - put a space after the comma to separate site addresses", value)
265 }
266
267 // After the above, a comma surrounded by spaces would result
268 // in an empty token which we should ignore
269 if value != "" {
270 // Add the token as a site address
271 token.Text = value
272 p.block.Keys = append(p.block.Keys, token)
273 }
274 }
275
276 // Advance token and possibly break out of loop or return error
277 hasNext := p.Next()
278 if expectingAnother && !hasNext {
279 return p.EOFErr()
280 }
281 if !hasNext {
282 p.eof = true
283 break // EOF
284 }
285 if !expectingAnother && p.isNewLine() {
286 break
287 }
288 }
289
290 return nil
291 }
292
293 func (p *parser) blockContents() error {
294 errOpenCurlyBrace := p.openCurlyBrace()
295 if errOpenCurlyBrace != nil {
296 // single-server configs don't need curly braces
297 p.cursor--
298 }
299
300 err := p.directives()
301 if err != nil {
302 return err
303 }
304
305 // only look for close curly brace if there was an opening
306 if errOpenCurlyBrace == nil {
307 err = p.closeCurlyBrace()
308 if err != nil {
309 return err
310 }
311 }
312
313 return nil
314 }
315
316 // directives parses through all the lines for directives
317 // and it expects the next token to be the first
318 // directive. It goes until EOF or closing curly brace
319 // which ends the server block.
320 func (p *parser) directives() error {
321 for p.Next() {
322 // end of server block
323 if p.Val() == "}" {
324 // p.nesting has already been decremented
325 break
326 }
327
328 // special case: import directive replaces tokens during parse-time
329 if p.Val() == "import" {
330 err := p.doImport(1)
331 if err != nil {
332 return err
333 }
334 p.cursor-- // cursor is advanced when we continue, so roll back one more
335 continue
336 }
337
338 // normal case: parse a directive as a new segment
339 // (a "segment" is a line which starts with a directive
340 // and which ends at the end of the line or at the end of
341 // the block that is opened at the end of the line)
342 if err := p.directive(); err != nil {
343 return err
344 }
345 }
346
347 return nil
348 }
349
350 // doImport swaps out the import directive and its argument
351 // (a total of 2 tokens) with the tokens in the specified file
352 // or globbing pattern. When the function returns, the cursor
353 // is on the token before where the import directive was. In
354 // other words, call Next() to access the first token that was
355 // imported.
356 func (p *parser) doImport(nesting int) error {
357 // syntax checks
358 if !p.NextArg() {
359 return p.ArgErr()
360 }
361 importPattern := p.Val()
362 if importPattern == "" {
363 return p.Err("Import requires a non-empty filepath")
364 }
365
366 // grab remaining args as placeholder replacements
367 args := p.RemainingArgs()
368
369 // set up a replacer for non-variadic args replacement
370 repl := makeArgsReplacer(args)
371
372 // grab all the tokens (if it exists) from within a block that follows the import
373 var blockTokens []Token
374 for currentNesting := p.Nesting(); p.NextBlock(currentNesting); {
375 blockTokens = append(blockTokens, p.Token())
376 }
377 // initialize with size 1
378 blockMapping := make(map[string][]Token, 1)
379 if len(blockTokens) > 0 {
380 // use such tokens to create a new dispenser, and then use it to parse each block
381 bd := NewDispenser(blockTokens)
382
383 // one iteration processes one sub-block inside the import
384 for bd.Next() {
385 currentMappingKey := bd.Val()
386
387 if currentMappingKey == "{" {
388 return p.Err("anonymous blocks are not supported")
389 }
390
391 // load up all arguments (if there even are any)
392 currentMappingTokens := bd.RemainingArgsAsTokens()
393
394 // load up the entire block
395 for mappingNesting := bd.Nesting(); bd.NextBlock(mappingNesting); {
396 currentMappingTokens = append(currentMappingTokens, bd.Token())
397 }
398
399 blockMapping[currentMappingKey] = currentMappingTokens
400 }
401 }
402
403 // splice out the import directive and its arguments
404 // (2 tokens, plus the length of args)
405 tokensBefore := p.tokens[:p.cursor-1-len(args)-len(blockTokens)]
406 tokensAfter := p.tokens[p.cursor+1:]
407 var importedTokens []Token
408 var nodes []string
409
410 // first check snippets. That is a simple, non-recursive replacement
411 if p.definedSnippets != nil && p.definedSnippets[importPattern] != nil {
412 importedTokens = p.definedSnippets[importPattern]
413 if len(importedTokens) > 0 {
414 // just grab the first one
415 nodes = append(nodes, fmt.Sprintf("%s:%s", importedTokens[0].File, importedTokens[0].snippetName))
416 }
417 } else {
418 // make path relative to the file of the _token_ being processed rather
419 // than current working directory (issue #867) and then use glob to get
420 // list of matching filenames
421 absFile, err := caddy.FastAbs(p.Dispenser.File())
422 if err != nil {
423 return p.Errf("Failed to get absolute path of file: %s: %v", p.Dispenser.File(), err)
424 }
425
426 var matches []string
427 var globPattern string
428 if !filepath.IsAbs(importPattern) {
429 globPattern = filepath.Join(filepath.Dir(absFile), importPattern)
430 } else {
431 globPattern = importPattern
432 }
433 if strings.Count(globPattern, "*") > 1 || strings.Count(globPattern, "?") > 1 ||
434 (strings.Contains(globPattern, "[") && strings.Contains(globPattern, "]")) {
435 // See issue #2096 - a pattern with many glob expansions can hang for too long
436 return p.Errf("Glob pattern may only contain one wildcard (*), but has others: %s", globPattern)
437 }
438 matches, err = filepath.Glob(globPattern)
439 if err != nil {
440 return p.Errf("Failed to use import pattern %s: %v", importPattern, err)
441 }
442 if len(matches) == 0 {
443 if strings.ContainsAny(globPattern, "*?[]") {
444 caddy.Log().Warn("No files matching import glob pattern", zap.String("pattern", importPattern))
445 } else {
446 return p.Errf("File to import not found: %s", importPattern)
447 }
448 } else {
449 // See issue #5295 - should skip any files that start with a . when iterating over them.
450 sep := string(filepath.Separator)
451 segGlobPattern := strings.Split(globPattern, sep)
452 if strings.HasPrefix(segGlobPattern[len(segGlobPattern)-1], "*") {
453 var tmpMatches []string
454 for _, m := range matches {
455 seg := strings.Split(m, sep)
456 if !strings.HasPrefix(seg[len(seg)-1], ".") {
457 tmpMatches = append(tmpMatches, m)
458 }
459 }
460 matches = tmpMatches
461 }
462 }
463
464 // collect all the imported tokens
465 for _, importFile := range matches {
466 newTokens, err := p.doSingleImport(importFile)
467 if err != nil {
468 return err
469 }
470 importedTokens = append(importedTokens, newTokens...)
471 }
472 nodes = matches
473 }
474
475 nodeName := p.File()
476 if p.Token().snippetName != "" {
477 nodeName += fmt.Sprintf(":%s", p.Token().snippetName)
478 }
479 p.importGraph.addNode(nodeName)
480 p.importGraph.addNodes(nodes)
481 if err := p.importGraph.addEdges(nodeName, nodes); err != nil {
482 p.importGraph.removeNodes(nodes)
483 return err
484 }
485
486 // copy the tokens so we don't overwrite p.definedSnippets
487 tokensCopy := make([]Token, 0, len(importedTokens))
488
489 var (
490 maybeSnippet bool
491 maybeSnippetId bool
492 index int
493 )
494
495 // run the argument replacer on the tokens
496 // golang for range slice return a copy of value
497 // similarly, append also copy value
498 for i, token := range importedTokens {
499 // update the token's imports to refer to import directive filename, line number and snippet name if there is one
500 if token.snippetName != "" {
501 token.imports = append(token.imports, fmt.Sprintf("%s:%d (import %s)", p.File(), p.Line(), token.snippetName))
502 } else {
503 token.imports = append(token.imports, fmt.Sprintf("%s:%d (import)", p.File(), p.Line()))
504 }
505
506 // naive way of determine snippets, as snippets definition can only follow name + block
507 // format, won't check for nesting correctness or any other error, that's what parser does.
508 if !maybeSnippet && nesting == 0 {
509 // first of the line
510 if i == 0 || isNextOnNewLine(tokensCopy[len(tokensCopy)-1], token) {
511 index = 0
512 } else {
513 index++
514 }
515
516 if index == 0 && len(token.Text) >= 3 && strings.HasPrefix(token.Text, "(") && strings.HasSuffix(token.Text, ")") {
517 maybeSnippetId = true
518 }
519 }
520
521 switch token.Text {
522 case "{":
523 nesting++
524 if index == 1 && maybeSnippetId && nesting == 1 {
525 maybeSnippet = true
526 maybeSnippetId = false
527 }
528 case "}":
529 nesting--
530 if nesting == 0 && maybeSnippet {
531 maybeSnippet = false
532 }
533 }
534 // if it is {block}, we substitute with all tokens in the block
535 // if it is {blocks.*}, we substitute with the tokens in the mapping for the *
536 var tokensToAdd []Token
537 foundBlockDirective := false
538 switch {
539 case token.Text == "{block}":
540 foundBlockDirective = true
541 tokensToAdd = blockTokens
542 case strings.HasPrefix(token.Text, "{blocks.") && strings.HasSuffix(token.Text, "}"):
543 foundBlockDirective = true
544 // {blocks.foo.bar} will be extracted to key `foo.bar`
545 blockKey := strings.TrimPrefix(strings.TrimSuffix(token.Text, "}"), "{blocks.")
546 val, ok := blockMapping[blockKey]
547 if ok {
548 tokensToAdd = val
549 }
550 }
551
552 if foundBlockDirective {
553 if maybeSnippet {
554 tokensCopy = append(tokensCopy, token)
555 } else {
556 tokensCopy = append(tokensCopy, tokensToAdd...)
557 }
558 continue
559 }
560
561 if maybeSnippet {
562 tokensCopy = append(tokensCopy, token)
563 continue
564 }
565
566 foundVariadic, startIndex, endIndex := parseVariadic(token, len(args))
567 if foundVariadic {
568 for _, arg := range args[startIndex:endIndex] {
569 token.Text = arg
570 tokensCopy = append(tokensCopy, token)
571 }
572 } else {
573 token.Text = repl.ReplaceKnown(token.Text, "")
574 tokensCopy = append(tokensCopy, token)
575 }
576 }
577
578 // splice the imported tokens in the place of the import statement
579 // and rewind cursor so Next() will land on first imported token
580 p.tokens = append(tokensBefore, append(tokensCopy, tokensAfter...)...)
581 p.cursor -= len(args) + len(blockTokens) + 1
582
583 return nil
584 }
585
586 // doSingleImport lexes the individual file at importFile and returns
587 // its tokens or an error, if any.
588 func (p *parser) doSingleImport(importFile string) ([]Token, error) {
589 file, err := os.Open(importFile)
590 if err != nil {
591 return nil, p.Errf("Could not import %s: %v", importFile, err)
592 }
593 defer file.Close()
594
595 if info, err := file.Stat(); err != nil {
596 return nil, p.Errf("Could not import %s: %v", importFile, err)
597 } else if info.IsDir() {
598 return nil, p.Errf("Could not import %s: is a directory", importFile)
599 }
600
601 input, err := io.ReadAll(file)
602 if err != nil {
603 return nil, p.Errf("Could not read imported file %s: %v", importFile, err)
604 }
605
606 // only warning in case of empty files
607 if len(input) == 0 || len(strings.TrimSpace(string(input))) == 0 {
608 caddy.Log().Warn("Import file is empty", zap.String("file", importFile))
609 return []Token{}, nil
610 }
611
612 importedTokens, err := allTokens(importFile, input)
613 if err != nil {
614 return nil, p.Errf("Could not read tokens while importing %s: %v", importFile, err)
615 }
616
617 // Tack the file path onto these tokens so errors show the imported file's name
618 // (we use full, absolute path to avoid bugs: issue #1892)
619 filename, err := caddy.FastAbs(importFile)
620 if err != nil {
621 return nil, p.Errf("Failed to get absolute path of file: %s: %v", importFile, err)
622 }
623 for i := range importedTokens {
624 importedTokens[i].File = filename
625 }
626
627 return importedTokens, nil
628 }
629
630 // directive collects tokens until the directive's scope
631 // closes (either end of line or end of curly brace block).
632 // It expects the currently-loaded token to be a directive
633 // (or } that ends a server block). The collected tokens
634 // are loaded into the current server block for later use
635 // by directive setup functions.
636 func (p *parser) directive() error {
637 // a segment is a list of tokens associated with this directive
638 var segment Segment
639
640 // the directive itself is appended as a relevant token
641 segment = append(segment, p.Token())
642
643 for p.Next() {
644 if p.Val() == "{" {
645 p.nesting++
646 if !p.isNextOnNewLine() && p.Token().wasQuoted == 0 {
647 return p.Err("Unexpected next token after '{' on same line")
648 }
649 if p.isNewLine() {
650 return p.Err("Unexpected '{' on a new line; did you mean to place the '{' on the previous line?")
651 }
652 } else if p.Val() == "{}" {
653 if p.isNextOnNewLine() && p.Token().wasQuoted == 0 {
654 return p.Err("Unexpected '{}' at end of line")
655 }
656 } else if p.isNewLine() && p.nesting == 0 {
657 p.cursor-- // read too far
658 break
659 } else if p.Val() == "}" && p.nesting > 0 {
660 p.nesting--
661 } else if p.Val() == "}" && p.nesting == 0 {
662 return p.Err("Unexpected '}' because no matching opening brace")
663 } else if p.Val() == "import" && p.isNewLine() {
664 if err := p.doImport(1); err != nil {
665 return err
666 }
667 p.cursor-- // cursor is advanced when we continue, so roll back one more
668 continue
669 }
670
671 segment = append(segment, p.Token())
672 }
673
674 p.block.Segments = append(p.block.Segments, segment)
675
676 if p.nesting > 0 {
677 return p.EOFErr()
678 }
679
680 return nil
681 }
682
683 // openCurlyBrace expects the current token to be an
684 // opening curly brace. This acts like an assertion
685 // because it returns an error if the token is not
686 // an opening curly brace. It does NOT advance the token.
687 func (p *parser) openCurlyBrace() error {
688 if p.Val() != "{" {
689 if p.valLooksLikeGlobalOptionsAfterImportedSnippets() {
690 return p.Err("global options block must appear before import directives; move the global options block to the top of the Caddyfile")
691 }
692 return p.SyntaxErr("{")
693 }
694 return nil
695 }
696
697 func (p *parser) valLooksLikeGlobalOptionsAfterImportedSnippets() bool {
698 if p.Val() != "import" || len(p.block.Keys) == 0 {
699 return false
700 }
701
702 for _, key := range p.block.Keys {
703 if !strings.HasPrefix(key.Text, "(") || !strings.HasSuffix(key.Text, ")") {
704 return false
705 }
706 }
707
708 return true
709 }
710
711 // closeCurlyBrace expects the current token to be
712 // a closing curly brace. This acts like an assertion
713 // because it returns an error if the token is not
714 // a closing curly brace. It does NOT advance the token.
715 func (p *parser) closeCurlyBrace() error {
716 if p.Val() != "}" {
717 return p.SyntaxErr("}")
718 }
719 return nil
720 }
721
722 func (p *parser) isNamedRoute() (bool, string) {
723 keys := p.block.Keys
724 // A named route block is a single key with parens, prefixed with &.
725 if len(keys) == 1 && strings.HasPrefix(keys[0].Text, "&(") && strings.HasSuffix(keys[0].Text, ")") {
726 return true, strings.TrimSuffix(keys[0].Text[2:], ")")
727 }
728 return false, ""
729 }
730
731 func (p *parser) isSnippet() (bool, string) {
732 keys := p.block.Keys
733 // A snippet block is a single key with parens. Nothing else qualifies.
734 if len(keys) == 1 && strings.HasPrefix(keys[0].Text, "(") && strings.HasSuffix(keys[0].Text, ")") {
735 return true, strings.TrimSuffix(keys[0].Text[1:], ")")
736 }
737 return false, ""
738 }
739
740 // read and store everything in a block for later replay.
741 func (p *parser) blockTokens(retainCurlies bool) ([]Token, error) {
742 // block must have curlies.
743 err := p.openCurlyBrace()
744 if err != nil {
745 return nil, err
746 }
747 nesting := 1 // count our own nesting
748 tokens := []Token{}
749 if retainCurlies {
750 tokens = append(tokens, p.Token())
751 }
752 for p.Next() {
753 if p.Val() == "}" {
754 nesting--
755 if nesting == 0 {
756 if retainCurlies {
757 tokens = append(tokens, p.Token())
758 }
759 break
760 }
761 }
762 if p.Val() == "{" {
763 nesting++
764 }
765 tokens = append(tokens, p.tokens[p.cursor])
766 }
767 // make sure we're matched up
768 if nesting != 0 {
769 return nil, p.SyntaxErr("}")
770 }
771 return tokens, nil
772 }
773
774 // ServerBlock associates any number of keys from the
775 // head of the server block with tokens, which are
776 // grouped by segments.
777 type ServerBlock struct {
778 HasBraces bool
779 Keys []Token
780 Segments []Segment
781 IsNamedRoute bool
782 }
783
784 func (sb ServerBlock) GetKeysText() []string {
785 res := make([]string, 0, len(sb.Keys))
786 for _, k := range sb.Keys {
787 res = append(res, k.Text)
788 }
789 return res
790 }
791
792 // DispenseDirective returns a dispenser that contains
793 // all the tokens in the server block.
794 func (sb ServerBlock) DispenseDirective(dir string) *Dispenser {
795 var tokens []Token
796 for _, seg := range sb.Segments {
797 if len(seg) > 0 && seg[0].Text == dir {
798 tokens = append(tokens, seg...)
799 }
800 }
801 return NewDispenser(tokens)
802 }
803
804 // Segment is a list of tokens which begins with a directive
805 // and ends at the end of the directive (either at the end of
806 // the line, or at the end of a block it opens).
807 type Segment []Token
808
809 // Directive returns the directive name for the segment.
810 // The directive name is the text of the first token.
811 func (s Segment) Directive() string {
812 if len(s) > 0 {
813 return s[0].Text
814 }
815 return ""
816 }
817
818 // spanOpen and spanClose are used to bound spans that
819 // contain the name of an environment variable.
820 var (
821 spanOpen, spanClose = []byte{'{', '$'}, []byte{'}'}
822 envVarDefaultDelimiter = ":"
823 )