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