| 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 caddy |
| 16 | |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "fmt" |
| 20 | "io" |
| 21 | "net/http" |
| 22 | "os" |
| 23 | "path/filepath" |
| 24 | "runtime" |
| 25 | "strconv" |
| 26 | "strings" |
| 27 | "sync" |
| 28 | "time" |
| 29 | |
| 30 | "go.uber.org/zap" |
| 31 | ) |
| 32 | |
| 33 | // NewReplacer returns a new Replacer. |
| 34 | func NewReplacer() *Replacer { |
| 35 | rep := &Replacer{ |
| 36 | static: make(map[string]any), |
| 37 | mapMutex: &sync.RWMutex{}, |
| 38 | } |
| 39 | rep.providers = []replacementProvider{ |
| 40 | globalDefaultReplacementProvider{}, |
| 41 | fileReplacementProvider{}, |
| 42 | ReplacerFunc(rep.fromStatic), |
| 43 | } |
| 44 | return rep |
| 45 | } |
| 46 | |
| 47 | // NewEmptyReplacer returns a new Replacer, |
| 48 | // without the global default replacements. |
| 49 | func NewEmptyReplacer() *Replacer { |
| 50 | rep := &Replacer{ |
| 51 | static: make(map[string]any), |
| 52 | mapMutex: &sync.RWMutex{}, |
| 53 | } |
| 54 | rep.providers = []replacementProvider{ |
| 55 | ReplacerFunc(rep.fromStatic), |
| 56 | } |
| 57 | return rep |
| 58 | } |
| 59 | |
| 60 | // Replacer can replace values in strings. |
| 61 | // A default/empty Replacer is not valid; |
| 62 | // use NewReplacer to make one. |
| 63 | type Replacer struct { |
| 64 | providers []replacementProvider |
| 65 | static map[string]any |
| 66 | mapMutex *sync.RWMutex |
| 67 | } |
| 68 | |
| 69 | // WithoutFile returns a copy of the current Replacer |
| 70 | // without support for the {file.*} placeholder, which |
| 71 | // may be unsafe in some contexts. |
| 72 | // |
| 73 | // EXPERIMENTAL: Subject to change or removal. |
| 74 | func (r *Replacer) WithoutFile() *Replacer { |
| 75 | rep := &Replacer{static: r.static} |
| 76 | for _, v := range r.providers { |
| 77 | if _, ok := v.(fileReplacementProvider); ok { |
| 78 | continue |
| 79 | } |
| 80 | rep.providers = append(rep.providers, v) |
| 81 | } |
| 82 | return rep |
| 83 | } |
| 84 | |
| 85 | // Map adds mapFunc to the list of value providers. |
| 86 | // mapFunc will be executed only at replace-time. |
| 87 | func (r *Replacer) Map(mapFunc ReplacerFunc) { |
| 88 | r.providers = append(r.providers, mapFunc) |
| 89 | } |
| 90 | |
| 91 | // Set sets a custom variable to a static value. |
| 92 | func (r *Replacer) Set(variable string, value any) { |
| 93 | r.mapMutex.Lock() |
| 94 | r.static[variable] = value |
| 95 | r.mapMutex.Unlock() |
| 96 | } |
| 97 | |
| 98 | // Get gets a value from the replacer. It returns |
| 99 | // the value and whether the variable was known. |
| 100 | func (r *Replacer) Get(variable string) (any, bool) { |
| 101 | for _, mapFunc := range r.providers { |
| 102 | if val, ok := mapFunc.replace(variable); ok { |
| 103 | return val, true |
| 104 | } |
| 105 | } |
| 106 | return nil, false |
| 107 | } |
| 108 | |
| 109 | // GetString is the same as Get, but coerces the value to a |
| 110 | // string representation as efficiently as possible. |
| 111 | func (r *Replacer) GetString(variable string) (string, bool) { |
| 112 | s, found := r.Get(variable) |
| 113 | return ToString(s), found |
| 114 | } |
| 115 | |
| 116 | // Delete removes a variable with a static value |
| 117 | // that was created using Set. |
| 118 | func (r *Replacer) Delete(variable string) { |
| 119 | r.mapMutex.Lock() |
| 120 | delete(r.static, variable) |
| 121 | r.mapMutex.Unlock() |
| 122 | } |
| 123 | |
| 124 | // DeleteByPrefix removes all static variables with |
| 125 | // keys starting with the given prefix |
| 126 | func (r *Replacer) DeleteByPrefix(prefix string) { |
| 127 | r.mapMutex.Lock() |
| 128 | for key := range r.static { |
| 129 | if strings.HasPrefix(key, prefix) { |
| 130 | delete(r.static, key) |
| 131 | } |
| 132 | } |
| 133 | r.mapMutex.Unlock() |
| 134 | } |
| 135 | |
| 136 | // fromStatic provides values from r.static. |
| 137 | func (r *Replacer) fromStatic(key string) (any, bool) { |
| 138 | r.mapMutex.RLock() |
| 139 | defer r.mapMutex.RUnlock() |
| 140 | val, ok := r.static[key] |
| 141 | return val, ok |
| 142 | } |
| 143 | |
| 144 | // ReplaceOrErr is like ReplaceAll, but any placeholders |
| 145 | // that are empty or not recognized will cause an error to |
| 146 | // be returned. |
| 147 | func (r *Replacer) ReplaceOrErr(input string, errOnEmpty, errOnUnknown bool) (string, error) { |
| 148 | return r.replace(input, "", false, errOnEmpty, errOnUnknown, nil) |
| 149 | } |
| 150 | |
| 151 | // ReplaceKnown is like ReplaceAll but only replaces |
| 152 | // placeholders that are known (recognized). Unrecognized |
| 153 | // placeholders will remain in the output. |
| 154 | func (r *Replacer) ReplaceKnown(input, empty string) string { |
| 155 | out, _ := r.replace(input, empty, false, false, false, nil) |
| 156 | return out |
| 157 | } |
| 158 | |
| 159 | // ReplaceAll efficiently replaces placeholders in input with |
| 160 | // their values. All placeholders are replaced in the output |
| 161 | // whether they are recognized or not. Values that are empty |
| 162 | // string will be substituted with empty. |
| 163 | func (r *Replacer) ReplaceAll(input, empty string) string { |
| 164 | out, _ := r.replace(input, empty, true, false, false, nil) |
| 165 | return out |
| 166 | } |
| 167 | |
| 168 | // ReplaceFunc is the same as ReplaceAll, but calls f for every |
| 169 | // replacement to be made, in case f wants to change or inspect |
| 170 | // the replacement. |
| 171 | func (r *Replacer) ReplaceFunc(input string, f ReplacementFunc) (string, error) { |
| 172 | return r.replace(input, "", true, false, false, f) |
| 173 | } |
| 174 | |
| 175 | func (r *Replacer) replace(input, empty string, |
| 176 | treatUnknownAsEmpty, errOnEmpty, errOnUnknown bool, |
| 177 | f ReplacementFunc, |
| 178 | ) (string, error) { |
| 179 | if !strings.Contains(input, string(phOpen)) && !strings.Contains(input, string(phClose)) { |
| 180 | return input, nil |
| 181 | } |
| 182 | |
| 183 | var sb strings.Builder |
| 184 | |
| 185 | // it is reasonable to assume that the output |
| 186 | // will be approximately as long as the input |
| 187 | sb.Grow(len(input)) |
| 188 | |
| 189 | // iterate the input to find each placeholder |
| 190 | var lastWriteCursor int |
| 191 | |
| 192 | // fail fast if too many placeholders are unclosed |
| 193 | var unclosedCount int |
| 194 | |
| 195 | scan: |
| 196 | for i := 0; i < len(input); i++ { |
| 197 | // check for escaped braces |
| 198 | if i > 0 && input[i-1] == phEscape && (input[i] == phClose || input[i] == phOpen) { |
| 199 | sb.WriteString(input[lastWriteCursor : i-1]) |
| 200 | lastWriteCursor = i |
| 201 | continue |
| 202 | } |
| 203 | |
| 204 | if input[i] != phOpen { |
| 205 | continue |
| 206 | } |
| 207 | |
| 208 | // our iterator is now on an unescaped open brace (start of placeholder) |
| 209 | |
| 210 | // too many unclosed placeholders in absolutely ridiculous input can be extremely slow (issue #4170) |
| 211 | if unclosedCount > 100 { |
| 212 | return "", fmt.Errorf("too many unclosed placeholders") |
| 213 | } |
| 214 | |
| 215 | // find the end of the placeholder |
| 216 | end := strings.Index(input[i:], string(phClose)) + i |
| 217 | if end < i { |
| 218 | unclosedCount++ |
| 219 | continue |
| 220 | } |
| 221 | |
| 222 | // if necessary look for the first closing brace that is not escaped |
| 223 | for end > 0 && end < len(input)-1 && input[end-1] == phEscape { |
| 224 | nextEnd := strings.Index(input[end+1:], string(phClose)) |
| 225 | if nextEnd < 0 { |
| 226 | unclosedCount++ |
| 227 | continue scan |
| 228 | } |
| 229 | end += nextEnd + 1 |
| 230 | } |
| 231 | |
| 232 | // write the substring from the last cursor to this point |
| 233 | sb.WriteString(input[lastWriteCursor:i]) |
| 234 | |
| 235 | // trim opening bracket |
| 236 | key := input[i+1 : end] |
| 237 | |
| 238 | // try to get a value for this key, handle empty values accordingly |
| 239 | val, found := r.Get(key) |
| 240 | if !found { |
| 241 | // placeholder is unknown (unrecognized); handle accordingly |
| 242 | if errOnUnknown { |
| 243 | return "", fmt.Errorf("unrecognized placeholder %s%s%s", |
| 244 | string(phOpen), key, string(phClose)) |
| 245 | } else if !treatUnknownAsEmpty { |
| 246 | // if treatUnknownAsEmpty is true, we'll handle an empty |
| 247 | // val later; so only continue otherwise |
| 248 | lastWriteCursor = i |
| 249 | continue |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // apply any transformations |
| 254 | if f != nil { |
| 255 | var err error |
| 256 | val, err = f(key, val) |
| 257 | if err != nil { |
| 258 | return "", err |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | // convert val to a string as efficiently as possible |
| 263 | valStr := ToString(val) |
| 264 | |
| 265 | // write the value; if it's empty, either return |
| 266 | // an error or write a default value |
| 267 | if valStr == "" { |
| 268 | if errOnEmpty { |
| 269 | return "", fmt.Errorf("evaluated placeholder %s%s%s is empty", |
| 270 | string(phOpen), key, string(phClose)) |
| 271 | } else if empty != "" { |
| 272 | sb.WriteString(empty) |
| 273 | } |
| 274 | } else { |
| 275 | sb.WriteString(valStr) |
| 276 | } |
| 277 | |
| 278 | // advance cursor to end of placeholder |
| 279 | i = end |
| 280 | lastWriteCursor = i + 1 |
| 281 | } |
| 282 | |
| 283 | // flush any unwritten remainder |
| 284 | sb.WriteString(input[lastWriteCursor:]) |
| 285 | |
| 286 | return sb.String(), nil |
| 287 | } |
| 288 | |
| 289 | // ToString returns val as a string, as efficiently as possible. |
| 290 | // EXPERIMENTAL: may be changed or removed later. |
| 291 | func ToString(val any) string { |
| 292 | switch v := val.(type) { |
| 293 | case nil: |
| 294 | return "" |
| 295 | case string: |
| 296 | return v |
| 297 | case fmt.Stringer: |
| 298 | return v.String() |
| 299 | case error: |
| 300 | return v.Error() |
| 301 | case byte: |
| 302 | return string(v) |
| 303 | case []byte: |
| 304 | return string(v) |
| 305 | case []rune: |
| 306 | return string(v) |
| 307 | case int: |
| 308 | return strconv.Itoa(v) |
| 309 | case int32: |
| 310 | return strconv.Itoa(int(v)) |
| 311 | case int64: |
| 312 | return strconv.Itoa(int(v)) |
| 313 | case uint: |
| 314 | return strconv.FormatUint(uint64(v), 10) |
| 315 | case uint32: |
| 316 | return strconv.FormatUint(uint64(v), 10) |
| 317 | case uint64: |
| 318 | return strconv.FormatUint(v, 10) |
| 319 | case float32: |
| 320 | return strconv.FormatFloat(float64(v), 'f', -1, 32) |
| 321 | case float64: |
| 322 | return strconv.FormatFloat(v, 'f', -1, 64) |
| 323 | case bool: |
| 324 | if v { |
| 325 | return "true" |
| 326 | } |
| 327 | return "false" |
| 328 | default: |
| 329 | return fmt.Sprintf("%+v", v) |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | // ReplacerFunc is a function that returns a replacement for the |
| 334 | // given key along with true if the function is able to service |
| 335 | // that key (even if the value is blank). If the function does |
| 336 | // not recognize the key, false should be returned. |
| 337 | type ReplacerFunc func(key string) (any, bool) |
| 338 | |
| 339 | func (f ReplacerFunc) replace(key string) (any, bool) { |
| 340 | return f(key) |
| 341 | } |
| 342 | |
| 343 | // replacementProvider is a type that can provide replacements |
| 344 | // for placeholders. Allows for type assertion to determine |
| 345 | // which type of provider it is. |
| 346 | type replacementProvider interface { |
| 347 | replace(key string) (any, bool) |
| 348 | } |
| 349 | |
| 350 | // fileReplacementProvider handles {file.*} replacements, |
| 351 | // reading a file from disk and replacing with its contents. |
| 352 | type fileReplacementProvider struct{} |
| 353 | |
| 354 | func (f fileReplacementProvider) replace(key string) (any, bool) { |
| 355 | if !strings.HasPrefix(key, filePrefix) { |
| 356 | return nil, false |
| 357 | } |
| 358 | |
| 359 | filename := key[len(filePrefix):] |
| 360 | maxSize := 1024 * 1024 |
| 361 | body, err := readFileIntoBuffer(filename, maxSize) |
| 362 | if err != nil { |
| 363 | wd, _ := os.Getwd() |
| 364 | Log().Error("placeholder: failed to read file", |
| 365 | zap.String("file", filename), |
| 366 | zap.String("working_dir", wd), |
| 367 | zap.Error(err)) |
| 368 | return nil, true |
| 369 | } |
| 370 | body = bytes.TrimSuffix(body, []byte("\n")) |
| 371 | body = bytes.TrimSuffix(body, []byte("\r")) |
| 372 | return string(body), true |
| 373 | } |
| 374 | |
| 375 | // globalDefaultReplacementProvider handles replacements |
| 376 | // that can be used in any context, such as system variables, |
| 377 | // time, or environment variables. |
| 378 | type globalDefaultReplacementProvider struct{} |
| 379 | |
| 380 | func (f globalDefaultReplacementProvider) replace(key string) (any, bool) { |
| 381 | // check environment variable |
| 382 | const envPrefix = "env." |
| 383 | if strings.HasPrefix(key, envPrefix) { |
| 384 | return os.Getenv(key[len(envPrefix):]), true |
| 385 | } |
| 386 | |
| 387 | switch key { |
| 388 | case "system.hostname": |
| 389 | // OK if there is an error; just return empty string |
| 390 | name, _ := os.Hostname() |
| 391 | return name, true |
| 392 | case "system.slash": |
| 393 | return string(filepath.Separator), true |
| 394 | case "system.os": |
| 395 | return runtime.GOOS, true |
| 396 | case "system.wd": |
| 397 | // OK if there is an error; just return empty string |
| 398 | wd, _ := os.Getwd() |
| 399 | return wd, true |
| 400 | case "system.arch": |
| 401 | return runtime.GOARCH, true |
| 402 | case "time.now": |
| 403 | return nowFunc(), true |
| 404 | case "time.now.http": |
| 405 | // According to the comment for http.TimeFormat, the timezone must be in UTC |
| 406 | // to generate the correct format. |
| 407 | // https://github.com/caddyserver/caddy/issues/5773 |
| 408 | return nowFunc().UTC().Format(http.TimeFormat), true |
| 409 | case "time.now.common_log": |
| 410 | return nowFunc().Format("02/Jan/2006:15:04:05 -0700"), true |
| 411 | case "time.now.year": |
| 412 | return strconv.Itoa(nowFunc().Year()), true |
| 413 | case "time.now.unix": |
| 414 | return strconv.FormatInt(nowFunc().Unix(), 10), true |
| 415 | case "time.now.unix_ms": |
| 416 | return strconv.FormatInt(nowFunc().UnixNano()/int64(time.Millisecond), 10), true |
| 417 | } |
| 418 | |
| 419 | return nil, false |
| 420 | } |
| 421 | |
| 422 | // readFileIntoBuffer reads the file at filePath into a size limited buffer. |
| 423 | func readFileIntoBuffer(filename string, size int) ([]byte, error) { |
| 424 | file, err := os.Open(filename) |
| 425 | if err != nil { |
| 426 | return nil, err |
| 427 | } |
| 428 | defer file.Close() |
| 429 | |
| 430 | // io.LimitReader ensures we never read more than 'size' bytes. |
| 431 | // io.ReadAll starts with a small buffer and grows it as needed, |
| 432 | // preventing a massive 1MB allocation for small files. |
| 433 | return io.ReadAll(io.LimitReader(file, int64(size))) |
| 434 | } |
| 435 | |
| 436 | // ReplacementFunc is a function that is called when a |
| 437 | // replacement is being performed. It receives the |
| 438 | // variable (i.e. placeholder name) and the value that |
| 439 | // will be the replacement, and returns the value that |
| 440 | // will actually be the replacement, or an error. Note |
| 441 | // that errors are sometimes ignored by replacers. |
| 442 | type ReplacementFunc func(variable string, val any) (any, error) |
| 443 | |
| 444 | // nowFunc is a variable so tests can change it |
| 445 | // in order to obtain a deterministic time. |
| 446 | var nowFunc = time.Now |
| 447 | |
| 448 | // ReplacerCtxKey is the context key for a replacer. |
| 449 | const ReplacerCtxKey CtxKey = "replacer" |
| 450 | |
| 451 | const phOpen, phClose, phEscape = '{', '}', '\\' |
| 452 | |
| 453 | const filePrefix = "file." |