Beispiel #1
0
def round():
    global session, mygames, myinvite, rounds
    gc = GameCast.getInstance()
    gc_db = session.open_dbhandler(NTFY_GAMECAST)
    if not myinvite and len(mygames) < MAXBOTS:
        # Send out a new random game/invite
        game = {}
        game['game_id'] = gc_db.getNextGameID(0)
        game['owner_id'] = 0
        game['winner_permid'] = ''
        game['moves'] = bencode([])
        mycolour = random.choice(['black','white'])
        mypermid = bin2str(session.get_permid())
        players = {mypermid:mycolour}
        game['players'] = bencode(players)
        game['gamename'] = 'chess'
        game['time'] = random.choice([10,20,30])
        game['inc'] = random.choice([60,120,180])
        game['is_finished'] = 0
        game['lastmove_time'] = 0
        game['creation_time'] = 0
        gc_db.addGame(game)
        invite = {}
        invite['target_id'] = -1
        invite['game_id'] = game['game_id']
        invite['min_rating'] = 0
        invite['max_rating'] = 9999
        invite['time'] = game['time']
        invite['inc'] = game['inc']
        invite['gamename'] = 'chess'
        if mycolour == 'black':
            invite['colour'] = 'white'
        else:
            invite['colour'] = 'black'
        if DEBUG:
            print >> sys.stderr, 'chessbot: sending out invite for game (%d,%d)' % (0, game['game_id'])
        myinvite = gc._executeSeekOrMatch(invite)
    elif myinvite:
        # Check if the game related to our invite has started yet
        owner_id = myinvite['owner_id']
        game_id = myinvite['game_id']
        games = gc_db.getGames(game_id = game_id, owner_id = owner_id)
        if games and len(games) == 1:
            game = games[0]
            if game['creation_time']:
                # Game has started
                myinvite = None
                mygames.append((owner_id, game_id))
                if DEBUG:
                    print >> sys.stderr, 'chessbot: starting chessbot for game (%d,%d)' % (owner_id, game_id)
                func = lambda:launchchessbot(game)
                overlay_bridge.add_task(func, 0)
            else:
                # Game has not yet started, resend the invite
                if int(time()) > myinvite['creation_time']+INV_EXPIRE_TIME:
                    myinvite = None
                elif (rounds % 5) == 0:
                    gc.resendSeek(myinvite)
        else:
            myinvite = None
 def create_bad_metadata_bad_torrent3(self):
     torrent = {'info':481}
     data = bencode(torrent)
     
     d = self.create_good_metadata_dict(data)
     d['metadata'] = data
     bd = bencode(d)
     return METADATA+bd
    def create_bad_metadata_bad_torrent2(self):
        torrent = {}
        data = bencode(torrent)

        d = self.create_good_metadata_dict(data)
        d["metadata"] = data
        bd = bencode(d)
        return METADATA + bd
 def create_good_simpleplustorrents_reply(self,id):
     d = self.create_good_simple_reply_dict(id)
     bmetainfo = bencode(self.tdef.get_metainfo())
     d['a'][self.tdef.get_infohash()]['torrent_size'] = len(bmetainfo)
     d['a'][self.tdef.get_infohash()]['metatype'] = 'application/x-tribler-stream' 
     d['a'][self.tdef.get_infohash()]['metadata'] = bmetainfo 
     b = bencode(d)
     return QUERY_REPLY+b
Beispiel #5
0
    def create_bad_metadata_bad_torrent3(self):
        torrent = {'info': 481}
        data = bencode(torrent)

        d = self.create_good_metadata_dict(data)
        d['metadata'] = data
        bd = bencode(d)
        return METADATA + bd
Beispiel #6
0
    def save_torrent(self, torrent_data, source = ''):
        if 'info' in torrent_data:
            infohash = sha.sha(bencode(torrent_data['info'])).digest()
            if not self.torrent_db.hasTorrent(infohash):
                if DEBUG:
                    print >>sys.stderr,"subscrip:Injecting", torrent_data["info"].get("name", infohash)
                
                hexinfohash = binascii.hexlify(infohash)
                if DEBUG:
                    print >>sys.stderr,"subscript: Writing",hexinfohash
        
                filename = os.path.join(self.torrent_dir, hexinfohash+'.torrent' )
                f = open(filename,"wb")
                f.write(bencode(torrent_data))
                f.close()
        
                # Arno: hack, make sure these torrents are always good so they show up
                # in Torrent DBHandler.getTorrents()
                extra_info = {'status':'good'}
                extra_info['filename'] = filename
                
                torrentdef = TorrentDef.load_from_dict(torrent_data)
                self.torrent_db.addExternalTorrent(torrentdef,source=source,extra_info=extra_info)
                        
        # perform all url-specific callbacks
        for feed, on_torrent_callback, callback in self.feeds:
            if feed.feed_url == source:
                if on_torrent_callback:
                    if DEBUG: 
                        print >> sys.stderr , "ON TORRENT CALLBACK"
                    on_torrent_callback(source, infohash, torrent_data)
                if callback:
                    if DEBUG: 
                        print >> sys.stderr , "USER CALLBACK"
                    callback(source, infohash, torrent_data)
                break

        # perform all non-url-specific callbacks
        self.lock.acquire()
        callbacks = self.callbacks[:]
        self.lock.release()
        
        for callback in callbacks:
            try:
                if DEBUG:
                    print >> sys.stderr , "RSS CALLBACK"
                callback(source, infohash, torrent_data)
            except:
                traceback.print_exc()
    def subtest_good_friendship_stats(self):
        """
        Send a valid message-id from a registered crawler peer
        """
        print >>sys.stderr, "-"*80, "\ntest: good friendship stats"

        s = OLConnection(self.my_keypair, "localhost", self.hisport)

        t = time.time() - 100.0
        msg_dict = {'current time':int(t)}
        payload = bencode(msg_dict)
        self.send_crawler_request(s, CRAWLER_FRIENDSHIP_STATS, 0, 0, payload)

        error, payload = self.receive_crawler_reply(s, CRAWLER_FRIENDSHIP_STATS, 0)
        assert error == 0
        
        d = bdecode(payload)
        if DEBUG:
            print >>sys.stderr, "test: Got FRIENDSHIPSTATISTICS",`d`
        stats = d['stats']
        self.assert_(len(stats) == 1)
        record = d['stats'][0]
        self.assert_(record[0] == bin2str(self.his_permid))  # source_permid
        self.assert_(record[1] == bin2str(self.some_permid)) # target_permid
        self.assert_(record[2] == 0) # isForwarder

        time.sleep(1)
        s.close()
