Class: Mechanize::HTTP::Agent

Inherits:
Object
  • Object
show all
Defined in:
lib/mechanize/http/agent.rb

Overview

An HTTP (and local disk access) user agent. This class is an implementation detail and is subject to change at any time.

Constant Summary collapse

CREDENTIAL_HEADERS =
['Authorization', 'Proxy-Authorization']
['Cookie', 'Cookie2']
POST_HEADERS =
['Content-Length', 'Content-MD5', 'Content-Type']
SYMBOL_HEADERS =

Symbols accepted as header names in the per-request headers hash, and the header each one names.

{ :etag => 'ETag', :if_modified_since => 'If-Modified-Since' }.freeze
RobotsKey =

:section: Robots

:__mechanize_get_robots__

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection_name = 'mechanize') ⇒ Agent

The connection_name can be used to segregate SSL connections. Agents with different names will not share the same persistent connection.



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/mechanize/http/agent.rb', line 149

def initialize(connection_name = 'mechanize')
  @allowed_error_codes      = []
  @conditional_requests     = true
  @context                  = nil
  @content_encoding_hooks   = []
  @cookie_jar               = Mechanize::CookieJar.new
  @follow_meta_refresh      = false
  @follow_meta_refresh_self = false
  @gzip_enabled             = true
  @history                  = Mechanize::History.new
  @ignore_bad_chunking      = false
  @keep_alive               = true
  @max_file_buffer          = 100_000 # 5MB for response bodies
  @open_timeout             = nil
  @post_connect_hooks       = []
  @pre_connect_hooks        = []
  @read_timeout             = nil
  @redirect_ok              = true
  @redirection_limit        = 20
  @request_headers          = {}
  @robots                   = false
  @robots_mutex             = Mutex.new
  @user_agent               = nil
  @webrobots                = nil
  @write_timeout            = nil

  # HTTP Authentication
  @auth_store           = Mechanize::HTTP::AuthStore.new
  @authenticate_parser  = Mechanize::HTTP::WWWAuthenticateParser.new
  @authenticate_methods = Hash.new do |methods, uri|
    methods[uri] = Hash.new do |realms, auth_scheme|
      realms[auth_scheme] = []
    end
  end
  @digest_auth          = Net::HTTP::DigestAuth.new
  @digest_challenges    = {}

  # SSL
  @pass = nil

  @scheme_handlers = Hash.new { |h, scheme|
    h[scheme] = lambda { |link, page|
      raise Mechanize::UnsupportedSchemeError.new(scheme, link)
    }
  }

  @scheme_handlers['http']      = lambda { |link, page| link }
  @scheme_handlers['https']     = @scheme_handlers['http']
  @scheme_handlers['relative']  = @scheme_handlers['http']
  @scheme_handlers['file']      = @scheme_handlers['http']

  @http =
    if defined?(Net::HTTP::Persistent::DEFAULT_POOL_SIZE)
      Net::HTTP::Persistent.new(name: connection_name)
    else
      # net-http-persistent < 3.0
      Net::HTTP::Persistent.new(connection_name)
    end
  @http.idle_timeout = 5
  @http.keep_alive   = 300
end

Instance Attribute Details

#allowed_error_codesObject

List of error codes (in String or Integer) to handle without raising Mechanize::ResponseCodeError, defaulted to an empty array. Note that 2xx, 3xx and 401 status codes will be handled without checking this list.



89
90
91
# File 'lib/mechanize/http/agent.rb', line 89

def allowed_error_codes
  @allowed_error_codes
end

#auth_storeObject (readonly)

:section: HTTP Authentication



56
57
58
# File 'lib/mechanize/http/agent.rb', line 56

def auth_store
  @auth_store
end

#authenticate_methodsObject (readonly)

:nodoc:



57
58
59
# File 'lib/mechanize/http/agent.rb', line 57

def authenticate_methods
  @authenticate_methods
end

#conditional_requestsObject

Disables If-Modified-Since conditional requests (enabled by default)



23
24
25
# File 'lib/mechanize/http/agent.rb', line 23

def conditional_requests
  @conditional_requests
end

#content_encoding_hooksObject (readonly)

A list of hooks to call to handle the content-encoding of a request.



52
53
54
# File 'lib/mechanize/http/agent.rb', line 52

def content_encoding_hooks
  @content_encoding_hooks
end

#contextObject

The context parses responses into pages



130
131
132
# File 'lib/mechanize/http/agent.rb', line 130

def context
  @context
end

The cookies for this agent



121
122
123
# File 'lib/mechanize/http/agent.rb', line 121

def cookie_jar
  @cookie_jar
end

#digest_challengesObject (readonly)

:nodoc:



58
59
60
# File 'lib/mechanize/http/agent.rb', line 58

def digest_challenges
  @digest_challenges
end

#follow_meta_refreshObject

Follow HTML meta refresh and HTTP Refresh. If set to :anywhere meta refresh tags outside of the head element will be followed.



64
65
66
# File 'lib/mechanize/http/agent.rb', line 64

def follow_meta_refresh
  @follow_meta_refresh
end

#follow_meta_refresh_selfObject

Follow an HTML meta refresh that has no "url=" in the content attribute.

Defaults to false to prevent infinite refresh loops.



69
70
71
# File 'lib/mechanize/http/agent.rb', line 69

def follow_meta_refresh_self
  @follow_meta_refresh_self
end

#gzip_enabledObject

Is gzip compression of requests enabled?



26
27
28
# File 'lib/mechanize/http/agent.rb', line 26

def gzip_enabled
  @gzip_enabled
end

#historyObject

history of requests made



39
40
41
# File 'lib/mechanize/http/agent.rb', line 39

def history
  @history
end

#httpObject (readonly)

:nodoc:



132
133
134
# File 'lib/mechanize/http/agent.rb', line 132

def http
  @http
end

#ignore_bad_chunkingObject

When set to true mechanize will ignore an EOF during chunked transfer encoding so long as at least one byte was received. Be careful when enabling this as it may cause data loss.



137
138
139
# File 'lib/mechanize/http/agent.rb', line 137

def ignore_bad_chunking
  @ignore_bad_chunking
end

#keep_aliveObject

Set to false to disable HTTP/1.1 keep-alive requests



107
108
109
# File 'lib/mechanize/http/agent.rb', line 107

def keep_alive
  @keep_alive
end

#max_file_bufferObject

