This repository was archived by the owner on Sep 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathbson.cc
1820 lines (1552 loc) · 63.2 KB
/
bson.cc
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
//===========================================================================
#include <stdarg.h>
#include <cstdlib>
#include <cstring>
#include <string.h>
#include <stdlib.h>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#endif
#include <v8.h>
// this and the above block must be around the v8.h header otherwise
// v8 is not happy
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include <node.h>
#include <node_version.h>
#include <node_buffer.h>
#include <cmath>
#include <iostream>
#include <limits>
#include <vector>
#include <errno.h>
#if defined(__sun) || defined(_AIX)
#include <alloca.h>
#endif
#include "utf8decoder.h"
#include "bson.h"
void die(const char *message) {
if(errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
bool ValidateEncoding(const uint8_t* bytes, size_t length) {
Utf8DfaDecoder::State state = Utf8DfaDecoder::State::kAccept;
uint32_t throw_away = 0;
for (size_t i = 0; i < length && state != Utf8DfaDecoder::State::kReject; i++) {
Utf8DfaDecoder::Decode(bytes[i], &state, &throw_away);
}
return state == Utf8DfaDecoder::State::kAccept;
}
//===========================================================================
// Equality Objects
static const char* LONG_CLASS_NAME = "Long";
static const char* OBJECT_ID_CLASS_NAME = "ObjectID";
static const char* BINARY_CLASS_NAME = "Binary";
static const char* CODE_CLASS_NAME = "Code";
static const char* DBREF_CLASS_NAME = "DBRef";
static const char* SYMBOL_CLASS_NAME = "Symbol";
static const char* DOUBLE_CLASS_NAME = "Double";
static const char* TIMESTAMP_CLASS_NAME = "Timestamp";
static const char* MIN_KEY_CLASS_NAME = "MinKey";
static const char* MAX_KEY_CLASS_NAME = "MaxKey";
static const char* REGEXP_CLASS_NAME = "BSONRegExp";
static const char* DECIMAL128_CLASS_NAME = "Decimal128";
static const char* INT32_CLASS_NAME = "Int32";
// Equality speed up comparison objects
static const char* BSONTYPE_PROPERTY_NAME = "_bsontype";
static const char* LONG_LOW_PROPERTY_NAME = "low_";
static const char* LONG_HIGH_PROPERTY_NAME = "high_";
static const char* OBJECT_ID_ID_PROPERTY_NAME = "id";
static const char* BINARY_POSITION_PROPERTY_NAME = "position";
static const char* BINARY_SUBTYPE_PROPERTY_NAME = "sub_type";
static const char* BINARY_BUFFER_PROPERTY_NAME = "buffer";
static const char* SYMBOL_VALUE_PROPERTY_NAME = "value";
static const char* DECIMAL128_VALUE_PROPERTY_NAME = "bytes";
static const char* DOUBLE_VALUE_PROPERTY_NAME = "value";
static const char* INT32_VALUE_PROPERTY_NAME = "value";
static const char* DBREF_REF_PROPERTY_NAME = "$ref";
static const char* DBREF_ID_REF_PROPERTY_NAME = "$id";
static const char* DBREF_DB_REF_PROPERTY_NAME = "$db";
static const char* DBREF_NAMESPACE_PROPERTY_NAME = "collection";
static const char* DBREF_DB_PROPERTY_NAME = "db";
static const char* DBREF_FIELDS_PROPERTY_NAME = "fields";
static const char* DBREF_OID_PROPERTY_NAME = "oid";
static const char* REGEX_PATTERN_PROPERTY_NAME = "pattern";
static const char* REGEX_OPTIONS_PROPERTY_NAME = "options";
static const char* CODE_CODE_PROPERTY_NAME = "code";
static const char* CODE_SCOPE_PROPERTY_NAME = "scope";
static const char* TO_BSON_PROPERTY_NAME = "toBSON";
static const char* TO_OBJECT_PROPERTY_NAME = "toObject";
// Equality Object for Map
static const char* MAP_NAME = "[object Map]";
void DataStream::WriteObjectId(const Local<Object>& object, const Local<String>& key)
{
uint16_t buffer[12];
Nan::MaybeLocal<v8::Value> obj = NanGet(object, key);
if(node::Buffer::HasInstance(obj.ToLocalChecked())) {
uint32_t length = (uint32_t)node::Buffer::Length(obj.ToLocalChecked());
this->WriteData(node::Buffer::Data(obj.ToLocalChecked()), length);
} else {
NanGet(object, key)->ToString()->Write(buffer, 0, 12);
for(uint32_t i = 0; i < 12; ++i)
{
*p++ = (char) buffer[i];
}
}
}
void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...)
{
va_list args;
va_start(args, format);
char* string = (char*) malloc(allocationSize);
if(string == NULL) die("Failed to allocate ThrowAllocatedStringException");
vsprintf(string, format, args);
va_end(args);
throw string;
}
void DataStream::CheckKey(const Local<String>& keyName)
{
size_t keyLength = keyName->Utf8Length();
if(keyLength == 0) return;
// Allocate space for the key, do not need to zero terminate as WriteUtf8 does it
char* keyStringBuffer = (char*) alloca(keyLength + 1);
// Write the key to the allocated buffer
keyName->WriteUtf8(keyStringBuffer);
// Check for the zero terminator
char* terminator = strchr(keyStringBuffer, 0x00);
// If the location is not at the end of the string we've got an illegal 0x00 byte somewhere
if(terminator != &keyStringBuffer[keyLength]) {
ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer);
}
if(keyStringBuffer[0] == '$')
{
ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer);
}
if(strchr(keyStringBuffer, '.') != NULL)
{
ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer);
}
}
void DataStream::CheckForIllegalString(const Local<String>& keyName)
{
size_t keyLength = keyName->Utf8Length();
if(keyLength == 0) return;
// Allocate space for the key, do not need to zero terminate as WriteUtf8 does it
char* keyStringBuffer = (char*) alloca(keyLength + 1);
// Write the key to the allocated buffer
keyName->WriteUtf8(keyStringBuffer);
// Check for the zero terminator
char* terminator = strchr(keyStringBuffer, 0x00);
// If the location is not at the end of the string we've got an illegal 0x00 byte somewhere
if(terminator != &keyStringBuffer[keyLength]) {
ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer);
}
}
template<typename T> void BSONSerializer<T>::SerializeDocument(const Local<Value>& value)
{
bool valid = this->BeginDocument();
if(!valid) {
return ThrowAllocatedStringException(64, "cyclic dependency detected");
}
void* documentSize = this->BeginWriteSize();
Local<Object> object = bson->GetSerializeObject(value);
Local<String> propertyName;
Local<Value> propertyValue;
Local<String> str = object->ToString();
if(!str->StrictEquals(Nan::New(bson->MAP_NAME_STR)->ToString())) {
// Get the object property names
Local<Array> propertyNames = object->GetPropertyNames();
// Length of the property
int propertyLength = propertyNames->Length();
for(int i = 0; i < propertyLength; ++i)
{
propertyName = NanGet(propertyNames, i)->ToString();
if(checkKeys) this->CheckKey(propertyName);
propertyValue = NanGet(object, propertyName);
// We are not serializing the function
if(!serializeFunctions && propertyValue->IsFunction()) {
continue;
}
// We are ignoring undefined values
if(ignoreUndefined && propertyValue->IsUndefined()) {
continue;
}
// Serialize the value
void* typeLocation = this->BeginWriteType();
this->WriteString(propertyName);
SerializeValue(typeLocation, propertyValue, false);
}
} else {
// Get the entries function
const Local<Value>& entries = NanGet(object, "entries");
if(!entries->IsFunction()) {
ThrowAllocatedStringException(64, "Map.entries is not a function");
}
// Get the iterator
Local<Object> iterator = Local<Function>::Cast(entries)->Call(object, 0, NULL)->ToObject();
// Check if we have the next value
const Local<Value>& next = NanGet(iterator, "next");
if(!next->IsFunction()) ThrowAllocatedStringException(64, "Map.iterator.next is not a function");
// Iterate until we are done
while(true) {
// Get the entry
Local<Object> entry = Local<Function>::Cast(next)->Call(iterator, 0, NULL)->ToObject();
// Check if we are done
if(NanGet(entry, "done")->ToBoolean()->Value()) {
break;
}
// Get the value object
Local<Object> value = NanGet(entry, "value")->ToObject();
// Not done then lets get the value items
propertyName = NanGet(value, "0")->ToString();
if(checkKeys) this->CheckKey(propertyName);
// Get the property value
propertyValue = NanGet(value, "1");
// We are not serializing the function
if(!serializeFunctions && propertyValue->IsFunction()) {
continue;
}
// We are ignoring undefined values
if(ignoreUndefined && propertyValue->IsUndefined()) {
continue;
}
// Serialize the value
void* typeLocation = this->BeginWriteType();
this->WriteString(propertyName);
SerializeValue(typeLocation, propertyValue, false);
}
}
this->WriteByte(0);
this->CommitSize(documentSize);
this->EndDocument();
}
template<typename T> void BSONSerializer<T>::SerializeArray(const Local<Value>& value)
{
void* documentSize = this->BeginWriteSize();
Local<Array> array = Local<Array>::Cast(value->ToObject());
uint32_t arrayLength = array->Length();
for(uint32_t i = 0; i < arrayLength; ++i)
{
void* typeLocation = this->BeginWriteType();
this->WriteUInt32String(i);
if(i >= preLoadedIndex) {
SerializeValue(typeLocation, NanGet(array, i), true);
} else {
SerializeValue(typeLocation, NanGet(array, BSON::indexesStrings[i]), true);
}
}
this->WriteByte(0);
this->CommitSize(documentSize);
}
// This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes.
// The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths)
// and ensures that there is always consistency between bytes counted and bytes written by design.
template<typename T> void BSONSerializer<T>::SerializeValue(void* typeLocation, const Local<Value> constValue, bool isArray)
{
Local<Value> value = constValue;
// Process all the values
if(value->IsNumber())
{
double doubleValue = value->NumberValue();
int intValue = (int) doubleValue;
if(intValue == doubleValue)
{
this->CommitType(typeLocation, BSON_TYPE_INT);
this->WriteInt32(intValue);
}
else
{
this->CommitType(typeLocation, BSON_TYPE_NUMBER);
this->WriteDouble(doubleValue);
}
}
else if(value->IsString())
{
this->CommitType(typeLocation, BSON_TYPE_STRING);
this->WriteLengthPrefixedString(value->ToString());
}
else if(value->IsDate())
{
this->CommitType(typeLocation, BSON_TYPE_DATE);
this->WriteInt64(value->NumberValue());
}
else if(value->IsBoolean())
{
this->CommitType(typeLocation, BSON_TYPE_BOOLEAN);
this->WriteBool(value);
}
else if(value->IsArray())
{
this->CommitType(typeLocation, BSON_TYPE_ARRAY);
SerializeArray(value);
}
else if(value->IsObject())
{
Local<Object> object = value->ToObject();
if(NanHas(object, BSONTYPE_PROPERTY_NAME))
{
const Local<String>& constructorString = NanGet(object, BSONTYPE_PROPERTY_NAME)->ToString();
if(Nan::New(bson->LONG_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_LONG);
this->WriteInt32(object, Nan::New(bson->LONG_LOW_PROPERTY_NAME_STR));
this->WriteInt32(object, Nan::New(bson->LONG_HIGH_PROPERTY_NAME_STR));
}
else if(Nan::New(bson->TIMESTAMP_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP);
this->WriteInt32(object, Nan::New(bson->LONG_LOW_PROPERTY_NAME_STR));
this->WriteInt32(object, Nan::New(bson->LONG_HIGH_PROPERTY_NAME_STR));
}
else if(Nan::New(bson->OBJECT_ID_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_OID);
this->WriteObjectId(object, Nan::New(bson->OBJECT_ID_ID_PROPERTY_NAME_STR));
}
else if(Nan::New(bson->BINARY_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_BINARY);
uint32_t length = NanGet(object, Nan::New(bson->BINARY_POSITION_PROPERTY_NAME_STR))->Uint32Value();
Local<Object> bufferObj = NanGet(object, Nan::New(bson->BINARY_BUFFER_PROPERTY_NAME_STR))->ToObject();
// Add the deprecated 02 type 4 bytes of size to total
if(NanGet(object, Nan::New(bson->BINARY_SUBTYPE_PROPERTY_NAME_STR))->Int32Value() == 0x02) {
length = length + 4;
}
this->WriteInt32(length);
this->WriteByte(object, Nan::New(bson->BINARY_SUBTYPE_PROPERTY_NAME_STR)); // write subtype
// If type 0x02 write the array length aswell
if(NanGet(object, Nan::New(bson->BINARY_SUBTYPE_PROPERTY_NAME_STR))->Int32Value() == 0x02) {
length = length - 4;
this->WriteInt32(length);
}
// Write the actual data
this->WriteData(node::Buffer::Data(bufferObj), length);
}
else if(Nan::New(bson->DECIMAL128_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_DECIMAL128);
// Get the bytes length
uint32_t length = (uint32_t)node::Buffer::Length(NanGet(object, Nan::New(bson->DECIMAL128_VALUE_PROPERTY_NAME_STR)));
// Get the bytes buffer object
Local<Object> bufferObj = NanGet(object, Nan::New(bson->DECIMAL128_VALUE_PROPERTY_NAME_STR))->ToObject();
// Write the actual decimal128 bytes
this->WriteData(node::Buffer::Data(bufferObj), length);
}
else if(Nan::New(bson->DOUBLE_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_NUMBER);
this->WriteDouble(object, Nan::New(bson->DOUBLE_VALUE_PROPERTY_NAME_STR));
}
else if(Nan::New(bson->INT32_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_INT);
this->WriteInt32(object, Nan::New(bson->INT32_VALUE_PROPERTY_NAME_STR));
}
else if(Nan::New(bson->SYMBOL_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_SYMBOL);
this->WriteLengthPrefixedString(NanGet(object, Nan::New(bson->SYMBOL_VALUE_PROPERTY_NAME_STR))->ToString());
}
else if(Nan::New(bson->CODE_CLASS_NAME_STR)->Equals(constructorString))
{
const Local<String>& function = NanGet(object, Nan::New(bson->CODE_CODE_PROPERTY_NAME_STR))->ToString();
// Does the code object have a defined scope
bool hasScope = NanHas(object, Nan::New(bson->CODE_SCOPE_PROPERTY_NAME_STR))
&& NanGet(object, Nan::New(bson->CODE_SCOPE_PROPERTY_NAME_STR))->IsObject()
&& !NanGet(object, Nan::New(bson->CODE_SCOPE_PROPERTY_NAME_STR))->IsNull();
if(hasScope)
{
const Local<Object>& scope = NanGet(object, Nan::New(bson->CODE_SCOPE_PROPERTY_NAME_STR))->ToObject();
this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE);
void* codeWidthScopeSize = this->BeginWriteSize();
this->WriteLengthPrefixedString(function->ToString());
SerializeDocument(scope);
this->CommitSize(codeWidthScopeSize);
}
else
{
this->CommitType(typeLocation, BSON_TYPE_CODE);
this->WriteLengthPrefixedString(function->ToString());
}
}
else if(Nan::New(bson->DBREF_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_OBJECT);
void* dbRefSize = this->BeginWriteSize();
void* refType = this->BeginWriteType();
this->WriteData("$ref", 5);
SerializeValue(refType, NanGet(object, Nan::New(bson->DBREF_NAMESPACE_PROPERTY_NAME_STR)), false);
void* idType = this->BeginWriteType();
this->WriteData("$id", 4);
SerializeValue(idType, NanGet(object, Nan::New(bson->DBREF_OID_PROPERTY_NAME_STR)), false);
const Local<Value>& refDbValue = NanGet(object, Nan::New(bson->DBREF_DB_PROPERTY_NAME_STR));
if(!refDbValue->IsUndefined())
{
void* dbType = this->BeginWriteType();
this->WriteData("$db", 4);
SerializeValue(dbType, refDbValue, false);
}
// serialize any other values
const Local<Value>& refFieldsValue = NanGet(object, Nan::New(bson->DBREF_FIELDS_PROPERTY_NAME_STR));
if (!refFieldsValue->IsUndefined()) {
Local<Object> fieldsObject = refFieldsValue->ToObject();
Local<Array> propertyNames = fieldsObject->GetPropertyNames();
// Length of the property
int propertyLength = propertyNames->Length();
for (int i = 0; i < propertyLength; ++i)
{
Local<String> propertyName = NanGet(propertyNames, i)->ToString();
Local<Value> propertyValue = NanGet(fieldsObject, propertyName);
// We are not serializing the function
if (!serializeFunctions && propertyValue->IsFunction()) {
continue;
}
// We are ignoring undefined values
if (ignoreUndefined && propertyValue->IsUndefined()) {
continue;
}
// Serialize the value
void* typeLocation = this->BeginWriteType();
this->WriteString(propertyName);
SerializeValue(typeLocation, propertyValue, false);
}
}
this->WriteByte(0);
this->CommitSize(dbRefSize);
}
else if(Nan::New(bson->REGEXP_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_REGEXP);
// Get the pattern string
Local<String> pattern = NanGet(object, Nan::New(bson->REGEX_PATTERN_PROPERTY_NAME_STR))->ToString();
// Validate if the pattern is valid
this->CheckForIllegalString(pattern);
// Write the 0 terminated string
this->WriteString(pattern);
// Get the options string
Local<String> options = NanGet(object, Nan::New(bson->REGEX_OPTIONS_PROPERTY_NAME_STR))->ToString();
// Validate if the options is valid
this->CheckForIllegalString(options);
// Write the 0 terminated string
this->WriteString(options);
}
else if(Nan::New(bson->MIN_KEY_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_MIN_KEY);
}
else if(Nan::New(bson->MAX_KEY_CLASS_NAME_STR)->Equals(constructorString))
{
this->CommitType(typeLocation, BSON_TYPE_MAX_KEY);
}
}
else if(value->IsFunction())
{
this->CommitType(typeLocation, BSON_TYPE_CODE);
this->WriteLengthPrefixedString(value->ToString());
}
else if(node::Buffer::HasInstance(value))
{
this->CommitType(typeLocation, BSON_TYPE_BINARY);
#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3
Local<Object> buffer = ObjectWrap::Unwrap<Buffer>(value->ToObject());
uint32_t length = object->length();
#else
uint32_t length = (uint32_t)node::Buffer::Length(value->ToObject());
#endif
this->WriteInt32(length);
this->WriteByte(0);
this->WriteData(node::Buffer::Data(value->ToObject()), length);
}
else if(value->IsRegExp())
{
this->CommitType(typeLocation, BSON_TYPE_REGEXP);
const Local<RegExp>& regExp = Local<RegExp>::Cast(value);
const Local<String> regExpString = regExp->GetSource()->ToString();
// Validate if the string is valid
this->CheckForIllegalString(regExpString);
// Write the regular expression string
this->WriteString(regExpString);
// Unpack the flags
int flags = regExp->GetFlags();
if(flags & RegExp::kGlobal) this->WriteByte('s');
if(flags & RegExp::kIgnoreCase) this->WriteByte('i');
if(flags & RegExp::kMultiline) this->WriteByte('m');
return this->WriteByte(0);
}
else
{
// Check for toBSON function
if(NanHas(object, "toBSON")) {
const Local<Value>& toBSON = NanGet(object, "toBSON");
if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function");
value = Local<Function>::Cast(toBSON)->Call(object, 0, NULL);
return SerializeValue(typeLocation, value, false);
}
this->CommitType(typeLocation, BSON_TYPE_OBJECT);
SerializeDocument(value);
}
}
else if(value->IsNull())
{
this->CommitType(typeLocation, BSON_TYPE_NULL);
}
else if(value->IsUndefined() && !isArray && !ignoreUndefined)
{
this->CommitType(typeLocation, BSON_TYPE_NULL);
}
else if(value->IsUndefined() && isArray && ignoreUndefined)
{
this->CommitType(typeLocation, BSON_TYPE_NULL);
}
else if(value->IsUndefined() && isArray && !ignoreUndefined)
{
this->CommitType(typeLocation, BSON_TYPE_NULL);
}
}
// Data points to start of element list, length is length of entire document including '\0' but excluding initial size
BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length, bool bsonRegExp, bool promoteLongs, bool promoteBuffers, bool promoteValues, Local<Object> fieldsAsRaw)
: bson(aBson),
pStart(data),
p(data),
pEnd(data + length - 1),
bsonRegExp(bsonRegExp),
promoteLongs(promoteLongs),
promoteBuffers(promoteBuffers),
promoteValues(promoteValues),
fieldsAsRaw(fieldsAsRaw)
{
if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'");
}
BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length, bool bsonRegExp, bool promoteLongs, bool promoteBuffers, bool promoteValues, Local<Object> fieldsAsRaw)
: bson(parentSerializer.bson),
pStart(parentSerializer.p),
p(parentSerializer.p),
pEnd(parentSerializer.p + length - 1),
bsonRegExp(bsonRegExp),
promoteLongs(promoteLongs),
promoteBuffers(promoteBuffers),
promoteValues(promoteValues),
fieldsAsRaw(fieldsAsRaw)
{
parentSerializer.p += length;
if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds");
if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'");
}
Local<Value> BSONDeserializer::ReadCString() {
char* start = p;
while(*p++ && (p < pEnd)) { }
if(p > pEnd) {
ThrowAllocatedStringException(64, "Illegal CString found");
}
return Unmaybe(Nan::New<String>(start, (int32_t) (p-start-1) ));
}
int32_t BSONDeserializer::ReadJavascriptRegexOptions() {
int32_t options = 0;
for(;;) {
switch(*p++) {
case '\0': return options;
case 's': options |= RegExp::kGlobal; break;
case 'i': options |= RegExp::kIgnoreCase; break;
case 'm': options |= RegExp::kMultiline; break;
default:
ThrowAllocatedStringException(64, "Javascript RegExp option not one of s, i, m");
break;
}
}
}
int32_t BSONDeserializer::ReadBSONRegexOptions() {
int32_t options = 0;
for(;;) {
switch(*p++) {
case '\0': return options;
case 's': break;
case 'i': break;
case 'l': break;
case 'u': break;
case 'x': break;
case 'm': break;
default:
ThrowAllocatedStringException(64, "BSON RegExp option not one of s, i, l, u, x, m");
break;
}
}
}
void BSONDeserializer::ReadIntegerString() {
while(*p) {
p++;
}
++p;
}
Local<String> BSONDeserializer::ReadString() {
int32_t length = ReadInt32();
if(length <= 0 || length > (pEnd - p)) {
ThrowAllocatedStringException(64, "Invalid bson string length");
}
char* start = p;
p += length;
if(*(p - 1) != 0x00) {
ThrowAllocatedStringException(64, "Illegal bson string terminator found");
}
if (!ValidateEncoding(reinterpret_cast<const uint8_t*>(start), length - 1)) {
ThrowAllocatedStringException(64, "Invalid UTF8 string found");
}
return Unmaybe(Nan::New<String>(start, length - 1));
}
Local<Object> BSONDeserializer::ReadObjectId() {
// Copy the data into a buffer
Local<Object> buffer = Unmaybe(Nan::CopyBuffer(p, 12));
// Move pointer
p += 12;
// Return the buffer
return Unmaybe(buffer);
}
Local<Value> BSONDeserializer::DeserializeDocument(bool raw) {
const char* start = p;
uint32_t length = ReadUInt32();
if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes");
// Do we deserialize as a raw value
if(raw) {
// Copy the whole bon object
Local<Object> buffer = Unmaybe(Nan::CopyBuffer(p - 4, length));
// Adjust the length to the end of the object
p += length - 4;
// Return the new buffer
return buffer;
}
BSONDeserializer documentDeserializer(*this, length-4, bsonRegExp, promoteLongs, promoteBuffers, promoteValues, fieldsAsRaw);
// Serialize the document
Local<Value> value = documentDeserializer.DeserializeDocumentInternal();
if(length != (p - start)) {
ThrowAllocatedStringException(64, "Illegal Document Length");
}
// Return the value
return value;
}
Local<Value> BSONDeserializer::DeserializeDocumentInternal() {
Local<Object> returnObject = Unmaybe(Nan::New<Object>());
Local<String> propertyName;
bool raw = false;
while(HasMoreData()) {
BsonType type = (BsonType) ReadByte();
const Local<Value>& name = ReadCString();
if(name->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString");
// Special case for fieldsAsRaw matching the name and the value being a ARRAY
if(type == BSON_TYPE_ARRAY && !Nan::MaybeLocal<Object>(fieldsAsRaw).IsEmpty()) {
// Get the object property names
Local<Array> propertyNames = fieldsAsRaw->GetPropertyNames();
// Length of the property
int propertyLength = propertyNames->Length();
for(int i = 0; i < propertyLength; ++i)
{
propertyName = NanGet(propertyNames, i)->ToString();
// We found a field that matches name wise, we now want to return a raw buffer
// instead of deserializing the array;
if(name->StrictEquals(propertyName)) {
raw = true;
}
}
}
// Deserialize the value
const Local<Value>& value = DeserializeValue(type, raw);
returnObject->Set(name, value);
}
if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes");
// From JavaScript:
// if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']);
// Determine if we need to return a DBRef or not
Local<Value> dbRefRefValue = NanGet(returnObject, DBREF_REF_PROPERTY_NAME);
Local<Value> dbRefIdValue = NanGet(returnObject, DBREF_ID_REF_PROPERTY_NAME);
Local<Value> dbRefDbValue = NanGet(returnObject, DBREF_DB_REF_PROPERTY_NAME);
if (!dbRefRefValue->IsUndefined() && !dbRefIdValue->IsUndefined()) {
Local<Object> fieldsObject = Unmaybe(Nan::New<Object>());
Local<Array> propertyNames = returnObject->GetPropertyNames();
int propertyLength = propertyNames->Length();
for (int i = 0; i < propertyLength; ++i) {
propertyName = NanGet(propertyNames, i)->ToString();
// First check if we have an invalid escaped key
const char *check = *Nan::Utf8String(propertyName);
if (
check[0] == '$' &&
(
strcmp(check, DBREF_REF_PROPERTY_NAME) != 0 &&
strcmp(check, DBREF_ID_REF_PROPERTY_NAME) != 0 &&
strcmp(check, DBREF_DB_REF_PROPERTY_NAME) != 0
)
) {
// this is not a proper DBRef, we're safe to just return the returnObject
return returnObject;
}
// Now build up the `fields` object
if (
strcmp(check, DBREF_REF_PROPERTY_NAME) == 0 ||
strcmp(check, DBREF_ID_REF_PROPERTY_NAME) == 0 ||
strcmp(check, DBREF_DB_REF_PROPERTY_NAME) == 0
) {
continue;
}
fieldsObject->Set(propertyName, NanGet(returnObject, propertyName));
}
Local<Value> argv[] = { dbRefRefValue, dbRefIdValue, dbRefDbValue, fieldsObject };
Nan::MaybeLocal<Object> obj = Nan::NewInstance(Nan::New(bson->dbrefConstructor), 4, argv);
return obj.ToLocalChecked();
}
return returnObject;
}
Local<Value> BSONDeserializer::DeserializeArray(bool raw) {
uint32_t length = ReadUInt32();
if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes");
BSONDeserializer documentDeserializer(*this, length-4, bsonRegExp, promoteLongs, promoteBuffers, promoteValues, fieldsAsRaw);
return documentDeserializer.DeserializeArrayInternal(raw);
}
Local<Value> BSONDeserializer::DeserializeArrayInternal(bool raw) {
Local<Array> returnArray = Unmaybe(Nan::New<Array>());
uint32_t index = 0;
while(HasMoreData()) {
BsonType type = (BsonType) ReadByte();
ReadIntegerString();
const Local<Value>& value = DeserializeValue(type, raw);
if(index >= preLoadedIndex) {
returnArray->Set(Nan::New<Integer>(index++), value);
} else {
returnArray->Set(Nan::New(BSON::indexes[index++]), value);
}
}
if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes");
return returnArray;
}
Local<Value> BSONDeserializer::DeserializeValue(BsonType type, bool raw)
{
switch(type)
{
case BSON_TYPE_STRING: {
return ReadString();
}
case BSON_TYPE_INT: {
if((pEnd - p) < 4) {
ThrowAllocatedStringException(64, "Illegal BSON found, truncated Int32");
}
Local<Value> value = Nan::New<Integer>(ReadInt32());
if (!promoteValues) {
Local<Value> argv[] = { value };
Nan::MaybeLocal<Object> obj = Nan::NewInstance(Nan::New(bson->int32Constructor), 1, argv);
return obj.ToLocalChecked();
}
return value;
}
case BSON_TYPE_NUMBER: {
if((pEnd - p) < 8) {
ThrowAllocatedStringException(64, "Illegal BSON found, truncated Double");
}
Local<Value> value = Nan::New<Number>(ReadDouble());
if (!promoteValues) {
Local<Value> argv[] = { value };
Nan::MaybeLocal<Object> obj = Nan::NewInstance(Nan::New(bson->doubleConstructor), 1, argv);
return obj.ToLocalChecked();
}
return value;
}
case BSON_TYPE_NULL:
return Nan::Null();
case BSON_TYPE_UNDEFINED:
return Nan::Undefined();
case BSON_TYPE_TIMESTAMP: {
if((pEnd - p) < 8) {
ThrowAllocatedStringException(64, "Illegal BSON found, truncated Timestamp");
}
int32_t lowBits = ReadInt32();
int32_t highBits = ReadInt32();
Local<Value> argv[] = { Nan::New<Int32>(lowBits), Nan::New<Int32>(highBits) };
Nan::MaybeLocal<Object> obj = Nan::NewInstance(Nan::New(bson->timestampConstructor), 2, argv);
return obj.ToLocalChecked();
}
case BSON_TYPE_BOOLEAN: {
char value = ReadByte();
if(value != 0 && value != 1) {
ThrowAllocatedStringException(64, "Illegal BSON Binary value");
}
return (value != 0) ? Nan::True() : Nan::False();
}
case BSON_TYPE_REGEXP: {
const Local<Value>& regex = ReadCString();
if(regex->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString");
if (bsonRegExp) {
// Save pointer
char* start = p;
// Read and validate options
ReadBSONRegexOptions();
// Reset read pointer
p = start;
// Read the options
const Local<Value>& options = ReadCString();
Local<Value> argv[] = { regex, options };
Nan::MaybeLocal<Object> obj = Nan::NewInstance(Nan::New(bson->regexpConstructor), 2, argv);
return obj.ToLocalChecked();
} else {
int32_t options = ReadJavascriptRegexOptions();
return Unmaybe(Nan::New<RegExp>(regex->ToString(), (RegExp::Flags) options));
}
}
case BSON_TYPE_CODE: {
const Local<String>& code = ReadString();
Local<Value> argv[] = { code, Nan::Undefined() };
Nan::MaybeLocal<Object> obj = Nan::NewInstance(Nan::New(bson->codeConstructor), 2, argv);
return obj.ToLocalChecked();
}
case BSON_TYPE_CODE_W_SCOPE: {
char* const start = p;
int32_t length = ReadInt32();
if(length < (4+4+4+1)) {
ThrowAllocatedStringException(64, "code_w_scope total size shorter minimum expected length");
}
const Local<String>& code = ReadString();
const Local<Value>& scope = DeserializeDocument(false);
char* const end = p;
if((end-start) != length) {
ThrowAllocatedStringException(64, "code_w_scope total size shorter minimum expected length");
}
Local<Value> argv[] = { code, scope->ToObject() };
Nan::MaybeLocal<Object> obj = Nan::NewInstance(Nan::New(bson->codeConstructor), 2, argv);
return obj.ToLocalChecked();
}
case BSON_TYPE_OID: {
if((pEnd - p) < 12) {
ThrowAllocatedStringException(64, "Illegal BSON found, truncated ObjectId");
}
Local<Value> argv[] = { ReadObjectId() };
Nan::MaybeLocal<Object> obj = Nan::NewInstance(Nan::New(bson->objectIDConstructor), 1, argv);
return obj.ToLocalChecked();
}
case BSON_TYPE_BINARY: {
int32_t length = ReadInt32();
if(length < 0) {
ThrowAllocatedStringException(64, "binary bson object length must be >= 0");
}
// Illegal binary size
if(length > ((pEnd - p) + 4)) {
ThrowAllocatedStringException(64, "binary bson object size is longer than bson message");
}
uint32_t subType = ReadByte();
if(subType == 0x02) {
length = ReadInt32();
if(length < 0) {
ThrowAllocatedStringException(64, "binary bson type 0x02 object length must be >= 0");
}
// Illegal binary size
if(length > (pEnd - p)) {
ThrowAllocatedStringException(64, "binary bson object type 0x02 size is longer than bson message");
}
}
Local<Object> buffer = Unmaybe(Nan::CopyBuffer(p, length));
p += length;
if (promoteBuffers && promoteValues) {
return buffer;