コード例 #1
0
ファイル: unet.py プロジェクト: safvan010/123
 def simpleSetUp(self):
     #self.kfiles()
     d = dict([(x[0],x[1]) for x in common_options + rare_options])
     self.r = RawServer(Event(), d)
     self.l = []
     for i in range(self.num):
         self.l.append(UTKhashmir('', self.startport + i, 'kh%s.db' % (self.startport + i), self.r))
     
     for i in self.l:
         i.addContact(self.localip, self.l[randrange(0,self.num)].port)
         i.addContact(self.localip, self.l[randrange(0,self.num)].port)
         i.addContact(self.localip, self.l[randrange(0,self.num)].port)
         self.r.listen_once(1)
         self.r.listen_once(1)
         self.r.listen_once(1) 
         
     for i in self.l:
         self.done = 0
         i.findCloseNodes(self._done)
         while not self.done:
             self.r.listen_once(1)
     for i in self.l:
         self.done = 0
         i.findCloseNodes(self._done)
         while not self.done:
             self.r.listen_once(1)
コード例 #2
0
 def listen_forever(self):
     pool = NSAutoreleasePool.alloc().init()
     # XXX
     #self.profile = Profile("BT.prof");self.profile.start()
     self.rawserver = RawServer(self.config)
     self.mt = MultiTorrent(self.config, self.doneflag, self.rawserver,
                            self.multi_errorfunc, self.config['data_dir'])
     self.rawserver.ident = thread.get_ident()
     self.mt.set_option("max_upload_rate",
                        self.config['max_upload_rate'] * 1024)
     self.rawserver.listen_forever(self.doneflag)
コード例 #3
0
 def __init__(self, host, port, data_dir, rawserver=None, max_ul_rate=1024, checkpoint=True, errfunc=None, rlcount=foo, config={'pause':False, 'max_rate_period':20}):
     if rawserver:
         self.rawserver = rawserver
     else:
         self.flag = Event()
         d = dict([(x[0],x[1]) for x in common_options + rare_options])            
         self.rawserver = RawServer(self.flag, d)
     self.max_ul_rate = max_ul_rate
     self.socket = None
     self.config = config
     self.setup(host, port, data_dir, rlcount, checkpoint)
コード例 #4
0
ファイル: InitTableTest.py プロジェクト: hitzjd/DHT
class InitTableTest:
    def __init__(self):
        self.config, self.metainfo = self._load_settings()
        self.rawserver = RawServer(self.config)
        self.dht = UTKhashmir(self.config['bind'], self.config['port'],
                              self.config['dumpDir'], self.rawserver)

    def _load_settings(self):
        f = open('config/MyNodes.json')
        settings = json.load(f)
        return settings["config"], settings["metainfo"]

    def start_init(self):
        if self.dht:
            infohash = sha(bencode(self.metainfo['value'])).digest()
            # infohash = 0x0d0d7a9ef71434d31b893cec305264579b7cf262
            nodes = self.dht.table.findNodes(infohash)

            if len(nodes) < const.K:
                for node in self.metainfo['nodes']:
                    host = node['host']
                    port = node['port']
                    self.dht.addContact(host, port)

            # self.rawserver.add_task(30,self.show_table)
            self.rawserver.add_task(10, self.dht.getPeersAndAnnounce, infohash,
                                    self.metainfo['value'], self.show_value)
            # self.rawserver.add_task(10, self.dht.pingQuery, '207.134.242.20', 59464)
            # self.rawserver.add_task(10, self.dht.getPeerQuery,infohash,'176.31.225.184',8999)

            # self.rawserver.add_task(20,self.dht.announcePeer,infohash,self.metainfo['value'])

            # self.rawserver.add_task(10,self.dht.getPeers,infohash,self.show_value)

    def show_value(self, *arg):
        print "here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        try:
            result = arg[0][0]
            # print len(result)
            # ip_hex = result[:4]
            ip_int = struct.unpack(">L", result[:4])[0]
            ip = socket.inet_ntoa(struct.pack('L', socket.htonl(ip_int)))
            port = struct.unpack(">H", result[4:])[0]
            print "ip:port", ip, port
        except IndexError:
            print "not found"

    def show_table(self):
        for bucket in self.dht.table.buckets:
            for node in bucket.l:
                print node.host, node.port, node.num
コード例 #5
0
ファイル: unet.py プロジェクト: safvan010/123
class Network:
    def __init__(self, size=0, startport=5555, localip='127.0.0.1'):
        self.num = size
        self.startport = startport
        self.localip = localip

    def _done(self, val):
        self.done = 1
        
    def simpleSetUp(self):
        #self.kfiles()
        d = dict([(x[0],x[1]) for x in common_options + rare_options])
        self.r = RawServer(Event(), d)
        self.l = []
        for i in range(self.num):
            self.l.append(UTKhashmir('', self.startport + i, 'kh%s.db' % (self.startport + i), self.r))
        
        for i in self.l:
            i.addContact(self.localip, self.l[randrange(0,self.num)].port)
            i.addContact(self.localip, self.l[randrange(0,self.num)].port)
            i.addContact(self.localip, self.l[randrange(0,self.num)].port)
            self.r.listen_once(1)
            self.r.listen_once(1)
            self.r.listen_once(1) 
            
        for i in self.l:
            self.done = 0
            i.findCloseNodes(self._done)
            while not self.done:
                self.r.listen_once(1)
        for i in self.l:
            self.done = 0
            i.findCloseNodes(self._done)
            while not self.done:
                self.r.listen_once(1)

    def tearDown(self):
        for i in self.l:
            i.rawserver.stop_listening_udp(i.socket)
            i.socket.close()
        #self.kfiles()
        
    def kfiles(self):
        for i in range(self.startport, self.startport+self.num):
            try:
                os.unlink('kh%s.db' % i)
            except:
                pass
            
        self.r.listen_once(1)
コード例 #6
0
ファイル: InitTableTest.py プロジェクト: hitzjd/DHT
class InitTableTest:
	def __init__(self):
		self.config,self.metainfo = self._load_settings()
		self.rawserver = RawServer(self.config)
		self.dht = UTKhashmir(self.config['bind'],self.config['port'],'data',self.rawserver)

	def _load_settings(self):
		f = open('config/MyNodes.json')
		settings = json.load(f)
		return settings["config"],settings["metainfo"]
		

	def start_init(self):
		if self.dht:
			nodes = self.dht.table.findNodes(self.metainfo['infohash'],invalid=False)
			if len(nodes) < const.K:
				for node in self.metainfo['nodes']:
					host = node['host']
					port = node['port']
					df = self.rawserver.gethostbyname(host)
					df.addCallback(self.dht.addContact,port)

	def show_table(self):
		for bucket in self.dht.table.buckets:
			print bucket
コード例 #7
0
ファイル: test_krpc.py プロジェクト: safvan010/123
    def setUp(self):
        self.noisy = 0
        d = dict([(x[0],x[1]) for x in common_options + rare_options])
        self.r = RawServer(d)

        addr = ('127.0.0.1', 1180)
        self.as = self.r.create_udpsocket(addr[1], addr[0], True)
        self.af = Receiver(addr)
        self.a = hostbroker(self.af, addr, self.as, self.r.add_task)
        self.r.start_listening_udp(self.as, self.a)

        addr = ('127.0.0.1', 1181)
        self.bs = self.r.create_udpsocket(addr[1], addr[0], True)
        self.bf = Receiver(addr)
        self.b = hostbroker(self.bf, addr, self.bs, self.r.add_task)
        self.r.start_listening_udp(self.bs, self.b)
コード例 #8
0
    def main(self):
        """\
        Start the Mainline client and block forever listening for connectons
        """

        uiname = "bittorrent-console"
        defaults = get_defaults(uiname)
        config, args = configfile.parse_configuration_and_args(
            defaults, uiname)
        config = Preferences().initWithDict(config)
        data_dir = config['data_dir']
        self.core_doneflag = DeferredEvent()
        self.rawserver_doneflag = DeferredEvent()

        rawserver = RawServer(config)  #event and I/O scheduler
        self.multitorrent = MultiTorrent(
            config, rawserver,
            data_dir)  #class used to add, control and remove torrents

        self.tick()  #add periodic function call

        rawserver.add_task(0, self.core_doneflag.addCallback,
                           lambda r: rawserver.external_add_task(0, shutdown))
        rawserver.listen_forever(
            self.rawserver_doneflag)  # runs until the component terminates

        self.send(producerFinished(self), "signal")
        print "TorrentClient has shutdown"
コード例 #9
0
 def listen_forever(self):
     pool = NSAutoreleasePool.alloc().init()
     # XXX
     #self.profile = Profile("BT.prof");self.profile.start()
     self.rawserver = RawServer(self.config)
     self.mt = MultiTorrent(self.config, self.doneflag, self.rawserver, self.multi_errorfunc, self.config['data_dir'])
     self.rawserver.ident = thread.get_ident()
     self.mt.set_option("max_upload_rate", self.config['max_upload_rate'] * 1024)
     self.rawserver.listen_forever(self.doneflag)
コード例 #10
0
 def __init__(self, host, port, data_dir, rawserver=None, max_ul_rate=1024, checkpoint=True, errfunc=None, rlcount=foo, config={'pause':False, 'max_rate_period':20}):
     if rawserver:
         self.rawserver = rawserver
     else:
         self.flag = Event()
         d = dict([(x[0],x[1]) for x in common_options + rare_options])            
         self.rawserver = RawServer(self.flag, d)
     self.max_ul_rate = max_ul_rate
     self.socket = None
     self.config = config
     self.setup(host, port, data_dir, rlcount, checkpoint)
コード例 #11
0
ファイル: TorrentClient.py プロジェクト: casibbald/kamaelia
    def main(self):
        """\
        Start the Mainline client and block indefinitely, listening for connectons.
        """
      
        uiname = "bittorrent-console"
        defaults = get_defaults(uiname)
        config, args = configfile.parse_configuration_and_args(defaults, uiname)
        config = Preferences().initWithDict(config)
        data_dir = config['data_dir']
        self.core_doneflag = DeferredEvent()
        self.rawserver_doneflag = DeferredEvent()
        
        rawserver = RawServer(config) #event and I/O scheduler
        self.multitorrent = MultiTorrent(config, rawserver, data_dir) #class used to add, control and remove torrents

        self.tick() #add periodic function call
    
        rawserver.add_task(0, self.core_doneflag.addCallback, lambda r: rawserver.external_add_task(0, shutdown))
        rawserver.listen_forever(self.rawserver_doneflag) # runs until the component terminates

        self.send(producerFinished(self), "signal")
コード例 #12
0
    try:
        config, args = configfile.parse_configuration_and_args(
            defaults, 'bittorrent', sys.argv[1:], 0, None)
        if debug:
            config['upnp'] = False
            config['one_connection_per_ip'] = False

    except BTFailure, e:
        print unicode(e.args[0])
        sys.exit(1)

    config = Preferences().initWithDict(config)
    # bug set in DownloadInfoFrame

    rawserver = RawServer(config)
    zurllib.set_zurllib_rawserver(rawserver)
    rawserver.install_sigint_handler()

    ipc = ipc_interface(rawserver, config, "controlsocket")

    # make sure we clean up the ipc when everything is done
    atexit_threads.register_verbose(ipc.stop)

    # this could be on the ipc object
    ipc_master = True
    try:
        if not config['use_factory_defaults']:
            ipc.create()
    except BTFailure, e:
        ipc_master = False
コード例 #13
0
ファイル: test_upnp.py プロジェクト: galaxysd/BitTorrent
    print_list(list)

    df = nattraverser.register_port(internal_port, internal_port, "TCP")
    external_port = like_yield(df)
    print "Mapped:", external_port

    list = like_yield(nattraverser.list_ports())
    print_list(list)

    # synchronous
    nattraverser.unregister_port(external_port, "TCP")
    
    list = like_yield(nattraverser.list_ports())
    print_list(list)


if __name__ == "__main__":
    rawserver = RawServer({'upnp': True})
    nattraverser = NatTraverser(rawserver)

    port = 6881
    if len(sys.argv) > 1:
        port = int(sys.argv[1])
        
    df = run_tests(port)
    def error(f):
        print f
    df.addErrback(error)
    df.addBoth(lambda r: rawserver.stop())
    rawserver.listen_forever()
