diff --git a/lib/Client.py b/lib/Client.py index 6219e29..007de66 100644 --- a/lib/Client.py +++ b/lib/Client.py @@ -5,87 +5,94 @@ import NetworkUtil as NU from Connectable import Connectable -from MIDaCSerializer import MSGType, MIDaCSerializationException, MIDaCSerializer; -from Logger import Logger; +from MIDaCSerializer import MSGType, MIDaCSerializationException, MIDaCSerializer +from Logger import Logger +#Class for storing client information and handle specific operations class Client(Connectable): - controllable = True; - midac = None; - connectingId = None; + controllable = True + midac = None + connectingId = None conf = None - LAO = None; - isWebsocket = False; - log = None; + LAO = None + isWebsocket = False + log = None def __init__(self, socket, size, address, port, connectingId, conf, LAO, log): - self.socket = socket; - self.messageSize = size; - self.midac = MIDaCSerializer(); - self.address = address; - self.port = port; - self.connectingId = connectingId; - self.conf = conf; - self.LAO = LAO; - self.log = log; + self.socket = socket + self.messageSize = size + self.midac = MIDaCSerializer() + self.address = address + self.port = port + self.connectingId = connectingId + self.conf = conf + self.LAO = LAO + self.log = log + #receives message and performs def receiveAndDecode(self): try: if self.isWebsocket: - return NU.decode(self.socket.recv(self.messageSize)); + return NU.decode(self.socket.recv(self.messageSize)) else: - return self.socket.recv(self.messageSize).decode("utf-8"); + return self.socket.recv(self.messageSize).decode("utf-8") except socket.error: - self.log.logAndPrintError("Connection reset by peer, if reocurring restart server"); + self.log.logAndPrintError("Connection reset by peer, if reocurring restart server") return False + #performs utf-8 encoding on msg and sends it or uses the webscoket send function def sendAndEncode(self, msg): if self.isWebsocket : NU.sendData(self.socket, msg) else: - self.socket.send(msg.encode("utf-8")); + self.socket.send(msg.encode("utf-8")) + #perform handshake def performHandshake(self): if not self.established: + #receive connreq or perform websocket handshake if client is connecting over websockets if self.handshakeStatus == 0: - inputMSG = self.receiveAndDecode(); + inputMSG = self.receiveAndDecode() if not inputMSG: self.socket.close() if inputMSG[:3] == "GET": handshake = NU.create_handshake(inputMSG) self.sendAndEncode(handshake) - self.isWebsocket = True; + self.isWebsocket = True else: try: - msg = json.loads(inputMSG); + msg = json.loads(inputMSG) if self.midac.GetMessageType(msg) == MSGType.ConnREQ: - self.handshakeStatus = 1; + self.handshakeStatus = 1 except ValueError: - self.log.logAndPrintError("Error while parsing input"); + self.log.logAndPrintError("Error while parsing input") + #send connack to client elif self.handshakeStatus == 1: - self.sendAndEncode(self.midac.GenerateConnACK("None", self.conf.SEGMENT_SIZE)); - self.handshakeStatus = 2; + self.sendAndEncode(self.midac.GenerateConnACK("None", self.conf.SEGMENT_SIZE)) + self.handshakeStatus = 2 + #send connlao to client elif self.handshakeStatus == 2: - #Creating test MIDaC Conn LAO here - self.sendAndEncode(self.LAO); - self.handshakeStatus = 3; + self.sendAndEncode(self.LAO) + self.handshakeStatus = 3 + #receive connstt and set status to established else: - inputMSG = self.receiveAndDecode(); + inputMSG = self.receiveAndDecode() if not inputMSG: - self.socket.close(); + self.socket.close() try: - msg = json.loads(inputMSG); + msg = json.loads(inputMSG) if self.midac.GetMessageType(msg) == MSGType.ConnSTT: - self.established = True; + self.established = True except ValueError: - self.established = False; + self.established = False else: - raise Exception("Handshake already performed"); + raise Exception("Handshake already performed") diff --git a/lib/ClientManager.py b/lib/ClientManager.py index 25ec4d9..85caa3a 100644 --- a/lib/ClientManager.py +++ b/lib/ClientManager.py @@ -6,120 +6,126 @@ import NetworkUtil as NU from Client import Client from ConfigHandler import ConfigHandler -from MIDaCSerializer import MSGType, MIDaCSerializationException, MIDaCSerializer; +from MIDaCSerializer import MSGType, MIDaCSerializationException, MIDaCSerializer +#Class for managing all connected clients class ClientManager(): - clients = None; - inputready = None; - outputready = None; - server = None; - newConnectedId = 0; + clients = None + inputready = None + outputready = None + server = None + newConnectedId = 0 - log = None; - conf = None; - LAO = None; + log = None + conf = None + LAO = None def __init__(self, server, log, conf, LAO): - self.clients = []; - self.inputready = []; - self.outputready = []; - self.server = server; - self.log = log; - self.conf = conf; - self.LAO = LAO; + self.clients = [] + self.inputready = [] + self.outputready = [] + self.server = server + self.log = log + self.conf = conf + self.LAO = LAO #Gets the socket descriptors of the clients, including an optional added socket descriptor def getClientsSockets(self, added): - sockets = added; + sockets = added for client in self.clients: - sockets.append(client.socket); - return sockets; + sockets.append(client.socket) + return sockets #get the stored client object that has the given socket descriptor def getClientBySocket(self, socket): - reqClient = None; + reqClient = None for client in self.clients: if client.socket == socket: - reqClient = client; + reqClient = client - return reqClient; + return reqClient + #get the handshaking clients def getHandshakeSockets(self): - handshaking = []; + handshaking = [] for client in self.clients: if not client.established: - handshaking.append(client); - return handshaking; + handshaking.append(client) + return handshaking + #performs select on all connected clients def update(self): - self.inputready, self.outputready, excepts = select.select(self.getClientsSockets([self.server]), self.getClientsSockets([]), []); + self.inputready, self.outputready, excepts = select.select(self.getClientsSockets([self.server]), self.getClientsSockets([]), []) + #creates client object and adds it to client list. performed when client connected def handleConnect(self): - client, address = self.server.accept(); - client.setblocking(0); + client, address = self.server.accept() + client.setblocking(0) - self.clients.append(Client(client, self.conf.SEGMENT_SIZE, address[0], address[1], self.newConnectedId, self.conf, self.LAO, self.log)); + self.clients.append(Client(client, self.conf.SEGMENT_SIZE, address[0], address[1], self.newConnectedId, self.conf, self.LAO, self.log)) - self.log.logAndPrintMessage("Client "+`self.newConnectedId`+" ("+address[0]+":"+`address[1]`+") connected"); - self.newConnectedId+=1; + self.log.logAndPrintMessage("Client "+`self.newConnectedId`+" ("+address[0]+":"+`address[1]`+") connected") + self.newConnectedId+=1 + #calls handshake handling function on every connected client that is in handshake mode def handleHandshake(self): for client in self.getHandshakeSockets(): if (client.socket in self.inputready and (client.handshakeStatus == 0 or client.handshakeStatus == 3 )) or (client.socket in self.outputready and (client.handshakeStatus == 1 or client.handshakeStatus == 2)): #try: - client.performHandshake(); + client.performHandshake() if client.established: - self.log.logAndPrintSuccess("Handshake with Client "+`client.connectingId`+" successful!"); + self.log.logAndPrintSuccess("Handshake with Client "+`client.connectingId`+" successful!") #except TypeError: # self.clients.remove(client) - # self.log.logAndPrintWarning("Client "+`client.connectingId`+" ("+client.address+":"+`client.port`+") disconnected!"); + # self.log.logAndPrintWarning("Client "+`client.connectingId`+" ("+client.address+":"+`client.port`+") disconnected!") if client.socket in self.inputready: - self.inputready.remove(client.socket); + self.inputready.remove(client.socket) if client.socket in self.outputready: - self.outputready.remove(client.socket); + self.outputready.remove(client.socket) + #handles input from clients (also used for disconnect) def handleInput(self): - control = None; + control = None for sock in self.inputready: if sock == self.server: - self.handleConnect(); + self.handleConnect() else: try: - client = self.getClientBySocket(sock); + client = self.getClientBySocket(sock) if client.isWebsocket: - data = client.receiveAndDecode(); + data = client.receiveAndDecode() else: - data = NU.multiReceive(sock, self.conf.SEGMENT_SIZE); + data = NU.multiReceive(sock, self.conf.SEGMENT_SIZE) if data: #Only the longest lasting connected can send if self.clients.index(self.getClientBySocket(sock)) == 0: try: - control = json.dumps(data); + control = json.dumps(data) except: - self.log.logAndPrintWarning("Unparseable client input"); + self.log.logAndPrintWarning("Unparseable client input") else: if(sock in self.inputready): - self.inputready.remove(sock); + self.inputready.remove(sock) if(sock in self.outputready): - self.outputready.remove(sock); - client = self.getClientBySocket(sock); - self.log.logAndPrintWarning("Client "+`client.connectingId`+" ("+client.address+":"+`client.port`+") disconnected!"); - self.clients.remove(client); + self.outputready.remove(sock) + client = self.getClientBySocket(sock) + self.log.logAndPrintWarning("Client "+`client.connectingId`+" ("+client.address+":"+`client.port`+") disconnected!") + self.clients.remove(client) except socket.error: - self.log.logAndPrintWarning("Socket Error"); - return control; - + self.log.logAndPrintWarning("Socket Error") + return control + #sends output to connected clients def handleOutput(self, msg): for sock in self.outputready: try: - client = self.getClientBySocket(sock); + client = self.getClientBySocket(sock) if client.isWebsocket: client.sendAndEncode(msg) else: - sock.send(msg); + sock.send(msg) except socket.error: - self.log.logAndPrintError("Broken pipe warning, if reocurring restart server"); + self.log.logAndPrintError("Broken pipe warning, if reocurring restart server") diff --git a/lib/ConfigHandler.py b/lib/ConfigHandler.py index f43e5cf..d239901 100644 --- a/lib/ConfigHandler.py +++ b/lib/ConfigHandler.py @@ -3,62 +3,65 @@ import os from sys import platform as _platform +#Used to store, load and manage the configuration class ConfigHandler(): - CONFIGPATH = "config.conf"; - PORT = 62626; - SAMPLERATE = 0.01; - HOST = 'localhost'; - BACKLOG = 20; - SEGMENT_SIZE = 2048; + CONFIGPATH = "config.conf" + PORT = 62626 + SAMPLERATE = 0.01 + HOST = 'localhost' + BACKLOG = 20 + SEGMENT_SIZE = 2048 - log = None; + log = None + #dirty trick to get current ip on eth0/en0/wlan0 (TODO: make it work based on settings not by guesstimation) def get_host(self): if _platform == "linux" or _platform == "linux2": - self.HOST = os.popen('ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1').read().strip(); + self.HOST = os.popen('ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1').read().strip() if _platform == "linux3": - self.HOST = os.popen('ifconfig wlan0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1').read().strip(); + self.HOST = os.popen('ifconfig wlan0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1').read().strip() if _platform == "darwin": - self.HOST = os.popen('ifconfig en0 | grep "inet " | cut -d" " -f2 | cut -d" " -f1').read().strip(); + self.HOST = os.popen('ifconfig en0 | grep "inet " | cut -d" " -f2 | cut -d" " -f1').read().strip() if _platform == "win32" or _platform == "win64": - self.log.logAndPrintWarning("Platform not supported, using 'localhost' for host"); + self.log.logAndPrintWarning("Platform not supported, using 'localhost' for host") + #loads the config file and prints the running config def __init__(self, path, log): - self.log = log; + self.log = log if path != "": - self.CONFIGPATH = path; + self.CONFIGPATH = path else: self.log.logAndPrintWarning("No configpath, using default") - config = json.loads(open(self.CONFIGPATH, 'r').read()); + config = json.loads(open(self.CONFIGPATH, 'r').read()) if "Server" in config: - config = config["Server"]; + config = config["Server"] if "Port" in config: - self.PORT = config["Port"]; + self.PORT = config["Port"] else: - self.log.logAndPrintWarning("No port in configfile, using default"); + self.log.logAndPrintWarning("No port in configfile, using default") if "Samplerate" in config: - self.SAMPLERATE = config["Samplerate"]; + self.SAMPLERATE = config["Samplerate"] else: - self.log.logAndPrintWarning("No samplerate in configfile, using default"); + self.log.logAndPrintWarning("No samplerate in configfile, using default") if "Backlog" in config: - self.BACKLOG = config["Backlog"]; + self.BACKLOG = config["Backlog"] else: - self.log.logAndPrintWarning("No backlog in configfile, using default"); + self.log.logAndPrintWarning("No backlog in configfile, using default") if "Segment_Size" in config: - self.SEGMENT_SIZE = config["Segment_Size"]; + self.SEGMENT_SIZE = config["Segment_Size"] else: - self.log.logAndPrintWarning("No segment size in configfile, using default"); + self.log.logAndPrintWarning("No segment size in configfile, using default") - self.get_host(); + self.get_host() else: - self.log.logAndPrintError("Invalid config file, using default values"); + self.log.logAndPrintError("Invalid config file, using default values") - ph = " ";#placeholder string for better looking output + ph = " " #placeholder string for better looking output self.log.logAndPrintMessage("Running config: \n"+ph+"CONFIGPATH "+self.CONFIGPATH+ "\n"+ph+"PORT "+`self.PORT`+"\n"+ph+"SAMPLERATE "+`self.SAMPLERATE`+"\n"+ph+"HOST "+self.HOST+ diff --git a/lib/Connectable.py b/lib/Connectable.py index 19e029c..17e2d84 100644 --- a/lib/Connectable.py +++ b/lib/Connectable.py @@ -1,13 +1,13 @@ class Connectable(): - socket = None; - handshakeStatus = 0; - established = False; - messageSize = None; - address = None; - port = None; + socket = None + handshakeStatus = 0 + established = False + messageSize = None + address = None + port = None def __init__(self, socket, size): - self.socket = socket; - self.messageSize = size; - self.handshakeStatus = 0; + self.socket = socket + self.messageSize = size + self.handshakeStatus = 0 diff --git a/lib/Logger.py b/lib/Logger.py index 2564d66..5390fe0 100644 --- a/lib/Logger.py +++ b/lib/Logger.py @@ -1,7 +1,8 @@ -import time; +import time +#used for colored and timed debug output with file logging ability class Logger(): - logfile_location = None; + logfile_location = None OK = '\033[32m' #Success Green WARNING = '\033[33m' #Warning Yellow @@ -10,68 +11,68 @@ class Logger(): ENDC = '\033[0m' def __init__(self, logfile_location): - self.logfile_location = logfile_location; - self.clearLogfile(); + self.logfile_location = logfile_location + self.clearLogfile() def logWithTime(self, text): with open(self.logfile_location, "a") as logfile: - logfile.write(time.strftime("%x %H:%M:%S") + " " + text+"\n"); + logfile.write(time.strftime("%x %H:%M:%S") + " " + text+"\n") def log(self, text): with open(self.logfile_location, "a") as logfile: - logfile.write(text+"\n"); + logfile.write(text+"\n") def printWithTime(self, text): - print(time.strftime("%x %H:%M:%S") + " " + text); + print(time.strftime("%x %H:%M:%S") + " " + text) def logWarning(self, text): - text = "[Warning] "+text; - self.logWithTime(text); + text = "[Warning] "+text + self.logWithTime(text) def logError(self, text): - text = "[Error] "+text; - self.logWithTime(text); + text = "[Error] "+text + self.logWithTime(text) def logSuccess(self, text): - text = "[Success] "+text; - self.logWithTime(text); + text = "[Success] "+text + self.logWithTime(text) def logMessage(self, text): - text = "[Message] "+text; - self.logWithTime(text); + text = "[Message] "+text + self.logWithTime(text) def printWarning(self, text): - text = self.WARNING+"[Warning]"+self.ENDC+" "+text; - self.printWithTime(text); + text = self.WARNING+"[Warning]"+self.ENDC+" "+text + self.printWithTime(text) def printError(self, text): - text = self.ERROR+"[Error]"+self.ENDC+" "+text; - self.printWithTime(text); + text = self.ERROR+"[Error]"+self.ENDC+" "+text + self.printWithTime(text) def printSuccess(self, text): - text = self.OK+"[Success]"+self.ENDC+" "+text; - self.printWithTime(text); + text = self.OK+"[Success]"+self.ENDC+" "+text + self.printWithTime(text) def printMessage(self, text): - text = self.MESSAGE+"[Message]"+self.ENDC+" "+text; - self.printWithTime(text); + text = self.MESSAGE+"[Message]"+self.ENDC+" "+text + self.printWithTime(text) def logAndPrintWarning(self, text): - self.logWarning(text); - self.printWarning(text); + self.logWarning(text) + self.printWarning(text) def logAndPrintError(self, text): - self.logError(text); - self.printError(text); + self.logError(text) + self.printError(text) def logAndPrintSuccess(self, text): - self.logSuccess(text); - self.printSuccess(text); + self.logSuccess(text) + self.printSuccess(text) def logAndPrintMessage(self, text): - self.logMessage(text); - self.printMessage(text); + self.logMessage(text) + self.printMessage(text) def clearLogfile(self): - self.printWarning("Clearing logfile"); - open(self.logfile_location, 'w').close(); + self.printWarning("Clearing logfile") + open(self.logfile_location, 'w').close() diff --git a/lib/MIDaCSerializer.py b/lib/MIDaCSerializer.py index cf22dc3..31fa8eb 100644 --- a/lib/MIDaCSerializer.py +++ b/lib/MIDaCSerializer.py @@ -1,48 +1,50 @@ import json +#ENUM style class for easier comparison class MSGType(): - ConnREQ = 1; - ConnACK = 2; - ConnREJ = 3; - ConnLAO = 4; - ConnSTT = 5; - ConnB = 6; - + ConnREQ = 1 + ConnACK = 2 + ConnREJ = 3 + ConnLAO = 4 + ConnSTT = 5 + ConnB = 6 + +#exception thrown when a message is not midac serializeable class MIDaCSerializationException(Exception): def __init__(self, value): - self.value = value; + self.value = value def __str__(self): - return "MIDaC Serialization Exception for "+repr(self.value); - + return "MIDaC Serialization Exception for "+repr(self.value) +#Class used to create, compare and serialze midac messages class MIDaCSerializer(): def GetMessageType(self, msg): if type(msg) is str: - json.loads(msg); + json.loads(msg) if type(msg) is dict: if "ConnLAO" in msg: - return MSGType.ConnLAO; + return MSGType.ConnLAO if "ConnACK" in msg: - return MSGType.ConnACK; + return MSGType.ConnACK if "ConnREQ" in msg: - return MSGType.ConnREQ; + return MSGType.ConnREQ if "ConnREJ" in msg: - return MSGType.ConnREJ; + return MSGType.ConnREJ if "ConnSTT" in msg: - return MSGType.ConnSTT; + return MSGType.ConnSTT if "B-Connect" in msg: - return MSGType.ConnB; + return MSGType.ConnB else: - raise MIDaCSerializationException(msg); + raise MIDaCSerializationException(msg) def GenerateConnACK(self, crypto, size): - ConnACK = {"ConnACK" : {"ChosenCrypto" : crypto, "SegmentSize" : size}}; - return json.dumps(ConnACK); + ConnACK = {"ConnACK" : {"ChosenCrypto" : crypto, "SegmentSize" : size}} + return json.dumps(ConnACK) def GenerateConnACK_B(self): - ConnACK = { "ConnACK" : ""}; - return json.dumps(ConnACK); + ConnACK = { "ConnACK" : ""} + return json.dumps(ConnACK) def GenerateConnLAO(self, integers, floats, bools, strings, sliders, buttons): ConnLAO = {"ConnLAO" : { @@ -59,7 +61,7 @@ def GenerateConnLAO(self, integers, floats, bools, strings, sliders, buttons): } } - return json.dumps(ConnLAO); + return json.dumps(ConnLAO) def GenerateConnREJ(self, message): ConnREJ = {"ConnREJ" : {"Error" : message}} @@ -72,7 +74,7 @@ def GenerateIntegerLAO(self, name, minbound, maxbound, graph): "MaxBound" : maxbound, } } - return IntLAO; + return IntLAO else: IntLAO = {name : { "DataType" : "Integer", @@ -81,7 +83,7 @@ def GenerateIntegerLAO(self, name, minbound, maxbound, graph): "Graph" : graph } } - return IntLAO; + return IntLAO def GenerateFloatLAO(self, name, minbound, maxbound, graph): if graph is None: @@ -116,7 +118,7 @@ def GenerateBoolLAO(self, name): "DataType" : "Bool" } } - return BoolLAO; + return BoolLAO def GenerateSliderLAO(self, name, maxbound, minbound): SliderLAO = {name : { @@ -125,7 +127,7 @@ def GenerateSliderLAO(self, name, maxbound, minbound): "MaxBound" : maxbound } } - return SliderLAO; + return SliderLAO def GenerateButtonLAO(self, name): ButtonLAO = {name : { diff --git a/lib/NetworkUtil.py b/lib/NetworkUtil.py index 0e0630a..4ae2310 100644 --- a/lib/NetworkUtil.py +++ b/lib/NetworkUtil.py @@ -1,33 +1,38 @@ import json -import select; -import socket; +import select +import socket import sys import base64 import struct import sha +#NetworkUtil contains functions used to simplify network communication + + +#receives and stitches multiple messages until they are midac parseable def multiReceive(client, SEGMENT_SIZE): - finished = False; - jsonMsg = None; - msg = client.recv(SEGMENT_SIZE).decode("utf-8"); + finished = False + jsonMsg = None + msg = client.recv(SEGMENT_SIZE).decode("utf-8") if not msg: - return False; + return False while not finished: try: - jsonMsg = json.loads(msg); + jsonMsg = json.loads(msg) - finished = True; + finished = True except ValueError: - inputready, outputready, excepts = select.select([client], [], []); + inputready, outputready, excepts = select.select([client], [], []) if len(inputready) == 1: - msg1 = client.recv(SEGMENT_SIZE).decode("utf-8"); - msg = msg+msg1; + msg1 = client.recv(SEGMENT_SIZE).decode("utf-8") + msg = msg+msg1 if not msg: - return False; - return jsonMsg; + return False + return jsonMsg +#creates the handshake message used to connect a websocket client def create_handshake(handshake): handshakelines = handshake.split("\r\n") matching = [s for s in handshakelines if "Sec-WebSocket-Key: " in s] @@ -39,6 +44,7 @@ def create_handshake(handshake): returning_handshake+="\r\n\r\n" return returning_handshake +#decodes messages from websockets def decode(data): frame = bytearray(data) @@ -63,10 +69,8 @@ def decode(data): return "".join(chr(byte) for byte in decoded) +#encodes messages for websockets def encode(data): - """ - Encode and send a WebSocket message - """ message = bytes() b1 = b'\x81' @@ -99,6 +103,7 @@ def encode(data): return message +#Masks messages for websockets and sends them def sendData(sock, data, fin=True, opcode=1, masking_key=False): if fin > 0x1: raise ValueError('FIN bit parameter must be 0 or 1') diff --git a/lib/RS.py b/lib/RS.py index 6b3b0c2..c82a913 100644 --- a/lib/RS.py +++ b/lib/RS.py @@ -9,12 +9,14 @@ from Logger import Logger from ConfigHandler import ConfigHandler +#class used to start, connect and manage the rsal class RS(): server_address = 'echo_socket' - connection = None; - sock = None; - LAO = None; + connection = None + sock = None + LAO = None + #initializes rs object, creates uds socket used for connection def __init__(self, conf, log): self.messageSize = conf.SEGMENT_SIZE self.conf = conf @@ -36,6 +38,7 @@ def __init__(self, conf, log): # Listen for incoming connections self.sock.listen(1) + #receives and stitches multiple messages until they are midac parseable def multiReceive(self): finished = False jsonMsg = None @@ -60,12 +63,15 @@ def multiReceive(self): return False return msg + #handles input from rsal def handleInput(self): return self.multiReceive().encode("utf-8") + #handles output to rsal def handleOutput(self, msg): print("Should implement sending function!") + #launches and connects rsal def connect(self): self.rsalProcss = Popen(['./RSAL/RSAL']) # Wait for a connection diff --git a/lib/__init__.py b/lib/__init__.py index 70c298d..6b7087f 100644 --- a/lib/__init__.py +++ b/lib/__init__.py @@ -1,4 +1,5 @@ +#simplifies import for main.py from Logger import Logger -from ClientManager import ClientManager; -from ConfigHandler import ConfigHandler; -from RS import RS; +from ClientManager import ClientManager +from ConfigHandler import ConfigHandler +from RS import RS diff --git a/lib/sha.py b/lib/sha.py index a481e1c..e2b107d 100644 --- a/lib/sha.py +++ b/lib/sha.py @@ -1,9 +1,11 @@ import struct import base64 +#left rotates byte def _left_rotate(n, b): return ((n << b) | (n >> (32 - b))) & 0xffffffff +#python only implementation of sha1 def sha1(message, hexDigest): """SHA-1 Hashing Function A custom SHA-1 hashing function implemented entirely in Python. @@ -74,9 +76,10 @@ def sha1(message, hexDigest): h3 = (h3 + d) & 0xffffffff h4 = (h4 + e) & 0xffffffff - # Produce the final hash value (big-endian): + # Produce the final hash value (big-endian): as hexdigest if hexDigest: return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4) + #as normal digest else: return ('%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4)).decode('hex') diff --git a/main.py b/main.py index 70b8947..1fc2664 100755 --- a/main.py +++ b/main.py @@ -1,62 +1,70 @@ #!/usr/bin/env python -import sys; -import socket; -import time; +import sys +import socket +import time #Own Libraries from lib import * -server = None; +server = None -print("MissionControl Server (MIDaC V1)\n"); +print("MissionControl Server (MIDaC V1)\n") -log = Logger("eventlog.log"); -conf = ConfigHandler("config.conf", log); +log = Logger("eventlog.log") +conf = ConfigHandler("config.conf", log) -log.logAndPrintMessage("Setting up server"); +log.logAndPrintMessage("Setting up server") +#Create Socket try: - server = socket.socket(socket.AF_INET, socket.SOCK_STREAM); - server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); - server.bind((conf.HOST, conf.PORT)); - server.listen(conf.BACKLOG); + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind((conf.HOST, conf.PORT)) + server.listen(conf.BACKLOG) except socket.error: if server: - server.close(); - log.logAndPrintError("Could not open socket: "+`sys.exc_info()[1]`); - sys.exit(); + server.close() + log.logAndPrintError("Could not open socket: "+`sys.exc_info()[1]`) + sys.exit() +#Create RSAL object, launch RSAL as subprocess and connect rsal = RS(conf, log) rsal.connect() -log.logAndPrintSuccess("RSAL Connected!"); - -log.logAndPrintSuccess("Server running!"); +log.logAndPrintSuccess("RSAL Connected!") +log.logAndPrintSuccess("Server running!") -clients = ClientManager(server, log, conf, rsal.LAO); -log.logAndPrintSuccess("Client Manager started!"); +#Create client manager +clients = ClientManager(server, log, conf, rsal.LAO) +log.logAndPrintSuccess("Client Manager started!") -running = True; +running = True +#main loop while running: try: - clients.update(); - clients.handleHandshake(); + #run select on all clients + clients.update() + #perform handshake operations with clients that are in handshake + clients.handleHandshake() - control = clients.handleInput(); + #receive input from connnected clients and send it to rsal + control = clients.handleInput() if control != None: - rsal.handleOutput(control); + rsal.handleOutput(control) - data = rsal.handleInput(); + #receive input from rsal and send it to all ready connected clients + data = rsal.handleInput() if data != None: - clients.handleOutput(data); + clients.handleOutput(data) - time.sleep(conf.SAMPLERATE); + #wait for steprate time + time.sleep(conf.SAMPLERATE) except KeyboardInterrupt: - server.close(); - log.logAndPrintWarning("Server manually stopped"); - sys.exit(); - rsal.rsalProcss.terminate(); + server.close() + rsal.rsalProcss.terminate() + log.logAndPrintWarning("Server manually stopped") + sys.exit() except: server.close() rsal.rsalProcss.terminate()