fog--fog/lib/fog/aws.rb

95 lines
2.5 KiB
Ruby
Raw Normal View History

2009-05-19 06:06:49 +00:00
require File.dirname(__FILE__) + '/aws/simpledb'
require File.dirname(__FILE__) + '/aws/s3'
require 'rubygems'
2009-06-22 05:13:01 +00:00
require 'openssl'
require 'socket'
require 'uri'
module Fog
module AWS
2009-06-22 05:13:01 +00:00
class Connection
2009-06-11 17:25:05 +00:00
2009-06-22 05:13:01 +00:00
def initialize(url)
@uri = URI.parse(url)
@connection = TCPSocket.open(@uri.host, @uri.port)
if @uri.scheme == 'https'
@ssl_context = OpenSSL::SSL::SSLContext.new
@ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
@connection = OpenSSL::SSL::SSLSocket.new(@connection, @ssl_context)
@connection.sync_close = true
@connection.connect
end
end
2009-06-22 05:13:01 +00:00
def request(params)
params = {
:headers => {}
}.merge(params)
uri = URI.parse(params[:url])
path = "#{uri.path}"
2009-06-22 17:06:49 +00:00
if uri.query
path << "?#{uri.query}"
end
2009-06-22 05:13:01 +00:00
host = "#{uri.host}"
2009-06-22 17:06:49 +00:00
if (uri.scheme == "http" && uri.port != 80) ||
(uri.scheme == 'https' && uri.port != 443)
host << ":#{uri.port}"
end
2009-06-22 05:13:01 +00:00
request = "#{params[:method]} #{path} HTTP/1.1\r\n"
params[:headers]['Host'] = uri.host
2009-06-22 17:06:49 +00:00
if params[:body]
params[:headers]['Content-Length'] = params[:body].length
end
2009-06-22 05:13:01 +00:00
for key, value in params[:headers]
request << "#{key}: #{value}\r\n"
end
2009-06-22 17:06:49 +00:00
request << "\r\n#{params[:body]}"
2009-06-22 05:13:01 +00:00
@connection.write(request)
2009-06-22 05:13:01 +00:00
response = AWS::Response.new
@connection.readline =~ /\AHTTP\/1.1 ([\d]{3})/
response.status = $1.to_i
while true
data = @connection.readline
2009-06-22 17:06:49 +00:00
if data == "\r\n"
break
end
2009-06-22 05:13:01 +00:00
if header = data.match(/(.*):\s(.*)\r\n/)
response.headers[header[1]] = header[2]
end
2009-06-22 05:13:01 +00:00
end
if response.headers['Content-Length']
content_length = response.headers['Content-Length'].to_i
response.body << @connection.read(content_length)
elsif response.headers['Transfer-Encoding'] == 'chunked'
while true
@connection.readline =~ /([a-f0-9]*)\r\n/i
chunk_size = $1.to_i(16) + 2 # 2 = "/r/n".length
response.body << @connection.read(chunk_size)
2009-06-22 17:06:49 +00:00
if $1.to_i(16) == 0
break
end
end
end
2009-06-22 05:13:01 +00:00
response
end
2009-06-22 05:13:01 +00:00
end
class Response
2009-06-22 05:13:01 +00:00
attr_accessor :status, :headers, :body
def initialize
2009-06-22 05:13:01 +00:00
@body = ''
@headers = {}
end
2009-06-22 05:13:01 +00:00
end
2009-06-22 05:13:01 +00:00
end
2009-06-07 07:54:40 +00:00
end