1
0

bencode.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 >= 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') == 4L
  86. assert bdecode('i0e') == 0L
  87. assert bdecode('i123456789e') == 123456789L
  88. assert bdecode('i-10e') == -10L
  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. from types import StringType, IntType, LongType, DictType, ListType, TupleType
  227. class Bencached(object):
  228. __slots__ = ['bencoded']
  229. def __init__(self, s):
  230. self.bencoded = s
  231. def encode_bencached(x,r):
  232. r.append(x.bencoded)
  233. def encode_int(x, r):
  234. r.extend(('i', str(x), 'e'))
  235. def encode_string(x, r):
  236. r.extend((str(len(x)), ':', x))
  237. def encode_list(x, r):
  238. r.append('l')
  239. for i in x:
  240. encode_func[type(i)](i, r)
  241. r.append('e')
  242. def encode_dict(x,r):
  243. r.append('d')
  244. ilist = x.items()
  245. ilist.sort()
  246. for k, v in ilist:
  247. r.extend((str(len(k)), ':', k))
  248. encode_func[type(v)](v, r)
  249. r.append('e')
  250. encode_func = {}
  251. encode_func[type(Bencached(0))] = encode_bencached
  252. encode_func[IntType] = encode_int
  253. encode_func[LongType] = encode_int
  254. encode_func[StringType] = encode_string
  255. encode_func[ListType] = encode_list
  256. encode_func[TupleType] = encode_list
  257. encode_func[DictType] = encode_dict
  258. try:
  259. from types import BooleanType
  260. encode_func[BooleanType] = encode_int
  261. except ImportError:
  262. pass
  263. def bencode(x):
  264. r = []
  265. encode_func[type(x)](x, r)
  266. return ''.join(r)
  267. def test_bencode():
  268. assert bencode(4) == 'i4e'
  269. assert bencode(0) == 'i0e'
  270. assert bencode(-10) == 'i-10e'
  271. assert bencode(12345678901234567890L) == 'i12345678901234567890e'
  272. assert bencode('') == '0:'
  273. assert bencode('abc') == '3:abc'
  274. assert bencode('1234567890') == '10:1234567890'
  275. assert bencode([]) == 'le'
  276. assert bencode([1, 2, 3]) == 'li1ei2ei3ee'
  277. assert bencode([['Alice', 'Bob'], [2, 3]]) == 'll5:Alice3:Bobeli2ei3eee'
  278. assert bencode({}) == 'de'
  279. assert bencode({'age': 25, 'eyes': 'blue'}) == 'd3:agei25e4:eyes4:bluee'
  280. assert bencode({'spam.mp3': {'author': 'Alice', 'length': 100000}}) == 'd8:spam.mp3d6:author5:Alice6:lengthi100000eee'
  281. assert bencode(Bencached(bencode(3))) == 'i3e'
  282. try:
  283. bencode({1: 'foo'})
  284. except TypeError:
  285. return
  286. assert 0
  287. try:
  288. import psyco
  289. psyco.bind(bdecode)
  290. psyco.bind(bencode)
  291. except ImportError:
  292. pass