2009-03-16 18:28:20 -04:00
|
|
|
require 'tempfile'
|
2009-12-29 14:30:38 -05:00
|
|
|
require 'mime/types'
|
2010-05-07 09:21:05 -04:00
|
|
|
require 'cgi'
|
2011-11-14 20:07:00 -05:00
|
|
|
require 'netrc'
|
2009-03-16 18:28:20 -04:00
|
|
|
|
2009-01-24 17:49:01 -05:00
|
|
|
module RestClient
|
2009-12-29 12:27:39 -05:00
|
|
|
# This class is used internally by RestClient to send the request, but you can also
|
|
|
|
# call it directly if you'd like to use a method not supported by the
|
|
|
|
# main API. For example:
|
|
|
|
#
|
|
|
|
# RestClient::Request.execute(:method => :head, :url => 'http://example.com')
|
|
|
|
#
|
|
|
|
# Mandatory parameters:
|
|
|
|
# * :method
|
|
|
|
# * :url
|
|
|
|
# Optional parameters (have a look at ssl and/or uri for some explanations):
|
|
|
|
# * :headers a hash containing the request headers
|
|
|
|
# * :cookies will replace possible cookies in the :headers
|
|
|
|
# * :user and :password for basic auth, will be replaced by a user/password available in the :url
|
2010-12-07 13:50:54 -05:00
|
|
|
# * :block_response call the provided block with the HTTPResponse as parameter
|
2009-12-29 12:27:39 -05:00
|
|
|
# * :raw_response return a low-level RawResponse instead of a Response
|
2010-12-18 12:15:04 -05:00
|
|
|
# * :max_redirects maximum number of redirections (default to 10)
|
2009-12-29 12:27:39 -05:00
|
|
|
# * :verify_ssl enable ssl verification, possible values are constants from OpenSSL::SSL
|
2011-08-22 12:10:45 -04:00
|
|
|
# * :timeout and :open_timeout passing in -1 will disable the timeout by setting the corresponding net timeout values to nil
|
2009-12-29 12:27:39 -05:00
|
|
|
# * :ssl_client_cert, :ssl_client_key, :ssl_ca_file
|
2012-12-08 00:34:22 -05:00
|
|
|
# * :ssl_version specifies the SSL version for the underlying Net::HTTP connection (defaults to 'SSLv3')
|
2009-12-29 12:27:39 -05:00
|
|
|
class Request
|
2010-01-18 16:15:15 -05:00
|
|
|
|
2010-01-31 07:31:30 -05:00
|
|
|
attr_reader :method, :url, :headers, :cookies,
|
2010-12-16 12:41:12 -05:00
|
|
|
:payload, :user, :password, :timeout, :max_redirects,
|
2010-01-31 07:31:30 -05:00
|
|
|
:open_timeout, :raw_response, :verify_ssl, :ssl_client_cert,
|
2012-12-08 00:34:22 -05:00
|
|
|
:ssl_client_key, :ssl_ca_file, :processed_headers, :args,
|
|
|
|
:ssl_version
|
2010-01-18 16:15:15 -05:00
|
|
|
|
2010-05-25 14:05:41 -04:00
|
|
|
def self.execute(args, & block)
|
|
|
|
new(args).execute(& block)
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
|
|
|
|
2010-01-22 15:04:49 -05:00
|
|
|
def initialize args
|
2009-12-29 12:27:39 -05:00
|
|
|
@method = args[:method] or raise ArgumentError, "must pass :method"
|
|
|
|
@headers = args[:headers] || {}
|
2010-05-25 14:05:41 -04:00
|
|
|
if args[:url]
|
2011-06-26 11:31:07 -04:00
|
|
|
@url = process_url_params(args[:url], headers)
|
2010-05-25 14:05:41 -04:00
|
|
|
else
|
|
|
|
raise ArgumentError, "must pass :url"
|
|
|
|
end
|
2009-12-29 12:27:39 -05:00
|
|
|
@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]
|
2010-12-07 13:50:54 -05:00
|
|
|
@block_response = args[:block_response]
|
2009-12-29 12:27:39 -05:00
|
|
|
@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
|
2012-12-08 00:34:22 -05:00
|
|
|
@ssl_version = args[:ssl_version] || 'SSLv3'
|
2009-12-29 12:27:39 -05:00
|
|
|
@tf = nil # If you are a raw request, this is your tempfile
|
2010-12-16 12:41:12 -05:00
|
|
|
@max_redirects = args[:max_redirects] || 10
|
2009-12-29 14:30:38 -05:00
|
|
|
@processed_headers = make_headers headers
|
2010-01-31 07:31:30 -05:00
|
|
|
@args = args
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
|
|
|
|
2010-05-25 14:05:41 -04:00
|
|
|
def execute & block
|
2009-12-29 12:27:39 -05:00
|
|
|
uri = parse_url_with_auth(url)
|
2010-05-25 14:05:41 -04:00
|
|
|
transmit uri, net_http_request_class(method).new(uri.request_uri, processed_headers), payload, & block
|
2011-07-05 18:56:27 -04:00
|
|
|
ensure
|
|
|
|
payload.close if payload
|
2010-05-25 14:05:41 -04:00
|
|
|
end
|
|
|
|
|
2011-06-26 11:31:07 -04:00
|
|
|
# Extract the query parameters and append them to the url
|
|
|
|
def process_url_params url, headers
|
|
|
|
url_params = {}
|
|
|
|
headers.delete_if do |key, value|
|
|
|
|
if 'params' == key.to_s.downcase && value.is_a?(Hash)
|
2011-08-22 12:10:45 -04:00
|
|
|
url_params.merge! value
|
2011-06-26 11:31:07 -04:00
|
|
|
true
|
2010-05-25 14:05:41 -04:00
|
|
|
else
|
2011-06-26 11:31:07 -04:00
|
|
|
false
|
2010-05-25 14:05:41 -04:00
|
|
|
end
|
2011-06-26 11:31:07 -04:00
|
|
|
end
|
2011-08-22 12:10:45 -04:00
|
|
|
unless url_params.empty?
|
|
|
|
query_string = url_params.collect { |k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}" }.join('&')
|
2011-06-26 11:31:07 -04:00
|
|
|
url + "?#{query_string}"
|
2010-05-25 14:05:41 -04:00
|
|
|
else
|
|
|
|
url
|
|
|
|
end
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
|
|
|
|
2009-12-29 14:30:38 -05:00
|
|
|
def make_headers user_headers
|
2009-12-29 12:27:39 -05:00
|
|
|
unless @cookies.empty?
|
2011-09-19 20:18:42 -04:00
|
|
|
user_headers[:cookie] = @cookies.map { |(key, val)| "#{key.to_s}=#{CGI::unescape(val.to_s)}" }.sort.join('; ')
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
2010-03-28 04:58:21 -04:00
|
|
|
headers = stringify_headers(default_headers).merge(stringify_headers(user_headers))
|
2009-12-29 12:27:39 -05:00
|
|
|
headers.merge!(@payload.headers) if @payload
|
|
|
|
headers
|
|
|
|
end
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
def net_http_request_class(method)
|
|
|
|
Net::HTTP.const_get(method.to_s.capitalize)
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse_url(url)
|
|
|
|
url = "http://#{url}" unless url.match(/^http/)
|
|
|
|
URI.parse(url)
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse_url_with_auth(url)
|
|
|
|
uri = parse_url(url)
|
2010-05-07 09:21:05 -04:00
|
|
|
@user = CGI.unescape(uri.user) if uri.user
|
|
|
|
@password = CGI.unescape(uri.password) if uri.password
|
2011-11-14 20:07:00 -05:00
|
|
|
if !@user && !@password
|
|
|
|
@user, @password = Netrc.read[uri.host]
|
|
|
|
end
|
2009-12-29 12:27:39 -05:00
|
|
|
uri
|
|
|
|
end
|
|
|
|
|
|
|
|
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 = URI.escape(p[k].to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
|
|
|
|
"#{key}=#{value}"
|
|
|
|
end
|
|
|
|
end.join("&")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2010-05-25 14:05:41 -04:00
|
|
|
def transmit uri, req, payload, & block
|
2010-01-22 15:04:49 -05:00
|
|
|
setup_credentials req
|
2009-12-29 12:27:39 -05:00
|
|
|
|
|
|
|
net = net_http_class.new(uri.host, uri.port)
|
|
|
|
net.use_ssl = uri.is_a?(URI::HTTPS)
|
2012-12-08 00:34:22 -05:00
|
|
|
net.ssl_version = @ssl_version
|
2011-05-06 11:19:47 -04:00
|
|
|
if (@verify_ssl == false) || (@verify_ssl == OpenSSL::SSL::VERIFY_NONE)
|
2009-12-29 12:27:39 -05:00
|
|
|
net.verify_mode = OpenSSL::SSL::VERIFY_NONE
|
|
|
|
elsif @verify_ssl.is_a? Integer
|
|
|
|
net.verify_mode = @verify_ssl
|
2012-12-08 00:34:22 -05:00
|
|
|
net.verify_callback = lambda do |preverify_ok, ssl_context|
|
|
|
|
if (!preverify_ok) || ssl_context.error != 0
|
|
|
|
err_msg = "SSL Verification failed -- Preverify: #{preverify_ok}, Error: #{ssl_context.error_string} (#{ssl_context.error})"
|
|
|
|
raise SSLCertificateNotVerified.new(err_msg)
|
|
|
|
end
|
|
|
|
true
|
|
|
|
end
|
2009-12-29 12:27:39 -05:00
|
|
|
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
|
|
|
|
|
2011-08-22 12:10:45 -04:00
|
|
|
# disable the timeout if the timeout value is -1
|
|
|
|
net.read_timeout = nil if @timeout == -1
|
|
|
|
net.out_timeout = nil if @open_timeout == -1
|
|
|
|
|
2010-03-05 19:55:56 -05:00
|
|
|
RestClient.before_execution_procs.each do |before_proc|
|
|
|
|
before_proc.call(req, args)
|
2010-01-31 07:31:30 -05:00
|
|
|
end
|
|
|
|
|
2010-01-05 15:03:27 -05:00
|
|
|
log_request
|
2009-12-29 12:27:39 -05:00
|
|
|
|
|
|
|
net.start do |http|
|
2010-12-07 13:50:54 -05:00
|
|
|
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
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
|
|
|
rescue EOFError
|
|
|
|
raise RestClient::ServerBrokeConnection
|
|
|
|
rescue Timeout::Error
|
|
|
|
raise RestClient::RequestTimeout
|
|
|
|
end
|
|
|
|
|
|
|
|
def setup_credentials(req)
|
|
|
|
req.basic_auth(user, password) if user
|
|
|
|
end
|
|
|
|
|
|
|
|
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|
|
2010-01-22 15:04:49 -05:00
|
|
|
@tf.write chunk
|
2009-12-29 12:27:39 -05:00
|
|
|
size += chunk.size
|
2010-01-05 15:03:27 -05:00
|
|
|
if RestClient.log
|
|
|
|
if size == 0
|
2010-01-24 11:22:48 -05:00
|
|
|
RestClient.log << "#{@method} #{@url} done (0 length file\n)"
|
2010-01-05 15:03:27 -05:00
|
|
|
elsif total == 0
|
2010-01-24 11:22:48 -05:00
|
|
|
RestClient.log << "#{@method} #{@url} (zero content length)\n"
|
2010-01-05 15:03:27 -05:00
|
|
|
else
|
2010-01-24 11:22:48 -05:00
|
|
|
RestClient.log << "#{@method} #{@url} %d%% done (%d of %d)\n" % [(size * 100) / total, size, total]
|
2010-01-05 15:03:27 -05:00
|
|
|
end
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
@tf.close
|
|
|
|
@tf
|
|
|
|
else
|
|
|
|
http_response.read_body
|
|
|
|
end
|
|
|
|
http_response
|
|
|
|
end
|
|
|
|
|
2010-05-25 14:05:41 -04:00
|
|
|
def process_result res, & block
|
2010-01-18 16:15:15 -05:00
|
|
|
if @raw_response
|
2009-12-29 12:27:39 -05:00
|
|
|
# We don't decode raw requests
|
2010-02-10 15:31:59 -05:00
|
|
|
response = RawResponse.new(@tf, res, args)
|
2010-01-18 16:15:15 -05:00
|
|
|
else
|
2010-03-29 13:38:23 -04:00
|
|
|
response = Response.create(Request.decode(res['content-encoding'], res.body), res, args)
|
2010-01-18 16:15:15 -05:00
|
|
|
end
|
|
|
|
|
2010-02-10 15:31:59 -05:00
|
|
|
if block_given?
|
2010-07-04 14:36:16 -04:00
|
|
|
block.call(response, self, res, & block)
|
2009-12-29 12:27:39 -05:00
|
|
|
else
|
2010-07-04 14:36:16 -04:00
|
|
|
response.return!(self, res, & block)
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
2010-02-10 15:31:59 -05:00
|
|
|
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
|
|
|
|
2010-01-18 16:15:15 -05:00
|
|
|
def self.decode content_encoding, body
|
2010-02-24 12:28:29 -05:00
|
|
|
if (!body) || body.empty?
|
|
|
|
body
|
|
|
|
elsif content_encoding == 'gzip'
|
2009-12-29 12:27:39 -05:00
|
|
|
Zlib::GzipReader.new(StringIO.new(body)).read
|
|
|
|
elsif content_encoding == 'deflate'
|
2011-06-04 18:35:46 -04:00
|
|
|
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
|
2009-12-29 12:27:39 -05:00
|
|
|
else
|
|
|
|
body
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2010-01-05 15:03:27 -05:00
|
|
|
def log_request
|
2009-12-29 14:30:38 -05:00
|
|
|
if RestClient.log
|
|
|
|
out = []
|
|
|
|
out << "RestClient.#{method} #{url.inspect}"
|
2010-01-05 15:03:27 -05:00
|
|
|
out << payload.short_inspect if payload
|
2010-05-25 14:05:41 -04:00
|
|
|
out << processed_headers.to_a.sort.map { |(k, v)| [k.inspect, v.inspect].join("=>") }.join(", ")
|
2010-01-24 11:22:48 -05:00
|
|
|
RestClient.log << out.join(', ') + "\n"
|
2009-12-29 14:30:38 -05:00
|
|
|
end
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
|
|
|
|
2010-01-05 15:03:27 -05:00
|
|
|
def log_response res
|
|
|
|
if RestClient.log
|
|
|
|
size = @raw_response ? File.size(@tf.path) : (res.body.nil? ? 0 : res.body.size)
|
2010-01-24 11:22:48 -05:00
|
|
|
RestClient.log << "# => #{res.code} #{res.class.to_s.gsub(/^Net::HTTP/, '')} | #{(res['Content-type'] || '').gsub(/;.*$/, '')} #{size} bytes\n"
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2010-03-28 04:58:21 -04:00
|
|
|
# Return a hash of headers whose keys are capitalized strings
|
|
|
|
def stringify_headers headers
|
|
|
|
headers.inject({}) do |result, (key, value)|
|
2010-04-30 13:02:36 -04:00
|
|
|
if key.is_a? Symbol
|
2010-05-25 14:05:41 -04:00
|
|
|
key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')
|
2010-04-30 13:02:36 -04:00
|
|
|
end
|
|
|
|
if 'CONTENT-TYPE' == key.upcase
|
2010-03-28 04:58:21 -04:00
|
|
|
target_value = value.to_s
|
2010-04-30 13:02:36 -04:00
|
|
|
result[key] = MIME::Types.type_for_extension target_value
|
|
|
|
elsif 'ACCEPT' == key.upcase
|
2010-03-28 04:58:21 -04:00
|
|
|
# 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
|
2010-05-25 14:05:41 -04:00
|
|
|
result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')
|
2010-03-28 04:58:21 -04:00
|
|
|
else
|
2010-04-30 13:02:36 -04:00
|
|
|
result[key] = value.to_s
|
2010-03-28 04:58:21 -04:00
|
|
|
end
|
|
|
|
result
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2009-12-29 12:27:39 -05:00
|
|
|
def default_headers
|
2010-05-25 14:05:41 -04:00
|
|
|
{:accept => '*/*; q=0.5, application/xml', :accept_encoding => 'gzip, deflate'}
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
2010-03-28 04:58:21 -04:00
|
|
|
|
2009-12-29 12:27:39 -05:00
|
|
|
end
|
2009-01-24 17:49:01 -05:00
|
|
|
end
|
2009-12-29 14:30:38 -05:00
|
|
|
|
|
|
|
module MIME
|
|
|
|
class Types
|
|
|
|
|
|
|
|
# Return the first found content-type for a value considered as an extension or the value itself
|
|
|
|
def type_for_extension ext
|
2010-01-05 15:03:27 -05:00
|
|
|
candidates = @extension_index[ext]
|
2009-12-29 14:30:38 -05:00
|
|
|
candidates.empty? ? ext : candidates[0].content_type
|
|
|
|
end
|
|
|
|
|
|
|
|
class << self
|
|
|
|
def type_for_extension ext
|
|
|
|
@__types__.type_for_extension ext
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2012-12-08 00:37:14 -05:00
|
|
|
end
|