Ejemplo n.º 1
0
    def run_server(self, port=None):

        log.info("home_dir %s",config.get('DEFAULT', 'home_dir'))
        log.info("hydra_base_dir %s",config.get('DEFAULT', 'hydra_base_dir'))
        log.info("common_app_data_folder %s",config.get('DEFAULT', 'common_app_data_folder'))
        log.info("win_common_documents %s",config.get('DEFAULT', 'win_common_documents'))
        log.info("sqlite url %s",config.get('mysqld', 'url'))
        log.info("layout_xsd_path %s",config.get('hydra_server', 'layout_xsd_path'))
        log.info("default_directory %s",config.get('plugin', 'default_directory'))
        log.info("result_file %s",config.get('plugin', 'result_file'))
        log.info("plugin_xsd_path %s",config.get('plugin', 'plugin_xsd_path'))
        log.info("log_config_path %s",config.get('logging_conf', 'log_config_path'))

        if port is None:
            port = config.getint('hydra_server', 'port', 8080)

        domain = config.get('hydra_server', 'domain', '127.0.0.1')

        check_port_available(domain, port)

        spyne.const.xml_ns.DEFAULT_NS = 'soap_server.hydra_complexmodels'
        cp_wsgi_application = Server((domain,port), application, numthreads=10)

        log.info("listening to http://%s:%s", domain, port)
        log.info("wsdl is at: http://%s:%s/soap/?wsdl", domain, port)

        try:
            cp_wsgi_application.start()
        except KeyboardInterrupt:
            cp_wsgi_application.stop()
Ejemplo n.º 2
0
def launch_server(host, port, app, **kwargs):
    """Use cheroot WSGI server, a multithreaded scallable server."""

    server = Server((host, port), app, **kwargs)
    logging.info("Starting server, listening on port %s", port)
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Ejemplo n.º 3
0
class Controller (object):
    def listen(self):
        print("listening")
        self.server = WSGIServer(('0.0.0.0', 8000), webapp)
        # run(webapp, server=self.server)
        # run(webapp, server='bjoern', port=8000)
        self.server.start()

    def shutdown(self):
        self.server.stop()
        print("done listening")
Ejemplo n.º 4
0
def start_server(config):
    from cheroot.wsgi import Server as WSGIServer
    hostname = config['server_host']['host']
    port = int(config['server_host']['port'])
    scheme = config['server_host']['scheme']
    app = load_app()
    server = WSGIServer((hostname, port), app)
    try:
        LOGGER.debug('starting Cheroot at %s://%s:%s',
                scheme, hostname, port)
        std_error_message("Starting Cheroot at %s://%s:%s"
                % (scheme, hostname, port))
        server.start()
    except KeyboardInterrupt:
        server.stop()
        sys.exit(0)
Ejemplo n.º 5
0
    def test_server(self):
        """Test http server"""
        test_dir, application = self.create_server()

        # Prepare server thread
        server = Server(('localhost', 0), application.rest)
        server.prepare()
        server_port = server.bind_addr[1]
        thread = threading.Thread(target=server.serve)
        thread.start()

        # Run test
        response = urlopen('http://localhost:{}/en/cs/unit/Hello/'.format(server_port))
        payload = json.loads(response.read().decode('utf-8'))
        assert payload[0]['target'] == 'Ahoj'

        # Shutdown the server thread
        server.stop()
        thread.join()
        self.cleanup(test_dir, application)
Ejemplo n.º 6
0
    def start(self):
        d = PathInfoDispatcher({'/': self.app})
        self.server = Server(('0.0.0.0', self.rpcport), d)
        self.proxy_thread = threading.Thread(target=self.server.start)
        self.proxy_thread.daemon = True
        self.proxy_thread.start()

        # Now that bitcoind is running on the real rpcport, let's tell all
        # future callers to talk to the proxyport. We use the bind_addr as a
        # signal that the port is bound and accepting connections.
        while self.server.bind_addr[1] == 0:
            pass
        self.rpcport = self.server.bind_addr[1]
        logging.debug("BitcoinRpcProxy proxying incoming port {} to {}".format(self.rpcport, self.bitcoind.rpcport))
Ejemplo n.º 7
0
def main(argv=sys.argv[1:]):

    parser = argparse.ArgumentParser(
        description='Start Aurora on http://<host>:<port>')

    parser.add_argument(
        dest='input',
        nargs='?',
        help='Path where to find Aurora content or catalog file',
        default='.')

    parser.add_argument('--live',
                        dest='live',
                        help='Run Aurora in live mode',
                        action='store_true')

    parser.add_argument('-p',
                        '--port',
                        dest='port',
                        help='Port to serve HTTP files at (default: 5000)',
                        default=PORT)

    parser.add_argument('-H',
                        '--host',
                        dest='host',
                        help='IP to serve HTTP files at (default: localhost)',
                        default=HOST)

    args = parser.parse_args(argv)

    # The default behavior should be as follows:
    # * If the user provides a catalog file to open, open it
    # * If the user does not provide a catalog file to open:
    #     * Webapp should prompt them to either open a file
    #       or specify the location for a new one.
    #
    # In the meantime, we'll just create one in memory

    if os.path.isfile(args.input):
        # User provided a catalog file
        engine = new_engine(catalog=args.input)
    else:
        engine = new_engine()

    session = new_session(engine)
    Base.metadata.create_all(bind=engine)

    api.session = scoped_session(session, scopefunc=_app_ctx_stack)

    # We need to read the config from the db here to figure out what to do re: a bunch of stuff

    server = Server((args.host, args.port), app)

    if args.live:
        print("F**k it, we'll do it live")
    else:
        pass

    # Stand up the webserver
    print(f'Running Aurora on http://{args.host}:{args.port}')

    try:
        server.start()
        if CONFIG['autolaunch_browser']:
            webbrowser.open(f'http://{HOST}:{PORT}', new=2)
    except KeyboardInterrupt:
        print(f'\n\nShutting down Aurora')
        server.stop()
Ejemplo n.º 8
0
class ProxiedBitcoinD(BitcoinD):
    def __init__(self, bitcoin_dir, proxyport=0):
        BitcoinD.__init__(self, bitcoin_dir, rpcport=None)
        self.app = Flask("BitcoindProxy")
        self.app.add_url_rule("/",
                              "API entrypoint",
                              self.proxy,
                              methods=['POST'])
        self.proxyport = proxyport
        self.mocks = {}

    def _handle_request(self, r):
        conf_file = os.path.join(self.bitcoin_dir, 'bitcoin.conf')
        brpc = BitcoinProxy(btc_conf_file=conf_file)
        method = r['method']

        # If we have set a mock for this method reply with that instead of
        # forwarding the request.
        if method in self.mocks and type(method) == dict:
            return self.mocks[method]
        elif method in self.mocks and callable(self.mocks[method]):
            return self.mocks[method](r)

        try:
            reply = {
                "result": brpc._call(r['method'], *r['params']),
                "error": None,
                "id": r['id']
            }
        except JSONRPCError as e:
            reply = {"error": e.error, "id": r['id']}
        return reply

    def proxy(self):
        r = json.loads(request.data.decode('ASCII'))

        if isinstance(r, list):
            reply = [self._handle_request(subreq) for subreq in r]
        else:
            reply = self._handle_request(r)

        reply = json.dumps(reply, cls=DecimalEncoder)
        logging.debug("Replying to %r with %r", r, reply)

        response = flask.Response(reply)
        response.headers['Content-Type'] = 'application/json'
        return response

    def start(self):
        d = PathInfoDispatcher({'/': self.app})
        self.server = Server(('0.0.0.0', self.proxyport), d)
        self.proxy_thread = threading.Thread(target=self.server.start)
        self.proxy_thread.daemon = True
        self.proxy_thread.start()
        BitcoinD.start(self)

        # Now that bitcoind is running on the real rpcport, let's tell all
        # future callers to talk to the proxyport. We use the bind_addr as a
        # signal that the port is bound and accepting connections.
        while self.server.bind_addr[1] == 0:
            pass
        self.proxiedport = self.rpcport
        self.rpcport = self.server.bind_addr[1]
        logging.debug(
            "bitcoind reverse proxy listening on {}, forwarding to {}".format(
                self.rpcport, self.proxiedport))

    def stop(self):
        BitcoinD.stop(self)
        self.server.stop()
        self.proxy_thread.join()

    def mock_rpc(self, method, response=None):
        """Mock the response to a future RPC call of @method

        The response can either be a dict with the full JSON-RPC response, or a
        function that returns such a response. If the response is None the mock
        is removed and future calls will be passed through to bitcoind again.

        """
        if response is not None:
            self.mocks[method] = response
        elif method in self.mocks:
            del self.mocks[method]
