2019-06-30 17:07:58 -05:00
|
|
|
// 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.
|
|
|
|
|
2019-06-18 12:13:12 -05:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
2020-04-07 13:26:08 -05:00
|
|
|
"os"
|
2019-06-18 12:13:12 -05:00
|
|
|
"path"
|
2019-10-16 16:18:02 -05:00
|
|
|
"strconv"
|
2019-06-18 12:13:12 -05:00
|
|
|
"strings"
|
|
|
|
"sync"
|
2020-04-06 13:50:54 -05:00
|
|
|
"text/template"
|
2019-06-18 12:13:12 -05:00
|
|
|
|
2019-10-10 16:47:26 -05:00
|
|
|
"github.com/Masterminds/sprig/v3"
|
2019-12-23 14:56:41 -05:00
|
|
|
"github.com/alecthomas/chroma/formatters/html"
|
2020-07-20 18:17:38 -05:00
|
|
|
"github.com/caddyserver/caddy/v2"
|
2019-07-02 13:37:06 -05:00
|
|
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
2019-12-23 14:56:41 -05:00
|
|
|
"github.com/yuin/goldmark"
|
|
|
|
highlighting "github.com/yuin/goldmark-highlighting"
|
|
|
|
"github.com/yuin/goldmark/extension"
|
|
|
|
"github.com/yuin/goldmark/parser"
|
|
|
|
gmhtml "github.com/yuin/goldmark/renderer/html"
|
2019-06-18 12:13:12 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// templateContext is the templateContext with which HTTP templates are executed.
|
|
|
|
type templateContext struct {
|
|
|
|
Root http.FileSystem
|
|
|
|
Req *http.Request
|
2020-04-27 15:30:37 -05:00
|
|
|
Args []interface{} // defined by arguments to funcInclude
|
2019-06-18 12:13:12 -05:00
|
|
|
RespHeader tplWrappedHeader
|
2019-06-18 16:17:48 -05:00
|
|
|
|
|
|
|
config *Templates
|
2019-06-18 12:13:12 -05:00
|
|
|
}
|
|
|
|
|
2019-12-23 14:56:41 -05:00
|
|
|
// OriginalReq returns the original, unmodified, un-rewritten request as
|
|
|
|
// it originally came in over the wire.
|
|
|
|
func (c templateContext) OriginalReq() http.Request {
|
|
|
|
or, _ := c.Req.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
|
|
|
|
return or
|
|
|
|
}
|
|
|
|
|
|
|
|
// funcInclude returns the contents of filename relative to the site root.
|
2019-06-27 14:30:41 -05:00
|
|
|
// Note that included files are NOT escaped, so you should only include
|
|
|
|
// trusted files. If it is not trusted, be sure to use escaping functions
|
|
|
|
// in your template.
|
2020-04-06 13:50:54 -05:00
|
|
|
func (c templateContext) funcInclude(filename string, args ...interface{}) (string, error) {
|
2019-06-18 12:13:12 -05:00
|
|
|
if c.Root == nil {
|
|
|
|
return "", fmt.Errorf("root file system not specified")
|
|
|
|
}
|
|
|
|
|
|
|
|
file, err := c.Root.Open(filename)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
bodyBuf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
bodyBuf.Reset()
|
|
|
|
defer bufPool.Put(bodyBuf)
|
|
|
|
|
|
|
|
_, err = io.Copy(bodyBuf, file)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Args = args
|
|
|
|
|
2019-06-18 16:17:48 -05:00
|
|
|
err = c.executeTemplateInBuffer(filename, bodyBuf)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2020-04-06 13:50:54 -05:00
|
|
|
return bodyBuf.String(), nil
|
2019-06-18 12:13:12 -05:00
|
|
|
}
|
|
|
|
|
2019-12-23 14:56:41 -05:00
|
|
|
// funcHTTPInclude returns the body of a virtual (lightweight) request
|
2019-06-27 14:30:41 -05:00
|
|
|
// to the given URI on the same server. Note that included bodies
|
|
|
|
// are NOT escaped, so you should only include trusted resources.
|
|
|
|
// If it is not trusted, be sure to use escaping functions yourself.
|
2020-04-06 13:50:54 -05:00
|
|
|
func (c templateContext) funcHTTPInclude(uri string) (string, error) {
|
2019-10-16 16:18:02 -05:00
|
|
|
// prevent virtual request loops by counting how many levels
|
|
|
|
// deep we are; and if we get too deep, return an error
|
|
|
|
recursionCount := 1
|
|
|
|
if numStr := c.Req.Header.Get(recursionPreventionHeader); numStr != "" {
|
|
|
|
num, err := strconv.Atoi(numStr)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("parsing %s: %v", recursionPreventionHeader, err)
|
|
|
|
}
|
|
|
|
if num >= 3 {
|
|
|
|
return "", fmt.Errorf("virtual request cycle")
|
|
|
|
}
|
|
|
|
recursionCount = num + 1
|
2019-06-18 12:13:12 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
buf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
buf.Reset()
|
|
|
|
defer bufPool.Put(buf)
|
|
|
|
|
|
|
|
virtReq, err := http.NewRequest("GET", uri, nil)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2019-10-16 16:18:02 -05:00
|
|
|
virtReq.Host = c.Req.Host
|
|
|
|
virtReq.Header = c.Req.Header.Clone()
|
|
|
|
virtReq.Trailer = c.Req.Trailer.Clone()
|
|
|
|
virtReq.Header.Set(recursionPreventionHeader, strconv.Itoa(recursionCount))
|
2019-06-18 12:13:12 -05:00
|
|
|
|
|
|
|
vrw := &virtualResponseWriter{body: buf, header: make(http.Header)}
|
|
|
|
server := c.Req.Context().Value(caddyhttp.ServerCtxKey).(http.Handler)
|
|
|
|
|
|
|
|
server.ServeHTTP(vrw, virtReq)
|
|
|
|
if vrw.status >= 400 {
|
|
|
|
return "", fmt.Errorf("http %d", vrw.status)
|
|
|
|
}
|
|
|
|
|
2019-06-18 16:17:48 -05:00
|
|
|
err = c.executeTemplateInBuffer(uri, buf)
|
2019-06-18 12:13:12 -05:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2020-04-06 13:50:54 -05:00
|
|
|
return buf.String(), nil
|
2019-06-18 16:17:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buffer) error {
|
2019-12-23 14:56:41 -05:00
|
|
|
tpl := template.New(tplName)
|
2019-06-18 16:17:48 -05:00
|
|
|
if len(c.config.Delimiters) == 2 {
|
|
|
|
tpl.Delims(c.config.Delimiters[0], c.config.Delimiters[1])
|
|
|
|
}
|
2019-06-18 12:13:12 -05:00
|
|
|
|
2019-12-23 14:56:41 -05:00
|
|
|
tpl.Funcs(sprigFuncMap)
|
|
|
|
|
|
|
|
tpl.Funcs(template.FuncMap{
|
|
|
|
"include": c.funcInclude,
|
|
|
|
"httpInclude": c.funcHTTPInclude,
|
|
|
|
"stripHTML": c.funcStripHTML,
|
|
|
|
"markdown": c.funcMarkdown,
|
|
|
|
"splitFrontMatter": c.funcSplitFrontMatter,
|
|
|
|
"listFiles": c.funcListFiles,
|
2020-04-07 13:26:08 -05:00
|
|
|
"env": c.funcEnv,
|
2020-07-20 18:17:38 -05:00
|
|
|
"placeholder": c.placeholder,
|
2019-12-23 14:56:41 -05:00
|
|
|
})
|
|
|
|
|
2019-06-18 16:17:48 -05:00
|
|
|
parsedTpl, err := tpl.Parse(buf.String())
|
2019-06-18 12:13:12 -05:00
|
|
|
if err != nil {
|
2019-06-18 16:17:48 -05:00
|
|
|
return err
|
2019-06-18 12:13:12 -05:00
|
|
|
}
|
|
|
|
|
2019-06-18 16:17:48 -05:00
|
|
|
buf.Reset() // reuse buffer for output
|
|
|
|
|
|
|
|
return parsedTpl.Execute(buf, c)
|
2019-06-18 12:13:12 -05:00
|
|
|
}
|
|
|
|
|
2020-07-20 18:17:38 -05:00
|
|
|
func (c templateContext) placeholder(name string) string {
|
|
|
|
repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
|
|
|
|
value, _ := repl.GetString(name)
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
2020-04-07 13:26:08 -05:00
|
|
|
func (templateContext) funcEnv(varName string) string {
|
|
|
|
return os.Getenv(varName)
|
|
|
|
}
|
|
|
|
|
2019-06-18 12:13:12 -05:00
|
|
|
// Cookie gets the value of a cookie with name name.
|
|
|
|
func (c templateContext) Cookie(name string) string {
|
|
|
|
cookies := c.Req.Cookies()
|
|
|
|
for _, cookie := range cookies {
|
|
|
|
if cookie.Name == name {
|
|
|
|
return cookie.Value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2019-06-21 09:08:26 -05:00
|
|
|
// RemoteIP gets the IP address of the client making the request.
|
|
|
|
func (c templateContext) RemoteIP() string {
|
2019-06-18 12:13:12 -05:00
|
|
|
ip, _, err := net.SplitHostPort(c.Req.RemoteAddr)
|
|
|
|
if err != nil {
|
|
|
|
return c.Req.RemoteAddr
|
|
|
|
}
|
|
|
|
return ip
|
|
|
|
}
|
|
|
|
|
|
|
|
// Host returns the hostname portion of the Host header
|
|
|
|
// from the HTTP request.
|
|
|
|
func (c templateContext) Host() (string, error) {
|
|
|
|
host, _, err := net.SplitHostPort(c.Req.Host)
|
|
|
|
if err != nil {
|
|
|
|
if !strings.Contains(c.Req.Host, ":") {
|
|
|
|
// common with sites served on the default port 80
|
|
|
|
return c.Req.Host, nil
|
|
|
|
}
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return host, nil
|
|
|
|
}
|
|
|
|
|
2019-12-23 14:56:41 -05:00
|
|
|
// funcStripHTML returns s without HTML tags. It is fairly naive
|
2019-06-18 12:13:12 -05:00
|
|
|
// but works with most valid HTML inputs.
|
2020-04-07 13:26:08 -05:00
|
|
|
func (templateContext) funcStripHTML(s string) string {
|
2019-06-18 12:13:12 -05:00
|
|
|
var buf bytes.Buffer
|
|
|
|
var inTag, inQuotes bool
|
|
|
|
var tagStart int
|
|
|
|
for i, ch := range s {
|
|
|
|
if inTag {
|
|
|
|
if ch == '>' && !inQuotes {
|
|
|
|
inTag = false
|
|
|
|
} else if ch == '<' && !inQuotes {
|
|
|
|
// false start
|
|
|
|
buf.WriteString(s[tagStart:i])
|
|
|
|
tagStart = i
|
|
|
|
} else if ch == '"' {
|
|
|
|
inQuotes = !inQuotes
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if ch == '<' {
|
|
|
|
inTag = true
|
|
|
|
tagStart = i
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
buf.WriteRune(ch)
|
|
|
|
}
|
|
|
|
if inTag {
|
|
|
|
// false start
|
|
|
|
buf.WriteString(s[tagStart:])
|
|
|
|
}
|
|
|
|
return buf.String()
|
|
|
|
}
|
|
|
|
|
2019-12-23 14:56:41 -05:00
|
|
|
// funcMarkdown renders the markdown body as HTML. The resulting
|
2019-06-27 14:30:41 -05:00
|
|
|
// HTML is NOT escaped so that it can be rendered as HTML.
|
2020-04-07 13:26:08 -05:00
|
|
|
func (templateContext) funcMarkdown(input interface{}) (string, error) {
|
2019-12-23 14:56:41 -05:00
|
|
|
inputStr := toString(input)
|
|
|
|
|
|
|
|
md := goldmark.New(
|
|
|
|
goldmark.WithExtensions(
|
|
|
|
extension.GFM,
|
2020-03-19 00:38:37 -05:00
|
|
|
extension.Footnote,
|
2019-12-23 14:56:41 -05:00
|
|
|
highlighting.NewHighlighting(
|
|
|
|
highlighting.WithFormatOptions(
|
|
|
|
html.WithClasses(true),
|
|
|
|
),
|
|
|
|
),
|
|
|
|
),
|
|
|
|
goldmark.WithParserOptions(
|
|
|
|
parser.WithAutoHeadingID(),
|
|
|
|
),
|
|
|
|
goldmark.WithRendererOptions(
|
|
|
|
gmhtml.WithUnsafe(), // TODO: this is not awesome, maybe should be configurable?
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
buf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
buf.Reset()
|
|
|
|
defer bufPool.Put(buf)
|
|
|
|
|
2020-11-22 16:50:29 -05:00
|
|
|
err := md.Convert([]byte(inputStr), buf)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2019-12-23 14:56:41 -05:00
|
|
|
|
2020-04-06 13:50:54 -05:00
|
|
|
return buf.String(), nil
|
2019-12-23 14:56:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// splitFrontMatter parses front matter out from the beginning of input,
|
|
|
|
// and returns the separated key-value pairs and the body/content. input
|
|
|
|
// must be a "stringy" value.
|
2020-04-07 13:26:08 -05:00
|
|
|
func (templateContext) funcSplitFrontMatter(input interface{}) (parsedMarkdownDoc, error) {
|
2019-12-23 14:56:41 -05:00
|
|
|
meta, body, err := extractFrontMatter(toString(input))
|
|
|
|
if err != nil {
|
|
|
|
return parsedMarkdownDoc{}, err
|
|
|
|
}
|
|
|
|
return parsedMarkdownDoc{Meta: meta, Body: body}, nil
|
2019-06-18 12:13:12 -05:00
|
|
|
}
|
|
|
|
|
2019-12-23 14:56:41 -05:00
|
|
|
// funcListFiles reads and returns a slice of names from the given
|
2019-06-18 12:13:12 -05:00
|
|
|
// directory relative to the root of c.
|
2019-12-23 14:56:41 -05:00
|
|
|
func (c templateContext) funcListFiles(name string) ([]string, error) {
|
2019-06-18 12:13:12 -05:00
|
|
|
if c.Root == nil {
|
|
|
|
return nil, fmt.Errorf("root file system not specified")
|
|
|
|
}
|
|
|
|
|
|
|
|
dir, err := c.Root.Open(path.Clean(name))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer dir.Close()
|
|
|
|
|
|
|
|
stat, err := dir.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if !stat.IsDir() {
|
|
|
|
return nil, fmt.Errorf("%v is not a directory", name)
|
|
|
|
}
|
|
|
|
|
|
|
|
dirInfo, err := dir.Readdir(0)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
names := make([]string, len(dirInfo))
|
|
|
|
for i, fileInfo := range dirInfo {
|
|
|
|
names[i] = fileInfo.Name()
|
|
|
|
}
|
|
|
|
|
|
|
|
return names, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// tplWrappedHeader wraps niladic functions so that they
|
|
|
|
// can be used in templates. (Template functions must
|
|
|
|
// return a value.)
|
|
|
|
type tplWrappedHeader struct{ http.Header }
|
|
|
|
|
|
|
|
// Add adds a header field value, appending val to
|
|
|
|
// existing values for that field. It returns an
|
|
|
|
// empty string.
|
|
|
|
func (h tplWrappedHeader) Add(field, val string) string {
|
|
|
|
h.Header.Add(field, val)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set sets a header field value, overwriting any
|
|
|
|
// other values for that field. It returns an
|
|
|
|
// empty string.
|
|
|
|
func (h tplWrappedHeader) Set(field, val string) string {
|
|
|
|
h.Header.Set(field, val)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// Del deletes a header field. It returns an empty string.
|
|
|
|
func (h tplWrappedHeader) Del(field string) string {
|
|
|
|
h.Header.Del(field)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2019-12-23 14:56:41 -05:00
|
|
|
func toString(input interface{}) string {
|
|
|
|
switch v := input.(type) {
|
|
|
|
case string:
|
|
|
|
return v
|
|
|
|
case fmt.Stringer:
|
|
|
|
return v.String()
|
|
|
|
case error:
|
|
|
|
return v.Error()
|
|
|
|
default:
|
2020-04-06 13:50:54 -05:00
|
|
|
return fmt.Sprintf("%v", input)
|
2019-12-23 14:56:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-18 12:13:12 -05:00
|
|
|
var bufPool = sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
return new(bytes.Buffer)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2019-12-23 14:56:41 -05:00
|
|
|
// at time of writing, sprig.FuncMap() makes a copy, thus
|
|
|
|
// involves iterating the whole map, so do it just once
|
2020-04-06 13:50:54 -05:00
|
|
|
var sprigFuncMap = sprig.TxtFuncMap()
|
2019-12-23 14:56:41 -05:00
|
|
|
|
2019-06-18 12:13:12 -05:00
|
|
|
const recursionPreventionHeader = "Caddy-Templates-Include"
|