Example #1
0
 def __new__(typ, value):
     value = value.lower()
     try:
         return __import__('xcap.interfaces.backend.%s' % value, globals(), locals(), [''])
     except (ImportError, AssertionError), e:
         log.fatal("Cannot load '%s' backend module: %s" % (value, str(e)))
         sys.exit(1)
Example #2
0
 def __init__(self):
     main_config_file = process.config_file(Config.config_file)
     if main_config_file is None:
         raise RuntimeError("Cannot find the radius configuration file: `%s'" % Config.config_file)
     try:
         config = dict(line.rstrip("\n").split(None, 1) for line in open(main_config_file) if len(line.split(None, 1)) == 2 and not line.startswith("#"))
         secrets = dict(line.rstrip("\n").split(None, 1) for line in open(config["servers"]) if len(line.split(None, 1)) == 2 and not line.startswith("#"))
         server = config["acctserver"]
         try:
             server, acctport = server.split(":")
             acctport = int(acctport)
         except ValueError:
             acctport = 1813
         secret = secrets[server]
         dicts = [RadiusDictionaryFile(config["dictionary"])]
         if Config.additional_dictionary:
             additional_dictionary = process.config_file(Config.additional_dictionary)
             if additional_dictionary:
                 dicts.append(RadiusDictionaryFile(additional_dictionary))
             else:
                 log.warn("Could not load additional RADIUS dictionary file: `%s'" % Config.additional_dictionary)
         raddict = pyrad.dictionary.Dictionary(*dicts)
         timeout = int(config["radius_timeout"])
         retries = int(config["radius_retries"])
     except Exception, e:
         log.fatal("cannot read the RADIUS configuration file")
         raise
Example #3
0
def main():
    name = 'ip-streamer'
    fullname = 'IP Streamer v2'
    version = ipstreamer.__version__
    runtime_directory = '/var/run/ip-streamer'
    system_config_directory = '/etc/vice'
    default_pid = os.path.join(runtime_directory, 'server.pid')
    default_config = ipstreamer.cfg_filename if os.path.isfile(ipstreamer.cfg_filename) else os.path.join(system_config_directory, ipstreamer.cfg_filename)

    parser = argparse.ArgumentParser(description='VICE ip streamer to control mumudvb.')
    parser.add_argument('--version', action='version', version='%s %s' % (fullname, version))
    parser.add_argument('--no-fork', action='store_false', dest='fork', default=True, help='run the process in the foreground')
    parser.add_argument('-c', '--config-file', dest='config_file', default=default_config, help='configuration file', metavar='FILE')
    parser.add_argument('-p', '--pid', dest='pid_file', default=default_pid, help='PID file', metavar='FILE')
    parser.add_argument('-d', '--debug', help='Run in debug mode', action='store_true', default=False, dest='debug')
    args = parser.parse_args()
    debug = args.debug

    path, cfg_file = os.path.split(args.config_file)
    if path:
        system_config_directory = path

    process.system_config_directory = system_config_directory
    ipstreamer.cfg_filename = process.config_file(cfg_file)

    # when run in foreground, do not require root access because of PID file in /var/run
    if args.fork:
        try:
            process.runtime_directory = runtime_directory
            process.daemonize(args.pid_file)
        except ProcessError, e:
            log.fatal("Cannot start %s: %s" % (fullname, e))
            sys.exit(1)
        log.start_syslog(name)
Example #4
0
 def _start_https(self, reactor):
     from gnutls.interfaces.twisted import X509Credentials
     cert, pKey = TLSConfig.certificate, TLSConfig.private_key
     if cert is None or pKey is None:
         log.fatal("the TLS certificates or the private key could not be loaded")
         sys.exit(1)
     credentials = X509Credentials(cert, pKey)
     reactor.listenTLS(ServerConfig.root.port, HTTPFactory(self.site), credentials, interface=ServerConfig.address)
     log.msg("TLS started")
