Exemplo n.º 1
1
    def _is_client_request_ssl(cls, socket_: socket.socket) -> bool:
        while True:
            original_timeout = socket_.gettimeout()
            socket_.setblocking(False)

            try:
                data = socket_.recv(3, socket.MSG_PEEK)
            except OSError as error:
                if error.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
                    yield from asyncio.sleep(0.01)
                else:
                    raise
            else:
                break
            finally:
                socket_.settimeout(original_timeout)

        _logger.debug('peeked data %s', data)
        if all(ord('A') <= char_code <= ord('Z') for char_code in data):
            return False
        else:
            return True
Exemplo n.º 2
1
    def __demodulate(self, connection: socket.socket):
        connection.settimeout(0.1)
        time.sleep(self.TIMEOUT)

        total_data = []
        while True:
            try:
                data = connection.recv(65536)
                if data:
                    total_data.append(data)
                else:
                    break
            except socket.timeout:
                break

        if len(total_data) == 0:
            logger.error("Did not receive any data from socket.")

        arr = np.array(np.frombuffer(b"".join(total_data), dtype=np.complex64))
        signal = Signal("", "")
        signal._fulldata = arr
        pa = ProtocolAnalyzer(signal)
        pa.get_protocol_from_signal()
        return pa.plain_bits_str
    def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
        # Grab the banner
        if self.SHOULD_WAIT_FOR_SERVER_BANNER:
            sock.recv(2048)

        # Send Start TLS
        sock.send(self.START_TLS_CMD)
        if self.START_TLS_OK not in sock.recv(2048):
            raise StartTlsError(self.ERR_NO_STARTTLS)
    def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
        sock.send(self.START_TLS_CMD)
        data = sock.recv(4)
        if not data or len(data) != 4 or data[:2] != b'\x03\x00':
            raise StartTlsError(self.ERR_NO_STARTTLS)
        packet_len = struct.unpack(">H", data[2:])[0] - 4
        data = sock.recv(packet_len)

        if not data or len(data) != packet_len:
            raise StartTlsError(self.ERR_NO_STARTTLS)
    def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
        # Get the SMTP banner
        sock.recv(2048)

        # Send a EHLO and wait for the 250 status
        sock.send(b'EHLO sslyze.scan\r\n')
        if b'250 ' not in sock.recv(2048):
            raise StartTlsError(self.ERR_SMTP_REJECTED)

        # Send a STARTTLS
        sock.send(b'STARTTLS\r\n')
        if b'220' not in sock.recv(2048):
            raise StartTlsError(self.ERR_NO_SMTP_STARTTLS)
Exemplo n.º 6
0
def addNewNode(s : socket.socket, orderNode):
    global lockCount
    global lockLst, eps, numNode, k, evnValidate, nodeRecv

    try:
        #receive name of the node
        dataRecv = s.recv(1024).decode()
        addNetworkIn(len(dataRecv))
        try:
            if (dataRecv != ''):
                arg = parser.parse_args(dataRecv.lstrip().split(' '))
                nameNode = arg.name[0]
                if (numNode == 0):
                    numNode = arg.num_node[0]
                    for i in range(numNode):
                        nodeRecv.append(False)
        except socket.error as e:
            print('Error: ' + str(e))
            return

        lockLst.acquire()
        lstSock.append(s)
        lstName.append(nameNode)
        lockLst.release()

        if (orderNode == NUMBER_NODE):
            evnInitComplete.set()

    except socket.error:
        pass
Exemplo n.º 7
0
def _recv(sock: socket.socket, size: int) -> bytes:
    """Secondary function to receive a specified amount of data."""
    message = b''
    while len(message) < size:
        packet = sock.recv(size - len(message))
        if not packet:
            sock.close()
            raise OSError("Nothing else to read from socket")
        message += packet
    return message
Exemplo n.º 8
0
Arquivo: helper.py Projeto: kytos/kyco
def do_handshake(client: socket):
    """Get a client socket and do the handshake of it.

    This method receives a client socket that simulates a switch on the
    network and does the OpenFlow handshake process with a running controller
    on the network.

    Args:
        client (socket): a socket object connected to the controller.

    Returns:
        The client with the handshake process done.

    """
    # -- STEP 1: Send Hello message
    client.send(Hello(xid=3).pack())

    # -- STEP 2: Wait for Hello response
    binary_packet = b''
    while len(binary_packet) < 8:
        binary_packet = client.recv(8)
    header = Header()
    header.unpack(binary_packet)

    # -- STEP 3: Wait for features_request message
    binary_packet = b''
    # len() < 8 here because we just expect a Hello as response
    while len(binary_packet) < 8:
        binary_packet = client.recv(8)
    header = Header()
    header.unpack(binary_packet)

    # -- STEP 4: Send features_reply to the controller
    basedir = os.path.dirname(os.path.abspath(__file__))
    raw_dir = os.path.join(basedir, 'raw')
    message = None
    with open(os.path.join(raw_dir, 'features_reply.cap'), 'rb') as file:
        message = file.read()
    client.send(message)

    return client
