Example #1
0
 def put_on_truck_recv(self, recv_wrapper, packages_data):
     # send ack back to world
     ack_wrapper = MessageWrapper(self.create_acks_msg_in_batch(recv_wrapper.get_data().loaded))
     cfg.logger.info('Send acks: {}'.format(ack_wrapper.parse_itself(wapb.ACommands)))
     ack_wrapper.encode_and_send(self.socket)
     for data in recv_wrapper.get_data().loaded:
         key = data.shipid
         db_command = 'UPDATE miniamazon_app_ordercollection SET status = \'Loaded\'' + \
             ' WHERE order_collection_id = ' + str(key)
         db_interface = DBInterface(cfg.db_name, cfg.db_user, cfg.db_password, cfg.db_host, cfg.db_port)
         db_interface.setup_excecute_and_close(db_command)
     return recv_wrapper
Example #2
0
    def recv(self, cmd_key, response_queue):
        assert self.socket is not None
        assert cmd_key == 'AResponses' or cmd_key == 'UA_Responses'
        recv_wrapper = MessageWrapper('')
        while True:
            # receiving
            try:
                cmd_type = cfg.lookup_table[cmd_key]
                recv_wrapper.recv_and_parse(self.socket, cmd_type)
            except socket.timeout as e:
                # cfg.logger.debug('Timeout.')
                continue
            except SocketError as e:
                cfg.logger.debug('Error in receive: {}.'.format(e))
                continue
            except DecodeError as e:
                cfg.logger.debug('Error in decoding: {}'.format())
                continue
            except IndexError as e:
                # pass
                cfg.logger.debug('IndexError in recv_and_parse _DecodeVariant32: {}'.format(e))
                cfg.logger.debug('Stop receiving! Please re-start the backend.')
                sys.exit()
                break
        
            if recv_wrapper.get_message():
                cfg.logger.info('Received: {}'.format(recv_wrapper.get_data()))
                if cmd_key == 'AResponses':
                    if recv_wrapper.get_data().arrived or recv_wrapper.get_data().ready or recv_wrapper.get_data().loaded:
                        response_queue.put((cmd_key, recv_wrapper))
                else:
                    response_queue.put((cmd_key, recv_wrapper))

        return recv_wrapper
Example #3
0
    def purchase_more(self, warehouse_id, product_id, description, count, seqnum):
        send_wrapper = MessageWrapper(self.create_purchase_more_msg(warehouse_id, product_id, description, count, seqnum))
        cfg.logger.info('Purchase more.')
        recv_wrapper = self.communicate(send_wrapper, 'AResponses', seqnum)
        cfg.logger.info('Received from warehouse: \n{}'.format(recv_wrapper.get_data()))
        acks = recv_wrapper.get_data().acks
        # check if acks from response matches seqnum
        if seqnum == acks[0]:
            # send ack back to world
            world_seqnum = recv_wrapper.get_data().arrived[0].seqnum
            cfg.logger.info('Send acks: {}'.format(world_seqnum))
            ack_wrapper = MessageWrapper(self.create_acks_msg(world_seqnum))
            ack_wrapper.encode_and_send(self.socket)

        return recv_wrapper
Example #4
0
    def connect_to_world(self, warehouse_data, worldid=None):
        send_wrapper = MessageWrapper(self.create_connection_msg(warehouse_data, worldid))
        recv_wrapper = self.communicate(send_wrapper, 'AConnected')
        cfg.logger.info('Received from warehouse: \n{}'.format(recv_wrapper.get_data()))

        # Consider sending acks
        return recv_wrapper
Example #5
0
class ShellHandler(MessageHandlerMixin):

    def __init__(self, identity_key, authorized_hosts, secure = True):
        self.message_wrapper = MessageWrapper(identity_key, authorized_hosts)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.rfile = io.BytesIO()  # Here, hold this for a moment
        self.secure = secure

    def _do_handshake(self):
        print(f"[+] Authenticating . . .")
        challenge = base64.b64decode(self.rfile.readline().strip())
        print(f"[+] Got challenge: {challenge}")
        self._write_line(self.message_wrapper.get_challenge_response(challenge))
        server_response = base64.b64decode(self.rfile.readline().strip())
        print(f"[+] Got response: {server_response}")
        self.message_wrapper.finalize_handshake(server_response)
        print("[+] Authentication successful!")

    def connect(self, remote_addr, remote_port):
        self.socket.connect((remote_addr, remote_port))
        self.rfile = self.socket.makefile()
        if self.secure:
            self._do_handshake()
        else:
            print("[+] Insecure flag is set, skipping authentication")

    def run(self):
        command = ""
        while command != "exit":
            command = input("> ").lower().strip()
            if command:
                for packed_message in Message.packed_from_string(self.message_wrapper, command, secure=self.secure):
                    self._write_line(packed_message)
                if command != "exit":                    
                    response = self._get_message(self.message_wrapper, secure=self.secure)
                    try:
                        # Try to pretty print JSON responses
                        response = json.loads(response)                        
                        response = json.dumps(response, indent=4)
                    except (ValueError, json.JSONDecodeError):
                        pass
                    print(response)
Example #6
0
 def handle(self):
     print("[+] Client connected!")
     message_wrapper = MessageWrapper(configuration.identity_file_path, configuration.authorized_keys_folder)
     original_timeout = self.server.socket.timeout
     self.server.socket.settimeout(configuration.socket_timeout)
     self.socket = self.server.socket
     try:
         if configuration.secure:
             print("[+] Sending handshake challenge . . .")
             self._write_line(message_wrapper.get_challenge())
             challenge_response = base64.b64decode(self.rfile.readline().strip())
             # This will throw a permission error if client authorization fails.  Not ideal, but I can't reset the handshake yet, so this is the behavior I want for now
             print("[+] Validating client response . . .")
             server_response = message_wrapper.finalize_handshake(challenge_response)
             print(f"[+] Successful authentication from client at {self.client_address[0]}")
             self._write_line(server_response)            
         else:
             print("[+] Security is disabled, skipping authentication handshake")
     finally:
         self.server.socket.settimeout(original_timeout)
     self.command_loop(message_wrapper)
     print("[+] Session terminated.")
     CommandHandlerFactory.get_instance(configuration).unload_all()
Example #7
0
    def get_world_id(self):
        assert self.socket is not None
        recv_wrapper = MessageWrapper('')
        start = datetime.datetime.now()
        while True:
            curr = datetime.datetime.now()
            duration = curr - start
            if duration.seconds > cfg.max_timeout:
                raise UserTimeoutException('timeout')
            try:
                recv_wrapper.recv_and_parse(self.socket, wapb.UA_Connect)
            except SocketError as e:
                cfg.logger.debug('Error in receive: {}.'.format(e))
                continue
            if recv_wrapper.get_message():
                break

        return recv_wrapper.get_data().worldid
Example #8
0
    def communicate(self, send_wrapper, cmd_key, seqnum_check=None):
        assert self.socket is not None
        recv_wrapper = MessageWrapper('')
        while True:
            # sending
            try:
                send_wrapper.encode_and_send(self.socket)
            except SocketError as e:
                if not seqnum_check:
                    cfg.logger.debug('Error in send: {}.'.format(e))
                else:
                    cfg.logger.debug('Error in send: {}.'.format(e))
                continue

            # receiving
            try:
                cmd_type = cfg.lookup_table[cmd_key]
                recv_wrapper.recv_and_parse(self.socket, cmd_type)
            except socket.timeout as e:
                # cfg.logger.debug('Timeout.')
                continue
            except SocketError as e:
                cfg.logger.debug('Error in receive: {}.'.format(e))
                continue
            except DecodeError as e:
                cfg.logger.debug('Error in decoding: {}'.format())
                continue
            except IndexError as e:
                # pass
                cfg.logger.debug('IndexError in recv_and_parse _DecodeVariant32: {}'.format(e))
                continue
        
            if recv_wrapper.get_message():
                if cmd_key != 'AResponses' and cmd_key != 'UA_Responses':
                    break
                else:
                    assert seqnum_check is not None
                    acks = recv_wrapper.get_data().acks
                    if acks and seqnum_check == acks[0]:
                        break

        return recv_wrapper
