forked from mongodb/mongo-php-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphp_phongo.c
2593 lines (2121 loc) · 77.4 KB
/
php_phongo.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
/*
+---------------------------------------------------------------------------+
| PHP Driver for MongoDB |
+---------------------------------------------------------------------------+
| Copyright 2013-2015 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. |
+---------------------------------------------------------------------------+
| Copyright (c) 2014-2015 MongoDB, Inc. |
+---------------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
/* External libs */
#include "bson.h"
#include "mongoc.h"
#include "mongoc-cursor-cursorid-private.h"
#include "mongoc-read-prefs-private.h"
#include "mongoc-bulk-operation-private.h"
#include "mongoc-read-concern-private.h"
#include "mongoc-write-concern-private.h"
#include "mongoc-uri-private.h"
#include "mongoc-trace.h"
/* PHP Core stuff */
#include <php.h>
#include <php_ini.h>
#include <ext/standard/info.h>
#include <ext/standard/file.h>
#include <Zend/zend_hash.h>
#include <Zend/zend_interfaces.h>
#include <Zend/zend_exceptions.h>
#include <ext/spl/spl_iterators.h>
#include <ext/spl/spl_exceptions.h>
/* Stream wrapper */
#include <main/php_streams.h>
#include <main/php_network.h>
/* Debug log writing */
#include <main/php_open_temporary_file.h>
/* For formating timestamp in the log */
#include <ext/date/php_date.h>
/* String manipulation */
#include <Zend/zend_string.h>
/* PHP array helpers */
#include "php_array_api.h"
/* For our stream verifications */
#include <openssl/x509.h>
/* Our Compatability header */
#include "phongo_compat.h"
/* Our stuffz */
#include "php_phongo.h"
#include "php_bson.h"
#include "php-ssl.h"
#undef MONGOC_LOG_DOMAIN
#define MONGOC_LOG_DOMAIN "PHONGO"
#define PHONGO_DEBUG_INI "mongodb.debug"
#define PHONGO_DEBUG_INI_DEFAULT ""
#define PHONGO_STREAM_BUFFER_SIZE 4096
ZEND_DECLARE_MODULE_GLOBALS(mongodb)
#if PHP_VERSION_ID >= 70000
#if defined(ZTS) && defined(COMPILE_DL_MONGODB)
ZEND_TSRMLS_CACHE_DEFINE();
#endif
#endif
/* {{{ phongo_std_object_handlers */
zend_object_handlers phongo_std_object_handlers;
PHONGO_API zend_object_handlers *phongo_get_std_object_handlers(void)
{
return &phongo_std_object_handlers;
}
/* }}} */
/* {{{ Error reporting and logging */
zend_class_entry* phongo_exception_from_phongo_domain(php_phongo_error_domain_t domain)
{
switch (domain) {
case PHONGO_ERROR_INVALID_ARGUMENT:
return php_phongo_invalidargumentexception_ce;
case PHONGO_ERROR_LOGIC:
return php_phongo_logicexception_ce;
case PHONGO_ERROR_RUNTIME:
return php_phongo_runtimeexception_ce;
case PHONGO_ERROR_UNEXPECTED_VALUE:
return php_phongo_unexpectedvalueexception_ce;
case PHONGO_ERROR_MONGOC_FAILED:
return php_phongo_runtimeexception_ce;
case PHONGO_ERROR_WRITE_FAILED:
return php_phongo_bulkwriteexception_ce;
case PHONGO_ERROR_CONNECTION_FAILED:
return php_phongo_connectionexception_ce;
}
MONGOC_ERROR("Resolving unknown phongo error domain: %d", domain);
return php_phongo_runtimeexception_ce;
}
zend_class_entry* phongo_exception_from_mongoc_domain(uint32_t /* mongoc_error_domain_t */ domain, uint32_t /* mongoc_error_code_t */ code)
{
switch(code) {
case 50: /* ExceededTimeLimit */
return php_phongo_executiontimeoutexception_ce;
case MONGOC_ERROR_STREAM_SOCKET:
case MONGOC_ERROR_SERVER_SELECTION_FAILURE:
return php_phongo_connectiontimeoutexception_ce;
case MONGOC_ERROR_CLIENT_AUTHENTICATE:
return php_phongo_authenticationexception_ce;
case MONGOC_ERROR_STREAM_INVALID_TYPE:
case MONGOC_ERROR_STREAM_INVALID_STATE:
case MONGOC_ERROR_STREAM_NAME_RESOLUTION:
case MONGOC_ERROR_STREAM_CONNECT:
case MONGOC_ERROR_STREAM_NOT_ESTABLISHED:
return php_phongo_connectionexception_ce;
case MONGOC_ERROR_CLIENT_NOT_READY:
case MONGOC_ERROR_CLIENT_TOO_BIG:
case MONGOC_ERROR_CLIENT_TOO_SMALL:
case MONGOC_ERROR_CLIENT_GETNONCE:
case MONGOC_ERROR_CLIENT_NO_ACCEPTABLE_PEER:
case MONGOC_ERROR_CLIENT_IN_EXHAUST:
case MONGOC_ERROR_PROTOCOL_INVALID_REPLY:
case MONGOC_ERROR_PROTOCOL_BAD_WIRE_VERSION:
case MONGOC_ERROR_CURSOR_INVALID_CURSOR:
case MONGOC_ERROR_QUERY_FAILURE:
/*case MONGOC_ERROR_PROTOCOL_ERROR:*/
case MONGOC_ERROR_BSON_INVALID:
case MONGOC_ERROR_MATCHER_INVALID:
case MONGOC_ERROR_NAMESPACE_INVALID:
case MONGOC_ERROR_COMMAND_INVALID_ARG:
case MONGOC_ERROR_COLLECTION_INSERT_FAILED:
case MONGOC_ERROR_GRIDFS_INVALID_FILENAME:
case MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND:
case MONGOC_ERROR_QUERY_NOT_TAILABLE:
return php_phongo_runtimeexception_ce;
}
switch (domain) {
case MONGOC_ERROR_CLIENT:
case MONGOC_ERROR_STREAM:
case MONGOC_ERROR_PROTOCOL:
case MONGOC_ERROR_CURSOR:
case MONGOC_ERROR_QUERY:
case MONGOC_ERROR_INSERT:
case MONGOC_ERROR_SASL:
case MONGOC_ERROR_BSON:
case MONGOC_ERROR_MATCHER:
case MONGOC_ERROR_NAMESPACE:
case MONGOC_ERROR_COMMAND:
case MONGOC_ERROR_COLLECTION:
case MONGOC_ERROR_GRIDFS:
/* FIXME: We don't have the Exceptions mocked yet.. */
#if 0
return phongo_ce_mongo_connection_exception;
#endif
default:
return php_phongo_runtimeexception_ce;
}
}
void phongo_throw_exception(php_phongo_error_domain_t domain TSRMLS_DC, const char *format, ...)
{
va_list args;
char *message;
int message_len;
va_start(args, format);
message_len = vspprintf(&message, 0, format, args);
zend_throw_exception(phongo_exception_from_phongo_domain(domain), message, 0 TSRMLS_CC);
efree(message);
va_end(args);
}
void phongo_throw_exception_from_bson_error_t(bson_error_t *error TSRMLS_DC)
{
zend_throw_exception(phongo_exception_from_mongoc_domain(error->domain, error->code), error->message, error->code TSRMLS_CC);
}
static void php_phongo_log(mongoc_log_level_t log_level, const char *log_domain, const char *message, void *user_data)
{
PHONGO_TSRMLS_FETCH_FROM_CTX(user_data);
(void)user_data;
switch(log_level) {
case MONGOC_LOG_LEVEL_ERROR:
case MONGOC_LOG_LEVEL_CRITICAL:
phongo_throw_exception(PHONGO_ERROR_MONGOC_FAILED TSRMLS_CC, "%s", message);
return;
case MONGOC_LOG_LEVEL_WARNING:
case MONGOC_LOG_LEVEL_MESSAGE:
case MONGOC_LOG_LEVEL_INFO:
case MONGOC_LOG_LEVEL_DEBUG:
case MONGOC_LOG_LEVEL_TRACE:
{
time_t t;
phongo_char *dt;
time(&t);
dt = php_format_date((char *)"Y-m-d\\TH:i:sP", strlen("Y-m-d\\TH:i:sP"), t, 0 TSRMLS_CC);
fprintf(MONGODB_G(debug_fd), "[%s] %10s: %-8s> %s\n", phongo_str(dt), log_domain, mongoc_log_level_str(log_level), message);
fflush(MONGODB_G(debug_fd));
efree(dt);
} break;
}
}
/* }}} */
/* {{{ Init objects */
static void phongo_cursor_init(zval *return_value, mongoc_cursor_t *cursor, mongoc_client_t *client TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_t *intern;
object_init_ex(return_value, php_phongo_cursor_ce);
intern = Z_CURSOR_OBJ_P(return_value);
intern->cursor = cursor;
intern->server_id = mongoc_cursor_get_hint(cursor);
intern->client = client;
} /* }}} */
void phongo_server_init(zval *return_value, mongoc_client_t *client, int server_id TSRMLS_DC) /* {{{ */
{
php_phongo_server_t *server;
object_init_ex(return_value, php_phongo_server_ce);
server = Z_SERVER_OBJ_P(return_value);
server->client = client;
server->server_id = server_id;
}
/* }}} */
void phongo_readconcern_init(zval *return_value, const mongoc_read_concern_t *read_concern TSRMLS_DC) /* {{{ */
{
php_phongo_readconcern_t *intern;
object_init_ex(return_value, php_phongo_readconcern_ce);
intern = Z_READCONCERN_OBJ_P(return_value);
intern->read_concern = mongoc_read_concern_copy(read_concern);
}
/* }}} */
void phongo_readpreference_init(zval *return_value, const mongoc_read_prefs_t *read_prefs TSRMLS_DC) /* {{{ */
{
php_phongo_readpreference_t *intern;
object_init_ex(return_value, php_phongo_readpreference_ce);
intern = Z_READPREFERENCE_OBJ_P(return_value);
intern->read_preference = mongoc_read_prefs_copy(read_prefs);
}
/* }}} */
void phongo_writeconcern_init(zval *return_value, const mongoc_write_concern_t *write_concern TSRMLS_DC) /* {{{ */
{
php_phongo_writeconcern_t *intern;
object_init_ex(return_value, php_phongo_writeconcern_ce);
intern = Z_WRITECONCERN_OBJ_P(return_value);
intern->write_concern = mongoc_write_concern_copy(write_concern);
}
/* }}} */
int32_t phongo_bson_find_as_int32(bson_t *bson, const char *key, int32_t fallback)
{
bson_iter_t iter;
if (bson_iter_init_find(&iter, bson, key) && BSON_ITER_HOLDS_INT32(&iter)) {
return bson_iter_int32(&iter);
}
return fallback;
}
bool phongo_bson_find_as_bool(bson_t *bson, const char *key, bool fallback)
{
bson_iter_t iter;
if (bson_iter_init_find(&iter, bson, key) && BSON_ITER_HOLDS_BOOL(&iter)) {
return bson_iter_bool(&iter);
}
return fallback;
}
void phongo_bson_iter_as_document(const bson_iter_t *iter, uint32_t *document_len, const uint8_t **document)
{
*document = NULL;
*document_len = 0;
if (BSON_ITER_HOLDS_DOCUMENT(iter) || BSON_ITER_HOLDS_ARRAY(iter)) {
memcpy (document_len, (iter->raw + iter->d1), sizeof (*document_len));
*document_len = BSON_UINT32_FROM_LE (*document_len);
*document = (iter->raw + iter->d1);
}
}
bool phongo_query_init(php_phongo_query_t *query, bson_t *filter, bson_t *options TSRMLS_DC) /* {{{ */
{
bson_iter_t iter;
if (options) {
query->batch_size = phongo_bson_find_as_int32(options, "batchSize", 0);
query->limit = phongo_bson_find_as_int32(options, "limit", 0);
query->skip = phongo_bson_find_as_int32(options, "skip", 0);
query->flags = 0;
query->flags |= phongo_bson_find_as_bool(options, "tailable", false) ? MONGOC_QUERY_TAILABLE_CURSOR : 0;
query->flags |= phongo_bson_find_as_bool(options, "slaveOk", false) ? MONGOC_QUERY_SLAVE_OK : 0;
query->flags |= phongo_bson_find_as_bool(options, "oplogReplay", false) ? MONGOC_QUERY_OPLOG_REPLAY : 0;
query->flags |= phongo_bson_find_as_bool(options, "noCursorTimeout", false) ? MONGOC_QUERY_NO_CURSOR_TIMEOUT : 0;
query->flags |= phongo_bson_find_as_bool(options, "awaitData", false) ? MONGOC_QUERY_AWAIT_DATA : 0;
query->flags |= phongo_bson_find_as_bool(options, "exhaust", false) ? MONGOC_QUERY_EXHAUST : 0;
query->flags |= phongo_bson_find_as_bool(options, "partial", false) ? MONGOC_QUERY_PARTIAL : 0;
if (bson_iter_init_find(&iter, options, "modifiers")) {
uint32_t len = 0;
const uint8_t *data = NULL;
if (! (BSON_ITER_HOLDS_DOCUMENT (&iter) || BSON_ITER_HOLDS_ARRAY (&iter))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected modifiers to be array or object, %d given", bson_iter_type(&iter));
return false;
}
bson_iter_document(&iter, &len, &data);
if (len) {
bson_t tmp;
bson_init_static(&tmp, data, len);
bson_copy_to_excluding_noinit(&tmp, query->query, "not-used-value", NULL);
bson_destroy (&tmp);
}
}
if (bson_iter_init_find(&iter, options, "projection")) {
uint32_t len = 0;
const uint8_t *data = NULL;
if (! (BSON_ITER_HOLDS_DOCUMENT (&iter) || BSON_ITER_HOLDS_ARRAY (&iter))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected projection to be array or object, %d given", bson_iter_type(&iter));
return false;
}
bson_iter_document(&iter, &len, &data);
if (len) {
query->selector = bson_new_from_data(data, len);
}
}
if (bson_iter_init_find(&iter, options, "sort")) {
uint32_t len = 0;
const uint8_t *data = NULL;
if (! (BSON_ITER_HOLDS_DOCUMENT (&iter) || BSON_ITER_HOLDS_ARRAY (&iter))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected sort to be array or object, %d given", bson_iter_type(&iter));
return false;
}
phongo_bson_iter_as_document(&iter, &len, &data);
if (len) {
bson_t tmp;
bson_init_static(&tmp, data, len);
bson_append_document(query->query, "$orderby", -1, &tmp);
bson_destroy(&tmp);
}
}
}
BSON_APPEND_DOCUMENT(query->query, "$query", filter);
return true;
} /* }}} */
zend_bool phongo_writeconcernerror_init(zval *return_value, bson_t *bson TSRMLS_DC) /* {{{ */
{
bson_iter_t iter;
php_phongo_writeconcernerror_t *writeconcernerror;
writeconcernerror = Z_WRITECONCERNERROR_OBJ_P(return_value);
if (bson_iter_init_find(&iter, bson, "code") && BSON_ITER_HOLDS_INT32(&iter)) {
writeconcernerror->code = bson_iter_int32(&iter);
}
if (bson_iter_init_find(&iter, bson, "errmsg") && BSON_ITER_HOLDS_UTF8(&iter)) {
writeconcernerror->message = bson_iter_dup_utf8(&iter, NULL);
}
if (bson_iter_init_find(&iter, bson, "errInfo") && BSON_ITER_HOLDS_DOCUMENT(&iter)) {
uint32_t len;
const uint8_t *data;
bson_iter_document(&iter, &len, &data);
if (!data) {
return false;
}
if (!phongo_bson_to_zval(data, len, &writeconcernerror->info)) {
zval_ptr_dtor(&writeconcernerror->info);
#if PHP_VERSION_ID >= 70000
ZVAL_UNDEF(&writeconcernerror->info);
#else
writeconcernerror->info = NULL;
#endif
return false;
}
}
return true;
} /* }}} */
zend_bool phongo_writeerror_init(zval *return_value, bson_t *bson TSRMLS_DC) /* {{{ */
{
bson_iter_t iter;
php_phongo_writeerror_t *writeerror;
writeerror = Z_WRITEERROR_OBJ_P(return_value);
if (bson_iter_init_find(&iter, bson, "code") && BSON_ITER_HOLDS_INT32(&iter)) {
writeerror->code = bson_iter_int32(&iter);
}
if (bson_iter_init_find(&iter, bson, "errmsg") && BSON_ITER_HOLDS_UTF8(&iter)) {
writeerror->message = bson_iter_dup_utf8(&iter, NULL);
}
if (bson_iter_init_find(&iter, bson, "errInfo")) {
bson_t info;
bson_init(&info);
bson_append_iter(&info, NULL, 0, &iter);
if (!phongo_bson_to_zval(bson_get_data(&info), info.len, &writeerror->info)) {
zval_ptr_dtor(&writeerror->info);
#if PHP_VERSION_ID >= 70000
ZVAL_UNDEF(&writeerror->info);
#else
writeerror->info = NULL;
#endif
return false;
}
}
if (bson_iter_init_find(&iter, bson, "index") && BSON_ITER_HOLDS_INT32(&iter)) {
writeerror->index = bson_iter_int32(&iter);
}
return true;
} /* }}} */
php_phongo_writeresult_t *phongo_writeresult_init(zval *return_value, bson_t *reply, mongoc_client_t *client, int server_id TSRMLS_DC) /* {{{ */
{
php_phongo_writeresult_t *writeresult;
object_init_ex(return_value, php_phongo_writeresult_ce);
writeresult = Z_WRITERESULT_OBJ_P(return_value);
writeresult->reply = bson_copy(reply);
writeresult->client = client;
writeresult->server_id = server_id;
return writeresult;
} /* }}} */
/* }}} */
/* {{{ CRUD */
/* Splits a namespace name into the database and collection names, allocated with estrdup. */
bool phongo_split_namespace(const char *namespace, char **dbname, char **cname) /* {{{ */
{
char *dot = strchr(namespace, '.');
if (!dot) {
return false;
}
if (cname) {
*cname = estrdup(namespace + (dot - namespace) + 1);
}
if (dbname) {
*dbname = estrndup(namespace, dot - namespace);
}
return true;
} /* }}} */
mongoc_bulk_operation_t *phongo_bulkwrite_init(zend_bool ordered) { /* {{{ */
return mongoc_bulk_operation_new(ordered);
} /* }}} */
bool phongo_execute_write(mongoc_client_t *client, const char *namespace, mongoc_bulk_operation_t *bulk, const mongoc_write_concern_t *write_concern, int server_id, zval *return_value, int return_value_used TSRMLS_DC) /* {{{ */
{
bson_error_t error;
char *dbname;
char *collname;
int success;
bson_t reply = BSON_INITIALIZER;
php_phongo_writeresult_t *writeresult;
if (!phongo_split_namespace(namespace, &dbname, &collname)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s: %s", "Invalid namespace provided", namespace);
return false;
}
mongoc_bulk_operation_set_database(bulk, dbname);
mongoc_bulk_operation_set_collection(bulk, collname);
mongoc_bulk_operation_set_client(bulk, client);
/* If a write concern was not specified, libmongoc will use the client's
* write concern; however, we should still fetch it for the write result. */
if (write_concern) {
mongoc_bulk_operation_set_write_concern(bulk, write_concern);
} else {
write_concern = mongoc_client_get_write_concern(client);
}
efree(dbname);
efree(collname);
if (server_id > 0) {
mongoc_bulk_operation_set_hint(bulk, server_id);
}
success = mongoc_bulk_operation_execute(bulk, &reply, &error);
/* Write succeeded and the user doesn't care for the results */
if (success && !return_value_used) {
bson_destroy(&reply);
return true;
}
/* Check for connection related exceptions */
if (EG(exception)) {
bson_destroy(&reply);
return false;
}
writeresult = phongo_writeresult_init(return_value, &reply, client, bulk->hint TSRMLS_CC);
writeresult->write_concern = mongoc_write_concern_copy(write_concern);
/* The Write failed */
if (!success) {
if (error.domain == MONGOC_ERROR_COMMAND || error.domain == MONGOC_ERROR_WRITE_CONCERN) {
phongo_throw_exception(PHONGO_ERROR_WRITE_FAILED TSRMLS_CC, "%s", error.message);
phongo_add_exception_prop(ZEND_STRL("writeResult"), return_value TSRMLS_CC);
} else {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
}
}
bson_destroy(&reply);
return success;
} /* }}} */
int phongo_execute_query(mongoc_client_t *client, const char *namespace, const php_phongo_query_t *query, const mongoc_read_prefs_t *read_preference, int server_id, zval *return_value, int return_value_used TSRMLS_DC) /* {{{ */
{
const bson_t *doc = NULL;
mongoc_cursor_t *cursor;
char *dbname;
char *collname;
mongoc_collection_t *collection;
if (!phongo_split_namespace(namespace, &dbname, &collname)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s: %s", "Invalid namespace provided", namespace);
return false;
}
collection = mongoc_client_get_collection(client, dbname, collname);
efree(dbname);
efree(collname);
if (query->read_concern) {
mongoc_collection_set_read_concern(collection, query->read_concern);
}
cursor = mongoc_collection_find(collection, query->flags, query->skip, query->limit, query->batch_size, query->query, query->selector, read_preference);
mongoc_collection_destroy(collection);
/* mongoc issues a warning we need to catch somehow */
if (!cursor) {
phongo_throw_exception(PHONGO_ERROR_MONGOC_FAILED TSRMLS_CC, "%s", "FIXME: Couldn't create cursor...");
return false;
}
if (server_id > 0) {
cursor->hint = server_id;
}
if (!mongoc_cursor_next(cursor, &doc)) {
bson_error_t error;
/* Check for connection related exceptions */
if (EG(exception)) {
mongoc_cursor_destroy(cursor);
return false;
}
/* Could simply be no docs, which is not an error */
if (mongoc_cursor_error(cursor, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
mongoc_cursor_destroy(cursor);
return false;
}
}
if (!return_value_used) {
mongoc_cursor_destroy(cursor);
return true;
}
phongo_cursor_init(return_value, cursor, client TSRMLS_CC);
return true;
} /* }}} */
int phongo_execute_command(mongoc_client_t *client, const char *db, const bson_t *command, const mongoc_read_prefs_t *read_preference, int server_id, zval *return_value, int return_value_used TSRMLS_DC) /* {{{ */
{
mongoc_cursor_t *cursor;
const bson_t *doc;
bson_iter_t iter;
bson_iter_t child;
cursor = mongoc_client_command(client, db, MONGOC_QUERY_NONE, 0, 1, 0, command, NULL, read_preference);
if (server_id > 0) {
cursor->hint = server_id;
}
if (!mongoc_cursor_next(cursor, &doc)) {
bson_error_t error;
/* Check for connection related exceptions */
if (EG(exception)) {
mongoc_cursor_destroy(cursor);
return false;
}
if (mongoc_cursor_error(cursor, &error)) {
mongoc_cursor_destroy(cursor);
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
return false;
}
}
if (!return_value_used) {
mongoc_cursor_destroy(cursor);
return true;
}
/* This code is adapated from _mongoc_cursor_cursorid_prime(), but we avoid
* advancing the cursor, since we are already positioned at the first result
* after the error checking above. */
if (bson_iter_init_find(&iter, doc, "cursor") && BSON_ITER_HOLDS_DOCUMENT(&iter) && bson_iter_recurse(&iter, &child)) {
mongoc_cursor_cursorid_t *cid;
bson_t empty = BSON_INITIALIZER;
_mongoc_cursor_cursorid_init(cursor, &empty);
cursor->limit = 0;
cid = cursor->iface_data;
cid->in_batch = true;
bson_destroy (&empty);
while (bson_iter_next(&child)) {
if (BSON_ITER_IS_KEY(&child, "id")) {
cursor->rpc.reply.cursor_id = bson_iter_as_int64(&child);
} else if (BSON_ITER_IS_KEY(&child, "ns")) {
const char *ns;
ns = bson_iter_utf8(&child, &cursor->nslen);
bson_strncpy(cursor->ns, ns, sizeof cursor->ns);
} else if (BSON_ITER_IS_KEY(&child, "firstBatch")) {
if (BSON_ITER_HOLDS_ARRAY(&child) && bson_iter_recurse(&child, &cid->batch_iter)) {
cid->in_batch = true;
}
}
}
cursor->is_command = false;
/* The cursor's current element is the command's response document.
* Advance once so that the cursor is positioned at the first document
* within the command cursor's result set.
*/
mongoc_cursor_next(cursor, &doc);
}
phongo_cursor_init(return_value, cursor, client TSRMLS_CC);
return true;
} /* }}} */
/* }}} */
/* {{{ Stream vtable */
void phongo_stream_destroy(mongoc_stream_t *stream_wrap) /* {{{ */
{
php_phongo_stream_socket *base_stream = (php_phongo_stream_socket *)stream_wrap;
if (base_stream->stream) {
MONGOC_DEBUG("Not destroying RSRC#%d", PHONGO_STREAM_ID(base_stream->stream));
} else {
MONGOC_DEBUG("Wrapped stream already destroyed");
}
/*
* DON'T DO ANYTHING TO THE INTERNAL base_stream->stream
* The stream should not be closed during normal dtor -- as we want it to
* survive until next request.
* We only clean it up on failure and (implicitly) MSHUTDOWN
*/
efree(base_stream);
} /* }}} */
void phongo_stream_failed(mongoc_stream_t *stream_wrap) /* {{{ */
{
php_phongo_stream_socket *base_stream = (php_phongo_stream_socket *)stream_wrap;
if (base_stream->stream) {
#if PHP_VERSION_ID < 70000
PHONGO_TSRMLS_FETCH_FROM_CTX(base_stream->tsrm_ls);
#endif
MONGOC_DEBUG("Destroying RSRC#%d", PHONGO_STREAM_ID(base_stream->stream));
php_stream_free(base_stream->stream, PHP_STREAM_FREE_CLOSE_PERSISTENT | PHP_STREAM_FREE_RSRC_DTOR);
base_stream->stream = NULL;
}
efree(base_stream);
} /* }}} */
int phongo_stream_close(mongoc_stream_t *stream_wrap) /* {{{ */
{
php_phongo_stream_socket *base_stream = (php_phongo_stream_socket *)stream_wrap;
MONGOC_DEBUG("Closing RSRC#%d", PHONGO_STREAM_ID(base_stream->stream));
if (base_stream->stream) {
#if PHP_VERSION_ID < 70000
TSRMLS_FETCH_FROM_CTX(base_stream->tsrm_ls);
#endif
MONGOC_DEBUG("Destroying RSRC#%d", PHONGO_STREAM_ID(base_stream->stream));
php_stream_free(base_stream->stream, PHP_STREAM_FREE_CLOSE_PERSISTENT | PHP_STREAM_FREE_RSRC_DTOR);
base_stream->stream = NULL;
}
return 0;
} /* }}} */
void php_phongo_set_timeout(php_phongo_stream_socket *base_stream, int32_t timeout_msec) /* {{{ */
{
struct timeval rtimeout = {0, 0};
PHONGO_TSRMLS_FETCH_FROM_CTX(base_stream->tsrm_ls);
if (timeout_msec > 0) {
rtimeout.tv_sec = timeout_msec / 1000;
rtimeout.tv_usec = (timeout_msec % 1000) * 1000;
}
php_stream_set_option(base_stream->stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &rtimeout);
MONGOC_DEBUG("Setting timeout to: %d", timeout_msec);
} /* }}} */
/* This is blatantr copy of _mongoc_stream_tls_writev
* https://github.com/mongodb/mongo-c-driver/blob/4ebba3d84286df3867bad89358eb6ae956e62a59/src/mongoc/mongoc-stream-tls.c#L500
*/
ssize_t phongo_stream_writev(mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, int32_t timeout_msec) /* {{{ */
{
char buf[PHONGO_STREAM_BUFFER_SIZE];
ssize_t ret = 0;
ssize_t child_ret;
size_t i;
size_t iov_pos = 0;
/* There's a bit of a dance to coalesce vectorized writes into
* PHONGO_STREAM_BUFFER_SIZE'd writes to avoid lots of small tls
* packets.
*
* The basic idea is that we want to combine writes in the buffer if they're
* smaller than the buffer, flushing as it gets full. For larger writes, or
* the last write in the iovec array, we want to ignore the buffer and just
* write immediately. We take care of doing buffer writes by re-invoking
* ourself with a single iovec_t, pointing at our stack buffer.
*/
char *buf_head = buf;
char *buf_tail = buf;
char *buf_end = buf + PHONGO_STREAM_BUFFER_SIZE;
size_t bytes;
char *to_write = NULL;
size_t to_write_len;
php_phongo_stream_socket *base_stream = (php_phongo_stream_socket *)stream;
PHONGO_TSRMLS_FETCH_FROM_CTX(base_stream->tsrm_ls);
php_phongo_set_timeout(base_stream, timeout_msec);
BSON_ASSERT (iov);
BSON_ASSERT (iovcnt);
for (i = 0; i < iovcnt; i++) {
iov_pos = 0;
while (iov_pos < iov[i].iov_len) {
if (buf_head != buf_tail ||
((i + 1 < iovcnt) &&
((buf_end - buf_tail) > (iov[i].iov_len - iov_pos)))) {
/* If we have either of:
* - buffered bytes already
* - another iovec to send after this one and we don't have more
* bytes to send than the size of the buffer.
*
* copy into the buffer */
bytes = BSON_MIN (iov[i].iov_len - iov_pos, buf_end - buf_tail);
memcpy (buf_tail, iov[i].iov_base + iov_pos, bytes);
buf_tail += bytes;
iov_pos += bytes;
if (buf_tail == buf_end) {
/* If we're full, request send */
to_write = buf_head;
to_write_len = buf_tail - buf_head;
buf_tail = buf_head = buf;
}
} else {
/* Didn't buffer, so just write it through */
to_write = (char *)iov[i].iov_base + iov_pos;
to_write_len = iov[i].iov_len - iov_pos;
iov_pos += to_write_len;
}
if (to_write) {
/* We get here if we buffered some bytes and filled the buffer, or
* if we didn't buffer and have to send out of the iovec */
child_ret = php_stream_write(base_stream->stream, to_write, to_write_len);
if (child_ret < 0) {
/* Buffer write failed, just return the error */
return child_ret;
}
ret += child_ret;
if (child_ret < to_write_len) {
/* we timed out, so send back what we could send */
return ret;
}
to_write = NULL;
}
}
}
if (buf_head != buf_tail) {
/* If we have any bytes buffered, send */
child_ret = php_stream_write(base_stream->stream, buf_head, buf_tail - buf_head);
if (child_ret < 0) {
return child_ret;
}
ret += child_ret;
}
return ret;
} /* }}} */
ssize_t phongo_stream_readv(mongoc_stream_t *stream, mongoc_iovec_t *iov, size_t iovcnt, size_t min_bytes, int32_t timeout_msec) /* {{{ */
{
php_phongo_stream_socket *base_stream = (php_phongo_stream_socket *)stream;
ssize_t ret = 0;
ssize_t read;
size_t cur = 0;
PHONGO_TSRMLS_FETCH_FROM_CTX(base_stream->tsrm_ls);
php_phongo_set_timeout(base_stream, timeout_msec);
do {
read = php_stream_read(base_stream->stream, iov[cur].iov_base, iov[cur].iov_len);
MONGOC_DEBUG("Reading got: %zd wanted: %zd", read, min_bytes);
if (read <= 0) {
if (ret >= (ssize_t)min_bytes) {
break;
}
return -1;
}
ret += read;
while ((cur < iovcnt) && (read >= (ssize_t)iov[cur].iov_len)) {
read -= iov[cur++].iov_len;
}
if (cur == iovcnt) {
break;
}
if (ret >= (ssize_t)min_bytes) {
break;
}
iov[cur].iov_base = ((char *)iov[cur].iov_base) + read;
iov[cur].iov_len -= read;
} while(1);
return ret;
} /* }}} */
int phongo_stream_setsockopt(mongoc_stream_t *stream, int level, int optname, void *optval, socklen_t optlen) /* {{{ */
{
php_phongo_stream_socket *base_stream = (php_phongo_stream_socket *)stream;
int socket = ((php_netstream_data_t *)base_stream->stream->abstract)->socket;
return setsockopt (socket, level, optname, optval, optlen);
} /* }}} */
bool phongo_stream_socket_check_closed(mongoc_stream_t *stream) /* {{{ */
{
php_phongo_stream_socket *base_stream = (php_phongo_stream_socket *)stream;
PHONGO_TSRMLS_FETCH_FROM_CTX(base_stream->tsrm_ls);
return PHP_STREAM_OPTION_RETURN_OK != php_stream_set_option(base_stream->stream, PHP_STREAM_OPTION_CHECK_LIVENESS, 0, NULL);
} /* }}} */
ssize_t phongo_stream_poll (mongoc_stream_poll_t *streams, size_t nstreams, int32_t timeout) /* {{{ */
{
php_pollfd *fds = NULL;
size_t i;
ssize_t rval = -1;
TSRMLS_FETCH();
fds = emalloc(sizeof(*fds) * nstreams);
for (i = 0; i < nstreams; i++) {
php_socket_t this_fd;
if (php_stream_cast(((php_phongo_stream_socket *)streams[i].stream)->stream, PHP_STREAM_AS_FD_FOR_SELECT | PHP_STREAM_CAST_INTERNAL, (void*)&this_fd, 0) == SUCCESS && this_fd >= 0) {
fds[i].fd = this_fd;
fds[i].events = streams[i].events;
fds[i].revents = 0;
}
}
rval = php_poll2(fds, nstreams, timeout);
if (rval > 0) {
for (i = 0; i < nstreams; i++) {
streams[i].revents = fds[i].revents;
}
}
efree(fds);
return rval;
} /* }}} */
#if PHP_VERSION_ID < 50600
int php_mongo_verify_hostname(const char *hostname, X509 *cert TSRMLS_DC)
{
if (php_mongo_matches_san_list(cert, hostname) == SUCCESS) {
return SUCCESS;
}
if (php_mongo_matches_common_name(cert, hostname TSRMLS_CC) == SUCCESS) {
return SUCCESS;
}
return FAILURE;
}
int php_phongo_peer_verify(php_stream *stream, X509 *cert, const char *hostname, bson_error_t *error TSRMLS_DC)
{