コード例 #14
0
class BTAppController (NibClassBuilder.AutoBaseClass):
    def init(self):
        self = super(BTAppController, self).init()
        self.prefs = Preferences.alloc().init()
        self.prefwindow = None
        self.generator = Generate.alloc().init()
        
        self.ic =ICHelper.alloc().init()
        
        # displayed torrent controllers
        self.torrents = []
        
        # waiting to die
        self.dead_torrents = []
        
        # ready to start
        # (<open panel>, <insert row>, (<filename>|<stream>, <is_stream>))  -1 insert row means use last row
        # stream = 0 if filename, 1 if bencoded torrent file
        self.tqueue = [] 
                
        self.retain()
        self.inited = 0
        self.launched = 0
        self.in_choose = 0
        self.last_qcheck = time()
        
        self.sc = 0
        self.defaults = NSUserDefaults.standardUserDefaults()

        self.tup = bdecode(self.defaults.objectForKey_(ULBYTES))
        self.tdown = bdecode(self.defaults.objectForKey_(DLBYTES))
        
        self.config = common_options + rare_options
        self.config = BTPreferences().initWithDict(dict([(name, value) for (name, value, doc) in self.config]))

        self.config['data_dir'] = PREFDIR
                
        self.config['bind'] = ''
        self.config['bad_libc_workaround'] = True
        self.config['filesystem_encoding'] = 'utf8'
        #XXXX
        #self.config['start_trackerless_client'] = False

        self.legacyConfig()
        self.reloadConfig()
        
        self.pyi = None
        
        self.doneflag = Event()

        if not os.path.exists(PREFDIR):
            os.mkdir(PREFDIR)
        if not os.path.exists(RESDIR):
            os.mkdir(RESDIR)


        self.ticon = None

        self.stalled = []
        self.terminated = False
        
        return self

    def loadConsole_(self, sender):
        if not self.pyi:
            self.pyi = PyInterpreter.alloc().init()
            NSBundle.loadNibNamed_owner_("PyInterpreter", self.pyi)
        else:
            self.pyi.textView.window().makeKeyAndOrderFront_(self)

    def legacyConfig(self):
        n = self.defaults.integerForKey_(QUEUESTOP)
        if n > 1:
            self.defaults.setObject_forKey_(0, QUEUESTOP)
        
    def reloadConfig(self):
        self.config['minport'] = self.defaults.integerForKey_(MINPORT)
        self.config['maxport'] = self.defaults.integerForKey_(MINPORT)
        self.config['max_upload_rate'] = self.defaults.integerForKey_(MAXULRATE)
        self.config['max_allow_in'] = self.defaults.integerForKey_(MAXACCEPT)
        self.config['max_initiate'] = self.defaults.integerForKey_(MAXINITIATE)
        self.config['max_uploads'] = self.defaults.integerForKey_(MAXULS)

    def listen_forever(self):
        pool = NSAutoreleasePool.alloc().init()
        # XXX
        #self.profile = Profile("BT.prof");self.profile.start()
        self.rawserver = RawServer(self.config)
        self.mt = MultiTorrent(self.config, self.doneflag, self.rawserver, self.multi_errorfunc, self.config['data_dir'])
        self.rawserver.ident = thread.get_ident()
        self.mt.set_option("max_upload_rate", self.config['max_upload_rate'] * 1024)
        self.rawserver.listen_forever(self.doneflag)
        #self.profile.stop();self.profile.close()

    def multi_errorfunc(self, level, text ):
        if level == CRITICAL:
            self.statusField.setStringValue_(NSLocalizedString("Critical Error: %s", "critical error") % text)
            # bomb out
        elif level == ERROR:
            self.statusField.setStringValue_(NSLocalizedString("Error: %s", "normal error") % text)
        elif level == WARNING:
            print ">>>", NSLocalizedString("Warning: %s", "warning error") % text
        elif level == INFO:
            print ">>>", NSLocalizedString("Info: %s", "info error") % text
    
    def awakeFromNib(self):
        if not self.inited:
            self.inited = 1
            NSBundle.loadNibNamed_owner_("TorrentWindow", self)
            self.drawerMenu.setTarget_(self.logDrawer)
            self.drawerMenu.setAction_(self.logDrawer.toggle_)
            self.logDrawer.delegate().menu = self.drawerMenu
            self.torrentTable.registerForDraggedTypes_([NSFilenamesPboardType])

    def openPage_(self, sender):
        NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(URL))

    def openHomePage_(self, sender):
        NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_("http://www.bittorrent.com/"))

    def nag(self):
        nag = self.defaults.objectForKey_(NAG)
        if nag == 0 or (nag != BitTorrent.version and randint(0,2) == 0):
            if nag == 0:
                self.defaults.setObject_forKey_(1, NAG)
            NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(URL))
            x = NSRunAlertPanel(NSLocalizedString("Please Donate", "nag window title"), 
                                NSLocalizedString("If you like BitTorrent and want to see more cool apps from the author, you should make a donation.", "nag message"), 
                                NSLocalizedString("Later", "nag later"), NSLocalizedString("Already Donated", "nag already"), None)
            if x == NSAlertAlternateReturn:
                self.defaults.setObject_forKey_(BitTorrent.version, NAG)
                NSRunInformationalAlertPanel(NSLocalizedString("Thank You", "Thank You"), NSLocalizedString("Thank you for making a donation.  You will not be bothered with donation requests until you upgrade.", "thanks for donating"),
                                             NSLocalizedString("OK", "OK"), None, None)

    def applicationDidFinishLaunching_(self, aNotification):
        try:
            NSThread.detachNewThreadSelector_toTarget_withObject_(self.listen_forever, self, None)
        except BTFailure, e:
            err = str(e)
            if err.startswith("Could not open a listening port"):
                p = PortChanger.alloc().initWithErr(err)
            else:
                x = NSRunAlertPanel(NSLocalizedString("Fatal Error", "fatal error"), 
                                    NSLocalizedString("Failed to initialize BitTorrent core.  Error: %s", "bittorrent failure message") % str(e), 
                                None, None, None)
                NSApp().terminate_(self)

        self.launched = 1

        #self.profile = Profile("BT.prof")
        #self.profile.start()

        tcell = PyTimeCell.alloc().init()
        fcell = PyFileCell.alloc().init()
        xcell = PyXFerCell.alloc().init()

        cols = self.torrentTable.tableColumns()
        for c in cols:
            #c.setHeaderCell_(TorrentTableHeaderCell.alloc().initTextCell_(c.headerCell().stringValue()))
            if c.identifier() == 'time':
                c.setDataCell_(tcell)
            elif c.identifier() == 'file':
                c.setDataCell_(fcell)
            elif c.identifier() == 'xfer':
                c.setDataCell_(xcell)


        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, self._otorrent, "DoneChoosingTorrent", None)        
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, self.saveTorrents, "NSWorkspaceWillPowerOffNotification", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, self.moveTorrent, "NSTableViewColumnDidMoveNotification", None)
        
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1.5, self, self.updateStatus, None, 1)
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(10, self, self.checkQueue, None, 1) 
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(300, self, self.saveTorrents, None, 1)
        
        self.loadTorrents()
        
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, self.reapDead, "TorrentStatusChanged", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, self.statusChanged, "TorrentStatusChanged", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, self.updateCycleMenu, "TorrentStatusChanged", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, self.updateCycleMenu, "TorrentSelectionChanged", None)

        if defaults.objectForKey_(VERSIONCHECK):
            self.checkVersion()

        # open any torrents waiting
        self.otorrent(None)
コード例 #15
0
ファイル: test_krpc.py プロジェクト: safvan010/123
class KRPCTests(TestCase):
    def setUp(self):
        self.noisy = 0
        d = dict([(x[0],x[1]) for x in common_options + rare_options])
        self.r = RawServer(d)

        addr = ('127.0.0.1', 1180)
        self.as = self.r.create_udpsocket(addr[1], addr[0], True)
        self.af = Receiver(addr)
        self.a = hostbroker(self.af, addr, self.as, self.r.add_task)
        self.r.start_listening_udp(self.as, self.a)

        addr = ('127.0.0.1', 1181)
        self.bs = self.r.create_udpsocket(addr[1], addr[0], True)
        self.bf = Receiver(addr)
        self.b = hostbroker(self.bf, addr, self.bs, self.r.add_task)
        self.r.start_listening_udp(self.bs, self.b)
        
    def tearDown(self):
        self.as.close()
        self.bs.close()

    def testSimpleMessage(self):
        self.noisy = 0
        self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
        self.r.listen_once(0.01)
        self.assertEqual(self.bf.buf, ["This is a test."])

    def testMessageBlast(self):
        self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
        self.r.listen_once(0.01)
        self.assertEqual(self.bf.buf, ["This is a test."])
        self.bf.buf = []
        
        for i in range(100):
            self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('store', {'msg' : "This is a test."})
            self.r.listen_once(0.01)
            #self.bf.buf = []
        self.assertEqual(self.bf.buf, ["This is a test."] * 100)

    def testEcho(self):
        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
        df.addCallback(self.gotMsg)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.msg, "This is a test.")

    def gotMsg(self, dict):
        _krpc_sender = dict['_krpc_sender']
        msg = dict['rsp']
        self.msg = msg

    def testManyEcho(self):
        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
        df.addCallback(self.gotMsg)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.msg, "This is a test.")
        for i in xrange(100):
            self.msg = None
            df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
            df.addCallback(self.gotMsg)
            self.r.listen_once(0.01)
            self.r.listen_once(0.01)
            self.assertEqual(self.msg, "This is a test.")

    def testMultiEcho(self):
        self.noisy = 0
        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
        df.addCallback(self.gotMsg)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.msg, "This is a test.")

        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
        df.addCallback(self.gotMsg)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.msg, "This is another test.")

        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
        df.addCallback(self.gotMsg)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.msg, "This is yet another test.")

    def testEchoReset(self):
        self.noisy = 0
        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is a test."})
        df.addCallback(self.gotMsg)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.msg, "This is a test.")

        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is another test."})
        df.addCallback(self.gotMsg)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.msg, "This is another test.")

        del(self.a.connections[('127.0.0.1', 1181)])
        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('echo', {'msg' : "This is yet another test."})
        df.addCallback(self.gotMsg)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.msg, "This is yet another test.")

    def testLotsofEchoReset(self):
        for i in range(100):
            self.testEchoReset()
            
    def testUnknownMeth(self):
        self.noisy = 0
        df = self.a.connectionForAddr(('127.0.0.1', 1181)).sendRequest('blahblah', {'msg' : "This is a test."})
        df.addErrback(self.gotErr)
        self.r.listen_once(0.01)
        self.r.listen_once(0.01)
        self.assertEqual(self.err, KRPC_ERROR_METHOD_UNKNOWN)

    def gotErr(self, err):
        self.err = err