Beispiel #8
0
    def olthread_proxy_unhave_connect_callback(self, exc, dns, permid,
                                               selversion, aggregated_string):
        """ Sends the proxy_unhave message on the connection with the doe
        
        Called by the overlay thread.
        
        @param exc: Peer reachable/unreachable information. None = peer reachable
        @param dns:
        @param permid: the permid of the doe
        @param selversion: selected Overlay protocol version
        @param aggregated_string: a bitstring of available pieces
        """
        if exc is None:
            # Create message according to protocol version
            message = PROXY_HAVE + self.infohash + bencode(aggregated_string)

            if DEBUG:
                print >> sys.stderr, "proxy: olthread_proxy_unhave_connect_callback: Sending PROXY_UNHAVE to", show_permid_short(
                    permid)

            # Connect using Tribler Ovrlay Swarm
            self.overlay_bridge.send(permid, message,
                                     self.olthread_proxy_unhave_send_callback)
        elif DEBUG:
            # The doe is unreachable
            print >> sys.stderr, "proxy: olthread_proxy_unhave_connect_callback: error connecting to", show_permid_short(
                permid), exc
    def udpConnect(self, permid, request_id, holePunchingAddr):

        if DEBUG:
            print >> sys.stderr, "NatCheckMsgHandler: request UDP connection"

        mh_data = request_id + ":" + holePunchingAddr[0] + ":" + str(
            holePunchingAddr[1])

        if DEBUG:
            print >> sys.stderr, "NatCheckMsgHandler: udpConnect message is", mh_data

        try:
            mh_msg = bencode(mh_data)
        except:
            print_exc()
            if DEBUG:
                print >> sys.stderr, "NatCheckMsgHandler: error mh_data:", mh_data
            return False

        # send the message
        self.crawler.send_request(permid,
                                  CRAWLER_NATTRAVERSAL,
                                  mh_msg,
                                  frequency=0,
                                  callback=self.udpConnectCallback)

        if DEBUG:
            print >> sys.stderr, "NatCheckMsgHandler: request for", show_permid_short(
                permid), "sent to crawler"
 def test_createSingleResponseMessage(self):
     langUtil = LanguagesProvider.getLanguagesInstance()
     data = {
             'permid' : testDestPermId,
             'channel_id' : testChannelId,
             'infohash' : testInfohash,
             'subtitles' : {"eng" : "This is content 1", "nld": "This is content  2",
                            "ita" : "This is content 3"},
             'selversion' : OLPROTO_VER_FOURTEENTH
             }
     langs = data['subtitles'].keys()
     
     bitmask = langUtil.langCodesToMask(langs)
     binaryBitmask = pack("!L", bitmask)
     expextedMessage = SUBS + \
                         bencode((
                                 data['channel_id'],
                                 data['infohash'],
                                 binaryBitmask,
                                 [data['subtitles']['eng'], data['subtitles']['ita'],
                                  data['subtitles']['nld']]
                                  ))
     msg = self.underTest._createSingleResponseMessage(data)
     decoded = bdecode(msg[1:])
     
     self.assertEquals(expextedMessage, msg)
 def test_receivedSUBSOtherRequest(self):
     langUtil = LanguagesProvider.getLanguagesInstance()
     data = {
             'permid' : testDestPermId,
             'channel_id' : testChannelId,
             'infohash' : testInfohash,
             'subtitles' : {"eng" : "This is content 1", "nld": "This is content  2",
                            "ita" : "This is content 3"},
             'selversion' : OLPROTO_VER_FOURTEENTH
             }
     langs = data['subtitles'].keys()
     
     bitmask = langUtil.langCodesToMask(langs)
     binaryBitmask = pack("!L", bitmask)
     expextedMessage = SUBS + \
                         bencode((
                                 data['channel_id'],
                                 data['infohash'],
                                 binaryBitmask,
                                 [data['subtitles']['eng'], data['subtitles']['ita'],
                                  data['subtitles']['nld']]
                                  ))
     
     list = MockMsgListener()
     self.underTest.registerListener(list) 
     
     #invalid bitmask
     self.underTest._addToRequestedSubtitles(testChannelId, testInfohash, int(0xFFFFFFFF & ~bitmask), None)                   
     
     val = self.underTest.handleMessage(testDestPermId, OLPROTO_VER_FOURTEENTH, expextedMessage)
     # never had a request for this message should be dropped
     self.assertFalse(val)
     self.assertEquals(0,list.subsCount)
    def setUpPostSession(self):
        """ override TestAsServer """
        TestAsServer.setUpPostSession(self)

        self.mypermid = str(self.my_keypair.pub().get_der())
        self.hispermid = str(self.his_keypair.pub().get_der())  
        
        # Calculating the infohash for proxyservice.test.torrent
        self.torrentfile = os.path.join('extend_hs_dir','proxyservice.test.torrent')
        
        # Read torrentfile to calculate the infohash
        torrentfile_content = open(self.torrentfile, "rb")
        # Decode all the file
        metainfo = bdecode(torrentfile_content.read())
        # Re-encode only the info section
        self.infohash = hashlib.sha1(bencode(metainfo['info'])).digest()
        # Close the torrentfile
        torrentfile_content.close()
        
        # Add us as friend, so he will accept the ASK_FOR_HELP
        if False:  # TEMP
            friendsdb = FriendDBHandler.getInstance()
            friendsdb.addFriend(self.mypermid)
        else:
            self.session.set_overlay_request_policy(AllowAllRequestPolicy())
          
        self.session.set_download_states_callback(self.states_callback)
