Пример #1
0
    def load_content(self, path):
        with open(path, 'rb') as file:
            contents = bdecode(file)

        self.torrent_file = contents

        # getting metainfo of torrent file in separate variables
        """
            Please refer to https://en.wikipedia.org/wiki/Torrent_file#File_structure 
            for understanding the structure of Torrent files containing metainfo
        """

        # creating hash info for handshaking purpose
        raw_info_hash = bencode(self.torrent_file['info'])
        self.info_hash = hashlib.sha1(raw_info_hash).digest()
        self.peer_id = self.generate_peer_id()

        # creating directory structure and store file info in the dictionary
        self.announce_list = self.get_trackers()
        self.init_files()

        # creating number of pieces
        self.piece_length = self.torrent_file['info']['piece length']
        self.pieces = self.torrent_file['info']['pieces']
        self.number_of_pieces = math.ceil(self.total_length /
                                          self.piece_length)

        # checking for the lengths.. if equal to zero, it will show an assertion error
        assert (self.total_length > 0)
        assert (len(self.file_names) > 0)

        # return all the values
        return self
Пример #2
0
def sendgetpeers(info, nodes, msg):
    print("start getpeer-----")
    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    getPeersMessage(clientSocket, info)
    for n in nodes:
        addr = (n.ip, n.port)
        clientSocket.sendto(bencode(msg), addr)
Пример #3
0
def dealFideNodes(msg,s,adress):
    print("fn")
    tid=msg['t']
    msg={"t":tid, "y":"r", "r":{"id":NodeId,"nodes":""}}
    print(msg)
    s.sendto(bencode(msg),(adress))
    return
Пример #4
0
def request_metadata(the_socket, ut_metadata, piece):
    """bep_0009"""
    msg = chr(BT_MSG_ID).encode() + chr(ut_metadata).encode() + bencode(
        {
            "msg_type": 0,
            "piece": piece
        })
    send_message(the_socket, msg)
Пример #5
0
def make_magnet_from_file(file) :
    file_torrent=open(file,"rb")
    metadata = bcoding.bdecode(file_torrent.read())
    subj = metadata[b'info']
    hashcontents = bcoding.bencode(subj)
    digest = hashlib.sha1(hashcontents).digest()
    b32hash = base64.b32encode(digest).decode()
    return 'magnet:?'+ 'xt=urn:btih:' + b32hash+ '&dn=' + metadata[b'info'][b'name'].decode()+ '&tr=' + metadata[b'announce'].decode()+ '&xl=' + str(metadata[b'info'][b'length'])
    '''convert torrent into magnet file for further sharing, not currently used, but for possible future development'''
Пример #6
0
 def __init__(self, torrent_file_path):
     self.peers = []
     self.pieces = deque([])
     self.peer_id = hashlib.sha1(str(time.time()).encode('utf-8')).digest()
     self.torrent_dict = bcoding.bdecode(open(torrent_file_path, 'rb').read())
     bencode_info = bcoding.bencode(self.torrent_dict['info'])
     self.infoHash = hashlib.sha1(bencode_info).digest()
     self.generate_peer_connections()
     self.generate_pieces_objects()
     self.num_pieces_so_far = 0
Пример #7
0
def dealGetPeer(msg,s,adress):
    tid=msg['t']
    infohash = msg["a"]["info_hash"]
    infohash = proper_infohash(infohash)
    print("getPeer: "+infohash)    
    token = infohash[:2]
    msg={"t":tid, "y":"r", "r":{"id":NodeId,"nodes":"", "token":token}}
    print(msg)
    s.sendto(bencode(msg),(adress))     
    return
Пример #8
0
def initRoute(clientSocket):
    for r in BOOTSTRAP_NODES:
        msg = {
            "t": "mycode",
            "y": "q",
            "q": "find_node",
            "a": {
                "id": random_id(),
                "target": random_id()
            }
        }
        clientSocket.sendto(bencode(msg), r)
Пример #9
0
def sendMSGUDP(q, s):
    a = 0
    while True:
        if q.empty():
            initRoute(s)

        a = a + 1
        qi = q.get()
        msg = qi[0]
        adress = qi[1]
        #print(adress)
        s.sendto(bencode(msg), adress)
Пример #10
0
def sendMSGUDP(q, s):
    a = 0
    while True:
        if q.qsize() < 100:
            #print("++++++++++++++initAgain++++++++++/n")
            initRoute(s)

        a = a + 1
        qi = q.get()
        msg = qi[0]
        adress = qi[1]
        #print(adress)
        s.sendto(bencode(msg), adress)
