Debian Codegraph @

conf/parse.go

raw
1 // Copyright 2013-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package conf supports a configuration file format used by gnatsd. It is
15 // a flexible format that combines the best of traditional
16 // configuration formats and newer styles such as JSON and YAML.
17 package conf
18
19 // The format supported is less restrictive than today's formats.
20 // Supports mixed Arrays [], nested Maps {}, multiple comment types (# and //)
21 // Also supports key value assignments using '=' or ':' or whiteSpace()
22 // e.g. foo = 2, foo : 2, foo 2
23 // maps can be assigned with no key separator as well
24 // semicolons as value terminators in key/value assignments are optional
25 //
26 // see parse_test.go for more examples.
27
28 import (
29 "crypto/sha256"
30 "encoding/json"
31 "fmt"
32 "os"
33 "path/filepath"
34 "strconv"
35 "strings"
36 "time"
37 "unicode"
38 )
39
40 const _EMPTY_ = ""
41
42 type parser struct {
43 mapping map[string]any
44 lx *lexer
45
46 // The current scoped context, can be array or map
47 ctx any
48
49 // stack of contexts, either map or array/slice stack
50 ctxs []any
51
52 // Keys stack
53 keys []string
54
55 // Keys stack as items
56 ikeys []item
57
58 // The config file path, empty by default.
59 fp string
60
61 // pedantic reports error when configuration is not correct.
62 pedantic bool
63
64 // Tracks environment variable references, to avoid cycles
65 envVarReferences map[string]bool
66 }
67
68 // Parse will return a map of keys to any, although concrete types
69 // underly them. The values supported are string, bool, int64, float64, DateTime.
70 // Arrays and nested Maps are also supported.
71 func Parse(data string) (map[string]any, error) {
72 p, err := parse(data, "", false)
73 if err != nil {
74 return nil, err
75 }
76 return p.mapping, nil
77 }
78
79 // ParseWithChecks is equivalent to Parse but runs in pedantic mode.
80 func ParseWithChecks(data string) (map[string]any, error) {
81 p, err := parse(data, "", true)
82 if err != nil {
83 return nil, err
84 }
85 return p.mapping, nil
86 }
87
88 // ParseFile is a helper to open file, etc. and parse the contents.
89 func ParseFile(fp string) (map[string]any, error) {
90 data, err := os.ReadFile(fp)
91 if err != nil {
92 return nil, fmt.Errorf("error opening config file: %v", err)
93 }
94
95 p, err := parse(string(data), fp, false)
96 if err != nil {
97 return nil, err
98 }
99 return p.mapping, nil
100 }
101
102 // ParseFileWithChecks is equivalent to ParseFile but runs in pedantic mode.
103 func ParseFileWithChecks(fp string) (map[string]any, error) {
104 data, err := os.ReadFile(fp)
105 if err != nil {
106 return nil, err
107 }
108
109 p, err := parse(string(data), fp, true)
110 if err != nil {
111 return nil, err
112 }
113
114 return p.mapping, nil
115 }
116
117 // configDigest returns a digest for the parsed config.
118 func configDigest(m map[string]any) (string, error) {
119 digest := sha256.New()
120 e := json.NewEncoder(digest)
121 if err := e.Encode(m); err != nil {
122 return _EMPTY_, err
123 }
124 return fmt.Sprintf("sha256:%x", digest.Sum(nil)), nil
125 }
126
127 // ParseFileWithChecksDigest returns the processed config and a digest
128 // that represents the configuration.
129 func ParseFileWithChecksDigest(fp string) (map[string]any, string, error) {
130 m, err := ParseFileWithChecks(fp)
131 if err != nil {
132 return nil, _EMPTY_, err
133 }
134 digest, err := configDigest(m)
135 if err != nil {
136 return nil, _EMPTY_, err
137 }
138 return m, digest, nil
139 }
140
141 type token struct {
142 item item
143 value any
144 usedVariable bool
145 sourceFile string
146 }
147
148 func (t *token) MarshalJSON() ([]byte, error) {
149 return json.Marshal(t.value)
150 }
151
152 func (t *token) Value() any {
153 return t.value
154 }
155
156 func (t *token) Line() int {
157 return t.item.line
158 }
159
160 func (t *token) IsUsedVariable() bool {
161 return t.usedVariable
162 }
163
164 func (t *token) SourceFile() string {
165 return t.sourceFile
166 }
167
168 func (t *token) Position() int {
169 return t.item.pos
170 }
171
172 func newParser(data, fp string, pedantic bool) *parser {
173 return &parser{
174 mapping: make(map[string]any),
175 lx: lex(data),
176 ctxs: make([]any, 0, 4),
177 keys: make([]string, 0, 4),
178 ikeys: make([]item, 0, 4),
179 fp: filepath.Dir(fp),
180 pedantic: pedantic,
181 envVarReferences: make(map[string]bool),
182 }
183 }
184
185 func parse(data, fp string, pedantic bool) (*parser, error) {
186 p := newParser(data, fp, pedantic)
187 if err := p.parse(fp); err != nil {
188 return nil, err
189 }
190 return p, nil
191 }
192
193 func parseEnv(data string, parent *parser) (*parser, error) {
194 p := newParser(data, "", false)
195 p.envVarReferences = parent.envVarReferences
196 if err := p.parse(""); err != nil {
197 return nil, err
198 }
199 return p, nil
200 }
201
202 func (p *parser) parse(fp string) error {
203 p.pushContext(p.mapping)
204
205 var prevItem item
206 for {
207 it := p.next()
208 if it.typ == itemEOF {
209 // Here we allow the final character to be a bracket '}'
210 // in order to support JSON like configurations.
211 if prevItem.typ == itemKey && prevItem.val != mapEndString {
212 return fmt.Errorf("config is invalid (%s:%d:%d)", fp, it.line, it.pos)
213 }
214 break
215 }
216 prevItem = it
217 if err := p.processItem(it, fp); err != nil {
218 return err
219 }
220 }
221 return nil
222 }
223
224 func (p *parser) next() item {
225 return p.lx.nextItem()
226 }
227
228 func (p *parser) pushContext(ctx any) {
229 p.ctxs = append(p.ctxs, ctx)
230 p.ctx = ctx
231 }
232
233 func (p *parser) popContext() any {
234 if len(p.ctxs) == 0 {
235 panic("BUG in parser, context stack empty")
236 }
237 li := len(p.ctxs) - 1
238 last := p.ctxs[li]
239 p.ctxs = p.ctxs[0:li]
240 p.ctx = p.ctxs[len(p.ctxs)-1]
241 return last
242 }
243
244 func (p *parser) pushKey(key string) {
245 p.keys = append(p.keys, key)
246 }
247
248 func (p *parser) popKey() string {
249 if len(p.keys) == 0 {
250 panic("BUG in parser, keys stack empty")
251 }
252 li := len(p.keys) - 1
253 last := p.keys[li]
254 p.keys = p.keys[0:li]
255 return last
256 }
257
258 func (p *parser) pushItemKey(key item) {
259 p.ikeys = append(p.ikeys, key)
260 }
261
262 func (p *parser) popItemKey() item {
263 if len(p.ikeys) == 0 {
264 panic("BUG in parser, item keys stack empty")
265 }
266 li := len(p.ikeys) - 1
267 last := p.ikeys[li]
268 p.ikeys = p.ikeys[0:li]
269 return last
270 }
271
272 func (p *parser) processItem(it item, fp string) error {
273 setValue := func(it item, v any) {
274 if p.pedantic {
275 p.setValue(&token{it, v, false, fp})
276 } else {
277 p.setValue(v)
278 }
279 }
280
281 switch it.typ {
282 case itemError:
283 return fmt.Errorf("Parse error on line %d: '%s'", it.line, it.val)
284 case itemKey:
285 // Keep track of the keys as items and strings,
286 // we do this in order to be able to still support
287 // includes without many breaking changes.
288 p.pushKey(it.val)
289
290 if p.pedantic {
291 p.pushItemKey(it)
292 }
293 case itemMapStart:
294 newCtx := make(map[string]any)
295 p.pushContext(newCtx)
296 case itemMapEnd:
297 setValue(it, p.popContext())
298 case itemString:
299 // FIXME(dlc) sanitize string?
300 setValue(it, it.val)
301 case itemInteger:
302 lastDigit := 0
303 for _, r := range it.val {
304 if !unicode.IsDigit(r) && r != '-' {
305 break
306 }
307 lastDigit++
308 }
309 numStr := it.val[:lastDigit]
310 num, err := strconv.ParseInt(numStr, 10, 64)
311 if err != nil {
312 if e, ok := err.(*strconv.NumError); ok &&
313 e.Err == strconv.ErrRange {
314 return fmt.Errorf("integer '%s' is out of the range", it.val)
315 }
316 return fmt.Errorf("expected integer, but got '%s'", it.val)
317 }
318 // Process a suffix
319 suffix := strings.ToLower(strings.TrimSpace(it.val[lastDigit:]))
320
321 switch suffix {
322 case "":
323 setValue(it, num)
324 case "k":
325 setValue(it, num*1000)
326 case "kb", "ki", "kib":
327 setValue(it, num*1024)
328 case "m":
329 setValue(it, num*1000*1000)
330 case "mb", "mi", "mib":
331 setValue(it, num*1024*1024)
332 case "g":
333 setValue(it, num*1000*1000*1000)
334 case "gb", "gi", "gib":
335 setValue(it, num*1024*1024*1024)
336 case "t":
337 setValue(it, num*1000*1000*1000*1000)
338 case "tb", "ti", "tib":
339 setValue(it, num*1024*1024*1024*1024)
340 case "p":
341 setValue(it, num*1000*1000*1000*1000*1000)
342 case "pb", "pi", "pib":
343 setValue(it, num*1024*1024*1024*1024*1024)
344 case "e":
345 setValue(it, num*1000*1000*1000*1000*1000*1000)
346 case "eb", "ei", "eib":
347 setValue(it, num*1024*1024*1024*1024*1024*1024)
348 }
349 case itemFloat:
350 num, err := strconv.ParseFloat(it.val, 64)
351 if err != nil {
352 if e, ok := err.(*strconv.NumError); ok &&
353 e.Err == strconv.ErrRange {
354 return fmt.Errorf("float '%s' is out of the range", it.val)
355 }
356 return fmt.Errorf("expected float, but got '%s'", it.val)
357 }
358 setValue(it, num)
359 case itemBool:
360 switch strings.ToLower(it.val) {
361 case "true", "yes", "on":
362 setValue(it, true)
363 case "false", "no", "off":
364 setValue(it, false)
365 default:
366 return fmt.Errorf("expected boolean value, but got '%s'", it.val)
367 }
368
369 case itemDatetime:
370 dt, err := time.Parse("2006-01-02T15:04:05Z", it.val)
371 if err != nil {
372 return fmt.Errorf(
373 "expected Zulu formatted DateTime, but got '%s'", it.val)
374 }
375 setValue(it, dt)
376 case itemArrayStart:
377 var array = make([]any, 0)
378 p.pushContext(array)
379 case itemArrayEnd:
380 array := p.ctx
381 p.popContext()
382 setValue(it, array)
383 case itemVariable:
384 value, found, err := p.lookupVariable(it.val)
385 if err != nil {
386 return fmt.Errorf("variable reference for '%s' on line %d could not be parsed: %s",
387 it.val, it.line, err)
388 }
389 if !found {
390 return fmt.Errorf("variable reference for '%s' on line %d can not be found",
391 it.val, it.line)
392 }
393
394 if p.pedantic {
395 switch tk := value.(type) {
396 case *token:
397 // Mark the looked up variable as used, and make
398 // the variable reference become handled as a token.
399 tk.usedVariable = true
400 p.setValue(&token{it, tk.Value(), false, fp})
401 default:
402 // Special case to add position context to bcrypt references.
403 p.setValue(&token{it, value, false, fp})
404 }
405 } else {
406 p.setValue(value)
407 }
408 case itemInclude:
409 var (
410 m map[string]any
411 err error
412 )
413 if p.pedantic {
414 m, err = ParseFileWithChecks(filepath.Join(p.fp, it.val))
415 } else {
416 m, err = ParseFile(filepath.Join(p.fp, it.val))
417 }
418 if err != nil {
419 return fmt.Errorf("error parsing include file '%s', %v", it.val, err)
420 }
421 for k, v := range m {
422 p.pushKey(k)
423
424 if p.pedantic {
425 switch tk := v.(type) {
426 case *token:
427 p.pushItemKey(tk.item)
428 }
429 }
430 p.setValue(v)
431 }
432 }
433
434 return nil
435 }
436
437 // Used to map an environment value into a temporary map to pass to secondary Parse call.
438 const pkey = "pk"
439
440 // We special case raw strings here that are bcrypt'd. This allows us not to force quoting the strings
441 const bcryptPrefix = "2a$"
442
443 // lookupVariable will lookup a variable reference. It will use block scoping on keys
444 // it has seen before, with the top level scoping being the environment variables. We
445 // ignore array contexts and only process the map contexts..
446 //
447 // Returns true for ok if it finds something, similar to map.
448 func (p *parser) lookupVariable(varReference string) (any, bool, error) {
449 // Do special check to see if it is a raw bcrypt string.
450 if strings.HasPrefix(varReference, bcryptPrefix) {
451 return "$" + varReference, true, nil
452 }
453
454 // Loop through contexts currently on the stack.
455 for i := len(p.ctxs) - 1; i >= 0; i-- {
456 ctx := p.ctxs[i]
457 // Process if it is a map context
458 if m, ok := ctx.(map[string]any); ok {
459 if v, ok := m[varReference]; ok {
460 return v, ok, nil
461 }
462 }
463 }
464
465 // If we are here, we have exhausted our context maps and still not found anything.
466 // Detect reference cycles
467 if p.envVarReferences[varReference] {
468 return nil, false, fmt.Errorf("variable reference cycle for '%s'", varReference)
469 }
470 p.envVarReferences[varReference] = true
471 defer delete(p.envVarReferences, varReference)
472
473 // Parse from the environment
474 if vStr, ok := os.LookupEnv(varReference); ok {
475 // Everything we get here will be a string value, so we need to process as a parser would.
476 if subp, err := parseEnv(fmt.Sprintf("%s=%s", pkey, vStr), p); err == nil {
477 v, ok := subp.mapping[pkey]
478 return v, ok, nil
479 } else {
480 return nil, false, err
481 }
482 }
483 return nil, false, nil
484 }
485
486 func (p *parser) setValue(val any) {
487 // Test to see if we are on an array or a map
488
489 // Array processing
490 if ctx, ok := p.ctx.([]any); ok {
491 p.ctx = append(ctx, val)
492 p.ctxs[len(p.ctxs)-1] = p.ctx
493 }
494
495 // Map processing
496 if ctx, ok := p.ctx.(map[string]any); ok {
497 key := p.popKey()
498
499 if p.pedantic {
500 // Change the position to the beginning of the key
501 // since more useful when reporting errors.
502 switch v := val.(type) {
503 case *token:
504 it := p.popItemKey()
505 v.item.pos = it.pos
506 v.item.line = it.line
507 ctx[key] = v
508 }
509 } else {
510 // FIXME(dlc), make sure to error if redefining same key?
511 ctx[key] = val
512 }
513 }
514 }