Skip to content

Instantly share code, notes, and snippets.

@gazay
Created October 5, 2012 05:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gazay/3838303 to your computer and use it in GitHub Desktop.
Save gazay/3838303 to your computer and use it in GitHub Desktop.
Simple proxy server
# Based on https://gist.github.com/74107 by # Copyright (C) 2009 Torsten Becker <torsten.becker@gmail.com>
#
# Rewrited by gazay
require 'socket'
require 'uri'
class Proxy
attr_accessor :socket
def run(port)
begin
socket = TCPServer.new port
puts "listening on localhost:#{port}"
loop do
s = socket.accept
Thread.new s, &method(:handle_request)
end
ensure
if @socket
@socket.close
puts 'Socked closed..'
end
puts 'Quitting.'
end
end
def handle_request(client)
destination = client.readline
verb, url, version, uri = parse_request destination
server = TCPSocket.new(uri.host, (uri.port.nil? ? 80 : uri.port))
puts "#{verb} - #{url}"
send_request server, client, destination
send_response client, server
client.close
server.close
end
def parse_request(destination)
verb = destination[/^\w+/]
url = destination[/^\w+\s+(\S+)/, 1]
version = destination[/HTTP\/(1\.\d)\s*$/, 1]
uri = URI::parse url
[verb, url, version, uri]
end
def send_request(server, request, destination)
server.write destination
content_size = 0
request.lines.each do |line|
if line =~ /^Content-Length:\s+(\d+)\s*$/
content_size = $1.to_i
end
# Strip proxy headers
if line =~ /^proxy/i
next
elsif line.strip.empty?
server.write("Connection: close\r\n\r\n")
if content_size >= 0
server.write(request.read(content_size))
end
break
else
server.write(line)
end
end
end
def send_response(client, response)
buff = ""
loop do
response.read(4048, buff)
client.write(buff)
break if buff.size < 4048
end
end
end
# Get parameters and start the server
if ARGV.empty?
port = 8080
elsif ARGV.size == 1
port = ARGV[0].to_i
elsif ARGV.size == 2 and ARGV[0] == '-p'
port = ARGV[1].to_i
else
puts 'Usage: proxy.rb [port] or proxy.rb -p [port]'
exit 1
end
Proxy.new.run port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment