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
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)
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
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)
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'''
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
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
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)
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)
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)
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
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)
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))
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 }
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()
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()
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
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
def get_info_hash(gto_dict): return hashlib.sha1(bencode.bencode(gto_dict.get('info')))
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)
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()
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]))
def hash_info(self, info): info_bytes = bencode(info) sha1 = hashlib.sha1() sha1.update(info_bytes) x = sha1.digest() return x
def dealPing(msg,s,adress): print("p") tid=msg['t'] msg={"t":tid, "y":"r", "r":{"id":NodeId}} s.sendto(bencode(msg),(adress)) return
def get_info_hash(self): raw_info_hash = (bencode(self.torrent_file['info'])) hash = hashlib.sha1(raw_info_hash).digest() return hash
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()
def write(pod, data): """Writes data to pod's stdin.""" pod.stdin.write(bcoding.bencode(data)) pod.stdin.flush()
def write(data): logging.info("write data: %s", data) sys.stdout.buffer.write(bcoding.bencode(data)) sys.stdout.flush()
def info_hash(torrent): raw_info_hash = (bencode(torrent['info'])) hash = hashlib.sha1(raw_info_hash).digest() return hash
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)
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)