ubencode.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.1 (the License). You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License. You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10. # Written by Petru Paler
  11. import re
  12. from BTL.translation import _
  13. from BTL.obsoletepythonsupport import *
  14. from BTL import BTFailure
  15. string_pat = re.compile("^[0123456789]+(:|u)")
  16. def decode_int(x, f):
  17. f += 1
  18. newf = x.index('e', f)
  19. n = int(x[f:newf])
  20. if x[f] == '-':
  21. if x[f + 1] == '0':
  22. raise ValueError
  23. elif x[f] == '0' and newf != f+1:
  24. raise ValueError
  25. return (n, newf+1)
  26. def decode_string(x, f):
  27. m = string_pat.match(f)
  28. if m is None:
  29. raise ValueError(_("No string seperator found."))
  30. colon = m.end() - 1
  31. n = int(x[f:colon])
  32. if x[f] == '0' and colon != f+1:
  33. raise ValueError
  34. colon += 1
  35. val = x[colon:colon+n]
  36. if m.groups()[0] == 'u':
  37. val = val.decode('utf8')
  38. return (val, colon+n)
  39. def decode_list(x, f):
  40. r, f = [], f+1
  41. while x[f] != 'e':
  42. v, f = decode_func[x[f]](x, f)
  43. r.append(v)
  44. return (r, f + 1)
  45. def decode_dict(x, f):
  46. r, f = {}, f+1
  47. lastkey = None
  48. while x[f] != 'e':
  49. k, f = decode_string(x, f)
  50. if lastkey >= k:
  51. raise ValueError
  52. lastkey = k
  53. r[k], f = decode_func[x[f]](x, f)
  54. return (r, f + 1)
  55. decode_func = {}
  56. decode_func['l'] = decode_list
  57. decode_func['d'] = decode_dict
  58. decode_func['i'] = decode_int
  59. decode_func['0'] = decode_string
  60. decode_func['1'] = decode_string
  61. decode_func['2'] = decode_string
  62. decode_func['3'] = decode_string
  63. decode_func['4'] = decode_string
  64. decode_func['5'] = decode_string
  65. decode_func['6'] = decode_string
  66. decode_func['7'] = decode_string
  67. decode_func['8'] = decode_string
  68. decode_func['9'] = decode_string
  69. def bdecode(x):
  70. try:
  71. r, l = decode_func[x[0]](x, 0)
  72. except (IndexError, KeyError, ValueError):
  73. raise BTFailure, _("not a valid bencoded string")
  74. if l != len(x):
  75. raise BTFailure, _("invalid bencoded value (data after valid prefix)")
  76. return r
  77. from types import StringType, UnicodeType, IntType, LongType, DictType, ListType, TupleType
  78. class Bencached(object):
  79. __slots__ = ['bencoded']
  80. def __init__(self, s):
  81. self.bencoded = s
  82. def encode_bencached(x,r):
  83. r.append(x.bencoded)
  84. def encode_int(x, r):
  85. r.extend(('i', str(x), 'e'))
  86. def encode_bool(x, r):
  87. if x:
  88. encode_int(1, r)
  89. else:
  90. encode_int(0, r)
  91. def encode_string(x, r):
  92. r.extend((str(len(x)), ':', x))
  93. def encode_unicode(x, r):
  94. x = x.encode('utf8')
  95. r.extend((str(len(x)), 'u', x))
  96. def encode_list(x, r):
  97. r.append('l')
  98. for i in x:
  99. encode_func[type(i)](i, r)
  100. r.append('e')
  101. def encode_dict(x,r):
  102. r.append('d')
  103. ilist = x.items()
  104. ilist.sort()
  105. for k, v in ilist:
  106. r.extend((str(len(k)), ':', k))
  107. encode_func[type(v)](v, r)
  108. r.append('e')
  109. encode_func = {}
  110. encode_func[Bencached] = encode_bencached
  111. encode_func[IntType] = encode_int
  112. encode_func[LongType] = encode_int
  113. encode_func[StringType] = encode_string
  114. encode_func[UnicodeType] = encode_unicode
  115. encode_func[ListType] = encode_list
  116. encode_func[TupleType] = encode_list
  117. encode_func[DictType] = encode_dict
  118. try:
  119. from types import BooleanType
  120. encode_func[BooleanType] = encode_bool
  121. except ImportError:
  122. pass
  123. def bencode(x):
  124. r = []
  125. encode_func[type(x)](x, r)
  126. return ''.join(r)