metainspector 5.21.1 → 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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +32 -0
- data/README.md +207 -36
- data/lib/meta_inspector/attempt_timeout.rb +40 -0
- data/lib/meta_inspector/document.rb +27 -4
- data/lib/meta_inspector/html_encoding.rb +177 -0
- data/lib/meta_inspector/http_session.rb +33 -5
- data/lib/meta_inspector/image_downloader.rb +2 -0
- data/lib/meta_inspector/limited_response.rb +125 -0
- data/lib/meta_inspector/parser.rb +112 -1
- data/lib/meta_inspector/parsers/head_links.rb +10 -3
- data/lib/meta_inspector/parsers/links.rb +10 -4
- data/lib/meta_inspector/parsers/meta_tags.rb +6 -2
- data/lib/meta_inspector/parsers/texts.rb +2 -2
- data/lib/meta_inspector/request.rb +45 -30
- data/lib/meta_inspector/url.rb +32 -5
- data/lib/meta_inspector/url_policy.rb +1 -1
- data/lib/meta_inspector/version.rb +1 -1
- data/meta_inspector.gemspec +1 -1
- data/spec/document_spec.rb +118 -0
- data/spec/meta_inspector/content_type_spec.rb +47 -0
- data/spec/meta_inspector/head_links_spec.rb +3 -3
- data/spec/meta_inspector/links_spec.rb +98 -2
- data/spec/meta_inspector/meta_tags_spec.rb +53 -0
- data/spec/meta_inspector/texts_spec.rb +82 -0
- data/spec/meta_inspector/timeouts_spec.rb +107 -0
- data/spec/noscript_spec.rb +179 -0
- data/spec/parser_spec.rb +382 -2
- data/spec/query_string_spec.rb +125 -0
- data/spec/request_errors_spec.rb +91 -0
- data/spec/request_spec.rb +28 -10
- data/spec/response_encoding_spec.rb +487 -0
- data/spec/response_size_spec.rb +176 -0
- data/spec/url_filter_spec.rb +2 -1
- data/spec/url_spec.rb +37 -0
- metadata +12 -2
|
@@ -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
|
|
@@ -7,14 +7,31 @@ require 'faraday/follow_redirects'
|
|
|
7
7
|
require 'faraday/gzip'
|
|
8
8
|
require 'faraday/retry'
|
|
9
9
|
require_relative 'url_policy'
|
|
10
|
+
require_relative 'limited_response'
|
|
11
|
+
require_relative 'attempt_timeout'
|
|
10
12
|
|
|
11
13
|
module MetaInspector
|
|
12
14
|
# Builds page and binary image transports from the same caller configuration.
|
|
13
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
|
+
|
|
14
29
|
def initialize(options = {})
|
|
15
30
|
@allow_redirections = options[:allow_redirections]
|
|
16
31
|
@retries = options[:retries]
|
|
32
|
+
@attempt_timeout = (options[:connection_timeout] || 0) + (options[:read_timeout] || 0) + 1
|
|
17
33
|
@headers = options[:headers]
|
|
34
|
+
@max_html_bytes = options[:max_html_bytes]
|
|
18
35
|
@url_filter = options[:url_filter]
|
|
19
36
|
if !@url_filter.nil? && !@url_filter.respond_to?(:call)
|
|
20
37
|
raise ArgumentError, 'url_filter must respond to call'
|
|
@@ -24,10 +41,15 @@ module MetaInspector
|
|
|
24
41
|
end
|
|
25
42
|
|
|
26
43
|
def build(url, image: false, origin: nil, protect_redirect_callback: false)
|
|
27
|
-
URLPolicy.validate!(url)
|
|
44
|
+
uri = URLPolicy.validate!(url)
|
|
28
45
|
# Image requests must keep trusting the initial origin after page redirects.
|
|
29
46
|
@page_origin ||= url.to_s unless image
|
|
30
|
-
|
|
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] || {})
|
|
31
53
|
redirects = (faraday_options.delete(:redirect) || {}).dup
|
|
32
54
|
if protect_redirect_callback && redirects[:callback]
|
|
33
55
|
callback = redirects[:callback]
|
|
@@ -39,10 +61,13 @@ module MetaInspector
|
|
|
39
61
|
end
|
|
40
62
|
end
|
|
41
63
|
end
|
|
42
|
-
Faraday.new(faraday_options) do |faraday|
|
|
64
|
+
connection = Faraday.new(faraday_options) do |faraday|
|
|
43
65
|
unless image
|
|
44
66
|
faraday.request :retry, max: @retries
|
|
45
|
-
faraday.
|
|
67
|
+
faraday.use AttemptTimeout, @attempt_timeout
|
|
68
|
+
# Responses run in reverse order: decompress before applying the charset.
|
|
69
|
+
faraday.response :encoding
|
|
70
|
+
faraday.request :gzip if @max_html_bytes.nil?
|
|
46
71
|
end
|
|
47
72
|
if @allow_redirections
|
|
48
73
|
redirects[:limit] ||= 10
|
|
@@ -51,15 +76,18 @@ module MetaInspector
|
|
|
51
76
|
end
|
|
52
77
|
faraday.use URLPolicy, @url_filter, image ? origin : nil,
|
|
53
78
|
request_origin: @page_origin || origin
|
|
79
|
+
faraday.use LimitedResponse, @max_html_bytes if !image && @max_html_bytes
|
|
54
80
|
if !image && @cache.is_a?(Hash)
|
|
55
81
|
cache_options = @cache.dup
|
|
56
82
|
cache_options[:serializer] ||= Marshal
|
|
57
83
|
faraday.use Faraday::HttpCache, **cache_options
|
|
58
84
|
end
|
|
85
|
+
faraday.use LimitedResponse::Streaming, @max_html_bytes if !image && @max_html_bytes
|
|
59
86
|
faraday.headers.merge!(@headers || {})
|
|
60
|
-
faraday.response :encoding unless image
|
|
61
87
|
faraday.adapter :net_http
|
|
62
88
|
end
|
|
89
|
+
connection.params.merge_query(query, connection.options.params_encoder)
|
|
90
|
+
connection
|
|
63
91
|
end
|
|
64
92
|
|
|
65
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
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
require 'zlib'
|
|
2
|
+
require 'stringio'
|
|
3
|
+
|
|
4
|
+
module MetaInspector
|
|
5
|
+
# Enforces max_html_bytes before charset conversion or parsing. Keep this
|
|
6
|
+
# outside the HTTP cache, and Streaming inside it, so cached bodies are checked
|
|
7
|
+
# too and the cache stores the received bytes rather than an empty stream.
|
|
8
|
+
class LimitedResponse < Faraday::Middleware
|
|
9
|
+
CHUNK_SIZE = 16 * 1024
|
|
10
|
+
|
|
11
|
+
def self.check_size!(size, limit)
|
|
12
|
+
return if size <= limit
|
|
13
|
+
|
|
14
|
+
raise MetaInspector::ParserError, "HTML response exceeds the limit of #{limit} bytes"
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def initialize(app, limit)
|
|
18
|
+
super(app)
|
|
19
|
+
@limit = limit
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def call(env)
|
|
23
|
+
env.request_headers['Accept-Encoding'] ||= 'gzip,deflate'
|
|
24
|
+
@app.call(env).on_complete do |response|
|
|
25
|
+
body = response.body
|
|
26
|
+
self.class.check_size!(body.bytesize, @limit)
|
|
27
|
+
next if body.empty? || response.status == 206
|
|
28
|
+
|
|
29
|
+
encodings = response.response_headers['Content-Encoding'].to_s.split(',').map { |value| value.strip.downcase }
|
|
30
|
+
next if encodings.empty? || encodings.include?('identity')
|
|
31
|
+
|
|
32
|
+
encodings.reverse_each do |encoding|
|
|
33
|
+
body = case encoding
|
|
34
|
+
when 'gzip' then gunzip(body)
|
|
35
|
+
when 'deflate' then inflate(body)
|
|
36
|
+
else
|
|
37
|
+
raise MetaInspector::RequestError, "Unsupported Content-Encoding with max_html_bytes: #{encoding}"
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
response.body = body
|
|
41
|
+
response.response_headers['Content-Length'] = body.bytesize
|
|
42
|
+
response.response_headers.delete('Content-Encoding')
|
|
43
|
+
end
|
|
44
|
+
rescue Zlib::Error => error
|
|
45
|
+
raise MetaInspector::RequestError.new(error)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
def append(body, chunk)
|
|
51
|
+
self.class.check_size!(body.bytesize + chunk.bytesize, @limit)
|
|
52
|
+
body << chunk
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def gunzip(bytes)
|
|
56
|
+
body = ''.b
|
|
57
|
+
io = StringIO.new(bytes)
|
|
58
|
+
# gzip can contain multiple members; apply one budget to all of them.
|
|
59
|
+
until io.eof?
|
|
60
|
+
reader = Zlib::GzipReader.new(io, encoding: Encoding::BINARY)
|
|
61
|
+
begin
|
|
62
|
+
while (chunk = reader.read(CHUNK_SIZE)) && !chunk.empty?
|
|
63
|
+
append(body, chunk)
|
|
64
|
+
end
|
|
65
|
+
unused = reader.unused
|
|
66
|
+
ensure
|
|
67
|
+
reader.finish
|
|
68
|
+
end
|
|
69
|
+
io.pos -= unused.bytesize if unused
|
|
70
|
+
end
|
|
71
|
+
body
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def inflate(bytes, window_bits = Zlib::MAX_WBITS)
|
|
75
|
+
body = ''.b
|
|
76
|
+
inflater = Zlib::Inflate.new(window_bits)
|
|
77
|
+
begin
|
|
78
|
+
# Block form yields bounded chunks instead of allocating the full output.
|
|
79
|
+
inflater.inflate(bytes) { |chunk| append(body, chunk) }
|
|
80
|
+
inflater.finish { |chunk| append(body, chunk) }
|
|
81
|
+
ensure
|
|
82
|
+
inflater.close
|
|
83
|
+
end
|
|
84
|
+
body
|
|
85
|
+
rescue Zlib::DataError
|
|
86
|
+
raise if window_bits < 0
|
|
87
|
+
|
|
88
|
+
# Some servers send raw DEFLATE rather than a zlib-wrapped stream.
|
|
89
|
+
inflate(bytes, -Zlib::MAX_WBITS)
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
class Streaming < Faraday::Middleware
|
|
93
|
+
def initialize(app, limit)
|
|
94
|
+
super(app)
|
|
95
|
+
@limit = limit
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def call(env)
|
|
99
|
+
body = ''.b
|
|
100
|
+
# Redirects copy the environment but share request options. Each hop
|
|
101
|
+
# needs its own buffer and callback, as do retries and HEAD/GET pairs.
|
|
102
|
+
env.request = env.request.dup
|
|
103
|
+
env.request.on_data = proc do |chunk, _total, _response|
|
|
104
|
+
LimitedResponse.check_size!(body.bytesize + chunk.bytesize, @limit)
|
|
105
|
+
body << chunk.b
|
|
106
|
+
end
|
|
107
|
+
@app.call(env).on_complete do |response|
|
|
108
|
+
# Net::HTTP tags its buffered body with the HTTP charset, including
|
|
109
|
+
# quoted labels. Streaming replaces that body, so retain the tag.
|
|
110
|
+
charset = response.response_headers['Content-Type'].to_s[/(?:\A|;)\s*charset=([^;]+)/i, 1]
|
|
111
|
+
if charset
|
|
112
|
+
charset = charset.strip
|
|
113
|
+
charset = charset[1...-1] if charset.start_with?('"') && charset.end_with?('"')
|
|
114
|
+
begin
|
|
115
|
+
body.force_encoding(charset)
|
|
116
|
+
rescue ArgumentError
|
|
117
|
+
# Unknown charsets are ignored, as in the Net::HTTP adapter.
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
response.body = body
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|
|
@@ -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
|
-
|
|
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| %
|
|
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.
|
|
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
|
-
|
|
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(
|
|
41
|
-
|
|
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.
|
|
15
|
+
@title ||= parsed.at_css('head title')&.inner_text.to_s rescue nil
|
|
16
16
|
end
|
|
17
17
|
|
|
18
18
|
def best_title
|