From 910d11b6b60a2716691261123383ec97e72d3fef Mon Sep 17 00:00:00 2001 From: Scratchcat1 Date: Thu, 19 Oct 2017 13:51:49 +0100 Subject: [PATCH] Add files via upload -Modified Server 002 to start moving identical components for User,Monitor and Drone Connections into a parent class ClientConnection --- AATC_Client_Text_UI.py | 27 +++-- AATC_Crypto.py | 8 +- AATC_DB.py | 4 +- AATC_Server_002.py | 256 +++++++++-------------------------------- AATC_Server_Starter.py | 2 +- HedaBot.py | 2 +- 6 files changed, 76 insertions(+), 223 deletions(-) diff --git a/AATC_Client_Text_UI.py b/AATC_Client_Text_UI.py index 165f260..de8a284 100644 --- a/AATC_Client_Text_UI.py +++ b/AATC_Client_Text_UI.py @@ -361,17 +361,14 @@ def GetMonitorPermissionUser(self): ################################################# def Call_Exit(self): - Choice = input("Exit? (Y/N) >>").upper() - if Choice == "Y": - print("Exiting..") - try: - Sucess,Message = self.UserInterface.Exit() - self.DisplayResults(Sucess,Message) - except: - print("Unable to close server connection") - self.Exit = True - else: - print("Exit cancelled") + print("Exiting..") + try: + Sucess,Message = self.UserInterface.Exit() + self.DisplayResults(Sucess,Message) + except: + print("Unable to close server connection") + self.Exit = True + @@ -386,7 +383,13 @@ def Call_Exit(self): TextUI = UserTextUI(U,MenuOptions) TextUI.Main_Loop() - Exit = True #When user selects exit + + Choice = input("Exit? (Y/N) >>").upper() + if Choice == "Y": + print("Exiting") + Exit = True #When user selects exit + else: + print("Exit cancelled") except Exception as e: print("Error occured creating user interface",e) diff --git a/AATC_Crypto.py b/AATC_Crypto.py index d99635d..8e81490 100644 --- a/AATC_Crypto.py +++ b/AATC_Crypto.py @@ -81,14 +81,15 @@ def ServerGenerateKey(self): if Command == "ExchangeKey": publicKey,AES_KeySize = Arguments[0],Arguments[1] + if AES_KeySize not in AATC_Config.ALLOWED_AES_KEYSIZES: AES_KeySize = AATC_Config.DEFAULT_AES_KEYSIZE #If key size is not valid set size to default of AATC_Config.DEFAULT_AES_KEYSIZE self.AESKey = binascii.b2a_hex(os.urandom(AES_KeySize//2)) # Here to allow regeneration of AES key while still in loop if required. - self.IV = binascii.b2a_hex(os.urandom(AES_KeySize//2)) + self.IV = binascii.b2a_hex(os.urandom(AES_KeySize//2)) - RSAPrivateKey = RSA.import_key(publicKey) - PublicKeyObject = PKCS1_OAEP.new(RSAPrivateKey) + RSAPublicKey = RSA.import_key(publicKey) + PublicKeyObject = PKCS1_OAEP.new(RSAPublicKey) EncryptedAESKey = PublicKeyObject.encrypt(self.AESKey) EncryptedIV = PublicKeyObject.encrypt(self.IV) @@ -136,6 +137,5 @@ def Send(self,data): def Recv(self): data = recvall.recvall(self.con) data = ast.literal_eval(codecs.decode(data)) - # (Command,Arguments) return data diff --git a/AATC_DB.py b/AATC_DB.py index d183c97..17576fa 100644 --- a/AATC_DB.py +++ b/AATC_DB.py @@ -200,7 +200,7 @@ def RemoveFlight(self,UserID,FlightID): def CheckForFlight(self,DroneID,MaxLookAheadTime): InvalidateDelay = 1800 - self.cur.execute("SELECT FlightID FROM Flight WHERE DroneID = %s AND StartTime < (%s+%s) AND StartTime > (%s-%s) ORDER BY StartTime ASC LIMIT 1",(DroneID,GetTime(),MaxLookAheadTime, GetTime(),InvalidateDelay)) + self.cur.execute("SELECT FlightID FROM Flight WHERE DroneID = %s AND StartTime < (%s+%s) AND StartTime > (%s-%s) AND Completed = 0 ORDER BY StartTime ASC LIMIT 1",(DroneID,GetTime(),MaxLookAheadTime, GetTime(),InvalidateDelay)) FlightIDFetch = self.cur.fetchall() self.db_con.commit() if FlightIDFetch != (): @@ -227,7 +227,7 @@ def MarkFlightComplete(self,DroneID,FlightID,Code): return False,"You do not have permission to mark this flight complete" def GetCompletedFlightIDs(self,EndTimeThreshold): - self.cur.execute("SELECT FlightID FROM Flight WHERE Completed > 0 AND (EndTime + %s) > %s",(EndTimeThreshold,GetTime())) + self.cur.execute("SELECT FlightID FROM Flight WHERE (Completed > 0 AND (EndTime + %s) > %s) OR (EndTime+ %s) > %s",(EndTimeThreshold,GetTime(),EndTimeThreshold*3,GetTime())) return True,"['FlightID']",self.cur.fetchall() def CleanCompletedFlights(self,EndTimeThreshold): diff --git a/AATC_Server_002.py b/AATC_Server_002.py index c42a1e3..cc589b2 100644 --- a/AATC_Server_002.py +++ b/AATC_Server_002.py @@ -18,10 +18,25 @@ def CoordLessThanOrEqual(Coord1,Coord2):# True if Coord1 <= Coord2 +class ClientConnection: + """This is the base class for Connections, all other connection objects will inherit from this object. + Will contain all similar components i.e. send, receive + + """ + + def Send(self,data): + self.con.sendall(self.Crypto.Encrypt(codecs.encode(str(data)))) + def Recv(self): + try: + data = self.Crypto.Decrypt(recvall.recvall(self.con)) + data = ast.literal_eval(codecs.decode(data)) + return data + except Exception as e: + return ("",())#Never references a command + - -class UserConnection: +class UserConnection(ClientConnection): def __init__(self,Thread_Name,Thread_Queue,Connection): self.DB = AATC_DB.DBConnection() self.Thread_Name = Thread_Name @@ -30,18 +45,7 @@ def __init__(self,Thread_Name,Thread_Queue,Connection): self.Crypto = AATC_Crypto.Crypter(self.con, mode = "SERVER" ) self.UserID = -1 #Used to identify if has logged in yet self.NOFLYZONE_THRESHOLD_COST = 50 - def Send(self,data): - self.con.sendall(self.Crypto.Encrypt(codecs.encode(str(data)))) - def Recv(self): - try: - data = self.Crypto.Decrypt(recvall.recvall(self.con)) - data = ast.literal_eval(codecs.decode(data)) - # (Command,Arguments) - return data - #return data[0],data[1],data[2] - except Exception as e: - print("UserID:",self.UserID," Socket data recive error",e) - data = ("",())#Never references a command + def Connection_Loop(self): """ @@ -454,7 +458,7 @@ def GetMonitorPermissionUser(self,Arguments = None): ################################################# def Exit(self,Arguments = None): - self.DB.db_con.close() + #self.DB.db_con.close() print("Process for UserID:",self.UserID," is exiting..") return True,"Server process is exiting",[] @@ -517,7 +521,7 @@ def Login(self,Arguments): -class MonitorConnection: +class MonitorConnection(ClientConnection): def __init__(self,Thread_Name,Thread_Queue,Connection): self.DB = AATC_DB.DBConnection() self.Thread_Name = Thread_Name @@ -525,17 +529,7 @@ def __init__(self,Thread_Name,Thread_Queue,Connection): self.con = Connection self.Crypto = AATC_Crypto.Crypter(self.con, mode = "SERVER") self.MonitorID = -1 #Used to identify if has logged in yet - def Send(self,data): - self.con.sendall(self.Crypto.Encrypt(codecs.encode(str(data)))) - def Recv(self): - try: - data = self.Crypto.Decrypt(recvall.recvall(self.con)) - data = ast.literal_eval(codecs.decode(data)) - # (Command,Arguments) - return data - #return data[0],data[1],data[2] - except Exception as e: - print("MonitorID:",self.MonitorID," Socket data recive error") + def Connection_Loop(self): """ @@ -621,83 +615,6 @@ def Connection_Loop(self): if Command == "Exit": Exit = True - - -## try: -## Exit = False -## while self.MonitorID == -1 and not Exit:#Repeats until logs in -## data = self.Recv() -## try: -## Command,Arguments = data[0],data[1] -## if Command == "Login": -## Sucess,Message,Data = self.Login(Arguments) -## elif Command == "AddMonitor": # If adding a new Monitor, one must create it first, then log in seperatly -## Sucess,Message,Data = self.AddMonitor(Arguments) -## else: -## Sucess,Message,Data = False,"Command does not exist",[] -## except Exception as e: -## Sucess,Message,Data = False,"An Error occured"+str(e),[] -## print("Error occured with MonitorID:",str(self.MonitorID),"Error :",str(e)," Sending failure message") -## self.Send((Sucess,Message,Data)) -## -## -## while not Exit: -## data = self.Recv() -## try: -## Command,Arguments = data[0],data[1] -## if Command == "GetNoFlyZones": -## Sucess,Message,Data = self.GetNoFlyZones(Arguments) -## -## elif Command == "GetDronesAll": -## Sucess,Message,Data = self.GetDronesAll(Arguments) -## -## elif Command == "GetUserID": -## Sucess,Message,Data = self.GetUserID(Arguments) -## elif Command == "GetUsername": -## Sucess,Message,Data = self.GetUsername(Arguments) -## -## elif Command == "GetMonitorDrones": -## Sucess,Message,Data = self.GetMonitorDrones(Arguments) -## elif Command == "GetMonitorFlights": -## Sucess,Message,Data = self.GetMonitorFlights(Arguments) -## elif Command == "GetMonitorFlightWaypoints": -## Sucess,Message,Data = self.GetMonitorFlightWaypoints(Arguments) -## -## elif Command == "GetMonitorID": -## Sucess,Message,Data = self.GetMonitorID(Arguments) -## elif Command == "GetMonitorName": -## Sucess,Message,Data = self.GetMonitorName(Arguments) -## -## elif Command == "RemoveMonitorPermission": -## Sucess,Message,Data = self.RemoveMonitorPermission(Arguments) -## elif Command == "GetMonitorPermissionMonitor": -## Sucess,Message,Data = self.GetMonitorPermissionMonitor(Arguments) -## -## elif Command == "GetFlightsAll": -## Sucess,Message,Data = self.GetFlightsAll(Arguments) -## -## elif Command == "GetFlightWaypointsAll": -## Sucess,Message,Data = self.GetFlightWaypointsAll(Arguments) -## -## elif Command == "Exit": -## Sucess,Message,Data = self.Exit(Arguments) -## Exit = True -## -## #Else if command doesnt exist send back Failure -## else: -## Sucess,Message,Data = False,"Command does not exist",[] -## print("Monitor tried to use unregistered command") -## except Exception as e: -## Sucess,Message,Data = False,"An Error occured"+str(e),[] -## print("Error occured with MonitorID:",str(self.MonitorID),"Error :",str(e)," Sending failure message") -## ## print(Message,str(Data)) -## self.Send((Sucess,Message,Data)) -## -## except Exception as e: -## if type(e) == BrokenPipeError: -## print("MonitorID:",self.MonitorID," disconnected") -## else: -## print("Serious exception occured with MonitorID ",self.MonitorID," Error",e) self.DB.Exit() print("Process is exiting") @@ -783,14 +700,14 @@ def GetFlightWaypointsAll(self,Arguments = None): ############################################# def Exit(self,Arguments = None): - self.DB.db_con.close() + #self.DB.db_con.close() print("Process for MonitorID:",self.MonitorID," is exiting..") return True,"Server process is exiting",[] -class DroneConnection: +class DroneConnection(ClientConnection): def __init__(self,Thread_Name,Thread_Queue,Connection): self.DB = AATC_DB.DBConnection() self.Thread_Name = Thread_Name @@ -798,17 +715,6 @@ def __init__(self,Thread_Name,Thread_Queue,Connection): self.con = Connection self.Crypto = AATC_Crypto.Crypter(self.con, mode = "SERVER") self.DroneID = -1 #Used to identify if has logged in yet - def Send(self,data): - self.con.sendall(self.Crypto.Encrypt(codecs.encode(str(data)))) - def Recv(self): - try: - data = self.Crypto.Decrypt(recvall.recvall(self.con)) - data = ast.literal_eval(codecs.decode(data)) - # (Command,Arguments) - return data - #return data[0],data[1],data[2] - except Exception as e: - print("DroneID:",self.DroneID," Socket data recive error") def Connection_Loop(self): @@ -875,63 +781,7 @@ def Connection_Loop(self): if Command == "Exit": Exit = True - - -## try: -## Exit = False -## while self.DroneID == -1 and not Exit:#Repeats until logs in -## data = self.Recv() -## try: -## Command,Arguments = data[0],data[1] -## if Command == "Login": -## Sucess,Message,Data = self.Login(Arguments) -## -## else: -## Sucess,Message,Data = False,"Command does not exist",[] -## except Exception as e: -## Sucess,Message,Data = False,"An Error occured"+str(e),[] -## print("Error occured with DroneID:",str(self.DroneID),"Error :",str(e)," Sending failure message") -## self.Send((Sucess,Message,Data)) -## -## -## while not Exit: -## data = self.Recv() -## try: -## Command,Arguments = data[0],data[1] -## if Command == "UpdateDroneStatus": -## Sucess,Message,Data = self.UpdateDroneStatus(Arguments) -## -## elif Command == "DroneGetDroneInfo": -## Sucess,Message,Data = self.DroneGetDroneInfo(Arguments) -## -## elif Command == "CheckForFlight": -## Sucess,Message,Data = self.CheckForFlight(Arguments) -## elif Command == "GetFlight": -## Sucess,Message,Data = self.GetFlight(Arguments) -## elif Command == "GetFlightWaypoints": -## Sucess,Message,Data = self.GetFlightWaypoints(Arguments) -## elif Command == "MarkFlightComplete": -## Sucess,Message,Data = self.MarkFlightComplete(Arguments) -## -## elif Command == "Exit": -## Sucess,Message,Data = self.Exit(Arguments) -## -## #Else if command doesnt exist send back Failure -## else: -## Sucess,Message,Data = False,"Command does not exist",[] -## print("Drone tried to use unregistered command") -## except Exception as e: -## if type(e) != TypeError:# if this error type occurs connection has failed and would otherwise flood console with irrelevant errors -## print("Error occured with DroneID:",str(self.DroneID),"Error :",str(e)," Sending failure message") -## Sucess,Message,Data = False,"An Error occured"+str(e),[] -## -## self.Send((Sucess,Message,Data)) -## -## except Exception as e: -## if type(e) == BrokenPipeError: -## print("DroneID:",self.DroneID," disconnected") -## else: -## print("Serious exception occured with DroneID ",self.DroneID," Error",e) + self.DB.Exit() print("Process is exiting") @@ -979,7 +829,7 @@ def MarkFlightComplete(self,Arguments): ###################################################### def Exit(self,Arguments = None): - self.DB.db_con.close() + #self.DB.db_con.close() print("Process for DroneID:",self.DroneID," is exiting..") return True,"Server process is exiting",[] @@ -1031,34 +881,34 @@ def Cleaner(Thread_Name,Thread_Queue,Interval = 36000,EndTimeThreshold = 72000): -if __name__ == "__main__": #For testing purposes - HOST = '' - PORT = 8000 - - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - print( 'Socket created') - - try: - s.bind((HOST, PORT)) - except: - print("Error binding port") - s.close() - sys.exit() - - print( 'Socket bind complete') - s.listen(10) - print( 'Socket now listening') - - - while 1: - try: - conn, addr = s.accept() - print( '\nConnected with ' + addr[0] + ':' + str(addr[1])) - UConn = MonitorConnection(conn) - UConn.Connection_Loop() - except Exception as e: - print(str(e)) +##if __name__ == "__main__": #For testing purposes +## HOST = '' +## PORT = 8000 +## +## s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +## s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +## print( 'Socket created') +## +## try: +## s.bind((HOST, PORT)) +## except: +## print("Error binding port") +## s.close() +## sys.exit() +## +## print( 'Socket bind complete') +## s.listen(10) +## print( 'Socket now listening') +## +## +## while 1: +## try: +## conn, addr = s.accept() +## print( '\nConnected with ' + addr[0] + ':' + str(addr[1])) +## UConn = MonitorConnection(conn) +## UConn.Connection_Loop() +## except Exception as e: +## print(str(e)) diff --git a/AATC_Server_Starter.py b/AATC_Server_Starter.py index 9e2fe47..8adc601 100644 --- a/AATC_Server_Starter.py +++ b/AATC_Server_Starter.py @@ -153,7 +153,7 @@ def ProcessSpawner(Name,Communications_Queue,Port,Type,Target): data = Communications_Queue.get() Command,Arguments = data[0],data[1] if Command == "Exit": - self.Exit = True + Exit = True except Exception as e: diff --git a/HedaBot.py b/HedaBot.py index e8b44b0..5502f69 100644 --- a/HedaBot.py +++ b/HedaBot.py @@ -439,7 +439,7 @@ def CreateCommandDictionary(): -BOT_TOKEN = "YOUR TOKEN HERE" +BOT_TOKEN = "472230564:AAEHTSJ446LE_BO_hQ8B4PeVmUTrB8gRsEA" if __name__ == "__main__": bot = telepot.Bot(BOT_TOKEN) heda = Telebot(bot)