Skip to content

Commit cd9e189

Browse files
committed
log: properly escape character sequences (ethereum#20987)
1 parent 25a7e09 commit cd9e189

File tree

1 file changed

+11
-43
lines changed

1 file changed

+11
-43
lines changed

log/format.go

Lines changed: 11 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,11 @@ type TerminalStringer interface {
7878
// a terminal with color-coded level output and terser human friendly timestamp.
7979
// This format should only be used for interactive programs or while developing.
8080
//
81-
// [LEVEL] [TIME] MESAGE key=value key=value ...
81+
// [LEVEL] [TIME] MESAGE key=value key=value ...
8282
//
8383
// Example:
8484
//
85-
// [DBUG] [May 16 20:58:45] remove route ns=haproxy addr=127.0.0.1:50002
86-
//
85+
// [DBUG] [May 16 20:58:45] remove route ns=haproxy addr=127.0.0.1:50002
8786
func TerminalFormat(usecolor bool) Format {
8887
return FormatFunc(func(r *Record) []byte {
8988
var color = 0
@@ -148,7 +147,6 @@ func TerminalFormat(usecolor bool) Format {
148147
// format for key/value pairs.
149148
//
150149
// For more details see: http://godoc.org/github.com/kr/logfmt
151-
//
152150
func LogfmtFormat() Format {
153151
return FormatFunc(func(r *Record) []byte {
154152
common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg}
@@ -358,49 +356,19 @@ func formatLogfmtValue(value interface{}, term bool) string {
358356
}
359357
}
360358

361-
var stringBufPool = sync.Pool{
362-
New: func() interface{} { return new(bytes.Buffer) },
363-
}
364-
359+
// escapeString checks if the provided string needs escaping/quoting, and
360+
// calls strconv.Quote if needed
365361
func escapeString(s string) string {
366-
needsQuotes := false
367-
needsEscape := false
362+
needsQuoting := false
368363
for _, r := range s {
369-
if r <= ' ' || r == '=' || r == '"' {
370-
needsQuotes = true
371-
}
372-
if r == '\\' || r == '"' || r == '\n' || r == '\r' || r == '\t' {
373-
needsEscape = true
364+
// We quote everything below " (0x34) and above~ (0x7E), plus equal-sign
365+
if r <= '"' || r > '~' || r == '=' {
366+
needsQuoting = true
367+
break
374368
}
375369
}
376-
if !needsEscape && !needsQuotes {
370+
if !needsQuoting {
377371
return s
378372
}
379-
e := stringBufPool.Get().(*bytes.Buffer)
380-
e.WriteByte('"')
381-
for _, r := range s {
382-
switch r {
383-
case '\\', '"':
384-
e.WriteByte('\\')
385-
e.WriteByte(byte(r))
386-
case '\n':
387-
e.WriteString("\\n")
388-
case '\r':
389-
e.WriteString("\\r")
390-
case '\t':
391-
e.WriteString("\\t")
392-
default:
393-
e.WriteRune(r)
394-
}
395-
}
396-
e.WriteByte('"')
397-
var ret string
398-
if needsQuotes {
399-
ret = e.String()
400-
} else {
401-
ret = string(e.Bytes()[1 : e.Len()-1])
402-
}
403-
e.Reset()
404-
stringBufPool.Put(e)
405-
return ret
373+
return strconv.Quote(s)
406374
}

0 commit comments

Comments
 (0)