Esempio n. 1
0
def main():
    """
    Main entry point
    """
    try:
        try:
            config=parse_args()
        except ValueError:
            usage()
            import sys
            sys.exit(0)
        if config["daemon"]:
            from daemon import daemon
            daemon()
        srv=server(config["bind"],config["port"],config["backlog"],config["buf"],config["nw"],
                   config["trash_telnet_garbage"],config["allow_empty_cmds"],config["egg"])
        print """
\033[0;36m/***************************************************************\\
|                IgAlJo python server starting...               |
\\***************************************************************/\033[0m
        """
        print "Presh Ctrl+C to stop execution, or send a SIGUSR1 signal to have some fun"
        srv.run()
    except SystemExit:
        pass
    except: # Esto es el control de errores, que más quieres!??
        import traceback,sys
        print "Cannot start the server due to an error: Check the traceback!!"
        trace=file("traceback.log","w")
        traceback.print_exc(file=trace)
        trace.close()
        traceback.print_exc(file=sys.stderr)
Esempio n. 2
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("config_file",
                        help="The configuration file",
                        nargs='?')
    parser.add_argument("--verbose", help="Enable debug level logging")

    group = parser.add_mutually_exclusive_group()
    group.add_argument("--task",
                       help="Trigger manually a legato task",
                       nargs='?')
    group.add_argument("--list", help="List of tasks", action='store_true')

    parser.add_argument("--filename",
                        help="Set filename for the action",
                        nargs='?')

    args = parser.parse_args()

    if args.config_file is None:
        if "LEGATO_CONFIG_PATH" in os.environ:
            args.config_file = os.environ["LEGATO_CONFIG_PATH"]
        else:
            parser.error("no legato configuration file specified")

    if args.task:
        run(args)
    elif args.list:
        list_tasks(args)
    else:
        daemon(args)
Esempio n. 3
0
	def main(self):
		"""main to run for the class."""

		# should evanescent be disabled, and exit right away?
		if not(config.STARTMEUP): sys.exit()

		# create the mainloop object
		# http://www.pygtk.org/docs/pygobject/class-gobjectmainloop.html
		self.mainloop = gobject.MainLoop()

		# start off our initial event source in one second from now.
		self.source_id = gobject.timeout_add_seconds(1, self.loop)

		# create daemon object
		if os.name == 'posix':
			d = daemon.daemon(pidfile=config.DAEMONPID, start_func=self.mainloop.run, logger=self.logs['daemon'], close_fds=not(config.DEBUGMODE))

		try:
			if os.name == 'posix': d.start_stop()
			elif os.name == 'nt': self.mainloop.run()
			else: raise AssertionError('os: `%s\' is not supported at this time.' % os.name)

		except KeyboardInterrupt, e:
			if os.name == 'posix':
				d.start_stop([os.path.basename(sys.argv[0]), 'stop'])
			elif os.name == 'nt':
				self.mainloop.run()
Esempio n. 4
0
    def start(self, background=False):
        sysstr = platform.system()
        if sysstr == 'Linux' and background:
            dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
            daemon(dirname)

        for http_obj in self._http_list:
            p = Process(target=http_obj.start, args=())
            self._http_pool.append(p)
            p.start()

        for p in self._http_pool:
            p.join()

        if gm.has_key("rpc"):
            for p in gm.get("rpc").process():
                p.join()
Esempio n. 5
0
 def openwatchfolder(self):
     """
     Start a daemon thread watching the selected folder
     """
     dialog = QtGui.QFileDialog(self.ui,
                                'Choose a folder to watch',
                                os.curdir,
                                options=QtGui.QFileDialog.ShowDirsOnly)
     d = dialog.getExistingDirectory()
     if d:
         self.ui.findChild(QtGui.QLabel, 'watchfolderpath').setText(d)
         self.folderwatcher.addPath(d)
         if self.ui.findChild(QtGui.QCheckBox,
                              'autoPreprocess').isChecked():
             self.daemonthread = daemon.daemon(d,
                                               self.experiment,
                                               procold=True)
             self.daemonthread.start()
Esempio n. 6
0
def cmd_daemon(arguments):
    """Go into daemon mode"""

    # get the config and a consumer
    config = ecommerce.config.getConfig()
    consumer = None
    try:
        consumer = ecommerce.queue.queue(config, queuePrefix, False)
    except QueueConfigurationException as ex:
        print "CONFIG: %s" % ex
        return -1
    except QueueRuntimeException as ex:
        print "RUNTIME: %s" % ex
        return -1
    except QueueFolderLockException:
        # not an error, there is another daemon running
        print "WARNING: cannot start daemon, already running"
        return 0
    except Exception as ex:
        print "ERROR: %s" % ex
        return -1

    # go daemon
    return daemon.daemon(config, configPrefix, daemonPrefix, consumer)
Esempio n. 7
0
            forum.notice(
                "This is the last time I'm going to beg for ops.  Puh-leaze?")


if __name__ == '__main__':
    import daemon
    import sys

    debug = False
    if "-d" in sys.argv:
        debug = True

    if not debug:
        # Become a daemon
        log = file('arsenic.log', 'a')
        daemon.daemon('arsenic.pid', log, log)

    # Short URL server
    us = shorturl.start(('', 0))
    firebot.URLSERVER = (socket.gethostbyaddr(socket.gethostname())[0],
                         us.getsockname()[1])

    NICK = ['arsenic']
    INFO = "I'm a little printf, short and stdout"

    l1 = Arsenic(('irc.lanl.gov', 6667),
                 NICK,
                 INFO, ["#x", "#csirt"],
                 ssl=False)
    l1.debug = debug
