Skip to content

Instantly share code, notes, and snippets.

@octplane
Created January 26, 2011 08:24
Show Gist options
  • Save octplane/796418 to your computer and use it in GitHub Desktop.
Save octplane/796418 to your computer and use it in GitHub Desktop.
enforce a 3s timeout when writing to the network, monkey-patch against 1.8 ruby net/http
module Net
class HTTP < Protocol
def connect
D "opening connection to #{conn_address()}..."
s = timeout(@open_timeout) { TCPSocket.open(conn_address(), conn_port()) }
D "opened"
if use_ssl?
unless @ssl_context.verify_mode
warn "warning: peer certificate won't be verified in this SSL session"
@ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
# Fotonauts HACK, implement send timeout
# [url]http://www.mikeperham.com/2009/03/15/socket-timeouts-in-ruby/[/url]
timeout = 3
secs = Integer(timeout)
usecs = Integer((timeout - secs) * 1_000_000)
optval = [secs, usecs].pack("l_2")
s.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval)
# End of Fotonauts HACK
s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
s.sync_close = true
end
@socket = BufferedIO.new(s)
@socket.read_timeout = @read_timeout
@socket.debug_output = @debug_output
if use_ssl?
if proxy?
@socket.writeline sprintf('CONNECT %s:%s HTTP/%s',
@address, @port, HTTPVersion)
@socket.writeline "Host: #{@address}:#{@port}"
if proxy_user
credential = ["#{proxy_user}:#{proxy_pass}"].pack('m')
credential.delete!("\r\n")
@socket.writeline "Proxy-Authorization: Basic #{credential}"
end
@socket.writeline ''
HTTPResponse.read_new(@socket).value
end
s.connect
if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
s.post_connection_check(@address)
end
end
on_connect
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment