Class: RestClient::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/restclient/request.rb,
lib/restclient/exceptions.rb

Overview

backwards compatibility

Constant Summary collapse

Redirect =
RestClient::Redirect
Unauthorized =
RestClient::Unauthorized
RequestFailed =
RestClient::RequestFailed

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Request

Returns a new instance of Request.


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/restclient/request.rb', line 38

def initialize args
  @method = args[:method] or raise ArgumentError, "must pass :method"
  @headers = args[:headers] || {}
  if args[:url]
    @url = process_url_params(args[:url], headers)
  else
    raise ArgumentError, "must pass :url"
  end
  @cookies = @headers.delete(:cookies) || args[:cookies] || {}
  @payload = Payload.generate(args[:payload])
  @user = args[:user]
  @password = args[:password]
  @timeout = args[:timeout]
  @open_timeout = args[:open_timeout]
  @block_response = args[:block_response]
  @raw_response = args[:raw_response] || false
  @verify_ssl = args[:verify_ssl] || false
  @ssl_client_cert = args[:ssl_client_cert] || nil
  @ssl_client_key = args[:ssl_client_key] || nil
  @ssl_ca_file = args[:ssl_ca_file] || nil
  @ssl_verify_callback = args[:ssl_verify_callback] || nil
  @ssl_verify_callback_warnings = args.fetch(:ssl_verify_callback, true)
  @tf = nil # If you are a raw request, this is your tempfile
  @max_redirects = args[:max_redirects] || 10
  @processed_headers = make_headers headers
  @args = args
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args


28
29
30
# File 'lib/restclient/request.rb', line 28

def args
  @args
end

#cookiesObject (readonly)

Returns the value of attribute cookies


28
29
30
# File 'lib/restclient/request.rb', line 28

def cookies
  @cookies
end

#headersObject (readonly)

Returns the value of attribute headers


28
29
30
# File 'lib/restclient/request.rb', line 28

def headers
  @headers
end

#max_redirectsObject (readonly)

Returns the value of attribute max_redirects


28
29
30
# File 'lib/restclient/request.rb', line 28

def max_redirects
  @max_redirects
end

#methodObject (readonly)

Returns the value of attribute method


28
29
30
# File 'lib/restclient/request.rb', line 28

def method
  @method
end

#open_timeoutObject (readonly)

Returns the value of attribute open_timeout


28
29
30
# File 'lib/restclient/request.rb', line 28

def open_timeout
  @open_timeout
end

#passwordObject (readonly)

Returns the value of attribute password


28
29
30
# File 'lib/restclient/request.rb', line 28

def password
  @password
end

#payloadObject (readonly)

Returns the value of attribute payload


28
29
30
# File 'lib/restclient/request.rb', line 28

def payload
  @payload
end

#processed_headersObject (readonly)

Returns the value of attribute processed_headers


28
29
30
# File 'lib/restclient/request.rb', line 28

def processed_headers
  @processed_headers
end

#raw_responseObject (readonly)

Returns the value of attribute raw_response


28
29
30
# File 'lib/restclient/request.rb', line 28

def raw_response
  @raw_response
end

#ssl_ca_fileObject (readonly)

Returns the value of attribute ssl_ca_file


28
29
30
# File 'lib/restclient/request.rb', line 28

def ssl_ca_file
  @ssl_ca_file
end

#ssl_client_certObject (readonly)

Returns the value of attribute ssl_client_cert


28
29
30
# File 'lib/restclient/request.rb', line 28

def ssl_client_cert
  @ssl_client_cert
end

#ssl_client_keyObject (readonly)

Returns the value of attribute ssl_client_key


28
29
30
# File 'lib/restclient/request.rb', line 28

def ssl_client_key
  @ssl_client_key
end

#ssl_verify_callbackObject (readonly)

Returns the value of attribute ssl_verify_callback


28
29
30
# File 'lib/restclient/request.rb', line 28

def ssl_verify_callback
  @ssl_verify_callback
end

#ssl_verify_callback_warningsObject (readonly)

Returns the value of attribute ssl_verify_callback_warnings


28
29
30
# File 'lib/restclient/request.rb', line 28

def ssl_verify_callback_warnings
  @ssl_verify_callback_warnings
end

#timeoutObject (readonly)

Returns the value of attribute timeout


28
29
30
# File 'lib/restclient/request.rb', line 28

def timeout
  @timeout
end

#urlObject (readonly)

Returns the value of attribute url


28
29
30
# File 'lib/restclient/request.rb', line 28

def url
  @url
end

#userObject (readonly)

Returns the value of attribute user


28
29
30
# File 'lib/restclient/request.rb', line 28

def user
  @user
end

#verify_sslObject (readonly)

Returns the value of attribute verify_ssl


28
29
30
# File 'lib/restclient/request.rb', line 28

def verify_ssl
  @verify_ssl
end

Class Method Details

.decode(content_encoding, body) ⇒ Object


274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/restclient/request.rb', line 274

def self.decode content_encoding, body
  if (!body) || body.empty?
    body
  elsif content_encoding == 'gzip'
    Zlib::GzipReader.new(StringIO.new(body)).read
  elsif content_encoding == 'deflate'
    begin
      Zlib::Inflate.new.inflate body
    rescue Zlib::DataError
      # No luck with Zlib decompression. Let's try with raw deflate,
      # like some broken web servers do.
      Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate body
    end
  else
    body
  end
end

.execute(args, &block) ⇒ Object


34
35
36
# File 'lib/restclient/request.rb', line 34

def self.execute(args, & block)
  new(args).execute(& block)
end

Instance Method Details

#default_headersObject


333
334
335
# File 'lib/restclient/request.rb', line 333

def default_headers
  {:accept => '*/*; q=0.5, application/xml', :accept_encoding => 'gzip, deflate'}
end

#execute(&block) ⇒ Object


66
67
68
69
70
71
# File 'lib/restclient/request.rb', line 66

def execute & block
  uri = parse_url_with_auth(url)
  transmit uri, net_http_request_class(method).new(uri.request_uri, processed_headers), payload, & block
ensure
  payload.close if payload
end

#fetch_body(http_response) ⇒ Object


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
# File 'lib/restclient/request.rb', line 230

def fetch_body(http_response)
  if @raw_response
    # Taken from Chef, which as in turn...
    # Stolen from http://www.ruby-forum.com/topic/166423
    # Kudos to _why!
    @tf = Tempfile.new("rest-client")
    size, total = 0, http_response.header['Content-Length'].to_i
    http_response.read_body do |chunk|
      @tf.write chunk
      size += chunk.size
      if RestClient.log
        if size == 0
          RestClient.log << "#{@method} #{@url} done (0 length file\n)"
        elsif total == 0
          RestClient.log << "#{@method} #{@url} (zero content length)\n"
        else
          RestClient.log << "#{@method} #{@url} %d%% done (%d of %d)\n" % [(size * 100) / total, size, total]
        end
      end
    end
    @tf.close
    @tf
  else
    http_response.read_body
  end
  http_response
end

#log_requestObject


292
293
294
295
296
297
298
299
300
# File 'lib/restclient/request.rb', line 292

def log_request
  if RestClient.log
    out = []
    out << "RestClient.#{method} #{url.inspect}"
    out << payload.short_inspect if payload
    out << processed_headers.to_a.sort.map { |(k, v)| [k.inspect, v.inspect].join("=>") }.join(", ")
    RestClient.log << out.join(', ') + "\n"
  end
end

#log_response(res) ⇒ Object


302
303
304
305
306
307
# File 'lib/restclient/request.rb', line 302

def log_response res
  if RestClient.log
    size = @raw_response ? File.size(@tf.path) : (res.body.nil? ? 0 : res.body.size)
    RestClient.log << "# => #{res.code} #{res.class.to_s.gsub(/^Net::HTTP/, '')} | #{(res['Content-type'] || '').gsub(/;.*$/, '')} #{size} bytes\n"
  end
end

#make_headers(user_headers) ⇒ Object


92
93
94
95
96
97
98
99
# File 'lib/restclient/request.rb', line 92

def make_headers user_headers
  unless @cookies.empty?
    user_headers[:cookie] = @cookies.map { |(key, val)| "#{key.to_s}=#{CGI::unescape(val)}" }.sort.join('; ')
  end
  headers = stringify_headers(default_headers).merge(stringify_headers(user_headers))
  headers.merge!(@payload.headers) if @payload
  headers
end

#net_http_classObject


101
102
103
104
105
106
107
108
# File 'lib/restclient/request.rb', line 101

def net_http_class
  if RestClient.proxy
    proxy_uri = URI.parse(RestClient.proxy)
    Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
  else
    Net::HTTP
  end
end

#net_http_request_class(method) ⇒ Object


110
111
112
# File 'lib/restclient/request.rb', line 110

def net_http_request_class(method)
  Net::HTTP.const_get(method.to_s.capitalize)
end

#parse_url(url) ⇒ Object


114
115
116
117
# File 'lib/restclient/request.rb', line 114

def parse_url(url)
  url = "http://#{url}" unless url.match(/^http/)
  URI.parse(url)
end

#parse_url_with_auth(url) ⇒ Object


119
120
121
122
123
124
# File 'lib/restclient/request.rb', line 119

def parse_url_with_auth(url)
  uri = parse_url(url)
  @user = CGI.unescape(uri.user) if uri.user
  @password = CGI.unescape(uri.password) if uri.password
  uri
end

143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/restclient/request.rb', line 143

def print_verify_callback_warnings
  warned = false
  if RestClient::Platform.mac?
    warn('warning: ssl_verify_callback return code is ignored on OS X')
    warned = true
  end
  if RestClient::Platform.jruby?
    warn('warning: SSL verify_callback may not work correctly in jruby')
    warn('see https://github.com/jruby/jruby/issues/597')
    warned = true
  end
  warned
