forked from mongodb/mongo-php-driver-legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bson.c
1376 lines (1170 loc) · 35.8 KB
/
bson.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-2012 10gen, 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.
*/
#include <php.h>
#include <zend_exceptions.h>
#ifdef WIN32
# include <memory.h>
# ifndef int64_t
typedef __int64 int64_t;
# endif
#endif
#include "php_mongo.h"
#include "bson.h"
#include "mongo_types.h"
extern zend_class_entry *mongo_ce_BinData,
*mongo_ce_Code,
*mongo_ce_Date,
*mongo_ce_Id,
*mongo_ce_Regex,
*mongo_ce_Timestamp,
*mongo_ce_MinKey,
*mongo_ce_MaxKey,
*mongo_ce_Exception,
*mongo_ce_CursorException,
*mongo_ce_Int32,
*mongo_ce_Int64;
ZEND_EXTERN_MODULE_GLOBALS(mongo);
static int get_limit(mongo_cursor *cursor);
static int prep_obj_for_db(buffer *buf, HashTable *array TSRMLS_DC);
#if ZEND_MODULE_API_NO >= 20090115
static int apply_func_args_wrapper(void **data TSRMLS_DC, int num_args, va_list args, zend_hash_key *key);
#else
static int apply_func_args_wrapper(void **data, int num_args, va_list args, zend_hash_key *key);
#endif /* ZEND_MODULE_API_NO >= 20090115 */
static int is_utf8(const char *s, int len);
static int insert_helper(buffer *buf, zval *doc, int max TSRMLS_DC);
static int prep_obj_for_db(buffer *buf, HashTable *array TSRMLS_DC) {
zval temp, **data, *newid;
// if _id field doesn't exist, add it
if (zend_hash_find(array, "_id", 4, (void**)&data) == FAILURE) {
// create new MongoId
MAKE_STD_ZVAL(newid);
object_init_ex(newid, mongo_ce_Id);
MONGO_METHOD(MongoId, __construct, &temp, newid);
// add to obj
zend_hash_add(array, "_id", 4, &newid, sizeof(zval*), NULL);
// set to data
data = &newid;
}
php_mongo_serialize_element("_id", data, buf, 0 TSRMLS_CC);
if (EG(exception)) {
return FAILURE;
}
return SUCCESS;
}
// serialize a zval
int zval_to_bson(buffer *buf, HashTable *hash, int prep TSRMLS_DC) {
uint start;
int num = 0;
// check buf size
if(BUF_REMAINING <= 5) {
resize_buf(buf, 5);
}
// keep a record of the starting position
// as an offset, in case the memory is resized
start = buf->pos-buf->start;
// skip first 4 bytes to leave room for size
buf->pos += INT_32;
if (zend_hash_num_elements(hash) > 0) {
if (prep) {
prep_obj_for_db(buf, hash TSRMLS_CC);
num++;
}
#if ZEND_MODULE_API_NO >= 20090115
zend_hash_apply_with_arguments(hash TSRMLS_CC, (apply_func_args_t)apply_func_args_wrapper, 3, buf, prep, &num);
#else
zend_hash_apply_with_arguments(hash, (apply_func_args_t)apply_func_args_wrapper, 4, buf, prep, &num TSRMLS_CC);
#endif /* ZEND_MODULE_API_NO >= 20090115 */
}
php_mongo_serialize_null(buf);
php_mongo_serialize_size(buf->start + start, buf TSRMLS_CC);
return EG(exception) ? FAILURE : num;
}
#if ZEND_MODULE_API_NO >= 20090115
static int apply_func_args_wrapper(void **data TSRMLS_DC, int num_args, va_list args, zend_hash_key *key)
#else
static int apply_func_args_wrapper(void **data, int num_args, va_list args, zend_hash_key *key)
#endif /* ZEND_MODULE_API_NO >= 20090115 */
{
buffer *buf = va_arg(args, buffer*);
int prep = va_arg(args, int);
int *num = va_arg(args, int*);
#if ZEND_MODULE_API_NO < 20090115
void ***tsrm_ls = va_arg(args, void***);
#endif /* ZEND_MODULE_API_NO < 20090115 */
if (key->nKeyLength) {
return php_mongo_serialize_element(key->arKey, (zval**)data, buf, prep TSRMLS_CC);
}
else {
long current = key->h;
int pos = 29, negative = 0;
char name[30];
// if the key is a number in ascending order, we're still
// dealing with an array, not an object, so increase the count
if (key->h == (unsigned int)*num) {
(*num)++;
}
name[pos--] = '\0';
// take care of negative indexes
if (current < 0) {
current *= -1;
negative = 1;
}
do {
int digit = current % 10;
digit += (int)'0';
name[pos--] = (char)digit;
current = current / 10;
} while (current > 0);
if (negative) {
name[pos--] = '-';
}
return php_mongo_serialize_element(name+pos+1, (zval**)data, buf, prep TSRMLS_CC);
}
}
int php_mongo_serialize_element(char *name, zval **data, buffer *buf, int prep TSRMLS_DC) {
int name_len = strlen(name);
if (prep && strcmp(name, "_id") == 0) {
return ZEND_HASH_APPLY_KEEP;
}
switch (Z_TYPE_PP(data)) {
case IS_NULL:
PHP_MONGO_SERIALIZE_KEY(BSON_NULL);
break;
case IS_LONG:
if (MonGlo(native_long)) {
#if SIZEOF_LONG == 4
PHP_MONGO_SERIALIZE_KEY(BSON_INT);
php_mongo_serialize_int(buf, Z_LVAL_PP(data));
#else
# if SIZEOF_LONG == 8
PHP_MONGO_SERIALIZE_KEY(BSON_LONG);
php_mongo_serialize_long(buf, Z_LVAL_PP(data));
# else
# error The PHP number size is neither 4 or 8 bytes; no clue what to do with that!
# endif
#endif
} else {
PHP_MONGO_SERIALIZE_KEY(BSON_INT);
php_mongo_serialize_int(buf, Z_LVAL_PP(data));
}
break;
case IS_DOUBLE:
PHP_MONGO_SERIALIZE_KEY(BSON_DOUBLE);
php_mongo_serialize_double(buf, Z_DVAL_PP(data));
break;
case IS_BOOL:
PHP_MONGO_SERIALIZE_KEY(BSON_BOOL);
php_mongo_serialize_bool(buf, Z_BVAL_PP(data));
break;
case IS_STRING: {
PHP_MONGO_SERIALIZE_KEY(BSON_STRING);
// if this is not a valid string, stop
if (MonGlo(utf8) && !is_utf8(Z_STRVAL_PP(data), Z_STRLEN_PP(data))) {
zend_throw_exception_ex(mongo_ce_Exception, 12 TSRMLS_CC, "non-utf8 string: %s", Z_STRVAL_PP(data));
return ZEND_HASH_APPLY_STOP;
}
php_mongo_serialize_int(buf, Z_STRLEN_PP(data)+1);
php_mongo_serialize_string(buf, Z_STRVAL_PP(data), Z_STRLEN_PP(data));
break;
}
case IS_ARRAY: {
int num;
// if we realloc, we need an offset, not an abs pos (phew)
int type_offset = buf->pos-buf->start;
//serialize
PHP_MONGO_SERIALIZE_KEY(BSON_ARRAY);
num = zval_to_bson(buf, Z_ARRVAL_PP(data), NO_PREP TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
// now go back and set the type bit
//php_mongo_set_type(buf, BSON_ARRAY);
if (num == zend_hash_num_elements(Z_ARRVAL_PP(data))) {
buf->start[type_offset] = BSON_ARRAY;
}
else {
buf->start[type_offset] = BSON_OBJECT;
}
break;
}
case IS_OBJECT: {
zend_class_entry *clazz = Z_OBJCE_PP( data );
/* check for defined classes */
// MongoId
if(clazz == mongo_ce_Id) {
mongo_id *id;
PHP_MONGO_SERIALIZE_KEY(BSON_OID);
id = (mongo_id*)zend_object_store_get_object(*data TSRMLS_CC);
if (!id->id) {
return ZEND_HASH_APPLY_KEEP;
}
php_mongo_serialize_bytes(buf, id->id, OID_SIZE);
}
// MongoDate
else if (clazz == mongo_ce_Date) {
PHP_MONGO_SERIALIZE_KEY(BSON_DATE);
php_mongo_serialize_date(buf, *data TSRMLS_CC);
}
// MongoRegex
else if (clazz == mongo_ce_Regex) {
PHP_MONGO_SERIALIZE_KEY(BSON_REGEX);
php_mongo_serialize_regex(buf, *data TSRMLS_CC);
}
// MongoCode
else if (clazz == mongo_ce_Code) {
PHP_MONGO_SERIALIZE_KEY(BSON_CODE);
php_mongo_serialize_code(buf, *data TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
}
// MongoBin
else if (clazz == mongo_ce_BinData) {
PHP_MONGO_SERIALIZE_KEY(BSON_BINARY);
php_mongo_serialize_bin_data(buf, *data TSRMLS_CC);
}
// MongoTimestamp
else if (clazz == mongo_ce_Timestamp) {
PHP_MONGO_SERIALIZE_KEY(BSON_TIMESTAMP);
php_mongo_serialize_ts(buf, *data TSRMLS_CC);
}
else if (clazz == mongo_ce_MinKey) {
PHP_MONGO_SERIALIZE_KEY(BSON_MINKEY);
}
else if (clazz == mongo_ce_MaxKey) {
PHP_MONGO_SERIALIZE_KEY(BSON_MAXKEY);
}
// Integer types
else if (clazz == mongo_ce_Int32) {
PHP_MONGO_SERIALIZE_KEY(BSON_INT);
php_mongo_serialize_int32(buf, *data TSRMLS_CC);
}
else if (clazz == mongo_ce_Int64) {
PHP_MONGO_SERIALIZE_KEY(BSON_LONG);
php_mongo_serialize_int64(buf, *data TSRMLS_CC);
}
// serialize a normal obj
else {
HashTable *hash = Z_OBJPROP_PP(data);
// go through the k/v pairs and serialize them
PHP_MONGO_SERIALIZE_KEY(BSON_OBJECT);
zval_to_bson(buf, hash, NO_PREP TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
}
break;
}
}
return ZEND_HASH_APPLY_KEEP;
}
int resize_buf(buffer *buf, int size) {
int total = buf->end - buf->start;
int used = buf->pos - buf->start;
total = total < GROW_SLOWLY ? total*2 : total+INITIAL_BUF_SIZE;
while (total-used < size) {
total += size;
}
buf->start = (char*)erealloc(buf->start, total);
buf->pos = buf->start + used;
buf->end = buf->start + total;
return total;
}
/*
* create a bson date
*
* type: 9
* 8 bytes of ms since the epoch
*/
void php_mongo_serialize_date(buffer *buf, zval *date TSRMLS_DC) {
int64_t ms;
zval *sec = zend_read_property(mongo_ce_Date, date, "sec", 3, 0 TSRMLS_CC);
zval *usec = zend_read_property(mongo_ce_Date, date, "usec", 4, 0 TSRMLS_CC);
ms = ((int64_t)Z_LVAL_P(sec) * 1000) + ((int64_t)Z_LVAL_P(usec) / 1000);
php_mongo_serialize_long(buf, ms);
}
#if defined(_MSC_VER)
# define strtoll(s, f, b) _atoi64(s)
#elif !defined(HAVE_STRTOLL)
# if defined(HAVE_ATOLL)
# define strtoll(s, f, b) atoll(s)
# else
# define strtoll(s, f, b) strtol(s, f, b)
# endif
#endif
/*
* create a bson int from an Int32 object
*/
void php_mongo_serialize_int32(buffer *buf, zval *data TSRMLS_DC) {
int value;
zval *zvalue = zend_read_property(mongo_ce_Int32, data, "value", 5, 0 TSRMLS_CC);
value = strtol(Z_STRVAL_P(zvalue), NULL, 10);
php_mongo_serialize_int(buf, value);
}
/*
* create a bson long from an Int64 object
*/
void php_mongo_serialize_int64(buffer *buf, zval *data TSRMLS_DC) {
int64_t value;
zval *zvalue = zend_read_property(mongo_ce_Int64, data, "value", 5, 0 TSRMLS_CC);
value = strtoll(Z_STRVAL_P(zvalue), NULL, 10);
php_mongo_serialize_long(buf, value);
}
/*
* create a bson regex
*
* type: 11
* cstring cstring
*/
void php_mongo_serialize_regex(buffer *buf, zval *regex TSRMLS_DC) {
zval *z;
z = zend_read_property(mongo_ce_Regex, regex, "regex", 5, 0 TSRMLS_CC);
php_mongo_serialize_string(buf, Z_STRVAL_P(z), Z_STRLEN_P(z));
z = zend_read_property(mongo_ce_Regex, regex, "flags", 5, 0 TSRMLS_CC);
php_mongo_serialize_string(buf, Z_STRVAL_P(z), Z_STRLEN_P(z));
}
/*
* create a bson code with scope
*
* type: 15
* 4 bytes total size
* 4 bytes cstring size + NULL
* cstring
* bson object scope
*/
void php_mongo_serialize_code(buffer *buf, zval *code TSRMLS_DC) {
uint start;
zval *zid;
// save spot for size
start = buf->pos-buf->start;
buf->pos += INT_32;
zid = zend_read_property(mongo_ce_Code, code, "code", 4, NOISY TSRMLS_CC);
// string size
php_mongo_serialize_int(buf, Z_STRLEN_P(zid)+1);
// string
php_mongo_serialize_string(buf, Z_STRVAL_P(zid), Z_STRLEN_P(zid));
// scope
zid = zend_read_property(mongo_ce_Code, code, "scope", 5, NOISY TSRMLS_CC);
zval_to_bson(buf, HASH_P(zid), NO_PREP TSRMLS_CC);
if (EG(exception)) {
return;
}
// get total size
php_mongo_serialize_size(buf->start+start, buf TSRMLS_CC);
}
/*
* create bson binary data
*
* type: 5
* 4 bytes: length of bindata
* 1 byte: bindata type
* bindata
*/
void php_mongo_serialize_bin_data(buffer *buf, zval *bin TSRMLS_DC) {
zval *zbin, *ztype;
zbin = zend_read_property(mongo_ce_BinData, bin, "bin", 3, 0 TSRMLS_CC);
ztype = zend_read_property(mongo_ce_BinData, bin, "type", 4, 0 TSRMLS_CC);
/*
* type 2 has the redundant structure:
*
* |------|--|-------==========|
* length 02 length bindata
*
* - 4 bytes: length of bindata (+4 for length below)
* - 1 byte type (0x02)
* - N bytes: 4 bytes of length of the following bindata + bindata
*
*/
if (Z_LVAL_P(ztype) == 2) {
// length
php_mongo_serialize_int(buf, Z_STRLEN_P(zbin)+4);
// 02
php_mongo_serialize_byte(buf, 2);
// length
php_mongo_serialize_int(buf, Z_STRLEN_P(zbin));
}
/* other types have
*
* |------|--|==========|
* length bindata
* type
*/
else {
// length
php_mongo_serialize_int(buf, Z_STRLEN_P(zbin));
// type
php_mongo_serialize_byte(buf, (unsigned char)Z_LVAL_P(ztype));
}
// bindata
php_mongo_serialize_bytes(buf, Z_STRVAL_P(zbin), Z_STRLEN_P(zbin));
}
/*
* create bson timestamp
*
* type: 17
* 4 bytes seconds since epoch
* 4 bytes increment
*/
void php_mongo_serialize_ts(buffer *buf, zval *time TSRMLS_DC) {
zval *ts, *inc;
ts = zend_read_property(mongo_ce_Timestamp, time, "sec", strlen("sec"), NOISY TSRMLS_CC);
inc = zend_read_property(mongo_ce_Timestamp, time, "inc", strlen("inc"), NOISY TSRMLS_CC);
php_mongo_serialize_int(buf, Z_LVAL_P(inc));
php_mongo_serialize_int(buf, Z_LVAL_P(ts));
}
void php_mongo_serialize_byte(buffer *buf, char b) {
if(BUF_REMAINING <= 1) {
resize_buf(buf, 1);
}
*(buf->pos) = b;
buf->pos += 1;
}
void php_mongo_serialize_bytes(buffer *buf, char *str, int str_len) {
if(BUF_REMAINING <= str_len) {
resize_buf(buf, str_len);
}
memcpy(buf->pos, str, str_len);
buf->pos += str_len;
}
void php_mongo_serialize_string(buffer *buf, char *str, int str_len) {
if(BUF_REMAINING <= str_len+1) {
resize_buf(buf, str_len+1);
}
memcpy(buf->pos, str, str_len);
// add \0 at the end of the string
buf->pos[str_len] = 0;
buf->pos += str_len + 1;
}
void php_mongo_serialize_int(buffer *buf, int num) {
int i = MONGO_32(num);
if(BUF_REMAINING <= INT_32) {
resize_buf(buf, INT_32);
}
memcpy(buf->pos, &i, INT_32);
buf->pos += INT_32;
}
void php_mongo_serialize_long(buffer *buf, int64_t num) {
int64_t i = MONGO_64(num);
if(BUF_REMAINING <= INT_64) {
resize_buf(buf, INT_64);
}
memcpy(buf->pos, &i, INT_64);
buf->pos += INT_64;
}
void php_mongo_serialize_double(buffer *buf, double num) {
int64_t dest, *dest_p;
dest_p = &dest;
memcpy(dest_p, &num, 8);
dest = MONGO_64(dest);
if(BUF_REMAINING <= INT_64) {
resize_buf(buf, INT_64);
}
memcpy(buf->pos, dest_p, DOUBLE_64);
buf->pos += DOUBLE_64;
}
/*
* prep == true
* we are inserting, so keys can't have .s in them
*/
void php_mongo_serialize_key(buffer *buf, char *str, int str_len, int prep TSRMLS_DC) {
if (str[0] == '\0' && !MonGlo(allow_empty_keys)) {
zend_throw_exception_ex(mongo_ce_Exception, 1 TSRMLS_CC, "zero-length keys are not allowed, did you use $ with double quotes?");
return;
}
if(BUF_REMAINING <= str_len+1) {
resize_buf(buf, str_len+1);
}
if (prep && (strchr(str, '.') != 0)) {
zend_throw_exception_ex(mongo_ce_Exception, 2 TSRMLS_CC, "'.' not allowed in key: %s", str);
return;
}
if (MonGlo(cmd_char) && strchr(str, MonGlo(cmd_char)[0]) == str) {
*(buf->pos) = '$';
memcpy(buf->pos+1, str+1, str_len-1);
}
else {
memcpy(buf->pos, str, str_len);
}
// add \0 at the end of the string
buf->pos[str_len] = 0;
buf->pos += str_len + 1;
}
/*
* replaces collection names starting with MonGlo(cmd_char)
* with the '$' character.
*
* TODO: this doesn't handle main.$oplog-type situations (if
* MonGlo(cmd_char) is set)
*/
void php_mongo_serialize_ns(buffer *buf, char *str TSRMLS_DC) {
char *collection = strchr(str, '.')+1;
if(BUF_REMAINING <= (int)strlen(str)+1) {
resize_buf(buf, strlen(str)+1);
}
if (MonGlo(cmd_char) && strchr(collection, MonGlo(cmd_char)[0]) == collection) {
memcpy(buf->pos, str, collection-str);
buf->pos += collection-str;
*(buf->pos) = '$';
memcpy(buf->pos+1, collection+1, strlen(collection)-1);
buf->pos[strlen(collection)] = 0;
buf->pos += strlen(collection) + 1;
}
else {
memcpy(buf->pos, str, strlen(str));
buf->pos[strlen(str)] = 0;
buf->pos += strlen(str) + 1;
}
}
/* the position is not increased, we are just filling
* in the first 4 bytes with the size.
*/
int php_mongo_serialize_size(char *start, buffer *buf TSRMLS_DC) {
int total = MONGO_32((buf->pos - start));
if (buf->pos - start > 16000000) {
zend_throw_exception_ex(mongo_ce_Exception, 3 TSRMLS_CC, "insert too large: %d, max: 16000000", buf->pos - start);
return FAILURE;
}
memcpy(start, &total, INT_32);
return SUCCESS;
}
static int insert_helper(buffer *buf, zval *doc, int max TSRMLS_DC) {
int start = buf->pos - buf->start;
int result = zval_to_bson(buf, HASH_P(doc), PREP TSRMLS_CC);
// throw exception if serialization crapped out
if (EG(exception) || FAILURE == result) {
return FAILURE;
}
// return if there were 0 elements
else if (0 == result) {
zend_throw_exception_ex(mongo_ce_Exception, 4 TSRMLS_CC, "no elements in doc");
return FAILURE;
}
// throw an exception if the doc was too big
if(buf->pos - (buf->start + start) > max) {
zend_throw_exception_ex(mongo_ce_Exception, 5 TSRMLS_CC, "size of BSON doc is %d bytes, max is %d",
buf->pos - (buf->start + start), max);
return FAILURE;
}
return php_mongo_serialize_size(buf->start + start, buf TSRMLS_CC);
}
int php_mongo_write_insert(buffer *buf, char *ns, zval *doc, int max TSRMLS_DC) {
mongo_msg_header header;
int start = buf->pos - buf->start;
CREATE_HEADER(buf, ns, OP_INSERT);
if (FAILURE == insert_helper(buf, doc, max TSRMLS_CC)) {
return FAILURE;
}
return php_mongo_serialize_size(buf->start + start, buf TSRMLS_CC);
}
int php_mongo_write_batch_insert(buffer *buf, char *ns, int flags, zval *docs, int max TSRMLS_DC) {
int start = buf->pos - buf->start, count = 0;
HashPosition pointer;
zval **doc;
mongo_msg_header header;
CREATE_HEADER_WITH_OPTS(buf, ns, OP_INSERT, flags);
// php_mongo_serialize_int(buf, flags);
for(zend_hash_internal_pointer_reset_ex(HASH_P(docs), &pointer);
zend_hash_get_current_data_ex(HASH_P(docs), (void**)&doc, &pointer) == SUCCESS;
zend_hash_move_forward_ex(HASH_P(docs), &pointer)) {
if (IS_SCALAR_PP(doc)) {
continue;
}
if (FAILURE == insert_helper(buf, *doc, max TSRMLS_CC) ||
buf->pos - buf->start >= MonGlo(max_send_size)) {
return FAILURE;
}
count++;
}
// if there are no elements, don't bother saving
if (count == 0) {
zend_throw_exception_ex(mongo_ce_Exception, 6 TSRMLS_CC, "no documents given");
return FAILURE;
}
// this is a hard limit in the db server (util/messages.cpp)
if (buf->pos - (buf->start + start) > 16000000) {
zend_throw_exception_ex(mongo_ce_Exception, 3 TSRMLS_CC, "insert too large: %d, max: 16000000", buf->pos - (buf->start+start));
return FAILURE;
}
return php_mongo_serialize_size(buf->start + start, buf TSRMLS_CC);
}
int php_mongo_write_update(buffer *buf, char *ns, int flags, zval *criteria, zval *newobj TSRMLS_DC) {
mongo_msg_header header;
int start = buf->pos - buf->start;
CREATE_HEADER(buf, ns, OP_UPDATE);
php_mongo_serialize_int(buf, flags);
if (zval_to_bson(buf, HASH_P(criteria), NO_PREP TSRMLS_CC) == FAILURE ||
EG(exception) ||
zval_to_bson(buf, HASH_P(newobj), NO_PREP TSRMLS_CC) == FAILURE ||
EG(exception)) {
return FAILURE;
}
return php_mongo_serialize_size(buf->start + start, buf TSRMLS_CC);
}
int php_mongo_write_delete(buffer *buf, char *ns, int flags, zval *criteria TSRMLS_DC) {
mongo_msg_header header;
int start = buf->pos - buf->start;
CREATE_HEADER(buf, ns, OP_DELETE);
php_mongo_serialize_int(buf, flags);
if (zval_to_bson(buf, HASH_P(criteria), NO_PREP TSRMLS_CC) == FAILURE ||
EG(exception)) {
return FAILURE;
}
return php_mongo_serialize_size(buf->start + start, buf TSRMLS_CC);
}
/*
* Creates a query string in buf.
*
* The following fields of cursor are used:
* - ns
* - opts
* - skip
* - limit
* - query
* - fields
*
*/
int php_mongo_write_query(buffer *buf, mongo_cursor *cursor TSRMLS_DC) {
mongo_msg_header header;
int start = buf->pos - buf->start;
CREATE_HEADER_WITH_OPTS(buf, cursor->ns, OP_QUERY, cursor->opts);
cursor->send.request_id = header.request_id;
php_mongo_serialize_int(buf, cursor->skip);
php_mongo_serialize_int(buf, get_limit(cursor));
if (zval_to_bson(buf, HASH_P(cursor->query), NO_PREP TSRMLS_CC) == FAILURE ||
EG(exception)) {
return FAILURE;
}
if (cursor->fields && zend_hash_num_elements(HASH_P(cursor->fields)) > 0) {
if (zval_to_bson(buf, HASH_P(cursor->fields), NO_PREP TSRMLS_CC) == FAILURE ||
EG(exception)) {
return FAILURE;
}
}
return php_mongo_serialize_size(buf->start + start, buf TSRMLS_CC);
}
int php_mongo_write_kill_cursors(buffer *buf, int64_t cursor_id TSRMLS_DC) {
mongo_msg_header header;
CREATE_MSG_HEADER(MonGlo(request_id)++, 0, OP_KILL_CURSORS);
APPEND_HEADER(buf, 0);
// # of cursors
php_mongo_serialize_int(buf, 1);
// cursor ids
php_mongo_serialize_long(buf, cursor_id);
return php_mongo_serialize_size(buf->start, buf TSRMLS_CC);
}
/*
* Creates a GET_MORE request
*
* The following fields of cursor are used:
* - ns
* - recv.request_id
* - limit
* - cursor_id
*/
int php_mongo_write_get_more(buffer *buf, mongo_cursor *cursor TSRMLS_DC) {
mongo_msg_header header;
int start = buf->pos - buf->start;
CREATE_RESPONSE_HEADER(buf, cursor->ns, cursor->recv.request_id, OP_GET_MORE);
cursor->send.request_id = header.request_id;
php_mongo_serialize_int(buf, get_limit(cursor));
php_mongo_serialize_long(buf, cursor->cursor_id);
return php_mongo_serialize_size(buf->start + start, buf TSRMLS_CC);
}
static int get_limit(mongo_cursor *cursor) {
int lim_at;
if (cursor->limit < 0) {
return cursor->limit;
}
else if (cursor->batch_size < 0) {
return cursor->batch_size;
}
lim_at = cursor->limit > cursor->batch_size ? cursor->limit - cursor->at : cursor->limit;
if (cursor->batch_size && (!lim_at || cursor->batch_size <= lim_at)) {
return cursor->batch_size;
}
else if (lim_at && (!cursor->batch_size || lim_at < cursor->batch_size)) {
return lim_at;
}
return 0;
}
char* bson_to_zval(char *buf, HashTable *result TSRMLS_DC) {
/*
* buf_start is used for debugging
*
* if the deserializer runs into bson it can't
* parse, it will dump the bytes to that point.
*
* we lose buf's position as we iterate, so we
* need buf_start to save it.
*/
char *buf_start = buf;
unsigned char type;
if (buf == 0) {
return 0;
}
// for size
buf += INT_32;
while ((type = *buf++) != 0) {
char *name;
zval *value;
name = buf;
// get past field name
buf += strlen(buf) + 1;
MAKE_STD_ZVAL(value);
ZVAL_NULL(value);
// get value
switch(type) {
case BSON_OID: {
mongo_id *this_id;
zval *str = 0;
object_init_ex(value, mongo_ce_Id);
this_id = (mongo_id*)zend_object_store_get_object(value TSRMLS_CC);
this_id->id = estrndup(buf, OID_SIZE);
MAKE_STD_ZVAL(str);
ZVAL_NULL(str);
MONGO_METHOD(MongoId, __toString, str, value);
zend_update_property(mongo_ce_Id, value, "$id", strlen("$id"), str TSRMLS_CC);
zval_ptr_dtor(&str);
buf += OID_SIZE;
break;
}
case BSON_DOUBLE: {
double d = *(double*)buf;
int64_t i, *i_p;
i_p = &i;
memcpy(i_p, &d, DOUBLE_64);
i = MONGO_64(i);
memcpy(&d, i_p, DOUBLE_64);
ZVAL_DOUBLE(value, d);
buf += DOUBLE_64;
break;
}
case BSON_SYMBOL:
case BSON_STRING: {
// len includes \0
int len = MONGO_32(*((int*)buf));
if (INVALID_STRING_LEN(len)) {
zval_ptr_dtor(&value);
zend_throw_exception_ex(mongo_ce_CursorException, 0 TSRMLS_CC, "invalid string length for key \"%s\": %d", name, len);
return 0;
}
buf += INT_32;
ZVAL_STRINGL(value, buf, len-1, 1);
buf += len;
break;
}
case BSON_OBJECT:
case BSON_ARRAY: {
array_init(value);
buf = bson_to_zval(buf, Z_ARRVAL_P(value) TSRMLS_CC);
if (EG(exception)) {
zval_ptr_dtor(&value);
return 0;
}
break;
}
case BSON_BINARY: {
unsigned char type;
int len = MONGO_32(*(int*)buf);
if (INVALID_STRING_LEN(len)) {
zval_ptr_dtor(&value);
zend_throw_exception_ex(mongo_ce_CursorException, 1 TSRMLS_CC, "invalid binary length for key \"%s\": %d", name, len);
return 0;
}
buf += INT_32;
type = *buf++;
/* If the type is 2, check if the binary data
* is prefixed by its length.
*
* There is an infinitesimally small chance that
* the first four bytes will happen to be the
* length of the rest of the string. In this
* case, the data will be corrupted.
*/
if ((int)type == 2) {
int len2 = MONGO_32(*(int*)buf);
/* if the lengths match, the data is to spec,
* so we use len2 as the true length.
*/
if (len2 == len - 4) {
len = len2;
buf += INT_32;
}
}
object_init_ex(value, mongo_ce_BinData);
zend_update_property_stringl(mongo_ce_BinData, value, "bin", strlen("bin"), buf, len TSRMLS_CC);
zend_update_property_long(mongo_ce_BinData, value, "type", strlen("type"), type TSRMLS_CC);
buf += len;
break;
}
case BSON_BOOL: {
char d = *buf++;
ZVAL_BOOL(value, d);
break;
}
case BSON_UNDEF:
case BSON_NULL: {
ZVAL_NULL(value);
break;
}
case BSON_INT: {
ZVAL_LONG(value, MONGO_32(*((int*)buf)));
buf += INT_32;
break;
}
case BSON_LONG: {
if (MonGlo(long_as_object)) {
char *buffer;
#ifdef WIN32
spprintf(&buffer, 0, "%I64d", (int64_t)MONGO_64(*((int64_t*)buf)));
#else
spprintf(&buffer, 0, "%lld", (long long int)MONGO_64(*((int64_t*)buf)));
#endif
object_init_ex(value, mongo_ce_Int64);
zend_update_property_string(mongo_ce_Int64, value, "value", strlen("value"), buffer TSRMLS_CC);