Beispiel #13
0
    def do_GET(self):

        print >> sys.stderr, "test: tracker: Got GET request", self.path

        p = []
        p1 = {
            'peer id': self.server.myid,
            'ip': self.server.myip,
            'port': self.server.myport
        }
        p.append(p1)
        d = {}
        d['interval'] = 1800
        d['peers'] = p
        bd = bencode(d)
        size = len(bd)

        self.send_response(200)
        self.send_header("Content-Type", "application/octet-stream")
        self.send_header("Content-Length", size)
        self.end_headers()

        try:
            self.wfile.write(bd)
        except Exception, e:
            print_exc(file=sys.stderr)
Beispiel #14
0
 def createAndSendChannelCastMessage(self, target_permid, selversion):
     """ Create and send a ChannelCast Message """
     # ChannelCast feature starts from eleventh version; hence, do not send to lower version peers
     if selversion < OLPROTO_VER_ELEVENTH:
         if DEBUG:
             print >> sys.stderr, time.asctime(),'-', "Do not send to lower version peer:", selversion
         return
     
     channelcast_data = self.createChannelCastMessage()
     if channelcast_data is None or len(channelcast_data)==0:
         if DEBUG:
             print >>sys.stderr, time.asctime(),'-', "No channels there.. hence we do not send"
         #self.session.chquery_connected_peers('k:MFIwEAYHKoZIzj0CAQYFK4EEABoDPgAEAf3BkHsZ6UdIpuIX441wjU5Ybe0HPjTDvS+iacFZABH20It9N9uwkwtpkS3uEvVvfcTX50jcFNXOSCwq')            
         return
     channelcast_msg = bencode(channelcast_data)
     
     if self.log:
         dns = self.dnsindb(target_permid)
         if dns:
             ip,port = dns
             MSG_ID = "CHANNELCAST"
             msg = repr(channelcast_data)
             self.overlay_log('SEND_MSG', ip, port, show_permid(target_permid), selversion, MSG_ID, msg)
     
     data = CHANNELCAST + channelcast_msg
     self.secure_overlay.send(target_permid, data, self.channelCastSendCallback)        
     if DEBUG: print >> sys.stderr, time.asctime(),'-', "Sent channelcastmsg",repr(channelcast_msg)
 def create_ohlist_wrong_no_hashes(self,chunkid):
     index,begin,length = chunkid
     ohlist = [ (0,'#' * 20),(1,'$' * 20)]  # should contain 3 for file2.wmv: own, sibling and root
     bohlist = bencode(ohlist)
     chunk = '*' * (2 ** 14)
     payload = tobinary(index)+tobinary(begin)+tobinary(len(bohlist))+bohlist+chunk
     return EXTEND+HASHPIECE+payload
Beispiel #16
0
    def ValueToString(self, value, typex):
        if typex == "boolean":
            if value:
                text = "1"
            else:
                text = "0"
        elif typex == "color":
            red = str(value.Red())
            while len(red) < 3:
                red = "0" + red

            green = str(value.Green())
            while len(green) < 3:
                green = "0" + green

            blue = str(value.Blue())
            while len(blue) < 3:
                blue = "0" + blue

            text = str(red) + str(green) + str(blue)
        elif typex.startswith("bencode"):
            text = bencode(value)
        else:
            if type(value) is unicode:
                text = value
            else:
                text = str(value)

        return text
