Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/xml: normalize \t, \r and \n to space in attributes #69198

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/encoding/xml/marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,12 @@ var marshalTests = []struct {
ExpectXML: `<Data Attr=""><Bytes></Bytes><Custom></Custom></Data>`,
UnmarshalOnly: true,
},
// Check attribute value normalization (issue 20614).
{
Value: &Data{Bytes: []byte{}, Custom: MyBytes{}, Attr: []byte(" a b c d")},
ExpectXML: "<Data Attr='\na\r\nb\tc\rd'><Bytes></Bytes><Custom></Custom></Data>",
UnmarshalOnly: true,
},

// Check that []byte works, including named []byte types.
{
Expand Down
12 changes: 9 additions & 3 deletions src/encoding/xml/xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -1118,11 +1118,17 @@ Input:
return nil
}

// We must rewrite unescaped \r and \r\n into \n.
if b == '\r' {
d.buf.WriteByte('\n')
// We must rewrite unescaped \r and \r\n into \n outside quotes,
// and unescaped \r, \r\n, \n, and \t into space inside quotes.
if b >= ' ' {
d.buf.WriteByte(b)
} else if b1 == '\r' && b == '\n' {
// Skip \r\n--we already wrote \n.
} else if quote >= 0 && (b == '\r' || b == '\n' || b == '\t') {
// Normalize newline, CR, and tab into space
d.buf.WriteByte(' ')
} else if b == '\r' {
d.buf.WriteByte('\n')
} else {
d.buf.WriteByte(b)
}
Expand Down
24 changes: 24 additions & 0 deletions src/encoding/xml/xml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,30 @@ type item struct {
FieldA string
}

func TestIssue20614(t *testing.T) {
data := "<item b='\n\r\t'/>"
dec := NewDecoder(strings.NewReader(data))
var tok1, tok2, tok3 Token
var err error
if tok1, err = dec.RawToken(); err != nil {
t.Fatalf("RawToken() failed: %#v", err)
}
if tok2, err = dec.RawToken(); err != nil {
t.Fatalf("RawToken() failed: %#v", err)
}
if tok3, err = dec.RawToken(); err != io.EOF || tok3 != nil {
t.Fatalf("Missed EOF")
}
s := StartElement{Name{"", "item"}, []Attr{Attr{Name{"","b"}, " "}}}
if !reflect.DeepEqual(tok1.(StartElement), s) {
t.Error("Wrong start element")
}
e := EndElement{Name{"","item"}}
if tok2.(EndElement) != e {
t.Error("Wrong end element")
}
}

func TestIssue569(t *testing.T) {
data := `<item><FieldA>abcd</FieldA></item>`
var i item
Expand Down