Example #5
0
    def __init__(self):
        self.connections = []
        if not RatingConfig.address:
            try:
                RatingConfig.address = RatingEngineAddresses('cdrtool.' + socket.gethostbyaddr(host.default_ip)[0].split('.', 1)[1])
            except Exception:
                log.fatal('Cannot resolve hostname %s' % ('cdrtool.' + socket.gethostbyaddr(host.default_ip)[0].split('.', 1)[1]))

        for engine in RatingConfig.address:
            self.connections.append(RatingEngine(engine))
Example #6
0
 def _start_https(self, reactor):
     from gnutls.interfaces.twisted import X509Credentials
     from gnutls.connection import TLSContext, TLSContextServerOptions
     cert, pKey = TLSConfig.certificate, TLSConfig.private_key
     if cert is None or pKey is None:
         log.fatal("the TLS certificates or the private key could not be loaded")
         sys.exit(1)
     credentials = X509Credentials(cert, pKey)
     tls_context = TLSContext(credentials, server_options=TLSContextServerOptions(certificate_request=None))
     reactor.listenTLS(ServerConfig.root.port, HTTPFactory(self.site), tls_context, interface=ServerConfig.address)
     log.msg("TLS started")
Example #7
0
 def __init__(self):
     main_config_file = process.config_file(RadiusConfig.config_file)
     if main_config_file is None:
         raise RuntimeError(
             "Cannot find the radius configuration file: `%s'" %
             RadiusConfig.config_file)
     try:
         config = dict(
             line.rstrip("\n").split(None, 1)
             for line in open(main_config_file)
             if len(line.split(None, 1)) == 2 and not line.startswith("#"))
         secrets = dict(
             line.rstrip("\n").split(None, 1)
             for line in open(config["servers"])
             if len(line.split(None, 1)) == 2 and not line.startswith("#"))
         server = config["acctserver"]
         try:
             server, acctport = server.split(":")
             acctport = int(acctport)
         except ValueError:
             acctport = 1813
         secret = secrets[server]
         dicts = [RadiusDictionaryFile(config["dictionary"])]
         if RadiusConfig.additional_dictionary:
             additional_dictionary = process.config_file(
                 RadiusConfig.additional_dictionary)
             if additional_dictionary:
                 dicts.append(RadiusDictionaryFile(additional_dictionary))
             else:
                 log.warn(
                     "Could not load additional RADIUS dictionary file: `%s'"
                     % RadiusConfig.additional_dictionary)
         raddict = pyrad.dictionary.Dictionary(*dicts)
         timeout = int(config["radius_timeout"])
         retries = int(config["radius_retries"])
     except Exception:
         log.fatal("cannot read the RADIUS configuration file")
         raise
     pyrad.client.Client.__init__(self, server, 1812, acctport, secret,
                                  raddict)
     self.timeout = timeout
     self.retries = retries
     if "bindaddr" in config and config["bindaddr"] != "*":
         self.bind((config["bindaddr"], 0))
     EventQueue.__init__(self, self.do_accounting)
Example #8
0
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'Server'

    address = ConfigSetting(type=IPAddress, value='0.0.0.0')
    root = ConfigSetting(type=XCAPRootURI, value=None)
    backend = ConfigSetting(type=Backend, value=None)

class TLSConfig(ConfigSection):
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'TLS'

    certificate = ConfigSetting(type=Certificate, value=None)
    private_key = ConfigSetting(type=PrivateKey, value=None)

if ServerConfig.root is None:
    log.fatal("the XCAP root URI is not defined")
    sys.exit(1)

if ServerConfig.backend is None:
    log.fatal("OpenXCAP needs a backend to be specified in order to run")
    sys.exit(1)


# Increase the system limit for the maximum number of open file descriptors
try:
    _resource.setrlimit(_resource.RLIMIT_NOFILE, (99999, 99999))
except ValueError:
    log.warn("Could not raise open file descriptor limit")


class XCAPRoot(resource.Resource, resource.LeafResource):
Example #9
0
            sys.exit(1)
        except Exception, e:
            log.err()
            sys.exit(1)


