decoder.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. "strings"
  10. "miniflux.app/v2/internal/reader/encoding"
  11. )
  12. // NewXMLDecoder returns a XML decoder that filters illegal characters.
  13. func NewXMLDecoder(data io.ReadSeeker) *xml.Decoder {
  14. var decoder *xml.Decoder
  15. // This is way fasted than io.ReadAll(data) as the buffer can be allocated in one go instead of dynamically grown.
  16. buffer := &bytes.Buffer{}
  17. io.Copy(buffer, data)
  18. enc := getEncoding(buffer.Bytes())
  19. if enc == "" || strings.EqualFold(enc, "utf-8") {
  20. // filter invalid chars now, since decoder.CharsetReader not called for utf-8 content
  21. filteredBytes := bytes.Map(filterValidXMLChar, buffer.Bytes())
  22. decoder = xml.NewDecoder(bytes.NewReader(filteredBytes))
  23. } else {
  24. // filter invalid chars later within decoder.CharsetReader
  25. data.Seek(0, io.SeekStart)
  26. decoder = xml.NewDecoder(data)
  27. }
  28. decoder.Entity = xml.HTMLEntity
  29. decoder.Strict = false
  30. decoder.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
  31. utf8Reader, err := encoding.CharsetReader(charset, input)
  32. if err != nil {
  33. return nil, err
  34. }
  35. rawData, err := io.ReadAll(utf8Reader)
  36. if err != nil {
  37. return nil, fmt.Errorf("encoding: unable to read data: %w", err)
  38. }
  39. filteredBytes := bytes.Map(filterValidXMLChar, rawData)
  40. return bytes.NewReader(filteredBytes), nil
  41. }
  42. return decoder
  43. }
  44. // This function is copied from encoding/xml package,
  45. // and is used to check if all the characters are legal.
  46. func filterValidXMLChar(r rune) rune {
  47. if r == 0x09 ||
  48. r == 0x0A ||
  49. r == 0x0D ||
  50. r >= 0x20 && r <= 0xD7FF ||
  51. r >= 0xE000 && r <= 0xFFFD ||
  52. r >= 0x10000 && r <= 0x10FFFF {
  53. return r
  54. }
  55. return -1
  56. }
  57. // This function is copied from encoding/xml's procInst and adapted for []bytes instead of string
  58. func getEncoding(b []byte) string {
  59. // TODO: this parsing is somewhat lame and not exact.
  60. // It works for all actual cases, though.
  61. idx := bytes.Index(b, []byte("encoding="))
  62. if idx == -1 {
  63. return ""
  64. }
  65. v := b[idx+len("encoding="):]
  66. if len(v) == 0 {
  67. return ""
  68. }
  69. if v[0] != '\'' && v[0] != '"' {
  70. return ""
  71. }
  72. idx = bytes.IndexRune(v[1:], rune(v[0]))
  73. if idx == -1 {
  74. return ""
  75. }
  76. return string(v[1 : idx+1])
  77. }