#!/usr/bin/python
# a proxy like script that logs the whole traffic

import socket
from select import select
import os.path
import datetime

REMOTE_HOST = '83.150.67.106'
REMOTE_PORT = 23
#REMOTE_HOST = '127.0.0.1'
#REMOTE_PORT = 2323
LOCAL_HOST = ''
LOCAL_PORT = 2323
TIMEOUT = 30
LOGDIR = '/home/dyuri/icesus/log/'
LOGPREFIX = 'color_'
LOGPOSTFIX = '_icesus.log'

def get_logfile():
    today = datetime.date.today()
    filename = LOGPREFIX + "%4d-%02d-%02d" % (today.year, today.month, today.day) + LOGPOSTFIX
    return open(os.path.join(LOGDIR, filename), "a+b")

def log(logfile, data, direction=None):
    if direction == 'out':
        logfile.write('< ')
    logfile.write(data)

def main():
    addr = (LOCAL_HOST, LOCAL_PORT)
    ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ssocket.bind(addr)
    ssocket.settimeout(TIMEOUT)
    ssocket.listen(1)

    try:
        while 1:
            # accept the incoming connection
            try:
                csocket, caddr = ssocket.accept()
            except KeyboardInterrupt:
                break
            except:
                continue
            
            # connect to remote host
            disconnect = False
            rsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            rsocket.settimeout(TIMEOUT)
            try:
                rsocket.connect((REMOTE_HOST, REMOTE_PORT))
            except:
                disconnect = True

            # logfile should be opened here
            logfile = get_logfile()

            # select loop
            while not disconnect:

                readysockets = select([csocket, rsocket], [], [], 1)[0]
                for s in readysockets:
                    try:
                        data = s.recv(16384)
                    except:
                        disconnect = True
                        break

                    if len(data) == 0:
                        # peer disconnected
                        disconnect = True
                        break

                    if s == csocket:
                        t = rsocket
                        direction = 'out'
                    else:
                        t = csocket
                        direction = 'in'

                    # write the date into the logfile
                    log(logfile, data, direction)

                    # forward the data
                    try:
                        t.send(data)
                    except:
                        disconnect = True
                        break
            
            # close connections
            try:
                csocket.close()
            except:
                pass

            try:
                rsocket.close()
            except:
                pass

            # close logfile
            logfile.close()

    finally:
        ssocket.close()

main()

