def get_server(uri):
    listen_uris, _, remote_uri = uri.partition("=")
    listen_uris = listen_uris.split(",")
    if not listen_uris:
        raise ValueError("no server found")
    if remote_uri:
        remote = uri_compile(remote_uri, False)
        via = partial(remote.proto, **remote.kw)
    else:
        via = None
    server_list = []
    for listen_uri in listen_uris:
        listen = uri_compile(listen_uri, True)
        if via:
            listen.kw["via"] = via
        host = listen.kw.pop("host")
        port = listen.kw.pop("port")
        ssl_context = listen.kw.pop("ssl_context", None)
        if listen.scheme in ("ss", "ssudp") and "cipher_cls" not in listen.kw:
            raise argparse.ArgumentTypeError(
                "you need to assign cryto algorithm and password: "******"{listen.scheme}://{host}:{port}")
        if listen.scheme.endswith("udp"):
            server = udp_server(host, port, listen.proto(**listen.kw))
        else:
            server = tcp_server(
                host,
                port,
                ProtoFactory(listen.proto, **listen.kw),
                backlog=1024,
                ssl=ssl_context,
            )
        server_list.append((server, (host, port), listen.scheme))
    return server_list
Example #2
0
def get_server(uri):
    listen_uris, _, remote_uri = uri.partition('=')
    listen_uris = listen_uris.split(',')
    if not listen_uris:
        raise ValueError('no server found')
    if remote_uri:
        remote = uri_compile(remote_uri)
        via = partial(remote.proto, **remote.kw)
    else:
        via = None
    server_list = []
    for listen_uri in listen_uris:
        listen = uri_compile(listen_uri)
        if via:
            listen.kw['via'] = via
        host = listen.kw.pop('host')
        port = listen.kw.pop('port')
        if listen.scheme in ('ss', 'udpss') and 'cipher_cls' not in listen.kw:
            raise argparse.ArgumentTypeError('you need to assign cryto algorithm and password: '******'{listen.scheme}://{host}:{port}')
        if listen.scheme.startswith('udp'):
            server = udp_server(host, port, listen.proto(**listen.kw))
        else:
            server = tcp_server(host, port, ProtoFactory(listen.proto, **listen.kw), backlog=1024)
        server_list.append((server, (host, port), listen.scheme))
    return server_list
Example #3
0
def main():

    parser = get_parser()
    args = parser.parse_args()

    curio.run(curio.tcp_server(args.host, args.port,
                               yosser_handler))
Example #4
0
def get_server(uri):
    listen_uris, _, remote_uri = uri.partition('=')
    listen_uris = listen_uris.split(',')
    if not listen_uris:
        raise ValueError('no server found')
    if remote_uri:
        remote = uri_compile(remote_uri)
        via = partial(remote.proto, **remote.kw)
    else:
        via = None
    server_list = []
    for listen_uri in listen_uris:
        listen = uri_compile(listen_uri)
        if via:
            listen.kw['via'] = via
        host = listen.kw.pop('host')
        port = listen.kw.pop('port')
        if listen.scheme in ('ss', 'udpss') and 'cipher_cls' not in listen.kw:
            raise argparse.ArgumentTypeError(
                'you need to assign cryto algorithm and password: '******'{listen.scheme}://{host}:{port}')
        if listen.scheme.startswith('udp'):
            server = udp_server(host, port, listen.proto(**listen.kw))
        else:
            server = tcp_server(host,
                                port,
                                ProtoFactory(listen.proto, **listen.kw),
                                backlog=1024)
        server_list.append((server, (host, port), listen.scheme))
    return server_list
Example #5
0
async def main(host, port):
    while True:
        async with SignalSet(signal.SIGHUP) as sigset:
            print('Starting the server')
            serv_task = await spawn(tcp_server(host, port, echo_client))
            await sigset.wait()
            print('Server shutting down')
            await serv_task.cancel()

            for task in list(clients):
                await task.cancel()
Example #6
0
    def serveForever(self, interface='', port=None):
        port = port or DEFAULT_PORT
        interface = interface if interface is not None else DEFAULT_INTERFACE

        kernel = curio.Kernel()
        try:
            kernel.run(curio.tcp_server(interface, port, self.handleConnection))
        except KeyboardInterrupt:
            # Cancel all daemonic tasks and perform a clean shutdown once all
            # regular tasks have completed.
            print(
                'KeyboardInterrupt: Waiting for all non-daemonic '
                'tasks to finish...')
            kernel.run(shutdown=True)
Example #7
0
async def start_server(host,
                       port,
                       client_connected_task,
                       *,
                       create_connection=None):
    """Start a server listening on *addr* and call *client_connected_cb*
    for every client connecting to it.

    """
    if create_connection is None:
        create_connection = protocol.Connection.get_factory()

    async def task(socket, _addr):
        connection = create_connection()
        channel = await Channel.create(socket, connection)
        return await client_connected_task(channel)

    return await curio.spawn(curio.tcp_server(host, port, task))
Example #8
0
def _test(argv):
    from curio import tcp_server

    kern = get_kernel()
    kern2 = get_kernel()

    assert kern is kern2

    async def _echo_handler(client, addr):
        print('Connection from', addr)
        while True:
            data = await client.recv(100)
            if not data:
                break
            await client.sendall(data)
        print('Connection closed')

    k = get_kernel()
    print("Server running. run 'nc localhost 5123' to test it.")
    k.run(tcp_server('', 5123, _echo_handler))
Example #9
0
        "method": request.method.decode("ascii"),
        "target": request.target.decode("ascii"),
        "headers": [(name.decode("ascii"), value.decode("ascii"))
                    for (name, value) in request.headers],
        "body": "",
    }
    while True:
        event = await wrapper.next_event()
        if type(event) is h11.EndOfMessage:
            break
        assert type(event) is h11.Data
        response_json["body"] += event.data.decode("ascii")
    response_body_unicode = json.dumps(response_json,
                                       sort_keys=True,
                                       indent=4,
                                       separators=(",", ": "))
    response_body_bytes = response_body_unicode.encode("utf-8")
    await send_simple_response(wrapper,
                               200,
                               "application/json; charset=utf-8",
                               response_body_bytes)

################################################################
# Run the server
################################################################

if __name__ == "__main__":
    kernel = curio.Kernel()
    print("Listening on http://localhost:8080")
    kernel.run(curio.tcp_server("localhost", 8080, http_serve))
Example #10
0
import curio
from curio import ssl
import time

KEYFILE = "ssl_test_rsa"    # Private key
CERTFILE = "ssl_test.crt"   # Certificate (self-signed)

async def handler(client, addr):
    s = client.as_stream()
    async for line in s:
        line = line.strip()
        if not line:
            break
        print(line)

    await s.write(
b'''HTTP/1.0 200 OK\r
Content-type: text/plain\r
\r
If you're seeing this, it probably worked. Yay!
''')
    await s.write(time.asctime().encode('ascii'))
    await client.close()

if __name__ == '__main__':
    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE)
    print('Connect to https://localhost:10000 to see if it works')
    curio.run(curio.tcp_server('', 10000, handler, ssl=ssl_context))
Example #11
0
# An example of a server involving a CPU-intensive task.  We'll farm the
# CPU-intensive work out to a separate process.

from curio import run, run_in_process, tcp_server


def fib(n):
    if n <= 2:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)


async def fib_handler(client, addr):
    print('Connection from', addr)
    s = client.as_stream()
    async for line in s:
        try:
            n = int(line)
            result = await run_in_process(fib, n)
            resp = str(result) + '\n'
            await s.write(resp.encode('ascii'))
        except ValueError:
            await s.write(b'Bad input\n')
    print('Connection closed')
    await client.close()


if __name__ == '__main__':
    run(tcp_server('', 25000, fib_handler))
Example #12
0
async def main():
    server = await spawn(tcp_server('127.0.0.1', 8080, echo))

    await SignalSet(signal.SIGTERM, signal.SIGINT).wait()

    await server.cancel()
Example #13
0
from curio import run, run_in_process, tcp_server


def fib(n):
    if n <= 2:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)


async def fib_handler(client, addr):
    print("Connection from", addr)
    s = client.as_stream()
    async for line in s:
        try:
            n = int(line)
            result = await run_in_process(fib, n)
            resp = str(result) + "\n"
            await s.write(resp.encode("ascii"))
        except ValueError:
            await s.write(b"Bad input\n")
    print("Connection closed")
    await client.close()


if __name__ == "__main__":
    try:
        run(tcp_server("", 25000, fib_handler))
    except KeyboardInterrupt:
        pass
Example #14
0
# echoserv.py
#
# Echo server using the run_server() function

from curio import run, tcp_server

async def echo_client(client, addr):
    print('Connection from', addr)
    while True:
        data = await client.recv(1000)
        if not data:
            break
        await client.sendall(data)
    print('Connection closed')

if __name__ == '__main__':
    run(tcp_server('', 25000, echo_client))
Example #15
0
async def main():
    server = await curio.spawn(curio.tcp_server('127.0.0.1', 8080, http_serve))

    await curio.SignalSet(signal.SIGTERM, signal.SIGINT).wait()

    await server.cancel()
Example #16
0
async def socks5_server(host, port):
    # start handshake server
    await curio.spawn(curio.tcp_server(host, port, socks5_handler))

    # start udp server to relay udp data
    await curio.spawn(udp_relay_server(host, port))
