Example #1
0
def main(argv):
    import getopt, imp

    def usage():
        print('usage: %s [-h host] [-p port] [-n name] module.class' % argv[0])
        return 100

    try:
        (opts, args) = getopt.getopt(argv[1:], 'h:p:n:')
    except getopt.GetoptError:
        return usage()
    host = ''
    port = 8080
    name = 'WebApp'
    for (k, v) in opts:
        if k == '-h': host = v
        elif k == '-p': port = int(v)
        elif k == '-n': name = v
    if not args: return usage()
    path = args.pop(0)
    module = imp.load_source('app', path)
    WebAppHandler.APP_CLASS = getattr(module, name)
    print('Listening %s:%d...' % (host, port))
    httpd = HTTPServer((host, port), WebAppHandler)
    httpd.serve_forever()
    return
Example #2
0
def main(ikey, skey, akey, host, port=8080):
    server = HTTPServer(('', port), RequestHandler)
    server.ikey = ikey
    server.skey = skey
    server.akey = akey
    server.host = host
    print("Visit the root URL with a 'user' argument, e.g.")
    print("'http://localhost:%d/?user=myname'." % port)
    server.serve_forever()
def start_webserver():
    """Start the webserver.
    """
    path = os.path.dirname(__file__)
    os.chdir(path)
    server_address = ("127.0.0.1", 0)
    httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
    print("http://127.0.0.1:%d" % httpd.server_port)
    httpd.serve_forever()
Example #4
0
def HelpServer():
	global server
	while 1:
		try:
			server = HTTPServer(('localhost', PORT_NUMBER), HelpHandler)
			server.serve_forever( poll_interval = 2 )
		except Exception as e:
			server = None
			time.sleep( 5 )
Example #5
0
def main(ikey, skey, akey, host, port=8080):
    server = HTTPServer(('', port), RequestHandler)
    server.ikey = ikey
    server.skey = skey
    server.akey = akey
    server.host = host
    print("Visit the root URL with a 'user' argument, e.g.")
    print("'http://localhost:%d/?user=myname'." % port)
    server.serve_forever()
class SimpleHTTPService(ServerCustomService):
    """Simple HTTP Honeycomb Service."""

    httpd = None

    def __init__(self, *args, **kwargs):
        super(SimpleHTTPService, self).__init__(*args, **kwargs)

    def alert(self, request):
        """Raise an alert."""
        params = {
            EVENT_TYPE_FIELD_NAME: SIMPLE_HTTP_ALERT_TYPE_NAME,
            ORIGINATING_IP_FIELD_NAME: request.client_address[0],
            ORIGINATING_PORT_FIELD_NAME: request.client_address[1],
            REQUEST_FIELD_NAME: " ".join([request.command, request.path]),
        }
        self.add_alert_to_queue(params)

    def on_server_start(self):
        """Initialize Service."""
        os.chdir(os.path.join(os.path.dirname(__file__), "www"))
        requestHandler = HoneyHTTPRequestHandler
        requestHandler.alert = self.alert
        requestHandler.logger = self.logger
        #requestHandler.server_version = self.service_args.get("version", DEFAULT_SERVER_VERSION)

        port = self.service_args.get("port", DEFAULT_PORT)
        threading = self.service_args.get("threading", False)
        if threading:
            self.httpd = ThreadingHTTPServer(("", port), requestHandler)
        else:
            self.httpd = HTTPServer(("", port), requestHandler)

        self.signal_ready()
        self.logger.info("Starting {}Simple HTTP service on port: {}".format(
            "Threading " if threading else "", port))
        self.httpd.serve_forever()

    def on_server_shutdown(self):
        """Shut down gracefully."""
        if self.httpd:
            self.httpd.shutdown()
            self.logger.info("Simple HTTP service stopped")
            self.httpd = None

    def test(self):
        """Test service alerts and return a list of triggered event types."""
        event_types = list()
        self.logger.debug("executing service test")
        requests.get("http://localhost:{}/".format(
            self.service_args.get("port", DEFAULT_PORT)))
        event_types.append(SIMPLE_HTTP_ALERT_TYPE_NAME)

        return event_types

    def __str__(self):
        return "Simple HTTP"
Example #7
0
class ProxyThread(threading.Thread):
    def __init__(self, token):
        self.proxy = HTTPServer(('localhost', 0), ProxyHandler)
        self.proxy._dcos_auth_token = token
        super(ProxyThread, self).__init__()

    def run(self):
        self.proxy.serve_forever()

    def port(self):
        return self.proxy.socket.getsockname()[1]
Example #8
0
class ProxyThread(threading.Thread):
    def __init__(self, token):
        self.proxy = HTTPServer(('localhost', 0), ProxyHandler)
        self.proxy._dcos_auth_token = token
        super(ProxyThread, self).__init__()

    def run(self):
        self.proxy.serve_forever()

    def port(self):
        return self.proxy.socket.getsockname()[1]
Example #9
0
def main(argv):
    args = argparser().parse_args(argv[1:])

    httpd = HTTPServer(('localhost', args.port), RestOATaggerHandler)
    info('REST-OA tagger service started')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    info('REST-OA tagger service stopped')
    httpd.server_close()
    return 0
Example #10
0
 def run(self):
     """
     Runs the server using Python's simple HTTPServer.
     TODO: make this multithreaded.
     """
     httpd = HTTPServer((self.host, self.port), self._Handler)
     sa = httpd.socket.getsockname()
     serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
     print(serve_message.format(host=sa[0], port=sa[1]))
     try:
         httpd.serve_forever()
     except KeyboardInterrupt:
         print("\nKeyboard interrupt received, exiting.")
         httpd.shutdown()
Example #11
0
def RunFakeServer(cbsd_sas_version, sas_sas_version, is_ecc, crl_index):
    FakeSasHandler.SetVersion(cbsd_sas_version, sas_sas_version)
    if is_ecc:
        assert ssl.HAS_ECDH
    server = HTTPServer((HOST, PORT), FakeSasHandler)

    ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    ssl_context.options |= ssl.CERT_REQUIRED

    # If CRLs were provided, then enable revocation checking.
    if crl_index is not None:
        ssl_context.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN

        try:
            crl_files = ParseCrlIndex(crl_index)
        except IOError as e:
            print("Failed to parse CRL index file %r: %s" % (crl_index, e))

        # https://tools.ietf.org/html/rfc5280#section-4.2.1.13 specifies that
        # CRLs MUST be DER-encoded, but SSLContext expects the name of a PEM-encoded
        # file, so we must convert it first.
        for f in crl_files:
            try:
                with file(f) as handle:
                    der = handle.read()
                    try:
                        crl = crypto.load_crl(crypto.FILETYPE_ASN1, der)
                    except crypto.Error as e:
                        print("Failed to parse CRL file %r as DER format: %s" %
                              (f, e))
                        return
                    with tempfile.NamedTemporaryFile() as tmp:
                        tmp.write(crypto.dump_crl(crypto.FILETYPE_PEM, crl))
                        tmp.flush()
                        ssl_context.load_verify_locations(cafile=tmp.name)
                print("Loaded CRL file: %r" % f)
            except IOError as e:
                print("Failed to load CRL file %r: %s" % (f, e))
                return

    ssl_context.load_verify_locations(cafile=CA_CERT)
    ssl_context.load_cert_chain(
        certfile=ECC_CERT_FILE if is_ecc else CERT_FILE,
        keyfile=ECC_KEY_FILE if is_ecc else KEY_FILE,
    )
    ssl_context.set_ciphers(':'.join(ECC_CIPHERS if is_ecc else CIPHERS))
    ssl_context.verify_mode = ssl.CERT_REQUIRED
    server.socket = ssl_context.wrap_socket(server.socket, server_side=True)
    print('Will start server at %s:%d, use <Ctrl-C> to stop.' % (HOST, PORT))
    server.serve_forever()
 def run(self):
     """
     Runs the server using Python's simple HTTPServer.
     TODO: make this multithreaded.
     """
     httpd = HTTPServer((self.host, self.port), self._Handler)
     sa = httpd.socket.getsockname()
     serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
     print(serve_message.format(host=sa[0], port=sa[1]))
     try:
         httpd.serve_forever()
     except KeyboardInterrupt:
         print("\nKeyboard interrupt received, exiting.")
         httpd.shutdown()