class ServerConfig(ConfigSection):
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'Server'

    backend = ConfigSetting(type=Backend, value=None)
    disabled_applications = ConfigSetting(type=StringList, value=[])
    document_validation = True

if ServerConfig.backend is None:
    log.fatal("OpenXCAP needs a backend to be specified in order to run")
    sys.exit(1)


class ApplicationUsage(object):
    """Base class defining an XCAP application"""
    id = None                ## the Application Unique ID (AUID)
    default_ns = None        ## the default XML namespace
    mime_type = None         ## the MIME type
    schema_file = None       ## filename of the schema for the application

    def __init__(self, storage):
        ## the XML schema that defines valid documents for this application
        if self.schema_file:
            xml_schema_doc = etree.parse(open(os.path.join(os.path.dirname(__file__), 'xml-schemas', self.schema_file), 'r'))
            self.xml_schema = etree.XMLSchema(xml_schema_doc)
Example #10
0
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'Server'

    root = ConfigSetting(type=XCAPRootURI, value=None)


class Config(ConfigSection):
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'OpenSIPS'

    xmlrpc_url = ConfigSetting(type=str, value=None)
    enable_publish_xcapdiff = False


if Config.xmlrpc_url is None:
    log.fatal("the OpenSIPS.xmlrpc_url option is not set")
    sys.exit(1)


class PlainPasswordChecker(database.PlainPasswordChecker):
    pass


class HashPasswordChecker(database.HashPasswordChecker):
    pass


class BaseStorage(database.Storage):
    def __init__(self):
        database.Storage.__init__(self)
        self._mi = ManagementInterface(Config.xmlrpc_url)
process.runtime_directory = '/tmp'

# These log lines will go to stdout.
log.info("Starting %s. Check syslog to see what's going on next." % name)
log.info(
    "Use `watch -n .1 ls /tmp' to see how the pid file is created and deleted."
)

# Set the process to run in the background and create a pid file.
# If daemonize is called without arguments or pidfile is None no pid file
# will be created.
pidfile = process.runtime_file('%s.pid' % name)
try:
    process.daemonize(pidfile)
except ProcessError as e:
    log.fatal(e)
    sys.exit(1)

# process was successfully put in the background. Redirect logging to syslog
log.start_syslog(name)

# This log line will go to syslog
log.info('application started (running in the background)')

# Add a signal handler for SIGUSR1
process.signals.add_handler(signal.SIGUSR1, signal_handler)
# Add another signal handler for SIGUSR1. Multiple handlers can be added
# for a given signal by different components/modules/threads of the
# application. The only limitation is that the first handler must be added
# from the main thread.
process.signals.add_handler(signal.SIGUSR1, signal_handler2)
Example #12
0
 def _NH_SIPApplicationFailedToStartTLS(self, notification):
     log.fatal('Could not set TLS options: %s' % notification.data.error)
     sys.exit(1)
Example #13
0
process.runtime_directory = '/tmp'

# These log lines will go to stdout.
log.msg("Starting %s. Check syslog to see what's going on next." % name)
log.msg(
    "Use `watch -n .1 ls /tmp' to see how the pid file is created and deleted."
)

# Set the process to run in the background and create a pid file.
# If daemonize is called without arguments or pidfile is None no pid file
# will be created.
pidfile = process.runtime_file('%s.pid' % name)
try:
    process.daemonize(pidfile)
except ProcessError, e:
    log.fatal(str(e))
    sys.exit(1)

# process was successfully put in the background. Redirect logging to syslog
log.start_syslog(name)

# This log line will go to syslog
log.msg('application started (running in the background)')

# Add a signal handler for SIGUSR1
process.signals.add_handler(signal.SIGUSR1, signal_handler)
# Add another signal handler for SIGUSR1. Multiple handlers can be added
# for a given signal by different components/modules/threads of the
# application. The only limitation is that the first handler must be added
# from the main thread.
process.signals.add_handler(signal.SIGUSR1, signal_handler2)
Example #14
0
class Config(ConfigSection):
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'Database'

    authentication_db_uri = ''
    storage_db_uri = ''
    subscriber_table = 'subscriber'
    user_col = 'username'
    domain_col = 'domain'
    password_col = 'password'
    ha1_col = 'ha1'
    xcap_table = 'xcap'


