Example #1
0
    async def _run_async_server(self, raw_socket):
        socket = anyio._get_asynclib().Socket(raw_socket)

        # TODO: resource usage warning
        async with anyio._networking.SocketStreamServer(socket, None, False, False) as tcp_server, \
                                                                anyio.create_task_group() as task_group:
            async for socket in tcp_server.accept_connections():
                await task_group.spawn(ConnectionHandler(self), socket)
Example #2
0
    async def _run_async_server(self, raw_socket):
        socket = anyio._get_asynclib().Socket(raw_socket)

        # TODO: resource usage warning
        async with async_exit_stack.AsyncExitStack() as stack:
            tcp_server = await stack.enter_async_context(
                anyio._networking.SocketStreamServer(socket, None, False, False))
            task_group = await stack.enter_async_context(anyio.create_task_group())

            services_dict = {}
            for key, value in self.services.items():
                services_dict[key] = await stack.enter_async_context(value)

            async for socket in tcp_server.accept_connections():
                await task_group.spawn(ConnectionHandler(services_dict), socket)
Example #3
0
    class ValueEvent(anyio._get_asynclib().Event):
        def __init__(self,
                     default: typing.Optional[typing.Any] = None) -> None:
            self._value: typing.Any = default

            super().__init__()

        async def set(self, value: typing.Any) -> None:
            self._value = value
            await super().set()

        def clear(self) -> None:
            self._value = None
            super().clear()

        @property
        async def value(self) -> typing.Any:
            await self.wait()

            return self._value
Example #4
0
async def connect_tcp_socksified(
        address: IPAddressType,
        port: int,
        chains,
        *,
        ssl_context: Optional[SSLContext] = None,
        autostart_tls: bool = False,
        bind_host: Optional[IPAddressType] = None,
        bind_port: Optional[int] = None,
        tls_standard_compatible: bool = True) -> SocketStream:
    """
    Connect to a host using the TCP protocol.

    :param address: the IP address or host name to connect to
    :param port: port on the target host to connect to
    :param ssl_context: default SSL context to use for TLS handshakes
    :param autostart_tls: ``True`` to do a TLS handshake on connect
    :param bind_host: the interface address or name to bind the socket to before connecting
    :param bind_port: the port to bind the socket to before connecting
    :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake before closing
        the stream and requires that the server does this as well. Otherwise,
        :exc:`~ssl.SSLEOFError` may be raised during reads from the stream.
        Some protocols, such as HTTP, require this option to be ``False``.
        See :meth:`~ssl.SSLContext.wrap_socket` for details.
    :return: a socket stream object

    """
    interface, family = None, 0  # type: Optional[str], int
    if bind_host:
        interface, family, _v6only = await _networking.get_bind_address(
            bind_host)

    socks_host, socks_port = chains[0]['host'], chains[0]['port']
    socks_user, socks_pass = chains[0].get('user', None), chains[0].get(
        'password', None)

    if socks_user and socks_pass:
        method = socks5.Socks5.USERPASS
    else:
        method = socks5.Socks5.NOAUTH

    transfer_stream = await trio.open_tcp_stream(socks_host, socks_port)
    if await socks5.Socks5Client.process_hello(socks5.Socks5Client,
                                               transfer_stream,
                                               method=method):
        if method == socks5.Socks5.USERPASS:
            if await socks5.Socks5Client.process_auth(socks5.Socks5Client,
                                                      transfer_stream,
                                                      socks_user, socks_pass):
                if await socks5.Socks5Client.process_establish_transfer(
                        socks5.Socks5Client, transfer_stream, str(address),
                        port):
                    print(f"CONNECTION ESTABLISHED !!!")
                    sock = transfer_stream.socket._sock

                    # getaddrinfo() will raise an exception if name resolution fails
                    # address = str(address)
                    # addrlist = await run_in_thread(socket.getaddrinfo, address, port, family, socket.SOCK_STREAM)
                    # family, type_, proto, _cn, sa = addrlist[0]
                    # raw_socket = socket.socket(family, type_, proto)
                    # sock = _get_asynclib().Socket(raw_socket)
                    sock = _get_asynclib().Socket(sock)
                    try:
                        # sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                        # if interface is not None and bind_port is not None:
                        #     await sock.bind((interface, bind_port))
                        #
                        # await sock.connect(sa)
                        stream = _networking.SocketStream(
                            sock, ssl_context, address,
                            tls_standard_compatible)
                        print(f"stream = {stream}, ast_tls = {autostart_tls}")
                        print(dir(stream))
                        print(stream.start_tls)

                        if autostart_tls:
                            await stream.start_tls()

                        return stream
                    except BaseException as e:
                        print(f"EXCEPTION! {e} {traceback.format_exc()}")
                        await sock.close()
                        raise
        else:
            if await socks5.Socks5Client.process_establish_transfer(
                    socks5.Socks5Client, transfer_stream, str(address), port):
                print(f"CONNECTION ESTABLISHED !!!")
                sock = transfer_stream.socket._sock

                # getaddrinfo() will raise an exception if name resolution fails
                # address = str(address)
                # addrlist = await run_in_thread(socket.getaddrinfo, address, port, family, socket.SOCK_STREAM)
                # family, type_, proto, _cn, sa = addrlist[0]
                # raw_socket = socket.socket(family, type_, proto)
                # sock = _get_asynclib().Socket(raw_socket)
                sock = _get_asynclib().Socket(sock)
                try:
                    # sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                    # if interface is not None and bind_port is not None:
                    #     await sock.bind((interface, bind_port))
                    #
                    # await sock.connect(sa)
                    stream = _networking.SocketStream(sock, ssl_context,
                                                      address,
                                                      tls_standard_compatible)
                    print(f"stream = {stream}, ast_tls = {autostart_tls}")
                    print(dir(stream))
                    print(stream.start_tls)

                    if autostart_tls:
                        await stream.start_tls()

                    return stream
                except BaseException as e:
                    print(f"EXCEPTION! {e} {traceback.format_exc()}")
                    await sock.close()
                    raise