Example #13
0
def run_echo_server():
    class Handler(BaseHTTPRequestHandler):
        def _do(self):
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            parsed = urlparse(self.path)
            query_parameters = parse_qs(parsed.query)
            response = {
                'path': parsed.path,
                'headers': dict(self.headers)
            }
            if query_parameters:
                response['query_params'] = query_parameters
            try:
                try:  # py2
                    raw_content_len = self.headers.getheader('content-length')
                except AttributeError:  # py3
                    raw_content_len = self.headers.get('content-length')
                content_len = int(raw_content_len)
            except TypeError:
                content_len = 0
            if content_len:
                body = self.rfile.read(content_len)
                try:  # py3
                    body = body.decode('UTF-8')
                except AttributeError:  # py2
                    pass
                if body:
                    response['body'] = body
            print(response)
            encoded_json = json.dumps(response)
            self.wfile.write(b(encoded_json))
            return

        do_GET = _do
        do_POST = _do
        do_PUT = _do
        do_HEAD = _do
        do_PATCH = _do
        do_OPTIONS = _do
        do_DELETE = _do
        do_TRACE = _do
        do_CONNECT = _do

    server_address = ('', PORT)
    httpd = HTTPServer(server_address, Handler)
    httpd.serve_forever()
Example #14
0
def runServer():
    import six.moves.SimpleHTTPServer
    import six.moves.socketserver

    PORT = 8000
    try:
        # Create a web server and define the handler to manage the
        # incoming request
        server = HTTPServer(('', PORT), myHandler)
        print('Started httpserver on port ', PORT)

        # Wait forever for incoming htto requests
        server.serve_forever()

    except KeyboardInterrupt:
        print('^C received, shutting down the web server')
        server.socket.close()
Example #15
0
def run_echo_server():
    class Handler(BaseHTTPRequestHandler):
        def _do(self):
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            parsed = urlparse(self.path)
            query_parameters = parse_qs(parsed.query)
            response = {'path': parsed.path, 'headers': dict(self.headers)}
            if query_parameters:
                response['query_params'] = query_parameters
            try:
                try:  #py2
                    raw_content_len = self.headers.getheader('content-length')
                except AttributeError:  #py3
                    raw_content_len = self.headers.get('content-length')
                content_len = int(raw_content_len)
            except TypeError:
                content_len = 0
            if content_len:
                body = self.rfile.read(content_len)
                try:  #py3
                    body = body.decode('UTF-8')
                except AttributeError:  #py2
                    pass
                if body:
                    response['body'] = body
            print(response)
            encoded_json = json.dumps(response)
            self.wfile.write(b(encoded_json))
            return

        do_GET = _do
        do_POST = _do
        do_PUT = _do
        do_HEAD = _do
        do_PATCH = _do
        do_OPTIONS = _do
        do_DELETE = _do
        do_TRACE = _do
        do_CONNECT = _do

    server_address = ('', PORT)
    httpd = HTTPServer(server_address, Handler)
    httpd.serve_forever()
Example #16
0
def main():
    """Run the HTTP server."""
    # Redirect our service output to a log file.
    global log
    ensure_directory_exists(os.path.dirname(config.bing_test_service.log))
    filelog = logging.FileHandler(config.bing_test_service.log)
    log.addHandler(filelog)
    log.setLevel(logging.DEBUG)

    # To support service shutdown we need to create a PID file that is
    # understood by the Launchpad services framework.
    global service_name
    make_pidfile(service_name)

    host, port = get_service_endpoint()
    server = HTTPServer((host, port), BingRequestHandler)

    log.info("Starting HTTP Bing webservice server on port %s", port)
    server.serve_forever()
Example #17
0
class HttpImageServerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.keep_running = True

    def stop(self):
        log.debug("HttpImageServerThread:stop called")
        self.keep_running = False
        self.server.shutdown()

    def run(self):
        log.debug("HttpImageServerThread:started")
        self.server = HTTPServer(('', PORT_NUMBER), HttpImageHandler)

        while self.keep_running:
            self.server.serve_forever()
            xbmc.sleep(1000)

        log.debug("HttpImageServerThread:exiting")
Example #18
0
def main(argv):
    import getopt, imp
    def usage():
        print ('usage: %s [-h host] [-p port] [-n name] module.class' % argv[0])
        return 100
    try:
        (opts, args) = getopt.getopt(argv[1:], 'h:p:n:')
    except getopt.GetoptError:
        return usage()
    host = ''
    port = 8080
    name = 'WebApp'
    for (k, v) in opts:
        if k == '-h': host = v
        elif k == '-p': port = int(v)
        elif k == '-n': name = v
    if not args: return usage()
    path = args.pop(0)
    module = imp.load_source('app', path)
    WebAppHandler.APP_CLASS = getattr(module, name)
    print ('Listening %s:%d...' % (host,port))
    httpd = HTTPServer((host,port), WebAppHandler)
    httpd.serve_forever()
    return
        call_request_reader = ipc.FramedReader(self.rfile)
        call_request = call_request_reader.read_framed_message()
        resp_body = self.responder.respond(call_request)
        self.send_response(200)
        self.send_header('Content-Type', 'avro/binary')
        self.end_headers()
        resp_writer = ipc.FramedWriter(self.wfile)
        resp_writer.write_framed_message(resp_body)


if __name__ == '__main__':
    if (len(sys.argv) <= 1):
        raise ValueError("Usage: mock_tether_parent command")

    cmd = sys.argv[1].lower()
    if (sys.argv[1] == 'start_server'):
        if (len(sys.argv) == 3):
            port = int(sys.argv[2])
        else:
            raise ValueError("Usage: mock_tether_parent start_server port")

        SERVER_ADDRESS = (SERVER_ADDRESS[0], port)
        print("mock_tether_parent: Launching Server on Port: {0}".format(
            SERVER_ADDRESS[1]))

        # flush the output so it shows up in the parent process
        sys.stdout.flush()
        parent_server = HTTPServer(SERVER_ADDRESS, MockParentHandler)
        parent_server.allow_reuse_address = True
        parent_server.serve_forever()
            self.wfile.write(b'no auth header received')
            if DEBUG_LOG:
                print('no auth header received')

        elif self.get_header('Authorization') == ('Basic ' + encoded_password):
            self.do_HEAD()
            self.wfile.write(self.get_header('Authorization').encode('utf-8'))
            self.wfile.write(b'authenticated!')

            self.get_file("web_files", "adsl_modem.html")

            if DEBUG_LOG:
                print('auth header was correct:',
                      self.get_header('Authorization'))

        else:
            self.do_AUTHHEAD()
            self.wfile.write(self.get_header('Authorization').encode('utf-8'))
            self.wfile.write(b'not authenticated')

            if DEBUG_LOG:
                print('auth header was wrong:',
                      self.get_header('Authorization'), 'expected',
                      encoded_password)


if __name__ == "__main__":
    server_address = ('127.0.0.1', 8080)
    httpd = HTTPServer(server_address, TestWebServerHandler)
    httpd.serve_forever()
Example #21
0
            raise Exception("%s failed to start" % (appname, ))

    # Nothing failed, let's say we've started and then signal we're up by
    # serving the webserver.
    _print("Synapse started!")

    class WebHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.end_headers()
            self.wfile.write("OK")
            return

    PORT_NUMBER = int(args["--addr"].split(":")[1])
    server = HTTPServer(('', PORT_NUMBER), WebHandler)
    server.serve_forever()

except KeyboardInterrupt:
   pass
except BaseException as e:
    # Log a traceback for debug
    import traceback
    traceback.print_exc()

    # If we get told to shut down, log it
    _print("Told to quit because %s" % (repr(e)))

    # Otherwise, something bad has happened.
    sys.exit(1)
finally:
   subprocess.run(["pkill", "-9", "-f", "synapse.app"])
Example #22
0
import textwrap

from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer


class HelloRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path != '/':
            self.send_error(404, "Object Not Found")
            return
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        response_text = textwrap.dedent('''\
      <!DOCTYPE html>
      <head>
        <title>Hello World</title>
      </head>
      <body>
        <h2>Hello World</h2>
      </body>
      </html>
    ''')
        self.wfile.write(response_text.encode('utf-8'))