Ejemplo n.º 9
0
def main():
    clear_screen()
    print_logo()
    redirect_url = ask(
        "Giriş yapıldıktan sonra nereye yönlendirilsin (Varsayılan: https://www.instagram.com)"
    )
    port = ask("Web sunucusu hangi port'u kullansın (Varsayılan: 80)")

    if (port != "" and (port.isdigit()) == False):
        error("Hatalı giriş!")
        _exit(0)

    try_accounts = ask(
        "Girilen kullanıcılar denensin mi (Varsayılan: Hayır) [E/H]")
    print("")

    if ((try_accounts != "") and (try_accounts.lower() != "e")
            and (try_accounts.lower() != "h")):
        error("Hatalı giriş!")
        _exit(0)

    if (redirect_url != ""):
        info("Yönlendirme '{0}' olarak ayarlandı!".format(redirect_url))
        SETTINGS["REDIRECT_URL"] = redirect_url
    else:
        info("Varsayılan yönlendirme adresi kullanılıyor!")
        SETTINGS["REDIRECT_URL"] = "https://www.instagram.com"

    if (port != ""):
        info("Sunucunun web portu '{0}' olarak ayarlandı!".format(port))
        SETTINGS["PORT"] = int(port)
    else:
        info("Varsayılan sunucu portu kullanılıyor!")
        SETTINGS["PORT"] = 80

    if (try_accounts != ""):
        if (try_accounts.lower() == "e"):
            info("Sunucuya girilen kullanıcılar giriş yapılarak denenecektir!")
            SETTINGS["TRY_ACCOUNTS"] = True

    print("")
    if ("arm" not in uname().machine):
        success("NGROK servisi başlatılıyor!")
        public_url = ngrok.connect()
        web_url = ngrok.connect(SETTINGS["PORT"], "http")
        success("Port yönlendirme başarılı!")
        print("")
        success("Web sunucusu {0} adresinde açıldı!".format(web_url))
        print("")
    else:
        info(
            "Program Termux'dan çalıştırılıyor! NGROK'u 'ngrok http 80' komutuyla manuel başlatmalısınız!"
        )
        print("")
        success("Web sunucusu http://localhost:{0} adresinde açıldı!".format(
            SETTINGS["PORT"]))
        print("")

    try:
        http_server = WSGIServer(('0.0.0.0', SETTINGS["PORT"]),
                                 PathInfoDispatcher({'/': website_app}))
        http_server.start()
    except:
        info(
            "Program yönetici olarak çalıştırılmadığından dolayı web portu 5000 olarak değiştirildi!"
        )
        SETTINGS["PORT"] = 5000
        http_server = WSGIServer(('0.0.0.0', SETTINGS["PORT"]),
                                 PathInfoDispatcher({'/': website_app}))
        http_server.start()
Ejemplo n.º 10
0
from cheroot.wsgi import Server as WSGIServer
from cheroot.wsgi import PathInfoDispatcher as WSGIPathInfoDispatcher
from cheroot.ssl.builtin import BuiltinSSLAdapter

from webpage import app
from net import get_ip

#script per il settaggio del wsgi

my_app = WSGIPathInfoDispatcher({'/': app})
server = WSGIServer((get_ip(), 443), my_app)

ssl_cert = "cert.pem"
ssl_key = "privkey.pem"
server.ssl_adapter = BuiltinSSLAdapter(ssl_cert, ssl_key, None)

if __name__ == '__main__':
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Ejemplo n.º 11
0
class CherryProxy:
    """
    CherryProxy: a filtering HTTP proxy.
    """

    # class variables: unique id for each request
    _req_id = 0
    _lock_req_id = threading.Lock()

    def __init__(self,
                 listen_address,
                 listen_port,
                 redirect_address,
                 redirect_port,
                 verbosity,
                 log_stream=sys.stdout):
        self.listen_address = listen_address
        self.listen_port = listen_port
        self.redirect_address = redirect_address
        self.redirect_port = redirect_port
        self._verbosity = verbosity
        self._log_stream = log_stream

        # thread local variables to store request/response data per thread:
        self.req = threading.local()
        self.resp = threading.local()

        self.server = CherryPyWSGIServer(
            (self.listen_address, self.listen_port), self._proxy_app)
        self.log_debug('__init__',
                       'server.bind_addr: {}'.format(self.server.bind_addr))

    def log(self, s, prefix='### ', req_id=None):
        if self._verbosity > 0:
            if req_id:
                prefix += '{:06} | '.format(req_id)
            self._log_stream.write('{}{}\n'.format(prefix, s))

    def log_debug(self, method_name, s):
        if self._verbosity > 1:
            options = {
                's': '{:25s} | {}'.format(method_name, s),
                'prefix': '*** ',
            }
            if hasattr(self.req, 'id'):
                options['req_id'] = self.req.id
            self.log(**options)

    def start(self):
        self.log('Starting proxy to listen on {} and redirect to {}'.format(
            self.server.bind_addr,
            (self.redirect_address, self.redirect_port)))
        self.log('Proxy listening ... (press Ctrl+C to stop)'.format(
            self.server.bind_addr))
        self.server.start()

    def stop(self):
        self.server.stop()
        self.log('Proxy stopped.')

    def set_response(self,
                     status,
                     reason=None,
                     data=None,
                     content_type='text/plain'):
        """
        Set a HTTP response to be sent to the client instead of the one from the server.
        :param status: int, HTTP status code (see RFC 2616)
        :param reason: str, optional text for the response line, standard text by default
        :param data: str, optional body for the response, default="status reason"
        :param content_type: str, content-type corresponding to data
        :return:
        """
        self.resp.status = status

        if not reason:
            reason = client.responses[
                status]  # get standard text corresponding to status
        self.resp.reason = reason

        if not data:
            data = '{} {}'.format(status, reason)
        self.resp.data = data

        # reset all headers
        self.resp.headers = []
        self.resp.headers.append(('content-type', content_type))
        # self.resp.headers.append(('content-length', str(len(data))))

    def set_response_forbidden(self):
        self.set_response(403, reason='Forbidden')

    def filter_request_headers(self):
        """
        Method to be overridden:
        Called to analyse/filter/modify the request received from the client,
        before reading the full request with its body if there is one,
        before it is sent to the server.

        This method may call set_response() if the request needs to be blocked
        before being sent to the server.

        The following attributes can be read and MODIFIED:
            self.req.headers: dictionary of HTTP headers, with lowercase names
            self.req.method: HTTP method, e.g. 'GET', 'POST', etc
            self.req.scheme: protocol from URL, e.g. 'http' or 'https'
            self.req.path: path in URL, for example '/folder/index.html'
            self.req.query: query string, found after question mark in URL

        The following attributes can be READ only:
            self.req.environ: dictionary of request attributes following WSGI format (PEP 333)
            self.req.url: partial URL containing 'path?query'
            self.req.content_type: content-type, for example 'text/html'
            self.req.charset: charset, for example 'UTF-8'
            self.req.length: length of request data in bytes, 0 if none
        """
        pass

    def filter_request(self):
        """
        Method to be overridden:
        Called to analyse/filter/modify the request received from the client,
        after reading the full request with its body if there is one,
        before it is sent to the server.

        This method may call set_response() if the request needs to be blocked
        before being sent to the server.

        The same attributes as in filter_request_headers are available:

        The following attributes can also be read and MODIFIED:
            self.req.data: data sent with the request (POST or PUT)
        """
        pass

    def filter_response_headers(self):
        """
        Method to be overridden:
        Called to analyse/filter/modify the response received from the server,
        before reading the full response with its body if there is one,
        before it is sent back to the client.

        This method may call set_response() if the response needs to be blocked
        (e.g. replaced by a simple response) before being sent to the client.

        The following attributes can be read and MODIFIED:
            self.resp.status: int, HTTP status of response, e.g. 200, 404, etc
            self.resp.reason: reason string, e.g. 'OK', 'Not Found', etc
            self.resp.headers: response headers, list of (header, value) tuples

        The following attributes can be READ only:
            self.resp.httpconn: httplib.HTTPConnection object
            self.resp.response: httplib.HTTPResponse object
            self.resp.content_type: content-type of response
        """
        pass

    def filter_response(self):
        """
        Method to be overridden:
        Called to analyse/filter/modify the response received from the server,
        after reading the full response with its body if there is one,
        before it is sent back to the client.

        This method may call set_response() if the response needs to be blocked
        (e.g. replaced by a simple response) before being sent to the client.

        The same attributes as in filter_response_headers are available:

        The following attributes can be read and MODIFIED:
            self.resp.data: data sent with the response
        """
        pass

    def _proxy_app(self, environ, f_start_response):
        """
        Main method called when a request is received from a client (WSGI application).
        :param environ:
        :param f_start_response:
        :return:
        """
        t_start = time.perf_counter()
        self._init_request_response()
        self.log('START', req_id=self.req.id)

        self._parse_request(environ)

        # method to be overridden by subclass: filter request headers before reading the body
        self.filter_request_headers()

        if not self.resp.status:
            self._read_request_body()

            # method to be overridden by subclass: filter request before sending it to the server
            self.filter_request()

        self.log('request {} {}'.format(self.req.method, self.req.url),
                 req_id=self.req.id)

        if not self.resp.status:
            self._send_request()
            self._parse_response()

            # method to be overridden by subclass: filter response headers before reading the body
            self.filter_response_headers()

        if not self.resp.data:  # here we need to check resp.data
            self._read_response_body()

            # method to be overridden by subclass: filter request before sending it to the client
            self.filter_response()

        # for now we always close the connection, even if the client sends several requests;
        # this is not optimal performance-wise, but simpler to code
        if self.resp.httpconn:
            self.resp.httpconn.close()

        self._send_response(f_start_response)

        t_end = time.perf_counter()
        self.log('response {} {} in {:5.3f} seconds'.format(
            self.resp.status, self.resp.reason, t_end - t_start),
                 req_id=self.req.id)
        return [self.resp.data]

    def _init_request_response(self):
        # set request id (simply increase number at each request)
        with self._lock_req_id:
            self._req_id += 1
            self.req.id = self._req_id

        # request variables
        self.req.environ = {}
        self.req.headers = {}
        self.req.method = None
        self.req.scheme = None
        self.req.path = None
        self.req.query = None
        self.req.url = None
        self.req.content_type = None
        self.req.charset = None
        self.req.length = 0
        self.req.data = None

        # response variables
        self.resp.httpconn = None
        self.resp.response = None
        self.resp.status = None
        self.resp.reason = None
        self.resp.headers = [
        ]  # http.client headers is a list of (header, value) tuples
        self.resp.content_type = None
        self.resp.data = None

    def _parse_request(self, environ):
        self.req.environ = environ
        self.log_debug('_parse_request', 'req.environ:')
        for k, v in sorted(environ.items(), key=lambda x: x[0]):
            self.log_debug('_parse_request', '   {}: {}'.format(k, v))

        # convert WSGI environ to a dict of HTTP headers:
        self.req.headers = {}
        for h in environ:
            if h.startswith('HTTP_'):
                self.req.headers[h[5:].replace('_', '-').lower()] = environ[h]

        # content-type is stored without 'HTTP_'
        # see RFC 2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
        content_type = environ.get('CONTENT_TYPE', None)
        if content_type:
            if ';' in content_type:
                content_type, charset = content_type.split(';', 1)
                self.req.content_type = content_type.strip()
                self.req.charset = charset.strip()
                ct = '{};{}'.format(self.req.content_type, self.req.charset)
            else:
                self.req.content_type = content_type.strip()
                ct = self.req.content_type
            self.req.headers['content-type'] = ct
        self.log_debug('_parse_request',
                       'req.content_type: {}'.format(self.req.content_type))
        self.log_debug('_parse_request',
                       'req.charset: {}'.format(self.req.charset))

        # content-length is also stored without 'HTTP_'
        self.req.headers['content-length'] = environ.get('CONTENT_LENGTH', 0)
        self.log_debug('_parse_request', 'req.headers:')
        for k, v in sorted(self.req.headers.items(), key=lambda x: x[0]):
            self.log_debug('_parse_request', '   {}: {}'.format(k, v))

        self.req.method = environ.get('REQUEST_METHOD', None)
        self.req.scheme = environ.get('wsgi.url_scheme', None)  # http
        self.req.path = environ.get('PATH_INFO', None)
        self.req.query = environ.get('QUERY_STRING', None)
        self.req.url = parse.urlunsplit(
            ('', '', self.req.path, self.req.query, ''))
        self.log_debug('_parse_request',
                       'req.method: {}'.format(self.req.method))
        self.log_debug('_parse_request',
                       'req.scheme: {}'.format(self.req.scheme))
        self.log_debug('_parse_request', 'req.path: {}'.format(self.req.path))
        self.log_debug('_parse_request',
                       'req.query: {}'.format(self.req.query))
        self.log_debug('_parse_request', 'req.url: {}'.format(self.req.url))

        if self.req.method not in ALLOWED_METHODS:
            # here I use 501 "not implemented" rather than 405 or 401, because it seems to be the
            # most appropriate response according to RFC 2616.
            # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            msg = 'Method "{}" not supported.'.format(self.req.method)
            self.set_response(501, reason=msg)
            self.log_debug('_parse_request', msg)

        if self.req.scheme not in ALLOWED_SCHEMES:
            msg = 'Scheme "{}" not supported.'.format(self.req.scheme)
            self.set_response(501, reason=msg)
            self.log_debug('_parse_request', msg)

    def _read_request_body(self):
        try:
            length = int(self.req.environ.get('CONTENT_LENGTH', 0))
        except ValueError:
            length = 0

        if length > 0:
            self.req.length = length
            input_ = self.req.environ.get('wsgi.input')
            if input_:
                self.req.data = input_.read(self.req.length)
                self.log_debug('_read_request_body',
                               'req.length: {}'.format(self.req.length))
                self.log_debug('_read_request_body',
                               'req.data: {} b'.format(len(self.req.data)))
                return

        self.log_debug('_read_request_body', 'No request body')

    def _send_request(self):
        self.log_debug('_send_request', 'starting')

        # forward a request received from a client to the server.
        # TO DO: handle connection errors
        self.resp.httpconn = client.HTTPConnection(self.redirect_address,
                                                   self.redirect_port)
        self.log_debug('_send_request', 'initialized connection')

        self.resp.httpconn.request(self.req.method,
                                   self.req.url,
                                   body=self.req.data,
                                   headers=self.req.headers)
        self.log_debug('_send_request', 'made request')

        # Get the response (but not the response body yet).
        self.resp.response = self.resp.httpconn.getresponse()
        self.log_debug('_send_request', 'got response')

    def _parse_response(self):
        self.resp.status = self.resp.response.status
        self.resp.reason = self.resp.response.reason
        self.log_debug(
            '_parse_response', 'resp: {} {}'.format(self.resp.status,
                                                    self.resp.reason))

        self.resp.headers = self.resp.response.getheaders()
        self.log_debug('_parse_response', 'resp.headers:')
        for e in sorted(self.resp.headers):
            self.log_debug('_parse_response', '   {}: {}'.format(e[0], e[1]))

        self.resp.content_type = self.resp.response.msg.get_content_type(
        ).lower()
        self.log_debug('_parse_response',
                       'resp.content_type: {}'.format(self.resp.content_type))

    def _read_response_body(self):
        # TO DO: check content-length?
        self.resp.data = self.resp.response.read()
        self.log_debug('_read_response_body',
                       'resp.data: {} b'.format(len(self.resp.data)))

    def _send_response(self, f_start_response):
        # Send the response with headers (but no body yet).
        status = '{} {}'.format(self.resp.status, self.resp.reason)
        f_start_response(status, self.resp.headers)
        self.log_debug('_send_response', 'status: {}'.format(status))
Ejemplo n.º 12
0
LOGGINGFORMAT = '%(asctime)-15s %(levelname)-8s %(name)-8s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=LOGGINGFORMAT, datefmt='%d-%b-%y %H:%M:%S')

mapp=Flask(__name__)
mapp.secret_key = os.getenv('tokenkey')


mapp.config['PROPAGATE_EXCEPTIONS'] = True

mapp.config['JWT_SECRET_KEY']=os.getenv('tokenkey')
mapp.config['JWT_DECODE_AUDIENCE']=os.getenv('usc')
#mapp.config['JWT_ENCODE_AUDIENCE']='testapp'
api.init_app(mapp)


