1
# Copyright (C) 2007, 2009, 2010 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Pyrex implementation for bencode coder/decoder"""
19
from __future__ import absolute_import
21
from cpython.bool cimport (
24
from cpython.bytes cimport (
26
PyBytes_FromStringAndSize,
30
from cpython.dict cimport (
33
from cpython.int cimport (
37
from cpython.list cimport (
41
from cpython.long cimport (
44
from cpython.mem cimport (
49
from cpython.tuple cimport (
53
from libc.stdlib cimport (
56
from libc.string cimport (
60
cdef extern from "python-compat.h":
61
int snprintf(char* buffer, size_t nsize, char* fmt, ...)
62
# Use wrapper with inverted error return so Cython can propogate
63
int BrzPy_EnterRecursiveCall(char *) except 0
65
cdef extern from "Python.h":
66
void Py_LeaveRecursiveCall()
71
cdef extern from "_bencode_pyx.h":
72
void D_UPDATE_TAIL(Decoder, int n)
73
void E_UPDATE_TAIL(Encoder, int n)
75
from ._static_tuple_c cimport StaticTuple, StaticTuple_CheckExact, \
78
import_static_tuple_c()
84
cdef readonly char *tail
85
cdef readonly int size
86
cdef readonly int _yield_tuples
89
def __init__(self, s, yield_tuples=0):
90
"""Initialize decoder engine.
91
@param s: Python string.
93
if not PyBytes_CheckExact(s):
94
raise TypeError("bytes required")
97
self.tail = PyBytes_AS_STRING(s)
98
self.size = PyBytes_GET_SIZE(s)
99
self._yield_tuples = int(yield_tuples)
102
result = self._decode_object()
104
raise ValueError('junk in stream')
107
def decode_object(self):
108
return self._decode_object()
110
cdef object _decode_object(self):
114
raise ValueError('stream underflow')
116
BrzPy_EnterRecursiveCall(" while bencode decoding")
119
if c'0' <= ch <= c'9':
120
return self._decode_string()
122
D_UPDATE_TAIL(self, 1)
123
return self._decode_list()
125
D_UPDATE_TAIL(self, 1)
126
return self._decode_int()
128
D_UPDATE_TAIL(self, 1)
129
return self._decode_dict()
131
Py_LeaveRecursiveCall()
132
raise ValueError('unknown object type identifier %r' % ch)
134
cdef int _read_digits(self, char stop_char) except -1:
137
while ((self.tail[i] >= c'0' and self.tail[i] <= c'9') or
138
self.tail[i] == c'-') and i < self.size:
141
if self.tail[i] != stop_char:
142
raise ValueError("Stop character %c not found: %c" %
143
(stop_char, self.tail[i]))
144
if (self.tail[0] == c'0' or
145
(self.tail[0] == c'-' and self.tail[1] == c'0')):
149
raise ValueError # leading zeroes are not allowed
152
cdef object _decode_int(self):
154
i = self._read_digits(c'e')
157
ret = PyInt_FromString(self.tail, NULL, 10)
160
D_UPDATE_TAIL(self, i+1)
163
cdef object _decode_string(self):
166
# strtol allows leading whitespace, negatives, and leading zeros
167
# however, all callers have already checked that '0' <= tail[0] <= '9'
168
# or they wouldn't have called _decode_string
169
# strtol will stop at trailing whitespace, etc
170
n = strtol(self.tail, &next_tail, 10)
171
if next_tail == NULL or next_tail[0] != c':':
172
raise ValueError('string len not terminated by ":"')
173
# strtol allows leading zeros, so validate that we don't have that
174
if (self.tail[0] == c'0'
175
and (n != 0 or (next_tail - self.tail != 1))):
176
raise ValueError('leading zeros are not allowed')
177
D_UPDATE_TAIL(self, next_tail - self.tail + 1)
181
raise ValueError('stream underflow')
183
raise ValueError('string size below zero: %d' % n)
185
result = PyBytes_FromStringAndSize(self.tail, n)
186
D_UPDATE_TAIL(self, n)
189
cdef object _decode_list(self):
193
if self.tail[0] == c'e':
194
D_UPDATE_TAIL(self, 1)
195
if self._yield_tuples:
200
# As a quick shortcut, check to see if the next object is a
201
# string, since we know that won't be creating recursion
202
# if self.tail[0] >= c'0' and self.tail[0] <= c'9':
203
PyList_Append(result, self._decode_object())
205
raise ValueError('malformed list')
207
cdef object _decode_dict(self):
216
D_UPDATE_TAIL(self, 1)
219
# keys should be strings only
220
if self.tail[0] < c'0' or self.tail[0] > c'9':
221
raise ValueError('key was not a simple string.')
222
key = self._decode_string()
223
if lastkey is not None and lastkey >= key:
224
raise ValueError('dict keys disordered')
227
value = self._decode_object()
230
raise ValueError('malformed dict')
233
def bdecode(object s):
234
"""Decode string x to Python object"""
235
return Decoder(s).decode()
238
def bdecode_as_tuple(object s):
239
"""Decode string x to Python object, using tuples rather than lists."""
240
return Decoder(s, True).decode()
243
class Bencached(object):
244
__slots__ = ['bencoded']
246
def __init__(self, s):
251
INITSIZE = 1024 # initial size for encoder buffer
256
"""Bencode encoder"""
258
cdef readonly char *tail
259
cdef readonly int size
260
cdef readonly char *buffer
261
cdef readonly int maxsize
263
def __init__(self, int maxsize=INITSIZE):
264
"""Initialize encoder engine
265
@param maxsize: initial size of internal char buffer
273
p = <char*>PyMem_Malloc(maxsize)
275
raise MemoryError('Not enough memory to allocate buffer '
278
self.maxsize = maxsize
281
def __dealloc__(self):
282
PyMem_Free(self.buffer)
287
if self.buffer != NULL and self.size != 0:
288
return PyBytes_FromStringAndSize(self.buffer, self.size)
291
cdef int _ensure_buffer(self, int required) except 0:
292
"""Ensure that tail of CharTail buffer has enough size.
293
If buffer is not big enough then function try to
296
cdef char *new_buffer
299
if self.size + required < self.maxsize:
302
new_size = self.maxsize
303
while new_size < self.size + required:
304
new_size = new_size * 2
305
new_buffer = <char*>PyMem_Realloc(self.buffer, <size_t>new_size)
306
if new_buffer == NULL:
307
raise MemoryError('Cannot realloc buffer for encoder')
309
self.buffer = new_buffer
310
self.maxsize = new_size
311
self.tail = &new_buffer[self.size]
314
cdef int _encode_int(self, int x) except 0:
315
"""Encode int to bencode string iNNNe
316
@param x: value to encode
319
self._ensure_buffer(INT_BUF_SIZE)
320
n = snprintf(self.tail, INT_BUF_SIZE, b"i%de", x)
322
raise MemoryError('int %d too big to encode' % x)
323
E_UPDATE_TAIL(self, n)
326
cdef int _encode_long(self, x) except 0:
327
return self._append_string(b'i%de' % x)
329
cdef int _append_string(self, s) except 0:
331
n = PyBytes_GET_SIZE(s)
332
self._ensure_buffer(n)
333
memcpy(self.tail, PyBytes_AS_STRING(s), n)
334
E_UPDATE_TAIL(self, n)
337
cdef int _encode_string(self, x) except 0:
339
cdef Py_ssize_t x_len
340
x_len = PyBytes_GET_SIZE(x)
341
self._ensure_buffer(x_len + INT_BUF_SIZE)
342
n = snprintf(self.tail, INT_BUF_SIZE, b'%ld:', x_len)
344
raise MemoryError('string %s too big to encode' % x)
345
memcpy(<void *>(self.tail+n), PyBytes_AS_STRING(x), x_len)
346
E_UPDATE_TAIL(self, n + x_len)
349
cdef int _encode_list(self, x) except 0:
350
self._ensure_buffer(1)
352
E_UPDATE_TAIL(self, 1)
357
self._ensure_buffer(1)
359
E_UPDATE_TAIL(self, 1)
362
cdef int _encode_dict(self, x) except 0:
363
self._ensure_buffer(1)
365
E_UPDATE_TAIL(self, 1)
368
if not PyBytes_CheckExact(k):
369
raise TypeError('key in dict should be string')
370
self._encode_string(k)
373
self._ensure_buffer(1)
375
E_UPDATE_TAIL(self, 1)
378
cpdef object process(self, object x):
379
BrzPy_EnterRecursiveCall(" while bencode encoding")
381
if PyBytes_CheckExact(x):
382
self._encode_string(x)
383
elif PyInt_CheckExact(x) and x.bit_length() < 32:
385
elif PyLong_CheckExact(x):
387
elif (PyList_CheckExact(x) or PyTuple_CheckExact(x)
388
or isinstance(x, StaticTuple)):
390
elif PyDict_CheckExact(x):
392
elif PyBool_Check(x):
393
self._encode_int(int(x))
394
elif isinstance(x, Bencached):
395
self._append_string(x.bencoded)
397
raise TypeError('unsupported type %r' % x)
399
Py_LeaveRecursiveCall()
403
"""Encode Python object x to string"""
406
return encoder.to_bytes()