-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
_cbsonmodule.c
3296 lines (3024 loc) · 106 KB
/
_cbsonmodule.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2009-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file contains C implementations of some of the functions
* needed by the bson module. If possible, these implementations
* should be used to speed up BSON encoding and decoding.
*/
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "datetime.h"
#include "buffer.h"
#include "time64.h"
#define _CBSON_MODULE
#include "_cbsonmodule.h"
/* New module state and initialization code.
* See the module-initialization-and-state
* section in the following doc:
* http://docs.python.org/release/3.1.3/howto/cporting.html
* which references the following pep:
* http://www.python.org/dev/peps/pep-3121/
* */
struct module_state {
PyObject* Binary;
PyObject* Code;
PyObject* ObjectId;
PyObject* DBRef;
PyObject* Regex;
PyObject* UUID;
PyObject* Timestamp;
PyObject* MinKey;
PyObject* MaxKey;
PyObject* UTC;
PyTypeObject* REType;
PyObject* BSONInt64;
PyObject* Decimal128;
PyObject* Mapping;
PyObject* DatetimeMS;
PyObject* _min_datetime_ms;
PyObject* _max_datetime_ms;
PyObject* _type_marker_str;
PyObject* _flags_str;
PyObject* _pattern_str;
PyObject* _encoder_map_str;
PyObject* _decoder_map_str;
PyObject* _fallback_encoder_str;
PyObject* _raw_str;
PyObject* _subtype_str;
PyObject* _binary_str;
PyObject* _scope_str;
PyObject* _inc_str;
PyObject* _time_str;
PyObject* _bid_str;
PyObject* _replace_str;
PyObject* _astimezone_str;
PyObject* _id_str;
PyObject* _dollar_ref_str;
PyObject* _dollar_id_str;
PyObject* _dollar_db_str;
PyObject* _tzinfo_str;
PyObject* _as_doc_str;
PyObject* _utcoffset_str;
PyObject* _from_uuid_str;
PyObject* _as_uuid_str;
PyObject* _from_bid_str;
};
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
/* Maximum number of regex flags */
#define FLAGS_SIZE 7
/* Default UUID representation type code. */
#define PYTHON_LEGACY 3
/* Other UUID representations. */
#define STANDARD 4
#define JAVA_LEGACY 5
#define CSHARP_LEGACY 6
#define UNSPECIFIED 0
#define BSON_MAX_SIZE 2147483647
/* The smallest possible BSON document, i.e. "{}" */
#define BSON_MIN_SIZE 5
/* Datetime codec options */
#define DATETIME 1
#define DATETIME_CLAMP 2
#define DATETIME_MS 3
#define DATETIME_AUTO 4
/* Converts integer to its string representation in decimal notation. */
extern int cbson_long_long_to_str(long long num, char* str, size_t size) {
// Buffer should fit 64-bit signed integer
if (size < 21) {
PyErr_Format(
PyExc_RuntimeError,
"Buffer too small to hold long long: %d < 21", size);
return -1;
}
int index = 0;
int sign = 1;
// Convert to unsigned to handle -LLONG_MIN overflow
unsigned long long absNum;
// Handle the case of 0
if (num == 0) {
str[index++] = '0';
str[index] = '\0';
return 0;
}
// Handle negative numbers
if (num < 0) {
sign = -1;
absNum = 0ULL - (unsigned long long)num;
} else {
absNum = (unsigned long long)num;
}
// Convert the number to string
unsigned long long digit;
while (absNum > 0) {
digit = absNum % 10ULL;
str[index++] = (char)digit + '0'; // Convert digit to character
absNum /= 10;
}
// Add minus sign if negative
if (sign == -1) {
str[index++] = '-';
}
str[index] = '\0'; // Null terminator
// Reverse the string
int start = 0;
int end = index - 1;
while (start < end) {
char temp = str[start];
str[start++] = str[end];
str[end--] = temp;
}
return 0;
}
static PyObject* _test_long_long_to_str(PyObject* self, PyObject* args) {
// Test extreme values
Py_ssize_t maxNum = PY_SSIZE_T_MAX;
Py_ssize_t minNum = PY_SSIZE_T_MIN;
Py_ssize_t num;
char str_1[BUF_SIZE];
char str_2[BUF_SIZE];
int res = LL2STR(str_1, (long long)minNum);
if (res == -1) {
return NULL;
}
INT2STRING(str_2, (long long)minNum);
if (strcmp(str_1, str_2) != 0) {
PyErr_Format(
PyExc_RuntimeError,
"LL2STR != INT2STRING: %s != %s", str_1, str_2);
return NULL;
}
LL2STR(str_1, (long long)maxNum);
INT2STRING(str_2, (long long)maxNum);
if (strcmp(str_1, str_2) != 0) {
PyErr_Format(
PyExc_RuntimeError,
"LL2STR != INT2STRING: %s != %s", str_1, str_2);
return NULL;
}
// Test common values
for (num = 0; num < 10000; num++) {
char str_1[BUF_SIZE];
char str_2[BUF_SIZE];
LL2STR(str_1, (long long)num);
INT2STRING(str_2, (long long)num);
if (strcmp(str_1, str_2) != 0) {
PyErr_Format(
PyExc_RuntimeError,
"LL2STR != INT2STRING: %s != %s", str_1, str_2);
return NULL;
}
}
return args;
}
/* Get an error class from the bson.errors module.
*
* Returns a new ref */
static PyObject* _error(char* name) {
PyObject* error;
PyObject* errors = PyImport_ImportModule("bson.errors");
if (!errors) {
return NULL;
}
error = PyObject_GetAttrString(errors, name);
Py_DECREF(errors);
return error;
}
/* Safely downcast from Py_ssize_t to int, setting an
* exception and returning -1 on error. */
static int
_downcast_and_check(Py_ssize_t size, uint8_t extra) {
if (size > BSON_MAX_SIZE || ((BSON_MAX_SIZE - extra) < size)) {
PyObject* InvalidStringData = _error("InvalidStringData");
if (InvalidStringData) {
PyErr_SetString(InvalidStringData,
"String length must be <= 2147483647");
Py_DECREF(InvalidStringData);
}
return -1;
}
return (int)size + extra;
}
static PyObject* elements_to_dict(PyObject* self, const char* string,
unsigned max,
const codec_options_t* options);
static int _write_element_to_buffer(PyObject* self, buffer_t buffer,
int type_byte, PyObject* value,
unsigned char check_keys,
const codec_options_t* options,
unsigned char in_custom_call,
unsigned char in_fallback_call);
/* Write a RawBSONDocument to the buffer.
* Returns the number of bytes written or 0 on failure.
*/
static int write_raw_doc(buffer_t buffer, PyObject* raw, PyObject* _raw);
/* Date stuff */
static PyObject* datetime_from_millis(long long millis) {
/* To encode a datetime instance like datetime(9999, 12, 31, 23, 59, 59, 999999)
* we follow these steps:
* 1. Calculate a timestamp in seconds: 253402300799
* 2. Multiply that by 1000: 253402300799000
* 3. Add in microseconds divided by 1000 253402300799999
*
* (Note: BSON doesn't support microsecond accuracy, hence the rounding.)
*
* To decode we could do:
* 1. Get seconds: timestamp / 1000: 253402300799
* 2. Get micros: (timestamp % 1000) * 1000: 999000
* Resulting in datetime(9999, 12, 31, 23, 59, 59, 999000) -- the expected result
*
* Now what if the we encode (1, 1, 1, 1, 1, 1, 111111)?
* 1. and 2. gives: -62135593139000
* 3. Gives us: -62135593138889
*
* Now decode:
* 1. Gives us: -62135593138
* 2. Gives us: -889000
* Resulting in datetime(1, 1, 1, 1, 1, 2, 15888216) -- an invalid result
*
* If instead to decode we do:
* diff = ((millis % 1000) + 1000) % 1000: 111
* seconds = (millis - diff) / 1000: -62135593139
* micros = diff * 1000 111000
* Resulting in datetime(1, 1, 1, 1, 1, 1, 111000) -- the expected result
*/
PyObject* datetime;
int diff = (int)(((millis % 1000) + 1000) % 1000);
int microseconds = diff * 1000;
Time64_T seconds = (millis - diff) / 1000;
struct TM timeinfo;
cbson_gmtime64_r(&seconds, &timeinfo);
datetime = PyDateTime_FromDateAndTime(timeinfo.tm_year + 1900,
timeinfo.tm_mon + 1,
timeinfo.tm_mday,
timeinfo.tm_hour,
timeinfo.tm_min,
timeinfo.tm_sec,
microseconds);
if(!datetime) {
PyObject *etype, *evalue, *etrace;
/*
* Calling _error clears the error state, so fetch it first.
*/
PyErr_Fetch(&etype, &evalue, &etrace);
/* Only add addition error message on ValueError exceptions. */
if (PyErr_GivenExceptionMatches(etype, PyExc_ValueError)) {
if (evalue) {
PyObject* err_msg = PyObject_Str(evalue);
if (err_msg) {
PyObject* appendage = PyUnicode_FromString(" (Consider Using CodecOptions(datetime_conversion=DATETIME_AUTO) or MongoClient(datetime_conversion='DATETIME_AUTO')). See: https://pymongo.readthedocs.io/en/stable/examples/datetimes.html#handling-out-of-range-datetimes");
if (appendage) {
PyObject* msg = PyUnicode_Concat(err_msg, appendage);
if (msg) {
Py_DECREF(evalue);
evalue = msg;
}
}
Py_XDECREF(appendage);
}
Py_XDECREF(err_msg);
}
PyErr_NormalizeException(&etype, &evalue, &etrace);
}
/* Steals references to args. */
PyErr_Restore(etype, evalue, etrace);
}
return datetime;
}
static long long millis_from_datetime(PyObject* datetime) {
struct TM timeinfo;
long long millis;
timeinfo.tm_year = PyDateTime_GET_YEAR(datetime) - 1900;
timeinfo.tm_mon = PyDateTime_GET_MONTH(datetime) - 1;
timeinfo.tm_mday = PyDateTime_GET_DAY(datetime);
timeinfo.tm_hour = PyDateTime_DATE_GET_HOUR(datetime);
timeinfo.tm_min = PyDateTime_DATE_GET_MINUTE(datetime);
timeinfo.tm_sec = PyDateTime_DATE_GET_SECOND(datetime);
millis = cbson_timegm64(&timeinfo) * 1000;
millis += PyDateTime_DATE_GET_MICROSECOND(datetime) / 1000;
return millis;
}
/* Extended-range datetime, returns a DatetimeMS object with millis */
static PyObject* datetime_ms_from_millis(PyObject* self, long long millis){
// Allocate a new DatetimeMS object.
struct module_state *state = GETSTATE(self);
PyObject* dt;
PyObject* ll_millis;
if (!(ll_millis = PyLong_FromLongLong(millis))){
return NULL;
}
dt = PyObject_CallFunctionObjArgs(state->DatetimeMS, ll_millis, NULL);
Py_DECREF(ll_millis);
return dt;
}
/* Extended-range datetime, takes a DatetimeMS object and extracts the long long value. */
static int millis_from_datetime_ms(PyObject* dt, long long* out){
PyObject* ll_millis;
long long millis;
if (!(ll_millis = PyNumber_Long(dt))){
return 0;
}
millis = PyLong_AsLongLong(ll_millis);
Py_DECREF(ll_millis);
if (millis == -1 && PyErr_Occurred()) { /* Overflow */
PyErr_SetString(PyExc_OverflowError,
"MongoDB datetimes can only handle up to 8-byte ints");
return 0;
}
*out = millis;
return 1;
}
/* Just make this compatible w/ the old API. */
int buffer_write_bytes(buffer_t buffer, const char* data, int size) {
if (pymongo_buffer_write(buffer, data, size)) {
return 0;
}
return 1;
}
int buffer_write_double(buffer_t buffer, double data) {
double data_le = BSON_DOUBLE_TO_LE(data);
return buffer_write_bytes(buffer, (const char*)&data_le, 8);
}
int buffer_write_int32(buffer_t buffer, int32_t data) {
uint32_t data_le = BSON_UINT32_TO_LE(data);
return buffer_write_bytes(buffer, (const char*)&data_le, 4);
}
int buffer_write_int64(buffer_t buffer, int64_t data) {
uint64_t data_le = BSON_UINT64_TO_LE(data);
return buffer_write_bytes(buffer, (const char*)&data_le, 8);
}
void buffer_write_int32_at_position(buffer_t buffer,
int position,
int32_t data) {
uint32_t data_le = BSON_UINT32_TO_LE(data);
memcpy(pymongo_buffer_get_buffer(buffer) + position, &data_le, 4);
}
static int write_unicode(buffer_t buffer, PyObject* py_string) {
int size;
const char* data;
PyObject* encoded = PyUnicode_AsUTF8String(py_string);
if (!encoded) {
return 0;
}
data = PyBytes_AS_STRING(encoded);
if (!data)
goto unicodefail;
if ((size = _downcast_and_check(PyBytes_GET_SIZE(encoded), 1)) == -1)
goto unicodefail;
if (!buffer_write_int32(buffer, (int32_t)size))
goto unicodefail;
if (!buffer_write_bytes(buffer, data, size))
goto unicodefail;
Py_DECREF(encoded);
return 1;
unicodefail:
Py_DECREF(encoded);
return 0;
}
/* returns 0 on failure */
static int write_string(buffer_t buffer, PyObject* py_string) {
int size;
const char* data;
if (PyUnicode_Check(py_string)){
return write_unicode(buffer, py_string);
}
data = PyBytes_AsString(py_string);
if (!data) {
return 0;
}
if ((size = _downcast_and_check(PyBytes_Size(py_string), 1)) == -1)
return 0;
if (!buffer_write_int32(buffer, (int32_t)size)) {
return 0;
}
if (!buffer_write_bytes(buffer, data, size)) {
return 0;
}
return 1;
}
/*
* Are we in the main interpreter or a sub-interpreter?
* Useful for deciding if we can use cached pure python
* types in mod_wsgi.
*/
static int
_in_main_interpreter(void) {
static PyInterpreterState* main_interpreter = NULL;
PyInterpreterState* interpreter;
if (main_interpreter == NULL) {
interpreter = PyInterpreterState_Head();
while (PyInterpreterState_Next(interpreter))
interpreter = PyInterpreterState_Next(interpreter);
main_interpreter = interpreter;
}
return (main_interpreter == PyThreadState_Get()->interp);
}
/*
* Get a reference to a pure python type. If we are in the
* main interpreter return the cached object, otherwise import
* the object we need and return it instead.
*/
static PyObject*
_get_object(PyObject* object, char* module_name, char* object_name) {
if (_in_main_interpreter()) {
Py_XINCREF(object);
return object;
} else {
PyObject* imported = NULL;
PyObject* module = PyImport_ImportModule(module_name);
if (!module)
return NULL;
imported = PyObject_GetAttrString(module, object_name);
Py_DECREF(module);
return imported;
}
}
/* Load a Python object to cache.
*
* Returns non-zero on failure. */
static int _load_object(PyObject** object, char* module_name, char* object_name) {
PyObject* module;
module = PyImport_ImportModule(module_name);
if (!module) {
return 1;
}
*object = PyObject_GetAttrString(module, object_name);
Py_DECREF(module);
return (*object) ? 0 : 2;
}
/* Load all Python objects to cache.
*
* Returns non-zero on failure. */
static int _load_python_objects(PyObject* module) {
PyObject* empty_string = NULL;
PyObject* re_compile = NULL;
PyObject* compiled = NULL;
struct module_state *state = GETSTATE(module);
/* Cache commonly used attribute names to improve performance. */
if (!((state->_type_marker_str = PyUnicode_FromString("_type_marker")) &&
(state->_flags_str = PyUnicode_FromString("flags")) &&
(state->_pattern_str = PyUnicode_FromString("pattern")) &&
(state->_encoder_map_str = PyUnicode_FromString("_encoder_map")) &&
(state->_decoder_map_str = PyUnicode_FromString("_decoder_map")) &&
(state->_fallback_encoder_str = PyUnicode_FromString("_fallback_encoder")) &&
(state->_raw_str = PyUnicode_FromString("raw")) &&
(state->_subtype_str = PyUnicode_FromString("subtype")) &&
(state->_binary_str = PyUnicode_FromString("binary")) &&
(state->_scope_str = PyUnicode_FromString("scope")) &&
(state->_inc_str = PyUnicode_FromString("inc")) &&
(state->_time_str = PyUnicode_FromString("time")) &&
(state->_bid_str = PyUnicode_FromString("bid")) &&
(state->_replace_str = PyUnicode_FromString("replace")) &&
(state->_astimezone_str = PyUnicode_FromString("astimezone")) &&
(state->_id_str = PyUnicode_FromString("_id")) &&
(state->_dollar_ref_str = PyUnicode_FromString("$ref")) &&
(state->_dollar_id_str = PyUnicode_FromString("$id")) &&
(state->_dollar_db_str = PyUnicode_FromString("$db")) &&
(state->_tzinfo_str = PyUnicode_FromString("tzinfo")) &&
(state->_as_doc_str = PyUnicode_FromString("as_doc")) &&
(state->_utcoffset_str = PyUnicode_FromString("utcoffset")) &&
(state->_from_uuid_str = PyUnicode_FromString("from_uuid")) &&
(state->_as_uuid_str = PyUnicode_FromString("as_uuid")) &&
(state->_from_bid_str = PyUnicode_FromString("from_bid")))) {
return 1;
}
if (_load_object(&state->Binary, "bson.binary", "Binary") ||
_load_object(&state->Code, "bson.code", "Code") ||
_load_object(&state->ObjectId, "bson.objectid", "ObjectId") ||
_load_object(&state->DBRef, "bson.dbref", "DBRef") ||
_load_object(&state->Timestamp, "bson.timestamp", "Timestamp") ||
_load_object(&state->MinKey, "bson.min_key", "MinKey") ||
_load_object(&state->MaxKey, "bson.max_key", "MaxKey") ||
_load_object(&state->UTC, "bson.tz_util", "utc") ||
_load_object(&state->Regex, "bson.regex", "Regex") ||
_load_object(&state->BSONInt64, "bson.int64", "Int64") ||
_load_object(&state->Decimal128, "bson.decimal128", "Decimal128") ||
_load_object(&state->UUID, "uuid", "UUID") ||
_load_object(&state->Mapping, "collections.abc", "Mapping") ||
_load_object(&state->DatetimeMS, "bson.datetime_ms", "DatetimeMS") ||
_load_object(&state->_min_datetime_ms, "bson.datetime_ms", "_min_datetime_ms") ||
_load_object(&state->_max_datetime_ms, "bson.datetime_ms", "_max_datetime_ms")) {
return 1;
}
/* Reload our REType hack too. */
empty_string = PyBytes_FromString("");
if (empty_string == NULL) {
state->REType = NULL;
return 1;
}
if (_load_object(&re_compile, "re", "compile")) {
state->REType = NULL;
Py_DECREF(empty_string);
return 1;
}
compiled = PyObject_CallFunction(re_compile, "O", empty_string);
Py_DECREF(re_compile);
if (compiled == NULL) {
state->REType = NULL;
Py_DECREF(empty_string);
return 1;
}
Py_INCREF(Py_TYPE(compiled));
state->REType = Py_TYPE(compiled);
Py_DECREF(empty_string);
Py_DECREF(compiled);
return 0;
}
/*
* Get the _type_marker from an Object.
*
* Return the type marker, 0 if there is no marker, or -1 on failure.
*/
static long _type_marker(PyObject* object, PyObject* _type_marker_str) {
PyObject* type_marker = NULL;
long type = 0;
if (PyObject_HasAttr(object, _type_marker_str)) {
type_marker = PyObject_GetAttr(object, _type_marker_str);
if (type_marker == NULL) {
return -1;
}
}
/*
* Python objects with broken __getattr__ implementations could return
* arbitrary types for a call to PyObject_GetAttrString. For example
* pymongo.database.Database returns a new Collection instance for
* __getattr__ calls with names that don't match an existing attribute
* or method. In some cases "value" could be a subtype of something
* we know how to serialize. Make a best effort to encode these types.
*/
if (type_marker && PyLong_CheckExact(type_marker)) {
type = PyLong_AsLong(type_marker);
Py_DECREF(type_marker);
} else {
Py_XDECREF(type_marker);
}
return type;
}
/* Fill out a type_registry_t* from a TypeRegistry object.
*
* Return 1 on success. options->document_class is a new reference.
* Return 0 on failure.
*/
int cbson_convert_type_registry(PyObject* registry_obj, type_registry_t* registry, PyObject* _encoder_map_str, PyObject* _decoder_map_str, PyObject* _fallback_encoder_str) {
registry->encoder_map = NULL;
registry->decoder_map = NULL;
registry->fallback_encoder = NULL;
registry->registry_obj = NULL;
registry->encoder_map = PyObject_GetAttr(registry_obj, _encoder_map_str);
if (registry->encoder_map == NULL) {
goto fail;
}
registry->is_encoder_empty = (PyDict_Size(registry->encoder_map) == 0);
registry->decoder_map = PyObject_GetAttr(registry_obj, _decoder_map_str);
if (registry->decoder_map == NULL) {
goto fail;
}
registry->is_decoder_empty = (PyDict_Size(registry->decoder_map) == 0);
registry->fallback_encoder = PyObject_GetAttr(registry_obj, _fallback_encoder_str);
if (registry->fallback_encoder == NULL) {
goto fail;
}
registry->has_fallback_encoder = (registry->fallback_encoder != Py_None);
registry->registry_obj = registry_obj;
Py_INCREF(registry->registry_obj);
return 1;
fail:
Py_XDECREF(registry->encoder_map);
Py_XDECREF(registry->decoder_map);
Py_XDECREF(registry->fallback_encoder);
return 0;
}
/* Fill out a codec_options_t* from a CodecOptions object.
*
* Return 1 on success. options->document_class is a new reference.
* Return 0 on failure.
*/
int convert_codec_options(PyObject* self, PyObject* options_obj, codec_options_t* options) {
PyObject* type_registry_obj = NULL;
struct module_state *state = GETSTATE(self);
long type_marker;
options->unicode_decode_error_handler = NULL;
if (!PyArg_ParseTuple(options_obj, "ObbzOOb",
&options->document_class,
&options->tz_aware,
&options->uuid_rep,
&options->unicode_decode_error_handler,
&options->tzinfo,
&type_registry_obj,
&options->datetime_conversion)) {
return 0;
}
type_marker = _type_marker(options->document_class,
state->_type_marker_str);
if (type_marker < 0) {
return 0;
}
if (!cbson_convert_type_registry(type_registry_obj,
&options->type_registry, state->_encoder_map_str, state->_decoder_map_str, state->_fallback_encoder_str)) {
return 0;
}
options->is_raw_bson = (101 == type_marker);
options->options_obj = options_obj;
Py_INCREF(options->options_obj);
Py_INCREF(options->document_class);
Py_INCREF(options->tzinfo);
return 1;
}
void destroy_codec_options(codec_options_t* options) {
Py_CLEAR(options->document_class);
Py_CLEAR(options->tzinfo);
Py_CLEAR(options->options_obj);
Py_CLEAR(options->type_registry.registry_obj);
Py_CLEAR(options->type_registry.encoder_map);
Py_CLEAR(options->type_registry.decoder_map);
Py_CLEAR(options->type_registry.fallback_encoder);
}
static int write_element_to_buffer(PyObject* self, buffer_t buffer,
int type_byte, PyObject* value,
unsigned char check_keys,
const codec_options_t* options,
unsigned char in_custom_call,
unsigned char in_fallback_call) {
int result = 0;
if(Py_EnterRecursiveCall(" while encoding an object to BSON ")) {
return 0;
}
result = _write_element_to_buffer(self, buffer, type_byte,
value, check_keys, options,
in_custom_call, in_fallback_call);
Py_LeaveRecursiveCall();
return result;
}
static void
_set_cannot_encode(PyObject* value) {
if (PyLong_Check(value)) {
if ((PyLong_AsLongLong(value) == -1) && PyErr_Occurred()) {
return PyErr_SetString(PyExc_OverflowError,
"MongoDB can only handle up to 8-byte ints");
}
}
PyObject* type = NULL;
PyObject* InvalidDocument = _error("InvalidDocument");
if (InvalidDocument == NULL) {
goto error;
}
type = PyObject_Type(value);
if (type == NULL) {
goto error;
}
PyErr_Format(InvalidDocument, "cannot encode object: %R, of type: %R",
value, type);
error:
Py_XDECREF(type);
Py_XDECREF(InvalidDocument);
}
/*
* Encode a builtin Python regular expression or our custom Regex class.
*
* Sets exception and returns 0 on failure.
*/
static int _write_regex_to_buffer(
buffer_t buffer, int type_byte, PyObject* value, PyObject* _flags_str, PyObject* _pattern_str) {
PyObject* py_flags;
PyObject* py_pattern;
PyObject* encoded_pattern;
PyObject* decoded_pattern;
long int_flags;
char flags[FLAGS_SIZE];
char check_utf8 = 0;
const char* pattern_data;
int pattern_length, flags_length;
/*
* Both the builtin re type and our Regex class have attributes
* "flags" and "pattern".
*/
py_flags = PyObject_GetAttr(value, _flags_str);
if (!py_flags) {
return 0;
}
int_flags = PyLong_AsLong(py_flags);
Py_DECREF(py_flags);
if (int_flags == -1 && PyErr_Occurred()) {
return 0;
}
py_pattern = PyObject_GetAttr(value, _pattern_str);
if (!py_pattern) {
return 0;
}
if (PyUnicode_Check(py_pattern)) {
encoded_pattern = PyUnicode_AsUTF8String(py_pattern);
Py_DECREF(py_pattern);
if (!encoded_pattern) {
return 0;
}
} else {
encoded_pattern = py_pattern;
check_utf8 = 1;
}
if (!(pattern_data = PyBytes_AsString(encoded_pattern))) {
Py_DECREF(encoded_pattern);
return 0;
}
if ((pattern_length = _downcast_and_check(PyBytes_Size(encoded_pattern), 0)) == -1) {
Py_DECREF(encoded_pattern);
return 0;
}
if (strlen(pattern_data) != (size_t) pattern_length){
PyObject* InvalidDocument = _error("InvalidDocument");
if (InvalidDocument) {
PyErr_SetString(InvalidDocument,
"regex patterns must not contain the NULL byte");
Py_DECREF(InvalidDocument);
}
Py_DECREF(encoded_pattern);
return 0;
}
if (check_utf8) {
decoded_pattern = PyUnicode_DecodeUTF8(pattern_data, (Py_ssize_t) pattern_length, NULL);
if (decoded_pattern == NULL) {
PyErr_Clear();
PyObject* InvalidStringData = _error("InvalidStringData");
if (InvalidStringData) {
PyErr_SetString(InvalidStringData,
"regex patterns must be valid UTF-8");
Py_DECREF(InvalidStringData);
}
Py_DECREF(encoded_pattern);
return 0;
}
Py_DECREF(decoded_pattern);
}
if (!buffer_write_bytes(buffer, pattern_data, pattern_length + 1)) {
Py_DECREF(encoded_pattern);
return 0;
}
Py_DECREF(encoded_pattern);
flags[0] = 0;
if (int_flags & 2) {
STRCAT(flags, FLAGS_SIZE, "i");
}
if (int_flags & 4) {
STRCAT(flags, FLAGS_SIZE, "l");
}
if (int_flags & 8) {
STRCAT(flags, FLAGS_SIZE, "m");
}
if (int_flags & 16) {
STRCAT(flags, FLAGS_SIZE, "s");
}
if (int_flags & 32) {
STRCAT(flags, FLAGS_SIZE, "u");
}
if (int_flags & 64) {
STRCAT(flags, FLAGS_SIZE, "x");
}
flags_length = (int)strlen(flags) + 1;
if (!buffer_write_bytes(buffer, flags, flags_length)) {
return 0;
}
*(pymongo_buffer_get_buffer(buffer) + type_byte) = 0x0B;
return 1;
}
/* Write a single value to the buffer (also write its type_byte, for which
* space has already been reserved.
*
* returns 0 on failure */
static int _write_element_to_buffer(PyObject* self, buffer_t buffer,
int type_byte, PyObject* value,
unsigned char check_keys,
const codec_options_t* options,
unsigned char in_custom_call,
unsigned char in_fallback_call) {
struct module_state *state = GETSTATE(self);
PyObject* mapping_type;
PyObject* new_value = NULL;
int retval;
PyObject* uuid_type;
int is_list;
/*
* Don't use PyObject_IsInstance for our custom types. It causes
* problems with python sub interpreters. Our custom types should
* have a _type_marker attribute, which we can switch on instead.
*/
long type = _type_marker(value, state->_type_marker_str);
if (type < 0) {
return 0;
}
switch (type) {
case 5:
{
/* Binary */
PyObject* subtype_object;
char subtype;
const char* data;
int size;
*(pymongo_buffer_get_buffer(buffer) + type_byte) = 0x05;
subtype_object = PyObject_GetAttr(value, state->_subtype_str);
if (!subtype_object) {
return 0;
}
subtype = (char)PyLong_AsLong(subtype_object);
if (subtype == -1) {
Py_DECREF(subtype_object);
return 0;
}
size = _downcast_and_check(PyBytes_Size(value), 0);
if (size == -1) {
Py_DECREF(subtype_object);
return 0;
}
Py_DECREF(subtype_object);
if (subtype == 2) {
int other_size = _downcast_and_check(PyBytes_Size(value), 4);
if (other_size == -1)
return 0;
if (!buffer_write_int32(buffer, other_size)) {
return 0;
}
if (!buffer_write_bytes(buffer, &subtype, 1)) {
return 0;
}
}
if (!buffer_write_int32(buffer, size)) {
return 0;
}
if (subtype != 2) {
if (!buffer_write_bytes(buffer, &subtype, 1)) {
return 0;
}
}
data = PyBytes_AsString(value);
if (!data) {
return 0;
}
if (!buffer_write_bytes(buffer, data, size)) {
return 0;
}
return 1;
}
case 7:
{
/* ObjectId */
const char* data;
PyObject* pystring = PyObject_GetAttr(value, state->_binary_str);
if (!pystring) {
return 0;
}
data = PyBytes_AsString(pystring);
if (!data) {
Py_DECREF(pystring);
return 0;
}
if (!buffer_write_bytes(buffer, data, 12)) {
Py_DECREF(pystring);
return 0;
}
Py_DECREF(pystring);
*(pymongo_buffer_get_buffer(buffer) + type_byte) = 0x07;
return 1;
}
case 11:
{
/* Regex */
return _write_regex_to_buffer(buffer, type_byte, value, state->_flags_str, state->_pattern_str);
}
case 13:
{
/* Code */
int start_position,
length_location,
length;