Esempio n. 8
0
def main():
    parser = optparse.OptionParser()
    parser.add_option(
        "-i", "--inetd", help="Run once on stdin (inetd mode)", action="store_true", dest="stdin", default=False
    )
    parser.add_option(
        "-l", "--port", help="What port to run on (default 2000)", action="store", dest="port", default=None, type="int"
    )
    parser.add_option(
        "-b",
        "--bindaddr",
        help="What IP address to bind to (default all)",
        action="store",
        dest="bindaddr",
        default=None,
    )
    parser.add_option("-p", "--pidfile", help="Where to write a PID file", action="store", dest="pidfile", default=None)
    parser.add_option(
        "-c",
        "--config",
        help="Location of config file",
        action="store",
        dest="config",
        default="/usr/local/etc/pysieved.ini",
    )
    parser.add_option(
        "-v",
        "--verbosity",
        help="Set logging verbosity level (default 1)",
        action="store",
        dest="verbosity",
        default=1,
        type="int",
    )
    parser.add_option(
        "-d", "--debug", help="Log to stderr (implies --no-daemon)", action="store_true", dest="debug", default=False
    )
    parser.add_option("-B", "--base", help="Mail base directory", action="store", dest="base", default="")
    parser.add_option("-t", "--tmpdir", help="Temp directory", action="store", dest="tmpdir", default="")
    parser.add_option(
        "-T",
        "--tls",
        help="STARTTLS required before authentication",
        action="store_true",
        dest="tls_required",
        default=False,
    )
    parser.add_option("-K", "--key", help="TLS private key file", action="store", dest="tls_key", default="")
    parser.add_option("-C", "--cert", help="TLS certificate file", action="store", dest="tls_cert", default="")
    parser.add_option(
        "--no-daemon",
        help="Do not daemonize (but stay in foreground)",
        action="store_true",
        dest="nodaemon",
        default=False,
    )
    (options, args) = parser.parse_args()

    # Read config file
    config = Config(options.config)

    port = options.port or config.getint("main", "port", 2000)
    addr = options.bindaddr or config.get("main", "bindaddr", "")
    pidfile = options.pidfile or config.get("main", "pidfile", "/var/run/pysieved.pid")
    base = options.base or config.get("main", "base", "")
    tmpdir = options.tmpdir or config.get("main", "tmpdir", "") or os.environ.get("TMPDIR", "/tmp")
    tls_required = options.tls_required or config.getboolean("TLS", "required", False)
    tls_key = options.tls_key or config.get("TLS", "key", "")
    tls_cert = options.tls_cert or config.get("TLS", "cert", "")
    tls_passphrase = config.get("TLS", "passphrase", "")

    if options.debug:
        options.nodaemon = True

    # Define the log function
    syslog.openlog("pysieved[%d]" % (os.getpid()), 0, syslog.LOG_MAIL)

    def log(l, s):
        if l <= options.verbosity:
            if options.debug:
                sys.stderr.write("%s %s\n" % ("=" * l, s))
            else:
                if l > 0:
                    lvl = syslog.LOG_NOTICE
                elif l == 0:
                    lvl = syslog.LOG_WARNING
                else:
                    lvl = syslog.LOG_ERR
                syslog.syslog(lvl, s)

    # Load TLS key and cert
    tls_privateKey = None
    tls_certChain = None
    if tls_key or tls_cert:
        # Expect to use TLS
        if not have_tls:
            log(1, "TLSLite is not available. STARTTLS will not be offered")
            tls_required = False
        elif not tls_key:
            log(1, "Cannot enable TLS without a key. STARTTLS will not be offered")
            tls_required = False
        elif not tls_cert:
            log(1, "Cannot enable TLS without a certificate. STARTTLS will not be offered")
            tls_required = False
        else:
            try:
                tls_read_cert = open(tls_cert).read()
                tls_x509 = X509()
                tls_x509.parse(tls_read_cert)
                tls_certChain = X509CertChain([tls_x509])
                tls_read_key = open(tls_key).read()

                def passphrase():
                    return tls_passphrase

                tls_privateKey = parsePEMKey(tls_read_key, private=True, passwordCallback=passphrase)
            except:
                log(1, "Failed to load TLS key or certificate. STARTTLS will not be offered.")
                tls_certChain = None
                tls_privateKey = None
                tls_required = False

    ##
    ## Import plugins
    ##
    auth = __import__("plugins.%s" % config.get("main", "auth", "SASL").lower(), None, None, True)
    userdb = __import__("plugins.%s" % config.get("main", "userdb", "passwd").lower(), None, None, True)
    storage = __import__("plugins.%s" % config.get("main", "storage", "Dovecot").lower(), None, None, True)
    consumer = __import__("plugins.%s" % config.get("main", "consumer", "Dovecot").lower(), None, None, True)

    # If the same plugin is used in two places, recycle it
    authenticate = auth.PysievedPlugin(log, config)

    if userdb == auth:
        homedir = authenticate
    else:
        homedir = userdb.PysievedPlugin(log, config)

    if storage == auth:
        store = authenticate
    elif storage == userdb:
        store = homedir
    else:
        store = storage.PysievedPlugin(log, config)

    if consumer == auth:
        consume = authenticate
    elif consumer == userdb:
        consume = homedir
    elif consumer == storage:
        consume = store
    else:
        consume = consumer.PysievedPlugin(log, config)

    class handler(managesieve.RequestHandler):
        capabilities = consume.capabilities

        def __init__(self, *args):
            self.params = {}
            managesieve.RequestHandler.__init__(self, *args)

        def log(self, l, s):
            log(l, s)

        def list_mech(self):
            mechs = authenticate.mechanisms()
            self.log(5, "Announcing mechanisms : %r" % mechs)
            return mechs

        def do_sasl_first(self, mechanism, *args):
            self.log(5, "Starting SASL authentication (%s) : %s" % (mechanism, " ".join(args)))
            ret = authenticate.do_sasl_first(mechanism, *args)
            if ret["result"] == "CONT":
                self.log(5, "Need more SASL authentication : %r" % ret)
            else:
                self.log(5, "Finished SASL authentication : %r" % ret)
            return ret

        def do_sasl_next(self, b64_string):
            self.log(5, "Continuing SASL authentication : %s" % b64_string)
            ret = authenticate.do_sasl_next(b64_string)
            if ret["result"] == "CONT":
                self.log(5, "Need more SASL authentication : %r" % ret)
            else:
                self.log(5, "Finished SASL authentication : %r" % ret)
            return ret

        def authenticate(self, username, passwd):
            self.log(5, "Authenticating %s" % username)
            self.params["username"] = username
            self.params["password"] = passwd
            return authenticate.auth(self.params)

        def get_homedir(self, username):
            self.params["username"] = username
            ret = homedir.lookup(self.params)
            self.log(5, "Plugin returned home : %r" % ret)
            if ret and not os.path.isabs(ret) and base:
                ret = os.path.join(base, ret)
                self.log(5, "Added base to home : %r" % ret)
            return ret

        def new_storage(self, homedir):
            self.params["homedir"] = homedir
            return store.create_storage(self.params)

        def get_tls_params(self):
            return {"required": tls_required, "key": tls_privateKey, "cert": tls_certChain}

        def pre_save(self, script):
            return consume.pre_save(tmpdir, script)

        def post_load(self, script):
            return consume.post_load(script)

    if options.stdin:
        sock = socket.fromfd(0, socket.AF_INET, socket.SOCK_STREAM)
        h = handler(sock, sock.getpeername(), None)
    else:
        import daemon

        s = Server((addr, port), handler)

        if not options.nodaemon:
            daemon.daemon(pidfile=pidfile)
        log(1, "Listening on %s port %d" % (addr or "INADDR_ANY", port))
        s.serve_forever()