end

#process_payload(p = nil, parent_key = nil) ⇒ Object


126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/restclient/request.rb', line 126

def process_payload(p=nil, parent_key=nil)
  unless p.is_a?(Hash)
    p
  else
    @headers[:content_type] ||= 'application/x-www-form-urlencoded'
    p.keys.map do |k|
      key = parent_key ? "#{parent_key}[#{k}]" : k
      if p[k].is_a? Hash
        process_payload(p[k], key)
      else
        value = parser.escape(p[k].to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
        "#{key}=#{value}"
      end
    end.join("&")
  end
end

#process_result(res, &block) ⇒ Object


258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/restclient/request.rb', line 258

def process_result res, & block
  if @raw_response
    # We don't decode raw requests
    response = RawResponse.new(@tf, res, args)
  else
    response = Response.create(Request.decode(res['content-encoding'], res.body), res, args)
  end

  if block_given?
    block.call(response, self, res, & block)
  else
    response.return!(self, res, & block)
  end

end

#process_url_params(url, headers) ⇒ Object

Extract the query parameters and append them to the url


74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/restclient/request.rb', line 74

def process_url_params url, headers
  url_params = {}
  headers.delete_if do |key, value|
    if 'params' == key.to_s.downcase && value.is_a?(Hash)
      url_params.merge! value
      true
    else
      false
    end
  end
  unless url_params.empty?
    query_string = url_params.collect { |k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}" }.join('&')
    url + "?#{query_string}"
  else
    url
  end
end

#setup_credentials(req) ⇒ Object


226
227
228
# File 'lib/restclient/request.rb', line 226

def setup_credentials(req)
  req.basic_auth(user, password) if user
end

#stringify_headers(headers) ⇒ Object

Return a hash of headers whose keys are capitalized strings


310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/restclient/request.rb', line 310

def stringify_headers headers
  headers.inject({}) do |result, (key, value)|
    if key.is_a? Symbol
      key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')
    end
    if 'CONTENT-TYPE' == key.upcase
      target_value = value.to_s
      result[key] = MIME::Types.type_for_extension target_value
    elsif 'ACCEPT' == key.upcase
      # Accept can be composed of several comma-separated values
      if value.is_a? Array
        target_values = value
      else
        target_values = value.to_s.split ','
      end
      result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')
    else
      result[key] = value.to_s
    end
    result
  end
end

#transmit(uri, req, payload, &block) ⇒ Object


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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/restclient/request.rb', line 157

def transmit uri, req, payload, & block
  setup_credentials req

  net = net_http_class.new(uri.host, uri.port)
  net.use_ssl = uri.is_a?(URI::HTTPS)
  if @verify_ssl
    if @verify_ssl.is_a? Integer
      net.verify_mode = @verify_ssl
    else
      net.verify_mode = OpenSSL::SSL::VERIFY_PEER
    end
  else
    net.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  net.cert = @ssl_client_cert if @ssl_client_cert
  net.key = @ssl_client_key if @ssl_client_key
  net.ca_file = @ssl_ca_file if @ssl_ca_file
  net.read_timeout = @timeout if @timeout
  net.open_timeout = @open_timeout if @open_timeout

  # disable the timeout if the timeout value is -1
  net.read_timeout = nil if @timeout == -1
  net.open_timeout = nil if @open_timeout == -1

  # verify_callback isn't well supported on all platforms, but do allow
  # users to set one if they want.
  if ssl_verify_callback
    net.verify_callback = ssl_verify_callback

    # Hilariously, jruby only calls the callback when cert_store is set to
    # something, so make sure to set one.
    # https://github.com/jruby/jruby/issues/597
    if RestClient::Platform.jruby?
      net.cert_store ||= OpenSSL::X509::Store.new
    end

    if ssl_verify_callback_warnings != false
      if print_verify_callback_warnings
        warn('pass :ssl_verify_callback_warnings => false to silence this')
      end
    end
  end

  RestClient.before_execution_procs.each do |before_proc|
    before_proc.call(req, args)
  end

  log_request

  net.start do |http|
    if @block_response
      http.request(req, payload ? payload.to_s : nil, & @block_response)
    else
      res = http.request(req, payload ? payload.to_s : nil) { |http_response| fetch_body(http_response) }
      log_response res
      process_result res, & block
    end
  end
rescue EOFError
  raise RestClient::ServerBrokeConnection
rescue Timeout::Error
  raise RestClient::RequestTimeout
rescue OpenSSL::SSL::SSLError => error
  # UGH. Not sure if this is needed at all. SSLCertificateNotVerified is not being used internally.
  # I think it would be better to leave SSLError processing to the client (they'd have to do that anyway...)
  raise SSLCertificateNotVerified.new(error.message) if error.message.include?("certificate verify failed")
  raise error
end