Responses larger than this will be written to a Tempfile instead of stored in memory. Setting this to nil disables creation of Tempfiles.



125
126
127
# File 'lib/mechanize/http/agent.rb', line 125

def max_file_buffer
  @max_file_buffer
end

#open_timeoutObject

Length of time to wait until a connection is opened in seconds



110
111
112
# File 'lib/mechanize/http/agent.rb', line 110

def open_timeout
  @open_timeout
end

#passObject

OpenSSL key password



102
103
104
# File 'lib/mechanize/http/agent.rb', line 102

def pass
  @pass
end

#post_connect_hooksObject (readonly)

A list of hooks to call after retrieving a response. Hooks are called with the agent and the response returned.



45
46
47
# File 'lib/mechanize/http/agent.rb', line 45

def post_connect_hooks
  @post_connect_hooks
end

#pre_connect_hooksObject (readonly)

A list of hooks to call before making a request. Hooks are called with the agent and the request to be performed.



49
50
51
# File 'lib/mechanize/http/agent.rb', line 49

def pre_connect_hooks
  @pre_connect_hooks
end

#read_timeoutObject

Length of time to attempt to read data from the server



113
114
115
# File 'lib/mechanize/http/agent.rb', line 113

def read_timeout
  @read_timeout
end

#redirect_okObject

Controls how this agent deals with redirects. The following values are allowed:

:all, true:: All 3xx redirects are followed (default) :permanent:: Only 301 Moved Permanently redirects are followed

false

No redirects are followed



77
78
79
# File 'lib/mechanize/http/agent.rb', line 77

def redirect_ok
  @redirect_ok
end

#redirection_limitObject

Maximum number of redirects to follow



80
81
82
# File 'lib/mechanize/http/agent.rb', line 80

def redirection_limit
  @redirection_limit
end

#request_headersObject

A hash of request headers to be used for every request. Headers named in CREDENTIAL_HEADERS or COOKIE_HEADERS are withheld from a request that follows a redirect across an origin; see #crosses_origin?.



31
32
33
# File 'lib/mechanize/http/agent.rb', line 31

def request_headers
  @request_headers
end

#robotsObject

When true, this agent will consult the site's robots.txt for each access.



94
95
96
# File 'lib/mechanize/http/agent.rb', line 94

def robots
  @robots
end

#robots_mutexObject (readonly)

Mutex used when fetching robots.txt



97
98
99
# File 'lib/mechanize/http/agent.rb', line 97

def robots_mutex
  @robots_mutex
end

#scheme_handlersObject

Handlers for various URI schemes



140
141
142
# File 'lib/mechanize/http/agent.rb', line 140

def scheme_handlers
  @scheme_handlers
end

#user_agentObject

The User-Agent header to send



34
35
36
# File 'lib/mechanize/http/agent.rb', line 34

def user_agent
  @user_agent
end

#write_timeoutObject

Length of time to attempt to write data to the server



116
117
118
# File 'lib/mechanize/http/agent.rb', line 116

def write_timeout
  @write_timeout
end

Instance Method Details

#add_auth(uri, user, password, realm = nil, domain = nil) ⇒ Object

Adds credentials user, pass for uri. If realm is set the credentials are used only for that realm. If realm is not set the credentials become the default for any realm on that URI.

domain and realm are exclusive as NTLM does not follow RFC 2617. If domain is given it is only used for NTLM authentication.



219
220
221
# File 'lib/mechanize/http/agent.rb', line 219

def add_auth uri, user, password, realm = nil, domain = nil
  @auth_store.add_auth uri, user, password, realm, domain
end

#add_default_auth(user, password, domain = nil) ⇒ Object

USE OF add_default_auth IS NOT RECOMMENDED AS IT MAY EXPOSE PASSWORDS TO THIRD PARTIES

Adds credentials user, pass as the default authentication credentials. If no other credentials are available these will be returned from credentials_for.

If domain is given it is only used for NTLM authentication.



233
234
235
# File 'lib/mechanize/http/agent.rb', line 233

def add_default_auth user, password, domain = nil # :nodoc:
  @auth_store.add_default_auth user, password, domain
end

#auto_io(name, read_size, input_io) ⇒ Object

Creates a new output IO by reading input_io in read_size chunks. If the output is over the max_file_buffer size a Tempfile with name is created.

If a block is provided, each chunk of input_io is yielded for further processing.



1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
# File 'lib/mechanize/http/agent.rb', line 1315

def auto_io name, read_size, input_io
  out_io = StringIO.new.set_encoding(Encoding::BINARY)

  until input_io.eof? do
    if StringIO === out_io and use_tempfile? out_io.size then
      new_io = make_tempfile name
      new_io.write out_io.string
      out_io = new_io
    end

    chunk = input_io.read read_size
    chunk = yield chunk if block_given?

    out_io.write chunk
  end

  out_io.rewind

  out_io
end

#backObject

Equivalent to the browser back button. Returns the most recent page visited.



390
391
392
# File 'lib/mechanize/http/agent.rb', line 390

def back
  @history.pop
end

#ca_fileObject

Path to an OpenSSL CA certificate file



1206
1207
1208
# File 'lib/mechanize/http/agent.rb', line 1206

def ca_file
  @http.ca_file
end

#ca_file=(ca_file) ⇒ Object

Sets the path to an OpenSSL CA certificate file



1211
1212
1213
# File 'lib/mechanize/http/agent.rb', line 1211

def ca_file= ca_file
  @http.ca_file = ca_file
end

#canonical_header_name(field) ⇒ Object



623
624
625
# File 'lib/mechanize/http/agent.rb', line 623

def canonical_header_name field
  (SYMBOL_HEADERS[field] || field).to_s.downcase
end

#cert_storeObject

The SSL certificate store used for validating connections



1216
1217
1218
# File 'lib/mechanize/http/agent.rb', line 1216

def cert_store
  @http.cert_store
end

#cert_store=(cert_store) ⇒ Object

Sets the SSL certificate store used for validating connections



1221
1222
1223
# File 'lib/mechanize/http/agent.rb', line 1221

def cert_store= cert_store
  @http.cert_store = cert_store
end

#certificateObject

The client X509 certificate



1226
1227
1228
# File 'lib/mechanize/http/agent.rb', line 1226

def certificate
  @http.certificate
end

#certificate=(certificate) ⇒ Object

Sets the client certificate to given X509 certificate. If a path is given the certificate will be loaded and set.



