summaryrefslogtreecommitdiff
path: root/caddyconfig/caddyfile/importargs.go
blob: c6dcd85671dfc495be6f3af82d9c62edbdfb9bd2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package caddyfile

import (
	"regexp"
	"strconv"
	"strings"

	"github.com/caddyserver/caddy/v2"
	"go.uber.org/zap"
)

// parseVariadic determines if the token is a variadic placeholder,
// and if so, determines the index range (start/end) of args to use.
// Returns a boolean signaling whether a variadic placeholder was found,
// and the start and end indices.
func parseVariadic(token Token, argCount int) (bool, int, int) {
	if !strings.HasPrefix(token.Text, "{args[") {
		return false, 0, 0
	}
	if !strings.HasSuffix(token.Text, "]}") {
		return false, 0, 0
	}

	argRange := strings.TrimSuffix(strings.TrimPrefix(token.Text, "{args["), "]}")
	if argRange == "" {
		caddy.Log().Named("caddyfile").Warn(
			"Placeholder "+token.Text+" cannot have an empty index",
			zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports))
		return false, 0, 0
	}

	start, end, found := strings.Cut(argRange, ":")

	// If no ":" delimiter is found, this is not a variadic.
	// The replacer will pick this up.
	if !found {
		return false, 0, 0
	}

	var (
		startIndex = 0
		endIndex   = argCount
		err        error
	)
	if start != "" {
		startIndex, err = strconv.Atoi(start)
		if err != nil {
			caddy.Log().Named("caddyfile").Warn(
				"Variadic placeholder "+token.Text+" has an invalid start index",
				zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports))
			return false, 0, 0
		}
	}
	if end != "" {
		endIndex, err = strconv.Atoi(end)
		if err != nil {
			caddy.Log().Named("caddyfile").Warn(
				"Variadic placeholder "+token.Text+" has an invalid end index",
				zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports))
			return false, 0, 0
		}
	}

	// bound check
	if startIndex < 0 || startIndex > endIndex || endIndex > argCount {
		caddy.Log().Named("caddyfile").Warn(
			"Variadic placeholder "+token.Text+" indices are out of bounds, only "+strconv.Itoa(argCount)+" argument(s) exist",
			zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports))
		return false, 0, 0
	}
	return true, startIndex, endIndex
}

// makeArgsReplacer prepares a Replacer which can replace
// non-variadic args placeholders in imported tokens.
func makeArgsReplacer(args []string) *caddy.Replacer {
	repl := caddy.NewEmptyReplacer()
	repl.Map(func(key string) (any, bool) {
		// TODO: Remove the deprecated {args.*} placeholder
		// support at some point in the future
		if matches := argsRegexpIndexDeprecated.FindStringSubmatch(key); len(matches) > 0 {
			value, err := strconv.Atoi(matches[1])
			if err != nil {
				caddy.Log().Named("caddyfile").Warn(
					"Placeholder {args." + matches[1] + "} has an invalid index")
				return nil, false
			}
			if value >= len(args) {
				caddy.Log().Named("caddyfile").Warn(
					"Placeholder {args." + matches[1] + "} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist")
				return nil, false
			}
			caddy.Log().Named("caddyfile").Warn(
				"Placeholder {args." + matches[1] + "} deprecated, use {args[" + matches[1] + "]} instead")
			return args[value], true
		}

		// Handle args[*] form
		if matches := argsRegexpIndex.FindStringSubmatch(key); len(matches) > 0 {
			if strings.Contains(matches[1], ":") {
				caddy.Log().Named("caddyfile").Warn(
					"Variadic placeholder {args[" + matches[1] + "]} must be a token on its own")
				return nil, false
			}
			value, err := strconv.Atoi(matches[1])
			if err != nil {
				caddy.Log().Named("caddyfile").Warn(
					"Placeholder {args[" + matches[1] + "]} has an invalid index")
				return nil, false
			}
			if value >= len(args) {
				caddy.Log().Named("caddyfile").Warn(
					"Placeholder {args[" + matches[1] + "]} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist")
				return nil, false
			}
			return args[value], true
		}

		// Not an args placeholder, ignore
		return nil, false
	})
	return repl
}

var (
	argsRegexpIndexDeprecated = regexp.MustCompile(`args\.(.+)`)
	argsRegexpIndex           = regexp.MustCompile(`args\[(.+)]`)
)