Beispiel #17
0
 def createAndSendChannelCastMessage(self, target_permid, selversion):
     """ Create and send a ChannelCast Message """
     # ChannelCast feature starts from eleventh version; hence, do not send to lower version peers
     # Arno, 2010-02-05: v12 uses a different on-the-wire format, ignore those.
     
     # Andrea, 2010-04-08: sending the "old-style" channelcast message to older
     # peers, and enriched channelcast messages to new versions, for full backward
     # compatibility
     if selversion < OLPROTO_VER_THIRTEENTH:
         if DEBUG:
             print >> sys.stderr, "channelcast: Do not send to lower version peer:", selversion
         return
     
     # 3/5/2010 Andrea: adding the destination parameters to createChannelCastMessage for
     # logging reasons only. When logging will be disabled, that parameter will
     # become useless
     channelcast_data = self.createChannelCastMessage(selversion, target_permid)
     if channelcast_data is None or len(channelcast_data)==0:
         if DEBUG:
             print >>sys.stderr, "channelcast: No channels there.. hence we do not send"
         return
     channelcast_msg = bencode(channelcast_data)
     
     if self.log:
         dns = self.dnsindb(target_permid)
         if dns:
             ip,port = dns
             MSG_ID = "CHANNELCAST"
             msg = repr(channelcast_data)
             self.overlay_log('SEND_MSG', ip, port, show_permid(target_permid), selversion, MSG_ID, msg)
     
     data = CHANNELCAST + channelcast_msg
     self.overlay_bridge.send(target_permid, data, self.channelCastSendCallback)        
Beispiel #18
0
 def check_response1(self, resp1_data, rB, myid):
     resp1 = bdecode(resp1_data)
     self.assert_(type(resp1) == DictType)
     self.assert_(resp1.has_key('certA'))
     self.assert_(resp1.has_key('rA'))
     self.assert_(resp1.has_key('B'))
     self.assert_(resp1.has_key('SA'))
     # show throw exception when key no good
     pubA = EC.pub_key_from_der(resp1['certA'])
     rA = resp1['rA']
     self.assert_(type(rA) == StringType)
     self.assert_(len(rA) == random_size)
     B = resp1['B']
     self.assert_(type(B) == StringType)
     self.assert_(B, myid)
     SA = resp1['SA']
     self.assert_(type(SA) == StringType)
     # verify signature
     sig_list = [rA, rB, myid]
     sig_data = bencode(sig_list)
     sig_hash = sha.sha(sig_data).digest()
     self.assert_(pubA.verify_dsa_asn1(sig_hash, SA))
     # Cannot resign the data with his keypair to double check. Signing
     # appears to yield different, supposedly valid sigs each time.
     return resp1
Beispiel #19
0
 def create_added_f_too_big(self):
     d = {}
     d['added'] = ''
     d['added.f'] = '\x00'
     d['dropped'] = ''
     bd = bencode(d)
     return EXTEND+chr(1)+bd
Beispiel #20
0
 def create_dropped_too_small(self):
     d = {}        
     d['added'] = ''
     d['added.f'] = ''
     d['dropped'] = '\x82\x25\xc1\x40\x00' # should be 6 bytes
     bd = bencode(d)
     return EXTEND+chr(1)+bd
Beispiel #21
0
 def create_good_nontribler_extend_hs(self):
     d = {}
     d['m'] = {'hallo': 12, 'dag': 255}
     d['p'] = self.mylistenport
     d['v'] = 'TestSweet 1.2.3.4'
     bd = bencode(d)
     return EXTEND + chr(0) + bd
Beispiel #22
0
 def create_dropped_not_str(self):
     d = {}
     d['added'] = ''
     d['added.f'] = ''
     d['dropped'] = 481
     bd = bencode(d)
     return EXTEND+chr(1)+bd
Beispiel #23
0
 def create_good_tribler_extend_hs(self):
     d = {}
     d['m'] = {'Tr_OVERLAYSWARM': 253}
     d['p'] = self.mylistenport
     d['v'] = 'Tribler 3.5.1'
     bd = bencode(d)
     return EXTEND + chr(0) + bd
Beispiel #24
0
 def create_good_ut_pex(self,pex_id=1):
     d = {}
     d['added'] = ''
     d['added.f'] = ''
     d['dropped'] = ''
     bd = bencode(d)
     return EXTEND+chr(pex_id)+bd
Beispiel #25
0
 def create_dropped_too_small(self):
     d = {}
     d['added'] = ''
     d['added.f'] = ''
     d['dropped'] = '\x82\x25\xc1\x40\x00'  # should be 6 bytes
     bd = bencode(d)
     return EXTEND + chr(1) + bd
