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 cpython.bool cimport (
22
from cpython.bytes cimport (
24
PyBytes_FromStringAndSize,
28
from cpython.dict cimport (
31
from cpython.int cimport (
35
from cpython.list cimport (
39
from cpython.long cimport (
42
from cpython.mem cimport (
47
from cpython.tuple cimport (
51
from libc.stdlib cimport (
54
from libc.string cimport (
58
cdef extern from "python-compat.h":
59
int snprintf(char* buffer, size_t nsize, char* fmt, ...)
60
# Use wrapper with inverted error return so Cython can propogate
61
int BrzPy_EnterRecursiveCall(char *) except 0
63
cdef extern from "Python.h":
64
void Py_LeaveRecursiveCall()
69
cdef extern from "_bencode_pyx.h":
70
void D_UPDATE_TAIL(Decoder, int n)
71
void E_UPDATE_TAIL(Encoder, int n)
73
from ._static_tuple_c cimport StaticTuple, StaticTuple_CheckExact, \
76
import_static_tuple_c()
82
cdef readonly char *tail
83
cdef readonly int size
84
cdef readonly int _yield_tuples
87
def __init__(self, s, yield_tuples=0):
88
"""Initialize decoder engine.
89
@param s: Python string.
91
if not PyBytes_CheckExact(s):
92
raise TypeError("bytes required")
95
self.tail = PyBytes_AS_STRING(s)
96
self.size = PyBytes_GET_SIZE(s)
97
self._yield_tuples = int(yield_tuples)
100
result = self._decode_object()
102
raise ValueError('junk in stream')
105
def decode_object(self):
106
return self._decode_object()
108
cdef object _decode_object(self):
112
raise ValueError('stream underflow')
114
BrzPy_EnterRecursiveCall(" while bencode decoding")
117
if c'0' <= ch <= c'9':
118
return self._decode_string()
120
D_UPDATE_TAIL(self, 1)
121
return self._decode_list()
123
D_UPDATE_TAIL(self, 1)
124
return self._decode_int()
126
D_UPDATE_TAIL(self, 1)
127
return self._decode_dict()
129
Py_LeaveRecursiveCall()
130
raise ValueError('unknown object type identifier %r' % ch)
132
cdef int _read_digits(self, char stop_char) except -1:
135
while ((self.tail[i] >= c'0' and self.tail[i] <= c'9') or
136
self.tail[i] == c'-') and i < self.size:
139
if self.tail[i] != stop_char:
140
raise ValueError("Stop character %c not found: %c" %
141
(stop_char, self.tail[i]))
142
if (self.tail[0] == c'0' or
143
(self.tail[0] == c'-' and self.tail[1] == c'0')):
147
raise ValueError # leading zeroes are not allowed
150
cdef object _decode_int(self):
152
i = self._read_digits(c'e')
155
ret = PyInt_FromString(self.tail, NULL, 10)
158
D_UPDATE_TAIL(self, i+1)
161
cdef object _decode_string(self):
164
# strtol allows leading whitespace, negatives, and leading zeros
165
# however, all callers have already checked that '0' <= tail[0] <= '9'
166
# or they wouldn't have called _decode_string
167
# strtol will stop at trailing whitespace, etc
168
n = strtol(self.tail, &next_tail, 10)
169
if next_tail == NULL or next_tail[0] != c':':
170
raise ValueError('string len not terminated by ":"')
171
# strtol allows leading zeros, so validate that we don't have that
172
if (self.tail[0] == c'0'
173
and (n != 0 or (next_tail - self.tail != 1))):
174
raise ValueError('leading zeros are not allowed')
175
D_UPDATE_TAIL(self, next_tail - self.tail + 1)
179
raise ValueError('stream underflow')
181
raise ValueError('string size below zero: %d' % n)
183
result = PyBytes_FromStringAndSize(self.tail, n)
184
D_UPDATE_TAIL(self, n)
187
cdef object _decode_list(self):
191
if self.tail[0] == c'e':
192
D_UPDATE_TAIL(self, 1)
193
if self._yield_tuples:
198
# As a quick shortcut, check to see if the next object is a
199
# string, since we know that won't be creating recursion
200
# if self.tail[0] >= c'0' and self.tail[0] <= c'9':
201
PyList_Append(result, self._decode_object())
203
raise ValueError('malformed list')
205
cdef object _decode_dict(self):
214
D_UPDATE_TAIL(self, 1)
217
# keys should be strings only
218
if self.tail[0] < c'0' or self.tail[0] > c'9':
219
raise ValueError('key was not a simple string.')
220
key = self._decode_string()
221
if lastkey is not None and lastkey >= key:
222
raise ValueError('dict keys disordered')
225
value = self._decode_object()
228
raise ValueError('malformed dict')
231
def bdecode(object s):
232
"""Decode string x to Python object"""
233
return Decoder(s).decode()
236
def bdecode_as_tuple(object s):
237
"""Decode string x to Python object, using tuples rather than lists."""
238
return Decoder(s, True).decode()
241
class Bencached(object):
242
__slots__ = ['bencoded']
244
def __init__(self, s):
249
INITSIZE = 1024 # initial size for encoder buffer
254
"""Bencode encoder"""
256
cdef readonly char *tail
257
cdef readonly int size
258
cdef readonly char *buffer
259
cdef readonly int maxsize
261
def __init__(self, int maxsize=INITSIZE):
262
"""Initialize encoder engine
263
@param maxsize: initial size of internal char buffer
271
p = <char*>PyMem_Malloc(maxsize)
273
raise MemoryError('Not enough memory to allocate buffer '
276
self.maxsize = maxsize
279
def __dealloc__(self):
280
PyMem_Free(self.buffer)
285
if self.buffer != NULL and self.size != 0:
286
return PyBytes_FromStringAndSize(self.buffer, self.size)
289
cdef int _ensure_buffer(self, int required) except 0:
290
"""Ensure that tail of CharTail buffer has enough size.
291
If buffer is not big enough then function try to
294
cdef char *new_buffer
297
if self.size + required < self.maxsize:
300
new_size = self.maxsize
301
while new_size < self.size + required:
302
new_size = new_size * 2
303
new_buffer = <char*>PyMem_Realloc(self.buffer, <size_t>new_size)
304
if new_buffer == NULL:
305
raise MemoryError('Cannot realloc buffer for encoder')
307
self.buffer = new_buffer
308
self.maxsize = new_size
309
self.tail = &new_buffer[self.size]
312
cdef int _encode_int(self, int x) except 0:
313
"""Encode int to bencode string iNNNe
314
@param x: value to encode
317
self._ensure_buffer(INT_BUF_SIZE)
318
n = snprintf(self.tail, INT_BUF_SIZE, b"i%de", x)
320
raise MemoryError('int %d too big to encode' % x)
321
E_UPDATE_TAIL(self, n)
324
cdef int _encode_long(self, x) except 0:
325
return self._append_string(b'i%de' % x)
327
cdef int _append_string(self, s) except 0:
329
n = PyBytes_GET_SIZE(s)
330
self._ensure_buffer(n)
331
memcpy(self.tail, PyBytes_AS_STRING(s), n)
332
E_UPDATE_TAIL(self, n)
335
cdef int _encode_string(self, x) except 0:
337
cdef Py_ssize_t x_len
338
x_len = PyBytes_GET_SIZE(x)
339
self._ensure_buffer(x_len + INT_BUF_SIZE)
340
n = snprintf(self.tail, INT_BUF_SIZE, b'%ld:', x_len)
342
raise MemoryError('string %s too big to encode' % x)
343
memcpy(<void *>(self.tail+n), PyBytes_AS_STRING(x), x_len)
344
E_UPDATE_TAIL(self, n + x_len)
347
cdef int _encode_list(self, x) except 0:
348
self._ensure_buffer(1)
350
E_UPDATE_TAIL(self, 1)
355
self._ensure_buffer(1)
357
E_UPDATE_TAIL(self, 1)
360
cdef int _encode_dict(self, x) except 0:
361
self._ensure_buffer(1)
363
E_UPDATE_TAIL(self, 1)
366
if not PyBytes_CheckExact(k):
367
raise TypeError('key in dict should be string')
368
self._encode_string(k)
371
self._ensure_buffer(1)
373
E_UPDATE_TAIL(self, 1)
376
cpdef object process(self, object x):
377
BrzPy_EnterRecursiveCall(" while bencode encoding")
379
if PyBytes_CheckExact(x):
380
self._encode_string(x)
381
elif PyInt_CheckExact(x) and x.bit_length() < 32:
383
elif PyLong_CheckExact(x):
385
elif (PyList_CheckExact(x) or PyTuple_CheckExact(x)
386
or isinstance(x, StaticTuple)):
388
elif PyDict_CheckExact(x):
390
elif PyBool_Check(x):
391
self._encode_int(int(x))
392
elif isinstance(x, Bencached):
393
self._append_string(x.bencoded)
395
raise TypeError('unsupported type %r' % x)
397
Py_LeaveRecursiveCall()
401
"""Encode Python object x to string"""
404
return encoder.to_bytes()