Exemple #1
0
    def new_client(self, transport: asyncio.Transport) -> Client:
        """Create a new client, add it to the list, and assign it a player ID.

        Args:
            transport (asyncio.Transport): Transport to send data across

        Raises:
            ClientError: The server is full

        Returns:
            Client: The newly constructed client
        """
        try:
            user_id = heappop(self.cur_id)
        except IndexError:
            transport.write(b'BD#This server is full.#%')
            raise ClientError

        peername = transport.get_extra_info('peername')[0]

        c = self.Client(self.server, transport, user_id,
                        database.ipid(peername))
        self.clients.add(c)
        temp_ipid = c.ipid
        for client in self.server.client_manager.clients:
            if client.ipid == temp_ipid:
                client.clientscon += 1
        return c
def send_file_response(path: str, http_version: str,
                       transport: asyncio.Transport) -> None:
    """
    Function used to send encoded file HTTP response on transport.

    Args:
        path: Path of the file requested by client.
        http_version: HTTP version.
        transport: The async object representing the connection with client.

    """

    file_type = path.split('.')[-1].upper()
    ok_response_line = ResponseLineHeader(http_version, HTTPStatus.OK, HTTPStatus.OK.phrase)
    response_headers = HTTPResponseHeaders(ok_response_line, list())
    try:
        with open(path, 'rb' if file_type in IMAGE_FILES else 'r') as f:
            body = f.read()
    except FileNotFoundError:
        print(f'Invalid client GET Request - File not found: {path.split("/")[-1]}')
        response_headers.response_line_header = ResponseLineHeader(
            http_version, HTTPStatus.NOT_FOUND, HTTPStatus.NOT_FOUND.phrase)
        body = INVALID_RESPONSE_HTML
        file_type = 'HTML'
    if file_type not in IMAGE_FILES:
        response_headers.headers.append(HTTPHeader('Charset', 'utf-8'))
    response_headers.headers.append(HTTPHeader('Content-Type',
                                               str(CONTENT_TYPES[file_type])))
    response_headers.headers.append(HTTPHeader('Content-Length', str(len(body))))
    response_headers.headers.append(HTTPHeader('Connection', 'Keep-Alive'))
    response = _get_response(file_type, response_headers, body)
    transport.write(response)
Exemple #3
0
    def connection_made(self, transport: asyncio.Transport):
        """Called when a connection is made.

        To receive data, wait for data_received() calls.
        When the connection is closed, connection_lost() is called.
        :param transport: the transport representing the pipe connection.
        """

        self.transport: asyncio.Transport = transport

        # we get additional info on the transport
        self.address = transport.get_extra_info('peername')
        self.socket = transport.get_extra_info('socket')

        # we set the TCP_NODELAY flag
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 0)

        # ip and port on which the server will listed
        self.listen_ip, self.listen_port = self.socket.getsockname()

        # we initialize the log
        if not self.log:
            logging.basicConfig(
                level=self._log_level,
                format='%(name)s: %(message)s',
                stream=self._log_stream,
            )

            self.log = logging.getLogger(
                'ServerProtocol_{}_{}'.format(*self.address)
            )

        self.log.debug('AsyncUOProtocol connection accepted')
Exemple #4
0
 def connection_made(self, transport: asyncio.Transport):
     self._transport = transport
     self.peername = self._transport.get_extra_info("peername")
     transport.write(self.local._connect_buffer)
     self.ready = True
     CONNECTION_MADE_COUNT.inc()
     ACTIVE_CONNECTION_COUNT.inc()
Exemple #5
0
    def new_client(self, transport: asyncio.Transport) -> Client:
        """Create a new client, add it to the list, and assign it a player ID.

        Args:
            transport (asyncio.Transport): Transport to send data across

        Raises:
            ClientError: The server is full

        Returns:
            Client: The newly constructed client
        """
        try:
            user_id = heappop(self.cur_id)
        except IndexError:
            transport.write(b'BD#This server is full.#%')
            raise ClientError

        peername = transport.get_extra_info('peername')[0]

        # hash IP into previous system's IPID system to maintain old banlist
        if 'server_number' in self.server.config:
            x = peername + str(self.server.config['server_number'])
            hash_object = hashlib.sha256(x.encode('utf-8'))
            peername = hash_object.hexdigest()[:12]

        c = self.Client(self.server, transport, user_id,
                        database.ipid(peername))
        self.clients.add(c)
        temp_ipid = c.ipid
        for client in self.server.client_manager.clients:
            if client.ipid == temp_ipid:
                client.clientscon += 1
        return c
Exemple #6
0
async def request_blob(loop: asyncio.BaseEventLoop, blob: 'AbstractBlob', address: str, tcp_port: int,
                       peer_connect_timeout: float, blob_download_timeout: float,
                       connected_transport: asyncio.Transport = None, connection_id: int = 0,
                       connection_manager: typing.Optional['ConnectionManager'] = None)\
        -> typing.Tuple[int, typing.Optional[asyncio.Transport]]:
    """
    Returns [<downloaded blob>, <keep connection>]
    """

    protocol = BlobExchangeClientProtocol(
        loop, blob_download_timeout, connection_manager
    )
    if connected_transport and not connected_transport.is_closing():
        connected_transport.set_protocol(protocol)
        protocol.transport = connected_transport
        log.debug("reusing connection for %s:%d", address, tcp_port)
    else:
        connected_transport = None
    try:
        if not connected_transport:
            await asyncio.wait_for(loop.create_connection(lambda: protocol, address, tcp_port),
                                   peer_connect_timeout, loop=loop)
        if blob.get_is_verified() or not blob.is_writeable():
            # file exists but not verified means someone is writing right now, give it time, come back later
            return 0, connected_transport
        return await protocol.download_blob(blob)
    except (asyncio.TimeoutError, ConnectionRefusedError, ConnectionAbortedError, OSError):
        return 0, None
Exemple #7
0
    def __call__(self, transport: asyncio.Transport) -> None:
        # send command
        cmd = str(self.id) + ' ' + self.command + '\n'
        transport.write(bytes(cmd, 'utf-8'))

        # store current time and set as sent
        self.time = time.time()
        self.sent = True
Exemple #8
0
    def connection_made(self, transport: asyncio.Transport):
        """
        Called when a connection is made, and is used to store the connection data.
        """
        self.ip, self.client_port = transport.get_extra_info("peername")
        self._transport = transport

        self.logger.debug("Recieved connection from {}:{}".format(*transport.get_extra_info("peername")))
Exemple #9
0
    async def _start_tls_connection(
        self,
        underlying_transport: asyncio.Transport,
        req: "ClientRequest",
        timeout: "ClientTimeout",
        client_error: Type[Exception] = ClientConnectorError,
    ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
        """Wrap the raw TCP transport with TLS."""
        tls_proto = self._factory()  # Create a brand new proto for TLS

        # Safety of the `cast()` call here is based on the fact that
        # internally `_get_ssl_context()` only returns `None` when
        # `req.is_ssl()` evaluates to `False` which is never gonna happen
        # in this code path. Of course, it's rather fragile
        # maintainability-wise but this is to be solved separately.
        sslcontext = cast(ssl.SSLContext, self._get_ssl_context(req))

        try:
            async with ceil_timeout(
                timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
            ):
                try:
                    tls_transport = await self._loop.start_tls(
                        underlying_transport,
                        tls_proto,
                        sslcontext,
                        server_hostname=req.host,
                        ssl_handshake_timeout=timeout.total,
                    )
                except BaseException:
                    # We need to close the underlying transport since
                    # `start_tls()` probably failed before it had a
                    # chance to do this:
                    underlying_transport.close()
                    raise
        except cert_errors as exc:
            raise ClientConnectorCertificateError(req.connection_key, exc) from exc
        except ssl_errors as exc:
            raise ClientConnectorSSLError(req.connection_key, exc) from exc
        except OSError as exc:
            raise client_error(req.connection_key, exc) from exc
        except TypeError as type_err:
            # Example cause looks like this:
            # TypeError: transport <asyncio.sslproto._SSLProtocolTransport
            # object at 0x7f760615e460> is not supported by start_tls()

            raise ClientConnectionError(
                "Cannot initialize a TLS-in-TLS connection to host "
                f"{req.host!s}:{req.port:d} through an underlying connection "
                f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} "
                f"[{type_err!s}]"
            ) from type_err
        else:
            tls_proto.connection_made(
                tls_transport
            )  # Kick the state machine of the new TLS protocol

        return tls_transport, tls_proto
Exemple #10
0
 def check(self, transport: asyncio.Transport) -> None:
     if not transport.get_extra_info('sslcontext'):
         return
     sslobj = transport.get_extra_info('ssl_object')
     cert = sslobj.getpeercert(binary_form=True)
     got = self._hashfunc(cert).digest()
     if got != self._fingerprint:
         host, port, *_ = transport.get_extra_info('peername')
         raise ServerFingerprintMismatch(self._fingerprint, got, host, port)
Exemple #11
0
def shutdown(_loop: Loop, _transport: asyncio.Transport, _server: Server,
             executors: List[Executor]):
    print('shutting down sockets, processes, threads and abort tasks')
    for task in asyncio.Task.all_tasks():
        task.cancel()
    for executor in executors:
        executor.shutdown()
    _transport.close()
    _server.close()
    _loop.stop()
Exemple #12
0
 def check(self, transport: asyncio.Transport) -> None:
     if not transport.get_extra_info('sslcontext'):
         return
     sslobj = transport.get_extra_info('ssl_object')
     cert = sslobj.getpeercert(binary_form=True)
     got = self._hashfunc(cert).digest()
     if got != self._fingerprint:
         host, port, *_ = transport.get_extra_info('peername')
         raise ServerFingerprintMismatch(self._fingerprint,
                                         got, host, port)
 def connection_made(self, transport: asyncio.Transport):
     self.transport = transport
     # Add to opened connections
     Server.serviceConnections.add(transport)
     # Send buffered data if any
     if len(self.redirectorServer.buffer) > 0:
         transport.write(self.redirectorServer.buffer)
     # No more buffer is needed
     self.redirectorServer.buffer = None
     self.redirectorServer = None
Exemple #14
0
 def __init__(self, network: NetRom, local_call: AX25Call,
              remote_call: AX25Call, circuit_id: int, origin_node: AX25Call,
              origin_user: AX25Call):
     Transport.__init__(self,
                        extra={"peername": (str(remote_call), circuit_id)})
     self.network = network
     self.remote_call = remote_call
     self.local_call = local_call
     self.circuit_id = circuit_id
     self.origin_node = origin_node
     self.origin_user = origin_user
Exemple #15
0
def get_local_addr(transport: asyncio.Transport) -> Optional[Tuple[str, int]]:
    socket_info = transport.get_extra_info("socket")
    if socket_info is not None:
        info = socket_info.getsockname()

        return (str(info[0]),
                int(info[1])) if isinstance(info, tuple) else None
    info = transport.get_extra_info("sockname")
    if info is not None and isinstance(info, (list, tuple)) and len(info) == 2:
        return (str(info[0]), int(info[1]))
    return None
Exemple #16
0
    def connection_made(self, transport: asyncio.Transport):
        """Receives a connection and calls the connection callback."""

        if self.max_connections is None or (len(self.transports) <
                                            self.max_connections):
            self.transports.append(transport)
        else:
            transport.write("Maximum number of connections reached.")
            transport.close()

        if self.connection_callback:
            self.connection_callback(transport)
Exemple #17
0
    def connection_made(self, transport: asyncio.Transport):
        self.transport = transport
        self.client_cert = transport.get_extra_info("peercert")

        ssl_context = transport.get_extra_info("ssl_object")
        if ssl.HAS_ALPN:
            agreed_protocol = ssl_context.selected_alpn_protocol()
        else:
            agreed_protocol = ssl_context.selected_npn_protocol()

        if agreed_protocol is None:
            error("Connection error, client does not support HTTP/2")
            transport.close()
        else:
            self.conn.initiate_connection()
Exemple #18
0
    def connection_made(self, transport: asyncio.Transport):
        """
        Called upon a connection being made.
        :param transport: The transport created.
        """
        super().connection_made(transport)
        self._transport = transport
        self.ip, self.client_port = transport.get_extra_info("peername")
        self.logger.info("Recieved connection from {}:{}".format(*transport.get_extra_info("peername")))

        # Call our handler.
        res = self._handler.on_connection(self)

        if asyncio.coroutines.iscoroutine(res):
            self._loop.create_task(res)
Exemple #19
0
 def connection_made(self, transport: asyncio.Transport):
     """ Connection has been accepted and established (callback).
     """
     sock = transport.get_extra_info('socket')
     self.transport_ = transport
     self.addr_ = sock.getpeername()
     LOG.info("Incoming from %s", self.addr_)
Exemple #20
0
def get_remote_addr(transport: asyncio.Transport) -> Optional[Tuple[str, int]]:
    socket_info = transport.get_extra_info("socket")
    if socket_info is not None:
        try:
            info = socket_info.getpeername()
            return (str(info[0]),
                    int(info[1])) if isinstance(info, tuple) else None
        except OSError:
            # This case appears to inconsistently occur with uvloop
            # bound to a unix domain socket.
            return None

    info = transport.get_extra_info("peername")
    if info is not None and isinstance(info, (list, tuple)) and len(info) == 2:
        return (str(info[0]), int(info[1]))
    return None
Exemple #21
0
 def connection_made(self, transport: asyncio.Transport):
     self.remote_address = transport.get_extra_info("peername")
     logger.debug(f"Connection from {self.remote_address}")
     self.transport = transport
     if self.banner:
         self.transport.write(self.banner + b"\r\n")
     self.transport.write(b"Login: ")
Exemple #22
0
 def connection_made(self, transport: asyncio.Transport):
     addr = transport.get_extra_info('peername')
     self.peer_address, self.peer_port = addr[0], addr[1]
     self.transport = transport
     if self.connection_manager:
         self.connection_manager.connection_made(f"{self.peer_address}:{self.peer_port}")
     log.debug("connection made to %s:%i", self.peer_address, self.peer_port)
    def connection_made(self, transport: asyncio.Transport) -> None:
        self.connection_open = True
        self.peername = transport.get_extra_info('peername')
        self.socket = transport.get_extra_info('socket')
        # ssl_socket = transport.get_extra_info('ssl_object')
        # negotiated_protocol = ssl_socket.selected_alpn_protocol()
        # if negotiated_protocol is None:
        #     negotiated_protocol = ssl_socket.selected_npn_protocol()
        # if negotiated_protocol != "h2":
        #     raise RuntimeError("The server does not support HTTP/2")
        self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.transport = transport

        self.h2conn.initiate_connection()
        self.h2conn.update_settings(self._settings)
        self.write_all()
Exemple #24
0
 def connection_made(self, transport: asyncio.Transport) -> None:
     """
     Handle an incoming connection. Do not register the client with a user
     until token data is received.
     """
     self.peername = transport.get_extra_info('peername')
     logging.info(f'Connected client {util.format_addr(self.peername)}')
     self.transport = transport
Exemple #25
0
 def connection_made(self, transport: asyncio.Transport) -> None:
     """Handle incoming connection."""
     self.last_activity = time.time()
     peername = transport.get_extra_info("peername")
     logger.info(
         "%s: Connection made to %s",
         peername,
         self.accessory_driver.accessory.display_name,
     )
     # Ensure we do not write a partial encrypted response
     # as it can cause the controller to send a RST and drop
     # the connection with large responses.
     transport.set_write_buffer_limits(high=HIGH_WRITE_BUFFER_SIZE)
     self.transport = transport
     self.peername = peername
     self.connections[peername] = self
     self.handler = HAPServerHandler(self.accessory_driver, peername)
Exemple #26
0
 def connection_made(self, transport: asyncio.Transport) -> None:
     """Handle incoming connection."""
     peername = transport.get_extra_info("peername")
     logger.info("%s: Connection made", peername)
     self.transport = transport
     self.peername = peername
     self.connections[peername] = self
     self.handler = ServerHandler(self.accessory_driver, peername)
    def connection_made(self, transport: Transport):
        self.session = Session(loop=self.loop)
        self.session.peer = transport.get_extra_info('peername')
        self._reset_timeout()
        super().connection_made(transport)
        self.transport = transport
        log.info('Peer: {}'.format(self.session.peer))

        self._handle_coro_client = self.loop.create_task(self._handle_client())
Exemple #28
0
    def connection_made(self, transport: asyncio.Transport):
        self.transport = transport
        self.player = Player(self.send_data)
        connected = self.game.register_player(self.player)

        if not connected:
            self.transport.write_eof()

        print("client connected!", transport.get_extra_info("peername"))
Exemple #29
0
 def connection_made(self, transport: asyncio.Transport):
     peername = transport.get_extra_info('peername')
     logger.info('Connection from %s', peername)
     self.transport = transport
     self.data_in = Subject()
     self.data_out = AnonymousObserver(self.on_data_out_next,
                                       self.on_data_out_error,
                                       self.on_data_out_completed)
     self.on_connect(self)
Exemple #30
0
 def connection_made(self, transport: asyncio.Transport):
     """Called on new client connections"""
     self._remote_addr = transport.get_extra_info('peername')
     print('[+] client {} connected.'.format(self._remote_addr))
     self._transport = transport
     ChatServerProtocol.clients[transport] = {
         'remote': self._remote_addr,
         'login-name': None
     }
Exemple #31
0
    def connection_made(self, transport: asyncio.Transport):
        """
        When connection has been made

        :param transport:
        :return:
        """
        self.transport = transport
        self.gateway = transport.get_extra_info("peername")
        self.__send_handshake()
Exemple #32
0
def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None:
    sock = transport.get_extra_info('socket')

    if sock is None:
        return

    if sock.family not in (socket.AF_INET, socket.AF_INET6):
        return

    value = bool(value)

    # socket may be closed already, on windows OSError get raised
    with suppress(OSError):
        sock.setsockopt(
            socket.IPPROTO_TCP, socket.TCP_NODELAY, value)
Exemple #33
0
def tcp_cork(transport: asyncio.Transport, value: bool) -> None:
    sock = transport.get_extra_info('socket')

    if CORK is None:
        return

    if sock is None:
        return

    if sock.family not in (socket.AF_INET, socket.AF_INET6):
        return

    value = bool(value)

    with suppress(OSError):
        sock.setsockopt(
            socket.IPPROTO_TCP, CORK, value)
Exemple #34
0
 def tcp_keepalive(transport: asyncio.Transport) -> None:
     sock = transport.get_extra_info('socket')
     if sock is not None:
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)