Skip to content

Instantly share code, notes, and snippets.

@hobodave
Created January 2, 2011 23:10
Show Gist options
  • Save hobodave/762920 to your computer and use it in GitHub Desktop.
Save hobodave/762920 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'eventmachine'
module ProxyConnection
def initialize(client, request)
@client, @request = client, request
end
def post_init
EM::enable_proxy(self, @client)
end
def connection_completed
send_data @request
end
def proxy_target_unbound
close_connection
end
def unbind
@client.close_connection_after_writing
end
end
module ProxyServer
def receive_data(data)
(@buf ||= "") << data
return if @buf.size < 9
null_index = @buf[8..-1].index("\0")
return if null_index.nil?
header_request = @buf.slice! 0, 9 + null_index
version, cmd, port, host = header_request.unpack("CCnA4")
if version != 4 || cmd != 1
resp = [0, 0x5b, 0, 0, 0, 0, 0, 0].pack("C8")
send_data resp
close_connection_after_writing
else
host = host.unpack("C*").join(".")
EM.connect host, port, ProxyConnection, self, data
send_data [0, 0x5a, 0, 0, 0, 0, 0, 0].pack("C8")
end
end
end
EventMachine::run {
EventMachine::start_server "127.0.0.1", 1080, ProxyServer
puts "running proxy"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment