Esempio n. 1
0
def run(params):
    cols = 80

    h = HeadlessDisplayer()
    while 1:
        configdir = ConfigDir('downloadheadless')
        defaultsToIgnore = ['responsefile', 'url', 'priority']
        configdir.setDefaults(defaults, defaultsToIgnore)
        configdefaults = configdir.loadConfig()
        defaults.append((
            'save_options', 0,
            "whether to save the current options as the new default configuration "
            + "(only for btdownloadheadless.py)"))
        try:
            config = parse_params(params, configdefaults)
        except ValueError, e:
            print 'error: ' + str(
                e) + '\nrun with no args for parameter explanations'
            break
        if not config:
            print get_usage(defaults, 80, configdefaults)
            break
        if config['save_options']:
            configdir.saveConfig(config)
        configdir.deleteOldCacheData(config['expire_cache_data'])

        myid = createPeerID()
        seed(myid)

        global doneFlag
        doneFlag = Event()

        def disp_exception(text):
            print text

        rawserver = RawServer(doneFlag,
                              config['timeout_check_interval'],
                              config['timeout'],
                              ipv6_enable=config['ipv6_enabled'],
                              failfunc=h.failed,
                              errorfunc=disp_exception)
        upnp_type = UPnP_test(config['upnp_nat_access'])
        while True:
            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'])
                break
            except socketerror, e:
                if upnp_type and e == UPnP_ERROR:
                    print 'WARNING: COULD NOT FORWARD VIA UPnP'
                    upnp_type = 0
                    continue
                print "error: Couldn't listen - " + str(e)
                h.failed()
                return
Esempio n. 2
0
    def __init__(self, utility):
        Thread.__init__(self)

        try:
            self.utility = utility

            self.Output = Output()

            btconfig = self.utility.getBTParams()

            self.stats_period = btconfig['display_interval']

            self.counter = 0
            self.doneflag = Event()

            self.hashcheck_queue = []
            self.hashcheck_current = None

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

            self.listen_port = self.getPort()

            self.handler = MultiHandler(self.rawserver, self.doneflag)
            seed(createPeerID())
            self.rawserver.add_task(self.stats, 0)
        except:
            data = StringIO()
            print_exc(file=data)
            self.Output.exception(data.getvalue())
Esempio n. 3
0
    def start(self):
        config = {k: v for k, v, _ in defaults}
        config['dfile'] = tempfile.mktemp(
        )  # Use temporary file since it won't be reused.
        config['port'] = self.port

        rawserver = RawServer(
            doneflag=Event(),
            timeout_check_interval=config['timeout_check_interval'],
            timeout=config['socket_timeout'],
            ipv6_enable=config['ipv6_enabled'])
        rawserver.bind(port=config['port'],
                       bind=config['bind'],
                       reuse=True,
                       ipv6_socket_style=config['ipv6_binds_v4'])

        self._tracker = _Tracker(config, rawserver)

        # Spawn in separate thread.
        spawn(
            rawserver.listen_forever,
            HTTPHandler(self._tracker.get,
                        config['min_time_between_log_flushes']))
Esempio n. 4
0
def run(scrwin, errlist, params):
    doneflag = threading.Event()
    d = CursesDisplayer(scrwin, errlist, doneflag)
    try:
        while 1:
            configdir = ConfigDir('downloadcurses')
            defaultsToIgnore = ['responsefile', 'url', 'priority']
            configdir.setDefaults(defaults, defaultsToIgnore)
            configdefaults = configdir.loadConfig()
            defaults.append(
                ('save_options', 0, 'whether to save the current options as '
                 'the new default configuration (only for btdownloadcurses.py)'
                 ))
            try:
                config = parse_params(params, configdefaults)
            except ValueError as e:
                d.error('error: {}\nrun with no args for parameter '
                        'explanations'.format(e))
                break
            if not config:
                d.error(get_usage(defaults, d.fieldw, configdefaults))
                break
            if config['save_options']:
                configdir.saveConfig(config)
            configdir.deleteOldCacheData(config['expire_cache_data'])

            myid = createPeerID()
            random.seed(myid)

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

            upnp_type = UPnP_test(config['upnp_nat_access'])
            while True:
                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'])
                    break
                except socket.error as e:
                    if upnp_type and e == UPnP_ERROR:
                        d.error('WARNING: COULD NOT FORWARD VIA UPnP')
                        upnp_type = 0
                        continue
                    d.error("Couldn't listen - " + str(e))
                    d.failed()
                    return

            response = get_response(config['responsefile'], config['url'],
                                    d.error)
            if not response:
                break

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

            dow = BT1Download(d.display, d.finished, d.error, d.error,
                              doneflag, config, response, infohash, myid,
                              rawserver, listen_port, configdir)

            if not dow.saveAs(d.chooseFile):
                break

            if not dow.initFiles(old_style=True):
                break
            if not dow.startEngine():
                dow.shutdown()
                break
            dow.startRerequester()
            dow.autoStats()

            if not dow.am_I_finished():
                d.display(activity='connecting to peers')
            rawserver.listen_forever(dow.getPortHandler())
            d.display(activity='shutting down')
            dow.shutdown()
            break

    except KeyboardInterrupt:
        # ^C to exit...
        pass
    try:
        rawserver.shutdown()
    except:
        pass
    if not d.done:
        d.failed()
Esempio n. 5
0
def run(autoDie, shareKill, userName, params):

    try:

        h = HeadlessDisplayer()
        h.autoShutdown = autoDie
        h.shareKill = shareKill
        h.user = userName

        while 1:
            try:
                config = parse_params(params)
            except ValueError, e:
                print 'error: ' + str(
                    e) + '\nrun with no args for parameter explanations'
                break
            if not config:
                print get_usage()
                break

            # log what we are starting up
            transferLog("tornado starting up :\n", True)
            transferLog(" - torrentfile : " + config['responsefile'] + "\n",
                        True)
            transferLog(" - userName : "******"\n", True)
            transferLog(" - transferStatFile : " + transferStatFile + "\n",
                        True)
            transferLog(
                " - transferCommandFile : " + transferCommandFile + "\n", True)
            transferLog(" - transferLogFile : " + transferLogFile + "\n", True)
            transferLog(" - transferPidFile : " + transferPidFile + "\n", True)
            transferLog(" - autoDie : " + autoDie + "\n", True)
            transferLog(" - shareKill : " + shareKill + "\n", True)
            transferLog(" - minport : " + str(config['minport']) + "\n", True)
            transferLog(" - maxport : " + str(config['maxport']) + "\n", True)
            transferLog(
                " - max_upload_rate : " + str(config['max_upload_rate']) +
                "\n", True)
            transferLog(
                " - max_download_rate : " + str(config['max_download_rate']) +
                "\n", True)
            transferLog(
                " - min_uploads : " + str(config['min_uploads']) + "\n", True)
            transferLog(
                " - max_uploads : " + str(config['max_uploads']) + "\n", True)
            transferLog(" - min_peers : " + str(config['min_peers']) + "\n",
                        True)
            transferLog(
                " - max_initiate : " + str(config['max_initiate']) + "\n",
                True)
            transferLog(
                " - max_connections : " + str(config['max_connections']) +
                "\n", True)
            transferLog(
                " - super_seeder : " + str(config['super_seeder']) + "\n",
                True)
            transferLog(" - security : " + str(config['security']) + "\n",
                        True)
            transferLog(" - auto_kick : " + str(config['auto_kick']) + "\n",
                        True)
            if 'crypto_allowed' in config:
                transferLog(
                    " - crypto_allowed : " + str(config['crypto_allowed']) +
                    "\n", True)
            if 'crypto_only' in config:
                transferLog(
                    " - crypto_only : " + str(config['crypto_only']) + "\n",
                    True)
            if 'crypto_stealth' in config:
                transferLog(
                    " - crypto_stealth : " + str(config['crypto_stealth']) +
                    "\n", True)
            transferLog(" - priority : " + str(config['priority']) + "\n",
                        True)
            transferLog(" - alloc_type : " + str(config['alloc_type']) + "\n",
                        True)
            transferLog(" - alloc_rate : " + str(config['alloc_rate']) + "\n",
                        True)
            transferLog(
                " - buffer_reads : " + str(config['buffer_reads']) + "\n",
                True)
            transferLog(
                " - write_buffer_size : " + str(config['write_buffer_size']) +
                "\n", True)
            transferLog(
                " - check_hashes : " + str(config['check_hashes']) + "\n",
                True)
            transferLog(
                " - max_files_open : " + str(config['max_files_open']) + "\n",
                True)
            transferLog(
                " - upnp_nat_access : " + str(config['upnp_nat_access']) +
                "\n", True)

            # remove command-file if exists
            if isfile(transferCommandFile):
                try:
                    transferLog(
                        "removing command-file " + transferCommandFile +
                        "...\n", True)
                    remove(transferCommandFile)
                except:
                    pass

            # write pid-file
            currentPid = (str(getpid())).strip()
            transferLog(
                "writing pid-file : " + transferPidFile + " (" + currentPid +
                ")\n", True)
            try:
                pidFile = open(transferPidFile, 'w')
                pidFile.write(currentPid + "\n")
                pidFile.flush()
                pidFile.close()
            except Exception, e:
                transferLog(
                    "Failed to write pid-file, shutting down : " +
                    transferPidFile + " (" + currentPid + ")" + "\n", True)
                break

            myid = createPeerID()
            seed(myid)

            doneflag = Event()

            def disp_exception(text):
                print text

            rawserver = RawServer(doneflag,
                                  config['timeout_check_interval'],
                                  config['timeout'],
                                  ipv6_enable=config['ipv6_enabled'],
                                  failfunc=h.failed,
                                  errorfunc=disp_exception)
            upnp_type = UPnP_test(config['upnp_nat_access'])
            while True:
                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'])
                    break
                except socketerror, e:
                    if upnp_type and e == UPnP_ERROR:
                        print 'WARNING: COULD NOT FORWARD VIA UPnP'
                        upnp_type = 0
                        continue
                    print "error: Couldn't listen - " + str(e)
                    h.failed()
                    return
Esempio n. 6
0
    def start(self):
        rawserver = None

        try:
            config = dict([(v[0], v[1]) for v in defaults])
            config['ip'] = self.ip
            config['responsefile'] = self.torrent_file
            config['saveas'] = self.destination_file

            random.seed(self.id)

            rawserver = RawServer(
                doneflag=self.done_flag,
                timeout_check_interval=config['timeout_check_interval'],
                timeout=config['timeout'],
                ipv6_enable=config['ipv6_enabled'],
                failfunc=self.on_fail,
                errorfunc=self.on_exception)
            rawserver.bind(port=self.port,
                           bind=config['bind'],
                           reuse=True,
                           ipv6_socket_style=config['ipv6_binds_v4'])

            # Download torrent metadata.
            response = get_response(file=config['responsefile'],
                                    url=config['url'],
                                    errorfunc=self.on_error)

            # Bail if tracker is done.
            if not response:
                return

            dow = BT1Download(statusfunc=self.on_status,
                              finfunc=self.on_finish,
                              errorfunc=self.on_error,
                              excfunc=self.on_exception,
                              doneflag=self.done_flag,
                              config=config,
                              response=response,
                              infohash=hashlib.sha1(bencode(
                                  response['info'])).digest(),
                              id=self.id,
                              rawserver=rawserver,
                              port=self.port)

            if not dow.saveAs(lambda default, size, saveas, dir: saveas
                              if saveas else default):
                return

            if not dow.initFiles(old_style=True):
                return

            if not dow.startEngine():
                dow.shutdown()
                return

            dow.startRerequester()
            dow.autoStats()

            if not dow.am_I_finished():
                self.on_status(activity='connecting to peers')

            rawserver.listen_forever(dow.getPortHandler())

            self.on_status(activity='shutting down')

            dow.shutdown()
        finally:
            if rawserver:
                rawserver.shutdown()

            if not self.finished_at:
                self.on_fail()
Esempio n. 7
0
   def doTheDownloadThing(self):
      """
      This was copied and modified directly from btdownloadheadless.py 
      """

      if self.disabled:
         LOGERROR('Attempted to start DL but DISABLE_TORRENT is True') 
         return
   
      while 1:

         # Use this var to identify if we've started downloading
         self.startTime = RightNow()


         configdir = ConfigDir(self.cacheDir)
         defaultsToIgnore = ['responsefile', 'url', 'priority']
         configdir.setDefaults(defaults, defaultsToIgnore)
         config = configdir.loadConfig()
         config['responsefile']   = self.torrent
         config['url']            = ''
         config['priority']       = ''
         config['saveas']         = self.savePath_temp
         config['save_options']   = 0
         config['max_uploads']    = 0
         config['max_files_open'] = 25

         configdir.deleteOldCacheData(config['expire_cache_data'])
   
         myid = createPeerID()
         seed(myid)
         
         rawserver = RawServer( self.doneObj, 
                                config['timeout_check_interval'],
                                config['timeout'], 
                                ipv6_enable = config['ipv6_enabled'],
                                failfunc = self.failedFunc, 
                                errorfunc = self.errorFunc)

         upnp_type = UPnP_test(config['upnp_nat_access'])

         while True:
            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'])
               break
            except socketerror, e:
               if upnp_type and e == UPnP_ERROR:
                  LOGWARN('WARNING: COULD NOT FORWARD VIA UPnP')
                  upnp_type = 0
                  continue
               LOGERROR("error: Couldn't listen - " + str(e))
               self.failedFunc()
               return
   
         if not self.response:
            break
   
         infohash = sha(bencode(self.response['info'])).digest()

         LOGINFO('Downloading: %s', self.torrentName)
         curr,tot = [float(a)/MEGABYTE for a in self.fileProgress()]
         if curr == 0:
            LOGINFO('Starting new download')
         elif curr==tot:
            LOGINFO('Torrent already finished!')
            return
         else:
            LOGINFO('Picking up where left off at %0.0f of %0.0f MB' % (curr,tot))
   
         self.bt1dow = BT1Download( self.statusFunc, 
                            self.finishedFunc, 
                            self.errorFunc, 
                            self.excFunc,
                            self.doneObj,
                            config, 
                            self.response, 
                            infohash, 
                            myid, 
                            rawserver, 
                            listen_port,
                            configdir)
         
         if not self.bt1dow.saveAs(self.chooseFileFunc):
            break
   
         if not self.bt1dow.initFiles(old_style = True):
            break

         if not self.bt1dow.startEngine():
            self.bt1dow.shutdown()
            break

         if self.nHashFailures >= self.killAfterNHashFails:
            self.bt1dow.shutdown()
            self.customCallbacks['errorFunc']('hashFail')
            break

         self.bt1dow.startRerequester()
         self.bt1dow.autoStats()
   
         if not self.bt1dow.am_I_finished():
            self.statusFunc(activity = 'Connecting to peers')

         rawserver.listen_forever(self.bt1dow.getPortHandler())
         self.statusFunc(activity = 'Shutting down')
         self.bt1dow.shutdown()
         break