blob: 714fb13646cf93688fc3631354d69904e21a5100 [file] [log] [blame]
David Reissea2cba82009-03-30 21:35:00 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
David Reiss382fc302007-08-25 18:01:30 +000019
20#include <Python.h>
21#include "cStringIO.h"
David Reiss382fc302007-08-25 18:01:30 +000022#include <stdint.h>
Roger Meierc3f033f2011-09-13 13:54:05 +000023#ifndef _WIN32
24# include <stdbool.h>
25# include <netinet/in.h>
26#else
27# include <WinSock2.h>
28# pragma comment (lib, "ws2_32.lib")
29# define BIG_ENDIAN (4321)
30# define LITTLE_ENDIAN (1234)
31# define BYTE_ORDER LITTLE_ENDIAN
32# if defined(_MSC_VER) && _MSC_VER < 1600
33 typedef int _Bool;
34# define bool _Bool
Roger Meier7daf00c2015-06-03 11:45:35 +020035# define false 0
Roger Meierc3f033f2011-09-13 13:54:05 +000036# define true 1
37# endif
38# define inline __inline
39#endif
David Reiss382fc302007-08-25 18:01:30 +000040
David Reiss49809102009-03-18 23:14:13 +000041/* Fix endianness issues on Solaris */
42#if defined (__SVR4) && defined (__sun)
43 #if defined(__i386) && !defined(__i386__)
44 #define __i386__
45 #endif
46
47 #ifndef BIG_ENDIAN
48 #define BIG_ENDIAN (4321)
49 #endif
50 #ifndef LITTLE_ENDIAN
51 #define LITTLE_ENDIAN (1234)
52 #endif
53
54 /* I386 is LE, even on Solaris */
55 #if !defined(BYTE_ORDER) && defined(__i386__)
56 #define BYTE_ORDER LITTLE_ENDIAN
57 #endif
58#endif
59
David Reiss382fc302007-08-25 18:01:30 +000060// TODO(dreiss): defval appears to be unused. Look into removing it.
61// TODO(dreiss): Make parse_spec_args recursive, and cache the output
62// permanently in the object. (Malloc and orphan.)
63// TODO(dreiss): Why do we need cStringIO for reading, why not just char*?
64// Can cStringIO let us work with a BufferedTransport?
65// TODO(dreiss): Don't ignore the rv from cwrite (maybe).
66
67/* ====== BEGIN UTILITIES ====== */
68
69#define INIT_OUTBUF_SIZE 128
70
71// Stolen out of TProtocol.h.
72// It would be a huge pain to have both get this from one place.
73typedef enum TType {
74 T_STOP = 0,
75 T_VOID = 1,
76 T_BOOL = 2,
77 T_BYTE = 3,
78 T_I08 = 3,
79 T_I16 = 6,
80 T_I32 = 8,
81 T_U64 = 9,
82 T_I64 = 10,
83 T_DOUBLE = 4,
84 T_STRING = 11,
85 T_UTF7 = 11,
86 T_STRUCT = 12,
87 T_MAP = 13,
88 T_SET = 14,
89 T_LIST = 15,
90 T_UTF8 = 16,
91 T_UTF16 = 17
92} TType;
93
David Reissfdd8b5a2009-02-17 20:06:08 +000094#ifndef __BYTE_ORDER
95# if defined(BYTE_ORDER) && defined(LITTLE_ENDIAN) && defined(BIG_ENDIAN)
96# define __BYTE_ORDER BYTE_ORDER
97# define __LITTLE_ENDIAN LITTLE_ENDIAN
98# define __BIG_ENDIAN BIG_ENDIAN
99# else
100# error "Cannot determine endianness"
101# endif
102#endif
103
David Reiss382fc302007-08-25 18:01:30 +0000104// Same comment as the enum. Sorry.
105#if __BYTE_ORDER == __BIG_ENDIAN
106# define ntohll(n) (n)
107# define htonll(n) (n)
108#elif __BYTE_ORDER == __LITTLE_ENDIAN
109# if defined(__GNUC__) && defined(__GLIBC__)
110# include <byteswap.h>
111# define ntohll(n) bswap_64(n)
112# define htonll(n) bswap_64(n)
113# else /* GNUC & GLIBC */
114# define ntohll(n) ( (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32) )
115# define htonll(n) ( (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32) )
116# endif /* GNUC & GLIBC */
117#else /* __BYTE_ORDER */
118# error "Can't define htonll or ntohll!"
119#endif
120
121// Doing a benchmark shows that interning actually makes a difference, amazingly.
122#define INTERN_STRING(value) _intern_ ## value
123
124#define INT_CONV_ERROR_OCCURRED(v) ( ((v) == -1) && PyErr_Occurred() )
125#define CHECK_RANGE(v, min, max) ( ((v) <= (max)) && ((v) >= (min)) )
126
David Reiss382fc302007-08-25 18:01:30 +0000127/**
128 * A cache of the spec_args for a set or list,
129 * so we don't have to keep calling PyTuple_GET_ITEM.
130 */
131typedef struct {
132 TType element_type;
133 PyObject* typeargs;
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900134 bool immutable;
David Reiss382fc302007-08-25 18:01:30 +0000135} SetListTypeArgs;
136
137/**
138 * A cache of the spec_args for a map,
139 * so we don't have to keep calling PyTuple_GET_ITEM.
140 */
141typedef struct {
142 TType ktag;
143 TType vtag;
144 PyObject* ktypeargs;
145 PyObject* vtypeargs;
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900146 bool immutable;
David Reiss382fc302007-08-25 18:01:30 +0000147} MapTypeArgs;
148
149/**
150 * A cache of the spec_args for a struct,
151 * so we don't have to keep calling PyTuple_GET_ITEM.
152 */
153typedef struct {
154 PyObject* klass;
155 PyObject* spec;
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900156 bool immutable;
David Reiss382fc302007-08-25 18:01:30 +0000157} StructTypeArgs;
158
159/**
160 * A cache of the item spec from a struct specification,
161 * so we don't have to keep calling PyTuple_GET_ITEM.
162 */
163typedef struct {
164 int tag;
165 TType type;
166 PyObject* attrname;
167 PyObject* typeargs;
168 PyObject* defval;
169} StructItemSpec;
170
171/**
172 * A cache of the two key attributes of a CReadableTransport,
173 * so we don't have to keep calling PyObject_GetAttr.
174 */
175typedef struct {
176 PyObject* stringiobuf;
177 PyObject* refill_callable;
178} DecodeBuffer;
179
180/** Pointer to interned string to speed up attribute lookup. */
181static PyObject* INTERN_STRING(cstringio_buf);
182/** Pointer to interned string to speed up attribute lookup. */
183static PyObject* INTERN_STRING(cstringio_refill);
184
185static inline bool
186check_ssize_t_32(Py_ssize_t len) {
187 // error from getting the int
188 if (INT_CONV_ERROR_OCCURRED(len)) {
189 return false;
190 }
191 if (!CHECK_RANGE(len, 0, INT32_MAX)) {
192 PyErr_SetString(PyExc_OverflowError, "string size out of range");
193 return false;
194 }
195 return true;
196}
197
Roger Meier7daf00c2015-06-03 11:45:35 +0200198#define MAX_LIST_SIZE (10000)
199
200static inline bool
201check_list_length(Py_ssize_t len) {
202 // error from getting the int
203 if (INT_CONV_ERROR_OCCURRED(len)) {
204 return false;
205 }
206 if (!CHECK_RANGE(len, 0, MAX_LIST_SIZE)) {
207 PyErr_SetString(PyExc_OverflowError, "list size out of the sanity limit (10000 items max)");
208 return false;
209 }
210 return true;
211}
212
David Reiss382fc302007-08-25 18:01:30 +0000213static inline bool
214parse_pyint(PyObject* o, int32_t* ret, int32_t min, int32_t max) {
215 long val = PyInt_AsLong(o);
216
217 if (INT_CONV_ERROR_OCCURRED(val)) {
218 return false;
219 }
220 if (!CHECK_RANGE(val, min, max)) {
221 PyErr_SetString(PyExc_OverflowError, "int out of range");
222 return false;
223 }
224
225 *ret = (int32_t) val;
226 return true;
227}
228
Nobuaki Sukegawa4733db42016-01-05 02:50:57 +0900229static bool
230is_utf8(PyObject* typeargs) {
231 return PyString_Check(typeargs) && !strcmp(PyString_AS_STRING(typeargs), "UTF8");
232}
David Reiss382fc302007-08-25 18:01:30 +0000233
234/* --- FUNCTIONS TO PARSE STRUCT SPECIFICATOINS --- */
235
236static bool
237parse_set_list_args(SetListTypeArgs* dest, PyObject* typeargs) {
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900238 if (PyTuple_Size(typeargs) != 3) {
239 PyErr_SetString(PyExc_TypeError, "expecting tuple of size 3 for list/set type args");
David Reiss382fc302007-08-25 18:01:30 +0000240 return false;
241 }
242
243 dest->element_type = PyInt_AsLong(PyTuple_GET_ITEM(typeargs, 0));
244 if (INT_CONV_ERROR_OCCURRED(dest->element_type)) {
245 return false;
246 }
247
248 dest->typeargs = PyTuple_GET_ITEM(typeargs, 1);
249
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900250 dest->immutable = Py_True == PyTuple_GET_ITEM(typeargs, 2);
251
David Reiss382fc302007-08-25 18:01:30 +0000252 return true;
253}
254
255static bool
256parse_map_args(MapTypeArgs* dest, PyObject* typeargs) {
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900257 if (PyTuple_Size(typeargs) != 5) {
258 PyErr_SetString(PyExc_TypeError, "expecting 5 arguments for typeargs to map");
David Reiss382fc302007-08-25 18:01:30 +0000259 return false;
260 }
261
262 dest->ktag = PyInt_AsLong(PyTuple_GET_ITEM(typeargs, 0));
263 if (INT_CONV_ERROR_OCCURRED(dest->ktag)) {
264 return false;
265 }
266
267 dest->vtag = PyInt_AsLong(PyTuple_GET_ITEM(typeargs, 2));
268 if (INT_CONV_ERROR_OCCURRED(dest->vtag)) {
269 return false;
270 }
271
272 dest->ktypeargs = PyTuple_GET_ITEM(typeargs, 1);
273 dest->vtypeargs = PyTuple_GET_ITEM(typeargs, 3);
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900274 dest->immutable = Py_True == PyTuple_GET_ITEM(typeargs, 4);
David Reiss382fc302007-08-25 18:01:30 +0000275
276 return true;
277}
278
279static bool
280parse_struct_args(StructTypeArgs* dest, PyObject* typeargs) {
281 if (PyTuple_Size(typeargs) != 2) {
282 PyErr_SetString(PyExc_TypeError, "expecting tuple of size 2 for struct args");
283 return false;
284 }
285
286 dest->klass = PyTuple_GET_ITEM(typeargs, 0);
287 dest->spec = PyTuple_GET_ITEM(typeargs, 1);
288
289 return true;
290}
291
292static int
293parse_struct_item_spec(StructItemSpec* dest, PyObject* spec_tuple) {
294
295 // i'd like to use ParseArgs here, but it seems to be a bottleneck.
296 if (PyTuple_Size(spec_tuple) != 5) {
Nobuaki Sukegawa7b894692015-12-23 21:45:06 +0900297 PyErr_Format(PyExc_TypeError, "expecting 5 arguments for spec tuple but got %d", (int)PyTuple_Size(spec_tuple));
David Reiss382fc302007-08-25 18:01:30 +0000298 return false;
299 }
300
301 dest->tag = PyInt_AsLong(PyTuple_GET_ITEM(spec_tuple, 0));
302 if (INT_CONV_ERROR_OCCURRED(dest->tag)) {
303 return false;
304 }
305
306 dest->type = PyInt_AsLong(PyTuple_GET_ITEM(spec_tuple, 1));
307 if (INT_CONV_ERROR_OCCURRED(dest->type)) {
308 return false;
309 }
310
311 dest->attrname = PyTuple_GET_ITEM(spec_tuple, 2);
312 dest->typeargs = PyTuple_GET_ITEM(spec_tuple, 3);
313 dest->defval = PyTuple_GET_ITEM(spec_tuple, 4);
314 return true;
315}
316
317/* ====== END UTILITIES ====== */
318
319
320/* ====== BEGIN WRITING FUNCTIONS ====== */
321
322/* --- LOW-LEVEL WRITING FUNCTIONS --- */
323
324static void writeByte(PyObject* outbuf, int8_t val) {
325 int8_t net = val;
326 PycStringIO->cwrite(outbuf, (char*)&net, sizeof(int8_t));
327}
328
329static void writeI16(PyObject* outbuf, int16_t val) {
330 int16_t net = (int16_t)htons(val);
331 PycStringIO->cwrite(outbuf, (char*)&net, sizeof(int16_t));
332}
333
334static void writeI32(PyObject* outbuf, int32_t val) {
335 int32_t net = (int32_t)htonl(val);
336 PycStringIO->cwrite(outbuf, (char*)&net, sizeof(int32_t));
337}
338
339static void writeI64(PyObject* outbuf, int64_t val) {
340 int64_t net = (int64_t)htonll(val);
341 PycStringIO->cwrite(outbuf, (char*)&net, sizeof(int64_t));
342}
343
344static void writeDouble(PyObject* outbuf, double dub) {
345 // Unfortunately, bitwise_cast doesn't work in C. Bad C!
346 union {
347 double f;
348 int64_t t;
349 } transfer;
350 transfer.f = dub;
351 writeI64(outbuf, transfer.t);
352}
353
354
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +0100355/* --- MAIN RECURSIVE OUTPUT FUNCTION -- */
David Reiss382fc302007-08-25 18:01:30 +0000356
Nobuaki Sukegawa7b894692015-12-23 21:45:06 +0900357static bool
David Reiss382fc302007-08-25 18:01:30 +0000358output_val(PyObject* output, PyObject* value, TType type, PyObject* typeargs) {
359 /*
360 * Refcounting Strategy:
361 *
362 * We assume that elements of the thrift_spec tuple are not going to be
363 * mutated, so we don't ref count those at all. Other than that, we try to
364 * keep a reference to all the user-created objects while we work with them.
365 * output_val assumes that a reference is already held. The *caller* is
366 * responsible for handling references
367 */
368
369 switch (type) {
370
371 case T_BOOL: {
372 int v = PyObject_IsTrue(value);
373 if (v == -1) {
374 return false;
375 }
376
377 writeByte(output, (int8_t) v);
378 break;
379 }
380 case T_I08: {
381 int32_t val;
382
383 if (!parse_pyint(value, &val, INT8_MIN, INT8_MAX)) {
384 return false;
385 }
386
387 writeByte(output, (int8_t) val);
388 break;
389 }
390 case T_I16: {
391 int32_t val;
392
393 if (!parse_pyint(value, &val, INT16_MIN, INT16_MAX)) {
394 return false;
395 }
396
397 writeI16(output, (int16_t) val);
398 break;
399 }
400 case T_I32: {
401 int32_t val;
402
403 if (!parse_pyint(value, &val, INT32_MIN, INT32_MAX)) {
404 return false;
405 }
406
407 writeI32(output, val);
408 break;
409 }
410 case T_I64: {
411 int64_t nval = PyLong_AsLongLong(value);
412
413 if (INT_CONV_ERROR_OCCURRED(nval)) {
414 return false;
415 }
416
417 if (!CHECK_RANGE(nval, INT64_MIN, INT64_MAX)) {
418 PyErr_SetString(PyExc_OverflowError, "int out of range");
419 return false;
420 }
421
422 writeI64(output, nval);
423 break;
424 }
425
426 case T_DOUBLE: {
427 double nval = PyFloat_AsDouble(value);
428 if (nval == -1.0 && PyErr_Occurred()) {
429 return false;
430 }
431
432 writeDouble(output, nval);
433 break;
434 }
435
436 case T_STRING: {
Nobuaki Sukegawa4733db42016-01-05 02:50:57 +0900437 Py_ssize_t len = 0;
438 if (is_utf8(typeargs) && PyUnicode_Check(value))
439 value = PyUnicode_AsUTF8String(value);
440 len = PyString_Size(value);
David Reiss382fc302007-08-25 18:01:30 +0000441
442 if (!check_ssize_t_32(len)) {
443 return false;
444 }
445
446 writeI32(output, (int32_t) len);
447 PycStringIO->cwrite(output, PyString_AsString(value), (int32_t) len);
448 break;
449 }
450
451 case T_LIST:
452 case T_SET: {
453 Py_ssize_t len;
454 SetListTypeArgs parsedargs;
455 PyObject *item;
456 PyObject *iterator;
457
458 if (!parse_set_list_args(&parsedargs, typeargs)) {
459 return false;
460 }
461
462 len = PyObject_Length(value);
463
464 if (!check_ssize_t_32(len)) {
465 return false;
466 }
467
468 writeByte(output, parsedargs.element_type);
469 writeI32(output, (int32_t) len);
470
471 iterator = PyObject_GetIter(value);
472 if (iterator == NULL) {
473 return false;
474 }
475
476 while ((item = PyIter_Next(iterator))) {
477 if (!output_val(output, item, parsedargs.element_type, parsedargs.typeargs)) {
478 Py_DECREF(item);
479 Py_DECREF(iterator);
480 return false;
481 }
482 Py_DECREF(item);
483 }
484
485 Py_DECREF(iterator);
486
487 if (PyErr_Occurred()) {
488 return false;
489 }
490
491 break;
492 }
493
494 case T_MAP: {
495 PyObject *k, *v;
David Reiss58434e62008-10-07 21:08:10 +0000496 Py_ssize_t pos = 0;
David Reiss382fc302007-08-25 18:01:30 +0000497 Py_ssize_t len;
498
499 MapTypeArgs parsedargs;
500
501 len = PyDict_Size(value);
502 if (!check_ssize_t_32(len)) {
503 return false;
504 }
505
506 if (!parse_map_args(&parsedargs, typeargs)) {
507 return false;
508 }
509
510 writeByte(output, parsedargs.ktag);
511 writeByte(output, parsedargs.vtag);
512 writeI32(output, len);
513
514 // TODO(bmaurer): should support any mapping, not just dicts
515 while (PyDict_Next(value, &pos, &k, &v)) {
516 // TODO(dreiss): Think hard about whether these INCREFs actually
517 // turn any unsafe scenarios into safe scenarios.
518 Py_INCREF(k);
519 Py_INCREF(v);
520
521 if (!output_val(output, k, parsedargs.ktag, parsedargs.ktypeargs)
522 || !output_val(output, v, parsedargs.vtag, parsedargs.vtypeargs)) {
523 Py_DECREF(k);
524 Py_DECREF(v);
525 return false;
526 }
Kevin Clark127d01c2009-03-24 01:40:56 +0000527 Py_DECREF(k);
528 Py_DECREF(v);
David Reiss382fc302007-08-25 18:01:30 +0000529 }
530 break;
531 }
532
533 // TODO(dreiss): Consider breaking this out as a function
534 // the way we did for decode_struct.
535 case T_STRUCT: {
536 StructTypeArgs parsedargs;
537 Py_ssize_t nspec;
538 Py_ssize_t i;
539
540 if (!parse_struct_args(&parsedargs, typeargs)) {
541 return false;
542 }
543
544 nspec = PyTuple_Size(parsedargs.spec);
545
546 if (nspec == -1) {
547 return false;
548 }
549
550 for (i = 0; i < nspec; i++) {
551 StructItemSpec parsedspec;
552 PyObject* spec_tuple;
553 PyObject* instval = NULL;
554
555 spec_tuple = PyTuple_GET_ITEM(parsedargs.spec, i);
556 if (spec_tuple == Py_None) {
557 continue;
558 }
559
560 if (!parse_struct_item_spec (&parsedspec, spec_tuple)) {
561 return false;
562 }
563
564 instval = PyObject_GetAttr(value, parsedspec.attrname);
565
566 if (!instval) {
567 return false;
568 }
569
570 if (instval == Py_None) {
571 Py_DECREF(instval);
572 continue;
573 }
574
575 writeByte(output, (int8_t) parsedspec.type);
576 writeI16(output, parsedspec.tag);
577
578 if (!output_val(output, instval, parsedspec.type, parsedspec.typeargs)) {
579 Py_DECREF(instval);
580 return false;
581 }
582
583 Py_DECREF(instval);
584 }
585
586 writeByte(output, (int8_t)T_STOP);
587 break;
588 }
589
590 case T_STOP:
591 case T_VOID:
592 case T_UTF16:
593 case T_UTF8:
594 case T_U64:
595 default:
596 PyErr_SetString(PyExc_TypeError, "Unexpected TType");
597 return false;
598
599 }
600
601 return true;
602}
603
604
605/* --- TOP-LEVEL WRAPPER FOR OUTPUT -- */
606
607static PyObject *
608encode_binary(PyObject *self, PyObject *args) {
609 PyObject* enc_obj;
610 PyObject* type_args;
611 PyObject* buf;
612 PyObject* ret = NULL;
613
614 if (!PyArg_ParseTuple(args, "OO", &enc_obj, &type_args)) {
615 return NULL;
616 }
617
618 buf = PycStringIO->NewOutput(INIT_OUTBUF_SIZE);
619 if (output_val(buf, enc_obj, T_STRUCT, type_args)) {
620 ret = PycStringIO->cgetvalue(buf);
621 }
622
623 Py_DECREF(buf);
624 return ret;
625}
626
627/* ====== END WRITING FUNCTIONS ====== */
628
629
630/* ====== BEGIN READING FUNCTIONS ====== */
631
632/* --- LOW-LEVEL READING FUNCTIONS --- */
633
634static void
635free_decodebuf(DecodeBuffer* d) {
636 Py_XDECREF(d->stringiobuf);
637 Py_XDECREF(d->refill_callable);
638}
639
640static bool
641decode_buffer_from_obj(DecodeBuffer* dest, PyObject* obj) {
642 dest->stringiobuf = PyObject_GetAttr(obj, INTERN_STRING(cstringio_buf));
643 if (!dest->stringiobuf) {
644 return false;
645 }
646
647 if (!PycStringIO_InputCheck(dest->stringiobuf)) {
648 free_decodebuf(dest);
649 PyErr_SetString(PyExc_TypeError, "expecting stringio input");
650 return false;
651 }
652
653 dest->refill_callable = PyObject_GetAttr(obj, INTERN_STRING(cstringio_refill));
654
655 if(!dest->refill_callable) {
656 free_decodebuf(dest);
657 return false;
658 }
659
660 if (!PyCallable_Check(dest->refill_callable)) {
661 free_decodebuf(dest);
662 PyErr_SetString(PyExc_TypeError, "expecting callable");
663 return false;
664 }
665
666 return true;
667}
668
669static bool readBytes(DecodeBuffer* input, char** output, int len) {
670 int read;
671
672 // TODO(dreiss): Don't fear the malloc. Think about taking a copy of
673 // the partial read instead of forcing the transport
674 // to prepend it to its buffer.
675
676 read = PycStringIO->cread(input->stringiobuf, output, len);
677
678 if (read == len) {
679 return true;
680 } else if (read == -1) {
681 return false;
682 } else {
683 PyObject* newiobuf;
684
685 // using building functions as this is a rare codepath
686 newiobuf = PyObject_CallFunction(
David Reiss2c2e6d22007-09-05 01:14:09 +0000687 input->refill_callable, "s#i", *output, read, len, NULL);
David Reiss382fc302007-08-25 18:01:30 +0000688 if (newiobuf == NULL) {
689 return false;
690 }
691
692 // must do this *AFTER* the call so that we don't deref the io buffer
693 Py_CLEAR(input->stringiobuf);
694 input->stringiobuf = newiobuf;
695
696 read = PycStringIO->cread(input->stringiobuf, output, len);
697
698 if (read == len) {
699 return true;
700 } else if (read == -1) {
701 return false;
702 } else {
703 // TODO(dreiss): This could be a valid code path for big binary blobs.
704 PyErr_SetString(PyExc_TypeError,
705 "refill claimed to have refilled the buffer, but didn't!!");
706 return false;
707 }
708 }
709}
710
711static int8_t readByte(DecodeBuffer* input) {
712 char* buf;
713 if (!readBytes(input, &buf, sizeof(int8_t))) {
714 return -1;
715 }
716
717 return *(int8_t*) buf;
718}
719
720static int16_t readI16(DecodeBuffer* input) {
721 char* buf;
722 if (!readBytes(input, &buf, sizeof(int16_t))) {
723 return -1;
724 }
725
726 return (int16_t) ntohs(*(int16_t*) buf);
727}
728
729static int32_t readI32(DecodeBuffer* input) {
730 char* buf;
731 if (!readBytes(input, &buf, sizeof(int32_t))) {
732 return -1;
733 }
734 return (int32_t) ntohl(*(int32_t*) buf);
735}
736
737
738static int64_t readI64(DecodeBuffer* input) {
739 char* buf;
740 if (!readBytes(input, &buf, sizeof(int64_t))) {
741 return -1;
742 }
743
744 return (int64_t) ntohll(*(int64_t*) buf);
745}
746
747static double readDouble(DecodeBuffer* input) {
748 union {
749 int64_t f;
750 double t;
751 } transfer;
752
753 transfer.f = readI64(input);
754 if (transfer.f == -1) {
755 return -1;
756 }
757 return transfer.t;
758}
759
760static bool
761checkTypeByte(DecodeBuffer* input, TType expected) {
762 TType got = readByte(input);
Mark Slee53d9c0c2007-11-26 21:15:40 +0000763 if (INT_CONV_ERROR_OCCURRED(got)) {
764 return false;
765 }
David Reiss382fc302007-08-25 18:01:30 +0000766
767 if (expected != got) {
768 PyErr_SetString(PyExc_TypeError, "got wrong ttype while reading field");
769 return false;
770 }
771 return true;
772}
773
774static bool
775skip(DecodeBuffer* input, TType type) {
776#define SKIPBYTES(n) \
777 do { \
778 if (!readBytes(input, &dummy_buf, (n))) { \
779 return false; \
780 } \
781 } while(0)
782
783 char* dummy_buf;
784
785 switch (type) {
786
787 case T_BOOL:
788 case T_I08: SKIPBYTES(1); break;
789 case T_I16: SKIPBYTES(2); break;
790 case T_I32: SKIPBYTES(4); break;
791 case T_I64:
792 case T_DOUBLE: SKIPBYTES(8); break;
793
794 case T_STRING: {
795 // TODO(dreiss): Find out if these check_ssize_t32s are really necessary.
796 int len = readI32(input);
797 if (!check_ssize_t_32(len)) {
798 return false;
799 }
800 SKIPBYTES(len);
801 break;
802 }
803
804 case T_LIST:
805 case T_SET: {
806 TType etype;
807 int len, i;
808
809 etype = readByte(input);
810 if (etype == -1) {
811 return false;
812 }
813
814 len = readI32(input);
815 if (!check_ssize_t_32(len)) {
816 return false;
817 }
818
819 for (i = 0; i < len; i++) {
820 if (!skip(input, etype)) {
821 return false;
822 }
823 }
824 break;
825 }
826
827 case T_MAP: {
828 TType ktype, vtype;
829 int len, i;
830
831 ktype = readByte(input);
832 if (ktype == -1) {
833 return false;
834 }
835
836 vtype = readByte(input);
837 if (vtype == -1) {
838 return false;
839 }
840
841 len = readI32(input);
842 if (!check_ssize_t_32(len)) {
843 return false;
844 }
845
846 for (i = 0; i < len; i++) {
847 if (!(skip(input, ktype) && skip(input, vtype))) {
848 return false;
849 }
850 }
851 break;
852 }
853
854 case T_STRUCT: {
855 while (true) {
856 TType type;
857
858 type = readByte(input);
859 if (type == -1) {
860 return false;
861 }
862
863 if (type == T_STOP)
864 break;
865
866 SKIPBYTES(2); // tag
867 if (!skip(input, type)) {
868 return false;
869 }
870 }
871 break;
872 }
873
874 case T_STOP:
875 case T_VOID:
876 case T_UTF16:
877 case T_UTF8:
878 case T_U64:
879 default:
880 PyErr_SetString(PyExc_TypeError, "Unexpected TType");
881 return false;
882
883 }
884
David Reissbc444b02008-02-14 20:20:08 +0000885 return true;
David Reiss382fc302007-08-25 18:01:30 +0000886
887#undef SKIPBYTES
888}
889
890
891/* --- HELPER FUNCTION FOR DECODE_VAL --- */
892
893static PyObject*
894decode_val(DecodeBuffer* input, TType type, PyObject* typeargs);
895
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900896static PyObject*
897decode_struct(DecodeBuffer* input, PyObject* output, PyObject* klass, PyObject* spec_seq) {
David Reiss382fc302007-08-25 18:01:30 +0000898 int spec_seq_len = PyTuple_Size(spec_seq);
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900899 bool immutable = output == Py_None;
900 PyObject* kwargs = NULL;
David Reiss382fc302007-08-25 18:01:30 +0000901 if (spec_seq_len == -1) {
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900902 return NULL;
903 }
904
905 if (immutable) {
906 kwargs = PyDict_New();
907 if (!kwargs) {
908 PyErr_SetString(PyExc_TypeError, "failed to prepare kwargument storage");
909 return NULL;
910 }
David Reiss382fc302007-08-25 18:01:30 +0000911 }
912
913 while (true) {
914 TType type;
915 int16_t tag;
916 PyObject* item_spec;
917 PyObject* fieldval = NULL;
918 StructItemSpec parsedspec;
919
920 type = readByte(input);
Mark Slee53d9c0c2007-11-26 21:15:40 +0000921 if (type == -1) {
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900922 goto error;
Mark Slee53d9c0c2007-11-26 21:15:40 +0000923 }
David Reiss382fc302007-08-25 18:01:30 +0000924 if (type == T_STOP) {
925 break;
926 }
927 tag = readI16(input);
Mark Slee53d9c0c2007-11-26 21:15:40 +0000928 if (INT_CONV_ERROR_OCCURRED(tag)) {
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900929 goto error;
Mark Slee53d9c0c2007-11-26 21:15:40 +0000930 }
David Reiss382fc302007-08-25 18:01:30 +0000931 if (tag >= 0 && tag < spec_seq_len) {
932 item_spec = PyTuple_GET_ITEM(spec_seq, tag);
933 } else {
934 item_spec = Py_None;
935 }
936
937 if (item_spec == Py_None) {
938 if (!skip(input, type)) {
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900939 goto error;
David Reissbc444b02008-02-14 20:20:08 +0000940 } else {
941 continue;
David Reiss382fc302007-08-25 18:01:30 +0000942 }
943 }
944
945 if (!parse_struct_item_spec(&parsedspec, item_spec)) {
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900946 goto error;
David Reiss382fc302007-08-25 18:01:30 +0000947 }
948 if (parsedspec.type != type) {
David Reissa528f542009-03-24 22:48:40 +0000949 if (!skip(input, type)) {
950 PyErr_SetString(PyExc_TypeError, "struct field had wrong type while reading and can't be skipped");
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900951 goto error;
David Reissa528f542009-03-24 22:48:40 +0000952 } else {
953 continue;
954 }
David Reiss382fc302007-08-25 18:01:30 +0000955 }
956
957 fieldval = decode_val(input, parsedspec.type, parsedspec.typeargs);
958 if (fieldval == NULL) {
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900959 goto error;
David Reiss382fc302007-08-25 18:01:30 +0000960 }
961
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900962 if ((immutable && PyDict_SetItem(kwargs, parsedspec.attrname, fieldval) == -1)
963 || (!immutable && PyObject_SetAttr(output, parsedspec.attrname, fieldval) == -1)) {
David Reiss382fc302007-08-25 18:01:30 +0000964 Py_DECREF(fieldval);
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900965 goto error;
David Reiss382fc302007-08-25 18:01:30 +0000966 }
967 Py_DECREF(fieldval);
968 }
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +0900969 if (immutable) {
970 PyObject* args = PyTuple_New(0);
971 PyObject* ret = NULL;
972 if (!args) {
973 PyErr_SetString(PyExc_TypeError, "failed to prepare argument storage");
974 goto error;
975 }
976 ret = PyObject_Call(klass, args, kwargs);
977 Py_DECREF(kwargs);
978 Py_DECREF(args);
979 return ret;
980 }
981 Py_INCREF(output);
982 return output;
983
984 error:
985 Py_XDECREF(kwargs);
986 return NULL;
David Reiss382fc302007-08-25 18:01:30 +0000987}
988
989
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +0100990/* --- MAIN RECURSIVE INPUT FUNCTION --- */
David Reiss382fc302007-08-25 18:01:30 +0000991
992// Returns a new reference.
993static PyObject*
994decode_val(DecodeBuffer* input, TType type, PyObject* typeargs) {
995 switch (type) {
996
997 case T_BOOL: {
998 int8_t v = readByte(input);
999 if (INT_CONV_ERROR_OCCURRED(v)) {
1000 return NULL;
1001 }
1002
1003 switch (v) {
1004 case 0: Py_RETURN_FALSE;
1005 case 1: Py_RETURN_TRUE;
1006 // Don't laugh. This is a potentially serious issue.
1007 default: PyErr_SetString(PyExc_TypeError, "boolean out of range"); return NULL;
1008 }
1009 break;
1010 }
1011 case T_I08: {
1012 int8_t v = readByte(input);
1013 if (INT_CONV_ERROR_OCCURRED(v)) {
1014 return NULL;
1015 }
1016
1017 return PyInt_FromLong(v);
1018 }
1019 case T_I16: {
1020 int16_t v = readI16(input);
1021 if (INT_CONV_ERROR_OCCURRED(v)) {
1022 return NULL;
1023 }
1024 return PyInt_FromLong(v);
1025 }
1026 case T_I32: {
1027 int32_t v = readI32(input);
1028 if (INT_CONV_ERROR_OCCURRED(v)) {
1029 return NULL;
1030 }
1031 return PyInt_FromLong(v);
1032 }
1033
1034 case T_I64: {
1035 int64_t v = readI64(input);
1036 if (INT_CONV_ERROR_OCCURRED(v)) {
1037 return NULL;
1038 }
1039 // TODO(dreiss): Find out if we can take this fastpath always when
1040 // sizeof(long) == sizeof(long long).
1041 if (CHECK_RANGE(v, LONG_MIN, LONG_MAX)) {
1042 return PyInt_FromLong((long) v);
1043 }
1044
1045 return PyLong_FromLongLong(v);
1046 }
1047
1048 case T_DOUBLE: {
1049 double v = readDouble(input);
1050 if (v == -1.0 && PyErr_Occurred()) {
1051 return false;
1052 }
1053 return PyFloat_FromDouble(v);
1054 }
1055
1056 case T_STRING: {
1057 Py_ssize_t len = readI32(input);
1058 char* buf;
1059 if (!readBytes(input, &buf, len)) {
1060 return NULL;
1061 }
1062
Nobuaki Sukegawa4733db42016-01-05 02:50:57 +09001063 if (is_utf8(typeargs))
1064 return PyUnicode_DecodeUTF8(buf, len, 0);
1065 else
1066 return PyString_FromStringAndSize(buf, len);
David Reiss382fc302007-08-25 18:01:30 +00001067 }
1068
1069 case T_LIST:
1070 case T_SET: {
1071 SetListTypeArgs parsedargs;
1072 int32_t len;
1073 PyObject* ret = NULL;
1074 int i;
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001075 bool use_tuple = false;
David Reiss382fc302007-08-25 18:01:30 +00001076
1077 if (!parse_set_list_args(&parsedargs, typeargs)) {
1078 return NULL;
1079 }
1080
1081 if (!checkTypeByte(input, parsedargs.element_type)) {
1082 return NULL;
1083 }
1084
1085 len = readI32(input);
Roger Meier7daf00c2015-06-03 11:45:35 +02001086 if (!check_list_length(len)) {
David Reiss382fc302007-08-25 18:01:30 +00001087 return NULL;
1088 }
1089
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001090 use_tuple = type == T_LIST && parsedargs.immutable;
1091 ret = use_tuple ? PyTuple_New(len) : PyList_New(len);
David Reiss382fc302007-08-25 18:01:30 +00001092 if (!ret) {
1093 return NULL;
1094 }
1095
1096 for (i = 0; i < len; i++) {
1097 PyObject* item = decode_val(input, parsedargs.element_type, parsedargs.typeargs);
1098 if (!item) {
1099 Py_DECREF(ret);
1100 return NULL;
1101 }
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001102 if (use_tuple) {
1103 PyTuple_SET_ITEM(ret, i, item);
1104 } else {
1105 PyList_SET_ITEM(ret, i, item);
1106 }
David Reiss382fc302007-08-25 18:01:30 +00001107 }
1108
1109 // TODO(dreiss): Consider biting the bullet and making two separate cases
1110 // for list and set, avoiding this post facto conversion.
1111 if (type == T_SET) {
1112 PyObject* setret;
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001113 setret = parsedargs.immutable ? PyFrozenSet_New(ret) : PySet_New(ret);
David Reiss382fc302007-08-25 18:01:30 +00001114 Py_DECREF(ret);
1115 return setret;
1116 }
1117 return ret;
1118 }
1119
1120 case T_MAP: {
1121 int32_t len;
1122 int i;
1123 MapTypeArgs parsedargs;
1124 PyObject* ret = NULL;
1125
1126 if (!parse_map_args(&parsedargs, typeargs)) {
1127 return NULL;
1128 }
1129
1130 if (!checkTypeByte(input, parsedargs.ktag)) {
1131 return NULL;
1132 }
1133 if (!checkTypeByte(input, parsedargs.vtag)) {
1134 return NULL;
1135 }
1136
1137 len = readI32(input);
1138 if (!check_ssize_t_32(len)) {
1139 return false;
1140 }
1141
1142 ret = PyDict_New();
1143 if (!ret) {
1144 goto error;
1145 }
1146
1147 for (i = 0; i < len; i++) {
1148 PyObject* k = NULL;
1149 PyObject* v = NULL;
1150 k = decode_val(input, parsedargs.ktag, parsedargs.ktypeargs);
1151 if (k == NULL) {
1152 goto loop_error;
1153 }
1154 v = decode_val(input, parsedargs.vtag, parsedargs.vtypeargs);
1155 if (v == NULL) {
1156 goto loop_error;
1157 }
1158 if (PyDict_SetItem(ret, k, v) == -1) {
1159 goto loop_error;
1160 }
1161
1162 Py_DECREF(k);
1163 Py_DECREF(v);
1164 continue;
1165
1166 // Yuck! Destructors, anyone?
1167 loop_error:
1168 Py_XDECREF(k);
1169 Py_XDECREF(v);
1170 goto error;
1171 }
1172
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001173 if (parsedargs.immutable) {
1174 PyObject* thrift = PyImport_ImportModule("thrift.Thrift");
1175 PyObject* cls = NULL;
1176 PyObject* arg = NULL;
1177 if (!thrift) {
1178 goto error;
1179 }
1180 cls = PyObject_GetAttrString(thrift, "TFrozenDict");
1181 if (!cls) {
1182 goto error;
1183 }
1184 arg = PyTuple_New(1);
1185 PyTuple_SET_ITEM(arg, 0, ret);
1186 return PyObject_CallObject(cls, arg);
1187 }
1188
David Reiss382fc302007-08-25 18:01:30 +00001189 return ret;
1190
1191 error:
1192 Py_XDECREF(ret);
1193 return NULL;
1194 }
1195
1196 case T_STRUCT: {
1197 StructTypeArgs parsedargs;
1198 if (!parse_struct_args(&parsedargs, typeargs)) {
1199 return NULL;
1200 }
1201
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001202 return decode_struct(input, Py_None, parsedargs.klass, parsedargs.spec);
David Reiss382fc302007-08-25 18:01:30 +00001203 }
1204
1205 case T_STOP:
1206 case T_VOID:
1207 case T_UTF16:
1208 case T_UTF8:
1209 case T_U64:
1210 default:
1211 PyErr_SetString(PyExc_TypeError, "Unexpected TType");
1212 return NULL;
1213 }
1214}
1215
1216
1217/* --- TOP-LEVEL WRAPPER FOR INPUT -- */
1218
1219static PyObject*
1220decode_binary(PyObject *self, PyObject *args) {
1221 PyObject* output_obj = NULL;
1222 PyObject* transport = NULL;
1223 PyObject* typeargs = NULL;
1224 StructTypeArgs parsedargs;
Roger Meierc3f033f2011-09-13 13:54:05 +00001225 DecodeBuffer input = {0, 0};
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001226 PyObject* ret = NULL;
Roger Meier7daf00c2015-06-03 11:45:35 +02001227
David Reiss382fc302007-08-25 18:01:30 +00001228 if (!PyArg_ParseTuple(args, "OOO", &output_obj, &transport, &typeargs)) {
1229 return NULL;
1230 }
1231
1232 if (!parse_struct_args(&parsedargs, typeargs)) {
1233 return NULL;
1234 }
1235
1236 if (!decode_buffer_from_obj(&input, transport)) {
1237 return NULL;
1238 }
1239
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001240 ret = decode_struct(&input, output_obj, parsedargs.klass, parsedargs.spec);
David Reiss382fc302007-08-25 18:01:30 +00001241 free_decodebuf(&input);
Nobuaki Sukegawae841b3d2015-11-17 11:01:17 +09001242 return ret;
David Reiss382fc302007-08-25 18:01:30 +00001243}
1244
1245/* ====== END READING FUNCTIONS ====== */
1246
1247
1248/* -- PYTHON MODULE SETUP STUFF --- */
1249
1250static PyMethodDef ThriftFastBinaryMethods[] = {
1251
1252 {"encode_binary", encode_binary, METH_VARARGS, ""},
1253 {"decode_binary", decode_binary, METH_VARARGS, ""},
1254
1255 {NULL, NULL, 0, NULL} /* Sentinel */
1256};
1257
1258PyMODINIT_FUNC
1259initfastbinary(void) {
1260#define INIT_INTERN_STRING(value) \
1261 do { \
1262 INTERN_STRING(value) = PyString_InternFromString(#value); \
1263 if(!INTERN_STRING(value)) return; \
1264 } while(0)
1265
1266 INIT_INTERN_STRING(cstringio_buf);
1267 INIT_INTERN_STRING(cstringio_refill);
1268#undef INIT_INTERN_STRING
1269
1270 PycString_IMPORT;
1271 if (PycStringIO == NULL) return;
1272
1273 (void) Py_InitModule("thrift.protocol.fastbinary", ThriftFastBinaryMethods);
1274}