Skip to content

Commit 5a4db10

Browse files
html/template: avoid race when escaping updates template
Fixes #39807 Change-Id: Icf384f800e2541bc753507daa3a9bc7e5d1c3f79 Reviewed-on: https://go-review.googlesource.com/c/go/+/274450 Trust: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Roberto Clapis <[email protected]> Reviewed-by: Russ Cox <[email protected]>
1 parent b0f01e1 commit 5a4db10

File tree

2 files changed

+147
-13
lines changed

2 files changed

+147
-13
lines changed

src/html/template/exec_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"io"
1515
"reflect"
1616
"strings"
17+
"sync"
1718
"testing"
1819
"text/template"
1920
)
@@ -1706,3 +1707,72 @@ func TestIssue31810(t *testing.T) {
17061707
t.Errorf("%s got %q, expected %q", textCall, b.String(), "result")
17071708
}
17081709
}
1710+
1711+
// Issue 39807. There was a race applying escapeTemplate.
1712+
1713+
const raceText = `
1714+
{{- define "jstempl" -}}
1715+
var v = "v";
1716+
{{- end -}}
1717+
<script type="application/javascript">
1718+
{{ template "jstempl" $ }}
1719+
</script>
1720+
`
1721+
1722+
func TestEscapeRace(t *testing.T) {
1723+
tmpl := New("")
1724+
_, err := tmpl.New("templ.html").Parse(raceText)
1725+
if err != nil {
1726+
t.Fatal(err)
1727+
}
1728+
const count = 20
1729+
for i := 0; i < count; i++ {
1730+
_, err := tmpl.New(fmt.Sprintf("x%d.html", i)).Parse(`{{ template "templ.html" .}}`)
1731+
if err != nil {
1732+
t.Fatal(err)
1733+
}
1734+
}
1735+
1736+
var wg sync.WaitGroup
1737+
for i := 0; i < 10; i++ {
1738+
wg.Add(1)
1739+
go func() {
1740+
defer wg.Done()
1741+
for j := 0; j < count; j++ {
1742+
sub := tmpl.Lookup(fmt.Sprintf("x%d.html", j))
1743+
if err := sub.Execute(io.Discard, nil); err != nil {
1744+
t.Error(err)
1745+
}
1746+
}
1747+
}()
1748+
}
1749+
wg.Wait()
1750+
}
1751+
1752+
func TestRecursiveExecute(t *testing.T) {
1753+
tmpl := New("")
1754+
1755+
recur := func() (HTML, error) {
1756+
var sb strings.Builder
1757+
if err := tmpl.ExecuteTemplate(&sb, "subroutine", nil); err != nil {
1758+
t.Fatal(err)
1759+
}
1760+
return HTML(sb.String()), nil
1761+
}
1762+
1763+
m := FuncMap{
1764+
"recur": recur,
1765+
}
1766+
1767+
top, err := tmpl.New("x.html").Funcs(m).Parse(`{{recur}}`)
1768+
if err != nil {
1769+
t.Fatal(err)
1770+
}
1771+
_, err = tmpl.New("subroutine").Parse(`<a href="/x?p={{"'a<b'"}}">`)
1772+
if err != nil {
1773+
t.Fatal(err)
1774+
}
1775+
if err := top.Execute(io.Discard, nil); err != nil {
1776+
t.Fatal(err)
1777+
}
1778+
}

src/html/template/template.go

Lines changed: 77 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"os"
1212
"path"
1313
"path/filepath"
14+
"reflect"
1415
"sync"
1516
"text/template"
1617
"text/template/parse"
@@ -26,7 +27,9 @@ type Template struct {
2627
// template's in sync.
2728
text *template.Template
2829
// The underlying template's parse tree, updated to be HTML-safe.
29-
Tree *parse.Tree
30+
Tree *parse.Tree
31+
// The original functions, before wrapping.
32+
funcMap FuncMap
3033
*nameSpace // common to all associated templates
3134
}
3235

@@ -35,7 +38,7 @@ var escapeOK = fmt.Errorf("template escaped correctly")
3538

3639
// nameSpace is the data structure shared by all templates in an association.
3740
type nameSpace struct {
38-
mu sync.Mutex
41+
mu sync.RWMutex
3942
set map[string]*Template
4043
escaped bool
4144
esc escaper
@@ -45,8 +48,8 @@ type nameSpace struct {
4548
// itself.
4649
func (t *Template) Templates() []*Template {
4750
ns := t.nameSpace
48-
ns.mu.Lock()
49-
defer ns.mu.Unlock()
51+
ns.mu.RLock()
52+
defer ns.mu.RUnlock()
5053
// Return a slice so we don't expose the map.
5154
m := make([]*Template, 0, len(ns.set))
5255
for _, v := range ns.set {
@@ -84,8 +87,8 @@ func (t *Template) checkCanParse() error {
8487
if t == nil {
8588
return nil
8689
}
87-
t.nameSpace.mu.Lock()
88-
defer t.nameSpace.mu.Unlock()
90+
t.nameSpace.mu.RLock()
91+
defer t.nameSpace.mu.RUnlock()
8992
if t.nameSpace.escaped {
9093
return fmt.Errorf("html/template: cannot Parse after Execute")
9194
}
@@ -94,6 +97,16 @@ func (t *Template) checkCanParse() error {
9497

9598
// escape escapes all associated templates.
9699
func (t *Template) escape() error {
100+
t.nameSpace.mu.RLock()
101+
escapeErr := t.escapeErr
102+
t.nameSpace.mu.RUnlock()
103+
if escapeErr != nil {
104+
if escapeErr == escapeOK {
105+
return nil
106+
}
107+
return escapeErr
108+
}
109+
97110
t.nameSpace.mu.Lock()
98111
defer t.nameSpace.mu.Unlock()
99112
t.nameSpace.escaped = true
@@ -121,6 +134,8 @@ func (t *Template) Execute(wr io.Writer, data interface{}) error {
121134
if err := t.escape(); err != nil {
122135
return err
123136
}
137+
t.nameSpace.mu.RLock()
138+
defer t.nameSpace.mu.RUnlock()
124139
return t.text.Execute(wr, data)
125140
}
126141

@@ -136,20 +151,36 @@ func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{})
136151
if err != nil {
137152
return err
138153
}
154+
t.nameSpace.mu.RLock()
155+
defer t.nameSpace.mu.RUnlock()
139156
return tmpl.text.Execute(wr, data)
140157
}
141158

142159
// lookupAndEscapeTemplate guarantees that the template with the given name
143160
// is escaped, or returns an error if it cannot be. It returns the named
144161
// template.
145162
func (t *Template) lookupAndEscapeTemplate(name string) (tmpl *Template, err error) {
146-
t.nameSpace.mu.Lock()
147-
defer t.nameSpace.mu.Unlock()
148-
t.nameSpace.escaped = true
163+
t.nameSpace.mu.RLock()
149164
tmpl = t.set[name]
165+
var escapeErr error
166+
if tmpl != nil {
167+
escapeErr = tmpl.escapeErr
168+
}
169+
t.nameSpace.mu.RUnlock()
170+
150171
if tmpl == nil {
151172
return nil, fmt.Errorf("html/template: %q is undefined", name)
152173
}
174+
if escapeErr != nil {
175+
if escapeErr != escapeOK {
176+
return nil, escapeErr
177+
}
178+
return tmpl, nil
179+
}
180+
181+
t.nameSpace.mu.Lock()
182+
defer t.nameSpace.mu.Unlock()
183+
t.nameSpace.escaped = true
153184
if tmpl.escapeErr != nil && tmpl.escapeErr != escapeOK {
154185
return nil, tmpl.escapeErr
155186
}
@@ -229,6 +260,7 @@ func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error
229260
nil,
230261
text,
231262
text.Tree,
263+
nil,
232264
t.nameSpace,
233265
}
234266
t.set[name] = ret
@@ -259,8 +291,10 @@ func (t *Template) Clone() (*Template, error) {
259291
nil,
260292
textClone,
261293
textClone.Tree,
294+
t.funcMap,
262295
ns,
263296
}
297+
ret.wrapFuncs()
264298
ret.set[ret.Name()] = ret
265299
for _, x := range textClone.Templates() {
266300
name := x.Name()
@@ -269,12 +303,15 @@ func (t *Template) Clone() (*Template, error) {
269303
return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
270304
}
271305
x.Tree = x.Tree.Copy()
272-
ret.set[name] = &Template{
306+
tc := &Template{
273307
nil,
274308
x,
275309
x.Tree,
310+
src.funcMap,
276311
ret.nameSpace,
277312
}
313+
tc.wrapFuncs()
314+
ret.set[name] = tc
278315
}
279316
// Return the template associated with the name of this template.
280317
return ret.set[ret.Name()], nil
@@ -288,6 +325,7 @@ func New(name string) *Template {
288325
nil,
289326
template.New(name),
290327
nil,
328+
nil,
291329
ns,
292330
}
293331
tmpl.set[name] = tmpl
@@ -313,6 +351,7 @@ func (t *Template) new(name string) *Template {
313351
nil,
314352
t.text.New(name),
315353
nil,
354+
nil,
316355
t.nameSpace,
317356
}
318357
if existing, ok := tmpl.set[name]; ok {
@@ -343,10 +382,35 @@ type FuncMap map[string]interface{}
343382
// type. However, it is legal to overwrite elements of the map. The return
344383
// value is the template, so calls can be chained.
345384
func (t *Template) Funcs(funcMap FuncMap) *Template {
346-
t.text.Funcs(template.FuncMap(funcMap))
385+
t.funcMap = funcMap
386+
t.wrapFuncs()
347387
return t
348388
}
349389

390+
// wrapFuncs records the functions with text/template. We wrap them to
391+
// unlock the nameSpace. See TestRecursiveExecute for a test case.
392+
func (t *Template) wrapFuncs() {
393+
if len(t.funcMap) == 0 {
394+
return
395+
}
396+
tfuncs := make(template.FuncMap, len(t.funcMap))
397+
for name, fn := range t.funcMap {
398+
fnv := reflect.ValueOf(fn)
399+
wrapper := func(args []reflect.Value) []reflect.Value {
400+
t.nameSpace.mu.RUnlock()
401+
defer t.nameSpace.mu.RLock()
402+
if fnv.Type().IsVariadic() {
403+
return fnv.CallSlice(args)
404+
} else {
405+
return fnv.Call(args)
406+
}
407+
}
408+
wrapped := reflect.MakeFunc(fnv.Type(), wrapper)
409+
tfuncs[name] = wrapped.Interface()
410+
}
411+
t.text.Funcs(tfuncs)
412+
}
413+
350414
// Delims sets the action delimiters to the specified strings, to be used in
351415
// subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
352416
// definitions will inherit the settings. An empty delimiter stands for the
@@ -360,8 +424,8 @@ func (t *Template) Delims(left, right string) *Template {
360424
// Lookup returns the template with the given name that is associated with t,
361425
// or nil if there is no such template.
362426
func (t *Template) Lookup(name string) *Template {
363-
t.nameSpace.mu.Lock()
364-
defer t.nameSpace.mu.Unlock()
427+
t.nameSpace.mu.RLock()
428+
defer t.nameSpace.mu.RUnlock()
365429
return t.set[name]
366430
}
367431

0 commit comments

Comments
 (0)