예제 #1
0
 def parseHandshake(self, data=""):
     # If the Info Hash matches the torrent's info hash, add the peer to the successful handshake set
     handshake_response_data = Messages.Handshake(data)
     handshake_info_hash = handshake_response_data.info_hash
     if handshake_info_hash == urllib.unquote(
             self.torrent.payload['info_hash']):
         self.factory.peers_handshaken.add((self.ip, self.port))
         # Check if Should we be interested or not else choke the peer if not already choked and add a timeout
         self.transport.write(str(Messages.Interested()))
         self.buffer += data[68:]
         self.transport.write(
             str(
                 Messages.Bitfield(bitfield=self.torrent.fileManager.
                                   pieces_status.tobytes())))
     else:
         self.killPeer()
     return
예제 #2
0
 def parseNonHandshakeMessage(self, data):
     bytestring = data
     if (bytestring[0:4] == '\x00\x00\x00\x00'):
         # Its a Keep Alive message #
         message_obj = Messages.KeepAlive(response=bytestring)
     else:
         message_obj = {
             0: lambda: Messages.Choke(response=bytestring),
             1: lambda: Messages.Unchoke(response=bytestring),
             2: lambda: Messages.Interested(response=bytestring),
             3: lambda: Messages.Interested(response=bytestring),
             4: lambda: Messages.Have(response=bytestring),
             5: lambda: Messages.Bitfield(response=bytestring),
             6: lambda: Messages.Request(response=bytestring),
             7: lambda: Messages.Piece(response=bytestring),
             8: lambda: Messages.Cancel(response=bytestring),
             9: lambda: Messages.Port(response=bytestring),
         }[struct.unpack(
             '!b',
             data[4])[0]]()  # The 5th byte in 'data' is the message type/id
     self.process_message(message_obj)
예제 #3
0
 def connect_to_random_peer(self):
     """
     Choose a random peer and connect to them.
     """
     peer = random.choice(self.peers)
     if peer not in self.connected_peers:
         peer.connect(timeout=6)
         if peer.is_connected():
             peer.send_handshake()
             peer.receive_msg()
             handshake = peer.decode_msg()
             if not handshake:
                 return False
             if handshake.info_hash == self.torrent.info_hash:
                 bitfield_msg = Messages.Bitfield(peer.piece_manager.bitfield.bytes)
                 peer.send_msg(bitfield_msg.encode())
                 peer.receive_msg()
                 response = peer.decode_msg()
                 peer.handle_msg(response)
                 peer.did_handshake = True
                 self.connected_peers.append(peer)
                 return True
     return False