Esempio n. 1
0
def client_connector(backend, local_port, tunnel_data,
            ready=gevent.event.Event()):
    while True:
        init = tunnel_data.pop('init', None)
        header = copy.copy(tunnel_data)
        if init:
            header['new'] = True
            ready.clear()
        elif not ready.isSet():
            ready.wait()
        backend_client = create_connection(backend)
        backend_client.sendall("{0}\n".format(json.dumps(header)))
        header = recv_json(backend_client)
        if header and 'banner' in header:
            print "  {0}".format(header['banner'])
            print "  Port {0} is now accessible from http://{1} ...\n".format(
                    local_port, header['host'])
            ready.set()
        elif header and 'error' in header:
            print "  ERROR: {0}".format(header['error'])
            gevent.hub.get_hub().parent.throw(SystemExit(1))
        else:
            try:
                local_client = create_connection(('0.0.0.0', local_port))
                join_sockets(backend_client, local_client)
            except IOError:
                backend_client.close()
Esempio n. 2
0
def client_connector(backend,
                     local_port,
                     tunnel_data,
                     ready=gevent.event.Event()):
    while True:
        init = tunnel_data.pop('init', None)
        header = copy.copy(tunnel_data)
        if init:
            header['new'] = True
            ready.clear()
        elif not ready.isSet():
            ready.wait()
        backend_client = create_connection(backend)
        backend_client.sendall("{0}\n".format(json.dumps(header)))
        header = recv_json(backend_client)
        if header and 'banner' in header:
            print "  {0}".format(header['banner'])
            print "  Port {0} is now accessible from http://{1} ...\n".format(
                local_port, header['host'])
            ready.set()
        elif header and 'error' in header:
            print "  ERROR: {0}".format(header['error'])
            gevent.hub.get_hub().parent.throw(SystemExit(1))
        else:
            try:
                local_client = create_connection(('0.0.0.0', local_port))
                join_sockets(backend_client, local_client)
            except IOError:
                backend_client.close()
Esempio n. 3
0
def open_proxy_backend(backend,
                       target,
                       name,
                       client,
                       use_ssl=False,
                       ssl_opts=None):
    proxy = eventlet.connect(backend)
    if use_ssl:
        ssl_opts = ssl_opts or {}
        proxy = eventlet.wrap_ssl(proxy, server_side=False, **ssl_opts)
    proxy.sendall(protocol.version)
    protocol.send_message(proxy,
                          protocol.proxy_request(
                              name=name,
                              client=client,
                          ))
    reply = protocol.recv_message(proxy)
    if reply and 'proxy' in reply:
        try:
            local = eventlet.connect(target)
            util.join_sockets(proxy, local)
        except IOError:
            proxy.close()
    elif reply and 'error' in reply:
        print "  ERROR: {0}".format(reply['error'])
        return
    else:
        pass
Esempio n. 4
0
def connection_handler(socket, address):
    hostname = peek_http_host(socket)
    if not hostname:
        send_http_error(socket, 'No hostname', '400 Bad Request')
        return

    if hostname == Tunnel.domain_suffix:
        meta.server.process_request((socket, address))
        return

    tunnel = Tunnel.get_by_hostname(hostname)
    if not tunnel:
        send_http_error(socket, 'No tunnel for {0}'.format(hostname),
                        '410 Gone')
        return

    conn, proxy_used = tunnel.pop_proxy_conn(timeout=2)
    if not conn:
        send_http_error(socket, 'No proxy connections', '502 Bad Gateway')
        return

    protocol.send_message(conn, protocol.proxy_reply())
    pool = util.join_sockets(conn, socket)
    proxy_used.send(pool)
    logging.debug("popped connection:\"{0}\" for frontend:\"{1}\"".format(
        tunnel.name, hostname))
    pool.waitall()
Esempio n. 5
0
def connection_handler(socket, address):
    hostname = peek_http_host(socket)
    if not hostname:
        send_http_error(socket, "No hostname", "400 Bad Request")
        return

    if hostname == Tunnel.domain_suffix:
        meta.server.process_request((socket, address))
        return

    tunnel = Tunnel.get_by_hostname(hostname)
    if not tunnel:
        send_http_error(socket, "No tunnel for {0}".format(hostname), "410 Gone")
        return

    conn, proxy_used = tunnel.pop_proxy_conn(timeout=2)
    if not conn:
        send_http_error(socket, "No proxy connections", "502 Bad Gateway")
        return

    protocol.send_message(conn, protocol.proxy_reply())
    pool = util.join_sockets(conn, socket)
    proxy_used.send(pool)
    logging.debug('popped connection:"{0}" for frontend:"{1}"'.format(tunnel.name, hostname))
    pool.waitall()
Esempio n. 6
0
def open_proxy_backend(backend, target, name, client, use_ssl=False, ssl_opts=None):
    proxy = eventlet.connect(backend)
    if use_ssl:
        ssl_opts = ssl_opts or {}
        proxy = eventlet.wrap_ssl(proxy, server_side=False, **ssl_opts)
    proxy.sendall(protocol.version)
    protocol.send_message(proxy, protocol.proxy_request(name=name, client=client))
    reply = protocol.recv_message(proxy)
    if reply and "proxy" in reply:
        try:
            local = eventlet.connect(target)
            util.join_sockets(proxy, local)
        except IOError:
            proxy.close()
    elif reply and "error" in reply:
        print "  ERROR: {0}".format(reply["error"])
        return
    else:
        pass
Esempio n. 7
0
def open_proxy_backend(backend, target, name, client):
    proxy = eventlet.connect(backend)
    proxy.sendall(protocol.version)
    protocol.send_message(proxy,
        protocol.proxy_request(
            name=name,
            client=client,
    ))
    reply = protocol.recv_message(proxy)
    if reply and 'proxy' in reply:
        try:
            local = eventlet.connect(target)
            util.join_sockets(proxy, local)
        except IOError:
            proxy.close()
    elif reply and 'error' in reply:
        print "  ERROR: {0}".format(reply['error'])
        return
    else:
        pass
Esempio n. 8
0
def open_proxy_backend(backend, port, name, client):
    proxy = eventlet.connect(backend)
    proxy.sendall(protocol.version)
    protocol.send_message(proxy, 
        protocol.proxy_request(
            name=name, 
            client=client,
    ))
    reply = protocol.recv_message(proxy)
    if reply and 'proxy' in reply:
        try:
            local = eventlet.connect(('0.0.0.0', port))
            util.join_sockets(proxy, local)
        except IOError:
            proxy.close()
    elif reply and 'error' in reply:
        print "  ERROR: {0}".format(reply['error'])
        return
    else:
        pass
Esempio n. 9
0
def frontend_handler(socket, address):
    hostname = ''
    hostheader = re.compile('host: ([^\(\);:,<>]+)', re.I)
    # Peek up to 512 bytes into data for the Host header
    for n in [128, 256, 512]:
        bytes = socket.recv(n, MSG_PEEK)
        if not bytes:
            break
        for line in bytes.split('\r\n'):
            match = hostheader.match(line)
            if match:
                hostname = match.group(1)
        if hostname:
            break
    hostname = hostname.split(':')[0]
    if not hostname:
        logging.debug("!frontend: no hostname, closing")
        socket.close()
        return
    if hostname.startswith('_backend.'):
        port = os.environ.get('DOTCLOUD_SERVER_BACKEND_PORT',
                              Tunnel.backend_port)
        data = """HTTP/1.1 200 OK\r\nContent-Length: {0}\r\nConnection: close\r\n\r\n{1}
               """.format(len(str(port)), port).strip()
        socket.sendall(data)
        socket.close()
        return
    tunnel = Tunnel.get_by_hostname(hostname)
    if not tunnel:
        logging.debug("!frontend: no tunnel, closing")
        socket.close()
        return
    conn = tunnel.pop_backend(timeout=2)
    if not conn:
        logging.debug("!frontend: no backend, closing")
        socket.close()
        return
    conn.send("\n")
    join_sockets(conn, socket)
    logging.debug("popped backend:\"{0}\" for frontend:\"{1}\"".format(
        tunnel.name, hostname))
Esempio n. 10
0
def frontend_handler(socket, address):
    hostname = ''
    hostheader = re.compile('host: ([^\(\);:,<>]+)', re.I)
    # Peek up to 512 bytes into data for the Host header
    for n in [128, 256, 512]:
        bytes = socket.recv(n, MSG_PEEK)
        if not bytes:
            break
        for line in bytes.split('\r\n'):
            match = hostheader.match(line)
            if match:
                hostname = match.group(1)
        if hostname:
            break
    hostname = hostname.split(':')[0]
    if not hostname:
        logging.debug("!frontend: no hostname, closing")
        socket.close()
        return
    if hostname.startswith('_backend.'):
        port = os.environ.get('DOTCLOUD_SERVER_BACKEND_PORT', Tunnel.backend_port)
        data = """HTTP/1.1 200 OK\r\nContent-Length: {0}\r\nConnection: close\r\n\r\n{1}
               """.format(len(str(port)), port).strip()
        socket.sendall(data)
        socket.close()
        return
    tunnel = Tunnel.get_by_hostname(hostname)
    if not tunnel:
        logging.debug("!frontend: no tunnel, closing")
        socket.close()
        return
    conn = tunnel.pop_backend(timeout=2)
    if not conn:
        logging.debug("!frontend: no backend, closing")
        socket.close()
        return
    conn.send("\n")
    join_sockets(conn, socket)
    logging.debug("popped backend:\"{0}\" for frontend:\"{1}\"".format(
                tunnel.name, hostname))
Esempio n. 11
0
def connection_handler(socket, address):
    host = peek_http_host(socket)
    hostname = host.split(':')[0]
    if not hostname:
        logging.debug("!no hostname, closing")
        socket.close()
        return

    if hostname.startswith('_version.'):
        send_http_response(socket, __version__)
        socket.close()
        logging.debug("version request from {0}".format(address[0]))
        return

    if hostname.startswith('_backend.'):
        port = os.environ.get('DOTCLOUD_SERVER_BACKEND_PORT',
                              Tunnel.backend_port)
        send_http_response(socket, port)
        socket.close()
        return

    if hostname.startswith('_metrics.'):
        content = json.dumps(metrics.dump_metrics(),
                             sort_keys=True,
                             indent=2,
                             separators=(',', ': '))
        send_http_response(socket, content)
        socket.close()
        logging.debug("metrics request from {0}".format(address[0]))
        return

    tunnel = Tunnel.get_by_hostname(hostname)
    if not tunnel:
        logging.debug("!no tunnel, closing ({0})".format(hostname))
        socket.close()
        return

    conn, proxy_used = tunnel.pop_proxy_conn(timeout=2)
    if not conn:
        logging.debug("!no proxy connection, closing")
        socket.close()
        return

    protocol.send_message(conn, protocol.proxy_reply())
    pool = util.join_sockets(conn, socket)
    proxy_used.send(pool)
    logging.debug("popped connection:\"{0}\" for frontend:\"{1}\"".format(
        tunnel.name, hostname))
    pool.waitall()
Esempio n. 12
0
def connection_handler(socket, address):
    host = peek_http_host(socket)
    hostname = host.split(':')[0]
    if not hostname:
        logging.debug("!no hostname, closing")
        socket.close()
        return

    if hostname.startswith('_version.'):
        send_http_response(socket, __version__)
        socket.close()
        logging.debug("version request from {0}".format(address[0]))
        return

    if hostname.startswith('_backend.'):
        port = os.environ.get('DOTCLOUD_SERVER_BACKEND_PORT', 
                    Tunnel.backend_port)
        send_http_response(socket, port)
        socket.close()
        return

    if hostname.startswith('_metrics.'):
        content = json.dumps(metrics.dump_metrics(),
                    sort_keys=True, indent=2, separators=(',', ': '))
        send_http_response(socket, content)
        socket.close()
        logging.debug("metrics request from {0}".format(address[0]))
        return

    tunnel = Tunnel.get_by_hostname(hostname)
    if not tunnel:
        logging.debug("!no tunnel, closing ({0})".format(
            hostname))
        socket.close()
        return

    conn, proxy_used = tunnel.pop_proxy_conn(timeout=2)
    if not conn:
        logging.debug("!no proxy connection, closing")
        socket.close()
        return

    protocol.send_message(conn, protocol.proxy_reply())
    pool = util.join_sockets(conn, socket)
    proxy_used.send(pool)
    logging.debug("popped connection:\"{0}\" for frontend:\"{1}\"".format(
                tunnel.name, hostname))
    pool.waitall()