コード例 #16
0
ファイル: test_udp.py プロジェクト: galaxysd/BitTorrent
class SimpleTests(TestCase):
    def setUp(self):
        d = dict([(x[0],x[1]) for x in common_options + rare_options])
        self.r = RawServer(d)
        self.a = self.r.create_udpsocket(8051, '127.0.0.1')
        self.b = self.r.create_udpsocket(8052, '127.0.0.1')

    def tearDown(self):
        self.a.close()
        self.b.close()
        
    def Handler(self, expected):
        class h(object):
            def __init__(self, expected, a=self.assertEqual):
                self.expected = expected
                self.a = a
            def data_came_in(self, connection, data):
                self.a(self.expected, data)
        return h(expected)

    def testFoo(self):
        self.r.start_listening_udp(self.a, self.Handler(''))
        self.r.start_listening_udp(self.b, self.Handler('foo'))
        self.a.sendto("foo", 0, ('127.0.0.1', 8052))
        self.r.listen_once()

    def testBackForth(self):
        self.r.start_listening_udp(self.a, self.Handler('bar'))
        self.r.start_listening_udp(self.b, self.Handler('foo'))
        self.a.sendto("foo", 0, ('127.0.0.1', 8052))
        self.r.listen_once()
        self.b.sendto("bar", 0, ('127.0.0.1', 8051))        
        self.r.listen_once()
コード例 #17
0
from twisted.internet import reactor

config = {
    'max_incomplete': 10,
    'max_upload_rate': 350000,
    'bind': '',
    'close_with_rst': False,
    'socket_timeout': 3000
}

m = 20000
a = [None] * m
i = 0

if __name__ == '__main__':
    rawserver = RawServer(config=config, noisy=True)

    rawserver.install_sigint_handler()

    def avg_dist(l):
        d = []
        p = None
        for x in l:
            if p is not None:
                d.append(x - p)
            p = x
        return sum(d) / len(d)

    def rerun():
        #print '.'
        global i
コード例 #18
0
    def _got_peer(self, addr, infohash):
        if self.got_peer:
            self.got_peer(addr, infohash)
            
    def stop(self):
        self.port = None
        self.got_peer = None
        for service in self.services:
            self.server.unregisterService(service)
        del self.services[:]

        
if __name__ == '__main__':
    import string
    import threading
    from BitTorrent.RawServer_twisted import RawServer

    rawserver = RawServer()

    def run_task_and_exit():
        l = LocalDiscovery(rawserver, 6881,
                           lambda *a:sys.stdout.write("GOT: %s\n" % str(a)))
        l.announce("63f27f5023d7e49840ce89fc1ff988336c514b64",
                   ''.join(random.sample(string.letters, 5)))
    
    rawserver.add_task(0, run_task_and_exit)

    rawserver.listen_forever()
         
    
コード例 #19
0
    df = nattraverser.register_port(internal_port, internal_port, "TCP")
    external_port = like_yield(df)
    print "Mapped:", external_port

    list = like_yield(nattraverser.list_ports())
    print_list(list)

    # synchronous
    nattraverser.unregister_port(external_port, "TCP")

    list = like_yield(nattraverser.list_ports())
    print_list(list)


if __name__ == "__main__":
    rawserver = RawServer({'upnp': True})
    nattraverser = NatTraverser(rawserver)

    port = 6881
    if len(sys.argv) > 1:
        port = int(sys.argv[1])

    df = run_tests(port)

    def error(f):
        print f

    df.addErrback(error)
    df.addBoth(lambda r: rawserver.stop())
    rawserver.listen_forever()
コード例 #20
0
ファイル: test_icmp.py プロジェクト: galaxysd/BitTorrent

def message_dump(data):
    print "Received: ", data.encode("hex")

def shutdown():
    print "shutdown."
    rawserver.stop()

if __name__ == "__main__":
    print "test2"
    sys.stdout.flush()
    uiname = "bittorrent-console"
    defaults = get_defaults(uiname)
    config, args = configfile.parse_configuration_and_args(defaults,
                                       uiname, sys.argv[1:], 0, 1)
    
    core_doneflag = DeferredEvent()
    rawserver = RawServer(config)
    core_doneflag.addCallback(
            lambda r: rawserver.external_add_task(0, shutdown))
    rawserver.install_sigint_handler(core_doneflag)

    print "Creating IcmpIPC"
    icmp = IcmpIPC(rawserver)
    icmp.create()
    print "Starting IcmpIPC"
    icmp.start(message_dump)
    rawserver.listen_forever()
    
コード例 #21
0
    try:
        import hotshot
        import hotshot.stats
        prof_file_name = 'NewRateLimiter.prof'
    except ImportError, e:
        print "profiling not available:", e
        profile = False

    import random

    from BitTorrent.RawServer_twisted import RawServer
    from twisted.internet import task
    from BitTorrent.defer import DeferredEvent

    config = {}
    rawserver = RawServer(config)

    doneflag = DeferredEvent()
     
    s = Scheduler(4096, add_task = rawserver.add_task)
    s.unitsize = 17000

    a = []
    for i in xrange(500):
        keyable = FakeConnection(global_rate)
        a.append(keyable)

    freq = 0.01

    def push():
        if random.randint(0, 5 / freq) == 0:
コード例 #22
0
        config, args = configfile.parse_configuration_and_args(
            defaults, 'bittorrent', sys.argv[1:], 0, None)
        config['upnp'] = False
        config['one_connection_per_ip'] = False
        config['log_tracker_info'] = True
        config['rerequest_interval'] = 5
        config['min_peers'] = NUM_PEERS  # -1 for self but +1 for the http seed
        config['start_trackerless_client'] = False
        config['max_download_rate'] = 180 * 1024
        config['max_upload_rate'] = 30 * 1024
        config['max_files_open'] = 1
    except BTFailure, e:
        print unicode(e.args[0])
        sys.exit(1)

    rawserver = RawServer(Preferences().initWithDict(dict(config)))
    zurllib.set_zurllib_rawserver(rawserver)
    rawserver.install_sigint_handler()

from BitTorrent.MultiTorrent import MultiTorrent
from BTL.ThreadProxy import ThreadProxy
from BitTorrent.TorrentButler import DownloadTorrentButler, SeedTorrentButler
from BTL.formatters import Rate, Size, Duration


class ODict(dict):
    def __getattr__(self, attr):
        return self.get(attr)


def format_status(status):
コード例 #23
0
    def __init__(self, config, display, configfile_key):
      """Starts torrents for all .torrent files in a directory tree.

         All errors are logged using Python logging to 'configfile_key' logger.

         @param config: Preferences object storing config.
         @param display: output function for stats.
      """

      # 4.4.x version of LaunchMany output exceptions to a displayer.
      # This version only outputs stats to the displayer.  We do not use
      # the logger to output stats so that a caller-provided object
      # can provide stats formatting as opposed to using the
      # logger Formatter, which is specific to exceptions, warnings, and
      # info messages.
      self.logger = logging.getLogger(configfile_key)
      try:
        self.multitorrent = None
        self.rawserver = None
        self.config = config
        self.configfile_key = configfile_key
        self.display = display

        self.torrent_dir = config['torrent_dir']

        # Ex: torrent_cache = infohash -> (path,metainfo)
        self.torrent_cache = {}

        # maps path -> [(modification time, size), infohash]
        self.file_cache = {}

        # used as set containing paths of files that do not have separate
        # entries in torrent_cache either because torrent_cache already
        # contains the torrent or because the torrent file is corrupt.
        self.blocked_files = {}

        #self.torrent_list = [] 
        #self.downloads = {}

        self.hashcheck_queue = []
        #self.hashcheck_store = {}
        self.hashcheck_current = None
                         
        self.core_doneflag = DeferredEvent()
        self.rawserver = RawServer(self.config)
        try:
   
            # set up shut-down procedure before we begin doing things that
            # can throw exceptions.
            def shutdown():
                self.logger.critical(_("shutting down"))
                for t in self.multitorrent.get_torrents():
                    self.logger.info(_('dropped "%s"') %
                                    self.torrent_cache[t.infohash][0])
                if self.multitorrent:
                    df = self.multitorrent.shutdown()
                    set_flag = lambda *a : self.rawserver.stop()
                    df.addCallbacks(set_flag, set_flag)
                else:
                    self.rawserver.stop()
                
            # It is safe to addCallback here, because there is only one thread,
            # but even if the code were multi-threaded, core_doneflag has not
            # been passed to anyone.  There is no chance of a race condition
            # between the DeferredEvent's callback and addCallback.
            self.core_doneflag.addCallback(
                lambda r: self.rawserver.external_add_task(0, shutdown))

            self.rawserver.install_sigint_handler(self.core_doneflag)
    
            data_dir = config['data_dir']
            self.multitorrent = MultiTorrent(config, self.rawserver, data_dir,
                                             resume_from_torrent_config=False)
    
            self.rawserver.add_task(0, self.scan)
            self.rawserver.add_task(0.5, self.periodic_check_hashcheck_queue)
            self.rawserver.add_task(self.config['display_interval'],
                                    self.periodic_stats)
            
            try:
                import signal
                def handler(signum, frame):
                    self.rawserver.external_add_task(0, self.read_config)
                signal.signal(signal.SIGHUP, handler)
            except Exception, e:
                self.logger.error(_("Could not set signal handler: ") +
                                    str_exc(e))
                self.rawserver.add_task(0,self.core_doneflag.set())
  
        except UserFailure, e:
            self.logger.error(str_exc(e))
            self.rawserver.add_task(0,self.core_doneflag.set())
        except:
            data = StringIO()
            print_exc(file = data)
            self.logger.error(data.getvalue())
            self.rawserver.add_task(0,self.core_doneflag.set())
           
        # always make sure events get processed even if only for
        # shutting down.
        self.rawserver.listen_forever()
コード例 #24
0
ファイル: LocalDiscovery.py プロジェクト: safvan010/123
    def removeService(self, server, type, name):
        discovery_logger.info("Service %s removed", repr(name))

    def _got_peer(self, addr, infohash):
        if self.got_peer:
            self.got_peer(addr, infohash)

    def stop(self):
        self.port = None
        self.got_peer = None
        for service in self.services:
            self.unannounce(service)


if __name__ == '__main__':
    import string
    from BitTorrent.RawServer_twisted import RawServer
    from BitTorrent.PeerID import make_id

    rawserver = RawServer()

    def run_task_and_exit():
        l = LocalDiscovery(rawserver, 6881,
                           lambda *a: sys.stdout.write("GOT: %s\n" % str(a)))
        l.announce("63f27f5023d7e49840ce89fc1ff988336c514b64",
                   make_id().encode('hex'))

    rawserver.add_task(0, run_task_and_exit)

    rawserver.listen_forever()
コード例 #25
0
def message_dump(data):
    print "Received: ", data.encode("hex")


def shutdown():
    print "shutdown."
    rawserver.stop()


if __name__ == "__main__":
    print "test2"
    sys.stdout.flush()
    uiname = "bittorrent-console"
    defaults = get_defaults(uiname)
    config, args = configfile.parse_configuration_and_args(
        defaults, uiname, sys.argv[1:], 0, 1)

    core_doneflag = DeferredEvent()
    rawserver = RawServer(config)
    core_doneflag.addCallback(
        lambda r: rawserver.external_add_task(0, shutdown))
    rawserver.install_sigint_handler(core_doneflag)

    print "Creating IcmpIPC"
    icmp = IcmpIPC(rawserver)
    icmp.create()
    print "Starting IcmpIPC"
    icmp.start(message_dump)
    rawserver.listen_forever()
コード例 #26
0
ファイル: launchmanycore.py プロジェクト: skn/floodgate
    def __init__(self, config, display, configfile_key):
        """Starts torrents for all .torrent files in a directory tree.

         All errors are logged using Python logging to 'configfile_key' logger.

         @param config: Preferences object storing config.
         @param display: output function for stats.
      """

        # 4.4.x version of LaunchMany output exceptions to a displayer.
        # This version only outputs stats to the displayer.  We do not use
        # the logger to output stats so that a caller-provided object
        # can provide stats formatting as opposed to using the
        # logger Formatter, which is specific to exceptions, warnings, and
        # info messages.
        self.logger = logging.getLogger(configfile_key)
        try:
            self.multitorrent = None
            self.rawserver = None
            self.config = config
            self.configfile_key = configfile_key
            self.display = display

            self.torrent_dir = config['torrent_dir']

            # Ex: torrent_cache = infohash -> (path,metainfo)
            self.torrent_cache = {}

            # maps path -> [(modification time, size), infohash]
            self.file_cache = {}

            # used as set containing paths of files that do not have separate
            # entries in torrent_cache either because torrent_cache already
            # contains the torrent or because the torrent file is corrupt.
            self.blocked_files = {}

            #self.torrent_list = []
            #self.downloads = {}

            self.hashcheck_queue = []
            #self.hashcheck_store = {}
            self.hashcheck_current = None

            self.core_doneflag = DeferredEvent()
            self.rawserver = RawServer(self.config)
            try:

                # set up shut-down procedure before we begin doing things that
                # can throw exceptions.
                def shutdown():
                    self.logger.critical(_("shutting down"))
                    if self.multitorrent:
                        if len(self.multitorrent.get_torrents()) > 0:
                            for t in self.multitorrent.get_torrents():
                                self.logger.info(
                                    _('dropped "%s"') %
                                    self.torrent_cache[t.infohash][0])

                        def after_mt(r):
                            self.logger.critical(
                                "multitorrent shutdown completed. Calling rawserver.stop"
                            )
                            self.rawserver.stop()

                        self.logger.critical("calling multitorrent shutdown")
                        df = self.multitorrent.shutdown()
                        #set_flag = lambda *a : self.rawserver.stop()
                        df.addCallbacks(after_mt, after_mt)
                    else:
                        self.rawserver.stop()

                    ### PROFILER POSTPROCESSING.
                    #self.logger.critical( "Disabling profiles" )
                    #prof.disable()
                    #self.logger.critical( "Running profiler post-processing" )
                    #stats = Stats(prof.getstats())
                    #stats.sort("inlinetime")
                    #self.logger.info( "Calling stats.pprint")
                    #stats.pprint()
                    #self.logger.info( "After stats.pprint")
                    ### PROFILER POSTPROCESSING

                # It is safe to addCallback here, because there is only one thread,
                # but even if the code were multi-threaded, core_doneflag has not
                # been passed to anyone.  There is no chance of a race condition
                # between the DeferredEvent's callback and addCallback.
                self.core_doneflag.addCallback(
                    lambda r: self.rawserver.external_add_task(0, shutdown))

                self.rawserver.install_sigint_handler(self.core_doneflag)

                data_dir = config['data_dir']
                self.multitorrent = MultiTorrent(
                    config,
                    self.rawserver,
                    data_dir,
                    resume_from_torrent_config=False)

                # first time sleep_time is 0 so that it will startup fast.  On
                # subsequent scans, the scan is slowed down to not affect performance.
                self.rawserver.add_task(0, self.scan, sleep_time=0)
                self.rawserver.add_task(0.5,
                                        self.periodic_check_hashcheck_queue)
                self.rawserver.add_task(self.config['display_interval'],
                                        self.periodic_stats)

                try:
                    import signal

                    def handler(signum, frame):
                        self.rawserver.external_add_task(0, self.read_config)

                    if hasattr(signal, 'SIGHUP'):
                        signal.signal(signal.SIGHUP, handler)
                except Exception, e:
                    self.logger.error(
                        _("Could not set signal handler: ") + str_exc(e))
                    self.rawserver.add_task(0, self.core_doneflag.set)

            except UserFailure, e:
                self.logger.error(str_exc(e))
                self.rawserver.add_task(0, self.core_doneflag.set)
            except:
                #data = StringIO()
                #print_exc(file = data)
                #self.logger.error(data.getvalue())
                self.logger.exception(
                    "Exception raised while initializing LaunchMany")
                self.rawserver.add_task(0, self.core_doneflag.set)

            # always make sure events get processed even if only for
            # shutting down.
            self.rawserver.listen_forever()
            self.logger.info("After rawserver.listen_forever")
コード例 #27
0
class SimpleTests(TestCase):
    def setUp(self):
        d = dict([(x[0], x[1]) for x in common_options + rare_options])
        self.r = RawServer(d)
        self.a = self.r.create_udpsocket(8051, '127.0.0.1')
        self.b = self.r.create_udpsocket(8052, '127.0.0.1')

    def tearDown(self):
        self.a.close()
        self.b.close()

    def Handler(self, expected):
        class h(object):
            def __init__(self, expected, a=self.assertEqual):
                self.expected = expected
                self.a = a

            def data_came_in(self, connection, data):
                self.a(self.expected, data)

        return h(expected)

    def testFoo(self):
        self.r.start_listening_udp(self.a, self.Handler(''))
        self.r.start_listening_udp(self.b, self.Handler('foo'))
        self.a.sendto("foo", 0, ('127.0.0.1', 8052))
        self.r.listen_once()

    def testBackForth(self):
        self.r.start_listening_udp(self.a, self.Handler('bar'))
        self.r.start_listening_udp(self.b, self.Handler('foo'))
        self.a.sendto("foo", 0, ('127.0.0.1', 8052))
        self.r.listen_once()
        self.b.sendto("bar", 0, ('127.0.0.1', 8051))
        self.r.listen_once()
コード例 #28
0
ファイル: test_udp.py プロジェクト: galaxysd/BitTorrent
 def setUp(self):
     d = dict([(x[0],x[1]) for x in common_options + rare_options])
     self.r = RawServer(d)
     self.a = self.r.create_udpsocket(8051, '127.0.0.1')
     self.b = self.r.create_udpsocket(8052, '127.0.0.1')
コード例 #29
0
        print _("error: ") + str_exc(e)
        print _("run with -? for parameter explanations")
        return

    if config['dfile']=="":
        config['dfile'] = decode_from_filesystem(
            os.path.join(platform.get_temp_dir(), efs2(u"dfile") +
            str(os.getpid())))

    config = Preferences().initWithDict(config)
    ef = lambda e: errorfunc(logging.WARNING, e)
    platform.write_pid_file(config['pid'], ef)

    t = None
    try:
        r = RawServer(config)
        t = Tracker(config, r)
        try:
            #DEBUG
            print "track: create_serversocket, port=", config['port']
            #END
            s = r.create_serversocket(config['port'], config['bind'])
            handler = HTTPHandler(t.get, config['min_time_between_log_flushes'])
            r.start_listening(s, handler)
        except socket.error, e:
            print ("Unable to open port %d.  Use a different port?" %
                   config['port'])
            return

        r.listen_forever()
    finally:
コード例 #30
0
        config, args = configfile.parse_configuration_and_args(defaults,
                                        'bittorrent', sys.argv[1:], 0, None)
        config['upnp'] = False
        config['one_connection_per_ip'] = False
        config['log_tracker_info'] = True
        config['rerequest_interval'] = 5
        config['min_peers'] = NUM_PEERS # -1 for self but +1 for the http seed
        config['start_trackerless_client'] = False
        config['max_download_rate'] = 180*1024
        config['max_upload_rate'] = 30*1024
        config['max_files_open'] = 1
    except BTFailure, e:
        print unicode(e.args[0])
        sys.exit(1)

    rawserver = RawServer(Preferences().initWithDict(dict(config)))
    zurllib.set_zurllib_rawserver(rawserver)
    rawserver.install_sigint_handler()



from BitTorrent.MultiTorrent import MultiTorrent
from BTL.ThreadProxy import ThreadProxy
from BitTorrent.TorrentButler import DownloadTorrentButler, SeedTorrentButler
from BTL.formatters import Rate, Size, Duration

class ODict(dict):
    def __getattr__(self, attr):
        return self.get(attr)

def format_status(status):
コード例 #31
0
ファイル: test_events.py プロジェクト: galaxysd/BitTorrent
from BitTorrent.RawServer_twisted import RawServer
from twisted.internet import defer
from twisted.internet import reactor

config = {'max_incomplete': 10,
          'max_upload_rate': 350000,
          'bind': '',
          'close_with_rst': False,
          'socket_timeout': 3000}

m = 20000
a = [None] * m
i = 0

if __name__ == '__main__':
    rawserver = RawServer(config=config, noisy=True)

    rawserver.install_sigint_handler()    

    def avg_dist(l):
        d = []
        p = None
        for x in l:
            if p is not None:
                d.append(x - p)
            p = x
        return sum(d) / len(d)

    def rerun():
        #print '.'
        global i
コード例 #32
0
 def setUp(self):
     d = dict([(x[0], x[1]) for x in common_options + rare_options])
     self.r = RawServer(d)
     self.a = self.r.create_udpsocket(8051, '127.0.0.1')
     self.b = self.r.create_udpsocket(8052, '127.0.0.1')
コード例 #33
0
ファイル: InitTableTest.py プロジェクト: hitzjd/DHT
 def __init__(self):
     self.config, self.metainfo = self._load_settings()
     self.rawserver = RawServer(self.config)
     self.dht = UTKhashmir(self.config['bind'], self.config['port'],
                           self.config['dumpDir'], self.rawserver)
コード例 #34
0
class KhashmirBase:
    _Node = KNodeBase

    def __init__(self,
                 host,
                 port,
                 data_dir,
                 rawserver=None,
                 max_ul_rate=1024,
                 checkpoint=True,
                 errfunc=None,
                 rlcount=foo,
                 config={
                     'pause': False,
                     'max_rate_period': 20
                 }):
        if rawserver:
            self.rawserver = rawserver
        else:
            self.flag = Event()
            d = dict([(x[0], x[1]) for x in common_options + rare_options])
            self.rawserver = RawServer(self.flag, d)
        self.max_ul_rate = max_ul_rate
        self.socket = None
        self.config = config
        self.setup(host, port, data_dir, rlcount, checkpoint)

    def setup(self, host, port, data_dir, rlcount, checkpoint=True):
        self.host = host
        self.port = port
        self.ddir = data_dir
        self.store = KStore()
        self.pingcache = {}
        self.socket = self.rawserver.create_udpsocket(self.port, self.host)
        self.udp = krpc.hostbroker(self, (self.host, self.port), self.socket,
                                   self.rawserver.add_task, self.max_ul_rate,
                                   self.config, rlcount)
        self._load()
        self.rawserver.start_listening_udp(self.socket, self.udp)
        self.last = time()
        KeyExpirer(self.store, self.rawserver.add_task)
        self.refreshTable(force=1)
        if checkpoint:
            self.rawserver.add_task(30, self.findCloseNodes, lambda a: a, True)
            self.rawserver.add_task(60, self.checkpoint, 1)

    def Node(self):
        n = self._Node(self.udp.connectionForAddr)
        n.table = self
        return n

    def __del__(self):
        if self.socket is not None:
            self.rawserver.stop_listening_udp(self.socket)
            self.socket.close()

    def _load(self):
        do_load = False
        try:
            s = open(os.path.join(self.ddir, "routing_table"), 'r').read()
            dict = bdecode(s)
        except:
            id = newID()
        else:
            id = dict['id']
            do_load = True

        self.node = self._Node(self.udp.connectionForAddr).init(
            id, self.host, self.port)
        self.table = KTable(self.node)
        if do_load:
            self._loadRoutingTable(dict['rt'])

    def checkpoint(self, auto=0):
        d = {}
        d['id'] = self.node.id
        d['rt'] = self._dumpRoutingTable()
        try:
            f = open(os.path.join(self.ddir, "routing_table"), 'wb')
            f.write(bencode(d))
            f.close()
        except Exception, e:
            #XXX real error here
            print ">>> unable to dump routing table!", str(e)
            pass

        if auto:
            self.rawserver.add_task(
                randrange(int(const.CHECKPOINT_INTERVAL * .9),
                          int(const.CHECKPOINT_INTERVAL * 1.1)),
                self.checkpoint, 1)
コード例 #35
0
class KhashmirBase:
    _Node = KNodeBase
    def __init__(self, host, port, data_dir, rawserver=None, max_ul_rate=1024, checkpoint=True, errfunc=None, rlcount=foo, config={'pause':False, 'max_rate_period':20}):
        if rawserver:
            self.rawserver = rawserver
        else:
            self.flag = Event()
            d = dict([(x[0],x[1]) for x in common_options + rare_options])            
            self.rawserver = RawServer(self.flag, d)
        self.max_ul_rate = max_ul_rate
        self.socket = None
        self.config = config
        self.setup(host, port, data_dir, rlcount, checkpoint)

    def setup(self, host, port, data_dir, rlcount, checkpoint=True):
        self.host = host
        self.port = port
        self.ddir = data_dir
        self.store = KStore()
        self.pingcache = {}
        self.socket = self.rawserver.create_udpsocket(self.port, self.host, False)
        self.udp = krpc.hostbroker(self, (self.host, self.port), self.socket, self.rawserver.add_task, self.max_ul_rate, self.config, rlcount)
        self._load()
        self.rawserver.start_listening_udp(self.socket, self.udp)
        self.last = time()
        KeyExpirer(self.store, self.rawserver.add_task)
        self.refreshTable(force=1)
        if checkpoint:
            self.rawserver.add_task(30, self.findCloseNodes, lambda a: a, True)
            self.rawserver.add_task(60, self.checkpoint, 1)

    def Node(self):
        n = self._Node(self.udp.connectionForAddr)
        n.table = self
        return n
    
    def __del__(self):
        if self.socket is not None:
            self.rawserver.stop_listening_udp(self.socket)
            self.socket.close()
        
    def _load(self):
        do_load = False
        try:
            s = open(os.path.join(self.ddir, "routing_table"), 'r').read()
            dict = bdecode(s)
        except:
            id = newID()
        else:
            id = dict['id']
            do_load = True
            
        self.node = self._Node(self.udp.connectionForAddr).init(id, self.host, self.port)
        self.table = KTable(self.node)
        if do_load:
            self._loadRoutingTable(dict['rt'])

        
    def checkpoint(self, auto=0):
        d = {}
        d['id'] = self.node.id
        d['rt'] = self._dumpRoutingTable()
        try:
            f = open(os.path.join(self.ddir, "routing_table"), 'wb')
            f.write(bencode(d))
            f.close()
        except Exception, e:
            #XXX real error here
            print ">>> unable to dump routing table!", str(e)
            pass
        
        
        if auto:
            self.rawserver.add_task(randrange(int(const.CHECKPOINT_INTERVAL * .9),
                                              int(const.CHECKPOINT_INTERVAL * 1.1)),
                                    self.checkpoint, 1)
コード例 #36
0
ファイル: bittorrent.py プロジェクト: forkable/p2pScrapper
    try:
        config, args = configfile.parse_configuration_and_args(defaults,
                                        'bittorrent', sys.argv[1:], 0, None)
        if debug:
            config['upnp'] = False
            config['one_connection_per_ip'] = False

    except BTFailure, e:
        print unicode(e.args[0])
        sys.exit(1)

    config = Preferences().initWithDict(config)
    # bug set in DownloadInfoFrame

    rawserver = RawServer(config)
    zurllib.set_zurllib_rawserver(rawserver)
    rawserver.install_sigint_handler()

    ipc = ipc_interface(rawserver, config, "controlsocket")

    # make sure we clean up the ipc when everything is done
    atexit_threads.register_verbose(ipc.stop)

    # this could be on the ipc object
    ipc_master = True
    try:
        if not config['use_factory_defaults']:
            ipc.create()
    except BTFailure, e:
        ipc_master = False
