lobzique 0.1.0-x86_64-linux

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +5 -0
  3. data/LICENSE-NOKOGIRI.md +15 -0
  4. data/LICENSE.txt +21 -0
  5. data/README.md +144 -0
  6. data/ext/lobzique/clippy.toml +15 -0
  7. data/lib/lobzique/3.3/lobzique.so +0 -0
  8. data/lib/lobzique/3.4/lobzique.so +0 -0
  9. data/lib/lobzique/4.0/lobzique.so +0 -0
  10. data/lib/lobzique/action_text.rb +29 -0
  11. data/lib/lobzique/class_resolver.rb +33 -0
  12. data/lib/lobzique/css/selector_cache.rb +36 -0
  13. data/lib/lobzique/css/syntax_error.rb +12 -0
  14. data/lib/lobzique/css/xpath_visitor.rb +60 -0
  15. data/lib/lobzique/css.rb +57 -0
  16. data/lib/lobzique/extension.rb +31 -0
  17. data/lib/lobzique/html.rb +14 -0
  18. data/lib/lobzique/html4/document.rb +235 -0
  19. data/lib/lobzique/html4/document_fragment.rb +75 -0
  20. data/lib/lobzique/html4/encoding_reader.rb +374 -0
  21. data/lib/lobzique/html4.rb +35 -0
  22. data/lib/lobzique/html5/document.rb +106 -0
  23. data/lib/lobzique/html5/document_fragment.rb +113 -0
  24. data/lib/lobzique/html5/node.rb +66 -0
  25. data/lib/lobzique/html5.rb +92 -0
  26. data/lib/lobzique/html5ever.rb +14 -0
  27. data/lib/lobzique/rails_dom_testing.rb +95 -0
  28. data/lib/lobzique/sanitizer/concerns.rb +110 -0
  29. data/lib/lobzique/sanitizer/document.rb +14 -0
  30. data/lib/lobzique/sanitizer/document_fragment.rb +12 -0
  31. data/lib/lobzique/sanitizer/escape_raw_text_in_select.rb +31 -0
  32. data/lib/lobzique/sanitizer/scrubbers.rb +46 -0
  33. data/lib/lobzique/sanitizer.rb +96 -0
  34. data/lib/lobzique/syntax_error.rb +8 -0
  35. data/lib/lobzique/version.rb +6 -0
  36. data/lib/lobzique/xml/attr.rb +23 -0
  37. data/lib/lobzique/xml/cdata.rb +13 -0
  38. data/lib/lobzique/xml/character_data.rb +11 -0
  39. data/lib/lobzique/xml/document.rb +149 -0
  40. data/lib/lobzique/xml/document_fragment.rb +109 -0
  41. data/lib/lobzique/xml/dtd.rb +28 -0
  42. data/lib/lobzique/xml/namespace.rb +19 -0
  43. data/lib/lobzique/xml/node/save_options.rb +52 -0
  44. data/lib/lobzique/xml/node.rb +629 -0
  45. data/lib/lobzique/xml/node_set.rb +329 -0
  46. data/lib/lobzique/xml/parse_options.rb +89 -0
  47. data/lib/lobzique/xml/pp/character_data.rb +22 -0
  48. data/lib/lobzique/xml/pp/node.rb +73 -0
  49. data/lib/lobzique/xml/pp.rb +6 -0
  50. data/lib/lobzique/xml/searchable.rb +123 -0
  51. data/lib/lobzique/xml/syntax_error.rb +77 -0
  52. data/lib/lobzique/xml/text.rb +14 -0
  53. data/lib/lobzique/xml/xpath/syntax_error.rb +20 -0
  54. data/lib/lobzique/xml/xpath.rb +16 -0
  55. data/lib/lobzique/xml/xpath_context.rb +27 -0
  56. data/lib/lobzique/xml.rb +22 -0
  57. data/lib/lobzique.rb +15 -0
  58. metadata +106 -0
