Exemple #1
0
 def __init__(self, service, settings_or_xml):
     self.verbose = service.verbose
     if type(settings_or_xml) is StringType:
         settings = Config([])
         settings.loadFromString(settings_or_xml)
     else:
         settings = settings_or_xml
     self.properties = settings.headerGetProperties('/settings')[0]
     create = False
     for table in (self.properties['tourneys_schedule2prizes'],
                   self.properties['prizes']):
         service.db.db.query("SHOW TABLES LIKE '%s'" % table)
         result = service.db.db.store_result()
         if result.num_rows() <= 0:
             create = True
         del result
     if create:
         parameters = service.settings.headerGetProperties(
             "/server/database")[0]
         cmd = service.db.mysql_command + " --host='" + parameters[
             "host"] + "' --user='******' --password='******' '" + parameters[
                         "name"] + "' < " + self.properties["schema"]
         if self.verbose:
             self.message(cmd)
         os.system(cmd)
Exemple #2
0
def getSettings(path):
    settings = Config([''])
    settings.load(path)
    assert settings.headerGet("/server/@admin") in (
        "yes", "true"
    ), "set <server admin='yes'> in %s to enable this CGI. It means anyone with access to the CGI will be able to inject arbitrary SQL code in the MySQL server" % path
    return settings
Exemple #3
0
 def __init__(self, configfile, settingsfile):
     self.settings = Config([''])
     self.settings.load(settingsfile)
     self.shutting_down = False
     if self.settings.header:
         rcdir = self.configureDirectory()
         self.dirs = split(self.settings.headerGet("/settings/path"))
         self.config = Config([''] + self.dirs)
         self.config.load(configfile)
         self.verbose = self.settings.headerGetInt("/settings/@verbose")
         self.poker_factory = None
Exemple #4
0
 def __init__(self, configfile, settingsfile):
     self.settings = Config([''])
     self.settings.load(settingsfile)
     self.shutting_down = False
     if self.settings.header:
         rcdir = self.configureDirectory()
         self.dirs = split(self.settings.headerGet("/settings/path"))
         self.config = Config([''] + self.dirs)
         self.config.load(configfile)
         self.verbose = self.settings.headerGetInt("/settings/@verbose")
         self.poker_factory = None
Exemple #5
0
def run(settingsFile, configFile, dataDir):
    settings = Config([""])
    settings.load(settingsFile)
    config = Config([""])
    config.load(configFile)
    (host, port) = settings.headerGet("/settings/servers").split(" ")[0].split(":")
    client = DummyPokerClientFactory(settings, config, dataDir)
    reactor.connectTCP(host, int(port), client)
    reactor.run()
Exemple #6
0
 def __init__(self, service, settings_or_xml):
     self.verbose = service.verbose
     if type(settings_or_xml) is StringType:
         settings = Config([])
         settings.loadFromString(settings_or_xml)
     else:
         settings = settings_or_xml
     self.properties = settings.headerGetProperties('/settings')[0]
     create = False
     for table in ( self.properties['tourneys_schedule2prizes'], self.properties['prizes'] ):
         service.db.db.query("SHOW TABLES LIKE '%s'" % table)
         result = service.db.db.store_result()
         if result.num_rows() <= 0:
             create = True
         del result
     if create:
         parameters = service.settings.headerGetProperties("/server/database")[0]            
         cmd = service.db.mysql_command + " --host='" + parameters["host"] + "' --user='******' --password='******' '" + parameters["name"] + "' < " + self.properties["schema"]
         if self.verbose:
             self.message(cmd)
         os.system(cmd)
