github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/html/template/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  	"text/template"
    13  	"text/template/parse"
    14  )
    15  
    16  // escapeTemplates rewrites the named templates, which must be
    17  // associated with t, to guarantee that the output of any of the named
    18  // templates is properly escaped.  Names should include the names of
    19  // all templates that might be Executed but need not include helper
    20  // templates.  If no error is returned, then the named templates have
    21  // been modified.  Otherwise the named templates have been rendered
    22  // unusable.
    23  func escapeTemplates(tmpl *Template, names ...string) error {
    24  	e := newEscaper(tmpl)
    25  	for _, name := range names {
    26  		c, _ := e.escapeTree(context{}, name, 0)
    27  		var err error
    28  		if c.err != nil {
    29  			err, c.err.Name = c.err, name
    30  		} else if c.state != stateText {
    31  			err = &Error{ErrEndContext, name, 0, fmt.Sprintf("ends in a non-text context: %v", c)}
    32  		}
    33  		if err != nil {
    34  			// Prevent execution of unsafe templates.
    35  			for _, name := range names {
    36  				if t := tmpl.set[name]; t != nil {
    37  					t.text.Tree = nil
    38  				}
    39  			}
    40  			return err
    41  		}
    42  		tmpl.escaped = true
    43  	}
    44  	e.commit()
    45  	return nil
    46  }
    47  
    48  // funcMap maps command names to functions that render their inputs safe.
    49  var funcMap = template.FuncMap{
    50  	"html_template_attrescaper":     attrEscaper,
    51  	"html_template_commentescaper":  commentEscaper,
    52  	"html_template_cssescaper":      cssEscaper,
    53  	"html_template_cssvaluefilter":  cssValueFilter,
    54  	"html_template_htmlnamefilter":  htmlNameFilter,
    55  	"html_template_htmlescaper":     htmlEscaper,
    56  	"html_template_jsregexpescaper": jsRegexpEscaper,
    57  	"html_template_jsstrescaper":    jsStrEscaper,
    58  	"html_template_jsvalescaper":    jsValEscaper,
    59  	"html_template_nospaceescaper":  htmlNospaceEscaper,
    60  	"html_template_rcdataescaper":   rcdataEscaper,
    61  	"html_template_urlescaper":      urlEscaper,
    62  	"html_template_urlfilter":       urlFilter,
    63  	"html_template_urlnormalizer":   urlNormalizer,
    64  }
    65  
    66  // equivEscapers matches contextual escapers to equivalent template builtins.
    67  var equivEscapers = map[string]string{
    68  	"html_template_attrescaper":    "html",
    69  	"html_template_htmlescaper":    "html",
    70  	"html_template_nospaceescaper": "html",
    71  	"html_template_rcdataescaper":  "html",
    72  	"html_template_urlescaper":     "urlquery",
    73  	"html_template_urlnormalizer":  "urlquery",
    74  }
    75  
    76  // escaper collects type inferences about templates and changes needed to make
    77  // templates injection safe.
    78  type escaper struct {
    79  	tmpl *Template
    80  	// output[templateName] is the output context for a templateName that
    81  	// has been mangled to include its input context.
    82  	output map[string]context
    83  	// derived[c.mangle(name)] maps to a template derived from the template
    84  	// named name templateName for the start context c.
    85  	derived map[string]*template.Template
    86  	// called[templateName] is a set of called mangled template names.
    87  	called map[string]bool
    88  	// xxxNodeEdits are the accumulated edits to apply during commit.
    89  	// Such edits are not applied immediately in case a template set
    90  	// executes a given template in different escaping contexts.
    91  	actionNodeEdits   map[*parse.ActionNode][]string
    92  	templateNodeEdits map[*parse.TemplateNode]string
    93  	textNodeEdits     map[*parse.TextNode][]byte
    94  }
    95  
    96  // newEscaper creates a blank escaper for the given set.
    97  func newEscaper(t *Template) *escaper {
    98  	return &escaper{
    99  		t,
   100  		map[string]context{},
   101  		map[string]*template.Template{},
   102  		map[string]bool{},
   103  		map[*parse.ActionNode][]string{},
   104  		map[*parse.TemplateNode]string{},
   105  		map[*parse.TextNode][]byte{},
   106  	}
   107  }
   108  
   109  // filterFailsafe is an innocuous word that is emitted in place of unsafe values
   110  // by sanitizer functions. It is not a keyword in any programming language,
   111  // contains no special characters, is not empty, and when it appears in output
   112  // it is distinct enough that a developer can find the source of the problem
   113  // via a search engine.
   114  const filterFailsafe = "ZgotmplZ"
   115  
   116  // escape escapes a template node.
   117  func (e *escaper) escape(c context, n parse.Node) context {
   118  	switch n := n.(type) {
   119  	case *parse.ActionNode:
   120  		return e.escapeAction(c, n)
   121  	case *parse.IfNode:
   122  		return e.escapeBranch(c, &n.BranchNode, "if")
   123  	case *parse.ListNode:
   124  		return e.escapeList(c, n)
   125  	case *parse.RangeNode:
   126  		return e.escapeBranch(c, &n.BranchNode, "range")
   127  	case *parse.TemplateNode:
   128  		return e.escapeTemplate(c, n)
   129  	case *parse.TextNode:
   130  		return e.escapeText(c, n)
   131  	case *parse.WithNode:
   132  		return e.escapeBranch(c, &n.BranchNode, "with")
   133  	}
   134  	panic("escaping " + n.String() + " is unimplemented")
   135  }
   136  
   137  // escapeAction escapes an action template node.
   138  func (e *escaper) escapeAction(c context, n *parse.ActionNode) context {
   139  	if len(n.Pipe.Decl) != 0 {
   140  		// A local variable assignment, not an interpolation.
   141  		return c
   142  	}
   143  	c = nudge(c)
   144  	s := make([]string, 0, 3)
   145  	switch c.state {
   146  	case stateError:
   147  		return c
   148  	case stateURL, stateCSSDqStr, stateCSSSqStr, stateCSSDqURL, stateCSSSqURL, stateCSSURL:
   149  		switch c.urlPart {
   150  		case urlPartNone:
   151  			s = append(s, "html_template_urlfilter")
   152  			fallthrough
   153  		case urlPartPreQuery:
   154  			switch c.state {
   155  			case stateCSSDqStr, stateCSSSqStr:
   156  				s = append(s, "html_template_cssescaper")
   157  			default:
   158  				s = append(s, "html_template_urlnormalizer")
   159  			}
   160  		case urlPartQueryOrFrag:
   161  			s = append(s, "html_template_urlescaper")
   162  		case urlPartUnknown:
   163  			return context{
   164  				state: stateError,
   165  				err:   errorf(ErrAmbigContext, n.Line, "%s appears in an ambiguous URL context", n),
   166  			}
   167  		default:
   168  			panic(c.urlPart.String())
   169  		}
   170  	case stateJS:
   171  		s = append(s, "html_template_jsvalescaper")
   172  		// A slash after a value starts a div operator.
   173  		c.jsCtx = jsCtxDivOp
   174  	case stateJSDqStr, stateJSSqStr:
   175  		s = append(s, "html_template_jsstrescaper")
   176  	case stateJSRegexp:
   177  		s = append(s, "html_template_jsregexpescaper")
   178  	case stateCSS:
   179  		s = append(s, "html_template_cssvaluefilter")
   180  	case stateText:
   181  		s = append(s, "html_template_htmlescaper")
   182  	case stateRCDATA:
   183  		s = append(s, "html_template_rcdataescaper")
   184  	case stateAttr:
   185  		// Handled below in delim check.
   186  	case stateAttrName, stateTag:
   187  		c.state = stateAttrName
   188  		s = append(s, "html_template_htmlnamefilter")
   189  	default:
   190  		if isComment(c.state) {
   191  			s = append(s, "html_template_commentescaper")
   192  		} else {
   193  			panic("unexpected state " + c.state.String())
   194  		}
   195  	}
   196  	switch c.delim {
   197  	case delimNone:
   198  		// No extra-escaping needed for raw text content.
   199  	case delimSpaceOrTagEnd:
   200  		s = append(s, "html_template_nospaceescaper")
   201  	default:
   202  		s = append(s, "html_template_attrescaper")
   203  	}
   204  	e.editActionNode(n, s)
   205  	return c
   206  }
   207  
   208  // ensurePipelineContains ensures that the pipeline has commands with
   209  // the identifiers in s in order.
   210  // If the pipeline already has some of the sanitizers, do not interfere.
   211  // For example, if p is (.X | html) and s is ["escapeJSVal", "html"] then it
   212  // has one matching, "html", and one to insert, "escapeJSVal", to produce
   213  // (.X | escapeJSVal | html).
   214  func ensurePipelineContains(p *parse.PipeNode, s []string) {
   215  	if len(s) == 0 {
   216  		return
   217  	}
   218  	n := len(p.Cmds)
   219  	// Find the identifiers at the end of the command chain.
   220  	idents := p.Cmds
   221  	for i := n - 1; i >= 0; i-- {
   222  		if cmd := p.Cmds[i]; len(cmd.Args) != 0 {
   223  			if _, ok := cmd.Args[0].(*parse.IdentifierNode); ok {
   224  				continue
   225  			}
   226  		}
   227  		idents = p.Cmds[i+1:]
   228  	}
   229  	dups := 0
   230  	for _, id := range idents {
   231  		if escFnsEq(s[dups], (id.Args[0].(*parse.IdentifierNode)).Ident) {
   232  			dups++
   233  			if dups == len(s) {
   234  				return
   235  			}
   236  		}
   237  	}
   238  	newCmds := make([]*parse.CommandNode, n-len(idents), n+len(s)-dups)
   239  	copy(newCmds, p.Cmds)
   240  	// Merge existing identifier commands with the sanitizers needed.
   241  	for _, id := range idents {
   242  		pos := id.Args[0].Position()
   243  		i := indexOfStr((id.Args[0].(*parse.IdentifierNode)).Ident, s, escFnsEq)
   244  		if i != -1 {
   245  			for _, name := range s[:i] {
   246  				newCmds = appendCmd(newCmds, newIdentCmd(name, pos))
   247  			}
   248  			s = s[i+1:]
   249  		}
   250  		newCmds = appendCmd(newCmds, id)
   251  	}
   252  	// Create any remaining sanitizers.
   253  	for _, name := range s {
   254  		newCmds = appendCmd(newCmds, newIdentCmd(name, p.Position()))
   255  	}
   256  	p.Cmds = newCmds
   257  }
   258  
   259  // redundantFuncs[a][b] implies that funcMap[b](funcMap[a](x)) == funcMap[a](x)
   260  // for all x.
   261  var redundantFuncs = map[string]map[string]bool{
   262  	"html_template_commentescaper": {
   263  		"html_template_attrescaper":    true,
   264  		"html_template_nospaceescaper": true,
   265  		"html_template_htmlescaper":    true,
   266  	},
   267  	"html_template_cssescaper": {
   268  		"html_template_attrescaper": true,
   269  	},
   270  	"html_template_jsregexpescaper": {
   271  		"html_template_attrescaper": true,
   272  	},
   273  	"html_template_jsstrescaper": {
   274  		"html_template_attrescaper": true,
   275  	},
   276  	"html_template_urlescaper": {
   277  		"html_template_urlnormalizer": true,
   278  	},
   279  }
   280  
   281  // appendCmd appends the given command to the end of the command pipeline
   282  // unless it is redundant with the last command.
   283  func appendCmd(cmds []*parse.CommandNode, cmd *parse.CommandNode) []*parse.CommandNode {
   284  	if n := len(cmds); n != 0 {
   285  		last, ok := cmds[n-1].Args[0].(*parse.IdentifierNode)
   286  		next, _ := cmd.Args[0].(*parse.IdentifierNode)
   287  		if ok && redundantFuncs[last.Ident][next.Ident] {
   288  			return cmds
   289  		}
   290  	}
   291  	return append(cmds, cmd)
   292  }
   293  
   294  // indexOfStr is the first i such that eq(s, strs[i]) or -1 if s was not found.
   295  func indexOfStr(s string, strs []string, eq func(a, b string) bool) int {
   296  	for i, t := range strs {
   297  		if eq(s, t) {
   298  			return i
   299  		}
   300  	}
   301  	return -1
   302  }
   303  
   304  // escFnsEq returns whether the two escaping functions are equivalent.
   305  func escFnsEq(a, b string) bool {
   306  	if e := equivEscapers[a]; e != "" {
   307  		a = e
   308  	}
   309  	if e := equivEscapers[b]; e != "" {
   310  		b = e
   311  	}
   312  	return a == b
   313  }
   314  
   315  // newIdentCmd produces a command containing a single identifier node.
   316  func newIdentCmd(identifier string, pos parse.Pos) *parse.CommandNode {
   317  	return &parse.CommandNode{
   318  		NodeType: parse.NodeCommand,
   319  		Args:     []parse.Node{parse.NewIdentifier(identifier).SetPos(pos)},
   320  	}
   321  }
   322  
   323  // nudge returns the context that would result from following empty string
   324  // transitions from the input context.
   325  // For example, parsing:
   326  //     `<a href=`
   327  // will end in context{stateBeforeValue, attrURL}, but parsing one extra rune:
   328  //     `<a href=x`
   329  // will end in context{stateURL, delimSpaceOrTagEnd, ...}.
   330  // There are two transitions that happen when the 'x' is seen:
   331  // (1) Transition from a before-value state to a start-of-value state without
   332  //     consuming any character.
   333  // (2) Consume 'x' and transition past the first value character.
   334  // In this case, nudging produces the context after (1) happens.
   335  func nudge(c context) context {
   336  	switch c.state {
   337  	case stateTag:
   338  		// In `<foo {{.}}`, the action should emit an attribute.
   339  		c.state = stateAttrName
   340  	case stateBeforeValue:
   341  		// In `<foo bar={{.}}`, the action is an undelimited value.
   342  		c.state, c.delim, c.attr = attrStartStates[c.attr], delimSpaceOrTagEnd, attrNone
   343  	case stateAfterName:
   344  		// In `<foo bar {{.}}`, the action is an attribute name.
   345  		c.state, c.attr = stateAttrName, attrNone
   346  	}
   347  	return c
   348  }
   349  
   350  // join joins the two contexts of a branch template node. The result is an
   351  // error context if either of the input contexts are error contexts, or if the
   352  // the input contexts differ.
   353  func join(a, b context, line int, nodeName string) context {
   354  	if a.state == stateError {
   355  		return a
   356  	}
   357  	if b.state == stateError {
   358  		return b
   359  	}
   360  	if a.eq(b) {
   361  		return a
   362  	}
   363  
   364  	c := a
   365  	c.urlPart = b.urlPart
   366  	if c.eq(b) {
   367  		// The contexts differ only by urlPart.
   368  		c.urlPart = urlPartUnknown
   369  		return c
   370  	}
   371  
   372  	c = a
   373  	c.jsCtx = b.jsCtx
   374  	if c.eq(b) {
   375  		// The contexts differ only by jsCtx.
   376  		c.jsCtx = jsCtxUnknown
   377  		return c
   378  	}
   379  
   380  	// Allow a nudged context to join with an unnudged one.
   381  	// This means that
   382  	//   <p title={{if .C}}{{.}}{{end}}
   383  	// ends in an unquoted value state even though the else branch
   384  	// ends in stateBeforeValue.
   385  	if c, d := nudge(a), nudge(b); !(c.eq(a) && d.eq(b)) {
   386  		if e := join(c, d, line, nodeName); e.state != stateError {
   387  			return e
   388  		}
   389  	}
   390  
   391  	return context{
   392  		state: stateError,
   393  		err:   errorf(ErrBranchEnd, line, "{{%s}} branches end in different contexts: %v, %v", nodeName, a, b),
   394  	}
   395  }
   396  
   397  // escapeBranch escapes a branch template node: "if", "range" and "with".
   398  func (e *escaper) escapeBranch(c context, n *parse.BranchNode, nodeName string) context {
   399  	c0 := e.escapeList(c, n.List)
   400  	if nodeName == "range" && c0.state != stateError {
   401  		// The "true" branch of a "range" node can execute multiple times.
   402  		// We check that executing n.List once results in the same context
   403  		// as executing n.List twice.
   404  		c1, _ := e.escapeListConditionally(c0, n.List, nil)
   405  		c0 = join(c0, c1, n.Line, nodeName)
   406  		if c0.state == stateError {
   407  			// Make clear that this is a problem on loop re-entry
   408  			// since developers tend to overlook that branch when
   409  			// debugging templates.
   410  			c0.err.Line = n.Line
   411  			c0.err.Description = "on range loop re-entry: " + c0.err.Description
   412  			return c0
   413  		}
   414  	}
   415  	c1 := e.escapeList(c, n.ElseList)
   416  	return join(c0, c1, n.Line, nodeName)
   417  }
   418  
   419  // escapeList escapes a list template node.
   420  func (e *escaper) escapeList(c context, n *parse.ListNode) context {
   421  	if n == nil {
   422  		return c
   423  	}
   424  	for _, m := range n.Nodes {
   425  		c = e.escape(c, m)
   426  	}
   427  	return c
   428  }
   429  
   430  // escapeListConditionally escapes a list node but only preserves edits and
   431  // inferences in e if the inferences and output context satisfy filter.
   432  // It returns the best guess at an output context, and the result of the filter
   433  // which is the same as whether e was updated.
   434  func (e *escaper) escapeListConditionally(c context, n *parse.ListNode, filter func(*escaper, context) bool) (context, bool) {
   435  	e1 := newEscaper(e.tmpl)
   436  	// Make type inferences available to f.
   437  	for k, v := range e.output {
   438  		e1.output[k] = v
   439  	}
   440  	c = e1.escapeList(c, n)
   441  	ok := filter != nil && filter(e1, c)
   442  	if ok {
   443  		// Copy inferences and edits from e1 back into e.
   444  		for k, v := range e1.output {
   445  			e.output[k] = v
   446  		}
   447  		for k, v := range e1.derived {
   448  			e.derived[k] = v
   449  		}
   450  		for k, v := range e1.called {
   451  			e.called[k] = v
   452  		}
   453  		for k, v := range e1.actionNodeEdits {
   454  			e.editActionNode(k, v)
   455  		}
   456  		for k, v := range e1.templateNodeEdits {
   457  			e.editTemplateNode(k, v)
   458  		}
   459  		for k, v := range e1.textNodeEdits {
   460  			e.editTextNode(k, v)
   461  		}
   462  	}
   463  	return c, ok
   464  }
   465  
   466  // escapeTemplate escapes a {{template}} call node.
   467  func (e *escaper) escapeTemplate(c context, n *parse.TemplateNode) context {
   468  	c, name := e.escapeTree(c, n.Name, n.Line)
   469  	if name != n.Name {
   470  		e.editTemplateNode(n, name)
   471  	}
   472  	return c
   473  }
   474  
   475  // escapeTree escapes the named template starting in the given context as
   476  // necessary and returns its output context.
   477  func (e *escaper) escapeTree(c context, name string, line int) (context, string) {
   478  	// Mangle the template name with the input context to produce a reliable
   479  	// identifier.
   480  	dname := c.mangle(name)
   481  	e.called[dname] = true
   482  	if out, ok := e.output[dname]; ok {
   483  		// Already escaped.
   484  		return out, dname
   485  	}
   486  	t := e.template(name)
   487  	if t == nil {
   488  		// Two cases: The template exists but is empty, or has never been mentioned at
   489  		// all. Distinguish the cases in the error messages.
   490  		if e.tmpl.set[name] != nil {
   491  			return context{
   492  				state: stateError,
   493  				err:   errorf(ErrNoSuchTemplate, line, "%q is an incomplete or empty template", name),
   494  			}, dname
   495  		}
   496  		return context{
   497  			state: stateError,
   498  			err:   errorf(ErrNoSuchTemplate, line, "no such template %q", name),
   499  		}, dname
   500  	}
   501  	if dname != name {
   502  		// Use any template derived during an earlier call to escapeTemplate
   503  		// with different top level templates, or clone if necessary.
   504  		dt := e.template(dname)
   505  		if dt == nil {
   506  			dt = template.New(dname)
   507  			dt.Tree = &parse.Tree{Name: dname, Root: t.Root.CopyList()}
   508  			e.derived[dname] = dt
   509  		}
   510  		t = dt
   511  	}
   512  	return e.computeOutCtx(c, t), dname
   513  }
   514  
   515  // computeOutCtx takes a template and its start context and computes the output
   516  // context while storing any inferences in e.
   517  func (e *escaper) computeOutCtx(c context, t *template.Template) context {
   518  	// Propagate context over the body.
   519  	c1, ok := e.escapeTemplateBody(c, t)
   520  	if !ok {
   521  		// Look for a fixed point by assuming c1 as the output context.
   522  		if c2, ok2 := e.escapeTemplateBody(c1, t); ok2 {
   523  			c1, ok = c2, true
   524  		}
   525  		// Use c1 as the error context if neither assumption worked.
   526  	}
   527  	if !ok && c1.state != stateError {
   528  		return context{
   529  			state: stateError,
   530  			// TODO: Find the first node with a line in t.text.Tree.Root
   531  			err: errorf(ErrOutputContext, 0, "cannot compute output context for template %s", t.Name()),
   532  		}
   533  	}
   534  	return c1
   535  }
   536  
   537  // escapeTemplateBody escapes the given template assuming the given output
   538  // context, and returns the best guess at the output context and whether the
   539  // assumption was correct.
   540  func (e *escaper) escapeTemplateBody(c context, t *template.Template) (context, bool) {
   541  	filter := func(e1 *escaper, c1 context) bool {
   542  		if c1.state == stateError {
   543  			// Do not update the input escaper, e.
   544  			return false
   545  		}
   546  		if !e1.called[t.Name()] {
   547  			// If t is not recursively called, then c1 is an
   548  			// accurate output context.
   549  			return true
   550  		}
   551  		// c1 is accurate if it matches our assumed output context.
   552  		return c.eq(c1)
   553  	}
   554  	// We need to assume an output context so that recursive template calls
   555  	// take the fast path out of escapeTree instead of infinitely recursing.
   556  	// Naively assuming that the input context is the same as the output
   557  	// works >90% of the time.
   558  	e.output[t.Name()] = c
   559  	return e.escapeListConditionally(c, t.Tree.Root, filter)
   560  }
   561  
   562  // delimEnds maps each delim to a string of characters that terminate it.
   563  var delimEnds = [...]string{
   564  	delimDoubleQuote: `"`,
   565  	delimSingleQuote: "'",
   566  	// Determined empirically by running the below in various browsers.
   567  	// var div = document.createElement("DIV");
   568  	// for (var i = 0; i < 0x10000; ++i) {
   569  	//   div.innerHTML = "<span title=x" + String.fromCharCode(i) + "-bar>";
   570  	//   if (div.getElementsByTagName("SPAN")[0].title.indexOf("bar") < 0)
   571  	//     document.write("<p>U+" + i.toString(16));
   572  	// }
   573  	delimSpaceOrTagEnd: " \t\n\f\r>",
   574  }
   575  
   576  var doctypeBytes = []byte("<!DOCTYPE")
   577  
   578  // escapeText escapes a text template node.
   579  func (e *escaper) escapeText(c context, n *parse.TextNode) context {
   580  	s, written, i, b := n.Text, 0, 0, new(bytes.Buffer)
   581  	for i != len(s) {
   582  		c1, nread := contextAfterText(c, s[i:])
   583  		i1 := i + nread
   584  		if c.state == stateText || c.state == stateRCDATA {
   585  			end := i1
   586  			if c1.state != c.state {
   587  				for j := end - 1; j >= i; j-- {
   588  					if s[j] == '<' {
   589  						end = j
   590  						break
   591  					}
   592  				}
   593  			}
   594  			for j := i; j < end; j++ {
   595  				if s[j] == '<' && !bytes.HasPrefix(bytes.ToUpper(s[j:]), doctypeBytes) {
   596  					b.Write(s[written:j])
   597  					b.WriteString("&lt;")
   598  					written = j + 1
   599  				}
   600  			}
   601  		} else if isComment(c.state) && c.delim == delimNone {
   602  			switch c.state {
   603  			case stateJSBlockCmt:
   604  				// http://es5.github.com/#x7.4:
   605  				// "Comments behave like white space and are
   606  				// discarded except that, if a MultiLineComment
   607  				// contains a line terminator character, then
   608  				// the entire comment is considered to be a
   609  				// LineTerminator for purposes of parsing by
   610  				// the syntactic grammar."
   611  				if bytes.IndexAny(s[written:i1], "\n\r\u2028\u2029") != -1 {
   612  					b.WriteByte('\n')
   613  				} else {
   614  					b.WriteByte(' ')
   615  				}
   616  			case stateCSSBlockCmt:
   617  				b.WriteByte(' ')
   618  			}
   619  			written = i1
   620  		}
   621  		if c.state != c1.state && isComment(c1.state) && c1.delim == delimNone {
   622  			// Preserve the portion between written and the comment start.
   623  			cs := i1 - 2
   624  			if c1.state == stateHTMLCmt {
   625  				// "<!--" instead of "/*" or "//"
   626  				cs -= 2
   627  			}
   628  			b.Write(s[written:cs])
   629  			written = i1
   630  		}
   631  		if i == i1 && c.state == c1.state {
   632  			panic(fmt.Sprintf("infinite loop from %v to %v on %q..%q", c, c1, s[:i], s[i:]))
   633  		}
   634  		c, i = c1, i1
   635  	}
   636  
   637  	if written != 0 && c.state != stateError {
   638  		if !isComment(c.state) || c.delim != delimNone {
   639  			b.Write(n.Text[written:])
   640  		}
   641  		e.editTextNode(n, b.Bytes())
   642  	}
   643  	return c
   644  }
   645  
   646  // contextAfterText starts in context c, consumes some tokens from the front of
   647  // s, then returns the context after those tokens and the unprocessed suffix.
   648  func contextAfterText(c context, s []byte) (context, int) {
   649  	if c.delim == delimNone {
   650  		c1, i := tSpecialTagEnd(c, s)
   651  		if i == 0 {
   652  			// A special end tag (`</script>`) has been seen and
   653  			// all content preceding it has been consumed.
   654  			return c1, 0
   655  		}
   656  		// Consider all content up to any end tag.
   657  		return transitionFunc[c.state](c, s[:i])
   658  	}
   659  
   660  	i := bytes.IndexAny(s, delimEnds[c.delim])
   661  	if i == -1 {
   662  		i = len(s)
   663  	}
   664  	if c.delim == delimSpaceOrTagEnd {
   665  		// http://www.w3.org/TR/html5/tokenization.html#attribute-value-unquoted-state
   666  		// lists the runes below as error characters.
   667  		// Error out because HTML parsers may differ on whether
   668  		// "<a id= onclick=f("     ends inside id's or onclick's value,
   669  		// "<a class=`foo "        ends inside a value,
   670  		// "<a style=font:'Arial'" needs open-quote fixup.
   671  		// IE treats '`' as a quotation character.
   672  		if j := bytes.IndexAny(s[:i], "\"'<=`"); j >= 0 {
   673  			return context{
   674  				state: stateError,
   675  				err:   errorf(ErrBadHTML, 0, "%q in unquoted attr: %q", s[j:j+1], s[:i]),
   676  			}, len(s)
   677  		}
   678  	}
   679  	if i == len(s) {
   680  		// Remain inside the attribute.
   681  		// Decode the value so non-HTML rules can easily handle
   682  		//     <button onclick="alert(&quot;Hi!&quot;)">
   683  		// without having to entity decode token boundaries.
   684  		for u := []byte(html.UnescapeString(string(s))); len(u) != 0; {
   685  			c1, i1 := transitionFunc[c.state](c, u)
   686  			c, u = c1, u[i1:]
   687  		}
   688  		return c, len(s)
   689  	}
   690  	if c.delim != delimSpaceOrTagEnd {
   691  		// Consume any quote.
   692  		i++
   693  	}
   694  	// On exiting an attribute, we discard all state information
   695  	// except the state and element.
   696  	return context{state: stateTag, element: c.element}, i
   697  }
   698  
   699  // editActionNode records a change to an action pipeline for later commit.
   700  func (e *escaper) editActionNode(n *parse.ActionNode, cmds []string) {
   701  	if _, ok := e.actionNodeEdits[n]; ok {
   702  		panic(fmt.Sprintf("node %s shared between templates", n))
   703  	}
   704  	e.actionNodeEdits[n] = cmds
   705  }
   706  
   707  // editTemplateNode records a change to a {{template}} callee for later commit.
   708  func (e *escaper) editTemplateNode(n *parse.TemplateNode, callee string) {
   709  	if _, ok := e.templateNodeEdits[n]; ok {
   710  		panic(fmt.Sprintf("node %s shared between templates", n))
   711  	}
   712  	e.templateNodeEdits[n] = callee
   713  }
   714  
   715  // editTextNode records a change to a text node for later commit.
   716  func (e *escaper) editTextNode(n *parse.TextNode, text []byte) {
   717  	if _, ok := e.textNodeEdits[n]; ok {
   718  		panic(fmt.Sprintf("node %s shared between templates", n))
   719  	}
   720  	e.textNodeEdits[n] = text
   721  }
   722  
   723  // commit applies changes to actions and template calls needed to contextually
   724  // autoescape content and adds any derived templates to the set.
   725  func (e *escaper) commit() {
   726  	for name := range e.output {
   727  		e.template(name).Funcs(funcMap)
   728  	}
   729  	for _, t := range e.derived {
   730  		if _, err := e.tmpl.text.AddParseTree(t.Name(), t.Tree); err != nil {
   731  			panic("error adding derived template")
   732  		}
   733  	}
   734  	for n, s := range e.actionNodeEdits {
   735  		ensurePipelineContains(n.Pipe, s)
   736  	}
   737  	for n, name := range e.templateNodeEdits {
   738  		n.Name = name
   739  	}
   740  	for n, s := range e.textNodeEdits {
   741  		n.Text = s
   742  	}
   743  }
   744  
   745  // template returns the named template given a mangled template name.
   746  func (e *escaper) template(name string) *template.Template {
   747  	t := e.tmpl.text.Lookup(name)
   748  	if t == nil {
   749  		t = e.derived[name]
   750  	}
   751  	return t
   752  }
   753  
   754  // Forwarding functions so that clients need only import this package
   755  // to reach the general escaping functions of text/template.
   756  
   757  // HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
   758  func HTMLEscape(w io.Writer, b []byte) {
   759  	template.HTMLEscape(w, b)
   760  }
   761  
   762  // HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
   763  func HTMLEscapeString(s string) string {
   764  	return template.HTMLEscapeString(s)
   765  }
   766  
   767  // HTMLEscaper returns the escaped HTML equivalent of the textual
   768  // representation of its arguments.
   769  func HTMLEscaper(args ...interface{}) string {
   770  	return template.HTMLEscaper(args...)
   771  }
   772  
   773  // JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
   774  func JSEscape(w io.Writer, b []byte) {
   775  	template.JSEscape(w, b)
   776  }
   777  
   778  // JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
   779  func JSEscapeString(s string) string {
   780  	return template.JSEscapeString(s)
   781  }
   782  
   783  // JSEscaper returns the escaped JavaScript equivalent of the textual
   784  // representation of its arguments.
   785  func JSEscaper(args ...interface{}) string {
   786  	return template.JSEscaper(args...)
   787  }
   788  
   789  // URLQueryEscaper returns the escaped value of the textual representation of
   790  // its arguments in a form suitable for embedding in a URL query.
   791  func URLQueryEscaper(args ...interface{}) string {
   792  	return template.URLQueryEscaper(args...)
   793  }