@@ -0,0 +1,235 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/html4/document.rb (MIT, see
4
+ # LICENSE-NOKOGIRI.md). lobzique: the HTML4 names parse with the HTML5 parser,
5
+ # after the input is decoded as libxml2 decodes it (plan.md decision 3).
6
+
7
+ require "pathname"
8
+
9
+ module Lobzique
10
+ module HTML4
11
+ class Document < XML::Document
12
+ # lobzique: the first read of libxml2 from an IO. EncodingReader looks
13
+ # for an encoding in this chunk.
14
+ IO_CHUNK = 4000
15
+ private_constant :IO_CHUNK
16
+
17
+ ###
18
+ # Get the meta tag encoding for this document. If there is no meta tag,
19
+ # then nil is returned.
20
+ def meta_encoding
21
+ if (meta = at_xpath("//meta[@charset]"))
22
+ meta[:charset]
23
+ elsif (meta = meta_content_type)
24
+ meta["content"][/charset\s*=\s*([\w-]+)/i, 1]
25
+ end
26
+ end
27
+
28
+ ###
29
+ # Set the meta tag encoding for this document.
30
+ #
31
+ # If an meta encoding tag is already present, its content is
32
+ # replaced with the given text.
33
+ #
34
+ # Otherwise, this method tries to create one at an appropriate
35
+ # place supplying head and/or html elements as necessary, which
36
+ # is inside a head element if any, and before any text node or
37
+ # content element (typically <body>) if any.
38
+ #
39
+ # The result when trying to set an encoding that is different
40
+ # from the document encoding is undefined.
41
+ def meta_encoding=(encoding)
42
+ if (meta = meta_content_type)
43
+ meta["content"] = format("text/html; charset=%s", encoding)
44
+ encoding
45
+ elsif (meta = at_xpath("//meta[@charset]"))
46
+ meta["charset"] = encoding
47
+ else
48
+ meta = XML::Node.new("meta", self)
49
+ if (dtd = internal_subset) && dtd.html5_dtd?
50
+ meta["charset"] = encoding
51
+ else
52
+ meta["http-equiv"] = "Content-Type"
53
+ meta["content"] = format("text/html; charset=%s", encoding)
54
+ end
55
+
56
+ if (head = at_xpath("//head"))
57
+ head.prepend_child(meta)
58
+ else
59
+ set_metadata_element(meta)
60
+ end
61
+ encoding
62
+ end
63
+ end
64
+
65
+ def meta_content_type
66
+ xpath("//meta[@http-equiv and boolean(@content)]").find do |node|
67
+ node["http-equiv"] =~ /\AContent-Type\z/i
68
+ end
69
+ end
70
+ private :meta_content_type
71
+
72
+ ###
73
+ # Get the title string of this document. Return nil if there is
74
+ # no title tag.
75
+ def title
76
+ (title = at_xpath("//title")) && title.inner_text
77
+ end
78
+
79
+ ###
80
+ # Set the title string of this document.
81
+ #
82
+ # If a title element is already present, its content is replaced
83
+ # with the given text.
84
+ #
85
+ # Otherwise, this method tries to create one at an appropriate
86
+ # place supplying head and/or html elements as necessary, which
87
+ # is inside a head element if any, right after a meta
88
+ # encoding/charset tag if any, and before any text node or
89
+ # content element (typically <body>) if any.
90
+ def title=(text)
91
+ tnode = XML::Text.new(text, self)
92
+ if (title = at_xpath("//title"))
93
+ title.children = tnode
94
+ return text # rubocop:disable Lint/ReturnInVoidContext
95
+ end
96
+
97
+ title = XML::Node.new("title", self) << tnode
98
+ if (head = at_xpath("//head"))
99
+ head << title
100
+ elsif (meta = at_xpath("//meta[@charset]") || meta_content_type)
101
+ # better put after charset declaration
102
+ meta.add_next_sibling(title)
103
+ else
104
+ set_metadata_element(title)
105
+ end
106
+ end
107
+
108
+ def set_metadata_element(element) # rubocop:disable Naming/AccessorMethodName
109
+ if (head = at_xpath("//head"))
110
+ head << element
111
+ elsif (html = at_xpath("//html"))
112
+ head = html.prepend_child(XML::Node.new("head", self))
113
+ head.prepend_child(element)
114
+ elsif (first = children.find do |node|
115
+ case node
116
+ when XML::Element, XML::Text
117
+ true
118
+ end
119
+ end)
120
+ # We reach here only if the underlying document model
121
+ # allows <html>/<head> elements to be omitted and does not
122
+ # automatically supply them.
123
+ first.add_previous_sibling(element)
124
+ else
125
+ html = add_child(XML::Node.new("html", self))
126
+ head = html.add_child(XML::Node.new("head", self))
127
+ head.prepend_child(element)
128
+ end
129
+ end
130
+ private :set_metadata_element
131
+
132
+ ####
133
+ # Serialize Node using +options+. Save options can also be set using a block.
134
+ def serialize(options = {})
135
+ options[:save_with] ||= XML::Node::SaveOptions::DEFAULT_HTML
136
+ super
137
+ end
138
+
139
+ ####
140
+ # Create a Nokogiri::XML::DocumentFragment from +tags+
141
+ def fragment(tags = nil)
142
+ # lobzique: no context. Nokogiri passes the root, and the HTML5 parser
143
+ # in the context of <html> would put the input in a <body>
144
+ # of the fragment's own (plan.md decision 3).
145
+ DocumentFragment.new(self, tags)
146
+ end
147
+
148
+ # lobzique: CSS::XPathVisitor::DoctypeConfig::HTML4 in Nokogiri
149
+ def xpath_doctype
150
+ :html4
151
+ end
152
+
153
+ class << self
154
+ # Parse \HTML4 input from a String or IO object, and return a new HTML4::Document.
155
+ def parse(
156
+ input,
157
+ url_ = nil, encoding_ = nil, options_ = XML::ParseOptions::DEFAULT_HTML,
158
+ url: url_, encoding: encoding_, options: options_
159
+ )
160
+ options = XML::ParseOptions.new(options) if Integer === options
161
+ yield options if block_given?
162
+
163
+ url ||= input.respond_to?(:path) ? input.path : nil
164
+
165
+ if input.respond_to?(:encoding)
166
+ unless input.encoding == Encoding::ASCII_8BIT
167
+ encoding ||= input.encoding.name
168
+ end
169
+ end
170
+
171
+ if input.respond_to?(:read)
172
+ if input.is_a?(Pathname)
173
+ # resolve the Pathname to the file and open it as an IO object, see #2110
174
+ input = input.expand_path.open
175
+ url ||= input.path
176
+ end
177
+
178
+ unless encoding
179
+ input = EncodingReader.new(input)
180
+ begin
181
+ return read_io(input, url, encoding, options.to_i)
182
+ rescue EncodingReader::EncodingFound => e
183
+ encoding = e.found_encoding
184
+ end
185
+ end
186
+ return read_io(input, url, encoding, options.to_i)
187
+ end
188
+
189
+ # read_memory pukes on empty docs
190
+ if input.nil? || input.empty?
191
+ return encoding ? new.tap { |i| i.encoding = encoding } : new
192
+ end
193
+
194
+ encoding ||= EncodingReader.detect_encoding(input)
195
+
196
+ read_memory(input, url, encoding, options.to_i)
197
+ end
198
+
199
+ # lobzique: native in Nokogiri (htmlReadMemory of libxml2). The options
200
+ # are ignored: the HTML5 parser always recovers and keeps its own
201
+ # errors, at most 100 as for Node#parse.
202
+ def read_memory(string, url, encoding, options)
203
+ html, encoding, errors = EncodingReader.decode(string, encoding)
204
+ parse_decoded(html, url, encoding, errors)
205
+ end
206
+
207
+ # lobzique: native in Nokogiri (htmlReadIO of libxml2). It reads the IO
208
+ # as libxml2 asks for it, so EncodingReader sees the same first chunk.
209
+ def read_io(io, url, encoding, options)
210
+ input = +""
211
+ while (chunk = io.read(IO_CHUNK))
212
+ input << chunk.b
213
+ end
214
+ html, encoding, errors = EncodingReader.decode(input, encoding, chunk: IO_CHUNK)
215
+ parse_decoded(html, url, encoding, errors)
216
+ end
217
+
218
+ private
219
+
220
+ def parse_decoded(html, url, encoding, errors)
221
+ doc = Html5ever.parse(
222
+ html, url, self,
223
+ max_attributes: Html5ever::DEFAULT_MAX_ATTRIBUTES,
224
+ max_errors: 100,
225
+ max_tree_depth: Html5ever::DEFAULT_MAX_TREE_DEPTH,
226
+ keep_bom: true # decoding took one off, as libxml2's does
227
+ )
228
+ doc.encoding = encoding if encoding
229
+ doc.errors = errors + doc.errors
230
+ doc
231
+ end
232
+ end
233
+ end
234
+ end
235
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/html4/document_fragment.rb (MIT, see LICENSE-NOKOGIRI.md).
4
+
5
+ module Lobzique
6
+ module HTML4
7
+ class DocumentFragment < XML::DocumentFragment
8
+ # Parse a fragment in a new HTML4::Document whose encoding is the encoding
9
+ # of the input, or UTF-8 for binary input.
10
+ def self.parse(
11
+ input,
12
+ encoding_ = nil, options_ = XML::ParseOptions::DEFAULT_HTML,
13
+ encoding: encoding_, options: options_,
14
+ &block
15
+ )
16
+ doc = HTML4::Document.new
17
+
18
+ if input.respond_to?(:read)
19
+ input.set_encoding(encoding) if encoding && input.respond_to?(:set_encoding)
20
+ input = input.read
21
+ end
22
+
23
+ encoding ||= if input.respond_to?(:encoding)
24
+ encoding = input.encoding
25
+ if encoding == ::Encoding::ASCII_8BIT
26
+ "UTF-8"
27
+ else
28
+ encoding.name
29
+ end
30
+ else
31
+ "UTF-8"
32
+ end
33
+
34
+ doc.encoding = encoding
35
+
36
+ new(doc, input, options: options, &block)
37
+ end
38
+
39
+ def initialize(
40
+ document, input = nil,
41
+ context_ = nil, options_ = XML::ParseOptions::DEFAULT_HTML,
42
+ context: context_, options: options_
43
+ ) # rubocop:disable Lint/MissingSuper
44
+ return self unless input # rubocop:disable Lint/ReturnInVoidContext
45
+
46
+ options = XML::ParseOptions.new(options) if Integer === options
47
+ @parse_options = options
48
+ yield options if block_given?
49
+
50
+ # lobzique: the HTML5 fragment parser, in <body> or in the given context
51
+ # (plan.md decision 3). Nokogiri parses the input in a document
52
+ # of its own, or as the content of a <div> in the context. The input
53
+ # is decoded as the parse of that document would decode it, after
54
+ # the markup, so a byte order mark is a character.
55
+ input = input.to_str
56
+ encoding = document.encoding
57
+ encoding ||= input.encoding.name unless input.encoding == Encoding::ASCII_8BIT
58
+ encoding ||= EncodingReader.detect_encoding(input)
59
+ html, _, errors = EncodingReader.decode(input, encoding, at_start: false)
60
+
61
+ Html5ever.fragment(
62
+ self, html, context,
63
+ max_attributes: Html5ever::DEFAULT_MAX_ATTRIBUTES,
64
+ max_errors: 100,
65
+ max_tree_depth: Html5ever::DEFAULT_MAX_TREE_DEPTH,
66
+ keep_bom: true
67
+ )
68
+ # Html5ever.fragment keeps errors in @errors, as HTML5 fragments do.
69
+ parse_errors = instance_variable_defined?(:@errors) ? remove_instance_variable(:@errors) : []
70
+ self.errors = errors + parse_errors
71
+ children
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,374 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adapted from Nokogiri 1.19.7, lib/nokogiri/html4/encoding_reader.rb (MIT, see
4
+ # LICENSE-NOKOGIRI.md). lobzique: adds EncodingReader.decode. It decodes input
5
+ # as libxml2 2.13 does before the HTML5 parser reads it (plan.md decision 3).
6
+
7
+ module Lobzique
8
+ module HTML4
9
+ # Libxml2's parser has poor support for encoding detection. First, it does not recognize the
10
+ # HTML5 style meta charset declaration. Secondly, even if it successfully detects an encoding
11
+ # hint, it does not re-decode or re-parse the preceding part which may be garbled.
12
+ #
13
+ # EncodingReader aims to perform advanced encoding detection beyond what Libxml2 does, and to
14
+ # emulate rewinding of a stream and make Libxml2 redo parsing from the start when an encoding
15
+ # hint is found.
16
+
17
+ # :nodoc: all
18
+ class EncodingReader
19
+ class EncodingFound < StandardError
20
+ attr_reader :found_encoding
21
+
22
+ def initialize(encoding)
23
+ @found_encoding = encoding
24
+ super(format("encoding found: %s", encoding))
25
+ end
26
+ end
27
+
28
+ # lobzique: SAXHandler and JumpSAXHandler are left out with SAX.
29
+ # meta_charset reads what SAXHandler#start_element records.
30
+
31
+ def self.detect_encoding(chunk)
32
+ # lobzique: Nokogiri reads the declaration with Nokogiri.XML,
33
+ # which is out of scope (plan.md decision 4).
34
+ (m = chunk.match(/\A(<\?xml[ \t\r\n][^>]*>)/)) &&
35
+ (return m[1].match(/[ \t\r\n]encoding[ \t\r\n]*=[ \t\r\n]*(?:"([^"]*)"|'([^']*)')/)&.captures&.compact&.first)
36
+
37
+ meta_charset(chunk)
38
+ end
39
+
40
+ # lobzique: Nokogiri pushes the chunk through the HTML4 SAX parser
41
+ # of libxml2 and keeps the charset of the last <meta> that has one.
42
+ # This code parses it with the HTML5 parser, read as ISO-8859-1
43
+ # so that any bytes work, and walks the <meta> elements in document order.
44
+ def self.meta_charset(chunk)
45
+ return unless chunk.b.match?(/<meta/i)
46
+
47
+ metas(chunk).filter_map do |meta|
48
+ content = meta["content"] if meta["http-equiv"]&.match?(/\AContent-Type\z/i)
49
+ content&.[](/;\s*charset\s*=\s*([\w-]+)/, 1) || meta["charset"]
50
+ end.last
51
+ end
52
+
53
+ # The <meta> elements of bytes in any encoding, read as ISO-8859-1.
54
+ def self.metas(bytes)
55
+ html = bytes.b.force_encoding(Encoding::ISO_8859_1).encode(Encoding::UTF_8)
56
+ doc = Html5ever.parse(
57
+ html, nil, Document,
58
+ max_attributes: Html5ever::DEFAULT_MAX_ATTRIBUTES,
59
+ max_errors: 0,
60
+ max_tree_depth: Html5ever::DEFAULT_MAX_TREE_DEPTH
61
+ )
62
+ doc.xpath("//meta")
63
+ end
64
+ private_class_method :meta_charset, :metas
65
+
66
+ def initialize(io)
67
+ @io = io
68
+ @firstchunk = nil
69
+ @encoding_found = nil
70
+ end
71
+
72
+ # This method is used by the C extension so that
73
+ # Nokogiri::HTML4::Document#read_io() does not leak memory when
74
+ # EncodingFound is raised.
75
+ attr_reader :encoding_found
76
+
77
+ def read(len)
78
+ # No support for a call without len.
79
+
80
+ unless @firstchunk
81
+ (@firstchunk = @io.read(len)) || return
82
+
83
+ # This implementation expects that the first call from
84
+ # htmlReadIO() is made with a length long enough (~1KB) to
85
+ # achieve advanced encoding detection.
86
+ if (encoding = EncodingReader.detect_encoding(@firstchunk))
87
+ # The first chunk is stored for the next read in retry.
88
+ raise @encoding_found = EncodingFound.new(encoding)
89
+ end
90
+ end
91
+ @encoding_found = nil
92
+
93
+ ret = @firstchunk.slice!(0, len)
94
+ if (len -= ret.length) > 0
95
+ (rest = @io.read(len)) && ret << rest
96
+ end
97
+ if ret.empty?
98
+ nil
99
+ else
100
+ ret
101
+ end
102
+ end
103
+
104
+ # lobzique: from here on, lobzique's own.
105
+
106
+ # What happens to bytes that are invalid in the encoding of the input:
107
+ # :replacement (U+FFFD) or :latin1 (each byte read as ISO-8859-1). Open,
108
+ # see docs/html4-invalid-bytes.md.
109
+ INVALID_BYTES = :replacement
110
+
111
+ # The built-in decoders of libxml2. They give document.encoding their own
112
+ # names. The names of iconv stay as given.
113
+ BUILT_IN = {
114
+ "UTF-16LE" => Encoding::UTF_16LE,
115
+ "UTF-16BE" => Encoding::UTF_16BE,
116
+ "UTF-16" => Encoding::UTF_16LE,
117
+ "ISO-8859-1" => Encoding::ISO_8859_1,
118
+ "ASCII" => Encoding::US_ASCII,
119
+ "US-ASCII" => Encoding::US_ASCII
120
+ }.freeze
121
+
122
+ # The canonical names of xmlParseCharEncoding. This is the fallback
123
+ # for a name that neither a built-in decoder nor iconv takes.
124
+ CANONICAL = {
125
+ "ISO-LATIN-1" => "ISO-8859-1", "ISO LATIN 1" => "ISO-8859-1",
126
+ "ISO-LATIN-2" => "ISO-8859-2", "ISO LATIN 2" => "ISO-8859-2",
127
+ "ISO-10646-UCS-2" => "UCS-2", "UCS2" => "UCS-2",
128
+ "ISO-10646-UCS-4" => "UCS-4", "UCS4" => "UCS-4"
129
+ }.freeze
130
+
131
+ # Names that iconv knows and Ruby does not, in their usual spellings.
132
+ ICONV = {
133
+ /\AISO[_-]?8859[_-](\d+)(?::\d+)?\z/i => ->(m) { "ISO-8859-#{m[1]}" },
134
+ /\ALATIN-?([1-9]|10)\z/i => ->(m) { "ISO-8859-#{%w[1 2 3 4 9 10 13 14 15 16][m[1].to_i - 1]}" },
135
+ /\AUTF-?(16|32)(LE|BE)?\z/i => ->(m) { "UTF-#{m[1]}#{m[2]&.upcase || "BE"}" },
136
+ /\AUCS-2\z/i => ->(_) { "UTF-16BE" },
137
+ /\AUCS-4\z/i => ->(_) { "UTF-32BE" },
138
+ /\A(?:MAC|MACINTOSH|MACROMAN)\z/i => ->(_) { "macRoman" },
139
+ /\A(?:SHIFT-JIS|MS_KANJI|CSSHIFTJIS)\z/i => ->(_) { "Shift_JIS" },
140
+ /\AWINDOWS-?(\d+)\z/i => ->(m) { "Windows-#{m[1]}" },
141
+ # The iconv of libiconv is the bare KS X 1001 set. Pages that declare
142
+ # it are EUC-KR or its superset, as browsers read them.
143
+ /\A(?:KS_C_5601-198[79]|KSC_5601|CSKSC56011987)\z/i => ->(_) { "CP949" }
144
+ }.freeze
145
+
146
+ BOMS = {
147
+ "\xEF\xBB\xBF".b => [Encoding::UTF_8, 3],
148
+ "\xFE\xFF".b => [Encoding::UTF_16BE, 2],
149
+ "\xFF\xFE".b => [Encoding::UTF_16LE, 2],
150
+ "\x3C\x00\x3F\x00".b => [Encoding::UTF_16LE, 0],
151
+ "\x00\x3C\x00\x3F".b => [Encoding::UTF_16BE, 0]
152
+ }.freeze
153
+
154
+ # Names that Encoding.find resolves to whatever the process is set up
155
+ # with.
156
+ RUBY_ONLY = %w[locale external internal filesystem].freeze
157
+
158
+ private_constant :INVALID_BYTES, :BUILT_IN, :CANONICAL, :ICONV, :BOMS, :RUBY_ONLY
159
+
160
+ class << self
161
+ # Input bytes as the HTML parser of libxml2 decodes them with +encoding+
162
+ # (a name, or nil): [UTF-8 string, document.encoding, errors]. Input
163
+ # read from an IO in +chunk+-sized reads is only partly buffered
164
+ # when libxml2 guesses. Input that is not +at_start+ of what libxml2
165
+ # parses has no byte order mark.
166
+ def decode(input, encoding, chunk: nil, at_start: true)
167
+ bytes = input.to_str.b
168
+ errors = []
169
+ if encoding
170
+ ruby_encoding, name = open_decoder(encoding)
171
+ return decode_with(bytes, ruby_encoding, name, errors, at_start) if ruby_encoding
172
+
173
+ errors << syntax_error("Unsupported encoding: #{encoding}", domain: 1, code: 32, level: 1, str1: encoding)
174
+ end
175
+ guess(bytes, errors, chunk, at_start)
176
+ end
177
+
178
+ private
179
+
180
+ # No encoding: a byte order mark; UTF-8 if the input starts with an XML
181
+ # declaration; a <meta> that the parser meets before any non-ASCII byte;
182
+ # else, at the first non-ASCII byte, an http-equiv charset anywhere
183
+ # after it (htmlFindEncoding), or ISO-8859-1. ASCII input has no
184
+ # encoding.
185
+ def guess(bytes, errors, chunk, at_start)
186
+ bom = BOMS.keys.find { |mark| bytes.start_with?(mark) } if at_start && bytes.bytesize >= 4
187
+ if bom
188
+ ruby_encoding, size = BOMS[bom]
189
+ return [transcode(bytes.byteslice(size..).force_encoding(ruby_encoding), bytes, errors), nil, errors]
190
+ end
191
+
192
+ # htmlParseDocument: "wrong but matches long-standing behavior"
193
+ return decode_with(bytes, Encoding::UTF_8, "UTF-8", errors, at_start) if at_start && bytes.start_with?("<?xm")
194
+
195
+ first = bytes.index(/[\x80-\xFF]/n)
196
+ declared = declared_while_parsing(bytes, first, errors, at_start)
197
+ return declared if declared
198
+ return [bytes.force_encoding(Encoding::UTF_8), nil, errors] unless first
199
+
200
+ declared = find_encoding(bytes, first, chunk)
201
+ return decode_with(bytes, Encoding::ISO_8859_1, "ISO-8859-1", errors, at_start) unless declared
202
+
203
+ ruby_encoding, name = open_decoder(declared)
204
+ return decode_with(bytes, ruby_encoding, name, errors, at_start) if ruby_encoding
205
+
206
+ line, column = position(bytes, first)
207
+ errors << syntax_error("Unsupported encoding: #{declared}", domain: 1, code: 32, level: 1, str1: declared, line:, column:)
208
+ # libxml2 has stopped guessing, so the input is UTF-8.
209
+ decode_with(bytes, Encoding::UTF_8, "UTF-8", errors, at_start)
210
+ end
211
+
212
+ # htmlCheckMeta, which EncodingReader misses when its regexp does
213
+ # not match or the <meta> is after the first chunk of an IO. The first
214
+ # supported declaration before the first non-ASCII byte decodes
215
+ # the input. document.encoding is the last one declared, as written.
216
+ def declared_while_parsing(bytes, first, errors, at_start)
217
+ prefix = first ? bytes.byteslice(0, first) : bytes
218
+ return unless prefix.match?(/<meta/ni)
219
+
220
+ declared = declarations(prefix)
221
+ switch = nil
222
+ declared.each do |name|
223
+ break if (switch = open_decoder(name))
224
+
225
+ errors << syntax_error("Unsupported encoding: #{name}", domain: 1, code: 32, level: 3, str1: name)
226
+ end
227
+ return unless switch
228
+
229
+ declared = declarations(bytes) if first
230
+ decode_with(bytes, switch.first, declared.last, errors, at_start)
231
+ end
232
+
233
+ # What htmlCheckMeta declares, meta by meta: the value of a charset
234
+ # attribute, then the charset of an http-equiv Content-Type.
235
+ def declarations(bytes)
236
+ metas(bytes).flat_map do |meta|
237
+ http_equiv = content = nil
238
+ charsets = meta.attribute_nodes.filter_map do |attribute|
239
+ name, value = attribute.name, attribute.value
240
+ if name.casecmp?("http-equiv") && value.casecmp?("Content-Type")
241
+ http_equiv = true
242
+ nil
243
+ elsif name.casecmp?("content")
244
+ content = value
245
+ nil
246
+ elsif name.casecmp?("charset")
247
+ value
248
+ end
249
+ end
250
+ charset = http_equiv && content && charset_in_content(content)
251
+ # Back to the bytes of the input. A character reference loses
252
+ # its bytes.
253
+ (charset ? charsets << charset : charsets).map { _1.encode(Encoding::ISO_8859_1, undef: :replace).b }
254
+ end
255
+ end
256
+
257
+ # htmlCheckEncoding: everything after the "=" that follows "charset",
258
+ # or after the first "=" if a blank follows "charset".
259
+ def charset_in_content(content)
260
+ at = content.index(/charset/i) or return
261
+ at += 7
262
+ at = content.index("=") if content[at]&.match?(/[ \t\r\n]/)
263
+ content[(at + 1)..] if at && content[at] == "="
264
+ end
265
+
266
+ # htmlFindEncoding: a case-insensitive search of the raw bytes up
267
+ # to the first NUL, comments and text included, as far as they
268
+ # are buffered: htmlCurrentChar keeps INPUT_CHUNK (250) bytes ahead.
269
+ def find_encoding(bytes, from, chunk)
270
+ rest = chunk ? bytes.byteslice(from...((from + 250).fdiv(chunk).ceil * chunk)) : bytes.byteslice(from..)
271
+ rest = rest.byteslice(0, rest.index("\0")) if rest.include?("\0")
272
+ (at = rest.index(/HTTP-EQUIV/ni)) &&
273
+ (at = rest.index(/CONTENT/ni, at)) &&
274
+ (at = rest.index(/CHARSET=/ni, at)) &&
275
+ rest.byteslice((at + 8)..)[/\A[A-Za-z0-9\-_:\/]+/n]
276
+ end
277
+
278
+ def decode_with(bytes, ruby_encoding, name, errors, at_start)
279
+ string = transcode(bytes.dup.force_encoding(ruby_encoding), bytes, errors)
280
+ # xmlDetectEncoding skips a UTF-8 BOM even when the encoding is set.
281
+ string = string.byteslice(3..) if at_start && string.start_with?("\uFEFF")
282
+ [string, name, errors]
283
+ end
284
+
285
+ def transcode(string, bytes, errors)
286
+ invalid_bytes(bytes, string, errors) unless string.valid_encoding?
287
+ if string.encoding != Encoding::UTF_8
288
+ # invalid: always, as the string of a stateful encoding
289
+ # (ISO-2022-JP) is valid_encoding? whatever its bytes.
290
+ string.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
291
+ elsif INVALID_BYTES == :latin1
292
+ string.scrub { |b| b.unpack("C*").pack("U*") }
293
+ else
294
+ string.scrub
295
+ end
296
+ end
297
+
298
+ def invalid_bytes(bytes, string, errors)
299
+ offset = string.each_char.take_while(&:valid_encoding?).sum(&:bytesize)
300
+ line, column = position(bytes, offset)
301
+ errors << syntax_error("Invalid bytes in character encoding", domain: 8, code: 81, level: 3, line:, column:)
302
+ end
303
+
304
+ def position(bytes, offset)
305
+ before = bytes.byteslice(0, offset)
306
+ [before.count("\n") + 1, offset - (before.rindex("\n") || -1)]
307
+ end
308
+
309
+ # xmlOpenCharEncodingHandler: [Ruby encoding, document.encoding], or nil
310
+ # for a name that libxml2 does not support.
311
+ def open_decoder(name)
312
+ return [Encoding::UTF_8, "UTF-8"] if name.casecmp?("UTF-8") || name.casecmp?("UTF8")
313
+
314
+ if (ruby_encoding = BUILT_IN[built_in = name.upcase])
315
+ return [ruby_encoding, built_in]
316
+ end
317
+ if (ruby_encoding = iconv(name))
318
+ return [ruby_encoding, name]
319
+ end
320
+
321
+ canonical = CANONICAL[name.upcase]
322
+ return unless canonical
323
+
324
+ open_decoder(canonical)
325
+ end
326
+
327
+ # A decoder that iconv would open, if Ruby can transcode
328
+ # from it. The other names of Ruby for UTF-8 are not names of iconv.
329
+ def iconv(name)
330
+ name = glibc_name(name)
331
+ return Encoding::UTF_8 if name.casecmp?("UTF-8") || name.casecmp?("UTF8")
332
+ return if name.empty? || RUBY_ONLY.any? { _1.casecmp?(name) }
333
+
334
+ candidates = ICONV.filter_map { |pattern, rename| (m = pattern.match(name)) && rename.call(m) } << name
335
+ candidates.each do |candidate|
336
+ encoding = Encoding.find(candidate)
337
+ next if encoding == Encoding::BINARY
338
+
339
+ Encoding::Converter.new(encoding, Encoding::UTF_8)
340
+ return encoding
341
+ rescue ArgumentError, Encoding::ConverterNotFoundError
342
+ next
343
+ end
344
+ nil
345
+ end
346
+
347
+ # The name that iconv_open of glibc looks up (gconv_parse_code and strip
348
+ # in gconv_charset.c): without suffixes after a second "/", trailing
349
+ # blanks, "," and "/", and any character except letters, digits
350
+ # and "_-.,:/", so `"utf-8"` is UTF-8. Nokogiri uses GNU libiconv
351
+ # on macOS and Windows, which takes the name as given. An empty name
352
+ # is the encoding of the locale in glibc. It is unsupported here.
353
+ def glibc_name(name)
354
+ code = name.b
355
+ loop do
356
+ code = code.sub(%r{[\s,/]+\z}n, "")
357
+ break if code.count("/") < 2
358
+
359
+ code = code.byteslice(0, code.rindex(%r{[/,]}n))
360
+ end
361
+ code.delete("^A-Za-z0-9_.,:/-")
362
+ end
363
+
364
+ def syntax_error(message, domain:, code:, level:, str1: nil, line: 0, column: 0)
365
+ XML::SyntaxError.new(message).tap do |error|
366
+ {domain:, code:, level:, file: nil, line:, str1:, str2: nil, str3: nil, int1: 0, column:}.each do |name, value|
367
+ error.instance_variable_set(:"@#{name}", value)
368
+ end
369
+ end
370
+ end
371
+ end
372
+ end
373
+ end
374
+ end