⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 track.py

📁 BitTorrent(简称BT
💻 PY
📖 第 1 页 / 共 3 页
字号:
                    else:                        recheck = True            if port and self.natcheck:                if recheck:                    if peer.has_key('nat'):                        if not peer['nat']:                            l = self.becache[infohash]                            y = not peer['left']                            for x in l:                                del x[y][myid]                        del peer['nat'] # restart NAT testing                else:                    natted = peer.get('nat', -1)                    if natted and natted < self.natcheck:                        recheck = True                if recheck:                    NatCheck(self.connectback_result,infohash,myid,ip1,port,self.rawserver)        return rsize    def peerlist(self, infohash, stopped, is_seed, return_type, rsize):        data = {}    # return data        seeds = self.seedcount[infohash]        data['complete'] = seeds        data['incomplete'] = len(self.downloads[infohash]) - seeds        if ( self.allowed is not None and self.config['allowed_controls'] and                                self.allowed[infohash].has_key('warning message') ):            data['warning message'] = self.allowed[infohash]['warning message']        data['interval'] = self.reannounce_interval        if stopped or not rsize:     # save some bandwidth            data['peers'] = []            return data        bc = self.becache.setdefault(infohash,[[{}, {}], [{}, {}], [{}, {}]])        len_l = len(bc[0][0])        len_s = len(bc[0][1])        if not (len_l+len_s):   # caches are empty!            data['peers'] = []            return data        l_get_size = int(float(rsize)*(len_l)/(len_l+len_s))        cache = self.cached.setdefault(infohash,[None,None,None])[return_type]        if cache:            if cache[0] + self.config['min_time_between_cache_refreshes'] < time():                cache = None            else:                if ( (is_seed and len(cache[1]) < rsize)                     or len(cache[1]) < l_get_size or not cache[1] ):                        cache = None        if not cache:            vv = [[],[],[]]            cache = [ time(),                      bc[return_type][0].values()+vv[return_type],                      bc[return_type][1].values() ]            shuffle(cache[1])            shuffle(cache[2])            self.cached[infohash][return_type] = cache            for rr in xrange(len(self.cached[infohash])):                if rr != return_type:                    try:                        self.cached[infohash][rr][1].extend(vv[rr])                    except:                        pass        if len(cache[1]) < l_get_size:            peerdata = cache[1]            if not is_seed:                peerdata.extend(cache[2])            cache[1] = []            cache[2] = []        else:            if not is_seed:                peerdata = cache[2][l_get_size-rsize:]                del cache[2][l_get_size-rsize:]                rsize -= len(peerdata)            else:                peerdata = []            if rsize:                peerdata.extend(cache[1][-rsize:])                del cache[1][-rsize:]        if return_type == 2:            peerdata = ''.join(peerdata)        data['peers'] = peerdata        return data    def get(self, connection, path, headers):        ip = connection.get_ip()        nip = get_forwarded_ip(headers)        if nip and not self.only_local_override_ip:            ip = nip        paramslist = {}        def params(key, default = None, l = paramslist):            if l.has_key(key):                return l[key][0]            return default        try:            (scheme, netloc, path, pars, query, fragment) = urlparse(path)            if self.uq_broken == 1:                path = path.replace('+',' ')                query = query.replace('+',' ')            path = unquote(path)[1:]            for s in query.split('&'):                if s != '':                    i = s.index('=')                    kw = unquote(s[:i])                    paramslist.setdefault(kw, [])                    paramslist[kw] += [unquote(s[i+1:])]            if path == '' or path == 'index.html':                return self.get_infopage()            if path == 'scrape':                return self.get_scrape(paramslist)            if (path == 'file'):                return self.get_file(params('info_hash'))            if path == 'favicon.ico' and self.favicon is not None:                return (200, 'OK', {'Content-Type' : 'image/x-icon'}, self.favicon)            if path != 'announce':                return (404, 'Not Found', {'Content-Type': 'text/plain', 'Pragma': 'no-cache'}, alas)            # main tracker function            infohash = params('info_hash')            if not infohash:                raise ValueError, 'no info hash'            notallowed = self.check_allowed(infohash, paramslist)            if notallowed:                return notallowed            event = params('event')            rsize = self.add_data(infohash, event, ip, paramslist)        except ValueError, e:            return (400, 'Bad Request', {'Content-Type': 'text/plain'},                'you sent me garbage - ' + str(e))        if params('compact'):            return_type = 2        elif params('no_peer_id'):            return_type = 1        else:            return_type = 0        data = self.peerlist(infohash, event=='stopped', not params('left'),                             return_type, rsize)        if paramslist.has_key('scrape'):            data['scrape'] = self.scrapedata(infohash, False)        return (200, 'OK', {'Content-Type': 'text/plain', 'Pragma': 'no-cache'}, bencode(data))    def natcheckOK(self, infohash, peerid, ip, port, not_seed):        bc = self.becache.setdefault(infohash,[[{}, {}], [{}, {}], [{}, {}]])        bc[0][not not_seed][peerid] = Bencached(bencode({'ip': ip, 'port': port,                                              'peer id': peerid}))        bc[1][not not_seed][peerid] = Bencached(bencode({'ip': ip, 'port': port}))        bc[2][not not_seed][peerid] = compact_peer_info(ip, port)    def natchecklog(self, peerid, ip, port, result):        year, month, day, hour, minute, second, a, b, c = localtime(time())        print '%s - %s [%02d/%3s/%04d:%02d:%02d:%02d] "!natcheck-%s:%i" %i 0 - -' % (            ip, quote(peerid), day, months[month], year, hour, minute, second,            ip, port, result)    def connectback_result(self, result, downloadid, peerid, ip, port):        record = self.downloads.get(downloadid, {}).get(peerid)        if ( record is None                 or (record['ip'] != ip and record.get('given ip') != ip)                 or record['port'] != port ):            if self.config['log_nat_checks']:                self.natchecklog(peerid, ip, port, 404)            return        if self.config['log_nat_checks']:            if result:                x = 200            else:                x = 503            self.natchecklog(peerid, ip, port, x)        if not record.has_key('nat'):            record['nat'] = int(not result)            if result:                self.natcheckOK(downloadid,peerid,ip,port,record['left'])        elif result and record['nat']:            record['nat'] = 0            self.natcheckOK(downloadid,peerid,ip,port,record['left'])        elif not result:            record['nat'] += 1    def save_dfile(self):        self.rawserver.add_task(self.save_dfile, self.save_dfile_interval)        h = open(self.dfile, 'wb')        h.write(bencode(self.state))        h.close()    def parse_allowed(self):        self.rawserver.add_task(self.parse_allowed, self.parse_dir_interval)        # logging broken .torrent files would be useful but could confuse        # programs parsing log files, so errors are just ignored for now        def ignore(message):            pass        r = parsedir(self.allowed_dir, self.allowed, self.allowed_dir_files,                     self.allowed_dir_blocked, ignore,include_metainfo = False)        ( self.allowed, self.allowed_dir_files, self.allowed_dir_blocked,          added, garbage2 ) = r        for infohash in added:            self.downloads.setdefault(infohash, {})            self.completed.setdefault(infohash, 0)            self.seedcount.setdefault(infohash, 0)        self.state['allowed'] = self.allowed        self.state['allowed_dir_files'] = self.allowed_dir_files    def delete_peer(self, infohash, peerid):        dls = self.downloads[infohash]        peer = dls[peerid]        if not peer['left']:            self.seedcount[infohash] -= 1        if not peer.get('nat',-1):            l = self.becache[infohash]            y = not peer['left']            for x in l:                del x[y][peerid]        del self.times[infohash][peerid]        del dls[peerid]    def expire_downloaders(self):        for infohash, peertimes in self.times.items():            for myid, t in peertimes.items():                if t < self.prevtime:                    self.delete_peer(infohash, myid)        self.prevtime = time()        if (self.keep_dead != 1):            for key, peers in self.downloads.items():                if len(peers) == 0 and (self.allowed is None or                                        key not in self.allowed):                    del self.times[key]                    del self.downloads[key]                    del self.seedcount[key]        self.rawserver.add_task(self.expire_downloaders, self.timeout_downloaders_interval)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)    t = Tracker(config, r)    s = r.create_serversocket(config['port'], config['bind'], True)    r.start_listening(s, HTTPHandler(t.get, config['min_time_between_log_flushes']))    r.listen_forever()    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 < 1073741824):        r = str(int(s/1048576)) + 'MiB'    elif (s < 1099511627776):        r = str(int((s/1073741824.0)*100.0)/100.0) + 'GiB'    else:        r = str(int((s/1099511627776.0)*100.0)/100.0) + 'TiB'    return(r)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -