Skip to content

Instantly share code, notes, and snippets.

@mdauphin
Created November 26, 2018 14:56
Show Gist options
  • Save mdauphin/c223670aed69b8c8d0d722dc21dec5c6 to your computer and use it in GitHub Desktop.
Save mdauphin/c223670aed69b8c8d0d722dc21dec5c6 to your computer and use it in GitHub Desktop.
#decode torrent file
import os
import sys
def decode(f):
c = f.read(1)
if c.isdigit(): #string
len = dec_size(f,c)
return f.read(len)
if c == 'd':
return dec_dict(f)
if c == 'i':
return dec_int(f)
if c == 'l':
return dec_list(f)
if c == 'e':
return None
return None
def dec_size(f,init=''):
c = f.read(1)
num = init
while c.isdigit():
num = num + c
c = f.read(1)
assert( c == ':' )
return int(num)
def dec_int(f,init=''):
c = f.read(1)
num = init
while c.isdigit():
num = num + c
c = f.read(1)
assert( c == 'e' )
return int(num)
def dec_dict(f):
ret = {}
key = decode(f)
while key:
value = decode(f)
ret[key] = value
key = decode(f)
return ret
def dec_list(f):
ret = []
item = decode(f)
while item:
ret.append(item)
item = decode(f)
return ret
def decode_torrent(filename):
with open(filename,"rb") as f:
return decode(f)
if __name__ == '__main__':
item = decode_torrent(sys.argv[1])
print item['info']['length']
print item['info']['name']
for k,v in item['info'].iteritems():
print k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment