github.com/linchen2chris/hugo@v0.0.0-20230307053224-cec209389705/tpl/internal/go_templates/htmltemplate/escape.go (about)

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