Example #17
0
KEYFILE = os.path.dirname(__file__) + "/ssl_test_rsa"  # Private key
CERTFILE = os.path.dirname(
    __file__) + "/ssl_test.crt"  # Certificate (self-signed)


async def handler(client, addr):
    s = client.as_stream()
    async for line in s:
        line = line.strip()
        if not line:
            break
        print(line)

    await s.write(b'''HTTP/1.0 200 OK\r
Content-type: text/plain\r
\r
If you're seeing this, it probably worked. Yay!
''')
    await s.write(time.asctime().encode('ascii'))
    await client.close()


if __name__ == '__main__':
    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE)
    print('Connect to https://localhost:10000 to see if it works')
    try:
        curio.run(curio.tcp_server('', 10000, handler, ssl=ssl_context))
    except KeyboardInterrupt:
        pass
Example #18
0
        "target":
        request.target.decode("ascii"),
        "headers": [(name.decode("ascii"), value.decode("ascii"))
                    for (name, value) in request.headers],
        "body":
        "",
    }
    while True:
        event = await wrapper.next_event()
        if type(event) is h11.EndOfMessage:
            break
        assert type(event) is h11.Data
        response_json["body"] += event.data.decode("ascii")
    response_body_unicode = json.dumps(response_json,
                                       sort_keys=True,
                                       indent=4,
                                       separators=(",", ": "))
    response_body_bytes = response_body_unicode.encode("utf-8")
    await send_simple_response(wrapper, 200, "application/json; charset=utf-8",
                               response_body_bytes)


################################################################
# Run the server
################################################################

if __name__ == "__main__":
    kernel = curio.Kernel()
    print("Listening on http://localhost:8080")
    kernel.run(curio.tcp_server("localhost", 8080, http_serve))
 async def initialize(self):
     await super().initialize()
     self.server_task = await TaskWatcher.daemon_spawn(
         curio.tcp_server(host='',
                          port=self._port,
                          client_connected_task=self._serve_client))
Example #20
0
import logbook
import sys
import curio
from responds import Response
from responds.server import Server
from responds.router import Router

log = logbook.Logger('app')
logbook.StreamHandler(sys.stdout).push_application()

r = Router()
s = Server(r)


@r.route('/hello/async')
async def handle(event):
    log.info('our state: {}', event.wrapper.conn.our_state)
    log.info('their state: {}', event.wrapper.conn.their_state)
    log.info('app got body: {}', await event.body())
    log.info('our state: {}', event.wrapper.conn.our_state)
    log.info('their state: {}', event.wrapper.conn.their_state)
    return Response(status_code=200, headers=[], body=b'Hello world!')


kernel = curio.Kernel()
kernel.run(curio.tcp_server('0.0.0.0', 8080, s.tcp_handle))
Example #21
0
async def ws_echo_server(in_queue, out_queue):
    """Just echo websocket messages, reversed. Echo 3 times, then close."""
    for _ in range(3):
        msg = await in_queue.get()
        if msg is None:
            # The ws connection was closed.
            break
        await out_queue.put(msg[::-1])
    print("Handler done.")


def serve_ws(handler):
    """Start processing web socket messages using the given handler."""
    async def run_ws(client, addr):
        in_q, out_q = Queue(), Queue()
        ws_task = await spawn(ws_adapter(in_q, out_q, client, addr))
        await handler(in_q, out_q)
        await out_q.put(None)
        await ws_task.join()  # Wait until it's done.
        # Curio will close the socket for us after we drop off here.
        print("Master task done.")

    return run_ws


if __name__ == '__main__':
    from curio import tcp_server
    port = 5000
    print(f'Listening on port {port}.')
    run(tcp_server('', port, serve_ws(ws_echo_server)))
Example #22
0
from curio import run, spawn, tcp_server
from socket import *


async def echo_handler(client, addr):
    print('Connection from', addr)
    try:
        client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
    except (OSError, NameError):
        pass
    s = client.as_stream()
    while True:
        data = await s.readline()
        if not data:
            break
        await s.write(data)
    await s.close()
    print('Connection closed')


if __name__ == '__main__':
    run(tcp_server('', 25000, echo_handler))
Example #23
0
from curio import run, tcp_server


def fibonacci(n):
    if n <= 2:
        return 2
    return fibonacci(n-1) + fibonacci(n-2)


async def handle_connection(client, addr):
    while True:
        data = await client.recv(100000)
        result = fibonacci(int(data))
        await client.sendall(data)


if __name__ == "__main__":
    run(tcp_server('', 25000, handle_connection))
Example #24
0
from curio import run, spawn, tcp_server
from curio import ssl
from socket import *

KEYFILE = "ssl_test_rsa"  # Private key
CERTFILE = "ssl_test.crt"  # Certificate (self-signed)