Esempio n. 9
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('-i', '--inetd',
                      help='Run once on stdin (inetd mode)',
                      action='store_true', dest='stdin', default=False)
    parser.add_option('-l', '--port',
                      help='What port to run on (default 2000)',
                      action='store', dest='port', default=None, type='int')
    parser.add_option('-b', '--bindaddr',
                      help='What IP address to bind to (default all)',
                      action='store', dest='bindaddr', default=None)
    parser.add_option('-p', '--pidfile',
                      help='Where to write a PID file',
                      action='store', dest='pidfile', default=None)
    parser.add_option('-c', '--config',
                      help='Location of config file',
                      action='store', dest='config',
                      default='/usr/local/etc/pysieved.ini')
    parser.add_option('-v', '--verbosity',
                      help="Set logging verbosity level (default 1)",
                      action='store', dest='verbosity', default=1, type='int')
    parser.add_option('-d', '--debug',
                      help='Log to stderr (implies --no-daemon)',
                      action='store_true', dest='debug', default=False)
    parser.add_option('-B', '--base',
                      help='Mail base directory',
                      action='store', dest='base', default='')
    parser.add_option('-t', '--tmpdir',
                      help='Temp directory',
                      action='store', dest='tmpdir', default='')
    parser.add_option('-T', '--tls',
                      help='STARTTLS required before authentication',
                      action='store_true', dest='tls_required', default=False)
    parser.add_option('-K', '--key',
                      help='TLS private key file',
                      action='store', dest='tls_key', default='')
    parser.add_option('-C', '--cert',
                      help='TLS certificate file',
                      action='store', dest='tls_cert', default='')
    parser.add_option('--no-daemon',
                      help='Do not daemonize (but stay in foreground)',
                      action='store_true', dest='nodaemon', default=False)
    (options, args) = parser.parse_args()

    # Read config file
    config = Config(options.config)

    port = options.port or config.getint('main', 'port', 2000)
    addr = options.bindaddr or config.get('main', 'bindaddr', '')
    pidfile = options.pidfile or config.get('main', 'pidfile',
                                            '/var/run/pysieved.pid')
    base = options.base or config.get('main', 'base', '')
    tmpdir = options.tmpdir or config.get('main', 'tmpdir', '') or \
             os.environ.get('TMPDIR', '/tmp')
    tls_required = options.tls_required or config.getboolean('TLS', 'required', False)
    tls_key = options.tls_key or config.get('TLS', 'key', '')
    tls_cert = options.tls_cert or config.get('TLS', 'cert', '')
    tls_passphrase = config.get('TLS', 'passphrase', '')

    if options.debug:
        options.nodaemon = True

    # Define the log function
    syslog.openlog('pysieved[%d]' % (os.getpid()), 0, syslog.LOG_MAIL)
    def log(l, s):
        if l <= options.verbosity:
            if options.debug:
                sys.stderr.write('%s %s\n' % ("=" * l, s))
            else:
                if l > 0:
                    lvl = syslog.LOG_NOTICE
                elif l == 0:
                    lvl = syslog.LOG_WARNING
                else:
                    lvl = syslog.LOG_ERR
                syslog.syslog(lvl, s)


    # Load TLS key and cert
    tls_privateKey = None
    tls_certChain = None
    if tls_key or tls_cert:
        # Expect to use TLS
        if not have_tls:
            log(1, "TLSLite is not available. STARTTLS will not be offered")
            tls_required = False
        elif not tls_key:
            log(1, "Cannot enable TLS without a key. STARTTLS will not be offered")
            tls_required = False
        elif not tls_cert:
            log(1, "Cannot enable TLS without a certificate. STARTTLS will not be offered")
            tls_required = False
        else:
            try:
                tls_read_cert = open(tls_cert).read()
                tls_x509 = X509()
                tls_x509.parse(tls_read_cert)
                tls_certChain = X509CertChain([tls_x509])
                tls_read_key = open(tls_key).read()

                def passphrase():
                    return tls_passphrase

                tls_privateKey = parsePEMKey(tls_read_key, private=True, passwordCallback=passphrase)
            except:
                log(1, "Failed to load TLS key or certificate. STARTTLS will not be offered.")
                tls_certChain = None
                tls_privateKey = None
                tls_required = False


    ##
    ## Import plugins
    ##
    auth = __import__('plugins.%s' % config.get('main', 'auth', 'SASL').lower(),
                      None, None, True)
    userdb = __import__('plugins.%s' % config.get('main', 'userdb', 'passwd').lower(),
                      None, None, True)
    storage = __import__('plugins.%s' % config.get('main', 'storage', 'Dovecot').lower(),
                         None, None, True)
    consumer = __import__('plugins.%s' % config.get('main', 'consumer', 'Dovecot').lower(),
                          None, None, True)


    # If the same plugin is used in two places, recycle it
    authenticate = auth.PysievedPlugin(log, config)

    if userdb == auth:
        homedir = authenticate
    else:
        homedir = userdb.PysievedPlugin(log, config)

    if storage == auth:
        store = authenticate
    elif storage == userdb:
        store = homedir
    else:
        store = storage.PysievedPlugin(log, config)

    if consumer == auth:
        consume = authenticate
    elif consumer == userdb:
        consume = homedir
    elif consumer == storage:
        consume = store
    else:
        consume = consumer.PysievedPlugin(log, config)


    class handler(managesieve.RequestHandler):
        capabilities = consume.capabilities

        def __init__(self, *args):
            self.params = {}
            managesieve.RequestHandler.__init__(self, *args)

        def log(self, l, s):
            log(l, s)

        def list_mech(self):
            mechs = authenticate.mechanisms()
            self.log(5, "Announcing mechanisms : %r" % mechs)
            return mechs

        def do_sasl_first(self, mechanism, *args):
            self.log(5, "Starting SASL authentication (%s) : %s" % (mechanism, ' '.join(args)))
            ret = authenticate.do_sasl_first(mechanism, *args);
            if ret['result'] == 'CONT':
                self.log(5, "Need more SASL authentication : %r" % ret)
            else:
                self.log(5, "Finished SASL authentication : %r" % ret)
            return ret

        def do_sasl_next(self, b64_string):
            self.log(5, "Continuing SASL authentication : %s" % b64_string)
            ret = authenticate.do_sasl_next(b64_string);
            if ret['result'] == 'CONT':
                self.log(5, "Need more SASL authentication : %r" % ret)
            else:
                self.log(5, "Finished SASL authentication : %r" % ret)
            return ret

        def authenticate(self, username, passwd):
            self.log(5, "Authenticating %s" % username)
            self.params['username'] = username
            self.params['password'] = passwd
            return authenticate.auth(self.params)

        def get_homedir(self, username):
            self.params['username'] = username
            ret = homedir.lookup(self.params)
            self.log(5, "Plugin returned home : %r" % ret)
            if ret and not os.path.isabs(ret) and base:
                ret = os.path.join(base, ret)
                self.log(5, "Added base to home : %r" % ret)
            return ret

        def new_storage(self, homedir):
            self.params['homedir'] = homedir
            return store.create_storage(self.params)

        def get_tls_params(self):
            return {'required': tls_required,
                    'key': tls_privateKey,
                    'cert': tls_certChain}

        def pre_save(self, script):
            return consume.pre_save(tmpdir, script)

        def post_load(self, script):
            return consume.post_load(script)

    if options.stdin:
        sock = socket.fromfd(0, socket.AF_INET, socket.SOCK_STREAM)
        h = handler(sock, sock.getpeername(), None)
    else:
        import daemon

        s = Server((addr, port), handler)

        if not options.nodaemon:
            daemon.daemon(pidfile=pidfile)
        log(1, 'Listening on %s port %d' % (addr or "INADDR_ANY", port))
        s.serve_forever()
Esempio n. 10
0
        f2 = open('iptables-save.json', 'a+')
        f2.close()
        pass

    client.loop_forever()


"""
command to start the daemon application is `python <name>.py start`, similarly to restart and stop the application.
run() fucntion will be executed in a dameon mode when you run this python script with start argument
"""
run()

if __name__ == "__main__":
    file_name = os.path.basename(__file__)
    daemon = daemon("/daemon_pids/" + file_name[:-3] + ".pid", run)

    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print("Unknown command")
            sys.exit(2)
        print("program ended")
        sys.exit(0)
    else:
        print("usage: %s start|stop|restart" % sys.argv[0])
Esempio n. 11
0
def main(sysargv):
	parser = argparse.ArgumentParser(prog='transmgmt', usage='%(prog)s [OPTIONS] [ACTION] [ARGS...]', description='Multi-Server Transmission Management!', epilog='Seed! \n\n')
	parser.add_argument('action', help='action for transmgmt to run')
	parser.add_argument('args', help='depends on action: files, directories, or sites', nargs='*')
	parser.add_argument('-v','--verbose', help='increase transmgmt verbosity', action='store_true')
	parser.add_argument('-p','--pretend', help='pretend actions, don\'t actually run them', default=False, action='store_true')
	parser.add_argument('-d','--dircreate', help='create directories if they do not exist', default=False, action='store_true')
	parser.add_argument('-c','--copy', help='*Always* copy, even if you say move', default=False, action='store_true')
	parser.add_argument('-s','--start', help='start torrent upon add/import', default=False,action='store_true')
	args = parser.parse_args()
	if len(sysargv) < 1:
		parser.print_help()
		sys.exit(0)

	if args.verbose:
		print "reading action: %s..." % args.action
		print "reading args: %s..." % args.args
		print "verbose: %s" % args.verbose
		print "pretend: %s" % args.pretend
		print "dircreate: %s" % args.dircreate
		print "copy: %s" % args.copy
		print "start: %s" % args.start

	inputlist = args.args

	#Action Handling
	if args.action.lower() == 'test':
		test(inputlist)

	if args.action.lower() == 'check':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt check [torrentfile] [torrentdirectory]'
			sys.exit(1)
		try:
			torrentfile = os.path.expanduser(inputlist[0])
			torrentdirectory = os.path.expanduser(inputlist[1])
		except:
			print 'usage: transmgmt check [torrentfile] [torrentdirectory]'
			sys.exit(1)
		try:
			t = torrent.torrent(filename=torrentfile)
		except IOError as e:
			print 'Not a valid torrent file'
			sys.exit(1)
		print t.check(torrentdirectory,pretend=args.pretend)

	if args.action.lower() == 'copy':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt copy [torrentfile] [sourcedir] [targetdir]'
			sys.exit(1)
		try:
			torrentfile = os.path.expanduser(inputlist[0])
			sourcedir = os.path.expanduser(inputlist[1])
			targetdir = os.path.expanduser(inputlist[2])
		except IndexError as e:
			print 'usage: transmgmt copy [torrentfile] [sourcedir] [targetdir]'
			sys.exit(1)
		if not os.path.isdir(sourcedir):
			print 'Source directory does not exist'
			sys.exit(1)
		if not os.path.isdir(targetdir) and not args.dircreate:
			print "Target directory does not exist, use -d to force create"
		try:
			t = torrent.torrent(filename=torrentfile)
		except IOError as e:
			print 'Torrent file does not exist!'
			sys.exit(1)
		print t.copy(sourcedir,targetdir,copy=True,pretend=args.pretend,dircreate=args.dircreate)

	if args.action.lower() == 'move':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt copy [torrentfile] [sourcedir] [targetdir]'
			sys.exit(1)
		try:
			torrentfile = os.path.expanduser(inputlist[0])
			sourcedir = os.path.expanduser(inputlist[1])
			targetdir = os.path.expanduser(inputlist[2])
		except IndexError as e:
			print 'usage: transmgmt copy [torrentfile] [sourcedir] [targetdir]'
			sys.exit(1)
		if not os.path.isdir(sourcedir):
			print 'Source directory does not exist'
			sys.exit(1)
		if not os.path.isdir(targetdir) and not args.dircreate:
			print "Target directory does not exist, use -c to force create"
		try:
			t = torrent.torrent(filename=torrentfile)
		except IOError as e:
			print 'Torrent file does not exist!'
			sys.exit(1)
		print t.copy(sourcedir,targetdir,copy=args.copy,pretend=args.pretend,dircreate=args.dircreate)

	if args.action.lower() == 'sort':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt sort [torrentfile] [sourcedir] [torrentbasedir]'
			sys.exit(1)
		try:
			torrentfile = os.path.expanduser(inputlist[0])
			sourcedir = os.path.expanduser(inputlist[1])
			torrentbasedir = os.path.expanduser(inputlist[2])
		except:
			print 'usage: transmgmt sort [torrentfile] [sourcedir] [torrentbasedir]'
			sys.exit(1)
		if not os.path.exists(sourcedir):
			print 'Source directory does not exist'
			sys.exit(1)
		if not os.path.isdir(torrentbasedir) and not args.dircreate:
			print "Torrent base directory does not exist, use -c to force create"
		try:
			t = torrent.torrent(filename=torrentfile)
		except IOError as e:
			print 'Torrent file does not exist!'
			sys.exit(1)
		print t.sort(sourcedir,torrentbasedir,copy=args.copy,pretend=args.pretend,dircreate=args.dircreate)



	if args.action.lower() == 'addtodaemon':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt addtodaemon [torrentfile] [sourcedir] [daemonname]'
			sys.exit(1)
		try:
			torrentfile = os.path.expanduser(inputlist[0])
			sourcedir = os.path.expanduser(inputlist[1])
			daemonname = inputlist[2]
		except:
			print 'usage: transmgmt addtodaemon [torrentfile] [sourcedir] [daemonname]'
			sys.exit(1)
		for d in config.jsonconfig['daemons']:
			#print c
			if d['name'] == daemonname:
				td = daemon.daemon(d)
		try:
			pprint (vars(td))
		except UnboundLocalError as e:
			print 'Did not find torrent client named: %s' % (daemonname)
			sys.exit(1)
		try:
			t = torrent.torrent(filename=torrentfile)
		except IOError as e:
			print 'Torrent file does not exist!'
			sys.exit(1)
		print addtodaemon(t,td,sourcedir,basedir,copy=args.copy,pretend=args.pretend,dircreate=args.dircreate)
			#print addtodaemon(inputlist[0],inputlist[1],inputlist[2],copy=args.copy,pretend=args.pretend,dircreate=args.dircreate)

	if args.action.lower() == 'add':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt add [torrentfile]'
			sys.exit(1)
		try:
			torrentfile = os.path.expanduser(inputlist[0])
		except:
			print 'usage: transmgmt add [torrentfile] [optional:sourcedir]'
			sys.exit(1)
		try:
			sourcedir = os.path.expanduser(inputlist[1])
		except IndexError:
			sourcedir = None
		try:
			t = torrent.torrent(filename=torrentfile)
		except IOError as e:
			print 'Torrent file does not exist!'
		listofdaemons = []
		for d in config.jsonconfig['daemons']:
			listofdaemons.append(daemon.daemon(d))
		addtorrent(t,listofdaemons,sourcedir,copy=args.copy,pretend=args.pretend,dircreate=args.dircreate,startflag=args.start)

	if args.action.lower() == 'import':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt import [dottorrentfolder] [optional: torrentdatafolder]'
			sys.exit(1)
		if os.path.isdir(inputlist[0]):
			dottorrentfolder = os.path.expanduser(inputlist[0])
		try:
			torrentdatafolder = os.path.expanduser(inputlist[1])
		except IndexError:
			torrentdatafolder = None
		listofdaemons = []
		for d in config.jsonconfig['daemons']:
			listofdaemons.append(daemon.daemon(d))
		torrentimport(dottorrentfolder,listofdaemons,torrentdatafolder,copy=args.copy,pretend=args.pretend,dircreate=args.dircreate)

	if args.action.lower() == 'hunt':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt look [hunt folder]'
			sys.exit(1)
		#infohash = inputlist[0]
		inputdirectory = os.path.expanduser(inputlist[0])
		listofdaemons = []
		for d in config.jsonconfig['daemons']:
			listofdaemons.append(daemon.daemon(d))
		for d in listofdaemons:
			for tdt in d._client.get_torrents():
				if tdt.percentDone < 1 and tdt.status == 'stopped':
					print tdt.name
					t = torrent.torrent(filename=tdt.torrentFile)
					downloaddir = tdt.downloadDir
					print downloaddir
					t.copy(inputdirectory,downloaddir,copy=args.copy,pretend=args.pretend,dircreate=args.dircreate)
					#tdt = d._client.get_torrent(infohash)

	if args.action.lower() == 'look':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt look [hash] [look folder]'
			sys.exit(1)
		infohash = inputlist[0]
		inputdirectory = os.path.expanduser(inputlist[1])
		listofdaemons = []
		for d in config.jsonconfig['daemons']:
			listofdaemons.append(daemon.daemon(d))
		for d in listofdaemons:
			try:
				tdt = d._client.get_torrent(infohash)
			except KeyError as e:
				print e
			else:
				t = torrent.torrent(filename=tdt.torrentFile)
				downloaddir = tdt.downloadDir
				print downloaddir
				t.copy(inputdirectory,downloaddir,copy=args.copy,pretend=args.pretend,dircreate=args.dircreate)


