Debian Codegraph @

modules/caddyhttp/templates/tplcontext.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 templates
16
17 import (
18 "bytes"
19 "fmt"
20 "io"
21 "io/fs"
22 "net"
23 "net/http"
24 "net/url"
25 "os"
26 "path"
27 "reflect"
28 "strconv"
29 "strings"
30 "sync"
31 "text/template"
32 "time"
33
34 "github.com/Masterminds/sprig/v3"
35 chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
36 "github.com/dustin/go-humanize"
37 "github.com/yuin/goldmark"
38 highlighting "github.com/yuin/goldmark-highlighting/v2"
39 "github.com/yuin/goldmark/extension"
40 "github.com/yuin/goldmark/parser"
41 gmhtml "github.com/yuin/goldmark/renderer/html"
42 "go.uber.org/zap"
43
44 "github.com/caddyserver/caddy/v2"
45 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
46 )
47
48 // TemplateContext is the TemplateContext with which HTTP templates are executed.
49 type TemplateContext struct {
50 Root http.FileSystem
51 Req *http.Request
52 Args []any // defined by arguments to funcInclude
53 RespHeader WrappedHeader
54 CustomFuncs []template.FuncMap // functions added by plugins
55
56 config *Templates
57 tpl *template.Template
58 }
59
60 // NewTemplate returns a new template intended to be evaluated with this
61 // context, as it is initialized with configuration from this context.
62 func (c *TemplateContext) NewTemplate(tplName string) *template.Template {
63 c.tpl = template.New(tplName).Option("missingkey=zero")
64
65 // customize delimiters, if applicable
66 if c.config != nil && len(c.config.Delimiters) == 2 {
67 c.tpl.Delims(c.config.Delimiters[0], c.config.Delimiters[1])
68 }
69
70 // add sprig library
71 c.tpl.Funcs(sprigFuncMap)
72
73 // add all custom functions
74 for _, funcMap := range c.CustomFuncs {
75 c.tpl.Funcs(funcMap)
76 }
77
78 // add our own library
79 c.tpl.Funcs(template.FuncMap{
80 "include": c.funcInclude,
81 "readFile": c.funcReadFile,
82 "import": c.funcImport,
83 "httpInclude": c.funcHTTPInclude,
84 "stripHTML": c.funcStripHTML,
85 "markdown": c.funcMarkdown,
86 "splitFrontMatter": c.funcSplitFrontMatter,
87 "listFiles": c.funcListFiles,
88 "fileStat": c.funcFileStat,
89 "env": c.funcEnv,
90 "placeholder": c.funcPlaceholder,
91 "ph": c.funcPlaceholder, // shortcut
92 "fileExists": c.funcFileExists,
93 "httpError": c.funcHTTPError,
94 "humanize": c.funcHumanize,
95 "maybe": c.funcMaybe,
96 "pathEscape": url.PathEscape,
97 })
98 return c.tpl
99 }
100
101 // OriginalReq returns the original, unmodified, un-rewritten request as
102 // it originally came in over the wire.
103 func (c TemplateContext) OriginalReq() http.Request {
104 or, _ := c.Req.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
105 return or
106 }
107
108 // funcInclude returns the contents of filename relative to the site root and renders it in place.
109 // Note that included files are NOT escaped, so you should only include
110 // trusted files. If it is not trusted, be sure to use escaping functions
111 // in your template.
112 func (c TemplateContext) funcInclude(filename string, args ...any) (string, error) {
113 bodyBuf := bufPool.Get().(*bytes.Buffer)
114 bodyBuf.Reset()
115 defer bufPool.Put(bodyBuf)
116
117 err := c.readFileToBuffer(filename, bodyBuf)
118 if err != nil {
119 return "", err
120 }
121
122 c.Args = args
123
124 err = c.executeTemplateInBuffer(filename, bodyBuf)
125 if err != nil {
126 return "", err
127 }
128
129 return bodyBuf.String(), nil
130 }
131
132 // funcReadFile returns the contents of a filename relative to the site root.
133 // Note that included files are NOT escaped, so you should only include
134 // trusted files. If it is not trusted, be sure to use escaping functions
135 // in your template.
136 func (c TemplateContext) funcReadFile(filename string) (string, error) {
137 bodyBuf := bufPool.Get().(*bytes.Buffer)
138 bodyBuf.Reset()
139 defer bufPool.Put(bodyBuf)
140
141 err := c.readFileToBuffer(filename, bodyBuf)
142 if err != nil {
143 return "", err
144 }
145
146 return bodyBuf.String(), nil
147 }
148
149 // readFileToBuffer reads a file into a buffer
150 func (c TemplateContext) readFileToBuffer(filename string, bodyBuf *bytes.Buffer) error {
151 if c.Root == nil {
152 return fmt.Errorf("root file system not specified")
153 }
154
155 file, err := c.Root.Open(filename)
156 if err != nil {
157 return err
158 }
159 defer file.Close()
160
161 _, err = io.Copy(bodyBuf, file)
162 if err != nil {
163 return err
164 }
165
166 return nil
167 }
168
169 // funcHTTPInclude returns the body of a virtual (lightweight) request
170 // to the given URI on the same server. Note that included bodies
171 // are NOT escaped, so you should only include trusted resources.
172 // If it is not trusted, be sure to use escaping functions yourself.
173 func (c TemplateContext) funcHTTPInclude(uri string) (string, error) {
174 // prevent virtual request loops by counting how many levels
175 // deep we are; and if we get too deep, return an error
176 recursionCount := 1
177 if numStr := c.Req.Header.Get(recursionPreventionHeader); numStr != "" {
178 num, err := strconv.Atoi(numStr)
179 if err != nil {
180 return "", fmt.Errorf("parsing %s: %v", recursionPreventionHeader, err)
181 }
182 if num >= 3 {
183 return "", fmt.Errorf("virtual request cycle")
184 }
185 recursionCount = num + 1
186 }
187
188 buf := bufPool.Get().(*bytes.Buffer)
189 buf.Reset()
190 defer bufPool.Put(buf)
191
192 virtReq, err := http.NewRequest("GET", uri, nil)
193 if err != nil {
194 return "", err
195 }
196 virtReq.Host = c.Req.Host
197 virtReq.RemoteAddr = "127.0.0.1:10000" // https://github.com/caddyserver/caddy/issues/5835
198 virtReq.Header = c.Req.Header.Clone()
199 virtReq.Header.Set("Accept-Encoding", "identity") // https://github.com/caddyserver/caddy/issues/4352
200 virtReq.Trailer = c.Req.Trailer.Clone()
201 virtReq.Header.Set(recursionPreventionHeader, strconv.Itoa(recursionCount))
202
203 vrw := &virtualResponseWriter{body: buf, header: make(http.Header)}
204 server := c.Req.Context().Value(caddyhttp.ServerCtxKey).(http.Handler)
205
206 server.ServeHTTP(vrw, virtReq)
207 if vrw.status >= 400 {
208 return "", fmt.Errorf("http %d", vrw.status)
209 }
210
211 err = c.executeTemplateInBuffer(uri, buf)
212 if err != nil {
213 return "", err
214 }
215
216 return buf.String(), nil
217 }
218
219 // funcImport parses the filename into the current template stack. The imported
220 // file will be rendered within the current template by calling {{ block }} or
221 // {{ template }} from the standard template library. If the imported file has
222 // no {{ define }} blocks, the name of the import will be the path
223 func (c *TemplateContext) funcImport(filename string) (string, error) {
224 bodyBuf := bufPool.Get().(*bytes.Buffer)
225 bodyBuf.Reset()
226 defer bufPool.Put(bodyBuf)
227
228 err := c.readFileToBuffer(filename, bodyBuf)
229 if err != nil {
230 return "", err
231 }
232
233 _, err = c.tpl.Parse(bodyBuf.String())
234 if err != nil {
235 return "", err
236 }
237 return "", nil
238 }
239
240 func (c *TemplateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buffer) error {
241 c.NewTemplate(tplName)
242
243 _, err := c.tpl.Parse(buf.String())
244 if err != nil {
245 return err
246 }
247
248 buf.Reset() // reuse buffer for output
249
250 return c.tpl.Execute(buf, c)
251 }
252
253 func (c TemplateContext) funcPlaceholder(name string) string {
254 repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
255
256 // For safety, we don't want to allow the file placeholder in
257 // templates because it could be used to read arbitrary files
258 // if the template contents were not trusted.
259 repl = repl.WithoutFile()
260
261 value, _ := repl.GetString(name)
262 return value
263 }
264
265 func (TemplateContext) funcEnv(varName string) string {
266 return os.Getenv(varName)
267 }
268
269 // Cookie gets the value of a cookie with name.
270 func (c TemplateContext) Cookie(name string) string {
271 cookies := c.Req.Cookies()
272 for _, cookie := range cookies {
273 if cookie.Name == name {
274 return cookie.Value
275 }
276 }
277 return ""
278 }
279
280 // RemoteIP gets the IP address of the connection's remote IP.
281 func (c TemplateContext) RemoteIP() string {
282 ip, _, err := net.SplitHostPort(c.Req.RemoteAddr)
283 if err != nil {
284 return c.Req.RemoteAddr
285 }
286 return ip
287 }
288
289 // ClientIP gets the IP address of the real client making the request
290 // if the request is trusted (see trusted_proxies), otherwise returns
291 // the connection's remote IP.
292 func (c TemplateContext) ClientIP() string {
293 address := caddyhttp.GetVar(c.Req.Context(), caddyhttp.ClientIPVarKey).(string)
294 clientIP, _, err := net.SplitHostPort(address)
295 if err != nil {
296 clientIP = address // no port
297 }
298 return clientIP
299 }
300
301 // Host returns the hostname portion of the Host header
302 // from the HTTP request.
303 func (c TemplateContext) Host() (string, error) {
304 host, _, err := net.SplitHostPort(c.Req.Host)
305 if err != nil {
306 if !strings.Contains(c.Req.Host, ":") {
307 // common with sites served on the default port 80
308 return c.Req.Host, nil
309 }
310 return "", err
311 }
312 return host, nil
313 }
314
315 // funcStripHTML returns s without HTML tags. Similar to PHP's strip_tags()
316 func (TemplateContext) funcStripHTML(s string) string {
317 var buf bytes.Buffer
318 depth := 0
319 var quoteChar rune
320 for _, ch := range s {
321 switch {
322 case depth > 0 && quoteChar == 0 && (ch == '"' || ch == '\''):
323 // entering a quoted attribute value
324 quoteChar = ch
325 case depth > 0 && ch == quoteChar:
326 // leaving a quoted attribute value
327 quoteChar = 0
328 case ch == '<' && quoteChar == 0:
329 depth++
330 case ch == '>' && quoteChar == 0:
331 if depth > 0 {
332 depth--
333 } else {
334 buf.WriteRune(ch) // stray '>' with no opening '<', keep it
335 }
336 default:
337 if depth == 0 {
338 buf.WriteRune(ch)
339 }
340 }
341 }
342 return buf.String()
343 }
344
345 // funcMarkdown renders the markdown body as HTML. The resulting
346 // HTML is NOT escaped so that it can be rendered as HTML.
347 func (TemplateContext) funcMarkdown(input any) (string, error) {
348 inputStr := caddy.ToString(input)
349
350 md := goldmark.New(
351 goldmark.WithExtensions(
352 extension.GFM,
353 extension.Footnote,
354 highlighting.NewHighlighting(
355 highlighting.WithFormatOptions(
356 chromahtml.WithClasses(true),
357 ),
358 ),
359 ),
360 goldmark.WithParserOptions(
361 parser.WithAutoHeadingID(),
362 ),
363 goldmark.WithRendererOptions(
364 gmhtml.WithUnsafe(), // TODO: this is not awesome, maybe should be configurable?
365 ),
366 )
367
368 buf := bufPool.Get().(*bytes.Buffer)
369 buf.Reset()
370 defer bufPool.Put(buf)
371
372 err := md.Convert([]byte(inputStr), buf)
373 if err != nil {
374 return "", err
375 }
376
377 return buf.String(), nil
378 }
379
380 // funcSplitFrontMatter parses front matter out from the beginning of input,
381 // and returns the separated key-value pairs and the body/content. input
382 // must be a "stringy" value.
383 func (TemplateContext) funcSplitFrontMatter(input any) (parsedMarkdownDoc, error) {
384 meta, body, err := extractFrontMatter(caddy.ToString(input))
385 if err != nil {
386 return parsedMarkdownDoc{}, err
387 }
388 return parsedMarkdownDoc{Meta: meta, Body: body}, nil
389 }
390
391 // funcListFiles reads and returns a slice of names from the given
392 // directory relative to the root of c.
393 func (c TemplateContext) funcListFiles(name string) ([]string, error) {
394 if c.Root == nil {
395 return nil, fmt.Errorf("root file system not specified")
396 }
397
398 dir, err := c.Root.Open(path.Clean(name))
399 if err != nil {
400 return nil, err
401 }
402 defer dir.Close()
403
404 stat, err := dir.Stat()
405 if err != nil {
406 return nil, err
407 }
408 if !stat.IsDir() {
409 return nil, fmt.Errorf("%v is not a directory", name)
410 }
411
412 dirInfo, err := dir.Readdir(0)
413 if err != nil {
414 return nil, err
415 }
416
417 names := make([]string, len(dirInfo))
418 for i, fileInfo := range dirInfo {
419 names[i] = fileInfo.Name()
420 }
421
422 return names, nil
423 }
424
425 // funcFileExists returns true if filename can be opened successfully.
426 func (c TemplateContext) funcFileExists(filename string) (bool, error) {
427 if c.Root == nil {
428 return false, fmt.Errorf("root file system not specified")
429 }
430 file, err := c.Root.Open(filename)
431 if err == nil {
432 file.Close()
433 return true, nil
434 }
435 return false, nil
436 }
437
438 // funcFileStat returns Stat of a filename
439 func (c TemplateContext) funcFileStat(filename string) (fs.FileInfo, error) {
440 if c.Root == nil {
441 return nil, fmt.Errorf("root file system not specified")
442 }
443
444 file, err := c.Root.Open(path.Clean(filename))
445 if err != nil {
446 return nil, err
447 }
448 defer file.Close()
449
450 return file.Stat()
451 }
452
453 // funcHTTPError returns a structured HTTP handler error. EXPERIMENTAL; SUBJECT TO CHANGE.
454 // Example usage: `{{if not (fileExists $includeFile)}}{{httpError 404}}{{end}}`
455 func (c TemplateContext) funcHTTPError(statusCode int) (bool, error) {
456 // Delete some headers that may have been set by the underlying
457 // handler (such as file_server) which may break the error response.
458 c.RespHeader.Header.Del("Content-Length")
459 c.RespHeader.Header.Del("Content-Type")
460 c.RespHeader.Header.Del("Etag")
461 c.RespHeader.Header.Del("Last-Modified")
462 c.RespHeader.Header.Del("Accept-Ranges")
463
464 return false, caddyhttp.Error(statusCode, nil)
465 }
466
467 // funcHumanize transforms size and time inputs to a human readable format.
468 //
469 // Size inputs are expected to be integers, and are formatted as a
470 // byte size, such as "83 MB".
471 //
472 // Time inputs are parsed using the given layout (default layout is RFC1123Z)
473 // and are formatted as a relative time, such as "2 weeks ago".
474 // See https://pkg.go.dev/time#pkg-constants for time layout docs.
475 func (c TemplateContext) funcHumanize(formatType, data string) (string, error) {
476 // The format type can optionally be followed
477 // by a colon to provide arguments for the format
478 parts := strings.Split(formatType, ":")
479
480 switch parts[0] {
481 case "size":
482 dataint, dataerr := strconv.ParseUint(data, 10, 64)
483 if dataerr != nil {
484 return "", fmt.Errorf("humanize: size cannot be parsed: %s", dataerr.Error())
485 }
486 return humanize.Bytes(dataint), nil
487
488 case "time":
489 timelayout := time.RFC1123Z
490 if len(parts) > 1 {
491 timelayout = parts[1]
492 }
493
494 dataint, dataerr := time.Parse(timelayout, data)
495 if dataerr != nil {
496 return "", fmt.Errorf("humanize: time cannot be parsed: %s", dataerr.Error())
497 }
498 return humanize.Time(dataint), nil
499 }
500
501 return "", fmt.Errorf("no know function was given")
502 }
503
504 // funcMaybe invokes the plugged-in function named functionName if it is plugged in
505 // (is a module in the 'http.handlers.templates.functions' namespace). If it is not
506 // available, a log message is emitted.
507 //
508 // The first argument is the function name, and the rest of the arguments are
509 // passed on to the actual function.
510 //
511 // This function is useful for executing templates that use components that may be
512 // considered as optional in some cases (like during local development) where you do
513 // not want to require everyone to have a custom Caddy build to be able to execute
514 // your template.
515 //
516 // NOTE: This function is EXPERIMENTAL and subject to change or removal.
517 func (c TemplateContext) funcMaybe(functionName string, args ...any) (any, error) {
518 for _, funcMap := range c.CustomFuncs {
519 if fn, ok := funcMap[functionName]; ok {
520 val := reflect.ValueOf(fn)
521 if val.Kind() != reflect.Func {
522 continue
523 }
524 argVals := make([]reflect.Value, len(args))
525 for i, arg := range args {
526 argVals[i] = reflect.ValueOf(arg)
527 }
528 returnVals := val.Call(argVals)
529 switch len(returnVals) {
530 case 0:
531 return "", nil
532 case 1:
533 return returnVals[0].Interface(), nil
534 case 2:
535 var err error
536 if !returnVals[1].IsNil() {
537 err = returnVals[1].Interface().(error)
538 }
539 return returnVals[0].Interface(), err
540 default:
541 return nil, fmt.Errorf("maybe %s: invalid number of return values: %d", functionName, len(returnVals))
542 }
543 }
544 }
545 c.config.logger.Named("maybe").Warn("template function could not be found; ignoring invocation", zap.String("name", functionName))
546 return "", nil
547 }
548
549 // WrappedHeader wraps niladic functions so that they
550 // can be used in templates. (Template functions must
551 // return a value.)
552 type WrappedHeader struct{ http.Header }
553
554 // Add adds a header field value, appending val to
555 // existing values for that field. It returns an
556 // empty string.
557 func (h WrappedHeader) Add(field, val string) string {
558 h.Header.Add(field, val)
559 return ""
560 }
561
562 // Set sets a header field value, overwriting any
563 // other values for that field. It returns an
564 // empty string.
565 func (h WrappedHeader) Set(field, val string) string {
566 h.Header.Set(field, val)
567 return ""
568 }
569
570 // Del deletes a header field. It returns an empty string.
571 func (h WrappedHeader) Del(field string) string {
572 h.Header.Del(field)
573 return ""
574 }
575
576 var bufPool = sync.Pool{
577 New: func() any {
578 return new(bytes.Buffer)
579 },
580 }
581
582 // at time of writing, sprig.FuncMap() makes a copy, thus
583 // involves iterating the whole map, so do it just once
584 var sprigFuncMap = sprig.TxtFuncMap()
585
586 const recursionPreventionHeader = "Caddy-Templates-Include"