#****************************************************
# *
# HTTP PROXY *
# Version: 1.0 *
# Author: Luu Gia Thuy *
# Modified by Febru Wasono*
#****************************************************

import os,sys,thread,socket

#********* CONSTANT VARIABLES *********
BACKLOG = 50 # how many pending connections queue will hold
MAX_DATA_RECV = 4096 # max number of bytes we receive at once
DEBUG = False # set to True to see the debug msgs

#**************************************
#********* MAIN PROGRAM ***************
#**************************************
def main():

    # check the length of command running
    if (len(sys.argv)<2):
        print "usage: proxy <port>"
        return sys.stdout

    # host and port info.
    host = '' # blank for localhost
    port = int(sys.argv[1]) # port from argument
    
    try:
        # create a socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # associate the socket to host and port
        s.bind((host, port))

        # listenning
        s.listen(BACKLOG)
    
    except socket.error, (value, message):
        if s:
            s.close()
        print "Could not open socket:", message
        sys.exit(1)

    # get the connection from client
    while 1:
        conn, client_addr = s.accept()

        # create a thread to handle request
        thread.start_new_thread(proxy_thread, (conn, client_addr))
        
    s.close()
#************** END MAIN PROGRAM ***************


#*******************************************
#********* PROXY_THREAD FUNC ***************
# A thread to handle request from browser
#*******************************************
def proxy_thread(conn, client_addr):

    # get the request from browser
    request = conn.recv(MAX_DATA_RECV)
    
    if (request.find('\n')!=-1 or request.find(' ')!=-1):
        # parse the first line
        first_line = request.split('\n')[0]
        # get url
        url = first_line.split(' ')[1]
        print request
    else:
        first_line= url = ''
    if (DEBUG):
        print first_line
        print "request", unicode(request)
        print "URL:",url
        print
    
    # find the webserver and port
    http_pos = url.find("://") # find pos of ://
    if (http_pos==-1):
        temp = url
    else:
        temp = url[(http_pos+3):] # get the rest of url
    
    port_pos = temp.find(":") # find the port pos (if any)

    # find end of web server
    webserver_pos = temp.find("/")
    if webserver_pos == -1:
        webserver_pos = len(temp)

    webserver = "10.1.89.130"  # << the victims here please mas bro
    port = 8000 # the port of victims di sini ya...
#    port = -1
#    if (port_pos==-1 or webserver_pos < port_pos): # default port
#        port = 80
#        webserver = temp[:webserver_pos]
#    else: # specific port
#        port = int((temp[(port_pos+1):])[:webserver_pos-port_pos-1])
#        webserver = temp[:port_pos]

    print "Connect to:", webserver, port
    #request.replace('CONNECT', 'GET')
    fake_request = """
    DELETE ads·telkomsel·com:80 HTTP/1.1
    User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0
    Proxy-Connection: keep-alive
    Connection: keep-alive
    Host: ads·telkomsel·com \r\r"""
    try:
        # create a socket to connect to the web server
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((webserver, port))
        s.send(fake_request)
        s.send(request) # send request to webserver

        while 1:
            # receive data from web server
            data = s.recv(MAX_DATA_RECV)
            
            if (len(data) > 0):
                # send to browser
                conn.send(data)
            else:
                break
        s.close()
        conn.close()
    except socket.error, (value, message):
        if s:
            s.close()
        if conn:
            conn.close()
        print "Runtime Error:", message
        sys.exit(1)
#********** END PROXY_THREAD ***********
    
if __name__ == '__main__':
    main()


