Debian Codegraph @

libgo/go/html/template/escape.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package template
6
7 import (
8 "bytes"
9 "fmt"
10 "html"
11 "io"
12 "text/template"
13 "text/template/parse"
14 )
15
16 // escapeTemplate rewrites the named template, which must be
17 // associated with t, to guarantee that the output of any of the named
18 // templates is properly escaped. If no error is returned, then the named templates have
19 // been modified. Otherwise the named templates have been rendered
20 // unusable.
21 func escapeTemplate(tmpl *Template, node parse.Node, name string) error {
22 c, _ := tmpl.esc.escapeTree(context{}, node, name, 0)
23 var err error
24 if c.err != nil {
25 err, c.err.Name = c.err, name
26 } else if c.state != stateText {
27 err = &Error{ErrEndContext, nil, name, 0, fmt.Sprintf("ends in a non-text context: %v", c)}
28 }
29 if err != nil {
30 // Prevent execution of unsafe templates.
31 if t := tmpl.set[name]; t != nil {
32 t.escapeErr = err
33 t.text.Tree = nil
34 t.Tree = nil
35 }
36 return err
37 }
38 tmpl.esc.commit()
39 if t := tmpl.set[name]; t != nil {
40 t.escapeErr = escapeOK
41 t.Tree = t.text.Tree
42 }
43 return nil
44 }
45
46 // evalArgs formats the list of arguments into a string. It is equivalent to
47 // fmt.Sprint(args...), except that it deferences all pointers.
48 func evalArgs(args ...any) string {
49 // Optimization for simple common case of a single string argument.
50 if len(args) == 1 {
51 if s, ok := args[0].(string); ok {
52 return s
53 }
54 }
55 for i, arg := range args {
56 args[i] = indirectToStringerOrError(arg)
57 }
58 return fmt.Sprint(args...)
59 }
60
61 // funcMap maps command names to functions that render their inputs safe.
62 var funcMap = template.FuncMap{
63 "_html_template_attrescaper": attrEscaper,
64 "_html_template_commentescaper": commentEscaper,
65 "_html_template_cssescaper": cssEscaper,
66 "_html_template_cssvaluefilter": cssValueFilter,
67 "_html_template_htmlnamefilter": htmlNameFilter,
68 "_html_template_htmlescaper": htmlEscaper,
69 "_html_template_jsregexpescaper": jsRegexpEscaper,
70 "_html_template_jsstrescaper": jsStrEscaper,
71 "_html_template_jsvalescaper": jsValEscaper,
72 "_html_template_nospaceescaper": htmlNospaceEscaper,
73 "_html_template_rcdataescaper": rcdataEscaper,
74 "_html_template_srcsetescaper": srcsetFilterAndEscaper,
75 "_html_template_urlescaper": urlEscaper,
76 "_html_template_urlfilter": urlFilter,
77 "_html_template_urlnormalizer": urlNormalizer,
78 "_eval_args_": evalArgs,
79 }
80
81 // escaper collects type inferences about templates and changes needed to make
82 // templates injection safe.
83 type escaper struct {
84 // ns is the nameSpace that this escaper is associated with.
85 ns *nameSpace
86 // output[templateName] is the output context for a templateName that
87 // has been mangled to include its input context.
88 output map[string]context
89 // derived[c.mangle(name)] maps to a template derived from the template
90 // named name templateName for the start context c.
91 derived map[string]*template.Template
92 // called[templateName] is a set of called mangled template names.
93 called map[string]bool
94 // xxxNodeEdits are the accumulated edits to apply during commit.
95 // Such edits are not applied immediately in case a template set
96 // executes a given template in different escaping contexts.
97 actionNodeEdits map[*parse.ActionNode][]string
98 templateNodeEdits map[*parse.TemplateNode]string
99 textNodeEdits map[*parse.TextNode][]byte
100 // rangeContext holds context about the current range loop.
101 rangeContext *rangeContext
102 }
103
104 // rangeContext holds information about the current range loop.
105 type rangeContext struct {
106 outer *rangeContext // outer loop
107 breaks []context // context at each break action
108 continues []context // context at each continue action
109 }
110
111 // makeEscaper creates a blank escaper for the given set.
112 func makeEscaper(n *nameSpace) escaper {
113 return escaper{
114 n,
115 map[string]context{},
116 map[string]*template.Template{},
117 map[string]bool{},
118 map[*parse.ActionNode][]string{},
119 map[*parse.TemplateNode]string{},
120 map[*parse.TextNode][]byte{},
121 nil,
122 }
123 }
124
125 // filterFailsafe is an innocuous word that is emitted in place of unsafe values
126 // by sanitizer functions. It is not a keyword in any programming language,
127 // contains no special characters, is not empty, and when it appears in output
128 // it is distinct enough that a developer can find the source of the problem
129 // via a search engine.
130 const filterFailsafe = "ZgotmplZ"
131
132 // escape escapes a template node.
133 func (e *escaper) escape(c context, n parse.Node) context {
134 switch n := n.(type) {
135 case *parse.ActionNode:
136 return e.escapeAction(c, n)
137 case *parse.BreakNode:
138 c.n = n
139 e.rangeContext.breaks = append(e.rangeContext.breaks, c)
140 return context{state: stateDead}
141 case *parse.CommentNode:
142 return c
143 case *parse.ContinueNode:
144 c.n = n
145 e.rangeContext.continues = append(e.rangeContext.breaks, c)
146 return context{state: stateDead}
147 case *parse.IfNode:
148 return e.escapeBranch(c, &n.BranchNode, "if")
149 case *parse.ListNode:
150 return e.escapeList(c, n)
151 case *parse.RangeNode:
152 return e.escapeBranch(c, &n.BranchNode, "range")
153 case *parse.TemplateNode:
154 return e.escapeTemplate(c, n)
155 case *parse.TextNode:
156 return e.escapeText(c, n)
157 case *parse.WithNode:
158 return e.escapeBranch(c, &n.BranchNode, "with")
159 }
160 panic("escaping " + n.String() + " is unimplemented")
161 }
162
163 // escapeAction escapes an action template node.
164 func (e *escaper) escapeAction(c context, n *parse.ActionNode) context {
165 if len(n.Pipe.Decl) != 0 {
166 // A local variable assignment, not an interpolation.
167 return c
168 }
169 c = nudge(c)
170 // Check for disallowed use of predefined escapers in the pipeline.
171 for pos, idNode := range n.Pipe.Cmds {
172 node, ok := idNode.Args[0].(*parse.IdentifierNode)
173 if !ok {
174 // A predefined escaper "esc" will never be found as an identifier in a
175 // Chain or Field node, since:
176 // - "esc.x ..." is invalid, since predefined escapers return strings, and
177 // strings do not have methods, keys or fields.
178 // - "... .esc" is invalid, since predefined escapers are global functions,
179 // not methods or fields of any types.
180 // Therefore, it is safe to ignore these two node types.
181 continue
182 }
183 ident := node.Ident
184 if _, ok := predefinedEscapers[ident]; ok {
185 if pos < len(n.Pipe.Cmds)-1 ||
186 c.state == stateAttr && c.delim == delimSpaceOrTagEnd && ident == "html" {
187 return context{
188 state: stateError,
189 err: errorf(ErrPredefinedEscaper, n, n.Line, "predefined escaper %q disallowed in template", ident),
190 }
191 }
192 }
193 }
194 s := make([]string, 0, 3)
195 switch c.state {
196 case stateError:
197 return c
198 case stateURL, stateCSSDqStr, stateCSSSqStr, stateCSSDqURL, stateCSSSqURL, stateCSSURL:
199 switch c.urlPart {
200 case urlPartNone:
201 s = append(s, "_html_template_urlfilter")
202 fallthrough
203 case urlPartPreQuery:
204 switch c.state {
205 case stateCSSDqStr, stateCSSSqStr:
206 s = append(s, "_html_template_cssescaper")
207 default:
208 s = append(s, "_html_template_urlnormalizer")
209 }
210 case urlPartQueryOrFrag:
211 s = append(s, "_html_template_urlescaper")
212 case urlPartUnknown:
213 return context{
214 state: stateError,
215 err: errorf(ErrAmbigContext, n, n.Line, "%s appears in an ambiguous context within a URL", n),
216 }
217 default:
218 panic(c.urlPart.String())
219 }
220 case stateJS:
221 s = append(s, "_html_template_jsvalescaper")
222 // A slash after a value starts a div operator.
223 c.jsCtx = jsCtxDivOp
224 case stateJSDqStr, stateJSSqStr:
225 s = append(s, "_html_template_jsstrescaper")
226 case stateJSRegexp:
227 s = append(s, "_html_template_jsregexpescaper")
228 case stateCSS:
229 s = append(s, "_html_template_cssvaluefilter")
230 case stateText:
231 s = append(s, "_html_template_htmlescaper")
232 case stateRCDATA:
233 s = append(s, "_html_template_rcdataescaper")
234 case stateAttr:
235 // Handled below in delim check.
236 case stateAttrName, stateTag:
237 c.state = stateAttrName
238 s = append(s, "_html_template_htmlnamefilter")
239 case stateSrcset:
240 s = append(s, "_html_template_srcsetescaper")
241 default:
242 if isComment(c.state) {
243 s = append(s, "_html_template_commentescaper")
244 } else {
245 panic("unexpected state " + c.state.String())
246 }
247 }
248 switch c.delim {
249 case delimNone:
250 // No extra-escaping needed for raw text content.
251 case delimSpaceOrTagEnd:
252 s = append(s, "_html_template_nospaceescaper")
253 default:
254 s = append(s, "_html_template_attrescaper")
255 }
256 e.editActionNode(n, s)
257 return c
258 }
259
260 // ensurePipelineContains ensures that the pipeline ends with the commands with
261 // the identifiers in s in order. If the pipeline ends with a predefined escaper
262 // (i.e. "html" or "urlquery"), merge it with the identifiers in s.
263 func ensurePipelineContains(p *parse.PipeNode, s []string) {
264 if len(s) == 0 {
265 // Do not rewrite pipeline if we have no escapers to insert.
266 return
267 }
268 // Precondition: p.Cmds contains at most one predefined escaper and the
269 // escaper will be present at p.Cmds[len(p.Cmds)-1]. This precondition is
270 // always true because of the checks in escapeAction.
271 pipelineLen := len(p.Cmds)
272 if pipelineLen > 0 {
273 lastCmd := p.Cmds[pipelineLen-1]
274 if idNode, ok := lastCmd.Args[0].(*parse.IdentifierNode); ok {
275 if esc := idNode.Ident; predefinedEscapers[esc] {
276 // Pipeline ends with a predefined escaper.
277 if len(p.Cmds) == 1 && len(lastCmd.Args) > 1 {
278 // Special case: pipeline is of the form {{ esc arg1 arg2 ... argN }},
279 // where esc is the predefined escaper, and arg1...argN are its arguments.
280 // Convert this into the equivalent form
281 // {{ _eval_args_ arg1 arg2 ... argN | esc }}, so that esc can be easily
282 // merged with the escapers in s.
283 lastCmd.Args[0] = parse.NewIdentifier("_eval_args_").SetTree(nil).SetPos(lastCmd.Args[0].Position())
284 p.Cmds = appendCmd(p.Cmds, newIdentCmd(esc, p.Position()))
285 pipelineLen++
286 }
287 // If any of the commands in s that we are about to insert is equivalent
288 // to the predefined escaper, use the predefined escaper instead.
289 dup := false
290 for i, escaper := range s {
291 if escFnsEq(esc, escaper) {
292 s[i] = idNode.Ident
293 dup = true
294 }
295 }
296 if dup {
297 // The predefined escaper will already be inserted along with the
298 // escapers in s, so do not copy it to the rewritten pipeline.
299 pipelineLen--
300 }
301 }
302 }
303 }
304 // Rewrite the pipeline, creating the escapers in s at the end of the pipeline.
305 newCmds := make([]*parse.CommandNode, pipelineLen, pipelineLen+len(s))
306 insertedIdents := make(map[string]bool)
307 for i := 0; i < pipelineLen; i++ {
308 cmd := p.Cmds[i]
309 newCmds[i] = cmd
310 if idNode, ok := cmd.Args[0].(*parse.IdentifierNode); ok {
311 insertedIdents[normalizeEscFn(idNode.Ident)] = true
312 }
313 }
314 for _, name := range s {
315 if !insertedIdents[normalizeEscFn(name)] {
316 // When two templates share an underlying parse tree via the use of
317 // AddParseTree and one template is executed after the other, this check
318 // ensures that escapers that were already inserted into the pipeline on
319 // the first escaping pass do not get inserted again.
320 newCmds = appendCmd(newCmds, newIdentCmd(name, p.Position()))
321 }
322 }
323 p.Cmds = newCmds
324 }
325
326 // predefinedEscapers contains template predefined escapers that are equivalent
327 // to some contextual escapers. Keep in sync with equivEscapers.
328 var predefinedEscapers = map[string]bool{
329 "html": true,
330 "urlquery": true,
331 }
332
333 // equivEscapers matches contextual escapers to equivalent predefined
334 // template escapers.
335 var equivEscapers = map[string]string{
336 // The following pairs of HTML escapers provide equivalent security
337 // guarantees, since they all escape '\000', '\'', '"', '&', '<', and '>'.
338 "_html_template_attrescaper": "html",
339 "_html_template_htmlescaper": "html",
340 "_html_template_rcdataescaper": "html",
341 // These two URL escapers produce URLs safe for embedding in a URL query by
342 // percent-encoding all the reserved characters specified in RFC 3986 Section
343 // 2.2
344 "_html_template_urlescaper": "urlquery",
345 // These two functions are not actually equivalent; urlquery is stricter as it
346 // escapes reserved characters (e.g. '#'), while _html_template_urlnormalizer
347 // does not. It is therefore only safe to replace _html_template_urlnormalizer
348 // with urlquery (this happens in ensurePipelineContains), but not the otherI've
349 // way around. We keep this entry around to preserve the behavior of templates
350 // written before Go 1.9, which might depend on this substitution taking place.
351 "_html_template_urlnormalizer": "urlquery",
352 }
353
354 // escFnsEq reports whether the two escaping functions are equivalent.
355 func escFnsEq(a, b string) bool {
356 return normalizeEscFn(a) == normalizeEscFn(b)
357 }
358
359 // normalizeEscFn(a) is equal to normalizeEscFn(b) for any pair of names of
360 // escaper functions a and b that are equivalent.
361 func normalizeEscFn(e string) string {
362 if norm := equivEscapers[e]; norm != "" {
363 return norm
364 }
365 return e
366 }
367
368 // redundantFuncs[a][b] implies that funcMap[b](funcMap[a](x)) == funcMap[a](x)
369 // for all x.
370 var redundantFuncs = map[string]map[string]bool{
371 "_html_template_commentescaper": {
372 "_html_template_attrescaper": true,
373 "_html_template_nospaceescaper": true,
374 "_html_template_htmlescaper": true,
375 },
376 "_html_template_cssescaper": {
377 "_html_template_attrescaper": true,
378 },
379 "_html_template_jsregexpescaper": {
380 "_html_template_attrescaper": true,
381 },
382 "_html_template_jsstrescaper": {
383 "_html_template_attrescaper": true,
384 },
385 "_html_template_urlescaper": {
386 "_html_template_urlnormalizer": true,
387 },
388 }
389
390 // appendCmd appends the given command to the end of the command pipeline
391 // unless it is redundant with the last command.
392 func appendCmd(cmds []*parse.CommandNode, cmd *parse.CommandNode) []*parse.CommandNode {
393 if n := len(cmds); n != 0 {
394 last, okLast := cmds[n-1].Args[0].(*parse.IdentifierNode)
395 next, okNext := cmd.Args[0].(*parse.IdentifierNode)
396 if okLast && okNext && redundantFuncs[last.Ident][next.Ident] {
397 return cmds
398 }
399 }
400 return append(cmds, cmd)
401 }
402
403 // newIdentCmd produces a command containing a single identifier node.
404 func newIdentCmd(identifier string, pos parse.Pos) *parse.CommandNode {
405 return &parse.CommandNode{
406 NodeType: parse.NodeCommand,
407 Args: []parse.Node{parse.NewIdentifier(identifier).SetTree(nil).SetPos(pos)}, // TODO: SetTree.
408 }
409 }
410
411 // nudge returns the context that would result from following empty string
412 // transitions from the input context.
413 // For example, parsing:
414 // `<a href=`
415 // will end in context{stateBeforeValue, attrURL}, but parsing one extra rune:
416 // `<a href=x`
417 // will end in context{stateURL, delimSpaceOrTagEnd, ...}.
418 // There are two transitions that happen when the 'x' is seen:
419 // (1) Transition from a before-value state to a start-of-value state without
420 // consuming any character.
421 // (2) Consume 'x' and transition past the first value character.
422 // In this case, nudging produces the context after (1) happens.
423 func nudge(c context) context {
424 switch c.state {
425 case stateTag:
426 // In `<foo {{.}}`, the action should emit an attribute.
427 c.state = stateAttrName
428 case stateBeforeValue:
429 // In `<foo bar={{.}}`, the action is an undelimited value.
430 c.state, c.delim, c.attr = attrStartStates[c.attr], delimSpaceOrTagEnd, attrNone
431 case stateAfterName:
432 // In `<foo bar {{.}}`, the action is an attribute name.
433 c.state, c.attr = stateAttrName, attrNone
434 }
435 return c
436 }
437
438 // join joins the two contexts of a branch template node. The result is an
439 // error context if either of the input contexts are error contexts, or if the
440 // input contexts differ.
441 func join(a, b context, node parse.Node, nodeName string) context {
442 if a.state == stateError {
443 return a
444 }
445 if b.state == stateError {
446 return b
447 }
448 if a.state == stateDead {
449 return b
450 }
451 if b.state == stateDead {
452 return a
453 }
454 if a.eq(b) {
455 return a
456 }
457
458 c := a
459 c.urlPart = b.urlPart
460 if c.eq(b) {
461 // The contexts differ only by urlPart.
462 c.urlPart = urlPartUnknown
463 return c
464 }
465
466 c = a
467 c.jsCtx = b.jsCtx
468 if c.eq(b) {
469 // The contexts differ only by jsCtx.
470 c.jsCtx = jsCtxUnknown
471 return c
472 }
473
474 // Allow a nudged context to join with an unnudged one.
475 // This means that
476 // <p title={{if .C}}{{.}}{{end}}
477 // ends in an unquoted value state even though the else branch
478 // ends in stateBeforeValue.
479 if c, d := nudge(a), nudge(b); !(c.eq(a) && d.eq(b)) {
480 if e := join(c, d, node, nodeName); e.state != stateError {
481 return e
482 }
483 }
484
485 return context{
486 state: stateError,
487 err: errorf(ErrBranchEnd, node, 0, "{{%s}} branches end in different contexts: %v, %v", nodeName, a, b),
488 }
489 }
490
491 // escapeBranch escapes a branch template node: "if", "range" and "with".
492 func (e *escaper) escapeBranch(c context, n *parse.BranchNode, nodeName string) context {
493 if nodeName == "range" {
494 e.rangeContext = &rangeContext{outer: e.rangeContext}
495 }
496 c0 := e.escapeList(c, n.List)
497 if nodeName == "range" {
498 if c0.state != stateError {
499 c0 = joinRange(c0, e.rangeContext)
500 }
501 e.rangeContext = e.rangeContext.outer
502 if c0.state == stateError {
503 return c0
504 }
505
506 // The "true" branch of a "range" node can execute multiple times.
507 // We check that executing n.List once results in the same context
508 // as executing n.List twice.
509 e.rangeContext = &rangeContext{outer: e.rangeContext}
510 c1, _ := e.escapeListConditionally(c0, n.List, nil)
511 c0 = join(c0, c1, n, nodeName)
512 if c0.state == stateError {
513 e.rangeContext = e.rangeContext.outer
514 // Make clear that this is a problem on loop re-entry
515 // since developers tend to overlook that branch when
516 // debugging templates.
517 c0.err.Line = n.Line
518 c0.err.Description = "on range loop re-entry: " + c0.err.Description
519 return c0
520 }
521 c0 = joinRange(c0, e.rangeContext)
522 e.rangeContext = e.rangeContext.outer
523 if c0.state == stateError {
524 return c0
525 }
526 }
527 c1 := e.escapeList(c, n.ElseList)
528 return join(c0, c1, n, nodeName)
529 }
530
531 func joinRange(c0 context, rc *rangeContext) context {
532 // Merge contexts at break and continue statements into overall body context.
533 // In theory we could treat breaks differently from continues, but for now it is
534 // enough to treat them both as going back to the start of the loop (which may then stop).
535 for _, c := range rc.breaks {
536 c0 = join(c0, c, c.n, "range")
537 if c0.state == stateError {
538 c0.err.Line = c.n.(*parse.BreakNode).Line
539 c0.err.Description = "at range loop break: " + c0.err.Description
540 return c0
541 }
542 }
543 for _, c := range rc.continues {
544 c0 = join(c0, c, c.n, "range")
545 if c0.state == stateError {
546 c0.err.Line = c.n.(*parse.ContinueNode).Line
547 c0.err.Description = "at range loop continue: " + c0.err.Description
548 return c0
549 }
550 }
551 return c0
552 }
553
554 // escapeList escapes a list template node.
555 func (e *escaper) escapeList(c context, n *parse.ListNode) context {
556 if n == nil {
557 return c
558 }
559 for _, m := range n.Nodes {
560 c = e.escape(c, m)
561 if c.state == stateDead {
562 break
563 }
564 }
565 return c
566 }
567
568 // escapeListConditionally escapes a list node but only preserves edits and
569 // inferences in e if the inferences and output context satisfy filter.
570 // It returns the best guess at an output context, and the result of the filter
571 // which is the same as whether e was updated.
572 func (e *escaper) escapeListConditionally(c context, n *parse.ListNode, filter func(*escaper, context) bool) (context, bool) {
573 e1 := makeEscaper(e.ns)
574 e1.rangeContext = e.rangeContext
575 // Make type inferences available to f.
576 for k, v := range e.output {
577 e1.output[k] = v
578 }
579 c = e1.escapeList(c, n)
580 ok := filter != nil && filter(&e1, c)
581 if ok {
582 // Copy inferences and edits from e1 back into e.
583 for k, v := range e1.output {
584 e.output[k] = v
585 }
586 for k, v := range e1.derived {
587 e.derived[k] = v
588 }
589 for k, v := range e1.called {
590 e.called[k] = v
591 }
592 for k, v := range e1.actionNodeEdits {
593 e.editActionNode(k, v)
594 }
595 for k, v := range e1.templateNodeEdits {
596 e.editTemplateNode(k, v)
597 }
598 for k, v := range e1.textNodeEdits {
599 e.editTextNode(k, v)
600 }
601 }
602 return c, ok
603 }
604
605 // escapeTemplate escapes a {{template}} call node.
606 func (e *escaper) escapeTemplate(c context, n *parse.TemplateNode) context {
607 c, name := e.escapeTree(c, n, n.Name, n.Line)
608 if name != n.Name {
609 e.editTemplateNode(n, name)
610 }
611 return c
612 }
613
614 // escapeTree escapes the named template starting in the given context as
615 // necessary and returns its output context.
616 func (e *escaper) escapeTree(c context, node parse.Node, name string, line int) (context, string) {
617 // Mangle the template name with the input context to produce a reliable
618 // identifier.
619 dname := c.mangle(name)
620 e.called[dname] = true
621 if out, ok := e.output[dname]; ok {
622 // Already escaped.
623 return out, dname
624 }
625 t := e.template(name)
626 if t == nil {
627 // Two cases: The template exists but is empty, or has never been mentioned at
628 // all. Distinguish the cases in the error messages.
629 if e.ns.set[name] != nil {
630 return context{
631 state: stateError,
632 err: errorf(ErrNoSuchTemplate, node, line, "%q is an incomplete or empty template", name),
633 }, dname
634 }
635 return context{
636 state: stateError,
637 err: errorf(ErrNoSuchTemplate, node, line, "no such template %q", name),
638 }, dname
639 }
640 if dname != name {
641 // Use any template derived during an earlier call to escapeTemplate
642 // with different top level templates, or clone if necessary.
643 dt := e.template(dname)
644 if dt == nil {
645 dt = template.New(dname)
646 dt.Tree = &parse.Tree{Name: dname, Root: t.Root.CopyList()}
647 e.derived[dname] = dt
648 }
649 t = dt
650 }
651 return e.computeOutCtx(c, t), dname
652 }
653
654 // computeOutCtx takes a template and its start context and computes the output
655 // context while storing any inferences in e.
656 func (e *escaper) computeOutCtx(c context, t *template.Template) context {
657 // Propagate context over the body.
658 c1, ok := e.escapeTemplateBody(c, t)
659 if !ok {
660 // Look for a fixed point by assuming c1 as the output context.
661 if c2, ok2 := e.escapeTemplateBody(c1, t); ok2 {
662 c1, ok = c2, true
663 }
664 // Use c1 as the error context if neither assumption worked.
665 }
666 if !ok && c1.state != stateError {
667 return context{
668 state: stateError,
669 err: errorf(ErrOutputContext, t.Tree.Root, 0, "cannot compute output context for template %s", t.Name()),
670 }
671 }
672 return c1
673 }
674
675 // escapeTemplateBody escapes the given template assuming the given output
676 // context, and returns the best guess at the output context and whether the
677 // assumption was correct.
678 func (e *escaper) escapeTemplateBody(c context, t *template.Template) (context, bool) {
679 filter := func(e1 *escaper, c1 context) bool {
680 if c1.state == stateError {
681 // Do not update the input escaper, e.
682 return false
683 }
684 if !e1.called[t.Name()] {
685 // If t is not recursively called, then c1 is an
686 // accurate output context.
687 return true
688 }
689 // c1 is accurate if it matches our assumed output context.
690 return c.eq(c1)
691 }
692 // We need to assume an output context so that recursive template calls
693 // take the fast path out of escapeTree instead of infinitely recursing.
694 // Naively assuming that the input context is the same as the output
695 // works >90% of the time.
696 e.output[t.Name()] = c
697 return e.escapeListConditionally(c, t.Tree.Root, filter)
698 }
699
700 // delimEnds maps each delim to a string of characters that terminate it.
701 var delimEnds = [...]string{
702 delimDoubleQuote: `"`,
703 delimSingleQuote: "'",
704 // Determined empirically by running the below in various browsers.
705 // var div = document.createElement("DIV");
706 // for (var i = 0; i < 0x10000; ++i) {
707 // div.innerHTML = "<span title=x" + String.fromCharCode(i) + "-bar>";
708 // if (div.getElementsByTagName("SPAN")[0].title.indexOf("bar") < 0)
709 // document.write("<p>U+" + i.toString(16));
710 // }
711 delimSpaceOrTagEnd: " \t\n\f\r>",
712 }
713
714 var doctypeBytes = []byte("<!DOCTYPE")
715
716 // escapeText escapes a text template node.
717 func (e *escaper) escapeText(c context, n *parse.TextNode) context {
718 s, written, i, b := n.Text, 0, 0, new(bytes.Buffer)
719 for i != len(s) {
720 c1, nread := contextAfterText(c, s[i:])
721 i1 := i + nread
722 if c.state == stateText || c.state == stateRCDATA {
723 end := i1
724 if c1.state != c.state {
725 for j := end - 1; j >= i; j-- {
726 if s[j] == '<' {
727 end = j
728 break
729 }
730 }
731 }
732 for j := i; j < end; j++ {
733 if s[j] == '<' && !bytes.HasPrefix(bytes.ToUpper(s[j:]), doctypeBytes) {
734 b.Write(s[written:j])
735 b.WriteString("&lt;")
736 written = j + 1
737 }
738 }
739 } else if isComment(c.state) && c.delim == delimNone {
740 switch c.state {
741 case stateJSBlockCmt:
742 // https://es5.github.com/#x7.4:
743 // "Comments behave like white space and are
744 // discarded except that, if a MultiLineComment
745 // contains a line terminator character, then
746 // the entire comment is considered to be a
747 // LineTerminator for purposes of parsing by
748 // the syntactic grammar."
749 if bytes.ContainsAny(s[written:i1], "\n\r\u2028\u2029") {
750 b.WriteByte('\n')
751 } else {
752 b.WriteByte(' ')
753 }
754 case stateCSSBlockCmt:
755 b.WriteByte(' ')
756 }
757 written = i1
758 }
759 if c.state != c1.state && isComment(c1.state) && c1.delim == delimNone {
760 // Preserve the portion between written and the comment start.
761 cs := i1 - 2
762 if c1.state == stateHTMLCmt {
763 // "<!--" instead of "/*" or "//"
764 cs -= 2
765 }
766 b.Write(s[written:cs])
767 written = i1
768 }
769 if i == i1 && c.state == c1.state {
770 panic(fmt.Sprintf("infinite loop from %v to %v on %q..%q", c, c1, s[:i], s[i:]))
771 }
772 c, i = c1, i1
773 }
774
775 if written != 0 && c.state != stateError {
776 if !isComment(c.state) || c.delim != delimNone {
777 b.Write(n.Text[written:])
778 }
779 e.editTextNode(n, b.Bytes())
780 }
781 return c
782 }
783
784 // contextAfterText starts in context c, consumes some tokens from the front of
785 // s, then returns the context after those tokens and the unprocessed suffix.
786 func contextAfterText(c context, s []byte) (context, int) {
787 if c.delim == delimNone {
788 c1, i := tSpecialTagEnd(c, s)
789 if i == 0 {
790 // A special end tag (`</script>`) has been seen and
791 // all content preceding it has been consumed.
792 return c1, 0
793 }
794 // Consider all content up to any end tag.
795 return transitionFunc[c.state](c, s[:i])
796 }
797
798 // We are at the beginning of an attribute value.
799
800 i := bytes.IndexAny(s, delimEnds[c.delim])
801 if i == -1 {
802 i = len(s)
803 }
804 if c.delim == delimSpaceOrTagEnd {
805 // https://www.w3.org/TR/html5/syntax.html#attribute-value-(unquoted)-state
806 // lists the runes below as error characters.
807 // Error out because HTML parsers may differ on whether
808 // "<a id= onclick=f(" ends inside id's or onclick's value,
809 // "<a class=`foo " ends inside a value,
810 // "<a style=font:'Arial'" needs open-quote fixup.
811 // IE treats '`' as a quotation character.
812 if j := bytes.IndexAny(s[:i], "\"'<=`"); j >= 0 {
813 return context{
814 state: stateError,
815 err: errorf(ErrBadHTML, nil, 0, "%q in unquoted attr: %q", s[j:j+1], s[:i]),
816 }, len(s)
817 }
818 }
819 if i == len(s) {
820 // Remain inside the attribute.
821 // Decode the value so non-HTML rules can easily handle
822 // <button onclick="alert(&quot;Hi!&quot;)">
823 // without having to entity decode token boundaries.
824 for u := []byte(html.UnescapeString(string(s))); len(u) != 0; {
825 c1, i1 := transitionFunc[c.state](c, u)
826 c, u = c1, u[i1:]
827 }
828 return c, len(s)
829 }
830
831 element := c.element
832
833 // If this is a non-JS "type" attribute inside "script" tag, do not treat the contents as JS.
834 if c.state == stateAttr && c.element == elementScript && c.attr == attrScriptType && !isJSType(string(s[:i])) {
835 element = elementNone
836 }
837
838 if c.delim != delimSpaceOrTagEnd {
839 // Consume any quote.
840 i++
841 }
842 // On exiting an attribute, we discard all state information
843 // except the state and element.
844 return context{state: stateTag, element: element}, i
845 }
846
847 // editActionNode records a change to an action pipeline for later commit.
848 func (e *escaper) editActionNode(n *parse.ActionNode, cmds []string) {
849 if _, ok := e.actionNodeEdits[n]; ok {
850 panic(fmt.Sprintf("node %s shared between templates", n))
851 }
852 e.actionNodeEdits[n] = cmds
853 }
854
855 // editTemplateNode records a change to a {{template}} callee for later commit.
856 func (e *escaper) editTemplateNode(n *parse.TemplateNode, callee string) {
857 if _, ok := e.templateNodeEdits[n]; ok {
858 panic(fmt.Sprintf("node %s shared between templates", n))
859 }
860 e.templateNodeEdits[n] = callee
861 }
862
863 // editTextNode records a change to a text node for later commit.
864 func (e *escaper) editTextNode(n *parse.TextNode, text []byte) {
865 if _, ok := e.textNodeEdits[n]; ok {
866 panic(fmt.Sprintf("node %s shared between templates", n))
867 }
868 e.textNodeEdits[n] = text
869 }
870
871 // commit applies changes to actions and template calls needed to contextually
872 // autoescape content and adds any derived templates to the set.
873 func (e *escaper) commit() {
874 for name := range e.output {
875 e.template(name).Funcs(funcMap)
876 }
877 // Any template from the name space associated with this escaper can be used
878 // to add derived templates to the underlying text/template name space.
879 tmpl := e.arbitraryTemplate()
880 for _, t := range e.derived {
881 if _, err := tmpl.text.AddParseTree(t.Name(), t.Tree); err != nil {
882 panic("error adding derived template")
883 }
884 }
885 for n, s := range e.actionNodeEdits {
886 ensurePipelineContains(n.Pipe, s)
887 }
888 for n, name := range e.templateNodeEdits {
889 n.Name = name
890 }
891 for n, s := range e.textNodeEdits {
892 n.Text = s
893 }
894 // Reset state that is specific to this commit so that the same changes are
895 // not re-applied to the template on subsequent calls to commit.
896 e.called = make(map[string]bool)
897 e.actionNodeEdits = make(map[*parse.ActionNode][]string)
898 e.templateNodeEdits = make(map[*parse.TemplateNode]string)
899 e.textNodeEdits = make(map[*parse.TextNode][]byte)
900 }
901
902 // template returns the named template given a mangled template name.
903 func (e *escaper) template(name string) *template.Template {
904 // Any template from the name space associated with this escaper can be used
905 // to look up templates in the underlying text/template name space.
906 t := e.arbitraryTemplate().text.Lookup(name)
907 if t == nil {
908 t = e.derived[name]
909 }
910 return t
911 }
912
913 // arbitraryTemplate returns an arbitrary template from the name space
914 // associated with e and panics if no templates are found.
915 func (e *escaper) arbitraryTemplate() *Template {
916 for _, t := range e.ns.set {
917 return t
918 }
919 panic("no templates in name space")
920 }
921
922 // Forwarding functions so that clients need only import this package
923 // to reach the general escaping functions of text/template.
924
925 // HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
926 func HTMLEscape(w io.Writer, b []byte) {
927 template.HTMLEscape(w, b)
928 }
929
930 // HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
931 func HTMLEscapeString(s string) string {
932 return template.HTMLEscapeString(s)
933 }
934
935 // HTMLEscaper returns the escaped HTML equivalent of the textual
936 // representation of its arguments.
937 func HTMLEscaper(args ...any) string {
938 return template.HTMLEscaper(args...)
939 }
940
941 // JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
942 func JSEscape(w io.Writer, b []byte) {
943 template.JSEscape(w, b)
944 }
945
946 // JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
947 func JSEscapeString(s string) string {
948 return template.JSEscapeString(s)
949 }
950
951 // JSEscaper returns the escaped JavaScript equivalent of the textual
952 // representation of its arguments.
953 func JSEscaper(args ...any) string {
954 return template.JSEscaper(args...)
955 }
956
957 // URLQueryEscaper returns the escaped value of the textual representation of
958 // its arguments in a form suitable for embedding in a URL query.
959 func URLQueryEscaper(args ...any) string {
960 return template.URLQueryEscaper(args...)
961 }