server_address = ('', 8000)
http = HTTPServer(server_address, HelloRequestHandler)
http.serve_forever()
Example #23
0
class OAuthHelper(object):

    params = OAuthHandler.params

    def __init__(self, reddit, term, config):

        self.term = term
        self.reddit = reddit
        self.config = config

        # Wait to initialize the server, we don't want to reserve the port
        # unless we know that the server needs to be used.
        self.server = None

        self.reddit.set_oauth_app_info(self.config['oauth_client_id'],
                                       self.config['oauth_client_secret'],
                                       self.config['oauth_redirect_uri'])

        # Reddit's mobile website works better on terminal browsers
        if not self.term.display:
            if '.compact' not in self.reddit.config.API_PATHS['authorize']:
                self.reddit.config.API_PATHS['authorize'] += '.compact'

    def authorize(self):

        self.params.update(state=None, code=None, error=None)

        # If we already have a token, request new access credentials
        if self.config.refresh_token:
            with self.term.loader('Logging in'):
                try:
                    self.reddit.refresh_access_information(
                        self.config.refresh_token)
                except (HTTPException, OAuthException) as e:
                    # Reddit didn't accept the refresh-token
                    # This appears to throw a generic 400 error instead of the
                    # more specific invalid_token message that it used to send
                    if isinstance(e, HTTPException):
                        if e._raw.status_code != 400:
                            # No special handling if the error is something
                            # temporary like a 5XX.
                            raise e

                    # Otherwise we know the token is bad, so we can remove it.
                    _logger.exception(e)
                    self.clear_oauth_data()
                    raise InvalidRefreshToken(
                        '       Invalid user credentials!\n'
                        'The cached refresh token has been removed')
            return

        state = uuid.uuid4().hex
        authorize_url = self.reddit.get_authorize_url(
            state, scope=self.config['oauth_scope'], refreshable=True)

        if self.server is None:
            address = ('', self.config['oauth_redirect_port'])
            self.server = HTTPServer(address, OAuthHandler)

        if self.term.display:
            # Open a background browser (e.g. firefox) which is non-blocking.
            # The server will block until it responds to its first request,
            # at which point we can check the callback params.
            OAuthHandler.shutdown_on_request = True
            with self.term.loader('Opening browser for authorization'):
                self.term.open_browser(authorize_url)
                self.server.serve_forever()
            if self.term.loader.exception:
                # Don't need to call server.shutdown() because serve_forever()
                # is wrapped in a try-finally that doees it for us.
                return
        else:
            # Open the terminal webbrowser in a background thread and wait
            # while for the user to close the process. Once the process is
            # closed, the iloop is stopped and we can check if the user has
            # hit the callback URL.
            OAuthHandler.shutdown_on_request = False
            with self.term.loader('Redirecting to reddit', delay=0):
                # This load message exists to provide user feedback
                time.sleep(1)

            thread = threading.Thread(target=self.server.serve_forever)
            thread.daemon = True
            thread.start()
            try:
                self.term.open_browser(authorize_url)
            except Exception as e:
                # If an exception is raised it will be seen by the thread
                # so we don't need to explicitly shutdown() the server
                _logger.exception(e)
                self.term.show_notification('Browser Error', style='Error')
            else:
                self.server.shutdown()
            finally:
                thread.join()

        if self.params['error'] == 'access_denied':
            self.term.show_notification('Denied access', style='Error')
            return
        elif self.params['error']:
            self.term.show_notification('Authentication error', style='Error')
            return
        elif self.params['state'] is None:
            # Something went wrong but it's not clear what happened
            return
        elif self.params['state'] != state:
            self.term.show_notification('UUID mismatch', style='Error')
            return

        with self.term.loader('Logging in'):
            info = self.reddit.get_access_information(self.params['code'])
        if self.term.loader.exception:
            return

        message = 'Welcome {}!'.format(self.reddit.user.name)
        self.term.show_notification(message)

        self.config.refresh_token = info['refresh_token']
        if self.config['persistent']:
            self.config.save_refresh_token()

    def clear_oauth_data(self):
        self.reddit.clear_authentication()
        self.config.delete_refresh_token()
Example #24
0
 def serve_forever(self, *args, **kwargs):
     self.listening_event.set()
     return HTTPServer.serve_forever(self, *args, **kwargs)
Example #25
0
def start_mock_server():
    server_address = ('127.0.0.1', 8545)
    httpd = HTTPServer(server_address, MockedTestrpc)
    httpd.serve_forever()
    print('served internal')
Example #26
0
 def serve_forever(self, *args, **kwargs):
     self.listening_event.set()
     return HTTPServer.serve_forever(self, *args, **kwargs)
class IPCamTrendnetTvIp100Service(ServerCustomService):
    """IP Cam TRENDnet TV-IP100 Service."""

    httpd = None

    def alert(self, request, event):
        """Raise an alert."""
        params = {
            EVENT_TYPE_FIELD_NAME: event,
            ORIGINATING_IP_FIELD_NAME: request.client_address[0],
            ORIGINATING_PORT_FIELD_NAME: request.client_address[1],
            REQUEST_FIELD_NAME: " ".join([request.command, request.path]),
        }
        self.add_alert_to_queue(params)

    def on_server_start(self):
        """Initialize Service."""
        os.chdir(os.path.join(os.path.dirname(__file__), "www"))
        requestHandler = TrendnetTVIP100CamRequestHandler
        requestHandler.alert = self.alert
        requestHandler.logger = self.logger
        requestHandler.server_version = self.service_args.get("version", DEFAULT_SERVER_VERSION)
        requestHandler.image_src_url = self.service_args.get("image_src_url", None)
        requestHandler.image_src_path = self.service_args.get("image_src_path", None)

        if requestHandler.image_src_path and requestHandler.image_src_url:
            raise ValueError("cannot process both image_src_path and image_src_url")

        if not requestHandler.image_src_path and not requestHandler.image_src_url:
            raise ValueError("image_src_path or image_src_url must be provided")

        port = self.service_args.get("port")
        threading = self.service_args.get("threading", False)
        if threading:
            self.httpd = ThreadingHTTPServer(("", port), requestHandler)
        else:
            self.httpd = HTTPServer(("", port), requestHandler)

        self.signal_ready()
        self.logger.info(
            "Starting {}IP Cam TRENDnet TV-IP100 service on port: {}".format("Threading " if threading else "", port))
        self.httpd.serve_forever()

    def on_server_shutdown(self):
        """Shut down gracefully."""
        if self.httpd:
            self.httpd.shutdown()
            self.logger.info("IP Cam TRENDnet TV-IP100 service stopped")
            self.httpd = None

    def test(self):
        """Test service alerts and return a list of triggered event types."""
        event_types = list()
        self.logger.debug("executing service test")
        # basic screen
        requests.get("http://localhost:{}".format(self.service_args.get("port")))

        # camera shot
        requests.get("http://localhost:{}{}".format(self.service_args.get("port"), CAMERA_IMAGE_PATH))

        # Invalid url
        requests.get("http://localhost:{}/asdasdad.html".format(self.service_args.get("port")))

        # / redirect
        requests.get("http://localhost:{}/".format(self.service_args.get("port")))

        # One alert for authorization attempt
        requests.get("http://localhost:{}/content.html".format(self.service_args.get("port")),
                     headers={"Authorization": "username=\"test\""})
        event_types.append(TRENDNET_ADMIN_ACCESS_EVENT)

        # And for POST
        requests.post("http://localhost:{}/content.html".format(self.service_args.get("port")), data={})
        event_types.append(TRENDNET_ADMIN_POST_ATTEMPT)
        return event_types

    def __str__(self):
        return "IP Cam TRENDnet TV-IP100"
Example #28
0
            raise Exception("%s failed to start" % (appname, ))

    # Nothing failed, let's say we've started and then signal we're up by
    # serving the webserver.
    _print("Synapse started!")

    class WebHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.end_headers()
            self.wfile.write("OK")
            return

    PORT_NUMBER = int(args["--addr"].split(":")[1])
    server = HTTPServer(('', PORT_NUMBER), WebHandler)
    server.serve_forever()

except KeyboardInterrupt:
    pass
except BaseException as e:
    # Log a traceback for debug
    import traceback
    traceback.print_exc()

    # If we get told to shut down, log it
    _print("Told to quit because %s" % (repr(e)))

    # Otherwise, something bad has happened.
    sys.exit(1)
finally:
    subprocess.run(["pkill", "-9", "-f", "synapse.app"])
Example #29
0
                resp_data['primary_calendar_events'] = (
                    primary_calendar_events.data)

            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(resp_data).encode('utf8'))


if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('app_id', type=str,
                        help='You can access app_id via https://developers.klo'
                             'udless.com/applications/*/details')
    parser.add_argument('api_key', type=str,
                        help='You can access api_key via https://developers.klo'
                             'udless.com/applications/*/details')
    parser.add_argument('--port', type=int, default=8020,
                        help='Port number to run the server, default to 8020')

    args = parser.parse_args()

    app_id = args.app_id
    api_key = args.api_key
    port = args.port

    print('Listening on localhost:%s' % port)
    httpd = HTTPServer(('', port), RequestHandler)
    httpd.serve_forever()
Example #30
0
def _multiproc_serve_path_via_http(hostname, path_to_serve_from,
                                   queue):  # pragma: no cover
    chpwd(path_to_serve_from)
    httpd = HTTPServer((hostname, 0), SilentHTTPHandler)
    queue.put(httpd.server_port)
    httpd.serve_forever()
Example #31
0
def _multiproc_serve_path_via_http(hostname, path_to_serve_from, queue): # pragma: no cover
    chpwd(path_to_serve_from)
    httpd = HTTPServer((hostname, 0), SilentHTTPHandler)
    queue.put(httpd.server_port)
    httpd.serve_forever()