コード例 #37
0
class BTAppController(NibClassBuilder.AutoBaseClass):
    def init(self):
        self = super(BTAppController, self).init()
        self.prefs = Preferences.alloc().init()
        self.prefwindow = None
        self.generator = Generate.alloc().init()

        self.ic = ICHelper.alloc().init()

        # displayed torrent controllers
        self.torrents = []

        # waiting to die
        self.dead_torrents = []

        # ready to start
        # (<open panel>, <insert row>, (<filename>|<stream>, <is_stream>))  -1 insert row means use last row
        # stream = 0 if filename, 1 if bencoded torrent file
        self.tqueue = []

        self.retain()
        self.inited = 0
        self.launched = 0
        self.in_choose = 0
        self.last_qcheck = time()

        self.sc = 0
        self.defaults = NSUserDefaults.standardUserDefaults()

        self.tup = bdecode(self.defaults.objectForKey_(ULBYTES))
        self.tdown = bdecode(self.defaults.objectForKey_(DLBYTES))

        self.config = common_options + rare_options
        self.config = BTPreferences().initWithDict(
            dict([(name, value) for (name, value, doc) in self.config]))

        self.config['data_dir'] = PREFDIR

        self.config['bind'] = ''
        self.config['bad_libc_workaround'] = True
        self.config['filesystem_encoding'] = 'utf8'
        #XXXX
        #self.config['start_trackerless_client'] = False

        self.legacyConfig()
        self.reloadConfig()

        self.pyi = None

        self.doneflag = Event()

        if not os.path.exists(PREFDIR):
            os.mkdir(PREFDIR)
        if not os.path.exists(RESDIR):
            os.mkdir(RESDIR)

        self.ticon = None

        self.stalled = []
        self.terminated = False

        return self

    def loadConsole_(self, sender):
        if not self.pyi:
            self.pyi = PyInterpreter.alloc().init()
            NSBundle.loadNibNamed_owner_("PyInterpreter", self.pyi)
        else:
            self.pyi.textView.window().makeKeyAndOrderFront_(self)

    def legacyConfig(self):
        n = self.defaults.integerForKey_(QUEUESTOP)
        if n > 1:
            self.defaults.setObject_forKey_(0, QUEUESTOP)

    def reloadConfig(self):
        self.config['minport'] = self.defaults.integerForKey_(MINPORT)
        self.config['maxport'] = self.defaults.integerForKey_(MINPORT)
        self.config['max_upload_rate'] = self.defaults.integerForKey_(
            MAXULRATE)
        self.config['max_allow_in'] = self.defaults.integerForKey_(MAXACCEPT)
        self.config['max_initiate'] = self.defaults.integerForKey_(MAXINITIATE)
        self.config['max_uploads'] = self.defaults.integerForKey_(MAXULS)

    def listen_forever(self):
        pool = NSAutoreleasePool.alloc().init()
        # XXX
        #self.profile = Profile("BT.prof");self.profile.start()
        self.rawserver = RawServer(self.config)
        self.mt = MultiTorrent(self.config, self.doneflag, self.rawserver,
                               self.multi_errorfunc, self.config['data_dir'])
        self.rawserver.ident = thread.get_ident()
        self.mt.set_option("max_upload_rate",
                           self.config['max_upload_rate'] * 1024)
        self.rawserver.listen_forever(self.doneflag)
        #self.profile.stop();self.profile.close()

    def multi_errorfunc(self, level, text):
        if level == CRITICAL:
            self.statusField.setStringValue_(
                NSLocalizedString("Critical Error: %s", "critical error") %
                text)
            # bomb out
        elif level == ERROR:
            self.statusField.setStringValue_(
                NSLocalizedString("Error: %s", "normal error") % text)
        elif level == WARNING:
            print ">>>", NSLocalizedString("Warning: %s",
                                           "warning error") % text
        elif level == INFO:
            print ">>>", NSLocalizedString("Info: %s", "info error") % text

    def awakeFromNib(self):
        if not self.inited:
            self.inited = 1
            NSBundle.loadNibNamed_owner_("TorrentWindow", self)
            self.drawerMenu.setTarget_(self.logDrawer)
            self.drawerMenu.setAction_(self.logDrawer.toggle_)
            self.logDrawer.delegate().menu = self.drawerMenu
            self.torrentTable.registerForDraggedTypes_([NSFilenamesPboardType])

    def openPage_(self, sender):
        NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(URL))

    def openHomePage_(self, sender):
        NSWorkspace.sharedWorkspace().openURL_(
            NSURL.URLWithString_("http://www.bittorrent.com/"))

    def nag(self):
        nag = self.defaults.objectForKey_(NAG)
        if nag == 0 or (nag != BitTorrent.version and randint(0, 2) == 0):
            if nag == 0:
                self.defaults.setObject_forKey_(1, NAG)
            NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(URL))
            x = NSRunAlertPanel(
                NSLocalizedString("Please Donate", "nag window title"),
                NSLocalizedString(
                    "If you like BitTorrent and want to see more cool apps from the author, you should make a donation.",
                    "nag message"), NSLocalizedString("Later", "nag later"),
                NSLocalizedString("Already Donated", "nag already"), None)
            if x == NSAlertAlternateReturn:
                self.defaults.setObject_forKey_(BitTorrent.version, NAG)
                NSRunInformationalAlertPanel(
                    NSLocalizedString("Thank You", "Thank You"),
                    NSLocalizedString(
                        "Thank you for making a donation.  You will not be bothered with donation requests until you upgrade.",
                        "thanks for donating"), NSLocalizedString("OK", "OK"),
                    None, None)

    def applicationDidFinishLaunching_(self, aNotification):
        try:
            NSThread.detachNewThreadSelector_toTarget_withObject_(
                self.listen_forever, self, None)
        except BTFailure, e:
            err = str(e)
            if err.startswith("Could not open a listening port"):
                p = PortChanger.alloc().initWithErr(err)
            else:
                x = NSRunAlertPanel(
                    NSLocalizedString("Fatal Error", "fatal error"),
                    NSLocalizedString(
                        "Failed to initialize BitTorrent core.  Error: %s",
                        "bittorrent failure message") % str(e), None, None,
                    None)
                NSApp().terminate_(self)

        self.launched = 1

        #self.profile = Profile("BT.prof")
        #self.profile.start()

        tcell = PyTimeCell.alloc().init()
        fcell = PyFileCell.alloc().init()
        xcell = PyXFerCell.alloc().init()

        cols = self.torrentTable.tableColumns()
        for c in cols:
            #c.setHeaderCell_(TorrentTableHeaderCell.alloc().initTextCell_(c.headerCell().stringValue()))
            if c.identifier() == 'time':
                c.setDataCell_(tcell)
            elif c.identifier() == 'file':
                c.setDataCell_(fcell)
            elif c.identifier() == 'xfer':
                c.setDataCell_(xcell)

        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, self._otorrent, "DoneChoosingTorrent", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, self.saveTorrents, "NSWorkspaceWillPowerOffNotification",
            None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, self.moveTorrent, "NSTableViewColumnDidMoveNotification",
            None)

        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
            1.5, self, self.updateStatus, None, 1)
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
            10, self, self.checkQueue, None, 1)
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
            300, self, self.saveTorrents, None, 1)

        self.loadTorrents()

        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, self.reapDead, "TorrentStatusChanged", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, self.statusChanged, "TorrentStatusChanged", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, self.updateCycleMenu, "TorrentStatusChanged", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, self.updateCycleMenu, "TorrentSelectionChanged", None)

        if defaults.objectForKey_(VERSIONCHECK):
            self.checkVersion()

        # open any torrents waiting
        self.otorrent(None)