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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
|
/*
* 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.
*/
/*
* This file contains C implementations of some of the functions
* needed by the bson module. If possible, these implementations
* should be used to speed up BSON encoding and decoding.
*/
#include "Python.h"
#include "datetime.h"
#include "buffer.h"
#include "time64.h"
#include "encoding_helpers.h"
#define _CBSON_MODULE
#include "_cbsonmodule.h"
/* New module state and initialization code.
* See the module-initialization-and-state
* section in the following doc:
* http://docs.python.org/release/3.1.3/howto/cporting.html
* which references the following pep:
* http://www.python.org/dev/peps/pep-3121/
* */
struct module_state {
PyObject* Binary;
PyObject* Code;
PyObject* ObjectId;
PyObject* DBRef;
PyObject* RECompile;
PyObject* UUID;
PyObject* Timestamp;
PyObject* MinKey;
PyObject* MaxKey;
PyObject* UTC;
PyTypeObject* REType;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif
#if PY_VERSION_HEX < 0x02050000
#define WARN(category, message) \
PyErr_Warn((category), (message))
#else
#define WARN(category, message) \
PyErr_WarnEx((category), (message), 1)
#endif
/* Maximum number of regex flags */
#define FLAGS_SIZE 7
#if defined(WIN32) || defined(_MSC_VER)
/* This macro is basically an implementation of asprintf for win32
* We get the length of the int as string and malloc a buffer for it,
* returning -1 if that malloc fails. We then actually print to the
* buffer to get the string value as an int. Like asprintf, the result
* must be explicitly free'd when done being used.
*/
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#define INT2STRING(buffer, i) \
*(buffer) = malloc(_scprintf("%d", (i)) + 1), \
(!(buffer) ? \
-1 : \
_snprintf_s(*(buffer), \
_scprintf("%d", (i)) + 1, \
_scprintf("%d", (i)) + 1, \
"%d", \
(i)))
#define STRCAT(dest, n, src) strcat_s((dest), (n), (src))
#else
#define INT2STRING(buffer, i) \
*(buffer) = malloc(_scprintf("%d", (i)) + 1), \
(!(buffer) ? \
-1 : \
_snprintf(*(buffer), \
_scprintf("%d", (i)) + 1, \
"%d", \
(i)))
#define STRCAT(dest, n, src) strcat((dest), (src))
#endif
#else
#define INT2STRING(buffer, i) asprintf((buffer), "%d", (i))
#define STRCAT(dest, n, src) strcat((dest), (src))
#endif
static PyObject* elements_to_dict(PyObject* self, const char* string, int max,
PyObject* as_class, unsigned char tz_aware);
static int _write_element_to_buffer(PyObject* self, buffer_t buffer, int type_byte,
PyObject* value, unsigned char check_keys,
unsigned char uuid_subtype, unsigned char first_attempt);
/* Date stuff */
static PyObject* datetime_from_millis(long long millis) {
int microseconds = (millis % 1000) * 1000;
Time64_T seconds = millis / 1000;
struct TM timeinfo;
gmtime64_r(&seconds, &timeinfo);
return PyDateTime_FromDateAndTime(timeinfo.tm_year + 1900,
timeinfo.tm_mon + 1,
timeinfo.tm_mday,
timeinfo.tm_hour,
timeinfo.tm_min,
timeinfo.tm_sec,
microseconds);
}
static long long millis_from_datetime(PyObject* datetime) {
struct TM timeinfo;
long long millis;
timeinfo.tm_year = PyDateTime_GET_YEAR(datetime) - 1900;
timeinfo.tm_mon = PyDateTime_GET_MONTH(datetime) - 1;
timeinfo.tm_mday = PyDateTime_GET_DAY(datetime);
timeinfo.tm_hour = PyDateTime_DATE_GET_HOUR(datetime);
timeinfo.tm_min = PyDateTime_DATE_GET_MINUTE(datetime);
timeinfo.tm_sec = PyDateTime_DATE_GET_SECOND(datetime);
millis = timegm64(&timeinfo) * 1000;
millis += PyDateTime_DATE_GET_MICROSECOND(datetime) / 1000;
return millis;
}
/* Just make this compatible w/ the old API. */
int buffer_write_bytes(buffer_t buffer, const char* data, int size) {
if (buffer_write(buffer, data, size)) {
PyErr_NoMemory();
return 0;
}
return 1;
}
#if PY_MAJOR_VERSION >= 3
static int write_unicode(buffer_t buffer, PyObject* py_string) {
Py_ssize_t string_length;
const char* string;
PyObject* encoded = PyUnicode_AsUTF8String(py_string);
if (!encoded) {
return 0;
}
string = PyBytes_AsString(encoded);
if (!string) {
Py_DECREF(encoded);
return 0;
}
string_length = PyBytes_Size(encoded) + 1;
if (!buffer_write_bytes(buffer, (const char*)&string_length, 4)) {
Py_DECREF(encoded);
return 0;
}
if (!buffer_write_bytes(buffer, string, string_length)) {
Py_DECREF(encoded);
return 0;
}
Py_DECREF(encoded);
return 1;
}
#endif
/* returns 0 on failure */
static int write_string(buffer_t buffer, PyObject* py_string) {
Py_ssize_t string_length;
const char* string;
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(py_string)){
return write_unicode(buffer, py_string);
}
string = PyBytes_AsString(py_string);
#else
string = PyString_AsString(py_string);
#endif
if (!string) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
string_length = PyBytes_Size(py_string) + 1;
#else
string_length = PyString_Size(py_string) + 1;
#endif
if (!buffer_write_bytes(buffer, (const char*)&string_length, 4)) {
return 0;
}
if (!buffer_write_bytes(buffer, string, string_length)) {
return 0;
}
return 1;
}
/* Get an error class from the bson.errors module.
*
* Returns a new ref */
static PyObject* _error(char* name) {
PyObject* error;
PyObject* errors = PyImport_ImportModule("bson.errors");
if (!errors) {
return NULL;
}
error = PyObject_GetAttrString(errors, name);
Py_DECREF(errors);
return error;
}
/* Reload a cached Python object.
*
* Returns non-zero on failure. */
static int _reload_object(PyObject** object, char* module_name, char* object_name) {
PyObject* module;
module = PyImport_ImportModule(module_name);
if (!module) {
return 1;
}
*object = PyObject_GetAttrString(module, object_name);
Py_DECREF(module);
return (*object) ? 0 : 2;
}
/* Reload all cached Python objects.
*
* Returns non-zero on failure. */
static int _reload_python_objects(PyObject* module) {
struct module_state *state = GETSTATE(module);
if (_reload_object(&state->Binary, "bson.binary", "Binary") ||
_reload_object(&state->Code, "bson.code", "Code") ||
_reload_object(&state->ObjectId, "bson.objectid", "ObjectId") ||
_reload_object(&state->DBRef, "bson.dbref", "DBRef") ||
_reload_object(&state->Timestamp, "bson.timestamp", "Timestamp") ||
_reload_object(&state->MinKey, "bson.min_key", "MinKey") ||
_reload_object(&state->MaxKey, "bson.max_key", "MaxKey") ||
_reload_object(&state->UTC, "bson.tz_util", "utc") ||
_reload_object(&state->RECompile, "re", "compile")) {
return 1;
}
/* If we couldn't import uuid then we must be on 2.4. Just ignore. */
if (_reload_object(&state->UUID, "uuid", "UUID") == 1) {
state->UUID = NULL;
PyErr_Clear();
}
/* Reload our REType hack too. */
state->REType = PyObject_CallFunction(state->RECompile, "O",
#if PY_MAJOR_VERSION >= 3
PyBytes_FromString(""))->ob_type;
#else
PyString_FromString(""))->ob_type;
#endif
return 0;
}
static int write_element_to_buffer(PyObject* self, buffer_t buffer, int type_byte,
PyObject* value, unsigned char check_keys,
unsigned char uuid_subtype,
unsigned char first_attempt) {
int result;
if(Py_EnterRecursiveCall(" while encoding an object to BSON "))
return 0;
result = _write_element_to_buffer(self, buffer, type_byte, value,
check_keys, uuid_subtype, first_attempt);
Py_LeaveRecursiveCall();
return result;
}
/* TODO our platform better be little-endian w/ 4-byte ints! */
/* Write a single value to the buffer (also write it's type_byte, for which
* space has already been reserved.
*
* returns 0 on failure */
static int _write_element_to_buffer(PyObject* self, buffer_t buffer, int type_byte,
PyObject* value, unsigned char check_keys,
unsigned char uuid_subtype, unsigned char first_attempt) {
struct module_state *state = GETSTATE(self);
if (PyBool_Check(value)) {
#if PY_MAJOR_VERSION >= 3
const long bool = PyLong_AsLong(value);
#else
const long bool = PyInt_AsLong(value);
#endif
const char c = bool ? 0x01 : 0x00;
*(buffer_get_buffer(buffer) + type_byte) = 0x08;
return buffer_write_bytes(buffer, &c, 1);
}
#if PY_MAJOR_VERSION >= 3
else if (PyLong_Check(value)) {
const long long_value = PyLong_AsLong(value);
#else
else if (PyInt_Check(value)) {
const long long_value = PyInt_AsLong(value);
#endif
const int int_value = (int)long_value;
if (PyErr_Occurred() || long_value != int_value) { /* Overflow */
long long long_long_value;
PyErr_Clear();
long_long_value = PyLong_AsLongLong(value);
if (PyErr_Occurred()) { /* Overflow AGAIN */
PyErr_SetString(PyExc_OverflowError,
"MongoDB can only handle up to 8-byte ints");
return 0;
}
*(buffer_get_buffer(buffer) + type_byte) = 0x12;
return buffer_write_bytes(buffer, (const char*)&long_long_value, 8);
}
*(buffer_get_buffer(buffer) + type_byte) = 0x10;
return buffer_write_bytes(buffer, (const char*)&int_value, 4);
#if PY_MAJOR_VERSION < 3
} else if (PyLong_Check(value)) {
const long long long_long_value = PyLong_AsLongLong(value);
if (PyErr_Occurred()) { /* Overflow */
PyErr_SetString(PyExc_OverflowError,
"MongoDB can only handle up to 8-byte ints");
return 0;
}
*(buffer_get_buffer(buffer) + type_byte) = 0x12;
return buffer_write_bytes(buffer, (const char*)&long_long_value, 8);
#endif
} else if (PyFloat_Check(value)) {
const double d = PyFloat_AsDouble(value);
*(buffer_get_buffer(buffer) + type_byte) = 0x01;
return buffer_write_bytes(buffer, (const char*)&d, 8);
} else if (value == Py_None) {
*(buffer_get_buffer(buffer) + type_byte) = 0x0A;
return 1;
} else if (PyDict_Check(value)) {
*(buffer_get_buffer(buffer) + type_byte) = 0x03;
return write_dict(self, buffer, value, check_keys, uuid_subtype, 0);
} else if (PyList_Check(value) || PyTuple_Check(value)) {
int start_position,
length_location,
items,
length,
i;
char zero = 0;
*(buffer_get_buffer(buffer) + type_byte) = 0x04;
start_position = buffer_get_position(buffer);
/* save space for length */
length_location = buffer_save_space(buffer, 4);
if (length_location == -1) {
PyErr_NoMemory();
return 0;
}
items = PySequence_Size(value);
for(i = 0; i < items; i++) {
int list_type_byte = buffer_save_space(buffer, 1);
char* name;
PyObject* item_value;
if (list_type_byte == -1) {
PyErr_NoMemory();
return 0;
}
if (INT2STRING(&name, i) < 0 || !name) {
PyErr_NoMemory();
return 0;
}
if (!buffer_write_bytes(buffer, name, strlen(name) + 1)) {
free(name);
return 0;
}
free(name);
item_value = PySequence_GetItem(value, i);
if (!write_element_to_buffer(self, buffer, list_type_byte,
item_value, check_keys, uuid_subtype, 1)) {
Py_DECREF(item_value);
return 0;
}
Py_DECREF(item_value);
}
/* write null byte and fill in length */
if (!buffer_write_bytes(buffer, &zero, 1)) {
return 0;
}
length = buffer_get_position(buffer) - start_position;
memcpy(buffer_get_buffer(buffer) + length_location, &length, 4);
return 1;
} else if (PyObject_IsInstance(value, state->Binary)) {
PyObject* subtype_object;
*(buffer_get_buffer(buffer) + type_byte) = 0x05;
subtype_object = PyObject_GetAttrString(value, "subtype");
if (!subtype_object) {
return 0;
}
{
#if PY_MAJOR_VERSION >= 3
const long long_subtype = PyLong_AsLong(subtype_object);
const char subtype = (const char)long_subtype;
const int length = PyBytes_Size(value);
#else
const long long_subtype = PyInt_AsLong(subtype_object);
const char subtype = (const char)long_subtype;
const int length = PyString_Size(value);
#endif
Py_DECREF(subtype_object);
if (subtype == 2) {
const int other_length = length + 4;
if (!buffer_write_bytes(buffer, (const char*)&other_length, 4)) {
return 0;
}
if (!buffer_write_bytes(buffer, &subtype, 1)) {
return 0;
}
}
if (!buffer_write_bytes(buffer, (const char*)&length, 4)) {
return 0;
}
if (subtype != 2) {
if (!buffer_write_bytes(buffer, &subtype, 1)) {
return 0;
}
}
{
#if PY_MAJOR_VERSION >= 3
const char* string = PyBytes_AsString(value);
#else
const char* string = PyString_AsString(value);
#endif
if (!string) {
return 0;
}
if (!buffer_write_bytes(buffer, string, length)) {
return 0;
}
}
}
return 1;
} else if (state->UUID && PyObject_IsInstance(value, state->UUID)) {
// Just a special case of Binary above, but simpler to do as a separate case
// Could be bytes, bytearray, str...
const char* binarr;
// UUID is always 16 bytes
int length = 16;
const char subtype = (const char)uuid_subtype;
PyObject* bytes;
*(buffer_get_buffer(buffer) + type_byte) = 0x05;
if (!buffer_write_bytes(buffer, (const char*)&length, 4)) {
return 0;
}
if (!buffer_write_bytes(buffer, &subtype, 1)) {
return 0;
}
bytes = PyObject_GetAttrString(value, "bytes");
if (!bytes) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
/* Work around http://bugs.python.org/issue7380 */
if (PyByteArray_Check(bytes)) {
binarr = PyByteArray_AsString(bytes);
}
else {
binarr = PyBytes_AsString(bytes);
}
#else
binarr = PyString_AsString(bytes);
#endif
if (!buffer_write_bytes(buffer, binarr, length)) {
Py_DECREF(bytes);
return 0;
}
Py_DECREF(bytes);
return 1;
} else if (PyObject_IsInstance(value, state->Code)) {
int start_position,
length_location,
length;
PyObject* scope = PyObject_GetAttrString(value, "scope");
if (!scope) {
return 0;
}
if (!PyDict_Size(scope)) {
Py_DECREF(scope);
*(buffer_get_buffer(buffer) + type_byte) = 0x0D;
return write_string(buffer, value);
}
*(buffer_get_buffer(buffer) + type_byte) = 0x0F;
start_position = buffer_get_position(buffer);
/* save space for length */
length_location = buffer_save_space(buffer, 4);
if (length_location == -1) {
PyErr_NoMemory();
return 0;
}
if (!write_string(buffer, value)) {
return 0;
}
if (!write_dict(self, buffer, scope, 0, uuid_subtype, 0)) {
Py_DECREF(scope);
return 0;
}
Py_DECREF(scope);
length = buffer_get_position(buffer) - start_position;
memcpy(buffer_get_buffer(buffer) + length_location, &length, 4);
return 1;
#if PY_MAJOR_VERSION >= 3
/* Python3 special case. Store bytes as BSON binary subtype 0. */
} else if (PyBytes_Check(value)) {
Py_ssize_t length = PyBytes_Size(value);
const char subtype = 0;
*(buffer_get_buffer(buffer) + type_byte) = 0x05;
if (!buffer_write_bytes(buffer, (const char*)&length, 4)) {
return 0;
}
if (!buffer_write_bytes(buffer, &subtype, 1)) {
return 0;
}
if (!buffer_write_bytes(buffer, PyBytes_AsString(value), length)) {
return 0;
}
return 1;
#else
/* PyString_Check only works in Python 2.x. */
} else if (PyString_Check(value)) {
int result;
result_t status;
*(buffer_get_buffer(buffer) + type_byte) = 0x02;
status = check_string((const unsigned char*)PyString_AsString(value),
PyString_Size(value), 1, 0);
if (status == NOT_UTF_8) {
PyObject* InvalidStringData = _error("InvalidStringData");
PyErr_SetString(InvalidStringData,
"strings in documents must be valid UTF-8");
Py_DECREF(InvalidStringData);
return 0;
}
result = write_string(buffer, value);
return result;
#endif
} else if (PyUnicode_Check(value)) {
PyObject* encoded;
int result;
*(buffer_get_buffer(buffer) + type_byte) = 0x02;
encoded = PyUnicode_AsUTF8String(value);
if (!encoded) {
return 0;
}
result = write_string(buffer, encoded);
Py_DECREF(encoded);
return result;
} else if (PyDateTime_Check(value)) {
long long millis;
PyObject* utcoffset = PyObject_CallMethod(value, "utcoffset", NULL);
if (utcoffset != Py_None) {
PyObject* result = PyNumber_Subtract(value, utcoffset);
Py_DECREF(utcoffset);
if (!result) {
return 0;
}
millis = millis_from_datetime(result);
Py_DECREF(result);
} else {
millis = millis_from_datetime(value);
}
*(buffer_get_buffer(buffer) + type_byte) = 0x09;
return buffer_write_bytes(buffer, (const char*)&millis, 8);
} else if (PyObject_IsInstance(value, state->ObjectId)) {
PyObject* pystring = PyObject_GetAttrString(value, "_ObjectId__id");
if (!pystring) {
return 0;
}
{
#if PY_MAJOR_VERSION >= 3
const char* as_string = PyBytes_AsString(pystring);
#else
const char* as_string = PyString_AsString(pystring);
#endif
if (!as_string) {
Py_DECREF(pystring);
return 0;
}
if (!buffer_write_bytes(buffer, as_string, 12)) {
Py_DECREF(pystring);
return 0;
}
Py_DECREF(pystring);
*(buffer_get_buffer(buffer) + type_byte) = 0x07;
}
return 1;
} else if (PyObject_IsInstance(value, state->DBRef)) {
PyObject* as_doc = PyObject_CallMethod(value, "as_doc", NULL);
if (!as_doc) {
return 0;
}
if (!write_dict(self, buffer, as_doc, 0, uuid_subtype, 0)) {
Py_DECREF(as_doc);
return 0;
}
Py_DECREF(as_doc);
*(buffer_get_buffer(buffer) + type_byte) = 0x03;
return 1;
} else if (PyObject_IsInstance(value, state->Timestamp)) {
PyObject* obj;
long i;
obj = PyObject_GetAttrString(value, "inc");
if (!obj) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
i = PyLong_AsLong(obj);
#else
i = PyInt_AsLong(obj);
#endif
Py_DECREF(obj);
if (!buffer_write_bytes(buffer, (const char*)&i, 4)) {
return 0;
}
obj = PyObject_GetAttrString(value, "time");
if (!obj) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
i = PyLong_AsLong(obj);
#else
i = PyInt_AsLong(obj);
#endif
Py_DECREF(obj);
if (!buffer_write_bytes(buffer, (const char*)&i, 4)) {
return 0;
}
*(buffer_get_buffer(buffer) + type_byte) = 0x11;
return 1;
}
else if (PyObject_TypeCheck(value, state->REType)) {
PyObject* py_flags = PyObject_GetAttrString(value, "flags");
PyObject* py_pattern;
PyObject* encoded_pattern;
long int_flags;
char flags[FLAGS_SIZE];
char check_utf8 = 0;
int pattern_length,
flags_length;
result_t status;
if (!py_flags) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
int_flags = PyLong_AsLong(py_flags);
#else
int_flags = PyInt_AsLong(py_flags);
#endif
Py_DECREF(py_flags);
py_pattern = PyObject_GetAttrString(value, "pattern");
if (!py_pattern) {
return 0;
}
if (PyUnicode_Check(py_pattern)) {
encoded_pattern = PyUnicode_AsUTF8String(py_pattern);
Py_DECREF(py_pattern);
if (!encoded_pattern) {
return 0;
}
} else {
encoded_pattern = py_pattern;
check_utf8 = 1;
}
#if PY_MAJOR_VERSION >= 3
status = check_string((const unsigned char*)PyBytes_AsString(encoded_pattern),
PyBytes_Size(encoded_pattern), check_utf8, 1);
#else
status = check_string((const unsigned char*)PyString_AsString(encoded_pattern),
PyString_Size(encoded_pattern), check_utf8, 1);
#endif
if (status == NOT_UTF_8) {
PyObject* InvalidStringData = _error("InvalidStringData");
PyErr_SetString(InvalidStringData,
"regex patterns must be valid UTF-8");
Py_DECREF(InvalidStringData);
return 0;
} else if (status == HAS_NULL) {
PyObject* InvalidDocument = _error("InvalidDocument");
PyErr_SetString(InvalidDocument,
"regex patterns must not contain the NULL byte");
Py_DECREF(InvalidDocument);
return 0;
}
{
#if PY_MAJOR_VERSION >= 3
const char* pattern = PyBytes_AsString(encoded_pattern);
#else
const char* pattern = PyString_AsString(encoded_pattern);
#endif
pattern_length = strlen(pattern) + 1;
if (!buffer_write_bytes(buffer, pattern, pattern_length)) {
Py_DECREF(encoded_pattern);
return 0;
}
}
Py_DECREF(encoded_pattern);
flags[0] = 0;
/* TODO don't hardcode these */
if (int_flags & 2) {
STRCAT(flags, FLAGS_SIZE, "i");
}
if (int_flags & 4) {
STRCAT(flags, FLAGS_SIZE, "l");
}
if (int_flags & 8) {
STRCAT(flags, FLAGS_SIZE, "m");
}
if (int_flags & 16) {
STRCAT(flags, FLAGS_SIZE, "s");
}
if (int_flags & 32) {
STRCAT(flags, FLAGS_SIZE, "u");
}
if (int_flags & 64) {
STRCAT(flags, FLAGS_SIZE, "x");
}
flags_length = strlen(flags) + 1;
if (!buffer_write_bytes(buffer, flags, flags_length)) {
return 0;
}
*(buffer_get_buffer(buffer) + type_byte) = 0x0B;
return 1;
} else if (PyObject_IsInstance(value, state->MinKey)) {
*(buffer_get_buffer(buffer) + type_byte) = 0xFF;
return 1;
} else if (PyObject_IsInstance(value, state->MaxKey)) {
*(buffer_get_buffer(buffer) + type_byte) = 0x7F;
return 1;
} else if (first_attempt) {
/* Try reloading the modules and having one more go at it. */
if (WARN(PyExc_RuntimeWarning, "couldn't encode - reloading python "
"modules and trying again. if you see this without getting "
"an InvalidDocument exception please see http://api.mongodb"
".org/python/current/faq.html#does-pymongo-work-with-mod-"
"wsgi") == -1) {
return 0;
}
if (_reload_python_objects(self)) {
return 0;
}
return write_element_to_buffer(self, buffer, type_byte, value, check_keys, uuid_subtype, 0);
}
{
PyObject* repr = PyObject_Repr(value);
PyObject* InvalidDocument = _error("InvalidDocument");
#if PY_MAJOR_VERSION >= 3
PyObject* errmsg = PyUnicode_FromString("Cannot encode object: ");
PyObject* error = PyUnicode_Concat(errmsg, repr);
PyErr_SetObject(InvalidDocument, error);
Py_DECREF(error);
Py_DECREF(repr);
#else
PyObject* errmsg = PyString_FromString("Cannot encode object: ");
PyString_ConcatAndDel(&errmsg, repr);
PyErr_SetString(InvalidDocument, PyString_AsString(errmsg));
#endif
Py_DECREF(errmsg);
Py_DECREF(InvalidDocument);
return 0;
}
}
static int check_key_name(const char* name,
const Py_ssize_t name_length) {
int i;
if (name_length > 0 && name[0] == '$') {
PyObject* InvalidDocument = _error("InvalidDocument");
#if PY_MAJOR_VERSION >= 3
PyObject* errmsg = PyUnicode_FromFormat("key '%s' must not start with '$'", name);
PyErr_SetObject(InvalidDocument, errmsg);
#else
PyObject* errmsg = PyString_FromFormat("key '%s' must not start with '$'", name);
PyErr_SetString(InvalidDocument, PyString_AsString(errmsg));
#endif
Py_DECREF(errmsg);
Py_DECREF(InvalidDocument);
return 0;
}
for (i = 0; i < name_length; i++) {
if (name[i] == '.') {
PyObject* InvalidDocument = _error("InvalidDocument");
#if PY_MAJOR_VERSION >= 3
PyObject* errmsg = PyUnicode_FromFormat("key '%s' must not contain '.'", name);
PyErr_SetObject(InvalidDocument, errmsg);
#else
PyObject* errmsg = PyString_FromFormat("key '%s' must not contain '.'", name);
PyErr_SetString(InvalidDocument, PyString_AsString(errmsg));
#endif
Py_DECREF(errmsg);
Py_DECREF(InvalidDocument);
return 0;
}
}
return 1;
}
/* Write a (key, value) pair to the buffer.
*
* Returns 0 on failure */
int write_pair(PyObject* self, buffer_t buffer, const char* name, Py_ssize_t name_length,
PyObject* value, unsigned char check_keys,
unsigned char uuid_subtype, unsigned char allow_id) {
int type_byte;
/* Don't write any _id elements unless we're explicitly told to -
* _id has to be written first so we do so, but don't bother
* deleting it from the dictionary being written. */
if (!allow_id && strcmp(name, "_id") == 0) {
return 1;
}
type_byte = buffer_save_space(buffer, 1);
if (type_byte == -1) {
PyErr_NoMemory();
return 0;
}
if (check_keys && !check_key_name(name, name_length)) {
return 0;
}
if (!buffer_write_bytes(buffer, name, name_length + 1)) {
return 0;
}
if (!write_element_to_buffer(self, buffer, type_byte, value,
check_keys, uuid_subtype, 1)) {
return 0;
}
return 1;
}
int decode_and_write_pair(PyObject* self, buffer_t buffer,
PyObject* key, PyObject* value,
unsigned char check_keys,
unsigned char uuid_subtype, unsigned char top_level) {
PyObject* encoded;
if (PyUnicode_Check(key)) {
result_t status;
encoded = PyUnicode_AsUTF8String(key);
if (!encoded) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
status = check_string((const unsigned char*)PyBytes_AsString(encoded),
PyBytes_Size(encoded), 0, 1);
#else
status = check_string((const unsigned char*)PyString_AsString(encoded),
PyString_Size(encoded), 0, 1);
#endif
if (status == HAS_NULL) {
PyObject* InvalidDocument = _error("InvalidDocument");
PyErr_SetString(InvalidDocument,
"Key names must not contain the NULL byte");
Py_DECREF(InvalidDocument);
return 0;
}
#if PY_MAJOR_VERSION < 3
} else if (PyString_Check(key)) {
result_t status;
encoded = key;
Py_INCREF(encoded);
status = check_string((const unsigned char*)PyString_AsString(encoded),
PyString_Size(encoded), 1, 1);
if (status == NOT_UTF_8) {
PyObject* InvalidStringData = _error("InvalidStringData");
PyErr_SetString(InvalidStringData,
"strings in documents must be valid UTF-8");
Py_DECREF(InvalidStringData);
return 0;
} else if (status == HAS_NULL) {
PyObject* InvalidDocument = _error("InvalidDocument");
PyErr_SetString(InvalidDocument,
"Key names must not contain the NULL byte");
Py_DECREF(InvalidDocument);
return 0;
}
#endif
} else {
PyObject* InvalidDocument = _error("InvalidDocument");
PyObject* repr = PyObject_Repr(key);
#if PY_MAJOR_VERSION >= 3
PyObject* errmsg = PyUnicode_FromString("documents must have only string keys, key was ");
PyObject* error = PyUnicode_Concat(errmsg, repr);
PyErr_SetObject(InvalidDocument, error);
Py_DECREF(error);
#else
PyObject* errmsg = PyString_FromString("documents must have only string keys, key was ");
PyString_ConcatAndDel(&errmsg, repr);
PyErr_SetString(InvalidDocument, PyString_AsString(errmsg));
#endif
Py_DECREF(InvalidDocument);
Py_DECREF(errmsg);
return 0;
}
/* If top_level is True, don't allow writing _id here - it was already written. */
#if PY_MAJOR_VERSION >= 3
if (!write_pair(self, buffer, PyBytes_AsString(encoded),
PyBytes_Size(encoded), value,
check_keys, uuid_subtype, !top_level)) {
#else
if (!write_pair(self, buffer, PyString_AsString(encoded),
PyString_Size(encoded), value,
check_keys, uuid_subtype, !top_level)) {
#endif
Py_DECREF(encoded);
return 0;
}
Py_DECREF(encoded);
return 1;
}
/* returns 0 on failure */
int write_dict(PyObject* self, buffer_t buffer, PyObject* dict,
unsigned char check_keys, unsigned char uuid_subtype, unsigned char top_level) {
PyObject* key;
PyObject* iter;
char zero = 0;
int length;
int length_location;
if (!PyDict_Check(dict)) {
PyObject* repr = PyObject_Repr(dict);
#if PY_MAJOR_VERSION >= 3
PyObject* errmsg = PyUnicode_FromString("encoder expected a mapping type but got: ");
PyObject* error = PyUnicode_Concat(errmsg, repr);
PyErr_SetObject(PyExc_TypeError, error);
Py_DECREF(error);
Py_DECREF(repr);
#else
PyObject* errmsg = PyString_FromString("encoder expected a mapping type but got: ");
PyString_ConcatAndDel(&errmsg, repr);
PyErr_SetString(PyExc_TypeError, PyString_AsString(errmsg));
#endif
Py_DECREF(errmsg);
return 0;
}
length_location = buffer_save_space(buffer, 4);
if (length_location == -1) {
PyErr_NoMemory();
return 0;
}
/* Write _id first if this is a top level doc. */
if (top_level) {
PyObject* _id = PyDict_GetItemString(dict, "_id");
if (_id) {
/* Don't bother checking keys, but do make sure we're allowed to
* write _id */
if (!write_pair(self, buffer, "_id", 3, _id, 0, uuid_subtype, 1)) {
return 0;
}
}
}
iter = PyObject_GetIter(dict);
if (iter == NULL) {
return 0;
}
while ((key = PyIter_Next(iter)) != NULL) {
PyObject* value = PyDict_GetItem(dict, key);
if (!value) {
PyErr_SetObject(PyExc_KeyError, key);
Py_DECREF(key);
Py_DECREF(iter);
return 0;
}
if (!decode_and_write_pair(self, buffer, key, value,
check_keys, uuid_subtype, top_level)) {
Py_DECREF(key);
Py_DECREF(iter);
return 0;
}
Py_DECREF(key);
}
Py_DECREF(iter);
/* write null byte and fill in length */
if (!buffer_write_bytes(buffer, &zero, 1)) {
return 0;
}
length = buffer_get_position(buffer) - length_location;
memcpy(buffer_get_buffer(buffer) + length_location, &length, 4);
return 1;
}
static PyObject* _cbson_dict_to_bson(PyObject* self, PyObject* args) {
PyObject* dict;
PyObject* result;
unsigned char check_keys;
unsigned char uuid_subtype;
buffer_t buffer;
if (!PyArg_ParseTuple(args, "Obb", &dict, &check_keys, &uuid_subtype)) {
return NULL;
}
buffer = buffer_new();
if (!buffer) {
PyErr_NoMemory();
return NULL;
}
if (!write_dict(self, buffer, dict, check_keys, uuid_subtype, 1)) {
buffer_free(buffer);
return NULL;
}
/* objectify buffer */
#if PY_MAJOR_VERSION >= 3
result = Py_BuildValue("y#", buffer_get_buffer(buffer),
buffer_get_position(buffer));
#else
result = Py_BuildValue("s#", buffer_get_buffer(buffer),
buffer_get_position(buffer));
#endif
buffer_free(buffer);
return result;
}
static PyObject* get_value(PyObject* self, const char* buffer, int* position, int type,
int max, PyObject* as_class, unsigned char tz_aware) {
struct module_state *state = GETSTATE(self);
PyObject* value;
PyObject* error;
switch (type) {
case 1:
{
double d;
if (max < 8) {
goto invalid;
}
memcpy(&d, buffer + *position, 8);
value = PyFloat_FromDouble(d);
if (!value) {
return NULL;
}
*position += 8;
break;
}
case 2:
case 14:
{
int value_length = ((int*)(buffer + *position))[0] - 1;
if (max < value_length) {
goto invalid;
}
*position += 4;
value = PyUnicode_DecodeUTF8(buffer + *position, value_length, "strict");
if (!value) {
return NULL;
}
*position += value_length + 1;
break;
}
case 3:
{
int size;
memcpy(&size, buffer + *position, 4);
if (max < size) {
goto invalid;
}
value = elements_to_dict(self, buffer + *position + 4, size - 5, as_class, tz_aware);
if (!value) {
return NULL;
}
/* Decoding for DBRefs */
if (strcmp(buffer + *position + 5, "$ref") == 0) { /* DBRef */
PyObject* dbref;
PyObject* collection = PyDict_GetItemString(value, "$ref");
PyObject* id = PyDict_GetItemString(value, "$id");
PyObject* database = PyDict_GetItemString(value, "$db");
Py_INCREF(collection);
PyDict_DelItemString(value, "$ref");
if (id == NULL) {
id = Py_None;
Py_INCREF(id);
} else {
Py_INCREF(id);
PyDict_DelItemString(value, "$id");
}
if (database == NULL) {
database = Py_None;
Py_INCREF(database);
} else {
Py_INCREF(database);
PyDict_DelItemString(value, "$db");
}
dbref = PyObject_CallFunctionObjArgs(state->DBRef, collection, id, database, value, NULL);
Py_DECREF(value);
value = dbref;
Py_DECREF(id);
Py_DECREF(collection);
Py_DECREF(database);
if (!value) {
return NULL;
}
}
*position += size;
break;
}
case 4:
{
int size,
end;
memcpy(&size, buffer + *position, 4);
if (max < size) {
goto invalid;
}
end = *position + size - 1;
*position += 4;
value = PyList_New(0);
if (!value) {
return NULL;
}
while (*position < end) {
PyObject* to_append;
int type = (int)buffer[(*position)++];
int key_size = strlen(buffer + *position);
*position += key_size + 1; /* just skip the key, they're in order. */
to_append = get_value(self, buffer, position, type, max - key_size, as_class, tz_aware);
if (!to_append) {
return NULL;
}
PyList_Append(value, to_append);
Py_DECREF(to_append);
}
(*position)++;
break;
}
case 5:
{
PyObject* data;
PyObject* st;
int length,
subtype;
memcpy(&length, buffer + *position, 4);
if (max < length) {
goto invalid;
}
subtype = (unsigned char)buffer[*position + 4];
#if PY_MAJOR_VERSION >= 3
/* Python3 special case. Decode BSON binary subtype 0 to bytes. */
if (subtype == 0) {
value = PyBytes_FromStringAndSize(buffer + *position + 5, length);
*position += length + 5;
break;
}
if (subtype == 2) {
data = PyBytes_FromStringAndSize(buffer + *position + 9, length - 4);
} else {
data = PyBytes_FromStringAndSize(buffer + *position + 5, length);
}
#else
if (subtype == 2) {
data = PyString_FromStringAndSize(buffer + *position + 9, length - 4);
} else {
data = PyString_FromStringAndSize(buffer + *position + 5, length);
}
#endif
if (!data) {
return NULL;
}
if ((subtype == 3 || subtype == 4) && state->UUID) { // Encode as UUID, not Binary
PyObject* kwargs;
PyObject* args = PyTuple_New(0);
if (!args) {
Py_DECREF(data);
return NULL;
}
kwargs = PyDict_New();
if (!kwargs) {
Py_DECREF(data);
Py_DECREF(args);
return NULL;
}
assert(length == 16); // UUID should always be 16 bytes
PyDict_SetItemString(kwargs, "bytes", data);
value = PyObject_Call(state->UUID, args, kwargs);
Py_DECREF(args);
Py_DECREF(kwargs);
Py_DECREF(data);
if (!value) {
return NULL;
}
*position += length + 5;
break;
}
#if PY_MAJOR_VERSION >= 3
st = PyLong_FromLong(subtype);
#else
st = PyInt_FromLong(subtype);
#endif
if (!st) {
Py_DECREF(data);
return NULL;
}
value = PyObject_CallFunctionObjArgs(state->Binary, data, st, NULL);
Py_DECREF(st);
Py_DECREF(data);
if (!value) {
return NULL;
}
*position += length + 5;
break;
}
case 6:
case 10:
{
value = Py_None;
Py_INCREF(value);
break;
}
case 7:
{
if (max < 12) {
goto invalid;
}
#if PY_MAJOR_VERSION >= 3
value = PyObject_CallFunction(state->ObjectId, "y#", buffer + *position, 12);
#else
value = PyObject_CallFunction(state->ObjectId, "s#", buffer + *position, 12);
#endif
if (!value) {
return NULL;
}
*position += 12;
break;
}
case 8:
{
value = buffer[(*position)++] ? Py_True : Py_False;
Py_INCREF(value);
break;
}
case 9:
{
PyObject* naive;
PyObject* replace;
PyObject* args;
PyObject* kwargs;
if (max < 8) {
goto invalid;
}
naive = datetime_from_millis(*(long long*)(buffer + *position));
*position += 8;
if (!tz_aware) { /* In the naive case, we're done here. */
value = naive;
break;
}
if (!naive) {
return NULL;
}
replace = PyObject_GetAttrString(naive, "replace");
Py_DECREF(naive);
if (!replace) {
return NULL;
}
args = PyTuple_New(0);
if (!args) {
Py_DECREF(replace);
return NULL;
}
kwargs = PyDict_New();
if (!kwargs) {
Py_DECREF(replace);
Py_DECREF(args);
return NULL;
}
if (PyDict_SetItemString(kwargs, "tzinfo", state->UTC) == -1) {
Py_DECREF(replace);
Py_DECREF(args);
Py_DECREF(kwargs);
return NULL;
}
value = PyObject_Call(replace, args, kwargs);
Py_DECREF(replace);
Py_DECREF(args);
Py_DECREF(kwargs);
break;
}
case 11:
{
PyObject* pattern;
int flags_length,
flags,
i;
int pattern_length = strlen(buffer + *position);
if (max < pattern_length) {
goto invalid;
}
pattern = PyUnicode_DecodeUTF8(buffer + *position, pattern_length, "strict");
if (!pattern) {
return NULL;
}
*position += pattern_length + 1;
flags_length = strlen(buffer + *position);
if (max < pattern_length + flags_length) {
goto invalid;
}
flags = 0;
for (i = 0; i < flags_length; i++) {
if (buffer[*position + i] == 'i') {
flags |= 2;
} else if (buffer[*position + i] == 'l') {
flags |= 4;
} else if (buffer[*position + i] == 'm') {
flags |= 8;
} else if (buffer[*position + i] == 's') {
flags |= 16;
} else if (buffer[*position + i] == 'u') {
flags |= 32;
} else if (buffer[*position + i] == 'x') {
flags |= 64;
}
}
*position += flags_length + 1;
value = PyObject_CallFunction(state->RECompile, "Oi", pattern, flags);
Py_DECREF(pattern);
break;
}
case 12:
{
int collection_length;
PyObject* collection;
PyObject* id;
*position += 4;
collection_length = strlen(buffer + *position);
if (max < collection_length) {
goto invalid;
}
collection = PyUnicode_DecodeUTF8(buffer + *position, collection_length, "strict");
if (!collection) {
return NULL;
}
*position += collection_length + 1;
if (max < collection_length + 12) {
goto invalid;
}
id = PyObject_CallFunction(state->ObjectId, "s#", buffer + *position, 12);
if (!id) {
Py_DECREF(collection);
return NULL;
}
*position += 12;
value = PyObject_CallFunctionObjArgs(state->DBRef, collection, id, NULL);
Py_DECREF(collection);
Py_DECREF(id);
break;
}
case 13:
{
PyObject* code;
int value_length = ((int*)(buffer + *position))[0] - 1;
if (max < value_length) {
goto invalid;
}
*position += 4;
code = PyUnicode_DecodeUTF8(buffer + *position, value_length, "strict");
if (!code) {
return NULL;
}
*position += value_length + 1;
value = PyObject_CallFunctionObjArgs(state->Code, code, NULL, NULL);
Py_DECREF(code);
break;
}
case 15:
{
int code_length,
scope_size;
PyObject* code;
PyObject* scope;
*position += 8;
code_length = strlen(buffer + *position);
if (max < 8 + code_length) {
goto invalid;
}
code = PyUnicode_DecodeUTF8(buffer + *position, code_length, "strict");
if (!code) {
return NULL;
}
*position += code_length + 1;
memcpy(&scope_size, buffer + *position, 4);
scope = elements_to_dict(self, buffer + *position + 4, scope_size - 5,
(PyObject*)&PyDict_Type, tz_aware);
if (!scope) {
Py_DECREF(code);
return NULL;
}
*position += scope_size;
value = PyObject_CallFunctionObjArgs(state->Code, code, scope, NULL);
Py_DECREF(code);
Py_DECREF(scope);
break;
}
case 16:
{
int i;
if (max < 4) {
goto invalid;
}
memcpy(&i, buffer + *position, 4);
#if PY_MAJOR_VERSION >= 3
value = PyLong_FromLong(i);
#else
value = PyInt_FromLong(i);
#endif
if (!value) {
return NULL;
}
*position += 4;
break;
}
case 17:
{
unsigned int time, inc;
if (max < 8) {
goto invalid;
}
memcpy(&inc, buffer + *position, 4);
memcpy(&time, buffer + *position + 4, 4);
value = PyObject_CallFunction(state->Timestamp, "II", time, inc);
if (!value) {
return NULL;
}
*position += 8;
break;
}
case 18:
{
long long ll;
if (max < 8) {
goto invalid;
}
memcpy(&ll, buffer + *position, 8);
value = PyLong_FromLongLong(ll);
if (!value) {
return NULL;
}
*position += 8;
break;
}
case -1:
{
value = PyObject_CallFunctionObjArgs(state->MinKey, NULL);
break;
}
case 127:
{
value = PyObject_CallFunctionObjArgs(state->MaxKey, NULL);
break;
}
default:
{
PyObject* InvalidDocument = _error("InvalidDocument");
PyErr_SetString(InvalidDocument, "no c decoder for this type yet");
Py_DECREF(InvalidDocument);
return NULL;
}
}
return value;
invalid:
error = _error("InvalidBSON");
PyErr_SetNone(error);
Py_DECREF(error);
return NULL;
}
static PyObject* elements_to_dict(PyObject* self, const char* string, int max,
PyObject* as_class, unsigned char tz_aware) {
int position = 0;
PyObject* dict = PyObject_CallObject(as_class, NULL);
if (!dict) {
return NULL;
}
while (position < max) {
PyObject* name;
PyObject* value;
int type = (int)string[position++];
int name_length = strlen(string + position);
if (position + name_length >= max) {
PyObject* InvalidBSON = _error("InvalidBSON");
PyErr_SetNone(InvalidBSON);
Py_DECREF(InvalidBSON);
return NULL;
}
name = PyUnicode_DecodeUTF8(string + position, name_length, "strict");
if (!name) {
return NULL;
}
position += name_length + 1;
value = get_value(self, string, &position, type, max - position, as_class, tz_aware);
if (!value) {
return NULL;
}
PyObject_SetItem(dict, name, value);
Py_DECREF(name);
Py_DECREF(value);
}
return dict;
}
static PyObject* _cbson_bson_to_dict(PyObject* self, PyObject* args) {
unsigned int size;
Py_ssize_t total_size;
const char* string;
PyObject* bson;
PyObject* as_class;
unsigned char tz_aware;
PyObject* dict;
PyObject* remainder;
PyObject* result;
if (!PyArg_ParseTuple(args, "OOb", &bson, &as_class, &tz_aware)) {
return NULL;
}
#if PY_MAJOR_VERSION >= 3
if (!PyBytes_Check(bson)) {
PyErr_SetString(PyExc_TypeError, "argument to _bson_to_dict must be a bytes object");
#else
if (!PyString_Check(bson)) {
PyErr_SetString(PyExc_TypeError, "argument to _bson_to_dict must be a string");
#endif
return NULL;
}
#if PY_MAJOR_VERSION >= 3
total_size = PyBytes_Size(bson);
#else
total_size = PyString_Size(bson);
#endif
if (total_size < 5) {
PyObject* InvalidBSON = _error("InvalidBSON");
PyErr_SetString(InvalidBSON,
"not enough data for a BSON document");
Py_DECREF(InvalidBSON);
return NULL;
}
#if PY_MAJOR_VERSION >= 3
string = PyBytes_AsString(bson);
#else
string = PyString_AsString(bson);
#endif
if (!string) {
return NULL;
}
memcpy(&size, string, 4);
if (total_size < size) {
PyObject* InvalidBSON = _error("InvalidBSON");
PyErr_SetString(InvalidBSON,
"objsize too large");
Py_DECREF(InvalidBSON);
return NULL;
}
if (string[size - 1]) {
PyObject* InvalidBSON = _error("InvalidBSON");
PyErr_SetString(InvalidBSON,
"bad eoo");
Py_DECREF(InvalidBSON);
return NULL;
}
dict = elements_to_dict(self, string + 4, size - 5, as_class, tz_aware);
if (!dict) {
return NULL;
}
#if PY_MAJOR_VERSION >= 3
remainder = PyBytes_FromStringAndSize(string + size, total_size - size);
#else
remainder = PyString_FromStringAndSize(string + size, total_size - size);
#endif
if (!remainder) {
Py_DECREF(dict);
return NULL;
}
result = Py_BuildValue("OO", dict, remainder);
Py_DECREF(dict);
Py_DECREF(remainder);
return result;
}
static PyObject* _cbson_decode_all(PyObject* self, PyObject* args) {
unsigned int size;
Py_ssize_t total_size;
const char* string;
PyObject* bson;
PyObject* dict;
PyObject* result;
PyObject* as_class = (PyObject*)&PyDict_Type;
unsigned char tz_aware = 1;
if (!PyArg_ParseTuple(args, "O|Ob", &bson, &as_class, &tz_aware)) {
return NULL;
}
#if PY_MAJOR_VERSION >= 3
if (!PyBytes_Check(bson)) {
PyErr_SetString(PyExc_TypeError, "argument to decode_all must be a bytes object");
#else
if (!PyString_Check(bson)) {
PyErr_SetString(PyExc_TypeError, "argument to decode_all must be a string");
#endif
return NULL;
}
#if PY_MAJOR_VERSION >= 3
total_size = PyBytes_Size(bson);
string = PyBytes_AsString(bson);
#else
total_size = PyString_Size(bson);
string = PyString_AsString(bson);
#endif
if (!string) {
return NULL;
}
result = PyList_New(0);
while (total_size > 0) {
if (total_size < 5) {
PyObject* InvalidBSON = _error("InvalidBSON");
PyErr_SetString(InvalidBSON,
"not enough data for a BSON document");
Py_DECREF(InvalidBSON);
return NULL;
}
memcpy(&size, string, 4);
if (total_size < size) {
PyObject* InvalidBSON = _error("InvalidBSON");
PyErr_SetString(InvalidBSON,
"objsize too large");
Py_DECREF(InvalidBSON);
return NULL;
}
if (string[size - 1]) {
PyObject* InvalidBSON = _error("InvalidBSON");
PyErr_SetString(InvalidBSON,
"bad eoo");
Py_DECREF(InvalidBSON);
return NULL;
}
dict = elements_to_dict(self, string + 4, size - 5, as_class, tz_aware);
if (!dict) {
return NULL;
}
PyList_Append(result, dict);
Py_DECREF(dict);
string += size;
total_size -= size;
}
return result;
}
static PyMethodDef _CBSONMethods[] = {
{"_dict_to_bson", _cbson_dict_to_bson, METH_VARARGS,
"convert a dictionary to a string containing its BSON representation."},
{"_bson_to_dict", _cbson_bson_to_dict, METH_VARARGS,
"convert a BSON string to a SON object."},
{"decode_all", _cbson_decode_all, METH_VARARGS,
"convert binary data to a sequence of documents."},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define INITERROR return NULL
static int _cbson_traverse(PyObject *m, visitproc visit, void *arg) {
Py_VISIT(GETSTATE(m)->Binary);
Py_VISIT(GETSTATE(m)->Code);
Py_VISIT(GETSTATE(m)->ObjectId);
Py_VISIT(GETSTATE(m)->DBRef);
Py_VISIT(GETSTATE(m)->RECompile);
Py_VISIT(GETSTATE(m)->UUID);
Py_VISIT(GETSTATE(m)->Timestamp);
Py_VISIT(GETSTATE(m)->MinKey);
Py_VISIT(GETSTATE(m)->MaxKey);
Py_VISIT(GETSTATE(m)->UTC);
Py_VISIT(GETSTATE(m)->REType);
return 0;
}
static int _cbson_clear(PyObject *m) {
Py_CLEAR(GETSTATE(m)->Binary);
Py_CLEAR(GETSTATE(m)->Code);
Py_CLEAR(GETSTATE(m)->ObjectId);
Py_CLEAR(GETSTATE(m)->DBRef);
Py_CLEAR(GETSTATE(m)->RECompile);
Py_CLEAR(GETSTATE(m)->UUID);
Py_CLEAR(GETSTATE(m)->Timestamp);
Py_CLEAR(GETSTATE(m)->MinKey);
Py_CLEAR(GETSTATE(m)->MaxKey);
Py_CLEAR(GETSTATE(m)->UTC);
Py_CLEAR(GETSTATE(m)->REType);
return 0;
}
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_cbson",
NULL,
sizeof(struct module_state),
_CBSONMethods,
NULL,
_cbson_traverse,
_cbson_clear,
NULL
};
PyMODINIT_FUNC
PyInit__cbson(void)
#else
#define INITERROR return
PyMODINIT_FUNC
init_cbson(void)
#endif
{
PyObject *m;
PyObject *c_api_object;
static void *_cbson_API[_cbson_API_POINTER_COUNT];
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&moduledef);
#else
m = Py_InitModule("_cbson", _CBSONMethods);
#endif
if (m == NULL) {
INITERROR;
}
PyDateTime_IMPORT;
if (PyDateTimeAPI == NULL) {
Py_DECREF(m);
INITERROR;
}
/* Import several python objects */
if (_reload_python_objects(m)) {
Py_DECREF(m);
INITERROR;
}
/* Export C API */
_cbson_API[_cbson_buffer_write_bytes_INDEX] = (void *) buffer_write_bytes;
_cbson_API[_cbson_write_dict_INDEX] = (void *) write_dict;
_cbson_API[_cbson_write_pair_INDEX] = (void *) write_pair;
_cbson_API[_cbson_decode_and_write_pair_INDEX] = (void *) decode_and_write_pair;
#if PY_VERSION_HEX >= 0x03010000
/* PyCapsule is new in python 3.1 */
c_api_object = PyCapsule_New((void *) _cbson_API, "_cbson._C_API", NULL);
#else
c_api_object = PyCObject_FromVoidPtr((void *) _cbson_API, NULL);
#endif
if (c_api_object != NULL) {
PyModule_AddObject(m, "_C_API", c_api_object);
}
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}
|