Пример #11
0
 def load_from_path(self, path):
     with open(path, 'rb') as file:
         contents = bdecode(file)
     self.torrent_file = contents
     self.piece_length = self.torrent_file['info']['piece length']
     self.pieces = self.torrent_file['info']['pieces']
     self.info_hash = hashlib.sha1(bencode(
         self.torrent_file['info'])).digest()
     self.peer_id = self.generate_peer_id()
     self.announce_list = self.get_trakers()
     self.init_files()
     self.number_of_pieces = math.ceil(self.total_length /
                                       self.piece_length)
     return self
Пример #12
0
def sendgetpeers2(info, nodes, s):
    msg = {
        "t": random_id()[:6],
        "y": "q",
        "q": "get_peers",
        "a": {
            "id": random_id(),
            "info_hash": info
        }
    }
    for node in nodes:
        adress = (node[1], node[2])
        kt.dealNode(KNode(node[0], node[1], node[2]))
        s.sendto(bencode(msg), adress)
Пример #13
0
    def DO_GET(self, s):
        client_info = decode_request(s.path)
        if not client_info:
            s.send_error(403)
            return
        info_hash = client_info["info_hash"][0]
        ip = s.client_address[0]
        port = client_info["port"][0]
        peer_id = client_info["peer_id"][0]

        response = {}
        response["peers"] = s.server.torrent[info_hash]
        s.send_response(200)
        s.end_headers()
        s.wfile.write(bencode(response))
Пример #14
0
def get_torrent_data(meta_info):
    announce = meta_info['announce']
    announce_list = meta_info['announce-list']
    try:
        comment = meta_info['comment']
    except:
        comment = None
    created_by = meta_info['created by']
    creation_date = meta_info['creation date']
    files = []
    length = 0
    root = meta_info['info']['name']
    if 'files' in meta_info['info']:
        if not os.path.exists(root):
            os.mkdir(root, 0o0766)
        for file in meta_info['info']['files']:
            path = os.path.join(root, *file["path"])
            files.append({"path": path, "length": file["length"]})
            if not os.path.exists(os.path.dirname(path)):
                os.makedirs(os.path.dirname(path))
            files.append({"path": path, "length": file["length"]})
            length += file["length"]

    else:
        files.append({
            'path': meta_info['info']['name'],
            'length': meta_info['info']['length']
        })
        length = meta_info['info']['length']
    name = meta_info['info']['name']
    piece_length = meta_info['info']['piece length']
    info_hash = hashlib.sha1(bencode(meta_info['info'])).digest()
    print(
        "announce:{}\nannounce-list:{}\ncomment:{}\ncreated by:{}\ncreation date:{}\nlength:{}\nname:{}\npiece length:{}\ninfo-hash:{}\n"
        .format(announce, announce_list, comment, created_by, creation_date,
                length, name, piece_length, info_hash))
    return {
        'announce': announce,
        'announce_list': announce_list,
        'comment': comment,
        'created_by': created_by,
        'creation_date': creation_date,
        'length': length,
        'name': name,
        'piece_length': piece_length,
        'info_hash': info_hash,
        'files': files
    }
Пример #15
0
    def _open_file(self, path_to_file):
        #read torrent file as binary object
        with open(self.path_to_file, 'rb') as meta_file:
            self.decoded = bdecode(meta_file.read())

        #check to see if it's a multi-file torrent
        if 'files' in self.decoded['info']:
            self.multi_file = True
        '''
            This stuff doesn't care whether or not it's a
            multi-file torrent
        '''
        # extract the creation date
        self.creation_date = self.decoded['creation date']
        # extract the announce url
        self.announce = urllib.parse.urlparse(self.decoded['announce'])
        print(self.decoded['announce'])
        # calculates info hash
        self.info_hash = hashlib.sha1(bencode(self.decoded['info'])).digest()

        # extract piece length
        self.piece_length = self.decoded['info']['piece length']

        # extract pieces (in bytes)
        self.pieces = self.decoded['info']['pieces']
        self.num_pieces = len(self.pieces) // 20

        # extract name / dictionary as to where to store the files
        self.name = self.decoded['info']['name']

        if not self.multi_file:
            # extract length
            self.length = self.decoded['info']['length']
            self.last_piece_len = self.length - self.piece_length * (
                self.num_pieces - 1)
        else:
            self.files = []
            self.length = 0
            for f in self.decoded['info']['files']:
                self.length += int(f['length'])
                self.files.append({
                    'length': int(f['length']),
                    'path': f['path']
                })
            self.last_piece_len = self.length - self.piece_length * (
                self.num_pieces - 1)
        self.file_info()
Пример #16
0
def sendMSGUDP(q, s):
    a = 0
    while True:
        if q.qsize() < 100:
            #print("++++++++++++++initAgain++++++++++/n")
            initRoute(s)

        a = a + 1
        qi = q.get()
        msg = qi[0]
        adress = qi[1]
        #print(adress)
        s = createSocekt(adress)
        s.send(bencode(msg))
        t = threading.Thread(target=getMessage22, args=(
            s,
            q,
        ))
        t.start()
Пример #17
0
    def open_from_file(self, movie):
        with open(a1[1], 'r+b') as file2:
            contents2 = bdecode(file2)

        self.torrent_file2 = contents2
        self.piece_length = self.torrent_file2['info']['piece length']
        self.pieces = self.torrent_file2['info']['pieces']
        raw_info_hash = bencode(self.torrent_file2['info'])
        self.info_hash = hashlib.sha1(raw_info_hash).digest()
        self.peer_id = self.generate_peer_id()
        self.announce_list = self.get_trakers()
        self.init_files()
        self.number_of_pieces = math.ceil(self.total_length /
                                          self.piece_length)
        logging.debug(self.announce_list)
        logging.debug(self.file_names)

        assert (self.total_length > 0)
        assert (len(self.file_names) > 0)

        return self
Пример #18
0
    def parse_file(self):
        with open(self.file, 'rb') as file:
            content = bdecode(file)

        info = content['info']
        files = []
        full_size = 0
        for file in info['files']:
            file_info = {'size': file['length'], 'name': file['path'][0]}
            files.append(file_info)
            full_size += file['length']
        tracker_list = []
        for tracker in content['announce-list']:
            tracker_list.append(tracker[0])
        info_hash = hashlib.sha1(bencode(info)).hexdigest()
        announce_url = content['announce']
        data = {
            'info_hash': info_hash,
            'files': files,
            'announce': announce_url,
            'full_size': self.make_size(full_size),
            'tracker_list': tracker_list
        }
        return data
Пример #19
0
def get_info_hash(gto_dict):
    return hashlib.sha1(bencode.bencode(gto_dict.get('info')))
Пример #20
0
def send_ext_handshake(the_socket):
    msg = chr(BT_MSG_ID).encode() + chr(EXT_HANDSHAKE_ID).encode() + bencode(
        {"m": {
            "ut_metadata": 2
        }})
    send_message(the_socket, msg)
Пример #21
0
    infohash = msg["a"]["info_hash"]
    infohash = proper_infohash(infohash)
    print("getPeer: "+infohash)    
    token = infohash[:2]
    msg={"t":tid, "y":"r", "r":{"id":NodeId,"nodes":"", "token":token}}
    print(msg)
    s.sendto(bencode(msg),(adress))     
    return
def dealAnnouncePeer(msg,s,adress):
    infohash = msg["a"]["info_hash"]
    infohash = proper_infohash(infohash)
    print("AnnouncePeer: "+infohash)    
    return
print("start")
NodeId=random_id()
kt=Ktable(NodeId)
kb=KBucket(0,2**160)
kt.append(kb)
print(NodeId)
print(str(int(binascii.hexlify(NodeId), 16)))
ServerName = 'router.utorrent.com'
ServerPort = 6881
clientSocket =socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
clientSocket.bind((HOST,PORT))
clientSocket.settimeout(5)
msg={"t":"mycode", "y":"q","q":"find_node", "a":{"id":NodeId,"target":NodeId}}
clientSocket.sendto(bencode(msg),(ServerName,ServerPort))
_thread.start_new_thread( getMessage, (clientSocket, ) )


def write(obj):
    sys.stdout.buffer.write(bencode(obj))
    sys.stdout.flush()
Пример #23
0
def dealFindNodesBack(nodes,s):
    for node in nodes:
        if kt.dealNode(KNode(node[0],node[1],node[2])):
            msg={"t":"mycode", "y":"q","q":"find_node", "a":{"id":NodeId,"target":NodeId}}
            back=s.sendto(bencode(msg),(node[1],node[2]))
Пример #24
0
 def hash_info(self, info):
     info_bytes = bencode(info)
     sha1 = hashlib.sha1()
     sha1.update(info_bytes)
     x = sha1.digest()
     return x
Пример #25
0
def dealPing(msg,s,adress):
    print("p")
    tid=msg['t']
    msg={"t":tid, "y":"r", "r":{"id":NodeId}}
    s.sendto(bencode(msg),(adress))
    return
Пример #26
0
    def get_info_hash(self):
        raw_info_hash = (bencode(self.torrent_file['info']))
        hash = hashlib.sha1(raw_info_hash).digest()

        return hash
