Skip to content

Instantly share code, notes, and snippets.

@lisovskyvlad
Forked from gazay/proxy.rb
Created January 10, 2014 22:25
Show Gist options
  • Save lisovskyvlad/8363904 to your computer and use it in GitHub Desktop.
Save lisovskyvlad/8363904 to your computer and use it in GitHub Desktop.

Revisions

  1. @gazay gazay created this gist Oct 5, 2012.
    102 changes: 102 additions & 0 deletions proxy.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,102 @@
    # Based on https://gist.github.com/74107 by # Copyright (C) 2009 Torsten Becker <[email protected]>
    #
    # 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