async def echo_handler(client, addr):
    print('Connection from', addr)
    try:
        client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
    except (OSError, NameError):
        pass
    s = client.as_stream()
    while True:
        data = await s.read(102400)
        if not data:
            break
        await s.write(data)
    await s.close()
    print('Connection closed')


if __name__ == '__main__':
    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE)
    run(tcp_server('', 25000, echo_handler, ssl=ssl_context))
Example #25
0
    elif _event == "Socks4Request":
        event = Socks4Response(RESP_STATUS["REQUEST_GRANTED"], _event.addr,
                               _event.port)
        print("sending event: {}".format(event))
        data = conn.send(event)
        await client.send(data)

    print("socks end")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simple socks5 server")
    parser.add_argument("--host",
                        dest="host",
                        help="specify the host",
                        default="127.0.0.1")
    parser.add_argument("--port",
                        dest="port",
                        type=int,
                        help="specify the proxy port",
                        default=5580)
    options = parser.parse_args()

    try:
        print("Starting socks server at {host} {port}".format(
            **options.__dict__))
        run(tcp_server(options.host, options.port, socks5_handler),
            with_monitor=False)
    except KeyboardInterrupt:
        print("bye")
Example #26
0
from curio import run, spawn, tcp_server
from curio import ssl
from socket import *

KEYFILE = "ssl_test_rsa"  # Private key
CERTFILE = "ssl_test.crt"  # Certificate (self-signed)


async def echo_handler(client, addr):
    print("Connection from", addr)
    try:
        client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
    except (OSError, NameError):
        pass
    s = client.as_stream()
    while True:
        data = await s.read(102400)
        if not data:
            break
        await s.write(data)
    await s.close()
    print("Connection closed")


if __name__ == "__main__":
    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.load_cert_chain(certfile=CERTFILE, keyfile=KEYFILE)
    run(tcp_server("", 25000, echo_handler, ssl=ssl_context))
Example #27
0
from curio import run, spawn, tcp_server
from socket import *


async def echo_handler(client, addr):
    print("Connection from", addr)
    try:
        client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
    except (OSError, NameError):
        pass
    s = client.as_stream()
    while True:
        data = await s.readline()
        if not data:
            break
        await s.write(data)
    await s.close()
    print("Connection closed")


if __name__ == "__main__":
    run(tcp_server("", 25000, echo_handler))
Example #28
0
# echoserv.py
#
# Echo server using the run_server() function

from curio import run, tcp_server


async def echo_client(client, addr):
    print('Connection from', addr)
    while True:
        data = await client.recv(1000)
        if not data:
            break
        await client.sendall(data)
    print('Connection closed')


if __name__ == '__main__':
    try:
        run(tcp_server('', 25000, echo_client))
    except KeyboardInterrupt:
        pass
Example #29
0
 def run(self, host, port):
     kernel = curio.Kernel()
     logging.info(f"Listening on http://{host}:{port}")
     kernel.run(curio.tcp_server(host, port, self.http_serve))
Example #30
0
# CPU-intensive work out to a separate process.

from curio import run, run_in_process, tcp_server

def fib(n):
    if n <= 2:
        return 1
    else:
        return fib(n-1) + fib(n-2)

async def fib_handler(client, addr):
    print('Connection from', addr)
    s = client.as_stream()
    async for line in s:
        try:
            n = int(line)
            result = await run_in_process(fib, n)
            resp = str(result) + '\n'
            await s.write(resp.encode('ascii'))
        except ValueError:
            await s.write(b'Bad input\n')
    print('Connection closed')
    await client.close()

if __name__ == '__main__':
    run(tcp_server('', 25000, fib_handler))



    
Example #31
0
        # socks request
        data = await client.recv(1024)
        _event = conn.recv(data)
        print("receiving event: {}".format(_event))

        # socks response
        event = Response(RESP_STATUS["SUCCESS"], _event.atyp, _event.addr, _event.port)
        print("sending event: {}".format(event))
        data = conn.send(event)
        await client.send(data)

    elif _event == "Socks4Request":
        event = Socks4Response(RESP_STATUS["REQUEST_GRANTED"], _event.addr, _event.port)
        print("sending event: {}".format(event))
        data = conn.send(event)
        await client.send(data)

    print("socks end")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simple socks5 server")
    parser.add_argument("--host", dest="host", help="specify the host", default="127.0.0.1")
    parser.add_argument("--port", dest="port", type=int, help="specify the proxy port", default=5580)
    options = parser.parse_args()

    try:
        print("Starting socks server at {host} {port}".format(**options.__dict__))
        run(tcp_server(options.host, options.port, socks5_handler), with_monitor=False)
    except KeyboardInterrupt:
        print("bye")