decoder.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package xml // import "miniflux.app/v2/internal/reader/xml"
  4. import (
  5. "bytes"
  6. "encoding/xml"
  7. "fmt"
  8. "io"
  9. "unicode/utf8"
  10. "golang.org/x/text/encoding/unicode"
  11. "miniflux.app/v2/internal/reader/encoding"
  12. )
  13. // NewXMLDecoder returns a XML decoder that filters illegal characters.
  14. func NewXMLDecoder(data io.ReadSeeker) *xml.Decoder {
  15. var decoder *xml.Decoder
  16. // This is way fasted than io.ReadAll(data) as the buffer can be allocated in one go instead of dynamically grown.
  17. buffer := &bytes.Buffer{}
  18. io.Copy(buffer, data)
  19. if decoded, ok := decodeUTF16(buffer.Bytes()); ok {
  20. buffer = bytes.NewBuffer(decoded)
  21. data = bytes.NewReader(decoded)
  22. }
  23. if hasUTF8XMLDeclaration(buffer.Bytes()) {
  24. // TODO: detect actual encoding from bytes if not UTF-8 and convert to UTF-8 if needed.
  25. // For now we just expect the invalid characters to be stripped out.
  26. // Filter invalid chars now, since decoder.CharsetReader isn't called for utf-8 content
  27. filteredBytes := filterValidXMLChars(buffer.Bytes())
  28. decoder = xml.NewDecoder(bytes.NewReader(filteredBytes))
  29. } else {
  30. data.Seek(0, io.SeekStart)
  31. decoder = xml.NewDecoder(data)
  32. // The XML document will be converted to UTF-8 by encoding.CharsetReader
  33. // Invalid characters will be filtered later via decoder.CharsetReader
  34. decoder.CharsetReader = charsetReaderFilterInvalidUtf8
  35. }
  36. decoder.Entity = xml.HTMLEntity
  37. decoder.Strict = false
  38. return decoder
  39. }
  40. // decodeUTF16 converts a UTF-16 document to UTF-8, since encoding/xml reads the
  41. // XML declaration as ASCII. Without a BOM, the leading "<" gives the byte order.
  42. func decodeUTF16(data []byte) ([]byte, bool) {
  43. var endianness unicode.Endianness
  44. switch {
  45. case bytes.HasPrefix(data, []byte{0xFF, 0xFE}), bytes.HasPrefix(data, []byte{'<', 0}):
  46. endianness = unicode.LittleEndian
  47. case bytes.HasPrefix(data, []byte{0xFE, 0xFF}), bytes.HasPrefix(data, []byte{0, '<'}):
  48. endianness = unicode.BigEndian
  49. default:
  50. return nil, false
  51. }
  52. decoded, err := unicode.UTF16(endianness, unicode.UseBOM).NewDecoder().Bytes(data)
  53. if err != nil {
  54. return nil, false
  55. }
  56. // Stray bytes before a UTF-8 document would decode to CJK instead of markup.
  57. if trimmed := bytes.TrimSpace(decoded); len(trimmed) < 2 || trimmed[0] != '<' || trimmed[1] >= utf8.RuneSelf {
  58. return nil, false
  59. }
  60. return decoded, true
  61. }
  62. func charsetReaderFilterInvalidUtf8(charset string, input io.Reader) (io.Reader, error) {
  63. utf8Reader, err := encoding.CharsetReader(charset, input)
  64. if err != nil {
  65. return nil, err
  66. }
  67. rawData, err := io.ReadAll(utf8Reader)
  68. if err != nil {
  69. return nil, fmt.Errorf("xml: unable to read data: %w", err)
  70. }
  71. filteredBytes := filterValidXMLChars(rawData)
  72. return bytes.NewReader(filteredBytes), nil
  73. }
  74. // filterValidXMLChars filters inplace invalid XML characters.
  75. // This function is inspired from bytes.Map
  76. func filterValidXMLChars(s []byte) []byte {
  77. var i uint // declaring it as an uint removes a bound check in the loop.
  78. var j int
  79. for i = 0; i < uint(len(s)); {
  80. wid := 1
  81. r := rune(s[i])
  82. if r >= utf8.RuneSelf {
  83. r, wid = utf8.DecodeRune(s[i:])
  84. }
  85. if r != utf8.RuneError {
  86. if r = filterValidXMLChar(r); r >= 0 {
  87. utf8.EncodeRune(s[j:], r)
  88. j += wid
  89. }
  90. }
  91. i += uint(wid)
  92. }
  93. return s[:j]
  94. }
  95. // This function is copied from encoding/xml package,
  96. // and is used to check if all the characters are legal.
  97. func filterValidXMLChar(r rune) rune {
  98. if r == 0x09 ||
  99. r == 0x0A ||
  100. r == 0x0D ||
  101. r >= 0x20 && r <= 0xD7FF ||
  102. r >= 0xE000 && r <= 0xFFFD ||
  103. r >= 0x10000 && r <= 0x10FFFF {
  104. return r
  105. }
  106. return -1
  107. }
  108. // This function is copied from encoding/xml's procInst and adapted for []bytes instead of string
  109. func getEncoding(b []byte) []byte {
  110. // This parsing is somewhat lame and not exact.
  111. // It works for all actual cases, though.
  112. idx := bytes.Index(b, []byte("encoding="))
  113. if idx == -1 {
  114. return nil
  115. }
  116. v := b[idx+len("encoding="):]
  117. if len(v) == 0 {
  118. return nil
  119. }
  120. if v[0] != '\'' && v[0] != '"' {
  121. return nil
  122. }
  123. idx = bytes.IndexRune(v[1:], rune(v[0]))
  124. if idx == -1 {
  125. return nil
  126. }
  127. return v[1 : idx+1]
  128. }
  129. func hasUTF8XMLDeclaration(data []byte) bool {
  130. enc := getEncoding(data)
  131. return enc == nil || bytes.EqualFold(enc, []byte("utf-8"))
  132. }