Exemplo n.º 9
0
def handlerequest(clientsocket: socket.socket):
    conn = connecttodb()
    cursor = conn.cursor()
    tagid = bytes.decode(clientsocket.recv(3))
    query = 'select * from tagdata where id={0}'.format(tagid)
    cursor.execute(query)
    s=[]
    for (id, location, officehours, otherinfo, description) in cursor:
        s = [str(id)+','+location + ',', officehours + ',', otherinfo + ',', description]
        s.insert(0, str(len(''.join(s)))+',')
    clientsocket.send(bytes(''.join(s),encoding='utf8'))
    clientsocket.close()
    def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
        # Open an XMPP stream
        sock.send(self.XMPP_OPEN_STREAM.format(xmpp_to=self._xmpp_to).encode('utf-8'))

        # Get the server's features and check for an error
        server_resp = sock.recv(4096)
        if b'<stream:error>' in server_resp:
            raise StartTlsError(self.ERR_XMPP_REJECTED)
        elif b'</stream:features>' not in server_resp:
            # Get all the server features before initiating startTLS
            sock.recv(4096)

        # Send a STARTTLS message
        sock.send(self.XMPP_STARTTLS)
        xmpp_resp = sock.recv(2048)

        if b'host-unknown' in xmpp_resp:
            raise StartTlsError(self.ERR_XMPP_HOST_UNKNOWN)

        if b'proceed' not in xmpp_resp:
            raise StartTlsError(self.ERR_XMPP_NO_STARTTLS)
Exemplo n.º 11
0
def workWithUser(s : socket.socket):
    global parser
    global bUserConnect
    bUserConnect = True
    try:
        while 1:
            dataRecv = s.recv(1024).decode()
            if (dataRecv == ''):
                return
    except socket.error:
        return
    finally:
        bUserConnect = False
        s.close()
Exemplo n.º 12
0
    def recv(self, skt: socket.socket, nbytes: int, buf: bytes) -> Tuple[bytes, bytes]:
        while len(buf) < nbytes:
            data: bytes = b''
            try:
                data = skt.recv(max(nbytes - len(buf), 4096))
            except socket.timeout:
                logging.error("error: recv socket.timeout")
            except Exception as e:
                logging.error(f'error: recv exception: {e!s}')

            if data == b'':
                return b'', b''
            buf += data

        return buf[:nbytes], buf[nbytes:]
Exemplo n.º 13
0
    def _recv_exact(self, sock : socket.socket, num_bytes : int) -> bytes:
        """Receive an exact number of bytes from a socket. This is
        a wrapper around sock.recv() that can return less than the number
        of requested bytes.

        Args:
            sock (socket): Socket to receive data from.
            num_bytes (int): Number of bytes that will be returned.
        """
        bufs = []
        while num_bytes > 0:
            b = sock.recv(num_bytes)
            if len(b) == 0:
                break
            num_bytes -= len(b)
            bufs.append(b)
        return b''.join(bufs)
Exemplo n.º 14
0
def _recv_all(sock: socket.socket, n_bytes: int) -> Tuple[bytes, bool]:
    '''
    read n bytes from a socket
    '''
    data = b''

    while len(data) < n_bytes:
        try:
            fragment = sock.recv(n_bytes - len(data))
        except OSError:
            return b'', True

        if not fragment:
            break
        else:
            data += fragment

    return data, False
Exemplo n.º 15
0
    def recv(self, sock: socket.socket, client):  # 接受客户端数据
        while not self.event.is_set():
            data = sock.recv(1024)  # 阻塞到数据的到来

            msg = data.decode().strip()
            # 客户端退出命令
            if msg == 'quit' or msg == '':  # 主动断开得到空串
                with self.lock:
                    self.clients.pop(client)
                    sock.close()
                logging.info('{} quits'.format(client))
                break
            msg = "{:%Y%m/%d %H:%M:%S} {}:{}\n{}\n".format(
                datetime.datetime.now(), *client, data.decode())
            logging.info(msg)
            msg = msg.encode()
            for s in self.clients.values():
                s.send(msg)
Exemplo n.º 16
0
    def _receive_message_size(self, sock: socket.socket):

        message_size_chunks = []
        bytes_received = 0

        while bytes_received < self._header_size:
            chunk = sock.recv(
                min(
                    self._header_size - bytes_received,
                    self._header_size
                )
            )
            if chunk == b'':
                raise RuntimeError("JSONSocket: socket broken")
            message_size_chunks.append(chunk.decode('utf-8'))
            bytes_received += len(chunk)

        return int(''.join(message_size_chunks))
Exemplo n.º 17
0
 def call(self, *args, **kwargs):
     """
     Remote call.
     """
     socket = Socket(AF_INET, SOCK_STREAM)
     socket.connect(self.address)
     try:
         method = Document()
         method.name = self.name
         method.args = args
         method.kwargs = kwargs
         socket.send(method.dump())
         reply = socket.recv(4096)
         result = Document()
         result.load(reply)
         return result
     finally:
         socket.close()
Exemplo n.º 18
0
 def _echo(self, sock: socket):
     try:
         req_head = sock.recv(1024)
     except BrokenPipeError:
         return
     else:
         if not req_head:
             return
         head = self._get_head(req_head)
         head = head.replace('STATUS_CODE', str(self.status))
         sock.send(head.encode('utf-8'))
         self._send_body(sock)
         logging.info('HTTP/1.1 %s GET %s' % (self.status, Signal.path))
         if Signal.debug:
             print('\nReceived: %s' % req_head)
             print('\nSend headers: %s' % head)
             print('-'*36)
     sock.close()
Exemplo n.º 19
0
  def relay_connection(self, client_sock : socket.socket, client_addr : Tuple[str, int]):
    """
    Address: [1-byte type][variable-length host][2-byte port]
    The client's connection request is:
    +-----+----------+----------+-----------+-----------+----------+
    | VER | CMD CODE | RESERVED | ADDR TYPE | DEST TYPE | PORT NUM |
    +-----+----------+----------+-----------+-----------+----------+
    """
    future = Future()
    reg_socket_future_read(future, client_sock)
    yield future
    check_socket(client_sock)
    request_bytes = client_sock.recv(4096)
    try:
      logging.debug(str(decode_connection_request(request_bytes)))
    except:
      pass

    yield from self.local_relay(client_sock, client_addr, request_bytes)
Exemplo n.º 20
0
def _recv_n_byte(conn: socket.socket, packet_size: int):
    """
    Private function to receive n amount of bytes
    :param conn: Connection socket
    :param packet_size: Total size of a packet to receive
    :return: Received data in bytes. None if not all bytes were received.
    """
    data = b''
    try:
        while len(data) < packet_size:
            packet = conn.recv(packet_size - len(data))
            if not packet:
                return None
            data += packet
    except Exception as err:
        log.error("Unknown error in _recv_n_byte [%s]" % err)
        return False
    log.debug("Received [%s] bytes." % packet_size)
    return data
Exemplo n.º 21
0
def send_frames(client_sock: socket.socket, addr: tuple, buffer: queue.Queue):
    print('\n[Server] 클라이언트 접속: {}:{}'.format(addr[0], addr[1]))

    while True:
        try:
            data = client_sock.recv(1, socket.MSG_WAITALL)

            if not data:
                print('[Server] 클라이언트 종료: {}:{}'.format(addr[0], addr[1]))
                break

            data = buffer.get()
            client_sock.send(str(len(data)).ljust(16).encode())
            client_sock.send(data)

        except ConnectionResetError:
            print('[Server] 클라이언트 종료: {}:{}'.format(addr[0], addr[1]))
            break
    client_sock.close()
Exemplo n.º 22
0
def recv_from(server: socket.socket):
    end_marker = ";endTCPmessage"
    total_msg = []
    while True:
        msg = (server.recv(1024)).decode("utf-8")
        if end_marker in msg:
            total_msg.append(msg[:msg.find(end_marker)])
            break
        total_msg.append(msg)

        # TODO: Weird section. Supposed to handle split msg, not sure how it works
        if len(total_msg) > 1:
            # check if end of msg was split
            last_pair = total_msg[-2] + total_msg[-1]
            if end_marker in last_pair:
                total_msg[-2] = last_pair[:last_pair.find(end_marker)]
                total_msg.pop()
                break
    return ''.join(total_msg)
Exemplo n.º 23
0
def catp_mess_get(client: socket.socket) -> bytes:
    """
    Function for CATP messages receiving by socket library using TCP
    Args:
        client: socket object of connection from where you receive packet

    Returns:
        CATP packet in form of bytes object
    """
    message = bytes()
    while True:
        chunk = client.recv(128)
        if not chunk:
            raise ConnectionError
        message += chunk
        if b'\r\n\r\n' in message:
            break
    message = message.split(b'\r\n\r\n')[0] + b'\r\n\r\n'
    return message
Exemplo n.º 24
0
 def clientHandler(self, conn: socket.socket, address,
                   stop_event: threading.Event):
     print("clientHandler")
     disconnect = threading.Event()
     while not stop_event.is_set() and not disconnect.is_set():
         try:
             data = conn.recv(self.max_recv_bytes)
             if data:
                 if self.lag is not None:
                     time.sleep(self.lag)
                 response = self.produce_respose(data, disconnect)
                 conn.send(response)
             else:
                 raise Exception('Client disconnected')
         except Exception as e:
             disconnect.set()
             conn.shutdown(socket.SHUT_RDWR)
             conn.close()
     conn.close()
def get_page(server_address, request_string):
	try:
		client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
		client_socket.connect((server_address, REMOTE_PORT))

		client_socket.send(request_string.encode())

		reply = bytes()
		while True:
			part_body = client_socket.recv(BUFFER_SIZE).decode("utf-8", "ignore")
			# print part_body
			if not len(part_body):
				break
			reply += part_body

	finally:
		client_socket.close()

	return reply
Exemplo n.º 26
0
    def cmd_base_for_set_type(self, conn: socket.socket,
                              where_and_message: dict) -> None:
        """
        cmd base to set value for set type cmd
        :param conn: socket connect
        :param where_and_message: key is where, value is point message
        """
        for key_point in where_and_message:
            (big_type, big_key, change_type) = key_point
            big_type = {"global": self.get_global_config_args(), "static": self.get_static_config_args()}[big_type] \
                if big_type in ["global", "static"] else big_type
            if big_type is self.get_global_config_args(
            ) or big_type is self.get_static_config_args():
                conn.send(
                    self.send_keep_msg(where_and_message[key_point]).encode())
                return_mem = conn.recv(1024).decode()
                if return_mem == "exit":
                    conn.sendall(self.send_last_msg("bye~").encode())
                    return
                elif return_mem == "jump":
                    continue
                else:
                    config_shadow = big_type
                    big_type_point = big_key.split(".")
                    for value_get in big_type_point:
                        try:
                            if value_get is big_type_point[-1]:
                                config_shadow[value_get] = change_type(int(return_mem)) \
                                    if change_type == bool else change_type(return_mem)
                            else:
                                config_shadow = config_shadow[value_get]
                        except Exception:
                            self.traceback()
                            conn.sendall(
                                self.send_last_msg(
                                    "Error, nothing set.").encode())
                            return
            else:
                self.message("Invalid Big Type.", level="error")
                conn.sendall(self.send_last_msg("now over~").encode())
                return

        conn.sendall(self.send_last_msg("set complete~").encode())
Exemplo n.º 27
0
def mensagens(conexao: socket.socket):
    while True:
        try:
            msg = conexao.recv(1024)

            # caso há mensagem tentará decodificar a mensagem para mostrar ao usuário
            if msg:
                print(msg.decode())
                
            # se não há mensagem, há uma chance que a conexão foi fechada.
            # então a conexão será fechada e um erro será mostrado.
            else:
                conexao.close()
                break

        except Exception as e:
            print(f'Erro ao lidar com a mensagem do servidor: {e}')
            conexao.close()
            break
Exemplo n.º 28
0
def reader(client: socket.socket):
    global ready_write, continue_text, continuer
    while True:
        recv = client.recv(BUFFER_SIZE).decode('utf-8')
        print(recv)
        json_data = json.loads(recv)

        print("Got data: %s" % str(json_data))

        try:
            continuer = (continue_text == json_data["check"])
            continue
        except KeyError:
            pass

        try:
            ready_write = json_data["state"]
        except KeyError:
            pass
Exemplo n.º 29
0
    def client_handler(self, client_socket: socket.socket):

        recv_data = client_socket.recv(1024)

        recv_data_str = recv_data.decode("utf-8")

        recv_lines = recv_data_str.splitlines()

        for line in recv_lines:
            print(line)

        request_header = recv_lines[0]

        file_name = re.match("[^/]*(/[^ ]*)", request_header).group(1)

        if file_name == "/":
            file_name = "index.html"
        else:
            if file_name.startswith("/"):
                file_name = file_name[1:]

        dirPath = os.path.dirname(__file__)

        file_name = os.path.join(dirPath, file_name)
        print("file_name is:", file_name)

        file_context = self.readFile(file_name)

        response = None

        if file_context == None:
            response_header = "http/1.1 404 not found\r\n\r\n"
            response_body = ""

        else:
            response_header = "http/1.1 200 ok\r\n\r\n"
            response_body = file_context

        response = response_header + response_body

        client_socket.send(response.encode("utf-8"))

        client_socket.close()
Exemplo n.º 30
0
 def receive(self, socket_client: socket):
     while True:
         try:
             _bytes = socket_client.recv(4096)
             self.__mutex.acquire()
             for _byte in _bytes:
                 self.__byte_queue.put(int.to_bytes(_byte, 1, "little"))
             self.__mutex.release()
         except Exception as e:
             for pid, client in self.__pid2client.items():
                 if client == socket_client:
                     self.__pid2client.pop(pid)
                     return self.logger.warning(
                         f"A WeChat process has disconnected (PID:{pid}) : {e}"
                     )
             else:
                 pid = "unknown"
                 return self.logger.warning(
                     f"A WeChat process has disconnected (PID:{pid}) : {e}")
Exemplo n.º 31
0
def workWithUser(s: socket.socket):
    global parser
    global bUserConnect
    bUserConnect = True
    try:
        printTop()
        while 1:
            dataRecv = s.recv(1024).decode()
            if (dataRecv == ''):
                return
            arg = parser.parse_args(dataRecv.lstrip().split(' '))
            type = arg.type[0]
            if (type == MyEnum.User.USER_SET_ARG.value):
                updateArg(arg)
    except socket.error:
        return
    finally:
        bUserConnect = False
        s.close()
Exemplo n.º 32
0
def receive_msg(sock: socket.socket):
    json_bytes = bytes()
    while True:
        data = sock.recv(4096).strip()
        if data.endswith(MSG_TERMINATOR):
            data = data[:-1]
            json_bytes += data
            break
        else:
            json_bytes += data

    if not json_bytes:
        raise ConnectionClosedError()

    logger.debug("Received (size: %s): %s", len(json_bytes), json_bytes)

    json_string = json_bytes.decode('utf8')
    msg = json.loads(json_string)
    return msg
Exemplo n.º 33
0
def iter_lines(
    sock: socket.socket, bufsize: int = 16384
) -> typing.Generator[bytes, None, bytes]:
    buff = b""
    while True:
        data = sock.recv(bufsize)
        if not data:
            return b""
        buff += data
        while True:
            try:
                i = buff.index(b"\r\n")
                line, buff = buff[:i], buff[i + 2 :]
                if not line:
                    return buff

                yield line
            except IndexError:
                break
Exemplo n.º 34
0
    def handle_client(self, client_socket:socket.socket):

        recv_data = client_socket.recv(1024).decode("utf-8")
        request_header_lines = recv_data.splitlines()

        for line in request_header_lines:
            print(line)

        response_headers = "HTTP/1.1 200 OK\r\n"  # 200表示找到这个资源
        response_headers += "\r\n" # 用一个空的行与body进行隔开
        
        # 组织 内容主体

        response_body = "hello world"

        response = response_headers + response_body

        client_socket.send(response.encode("utf-8"))
        client_socket.close()
Exemplo n.º 35
0
def send_file(file_name, conn: socket):
    file = open(file_name, "rb")  # 文件对象
    length = getsize(file_name)  # 文件大小
    data = bytes
    try:
        print(("%s\n%d" % (split(file_name)[1], length)).encode())
        conn.send(("%s\n%d" % (split(file_name)[1], length)).encode())
        if conn.recv(3) != b"suc":
            return False
        while data != b"":
            data = file.read(65536)
            conn.send(data)
    except Exception as err:
        print(err)
        return False
    else:
        return True
    finally:
        file.close()
Exemplo n.º 36
0
def receive_n_bytes(conn: socket.socket, n_bytes: int) -> bytes:
    """
    Read n bytes, byte by byte.
    Stop if n_bytes have been read, or
    if a byte is not received.

    """

    data = b""

    while n_bytes > 0:
        res_data = conn.recv(n_bytes)
        if not res_data:
            break

        data += res_data
        n_bytes -= len(res_data)

    return data
Exemplo n.º 37
0
 def read(conn: socket.socket):
     """
     Read response string
     :param conn:
     :return:
     """
     ver = conn.recv(1)
     cmd = conn.recv(1)
     rsv = conn.recv(1)
     atyp = conn.recv(1)
     if atyp == ConnRequest.ADDR_IPV4:
         dst_addr = '.'.join(map(str, conn.recv(4)))
     elif atyp == ConnRequest.ADDR_DOMAIN:
         domain_len = conn.recv(1)[0]
         dst_addr = str(conn.recv(domain_len), encoding='ascii')
     elif atyp == ConnRequest.ADDR_IPV6:
         dst_addr = str(conn.recv(16), encoding='latin-1')
     else:
         dst_addr = ''
     dst_port = int.from_bytes(conn.recv(2), byteorder='big')
     return ConnRequest(dest=(dst_addr, dst_port), method=cmd, ver=ver)
Exemplo n.º 38
0
 def read(conn: socket.socket):
     """
     Read response string
     :param conn:
     :return: Connection Response
     """
     ver = conn.recv(1)
     rep = conn.recv(1)
     rsv = conn.recv(1)
     atyp = conn.recv(1)
     if atyp == ConnResponse.ADDR_IPV4:
         bnd_addr = '.'.join(map(str, conn.recv(4)))
     elif atyp == ConnResponse.ADDR_DOMAIN:
         domain_len = conn.recv(1)[0]
         bnd_addr = str(conn.recv(domain_len), encoding='ascii')
     elif atyp == ConnResponse.ADDR_IPV6:
         bnd_addr = str(conn.recv(16), encoding='latin-1')
     else:
         bnd_addr = ''
     bnd_port = int.from_bytes(conn.recv(2), byteorder='big')
     return ConnResponse(ver=ver, rep=rep, bind=(bnd_addr, bnd_port))
Exemplo n.º 39
0
 def listen_socket(self,sk:socket.socket):
     '''副线程接受sk消息并解码'''
     self.sk = sk
     while True:
         try:
             msg = sk.recv(2048)
         except OSError:
             break
         if self.all_over:
             break
         msg = msg.decode('utf8')
         if not msg:
             print(colored('peer disconnect, stop','red') )
             self.thread_exit(None,None)
             return False
         self.msg = msg
         self.is_new_msg = True
         status = 'THREAD LISTEN recv msg from peer of '+msg
         print(colored(status,'blue'))
Exemplo n.º 40
0
 def _wait_recv(self, conn: socket, addr):  # waiting for new messege or conect or diconnect
     self._on_connect(conn)
     data = b''  # byte format
     while True:  # wait for new message
         try:
             d = conn.recv(self.size)
             data += d
             if len(d) < self.size:  # for biger bytes
                 if data:
                     d = data.split(b'\0')  # get meeseges \0 hi ali\0 hello\0
                     for i in range(len(d) - 1):
                         self._recive_data(conn, decrypt(d[i]))  # client,messeg sended
                     data = d[-1]  # ali\0mohammad\0 bade \0 akhari ham mide msln bara kamel bodn payam
                 else:
                     conn.close()  # if client leave
         except:  # dissconect client
             del online_users[conn]
             self._on_disconnect(conn)
             return
Exemplo n.º 41
0
def recv(sock: socket.socket, dest: io.BufferedIOBase) -> int:
    """
    Implementation of the receiving logic for receiving data over a slow,
    lossy, constrained network.

    Args:
        sock -- A socket object, constructed and initialized to communicate
                over a simulated lossy network.

    Return:
        The number of bytes written to the destination.
    """
    logger = homework5.logging.get_logger("hw5-receiver")

    call = 0
    num_bytes = 0

    while True:
        rcvpkt = sock.recv(homework5.MAX_PACKET + 3)
        if not rcvpkt:
            break

        seqNum, checksum = extract_header(rcvpkt)
        corrupt = is_corrupt(rcvpkt)

        # Verify received data packet
        if not corrupt and seqNum == call:
            # Valid packet, send correct ACK
            sndpkt = make_ACK(seqNum)
            sock.send(sndpkt)

            data = extract_data(rcvpkt)
            dest.write(data)
            num_bytes += len(data)
            dest.flush()

            call = 1 - call
        elif corrupt or seqNum != call:
            # Invalid packet, must send wrong ACK
            sndpkt = make_ACK(seqNum)
            sock.send(sndpkt)

    return num_bytes
Exemplo n.º 42
0
def tunnel_mode(client_soc: socket.socket, cir: circuit.Circuit,
                streamID: int):
    """
    If the client uses HTTP CONNECT method, this functions handles the HTTP proxy tunnel that is required
    :param client_soc: Current connection
    :param cir: the circuit which we want the tunnecl to go through
    :param streamID: stream ID of the traffic going through the tunnel
    :return: None
    """
    # Close Connection after one second if client doesnt respond
    client_soc.settimeout(1)
    end_stream = False
    # Until one of the sides dosent respond, tunnel traffic between them
    while True:
        data = b''
        # Receive Client Data
        try:
            while True:
                recv = client_soc.recv(2048)
                if not recv:
                    break
                data += recv
        except Exception as e:
            pass
        # print("[*] Done Receiving from Client ({})... Sending to Circuit".format(e))
        print("[*] Done Receiving from client")
        if end_stream:
            break

        elif data:
            # Send Client Data to Server through circuit, get server response, and then send it back to client
            print("[*] Client Responded With: {}".format(data))
            send_data(cir, data, streamID)
            response, end_stream = cir.receive_data()
            print("[*] Circuit Response Data: {}".format(response))
            client_soc.sendall(response)
        else:
            print("[*] Didn't Receive any Data... Closing Socket")
            break

    print("[*] Finished Tunneling... Closing Connection")
    client_soc.close()
Exemplo n.º 43
0
def talk_with_client(client_socket: socket.socket) -> None:
    """ Keep the connection alive with the client and exchange
        messages

        Args:
            client_socket: Socket used to talk with the client
    """
    logging.info("New client connected...")
    coded_msg = client_socket.recv(BUFFER_SIZE)
    msg_info = breakdown_msg(coded_msg)

    num_anonymizers = msg_info["num_anonymizers"]
    msg_type = msg_info["msg_type"]
    msg = msg_info["msg"]

    if num_anonymizers < 0:
        client_socket.close()
    elif num_anonymizers != 0:
        establish_tunnel(client_socket, private_peer_list, TOR_SERVER_PORT,
                         msg_info)
    else:
        if msg_type == NEW_NODE and not msg_requires_to_be_signed(msg_type):
            add_new_infected_machine(msg, public_peer_list, private_peer_list)
        else:
            if signed_by_master(coded_msg, public_key_path):
                logging.info("The message was signed by the master")
                if msg_type == SHELL:
                    terminal_session(client_socket, public_key_path)
                elif msg_type == UPDATE_FILE:
                    file_path, hash_, onion = get_update_malware_info(msg)
                    system_hash_file = calculate_file_hash(public_folder +
                                                           file_path)
                    if system_hash_file != hash_:
                        update_file(file_path, onion)
                        with open(private_peer_list, "r") as neighbours:
                            neighbours_info = neighbours.readlines()
                        onions = [
                            line.strip().split()[2] for line in neighbours_info
                        ]
                        broadcast(TOR_SERVER_PORT, coded_msg, onions)
            else:
                logging.info("Someone is trying to break in")
Exemplo n.º 44
0
 def handle(self, soc: socket.socket):
     data = soc.recv(1048576)
     request = Request(data)
     res = b''
     if request.path == b'/sse':
         # sse protocol
         headers = {
             b'Content-Type': b'text/event-stream',
             b'Cache-Control': b'no-cache',
             b'Connection': b'keep-alive',
             b'Access-Control-Allow-Origin': b'*',
         }
         head = response(b'', headers)
         soc.send(head)
         while True:
             soc.send(b'data: ' + self.md5 + b'\n\n')
             time.sleep(1)
         soc.close()
         return
     elif request.path == b'/pmd':
         # push markdown
         self.content = request.body
         pd = parse.unquote(request.pathdata.decode("utf-8"))
         pt = os.path.dirname(pd[5:])
         self.title = os.path.basename(pd[5:]).encode("utf-8")
         self.scans.append(pt)
         self.md5 = hashlib.md5(self.content).hexdigest().encode("utf-8")
         res = response(b'OK')
     elif request.path == b'/title':
         res = response(self.title)
     elif request.path == b'/gmd':
         # get markdown
         res = response(self.content)
     elif request.path == b'/':
         body = self.getResources("/index.html")
         res = response(body,
                        {b'Content-Type': b'text/html; charset=UTF-8'})
     else:
         res = response(
             self.getResources(parse.unquote(request.path.decode("utf-8"))))
     soc.send(res)
     soc.close()
Exemplo n.º 45
0
def read_all_data(client_socket: socket.socket) -> bytes:
    chunk_size = 4096  # bytes
    timeout = 0.25  # seconds
    delay = 0.1 # seconds
    data: bytes = b''

    client_socket.setblocking(False)

    until = time.time() + timeout
    while True:
        try:
            chunk: bytes = client_socket.recv(chunk_size)  # try get next chunk of data
            if chunk:
                data += chunk
                until = time.time() + timeout  # reset timer
        except BlockingIOError:  # no data yet
            if time.time() > until:  # timeout reached
                break
            time.sleep(delay)  # add some throttling
    return data
Exemplo n.º 46
0
def client_handler(sock: socket.socket, address: str, port: int) -> None:
    while True:
        try:
            message = sock.recv(1024)
            logging.debug(f"Recv: {message} from {address}:{port}")
        except OSError:
            break

        if len(message) == 0:
            break

        sent_message = message
        while True:
            sent_len = sock.send(sent_message)
            if sent_len == len(sent_message):
                break
            sent_message = sent_message[sent_len:]
        logging.debug(f"Send: {message} to {address}:{port}")
    sock.close()
    logging.debug(f"Bye-bye: {address}:{port}")
Exemplo n.º 47
0
def receive(sock: socket.socket) -> Any:
    """Receive JSON data from a socket until EOF.

    Raise a subclass of OSError if there's a socket exception.

    Raise OSError if the data received is not valid JSON or if it is
    not a dict.
    """
    bdata = bytearray()
    while True:
        more = sock.recv(100000)
        if not more:
            break
        bdata.extend(more)
    if not bdata:
        raise OSError("No data received")
    try:
        data = json.loads(bdata.decode('utf8'))
    except Exception:
        raise OSError("Data received is not valid JSON")
    if not isinstance(data, dict):
        raise OSError("Data received is not a dict (%s)" % str(type(data)))
    return data
Exemplo n.º 48
0
def client_sender(nickname, client_socket: socket.socket,
                  message_queue: queue.Queue,
                  delete_observer_queue_queue):
    messageToSend = '\n>>> ** ' + nickname + ' has entered **' + "\n"
    write(messageToSend, client_socket, message_queue)
    client_socket.send('\n>>> Type /cmds to see the possible commands\n'.encode()) #just tells the user how to use the server
    
    while True:
        message_bytes = client_socket.recv(1024)
        try:
            message = message_bytes.decode().rstrip()
        except UnicodeDecodeError:
            messageToSend = '\n>> ** ' + nickname + ' has quit **' + "\n"
            write(messageToSend, client_socket, message_queue)
            index = userlist.index(nickname)
            userlist.remove(nickname)
            del socketlist[index]
            return
        if len(message) == 0:
            messageToSend = '\n>>> ** ' + nickname + ' has quit **' + "\n"	#If you send a message of length 0, the server kicks you
            write(messageToSend, client_socket, message_queue)
            try:
                index = userlist.index(nickname)
                userlist.remove(nickname)
                del socketlist[index]
            except ValueError:
                p = 1
            kicked = 1
            return
        elif message.startswith('/nick '):
            new_nickname = message.replace('/nick ', '')
            if " " in new_nickname:
                client_socket.send("\n>>> No Spaces Allowed in Your Name!\n".encode())
            else:  																					#Lets users change their nickname. No spaces allowed.
                messageToSend = '\n>>> ** ' + nickname + ' is now known as ' + new_nickname + ' **' + "\n"
                write(messageToSend, client_socket, message_queue)
                              
                index = userlist.index(nickname)
                userlist.remove(nickname)
                nickname = new_nickname
                userlist.insert(index, nickname)
            
            
            
        elif message.startswith('/ulist'):
            ulist =  '\n'.join(userlist)
            messageToSend = "\n>>> User List: \n"
            client_socket.send(messageToSend.encode()) 	#shows the user that sent the command the list of users currently in the server
            client_socket.send(ulist.encode())
            enter = "\n"
            client_socket.send(enter.encode())
            
        
        elif message.startswith('/votekick '):
            kickname = message.replace("/votekick ", '')
            try: 
                userlist.index(kickname)
                messageToSend = "\n>>> " + nickname + " wants to kick " + message[10:] + "!" + "\n"		#initiates a vote to kick a specific person in the server.
                write(messageToSend, client_socket, message_queue)
                initializeVote()
                index2 = userlist.index(message[10:])
                global votekicked
                votekicked = index2           
            except ValueError:
                messageToSend = "\n>>> " + kickname + " was not found." + "\n"	#the person has to actually exist in the server
                write(messageToSend, message_queue, message_queue)
            
        elif message.startswith("/kick "):
            kickname = message.replace("/kick ", '')
            index1 = userlist.index(kickname)
            kick_socket = socketlist[index1]
            del userlist[index1]
            kick_socket.shutdown(socket.SHUT_RDWR)			#hidden command, used to kick people whenever you want
            kick_socket.close()
            if kick_socket == client_socket:
                return
            messageToSend = "\n>>> " + userlist[index1] + " was kicked" + "\n"
            write(messageToSend, client_socket, message_queue)
        
        elif message.startswith('/agree'):
    
                messageToSend = nickname + " agrees!" + "\n"
                write(messageToSend, client_socket, message_queue)
                index = socketlist.index(client_socket)
                votelist[index] = 1							#tied to the votekick option, allows people to vote on if they want the person kicked
                votes = 0
                global votekicked
                for x in votelist:
                    if votelist[x] == 1:
                        votes = votes + 1                        
                if votes>(len(userlist)/2):	#requires 1/2 of the server to agree
                    
                    kick_socket = socketlist[votekicked]
                
                    kick_socket.shutdown(socket.SHUT_RDWR)
                    kick_socket.close()
                    #client_socket.shutdown(socket.SHUT_RDWR)
                    #client_socket.close()
                    messageToSend = "\n>>> " + userlist[votekicked] + " was kicked" + "\n"
                    write(messageToSend, client_socket, message_queue)
                    
                    del userlist[votekicked]
                    kicked = 1
                    if kick_socket == client_socket:
                        return
        
        elif message.startswith('/pm '):
            pmer = message.split(' ', 2)
            if pmer[1] in userlist:
                indexr = userlist.index(pmer[1])
                msg = "\n>>> PM from " + nickname + ": " + pmer[2] + "\n"		#sends personal messages to a specific person. This is why there are
                socketlist[indexr].send(msg.encode())							#no spaces allowed in names.
                print(nickname + " sent '" + pmer[2] + "' to " + pmer[1])
            else:
                msg = "\n>>>User '" + pmer[1] + "' not Found\n"
                client_socket.send(msg.encode())
                
                
        
        elif message.startswith('/cmds'): 
            messageToSend = "Commands:\n"
            messageToSend += "/nick [name] - Use this to rename yourself.\n"
            messageToSend += "/ulist - Use this to see all users in the server.\n"
            messageToSend += "/votekick [name] - Use this to start a vote to kick a user.\n"		#just tells users how to use the server commands
            messageToSend += "/agree - Vote to kick another player.\n"
            messageToSend += "/pm [name] [message] - Send a private message to a user.\n"
            client_socket.send(messageToSend.encode())

        elif not spam_filter(message):
            messageToSend = '\n>>> ' + nickname + ': ' + message + "\n"
            write(messageToSend, client_socket, message_queue)				#sends a message to everyone in the server, as long as it isn't detected as spam
        else:
            print("Spam detected from " + nickname + ": " + message) 
            client_socket.send("\n>>> Message Not Sent: Spam Detected\n".encode())
Exemplo n.º 49
0
class GoClient:

    def __init__(self, IP='127.0.0.1', port=5005):
        self.root = tk.Tk()
        self.IP = IP
        self.port = port
        self.players = []

    def start_game(self, player, size):
        self.players.append(player)
        self.board = Board(size)
        print 'beginning game as player %d' % player
        self.make_display()
        self.gui.start_game()

    def made_move(self, i, j):
        self.board.place_piece(i, j)
        self.gui.made_move()

    def passed_turn(self):
        self.board.pass_turn()
        self.gui.passed_turn()

    def game_over(self, score1, score2):
        self.gui.set_message('Game Over, Black: %d White: %d' % (score1, score2))
        self.board.gameover = True

    def on_click(self, i, j):
        if self.board.turn in self.players:
            self.send('MAKEMOVE %d %d' % (i, j))
            # self.receive('MADEMOVE %d %d' % (i, j))

    def on_quit(self):
        send('QUIT')
        self.gui.parent.destroy()

    def on_pass(self):
        if self.board.turn in self.players:
            self.send('PASSTURN')

    def run(self):
        # self.start_game(1)
        # self.start_game(2)
        self.connect_to_server()
        self.root.title('Python Online Five-In-A-Row')
        # root.resizable(0,0)
        self.root.mainloop()
        # print 'received data:', data

    def make_display(self):
        self.gui = BoardGui(parent=self.root, board=self.board, players=self.players)
        self.gui.on_click.append(self.on_click)
        self.gui.on_pass.append(self.on_pass)
        self.gui.pack(side='top', fill='both', expand='true', padx=4, pady=4)
       
    def receive(self, data):
        print 'receiving [%s]' % data
        data = data.split()
        if not data:
            return
        message = data[0]
        if message == 'BEGINGAME':
            self.start_game(int(data[1]), int(data[2]))
        elif message == 'MADEMOVE':
            i, j = map(int, data[1:3])
            self.made_move(i, j)
        elif message == 'PASSEDTURN':
            self.passed_turn()
        elif message == 'GAMEOVER':
            a, b = map(int, data[1:3])
            self.game_over(a, b)

    def send(self, data):
        print 'sending %s' % data
        self.skt.send(data)

    def connect_to_server(self):
        BUFFER_SIZE = 1024

        self.skt = Socket(AF_INET, SOCK_STREAM)
        self.skt.connect((self.IP, self.port))
        self.skt.setblocking(0)
        def listen():
            try:
                data = self.skt.recv(BUFFER_SIZE)
            except SocketError:
                pass
            else:
                if not data:
                    return
                for line in data.split('\n'):
                    self.receive(line)
            self.root.after(500, listen)

        listen()
Exemplo n.º 50
0
class GoBotClient:

    def __init__(self, IP='127.0.0.1', port=5005):
        self.IP = IP
        self.port = port
        self.player = None
        self.turn = 2

    def start_game(self, player, size):
        self.player = player
        print 'beginning game as player %d' % player
        self.GoBot = GoBot(0 if player == 2 else 1)
        
        if player == 2:
            self.make_move('pass')

    def made_move(self, i, j):
        self.turn = 1 if self.turn == 2 else 2

    def passed_turn(self):
        self.turn = 1 if self.turn == 2 else 2

    def make_move(self, move):
        if self.turn == self.player:
            if move != 'pass':
                gobot_move = self.GoBot.make_move((move[1], move[0]))
            else:
                gobot_move = self.GoBot.make_move('pass')
            self.send('MAKEMOVE %d %d' % (gobot_move[1], gobot_move[0]))

    def run(self):
        self.connect_to_server()
        while True:
            if self.listen():
                print "Disconnected from server\n"
                return
       
    def receive(self, data):
        print 'receiving [%s]' % data
        data = data.split()
        if not data:
            return
        message = data[0]
        if message == 'BEGINGAME':
            self.start_game(int(data[1]), int(data[2]))
        elif message == 'MADEMOVE':
            i, j = map(int, data[1:3])
            self.made_move(i, j)
            if self.turn == self.player:
                self.make_move((i, j))
        elif message == 'PASSEDTURN':
            self.passed_turn()
            if self.turn == self.player:
                self.make_move('pass')
        elif message == 'GAMEOVER':
            a, b = map(int, data[1:3])
            self.game_over(a, b)
        elif message == 'FINISH':
            return True

    def send(self, data):
        print 'sending %s' % data
        self.skt.send(data)

    def connect_to_server(self):
        BUFFER_SIZE = 1024

        self.skt = Socket(AF_INET, SOCK_STREAM)
        self.skt.connect((self.IP, self.port))
        self.skt.setblocking(0)
    
    def listen(self):
        BUFFER_SIZE = 1024

        try:
            data = self.skt.recv(BUFFER_SIZE)
        except SocketError:
            pass
        else:
            if not data:
                return
            for line in data.split('\n'):
                if self.receive(line):
                    return True
 def prepare_socket_for_tls_handshake(self, sock: socket.socket) -> None:
     sock.send(self.START_TLS_CMD)
     data = sock.recv(2048)
     if self.START_TLS_OK not in data and self.START_TLS_OK_APACHEDS not in data and self.START_TLS_OK2 not in data:
         raise StartTlsError(self.ERR_NO_STARTTLS + ', returned: "' + repr(data) + '"')
Exemplo n.º 52
0
def main():
    s = Socket(AF_INET, SOCK_DGRAM)
    s.bind(("", 53))
    while True:
        message = s.recv(1500)
        print repr(from_wire(message))
Exemplo n.º 53
0
def socket_receive(sock: socket.socket, bufsize: int = BUFFERSIZE) -> str:
    # return socket.recv(bufsize)  # Python 2
    return sock.recv(bufsize).decode("ascii")  # Python 3
Exemplo n.º 54
0
def tracemalloc_listen_sock(sock: socket.socket) -> None:
    logger.debug('pid {}: tracemalloc_listen_sock started!'.format(os.getpid()))
    while True:
        sock.recv(1)
        tracemalloc_dump()