Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- #credits to Copyright (C) 2009 Torsten Becker <torsten.becker@gmail.com> for the proxy bases
- #credits to &eric for work in progress url parser
- require 'socket'
- require 'uri'
- require "base64"
- class Proxy
- def run port
- begin
- # Start our server to handle connections (will raise things on errors)
- @socket = TCPServer.new port
- s = @socket
- # Handle every request in another thread
- loop do
- s = @socket.accept
- Thread.new s, &method(:handle_request)
- puts "Peer connected"
- end
- # CTRL-C
- rescue Interrupt
- puts 'Got Interrupt..'
- # Ensure that we release the socket on errors
- ensure
- if @socket
- @socket.close
- puts 'Socked closed..'
- end
- puts 'Quitting.'
- end
- end
- def handle_request to_client
- request_line = to_client.readline
- verb = request_line[/^\w+/]
- url = request_line[/^\w+\s+(\S+)/, 1]
- version = request_line[/HTTP\/(1\.\d)\s*$/, 1]
- uri = URI::parse url
- #Show what got requested
- puts((" %4s "%verb) + url)
- urlc = url.gsub( /https?:\/\//, "\\1")
- urlp = url.gsub( /https?:\/\/(.+?)(?>\/)(?:\/$)?/, "\\1")
- #############################IRC####################################
- if(verb == "CONNECT")
- host ,ircport = urlp.split(":")
- contents = File.read('m/hosts/'+host)
- ircip = Base64.decode64(contents)
- irc, ircpt = ircip.split(",")
- puts "Main irc network"
- p= TCPSocket.new(irc, ircpt)
- puts "Connecting to #{contents} port: #{ircpt}"
- loop do
- msg = p.gets #get everything from irc server
- to_client.write(msg) #write it to client or Hexchat
- puts msg
- request = request_line #get all the info from Hexchat
- send = p.puts(request)#send the Hexchat info to server
- end
- ####################################################################
- else
- contents = File.read('m/hosts/'+urlp)
- hostip = Base64.decode64(contents)
- ip, port = hostip.split(",")
- puts "Connecting to #{contents} port: #{port}"
- to_server = TCPSocket.new(ip, (uri.port.nil? ? 80 : uri.port))
- to_server.write("#{verb} #{uri.path}?#{uri.query} HTTP/#{version}\r\n")
- end
- content_len = 0
- loop do
- line = to_client.readline
- puts line
- if line =~ /^Content-Length:\s+(\d+)\s*$/
- content_len = $1.to_i
- end
- # Strip proxy headers
- if line =~ /^proxy/i
- next
- elsif line.strip.empty?
- to_server.write("Connection: close\r\n\r\n")
- if content_len >= 0
- to_server.write(to_client.read(content_len))
- end
- break
- else
- to_server.write(line)
- end
- end
- buff = ""
- loop do
- to_server.read(4048, buff)
- to_client.write(buff)
- break if buff.size < 4048
- end
- # Close the sockets
- to_client.close
- to_server.close
- end
- end
- # Get parameters and start the server
- if ARGV.empty?
- port = 8181
- elsif ARGV.size == 1
- port = ARGV[0].to_i
- else
- puts 'Usage: proxy.rb [port]'
- exit 1
- end
- Proxy.new.run port
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement