client/client/client.py

212 lines
7.0 KiB
Python

import getopt
import json
import os
import sys
from Crypto.PublicKey import RSA
from Crypto.PublicKey.RSA import RsaKey
from netwrapper import NetWrapper
ABSOLUTE_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
DOWNLOAD_LOCATION = ABSOLUTE_PATH + os.path.sep + 'download' + os.path.sep
CONFIG_LOCATION = ABSOLUTE_PATH + os.path.sep + 'config' + os.path.sep + 'config.txt'
PASSPHRASE = ''
SERVER_ADDRESS = ''
LOGGED_IN = False
def loadPublicKey() -> RsaKey:
with open(CONFIG_LOCATION) as json_file:
data = json.load(json_file)
key = data['publicServerKey']
key = bytes.fromhex(key)
try:
rsaKey = RSA.import_key(key)
except ValueError:
print('Invalid server public key!')
sys.exit(1)
return rsaKey
def loadPrivateKey(passphrase: str) -> RsaKey:
with open(CONFIG_LOCATION) as json_file:
data = json.load(json_file)
key = data['privateClientKey']
key = bytes.fromhex(key)
try:
rsaKey = RSA.import_key(key, passphrase)
except ValueError:
print('Invalid client key!')
sys.exit(1)
return rsaKey
def loadAddress() -> str:
with open(CONFIG_LOCATION) as json_file:
data = json.load(json_file)
return data['address']
def printCommand():
print('\nInvalid command! Available commands:\n' +
' Create directory -> MKD <directory name> \n' +
' Remove directory -> RMD <directory name> \n' +
' Get current directory -> GWD \n' +
' Change current directory -> CWD <path> \n' +
' List content of current directory -> LST \n' +
' Remove file from current directory -> RMF <filename> \n' +
' Upload file to current directory -> UPL <filename> \n' +
' Download file from current directory -> DNL <filename> \n' +
' Login -> LIN <username> <password> \n' +
' Logout -> LOUT \n')
def printCommandsWihtoutLogin():
print('\nYou must log in before issuing other commads!\n',
' Login -> LIN <username> <password> \n',
' Exit -> EXIT\n')
try:
opts, args = getopt.getopt(sys.argv[1:], 'hp:s:')
except getopt.GetoptError:
print('Error: Unknown option detected.')
sys.exit(1)
for opt, arg in opts:
if opt in '-p':
PASSPHRASE = arg
if opt in '-s':
SERVER_ADDRESS = arg
if PASSPHRASE == '':
print('Key required to start client!')
print('Usage:')
print(' client.py -p <passphrase> -s <server_address>')
sys.exit(1)
if not os.path.isfile(CONFIG_LOCATION) or os.stat(CONFIG_LOCATION).st_size == 0:
print('Invalid client config file')
sys.exit(1)
SERVER_PUBLIC_KEY = loadPublicKey()
CLIENT_PRIVATE_KEY = loadPrivateKey(PASSPHRASE)
CLIENT_ADDRESS = loadAddress()
LOGGED_IN = False
network = NetWrapper(CLIENT_PRIVATE_KEY, CLIENT_ADDRESS, SERVER_PUBLIC_KEY, serverAddr=SERVER_ADDRESS)
while True:
command = input("Type a command:")
separatedCommand = command.split(" ")
try:
if len(separatedCommand) > 3 or len(separatedCommand) < 1:
print("Invalid command format!")
continue
if not LOGGED_IN:
if separatedCommand[0] == 'LIN' and len(separatedCommand) == 3:
network.username = separatedCommand[1]
try:
network.connectToServer(separatedCommand[2])
response = network.recieveMessage().decode('UTF-8')
print(response)
if response == 'OK':
LOGGED_IN = True
else:
LOGGED_IN = False
except Exception as e:
print("Error: "+str(e))
LOGGED_IN = False
continue
else:
print('You are already logged in!')
if separatedCommand[0] == 'EXIT':
sys.exit(1)
if not LOGGED_IN:
printCommandsWihtoutLogin()
continue
if separatedCommand[0] == 'LOUT' and len(separatedCommand) == 1:
network.sendMessage(command.encode('UTF-8'))
print(network.recieveMessage().decode('UTF-8'))
LOGGED_IN = False
continue
if separatedCommand[0] == 'MKD' and len(separatedCommand) == 2:
network.sendMessage(command.encode('UTF-8'))
print(network.recieveMessage().decode('UTF-8'))
continue
if separatedCommand[0] == 'RMD' and len(separatedCommand) == 2:
network.sendMessage(command.encode('UTF-8'))
print(network.recieveMessage().decode('UTF-8'))
continue
if separatedCommand[0] == 'GWD' and len(separatedCommand) == 1:
network.sendMessage(command.encode('UTF-8'))
print(network.recieveMessage().decode('UTF-8'))
continue
if separatedCommand[0] == 'CWD' and len(separatedCommand) == 2:
network.sendMessage(command.encode('UTF-8'))
print(network.recieveMessage().decode('UTF-8'))
continue
if separatedCommand[0] == 'LST' and len(separatedCommand) == 1:
network.sendMessage(command.encode('UTF-8'))
print(network.recieveMessage().decode('UTF-8'))
continue
if separatedCommand[0] == 'RMF' and len(separatedCommand) == 2:
network.sendMessage(command.encode('UTF-8'))
print(network.recieveMessage().decode('UTF-8'))
continue
if separatedCommand[0] == 'UPL' and len(separatedCommand) == 2:
if os.path.isfile(separatedCommand[1]):
cmd = 'UPL ' + separatedCommand[1].split(os.path.sep)[-1]
network.sendMessage(cmd.encode('UTF-8'))
with open(separatedCommand[1], "rb") as file:
network.sendMessage(file.read())
network.sendMessage('EOF'.encode('UTF-8'))
response = network.recieveMessage().decode('UTF-8')
print(response)
else:
print('Invalid argument for file upload: ' + separatedCommand[1])
continue
if separatedCommand[0] == 'DNL' and len(separatedCommand) == 2:
dnlFilename = separatedCommand[1].split(os.path.sep)[-1]
cmd = 'DNL ' + dnlFilename
network.sendMessage(cmd.encode('UTF-8'))
filecontent = network.recieveMessage()
response = network.recieveMessage().decode('UTF-8')
print(DOWNLOAD_LOCATION + dnlFilename)
if response == 'EOF':
with open(DOWNLOAD_LOCATION + dnlFilename, "wb+") as file:
file.write(filecontent)
print('OK')
else:
print(response)
continue
printCommand()
except Exception as e:
print('Error: ' + str(e))
continue