# 	if args.action.lower() == 'startstopped':
# 		if inputlist[0] == 'help':
# 			print 'usage: transmgmt startstopped'
# 			sys.exit(1)
# 		listofdaemons = []
# 		for d in config.jsonconfig['daemons']:
# 			listofdaemons.append(daemon.daemon(d))
# 		daemon.startstopped(listofdaemons)

	if args.action.lower() == 'get':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt import [attribute] [hash]'
			sys.exit(1)
		listofdaemons = []
		for d in config.jsonconfig['daemons']:
			listofdaemons.append(daemon.daemon(d))
		try:
			attribute = inputlist[0]
		except IndexError:
			print 'usage: transmgmt import [attribute] [hash]'
			sys.exit(1)
		try:
			hashstring = inputlist[1].lower()
		except:
			print 'usage: transmgmt import [attribute] [hash]'
			sys.exit(1)
		print daemon.get_attribute(listofdaemons,attribute,hashstring)
		sys.exit(1)

	if args.action.lower() == 'remove':

		# build list of daemons
		listofdaemons = []
		for d in config.jsonconfig['daemons']:
			listofdaemons.append(daemon.daemon(d))

		# build list of hashes loaded into the daemons
		tdhash = []
		for d in listofdaemons:
			for t in d._client.get_torrents():
				tdhash.append(t.hashString.upper())

		# build list of hashes in download directories
		dlphashlist = []
		for d in config.jsonconfig['downloadpaths']:
			dlphashlist.extend(os.listdir(d))

		# find directories that do not have hashes loaded into transmission-daemon
		missing = list(set(dlphashlist) - set(tdhash))
		print missing
		for d in config.jsonconfig['downloadpaths']:
			for m in missing:
				if os.path.isdir(os.path.join(d,m)):
					src = os.path.join(d,m)
					dst = os.path.join(os.path.dirname(d),config.jsonconfig['removedpath'],m)
					print '%s moved to %s' % (src,dst)
					if not args.pretend:
						try:
							shutil.move(src,dst)
						except UnicodeDecodeError as e:
							print 'filename error, manually run: mv %s %s' % (src,dst)

	if args.action.lower() == 'backup':
		if len(inputlist) == 0 or inputlist[0] == 'help':
			print 'usage: transmgmt backup [optional: hash]'
			sys.exit(1)
		try:
			infohash = inputlist[0]
		except IndexError as e:
			print e
			infohash = False

		# build list of daemons
		listofdaemons = []
		for d in config.jsonconfig['daemons']:
			listofdaemons.append(daemon.daemon(d))

		# build list of existing hashes in backup
		if config.jsonconfig['remoteuser']:
			remoteconnection = config.jsonconfig['remoteuser']+'@'+config.jsonconfig['remotehost']
		else:
			remoteconnection = config.jsonconfig['remotehost']
		remotepath = config.jsonconfig['remotepath']
		ls = subprocess.Popen(['ssh',remoteconnection,'ls',remotepath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		remotehashes, err =  ls.communicate()
		#print remotehashes

		if infohash != 'all':
			# check if info has exists and is complete
			t = None
			for d in listofdaemons:
				try:
					t = d._client.get_torrent(infohash.lower())
				except KeyError as e:
					pass
			if t is not None and t.percentDone == 1 and t.hashString.upper() not in remotehashes:
				#print t.downloadDir
				processargs = ['rsync','-avhSP','--whole-file',t.downloadDir,remoteconnection+':'+remotepath]
				print ' '.join(processargs)
				if not args.pretend:
					subprocess.call(processargs)
			elif t is not None and t.percentDone == 1 and t.hashString.upper() in remotehashes:
				print '%s already backed up' % infohash
			elif t is not None and t.percentDone < 1:
				print '%s is not complete' % infohash
			else:
				print '%s does not exist' % infohash
		elif infohash == 'all':
			print 'full backup scan'
			for d in listofdaemons:
				listoftorrents = d._client.get_torrents()
				for t in listoftorrents:
					if t.percentDone == 1 and t.hashString.upper() not in remotehashes:
						#print t.downloadDir
						processargs = ['rsync','-avhSP','--whole-file',t.downloadDir,remoteconnection+':'+remotepath]
						print ' '.join(processargs)
						if not args.pretend:
							subprocess.call(processargs)
		else:
			print 'not sure what\'s going on here...'
			sys.exit(1)

	if args.action.lower() == 'getfilehash':
		inputfile = ' '.join(inputlist)
		t = torrent.torrent(inputfile)
		print t._info_hash.lower()
		sys.exit(0)
Esempio n. 12
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('-i', '--inetd',
                      help='Run once on stdin (inetd mode)',
                      action='store_true', dest='stdin', default=False)
    parser.add_option('-l', '--port',
                      help='What port to run on (default 2000)',
                      action='store', dest='port', default=None, type='int')
    parser.add_option('-b', '--bindaddr',
                      help='What IP address to bind to (default all)',
                      action='store', dest='bindaddr', default=None)
    parser.add_option('-p', '--pidfile',
                      help='Where to write a PID file',
                      action='store', dest='pidfile', default=None)
    parser.add_option('-c', '--config',
                      help='Location of config file',
                      action='store', dest='config',
                      default='/usr/local/etc/pysieved.ini')
    parser.add_option('-v', '--verbosity',
                      help="Set logging verbosity level (default 1)",
                      action='store', dest='verbosity', default=1, type='int')
    parser.add_option('-d', '--debug',
                      help='Log to stderr',
                      action='store_true', dest='debug', default=False)
    parser.add_option('-B', '--base',
                      help='Mail base directory',
                      action='store', dest='base', default='')
    parser.add_option('-T', '--tls',
                      help='STARTTLS required before authentication',
                      action='store_true', dest='tls_required', default=False)
    parser.add_option('-K', '--key',
                      help='TLS private key file',
                      action='store', dest='tls_key', default='')
    parser.add_option('-C', '--cert',
                      help='TLS certificate file',
                      action='store', dest='tls_cert', default='')
    (options, args) = parser.parse_args()

    # Read config file
    config = Config(options.config)

    port = options.port or config.getint('main', 'port', 2000)
    addr = options.bindaddr or config.get('main', 'bindaddr', '')
    pidfile = options.pidfile or config.get('main', 'pidfile',
                                            '/var/run/pysieved.pid')
    base = options.base or config.get('main', 'base', '')
    tls_required = options.tls_required or config.getboolean('TLS', 'required', False)
    tls_key = options.tls_key or config.get('TLS', 'key', '')
    tls_cert = options.tls_cert or config.get('TLS', 'cert', '')
    tls_passphrase = config.get('TLS', 'passphrase', '')


    # Define the log function
    syslog.openlog('pysieved[%d]' % (os.getpid()), 0, syslog.LOG_MAIL)
    def log(l, s):
        if l <= options.verbosity:
            if options.debug:
                sys.stderr.write('%s %s\n' % ("=" * l, s))
            else:
                if l > 0:
                    lvl = syslog.LOG_NOTICE
                elif l == 0:
                    lvl = syslog.LOG_WARNING
                else:
                    lvl = syslog.LOG_ERR
                syslog.syslog(lvl, s)


    # Load TLS key and cert
    tls_privateKey = None
    tls_certChain = None
    if tls_key or tls_cert:
        # Expect to use TLS
        if not have_tls:
            log(1, "TLSLite is not available. STARTTLS will not be offered")
            tls_required = False
        elif not tls_key:
            log(1, "Cannot enable TLS without a key. STARTTLS will not be offered")
            tls_required = False
        elif not tls_cert:
            log(1, "Cannot enable TLS without a certificate. STARTTLS will not be offered")
            tls_required = False
        else:
            try:
                tls_read_cert = open(tls_cert).read()
                tls_x509 = X509()
                tls_x509.parse(tls_read_cert)
                tls_certChain = X509CertChain([tls_x509])
                tls_read_key = open(tls_key).read()

                def passphrase():
                    return tls_passphrase

                tls_privateKey = parsePEMKey(tls_read_key, private=True, passwordCallback=passphrase)
            except:
                log(1, "Failed to load TLS key or certificate. STARTTLS will not be offered.")
                tls_certChain = None
                tls_privateKey = None
                tls_required = False


    ##
    ## Import plugins
    ##
    auth = __import__('plugins.%s' % config.get('main', 'auth', 'SASL').lower(),
                      None, None, True)
    userdb = __import__('plugins.%s' % config.get('main', 'userdb', 'passwd').lower(),
                      None, None, True)
    storage = __import__('plugins.%s' % config.get('main', 'storage', 'Dovecot').lower(),
                         None, None, True)


    # If the same plugin is used in two places, recycle it
    authenticate = auth.PysievedPlugin(log, config)

    if userdb == auth:
        homedir = authenticate
    else:
        homedir = userdb.PysievedPlugin(log, config)

    if storage == auth:
        store = authenticate
    elif storage == userdb:
        store = homedir
    else:
        store = storage.PysievedPlugin(log, config)


    class handler(managesieve.RequestHandler):
        capabilities = store.capabilities

        def __init__(self, *args):
            self.params = {}
            managesieve.RequestHandler.__init__(self, *args)

        def log(self, l, s):
            log(l, s)

        def list_mech(self):
            mechs = authenticate.mechanisms()
            self.log(5, "Announcing mechanisms : %r" % mechs)
            return mechs

        def do_sasl_first(self, mechanism, *args):
            self.log(5, "Starting SASL authentication (%s) : %s" % (mechanism, ' '.join(args)))
            ret = authenticate.do_sasl_first(mechanism, *args);
            if ret['result'] == 'CONT':
                self.log(5, "Need more SASL authentication : %r" % ret)
            else:
                self.log(5, "Finished SASL authentication : %r" % ret)
            return ret

        def do_sasl_next(self, b64_string):
            self.log(5, "Continuing SASL authentication : %s" % b64_string)
            ret = authenticate.do_sasl_next(b64_string);
            if ret['result'] == 'CONT':
                self.log(5, "Need more SASL authentication : %r" % ret)
            else:
                self.log(5, "Finished SASL authentication : %r" % ret)
            return ret

        def authenticate(self, username, passwd):
            self.log(5, "Authenticating %s" % username)
            self.params['username'] = username
            self.params['password'] = passwd
            return authenticate.auth(self.params)

        def get_homedir(self, username):
            self.params['username'] = username
            ret = homedir.lookup(self.params)
            self.log(5, "Plugin returned home : %r" % ret)
            if ret and not os.path.isabs(ret) and base:
                ret = os.path.join(base, ret)
                self.log(5, "Added base to home : %r" % ret)
            return ret

        def new_storage(self, homedir):
            self.params['homedir'] = homedir
            return store.create_storage(self.params)

        def get_tls_params(self):
            return {'required': tls_required,
                    'key': tls_privateKey,
                    'cert': tls_certChain}

    if options.stdin:
        sock = socket.fromfd(0, socket.AF_INET, socket.SOCK_STREAM)
        h = handler(sock, sock.getpeername(), None)
    else:
        import daemon

        s = Server((addr, port), handler)

        if not options.debug:
            daemon.daemon(pidfile=pidfile)
        log(1, 'Listening on %s port %d' % (addr or "INADDR_ANY", port))
        s.serve_forever()