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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAgent

Creates a new Mechanize HTTP user agent. The user agent is an implementation detail of mechanize and its API may change at any time.



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
# File 'lib/mechanize/http/agent.rb', line 150

def initialize
  @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
  @idle_timeout             = nil
  @keep_alive               = true
  @keep_alive_time          = 300
  @max_file_buffer          = 10240
  @open_timeout             = nil
  @post_connect_hooks       = []
  @pre_connect_hooks        = []
  @proxy_uri                = nil
  @read_timeout             = nil
  @redirect_ok              = true
  @redirection_limit        = 20
  @request_headers          = {}
  @retry_change_requests    = false
  @robots                   = false
  @user_agent               = nil
  @webrobots                = nil

  # HTTP Authentication
  @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    = {}
  @password             = nil # HTTP auth password
  @user                 = nil # HTTP auth user

  # SSL
  @ca_file         = nil
  @cert            = nil
  @cert_store      = nil
  @key             = nil
  @pass            = nil
  @verify_callback = nil
  @verify_mode     = nil

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

  @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']
end

Instance Attribute Details

#authenticate_methodsObject (readonly)

:section: HTTP Authentication



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

def authenticate_methods
  @authenticate_methods
end

#ca_fileObject

Path to an OpenSSL server certificate file



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

def ca_file
  @ca_file
end

#certObject

An OpenSSL client certificate or the path to a certificate file.



87
88
89
# File 'lib/mechanize/http/agent.rb', line 87

def cert
  @cert
end

#cert_storeObject

An SSL certificate store



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

def cert_store
  @cert_store
end

#conditional_requestsObject

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



15
16
17
# File 'lib/mechanize/http/agent.rb', line 15

def conditional_requests
  @conditional_requests
end

#content_encoding_hooksObject (readonly)

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



42
43
44
# File 'lib/mechanize/http/agent.rb', line 42

def content_encoding_hooks
  @content_encoding_hooks
end

#contextObject

The context parses responses into pages



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

def context
  @context
end

The cookies for this agent



123
124
125
# File 'lib/mechanize/http/agent.rb', line 123

def cookie_jar
  @cookie_jar
end

#digest_challengesObject (readonly)

:nodoc:



47
48
49
# File 'lib/mechanize/http/agent.rb', line 47

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.



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

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.



60
61
62
# File 'lib/mechanize/http/agent.rb', line 60

def follow_meta_refresh_self
  @follow_meta_refresh_self
end

#gzip_enabledObject

Is gzip compression of requests enabled?



18
19
20
# File 'lib/mechanize/http/agent.rb', line 18

def gzip_enabled
  @gzip_enabled
end

#historyObject

history of requests made



29
30
31
# File 'lib/mechanize/http/agent.rb', line 29

def history
  @history
end

#httpObject (readonly)

:nodoc:



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

def http
  @http
end

#idle_timeoutObject

Reset connections that have not been used in this many seconds



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

def idle_timeout
  @idle_timeout
end

#keep_aliveObject

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



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

def keep_alive
  @keep_alive
end

#keyObject

An OpenSSL private key or the path to a private key



84
85
86
# File 'lib/mechanize/http/agent.rb', line 84

def key
  @key
end

#max_file_bufferObject

Responses larger than this will be written to a Tempfile instead of stored in memory.



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

def max_file_buffer
  @max_file_buffer
end

#open_timeoutObject

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



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

def open_timeout
  @open_timeout
end

#passObject

OpenSSL key password



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

def pass
  @pass
end

#passwordObject

Returns the value of attribute password.



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

def password
  @password
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.



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

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.



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

def pre_connect_hooks
  @pre_connect_hooks
end

#proxy_uriObject (readonly)

URI for a proxy connection



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

def proxy_uri
  @proxy_uri
end

#read_timeoutObject

Length of time to attempt to read data from the server



118
119
120
# File 'lib/mechanize/http/agent.rb', line 118

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 Permanantly redirects are followed

false

No redirects are followed



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

def redirect_ok
  @redirect_ok