Beispiel #26
0
 def create_diff_ips(self, i):
     if self.NLISTENERS == 1:
         s = REPLY_IP
     else:
         s = '127.0.0.' + str(i)
     b = bencode(s)
     return DIALBACK_REPLY + b
 def create_not_hashpiece(self,chunkid):
     index,begin,length = chunkid
     ohlist = []
     bohlist = bencode(ohlist)
     chunk = self.read_chunk(index,begin,length)
     payload = tobinary(index)+tobinary(begin)+tobinary(len(bohlist))+bohlist+chunk
     return EXTEND+chr(231)+payload
    def _create_poa_message(self, msg_id, nonce_a, nonce_b):
        """
        Create the POA exchange message (messages 3 and 4).
        """
        assert msg_id
        assert nonce_a
        assert nonce_b
        assert self.poa
        
        # Provide the certificate 
        if not self.poa:
            raise MissingCertificateException("Missing certificate")

        msg = [msg_id] + self.poa.serialize_to_list()

        # Add signature
        lst = [nonce_a,
               nonce_b,
               self.poa.serialize()]
        
        b_list = bencode(lst)
        digest = permid.sha(b_list).digest()
        sig = self.my_keypair.sign_dsa_asn1(digest)
        msg.append(sig)

        return msg
Beispiel #29
0
 def create_added_f_too_big(self):
     d = {}
     d['added'] = ''
     d['added.f'] = '\x00'
     d['dropped'] = ''
     bd = bencode(d)
     return EXTEND + chr(1) + bd
Beispiel #30
0
def create_ut_pex(addedconns,droppedconns,thisconn):
    #print >>sys.stderr,"ut_pex: create_ut_pex:",addedconns,droppedconns,thisconn
    
    #Niels: Force max 50 added/dropped connections
    #"Some clients may choose to enforce these limits and drop connections which don't obey these limits." 
    #http://wiki.theory.org/BitTorrentPeerExchangeConventions
    addedconns = addedconns[:50]
    droppedconns = droppedconns[:50]
    
    d = {}
    compactedpeerstr = compact_connections(addedconns,thisconn)
    d['added'] = compactedpeerstr
    flags = ''
    for i in range(len(addedconns)):
        conn = addedconns[i]
        if conn == thisconn:
            continue
        flag = 0
        if conn.get_extend_encryption():
            flag |= 1
        if conn.download is not None and conn.download.peer_is_complete():
            flag |= 2
        if conn.is_tribler_peer():
            flag |= 4
            
        #print >>sys.stderr,"ut_pex: create_ut_pex: add flag",`flag`
        flags += chr(flag)
    d['added.f'] = flags
    compactedpeerstr = compact_connections(droppedconns)
    d['dropped'] = compactedpeerstr
    return bencode(d)
Beispiel #31
0
 def create_good_tribler_extend_hs(self):
     d = {}
     d['m'] = {'Tr_OVERLAYSWARM':253}
     d['p'] = self.mylistenport
     d['v'] = 'Tribler 3.5.1'
     bd = bencode(d)
     return EXTEND+chr(0)+bd
 def create_bad_chunk(self,chunkid):
     index,begin,length = chunkid
     ohlist = self.tree.get_hashes_for_piece(index)
     bohlist = bencode(ohlist)
     chunk = '*' * length
     payload = tobinary(index)+tobinary(begin)+tobinary(len(bohlist))+bohlist+chunk
     return EXTEND+HASHPIECE+payload
Beispiel #33
0
 def create_good_nontribler_extend_hs(self):
     d = {}
     d['m'] = {'hallo':12, 'dag':255 }
     d['p'] = self.mylistenport
     d['v'] = 'TestSweet 1.2.3.4'
     bd = bencode(d)
     return EXTEND+chr(0)+bd
Beispiel #34
0
 def create_dropped_not_str(self):
     d = {}
     d['added'] = ''
     d['added.f'] = ''
     d['dropped'] = 481
     bd = bencode(d)
     return EXTEND + chr(1) + bd
 def get_default_torrent(self,filename,title,paths=None):
     metainfo = {}
     metainfo['announce'] = 'http://localhost:0/announce'
     metainfo['announce-list'] = []
     metainfo['creation date'] = int(time.time())
     metainfo['encoding'] = 'UTF-8'
     info = {}
     info['name'] = title.encode("UTF-8")
     info['piece length'] = 2 ** 16
     info['pieces'] = '*' * 20
     if paths is None:
         info['length'] = 481
     else:
         d1 = {}
         d1['path'] = [paths[0].encode("UTF-8")]
         d1['length'] = 201
         d2 = {}
         d2['path'] = [paths[1].encode("UTF-8")]
         d2['length'] = 280
         info['files'] = [d1,d2]
         
     metainfo['info'] = info
     path = os.path.join(self.config.get_torrent_collecting_dir(),filename)
     tdef = TorrentDef.load_from_dict(metainfo)
     tdef.save(path)
     return tdef, bencode(metainfo)
    def subtest_invalidRequest3(self):
        """
        Trying to send an invalid message (valid for everythin except that there is one field more)
        The connection should be closed by the receiver
        """
        print >> sys.stderr, "test: test_subtitles_msgs_invalid_request_3 ------------------"
        ol_conn = OLConnection(self.my_keypair,'localhost',self.hisport)

        bitmask = LanguagesProvider.getLanguagesInstance().langCodesToMask(['nld','eng'])
        binmask = utilities.uintToBinaryString(bitmask, length=4)
        
        request = GET_SUBS + \
                      bencode((
                              self.anotherpermid,
                              self.testInfohash,
                              binmask,
                              42
                              ))
        
        ol_conn.send(request)
        self.assertEquals(0, len(ol_conn.recv()))
        print >> sys.stderr, "test: test_subtitles_msgs_invalid_request_3: connection closed as expected"
        
        ol_conn.close()
        print >> sys.stderr, "End of test_subtitles_msgs_invalid_request_3 ------------------"
Beispiel #37
0
    def createAndSendBarterCastMessage(self,
                                       target_permid,
                                       selversion,
                                       active=False):

        # for older versions of Tribler (non-BarterCast): do nothing
        if selversion <= OLPROTO_VER_FIFTH:
            return

        if DEBUG:
            print >> sys.stderr, "===========bartercast: Sending BarterCast msg to ", self.bartercastdb.getName(
                target_permid)

        # create a new bartercast message
        bartercast_data = self.createBarterCastMessage(target_permid)

        if LOG:
            self.logMsg(bartercast_data,
                        target_permid,
                        'out',
                        logfile=self.logfile)

        try:
            bartercast_msg = bencode(bartercast_data)
        except:
            print_exc()
            print >> sys.stderr, "error bartercast_data:", bartercast_data
            return

        # send the message
        self.overlay_bridge.send(target_permid, BARTERCAST + bartercast_msg,
                                 self.bartercastSendCallback)

        self.blockPeer(target_permid, self.send_block_list,
                       self.block_interval)
Beispiel #38
0
    def handle_crawler_request(self, permid, selversion, channel_id, message,
                               reply_callback):
        """
        Received a CRAWLER_FRIENDSHIP_QUERY request.
        @param permid The Crawler permid
        @param selversion The overlay protocol version
        @param channel_id Identifies a CRAWLER_REQUEST/CRAWLER_REPLY pair
        @param message The message payload
        @param reply_callback Call this function once to send the reply: reply_callback(payload [, error=123])
        """
        if DEBUG:
            print >> sys.stderr, "FriendshipCrawler: handle_friendship_crawler_database_query_request", message

        try:
            d = bdecode(message)

            stats = self.getStaticsFromFriendshipStatisticsTable(
                self.session.get_permid(), d['current time'])
            msg_dict = {'current time': d['current time'], 'stats': stats}
            msg = bencode(msg_dict)
            reply_callback(msg)

        except Exception, e:
            print_exc()
            reply_callback(str(e), 1)
 def create_diff_ips(self,i):
     if self.NLISTENERS==1:
         s = REPLY_IP
     else:
         s = '127.0.0.'+str(i)
     b = bencode(s)
     return DIALBACK_REPLY+b
Beispiel #40
0
def create_ut_pex(addedconns, droppedconns, thisconn):
    #print >>sys.stderr,"ut_pex: create_ut_pex:",addedconns,droppedconns,thisconn

    #Niels: Force max 50 added/dropped connections
    #"Some clients may choose to enforce these limits and drop connections which don't obey these limits."
    #http://wiki.theory.org/BitTorrentPeerExchangeConventions
    addedconns = addedconns[:50]
    droppedconns = droppedconns[:50]

    d = {}
    compactedpeerstr = compact_connections(addedconns, thisconn)
    d['added'] = compactedpeerstr
    flags = ''
    for i in range(len(addedconns)):
        conn = addedconns[i]
        if conn == thisconn:
            continue
        flag = 0
        if conn.get_extend_encryption():
            flag |= 1
        if conn.download is not None and conn.download.peer_is_complete():
            flag |= 2
        if conn.is_tribler_peer():
            flag |= 4

        #print >>sys.stderr,"ut_pex: create_ut_pex: add flag",`flag`
        flags += chr(flag)
    d['added.f'] = flags
    compactedpeerstr = compact_connections(droppedconns)
    d['dropped'] = compactedpeerstr
    return bencode(d)
 def create_remote_query_reply(self,id,hits,selversion):
     getsize = os.path.getsize
     join = os.path.join
     d = {}
     d['id'] = id
     d2 = {}
     for torrent in hits:
         r = {}
         # NEWDBSTANDARD. Do not rename r's fields: they are part of the 
         # rquery protocol spec.
         r['content_name'] = torrent['name'] # According to TorrentDBHandler.addExternalTorrentencoded this is the original encoded name, TODO: standardize on UTF-8 encoding. 
         r['length'] = torrent['length']
         r['leecher'] = torrent['num_leechers']
         r['seeder'] = torrent['num_seeders']
         # Arno: TODO: sending category doesn't make sense as that's user-defined
         # leaving it now because of time constraints
         r['category'] = torrent['category']
         if selversion >= OLPROTO_VER_NINETH:
             r['torrent_size'] = getsize(join(self.torrent_dir, torrent['torrent_file_name']))
         if selversion >= OLPROTO_VER_ELEVENTH:
             r['channel_permid'] = torrent['channel_permid']
             r['channel_name'] = torrent['channel_name']
         if selversion >= OLPROTO_VER_TWELFTH and 'metadata' in torrent:
             if DEBUG:
                 print >>sys.stderr,time.asctime(),'-', "rqmh: create_query_reply: Adding torrent file"
             r['metatype'] = torrent['metatype']
             r['metadata'] = torrent['metadata']
             
         d2[torrent['infohash']] = r
     d['a'] = d2
     return bencode(d)
Beispiel #42
0
 def create_good_ut_pex(self, pex_id=1):
     d = {}
     d['added'] = ''
     d['added.f'] = ''
     d['dropped'] = ''
     bd = bencode(d)
     return EXTEND + chr(pex_id) + bd
 def _packData(self):
     """
     Creates a bencode binary representation of this metadata instance.
     
     This representation is the one that is sent with ChannelCast messages.
     """
     if self.description is not None:
         assert isinstance(self.description, unicode)      
     if self.description is None:
         self.description = u""
     
     
     
     bitmask, checksums = self._getSubtitlesMaskAndChecksums()
     
     # The signature is taken over the bencoding of
     # binary representations of (channel,infohash,description,timestamp,bitmask)
     # that is the same message that is sent with channelcast
     tosign = (self.channel, 
               self.infohash, 
               self.description.encode("utf-8"),
               self.timestamp,
               pack("!L", bitmask),
               checksums )
 
     bencoding = bencode(tosign)
     return bencoding
Beispiel #44
0
    def _create(metainfo):  # TODO: replace with constructor
        # raises ValueErrors if not good
        validTorrentFile(metainfo)

        t = TorrentDef()
        t.metainfo = metainfo
        t.metainfo_valid = True
        # copy stuff into self.input
        maketorrent.copy_metainfo_to_input(t.metainfo, t.input)

        # For testing EXISTING LIVE, or EXISTING MERKLE: DISABLE, i.e. keep true infohash
        if t.get_url_compat():
            t.infohash = makeurl.metainfo2swarmid(t.metainfo)
        else:
            # Two places where infohash calculated, here and in maketorrent.py
            # Elsewhere: must use TorrentDef.get_infohash() to allow P2PURLs.
            t.infohash = sha(bencode(metainfo['info'])).digest()

        assert isinstance(
            t.infohash,
            str), "INFOHASH has invalid type: %s" % type(t.infohash)
        assert len(
            t.infohash
        ) == INFOHASH_LENGTH, "INFOHASH has invalid length: %d" % len(
            t.infohash)

        #print >>sys.stderr,"INFOHASH",`t.infohash`

        return t
    def ValueToString(self, value, typex):
        if typex == "boolean":
            if value:
                text = "1"
            else:
                text = "0"
        elif typex == "color":
            red = str(value.Red())
            while len(red) < 3:
                red = "0" + red

            green = str(value.Green())            
            while len(green) < 3:
                green = "0" + green
                
            blue = str(value.Blue())            
            while len(blue) < 3:
                blue = "0" + blue

            text = str(red) + str(green) + str(blue)
        elif typex.startswith("bencode"):
            text = bencode(value)
        else:
            if type(value) is unicode:
                text = value
            else:
                text = str(value)
        
        return text
Beispiel #46
0
    def createAndSendBarterCastMessage(self, target_permid, selversion, active = False):


        # for older versions of Tribler (non-BarterCast): do nothing
        if selversion <= OLPROTO_VER_FIFTH:
            return

        if DEBUG:
            print >> sys.stderr, "===========bartercast: Sending BarterCast msg to ", self.bartercastdb.getName(target_permid)

        # create a new bartercast message
        bartercast_data = self.createBarterCastMessage(target_permid)
        
        if LOG:
            self.logMsg(bartercast_data, target_permid, 'out', logfile = self.logfile)
        
        try:
            bartercast_msg = bencode(bartercast_data)
        except:
            print_exc()
            print >> sys.stderr, "error bartercast_data:", bartercast_data
            return
            
        # send the message    
        self.overlay_bridge.send(target_permid, BARTERCAST+bartercast_msg, self.bartercastSendCallback)

        self.blockPeer(target_permid, self.send_block_list, self.block_interval)
Beispiel #47
0
 def createAndSendVoteCastMessage(self, target_permid, selversion):
     """ Creates and sends a VOTECAST message """
     if selversion < OLPROTO_VER_ELEVENTH:
         if DEBUG:
             print >> sys.stderr, time.asctime(),'-', "Do not send to lower version peer:", selversion
         return
             
     votecast_data = self.createVoteCastMessage()
     if len(votecast_data) == 0:
         if DEBUG:
             print >>sys.stderr, time.asctime(),'-', "No votes there.. hence we do not send"            
         return
     
     votecast_msg = bencode(votecast_data)
      
     if self.log:
         dns = self.dnsindb(target_permid)
         if dns:
             ip,port = dns
             MSG_ID = "VOTECAST"
             msg = voteCastReplyMsgToString(votecast_data)
             self.overlay_log('SEND_MSG', ip, port, show_permid(target_permid), selversion, MSG_ID, msg)
     
     if DEBUG: print >> sys.stderr, time.asctime(),'-', "Sending votecastmsg",voteCastMsgToString(votecast_data)
     data = VOTECAST+votecast_msg
     self.secure_overlay.send(target_permid, data, self.voteCastSendCallback)        
