def login(self, sock: socket, vertex: int): """ Login function from a switch to this controller :sock: Socket from the switch connection :vertex: Vertex_ID of the switch """ self.logging.info( "Received login from: [{addr}] on port [{port}] with vertex_id [{vertex}]" .format(addr=sock.getpeername()[0], port=sock.getsockname()[1], vertex=vertex)) self.logging.debug("Packet [{}]".format( self.network_state.adjacency_packet)) self.logging.info( "Getting info for vertex[{}] at [{}]:[{}] for login".format( vertex, sock.getpeername()[0], sock.getsockname()[1])) send_data("Controller", self.router_sock, (f"{vertex}, " + str(self.network_state.adjacency_packet))) data = recv_data("Controller", self.router_sock) self.logging.info( "Sending forwarding packet from login to vertex[{}] at [{}]:[{}]". format(vertex, sock.getpeername()[0], sock.getsockname()[1])) self.send_data(sock, data)
async def readData(self, my_socket: socket): myPort = my_socket.getsockname() print("Starting to listen to port:", myPort) await asyncio.sleep(randint(1, 3)) count = 0 bytesReceived = 0 while True: try: current_loop = asyncio.get_event_loop() data = await current_loop.sock_recv(my_socket, MAX_UDP_DATA) #print(f"Got data on port {myPort}", data) if self.thread_lock.acquire(blocking=True, timeout=0.5): self.transport_mgr.gotMessage(data.decode()) self.thread_lock.release() else: print("UDP Message discarded, thread.lock failed") continue count = count + 1 bytesReceived = bytesReceived + len(data) print( f"We've got {count} packets, and a total of {bytesReceived} bytes" ) except Exception as err: print( f'Failure processing data from socket. Type: {type(err)}, errorValue:["{err}"]' ) raise break
def handle_client(self, client_socket: socket): '''开始接受并处理数据''' addr, port = client_socket.getsockname() # 处理函数 # self.getfile(session) session = Session(client_socket) self.chat(session)
def handle_client(self, client_socket: socket): '''开始接受并处理数据''' addr, port = client_socket.getsockname() # 处理函数 self.chat(client_socket) client_socket.close() print("[-] Connection {}:{} closed".format(addr, port))
def register_connection(self, client_socket: socket, client_id: str): new_client = ClientInfo(client_id, socket=client_socket) self.clients[client_id] = new_client self.verbose_debug("New client: " + new_client.get_tag() + " with address " + str(client_socket.getsockname()) + " connected.") Thread(target=self.handle_client, args=[new_client], daemon=True).start()
def handle_client(self, client_socket: socket, data: bytes, buffer=1024): '''开始接受并处理数据''' addr, port = client_socket.getsockname() # 接收数据 request = client_socket.recv(buffer) self.data.append(request.decode('utf-8')) # print("[*] Recieved: {} \t from {}:{}".format(str(request),addr,port)) # 发送数据 client_socket.send(data) client_socket.close() print("[-] Connection {}:{} closed".format(addr, port))
def connect_socket(my_socket : socket, dst_addr : str, dst_port : int): """This is needed to get the local IP and Port""" #print(f"Will (attempt to) connect with: socket({my_socket.fileno()}), towards {dst_addr}, {dst_port}") try: my_socket.connect((dst_addr, dst_port)) except socket.error as err: print("Socket connect failed: ", my_socket, " ", err) return "", 0 (localAddr, localPort) = my_socket.getsockname() return (localAddr, localPort)
def bind_socket(my_socket: socket, *, bindAddress ="", bindPort = 0) -> bool: """""" #print(f"Binding: {bindPort}") try: ### TODO: Acquire local-IP. Will be 172.x in docker... print(f"Trying to bind socket({my_socket.fileno()}) with: [{bindAddress}] and Port: [{bindPort}]") ### TQ-TODO: IpV6 will expect a 4-tuple. (host, port, flowinfo, scopeid) my_socket.bind((bindAddress, bindPort)) except socket.error as err: print("Socket bind failed with error %s" % (err)) return False print("Socket bound successfully: ", my_socket.getsockname()) return True
def handle_client(self, client_socket: socket): '''开始接受并处理数据''' addr, port = client_socket.getsockname() # 处理函数 session = Session(client_socket) # print(session.receive()) # session.send(b'this is a server') session.close() print("[-] Connection {}:{} closed".format(addr, port))
def add(self, sock: socket, vertex: int, port: int, ip: str): """ """ self.logging.info( "Adding connection for vertex[{}] at [{}]:[{}] : [{}]:[{}]". format(vertex, sock.getpeername()[0], sock.getsockname()[1], ip, port)) self.network_state.update_port(vertex, port, ip) send_data("Controller", self.router_sock, (f"{vertex}, " + str(self.network_state.adjacency_packet))) data = recv_data("Controller", self.router_sock) self.send_data(sock, data) self.logging.info("Connection added")
def delete(self, sock: socket, vertex: int, port: int): """ """ self.logging.info( "Removing connection for vertex[{}] at [{}]:[{}] : Vertex[{}]:Port[{}]" .format(vertex, sock.getpeername()[0], sock.getsockname()[1], vertex, port)) self.network_state.update_port(vertex, port, "0.0.0.0") self.send_data( self.router_sock, (f"{vertex}, " + str(self.network_state.adjacency_packet))) data = recv_data("Controller", self.router_sock) self.logging.info("Connection Removed") self.send_data(sock, data)
def exit(self, sock: socket, vertex: int): """ Closes socket and exits client thread :sock: Socket to clean up :vertex: Vertex ID that is closing """ self.logging.info( "Vertex[{vertex}] session from {addr} on port {port} closed". format(vertex=vertex, addr=sock.getpeername()[0], port=sock.getsockname()[1])) self.logging.debug("Closing socket for vertex: {}".format(vertex)) sock.close() self.send_data(self.router_sock, "EXIT") self.router_sock.close() exit(0)
def recv_greeting(app: str, sock: socket): """ :app: Which application is receiving the data :sock: Socket to receive the greeting on :return: Boolean, True if valid greeting, false otherwise """ logger = logging.getLogger(app) greeting = sock.recv(28) if greeting.decode('utf-8') == "-- CONNECTION ESTABLISHED --": logger.debug( "Connection established with host [{host}] on port [{port}]". format(host=sock.getpeername()[0], port=sock.getsockname()[1])) print(greeting.decode("utf-8")) return True else: logger.error("Error with connection, aborting.") logger.error(greeting.decode("utf-8")) return False
def read_socket(client: Client = None, current_socket: socket = None, address: str = ""): global all_clients, online_clients, all__admins, getting_img, img conn = sqlite3.connect("chatDB1.db") cursor = conn.cursor() now = datetime.datetime.now().time() # now = lambda: datetime.datetime.now().time() print("now is: ", now, " getting_img is: ", getting_img) if current_socket == None: current_socket = client.get_conn() boolean = True while boolean: if client and client.get_conn() is server: print("\nis server, name: ", str(current_socket.getsockname())) print("clients are: ", str(all_clients)) print("online clients are: ", str(online_clients)) (new_socket, address) = server.accept() conns.append(new_socket) new_socket.send( "Welcome to the server, pls send us your name".encode()) name = new_socket.recv(1024).decode() if len(all_clients) < 1: all_clients.append((name, "", 1)) else: all_clients.append((name, "", 0)) c = Client(name, new_socket, address) online_clients.append(c) elif getting_img: print("in getting img elif") data = current_socket.recv(1024).decode() img += data # if data[::-1].startswith("//ServerEnd"): if data[::-1].startswith("dnErevreS//"): getting_img = False for client2 in online_clients: if client2.get_conn() is not current_socket: client2.get_conn().send(img.encode()) img = "" print("done with get image for now") else: # print(f"pre data read - client:{client} - current_socket:{current_socket}\n") if current_socket == None: data = client.get_conn().recv(1024).decode() else: data = current_socket.recv(1024).decode() if client == None: for online_client in online_clients: if online_client.get_conn( ) == current_socket or online_client.get_conn is current_socket: client = online_client if data == "": time.sleep(2) print("no answer from the client - ") for Oclient in online_clients: if Oclient.get_conn() is current_socket: Oclient.get_conn.send("You were kicked! ".encode()) online_clients.remove(Oclient) print("connection closed") elif data.startswith("/signup"): param_list = data.split("-") exist = False for tup in all_clients: if tup[0] == param_list[1]: exist = True if exist: current_socket.send( "That name already exists, pls send us another name". encode()) if not exist: c = Client(param_list[1], current_socket, address, param_list[2]) client_tup = None if len(all_clients) < 1: client_tup = (param_list[1], param_list[2], 1) else: client_tup = (param_list[1], param_list[2], 0) all_clients.append(client_tup) all__admins.append(client_tup) online_clients.append(c) with conn: cursor.execute("INSERT INTO chatDB VALUES (?, ?, ?)", client_tup) # c.get_conn().send("ok, name was verified for: {}".format(param_list[1]).encode()) print( f"/signup trying to send: ok, verified for: {param_list[1]} : {param_list[2]}" ) c.get_conn().send( f"/signup ok, verified for: {param_list[1]} : {param_list[2]}" .encode()) print("/signup: name was verified for: {}\n".format( param_list[1])) elif data.startswith("/login"): print("entering /login") param_list = data.split("-") print("/login param_list: ", param_list) exist = False for tup in all_clients: if tup[0] == param_list[1]: exist = True if exist: c = Client(param_list[1], current_socket, address, param_list[2]) client_tup = None online_clients.append(c) print( f"/login trying to send: ok, verified for: {param_list[1]} : {param_list[2]}" ) c.get_conn().send( f"/login ok, name was verified for: {param_list[1]} : {param_list[2]}" .encode()) print("/login: name was verified for: {}\n".format( param_list[1])) else: print("first exist was false") string = "We cant find a phone number matching that name, or the opposite\nplease try again" current_socket.send(string.encode()) print( "/login: We cant find a phone number matching that name, or the opposite\nplease try again\n" ) # continue elif data.startswith("/img") or data.startswith("//serverimg"): print("in /img") img = "" img = data # print(f"got: {img}") print(f"client is: {client}") if data[::-1].startswith( "dnErevreS//") or "//ServerEnd" in data: getting_img = False for client2 in online_clients: if client2.get_conn() is not current_socket: if client: client2.get_conn().send( f"[{now}] {client.get_name()} sends: ". encode()) client2.get_conn().send(img.encode()) print("done with get image for now") else: getting_img = True print("starting getting img process, getting img is: ", getting_img) # img_thread = Thread(target=get_img, args=(client)) # img_thread.start() elif data == "/help": commands_string = """ /help - to get the full list of commands the server supports \n /private-[name]: [msg] - to send a private msg to one of the other clients who exists in the server \n /all_members - get the names of all the members in the server \n /online_members - get the names of all the members who are online \n /all_admins - get a list of all the admins in the server \n /img:[link] - send an img """ if client: client.get_conn().send(commands_string.encode()) else: current_socket.send(commands_string.encode()) elif data.startswith("/private"): x = data.find("-") # position where the name starts y = data.find(":") # position where the msg starts if x == -1 or y == -1: client.get_conn().send( "Error in receiving the msg, pls try again".encode()) else: name = data[x + 1:y] msg = data[y + 1:] found = False for client2 in online_clients: if client2.get_name() == name: found = True client2.get_conn().send( "[{}] {} whispers: {}".format( now, client.get_name(), msg).encode()) # client2.get_conn().send("[{}] {} whispers: {}".format(now.strftime("%Y-%m-%d %H:%M:%S"), client.get_name(), msg).encode()) if found == False: client2.get_conn().send( "[{}] User: {} not found".format(now, name).encode()) elif data.startswith("/all_members"): clients = "" for tup in all_clients: print("tup: ", tup[0]) clients += tup[0] + ", " clients = clients[0:len(clients) - 2] client.get_conn().send("[{}] all the members are: {} ".format( now, clients).encode()) print( "/all_members - all_clients is: {}, clients is: {}".format( all_clients, clients)) elif data.startswith("/online_members"): clients = "" for client in online_clients: clients += client.get_name() + ", " clients = clients[0:len(clients) - 2] client.get_conn().send( "[{}] all the online members are: {} ".format( now, clients).encode()) elif data.startswith("/all_admins"): clients = "" for tup in all__admins: clients += tup[0] + ", " clients = clients[0:len(clients) - 2] client.get_conn().send("[{}] all the admins are: {} ".format( now, clients).encode()) else: if client == None: for online_client in online_clients: if online_client.get_conn( ) == current_socket or online_client.get_conn is current_socket: client = online_client print( f"last else - client:{client} - current_socket:{current_socket}\n" ) print(f"online clients is: {online_clients}\n") print(f"last else - {client.get_name()} sends: {data}\n") for client2 in online_clients: if client2.get_conn() is not current_socket: client2.get_conn().send( f"[{now}] {client.get_name()} sends: {data}". encode())
def receive_one_ping(sock: socket, icmp_id: int, seq: int, timeout: int) -> float: """Receives the ping from the socket. IP Header (bits): version (8), type of service (8), length (16), id (16), flags (16), time to live (8), protocol (8), checksum (16), source ip (32), destination ip (32). ICMP Packet (bytes): IP Header (20), ICMP Header (8), ICMP Payload (*). Ping Wikipedia: https://en.wikipedia.org/wiki/Ping_(networking_utility) ToS (Type of Service) in IP header for ICMP is 0. Protocol in IP header for ICMP is 1. Args: sock: The same socket used for send the ping. icmp_id: ICMP packet id. Sent packet id should be identical with received packet id. seq: ICMP packet sequence. Sent packet sequence should be identical with received packet sequence. timeout: Timeout in seconds. Returns: The delay in seconds or None on timeout. Raises: TimeToLiveExpired: If the Time-To-Live in IP Header is not large enough for destination. TimeExceeded: If time exceeded but Time-To-Live does not expired. DestinationHostUnreachable: If the destination host is unreachable. DestinationUnreachable: If the destination is unreachable. """ has_ip_header = (os.name != 'posix') or (platform.system() == 'Darwin') or ( sock.type == socket.SOCK_RAW ) # No IP Header when unprivileged on Linux. if has_ip_header: ip_header_slice = slice(0, struct.calcsize(IP_HEADER_FORMAT)) # [0:20] icmp_header_slice = slice( ip_header_slice.stop, ip_header_slice.stop + struct.calcsize(ICMP_HEADER_FORMAT)) # [20:28] else: _debug("Unprivileged on Linux") icmp_header_slice = slice(0, struct.calcsize(ICMP_HEADER_FORMAT)) # [0:8] timeout_time = time.time() + timeout # Exactly time when timeout. _debug("Timeout time: {} ({})".format(time.ctime(timeout_time), timeout_time)) while True: timeout_left = timeout_time - time.time( ) # How many seconds left until timeout. timeout_left = timeout_left if timeout_left > 0 else 0 # Timeout must be non-negative _debug("Timeout left: {:.2f}s".format(timeout_left)) selected = select.select( [ sock, ], [], [], timeout_left) # Wait until sock is ready to read or time is out. if selected[0] == []: # Timeout raise errors.Timeout(timeout=timeout) time_recv = time.time() _debug("Received time: {} ({}))".format(time.ctime(time_recv), time_recv)) recv_data, addr = sock.recvfrom( 1500 ) # Single packet size limit is 65535 bytes, but usually the network packet limit is 1500 bytes. if has_ip_header: ip_header_raw = recv_data[ip_header_slice] ip_header = read_ip_header(ip_header_raw) _debug("Received IP header:", ip_header) else: ip_header = None icmp_header_raw, icmp_payload_raw = recv_data[ icmp_header_slice], recv_data[icmp_header_slice.stop:] icmp_header = read_icmp_header(icmp_header_raw) _debug("Received ICMP header:", icmp_header) _debug("Received ICMP payload:", icmp_payload_raw) if not has_ip_header: # When unprivileged on Linux, ICMP ID is rewrited by kernel. icmp_id = sock.getsockname()[ 1] # According to https://stackoverflow.com/a/14023878/4528364 if icmp_header[ 'type'] == IcmpType.TIME_EXCEEDED: # TIME_EXCEEDED has no icmp_id and icmp_seq. Usually they are 0. if icmp_header[ 'code'] == IcmpTimeExceededCode.TTL_EXPIRED: # Windows raw socket cannot get TTL_EXPIRED. See https://stackoverflow.com/questions/43239862/socket-sock-raw-ipproto-icmp-cant-read-ttl-response. raise errors.TimeToLiveExpired( ip_header=ip_header, icmp_header=icmp_header ) # Some router does not report TTL expired and then timeout shows. raise errors.TimeExceeded() if icmp_header[ 'type'] == IcmpType.DESTINATION_UNREACHABLE: # DESTINATION_UNREACHABLE has no icmp_id and icmp_seq. Usually they are 0. if icmp_header[ 'code'] == IcmpDestinationUnreachableCode.DESTINATION_HOST_UNREACHABLE: raise errors.DestinationHostUnreachable( ip_header=ip_header, icmp_header=icmp_header) raise errors.DestinationUnreachable(ip_header=ip_header, icmp_header=icmp_header) if icmp_header['id']: if icmp_header[ 'type'] == IcmpType.ECHO_REQUEST: # filters out the ECHO_REQUEST itself. _debug("ECHO_REQUEST received. Packet filtered out.") continue if icmp_header[ 'id'] != icmp_id: # ECHO_REPLY should match the ICMP ID field. _debug("ICMP ID dismatch. Packet filtered out.") continue if icmp_header[ 'seq'] != seq: # ECHO_REPLY should match the ICMP SEQ field. _debug("IMCP SEQ dismatch. Packet filtered out.") continue if icmp_header['type'] == IcmpType.ECHO_REPLY: time_sent = struct.unpack( ICMP_TIME_FORMAT, icmp_payload_raw[0:struct.calcsize(ICMP_TIME_FORMAT)])[0] _debug("Received sent time: {} ({})".format( time.ctime(time_sent), time_sent)) return time_recv - time_sent _debug("Uncatched ICMP packet:", icmp_header)
def __end(self, sock: socket): print("Disconnecting from:", sock.getsockname()) self.__selector.unregister(sock) sock.close()