1232
1233
1234
1235
1236
1237
1238
1239
1240
# File 'lib/mechanize/http/agent.rb', line 1232

def certificate= certificate
  certificate = if OpenSSL::X509::Certificate === certificate then
                  certificate
                else
                  OpenSSL::X509::Certificate.new File.read certificate
                end

  @http.certificate = certificate
end

#connection_for(uri) ⇒ Object

:section: Request



453
454
455
456
457
458
459
460
# File 'lib/mechanize/http/agent.rb', line 453

def connection_for uri
  case uri.scheme.downcase
  when 'http', 'https' then
    return @http
  when 'file' then
    return Mechanize::FileConnection.new
  end
end

#content_encoding_brotli(body_io) ⇒ Object

Decodes a Brotli-encoded body_io

(Experimental, CRuby only) Although Mechanize will never request a Brotli-encoded response via accept-encoding, buggy servers may return brotli-encoded responses anyway. Let's try to handle that case if the Brotli gem is loaded.

If you need to handle Brotli-encoded responses, install the 'brotli' gem and require it in your application. If the Brotli constant is defined, Mechanize will attempt to use it to inflate the response.



533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/mechanize/http/agent.rb', line 533

def content_encoding_brotli(body_io)
  log.debug('deflate brotli body') if log

  unless defined?(::Brotli)
    raise Mechanize::Error, "cannot deflate brotli-encoded response. Please install and require the 'brotli' gem."
  end

  begin
    return StringIO.new(Brotli.inflate(body_io.read))
  rescue Brotli::Error
    log.error("unable to brotli-inflate response") if log
    raise Mechanize::Error, "error inflating brotli-encoded response."
  end
ensure
  body_io.close
end

#content_encoding_gunzip(body_io) ⇒ Object

Decodes a gzip-encoded body_io. If it cannot be decoded, inflate is tried followed by raising an error.



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/mechanize/http/agent.rb', line 471

def content_encoding_gunzip body_io
  log.debug('gzip response') if log

  zio = Zlib::GzipReader.new body_io
  out_io = auto_io 'mechanize-gunzip', 16384, zio
  zio.finish

  return out_io
rescue Zlib::Error => gz_error
  log.warn "unable to gunzip response: #{gz_error} (#{gz_error.class})" if
    log

  body_io.rewind
  body_io.read 10

  begin
    log.warn "trying raw inflate on response" if log
    return inflate body_io, -Zlib::MAX_WBITS
  rescue Zlib::Error => e
    log.error "unable to inflate response: #{e} (#{e.class})" if log
    raise
  end
ensure
  # do not close a second time if we failed the first time
  zio.close if zio and !(zio.closed? or gz_error)
  body_io.close unless body_io.closed?
end

#content_encoding_inflate(body_io) ⇒ Object

Decodes a deflate-encoded body_io. If it cannot be decoded, raw inflate is tried followed by raising an error.



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/mechanize/http/agent.rb', line 503

def content_encoding_inflate body_io
  log.debug('deflate body') if log

  return inflate body_io
rescue Zlib::Error
  log.error('unable to inflate response, trying raw deflate') if log

  body_io.rewind

  begin
    return inflate body_io, -Zlib::MAX_WBITS
  rescue Zlib::Error => e
    log.error("unable to inflate response: #{e}") if log
    raise
  end
ensure
  body_io.close
end

#content_encoding_zstd(body_io) ⇒ Object

Decodes a Zstd-encoded body_io

(Experimental, CRuby only) Although Mechanize will never request a zstd-encoded response via accept-encoding, buggy servers may return zstd-encoded responses, or you might need to inform the zstd keyword on your Accept-Encoding headers. Let's try to handle those cases if the Zstd gem is loaded.

If you need to handle Zstd-encoded responses, install the 'zstd-ruby' gem and require it in your application. If the Zstd constant is defined, Mechanize will attempt to use it to inflate the response.



562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# File 'lib/mechanize/http/agent.rb', line 562

def content_encoding_zstd(body_io)
  log.debug('deflate zstd body') if log

  unless defined?(::Zstd)
    raise Mechanize::Error, "cannot deflate zstd-encoded response. Please install and require the 'zstd-ruby' gem."
  end

  begin
    return StringIO.new(Zstd.decompress(body_io.read))
  rescue StandardError
    log.error("unable to zstd#decompress response") if log
    raise Mechanize::Error, "error decompressing zstd-encoded response."
  end
ensure
  body_io.close
end

#crosses_origin?(from_uri, to_uri) ⇒ Boolean

Does moving from from_uri to to_uri cross an origin? An origin is the scheme, host and port together; see RFC 6454.

Returns:

  • (Boolean)


641
642
643
644
645
# File 'lib/mechanize/http/agent.rb', line 641

def crosses_origin? from_uri, to_uri
  to_uri.scheme != from_uri.scheme ||
    to_uri.host != from_uri.host ||
    to_uri.port != from_uri.port
end

#current_pageObject

Returns the latest page loaded by the agent



397
398
399
# File 'lib/mechanize/http/agent.rb', line 397

def current_page
  @history.last
end

#disable_keep_alive(request) ⇒ Object



579
580
581
# File 'lib/mechanize/http/agent.rb', line 579

def disable_keep_alive request
  request['connection'] = 'close' unless @keep_alive
end

#drop_after_redirect?(name, crossed_origin) ⇒ Boolean

Should the header named name be withheld from a request issued after a redirect that crossed an origin?

Returns:

  • (Boolean)


649
650
651
# File 'lib/mechanize/http/agent.rb', line 649

def drop_after_redirect? name, crossed_origin
  crossed_origin && match_header?(name, CREDENTIAL_HEADERS + COOKIE_HEADERS)
end

#enable_gzip(request) ⇒ Object



583
584
585
586
587
588
589
# File 'lib/mechanize/http/agent.rb', line 583

def enable_gzip request
  request['accept-encoding'] = if @gzip_enabled
                                 'gzip,deflate,identity'
                               else
                                 'identity'
                               end
end

#fetch(uri, method = :get, headers = {}, params = [], referer = current_page, redirects = 0, apply_request_headers = true) ⇒ Object

Retrieves uri and parses it into a page or other object according to PluggableParser. If the URI is an HTTP or HTTPS scheme URI the given HTTP method is used to retrieve it, along with the HTTP headers, request params and HTTP referer.

The final URI to access is built with uri and params, the latter of which is formatted into a string using Mechanize::Util.build_query_string, which see.

redirects tracks the number of redirects experienced when retrieving the page. If it is over the redirection_limit an error will be raised.

apply_request_headers merges #request_headers into headers. It is true for a request the caller initiated and false for one continuing an operation already under way, such as following a redirect, where headers already carries the merged set minus anything withheld along the way.



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/mechanize/http/agent.rb', line 255

def fetch uri, method = :get, headers = {}, params = [],
          referer = current_page, redirects = 0, apply_request_headers = true

  # Fold the agent defaults into the caller's headers once, at the start of
  # the operation, so that from here on a single hash carries every header
  # and #response_redirect can drop a credential from it for good.  Requests
  # continuing an operation pass false and supply the hash they were given.
  headers = merge_request_headers headers if apply_request_headers

  referer_uri = referer ? referer.uri : nil
  uri         = resolve uri, referer
  uri, params = resolve_parameters uri, method, params
  request     = http_request uri, method, params
  connection  = connection_for uri

  request_auth             request, uri
  disable_keep_alive       request
  enable_gzip              request
  request_language_charset request
  request_cookies          request, uri
  request_host             request, uri
  request_referer          request, uri, referer_uri
  request_user_agent       request
  request_add_headers      request, headers
  pre_connect              request

  # Consult robots.txt
  if robots && uri.is_a?(URI::HTTP)
    robots_allowed?(uri) or raise Mechanize::RobotsDisallowedError.new(uri)
  end

  # Add If-Modified-Since if page is in history
  if page = visited_page(uri) and last_modified = page.response['Last-Modified']
    request['If-Modified-Since'] = last_modified
  end if @conditional_requests

  # Specify timeouts if supplied and our connection supports them
  if @open_timeout && connection.respond_to?(:open_timeout=)
    connection.open_timeout = @open_timeout
  end
  if @read_timeout && connection.respond_to?(:read_timeout=)
    connection.read_timeout = @read_timeout
  end
  if @write_timeout && connection.respond_to?(:write_timeout=)
    connection.write_timeout = @write_timeout
  end

  request_log request

  response_body_io = nil

  # Send the request
  begin
    response = connection.request(uri, request) { |res|
      response_log res

      response_body_io = response_read res, request, uri

      res
    }
  rescue Mechanize::ChunkedTerminationError => e
    raise unless @ignore_bad_chunking

    response = e.response
    response_body_io = e.body_io
  end

  hook_content_encoding response, uri, response_body_io

  response_body_io = response_content_encoding response, response_body_io if
    request.response_body_permitted?

  post_connect uri, response, response_body_io

  page = response_parse response, response_body_io, uri

  response_cookies response, uri, page

  meta = response_follow_meta_refresh response, uri, page, redirects, headers
  return meta if meta

  if robots && page.is_a?(Mechanize::Page)
    page.parser.noindex? and raise Mechanize::RobotsDisallowedError.new(uri)
  end

  case response
  when Net::HTTPSuccess
    page
  when Mechanize::FileResponse
    page
  when Net::HTTPNotModified
    log.debug("Got cached page") if log
    visited_page(uri) || page
  when Net::HTTPRedirection
    response_redirect response, method, page, redirects, headers, referer
  when Net::HTTPUnauthorized
    response_authenticate(response, page, uri, request, headers, params,
                          referer)
  else
    if @allowed_error_codes.any? {|code| code.to_s == page.code} then
      page
    else
      raise Mechanize::ResponseCodeError.new(page, 'unhandled response')
    end
  end
end

#get_meta_refresh(response, uri, page) ⇒ Object

:section: Response



840
841
842
843
844
845
846
847
848
849
850
851
852
853
# File 'lib/mechanize/http/agent.rb', line 840

def get_meta_refresh response, uri, page
  return nil unless @follow_meta_refresh

  if page.respond_to?(:meta_refresh) and
     (redirect = page.meta_refresh.first) then
    [redirect.delay, redirect.href] unless
      not @follow_meta_refresh_self and redirect.link_self
  elsif refresh = response['refresh']
    delay, href, link_self = Mechanize::Page::MetaRefresh.parse refresh, uri
    raise Mechanize::Error, 'Invalid refresh http header' unless delay
    [delay.to_f, href] unless
      not @follow_meta_refresh_self and link_self
  end
end

#get_robots(uri) ⇒ Object

:nodoc:



1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
# File 'lib/mechanize/http/agent.rb', line 1140

def get_robots(uri) # :nodoc:
  robots_mutex.synchronize do
    Thread.current[RobotsKey] = true
    begin
      fetch(uri, :get, {}, [], current_page, 0, false).body
    rescue Mechanize::ResponseCodeError => e
      case e.response_code
      when /\A4\d\d\z/
        ''
      else
        raise e
      end
    rescue Mechanize::RedirectLimitReachedError
      ''
    ensure
      Thread.current[RobotsKey] = false
    end
  end
end

#hook_content_encoding(response, uri, response_body_io) ⇒ Object

:section: Hooks



418
419
420
421
422
# File 'lib/mechanize/http/agent.rb', line 418

def hook_content_encoding response, uri, response_body_io
  @content_encoding_hooks.each do |hook|
    hook.call self, uri, response, response_body_io
  end
end

#http_request(uri, method, params = nil) ⇒ Object



591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'lib/mechanize/http/agent.rb', line 591

def http_request uri, method, params = nil
  case uri.scheme.downcase
  when 'http', 'https' then
    klass = Net::HTTP.const_get(method.to_s.capitalize)

    request ||= klass.new(uri.request_uri)
    request.body = params.first if params

    request
  when 'file' then
    Mechanize::FileRequest.new uri
  end
end

#idle_timeoutObject

Reset connections that have not been used in this many seconds



1296
1297
1298
# File 'lib/mechanize/http/agent.rb', line 1296

def idle_timeout
  @http.idle_timeout
end

#idle_timeout=(timeout) ⇒ Object

Sets the connection idle timeout for persistent connections



1301
1302
1303
# File 'lib/mechanize/http/agent.rb', line 1301

def idle_timeout= timeout
  @http.idle_timeout = timeout
end

#inflate(compressed, window_bits = nil) ⇒ Object



1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
# File 'lib/mechanize/http/agent.rb', line 1336

def inflate compressed, window_bits = nil
  inflate = Zlib::Inflate.new window_bits

  out_io = auto_io 'mechanize-inflate', 1024, compressed do |chunk|
    inflate.inflate chunk
  end

  inflate.finish

  out_io
ensure
  inflate.close if inflate.finished?
end

#logObject



1350
1351
1352
# File 'lib/mechanize/http/agent.rb', line 1350

def log
  @context.log
end

#make_tempfile(name) ⇒ Object



1394
1395
1396
1397
1398
1399
# File 'lib/mechanize/http/agent.rb', line 1394

def make_tempfile name
  io = Tempfile.new name
  io.unlink
  io.binmode
  io
end

#match_header?(name, candidates) ⇒ Boolean

Returns:

  • (Boolean)


653
654
655
# File 'lib/mechanize/http/agent.rb', line 653

def match_header? name, candidates
  candidates.any? { |candidate| name.to_s.casecmp?(candidate) }
end

#max_historyObject

Returns the maximum size for the history stack.



402
403
404
# File 'lib/mechanize/http/agent.rb', line 402

def max_history
  @history.max_size
end

#max_history=(length) ⇒ Object

Set the maximum size for the history stack.



407
408
409
# File 'lib/mechanize/http/agent.rb', line 407

def max_history=(length)
  @history.max_size = length
end

#merge_request_headers(headers) ⇒ Object

The agent defaults, with headers applied on top. A header in headers replaces an agent default naming the same header, whatever the spelling, because header names are case-insensitive and the agent's keys may be symbols.



609
610
611
612
613
614
615
616
617
618
619
620
621
# File 'lib/mechanize/http/agent.rb', line 609

def merge_request_headers headers
  merged = {}

  @request_headers.each { |field, value| merged[field.to_s] = value }

  headers.each do |field, value|
    name = canonical_header_name field
    merged.delete_if { |existing, _| canonical_header_name(existing) == name }
    merged[field] = value
  end

  merged
end

#post_connect(uri, response, body_io) ⇒ Object

Invokes hooks added to post_connect_hooks after a response is returned and the response body is handled.

Yields the context, the uri for the request, the response and the response body.



431
432
433
434
435
436
437
438
439
# File 'lib/mechanize/http/agent.rb', line 431

def post_connect uri, response, body_io # :yields: agent, uri, response, body
  @post_connect_hooks.each do |hook|
    begin
      hook.call self, uri, response, body_io.read
    ensure
      body_io.rewind
    end
  end
end

#pre_connect(request) ⇒ Object

Invokes hooks added to pre_connect_hooks before a request is made. Yields the agent and the request that will be performed to each hook.



445
446
447
448
449
# File 'lib/mechanize/http/agent.rb', line 445

def pre_connect request # :yields: agent, request
  @pre_connect_hooks.each do |hook|
    hook.call self, request
  end
end

#private_keyObject

An OpenSSL private key or the path to a private key



1243
1244
1245
# File 'lib/mechanize/http/agent.rb', line 1243

def private_key
  @http.private_key
end

#private_key=(private_key) ⇒ Object

Sets the client's private key



1248
1249
1250
1251
1252
1253
1254
1255
1256
# File 'lib/mechanize/http/agent.rb', line 1248

def private_key= private_key
  private_key = if OpenSSL::PKey::PKey === private_key then
                  private_key
                else
                  OpenSSL::PKey::RSA.new File.read(private_key), @pass
                end

  @http.private_key = private_key
end

#proxy_uriObject

URI for a proxy connection



364
365
366
# File 'lib/mechanize/http/agent.rb', line 364

def proxy_uri
  @http.proxy_uri
end

#request_add_headers(request, headers = {}) ⇒ Object



627
628
629
630
631
632
633
634
635
636
637
# File 'lib/mechanize/http/agent.rb', line 627

def request_add_headers request, headers = {}
  headers.each do |field, value|
    if Symbol === field then
      name = SYMBOL_HEADERS[field] or
        raise ArgumentError, "unknown header symbol #{field}"
      request[name] = value
    else
      request[field] = value
    end
  end
end

#request_auth(request, uri) ⇒ Object



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/mechanize/http/agent.rb', line 657

def request_auth request, uri
  base_uri = uri + '/'
  base_uri.user     &&= nil
  base_uri.password &&= nil
  schemes = @authenticate_methods[base_uri]

  if realm = schemes[:digest].find { |r| r.uri == base_uri } then
    request_auth_digest request, uri, realm, base_uri, false
  elsif realm = schemes[:iis_digest].find { |r| r.uri == base_uri } then
    request_auth_digest request, uri, realm, base_uri, true
  elsif realm = schemes[:basic].find { |r| r.uri == base_uri } then
    user, password, = @auth_store.credentials_for uri, realm.realm
    request.basic_auth user, password
  end
end

#request_auth_digest(request, uri, realm, base_uri, iis) ⇒ Object



673
674
675
676
677
678
679
680
# File 'lib/mechanize/http/agent.rb', line 673

def request_auth_digest request, uri, realm, base_uri, iis
  challenge = @digest_challenges[realm]

  uri.user, uri.password, = @auth_store.credentials_for uri, realm.realm

  auth = @digest_auth.auth_header uri, challenge.to_s, request.method, iis
  request['Authorization'] = auth
end

#request_cookies(request, uri) ⇒ Object



682
683
684
685
686
687
688
689
690
# File 'lib/mechanize/http/agent.rb', line 682

def request_cookies request, uri
  return if @cookie_jar.empty? uri

  cookies = @cookie_jar.cookies uri

  return if cookies.empty?

  request.add_field 'Cookie', cookies.join('; ')
end

#request_host(request, uri) ⇒ Object



692
693
694
695
696
697
# File 'lib/mechanize/http/agent.rb', line 692

def request_host request, uri
  port = [80, 443].include?(uri.port.to_i) ? nil : uri.port
  host = uri.host

  request['Host'] = [host, port].compact.join ':'
end

#request_language_charset(request) ⇒ Object



699
700
701
# File 'lib/mechanize/http/agent.rb', line 699

def request_language_charset request
  request['accept-language'] = 'en-us,en;q=0.5'
end

#request_log(request) ⇒ Object

Log specified headers for the request



704
705
706
707
708
709
710
711
712
# File 'lib/mechanize/http/agent.rb', line 704

def request_log request
  return unless log

  log.info("#{request.class}: #{request.path}")

  request.each_header do |k, v|
    log.debug("request-header: #{k} => #{v}")
  end
end

#request_referer(request, uri, referer) ⇒ Object

Sets a Referer header. Fragment part is removed as demanded by RFC 2616 14.36, and user information part is removed just like major browsers do.



717
718
719
720
721
722
723
724
725
726
# File 'lib/mechanize/http/agent.rb', line 717

def request_referer request, uri, referer
  return unless referer
  return if 'https'.casecmp(referer.scheme) == 0 and
            'https'.casecmp(uri.scheme) != 0
  if referer.fragment || referer.user || referer.password
    referer = referer.dup
    referer.fragment = referer.user = referer.password = nil
  end
  request['Referer'] = referer
end

#request_user_agent(request) ⇒ Object



728
729
730
# File 'lib/mechanize/http/agent.rb', line 728

def request_user_agent request
  request['User-Agent'] = @user_agent if @user_agent
end

#resetObject



1408
1409
1410
1411
# File 'lib/mechanize/http/agent.rb', line 1408

def reset
  @cookie_jar.clear
  @history.clear
end

#resolve(uri, referer = current_page) ⇒ Object



732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
# File 'lib/mechanize/http/agent.rb', line 732

def resolve(uri, referer = current_page)
  referer_uri = referer && referer.uri
  if uri.is_a?(URI)
    uri = uri.dup
  elsif uri.nil?
    if referer_uri
      return referer_uri
    end
    raise ArgumentError, "absolute URL needed (not nil)"
  else
    url = uri.to_s.strip
    if url.empty?
      if referer_uri
        return referer_uri.dup.tap { |u| u.fragment = nil }
      end
      raise ArgumentError, "absolute URL needed (not #{uri.inspect})"
    end

    url.gsub!(/[^#{0.chr}-#{126.chr}]/o) { |match|
      Mechanize::Util.uri_escape(match)
    }

    escaped_url = Mechanize::Util.html_unescape(
      url.split(/((?:%[0-9A-Fa-f]{2})+|#)/).each_slice(2).map { |x, y|
        "#{WEBrick::HTTPUtils.escape(x)}#{y}"
      }.join('')
    )

    begin
      uri = URI.parse(escaped_url)
    rescue
      uri = URI.parse(WEBrick::HTTPUtils.escape(escaped_url))
    end
  end

  uri.host = referer_uri.host if referer_uri && URI::HTTP === uri && uri.host.nil?

  scheme = uri.relative? ? 'relative' : uri.scheme.downcase
  uri = @scheme_handlers[scheme].call(uri, referer)

  if uri.relative?
    raise ArgumentError, "absolute URL needed (not #{uri})" unless
      referer_uri

    if referer.respond_to?(:bases) && referer.parser &&
        (lbase = referer.bases.last) && lbase.uri && lbase.uri.absolute?
      base = lbase
    else
      base = nil
    end

    base = referer_uri + (base ? base.uri : referer_uri)

    # Workaround for URI's bug in that it squashes consecutive
    # slashes.  See #304.
    if uri.path.match(%r{\A(.*?/)(?!/\.\.?(?!/))(/.*)\z}i)
      uri = URI((base + $1).to_s + $2)
    else
      uri = base + uri
    end

    # Strip initial "/.." bits from the path
    uri.path.sub!(/^(\/\.\.)+(?=\/)/, '')
  end

  unless ['http', 'https', 'file'].include?(uri.scheme.downcase)
    raise ArgumentError, "unsupported scheme: #{uri.scheme}"
  end

  case uri.path
  when nil
    raise ArgumentError, "hierarchical URL needed (not #{uri})"
  when ''.freeze
    uri.path = '/'
  end

  uri
end

#resolve_parameters(uri, method, parameters) ⇒ Object



823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'lib/mechanize/http/agent.rb', line 823

def resolve_parameters uri, method, parameters
  case method
  when :head, :get, :delete, :trace then
    if parameters and parameters.length > 0
      uri.query ||= ''
      uri.query << '&' if uri.query.length > 0
      uri.query << Mechanize::Util.build_query_string(parameters)
    end

    return uri, nil
  end

  return uri, parameters
end

#response_authenticate(response, page, uri, request, headers, params, referer) ⇒ Object



855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
# File 'lib/mechanize/http/agent.rb', line 855

def response_authenticate(response, page, uri, request, headers, params,
                          referer)
  www_authenticate = response['www-authenticate']

  unless www_authenticate = response['www-authenticate'] then
    message = 'WWW-Authenticate header missing in response'
    raise Mechanize::UnauthorizedError.new(page, nil, message)
  end

  challenges = @authenticate_parser.parse www_authenticate

  unless @auth_store.credentials? uri, challenges then
    message = "no credentials found, provide some with #add_auth"
    raise Mechanize::UnauthorizedError.new(page, challenges, message)
  end

  if challenge = challenges.find { |c| c.scheme =~ /^Digest$/i } then
    realm = challenge.realm uri

    auth_scheme = if response['server'] =~ /Microsoft-IIS/ then
                    :iis_digest
                  else
                    :digest
                  end

    existing_realms = @authenticate_methods[realm.uri][auth_scheme]

    if existing_realms.include? realm
      message = 'Digest authentication failed'
      raise Mechanize::UnauthorizedError.new(page, challenges, message)
    end

    existing_realms << realm
    @digest_challenges[realm] = challenge
  elsif challenge = challenges.find { |c| c.scheme == 'NTLM' } then
    existing_realms = @authenticate_methods[uri + '/'][:ntlm]

    if existing_realms.include?(realm) and not challenge.params then
      message = 'NTLM authentication failed'
      raise Mechanize::UnauthorizedError.new(page, challenges, message)
    end

    existing_realms << realm

    if challenge.params then
      type_2 = Net::NTLM::Message.decode64 challenge.params

      user, password, domain = @auth_store.credentials_for uri, nil

      type_3 = type_2.response({ :user => user, :password => password,
                                 :domain => domain },
                               { :ntlmv2 => true }).encode64

      headers['Authorization'] = "NTLM #{type_3}"
    else
      type_1 = Net::NTLM::Message::Type1.new.encode64
      headers['Authorization'] = "NTLM #{type_1}"
    end
  elsif challenge = challenges.find { |c| c.scheme == 'Basic' } then
    realm = challenge.realm uri

    existing_realms = @authenticate_methods[realm.uri][:basic]

    if existing_realms.include? realm then
      message = 'Basic authentication failed'
      raise Mechanize::UnauthorizedError.new(page, challenges, message)
    end

    existing_realms << realm
  else
    message = 'unsupported authentication scheme'
    raise Mechanize::UnauthorizedError.new(page, challenges, message)
  end

  fetch uri, request.method.downcase.to_sym, headers, params, referer, 0, false
end

#response_content_encoding(response, body_io) ⇒ Object



932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
# File 'lib/mechanize/http/agent.rb', line 932

def response_content_encoding response, body_io
  length = response.content_length ||
    case body_io
    when Tempfile, IO then
      body_io.stat.size
    else
      body_io.length
    end

  return body_io if length.zero?

  out_io = case response['Content-Encoding']
           when nil, 'none', '7bit', 'identity', "" then
             body_io
           when 'deflate' then
             content_encoding_inflate body_io
           when 'gzip', 'x-gzip' then
             content_encoding_gunzip body_io
           when 'br' then
             content_encoding_brotli body_io
           when 'zstd' then
             content_encoding_zstd body_io
           else
             raise Mechanize::Error,
               "unsupported content-encoding: #{response['Content-Encoding']}"
           end

  out_io.flush
  out_io.rewind

  out_io
rescue Zlib::Error => e
  message = String.new("error handling content-encoding #{response['Content-Encoding']}:")
  message << " #{e.message} (#{e.class})"
  raise Mechanize::Error, message
ensure
  begin
    if Tempfile === body_io and
       (StringIO === out_io or (out_io and out_io.path != body_io.path)) then
      body_io.close!
    end
  rescue IOError
    # HACK ruby 1.8 raises IOError when closing the stream
  end
end

#response_cookies(response, uri, page) ⇒ Object



978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
# File 'lib/mechanize/http/agent.rb', line 978

def response_cookies response, uri, page
  if Mechanize::Page === page and page.body =~ /Set-Cookie/n
    page.search('//head/meta[@http-equiv="Set-Cookie"]').each do |meta|
      save_cookies(uri, meta['content'])
    end
  end

  header_cookies = response.get_fields 'Set-Cookie'

  return unless header_cookies

  header_cookies.each do |set_cookie|
    save_cookies(uri, set_cookie)
  end
end

#response_follow_meta_refresh(response, uri, page, redirects, headers = {}) ⇒ Object



1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
# File 'lib/mechanize/http/agent.rb', line 1006

def response_follow_meta_refresh response, uri, page, redirects, headers = {}
  delay, new_url = get_meta_refresh(response, uri, page)
  return nil unless delay
  new_url = new_url ? secure_resolve!(new_url, page) : uri

  raise Mechanize::RedirectLimitReachedError.new(page, redirects) if
    redirects + 1 > @redirection_limit

  sleep delay
  @history.push(page, page.uri)

  headers = headers.dup

  # The refresh is fetched with GET, so the original request's entity headers
  # must not describe it.
  POST_HEADERS.each { |key| headers.delete_if { |h, _| h.to_s.casecmp?(key) } }
  headers.delete_if { |h, _| drop_after_redirect? h, crosses_origin?(uri, new_url) }

  fetch new_url, :get, headers, [],
        Mechanize::Page.new, redirects + 1, false
end

#response_log(response) ⇒ Object



1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/mechanize/http/agent.rb', line 1028

def response_log response
  return unless log

  log.info("status: #{response.class} #{response.http_version} " \
           "#{response.code} #{response.message}")

  response.each_header do |k, v|
    log.debug("response-header: #{k} => #{v}")
  end
end

#response_parse(response, body_io, uri) ⇒ Object



1039
1040
1041
# File 'lib/mechanize/http/agent.rb', line 1039

def response_parse response, body_io, uri
  @context.parse uri, response, body_io
end

#response_read(response, request, uri) ⇒ Object



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
# File 'lib/mechanize/http/agent.rb', line 1043

def response_read response, request, uri
  content_length = response.content_length

  if use_tempfile? content_length then
    body_io = make_tempfile 'mechanize-raw'
  else
    body_io = StringIO.new.set_encoding(Encoding::BINARY)
  end

  total = 0

  begin
    response.read_body { |part|
      total += part.length

      if StringIO === body_io and use_tempfile? total then
        new_io = make_tempfile 'mechanize-raw'

        new_io.write body_io.string

        body_io = new_io
      end

      body_io.write(part)
      log.debug("Read #{part.length} bytes (#{total} total)") if log
    }
  rescue EOFError => e
    # terminating CRLF might be missing, let the user check the document
    raise unless response.chunked? and total.nonzero?

    body_io.rewind
    raise Mechanize::ChunkedTerminationError.new(e, response, body_io, uri,
                                                 @context)
  rescue Net::HTTP::Persistent::Error, Errno::ECONNRESET => e
    body_io.rewind
    raise Mechanize::ResponseReadError.new(e, response, body_io, uri,
                                           @context)
  end

  body_io.flush
  body_io.rewind

  raise Mechanize::ResponseCodeError.new(response, uri) if
    Net::HTTPUnknownResponse === response

  content_length = response.content_length

  unless Net::HTTP::Head === request or Net::HTTPRedirection === response then
    if content_length and content_length != body_io.length
      err = EOFError.new("Content-Length (#{content_length}) does not " \
                    "match response body length (#{body_io.length})")
      raise Mechanize::ResponseReadError.new(err, response, body_io, uri,
                                              @context)
    end
  end

  body_io
end

#response_redirect(response, method, page, redirects, headers, referer = current_page) ⇒ Object



1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
# File 'lib/mechanize/http/agent.rb', line 1102

def response_redirect(response, method, page, redirects, headers,
                      referer = current_page)
  case @redirect_ok
  when true, :all
    # shortcut
  when false, nil
    return page
  when :permanent
    return page unless Net::HTTPMovedPermanently === response
  end

  log.info("follow redirect to: #{response['Location']}") if log

  raise Mechanize::RedirectLimitReachedError.new(page, redirects) if
    redirects + 1 > @redirection_limit

  redirect_method = method == :head ? :head : :get

  new_uri = secure_resolve!(response['Location'].to_s, page)
  @history.push(page, page.uri)

  # Make sure we are not copying over the POST headers from the original request
  POST_HEADERS.each do |key|
    headers.delete_if { |h| h.casecmp?(key) }
  end

  # Sensitive headers must not follow a redirect across an origin.
  crossed_origin = crosses_origin? page.uri, new_uri

  headers.delete_if { |h, _| drop_after_redirect? h, crossed_origin }

  fetch new_uri, redirect_method, headers, [], referer, redirects + 1, false
end

#retry_change_requestsObject

Retry non-idempotent requests?



369
370
371
# File 'lib/mechanize/http/agent.rb', line 369

def retry_change_requests
  @http.retry_change_requests
end

#retry_change_requests=(retri) ⇒ Object

Retry non-idempotent requests



375
376
377
# File 'lib/mechanize/http/agent.rb', line 375

def retry_change_requests= retri
  @http.retry_change_requests = retri
end

#robots_allowed?(uri) ⇒ Boolean

Tests if this agent is allowed to access url, consulting the site's robots.txt.

Returns:

  • (Boolean)


1170
1171
1172
1173
1174
# File 'lib/mechanize/http/agent.rb', line 1170

def robots_allowed? uri
  return true if Thread.current[RobotsKey]

  webrobots.allowed? uri
end

#robots_disallowed?(url) ⇒ Boolean

Opposite of robots_allowed?

Returns:

  • (Boolean)


1178
1179
1180
# File 'lib/mechanize/http/agent.rb', line 1178

def robots_disallowed? url
  !robots_allowed? url
end

#robots_error(url) ⇒ Object

Returns an error object if there is an error in fetching or parsing robots.txt of the site url.



1184
1185
1186
# File 'lib/mechanize/http/agent.rb', line 1184

def robots_error(url)
  webrobots.error(url)
end

#robots_error!(url) ⇒ Object

Raises the error if there is an error in fetching or parsing robots.txt of the site url.



1190
1191
1192
# File 'lib/mechanize/http/agent.rb', line 1190

def robots_error!(url)
  webrobots.error!(url)
end

#robots_reset(url) ⇒ Object

Removes robots.txt cache for the site url.



1195
1196
1197
# File 'lib/mechanize/http/agent.rb', line 1195

def robots_reset(url)
  webrobots.reset(url)
end

#save_cookies(uri, set_cookie) ⇒ Object



994
995
996
997
998
999
1000
1001
1002
1003
1004
# File 'lib/mechanize/http/agent.rb', line 994

def save_cookies(uri, set_cookie)
  return [] if set_cookie.nil?
  if log = log()	 # reduce method calls
    @cookie_jar.parse(set_cookie, uri, :logger => log) { |c|
      log.debug("saved cookie: #{c}")
      true
    }
  else
    @cookie_jar.parse(set_cookie, uri)
  end
end

#secure_resolve!(uri, referer = current_page) ⇒ Object



811
812
813
814
815
816
817
818
819
820
821
# File 'lib/mechanize/http/agent.rb', line 811

def secure_resolve!(uri, referer = current_page)
  new_uri = resolve(uri, referer)

  if (referer_uri = referer && referer.uri) &&
     referer_uri.scheme != 'file'.freeze &&
     new_uri.scheme == 'file'.freeze
    raise Mechanize::Error, "insecure redirect to a file URI"
  end

  new_uri
end

#set_proxy(addr, port = nil, user = nil, pass = nil) ⇒ Object

Sets the proxy address, port, user, and password. addr may be an HTTP URL/URI or a host name, port may be a port number, service name or port number string.



1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
# File 'lib/mechanize/http/agent.rb', line 1359

def set_proxy addr, port = nil, user = nil, pass = nil
  case addr
  when URI::HTTP
    proxy_uri = addr.dup
  when %r{\Ahttps?://}i
    proxy_uri = URI addr
  when String
    proxy_uri = URI "http://#{addr}"
  when nil
    @http.proxy = nil
    return
  end

  case port
  when Integer
    proxy_uri.port = port
  when nil
  else
    begin
      proxy_uri.port = Socket.getservbyname port
    rescue SocketError
      begin
        proxy_uri.port = Integer port
      rescue ArgumentError
        raise ArgumentError, "invalid value for port: #{port.inspect}"
      end
    end
  end

  proxy_uri.user     = user if user
  proxy_uri.password = pass if pass

  @http.proxy = proxy_uri
end

#shutdownObject

Closes all open connections for this agent.



463
464
465
# File 'lib/mechanize/http/agent.rb', line 463

def shutdown
  http.shutdown
end

#ssl_versionObject

SSL version to use



1259
1260
1261
# File 'lib/mechanize/http/agent.rb', line 1259

def ssl_version
  @http.ssl_version
end

#ssl_version=(ssl_version) ⇒ Object

Sets the SSL version to use



1264
1265
1266
# File 'lib/mechanize/http/agent.rb', line 1264

def ssl_version= ssl_version
  @http.ssl_version = ssl_version
end

#use_tempfile?(size) ⇒ Boolean

Returns:

  • (Boolean)


1401
1402
1403
1404
1405
1406
# File 'lib/mechanize/http/agent.rb', line 1401

def use_tempfile? size
  return false unless @max_file_buffer
  return false unless size

  size >= @max_file_buffer
end

#verify_callbackObject

A callback for additional certificate verification. See OpenSSL::SSL::SSLContext#verify_callback

The callback can be used for debugging or to ignore errors by always returning true. Specifying nil uses the default method that was valid when the SSLContext was created



1274
1275
1276
# File 'lib/mechanize/http/agent.rb', line 1274

def verify_callback
  @http.verify_callback
end

#verify_callback=(verify_callback) ⇒ Object

Sets the certificate verify callback



1279
1280
1281
# File 'lib/mechanize/http/agent.rb', line 1279

def verify_callback= verify_callback
  @http.verify_callback = verify_callback
end

#verify_modeObject

How to verify SSL connections. Defaults to VERIFY_PEER



1284
1285
1286
# File 'lib/mechanize/http/agent.rb', line 1284

def verify_mode
  @http.verify_mode
end

#verify_mode=(verify_mode) ⇒ Object

Sets the mode for verifying SSL connections



1289
1290
1291
# File 'lib/mechanize/http/agent.rb', line 1289

def verify_mode= verify_mode
  @http.verify_mode = verify_mode
end

#visited_page(url) ⇒ Object

Returns a visited page for the url passed in, otherwise nil



412
413
414
# File 'lib/mechanize/http/agent.rb', line 412

def visited_page url
  @history.visited_page resolve url
end

#webrobotsObject



1199
1200
1201
# File 'lib/mechanize/http/agent.rb', line 1199

def webrobots
  @webrobots ||= WebRobots.new(@user_agent, :http_get => method(:get_robots))
end