jwt = JWTManager(mapp)
#register error handlers (inbuilt)
jwt._set_error_handler_callbacks(api)




#host multiple instances
d=PathInfoDispatcher({'/':mapp})
server=WSGIServer(('0.0.0.0',80),d)
#docker run -d -p 8088:8088 -t nginx
#start web server
try:
      server.start()
except KeyboardInterrupt:
      server.stop()
Ejemplo n.º 13
0
 def run(self):
     self._configure_flask_app()
     dispatcher = PathInfoDispatcher({"/": app})
     self.server = WSGIServer((self.host, self.port), dispatcher)
     self.server.start()
Ejemplo n.º 14
0
                        action='store_true',
                        help='Enable pudb post mortem debugging')
    parser.add_argument('--port',
                        type=int,
                        default=8034,
                        help='Port to listen for connections on')
    parser.add_argument('--host', default='0.0.0.0', help='Host to bind to')
    args = parser.parse_args()

    eliot.add_destination(eliot.FileDestination(sys.stderr))
    dbdir = args.database or tempfile.mkdtemp()
    try:
        with Database(dbdir) as db:
            the_app = app(db)
            if args.debug:
                the_app = debug_wrapper(the_app)
            httpd = Server((args.host, args.port), the_app)
            print('Serving "{dbdir}" on {args.host}:{args.port}'.format(
                dbdir=dbdir, args=args))
            httpd.safe_start()
    finally:
        if not args.database:
            shutil.rmtree(dbdir)

elif os.getenv(_DB_DIR_ENV_VAR):
    # To run from within a WSGI container like uWSGI, must configure DB dir via
    # env var PROFILOMATIC_DB_DIR
    eliot.add_destination(eliot.FileDestination(sys.stderr))
    db = Database(os.getenv(_DB_DIR_ENV_VAR))
    the_app = app(db)
Ejemplo n.º 15
0
    parser.add_argument('--certificate', nargs='?', help='TLS cert location')
    parser.add_argument('--key', nargs='?', help='TLS private key location')
    args = parser.parse_args()
    bp_perf = BPPerformance(classifiers, endpoint=args.nodeos_url)
    thread = threading.Thread(target=bp_perf.watch)
    thread.start()

    app = cache_middleware(60)(
        PathInfoDispatcher({
            '/': index(bp_perf),
            '/chart': transaction_chart(bp_perf),
            '/transactions.csv': transaction_csv(bp_perf),
            '/missed_slots': missed_slots(bp_perf),
            '/missed_slots_by_time': missed_slots_by_time(bp_perf),
            '/missed_slots.csv': missed_slots_csv(bp_perf),
            '/transactions_per_block': transactions_per_block(bp_perf)
        })
    )

    httpd = Server((args.host, args.port), app)

    if args.certificate:
        from cheroot.ssl.builtin import BuiltinSSLAdapter
        httpd.ssl_adapter = BuiltinSSLAdapter(args.certificate, args.key)

    try:
        print(f"Serving on {args.host}:{args.port}")
        httpd.safe_start()
    finally:
        bp_perf.stop()
Ejemplo n.º 16
0
 def listen(self):
     print("listening")
     self.server = WSGIServer(('0.0.0.0', 8000), webapp)
     # run(webapp, server=self.server)
     # run(webapp, server='bjoern', port=8000)
     self.server.start()
def _build_fake_ssm():
    app = DomainDispatcherApplication(create_backend_app, "ssm")
    httpd = Server((FAKE_SSM_HOST, FAKE_SSM_PORT), app)
    return ThreadedHttpd(httpd)
Ejemplo n.º 18
0
        cur_image = img
        with new_img_ev:
            new_img_ev.notify_all()
    with new_img_ev:
        new_img_ev.notify_all()


def stop_capture():
    global running
    running = False
    print('Stop Capturing...')


d = PathInfoDispatcher({'/': app})
server = None

if __name__ == '__main__':
    print('Usage: python cam.py [src] [width height]')

    server = Server(
        ('0.0.0.0', 8081 + (int(sys.argv[1]) if len(sys.argv) > 1 else 0)), d)

    t = threading.Thread(target=worker)
    t.start()
    try:
        server.start()
    except KeyboardInterrupt:
        stop_capture()
        server.stop()
    print('Terminated.')
Ejemplo n.º 19
0
# Denne fila kjører dere når dere vil gjøre serveren offentlig, eller generelt når dere vil teste den på en "skikkelig" server

from cheroot.wsgi import Server as WSGIServer
from cheroot.wsgi import PathInfoDispatcher as WSGIPathInfoDispatcher
from cheroot.ssl.builtin import BuiltinSSLAdapter

from app import app  # Importerer variabelen app fra filen app.py

my_app = WSGIPathInfoDispatcher({'/': app})

#                    'localhost'        privat, bare lokal
#                    '127.0.0.1'        privat, bare lokal
#                    '192.168.0.37'     offentlig, tilgjengelig for andre på nettverket (eksempel IPv4 addresse, sett inn din egen)
#                    '0.0.0.0'          offentlig, tilgjengelig for andre på nettverket (alle IP addressene til maskinen kan brukes for å nå siden)
server = WSGIServer(('0.0.0.0', 443), my_app)   # For å åpne denne serveren må en skrive https:// forran addressen

ssl_cert = "application/certificate/MyCertificate.crt"
ssl_key = "application/certificate/MyKey.key"
server.ssl_adapter =  BuiltinSSLAdapter(ssl_cert, ssl_key, None)

if __name__ == '__main__':
   try:
      server.start()
   except KeyboardInterrupt:  # Med dette så mener den ctrl+c
      server.stop()                                            # På linje 2070 i koden hvor stop() er definert har jeg satt inn: self.serving = False  # We don't care, fordi koden fryser der, er noe feil med cheroot
   except SystemExit:
      server.stop()                                            # På linje 2070 i koden hvor stop() er definert har jeg satt inn: self.serving = False  # We don't care, fordi koden fryser der, er noe feil med cheroot

# TLS test
# https://www.ssllabs.com/ssltest/index.html
Ejemplo n.º 20
0
    def _run(self) -> None:
        # Server and end points
        app = Flask(__name__)

        def _with_state_lock(
                req: Request, callback: Callable[[Request],
                                                 Response]) -> Response:

            if self.processing:
                return Response("Processing contribution. Retry later.", 503)

            self.state_lock.acquire()
            try:
                return callback(req)
            except Exception as ex:
                warning(f"error in request: {ex}")
                print(f"error in request: {ex}")
                return Response("error: {ex}", 400)
            finally:
                self.state_lock.release()

        @app.route('/contributors', methods=['GET'])
        def contributors() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._contributors)

        @app.route('/state', methods=['GET'])
        def state() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._state)

        @app.route('/challenge', methods=['GET'])
        def challenge() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._challenge)

        @app.route('/contribute', methods=['POST'])
        def contribute() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._contribute)

        def _tick() -> None:
            self.state_lock.acquire()
            try:
                self._update_state(time.time())
            finally:
                self.state_lock.release()

        interval = Interval(60.0, _tick)
        try:
            if not exists(self.config.tls_certificate):
                raise Exception(f"no cert file {self.config.tls_certificate}")
            if not exists(self.config.tls_key):
                raise Exception(f"no key file {self.config.tls_key}")

            listen_addr = ('0.0.0.0', self.config.port)
            self.server = WSGIServer(listen_addr,
                                     PathInfoDispatcher({'/': app}),
                                     numthreads=1)
            self.server.ssl_adapter = BuiltinSSLAdapter(
                self.config.tls_certificate, self.config.tls_key)
            print(f"Listening on {listen_addr} ...")
            self.server.start()
        finally:
            interval.stop()
            self.server = None
Ejemplo n.º 21
0
def main():
    # Set null device file path to stdout, stdin, stderr if they are None
    for _name in ('stdin', 'stdout', 'stderr'):
        if getattr(sys, _name) is None:
            setattr(sys, _name,
                    open(os.devnull, 'r' if _name == 'stdin' else 'w'))

    # Build Javascript files when DEBUG
    if config.DEBUG:
        from pgadmin.utils.javascript.javascript_bundler import \
            JavascriptBundler, JsState
        app.debug = True

        javascript_bundler = JavascriptBundler()
        javascript_bundler.bundle()
        if javascript_bundler.report() == JsState.NONE:
            app.logger.error(
                "Unable to generate javascript.\n"
                "To run the app ensure that yarn install command runs "
                "successfully"
            )
            raise RuntimeError("No generated javascript, aborting")

    # Output a startup message if we're not under the runtime and startup.
    # If we're under WSGI, we don't need to worry about this
    if not app.PGADMIN_RUNTIME:
        print(
            "Starting %s. Please navigate to http://%s:%d in your browser." %
            (config.APP_NAME, config.DEFAULT_SERVER,
             config.EFFECTIVE_SERVER_PORT)
        )
        sys.stdout.flush()
    else:
        # For unknown reason the runtime does not pass the environment
        # variables (i.e. PYTHONHOME, and PYTHONPATH), to the Python
        # sub-processes, leading to failures executing background processes.
        #
        # This has been observed only on windows. On *nix systems, it is likely
        # picking the system python environment, which is good enough to run
        # the process-executor.
        #
        # Setting PYTHONHOME launch them properly.
        from pgadmin.utils import IS_WIN

        if IS_WIN:
            os.environ['PYTHONHOME'] = sys.prefix

    # Initialize Flask service only once
    # If `WERKZEUG_RUN_MAIN` is None, i.e: app is initializing for first time
    # so set `use_reloader` = False, thus reload won't call.
    # Reference:
    # https://github.com/pallets/werkzeug/issues/220#issuecomment-11176538
    try:
        if config.DEBUG:
            app.run(
                host=config.DEFAULT_SERVER,
                port=config.EFFECTIVE_SERVER_PORT,
                use_reloader=(
                    (not app.PGADMIN_RUNTIME) and app.debug and
                    os.environ.get("WERKZEUG_RUN_MAIN") is not None
                ),
                threaded=config.THREADED_MODE
            )
        else:
            # Can use cheroot instead of flask dev server when not in debug
            # 10 is default thread count in CherootServer
            num_threads = 10 if config.THREADED_MODE else 1
            prod_server = CherootServer(
                (config.DEFAULT_SERVER, config.EFFECTIVE_SERVER_PORT),
                wsgi_app=app,
                numthreads=num_threads,
                server_name=config.APP_NAME)
            try:
                print("Using production server...")
                prod_server.start()
            except KeyboardInterrupt:
                prod_server.stop()

    except IOError:
        app.logger.error("Error starting the app server: %s", sys.exc_info())
Ejemplo n.º 22
0
class Server:
    """
    Server to coordinate an MPC, that serves challenges and accepts responses
    from contributors. Performs basic contribution management, ensuring
    contributions are from the correct party and submitted within the correct
    time window. MPC-specific operations (validation / challenge computation,
    etc) are performed by an IContributionHandler object.
    """
    def __init__(self, handler: IContributionHandler,
                 server_config: Configuration, server_dir: str):

        logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG)
        self.handler = handler
        self.config = server_config
        self.contributors: ContributorList
        self.upload_file = join(server_dir, UPLOAD_FILE)
        self.state_file_path = join(server_dir, STATE_FILE)
        self.state: ServerState
        self.processing = False

        # Try to open contributors file and state files. Perform sanity checks.
        with open(self.config.contributors_file, "r") as contributors_f:
            self.contributors = ContributorList.from_json(
                contributors_f.read())
        print(f"Contributors: {self.contributors}")
        self.contributors.ensure_validity()

        if exists(STATE_FILE):
            info(f"run_server: using existing state file: {STATE_FILE}")
            with open(STATE_FILE, "r") as state_f:
                self.state = ServerState.from_json(state_f.read())
        else:
            self.state = initial_server_state(self.config, self.contributors)
            self._write_state_file()
            self._notify_next_contributor()

        self.handler_finalized = self.state.have_all_contributions()
        self.state_lock = Lock()
        self.server: Optional[WSGIServer] = None
        self.thread = Thread(target=self._run)
        self.thread.start()

        while self.server is None or self.server.socket is None:
            info("Waiting for MPC server to start ...")
            time.sleep(1)
        port = self.server.socket.getsockname()[1]
        info(f"MPC server started (port: {port}).")

    def stop(self) -> None:
        if self.server is not None:
            self.server.stop()
            while self.server is not None:
                info("Waiting for server to stop ...")
                time.sleep(1.0)
            self.thread.join()
            info("Server stopped.")

    def _write_state_file(self) -> None:
        info(f"Writing state: {self.state_file_path}")
        with open(self.state_file_path, "w") as state_f:
            state_f.write(self.state.to_json())

    def _finalize_handler_once(self) -> None:
        if (not self.handler_finalized
            ) and self.state.have_all_contributions():
            self.handler_finalized = True
            self.handler.on_completed()

    def _update_state(self, now: float) -> None:
        if self.state.update(now, self.config.contribution_interval):
            self._on_next_contributor()

    def _on_contribution(self, now: float) -> None:
        next_deadline = now + self.config.contribution_interval
        self.state.received_contribution(next_deadline)
        self._on_next_contributor()

    def _on_next_contributor(self) -> None:
        self._finalize_handler_once()
        self._write_state_file()
        self._notify_next_contributor()

    def _notify_next_contributor(self) -> None:
        if self.state.have_all_contributions() or not self.config.email_server:
            return

        contributor_idx = self.state.next_contributor_index
        idx_readable = contributor_idx + 1
        total = self.state.num_contributors
        contributor = self.contributors[contributor_idx]
        try:
            _send_mail(
                email_server=self.config.email_server,
                email_address=cast(str, self.config.email_address),
                email_password_file=cast(str, self.config.email_password_file),
                to_addr=contributor.email,
                subject=
                f"[MPC] Your timeslot has begun ({idx_readable}/{total})",
                body="Please contribute to the MPC using your key: " +
                export_verification_key(contributor.verification_key))
        except Exception as ex:
            print(f"Failed to notify: {contributor.email}: {ex}")
            error(f"Failed to notify: {contributor.email}: {ex}")

    def _tick(self) -> None:
        if self.processing:
            info("_tick: processing. Ignoring tick")
            return

        self.state_lock.acquire()
        try:
            self._update_state(time.time())
        finally:
            self.state_lock.release()

    def _contributors(self, _req: Request) -> Response:
        return Response(self.contributors.to_json(), 200)

    def _state(self, _req: Request) -> Response:
        return Response(self.state.to_json(), 200)

    def _challenge(self, _req: Request) -> Response:
        # TODO: Require authentication here, to avoid DoS?
        self._update_state(time.time())
        if self.state.have_all_contributions():
            return Response("MPC is complete. No remaining challenges", 405)

        # Function used to stream the challenge file to the contributor.
        # Streaming is required to avoid timing out while writing the
        # full challenge file on the socket.
        def produce_file_chunks(path: str) -> Iterable[bytes]:
            with open(path, 'rb') as in_f:
                while True:
                    buf = in_f.read(SEND_CHUNK_SIZE)
                    if buf:
                        yield buf
                    else:
                        break

        challenge_file = self.handler.get_current_challenge_file(
            self.state.next_contributor_index)
        return Response(stream_with_context(
            produce_file_chunks(challenge_file)),
                        mimetype="application/octet-stream")

    def _contribute(self, req: Request) -> Response:
        # Basic request check
        headers = req.headers
        if 'Content-Length' not in headers:
            raise Exception("no Content-Length header")
        if 'Content-Type' not in headers:
            raise Exception("no Content-Type header")
        if 'X-MPC-Digest' not in headers:
            raise Exception("no X-MPC-Digest header")
        if 'X-MPC-Public-Key' not in headers:
            raise Exception("no X-MPC-Public-Key header")
        if 'X-MPC-Signature' not in headers:
            raise Exception("no X-MPC-Signature header")

        content_length = int(headers['Content-Length'])
        content_type = headers['Content-Type']
        digest = import_digest(headers['X-MPC-Digest'])
        pub_key_str = headers.get('X-MPC-Public-Key')
        sig = import_signature(headers['X-MPC-Signature'])

        boundary: str = ""
        for val in content_type.split("; "):
            if val.startswith("boundary="):
                boundary = val[len("boundary="):]
                break
        if not boundary:
            raise Exception("content-type contains no boundary")

        now = time.time()
        info(f"Contribute: current time = {now}")

        # Update state using the current time and return an error if
        # the MPC is no longer active.
        self._update_state(now)
        if self.state.have_all_contributions():
            return Response("MPC complete. No contributions accepted.", 405)

        # Check that the public key matches the expected next
        # contributor (as text, rather than relying on comparison
        # operators)
        contributor_idx = self.state.next_contributor_index
        contributor = self.contributors[contributor_idx]
        verification_key = contributor.verification_key
        expect_pub_key_str = export_verification_key(verification_key)
        if expect_pub_key_str != pub_key_str:
            return Response(
                f"Contributor key mismatch (contributor {contributor_idx})",
                403)

        # Check signature correctness. Ensures that the uploader is the owner
        # of the correct key BEFORE the costly file upload, taking as little
        # time as possible with remote hosts other than the next contributor.
        # (Note that this pre-upload check requires the digest to be passed in
        # the HTTP header.)
        if not verify(sig, verification_key, digest):
            return Response(
                f"Signature check failed (contributor {contributor_idx})", 403)

        # Accept the upload (if the digest matches). If successful,
        # pass the file to the handler.
        if exists(self.upload_file):
            remove(self.upload_file)
        handle_upload_request(content_length, boundary, digest,
                              cast(io.BufferedIOBase, request.stream),
                              self.upload_file)

        # Mark this instance as busy, launch a processing thread, and
        # return (releasing the state lock). Until the processing thread
        # has finished, further requests will just return 503.
        self.processing = True
        Thread(target=self._process_contribution).start()
        info(f"Launched thread for {self.state.next_contributor_index}" +
             f"/{self.state.num_contributors} contrib")
        return Response("OK", 200)

    def _process_contribution(self) -> None:
        try:
            info("_process_contribution(thread): processing contribution " +
                 f"{self.state.next_contributor_index}" +
                 f"/{self.state.num_contributors} (start={time.time()})")

            if self.handler.process_contribution(
                    self.state.next_contributor_index, self.upload_file):
                now = time.time()
                info(
                    f"_process_contribution(thread): SUCCESS (finished {now})")
                self._on_contribution(now)

            else:
                warning("_process_contribution(thread): contribution failed")
                return

        finally:
            try:
                # Remove the uploaded file if it is still there
                if exists(self.upload_file):
                    remove(self.upload_file)
            finally:
                # Mark server as ready again
                self.processing = False
                info("_process_contribution(thread): completed")

    def _run(self) -> None:
        # Server and end points
        app = Flask(__name__)

        def _with_state_lock(
                req: Request, callback: Callable[[Request],
                                                 Response]) -> Response:

            if self.processing:
                return Response("Processing contribution. Retry later.", 503)

            self.state_lock.acquire()
            try:
                return callback(req)
            except Exception as ex:
                warning(f"error in request: {ex}")
                print(f"error in request: {ex}")
                return Response("error: {ex}", 400)
            finally:
                self.state_lock.release()

        @app.route('/contributors', methods=['GET'])
        def contributors() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._contributors)

        @app.route('/state', methods=['GET'])
        def state() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._state)

        @app.route('/challenge', methods=['GET'])
        def challenge() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._challenge)

        @app.route('/contribute', methods=['POST'])
        def contribute() -> Response:  # pylint: disable=unused-variable
            return _with_state_lock(request, self._contribute)

        def _tick() -> None:
            self.state_lock.acquire()
            try:
                self._update_state(time.time())
            finally:
                self.state_lock.release()

        interval = Interval(60.0, _tick)
        try:
            if not exists(self.config.tls_certificate):
                raise Exception(f"no cert file {self.config.tls_certificate}")
            if not exists(self.config.tls_key):
                raise Exception(f"no key file {self.config.tls_key}")

            listen_addr = ('0.0.0.0', self.config.port)
            self.server = WSGIServer(listen_addr,
                                     PathInfoDispatcher({'/': app}),
                                     numthreads=1)
            self.server.ssl_adapter = BuiltinSSLAdapter(
                self.config.tls_certificate, self.config.tls_key)
            print(f"Listening on {listen_addr} ...")
            self.server.start()
        finally:
            interval.stop()
            self.server = None
Ejemplo n.º 23
0
from cheroot.wsgi import Server

from personal_website import create_app

import cherrypy

app = create_app()

cherrypy.tree.graft(app, '/')
cherrypy.config.update({'engine.autoreload.on': True})
server = Server(('127.0.0.1', 5000), cherrypy.tree, server_name='XFU/1.1.0')

if __name__ == '__main__':
    server.start()
Ejemplo n.º 24
0
 def cherrypy(app, address, **options):
     from cheroot.wsgi import Server as WSGIServer
     server = WSGIServer(address, app)
     server.start()
Ejemplo n.º 25
0
    if len(customers) == 0:
        return '[]'

    for customer in customers:
        result += json.dumps(customer.to_dict()) + ','

    result = result[:-1]

    return result + ']'


#Take a look on running the cherry server:
#   https://stackoverflow.com/questions/55366395/how-to-run-a-flask-app-on-cherrypy-wsgi-server-cheroot-using-https
#   https://www.digitalocean.com/community/tutorials/how-to-deploy-python-wsgi-applications-using-a-cherrypy-web-server-behind-nginx
#

if __name__ == '__main__':
    """Run the cherry server"""
    d = PathInfoDispatcher({'/': app})
    server = WSGIServer(('0.0.0.0', 8000), d)

    path = settings['sslPath']

    server.ssl_adapter = BuiltinSSLAdapter(certificate=f'{path}cert.pem',
                                           private_key=f'{path}privkey.pem')

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Ejemplo n.º 26
0
class BitcoindRpcProxy(object):
    """A proxy to the bitcoind RPC interface that can replace commands with arbitrary results.

    Starts a HTTP server in a thread, listens for incoming JSONRPC requests, and responds with
    either a mocked result or the result it got from bitcoind.
    This was taken and adapted from the C-lightning test suite.
    """
    def __init__(self, bitcoind_rpc_port, bitcoind_cookie_path, mocks):
        self.app = Flask("BitcoindProxy")
        self.app.add_url_rule(
            "/",
            "Entrypoint",
            self.proxy,
            methods=["POST"],
            defaults={"path": ""},
        )
        self.app.add_url_rule(
            "/<path:path>",
            "Entrypoint",
            self.proxy,
            methods=["POST"],
        )
        self.rpcport = reserve()
        # A mapping from method name to result as a dict.
        # Eventually, the results could be callable.
        self.mocks = mocks
        self.bitcoind_rpc_port = bitcoind_rpc_port
        self.bitcoind_cookie_path = bitcoind_cookie_path

        self.start()

    def __del__(self):
        self.stop()

    def _handle_request(self, r, path):
        """Handle a JSONRPC request {r} made to the HTTP endpoint {path} (to handle
        wallet paths)"""
        method = r["method"]

        # If we have set a mock for this method reply with that
        if method in self.mocks:
            return {"id": r["id"], "error": None, "result": self.mocks[method]}

        # Otherwise, just forward the request
        with open(self.bitcoind_cookie_path) as fd:
            authpair = fd.read()
        service_url = f"http://{authpair}@localhost:{self.bitcoind_rpc_port}/{path}"

        try:
            res = AuthServiceProxy(service_url, r["method"])(*r["params"])
            return {"result": res, "id": r["id"]}
        except JSONRPCException as e:
            return {"error": e.error, "id": r["id"]}

    def proxy(self, path):
        r = json.loads(request.data.decode("ASCII"))

        if isinstance(r, list):
            reply = [self._handle_request(subreq, path) for subreq in r]
        else:
            reply = self._handle_request(r, path)

        # \r\n because rust-jsonrpc expects it..
        response = Response(json.dumps(reply, cls=DecimalEncoder) + "\r\n")
        response.headers["Content-Type"] = "application/json"
        return response

    def start(self):
        self.server = Server(
            ("127.0.0.1", self.rpcport),
            self.app,
            numthreads=32,
            request_queue_size=10,
            accepted_queue_timeout=20,
            timeout=TIMEOUT * 2,
        )
        self.proxy_thread = threading.Thread(target=self.server.start)
        self.proxy_thread.daemon = True
        self.proxy_thread.start()

        # Now that bitcoind is running on the real rpcport, let's tell all
        # future callers to talk to the proxyport. We use the bind_addr as a
        # signal that the port is bound and accepting connections.
        while self.server.bind_addr[1] == 0:
            pass
        self.rpcport = self.server.bind_addr[1]

    def stop(self):
        self.server.stop()
        self.proxy_thread.join()
Ejemplo n.º 27
0
class BitcoinRpcProxy(object):
    def __init__(self, bitcoind, rpcport=0):
        self.app = Flask("BitcoindProxy")
        self.app.add_url_rule("/", "API entrypoint", self.proxy, methods=['POST'])
        self.rpcport = rpcport
        self.mocks = {}
        self.mock_counts = {}
        self.bitcoind = bitcoind
        self.request_count = 0

    def _handle_request(self, r):
        conf_file = os.path.join(self.bitcoind.bitcoin_dir, 'bitcoin.conf')
        brpc = BitcoinProxy(btc_conf_file=conf_file)
        method = r['method']

        # If we have set a mock for this method reply with that instead of
        # forwarding the request.
        if method in self.mocks and type(method) == dict:
            self.mock_counts[method] += 1
            return self.mocks[method]
        elif method in self.mocks and callable(self.mocks[method]):
            self.mock_counts[method] += 1
            return self.mocks[method](r)

        try:
            reply = {
                "result": brpc._call(r['method'], *r['params']),
                "error": None,
                "id": r['id']
            }
        except JSONRPCError as e:
            reply = {
                "error": e.error,
                "code": -32603,
                "id": r['id']
            }
        self.request_count += 1
        return reply

    def proxy(self):
        r = json.loads(request.data.decode('ASCII'))

        if isinstance(r, list):
            reply = [self._handle_request(subreq) for subreq in r]
        else:
            reply = self._handle_request(r)

        response = flask.Response(json.dumps(reply, cls=DecimalEncoder))
        response.headers['Content-Type'] = 'application/json'
        return response

    def start(self):
        d = PathInfoDispatcher({'/': self.app})
        self.server = Server(('0.0.0.0', self.rpcport), d)
        self.proxy_thread = threading.Thread(target=self.server.start)
        self.proxy_thread.daemon = True
        self.proxy_thread.start()

        # Now that bitcoind is running on the real rpcport, let's tell all
        # future callers to talk to the proxyport. We use the bind_addr as a
        # signal that the port is bound and accepting connections.
        while self.server.bind_addr[1] == 0:
            pass
        self.rpcport = self.server.bind_addr[1]
        logging.debug("BitcoinRpcProxy proxying incoming port {} to {}".format(self.rpcport, self.bitcoind.rpcport))

    def stop(self):
        self.server.stop()
        self.proxy_thread.join()
        logging.debug("BitcoinRpcProxy shut down after processing {} requests".format(self.request_count))

    def mock_rpc(self, method, response=None):
        """Mock the response to a future RPC call of @method

        The response can either be a dict with the full JSON-RPC response, or a
        function that returns such a response. If the response is None the mock
        is removed and future calls will be passed through to bitcoind again.

        """
        if response is not None:
            self.mocks[method] = response
            self.mock_counts[method] = 0
        elif method in self.mocks:
            del self.mocks[method]
Ejemplo n.º 28
0
    HOST = CONFIG.HOST
    PORT = CONFIG.PORT

    sign_alg = None
    digest_alg = None
    try:
        sign_alg = CONFIG.SIGN_ALG
    except AttributeError:
        pass
    try:
        digest_alg = CONFIG.DIGEST_ALG
    except AttributeError:
        pass
    ds.DefaultSignature(sign_alg, digest_alg)

    SRV = WSGIServer((HOST, PORT), application)

    _https = ""
    if CONFIG.HTTPS:
        https = "using HTTPS"
        # SRV.ssl_adapter = ssl_pyopenssl.pyOpenSSLAdapter(
        #     config.SERVER_CERT, config.SERVER_KEY, config.CERT_CHAIN)
        SRV.ssl_adapter = BuiltinSSLAdapter(CONFIG.SERVER_CERT,
                                            CONFIG.SERVER_KEY,
                                            CONFIG.CERT_CHAIN)

    logger.info("Server starting")
    print("IDP listening on %s:%s%s" % (HOST, PORT, _https))
    try:
        SRV.start()
    except KeyboardInterrupt:
Ejemplo n.º 29
0
 def cherrypy(app, address, **options):
     from cheroot.wsgi import Server as WSGIServer
     server = WSGIServer(address, app)
     server.start()
Ejemplo n.º 30
0
def cherrypy_server_runner(
    app,
    global_conf=None,
    host='127.0.0.1',
    port=None,
    ssl_pem=None,
    protocol_version=None,
    numthreads=None,
    server_name=None,
    max=None,
    request_queue_size=None,
    timeout=None,
):  # pragma: no cover
    """
    Entry point for CherryPy's WSGI server

    Serves the specified WSGI app via CherryPyWSGIServer.

    ``app``

        The WSGI 'application callable'; multiple WSGI applications
        may be passed as (script_name, callable) pairs.

    ``host``

        This is the ipaddress to bind to (or a hostname if your
        nameserver is properly configured).  This defaults to
        127.0.0.1, which is not a public interface.

    ``port``

        The port to run on, defaults to 8080 for HTTP, or 4443 for
        HTTPS. This can be a string or an integer value.

    ``ssl_pem``

        This an optional SSL certificate file (via OpenSSL) You can
        generate a self-signed test PEM certificate file as follows:

            $ openssl genrsa 1024 > host.key
            $ chmod 400 host.key
            $ openssl req -new -x509 -nodes -sha1 -days 365  \\
                          -key host.key > host.cert
            $ cat host.cert host.key > host.pem
            $ chmod 400 host.pem

    ``protocol_version``

        The protocol used by the server, by default ``HTTP/1.1``.

    ``numthreads``

        The number of worker threads to create.

    ``server_name``

        The string to set for WSGI's SERVER_NAME environ entry.

    ``max``

        The maximum number of queued requests. (defaults to -1 = no
        limit).

    ``request_queue_size``

        The 'backlog' argument to socket.listen(); specifies the
        maximum number of queued connections.

    ``timeout``

        The timeout in seconds for accepted connections.
    """
    is_ssl = False
    if ssl_pem:
        port = port or 4443
        is_ssl = True

    if not port:
        if ':' in host:
            host, port = host.split(':', 1)
        else:
            port = 8080
    bind_addr = (host, int(port))

    kwargs = {}
    for var_name in ('numthreads', 'max', 'request_queue_size', 'timeout'):
        var = locals()[var_name]
        if var is not None:
            kwargs[var_name] = int(var)

    try:
        from cheroot.wsgi import Server as WSGIServer
    except ImportError:
        from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer

    server = WSGIServer(bind_addr, app, server_name=server_name, **kwargs)
    if ssl_pem is not None:
        if PY2:
            server.ssl_certificate = server.ssl_private_key = ssl_pem
        else:
            # creates wsgiserver.ssl_builtin as side-effect
            try:
                from cheroot.server import get_ssl_adapter_class
                from cheroot.ssl.builtin import BuiltinSSLAdapter
            except ImportError:
                from cherrypy.wsgiserver import get_ssl_adapter_class
                from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter
            get_ssl_adapter_class()
            server.ssl_adapter = BuiltinSSLAdapter(ssl_pem, ssl_pem)

    if protocol_version:
        server.protocol = protocol_version

    try:
        protocol = is_ssl and 'https' or 'http'
        if host == '0.0.0.0':
            print('serving on 0.0.0.0:%s view at %s://127.0.0.1:%s' %
                  (port, protocol, port))
        else:
            print('serving on %s://%s:%s' % (protocol, host, port))
        server.start()
    except (KeyboardInterrupt, SystemExit):
        server.stop()

    return server
from cheroot.wsgi import Server
from wsgi_benchmark.handlers import app
from multiprocessing import cpu_count

if __name__ == '__main__':
    httpd = Server(('0.0.0.0', 8765), app, numthreads=cpu_count() * 10)
    httpd.safe_start()
Ejemplo n.º 32
0
def cherrypy_server_runner(
        app, global_conf=None, host='127.0.0.1', port=None,
        ssl_pem=None, protocol_version=None, numthreads=None,
        server_name=None, max=None, request_queue_size=None,
        timeout=None
        ):  # pragma: no cover
    """
    Entry point for CherryPy's WSGI server

    Serves the specified WSGI app via CherryPyWSGIServer.

    ``app``

        The WSGI 'application callable'; multiple WSGI applications
        may be passed as (script_name, callable) pairs.

    ``host``

        This is the ipaddress to bind to (or a hostname if your
        nameserver is properly configured).  This defaults to
        127.0.0.1, which is not a public interface.

    ``port``

        The port to run on, defaults to 8080 for HTTP, or 4443 for
        HTTPS. This can be a string or an integer value.

    ``ssl_pem``

        This an optional SSL certificate file (via OpenSSL) You can
        generate a self-signed test PEM certificate file as follows:

            $ openssl genrsa 1024 > host.key
            $ chmod 400 host.key
            $ openssl req -new -x509 -nodes -sha1 -days 365  \\
                          -key host.key > host.cert
            $ cat host.cert host.key > host.pem
            $ chmod 400 host.pem

    ``protocol_version``

        The protocol used by the server, by default ``HTTP/1.1``.

    ``numthreads``

        The number of worker threads to create.

    ``server_name``

        The string to set for WSGI's SERVER_NAME environ entry.

    ``max``

        The maximum number of queued requests. (defaults to -1 = no
        limit).

    ``request_queue_size``

        The 'backlog' argument to socket.listen(); specifies the
        maximum number of queued connections.

    ``timeout``

        The timeout in seconds for accepted connections.
    """
    is_ssl = False
    if ssl_pem:
        port = port or 4443
        is_ssl = True

    if not port:
        if ':' in host:
            host, port = host.split(':', 1)
        else:
            port = 8080
    bind_addr = (host, int(port))

    kwargs = {}
    for var_name in ('numthreads', 'max', 'request_queue_size', 'timeout'):
        var = locals()[var_name]
        if var is not None:
            kwargs[var_name] = int(var)

    try:
        from cheroot.wsgi import Server as WSGIServer
    except ImportError:
        from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer

    server = WSGIServer(bind_addr, app,
                        server_name=server_name, **kwargs)
    if ssl_pem is not None:
        if PY2:
            server.ssl_certificate = server.ssl_private_key = ssl_pem
        else:
            # creates wsgiserver.ssl_builtin as side-effect
            try:
                from cheroot.server import get_ssl_adapter_class
                from cheroot.ssl.builtin import BuiltinSSLAdapter
            except ImportError:
                from cherrypy.wsgiserver import get_ssl_adapter_class
                from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter
            get_ssl_adapter_class()
            server.ssl_adapter = BuiltinSSLAdapter(ssl_pem, ssl_pem)

    if protocol_version:
        server.protocol = protocol_version

    try:
        protocol = is_ssl and 'https' or 'http'
        if host == '0.0.0.0':
            print('serving on 0.0.0.0:%s view at %s://127.0.0.1:%s' %
                  (port, protocol, port))
        else:
            print('serving on %s://%s:%s' % (protocol, host, port))
        server.start()
    except (KeyboardInterrupt, SystemExit):
        server.stop()

    return server
Ejemplo n.º 33
0
def main():
    server = Server(("0.0.0.0", 8000), PathInfoDispatcher({"/": app}))
    server.start()
Ejemplo n.º 34
0
    HOST = CONFIG.HOST
    PORT = CONFIG.PORT

    sign_alg = None
    digest_alg = None
    try:
        sign_alg = CONFIG.SIGN_ALG
    except AttributeError:
        pass
    try:
        digest_alg = CONFIG.DIGEST_ALG
    except AttributeError:
        pass
    ds.DefaultSignature(sign_alg, digest_alg)

    SRV = WSGIServer((HOST, PORT), application)

    _https = ""
    if CONFIG.HTTPS:
        https = "using HTTPS"
        # SRV.ssl_adapter = ssl_pyopenssl.pyOpenSSLAdapter(
        #     config.SERVER_CERT, config.SERVER_KEY, config.CERT_CHAIN)
        SRV.ssl_adapter = BuiltinSSLAdapter(
            CONFIG.SERVER_CERT, CONFIG.SERVER_KEY, CONFIG.CERT_CHAIN
        )

    logger.info("Server starting")
    print("IDP listening on %s:%s%s" % (HOST, PORT, _https))
    try:
        SRV.start()
    except KeyboardInterrupt:
Ejemplo n.º 35
0
def make_healthcheck_server(host='0.0.0.0', port=8888):
    app = HealthcheckApplication()
    return Server((host, port), app)
Ejemplo n.º 36
0
from cheroot.wsgi import Server
from titan_app import app

server = Server(('0.0.0.0', 1010), app)

if __name__ == '__main__':
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Ejemplo n.º 37
0
    SP = Saml2Client(config_file="%s" % CNFBASE)

    POLICY = service_conf.POLICY

    add_urls()
    sign_alg = None
    digest_alg = None
    try:
        sign_alg = service_conf.SIGN_ALG
    except:
        pass
    try:
        digest_alg = service_conf.DIGEST_ALG
    except:
        pass
    ds.DefaultSignature(sign_alg, digest_alg)

    SRV = WSGIServer((HOST, PORT), application)

    _https = ""
    if service_conf.HTTPS:
        SRV.ssl_adapter = pyopenssl.pyOpenSSLAdapter(SERVER_CERT, SERVER_KEY,
                                                     CERT_CHAIN)
        _https = " using SSL/TLS"
    logger.info("Server starting")
    print("SP listening on %s:%s%s" % (HOST, PORT, _https))
    try:
        SRV.start()
    except KeyboardInterrupt:
        SRV.stop()
Ejemplo n.º 38
0
Archivo: sp.py Proyecto: SUNET/pysaml2
    POLICY = service_conf.POLICY

    add_urls()
    sign_alg = None
    digest_alg = None
    try:
        sign_alg = service_conf.SIGN_ALG
    except:
        pass
    try:
        digest_alg = service_conf.DIGEST_ALG
    except:
        pass
    ds.DefaultSignature(sign_alg, digest_alg)

    SRV = WSGIServer((HOST, PORT), ToBytesMiddleware(application))

    _https = ""
    if service_conf.HTTPS:
        SRV.ssl_adapter = pyopenssl.pyOpenSSLAdapter(
            SERVER_CERT, SERVER_KEY, CERT_CHAIN
        )
        _https = " using SSL/TLS"
    logger.info("Server starting")
    print("SP listening on %s:%s%s" % (HOST, PORT, _https))
    try:
        SRV.start()
    except KeyboardInterrupt:
        SRV.stop()
Ejemplo n.º 39
0
class WebServer:
  bind_hostname: str = None
  bind_port: str = None
  wsgi_applications: List[WebApp] = None
  server: WSGIServer = None

  @inject
  def __init__(self, bind_hostname: _WebserverBindHostnameKey,
               bind_port: _WebserverBindPortKey,
               wsgi_applications: List[WebApp]):
    self.bind_hostname = bind_hostname
    self.bind_port = bind_port
    self.wsgi_applications = wsgi_applications

    self.url_map = Map(
        [rule for app in self.wsgi_applications for rule in app.get_rules()])
    self.mount_map = {
        mount.mount_path: mount.app for app in self.wsgi_applications
        for mount in app.get_mounts()
    }

  def _handler(self, environ, start_response):
    adapter = self.url_map.bind_to_environ(environ)
    try:
      rule, values = adapter.match(return_rule=True)
    except HTTPException as e:
      return e.get_response(environ)(environ, start_response)

    def custom_start_response(status_, response_headers_, exc_info_=None):
      framework_webserver_endpoint_requests_z.labels(
          rule=rule.rule,
          method=environ['REQUEST_METHOD'],
          status=_get_status_code(status_)).inc()
      return start_response(status_, response_headers_, exc_info_)

    try:
      return rule.endpoint(environ, custom_start_response, **values)
    except HTTPException as e:
      return e.get_response(environ)(environ, custom_start_response)
    except Exception as e:
      log.exception('Unknown error occurred processing request')
      return InternalServerError(
          description='Unknown error occurred',
          original_exception=e).get_response(environ)(environ,
                                                      custom_start_response)

  def _server_thread(self):
    log.info(f'Starting webserver on {self.bind_hostname}:{self.bind_port}')
    app = self._handler
    app = DispatcherMiddleware(app, self.mount_map)
    app = WSGILogger(app)
    self.server = WSGIServer((self.bind_hostname, self.bind_port), app)
    self.server.stats['Enabled'] = True
    self.server.start()

  @execute()
  def run(self):
    t = Thread(target=self._server_thread, name='Webserver')
    t.start()
    return t

  @on_shutdown()
  def on_shutdown(self):
    log.info('Shutting down webserver')
    if self.server:
      self.server.stop()