Пример #27
0
def sha1_info(torrent):
    """returns sha1 hash of torrent['info']"""
    sha1 = hashlib.sha1()
    info_bytes = bencode(torrent['info'])
    sha1.update(info_bytes)
    return sha1.digest()
Пример #28
0
def write(pod, data):
    """Writes data to pod's stdin."""
    pod.stdin.write(bcoding.bencode(data))
    pod.stdin.flush()
Пример #29
0
def write(data):
    logging.info("write data: %s", data)
    sys.stdout.buffer.write(bcoding.bencode(data))
    sys.stdout.flush()
Пример #30
0
def info_hash(torrent):
    raw_info_hash = (bencode(torrent['info']))
    hash = hashlib.sha1(raw_info_hash).digest()

    return hash
Пример #31
0
	def __init__(self, torrentpath):
		colorama.init()
		self.torrentpath = torrentpath
		self.announceData = ""
		self.infoHash = ""
		self.pieceHashes = []
		self.pieceLength = 0

		# List of files in this torrent
		self.files = []
		self.length = 0
		self.name = ""

		self.pieces = ""
		self.local_peer_id = bytes("-KC0010-" + str(random.randint(100000000000, 999999999999)), 'utf-8')
		self.shouldLoop = 1
		# Lock to synchronize calling pieceManager methods from peers (or anywhere else)
		self.piemLock = threading.Lock()

		self.announceCount = 1
		self.trackerid = -1 # -1 means trackerid is not available
		self.announceTimer = 0
		self.announceInterval = 0 # -1 means interval is not available
		self.elapsed = 0

		#Status
		"""
		Oldest Status (lower index) → Newest Status (higher index)
		"""
		self.NUM_STATUS = 6
		self.DISPLAY_STATUS = 1
		self.statusList = []
		for _ in range(self.NUM_STATUS):
			self.statusList.append("None")

		# Open .torrent file and decode data
		with open(torrentpath, "rb") as f:
			torrent = bdecode(f)

		# Fields common to both single file and multi file torrents
		self.announceData = torrent['announce']
		self.pieceLength = torrent['info']['piece length']
		self.pieces = torrent['info']['pieces']
		for index in range(0, len(self.pieces), 20):
			self.pieceHashes.append(self.pieces[index:index + 20])

		# Single file
		if('length' in torrent['info'].keys()):
			print("\033[92mSingle file torrent\033[0m")
			self.length = torrent['info']['length']
			self.name = torrent['info']['name']
			# For single file torrents, filepath and name are both ['info']['name']
			self.files.append(file.File(torrent['info']['name'], torrent['info']['name'], torrent['info']['length']))
			# self.lastPieceLength = self.length % self.pieceLength
		else:
			self.length = 0 # For multi file case, equal to sum of length of all files
			print("\033[91mMulti file torrent\033[0m")
			masterDir = torrent['info']['name'] # The top folder in which to store all the other dirs/files
			for f in torrent['info']['files']:
				self.length += f['length']
				"""
				fp - filepath
				fn - filename
				"""
				fp = masterDir
				for t in f['path']: # A list
					fp += ("/" + t)
				fn = f['path'][-1]
				self.files.append(file.File(fp, fn, f['length']))

		# Create list of pieces to give to pieceManager
		self.pieceList = []
		# Add all pieces except last piece
		for i in range(len(self.pieceHashes) - 1):
			self.pieceList.append(p.Piece(i, self.length, self.pieceLength, 0, 0))

		# Add last piece
		self.pieceList.append(p.Piece(len(self.pieceHashes) - 1, self.length, self.pieceLength, 0, 1))

		# Display piece and block info
		print("TORRENT INFO")
		print("LENGTH: {}, PIECES: {}, PIECE LENGTH: {}".format(self.length, len(self.pieceHashes), self.pieceLength))
		print("{} pieces are {} long and have {} blocks each {} long"
			.format(len(self.pieceHashes) - 1, self.pieceLength, self.pieceList[-2].number_of_blocks, self.pieceList[-2].block_size))
		print("Last piece is {} long and have {} blocks with \"LAST\" block {} long"
			.format(self.pieceList[-1].piece_size, self.pieceList[-1].number_of_blocks, self.pieceList[-1].last_block_size))

		i = input()
		# Calculate infohash
		encoded = bencode(torrent['info'])
		m = hashlib.sha1(encoded)
		self.infoHash = m.digest()

		# Instantiate a piece manager for this torrent file
		self.changeStatus("Creating piece manager for this torrent")
		self.pieManager = piem.pieceManager(self, self.pieceList)
Пример #32
0
 def decodeFile(self):
   f = open(self.inputURL, "rb")
   d = bdecode(f.read())
   self.url = d['announce']
   self.info = d['info']
   self.reencoded = bencode(self.info)