Exemple #7
0
class Main:
    "Poker gameplay"

    def __init__(self, configfile, settingsfile):
        self.settings = Config([''])
        self.settings.load(settingsfile)
        self.shutting_down = False
        if self.settings.header:
            rcdir = self.configureDirectory()
            self.dirs = split(self.settings.headerGet("/settings/path"))
            self.config = Config([''] + self.dirs)
            self.config.load(configfile)
            self.verbose = self.settings.headerGetInt("/settings/@verbose")
            self.poker_factory = None

    def configOk(self):
        return self.settings.header and self.config.header

    def shutdown(self, signal, stack_frame):
        self.shutting_down = True
        self.poker_factory.display.finish()
        reactor.stop()
        if self.verbose:
            print "received signal %s, exiting" % signal

    def configureDirectory(self):
        settings = self.settings
        if not settings.headerGet("/settings/user/@path"):
            print """
No <user path="user/settings/path" /> found in file %s.
Using current directory instead.
""" % settings.path
            return

        rcdir = expanduser(settings.headerGet("/settings/user/@path"))
        if not exists(rcdir):
            os.mkdir(rcdir)

    def run(self):
        settings = self.settings
        config = self.config

        signal.signal(signal.SIGINT, self.shutdown)
        if os.name == "posix":
            signal.signal(signal.SIGQUIT, self.shutdown)
        signal.signal(signal.SIGTERM, self.shutdown)

        poker_factory = None

        try:
            poker_factory = PokerClientFactory2D(settings=settings,
                                                 config=config)
            self.poker_factory = poker_factory

            if poker_factory.display:
                reactor.run()
            else:
                raise Exception, "PokerClientFactory2D instance has no display"
        except:
            print_exc()

        if poker_factory:
            if poker_factory.children:
                poker_factory.children.killall()
            if poker_factory.display:
                poker_factory.display.finish()
                poker_factory.display = None
def makeService(configuration):
    settings = Config([''])
    settings.load(configuration)
    if not settings.header:
        sys.exit(1)

    #
    # Setup Logging
    #
    root_logger = reflogging.RootLogger()
    root_logger.set_app_name('network')
    # accuire root log_level
    log_level = settings.headerGetInt('/server/logging/@log_level') or 30
    if 'LOG_LEVEL' in os.environ:
        log_level = int(os.environ['LOG_LEVEL'])
    if log_level not in (10, 20, 30, 40, 50):
        raise ValueError(
            "Unsupported log level %d. Supported log levels "
            "are DEBUG(10), INFO(20), WARNING(30), ERROR(40), CRITICAL(50)." % (log_level,)
        )
    root_logger.set_level(log_level)
    for node in settings.header.xpathEval('/server/logging/*'):
        _name = node.name
        _log_level_node = node.xpathEval('@log_level')
        _log_level = int(_log_level_node[0].content) if _log_level_node else 30
        if _name in ('stream', 'colorstream'):
            _output_node = node.xpathEval('@output')
            _output = _output_node[0].content if _output_node else 'stdout'
            if _output in ('stdout', '-'):
                _output = orig_stdout
            elif _output == 'stderr':
                _output = orig_stderr
            else:
                if _output.startswith('-'):
                    _output = open(_output[1:], 'w')
                else:
                    _output = open(_output, 'a')
            if _name == 'stream':
                _handler = StreamHandler(_output)
            elif _name == 'colorstream':
                _handler = ColorStreamHandler(_output)
        if _name == 'gelf':
            _host_node = node.xpathEval('@host')
            _port_node = node.xpathEval('@port')
            _host = _host_node[0].content if _host_node else 'localhost'
            _port = _port_node[0].content if _port_node else 12201
            _handler = GELFHandler(_host, _port)
        if _name == 'syslog':
            _handler = SyslogHandler('pokernetwork', 0)
        _handler.set_level(_log_level)
        root_logger.add_handler(_handler)

    serviceCollection = service.MultiService()
    poker_service = PokerService(settings)
    poker_service.setServiceParent(serviceCollection)

    poker_factory = IPokerFactory(poker_service)

    #
    # Poker protocol (with or without SSL)
    #
    tcp_port = settings.headerGetInt("/server/listen/@tcp")
    internet.TCPServer(tcp_port, poker_factory).setServiceParent(serviceCollection)

    tcp_ssl_port = settings.headerGetInt("/server/listen/@tcp_ssl")
    if HAS_OPENSSL and tcp_ssl_port:
        internet.SSLServer(tcp_ssl_port, poker_factory, SSLContextFactory(settings)).setServiceParent(serviceCollection)

    rest_site = PokerSite(settings, PokerRestTree(poker_service))

    #
    # HTTP (with or without SLL) that implements REST
    #
    rest_port = settings.headerGetInt("/server/listen/@rest")
    if rest_port:
        internet.TCPServer(rest_port, rest_site).setServiceParent(serviceCollection)

    rest_ssl_port = settings.headerGetInt("/server/listen/@rest_ssl")
    if HAS_OPENSSL and rest_ssl_port:
        internet.SSLServer(rest_ssl_port, rest_site, SSLContextFactory(settings)).setServiceParent(serviceCollection)

    http_site = server.Site(PokerTree(poker_service))

    #
    # HTTP (with or without SLL) that implements XML-RPC and SOAP
    #
    http_port = settings.headerGetInt("/server/listen/@http")
    if http_port:
        internet.TCPServer(http_port, http_site).setServiceParent(serviceCollection)

    http_ssl_port = settings.headerGetInt("/server/listen/@http_ssl")
    if HAS_OPENSSL and http_ssl_port:
        internet.SSLServer(http_ssl_port, http_site, SSLContextFactory(settings)).setServiceParent(serviceCollection)

    #
    # SSh twisted.conch.manhole
    #
    manhole_port = settings.headerGetInt("/server/listen/@manhole")
    if manhole_port:
        manhole_service = makeManholeService(manhole_port, {
            'poker_service': poker_service,
            'poker_site': rest_site
        })
        manhole_service.name = 'manhole'
        manhole_service.setServiceParent(serviceCollection)
        log.warn(
            "PokerManhole: manhole is useful for debugging, however, "
            "it can be a security risk and should be used only during debugging"
        )

    return serviceCollection
