bencode.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # Written by Petru Paler
  2. # see LICENSE.txt for license information
  3. # http://cvs.degreez.net/viewcvs.cgi/*checkout*/bittornado/LICENSE.txt?rev=1.2
  4. # "the MIT license"
  5. def decode_int(x, f):
  6. f += 1
  7. newf = x.index('e', f)
  8. try:
  9. n = int(x[f:newf])
  10. except (OverflowError, ValueError):
  11. n = long(x[f:newf])
  12. if x[f] == '-':
  13. if x[f + 1] == '0':
  14. raise ValueError
  15. elif x[f] == '0' and newf != f+1:
  16. raise ValueError
  17. return (n, newf+1)
  18. def decode_string(x, f):
  19. colon = x.index(':', f)
  20. try:
  21. n = int(x[f:colon])
  22. except (OverflowError, ValueError):
  23. n = long(x[f:colon])
  24. # Leading zeros are FINE --cjd
  25. # if x[f] == '0' and colon != f+1:
  26. # raise ValueError
  27. colon += 1
  28. return (x[colon:colon+n], colon+n)
  29. def decode_list(x, f):
  30. r, f = [], f+1
  31. while x[f] != 'e':
  32. v, f = decode_func[x[f]](x, f)
  33. r.append(v)
  34. return (r, f + 1)
  35. def decode_dict(x, f):
  36. r, f = {}, f+1
  37. lastkey = None
  38. while x[f] != 'e':
  39. k, f = decode_string(x, f)
  40. if lastkey != None and lastkey >= k:
  41. raise ValueError
  42. lastkey = k
  43. r[k], f = decode_func[x[f]](x, f)
  44. return (r, f + 1)
  45. decode_func = {}
  46. decode_func['l'] = decode_list
  47. decode_func['d'] = decode_dict
  48. decode_func['i'] = decode_int
  49. decode_func['0'] = decode_string
  50. decode_func['1'] = decode_string
  51. decode_func['2'] = decode_string
  52. decode_func['3'] = decode_string
  53. decode_func['4'] = decode_string
  54. decode_func['5'] = decode_string
  55. decode_func['6'] = decode_string
  56. decode_func['7'] = decode_string
  57. decode_func['8'] = decode_string
  58. decode_func['9'] = decode_string
  59. def bdecode_stream(x):
  60. return decode_func[x[0]](x, 0);
  61. def bdecode(x):
  62. try:
  63. r, l = bdecode_stream(x);
  64. except (IndexError, KeyError):
  65. raise ValueError
  66. if l != len(x):
  67. raise ValueError
  68. return r
  69. def test_bdecode():
  70. try:
  71. bdecode('0:0:')
  72. assert 0
  73. except ValueError:
  74. pass
  75. try:
  76. bdecode('ie')
  77. assert 0
  78. except ValueError:
  79. pass
  80. try:
  81. bdecode('i341foo382e')
  82. assert 0
  83. except ValueError:
  84. pass
  85. assert bdecode('i4e') == 4
  86. assert bdecode('i0e') == 0
  87. assert bdecode('i123456789e') == 123456789
  88. assert bdecode('i-10e') == -10
  89. try:
  90. bdecode('i-0e')
  91. assert 0
  92. except ValueError:
  93. pass
  94. try:
  95. bdecode('i123')
  96. assert 0
  97. except ValueError:
  98. pass
  99. try:
  100. bdecode('')
  101. assert 0
  102. except ValueError:
  103. pass
  104. try:
  105. bdecode('i6easd')
  106. assert 0
  107. except ValueError:
  108. pass
  109. try:
  110. bdecode('35208734823ljdahflajhdf')
  111. assert 0
  112. except ValueError:
  113. pass
  114. try:
  115. bdecode('2:abfdjslhfld')
  116. assert 0
  117. except ValueError:
  118. pass
  119. assert bdecode('0:') == ''
  120. assert bdecode('3:abc') == 'abc'
  121. assert bdecode('10:1234567890') == '1234567890'
  122. try:
  123. bdecode('02:xy')
  124. assert 0
  125. except ValueError:
  126. pass
  127. try:
  128. bdecode('l')
  129. assert 0
  130. except ValueError:
  131. pass
  132. assert bdecode('le') == []
  133. try:
  134. bdecode('leanfdldjfh')
  135. assert 0
  136. except ValueError:
  137. pass
  138. assert bdecode('l0:0:0:e') == ['', '', '']
  139. try:
  140. bdecode('relwjhrlewjh')
  141. assert 0
  142. except ValueError:
  143. pass
  144. assert bdecode('li1ei2ei3ee') == [1, 2, 3]
  145. assert bdecode('l3:asd2:xye') == ['asd', 'xy']
  146. assert bdecode('ll5:Alice3:Bobeli2ei3eee') == [['Alice', 'Bob'], [2, 3]]
  147. try:
  148. bdecode('d')
  149. assert 0
  150. except ValueError:
  151. pass
  152. try:
  153. bdecode('defoobar')
  154. assert 0
  155. except ValueError:
  156. pass
  157. assert bdecode('de') == {}
  158. assert bdecode('d3:agei25e4:eyes4:bluee') == {'age': 25, 'eyes': 'blue'}
  159. assert bdecode('d8:spam.mp3d6:author5:Alice6:lengthi100000eee') == {'spam.mp3': {'author': 'Alice', 'length': 100000}}
  160. try:
  161. bdecode('d3:fooe')
  162. assert 0
  163. except ValueError:
  164. pass
  165. try:
  166. bdecode('di1e0:e')
  167. assert 0
  168. except ValueError:
  169. pass
  170. try:
  171. bdecode('d1:b0:1:a0:e')
  172. assert 0
  173. except ValueError:
  174. pass
  175. try:
  176. bdecode('d1:a0:1:a0:e')
  177. assert 0
  178. except ValueError:
  179. pass
  180. try:
  181. bdecode('i03e')
  182. assert 0
  183. except ValueError:
  184. pass
  185. try:
  186. bdecode('l01:ae')
  187. assert 0
  188. except ValueError:
  189. pass
  190. try:
  191. bdecode('9999:x')
  192. assert 0
  193. except ValueError:
  194. pass
  195. try:
  196. bdecode('l0:')
  197. assert 0
  198. except ValueError:
  199. pass
  200. try:
  201. bdecode('d0:0:')
  202. assert 0
  203. except ValueError:
  204. pass
  205. try:
  206. bdecode('d0:')
  207. assert 0
  208. except ValueError:
  209. pass
  210. try:
  211. bdecode('00:')
  212. assert 0
  213. except ValueError:
  214. pass
  215. try:
  216. bdecode('l-3:e')
  217. assert 0
  218. except ValueError:
  219. pass
  220. try:
  221. bdecode('i-03e')
  222. assert 0
  223. except ValueError:
  224. pass
  225. bdecode('d0:i3ee')
  226. class Bencached(object):
  227. __slots__ = ['bencoded']
  228. def __init__(self, s):
  229. self.bencoded = s
  230. def encode_bencached(x,r):
  231. r.append(x.bencoded)
  232. def encode_int(x, r):
  233. r.extend(('i', str(x), 'e'))
  234. def encode_string(x, r):
  235. r.extend((str(len(x)), ':', x))
  236. def encode_list(x, r):
  237. r.append('l')
  238. for i in x:
  239. encode_func[type(i)](i, r)
  240. r.append('e')
  241. def encode_dict(x,r):
  242. r.append('d')
  243. ilist = sorted(x.items())
  244. for k, v in ilist:
  245. r.extend((str(len(k)), ':', k))
  246. encode_func[type(v)](v, r)
  247. r.append('e')
  248. encode_func = {}
  249. encode_func[type(Bencached(0))] = encode_bencached
  250. encode_func[type(0)] = encode_int
  251. encode_func[type('')] = encode_string
  252. encode_func[type([])] = encode_list
  253. encode_func[type(())] = encode_list
  254. encode_func[type({})] = encode_dict
  255. try:
  256. from types import BooleanType
  257. encode_func[BooleanType] = encode_int
  258. except ImportError:
  259. pass
  260. def bencode(x):
  261. r = []
  262. encode_func[type(x)](x, r)
  263. return ''.join(r)
  264. def test_bencode():
  265. assert bencode(4) == 'i4e'
  266. assert bencode(0) == 'i0e'
  267. assert bencode(-10) == 'i-10e'
  268. assert bencode(12345678901234567890) == 'i12345678901234567890e'
  269. assert bencode('') == '0:'
  270. assert bencode('abc') == '3:abc'
  271. assert bencode('1234567890') == '10:1234567890'
  272. assert bencode([]) == 'le'
  273. assert bencode([1, 2, 3]) == 'li1ei2ei3ee'
  274. assert bencode([['Alice', 'Bob'], [2, 3]]) == 'll5:Alice3:Bobeli2ei3eee'
  275. assert bencode({}) == 'de'
  276. assert bencode({'age': 25, 'eyes': 'blue'}) == 'd3:agei25e4:eyes4:bluee'
  277. assert bencode({'spam.mp3': {'author': 'Alice', 'length': 100000}}) == 'd8:spam.mp3d6:author5:Alice6:lengthi100000eee'
  278. assert bencode(Bencached(bencode(3))) == 'i3e'
  279. try:
  280. bencode({1: 'foo'})
  281. except TypeError:
  282. return
  283. assert 0
  284. try:
  285. import psyco
  286. psyco.bind(bdecode)
  287. psyco.bind(bencode)
  288. except ImportError:
  289. pass