end

#redirection_limitObject

Maximum number of redirects to follow



71
72
73
# File 'lib/mechanize/http/agent.rb', line 71

def redirection_limit
  @redirection_limit
end

#request_headersObject

A hash of request headers to be used for every request



21
22
23
# File 'lib/mechanize/http/agent.rb', line 21

def request_headers
  @request_headers
end

#retry_change_requestsObject

Retry non-idempotent requests?



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

def retry_change_requests
  @retry_change_requests
end

#robotsObject

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



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

def robots
  @robots
end

#scheme_handlersObject

Handlers for various URI schemes



143
144
145
# File 'lib/mechanize/http/agent.rb', line 143

def scheme_handlers
  @scheme_handlers
end

#userObject

Returns the value of attribute user.



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

def user
  @user
end

#user_agentObject

The User-Agent header to send



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

def user_agent
  @user_agent
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



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

def verify_callback
  @verify_callback
end

#verify_modeObject

How to verify SSL connections. Defaults to VERIFY_PEER



104
105
106
# File 'lib/mechanize/http/agent.rb', line 104

def verify_mode
  @verify_mode
end

Instance Method Details

#backObject

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



325
326
327
# File 'lib/mechanize/http/agent.rb', line 325

def back
  @history.pop
end

#certificateObject

:section: SSL



910
911
912
# File 'lib/mechanize/http/agent.rb', line 910

def certificate
  @http.certificate
end

#connection_for(uri) ⇒ Object

:section: Request



386
387
388
389
390
391
392
393
# File 'lib/mechanize/http/agent.rb', line 386

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

#current_pageObject

Returns the latest page loaded by the agent



332
333
334
# File 'lib/mechanize/http/agent.rb', line 332

def current_page
  @history.last
end

#disable_keep_alive(request) ⇒ Object



395
396
397
# File 'lib/mechanize/http/agent.rb', line 395

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

#enable_gzip(request) ⇒ Object



399
400
401
402
403
404
405
# File 'lib/mechanize/http/agent.rb', line 399

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) ⇒ 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.

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



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
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
# File 'lib/mechanize/http/agent.rb', line 217

def fetch uri, method = :get, headers = {}, params = [],
          referer = current_page, redirects = 0
  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
  page = visited_page(uri)

  if (page = visited_page(uri)) and page.response['Last-Modified']
    request['If-Modified-Since'] = page.response['Last-Modified']
  end if(@conditional_requests)

  # Specify timeouts if given
  connection.open_timeout = @open_timeout if @open_timeout
  connection.read_timeout = @read_timeout if @read_timeout

  request_log request

  response_body_io = nil

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

    response_body_io = response_read res, request

    res
  }

  hook_content_encoding response, uri, response_body_io

  response_body_io = response_content_encoding response, response_body_io

  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
  return meta if meta

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

    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, referer
  when Net::HTTPUnauthorized
    response_authenticate(response, page, uri, request, headers, params,
                          referer)
  else
    raise Mechanize::ResponseCodeError.new(page), "Unhandled response"
  end
end

#get_meta_refresh(response, uri, page) ⇒ Object

:section: Response



586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/mechanize/http/agent.rb', line 586

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

:section: Robots



858
859
860
861
862
863
# File 'lib/mechanize/http/agent.rb', line 858

def get_robots(uri) # :nodoc:
  fetch(uri).body
rescue Mechanize::ResponseCodeError => e
  return '' if e.response_code == '404'
  raise e
end

#hook_content_encoding(response, uri, response_body_io) ⇒ Object

:section: Hooks



351
352
353
354
355
# File 'lib/mechanize/http/agent.rb', line 351

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



407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/mechanize/http/agent.rb', line 407

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

#inflate(compressed, window_bits = nil) ⇒ Object

:section: Utility



924
925
926
927
928
929
930
931
932
933
934
935
# File 'lib/mechanize/http/agent.rb', line 924

def inflate compressed, window_bits = nil
  inflate = Zlib::Inflate.new window_bits
  out_io = Tempfile.new 'mechanize-decode'

  until compressed.eof? do
    out_io.write inflate.inflate compressed.read 1024
  end

  out_io.write inflate.finish

  out_io
end

#logObject



937
938
939
# File 'lib/mechanize/http/agent.rb', line 937

def log
  @context.log
end

#max_historyObject



336
337
338
# File 'lib/mechanize/http/agent.rb', line 336

def max_history
  @history.max_size
end

#max_history=(length) ⇒ Object



340
341
342
# File 'lib/mechanize/http/agent.rb', line 340

def max_history=(length)
  @history.max_size = length
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.



364
365
366
367
368
369
370
371
372
# File 'lib/mechanize/http/agent.rb', line 364

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.



378
379
380
381
382
# File 'lib/mechanize/http/agent.rb', line 378

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

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



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/mechanize/http/agent.rb', line 421

def request_add_headers request, headers = {}
  @request_headers.each do |k,v|
    request[k] = v
  end

  headers.each do |field, value|
    case field
    when :etag              then request["ETag"] = value
    when :if_modified_since then request["If-Modified-Since"] = value
    when Symbol then
      raise ArgumentError, "unknown header symbol #{field}"
    else
      request[field] = value
    end
  end
end

#request_auth(request, uri) ⇒ Object



438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/mechanize/http/agent.rb', line 438

def request_auth request, uri
  base_uri = uri + '/'
  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 schemes[:basic].find { |r| r.uri == base_uri } then
    request.basic_auth @user, @password
  end
end

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



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

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

  uri.user = @user
  uri.password = @password

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

#request_cookies(request, uri) ⇒ Object



461
462
463
464
465
466
467
468
469
# File 'lib/mechanize/http/agent.rb', line 461

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



471
472
473
474
475
476
# File 'lib/mechanize/http/agent.rb', line 471

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



478
479
480
481
# File 'lib/mechanize/http/agent.rb', line 478

def request_language_charset request
  request['accept-charset']  = 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
  request['accept-language'] = 'en-us,en;q=0.5'
end

#request_log(request) ⇒ Object

Log specified headers for the request



484
485
486
487
488
489
490
491
492
# File 'lib/mechanize/http/agent.rb', line 484

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



494
495
496
497
498
499
500
# File 'lib/mechanize/http/agent.rb', line 494

def request_referer request, uri, referer
  return unless referer
  return if 'https' == referer.scheme.downcase and
            'https' != uri.scheme.downcase

  request['Referer'] = referer
end

#request_user_agent(request) ⇒ Object



502
503
504
# File 'lib/mechanize/http/agent.rb', line 502

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

#resolve(uri, referer = current_page) ⇒ Object



506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/mechanize/http/agent.rb', line 506

def resolve(uri, referer = current_page)
  uri = uri.dup if uri.is_a?(URI)

  unless uri.is_a?(URI)
    uri = uri.to_s.strip.gsub(/[^#{0.chr}-#{126.chr}]/o) { |match|
      if RUBY_VERSION >= "1.9.0"
        Mechanize::Util.uri_escape(match)
      else
        sprintf('%%%X', match.unpack($KCODE == 'UTF8' ? 'U' : 'C')[0])
      end
    }

    unescaped = uri.split(/(?:%[0-9A-Fa-f]{2})+|#/)
    escaped   = uri.scan(/(?:%[0-9A-Fa-f]{2})+|#/)

    escaped_uri = Mechanize::Util.html_unescape(
      unescaped.zip(escaped).map { |x,y|
        "#{WEBrick::HTTPUtils.escape(x)}#{y}"
      }.join('')
    )

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

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

  if referer && referer.uri
    if uri.path.length == 0 && uri.relative?
      uri.path = referer.uri.path
    end
  end

  uri.path = '/' if uri.path.length == 0

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

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

    uri = ((base && base.uri && base.uri.absolute?) ?
           base.uri :
           referer.uri) + uri
    uri = referer.uri + uri
    # 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

  uri
end

#resolve_parameters(uri, method, parameters) ⇒ Object



569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/mechanize/http/agent.rb', line 569

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



601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/mechanize/http/agent.rb', line 601

def response_authenticate(response, page, uri, request, headers, params,
                          referer)
  raise Mechanize::UnauthorizedError, page unless @user || @password

  challenges = @authenticate_parser.parse response['www-authenticate']

  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]

    raise Mechanize::UnauthorizedError, page if
      existing_realms.include? realm

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

    raise Mechanize::UnauthorizedError, page if
      existing_realms.include?(realm) and not challenge.params

    existing_realms << realm

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

      type_3 = type_2.response({ :user => @user, :password => @password, },
                               { :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]

    raise Mechanize::UnauthorizedError, page if
      existing_realms.include? realm

    existing_realms << realm
  else
    raise Mechanize::UnauthorizedError, page
  end

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

#response_content_encoding(response, body_io) ⇒ Object



658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# File 'lib/mechanize/http/agent.rb', line 658

def response_content_encoding response, body_io
  length = response.content_length

  length = case body_io
           when IO, Tempfile then
             body_io.stat.size
           else
             body_io.length
           end unless length

  out_io = nil

  case response['Content-Encoding']
  when nil, 'none', '7bit' then
    out_io = body_io
  when 'deflate' then
    log.debug('deflate body') if log

    return if length.zero?

    begin
      out_io = inflate body_io
    rescue Zlib::BufError, Zlib::DataError
      log.error('Unable to inflate page, retrying with raw deflate') if log
      body_io.rewind
      begin
        out_io = inflate body_io, -Zlib::MAX_WBITS
      rescue Zlib::BufError, Zlib::DataError
        log.error("unable to inflate page: #{$!}") if log
        nil
      end
    end
  when 'gzip', 'x-gzip' then
    log.debug('gzip body') if log

    return if length.zero?

    begin
      zio = Zlib::GzipReader.new body_io
      out_io = Tempfile.new 'mechanize-decode', :encoding => 'ascii-8bit'
      out_io.binmode

      until zio.eof? do
        out_io.write zio.read 16384
      end
    rescue Zlib::BufError, Zlib::GzipFile::Error
      log.error('Unable to gunzip body, trying raw inflate') if log
      body_io.rewind
      body_io.read 10

      out_io = inflate body_io, -Zlib::MAX_WBITS
    rescue Zlib::DataError
      log.error("unable to gunzip page: #{$!}") if log
      ''
    ensure
      zio.close if zio and not zio.closed?
    end
  else
    raise Mechanize::Error,
          "Unsupported Content-Encoding: #{response['Content-Encoding']}"
  end

  out_io.flush
  out_io.rewind

  out_io
end

#response_cookies(response, uri, page) ⇒ Object



726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
# File 'lib/mechanize/http/agent.rb', line 726

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) ⇒ Object



753
754
755
756
757
758
759
760
761
762
763
764
# File 'lib/mechanize/http/agent.rb', line 753

def response_follow_meta_refresh response, uri, page, redirects
  delay, new_url = get_meta_refresh(response, uri, page)
  return nil unless new_url

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

  sleep delay
  @history.push(page, page.uri)
  fetch new_url, :get, {}, [],
        Mechanize::Page.new(nil, {'content-type'=>'text/html'}), redirects
end

#response_log(response) ⇒ Object



766
767
768
769
770
771
772
773
774
775
# File 'lib/mechanize/http/agent.rb', line 766

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



777
778
779
# File 'lib/mechanize/http/agent.rb', line 777

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

#response_read(response, request) ⇒ Object



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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# File 'lib/mechanize/http/agent.rb', line 781

def response_read response, request
  content_length = response.content_length

  if content_length and content_length > @max_file_buffer then
    body_io = Tempfile.new 'mechanize-raw'
    body_io.binmode if defined? body_io.binmode
  else
    body_io = StringIO.new
  end

  body_io.set_encoding Encoding::BINARY if body_io.respond_to? :set_encoding
  total = 0

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

      if StringIO === body_io and total > @max_file_buffer then
        new_io = Tempfile.new 'mechanize-raw'
        new_io.binmode if defined? binmode
        new_io.set_encoding(body_io.external_encoding) 
        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 Net::HTTP::Persistent::Error => e
    body_io.rewind
    raise Mechanize::ResponseReadError.new(e, response, body_io)
  end

  body_io.flush
  body_io.rewind

  raise Mechanize::ResponseCodeError, response if
    Net::HTTPUnknownResponse === response

  content_length = response.content_length

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

  body_io
end

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



832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
# File 'lib/mechanize/http/agent.rb', line 832

def response_redirect response, method, page, redirects, 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

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

  fetch new_uri, redirect_method, {}, [], referer, redirects + 1
end

#robots_allowed?(uri) ⇒ Boolean

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

Returns:

  • (Boolean)


875
876
877
878
879
# File 'lib/mechanize/http/agent.rb', line 875

def robots_allowed? uri
  return true if uri.request_uri == '/robots.txt'

  webrobots.allowed? uri
end

#robots_disallowed?(url) ⇒ Boolean

Opposite of robots_allowed?

Returns:

  • (Boolean)


883
884
885
# File 'lib/mechanize/http/agent.rb', line 883

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.



889
890
891
# File 'lib/mechanize/http/agent.rb', line 889

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.



895
896
897
# File 'lib/mechanize/http/agent.rb', line 895

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

#robots_reset(url) ⇒ Object

Removes robots.txt cache for the site url.



900
901
902
# File 'lib/mechanize/http/agent.rb', line 900

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

#save_cookies(uri, set_cookie) ⇒ Object



742
743
744
745
746
747
748
749
750
751
# File 'lib/mechanize/http/agent.rb', line 742

def save_cookies(uri, set_cookie)
  log = log()	 # reduce method calls
  Mechanize::Cookie.parse(uri, set_cookie, log) { |c|
    if @cookie_jar.add(uri, c)
      log.debug("saved cookie: #{c}") if log
    else
      log.debug("rejected cookie: #{c}") if log
    end
  }
end

#set_httpObject



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
# File 'lib/mechanize/http/agent.rb', line 941

def set_http
  @http = Net::HTTP::Persistent.new 'mechanize', @proxy_uri

  @http.keep_alive = @keep_alive_time
  @http.idle_timeout = @idle_timeout if @idle_timeout
  @http.retry_change_requests = @retry_change_requests

  @http.ca_file         = @ca_file
  @http.cert_store      = @cert_store if @cert_store
  @http.verify_callback = @verify_callback
  @http.verify_mode     = @verify_mode if @verify_mode

  # update our cached value
  @verify_mode = @http.verify_mode
  @cert_store  = @http.cert_store

  if @cert and @key then
    cert = if OpenSSL::X509::Certificate === @cert then
             @cert
           else
             OpenSSL::X509::Certificate.new ::File.read @cert
           end

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

    @http.certificate = cert
    @http.private_key = key
  end
end

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

Sets the proxy address, port, user, and password addr should be a host, with no “http://”, port may be a port number, service name or port number string.



980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
# File 'lib/mechanize/http/agent.rb', line 980

def set_proxy(addr, port, user = nil, pass = nil)
  return unless addr and port

  unless Integer === port then
    begin
      port = Socket.getservbyname port
    rescue SocketError
      begin
        port = Integer port
      rescue ArgumentError
        raise ArgumentError, "invalid value for port: #{port.inspect}"
      end
    end
  end

  @proxy_uri = URI "http://#{addr}"
  @proxy_uri.port = port
  @proxy_uri.user     = user if user
  @proxy_uri.password = pass if pass

  @proxy_uri
end

#visited_page(url) ⇒ Object

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



345
346
347
# File 'lib/mechanize/http/agent.rb', line 345

def visited_page url
  @history.visited_page resolve url
end

#webrobotsObject



904
905
906
# File 'lib/mechanize/http/agent.rb', line 904

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