ruby-link-checker 0.6.1 → 0.7.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.
data/UPGRADING.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Upgrading ruby-link-checker
2
2
 
3
+ ## Upgrading to 0.7.0
4
+
5
+ ### Fragments
6
+
7
+ Links with a `#fragment` are now requested with `GET` instead of `HEAD`, and fail when the page has no element with that `id` or `<a>` element with that `name`. These failures have `missing_fragment? == true` and the fragment in `missing_fragment`, publish `:failure`, and are collected in `results[:failure]`. GitHub source line anchors such as `#L10` are skipped by default, and pages that aren't HTML pass.
8
+
9
+ Skip fragments whose anchors are added by JavaScript with `fragments_to_skip`, or restore the previous behavior, which ignored fragments:
10
+
11
+ ```ruby
12
+ LinkChecker.configure do |config|
13
+ config.check_fragments = false
14
+ end
15
+ ```
16
+
17
+ See [Fragments](README.md#fragments) for details.
18
+
19
+ ### Meta Refresh
20
+
21
+ Checkers now follow the `<meta http-equiv="refresh">` of HTML pages that they read with `GET`, such as links with a fragment or a `GET` after a failed `HEAD`, so those links report the result of the refresh target. Refreshes count toward `max_redirects` and appear in `result.redirects`, and a refresh to a URL that isn't valid HTTP(S) fails with `invalid_meta_refresh? == true`. Set `max_redirects: 0` to follow neither redirects nor refreshes.
22
+
23
+ See [Meta Refresh](README.md#meta-refresh) for details.
24
+
3
25
  ## Upgrading to 0.6.0
4
26
 
5
27
  ### Blocked Results
@@ -10,18 +10,26 @@ module LinkChecker
10
10
 
11
11
  def _run!
12
12
  client = checker._client_for(uri)
13
- headers = ::Protocol::HTTP::Headers[
14
- checker.request_headers_for(uri).map { |key, value| [key.downcase, value] }
13
+ request_headers = ::Protocol::HTTP::Headers[
14
+ checker.request_headers_for(uri, headers).map { |key, value| [key.downcase, value] }
15
15
  ]
16
- request = ::Protocol::HTTP::Request[method, uri.request_uri, headers]
16
+ request = ::Protocol::HTTP::Request[method, uri.request_uri, request_headers]
17
17
  response = _call(client, request)
18
- result! Result.new(uri, method, original_uri, request, response, options)
18
+ result! Result.new(uri, method, original_uri, request, response, options, body: _read_body(response))
19
19
  rescue StandardError => e
20
20
  result! ResultError.new(uri, method, original_uri, e, options)
21
21
  ensure
22
22
  response&.close
23
23
  end
24
24
 
25
+ # Reads the body of a successful HTML GET, which other checkers' responses always include.
26
+ def _read_body(response)
27
+ return unless method.to_s.casecmp?('GET') && response.status.between?(200, 299)
28
+ return unless LinkChecker::HTML.html?(Headers.new(response.headers)['content-type'])
29
+
30
+ response.read
31
+ end
32
+
25
33
  def _call(client, request)
26
34
  if checker.read_timeout
27
35
  ::Async::Task.current.with_timeout(checker.read_timeout) { client.call(request) }
@@ -17,11 +17,12 @@ module LinkChecker
17
17
  # Wraps an Async::HTTP response to expose a `code` and case-insensitive
18
18
  # `headers`, similar to the other checkers' response objects.
19
19
  class Response
20
- attr_reader :status, :headers
20
+ attr_reader :status, :headers, :body
21
21
 
22
- def initialize(response)
22
+ def initialize(response, body = nil)
23
23
  @status = response.status
24
24
  @headers = Headers.new(response.headers)
25
+ @body = body
25
26
  end
26
27
 
27
28
  def code
@@ -32,9 +33,9 @@ module LinkChecker
32
33
  class Result < ::LinkChecker::Result
33
34
  attr_accessor :request, :response
34
35
 
35
- def initialize(uri, method, original_uri, request, response, options)
36
+ def initialize(uri, method, original_uri, request, response, options, body: nil)
36
37
  @request = request
37
- @response = response && Response.new(response)
38
+ @response = response && Response.new(response, body)
38
39
  super(uri, method, original_uri, options)
39
40
  end
40
41
 
@@ -58,6 +59,10 @@ module LinkChecker
58
59
  Headers.new(request.headers)
59
60
  end
60
61
 
62
+ def body
63
+ response&.body
64
+ end
65
+
61
66
  def response_headers
62
67
  response&.headers || {}
63
68
  end
@@ -74,7 +79,7 @@ module LinkChecker
74
79
  [301, 302, 303, 307, 308].include?(code)
75
80
  end
76
81
 
77
- def success?
82
+ def http_success?
78
83
  return false unless response
79
84
 
80
85
  code >= 200 && code <= 299
@@ -8,7 +8,7 @@ require 'uri'
8
8
 
9
9
  module LinkChecker
10
10
  class CachedResult < Result
11
- attr_reader :code, :challenge
11
+ attr_reader :code, :challenge, :anchors
12
12
 
13
13
  def initialize(data, uri)
14
14
  @code = data.fetch('code')
@@ -18,12 +18,23 @@ module LinkChecker
18
18
  end.freeze
19
19
  @blocked = data['blocked'] == true
20
20
  @challenge = data['challenge'] if data['challenge'].is_a?(String)
21
+ @body_checked = data.key?('anchors')
22
+ @anchors = data['anchors']&.to_set&.freeze
21
23
  @cached = true
22
24
  end
23
25
 
24
- def success?
26
+ def http_success?
25
27
  !blocked?
26
28
  end
29
+
30
+ def failure?
31
+ missing_fragment?
32
+ end
33
+
34
+ # Whether the cached check read the page, so that its fragment targets are known.
35
+ def body_checked?
36
+ @body_checked
37
+ end
27
38
  end
28
39
 
29
40
  class Cache
@@ -62,6 +73,7 @@ module LinkChecker
62
73
  return unless blocked?(data) ? data['code'].between?(100, 999) : data['code'].between?(200, 299)
63
74
  return unless data['method'].is_a?(String) && safe_uri?(data['result_uri'])
64
75
  return unless valid_redirects?(data['redirects'])
76
+ return unless valid_anchors?(data)
65
77
 
66
78
  CachedResult.new(data, uri)
67
79
  rescue URI::InvalidURIError
@@ -83,6 +95,7 @@ module LinkChecker
83
95
  'redirects' => result.redirects.map { |hop| [hop.uri.to_s, hop.code, hop.to.to_s] }
84
96
  }
85
97
  entries[key].merge!('blocked' => true, 'challenge' => result.challenge) if result.blocked?
98
+ entries[key]['anchors'] = result.anchors&.to_a if result.body_checked?
86
99
  entries
87
100
  end
88
101
  rescue IOError, SystemCallError, JSON::GeneratorError
@@ -137,10 +150,19 @@ module LinkChecker
137
150
 
138
151
  def valid_redirects?(redirects)
139
152
  redirects.is_a?(Array) && redirects.all? do |hop|
140
- hop.is_a?(Array) && hop.size == 3 && safe_uri?(hop[0]) && hop[1].is_a?(Integer) && safe_uri?(hop[2])
153
+ # Meta refresh hops have no status code.
154
+ hop.is_a?(Array) && hop.size == 3 && safe_uri?(hop[0]) && (hop[1].nil? || hop[1].is_a?(Integer)) &&
155
+ safe_uri?(hop[2])
141
156
  end
142
157
  end
143
158
 
159
+ # Entries of a page that was read list its fragment targets, or null when it isn't HTML.
160
+ def valid_anchors?(data)
161
+ return true unless data.key?('anchors')
162
+
163
+ data['anchors'].nil? || (data['anchors'].is_a?(Array) && data['anchors'].all?(String))
164
+ end
165
+
144
166
  def blocked?(data)
145
167
  data['blocked'] == true
146
168
  end
@@ -12,6 +12,7 @@ module LinkChecker
12
12
  IDENTITY_EXCLUDED_ATTRIBUTES = %i[
13
13
  logger cache deduplicate blocked_status_codes detect_challenges max_concurrency_per_host min_host_interval
14
14
  rate_limit_retries rate_limit_status_codes rate_limit_backoff max_rate_limit_delay
15
+ check_fragments fragments_to_skip follow_meta_refresh url_rewrites
15
16
  ].freeze
16
17
 
17
18
  attr_reader :results
@@ -38,29 +39,14 @@ module LinkChecker
38
39
  end
39
40
 
40
41
  def check(uri, options = {})
41
- return execute_check(uri, options) unless deduplicate || @cache_store
42
-
43
- key = request_key(uri)
44
- return execute_check(uri, options) unless key
45
-
46
- subscriber = [uri.to_s.dup, options]
47
- if deduplicate && (entry = @pending[key])
48
- entry[:subscribers] << subscriber
49
- entry[:events].each { |event, result| publish(event, copy_result(result, subscriber)) }
50
- return
51
- end
52
-
53
- cached_result = @successful[key] if deduplicate
54
- cached_result ||= @cache_store&.fetch(key, uri)
55
- if cached_result&.success?
56
- @successful[key] ||= cached_result if deduplicate
57
- return publish_cached(:success, cached_result, subscriber)
58
- end
59
- return publish_cached(:blocked, cached_result, subscriber) if blocked_result?(cached_result)
42
+ rewrite = _url_rewrite(uri)
43
+ rewrite ? _check_rewrite(uri, options, rewrite) : _check(uri, options)
44
+ end
60
45
 
61
- entry = { subscribers: [subscriber], events: [] }
62
- @pending[key] = entry if deduplicate
63
- execute_check(uri, options) { |event, result| handle_shared_result(key, entry, uri, event, result) }
46
+ # Request headers for uri: the user-agent, then global headers, then every matching host_headers entry, then the
47
+ # headers of a URL rewrite. Later values replace earlier ones with the same case-insensitive name.
48
+ def request_headers_for(uri, rewrite_headers = {})
49
+ _merge_headers([{ 'User-Agent' => user_agent }, headers] + _matching_host_headers(uri) + [rewrite_headers])
64
50
  end
65
51
 
66
52
  # Finishes a run. Checkers that queue requests run them first; Net::HTTP checks links as they are submitted.
@@ -81,12 +67,6 @@ module LinkChecker
81
67
  detect_challenges && result.challenge?
82
68
  end
83
69
 
84
- # Request headers for uri: the user-agent, then global headers, then every matching host_headers entry.
85
- # Later values replace earlier ones with the same case-insensitive name.
86
- def request_headers_for(uri)
87
- _merge_headers([{ 'User-Agent' => user_agent }, headers] + _matching_host_headers(uri))
88
- end
89
-
90
70
  # The host that per-host limits apply to, or nil when the URI has none.
91
71
  def _host_key(uri)
92
72
  URI(uri.to_s).host&.downcase
@@ -138,6 +118,84 @@ module LinkChecker
138
118
 
139
119
  private
140
120
 
121
+ # Checks uri, sending rewrite headers, and delivers its events to sink, or publishes them without one.
122
+ def _check(uri, options, headers: {}, sink: nil)
123
+ body = _body_required?(uri)
124
+ return execute_check(uri, options, body: body, headers: headers, sink: sink) unless deduplicate || @cache_store
125
+
126
+ key = request_key(uri, headers)
127
+ return execute_check(uri, options, body: body, headers: headers, sink: sink) unless key
128
+
129
+ subscriber = [uri.to_s.dup, options, sink]
130
+ # A check that reads the page also answers links that don't need it.
131
+ if deduplicate && (entry = @pending[[key, true]] || (@pending[[key, false]] unless body))
132
+ entry[:subscribers] << subscriber
133
+ entry[:events].each { |event, result| deliver(event, copy_result(result, subscriber), subscriber) }
134
+ return
135
+ end
136
+
137
+ cached_result = @successful[key] if deduplicate
138
+ cached_result = nil if body && cached_result && !cached_result.body_checked?
139
+ cached_result ||= @cache_store&.fetch(key, uri)
140
+ if cached_result&.success? && (!body || cached_result.body_checked?)
141
+ @successful[key] ||= cached_result if deduplicate
142
+ return publish_cached(:success, cached_result, subscriber)
143
+ end
144
+ return publish_cached(:blocked, cached_result, subscriber) if blocked_result?(cached_result)
145
+
146
+ entry = { subscribers: [subscriber], events: [] }
147
+ @pending[[key, body]] = entry if deduplicate
148
+ execute_check(uri, options, body: body, headers: headers) do |event, result|
149
+ handle_shared_result(key, [key, body], entry, uri, headers, event, result)
150
+ end
151
+ end
152
+
153
+ # The rewrite of uri by the first url_rewrites rule that matches it, or nil.
154
+ def _url_rewrite(uri)
155
+ return if url_rewrites.empty?
156
+
157
+ parsed = URI(uri.to_s)
158
+ UrlRewrites.rewrite(url_rewrites, parsed) if %w[http https].include?(parsed.scheme)
159
+ rescue URI::InvalidURIError
160
+ nil
161
+ end
162
+
163
+ # Checks the targets of a rewrite instead of uri. The link succeeds when every target succeeds, and otherwise
164
+ # reports the first target that didn't, or the result of uri itself with fallback. The :result events of targets
165
+ # are replaced by one for the reported result, and other events, such as :retry, are forwarded.
166
+ def _check_rewrite(uri, options, rewrite)
167
+ rewritten = rewrite.targets.map(&:uri).freeze
168
+ logger.info "#{uri} : rewritten to #{rewritten.join(', ')}"
169
+ report = lambda do |event, result|
170
+ publish(event, result.dup.tap do |copy|
171
+ copy.uri = URI(uri.to_s)
172
+ copy.options = options
173
+ copy.rewritten_uris = rewritten
174
+ end)
175
+ end
176
+ outcomes = Array.new(rewrite.targets.size)
177
+ rewrite.targets.each_with_index do |target, index|
178
+ _check(target.uri.to_s, options, headers: target.headers, sink: lambda do |event, result|
179
+ next if event == :result
180
+ next report.call(event, result) unless OUTCOME_EVENTS.include?(event)
181
+
182
+ outcomes[index] = [event, result]
183
+ _finish_rewrite(uri, options, rewrite, outcomes, report) if outcomes.all?
184
+ end)
185
+ end
186
+ end
187
+
188
+ def _finish_rewrite(uri, options, rewrite, outcomes, report)
189
+ event, result = outcomes.find { |outcome, _result| outcome != :success } || outcomes.first
190
+ if event != :success && rewrite.fallback
191
+ logger.info "#{uri} : rewrite failed, checking #{uri}"
192
+ return _check(uri, options, sink: report)
193
+ end
194
+
195
+ report.call(:result, result)
196
+ report.call(event, result)
197
+ end
198
+
141
199
  def _finish_run
142
200
  prune_cache! if @cache_store&.prune?
143
201
  end
@@ -168,16 +226,18 @@ module LinkChecker
168
226
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
169
227
  end
170
228
 
171
- def execute_check(uri, options, &handler)
229
+ def execute_check(uri, options, body: false, headers: {}, sink: nil, &handler)
172
230
  tasks = Tasks.new(
173
231
  self,
174
232
  task_klass,
175
233
  uri,
176
- methods,
177
- options
234
+ body ? _body_methods : methods,
235
+ options,
236
+ headers: headers
178
237
  )
238
+ subscriber = [uri.to_s, options, sink]
179
239
  tasks.on do |event, *args|
180
- handler ? handler.call(event, *args) : publish(event, args.first)
240
+ handler ? handler.call(event, *args) : deliver(event, args.first, subscriber)
181
241
  end
182
242
  tasks.execute!
183
243
  end
@@ -186,8 +246,21 @@ module LinkChecker
186
246
  result = copy_result(cached_result, subscriber)
187
247
  result.cached = true
188
248
  result.blocked = event == :blocked
189
- publish(:result, result)
190
- publish(event, result)
249
+ deliver(:result, result, subscriber)
250
+ deliver(event, result, subscriber)
251
+ end
252
+
253
+ # Publishes a result for a submission, failing a success whose page lacks the submission's fragment.
254
+ def deliver(event, result, subscriber)
255
+ if %i[result success].include?(event)
256
+ result.missing_fragment = _missing_fragment(result, subscriber.first)
257
+ if event == :success && result.missing_fragment?
258
+ logger.info "#{result.uri} : missing fragment ##{result.missing_fragment}"
259
+ event = :failure
260
+ end
261
+ end
262
+ sink = subscriber[2]
263
+ sink ? sink.call(event, result) : publish(event, result)
191
264
  end
192
265
 
193
266
  def publish(event, result)
@@ -198,29 +271,86 @@ module LinkChecker
198
271
  callback(:complete, result) if outcome
199
272
  end
200
273
 
201
- def handle_shared_result(key, entry, uri, event, result)
274
+ def handle_shared_result(key, pending_key, entry, uri, headers, event, result)
202
275
  entry[:events] << [event, result]
203
276
  subscribers = entry[:subscribers].dup
277
+ # Find the page's fragment targets once, rather than for every copy.
278
+ result.anchors if check_fragments && %i[result success].include?(event)
204
279
  if OUTCOME_EVENTS.include?(event)
205
- @pending.delete(key) if @pending[key].equal?(entry)
206
- if %i[success blocked].include?(event) && request_key(uri) == key
207
- @successful[key] = result if deduplicate && event == :success
280
+ @pending.delete(pending_key) if @pending[pending_key].equal?(entry)
281
+ if %i[success blocked].include?(event) && request_key(uri, headers) == key
282
+ if deduplicate && event == :success && (result.body_checked? || !@successful[key]&.body_checked?)
283
+ @successful[key] = result
284
+ end
208
285
  @cache_store&.store(key, result)
209
286
  end
210
287
  end
211
- subscribers.each { |subscriber| publish(event, copy_result(result, subscriber)) }
288
+ subscribers.each { |subscriber| deliver(event, copy_result(result, subscriber), subscriber) }
289
+ end
290
+
291
+ # Whether checking uri needs the page body, which HEAD requests don't return.
292
+ def _body_required?(uri)
293
+ return true if follow_meta_refresh
294
+
295
+ parsed = URI(uri.to_s)
296
+ check_fragments && !_fragment_target(parsed, parsed.fragment).nil?
297
+ rescue URI::InvalidURIError
298
+ false
299
+ end
300
+
301
+ # The methods to use when the page body is needed: GET without HEAD, unless GET isn't configured.
302
+ def _body_methods
303
+ without_head = methods.reject { |method| method.to_s.casecmp?('HEAD') }
304
+ without_head.any? { |method| method.to_s.casecmp?('GET') } ? without_head : methods
305
+ end
306
+
307
+ # The decoded fragment to look for on uri's page, or nil when there is nothing to check: no fragment,
308
+ # #top, a text fragment, or a fragment that matches fragments_to_skip.
309
+ def _fragment_target(uri, fragment)
310
+ return if fragment.nil?
311
+
312
+ target = URI.decode_uri_component(fragment.split(':~:', 2).first.to_s)
313
+ return if target.empty? || target.casecmp?('top')
314
+
315
+ url = uri.dup.tap { |copy| copy.fragment = nil }.to_s
316
+ skip = fragments_to_skip.any? do |url_pattern, fragment_pattern|
317
+ _pattern_match?(url_pattern, url) && (_pattern_match?(fragment_pattern, target) ||
318
+ _pattern_match?(fragment_pattern, fragment))
319
+ end
320
+ target unless skip
321
+ end
322
+
323
+ def _pattern_match?(pattern, value)
324
+ pattern.is_a?(Regexp) ? pattern.match?(value) : pattern == value
325
+ end
326
+
327
+ # The fragment that the final page of a successful result doesn't contain, or nil. A redirect with its
328
+ # own fragment replaces the submitted one, as in browsers. Pages that weren't read or aren't HTML pass.
329
+ def _missing_fragment(result, submitted)
330
+ return unless check_fragments && result.http_success?
331
+
332
+ submitted = URI(submitted)
333
+ fragment = result.redirects.reverse_each.find { |hop| hop.to.fragment }&.to&.fragment || submitted.fragment
334
+ target = _fragment_target(submitted, fragment)
335
+ anchors = result.anchors if target
336
+ return if anchors.nil? || anchors.include?(target) || anchors.include?(fragment)
337
+ # GitHub prefixes the ids of rendered Markdown headings and scrolls to them with JavaScript.
338
+ return if anchors.include?("user-content-#{target}")
339
+
340
+ fragment
212
341
  end
213
342
 
214
343
  def copy_result(result, subscriber)
215
344
  result.dup.tap do |copy|
345
+ copy.missing_fragment = nil
216
346
  copy.uri = URI(subscriber.first)
217
347
  # Without redirects, the final URL is the submitted one, including its own fragment.
218
348
  copy.result_uri = result.redirects.empty? ? URI(subscriber.first) : result.result_uri.dup
219
- copy.options = subscriber.last
349
+ copy.options = subscriber[1]
220
350
  end
221
351
  end
222
352
 
223
- def request_key(uri)
353
+ def request_key(uri, rewrite_headers = {})
224
354
  parsed = URI(uri.to_s)
225
355
  return unless %w[http https].include?(parsed.scheme) && parsed.host && !parsed.userinfo
226
356
 
@@ -231,7 +361,8 @@ module LinkChecker
231
361
  attributes += %i[timeout connecttimeout read_timeout open_timeout protocol].select { |key| respond_to?(key) }
232
362
  settings = attributes.to_h { |key| [key, send(key)] }
233
363
  # Only the headers sent for this URL are part of its identity, so changing the headers of other hosts keeps it.
234
- settings[:headers] = _merge_headers([headers] + _matching_host_headers(parsed)).sort_by { |key, _value| key }
364
+ settings[:headers] = _merge_headers([headers] + _matching_host_headers(parsed) + [rewrite_headers])
365
+ .sort_by { |key, _value| key }
235
366
  settings.delete(:host_headers)
236
367
  Digest::SHA256.hexdigest(JSON.generate([task_klass.name, parsed.to_s, settings]))
237
368
  rescue URI::InvalidURIError, JSON::GeneratorError, TypeError
@@ -28,8 +28,17 @@ module LinkChecker
28
28
  rate_limit_status_codes
29
29
  rate_limit_backoff
30
30
  max_rate_limit_delay
31
+ check_fragments
32
+ fragments_to_skip
33
+ follow_meta_refresh
34
+ url_rewrites
31
35
  ].freeze
32
36
 
37
+ # GitHub renders line anchors of source files, such as #L10 or #L10-L20, with JavaScript.
38
+ DEFAULT_FRAGMENTS_TO_SKIP = {
39
+ %r{\Ahttps://github\.com/[^/]+/[^/]+/blob/} => /\AL\d+/
40
+ }.freeze
41
+
33
42
  attr_accessor(*Config::ATTRIBUTES)
34
43
 
35
44
  def reset
@@ -56,6 +65,10 @@ module LinkChecker
56
65
  self.rate_limit_status_codes = [429]
57
66
  self.rate_limit_backoff = 1
58
67
  self.max_rate_limit_delay = 30
68
+ self.check_fragments = true
69
+ self.follow_meta_refresh = false
70
+ self.url_rewrites = []
71
+ self.fragments_to_skip = DEFAULT_FRAGMENTS_TO_SKIP
59
72
  end
60
73
 
61
74
  def host_headers=(value)
@@ -68,6 +81,37 @@ module LinkChecker
68
81
  @host_headers = value.transform_keys { |host| host.is_a?(String) ? host.downcase : host }
69
82
  end
70
83
 
84
+ def url_rewrites=(value)
85
+ value ||= []
86
+ unless value.is_a?(Array) && value.all? { |rule| LinkChecker::UrlRewrites.valid_rule?(rule) }
87
+ raise ArgumentError, "Invalid url_rewrites: #{value}"
88
+ end
89
+
90
+ @url_rewrites = value.dup.freeze
91
+ end
92
+
93
+ def follow_meta_refresh=(value)
94
+ raise ArgumentError, "Invalid follow_meta_refresh: #{value}" unless [true, false].include?(value)
95
+
96
+ @follow_meta_refresh = value
97
+ end
98
+
99
+ def check_fragments=(value)
100
+ raise ArgumentError, "Invalid check_fragments: #{value}" unless [true, false].include?(value)
101
+
102
+ @check_fragments = value
103
+ end
104
+
105
+ def fragments_to_skip=(value)
106
+ value ||= {}
107
+ valid = value.is_a?(Hash) && value.all? do |url, fragment|
108
+ [url, fragment].all? { |pattern| pattern.is_a?(String) || pattern.is_a?(Regexp) }
109
+ end
110
+ raise ArgumentError, "Invalid fragments to skip: #{value}" unless valid
111
+
112
+ @fragments_to_skip = value.dup
113
+ end
114
+
71
115
  def retries=(value)
72
116
  raise ArgumentError, "Invalid number of retries: #{value}" unless value.is_a?(Integer) && value >= 0
73
117
 
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LinkChecker
4
+ # A minimal HTML start-tag scanner, enough to find fragment targets without an HTML parser dependency.
5
+ module HTML
6
+ MEDIA_TYPES = %w[text/html application/xhtml+xml].freeze
7
+
8
+ # Comments and elements whose content is raw text, which can't contain elements, including noscript in browsers
9
+ # that run scripts.
10
+ RAW_TEXT = %w[script style textarea title xmp iframe noembed noframes noscript].freeze
11
+ IGNORED = %r{<!--.*?(?:-->|\z)|<(#{RAW_TEXT.join('|')})\b[^>]*>.*?(?:</\1\s*>|\z)}mi
12
+ TAG = %r{<([a-zA-Z][^\s/>]*)((?:[^>"']|"[^"]*"|'[^']*')*)>}m
13
+ ATTRIBUTE = %r{([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?}
14
+ # Tags with an id or name attribute that has a value; the characters before a name are those that end the previous
15
+ # one in ATTRIBUTE, so a tag that ATTRIBUTE finds such an attribute in always matches.
16
+ ANCHOR_ATTRIBUTES = %r{(?:\A|[\s"'/=])(?:id|name)\s*=}i
17
+ REFRESH_ATTRIBUTES = %r{(?:\A|[\s"'/=])http-equiv\s*=}i
18
+ # Pages without this text have no refresh, and are much faster to search than to scan.
19
+ REFRESH_TEXT = /http-equiv/i
20
+ ENTITY = /&(?:#(\d+)|#[xX](\h+)|(amp|lt|gt|quot|apos));/
21
+ ENTITIES = { 'amp' => '&', 'lt' => '<', 'gt' => '>', 'quot' => '"', 'apos' => "'" }.freeze
22
+ WHITESPACE = "\t\n\f\r "
23
+
24
+ module_function
25
+
26
+ # Whether a Content-Type header value is an HTML media type.
27
+ def html?(content_type)
28
+ MEDIA_TYPES.include?(content_type.to_s.split(';').first.to_s.strip.downcase)
29
+ end
30
+
31
+ # Yields the lower-cased name and attributes of each start tag, keeping the first of duplicate attributes. With a
32
+ # filter, skips the tags whose attributes don't match it without parsing them.
33
+ def each_tag(body, filter = nil)
34
+ return enum_for(:each_tag, body, filter) unless block_given?
35
+
36
+ text = body.to_s.dup.force_encoding(Encoding::UTF_8).scrub.gsub(IGNORED, '')
37
+ text.scan(TAG) do |name, attributes|
38
+ next if filter && !filter.match?(attributes)
39
+
40
+ values = {}
41
+ attributes.scan(ATTRIBUTE) do |key, double, single, bare|
42
+ values[key.downcase] ||= unescape(double || single || bare || '')
43
+ end
44
+ yield name.downcase, values
45
+ end
46
+ end
47
+
48
+ # The fragment targets of a page: element ids and the names of <a> elements.
49
+ def anchors(body)
50
+ each_tag(body, ANCHOR_ATTRIBUTES).with_object(Set.new) do |(name, attributes), anchors|
51
+ anchors << attributes['id'] unless attributes['id'].to_s.empty?
52
+ anchors << attributes['name'] if name == 'a' && !attributes['name'].to_s.empty?
53
+ end
54
+ end
55
+
56
+ # The URL of the first valid <meta http-equiv="refresh"> of a page, or nil when it has none or refreshes itself.
57
+ def meta_refresh(body)
58
+ return unless body.to_s.b.match?(REFRESH_TEXT)
59
+
60
+ each_tag(body, REFRESH_ATTRIBUTES) do |name, attributes|
61
+ next unless name == 'meta' && attributes['http-equiv'].to_s.strip.casecmp?('refresh') && attributes['content']
62
+
63
+ # A refresh without a URL reloads the page itself, and stops later refreshes.
64
+ refresh = refresh_url(attributes['content'])
65
+ return refresh.empty? ? nil : refresh unless refresh.nil?
66
+ end
67
+ nil
68
+ end
69
+
70
+ # Parses the content of a declarative refresh, returning its URL, "" without a URL, or nil when it's invalid.
71
+ # https://html.spec.whatwg.org/multipage/semantics.html#shared-declarative-refresh-steps
72
+ def refresh_url(content)
73
+ time = /\A[#{WHITESPACE}]*[\d.]+/o.match(content)
74
+ return unless time
75
+
76
+ rest = time.post_match
77
+ return '' if rest.empty?
78
+ return unless rest.match?(/\A[;,#{WHITESPACE}]/o)
79
+
80
+ rest = rest.sub(/\A[#{WHITESPACE}]*[;,]?[#{WHITESPACE}]*/o, '')
81
+ if (prefix = /\Aurl[#{WHITESPACE}]*=[#{WHITESPACE}]*/io.match(rest))
82
+ rest = prefix.post_match
83
+ elsif rest.match?(/\Au/i)
84
+ return rest.strip
85
+ end
86
+ quote = rest[0] if ['"', "'"].include?(rest[0])
87
+ rest = rest[1..].split(quote, 2).first.to_s if quote
88
+ rest.strip
89
+ end
90
+
91
+ # Decodes numeric character references, replacing invalid code points with U+FFFD, and the predefined XML entities.
92
+ def unescape(value)
93
+ value.gsub(ENTITY) do
94
+ if Regexp.last_match(1) then Regexp.last_match(1).to_i.chr(Encoding::UTF_8)
95
+ elsif Regexp.last_match(2) then Regexp.last_match(2).to_i(16).chr(Encoding::UTF_8)
96
+ else ENTITIES[Regexp.last_match(3)]
97
+ end
98
+ rescue RangeError
99
+ "\uFFFD"
100
+ end
101
+ end
102
+ end
103
+ end
@@ -10,7 +10,7 @@ module LinkChecker
10
10
  http.read_timeout = checker.read_timeout if checker.read_timeout
11
11
  http.open_timeout = checker.open_timeout if checker.open_timeout
12
12
  request = ::Net::HTTPGenericRequest.new(method, false, true, uri)
13
- checker.request_headers_for(uri).each { |key, value| request[key] = value }
13
+ checker.request_headers_for(uri, headers).each { |key, value| request[key] = value }
14
14
  response = http.request(request)
15
15
  result! Result.new(uri, method, original_uri, request, response, options)
16
16
  end
@@ -30,6 +30,10 @@ module LinkChecker
30
30
  request
31
31
  end
32
32
 
33
+ def body
34
+ response&.body
35
+ end
36
+
33
37
  def response_headers
34
38
  response || {}
35
39
  end
@@ -46,7 +50,7 @@ module LinkChecker
46
50
  [301, 302, 303, 307, 308].include?(code)
47
51
  end
48
52
 
49
- def success?
53
+ def http_success?
50
54
  return false unless response
51
55
 
52
56
  code >= 200 && code <= 299