def server_handshake(self): is_handshake_successful = False while not is_handshake_successful: self.get_header() self.get_payload_eop() self.quantity_packages_to_receive = self.package_header[3] print(f'header recebido: {self.r_header}') if self.package_header[2] == SERVER_ID: print(f'Recebido HS do client - ID correto\n') if self.package_header[0] == 1: payload = [] header_list = [0 for i in range(10)] header_list[0] = 2 # mensagem to tipo 2 - server ocioso header_list[1] = CLIENT_ID header_list[2] = SERVER_ID datagram_obj = Datagram(payload, header_list) self.package = datagram_obj.get_datagram() self.send_package() is_handshake_successful = True print(f'enviado resposta para o client') else: print(f'ID do servidor não confere, ignorando mensagem...')
def propose_session(self, recv_dtg): dtg = Datagram(TransportAim.SESSION_PROPOSAL, self.gainer.ip, self.gainer.port, recv_dtg.source_ip, recv_dtg.source_port) if recv_dtg.source_ip in self.gainer.sessions.keys(): session = self.gainer.sessions[recv_dtg.source_ip] dtg.set_payload(session) self.send_datagram(dtg) else: session = { 'session_id': len(self.gainer.sessions), 'server_ip': self.gainer.ip, 'server_port': self.gainer.port, 'client_ip': recv_dtg.source_ip, 'client_port': recv_dtg.source_port, 'AES_key': utils.random_string() } self.gainer.sessions[session['client_ip']] = session dtg.set_payload(session) self.send_datagram(dtg) self.gainer.AES_ciphers[recv_dtg.source_ip] = None cipher = AES.new(session['AES_key'].encode(), AES.MODE_ECB) self.gainer.AES_ciphers[recv_dtg.source_ip] = cipher
def server_close_session(self, session): print("Before closing session:", self.gainer.sessions) dtg = Datagram(TransportAim.CLOSE, self.gainer.ip, self.gainer.port, session['client_ip'], session['client_port']) app_layer_resp = {'verb': AppVerb.CLOSE, 'message': "Session closed."} dtg.set_payload(app_layer_resp) self.send_datagram(dtg) del self.gainer.sessions[session['client_ip']] print("After closing session:", self.gainer.sessions)
def create_shut_down_signal(self): payload = [] self.header_list = [1 for i in range(10)] self.header_list[0] = 5 # mensagem to tipo 1 - handshake self.header_list[1] = CLIENT_ID self.header_list[2] = SERVER_ID datagram_obj = Datagram(payload, self.header_list) self.package = datagram_obj.get_datagram()
def get_datagram(self, source_context): ADDRESS = self.sources[source_context] PORT = int(self.config.get("global", "PORT", "5005")) if source_context not in self.datagrams: self.logger.debug(f"building a datagram for {source_context}") self.datagrams[source_context] = \ Datagram("Bogus", server=ADDRESS, port=PORT) self.datagrams[source_context].ping() return self.datagrams[source_context]
def receive_full_packages(self): self.n_last_package_received = 0 while self.n_current_package < self.quantity_packages_to_receive: self.timer1 = time.time() self.timer2 = self.timer1 while self.com2.rx.getBufferLen() == 0: current_time = time.time() elapsed_timer1 = current_time - self.timer1 elapsed_timer2 = current_time - self.timer2 if elapsed_timer1 >= 20: print( f'Tempo máximo excedido, avisando client desligamento...' ) payload = [] header_list = [1 for i in range(10)] header_list[0] = 5 header_list[1] = CLIENT_ID header_list[2] = SERVER_ID datagram_obj = Datagram(payload, header_list) self.package = datagram_obj.get_datagram() self.send_package() self.shutdown() if elapsed_timer2 >= 5: print( f'5 segundos sem receber o proximo pacote, enviando resposta novamente...' ) self.send_package() self.timer2 = time.time() self.get_header() self.get_payload_eop() # verify eop and current == last + 1 # verificar se o pacote atual é igual ao anterior + 1 self.is_next_package = self.n_last_package_received + 1 == self.n_current_package self.is_eop_right = self.r_eop == b'\xff\xaa\xff\xaa' print(f'Recebeu o proximo? [{self.is_next_package}]', end=' | ') print(f'Is eop ok? [{self.is_eop_right}]', end=" | ") print( f'Received package [{self.n_current_package} / {self.quantity_packages_to_receive}]' ) self.build_response() self.send_package() print(f'Received all packages') self.juntar_imagem()
def send_handshake(self): packet = Datagram() packet.set_head(message_type=2, message_id=1, num_payloads=0, payload_index=0, payload_size=0, error_type=0, restart_index=0) packet.set_EOP() self.transmitter.send(packet.get_datagram())
def get_datagram(self, source_context): ADDRESS = config.host_for(self.sources[source_context]) PORT = int(self.config.get("global", "PORT", "5005")) if source_context not in self.datagrams: # self.logger.debug(f"building a datagram for {source_context}") name = f"Datagram {self.context}" self.datagrams[source_context] = \ Datagram("Bogus", server=ADDRESS, port=PORT, name=name, compress=True) self.datagrams[source_context].ping() return self.datagrams[source_context]
def client_close_session(self, app_layer_req): server_ip = app_layer_req['data']['server_ip'] dtg = Datagram(TransportAim.CLOSE, self.gainer.ip, self.gainer.port, self.gainer.sessions[server_ip]['server_ip'], self.gainer.sessions[server_ip]['server_port']) dtg.set_payload(app_layer_req) self.send_datagram(dtg) dtg, address = self.gainer.transport.receive_datagram() print(dtg.aim) print(self.gainer.sessions) del self.gainer.sessions[server_ip] print(self.gainer.sessions)
def send_packet(self, payload, num_payloads, payload_index): packet = Datagram() packet.set_head(message_type=1, message_id=1, num_payloads=num_payloads, payload_index=payload_index, payload_size=len(payload), error_type=0, restart_index=0) packet.set_payload(payload=payload) packet.set_EOP(0) self.transmitter.send(packet.get_datagram())
def receive(self, bus_handler): '''@summary: Read the data from Bus. Create a datagram. @param bus_handler: Handler to Bus to read data from. @type bus_handler: integer @return: An object with the obtained data. Null-able. @rtype: Datagram ''' ph_files = POINTER(c_int)() pp_metadata = (c_char_p)() pp_params = (c_char_p)() pn_files = (c_int)() pn_metadata = (c_int)() pn_params = (c_int)() # Invoke C function n_status = self.bus_back_.bus_recv_msg(bus_handler, ph_files, pn_files, pp_metadata, pn_metadata, pp_params, pn_params) result_dtg = None if 0 <= n_status: # The invocation was successful. # De-serialize the data # Aggregate file descriptors n_files = pn_files.value h_files = [] for i in range(n_files): h_files.append(ph_files[i]) # Extract Python strings n_metadata = pn_metadata.value str_metadata = pp_metadata.value n_params = pn_params.value str_params = pp_params.value # Trim the junk out if 0 < n_metadata: str_metadata = str_metadata[0:n_metadata] str_params = str_params[0:n_params] # Construct actual result datagram result_dtg = Datagram() result_dtg.from_raw_data(h_files, str_metadata, str_params) return result_dtg
def client_handshake(self): handshake_successful = False payload = [] self.header_list = [0 for i in range(10)] self.header_list[0] = 1 # mensagem to tipo 1 - handshake self.header_list[1] = CLIENT_ID self.header_list[2] = SERVER_ID self.header_list[3] = len(self.l_packages) self.header_list[5] = FILE_ID datagram_obj = Datagram(payload, self.header_list) datagram = datagram_obj.get_datagram() self.package = datagram print(f'Enviando handshake para o Servidor..') self.send_package() self.start_time1 = time.time() self.start_time2 = time.time() while not handshake_successful: while self.com1.rx.getBufferLen() == 0: self.time_delta1 = time.time() - self.start_time1 self.time_delta2 = time.time() - self.start_time2 if self.time_delta2 > 20: print( f'Tempo máximo excedido, avisando server desligamento...' ) self.create_shut_down_signal() self.send_package() time.sleep(1) self.shutdown() elif self.time_delta1 >= 5: should_send_again = input( 'Didn\'t receive response. Send again? (s/n) ') if should_send_again == 's': print(f'Enviando novamente...\n') self.send_package() self.start_time1 = time.time() else: self.shutdown() self.get_header() self.get_payload_eop() if self.package_header[0] == 2: handshake_successful = True print(f'Server está ocioso... começando o envio\n') else: print(f'Não teve sucesso no handshake...')
def delete_user(self, data, session): dtg = Datagram(TransportAim.APP_RESPONSE, self.gainer.ip, self.gainer.port, session['client_ip'], session['client_port']) if data['username'] not in self.gainer.users.keys(): app_layer_resp = { 'verb': AppVerb.ERR, 'message': "This user doe not exists in the database." } else: del self.gainer.users[data['username']] app_layer_resp = {'verb': AppVerb.OK, 'message': "User deleted."} dtg.set_payload(app_layer_resp) self.gainer.transport.send_datagram(dtg)
def get_session(self, dest_ip): dtg = Datagram(TransportAim.GET_SESSION, self.gainer.ip, self.gainer.port, dest_ip, config.SERVER_PORT) for i in range(config.GET_SESSION_ATTEMPTS): self.send_datagram(dtg) recv_dtg, address = self.receive_datagram() if recv_dtg and address: self.gainer.sessions[ recv_dtg.source_ip] = recv_dtg.get_payload() key = self.gainer.sessions[recv_dtg.source_ip]['AES_key'] self.gainer.AES_ciphers[recv_dtg.source_ip] = AES.new( key.encode(), AES.MODE_ECB) return self.gainer.sessions[recv_dtg.source_ip] return None
def client_send_data(self, app_layer_req, dest_ip): if dest_ip not in self.gainer.sessions.keys(): session = self.gainer.transport.get_session(dest_ip) if not session: raise Exception( "Could not get a session after several attempts.") session = self.gainer.sessions[dest_ip] print("===========================================================") dtg = Datagram(TransportAim.APP_REQUEST, self.gainer.ip, self.gainer.port, session['server_ip'], config.SERVER_PORT) dtg.set_payload(app_layer_req) self.gainer.transport.send_datagram(dtg) recv_dtg, address = self.gainer.transport.receive_datagram() print("App response:", recv_dtg.get_payload())
def build_packages(self): self.header_list = [1 for i in range(10)] self.header_list[0] = 3 # mensagem to tipo 1 - handshake self.header_list[1] = CLIENT_ID self.header_list[2] = SERVER_ID for index_package in range(len(self.l_bytes_img)): payload = self.l_bytes_img[index_package] self.header_list[3] = len(self.l_bytes_img) self.header_list[4] = index_package + 1 self.header_list[5] = len(payload) datagram = Datagram(payload, self.header_list) self.l_packages.append(datagram.get_datagram()) self.len_packages = len(self.l_packages)
def build_response(self): is_package_ok = self.is_next_package and self.is_eop_right payload = [] header_list = [0 for i in range(10)] if is_package_ok: # create type4 msg representing that the package was received successfully self.l_received_payloads.append(self.r_payload) print(f'package [{self.n_current_package}] received correctly') self.n_last_package_received = self.n_current_package header_list[0] = 4 # mensagem to tipo 1 - handshake header_list[1] = CLIENT_ID header_list[2] = SERVER_ID header_list[7] = self.n_last_package_received else: print( f'package [{self.n_current_package}] had some error, requesting again..' ) header_list[0] = 6 # mensagem to tipo 6 - solicitando reenvio header_list[1] = CLIENT_ID header_list[2] = SERVER_ID header_list[6] = self.n_last_package_received + 1 datagram_obj = Datagram(payload, header_list) self.package = datagram_obj.get_datagram()
def receive_datagram(self): time.sleep(10) print( "=====================================================================" ) recv_dtg, address = self.gainer.sock.recvfrom(config.RECV_DATA_SIZE) utils.write("Received dtg: ", recv_dtg) if address[0] in self.gainer.AES_ciphers.keys(): cipher = self.gainer.AES_ciphers[address[0]] recv_dtg = cipher.decrypt(recv_dtg) utils.write("Decrypted recv dtg: ", recv_dtg) recv_dtg: Datagram = pickle.loads(recv_dtg) utils.write("Received dtg aim: ", recv_dtg.aim) time.sleep(5) utils.write("Sending ack", "") if utils.valid_cksm(recv_dtg.get_payload(), recv_dtg.get_cksm()): aim = TransportAim.OK else: aim = TransportAim.CORRUPTED utils.write("Sending as ack: ", aim) ack_dtg = Datagram(aim, self.gainer.ip, self.gainer.port, recv_dtg.source_ip, recv_dtg.source_port) ack_dtg = pickle.dumps(ack_dtg) utils.write("Ack dtg encoded: ", ack_dtg) if address[0] in self.gainer.AES_ciphers.keys(): cipher = self.gainer.AES_ciphers[address[0]] ack_dtg = utils.append_zs(ack_dtg) ack_dtg = cipher.encrypt(ack_dtg) utils.write("Encrypted ack dtg: ", ack_dtg) self.gainer.sock.sendto(ack_dtg, address) print( "=====================================================================" ) return recv_dtg, address
from utils import open_image, separate_packages from datagram import Datagram img = open_image('imgs/advice.png') pkgs = separate_packages(img) for i in pkgs: header_list = [1 for i in range(10)] a = Datagram(payload=[], header_list=header_list).get_datagram() print(a) break