if not Config.authentication_db_uri or not Config.storage_db_uri:
    log.fatal("Authentication DB URI and Storage DB URI must be provided")
    sys.exit(1)


class DBBase(object):
    def __init__(self):
        self._db_connect()


class PasswordChecker(DBBase):
    """A credentials checker against a database subscriber table."""

    implements(checkers.ICredentialsChecker)

    credentialInterfaces = (credentials.IUsernamePassword,
                            credentials.IUsernameHashedPassword)
Example #15
0
    ipstreamer.cfg_filename = process.config_file(cfg_file)

    # when run in foreground, do not require root access because of PID file in /var/run
    if args.fork:
        try:
            process.runtime_directory = runtime_directory
            process.daemonize(args.pid_file)
        except ProcessError, e:
            log.fatal("Cannot start %s: %s" % (fullname, e))
            sys.exit(1)
        log.start_syslog(name)

    if ipstreamer.cfg_filename:
        log.msg("Starting %s %s, config=%s" % (fullname, version, ipstreamer.cfg_filename))
    else:
        log.fatal("Starting %s %s, with no configuration file" % (fullname, version))
        sys.exit(1)

    try:
        from ipstreamer.server import IPStreamerDaemon
        server = IPStreamerDaemon()
    except Exception, e:
        log.fatal("failed to start %s" % fullname)
        log.err()
        sys.exit(1)

    def stop_server(*args):
        if not server.stopping:
            log.msg('Stopping %s...' % fullname)
            server.stop()
Example #16
0
class ServerConfig(ConfigSection):
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'Server'

    root = ConfigSetting(type=XCAPRootURI, value=None)


class Config(ConfigSection):
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'OpenSIPS'

    xmlrpc_url = ConfigSetting(type=str, value=None)
    enable_publish_xcapdiff = False

if Config.xmlrpc_url is None:
    log.fatal("the OpenSIPS.xmlrpc_url option is not set")
    sys.exit(1)

class PlainPasswordChecker(database.PlainPasswordChecker): pass
class HashPasswordChecker(database.HashPasswordChecker): pass

class BaseStorage(database.Storage):

    def __init__(self):
        database.Storage.__init__(self)
        self._mi = ManagementInterface(Config.xmlrpc_url)

    def _notify_watchers(self, response, user_id, event, type):
        def _eb_mi(f):
            log.error("Error while notifying OpenSIPS management interface for user %s: %s" % (user_id, f.getErrorMessage()))
            return response
Example #17
0
                        [tmp[:100]])
                    if db_content.fetchall():
                        continue
                try:
                    message = "RT @%s: %s" % (twitt_author, twitt_content)
                    if len(message) > 140:
                        message = "%s..." % message[:137]
                    self._api.PostUpdate(message)
                except twitter.TwitterError, e:
                    log.error("Twitter Error: %s" % e.message)
                else:
                    con.execute("INSERT INTO twitts(id, content) VALUES(?, ?)",
                                [twitt_id, message])
            con.close()
        except sqlite.Error, e:
            log.fatal("SQLite error: %s" % str(e))
            sys.exit(1)


if __name__ == "__main__":
    if not Config.consumer_key or not Config.consumer_secret or not Config.access_token_key or not Config.access_token_secret:
        log.fatal("Please, fill the configuration file")
        sys.exit(1)

    usage = "usage: %prog [options]"
    parser = OptionParser(usage=usage)
    parser.add_option('-t', dest='tag', help='Hashtag to search for')
    options, args = parser.parse_args()

    if options.tag:
        log.start_syslog("twitterbot")
Example #18
0
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'Server'

    address = ConfigSetting(type=IPAddress, value='0.0.0.0')
    root = ConfigSetting(type=XCAPRootURI, value=None)
    backend = ConfigSetting(type=Backend, value=None)

class TLSConfig(ConfigSection):
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'TLS'

    certificate = ConfigSetting(type=Certificate, value=None)
    private_key = ConfigSetting(type=PrivateKey, value=None)

if ServerConfig.root is None:
    log.fatal("the XCAP root URI is not defined")
    sys.exit(1)

if ServerConfig.backend is None:
    log.fatal("OpenXCAP needs a backend to be specified in order to run")
    sys.exit(1)


# Increase the system limit for the maximum number of open file descriptors
try:
    _resource.setrlimit(_resource.RLIMIT_NOFILE, (99999, 99999))
except ValueError:
    log.warn("Could not raise open file descriptor limit")


class XCAPRoot(resource.Resource, resource.LeafResource):
Example #19
0
class Config(ConfigSection):
    __cfgfile__ = xcap.__cfgfile__
    __section__ = "Database"

    authentication_db_uri = ""
    storage_db_uri = ""
    subscriber_table = "subscriber"
    user_col = "username"
    domain_col = "domain"
    password_col = "password"
    ha1_col = "ha1"
    xcap_table = "xcap"


if not Config.authentication_db_uri or not Config.storage_db_uri:
    log.fatal("Authentication DB URI and Storage DB URI must be provided")
    sys.exit(1)


class DBBase(object):
    def __init__(self):
        self._db_connect()


class PasswordChecker(DBBase):
    """A credentials checker against a database subscriber table."""

    implements(checkers.ICredentialsChecker)

    credentialInterfaces = (credentials.IUsernamePassword, credentials.IUsernameHashedPassword)
Example #20
0
# but in this example we use /tmp because we need a place where we have
# write access even without running as root.
process.runtime_directory = '/tmp'

# These log lines will go to stdout.
log.msg("Starting %s. Check syslog to see what's going on next." % name)
log.msg("Use `watch -n .1 ls /tmp' to see how the pid file is created and deleted.")

# Set the process to run in the background and create a pid file.
# If daemonize is called without arguments or pidfile is None no pid file
# will be created.
pidfile = process.runtime_file('%s.pid' % name)
try:
    process.daemonize(pidfile)
except ProcessError, e:
    log.fatal(str(e))
    sys.exit(1)

# process was succesfully put in the background. Redirect logging to syslog
log.start_syslog(name)

# This log line will go to syslog
log.msg('application started (running in the background)')

# Add a signal handler for SIGUSR1
process.signals.add_handler(signal.SIGUSR1, signal_handler)
# Add another signal handler for SIGUSR1. Mutliple handlers can be added
# for a given signal by different components/modules/threads of the
# application. The only limitation is that the first handler must be added
# from the main thread.
process.signals.add_handler(signal.SIGUSR1, signal_handler2)
Example #21
0
                        continue
                    db_content = con.execute("SELECT id FROM twitts WHERE content MATCH ?", [tmp[:100]])
                    if db_content.fetchall():
                        continue
                try:
                    message = "RT @%s: %s" % (twitt_author,  twitt_content)
                    if len(message) > 140:
                        message = "%s..." % message[:137]
                    self._api.PostUpdate(message)
                except twitter.TwitterError, e:
                    log.error("Twitter Error: %s" % e.message)
                else:
                    con.execute("INSERT INTO twitts(id, content) VALUES(?, ?)", [twitt_id, message])
            con.close()
        except sqlite.Error, e:
            log.fatal("SQLite error: %s" % str(e))
            sys.exit(1)


if __name__ == "__main__":
    if not Config.consumer_key or not Config.consumer_secret or not Config.access_token_key or not Config.access_token_secret:
        log.fatal("Please, fill the configuration file")
        sys.exit(1)

    usage = "usage: %prog [options]"
    parser = OptionParser(usage=usage)
    parser.add_option('-t', dest='tag', help='Hashtag to search for')
    options, args = parser.parse_args()

    if options.tag:
        log.start_syslog("twitterbot")