Example #1
0
    def __init__(self, config, Output):
        try:
            self.config = config
            self.Output = Output

            self.torrent_dir = config['torrent_dir']
            self.torrent_cache = {}
            self.file_cache = {}
            self.blocked_files = {}
            self.scan_period = config['parse_dir_interval']
            self.stats_period = config['display_interval']

            self.torrent_list = []
            self.downloads = {}
            self.counter = 0
            self.doneflag = Event()

            self.hashcheck_queue = []
            self.hashcheck_current = None
            
            self.rawserver = RawServer(self.doneflag, config['timeout_check_interval'],
                              config['timeout'], ipv6_enable = config['ipv6_enabled'],
                              failfunc = self.failed, errorfunc = self.exchandler)
            upnp_type = UPnP_test(config['upnp_nat_access'])
            while True:
                try:
                    self.listen_port = self.rawserver.find_and_bind(
                                    config['minport'], config['maxport'], config['bind'],
                                    ipv6_socket_style = config['ipv6_binds_v4'],
                                    upnp = upnp_type, randomizer = config['random_port'])
                    break
                except socketerror, e:
                    if upnp_type and e == UPnP_ERROR:
                        self.Output.message('WARNING: COULD NOT FORWARD VIA UPnP')
                        upnp_type = 0
                        continue
                    self.failed("Couldn't listen - " + str(e))
                    return

            self.ratelimiter = RateLimiter(self.rawserver.add_task,
                                           config['upload_unit_size'])
            self.ratelimiter.set_upload_rate(config['max_upload_rate'])

            self.handler = MultiHandler(self.rawserver, self.doneflag)
            seed(createPeerID())
            self.rawserver.add_task(self.scan, 0)
            self.rawserver.add_task(self.stats, 0)

            self.handler.listen_forever()

            self.Output.message('shutting down')
            self.hashcheck_queue = []
            for hash in self.torrent_list:
                self.Output.message('dropped "'+self.torrent_cache[hash]['path']+'"')
                self.downloads[hash].shutdown()
            self.rawserver.shutdown()
Example #2
0
    def __init__(self, config):
        self.socket = {}
        self.rs = RawServer(Event(), 100, 1000)
        self.nh = NetworkHandler(self)
        self.shutdown = Event()
        self.config = config

        self.post_commit = []
        for pattern, action in self.config.items('post-commit'):
            try:
                self.post_commit.append((re.compile(pattern, re.I), action))
            except re.error, msg:
                raise ServerError, 'Bad post-commit pattern \"%s\": %s' % \
                      (pattern, msg)
Example #3
0
 except OSError, e:
     errorfunc("Couldn't allocate dir - " + str(e))
     return
 
 finflag = Event()
 ann = [None]
 myid = 'M' + version.replace('.', '-')
 myid = myid + ('-' * (8 - len(myid))) + b2a_hex(sha(repr(time()) + ' ' + str(getpid())).digest()[-6:])
 seed(myid)
 pieces = [info['pieces'][x:x+20] for x in xrange(0, 
     len(info['pieces']), 20)]
 def failed(reason, errorfunc = errorfunc, doneflag = doneflag):
     doneflag.set()
     if reason is not None:
         errorfunc(reason)
 rawserver = RawServer(doneflag, config['timeout_check_interval'], config['timeout'], errorfunc = errorfunc, maxconnects = config['max_allow_in'])
 try:
     try:
         storage = Storage(files, open, path.exists, path.getsize)
     except IOError, e:
         errorfunc('trouble accessing files - ' + str(e))
         return
     def finished(finfunc = finfunc, finflag = finflag, 
             ann = ann, storage = storage, errorfunc = errorfunc):
         finflag.set()
         try:
             storage.set_readonly()
         except (IOError, OSError), e:
             errorfunc('trouble setting readonly at end - ' + str(e))
         if ann[0] is not None:
             ann[0](1)
Example #4
0
def download(params,
             filefunc,
             statusfunc,
             finfunc,
             errorfunc,
             doneflag,
             cols,
             pathFunc=None,
             presets={},
             exchandler=None,
             failed=_failfunc,
             paramfunc=None):

    try:
        config = parse_params(params, presets)
    except ValueError as e:
        failed(
            'error: {}\nrun with no args for parameter explanations'.format(e))
        return
    if not config:
        errorfunc(get_usage())
        return

    myid = createPeerID()
    random.seed(myid)

    rawserver = RawServer(doneflag,
                          config['timeout_check_interval'],
                          config['timeout'],
                          ipv6_enable=config['ipv6_enabled'],
                          failfunc=failed,
                          errorfunc=exchandler)

    upnp_type = UPnP_test(config['upnp_nat_access'])
    try:
        listen_port = rawserver.find_and_bind(
            config['minport'],
            config['maxport'],
            config['bind'],
            ipv6_socket_style=config['ipv6_binds_v4'],
            upnp=upnp_type,
            randomizer=config['random_port'])
    except socket.error as e:
        failed("Couldn't listen - " + str(e))
        return

    response = get_response(config['responsefile'], config['url'], failed)
    if not response:
        return

    infohash = hashlib.sha1(bencode(response['info'])).digest()

    d = BT1Download(statusfunc, finfunc, errorfunc, exchandler, doneflag,
                    config, response, infohash, myid, rawserver, listen_port)

    if not d.saveAs(filefunc):
        return

    if pathFunc:
        pathFunc(d.getFilename())

    hashcheck = d.initFiles(old_style=True)
    if not hashcheck:
        return
    if not hashcheck():
        return
    if not d.startEngine():
        return
    d.startRerequester()
    d.autoStats()

    statusfunc(activity='connecting to peers')

    if paramfunc:
        paramfunc({
            # change_max_upload_rate(<int KiB/sec>)
            'max_upload_rate': d.setUploadRate,
            # change_max_uploads(<int max uploads>)
            'max_uploads': d.setConns,
            'listen_port': listen_port,  # int
            'peer_id': myid,  # string
            'info_hash': infohash,  # string
            # start_connection((<string ip>, <int port>), <peer id>)
            'start_connection': d._startConnection,
        })

    rawserver.listen_forever(d.getPortHandler())

    d.shutdown()
Example #5
0
            return 1
    except ValueError:
        return 0


def track(args):
    if len(args) == 0:
        print formatDefinitions(defaults, 80)
        return
    try:
        config, files = parseargs(args, defaults, 0, 0)
    except ValueError, e:
        print 'error: ' + str(e)
        print 'run with no arguments for parameter explanations'
        return
    r = RawServer(Event(), config['timeout_check_interval'],
                  config['socket_timeout'])
    t = Tracker(config, r)
    r.bind(config['port'], config['bind'], True)
    r.listen_forever(HTTPHandler(t.get,
                                 config['min_time_between_log_flushes']))
    t.save_dfile()
    print '# Shutting down: ' + isotime()


def size_format(s):
    if (s < 1024):
        r = str(s) + 'B'
    elif (s < 1048576):
        r = str(int(s / 1024)) + 'KiB'
    elif (s < 1073741824l):
        r = str(int(s / 1048576)) + 'MiB'
Example #6
0
 def __init__(self, co):
     self.co = co
     self.socket = {}
     self.rs = RawServer(Event(), 100, 1000)
     self.nh = NetworkHandler(self)