def __handle_peer(self, client_sock): """ handle_peer( new socket connection ) -> () Dispatches messages from the socket connection """ self.__debug('New child ' + str(threading.currentThread().getName())) self.__debug('Connected ' + str(client_sock.getpeername())) host, port = client_sock.getpeername() conn = Peer(port, client_sock) while True: try: msg_type, msg_data = conn.recv_data() if msg_type: msg_type = msg_type.upper() if msg_type not in self.handlers: self.__debug('Peer msg not handled') # : %s: %s' % (msg_type, msg_data)) break else: self.__debug('Handling peer msg') # : %s: %s' % (msg_type, msg_data)) disconnect = self.handlers[msg_type](conn, msg_data) if disconnect: break except KeyboardInterrupt: raise except: traceback.print_exc() self.__debug('Disconnecting ' + str(client_sock.getpeername())) conn.close()
def request_encrypted_file(self, host, port, file_name): try: conn = Peer(port) conn.send_data(Peer.SEND_CERT, self.encrypt.get_signed_cert_str()) debug('Sent %s' % Peer.SEND_CERT) msg_reply = conn.recv_data() # debug('Got reply %s' % (str(msg_reply))) debug("Received certificate") if msg_reply[0] != Peer.CERT_RESPONSE_VALID: debug("Certificate validation error.") return if conn.add_peer_cert(msg_reply[1].decode("utf-8")): public_key = conn.peer_cert.public_key() ciphertext = public_key.encrypt( bytes(file_name, 'utf-8'), padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) conn.send_data(Peer.REQUEST_FILE, ciphertext) else: print("ERROR") debug('Sent %s' % Peer.REQUEST_FILE) try: _substr_index = file_name.rindex('/')+1 except: _substr_index = 0 received_file_name = 'received_'+file_name[_substr_index:] try: os.remove(received_file_name) print('Removed existing file:', received_file_name) os.remove('tmp_recv_encrfile') except OSError: pass while True: msg_reply = conn.recv_data() # debug('Got reply %s' % (str(msg_reply))) if msg_reply == (None, None): break plain_data = self.encrypt.get_private_key().decrypt( msg_reply[1], padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) with open(received_file_name, 'ab') as f: f.write(plain_data) with open('tmp_recv_encrfile', 'ab') as f: f.write(msg_reply[1]) debug(f"File received written to: {received_file_name}") conn.close() except KeyboardInterrupt: raise except: traceback.print_exc()