Exemple #9
0
def getSettings(path):
    settings = Config([''])
    settings.load(path)
    assert settings.headerGet("/server/@admin") in ( "yes", "true" ), "set <server admin='yes'> in %s to enable this CGI. It means anyone with access to the CGI will be able to inject arbitrary SQL code in the MySQL server" % path
    return settings
def makeService(configuration):
    settings = Config([''])
    settings.load(configuration)
    if not settings.header:
        sys.exit(1)

    serviceCollection = service.MultiService()

    poker_database = pokerdatabase.PokerDatabase(settings)
    poker_service = PokerService(settings, poker_database)
    poker_service.setServiceParent(serviceCollection)

    poker_factory = IPokerFactory(poker_service)

    #
    # Poker protocol (with or without SSL)
    #
    tcp_port = settings.headerGetInt("/server/listen/@tcp")
    internet.TCPServer(tcp_port, poker_factory
                       ).setServiceParent(serviceCollection)

    tcp_ssl_port = settings.headerGetInt("/server/listen/@tcp_ssl")
    if HAS_OPENSSL and tcp_ssl_port:
            internet.SSLServer(tcp_ssl_port, poker_factory, SSLContextFactory(settings)
                           ).setServiceParent(serviceCollection)

    rest_site = PokerSite(settings, PokerRestTree(poker_service))

    #
    # HTTP (with or without SLL) that implements REST
    #
    rest_port = settings.headerGetInt("/server/listen/@rest")
    if rest_port:
            internet.TCPServer(rest_port, rest_site
                               ).setServiceParent(serviceCollection)

    rest_ssl_port = settings.headerGetInt("/server/listen/@rest_ssl")
    if HAS_OPENSSL and rest_ssl_port:
            internet.SSLServer(rest_ssl_port, rest_site, SSLContextFactory(settings)
                               ).setServiceParent(serviceCollection)

    http_site = server.Site(PokerTree(poker_service))

    #
    # HTTP (with or without SLL) that implements XML-RPC and SOAP
    #
    http_port = settings.headerGetInt("/server/listen/@http")
    if http_port:
            internet.TCPServer(http_port, http_site
                               ).setServiceParent(serviceCollection)

    http_ssl_port = settings.headerGetInt("/server/listen/@http_ssl")
    if HAS_OPENSSL and http_ssl_port:
            internet.SSLServer(http_ssl_port, http_site, SSLContextFactory(settings)
                               ).setServiceParent(serviceCollection)

    # API
    api_ssl_port = settings.headerGetInt("/server/listen/@api_ssl")
    if HAS_OPENSSL and api_ssl_port:
        from pokernetwork import apiserver, apiservice
        secret_store = apiserver.APIUserStore(poker_database)
        api_service = apiservice.APIService(poker_service)
        api_site = server.Site(apiserver.Root(api_service, secret_store))
        internet.SSLServer(api_ssl_port, api_site, SSLContextFactory(settings)
                          ).setServiceParent(serviceCollection)
    else:
        print 'Could not create API service!'

    #
    # TELNET twisted.manhole (without SSL)
    #
    manhole_port = settings.headerGetInt("/server/listen/@manhole")
    if manhole_port:
	    manhole_factory = telnet.ShellFactory()
	    manhole_factory.namespace['poker_service'] = poker_service
	    manhole_factory.namespace['poker_site'] = rest_site
	    manhole_service = internet.TCPServer(manhole_port, manhole_factory, interface = '127.0.0.1')
	    manhole_service.setName("manhole")
	    manhole_service.setServiceParent(serviceCollection)
	    if settings.headerGetInt("/server/@verbose") > 0:
		    print  "PokerManhole: manhole is useful for debugging, use with telnet admin/admin, however, it can be a security risk and should be used only during debugging"

    return serviceCollection
