/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/_bencode_pyx.pyx

  • Committer: Jelmer Vernooij
  • Date: 2017-08-07 11:49:46 UTC
  • mto: (6747.3.4 avoid-set-revid-3)
  • mto: This revision was merged to the branch mainline in revision 6750.
  • Revision ID: jelmer@jelmer.uk-20170807114946-luclmxuawyzhpiot
Avoid setting revision_ids.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007, 2009, 2010 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Pyrex implementation for bencode coder/decoder"""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
from cpython.bytes cimport (
 
22
    PyBytes_CheckExact,
 
23
    PyBytes_FromStringAndSize,
 
24
    PyBytes_AS_STRING,
 
25
    PyBytes_GET_SIZE,
 
26
    )
 
27
from cpython.long cimport (
 
28
    PyLong_CheckExact,
 
29
    )
 
30
from cpython.int cimport (
 
31
    PyInt_CheckExact,
 
32
    PyInt_FromString,
 
33
    )
 
34
from cpython.tuple cimport (
 
35
    PyTuple_CheckExact,
 
36
    )
 
37
from cpython.list cimport (
 
38
    PyList_CheckExact,
 
39
    PyList_Append,
 
40
    )
 
41
from cpython.dict cimport (
 
42
    PyDict_CheckExact,
 
43
    )
 
44
from cpython.bool cimport (
 
45
    PyBool_Check,
 
46
    )
 
47
from cpython.mem cimport (
 
48
    PyMem_Free,
 
49
    PyMem_Malloc,
 
50
    PyMem_Realloc,
 
51
    )
 
52
 
 
53
from libc.stdlib cimport (
 
54
    strtol,
 
55
    )
 
56
from libc.string cimport (
 
57
    memcpy,
 
58
    )
 
59
 
 
60
cdef extern from "Python.h":
 
61
    # There is no cython module for ceval.h for some reason
 
62
    int Py_GetRecursionLimit()
 
63
    int Py_EnterRecursiveCall(char *)
 
64
    void Py_LeaveRecursiveCall()
 
65
 
 
66
cdef extern from "python-compat.h":
 
67
    int snprintf(char* buffer, size_t nsize, char* fmt, ...)
 
68
 
 
69
cdef class Decoder
 
70
cdef class Encoder
 
71
 
 
72
cdef extern from "_bencode_pyx.h":
 
73
    void D_UPDATE_TAIL(Decoder, int n)
 
74
    void E_UPDATE_TAIL(Encoder, int n)
 
75
 
 
76
from ._static_tuple_c cimport StaticTuple, StaticTuple_CheckExact, \
 
77
    import_static_tuple_c
 
78
 
 
79
import_static_tuple_c()
 
80
 
 
81
 
 
82
cdef class Decoder:
 
83
    """Bencode decoder"""
 
84
 
 
85
    cdef readonly char *tail
 
86
    cdef readonly int size
 
87
    cdef readonly int _yield_tuples
 
88
    cdef object text
 
89
 
 
90
    def __init__(self, s, yield_tuples=0):
 
91
        """Initialize decoder engine.
 
92
        @param  s:  Python string.
 
93
        """
 
94
        if not PyBytes_CheckExact(s):
 
95
            raise TypeError("bytes required")
 
96
 
 
97
        self.text = s
 
98
        self.tail = PyBytes_AS_STRING(s)
 
99
        self.size = PyBytes_GET_SIZE(s)
 
100
        self._yield_tuples = int(yield_tuples)
 
101
 
 
102
    def decode(self):
 
103
        result = self._decode_object()
 
104
        if self.size != 0:
 
105
            raise ValueError('junk in stream')
 
106
        return result
 
107
 
 
108
    def decode_object(self):
 
109
        return self._decode_object()
 
110
 
 
111
    cdef object _decode_object(self):
 
112
        cdef char ch
 
113
 
 
114
        if 0 == self.size:
 
115
            raise ValueError('stream underflow')
 
116
 
 
117
        if Py_EnterRecursiveCall("_decode_object"):
 
118
            raise RuntimeError("too deeply nested")
 
119
        try:
 
120
            ch = self.tail[0]
 
121
            if c'0' <= ch <= c'9':
 
122
                return self._decode_string()
 
123
            elif ch == c'l':
 
124
                D_UPDATE_TAIL(self, 1)
 
125
                return self._decode_list()
 
126
            elif ch == c'i':
 
127
                D_UPDATE_TAIL(self, 1)
 
128
                return self._decode_int()
 
129
            elif ch == c'd':
 
130
                D_UPDATE_TAIL(self, 1)
 
131
                return self._decode_dict()
 
132
            else:
 
133
                raise ValueError('unknown object type identifier %r' % ch)
 
134
        finally:
 
135
            Py_LeaveRecursiveCall()
 
136
 
 
137
    cdef int _read_digits(self, char stop_char) except -1:
 
138
        cdef int i
 
139
        i = 0
 
140
        while ((self.tail[i] >= c'0' and self.tail[i] <= c'9') or
 
141
               self.tail[i] == c'-') and i < self.size:
 
142
            i = i + 1
 
143
 
 
144
        if self.tail[i] != stop_char:
 
145
            raise ValueError("Stop character %c not found: %c" % 
 
146
                (stop_char, self.tail[i]))
 
147
        if (self.tail[0] == c'0' or 
 
148
                (self.tail[0] == c'-' and self.tail[1] == c'0')):
 
149
            if i == 1:
 
150
                return i
 
151
            else:
 
152
                raise ValueError # leading zeroes are not allowed
 
153
        return i
 
154
 
 
155
    cdef object _decode_int(self):
 
156
        cdef int i
 
157
        i = self._read_digits(c'e')
 
158
        self.tail[i] = 0
 
159
        try:
 
160
            ret = PyInt_FromString(self.tail, NULL, 10)
 
161
        finally:
 
162
            self.tail[i] = c'e'
 
163
        D_UPDATE_TAIL(self, i+1)
 
164
        return ret
 
165
 
 
166
    cdef object _decode_string(self):
 
167
        cdef int n
 
168
        cdef char *next_tail
 
169
        # strtol allows leading whitespace, negatives, and leading zeros
 
170
        # however, all callers have already checked that '0' <= tail[0] <= '9'
 
171
        # or they wouldn't have called _decode_string
 
172
        # strtol will stop at trailing whitespace, etc
 
173
        n = strtol(self.tail, &next_tail, 10)
 
174
        if next_tail == NULL or next_tail[0] != c':':
 
175
            raise ValueError('string len not terminated by ":"')
 
176
        # strtol allows leading zeros, so validate that we don't have that
 
177
        if (self.tail[0] == c'0'
 
178
            and (n != 0 or (next_tail - self.tail != 1))):
 
179
            raise ValueError('leading zeros are not allowed')
 
180
        D_UPDATE_TAIL(self, next_tail - self.tail + 1)
 
181
        if n == 0:
 
182
            return b''
 
183
        if n > self.size:
 
184
            raise ValueError('stream underflow')
 
185
        if n < 0:
 
186
            raise ValueError('string size below zero: %d' % n)
 
187
 
 
188
        result = PyBytes_FromStringAndSize(self.tail, n)
 
189
        D_UPDATE_TAIL(self, n)
 
190
        return result
 
191
 
 
192
    cdef object _decode_list(self):
 
193
        result = []
 
194
 
 
195
        while self.size > 0:
 
196
            if self.tail[0] == c'e':
 
197
                D_UPDATE_TAIL(self, 1)
 
198
                if self._yield_tuples:
 
199
                    return tuple(result)
 
200
                else:
 
201
                    return result
 
202
            else:
 
203
                # As a quick shortcut, check to see if the next object is a
 
204
                # string, since we know that won't be creating recursion
 
205
                # if self.tail[0] >= c'0' and self.tail[0] <= c'9':
 
206
                PyList_Append(result, self._decode_object())
 
207
 
 
208
        raise ValueError('malformed list')
 
209
 
 
210
    cdef object _decode_dict(self):
 
211
        cdef char ch
 
212
 
 
213
        result = {}
 
214
        lastkey = None
 
215
 
 
216
        while self.size > 0:
 
217
            ch = self.tail[0]
 
218
            if ch == c'e':
 
219
                D_UPDATE_TAIL(self, 1)
 
220
                return result
 
221
            else:
 
222
                # keys should be strings only
 
223
                if self.tail[0] < c'0' or self.tail[0] > c'9':
 
224
                    raise ValueError('key was not a simple string.')
 
225
                key = self._decode_string()
 
226
                if lastkey is not None and lastkey >= key:
 
227
                    raise ValueError('dict keys disordered')
 
228
                else:
 
229
                    lastkey = key
 
230
                value = self._decode_object()
 
231
                result[key] = value
 
232
 
 
233
        raise ValueError('malformed dict')
 
234
 
 
235
 
 
236
def bdecode(object s):
 
237
    """Decode string x to Python object"""
 
238
    return Decoder(s).decode()
 
239
 
 
240
 
 
241
def bdecode_as_tuple(object s):
 
242
    """Decode string x to Python object, using tuples rather than lists."""
 
243
    return Decoder(s, True).decode()
 
244
 
 
245
 
 
246
class Bencached(object):
 
247
    __slots__ = ['bencoded']
 
248
 
 
249
    def __init__(self, s):
 
250
        self.bencoded = s
 
251
 
 
252
 
 
253
cdef enum:
 
254
    INITSIZE = 1024     # initial size for encoder buffer
 
255
    INT_BUF_SIZE = 32
 
256
 
 
257
 
 
258
cdef class Encoder:
 
259
    """Bencode encoder"""
 
260
 
 
261
    cdef readonly char *tail
 
262
    cdef readonly int size
 
263
    cdef readonly char *buffer
 
264
    cdef readonly int maxsize
 
265
 
 
266
    def __init__(self, int maxsize=INITSIZE):
 
267
        """Initialize encoder engine
 
268
        @param  maxsize:    initial size of internal char buffer
 
269
        """
 
270
        cdef char *p
 
271
 
 
272
        self.maxsize = 0
 
273
        self.size = 0
 
274
        self.tail = NULL
 
275
 
 
276
        p = <char*>PyMem_Malloc(maxsize)
 
277
        if p == NULL:
 
278
            raise MemoryError('Not enough memory to allocate buffer '
 
279
                              'for encoder')
 
280
        self.buffer = p
 
281
        self.maxsize = maxsize
 
282
        self.tail = p
 
283
 
 
284
    def __dealloc__(self):
 
285
        PyMem_Free(self.buffer)
 
286
        self.buffer = NULL
 
287
        self.maxsize = 0
 
288
 
 
289
    def to_bytes(self):
 
290
        if self.buffer != NULL and self.size != 0:
 
291
            return PyBytes_FromStringAndSize(self.buffer, self.size)
 
292
        return b''
 
293
 
 
294
    cdef int _ensure_buffer(self, int required) except 0:
 
295
        """Ensure that tail of CharTail buffer has enough size.
 
296
        If buffer is not big enough then function try to
 
297
        realloc buffer.
 
298
        """
 
299
        cdef char *new_buffer
 
300
        cdef int   new_size
 
301
 
 
302
        if self.size + required < self.maxsize:
 
303
            return 1
 
304
 
 
305
        new_size = self.maxsize
 
306
        while new_size < self.size + required:
 
307
            new_size = new_size * 2
 
308
        new_buffer = <char*>PyMem_Realloc(self.buffer, <size_t>new_size)
 
309
        if new_buffer == NULL:
 
310
            raise MemoryError('Cannot realloc buffer for encoder')
 
311
 
 
312
        self.buffer = new_buffer
 
313
        self.maxsize = new_size
 
314
        self.tail = &new_buffer[self.size]
 
315
        return 1
 
316
 
 
317
    cdef int _encode_int(self, int x) except 0:
 
318
        """Encode int to bencode string iNNNe
 
319
        @param  x:  value to encode
 
320
        """
 
321
        cdef int n
 
322
        self._ensure_buffer(INT_BUF_SIZE)
 
323
        n = snprintf(self.tail, INT_BUF_SIZE, b"i%de", x)
 
324
        if n < 0:
 
325
            raise MemoryError('int %d too big to encode' % x)
 
326
        E_UPDATE_TAIL(self, n)
 
327
        return 1
 
328
 
 
329
    cdef int _encode_long(self, x) except 0:
 
330
        return self._append_string(b'i%de' % x)
 
331
 
 
332
    cdef int _append_string(self, s) except 0:
 
333
        cdef Py_ssize_t n
 
334
        n = PyBytes_GET_SIZE(s)
 
335
        self._ensure_buffer(n)
 
336
        memcpy(self.tail, PyBytes_AS_STRING(s), n)
 
337
        E_UPDATE_TAIL(self, n)
 
338
        return 1
 
339
 
 
340
    cdef int _encode_string(self, x) except 0:
 
341
        cdef int n
 
342
        cdef Py_ssize_t x_len
 
343
        x_len = PyBytes_GET_SIZE(x)
 
344
        self._ensure_buffer(x_len + INT_BUF_SIZE)
 
345
        n = snprintf(self.tail, INT_BUF_SIZE, b'%d:', x_len)
 
346
        if n < 0:
 
347
            raise MemoryError('string %s too big to encode' % x)
 
348
        memcpy(<void *>(self.tail+n), PyBytes_AS_STRING(x), x_len)
 
349
        E_UPDATE_TAIL(self, n + x_len)
 
350
        return 1
 
351
 
 
352
    cdef int _encode_list(self, x) except 0:
 
353
        self._ensure_buffer(1)
 
354
        self.tail[0] = c'l'
 
355
        E_UPDATE_TAIL(self, 1)
 
356
 
 
357
        for i in x:
 
358
            self.process(i)
 
359
 
 
360
        self._ensure_buffer(1)
 
361
        self.tail[0] = c'e'
 
362
        E_UPDATE_TAIL(self, 1)
 
363
        return 1
 
364
 
 
365
    cdef int _encode_dict(self, x) except 0:
 
366
        self._ensure_buffer(1)
 
367
        self.tail[0] = c'd'
 
368
        E_UPDATE_TAIL(self, 1)
 
369
 
 
370
        for k in sorted(x):
 
371
            if not PyBytes_CheckExact(k):
 
372
                raise TypeError('key in dict should be string')
 
373
            self._encode_string(k)
 
374
            self.process(x[k])
 
375
 
 
376
        self._ensure_buffer(1)
 
377
        self.tail[0] = c'e'
 
378
        E_UPDATE_TAIL(self, 1)
 
379
        return 1
 
380
 
 
381
    def process(self, object x):
 
382
        if Py_EnterRecursiveCall("encode"):
 
383
            raise RuntimeError("too deeply nested")
 
384
        try:
 
385
            if PyBytes_CheckExact(x):
 
386
                self._encode_string(x)
 
387
            elif PyInt_CheckExact(x) and x.bit_length() < 32:
 
388
                self._encode_int(x)
 
389
            elif PyLong_CheckExact(x):
 
390
                self._encode_long(x)
 
391
            elif (PyList_CheckExact(x) or PyTuple_CheckExact(x)
 
392
                  or isinstance(x, StaticTuple)):
 
393
                self._encode_list(x)
 
394
            elif PyDict_CheckExact(x):
 
395
                self._encode_dict(x)
 
396
            elif PyBool_Check(x):
 
397
                self._encode_int(int(x))
 
398
            elif isinstance(x, Bencached):
 
399
                self._append_string(x.bencoded)
 
400
            else:
 
401
                raise TypeError('unsupported type %r' % x)
 
402
        finally:
 
403
            Py_LeaveRecursiveCall()
 
404
 
 
405
 
 
406
def bencode(x):
 
407
    """Encode Python object x to string"""
 
408
    encoder = Encoder()
 
409
    encoder.process(x)
 
410
    return encoder.to_bytes()