Beispiel #48
0
 def create_good_tribler_extend_hs(self, pex_id=1):
     d = {}
     d['m'] = {'Tr_OVERLAYSWARM': 253, 'ut_pex': pex_id}
     d['p'] = self.mylistenport
     d['v'] = 'Tribler 3.5.1'
     d['e'] = 0
     bd = bencode(d)
     return EXTEND + chr(0) + bd
 def send_overlap(self,permid,oldict):
     try:
         body = bencode(oldict)
         ## Optimization: we know we're currently connected
         self.overlay_bridge.send(permid, SOCIAL_OVERLAP + body,self.send_callback)
     except:
         if DEBUG:
             print_exc(file=sys.stderr)
Beispiel #50
0
def create_torrent_signature(response, keypairfilename):
    keypair = EC.load_key(keypairfilename)
    bresponse = bencode(response)
    digester = sha(bresponse[:])
    digest = digester.digest()
    sigstr = keypair.sign_dsa_asn1(digest)
    response['signature'] = sigstr
    response['signer'] = str(keypair.pub().get_der())
Beispiel #51
0
    def create_good_metadata(self):
        f = open(self.torrentfile, "rb")
        data = f.read()
        f.close()

        d = self.create_good_metadata_dict(data)
        bd = bencode(d)
        return METADATA + bd
Beispiel #52
0
 def create_good_tribler_extend_hs_v2(self,g2g_id=G2G_ID):
     d = {}
     d['m'] = {'Tr_OVERLAYSWARM':253,'Tr_G2G_v2':g2g_id}
     d['p'] = self.mylistenport
     d['v'] = 'Tribler 4.2.0'
     d['e'] = 0
     bd = bencode(d)
     return EXTEND+chr(0)+bd
Beispiel #53
0
def generate_response1(randomB, peeridB, keypairA):
    randomA = Rand.rand_bytes(num_random_bits / 8)
    response1 = {}
    response1['certA'] = str(keypairA.pub().get_der())
    response1['rA'] = randomA
    response1['B'] = peeridB
    response1['SA'] = sign_response(randomA, randomB, peeridB, keypairA)
    return [randomA, bencode(response1)]
Beispiel #54
0
 def serialize(self):
     """
     Return a bencoded, serialized POA
     """
     lst = [
         self.torrent_id, self.torrent_pub_key, self.node_pub_key,
         self.expire_time, self.signature
     ]
     return bencode(lst)
Beispiel #55
0
    def _createGETSUBSMessage(self, channel_id, infohash, bitmask):
        """
        Bencodes a GET_SUBS message and adds the appropriate header.
        """

        binaryBitmask = pack("!L", bitmask)
        body = bencode((channel_id, infohash, binaryBitmask))
        head = GET_SUBS
        return head + body
Beispiel #56
0
 def create_resp2_bad_cert(self, rB, resp1_dict, hisid):
     resp2 = {}
     resp2['certB'] = '\x00\x00\x00\x00\x00\x30\x00\x00'
     resp2['A'] = hisid
     sig_list = [rB, resp1_dict['rA'], hisid]
     sig_data = bencode(sig_list)
     sig_hash = sha.sha(sig_data).digest()
     sig_asn1 = str(self.my_keypair.sign_dsa_asn1(sig_hash))
     resp2['SB'] = sig_asn1
     return self.create_response2_payload(resp2)
Beispiel #57
0
 def create_resp2_wrong_randomA(self, rB, resp1_dict, hisid):
     resp2 = {}
     resp2['certB'] = str(self.my_keypair.pub().get_der())
     resp2['A'] = hisid
     sig_list = [rB, "wrong".zfill(random_size), hisid]
     sig_data = bencode(sig_list)
     sig_hash = sha.sha(sig_data).digest()
     sig_asn1 = str(self.my_keypair.sign_dsa_asn1(sig_hash))
     resp2['SB'] = sig_asn1
     return self.create_response2_payload(resp2)
Beispiel #58
0
 def create_resp2_sig_by_other_keypair(self, rB, resp1_dict, hisid):
     resp2 = {}
     resp2['certB'] = str(self.my_keypair.pub().get_der())
     resp2['A'] = hisid
     sig_list = [rB, resp1_dict['rA'], hisid]
     sig_data = bencode(sig_list)
     sig_hash = sha.sha(sig_data).digest()
     sig_asn1 = str(self.his_keypair.sign_dsa_asn1(sig_hash))
     resp2['SB'] = sig_asn1
     return self.create_response2_payload(resp2)
Beispiel #59
0
 def send_extend_handshake(self):
     d = {}
     d['m'] = self.connecter.EXTEND_HANDSHAKE_M_DICT
     d['p'] = self.connecter.mylistenport
     ver = version_short.replace('-', ' ', 1)
     d['v'] = ver
     d['e'] = 0  # Apparently this means we don't like uTorrent encryption
     self._send_message(EXTEND + EXTEND_MSG_HANDSHAKE_ID + bencode(d))
     if DEBUG:
         print >> sys.stderr, 'connecter: sent extend: id=0+', d