Example #9
0
    def run(self):

        local_ip, local_port = get_ip_address()
        log.info(f'local IP Address: {local_ip}, {local_port}')

        message = local_ip + SEPERATOR \
                    + str(local_port) + SEPERATOR \
                    + self.client.serial

        TIMEOUT_S = 60
        PING_INTERVAL_S = 30
        LOOP_INTERVAL_S = 5
        conn_flag = False

        server_peer = Peer(self.client.server_ip, self.client.server_port)
        while not self.is_interrupted():
            current_time = get_current_time_sec()
            with self.client.mutex_for_kcp_peer_map:
                for kcp_peer in list(self.kcp_peer_map.values()):
                    if kcp_peer.last_ping + TIMEOUT_S < current_time:
                        if kcp_peer.peer == server_peer:
                            continue

                        log.info(f'removed kcp_peer: {kcp_peer.peer.key}')
                        del self.kcp_peer_map[kcp_peer.peer.key]

                    elif kcp_peer.last_ping + PING_INTERVAL_S < current_time:
                        message_wrapper = MessageWrapper(
                            registered_types=self.client.registered_types,
                            message=None,
                            message_type=MessageType.RAWBYTE,
                            packet_type=RM.PING_REQUEST,
                            connection_id=0)

                        kcp_peer.send(message_wrapper)

            with self.client.mutex_for_rendvs_sess_map:
                for key, rendvs_sess in list(self.rendvs_sess_map.items()):
                    if rendvs_sess is None:
                        continue

                    if rendvs_sess.relay_kcp_peer is not None:
                        last_ping = rendvs_sess.relay_kcp_peer.last_ping
                        if last_ping + TIMEOUT_S < current_time:
                            log.warning(f'relay peer removed, {last_ping}')
                            rendvs_sess.relay_kcp_peer = None

                    if rendvs_sess.public_kcp_peer is not None:
                        last_ping = rendvs_sess.public_kcp_peer.last_ping
                        if last_ping + TIMEOUT_S < current_time:
                            log.warning(f'public peer removed, {last_ping}')
                            rendvs_sess.public_kcp_peer = None

                    if rendvs_sess.private_kcp_peer is not None:
                        last_ping = rendvs_sess.private_kcp_peer.last_ping
                        if last_ping + TIMEOUT_S < current_time:
                            log.warning(f'private peer removed, {last_ping}')
                            rendvs_sess.private_kcp_peer = None

                    if not rendvs_sess.is_connected():
                        del self.rendvs_sess_map[key]

                        if self.client.on_disconnected is not None:
                            self.client.on_disconnected(rendvs_sess)

                        log.info(f'Disconnected, connectionID=\
                                        {rendvs_sess.connection_id}')

            if not self.client.is_connected:
                if conn_flag:
                    with self.client.mutex_for_kcp_peer_map:
                        del self.client.kcp_peer_map[server_peer.key]
                    self.client.sock = create_udp_socket()
                    self.client.on_server_connect_failed()

                else:
                    conn_flag = True

                self.client.on_server_connecting()

                message_wrapper = MessageWrapper(
                    registered_types=self.client.registered_types,
                    message=message,
                    message_type=MessageType.RAWBYTE,
                    packet_type=RM.REGISTRATION_RENDEZVOUS_CLIENT_REQUEST,
                    connection_id=0)

                self.client.get_kcp_peer(server_peer).send(message_wrapper)

            elif self.client.get_kcp_peer(server_peer).last_ping \
                    + TIMEOUT_S < current_time:
                
                with self.client.mutex_for_kcp_peer_map:
                    del self.client.kcp_peer_map[server_peer.key]

                conn_flag = False
                self.client.is_connected = False
                self.client.sock = create_udp_socket()
                self.client.on_server_disconnected()

            else:
                message_wrapper = MessageWrapper(
                    registered_types=self.client.registered_types,
                    message=message,
                    message_type=MessageType.RAWBYTE,
                    packet_type=RM.REGISTRATION_RENDEZVOUS_CLIENT_REQUEST,
                    connection_id=0)

                self.client.get_kcp_peer(server_peer).send(message_wrapper)

            time.sleep(LOOP_INTERVAL_S)

        log.debug('registerThread finished')

        return 
Example #10
0
 def go_deliver_send(self, truckid, package_id, dest_x, dest_y, seqnum):
     send_wrapper = MessageWrapper(self.create_go_deliver_msg(truckid, package_id, dest_x, dest_y, seqnum))
     cfg.logger.info('Go deliver.')
     recv_wrapper = self.send_ups(send_wrapper)
Example #11
0
 def put_on_truck_send(self, warehouse_id, truckid, shipid, seqnum):
     send_wrapper = MessageWrapper(self.create_put_on_truck_msg(warehouse_id, truckid, shipid, seqnum))
     cfg.logger.info('Sending put on truck message to the warehouse.')
     self.send(send_wrapper)
Example #12
0
 def packing_send(self, warehouse_id, product_ids, descriptions, counts, shipid, seqnum):
     send_wrapper = MessageWrapper(self.create_pack_msg(warehouse_id, product_ids, descriptions, counts, shipid, seqnum))
     cfg.logger.info('Sending packing message to the warehouse.')
     self.send(send_wrapper)
Example #13
0
 def call_truck_send(self, package_id, warehouse_id, product_ids, descriptions, counts, owner, dest_x, dest_y, seqnum):
     send_wrapper = MessageWrapper(self.create_truck_call_msg(
         package_id, warehouse_id, product_ids, descriptions, counts, owner, dest_x, dest_y, seqnum))
     cfg.logger.info('Call a truck from the UPS.')
     recv_wrapper = self.send_ups(send_wrapper)
Example #14
0
 def purchase_more_recv(self, recv_wrapper):      
     # send ack back to world
     cfg.logger.info('Send acks: {}'.format(world_seqnum))
     ack_wrapper = MessageWrapper(self.create_acks_msg_in_batch(recv_wrapper.get_data().arrived))
     ack_wrapper.encode_and_send(self.socket)
     return recv_wrapper
Example #15
0
 def purchase_more_send(self, warehouse_id, product_id, description, count, seqnum):
     send_wrapper = MessageWrapper(self.create_purchase_more_msg(warehouse_id, product_id, description, count, seqnum))
     cfg.logger.info('Purchase more.')
     self.send(send_wrapper)
Example #16
0
 def __init__(self, identity_key, authorized_hosts, secure = True):
     self.message_wrapper = MessageWrapper(identity_key, authorized_hosts)
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.rfile = io.BytesIO()  # Here, hold this for a moment
     self.secure = secure