示例#1
0
文件: server.py 项目: cscheid/forte
class Server(object):
    def __init__(self):
        opts = Opts()
        _configure_logging(opts)
        os.chdir(opts.document_root)
        opts.dispatcher = dispatch.Dispatcher(
            opts.websock_handlers,
            opts.scan_dir,
            opts.allow_handlers_outside_root_dir)
        self._ws_server = WebSocketServer(opts)
    def serve(self):
        self._ws_server.serve_forever()
示例#2
0
 def spawnWebSocketServer(self):
     args = ["-p", "8081", "-d", "/var/www/html/python/ws"]
     #only log all errors in the webservice if we are debuging, turn level to critical
     if (not config['dispatch.debug']):
         args.append("--log-level")
         args.append("critical")
     options, args = _parse_args_and_config(args=args)
     options.cgi_directories = []
     options.is_executable_method = None
     os.chdir(options.document_root)
     _configure_logging(options)
     server = WebSocketServer(options)
     server.serve_forever()
示例#3
0
def run(user_data = []):
    parser = optparse.OptionParser()
    parser.add_option('-H', '--server-host', '--server_host',
                      dest='server_host',
                      default='',
                      help='server hostname to listen to')
    parser.add_option('-V', '--validation-host', '--validation_host',
                      dest='validation_host',
                      default=None,
                      help='server hostname to validate in absolute path.')
    parser.add_option('-p', '--port', dest='port', type='int',
                      default=common.DEFAULT_WEB_SOCKET_PORT,
                      help='port to listen to')
    parser.add_option('-P', '--validation-port', '--validation_port',
                      dest='validation_port', type='int',
                      default=None,
                      help='server port to validate in absolute path.')
    parser.add_option('-w', '--websock-handlers', '--websock_handlers',
                      dest='websock_handlers',
                      default='.',
                      help='WebSocket handlers root directory.')
    parser.add_option('-m', '--websock-handlers-map-file',
                      '--websock_handlers_map_file',
                      dest='websock_handlers_map_file',
                      default=None,
                      help=('WebSocket handlers map file. '
                            'Each line consists of alias_resource_path and '
                            'existing_resource_path, separated by spaces.'))
    parser.add_option('-s', '--scan-dir', '--scan_dir', dest='scan_dir',
                      default=None,
                      help=('WebSocket handlers scan directory. '
                            'Must be a directory under websock_handlers.'))
    parser.add_option('-d', '--document-root', '--document_root',
                      dest='document_root', default='.',
                      help='Document root directory.')
    parser.add_option('-x', '--cgi-paths', '--cgi_paths', dest='cgi_paths',
                      default=None,
                      help=('CGI paths relative to document_root.'
                            'Comma-separated. (e.g -x /cgi,/htbin) '
                            'Files under document_root/cgi_path are handled '
                            'as CGI programs. Must be executable.'))
    parser.add_option('-t', '--tls', dest='use_tls', action='store_true',
                      default=False, help='use TLS (wss://)')
    parser.add_option('-k', '--private-key', '--private_key',
                      dest='private_key',
                      default='', help='TLS private key file.')
    parser.add_option('-c', '--certificate', dest='certificate',
                      default='', help='TLS certificate file.')
    parser.add_option('-l', '--log-file', '--log_file', dest='log_file',
                      default='', help='Log file.')
    parser.add_option('--log-level', '--log_level', type='choice',
                      dest='log_level', default='warn',
                      choices=['debug', 'info', 'warning', 'warn', 'error',
                               'critical'],
                      help='Log level.')
    parser.add_option('--log-max', '--log_max', dest='log_max', type='int',
                      default=_DEFAULT_LOG_MAX_BYTES,
                      help='Log maximum bytes')
    parser.add_option('--log-count', '--log_count', dest='log_count',
                      type='int', default=_DEFAULT_LOG_BACKUP_COUNT,
                      help='Log backup count')
    parser.add_option('--allow-draft75', dest='allow_draft75',
                      action='store_true', default=False,
                      help='Allow draft 75 handshake')
    parser.add_option('--strict', dest='strict', action='store_true',
                      default=False, help='Strictly check handshake request')
    parser.add_option('-q', '--queue', dest='request_queue_size', type='int',
                      default=_DEFAULT_REQUEST_QUEUE_SIZE,
                      help='request queue size')
    options = parser.parse_args()[0]
    
    os.chdir(options.document_root)

    standalone._configure_logging(options)

    # TODO(tyoshino): Clean up initialization of CGI related values. Move some
    # of code here to WebSocketRequestHandler class if it's better.
    options.cgi_directories = []
    options.is_executable_method = None
    if options.cgi_paths:
        options.cgi_directories = options.cgi_paths.split(',')
        if sys.platform in ('cygwin', 'win32'):
            cygwin_path = None
            # For Win32 Python, it is expected that CYGWIN_PATH
            # is set to a directory of cygwin binaries.
            # For example, websocket_server.py in Chromium sets CYGWIN_PATH to
            # full path of third_party/cygwin/bin.
            if 'CYGWIN_PATH' in os.environ:
                cygwin_path = os.environ['CYGWIN_PATH']
            util.wrap_popen3_for_win(cygwin_path)

            def __check_script(scriptpath):
                return util.get_script_interp(scriptpath, cygwin_path)

            options.is_executable_method = __check_script

    if options.use_tls:
        if not _HAS_OPEN_SSL:
            logging.critical('To use TLS, install pyOpenSSL.')
            sys.exit(1)
        if not options.private_key or not options.certificate:
            logging.critical(
                    'To use TLS, specify private_key and certificate.')
            sys.exit(1)

    if not options.scan_dir:
        options.scan_dir = options.websock_handlers
        
    try:
        # Share a Dispatcher among request handlers to save time for
        # instantiation.  Dispatcher can be shared because it is thread-safe.
        dump_reveived_data = True
        options.dispatcher = FunctionDispatcher(my_receive_function, user_data)
        standalone._print_warnings_if_any(options.dispatcher)

        server = WebSocketServer(options)
        server.serve_forever()
    except Exception, e:
        logging.critical('mod_pywebsocket: %s' % e)
        logging.critical('mod_pywebsocket: %s' % util.get_stack_trace())
        sys.exit(1)    
示例#4
0
    def create_server(self, server_data):
        port = self.options.port
        host = self.options.host

        logging.basicConfig()

        # Work around a bug in Mac OS 10.6. Spawning a WebSockets server
        # will result in a call to |getaddrinfo|, which fails with "nodename
        # nor servname provided" for localhost:0 on 10.6.
        # TODO(ricea): Remove this if no longer needed.
        if self.options.server_type == SERVER_WEBSOCKET and \
           host == "localhost" and \
           port == 0:
            host = "127.0.0.1"

        # Construct the subjectAltNames for any ad-hoc generated certificates.
        # As host can be either a DNS name or IP address, attempt to determine
        # which it is, so it can be placed in the appropriate SAN.
        dns_sans = None
        ip_sans = None
        ip = None
        try:
            ip = socket.inet_aton(host)
            ip_sans = [ip]
        except socket.error:
            pass
        if ip is None:
            dns_sans = [host]

        if self.options.server_type == SERVER_HTTP:
            if self.options.https:
                if not self.options.cert_and_key_file:
                    raise testserver_base.OptionError(
                        'server cert file not specified')
                if not os.path.isfile(self.options.cert_and_key_file):
                    raise testserver_base.OptionError(
                        'specified server cert file not found: ' +
                        self.options.cert_and_key_file + ' exiting...')
                pem_cert_and_key = open(self.options.cert_and_key_file,
                                        'r').read()

                for ca_cert in self.options.ssl_client_ca:
                    if not os.path.isfile(ca_cert):
                        raise testserver_base.OptionError(
                            'specified trusted client CA file not found: ' +
                            ca_cert + ' exiting...')

                server = HTTPSServer(
                    (host, port), TestPageHandler, pem_cert_and_key,
                    self.options.ssl_client_auth, self.options.ssl_client_ca,
                    self.options.ssl_client_cert_type,
                    self.options.tls_intolerant,
                    self.options.tls_intolerance_type,
                    self.options.alert_after_handshake,
                    self.options.simulate_tls13_downgrade,
                    self.options.simulate_tls12_downgrade,
                    self.options.tls_max_version)
                print('HTTPS server started on https://%s:%d...' %
                      (host, server.server_port))
            else:
                server = HTTPServer((host, port), TestPageHandler)
                print('HTTP server started on http://%s:%d...' %
                      (host, server.server_port))

            server.data_dir = self.__make_data_dir()
            server.file_root_url = self.options.file_root_url
            server_data['port'] = server.server_port
        elif self.options.server_type == SERVER_WEBSOCKET:
            # TODO(toyoshim): Remove following os.chdir. Currently this operation
            # is required to work correctly. It should be fixed from pywebsocket side.
            os.chdir(self.__make_data_dir())
            websocket_options = WebSocketOptions(host, port, '.')
            scheme = "ws"
            if self.options.cert_and_key_file:
                scheme = "wss"
                websocket_options.use_tls = True
                key_path = os.path.join(ROOT_DIR,
                                        self.options.cert_and_key_file)
                if not os.path.isfile(key_path):
                    raise testserver_base.OptionError(
                        'specified server cert file not found: ' +
                        self.options.cert_and_key_file + ' exiting...')
                websocket_options.private_key = key_path
                websocket_options.certificate = key_path

            if self.options.ssl_client_auth:
                websocket_options.tls_client_cert_optional = False
                websocket_options.tls_client_auth = True
                if len(self.options.ssl_client_ca) != 1:
                    raise testserver_base.OptionError(
                        'one trusted client CA file should be specified')
                if not os.path.isfile(self.options.ssl_client_ca[0]):
                    raise testserver_base.OptionError(
                        'specified trusted client CA file not found: ' +
                        self.options.ssl_client_ca[0] + ' exiting...')
                websocket_options.tls_client_ca = self.options.ssl_client_ca[0]
            print('Trying to start websocket server on %s://%s:%d...' %
                  (scheme, websocket_options.server_host,
                   websocket_options.port))
            server = WebSocketServer(websocket_options)
            print('WebSocket server started on %s://%s:%d...' %
                  (scheme, host, server.server_port))
            server_data['port'] = server.server_port
            websocket_options.use_basic_auth = self.options.ws_basic_auth
        elif self.options.server_type == SERVER_PROXY:
            ProxyRequestHandler.redirect_connect_to_localhost = \
                self.options.redirect_connect_to_localhost
            server = ThreadingHTTPServer((host, port), ProxyRequestHandler)
            print('Proxy server started on port %d...' % server.server_port)
            server_data['port'] = server.server_port
        elif self.options.server_type == SERVER_BASIC_AUTH_PROXY:
            ProxyRequestHandler.redirect_connect_to_localhost = \
                self.options.redirect_connect_to_localhost
            server = ThreadingHTTPServer((host, port),
                                         BasicAuthProxyRequestHandler)
            print('BasicAuthProxy server started on port %d...' %
                  server.server_port)
            server_data['port'] = server.server_port
        else:
            raise testserver_base.OptionError('unknown server type' +
                                              self.options.server_type)

        return server
示例#5
0
def run(user_data=[]):
    parser = optparse.OptionParser()
    parser.add_option('-H',
                      '--server-host',
                      '--server_host',
                      dest='server_host',
                      default='',
                      help='server hostname to listen to')
    parser.add_option('-V',
                      '--validation-host',
                      '--validation_host',
                      dest='validation_host',
                      default=None,
                      help='server hostname to validate in absolute path.')
    parser.add_option('-p',
                      '--port',
                      dest='port',
                      type='int',
                      default=common.DEFAULT_WEB_SOCKET_PORT,
                      help='port to listen to')
    parser.add_option('-P',
                      '--validation-port',
                      '--validation_port',
                      dest='validation_port',
                      type='int',
                      default=None,
                      help='server port to validate in absolute path.')
    parser.add_option('-w',
                      '--websock-handlers',
                      '--websock_handlers',
                      dest='websock_handlers',
                      default='.',
                      help='WebSocket handlers root directory.')
    parser.add_option('-m',
                      '--websock-handlers-map-file',
                      '--websock_handlers_map_file',
                      dest='websock_handlers_map_file',
                      default=None,
                      help=('WebSocket handlers map file. '
                            'Each line consists of alias_resource_path and '
                            'existing_resource_path, separated by spaces.'))
    parser.add_option('-s',
                      '--scan-dir',
                      '--scan_dir',
                      dest='scan_dir',
                      default=None,
                      help=('WebSocket handlers scan directory. '
                            'Must be a directory under websock_handlers.'))
    parser.add_option('-d',
                      '--document-root',
                      '--document_root',
                      dest='document_root',
                      default='.',
                      help='Document root directory.')
    parser.add_option('-x',
                      '--cgi-paths',
                      '--cgi_paths',
                      dest='cgi_paths',
                      default=None,
                      help=('CGI paths relative to document_root.'
                            'Comma-separated. (e.g -x /cgi,/htbin) '
                            'Files under document_root/cgi_path are handled '
                            'as CGI programs. Must be executable.'))
    parser.add_option('-t',
                      '--tls',
                      dest='use_tls',
                      action='store_true',
                      default=False,
                      help='use TLS (wss://)')
    parser.add_option('-k',
                      '--private-key',
                      '--private_key',
                      dest='private_key',
                      default='',
                      help='TLS private key file.')
    parser.add_option('-c',
                      '--certificate',
                      dest='certificate',
                      default='',
                      help='TLS certificate file.')
    parser.add_option('-l',
                      '--log-file',
                      '--log_file',
                      dest='log_file',
                      default='',
                      help='Log file.')
    parser.add_option(
        '--log-level',
        '--log_level',
        type='choice',
        dest='log_level',
        default='warn',
        choices=['debug', 'info', 'warning', 'warn', 'error', 'critical'],
        help='Log level.')
    parser.add_option('--log-max',
                      '--log_max',
                      dest='log_max',
                      type='int',
                      default=_DEFAULT_LOG_MAX_BYTES,
                      help='Log maximum bytes')
    parser.add_option('--log-count',
                      '--log_count',
                      dest='log_count',
                      type='int',
                      default=_DEFAULT_LOG_BACKUP_COUNT,
                      help='Log backup count')
    parser.add_option('--allow-draft75',
                      dest='allow_draft75',
                      action='store_true',
                      default=False,
                      help='Allow draft 75 handshake')
    parser.add_option('--strict',
                      dest='strict',
                      action='store_true',
                      default=False,
                      help='Strictly check handshake request')
    parser.add_option('-q',
                      '--queue',
                      dest='request_queue_size',
                      type='int',
                      default=_DEFAULT_REQUEST_QUEUE_SIZE,
                      help='request queue size')
    options = parser.parse_args()[0]

    os.chdir(options.document_root)

    standalone._configure_logging(options)

    # TODO(tyoshino): Clean up initialization of CGI related values. Move some
    # of code here to WebSocketRequestHandler class if it's better.
    options.cgi_directories = []
    options.is_executable_method = None
    if options.cgi_paths:
        options.cgi_directories = options.cgi_paths.split(',')
        if sys.platform in ('cygwin', 'win32'):
            cygwin_path = None
            # For Win32 Python, it is expected that CYGWIN_PATH
            # is set to a directory of cygwin binaries.
            # For example, websocket_server.py in Chromium sets CYGWIN_PATH to
            # full path of third_party/cygwin/bin.
            if 'CYGWIN_PATH' in os.environ:
                cygwin_path = os.environ['CYGWIN_PATH']
            util.wrap_popen3_for_win(cygwin_path)

            def __check_script(scriptpath):
                return util.get_script_interp(scriptpath, cygwin_path)

            options.is_executable_method = __check_script

    if options.use_tls:
        if not _HAS_OPEN_SSL:
            logging.critical('To use TLS, install pyOpenSSL.')
            sys.exit(1)
        if not options.private_key or not options.certificate:
            logging.critical(
                'To use TLS, specify private_key and certificate.')
            sys.exit(1)

    if not options.scan_dir:
        options.scan_dir = options.websock_handlers

    try:
        # Share a Dispatcher among request handlers to save time for
        # instantiation.  Dispatcher can be shared because it is thread-safe.
        dump_reveived_data = True
        options.dispatcher = FunctionDispatcher(my_receive_function, user_data)
        standalone._print_warnings_if_any(options.dispatcher)

        server = WebSocketServer(options)
        server.serve_forever()
    except Exception, e:
        logging.critical('mod_pywebsocket: %s' % e)
        logging.critical('mod_pywebsocket: %s' % util.get_stack_trace())
        sys.exit(1)