Exemple #11
0
def makeService(configuration):
    settings = Config([''])
    settings.load(configuration)
    if not settings.header:
        sys.exit(1)

    serviceCollection = service.MultiService()
    poker_service = PokerService(settings)
    poker_service.setServiceParent(serviceCollection)

    poker_factory = IPokerFactory(poker_service)

    #
    # Poker protocol (with or without SSL)
    #
    tcp_port = settings.headerGetInt("/server/listen/@tcp")
    internet.TCPServer(tcp_port,
                       poker_factory).setServiceParent(serviceCollection)

    tcp_ssl_port = settings.headerGetInt("/server/listen/@tcp_ssl")
    if HAS_OPENSSL and tcp_ssl_port:
        internet.SSLServer(
            tcp_ssl_port, poker_factory,
            SSLContextFactory(settings)).setServiceParent(serviceCollection)

    rest_site = PokerSite(settings, PokerRestTree(poker_service))

    #
    # HTTP (with or without SLL) that implements REST
    #
    rest_port = settings.headerGetInt("/server/listen/@rest")
    if rest_port:
        internet.TCPServer(rest_port,
                           rest_site).setServiceParent(serviceCollection)

    rest_ssl_port = settings.headerGetInt("/server/listen/@rest_ssl")
    if HAS_OPENSSL and rest_ssl_port:
        internet.SSLServer(
            rest_ssl_port, rest_site,
            SSLContextFactory(settings)).setServiceParent(serviceCollection)

    http_site = server.Site(PokerTree(poker_service))

    #
    # HTTP (with or without SLL) that implements XML-RPC and SOAP
    #
    http_port = settings.headerGetInt("/server/listen/@http")
    if http_port:
        internet.TCPServer(http_port,
                           http_site).setServiceParent(serviceCollection)

    http_ssl_port = settings.headerGetInt("/server/listen/@http_ssl")
    if HAS_OPENSSL and http_ssl_port:
        internet.SSLServer(
            http_ssl_port, http_site,
            SSLContextFactory(settings)).setServiceParent(serviceCollection)

    #
    # TELNET twisted.manhole (without SSL)
    #
    manhole_port = settings.headerGetInt("/server/listen/@manhole")
    if manhole_port:
        manhole_factory = telnet.ShellFactory()
        manhole_factory.namespace['poker_service'] = poker_service
        manhole_factory.namespace['poker_site'] = rest_site
        manhole_service = internet.TCPServer(manhole_port,
                                             manhole_factory,
                                             interface='127.0.0.1')
        manhole_service.setName("manhole")
        manhole_service.setServiceParent(serviceCollection)
        if settings.headerGetInt("/server/@verbose") > 0:
            print "PokerManhole: manhole is useful for debugging, use with telnet admin/admin, however, it can be a security risk and should be used only during debugging"

    return serviceCollection
Exemple #12
0
def makeService(configuration):
    settings = Config([''])
    settings.load(configuration)
    if not settings.header:
        sys.exit(1)

    #
    # Setup Logging
    #
    root_logger = reflogging.RootLogger()
    root_logger.set_app_name('network')
    # acquire root log_level
    log_level = settings.headerGetInt('/server/logging/@log_level') or 30
    if 'LOG_LEVEL' in os.environ:
        log_level = int(os.environ['LOG_LEVEL'])
    if log_level not in (10, 20, 30, 40, 50):
        raise ValueError(
            "Unsupported log level %d. Supported log levels "
            "are DEBUG(10), INFO(20), WARNING(30), ERROR(40), CRITICAL(50)." % (log_level,)
        )
    root_logger.set_level(log_level)
    for node in settings.header.xpathEval('/server/logging/*'):
        _name = node.name
        _log_level_node = node.xpathEval('@log_level')
        _log_level = int(_log_level_node[0].content) if _log_level_node else 30
        if _name in ('stream', 'colorstream'):
            _output_node = node.xpathEval('@output')
            _output = _output_node[0].content if _output_node else 'stdout'
            if _output in ('stdout', '-'):
                _output = orig_stdout
            elif _output == 'stderr':
                _output = orig_stderr
            else:
                if _output.startswith('-'):
                    _output = open(_output[1:], 'w')
                else:
                    _output = open(_output, 'a')
            if _name == 'stream':
                _handler = StreamHandler(_output)
            elif _name == 'colorstream':
                _handler = ColorStreamHandler(_output)
        if _name == 'gelf':
            _host_node = node.xpathEval('@host')
            _port_node = node.xpathEval('@port')
            _host = _host_node[0].content if _host_node else 'localhost'
            _port = _port_node[0].content if _port_node else 12201
            _handler = GELFHandler(_host, _port)
        if _name == 'syslog':
            f = node.xpathEval('@facility')
            facility = {
                'user': syslog.LOG_USER,
                'daemon': syslog.LOG_DAEMON,
                'cron': syslog.LOG_CRON,
                'local0': syslog.LOG_LOCAL0,
                'local1': syslog.LOG_LOCAL1,
                'local2': syslog.LOG_LOCAL2,
                'local3': syslog.LOG_LOCAL3,
                'local4': syslog.LOG_LOCAL4,
                'local5': syslog.LOG_LOCAL5,
                'local6': syslog.LOG_LOCAL6,
                'local7': syslog.LOG_LOCAL7,
            }[f[0].content if f else 'user']
            _handler = SyslogHandler('pokernetwork', 0, facility=facility)
        _handler.set_level(_log_level)
        root_logger.add_handler(_handler)

    serviceCollection = service.MultiService()
    poker_service = PokerService(settings)
    poker_service.setServiceParent(serviceCollection)


    #
    # Poker protocol (with or without SSL)
    #
    poker_factory = IPokerFactory(poker_service)
    tcp_port = settings.headerGetInt("/server/listen/@tcp")
    internet.TCPServer(tcp_port, poker_factory).setServiceParent(serviceCollection)

    tcp_ssl_port = settings.headerGetInt("/server/listen/@tcp_ssl")
    if HAS_OPENSSL and tcp_ssl_port:
        internet.SSLServer(tcp_ssl_port, poker_factory, SSLContextFactory(settings)).setServiceParent(serviceCollection)

    #
    # msgpack protocol
    #
    msgpack_port = settings.headerGetInt("/server/listen/@msgpack")
    if msgpack_port:
        msgpack_factory = IPokerFactory(poker_service)
        msgpack_factory.setProtocol(ServerMsgpackProtocol)
        internet.TCPServer(msgpack_port, msgpack_factory).setServiceParent(serviceCollection)

    #
    # HTTP (with or without SLL) that implements REST
    #
    rest_site = PokerSite(settings, PokerRestTree(poker_service))
    rest_port = settings.headerGetInt("/server/listen/@rest")
    if rest_port:
        internet.TCPServer(rest_port, rest_site).setServiceParent(serviceCollection)

    rest_ssl_port = settings.headerGetInt("/server/listen/@rest_ssl")
    if HAS_OPENSSL and rest_ssl_port:
        internet.SSLServer(rest_ssl_port, rest_site, SSLContextFactory(settings)).setServiceParent(serviceCollection)

    #
    # SSh twisted.conch.manhole
    #
    manhole_port = settings.headerGetInt("/server/listen/@manhole")
    if manhole_port:
        manhole_service = makeManholeService(manhole_port, {
            'poker_service': poker_service,
            'poker_site': rest_site
        })
        manhole_service.name = 'manhole'
        manhole_service.setServiceParent(serviceCollection)

    #
    # Pub/Sub
    #
    pub_port = settings.headerGetInt("/server/listen/@pub")
    if pub_port:
        pub_service = internet.TCPServer(pub_port, PubService(poker_service))
        pub_service.name = 'pub'
        pub_service.setServiceParent(serviceCollection)

    return serviceCollection
Exemple #13
0
def makeService(configuration):
    settings = Config([''])
    settings.load(configuration)
    if not settings.header:
        sys.exit(1)

    #
    # Setup Logging
    #
    root_logger = reflogging.RootLogger()
    root_logger.set_app_name('network')
    # accuire root log_level
    log_level = settings.headerGetInt('/server/logging/@log_level') or 30
    if 'LOG_LEVEL' in os.environ:
        log_level = int(os.environ['LOG_LEVEL'])
    if log_level not in (10, 20, 30, 40, 50):
        raise ValueError(
            "Unsupported log level %d. Supported log levels "
            "are DEBUG(10), INFO(20), WARNING(30), ERROR(40), CRITICAL(50)." %
            (log_level, ))
    root_logger.set_level(log_level)
    for node in settings.header.xpathEval('/server/logging/*'):
        _name = node.name
        _log_level_node = node.xpathEval('@log_level')
        _log_level = int(_log_level_node[0].content) if _log_level_node else 30
        if _name in ('stream', 'colorstream'):
            _output_node = node.xpathEval('@output')
            _output = _output_node[0].content if _output_node else 'stdout'
            if _output in ('stdout', '-'):
                _output = orig_stdout
            elif _output == 'stderr':
                _output = orig_stderr
            else:
                if _output.startswith('-'):
                    _output = open(_output[1:], 'w')
                else:
                    _output = open(_output, 'a')
            if _name == 'stream':
                _handler = StreamHandler(_output)
            elif _name == 'colorstream':
                _handler = ColorStreamHandler(_output)
        if _name == 'gelf':
            _host_node = node.xpathEval('@host')
            _port_node = node.xpathEval('@port')
            _host = _host_node[0].content if _host_node else 'localhost'
            _port = _port_node[0].content if _port_node else 12201
            _handler = GELFHandler(_host, _port)
        if _name == 'syslog':
            _handler = SyslogHandler('pokernetwork', 0)
        _handler.set_level(_log_level)
        root_logger.add_handler(_handler)

    serviceCollection = service.MultiService()
    poker_service = PokerService(settings)
    poker_service.setServiceParent(serviceCollection)

    poker_factory = IPokerFactory(poker_service)

    #
    # Poker protocol (with or without SSL)
    #
    tcp_port = settings.headerGetInt("/server/listen/@tcp")
    internet.TCPServer(tcp_port,
                       poker_factory).setServiceParent(serviceCollection)

    tcp_ssl_port = settings.headerGetInt("/server/listen/@tcp_ssl")
    if HAS_OPENSSL and tcp_ssl_port:
        internet.SSLServer(
            tcp_ssl_port, poker_factory,
            SSLContextFactory(settings)).setServiceParent(serviceCollection)

    rest_site = PokerSite(settings, PokerRestTree(poker_service))

    #
    # HTTP (with or without SLL) that implements REST
    #
    rest_port = settings.headerGetInt("/server/listen/@rest")
    if rest_port:
        internet.TCPServer(rest_port,
                           rest_site).setServiceParent(serviceCollection)

    rest_ssl_port = settings.headerGetInt("/server/listen/@rest_ssl")
    if HAS_OPENSSL and rest_ssl_port:
        internet.SSLServer(
            rest_ssl_port, rest_site,
            SSLContextFactory(settings)).setServiceParent(serviceCollection)

    http_site = server.Site(PokerTree(poker_service))

    #
    # HTTP (with or without SLL) that implements XML-RPC and SOAP
    #
    http_port = settings.headerGetInt("/server/listen/@http")
    if http_port:
        internet.TCPServer(http_port,
                           http_site).setServiceParent(serviceCollection)

    http_ssl_port = settings.headerGetInt("/server/listen/@http_ssl")
    if HAS_OPENSSL and http_ssl_port:
        internet.SSLServer(
            http_ssl_port, http_site,
            SSLContextFactory(settings)).setServiceParent(serviceCollection)

    #
    # SSh twisted.conch.manhole
    #
    manhole_port = settings.headerGetInt("/server/listen/@manhole")
    if manhole_port:
        manhole_service = makeManholeService(manhole_port, {
            'poker_service': poker_service,
            'poker_site': rest_site
        })
        manhole_service.name = 'manhole'
        manhole_service.setServiceParent(serviceCollection)
        log.warn(
            "PokerManhole: manhole is useful for debugging, however, "
            "it can be a security risk and should be used only during debugging"
        )

    return serviceCollection
Exemple #14
0
class Main:
    "Poker gameplay"

    def __init__(self, configfile, settingsfile):
        self.settings = Config([''])
        self.settings.load(settingsfile)
        self.shutting_down = False
        if self.settings.header:
            rcdir = self.configureDirectory()
            self.dirs = split(self.settings.headerGet("/settings/path"))
            self.config = Config([''] + self.dirs)
            self.config.load(configfile)
            self.verbose = self.settings.headerGetInt("/settings/@verbose")
            self.poker_factory = None

    def configOk(self):
        return self.settings.header and self.config.header

    def shutdown(self, signal, stack_frame):
        self.shutting_down = True
        self.poker_factory.display.finish()
        reactor.stop()
        if self.verbose:
            print "received signal %s, exiting" % signal
            
    def configureDirectory(self):
        settings = self.settings
        if not settings.headerGet("/settings/user/@path"):
            print """
No <user path="user/settings/path" /> found in file %s.
Using current directory instead.
""" % settings.path
            return
        
        rcdir = expanduser(settings.headerGet("/settings/user/@path"))
        if not exists(rcdir):
            os.mkdir(rcdir)

    def run(self):
        settings = self.settings
        config = self.config

        signal.signal(signal.SIGINT, self.shutdown)
        if os.name == "posix":
            signal.signal(signal.SIGQUIT, self.shutdown)
        signal.signal(signal.SIGTERM, self.shutdown)

        poker_factory = None
        
        try:
            poker_factory = PokerClientFactory2D(settings = settings,
                                                 config = config)
            self.poker_factory = poker_factory

            if poker_factory.display:
                reactor.run()
            else:
                raise Exception, "PokerClientFactory2D instance has no display" 
        except:
            print_exc()

        if poker_factory:
            if poker_factory.children:
                poker_factory.children.killall()
            if poker_factory.display:
                poker_factory.display.finish()
                poker_factory.display = None
Exemple #15
0
def makeService(configuration):
    settings = Config([''])
    settings.load(configuration)
    if not settings.header:
        sys.exit(1)

    serviceCollection = service.MultiService()
    poker_service = PokerService(settings)
    poker_service.setServiceParent(serviceCollection)

    poker_factory = IPokerFactory(poker_service)

    #
    # Setup Logging
    #
    log_level = int(os.environ['LOG_LEVEL']) if \
        'LOG_LEVEL' in os.environ else \
        settings.headerGetInt("/server/@log_level")
    logger = logging.getLogger()
    handler = TwistedHandler(twisted_log.theLogPublisher)
    handler.setFormatter(SingleLineFormatter('[%(refs)s] %(message)s'))
    logger.addHandler(handler)
    if log_level:
        if log_level not in (10, 20, 30, 40, 50):
            raise ValueError("Unsupported log level %d. Supported log levels "
                "are DEBUG(10), INFO(20), WARNING(30), ERROR(40), CRITICAL(50)." % (log_level,)
            )
        logger.setLevel(log_level)
    else:
        logger.setLevel(logging.WARNING)

    #
    # Poker protocol (with or without SSL)
    #
    tcp_port = settings.headerGetInt("/server/listen/@tcp")
    internet.TCPServer(tcp_port, poker_factory).setServiceParent(serviceCollection)

    tcp_ssl_port = settings.headerGetInt("/server/listen/@tcp_ssl")
    if HAS_OPENSSL and tcp_ssl_port:
        internet.SSLServer(tcp_ssl_port, poker_factory, SSLContextFactory(settings)).setServiceParent(serviceCollection)

    rest_site = PokerSite(settings, PokerRestTree(poker_service))

    #
    # HTTP (with or without SLL) that implements REST
    #
    rest_port = settings.headerGetInt("/server/listen/@rest")
    if rest_port:
        internet.TCPServer(rest_port, rest_site).setServiceParent(serviceCollection)

    rest_ssl_port = settings.headerGetInt("/server/listen/@rest_ssl")
    if HAS_OPENSSL and rest_ssl_port:
        internet.SSLServer(rest_ssl_port, rest_site, SSLContextFactory(settings)).setServiceParent(serviceCollection)

    http_site = server.Site(PokerTree(poker_service))

    #
    # HTTP (with or without SLL) that implements XML-RPC and SOAP
    #
    http_port = settings.headerGetInt("/server/listen/@http")
    if http_port:
        internet.TCPServer(http_port, http_site).setServiceParent(serviceCollection)

    http_ssl_port = settings.headerGetInt("/server/listen/@http_ssl")
    if HAS_OPENSSL and http_ssl_port:
        internet.SSLServer(http_ssl_port, http_site, SSLContextFactory(settings)).setServiceParent(serviceCollection)

    #
    # SSh twisted.conch.manhole
    #
    manhole_port = settings.headerGetInt("/server/listen/@manhole")
    if manhole_port:
        makeManholeService(
            manhole_port,
            {
                'poker_service': poker_service,
                'poker_site': rest_site
            }
        ).setServiceParent(serviceCollection)
        log.warn("PokerManhole: manhole is useful for debugging, however, "
            "it can be a security risk and should be used only during debugging")

    return serviceCollection