Skip to content

Commit

Permalink
don't allow null character in strings being encoded
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Dirolf committed Jun 18, 2009
1 parent 51bf841 commit b839cd7
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
14 changes: 12 additions & 2 deletions pymongo/_cbsonmodule.c
Expand Up @@ -26,6 +26,7 @@

static PyObject* CBSONError;
static PyObject* InvalidName;
static PyObject* InvalidDocument;
static PyObject* SON;
static PyObject* Binary;
static PyObject* Code;
Expand Down Expand Up @@ -177,12 +178,20 @@ static int write_shuffled_oid(bson_buffer* buffer, const char* oid) {

/* returns 0 on failure */
static int write_string(bson_buffer* buffer, PyObject* py_string) {
int string_length;
int i;
Py_ssize_t string_length;
const char* string = PyString_AsString(py_string);
if (!string) {
return 1;
}
string_length = strlen(string) + 1;
string_length = PyString_Size(py_string) + 1;

for (i = 0; i < string_length - 1; i++) {
if (string[i] == 0) {
PyErr_SetString(InvalidDocument, "BSON strings must not contain a NULL character");
return 0;
}
}

if (!buffer_write_bytes(buffer, (const char*)&string_length, 4)) {
return 0;
Expand Down Expand Up @@ -1189,6 +1198,7 @@ PyMODINIT_FUNC init_cbson(void) {
}
CBSONError = PyObject_GetAttrString(module, "InvalidDocument");
InvalidName = PyObject_GetAttrString(module, "InvalidName");
InvalidDocument = PyObject_GetAttrString(module, "InvalidDocument");
Py_DECREF(module);

module = PyImport_ImportModule("pymongo.son");
Expand Down
2 changes: 2 additions & 0 deletions pymongo/bson.py
Expand Up @@ -56,6 +56,8 @@ def _get_c_string(data):


def _make_c_string(string):
if "\x00" in string:
raise InvalidDocument("BSON strings must not contain a NULL character")
return string.encode("utf-8") + "\x00"


Expand Down
6 changes: 5 additions & 1 deletion test/test_bson.py
Expand Up @@ -30,7 +30,7 @@
from pymongo.dbref import DBRef
from pymongo.son import SON
from pymongo.bson import BSON, is_valid, _to_dicts
from pymongo.errors import UnsupportedTag
from pymongo.errors import UnsupportedTag, InvalidDocument


class TestBSON(unittest.TestCase):
Expand Down Expand Up @@ -131,6 +131,10 @@ def test_basic_from_dict(self):
"\x00\x05\x00\x00\x00coll\x00\x07$id\x00\x07\x06\x05"
"\x04\x03\x02\x01\x00\x0B\x0A\x09\x08\x00\x00")

def test_null_character_encoding(self):
self.assertRaises(InvalidDocument, BSON.from_dict, {"with zero": "hello\x00world"})
self.assertRaises(InvalidDocument, BSON.from_dict, {"with zero": u"hello\x00world"})

def test_from_then_to_dict(self):

def helper(dict):
Expand Down

0 comments on commit b839cd7

Please sign in to comment.