metainspector 5.21.2 → 5.22.0

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.
@@ -0,0 +1,177 @@
1
+ require 'nokogiri'
2
+
3
+ module MetaInspector
4
+ # HTML uses browser-compatible supersets of several legacy encodings.
5
+ # https://encoding.spec.whatwg.org/#names-and-labels
6
+ module HtmlEncoding
7
+ SUPERSETS = {
8
+ Encoding.find('GB2312') => 'GBK',
9
+ Encoding.find('Shift_JIS') => 'Windows-31J',
10
+ Encoding.find('EUC-KR') => 'CP949',
11
+ Encoding.find('Big5') => 'Big5-HKSCS',
12
+ Encoding.find('ISO-8859-1') => 'Windows-1252',
13
+ Encoding.find('US-ASCII') => 'Windows-1252',
14
+ Encoding.find('ISO-8859-9') => 'Windows-1254',
15
+ Encoding.find('ISO-8859-11') => 'Windows-874',
16
+ Encoding.find('TIS-620') => 'Windows-874'
17
+ }.freeze
18
+
19
+ # Labels browsers accept, keyed by the Ruby name of their encoding.
20
+ # The replacement and x-user-defined encodings are left out: their labels
21
+ # are ignored like unknown ones.
22
+ LABELS = {
23
+ 'UTF-8' => %w[unicode-1-1-utf-8 unicode11utf8 unicode20utf8 utf-8 utf8 x-unicode20utf8],
24
+ 'IBM866' => %w[866 cp866 csibm866 ibm866],
25
+ 'ISO-8859-2' => %w[csisolatin2 iso-8859-2 iso-ir-101 iso8859-2 iso88592 iso_8859-2 iso_8859-2:1987 l2 latin2],
26
+ 'ISO-8859-3' => %w[csisolatin3 iso-8859-3 iso-ir-109 iso8859-3 iso88593 iso_8859-3 iso_8859-3:1988 l3 latin3],
27
+ 'ISO-8859-4' => %w[csisolatin4 iso-8859-4 iso-ir-110 iso8859-4 iso88594 iso_8859-4 iso_8859-4:1988 l4 latin4],
28
+ 'ISO-8859-5' => %w[csisolatincyrillic cyrillic iso-8859-5 iso-ir-144 iso8859-5 iso88595 iso_8859-5
29
+ iso_8859-5:1988],
30
+ 'ISO-8859-6' => %w[arabic asmo-708 csiso88596e csiso88596i csisolatinarabic ecma-114 iso-8859-6 iso-8859-6-e
31
+ iso-8859-6-i iso-ir-127 iso8859-6 iso88596 iso_8859-6 iso_8859-6:1987],
32
+ 'ISO-8859-7' => %w[csisolatingreek ecma-118 elot_928 greek greek8 iso-8859-7 iso-ir-126 iso8859-7 iso88597
33
+ iso_8859-7 iso_8859-7:1987 sun_eu_greek],
34
+ # Includes the ISO-8859-8-I labels, which only differ in text direction.
35
+ 'ISO-8859-8' => %w[csiso88598e csisolatinhebrew hebrew iso-8859-8 iso-8859-8-e iso-ir-138 iso8859-8 iso88598
36
+ iso_8859-8 iso_8859-8:1988 visual csiso88598i iso-8859-8-i logical],
37
+ 'ISO-8859-10' => %w[csisolatin6 iso-8859-10 iso-ir-157 iso8859-10 iso885910 l6 latin6],
38
+ 'ISO-8859-13' => %w[iso-8859-13 iso8859-13 iso885913],
39
+ 'ISO-8859-14' => %w[iso-8859-14 iso8859-14 iso885914],
40
+ 'ISO-8859-15' => %w[csisolatin9 iso-8859-15 iso8859-15 iso885915 iso_8859-15 l9],
41
+ 'ISO-8859-16' => %w[iso-8859-16],
42
+ 'KOI8-R' => %w[cskoi8r koi koi8 koi8-r koi8_r],
43
+ 'KOI8-U' => %w[koi8-ru koi8-u],
44
+ 'macRoman' => %w[csmacintosh mac macintosh x-mac-roman],
45
+ 'Windows-874' => %w[dos-874 iso-8859-11 iso8859-11 iso885911 tis-620 windows-874],
46
+ 'Windows-1250' => %w[cp1250 windows-1250 x-cp1250],
47
+ 'Windows-1251' => %w[cp1251 windows-1251 x-cp1251],
48
+ 'Windows-1252' => %w[ansi_x3.4-1968 ascii cp1252 cp819 csisolatin1 ibm819 iso-8859-1 iso-ir-100 iso8859-1
49
+ iso88591 iso_8859-1 iso_8859-1:1987 l1 latin1 us-ascii windows-1252 x-cp1252],
50
+ 'Windows-1253' => %w[cp1253 windows-1253 x-cp1253],
51
+ 'Windows-1254' => %w[cp1254 csisolatin5 iso-8859-9 iso-ir-148 iso8859-9 iso88599 iso_8859-9 iso_8859-9:1989
52
+ l5 latin5 windows-1254 x-cp1254],
53
+ 'Windows-1255' => %w[cp1255 windows-1255 x-cp1255],
54
+ 'Windows-1256' => %w[cp1256 windows-1256 x-cp1256],
55
+ 'Windows-1257' => %w[cp1257 windows-1257 x-cp1257],
56
+ 'Windows-1258' => %w[cp1258 windows-1258 x-cp1258],
57
+ 'macCyrillic' => %w[x-mac-cyrillic x-mac-ukrainian],
58
+ 'GBK' => %w[chinese csgb2312 csiso58gb231280 gb2312 gb_2312 gb_2312-80 gbk iso-ir-58 x-gbk],
59
+ 'GB18030' => %w[gb18030],
60
+ 'Big5' => %w[big5 big5-hkscs cn-big5 csbig5 x-x-big5],
61
+ 'EUC-JP' => %w[cseucpkdfmtjapanese euc-jp x-euc-jp],
62
+ 'ISO-2022-JP' => %w[csiso2022jp iso-2022-jp],
63
+ 'Shift_JIS' => %w[csshiftjis ms932 ms_kanji shift-jis shift_jis sjis windows-31j x-sjis],
64
+ 'EUC-KR' => %w[cseuckr csksc56011987 euc-kr iso-ir-149 korean ks_c_5601-1987 ks_c_5601-1989 ksc5601
65
+ ksc_5601 windows-949],
66
+ 'UTF-16BE' => %w[unicodefffe utf-16be],
67
+ 'UTF-16LE' => %w[csunicode iso-10646-ucs-2 ucs-2 unicode unicodefeff utf-16 utf-16le]
68
+ }.flat_map { |encoding, labels| labels.map { |label| [label, encoding] } }.to_h.freeze
69
+
70
+ # Returns the encoding for a charset label, or nil if browsers don't know it.
71
+ def self.resolve(label)
72
+ LABELS[label.to_s.strip.downcase]
73
+ end
74
+
75
+ def self.ruby_encoding?(label)
76
+ Encoding.find(label)
77
+ true
78
+ rescue ArgumentError
79
+ false
80
+ end
81
+
82
+ def self.superset(label)
83
+ SUPERSETS[Encoding.find(label)] if label
84
+ rescue ArgumentError
85
+ nil
86
+ end
87
+
88
+ def self.normalize(html)
89
+ encoding = superset(html.encoding)
90
+ return html unless encoding
91
+
92
+ # Ruby's Big5-HKSCS byte validation rejects some sequences its transcoder
93
+ # supports. Convert before scrub/tr can reject or replace those bytes.
94
+ html.dup.force_encoding(encoding).encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
95
+ end
96
+
97
+ # Resolve binary HTML before Nokogiri can choose a later meta tag.
98
+ class Detector < Nokogiri::XML::SAX::Document
99
+ BYTE_ORDER_MARKS = {
100
+ "\x00\x00\xFE\xFF".b => 'UTF-32BE',
101
+ "\xFF\xFE\x00\x00".b => 'UTF-32LE',
102
+ "\xEF\xBB\xBF".b => 'UTF-8',
103
+ "\xFE\xFF".b => 'UTF-16BE',
104
+ "\xFF\xFE".b => 'UTF-16LE'
105
+ }.freeze
106
+ TEXT_ELEMENTS = %w[script style title textarea xmp iframe noembed noframes plaintext].freeze
107
+ private_constant :BYTE_ORDER_MARKS, :TEXT_ELEMENTS
108
+
109
+ def self.detect(html)
110
+ # HTTP charsets and the encoding: option already tag the body string.
111
+ return html.encoding.name unless html.encoding == Encoding::BINARY
112
+
113
+ encoding = byte_order_mark_encoding(html)
114
+ return encoding if encoding
115
+
116
+ detector = new
117
+ catch(:metainspector_charset) do
118
+ # Every byte is valid in Latin-1. Only markup matters during this scan;
119
+ # using SAX avoids mistaking comments or script contents for meta tags.
120
+ Nokogiri::HTML4::SAX::Parser.new(detector, 'ISO-8859-1').parse(html) unless html.empty?
121
+ # Name the default rather than return nil, or libxml2 would read the
122
+ # unknown label from the meta tag and stop parsing there.
123
+ 'Windows-1252' if detector.unknown_label
124
+ end
125
+ end
126
+
127
+ attr_reader :unknown_label
128
+
129
+ def self.byte_order_mark_encoding(html)
130
+ BYTE_ORDER_MARKS.each do |mark, encoding|
131
+ return encoding if html.start_with?(mark)
132
+ end
133
+ nil
134
+ end
135
+
136
+ def start_element(name, attributes = [])
137
+ return if @text_element
138
+
139
+ if TEXT_ELEMENTS.include?(name)
140
+ @text_element = name
141
+ return
142
+ end
143
+ return unless name == 'meta'
144
+
145
+ attributes = attributes.to_h
146
+ charset = attributes['charset']
147
+ if !charset && attributes['http-equiv'].to_s.casecmp?('content-type')
148
+ charset = attributes['content'].to_s[/(?:\A|;)\s*charset\s*=\s*["']?([^;\s"']+)/i, 1]
149
+ end
150
+ return if charset.to_s.strip.empty?
151
+
152
+ encoding = HtmlEncoding.resolve(charset)
153
+ # A page whose meta tag can be read as ASCII isn't UTF-16.
154
+ # https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding
155
+ encoding = 'UTF-8' if encoding&.start_with?('UTF-16')
156
+ # Keep labels that only Ruby and libxml2 know, such as UTF-7.
157
+ encoding ||= charset.strip if HtmlEncoding.ruby_encoding?(charset.strip)
158
+ throw :metainspector_charset, encoding if encoding
159
+
160
+ @unknown_label = true
161
+ end
162
+
163
+ def end_element(name)
164
+ @text_element = nil if name == @text_element
165
+ end
166
+ end
167
+ private_constant :Detector
168
+
169
+ def self.detect(html)
170
+ Detector.detect(html)
171
+ end
172
+
173
+ def self.byte_order_mark_encoding(html)
174
+ Detector.byte_order_mark_encoding(html) if html.encoding == Encoding::BINARY
175
+ end
176
+ end
177
+ end
@@ -8,13 +8,28 @@ require 'faraday/gzip'
8
8
  require 'faraday/retry'
9
9
  require_relative 'url_policy'
10
10
  require_relative 'limited_response'
11
+ require_relative 'attempt_timeout'
11
12
 
12
13
  module MetaInspector
13
14
  # Builds page and binary image transports from the same caller configuration.
14
15
  class HttpSession
16
+ # Faraday stores the query as a params hash and rebuilds it for the request,
17
+ # which sorts keys, drops repeated ones and re-escapes values. This encoder
18
+ # keeps the whole query as a single key, so it is sent as written.
19
+ module RawQuery
20
+ def self.decode(query)
21
+ query.to_s.empty? ? {} : { query => nil }
22
+ end
23
+
24
+ def self.encode(params)
25
+ params.keys.join('&')
26
+ end
27
+ end
28
+
15
29
  def initialize(options = {})
16
30
  @allow_redirections = options[:allow_redirections]
17
31
  @retries = options[:retries]
32
+ @attempt_timeout = (options[:connection_timeout] || 0) + (options[:read_timeout] || 0) + 1
18
33
  @headers = options[:headers]
19
34
  @max_html_bytes = options[:max_html_bytes]
20
35
  @url_filter = options[:url_filter]
@@ -26,10 +41,15 @@ module MetaInspector
26
41
  end
27
42
 
28
43
  def build(url, image: false, origin: nil, protect_redirect_callback: false)
29
- URLPolicy.validate!(url)
44
+ uri = URLPolicy.validate!(url)
30
45
  # Image requests must keep trusting the initial origin after page redirects.
31
46
  @page_origin ||= url.to_s unless image
32
- faraday_options = @faraday_options.merge(url: url)
47
+ # Faraday.new decodes a query in its URL with the default encoder, before
48
+ # any configured one applies, so the query is added to the params below.
49
+ query = uri.query
50
+ uri.query = nil
51
+ faraday_options = @faraday_options.merge(url: uri.to_s)
52
+ faraday_options[:request] = { params_encoder: RawQuery }.merge(faraday_options[:request] || {})
33
53
  redirects = (faraday_options.delete(:redirect) || {}).dup
34
54
  if protect_redirect_callback && redirects[:callback]
35
55
  callback = redirects[:callback]
@@ -41,11 +61,12 @@ module MetaInspector
41
61
  end
42
62
  end
43
63
  end
44
- Faraday.new(faraday_options) do |faraday|
64
+ connection = Faraday.new(faraday_options) do |faraday|
45
65
  unless image
46
66
  faraday.request :retry, max: @retries
67
+ faraday.use AttemptTimeout, @attempt_timeout
47
68
  # Responses run in reverse order: decompress before applying the charset.
48
- faraday.response :encoding if @max_html_bytes
69
+ faraday.response :encoding
49
70
  faraday.request :gzip if @max_html_bytes.nil?
50
71
  end
51
72
  if @allow_redirections
@@ -63,9 +84,10 @@ module MetaInspector
63
84
  end
64
85
  faraday.use LimitedResponse::Streaming, @max_html_bytes if !image && @max_html_bytes
65
86
  faraday.headers.merge!(@headers || {})
66
- faraday.response :encoding unless image || @max_html_bytes
67
87
  faraday.adapter :net_http
68
88
  end
89
+ connection.params.merge_query(query, connection.options.params_encoder)
90
+ connection
69
91
  end
70
92
 
71
93
  private
@@ -80,6 +80,8 @@ module MetaInspector
80
80
  file_size: file_size(status, headers, completed, bytes.bytesize) }
81
81
  rescue URLPolicy::Failure => failure
82
82
  raise failure.original
83
+ rescue URI::InvalidComponentError => error
84
+ raise MetaInspector::RequestError.new(error)
83
85
  rescue Faraday::TimeoutError, Faraday::ConnectionFailed, Faraday::SSLError,
84
86
  Faraday::FollowRedirects::RedirectLimitReached, URI::InvalidURIError, Timeout::Error
85
87
  nil
@@ -1,4 +1,5 @@
1
1
  require 'nokogiri'
2
+ require_relative 'html_encoding'
2
3
 
3
4
  module MetaInspector
4
5
  ##
@@ -8,6 +9,10 @@ module MetaInspector
8
9
  # passing itself as a reference for coordination purposes
9
10
  #
10
11
  class Parser
12
+ # libxml2's limit for a single text node, attribute value or comment
13
+ # (XML_MAX_TEXT_LENGTH).
14
+ MAX_NODE_BYTES = 10_000_000
15
+
11
16
  def initialize(document, options = {})
12
17
  @document = document
13
18
  @max_html_bytes = options[:max_html_bytes]
@@ -51,8 +56,114 @@ module MetaInspector
51
56
  if @max_html_bytes && html.bytesize > @max_html_bytes
52
57
  raise MetaInspector::ParserError, "HTML is #{html.bytesize} bytes, exceeding the limit of #{@max_html_bytes} bytes"
53
58
  end
54
- Nokogiri::HTML(html)
59
+ html = HtmlEncoding.normalize(html).scrub
60
+ # Keep libxml2's resource-limit validation. HTML5 has different limits
61
+ # and would otherwise accept oversized text nodes.
62
+ document = Nokogiri::HTML(html, nil, HtmlEncoding.detect(html))
63
+ # For untagged bytes, use the selected declaration, then parse
64
+ # again after the same conversion used for tagged strings. libxml2's
65
+ # Windows-31J decoder still uses some strict Shift_JIS character mappings.
66
+ if html.encoding == Encoding::BINARY && HtmlEncoding.superset(document.encoding)
67
+ html = HtmlEncoding.normalize(html.dup.force_encoding(document.encoding))
68
+ document = Nokogiri::HTML(html)
69
+ end
70
+ raise_limit_error(document, /Resource limit exceeded|xmlSAX2Characters: huge text node/)
71
+
72
+ if (utf8 = html5_input(html, document))
73
+ # The HTML5 tree is the DOM and enforces its own depth limit, so
74
+ # libxml2's depth error doesn't apply: its HTML4 tree can be much
75
+ # deeper, as it leaves elements open that HTML5 closes (#612).
76
+ parsed = html5_document(utf8, document)
77
+ enforce_node_size_limit(parsed, utf8, document)
78
+ parsed
79
+ else
80
+ # libxml2's tree is the DOM, and past its depth limit it's truncated.
81
+ raise_limit_error(document, /Excessive depth in document/)
82
+ document
83
+ end
84
+ end
85
+ rescue ArgumentError, EncodingError => error
86
+ raise MetaInspector::ParserError.new(error)
87
+ end
88
+
89
+ private
90
+
91
+ def raise_limit_error(document, pattern)
92
+ return if non_html_content?
93
+
94
+ limit_error = document.errors.find { |error| error.message.match?(pattern) }
95
+ raise MetaInspector::ParserError, limit_error.message.strip if limit_error
96
+ end
97
+
98
+ # libxml2 may stop reading at a fatal error, such as its depth limit, so it
99
+ # may not have checked the size of everything after that point. Then apply
100
+ # its limit to the HTML5 tree, which has none of its own. Skip inputs too
101
+ # small to hold an oversized node: HTML5 parsing turns a byte into at most
102
+ # 3 (NUL to U+FFFD).
103
+ def enforce_node_size_limit(parsed, html, document)
104
+ return if non_html_content? || html.bytesize * 3 <= MAX_NODE_BYTES
105
+ return unless document.errors.any?(&:fatal?)
106
+
107
+ kind = catch(:oversized) do
108
+ parsed.traverse do |node|
109
+ if node.element?
110
+ throw :oversized, 'attribute value' if node.attribute_nodes.any? { |a| a.value.bytesize > MAX_NODE_BYTES }
111
+ elsif node.comment?
112
+ throw :oversized, 'comment' if node.content.bytesize > MAX_NODE_BYTES
113
+ elsif node.text? || node.cdata?
114
+ throw :oversized, 'text node' if node.content.bytesize > MAX_NODE_BYTES
115
+ end
116
+ end
117
+ nil
118
+ end
119
+ raise MetaInspector::ParserError, "Resource limit exceeded: #{kind} longer than #{MAX_NODE_BYTES} bytes" if kind
120
+ end
121
+
122
+ def html5_document(html, fallback)
123
+ parsed = Nokogiri::HTML5(html, max_attributes: -1, parse_noscript_content_as_text: true)
124
+ restore_noscript_content(parsed)
125
+ parsed.errors.concat(fallback.errors)
126
+ parsed
127
+ rescue ArgumentError
128
+ raise unless non_html_content?
129
+
130
+ # Binary files and XML feeds can nest past the HTML5 tree depth limit.
131
+ # The caller accepted non-HTML content, so keep libxml2's tree, whose
132
+ # depth is already capped, as 5.21.0 did.
133
+ fallback
134
+ end
135
+
136
+ # The caller opted in with allow_non_html_content and the response is not
137
+ # HTML, so resource limits that guard against truncated HTML do not apply.
138
+ def non_html_content?
139
+ return false unless @document.allow_non_html_content
140
+
141
+ content_type = @document.content_type
142
+ !content_type.nil? && content_type != 'text/html'
143
+ end
144
+
145
+ def restore_noscript_content(document)
146
+ document.css('noscript').each do |node|
147
+ # Isolate fallback markup so it cannot close the head or consume the
148
+ # rest of the page, while keeping it available to all extractors.
149
+ node.children = Nokogiri::HTML5.fragment(node.text, max_attributes: -1)
55
150
  end
56
151
  end
152
+
153
+ def html5_input(html, document)
154
+ encoding = html.encoding == Encoding::BINARY ? document.encoding || 'UTF-8' : html.encoding.name
155
+ encoding = encoding.sub(/\AISO_/i, 'ISO-').sub(/:\d+\z/, '')
156
+ encoding = case encoding.downcase
157
+ when 'latin1', 'l1' then 'ISO-8859-1'
158
+ when 'gb_2312-80' then 'GB2312'
159
+ else encoding
160
+ end
161
+ encoding = HtmlEncoding.superset(encoding) || encoding
162
+ html.encode(Encoding::UTF_8, encoding, invalid: :replace, undef: :replace)
163
+ rescue ArgumentError, Encoding::ConverterNotFoundError
164
+ # libxml2 supports encodings (such as UTF-7) that Ruby cannot transcode.
165
+ # Preserve the existing parser for those documents rather than rejecting them.
166
+ nil
167
+ end
57
168
  end
58
169
  end
@@ -3,8 +3,9 @@ module MetaInspector
3
3
  class HeadLinksParser < Base
4
4
  delegate [:parsed, :base_url] => :@main_parser
5
5
 
6
+ # application/json is JSON Feed 1.0; application/feed+json is 1.1.
6
7
  KNOWN_FEED_TYPES = %w[
7
- application/rss+xml application/atom+xml application/json
8
+ application/rss+xml application/atom+xml application/json application/feed+json
8
9
  ].freeze
9
10
 
10
11
  def head_links
@@ -32,7 +33,7 @@ module MetaInspector
32
33
  @feeds ||=
33
34
  parsed.search('//link[@rel]').map do |link|
34
35
  next unless rel_includes?(link['rel'], 'alternate')
35
- next if !KNOWN_FEED_TYPES.include?(link["type"]) || link["href"].to_s.strip == ''
36
+ next if !KNOWN_FEED_TYPES.include?(media_type(link["type"])) || link["href"].to_s.strip == ''
36
37
 
37
38
  {
38
39
  title: link["title"],
@@ -46,12 +47,18 @@ module MetaInspector
46
47
  def feed
47
48
  warn 'DEPRECATION WARNING: page.feed is deprecated and will be removed in 6.0. ' \
48
49
  'Use page.feeds instead.'
49
- first_feed = feeds.find { |link| %r{/(rss|atom)\+xml$}i.match?(link[:type]) }
50
+ first_feed = feeds.find { |link| %w[application/rss+xml application/atom+xml].include?(media_type(link[:type])) }
50
51
  first_feed && first_feed[:href]
51
52
  end
52
53
 
53
54
  private
54
55
 
56
+ # Media types are case-insensitive and may carry parameters
57
+ # (https://mimesniff.spec.whatwg.org/#mime-type-essence).
58
+ def media_type(type)
59
+ type.to_s.split(';', 2).first.to_s.strip.downcase(:ascii)
60
+ end
61
+
55
62
  def rel_includes?(rel, keyword)
56
63
  rel.to_s.downcase(:ascii).split(/[ \t\n\f\r]+/).include?(keyword)
57
64
  end
@@ -7,9 +7,11 @@ module MetaInspector
7
7
  self
8
8
  end
9
9
 
10
- # Returns all links found, unprocessed
10
+ # Returns all links found, unprocessed.
11
+ # Matches <a> by local name: in the HTML5 tree, links inside inline
12
+ # <svg> or <math> are in another namespace, and '//a' would miss them.
11
13
  def raw
12
- @raw ||= cleanup(parsed.search('//a/@href')).compact.uniq
14
+ @raw ||= cleanup(parsed.xpath('//*[local-name()="a"]/@href')).compact.uniq
13
15
  end
14
16
 
15
17
  # Returns all links found, unrelavitized and absolutified
@@ -52,9 +54,13 @@ module MetaInspector
52
54
  current_base_href || url
53
55
  end
54
56
 
55
- # Returns the value of the href attribute on the <base /> tag, if exists
57
+ # Returns the value of the href attribute on the <base /> tag, if exists.
58
+ # Memoized, nil included, as it's needed once per link, image, iframe
59
+ # and head link, and searching the whole document every time is slow.
56
60
  def base_href
57
- parsed.search('base').first.attributes['href'].value rescue nil
61
+ return @base_href if defined?(@base_href)
62
+
63
+ @base_href = parsed.search('base').first.attributes['href'].value rescue nil
58
64
  end
59
65
  end
60
66
  end
@@ -37,8 +37,12 @@ module MetaInspector
37
37
  end
38
38
 
39
39
  def charset_from_meta_content_type
40
- parsed.css("meta[http-equiv='Content-Type']")[0]
41
- .attributes['content'].value.split(';')[1].split('=')[1] rescue nil
40
+ tag = parsed.css('meta[http-equiv]').find do |meta|
41
+ meta['http-equiv'].casecmp('Content-Type').zero?
42
+ end
43
+ return unless tag
44
+
45
+ tag['content'].to_s[/;\s*charset\s*=\s*["']?([^;\s"']+)/i, 1]
42
46
  end
43
47
 
44
48
  def meta_tags_by(attribute)
@@ -9,10 +9,10 @@ module MetaInspector
9
9
  value unless value.to_s.empty?
10
10
  end
11
11
 
12
- # Returns the parsed document title, from the content of the <title> tag
12
+ # Returns the parsed document title, from the content of the first <title> tag
13
13
  # within the <head> section.
14
14
  def title
15
- @title ||= parsed.css('head title').inner_text rescue nil
15
+ @title ||= parsed.at_css('head title')&.inner_text.to_s rescue nil
16
16
  end
17
17
 
18
18
  def best_title
@@ -1,5 +1,5 @@
1
- require 'timeout'
2
1
  require_relative 'http_session'
2
+ require_relative 'html_encoding'
3
3
 
4
4
  module MetaInspector
5
5
 
@@ -27,9 +27,26 @@ module MetaInspector
27
27
  def read
28
28
  return unless response
29
29
  body = response.body
30
- body = body.encode!(@encoding, @encoding, :invalid => :replace) if @encoding
30
+ check_content_encoding!(body)
31
+ if body.encoding == Encoding::BINARY
32
+ # The adapter tags the body only with HTTP charsets Ruby knows.
33
+ label = response.headers['content-type'].to_s[/(?:\A|;)\s*charset\s*=\s*["']?([^;\s"']+)/i, 1]
34
+ charset = HtmlEncoding.resolve(label)
35
+ body = body.dup.force_encoding(charset) if charset
36
+ end
37
+ body = body.dup.force_encoding(@encoding) if @encoding
38
+ encoding = HtmlEncoding.byte_order_mark_encoding(body)
39
+ body = body.dup.force_encoding(encoding) if encoding && !Encoding.find(encoding).ascii_compatible?
40
+ body = HtmlEncoding.normalize(body)
41
+ # Replace invalid bytes with U+FFFD, as browsers do, so one bad byte
42
+ # doesn't make the whole page fail. Binary bodies are decoded later by the parser.
43
+ body = if body.encoding.ascii_compatible?
44
+ body.scrub
45
+ else
46
+ body.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
47
+ end
31
48
  body.tr("\000", '')
32
- rescue ArgumentError => e
49
+ rescue ArgumentError, EncodingError => e
33
50
  raise MetaInspector::RequestError.new(e)
34
51
  end
35
52
 
@@ -41,9 +58,10 @@ module MetaInspector
41
58
  @response ||= fetch
42
59
  rescue URLPolicy::Failure => failure
43
60
  raise failure.original
44
- rescue Faraday::TimeoutError => e
61
+ rescue Faraday::TimeoutError, AttemptTimeout::Expired => e
45
62
  raise MetaInspector::TimeoutError.new(e)
46
- rescue Faraday::ConnectionFailed, Faraday::SSLError, URI::InvalidURIError, Faraday::FollowRedirects::RedirectLimitReached => e
63
+ rescue Faraday::ConnectionFailed, Faraday::SSLError, URI::InvalidURIError, URI::InvalidComponentError,
64
+ Faraday::FollowRedirects::RedirectLimitReached, Zlib::Error => e
47
65
  raise MetaInspector::RequestError.new(e)
48
66
  end
49
67
 
@@ -61,20 +79,16 @@ module MetaInspector
61
79
  end
62
80
 
63
81
  def fetch
64
- Timeout::timeout(fatal_timeout) do
65
- session = @http_session.build(url)
66
-
67
- check_head_content_type(session) if @head_first
68
- response = perform_request(session, :get)
82
+ session = @http_session.build(url)
69
83
 
70
- if @allow_redirections
71
- @url.url = response.env.url.to_s
72
- end
84
+ check_head_content_type(session) if @head_first
85
+ response = perform_request(session, :get)
73
86
 
74
- response
87
+ if @allow_redirections
88
+ @url.url = response.env.url.to_s
75
89
  end
76
- rescue Timeout::Error => e
77
- raise MetaInspector::TimeoutError.new(e)
90
+
91
+ response
78
92
  end
79
93
 
80
94
  def check_head_content_type(session)
@@ -87,26 +101,27 @@ module MetaInspector
87
101
  end
88
102
  end
89
103
 
104
+ # The compression middleware removes Content-Encoding once it has decoded the
105
+ # body. If it's still there, the body is compressed bytes, not HTML (#597).
106
+ def check_content_encoding!(body)
107
+ return if body.empty?
108
+
109
+ header = response.headers['content-encoding'].to_s
110
+ encodings = header.split(',').map { |value| value.strip.downcase }.reject(&:empty?) - ['identity']
111
+ return if encodings.empty?
112
+
113
+ raise MetaInspector::RequestError, "Unsupported Content-Encoding: #{header.strip}"
114
+ end
115
+
90
116
  def response_content_type(response)
91
- response.headers['content-type']&.split(';')&.first
117
+ response.headers['content-type']&.split(';')&.first&.strip&.downcase
92
118
  end
93
119
 
94
120
  def perform_request(session, method)
95
121
  session.public_send(method) do |req|
96
- req.options.timeout = @connection_timeout
97
- req.options.open_timeout = @read_timeout
122
+ req.options.open_timeout = @connection_timeout
123
+ req.options.timeout = @read_timeout
98
124
  end
99
125
  end
100
-
101
- # Timeouts when connecting / reading a request are handled by Faraday, but in the
102
- # case of URLs that respond with streaming, Faraday will never return. In that case,
103
- # we'll resort to our own timeout
104
- #
105
- # https://github.com/jaimeiniesta/metainspector/issues/188
106
- # https://github.com/lostisland/faraday/issues/602
107
- #
108
- def fatal_timeout
109
- (@connection_timeout || 0) + (@read_timeout || 0) + 1
110
- end
111
126
  end
112
127
  end