2012-04-03 19:40:38 +00:00
|
|
|
require 'socket'
|
2011-08-26 21:35:40 +00:00
|
|
|
require 'openssl'
|
2012-04-03 19:40:38 +00:00
|
|
|
require 'timeout'
|
2011-08-26 21:35:40 +00:00
|
|
|
|
|
|
|
module Mongo
|
|
|
|
|
|
|
|
# A basic wrapper over Ruby's SSLSocket that initiates
|
|
|
|
# a TCP connection over SSL and then provides an basic interface
|
|
|
|
# mirroring Ruby's TCPSocket, vis., TCPSocket#send and TCPSocket#read.
|
|
|
|
class SSLSocket
|
|
|
|
|
2012-03-03 00:09:02 +00:00
|
|
|
attr_accessor :pool
|
|
|
|
|
2012-04-03 19:40:38 +00:00
|
|
|
def initialize(host, port, op_timeout=nil, connect_timeout=nil)
|
|
|
|
@op_timeout = op_timeout
|
|
|
|
@connect_timeout = connect_timeout
|
|
|
|
|
2012-04-08 14:48:25 +00:00
|
|
|
@socket = ::TCPSocket.new(host, port)
|
|
|
|
@socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
|
|
|
|
|
2011-08-26 21:35:40 +00:00
|
|
|
@ssl = OpenSSL::SSL::SSLSocket.new(@socket)
|
|
|
|
@ssl.sync_close = true
|
2012-04-03 19:40:38 +00:00
|
|
|
|
|
|
|
connect
|
2011-08-26 21:35:40 +00:00
|
|
|
end
|
|
|
|
|
2012-04-03 19:40:38 +00:00
|
|
|
def connect
|
|
|
|
if @connect_timeout
|
|
|
|
Timeout::timeout(@connect_timeout, ConnectionTimeoutError) do
|
|
|
|
@ssl.connect
|
|
|
|
end
|
|
|
|
else
|
|
|
|
@ssl.connect
|
|
|
|
end
|
2011-08-26 21:35:40 +00:00
|
|
|
end
|
|
|
|
|
2012-04-03 19:40:38 +00:00
|
|
|
def send(data)
|
|
|
|
@ssl.syswrite(data)
|
2011-08-26 21:35:40 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def read(length, buffer)
|
2012-04-03 19:40:38 +00:00
|
|
|
if @op_timeout
|
|
|
|
Timeout::timeout(@op_timeout, OperationTimeout) do
|
|
|
|
@ssl.sysread(length, buffer)
|
|
|
|
end
|
|
|
|
else
|
|
|
|
@ssl.sysread(length, buffer)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def setsockopt(key, value, n)
|
|
|
|
@ssl.setsockopt(key, value, n)
|
2011-08-26 21:35:40 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def close
|
|
|
|
@ssl.close
|
|
|
|
end
|
2012-04-03 19:40:38 +00:00
|
|
|
|
|
|
|
def closed?
|
|
|
|
@ssl.closed?
|
|
|
|
end
|
2011-08-26 21:35:40 +00:00
|
|
|
end
|
|
|
|
end
|