mongo-ruby-driver/lib/mongo/util/ssl_socket.rb

64 lines
1.3 KiB
Ruby
Raw Permalink Normal View History

require 'socket'
2011-08-26 21:35:40 +00:00
require 'openssl'
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
attr_accessor :pool
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
connect
2011-08-26 21:35:40 +00:00
end
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
def send(data)
@ssl.syswrite(data)
2011-08-26 21:35:40 +00:00
end
def read(length, buffer)
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
def closed?
@ssl.closed?
end
2011-08-26 21:35:40 +00:00
end
end