def send_get_request_to_master(self, current_machine_socket: socket, requestor_ip: str, master_port: int, master_IP_address: str, sdfs_file_name: str, local_file_name_to_store: str): """ This function sends a get request Parameters: current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the requester machine's IP address current_port (integer) : the requester machine's port master_IP_address (string): the master's ip address or the ip address of the node containing the file master_port (integer) : the master's port number or the port number of the node containing the file file_name (string) : name of the file to be deleted """ get_request = { 'Type': "get_request_to_master", 'sdfs_file_name': sdfs_file_name, 'local_file_name_to_store': local_file_name_to_store, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'requestor_ip': requestor_ip } get_request_json = json.dumps(get_request) current_machine_socket.sendto((get_request_json).encode('utf-8'), (master_IP_address, master_port))
def send_join_request_to_socket(self, target_ip_address: str, target_port: int, current_machine_socket: socket, current_machine_IP_address: str, current_port: int): """ This function sends a join request to the introducer machine. Parameters: target_ip_address (string) : The IP_address of the introducer machine to send the join request to. target_port (int) : The introducer's port number current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address timestamp : The timestamp of the message sent. """ join_request_dict = { 'Type': "Join_req", 'Process_id': (str(os.getpid())).strip(), 'IP_address': current_machine_IP_address, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'Port': str(current_port) } join_request_json = json.dumps(join_request_dict) self.bytes_sent += (sys.getsizeof(join_request_json) / 1024) current_machine_socket.sendto((join_request_json).encode('utf-8'), (target_ip_address, target_port))
def send_juice_start_request_to_master( self, current_machine_socket: socket, master_port: int, master_IP_address: str, juice_exe: str, num_juices: str, sdfs_intermediate_filename_prefix: str, sdfs_dest_filename: str, delete_input: str): juice_start_request_to_master = { 'Type': "juice_start_request_to_master", 'juice_exe': juice_exe, 'num_juices': num_juices, 'sdfs_intermediate_filename_prefix': sdfs_intermediate_filename_prefix, 'sdfs_dest_filename': sdfs_dest_filename, 'delete_input': delete_input, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } juice_start_request_to_master_json = json.dumps( juice_start_request_to_master) current_machine_socket.sendto( (juice_start_request_to_master_json).encode('utf-8'), (master_IP_address, master_port))
def send_delete_ack(self, current_machine_socket: socket, master_port: int, master_IP_address: str, sdfs_file_name: str, current_machine_IP_address: str): """ This function sends a delete acknowledgement to the master once file is deleted Parameters: current_machine_socket (socket) : This machine's socket master_IP_address (string): the master's ip address or the ip address of the node containing the file master_port (integer) : the master's port number or the port number of the node containing the file file_name (string) : name of the file to be deleted """ delete_ack = { 'Type': "delete_ack", 'IP_who_delete_file': current_machine_IP_address, 'sdfs_file_name': sdfs_file_name, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } delete_ack_json = json.dumps(delete_ack) current_machine_socket.sendto((delete_ack_json).encode('utf-8'), (master_IP_address, master_port))
def send_one_ping(sock: socket, dest_addr: str, icmp_id: int, seq: int, size: int): """Sends one ping to the given destination. ICMP Header (bits): type (8), code (8), checksum (16), id (16), sequence (16) ICMP Payload: time (double), data ICMP Wikipedia: https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol Args: sock: Socket. dest_addr: The destination address, can be an IP address or a domain name. Ex. "192.168.1.1"/"example.com" icmp_id: ICMP packet id, usually is same as pid. seq: ICMP packet sequence, usually increases from 0 in the same process. size: The ICMP packet payload size in bytes. Note this is only for the payload part. Raises: HostUnkown: If destination address is a domain name and cannot resolved. """ try: dest_addr = socket.gethostbyname(dest_addr) # Domain name will translated into IP address, and IP address leaves unchanged. except socket.gaierror as e: print("Cannot resolve {}: Unknown host".format(dest_addr)) raise errors.HostUnknown(dest_addr) from e pseudo_checksum = 0 # Pseudo checksum is used to calculate the real checksum. icmp_header = struct.pack(ICMP_HEADER_FORMAT, IcmpType.ECHO_REQUEST, ICMP_DEFAULT_CODE, pseudo_checksum, icmp_id, seq) padding = (size - struct.calcsize(ICMP_TIME_FORMAT) - struct.calcsize(ICMP_HEADER_FORMAT)) * "Q" # Using double to store current time. icmp_payload = struct.pack(ICMP_TIME_FORMAT, time.time()) + padding.encode() real_checksum = checksum(icmp_header + icmp_payload) # Calculates the checksum on the dummy header and the icmp_payload. # Don't know why I need socket.htons() on real_checksum since ICMP_HEADER_FORMAT already in Network Bytes Order (big-endian) icmp_header = struct.pack(ICMP_HEADER_FORMAT, IcmpType.ECHO_REQUEST, ICMP_DEFAULT_CODE, socket.htons(real_checksum), icmp_id, seq) # Put real checksum into ICMP header. packet = icmp_header + icmp_payload sock.sendto(packet, (dest_addr, 0)) # addr = (ip, port). Port is 0 respectively the OS default behavior will be used.
def send(self, channel: socket, other_node: NeighbourNode, token: Token): log(self.pid, ": sending a token of type ", token.type_, " from ", token.src_pid, " in ", token.direction, "direction") time.sleep(self.channel_delay) channel.sendto(json.dumps(token.__dict__).encode("utf-8"), (other_node.ip, other_node.port))
def send_quit_to_socket(self, target_ip_address: str, target_port: int, current_machine_socket: socket, current_machine_IP_address: str, current_port: int): """ This functions sends a quit message to the introducer machine. Parameters: target_ip_address (string) : The IP_address of the machine to send the quit request to. target_port (int) : The machine's port number current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address timestamp : The timestamp of the message sent. """ quit_to_send = { 'Type': "Quit", 'IP_address': current_machine_IP_address, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } quit_to_send_json = json.dumps(quit_to_send) self.bytes_sent += (sys.getsizeof(quit_to_send_json) / 1024) current_machine_socket.sendto((quit_to_send_json).encode('utf-8'), (target_ip_address, target_port))
def send_ack_msg_to_socket(self, target_ip_address: str, target_port: int, current_machine_socket: socket, current_machine_IP_address: str, current_port: int, membership_dict: dict): """ This function sends an acknowledge message to the specified machine. Parameters: target_ip_address (string) : The IP_address of the specified machine to send the acknowledge message to. target_port (int) : The specified machine's port number current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address timestamp : The timestamp of the message sent. """ for ip in membership_dict.keys(): membership_dict[ip][1] = str(membership_dict[ip][1]) ack_msg_dict = { 'Type': "Ack", 'Process_id': (str(os.getpid())).strip(), 'IP_address': current_machine_IP_address, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'Port': str(current_port), 'Membership_dict': json.dumps(membership_dict) } ack_msg_json = json.dumps(ack_msg_dict) self.bytes_sent += (sys.getsizeof(ack_msg_json) / 1024) current_machine_socket.sendto((ack_msg_json).encode('utf-8'), (target_ip_address, target_port))
def send(self, channel: socket, receiver: NeighbourNode, message: Message): log(self.id, "sending a message of type", message.type_, "with value", message.value, "to", receiver.id) time.sleep(receiver.channel_delay) channel.sendto(json.dumps(message.__dict__).encode("utf-8"), (receiver.ip, receiver.port))
def send_window(self, s: socket, e: threading.Event): while True: if self.send_base > len(self.pac_lis) - 1 or self.next_seq > len( self.pac_lis) - 1: break if self.next_seq < self.send_base + self.win_size: for i in range(self.win_size): s.sendto(self.pac_lis[self.next_seq], self.dst_addr) with self.mutex: self.next_seq += 1 if self.next_seq >= len(self.pac_lis) - 1: with self.mutex: self.next_seq = len(self.pac_lis) - 1 break logging.debug('ReBuild Window {0}'.format( list(range(self.send_base, self.next_seq)))) e.clear() logging.debug('Wait') if not e.wait(self.timeout): logging.debug('Timeout detected') for i in range(self.send_base, self.next_seq): s.sendto(self.pac_lis[i], self.dst_addr) logging.debug('ReSend pkt {0}'.format(i))
def main_send(self,so:socket,st:str='',Type=1,Dev=None): self.sendtocmd('s') if so == None: self.logger_add('错误的套接字端口,发送失败') self.sendtocmd('n') return True if st == None: string='' else: string=st self.logger_add('※发送:--------------------') self.logger_add('Data:{}'.format(string)+'\n目的设备号:{}'.format('广播' if Type == 1 else Dev)) msgsend=self.protocol_encode(string,Type=Type,DDev=Dev) for i in self.lower_addr: so.sendto(msgsend, i) self.logger_add('信息发送到下层了√') self.txt1.delete('1.0', 'end') self.txt1.insert(tk.END, self.log_show_tmp) self.log_show_tmp = '' self.sendtocmd('n') return True
def recv_ack(self, s: socket, e: threading.Event): buffer = 2 while True: ack_b, addr = s.recvfrom(buffer) ack = int.from_bytes(ack_b, 'big') logging.debug('recv ack {0}'.format(ack)) with self.mutex: if ack == self.send_base: if not self.next_seq > len(self.pac_lis) - 1: s.sendto(self.pac_lis[self.next_seq], self.dst_addr) self.send_base += 1 if self.next_seq < len(self.pac_lis) - 1: self.next_seq += 1 logging.debug('Forward Window {0}'.format( list(range(self.send_base, self.next_seq)))) e.set() elif ack > self.send_base: self.send_base = ack + 1 self.next_seq = self.send_base logging.debug('Reset Window {0}'.format( list(range(self.send_base, self.next_seq)))) e.set() if ack == len(self.pac_lis) - 1: break
def send_gossip__heartbeat(self,current_machine_socket:socket, current_machine_IP_address:str, current_port:int, membership_dict:dict, number_of_members_to_gossip): """ This function sends gossip heartbeats to the specified number Parameters: current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address current_port : The current machine's port number membership_dict : The membership dictionary of the system """ for ip in membership_dict.keys(): membership_dict[ip][1] = str(membership_dict[ip][1]) gossip__heartbeat_msg_dict = {'Type' : "gossip__heartbeat", 'IP_address' : current_machine_IP_address, 'Timestamp' : (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'Port' : str(current_port), 'Membership_dict' : json.dumps(membership_dict) } gossip_heartbeat_msg_json = json.dumps(gossip__heartbeat_msg_dict) data = (gossip_heartbeat_msg_json).encode('utf-8') for i in range(number_of_members_to_gossip): iprand, = random.sample(membership_dict.keys(), 1) while (iprand == current_machine_IP_address):#if iprand is current_machine_IP_address, reselect iprand, = random.sample(membership_dict.keys(), 1) target_ip_address = iprand target_port = int(membership_dict[target_ip_address][3]) self.bytes_sent += (sys.getsizeof(gossip_heartbeat_msg_json) / 1024) current_machine_socket.sendto(data, (target_ip_address, target_port))
def send_all_to_all__heartbeat(self, current_machine_socket: socket, current_machine_IP_address: str, current_port: int, membership_dict: dict): """ This functions sends all to all heartbeats. Parameters: current_machine_socket (socket) : This machine's socket. current_machine_IP_address (string) : the current machine's IP address current_port : The current machine's port number membership_dict : The membership dictionary of the system """ heartbeat_dict = { 'Type': "all_to_all_heart_beat", 'IP_address': current_machine_IP_address, 'Port': current_port, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } heartbeat_json = json.dumps(heartbeat_dict) for target_ip_address in membership_dict.keys(): target_port = membership_dict[target_ip_address][3] if (target_ip_address == current_machine_IP_address): continue self.bytes_sent += (sys.getsizeof(heartbeat_json) / 1024) current_machine_socket.sendto((heartbeat_json).encode('utf-8'), (target_ip_address, target_port))
def game_in_progress_loop(s: socket): while True: package = rp(s.recv(256)) request_type = package.get("rt") message = package.get("msg") if request_type == RT.start_turn.value: # Player start turn print("msg from server: ", message) coordinate = raw_input(": ") while not valid_coordinate(coordinate=coordinate): coordinate = raw_input(": ") s.sendto(create_message(RT.send_coord.value, coordinate), ADDR) elif request_type == RT.hit.value: # Player hit draw_opponents_map(coordinate=coordinate, hit=True) print("msg from server: ", message) coordinate = raw_input(": ") while not valid_coordinate(coordinate=coordinate): coordinate = raw_input(": ") s.sendto(create_message(RT.send_coord.value, coordinate), ADDR) elif request_type == RT.miss.value: # Player missed draw_opponents_map(coordinate=coordinate, hit=False) print("msg from server: ", message) elif request_type == RT.msg.value: # Message from server print("msg from server: ", message) s.close()
def resetCon(sock1: socket): global clientAddress try: sock1.sendto(serverResetCon().encode(), clientAddress) except OSError: print('OSError57') finally: sock1.close()
def send_payload(sock: socket, payload: PayloadEncoder or PayloadEventMessages, address=None): if sock is None or sock._closed or payload is None: print("[x] Unable to send payload [Payload %s, Socket %s]" % (payload, socket)) return if isinstance(payload, PayloadEventMessages): payload = payload.value if address is None: sock.sendall(encode_to_json(payload.content()).encode("utf-8")) else: sock.sendto(encode_to_json(payload.content()).encode("utf-8"), address)
def handshake(s: socket, target: tuple): global identifier, version SYN = struct.pack('iii', 1, 1, 0) print('Handshake : Send SYN') s.sendto(SYN, target) print('Handshake : Receive SYNACK') SYNACK, addr = s.recvfrom(1024) _, _, identifier, version, _, _ = decode_synack(SYNACK) ACK = struct.pack('iii', identifier, version, 1) print('Handshake : Send ACK') s.sendto(ACK, target) print('Handshake : Done')
def receiveMessages(sock1: socket): global clientAccepted, count, clientCount serverMessageCount = 1 while clientAccepted is True: isMsg: bool # sets a timer that runs the reset function when 4.0 sec has elapsed t = threading.Timer(4.0, resetCon, args=(sock1, )) t.start() try: data, address = sock1.recvfrom(1024) except ConnectionResetError: break except OSError: break # timer resets after every msg received t.cancel() try: clientCount = testCountMsg(data.decode()) isMsg = True except ValueError: isMsg = False if data.decode() == heartbeat(): t.cancel() else: resetCon(sock1) if isMsg: if serverMessageCount == clientCount + 1: print('\nClient: {} '.format(data.decode())) sock1.sendto( serverMessage(serverMessageCount).encode(), address) print('\nServer: {} '.format( serverMessage(serverMessageCount))) serverMessageCount = serverMessageCount + 2 else: logging.info(": Wrong count in messages") clientAccepted = False timeOfEvent = datetime.now() logging.info(str(timeOfEvent) + ": Resetting Connection") resetCon(sock1)
def send_payload(sock: socket, payload: PayloadEncoder or PayloadEventMessages, address=None): if sock is None or sock._closed or payload is None: print("[x] Unable to send payload [Payload %s, Socket %s]" % (payload, socket)) return if isinstance(payload, PayloadEventMessages): payload = payload.value if address is None: sock.sendall(encode_to_json(payload.to_dict()).encode("utf-8")) else: sock.sendto(encode_to_json(payload.to_dict()).encode("utf-8"), address)
def udp_thread(server: socket, address: tuple, data: bytes): ''' メッセージを受信 最初の00やmagic cookieの値の正当性を確かめる メッセージ長、メソッドとクラスの正当性 fingerprintを使ってる場合、その正しさ エラーがある場合はただ捨てる 認証チェック ''' # headerの中身をごにょごにょして残りの長さを求める header, payload = data[0:20], data[20:] obj = Parser.parse(header, payload, address) server.sendto(b''.join(map(lambda x: x.bin, obj)), address)
def ping(self, sock: socket) -> bool: """Returns `true` if the connection to the miio device is working. The token is not verified at this stage. """ try: sock.sendto(HELLO, self.addr) raw = sock.recv(1024) if raw[:2] == b"\x21\x31": self.device_id = int.from_bytes(raw[8:12], "big") self.delta_ts = time.time() - int.from_bytes(raw[12:16], "big") return True except: pass return False
def send_one_juice_task_complete(self, current_machine_socket: socket, master_IP_address: str, master_port: int, current_machine_IP_address: str): one_juice_task_complete = { 'Type': "one_juice_task_complete", 'finished_juice_ip': current_machine_IP_address, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } one_juice_task_complete_json = json.dumps(one_juice_task_complete) current_machine_socket.sendto( (one_juice_task_complete_json).encode('utf-8'), (master_IP_address, master_port))
def target_on_listening(s: socket, target: tuple): host = target[0] if target[0] != 'localhost' else '127.0.0.1' port = target[1] s.settimeout(1) try: SYN = struct.pack('iii', 1, 1, 0) s.sendto(SYN, target) s.recvfrom(1024) s.settimeout(None) return True except timeout: s.settimeout(None) return False
def client_handler(client: socket, address, c: Cache): proxy_response = http_request_pipeline(address, receive_client_request(client)) if isinstance(proxy_response, HttpErrorResponse): client.sendto( proxy_response.to_byte_array(proxy_response.to_http_string()), address) else: response = c.check(proxy_response) if response is None: response = server_handler(proxy_response) c.cache(proxy_response, response) if response is not None: for proxy_response in response: client.sendto(proxy_response, address) client.close()
def send_put_ack(self, current_machine_socket: socket, master_port: int, master_IP_address: str, sdfs_file_name: str, current_machine_ip: str): put_ack = { 'Type': "put_ack", 'IP_putted': current_machine_ip, 'sdfs_file_name': sdfs_file_name, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip(), } put_ack_json = json.dumps(put_ack) current_machine_socket.sendto((put_ack_json).encode('utf-8'), (master_IP_address, master_port))
def send_juice_task_to_node(self, current_machine_socket: socket, target_ip_address: str, target_port: int, juice_exe: str, task_files: list): send_juice_task_to_node_dic = { 'Type': "send_juice_task_to_node", 'juice_exe': juice_exe, 'task_files': task_files, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip() } send_juice_task_to_nodee_json = json.dumps(send_juice_task_to_node_dic) current_machine_socket.sendto( (send_juice_task_to_nodee_json).encode('utf-8'), (target_ip_address, target_port))
def recv_packet(s: socket, packets): while True: try: data, addr = s.recvfrom(2048) data, question, query = server_wrapper.server_decrypt(data) p = Packet(data, question, query, addr) if packets.full(): p2 = packets.get() s.sendto( server_wrapper.server_encrypt(p2.query, b'hi', p2.question), p2.addr) packets.put(p) if question != 'aGVsbG8=.group-7.cs305.fun' and question: tun.write(data) else: print('receive empty packet') except binascii.Error: continue
def untilRequestFromClient(sock1: socket): firstPartOfHandshake: bool = False while firstPartOfHandshake is False: # keep receiving incoming message until three way handshake data, address = sock1.recvfrom(4096) # if the first msg received equals the first msg in the protocol then send accept if data.decode() == request(address[0]): sent = sock1.sendto(serverAccept(address[0]).encode(), address) firstPartOfHandshake = True
def handle_client(sock: socket, addr: tuple, data: bytes, dns_retriever: DnsRetriever): message = DnsMessage(data) res_from_zone = dns_retriever.get_from_zone_file(message) if res_from_zone: response = res_from_zone else: cached_res = dns_retriever.get_cached_response( message.questions[0].name, message.questions[0].type) if len(cached_res) > 0: response = get_response(message, cached_res) else: lst = get_ips_for_NS(dns_retriever, dns_retriever.get_best_NS_servers(message.questions[0].name)) lst.append(dns_retriever.get_root_server()) response = dns_recursion(dns_retriever, message, lst, {}) if response: sock.sendto(data[:2] + response.data[2:], addr) else: sock.sendto( data[:2] + DnsMessage.get_cant_fount_header_flags() + data[4:], addr)
def send_put_request_to_master(self, current_machine_socket: socket, master_port: int, master_IP_address: str, requestor_ip: str, sdfs_file_name: str, local_file_name_to_store: str): put_request = { 'Type': "put_request_to_master", 'sdfs_file_name': sdfs_file_name, 'local_file_name_to_store': local_file_name_to_store, 'Timestamp': (str(datetime.now().isoformat(timespec='seconds'))).strip(), 'requestor_ip': requestor_ip } put_request_json = json.dumps(put_request) current_machine_socket.sendto((put_request_json).encode('utf-8'), (master_IP_address, master_port))