Просмотр исходного кода

fix(xml): convert UTF-16 feeds to UTF-8 before decoding

somaz 3 недель назад
Родитель
Сommit
ed3361d37a

+ 23 - 0
internal/reader/parser/parser_test.go

@@ -4,11 +4,34 @@
 package parser // import "miniflux.app/v2/internal/reader/parser"
 
 import (
+	"bytes"
 	"os"
 	"strings"
 	"testing"
+
+	"golang.org/x/text/encoding/unicode"
 )
 
+func TestParseFeedWithUTF16Encoding(t *testing.T) {
+	document := `<?xml version="1.0" encoding="utf-16"?><rss version="2.0"><channel><title>Título</title><item><title>i</title></item></channel></rss>`
+	data, err := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder().Bytes([]byte(document))
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	feed, err := ParseFeed("https://example.org/", bytes.NewReader(data))
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if feed.Title != "Título" {
+		t.Errorf(`Incorrect feed title, got: %q`, feed.Title)
+	}
+	if len(feed.Entries) != 1 {
+		t.Errorf(`Incorrect number of entries, got: %d`, len(feed.Entries))
+	}
+}
+
 func BenchmarkParse(b *testing.B) {
 	var testCases = map[string][]string{
 		"large_atom.xml": {"https://dustri.org/b", ""},

+ 31 - 0
internal/reader/xml/decoder.go

@@ -10,6 +10,7 @@ import (
 	"io"
 	"unicode/utf8"
 
+	"golang.org/x/text/encoding/unicode"
 	"miniflux.app/v2/internal/reader/encoding"
 )
 
@@ -21,6 +22,11 @@ func NewXMLDecoder(data io.ReadSeeker) *xml.Decoder {
 	buffer := &bytes.Buffer{}
 	io.Copy(buffer, data)
 
+	if decoded, ok := decodeUTF16(buffer.Bytes()); ok {
+		buffer = bytes.NewBuffer(decoded)
+		data = bytes.NewReader(decoded)
+	}
+
 	if hasUTF8XMLDeclaration(buffer.Bytes()) {
 		// TODO: detect actual encoding from bytes if not UTF-8 and convert to UTF-8 if needed.
 		// For now we just expect the invalid characters to be stripped out.
@@ -44,6 +50,31 @@ func NewXMLDecoder(data io.ReadSeeker) *xml.Decoder {
 	return decoder
 }
 
+// decodeUTF16 converts a UTF-16 document to UTF-8, since encoding/xml reads the
+// XML declaration as ASCII. Without a BOM, the leading "<" gives the byte order.
+func decodeUTF16(data []byte) ([]byte, bool) {
+	var endianness unicode.Endianness
+	switch {
+	case bytes.HasPrefix(data, []byte{0xFF, 0xFE}), bytes.HasPrefix(data, []byte{'<', 0}):
+		endianness = unicode.LittleEndian
+	case bytes.HasPrefix(data, []byte{0xFE, 0xFF}), bytes.HasPrefix(data, []byte{0, '<'}):
+		endianness = unicode.BigEndian
+	default:
+		return nil, false
+	}
+
+	decoded, err := unicode.UTF16(endianness, unicode.UseBOM).NewDecoder().Bytes(data)
+	if err != nil {
+		return nil, false
+	}
+
+	// Stray bytes before a UTF-8 document would decode to CJK instead of markup.
+	if trimmed := bytes.TrimSpace(decoded); len(trimmed) < 2 || trimmed[0] != '<' || trimmed[1] >= utf8.RuneSelf {
+		return nil, false
+	}
+	return decoded, true
+}
+
 func charsetReaderFilterInvalidUtf8(charset string, input io.Reader) (io.Reader, error) {
 	utf8Reader, err := encoding.CharsetReader(charset, input)
 	if err != nil {

+ 82 - 0
internal/reader/xml/decoder_test.go

@@ -4,12 +4,16 @@
 package xml // import "miniflux.app/v2/internal/reader/xml"
 
 import (
+	"bytes"
 	"encoding/xml"
 	"fmt"
 	"os"
 	"strings"
 	"testing"
 	"unicode/utf8"
+
+	"golang.org/x/text/encoding"
+	"golang.org/x/text/encoding/unicode"
 )
 
 func TestXMLDocumentWithISO88591Encoding(t *testing.T) {
@@ -206,6 +210,84 @@ func TestXMLDocumentWithIncorrectEncodingField(t *testing.T) {
 	}
 }
 
+func TestXMLDocumentWithUTF16Encoding(t *testing.T) {
+	type myXMLDocument struct {
+		XMLName xml.Name `xml:"note"`
+		To      string   `xml:"to"`
+		From    string   `xml:"from"`
+	}
+
+	encodings := map[string]encoding.Encoding{
+		"little endian with BOM":    unicode.UTF16(unicode.LittleEndian, unicode.UseBOM),
+		"big endian with BOM":       unicode.UTF16(unicode.BigEndian, unicode.UseBOM),
+		"little endian without BOM": unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM),
+		"big endian without BOM":    unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM),
+	}
+	documents := map[string]string{
+		"with prolog":    `<?xml version="1.0" encoding="utf-16"?><note><to>Anaïs</to><from>Jürgen 😀</from></note>`,
+		"without prolog": `<note><to>Anaïs</to><from>Jürgen 😀</from></note>`,
+	}
+
+	for encodingName, enc := range encodings {
+		for documentName, document := range documents {
+			t.Run(encodingName+" "+documentName, func(t *testing.T) {
+				data, err := enc.NewEncoder().Bytes([]byte(document))
+				if err != nil {
+					t.Fatal(err)
+				}
+
+				var doc myXMLDocument
+				if err := NewXMLDecoder(bytes.NewReader(data)).Decode(&doc); err != nil {
+					t.Fatal(err)
+				}
+
+				if doc.To != "Anaïs" {
+					t.Errorf(`Incorrect "to" field, got: %q`, doc.To)
+				}
+				if doc.From != "Jürgen 😀" {
+					t.Errorf(`Incorrect "from" field, got: %q`, doc.From)
+				}
+			})
+		}
+	}
+}
+
+func TestXMLDocumentWithStrayBytesBeforeUTF8Document(t *testing.T) {
+	type myXMLDocument struct {
+		XMLName xml.Name `xml:"note"`
+		To      string   `xml:"to"`
+	}
+
+	document := `<note><to>Anaïs</to></note>`
+	prefixes := map[string]string{
+		"little endian BOM": "\xFF\xFE",
+		"big endian BOM":    "\xFE\xFF",
+		"NUL":               "\x00",
+	}
+
+	for name, prefix := range prefixes {
+		t.Run(name, func(t *testing.T) {
+			var doc myXMLDocument
+			if err := NewXMLDecoder(strings.NewReader(prefix + document)).Decode(&doc); err != nil {
+				t.Fatal(err)
+			}
+			if doc.To != "Anaïs" {
+				t.Errorf(`Incorrect "to" field, got: %q`, doc.To)
+			}
+		})
+	}
+
+	t.Run("NUL after the first character", func(t *testing.T) {
+		var doc myXMLDocument
+		if err := NewXMLDecoder(strings.NewReader("<\x00" + document[1:])).Decode(&doc); err != nil {
+			t.Fatal(err)
+		}
+		if doc.To != "Anaïs" {
+			t.Errorf(`Incorrect "to" field, got: %q`, doc.To)
+		}
+	})
+}
+
 func TestFilterValidXMLCharsWithInvalidUTF8Sequence(t *testing.T) {
 	// Create input with invalid UTF-8 sequence
 	input := []byte{0x41, 0xC0, 0xAF, 0x42} // 'A', invalid UTF-8, 'B'