ctdb: Remove an unnecessary cast
[vlendec/samba-autobuild/.git] / lib / ldb / pyldb.c
index 6e845d15c36cf56a3e9eeecc2b4decda1e529483..5d995243d4462457f4aa9ff5e986df253b6abff3 100644 (file)
    License along with this library; if not, see <http://www.gnu.org/licenses/>.
 */
 
-#include <Python.h>
+#include "lib/replace/system/python.h"
 #include "ldb_private.h"
 #include "ldb_handlers.h"
 #include "pyldb.h"
 #include "dlinklist.h"
 
+/* discard signature of 'func' in favour of 'target_sig' */
+#define PY_DISCARD_FUNC_SIG(target_sig, func) (target_sig)(void(*)(void))func
+
 struct py_ldb_search_iterator_reply;
 
 typedef struct {
@@ -63,17 +66,13 @@ static PyTypeObject PyLdbResult;
 static PyTypeObject PyLdbSearchIterator;
 static PyTypeObject PyLdbMessage;
 #define PyLdbMessage_Check(ob) PyObject_TypeCheck(ob, &PyLdbMessage)
-static PyTypeObject PyLdbModule;
 static PyTypeObject PyLdbDn;
 #define pyldb_Dn_Check(ob) PyObject_TypeCheck(ob, &PyLdbDn)
 static PyTypeObject PyLdb;
-#define PyLdb_Check(ob) PyObject_TypeCheck(ob, &PyLdb)
 static PyTypeObject PyLdbMessageElement;
 #define pyldb_MessageElement_Check(ob) PyObject_TypeCheck(ob, &PyLdbMessageElement)
 
 static PyTypeObject PyLdbTree;
-static PyObject *PyLdb_FromLdbContext(struct ldb_context *ldb_ctx);
-static PyObject *PyLdbModule_FromModule(struct ldb_module *mod);
 static struct ldb_message_element *PyObject_AsMessageElement(
                                                      TALLOC_CTX *mem_ctx,
                                                      PyObject *set_obj,
@@ -81,16 +80,6 @@ static struct ldb_message_element *PyObject_AsMessageElement(
                                                      const char *attr_name);
 static PyTypeObject PyLdbBytesType;
 
-#if PY_MAJOR_VERSION >= 3
-#define PyStr_Check PyUnicode_Check
-#define PyStr_FromString PyUnicode_FromString
-#define PyStr_FromStringAndSize PyUnicode_FromStringAndSize
-#define PyStr_FromFormat PyUnicode_FromFormat
-#define PyStr_FromFormatV PyUnicode_FromFormatV
-#define PyStr_AsUTF8 PyUnicode_AsUTF8
-#define PyStr_AsUTF8AndSize PyUnicode_AsUTF8AndSize
-#define PyInt_FromLong PyLong_FromLong
-
 #define PYARG_STR_UNI "es"
 
 static PyObject *PyLdbBytes_FromStringAndSize(const char *msg, int size)
@@ -98,32 +87,13 @@ static PyObject *PyLdbBytes_FromStringAndSize(const char *msg, int size)
        PyObject* result = NULL;
        PyObject* args = NULL;
        args = Py_BuildValue("(y#)", msg, size);
+       if (args == NULL) {
+               return NULL;
+       }
        result = PyLdbBytesType.tp_new(&PyLdbBytesType, args, NULL);
        Py_DECREF(args);
        return result;
 }
-#else
-#define PyStr_Check PyString_Check
-#define PyStr_FromString PyString_FromString
-#define PyStr_FromStringAndSize PyString_FromStringAndSize
-#define PyStr_FromFormat PyString_FromFormat
-#define PyStr_FromFormatV PyString_FromFormatV
-#define PyStr_AsUTF8 PyString_AsString
-#define PyLdbBytes_FromStringAndSize PyString_FromStringAndSize
-
-#define PYARG_STR_UNI "et"
-
-const char *PyStr_AsUTF8AndSize(PyObject *pystr, Py_ssize_t *sizeptr);
-const char *
-PyStr_AsUTF8AndSize(PyObject *pystr, Py_ssize_t *sizeptr)
-{
-       const char * ret = PyString_AsString(pystr);
-       if (ret == NULL)
-               return NULL;
-       *sizeptr = PyString_Size(pystr);
-       return ret;
-}
-#endif
 
 static PyObject *richcmp(int cmp_val, int op)
 {
@@ -151,9 +121,9 @@ static PyObject *py_ldb_control_str(PyLdbControlObject *self)
                        PyErr_NoMemory();
                        return NULL;
                }
-               return PyStr_FromString(control);
+               return PyUnicode_FromString(control);
        } else {
-               return PyStr_FromString("ldb control");
+               return PyUnicode_FromString("ldb control");
        }
 }
 
@@ -189,18 +159,24 @@ static PyObject *wrap_text(const char *type, PyObject *wrapped)
        return inst;
 }
 
-static PyObject *py_ldb_control_get_oid(PyLdbControlObject *self)
+static PyObject *py_ldb_control_get_oid(PyLdbControlObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       return PyStr_FromString(self->data->oid);
+       return PyUnicode_FromString(self->data->oid);
 }
 
-static PyObject *py_ldb_control_get_critical(PyLdbControlObject *self)
+static PyObject *py_ldb_control_get_critical(PyLdbControlObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        return PyBool_FromLong(self->data->critical);
 }
 
-static PyObject *py_ldb_control_set_critical(PyLdbControlObject *self, PyObject *value, void *closure)
+static int py_ldb_control_set_critical(PyLdbControlObject *self, PyObject *value, void *closure)
 {
+       if (value == NULL) {
+               PyErr_SetString(PyExc_AttributeError, "cannot delete critical flag");
+               return -1;
+       }
        if (PyObject_IsTrue(value)) {
                self->data->critical = true;
        } else {
@@ -230,7 +206,7 @@ static PyObject *py_ldb_control_new(PyTypeObject *type, PyObject *args, PyObject
                return NULL;
        }
 
-       ldb_ctx = pyldb_Ldb_AsLdbContext(py_ldb);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(py_ldb);
        parsed_controls = ldb_parse_control_from_string(ldb_ctx, mem_ctx, data);
 
        if (!parsed_controls) {
@@ -286,13 +262,25 @@ static PyTypeObject PyLdbControl = {
 
 static void PyErr_SetLdbError(PyObject *error, int ret, struct ldb_context *ldb_ctx)
 {
-       if (ret == LDB_ERR_PYTHON_EXCEPTION)
+       PyObject *exc = NULL;
+       if (ret == LDB_ERR_PYTHON_EXCEPTION) {
                return; /* Python exception should already be set, just keep that */
-
-       PyErr_SetObject(error, 
-                       Py_BuildValue(discard_const_p(char, "(i,s)"), ret,
-                                     ldb_ctx == NULL?ldb_strerror(ret):ldb_errstring(ldb_ctx)));
+       }
+       exc = Py_BuildValue("(i,s)", ret,
+                           ldb_ctx == NULL?ldb_strerror(ret):ldb_errstring(ldb_ctx));
+       if (exc == NULL) {
+               /*
+                * Py_BuildValue failed, and will have set its own exception.
+                * It isn't the one we wanted, but it will have to do.
+                * This is all very unexpected.
+                */
+               fprintf(stderr, "could not make LdbError %d!\n", ret);
+               return;
+       }
+       PyErr_SetObject(error, exc);
+       Py_DECREF(exc);
 }
+
 static PyObject *py_ldb_bytes_str(PyBytesObject *self)
 {
        char *msg = NULL;
@@ -325,7 +313,7 @@ static PyObject *PyObject_FromLdbValue(const struct ldb_val *val)
 
 static PyObject *PyStr_FromLdbValue(const struct ldb_val *val)
 {
-       return PyStr_FromStringAndSize((const char *)val->data, val->length);
+       return PyUnicode_FromStringAndSize((const char *)val->data, val->length);
 }
 
 /**
@@ -389,7 +377,13 @@ static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
        }
 
        for (i = 0; i < result->count; i++) {
-               PyList_SetItem(list, i, PyLdbMessage_FromMessage(result->msgs[i]));
+               PyObject *pymessage = PyLdbMessage_FromMessage(result->msgs[i]);
+               if (pymessage == NULL) {
+                       Py_DECREF(ret);
+                       Py_DECREF(list);
+                       return NULL;
+               }
+               PyList_SetItem(list, i, pymessage);
        }
 
        ret->mem_ctx = talloc_new(NULL);
@@ -410,6 +404,7 @@ static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
                controls = PyList_New(i);
                if (controls == NULL) {
                        Py_DECREF(ret);
+                       Py_DECREF(list);
                        PyErr_NoMemory();
                        return NULL;
                }
@@ -417,6 +412,7 @@ static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
                        PyObject *ctrl = (PyObject*) PyLdbControl_FromControl(result->controls[i]);
                        if (ctrl == NULL) {
                                Py_DECREF(ret);
+                               Py_DECREF(list);
                                Py_DECREF(controls);
                                PyErr_NoMemory();
                                return NULL;
@@ -430,6 +426,7 @@ static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
                controls = PyList_New(0);
                if (controls == NULL) {
                        Py_DECREF(ret);
+                       Py_DECREF(list);
                        PyErr_NoMemory();
                        return NULL;
                }
@@ -446,85 +443,64 @@ static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
        referals = PyList_New(i);
        if (referals == NULL) {
                Py_DECREF(ret);
+               Py_DECREF(list);
                PyErr_NoMemory();
                return NULL;
        }
 
        for (i = 0;result->refs && result->refs[i]; i++) {
-               PyList_SetItem(referals, i, PyStr_FromString(result->refs[i]));
+               PyList_SetItem(referals, i, PyUnicode_FromString(result->refs[i]));
        }
        ret->referals = referals;
        return (PyObject *)ret;
 }
 
-/**
- * Create a LDB Result from a Python object.
- * If conversion fails, NULL will be returned and a Python exception set.
- *
- * Note: the result object only includes the messages at the moment; extended
- * result, controls and referrals are ignored.
- *
- * @param mem_ctx Memory context in which to allocate the LDB Result
- * @param obj Python object to convert
- * @return a ldb_result, or NULL if the conversion failed
- */
-static struct ldb_result *PyLdbResult_AsResult(TALLOC_CTX *mem_ctx, 
-                                              PyObject *obj)
-{
-       struct ldb_result *res;
-       Py_ssize_t i;
-
-       if (obj == Py_None)
-               return NULL;
-
-       res = talloc_zero(mem_ctx, struct ldb_result);
-       res->count = PyList_Size(obj);
-       res->msgs = talloc_array(res, struct ldb_message *, res->count);
-       for (i = 0; i < res->count; i++) {
-               PyObject *item = PyList_GetItem(obj, i);
-               res->msgs[i] = pyldb_Message_AsMessage(item);
-       }
-       return res;
-}
-
-static PyObject *py_ldb_dn_validate(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_validate(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        return PyBool_FromLong(ldb_dn_validate(self->dn));
 }
 
-static PyObject *py_ldb_dn_is_valid(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_is_valid(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        return PyBool_FromLong(ldb_dn_is_valid(self->dn));
 }
 
-static PyObject *py_ldb_dn_is_special(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_is_special(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        return PyBool_FromLong(ldb_dn_is_special(self->dn));
 }
 
-static PyObject *py_ldb_dn_is_null(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_is_null(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        return PyBool_FromLong(ldb_dn_is_null(self->dn));
 }
-static PyObject *py_ldb_dn_get_casefold(PyLdbDnObject *self)
+
+static PyObject *py_ldb_dn_get_casefold(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       return PyStr_FromString(ldb_dn_get_casefold(self->dn));
+       return PyUnicode_FromString(ldb_dn_get_casefold(self->dn));
 }
 
-static PyObject *py_ldb_dn_get_linearized(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_get_linearized(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       return PyStr_FromString(ldb_dn_get_linearized(self->dn));
+       return PyUnicode_FromString(ldb_dn_get_linearized(self->dn));
 }
 
-static PyObject *py_ldb_dn_canonical_str(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_canonical_str(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       return PyStr_FromString(ldb_dn_canonical_string(self->dn, self->dn));
+       return PyUnicode_FromString(ldb_dn_canonical_string(self->dn, self->dn));
 }
 
-static PyObject *py_ldb_dn_canonical_ex_str(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_canonical_ex_str(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       return PyStr_FromString(ldb_dn_canonical_ex_string(self->dn, self->dn));
+       return PyUnicode_FromString(ldb_dn_canonical_ex_string(self->dn, self->dn));
 }
 
 static PyObject *py_ldb_dn_extended_str(PyLdbDnObject *self, PyObject *args, PyObject *kwargs)
@@ -535,7 +511,7 @@ static PyObject *py_ldb_dn_extended_str(PyLdbDnObject *self, PyObject *args, PyO
                                         discard_const_p(char *, kwnames),
                                         &mode))
                return NULL;
-       return PyStr_FromString(ldb_dn_get_extended_linearized(self->dn, self->dn, mode));
+       return PyUnicode_FromString(ldb_dn_get_extended_linearized(self->dn, self->dn, mode));
 }
 
 static PyObject *py_ldb_dn_get_extended_component(PyLdbDnObject *self, PyObject *args)
@@ -582,7 +558,7 @@ static PyObject *py_ldb_dn_set_extended_component(PyLdbDnObject *self, PyObject
 
 static PyObject *py_ldb_dn_repr(PyLdbDnObject *self)
 {
-       PyObject *str = PyStr_FromString(ldb_dn_get_linearized(self->dn));
+       PyObject *str = PyUnicode_FromString(ldb_dn_get_linearized(self->dn));
        PyObject *repr, *result;
        if (str == NULL)
                return NULL;
@@ -591,7 +567,7 @@ static PyObject *py_ldb_dn_repr(PyLdbDnObject *self)
                Py_DECREF(str);
                return NULL;
        }
-       result = PyStr_FromFormat("Dn(%s)", PyStr_AsUTF8(repr));
+       result = PyUnicode_FromFormat("Dn(%s)", PyUnicode_AsUTF8(repr));
        Py_DECREF(str);
        Py_DECREF(repr);
        return result;
@@ -614,21 +590,33 @@ static PyObject *py_ldb_dn_richcmp(PyObject *dn1, PyObject *dn2, int op)
                Py_INCREF(Py_NotImplemented);
                return Py_NotImplemented;
        }
-       ret = ldb_dn_compare(pyldb_Dn_AsDn(dn1), pyldb_Dn_AsDn(dn2));
+       ret = ldb_dn_compare(pyldb_Dn_AS_DN(dn1), pyldb_Dn_AS_DN(dn2));
        return richcmp(ret, op);
 }
 
-static PyObject *py_ldb_dn_get_parent(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_get_parent(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_dn *dn = pyldb_Dn_AsDn((PyObject *)self);
+       struct ldb_dn *dn = pyldb_Dn_AS_DN((PyObject *)self);
        struct ldb_dn *parent;
        PyLdbDnObject *py_ret;
-       TALLOC_CTX *mem_ctx = talloc_new(NULL);
+       TALLOC_CTX *mem_ctx = NULL;
+
+       if (ldb_dn_get_comp_num(dn) < 1) {
+               Py_RETURN_NONE;
+       }
+
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
 
        parent = ldb_dn_get_parent(mem_ctx, dn);
        if (parent == NULL) {
+               PyErr_NoMemory();
                talloc_free(mem_ctx);
-               Py_RETURN_NONE;
+               return NULL;
        }
 
        py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
@@ -646,42 +634,63 @@ static PyObject *py_ldb_dn_add_child(PyLdbDnObject *self, PyObject *args)
 {
        PyObject *py_other;
        struct ldb_dn *dn, *other;
+       bool ok;
        if (!PyArg_ParseTuple(args, "O", &py_other))
                return NULL;
 
-       dn = pyldb_Dn_AsDn((PyObject *)self);
+       dn = pyldb_Dn_AS_DN((PyObject *)self);
 
        if (!pyldb_Object_AsDn(NULL, py_other, ldb_dn_get_ldb_context(dn), &other))
                return NULL;
 
-       return PyBool_FromLong(ldb_dn_add_child(dn, other));
+       ok = ldb_dn_add_child(dn, other);
+       if (!ok) {
+               PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, NULL);
+               return NULL;
+       }
+
+       Py_RETURN_TRUE;
 }
 
 static PyObject *py_ldb_dn_add_base(PyLdbDnObject *self, PyObject *args)
 {
        PyObject *py_other;
        struct ldb_dn *other, *dn;
+       bool ok;
        if (!PyArg_ParseTuple(args, "O", &py_other))
                return NULL;
 
-       dn = pyldb_Dn_AsDn((PyObject *)self);
+       dn = pyldb_Dn_AS_DN((PyObject *)self);
 
        if (!pyldb_Object_AsDn(NULL, py_other, ldb_dn_get_ldb_context(dn), &other))
                return NULL;
 
-       return PyBool_FromLong(ldb_dn_add_base(dn, other));
+       ok = ldb_dn_add_base(dn, other);
+       if (!ok) {
+               PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, NULL);
+               return NULL;
+       }
+
+       Py_RETURN_TRUE;
 }
 
 static PyObject *py_ldb_dn_remove_base_components(PyLdbDnObject *self, PyObject *args)
 {
        struct ldb_dn *dn;
        int i;
+       bool ok;
        if (!PyArg_ParseTuple(args, "i", &i))
                return NULL;
 
-       dn = pyldb_Dn_AsDn((PyObject *)self);
+       dn = pyldb_Dn_AS_DN((PyObject *)self);
+
+       ok = ldb_dn_remove_base_components(dn, i);
+       if (!ok) {
+               PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, NULL);
+               return NULL;
+       }
 
-       return PyBool_FromLong(ldb_dn_remove_base_components(dn, i));
+       Py_RETURN_TRUE;
 }
 
 static PyObject *py_ldb_dn_is_child_of(PyLdbDnObject *self, PyObject *args)
@@ -691,7 +700,7 @@ static PyObject *py_ldb_dn_is_child_of(PyLdbDnObject *self, PyObject *args)
        if (!PyArg_ParseTuple(args, "O", &py_base))
                return NULL;
 
-       dn = pyldb_Dn_AsDn((PyObject *)self);
+       dn = pyldb_Dn_AS_DN((PyObject *)self);
 
        if (!pyldb_Object_AsDn(NULL, py_base, ldb_dn_get_ldb_context(dn), &base))
                return NULL;
@@ -708,14 +717,14 @@ static PyObject *py_ldb_dn_get_component_name(PyLdbDnObject *self, PyObject *arg
        if (!PyArg_ParseTuple(args, "I", &num))
                return NULL;
 
-       dn = pyldb_Dn_AsDn((PyObject *)self);
+       dn = pyldb_Dn_AS_DN((PyObject *)self);
 
        name = ldb_dn_get_component_name(dn, num);
        if (name == NULL) {
                Py_RETURN_NONE;
        }
 
-       return PyStr_FromString(name);
+       return PyUnicode_FromString(name);
 }
 
 static PyObject *py_ldb_dn_get_component_value(PyLdbDnObject *self, PyObject *args)
@@ -727,7 +736,7 @@ static PyObject *py_ldb_dn_get_component_value(PyLdbDnObject *self, PyObject *ar
        if (!PyArg_ParseTuple(args, "I", &num))
                return NULL;
 
-       dn = pyldb_Dn_AsDn((PyObject *)self);
+       dn = pyldb_Dn_AS_DN((PyObject *)self);
 
        val = ldb_dn_get_component_val(dn, num);
        if (val == NULL) {
@@ -741,7 +750,7 @@ static PyObject *py_ldb_dn_set_component(PyLdbDnObject *self, PyObject *args)
 {
        unsigned int num = 0;
        char *name = NULL, *value = NULL;
-       struct ldb_val val = { NULL, };
+       struct ldb_val val = { 0 };
        int err;
        Py_ssize_t size = 0;
 
@@ -760,27 +769,29 @@ static PyObject *py_ldb_dn_set_component(PyLdbDnObject *self, PyObject *args)
        Py_RETURN_NONE;
 }
 
-static PyObject *py_ldb_dn_get_rdn_name(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_get_rdn_name(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        struct ldb_dn *dn;
        const char *name;
 
-       dn = pyldb_Dn_AsDn((PyObject *)self);
+       dn = pyldb_Dn_AS_DN((PyObject *)self);
 
        name = ldb_dn_get_rdn_name(dn);
        if (name == NULL) {
                Py_RETURN_NONE;
        }
 
-       return PyStr_FromString(name);
+       return PyUnicode_FromString(name);
 }
 
-static PyObject *py_ldb_dn_get_rdn_value(PyLdbDnObject *self)
+static PyObject *py_ldb_dn_get_rdn_value(PyLdbDnObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        struct ldb_dn *dn;
        const struct ldb_val *val;
 
-       dn = pyldb_Dn_AsDn((PyObject *)self);
+       dn = pyldb_Dn_AS_DN((PyObject *)self);
 
        val = ldb_dn_get_rdn_val(dn);
        if (val == NULL) {
@@ -791,7 +802,7 @@ static PyObject *py_ldb_dn_get_rdn_value(PyLdbDnObject *self)
 }
 
 static PyMethodDef py_ldb_dn_methods[] = {
-       { "validate", (PyCFunction)py_ldb_dn_validate, METH_NOARGS, 
+       { "validate", (PyCFunction)py_ldb_dn_validate, METH_NOARGS,
                "S.validate() -> bool\n"
                "Validate DN is correct." },
        { "is_valid", (PyCFunction)py_ldb_dn_is_valid, METH_NOARGS,
@@ -803,7 +814,9 @@ static PyMethodDef py_ldb_dn_methods[] = {
                "Check whether this is a null DN." },
        { "get_casefold", (PyCFunction)py_ldb_dn_get_casefold, METH_NOARGS,
                NULL },
-       { "get_linearized", (PyCFunction)py_ldb_dn_get_linearized, METH_NOARGS,
+       { "get_linearized", PY_DISCARD_FUNC_SIG(PyCFunction,
+                                               py_ldb_dn_get_linearized),
+               METH_NOARGS,
                NULL },
        { "canonical_str", (PyCFunction)py_ldb_dn_canonical_str, METH_NOARGS,
                "S.canonical_str() -> string\n"
@@ -813,17 +826,19 @@ static PyMethodDef py_ldb_dn_methods[] = {
        { "canonical_ex_str", (PyCFunction)py_ldb_dn_canonical_ex_str, METH_NOARGS,
                "S.canonical_ex_str() -> string\n"
                "Canonical version of this DN (like a posix path, with terminating newline)." },
-       { "extended_str", (PyCFunction)py_ldb_dn_extended_str, METH_VARARGS | METH_KEYWORDS,
+       { "extended_str", PY_DISCARD_FUNC_SIG(PyCFunction,
+                                             py_ldb_dn_extended_str),
+               METH_VARARGS | METH_KEYWORDS,
                "S.extended_str(mode=1) -> string\n"
                "Extended version of this DN" },
        { "parent", (PyCFunction)py_ldb_dn_get_parent, METH_NOARGS,
                "S.parent() -> dn\n"
                "Get the parent for this DN." },
-       { "add_child", (PyCFunction)py_ldb_dn_add_child, METH_VARARGS, 
-               "S.add_child(dn) -> None\n"
+       { "add_child", (PyCFunction)py_ldb_dn_add_child, METH_VARARGS,
+               "S.add_child(dn) -> bool\n"
                "Add a child DN to this DN." },
        { "add_base", (PyCFunction)py_ldb_dn_add_base, METH_VARARGS,
-               "S.add_base(dn) -> None\n"
+               "S.add_base(dn) -> bool\n"
                "Add a base DN to this DN." },
        { "remove_base_components", (PyCFunction)py_ldb_dn_remove_base_components, METH_VARARGS,
                "S.remove_base_components(int) -> bool\n"
@@ -844,7 +859,7 @@ static PyMethodDef py_ldb_dn_methods[] = {
                "S.get_component_value(num) -> string\n"
                "get the attribute value of the specified component as a binary string" },
        { "set_component", (PyCFunction)py_ldb_dn_set_component, METH_VARARGS,
-               "S.get_component_value(num, name, value) -> None\n"
+               "S.set_component(num, name, value) -> None\n"
                "set the attribute name and value of the specified component" },
        { "get_rdn_name", (PyCFunction)py_ldb_dn_get_rdn_name, METH_NOARGS,
                "S.get_rdn_name() -> string\n"
@@ -852,12 +867,12 @@ static PyMethodDef py_ldb_dn_methods[] = {
        { "get_rdn_value", (PyCFunction)py_ldb_dn_get_rdn_value, METH_NOARGS,
                "S.get_rdn_value() -> string\n"
                "get the RDN attribute value as a binary string" },
-       { NULL }
+       {0}
 };
 
 static Py_ssize_t py_ldb_dn_len(PyLdbDnObject *self)
 {
-       return ldb_dn_get_comp_num(pyldb_Dn_AsDn((PyObject *)self));
+       return ldb_dn_get_comp_num(pyldb_Dn_AS_DN((PyObject *)self));
 }
 
 /*
@@ -865,35 +880,69 @@ static Py_ssize_t py_ldb_dn_len(PyLdbDnObject *self)
  */
 static PyObject *py_ldb_dn_copy(struct ldb_dn *dn)
 {
+       TALLOC_CTX *mem_ctx = NULL;
+       struct ldb_dn *new_dn = NULL;
        PyLdbDnObject *py_ret;
 
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               return PyErr_NoMemory();
+       }
+
+       new_dn = ldb_dn_copy(mem_ctx, dn);
+       if (new_dn == NULL) {
+               talloc_free(mem_ctx);
+               return PyErr_NoMemory();
+       }
+
        py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
        if (py_ret == NULL) {
+               talloc_free(mem_ctx);
                PyErr_NoMemory();
                return NULL;
        }
-       py_ret->mem_ctx = talloc_new(NULL);
-       py_ret->dn = ldb_dn_copy(py_ret->mem_ctx, dn);
+       py_ret->mem_ctx = mem_ctx;
+       py_ret->dn = new_dn;
        return (PyObject *)py_ret;
 }
 
 static PyObject *py_ldb_dn_concat(PyLdbDnObject *self, PyObject *py_other)
 {
-       struct ldb_dn *dn = pyldb_Dn_AsDn((PyObject *)self), 
+       TALLOC_CTX *mem_ctx = NULL;
+       struct ldb_dn *dn = pyldb_Dn_AS_DN((PyObject *)self),
                                  *other;
+       struct ldb_dn *new_dn = NULL;
        PyLdbDnObject *py_ret;
 
        if (!pyldb_Object_AsDn(NULL, py_other, NULL, &other))
                return NULL;
 
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               return PyErr_NoMemory();
+       }
+
+       new_dn = ldb_dn_copy(mem_ctx, dn);
+       if (new_dn == NULL) {
+               talloc_free(mem_ctx);
+               return PyErr_NoMemory();
+       }
+
+       if (!ldb_dn_add_base(new_dn, other)) {
+               PyErr_SetString(PyExc_RuntimeError, "unable to concatenate DNs");
+               talloc_free(mem_ctx);
+               return NULL;
+       }
+
        py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
        if (py_ret == NULL) {
+               talloc_free(mem_ctx);
                PyErr_NoMemory();
                return NULL;
        }
-       py_ret->mem_ctx = talloc_new(NULL);
-       py_ret->dn = ldb_dn_copy(py_ret->mem_ctx, dn);
-       ldb_dn_add_base(py_ret->dn, other);
+       py_ret->mem_ctx = mem_ctx;
+       py_ret->dn = new_dn;
+
        return (PyObject *)py_ret;
 }
 
@@ -912,17 +961,12 @@ static PyObject *py_ldb_dn_new(PyTypeObject *type, PyObject *args, PyObject *kwa
        PyLdbDnObject *py_ret = NULL;
        const char * const kwnames[] = { "ldb", "dn", NULL };
 
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O"PYARG_STR_UNI,
+       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!"PYARG_STR_UNI,
                                         discard_const_p(char *, kwnames),
-                                        &py_ldb, "utf8", &str))
+                                        &PyLdb, &py_ldb, "utf8", &str))
                goto out;
 
-       if (!PyLdb_Check(py_ldb)) {
-               PyErr_SetString(PyExc_TypeError, "Expected Ldb");
-               goto out;
-       }
-
-       ldb_ctx = pyldb_Ldb_AsLdbContext(py_ldb);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(py_ldb);
 
        mem_ctx = talloc_new(NULL);
        if (mem_ctx == NULL) {
@@ -977,7 +1021,9 @@ static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *
 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap)
 {
        PyObject *fn = (PyObject *)context;
-       PyObject_CallFunction(fn, discard_const_p(char, "(i,O)"), level, PyStr_FromFormatV(fmt, ap));
+       PyObject *result = NULL;
+       result = PyObject_CallFunction(fn, discard_const_p(char, "(i,O)"), level, PyUnicode_FromFormatV(fmt, ap));
+       Py_XDECREF(result);
 }
 
 static PyObject *py_ldb_debug_func;
@@ -997,7 +1043,7 @@ static PyObject *py_ldb_set_debug(PyObject *self, PyObject *args)
        Py_INCREF(cb);
        /* FIXME: DECREF cb when exiting program */
        py_ldb_debug_func = cb;
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError,
                ldb_set_debug(ldb_ctx, py_ldb_debug, cb),
                ldb_ctx);
@@ -1011,7 +1057,7 @@ static PyObject *py_ldb_set_create_perms(PyTypeObject *self, PyObject *args)
        if (!PyArg_ParseTuple(args, "I", &perms))
                return NULL;
 
-       ldb_set_create_perms(pyldb_Ldb_AsLdbContext(self), perms);
+       ldb_set_create_perms(pyldb_Ldb_AS_LDBCONTEXT(self), perms);
 
        Py_RETURN_NONE;
 }
@@ -1022,50 +1068,55 @@ static PyObject *py_ldb_set_modules_dir(PyTypeObject *self, PyObject *args)
        if (!PyArg_ParseTuple(args, "s", &modules_dir))
                return NULL;
 
-       ldb_set_modules_dir(pyldb_Ldb_AsLdbContext(self), modules_dir);
+       ldb_set_modules_dir(pyldb_Ldb_AS_LDBCONTEXT(self), modules_dir);
 
        Py_RETURN_NONE;
 }
 
-static PyObject *py_ldb_transaction_start(PyLdbObject *self)
+static PyObject *py_ldb_transaction_start(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_context *ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       struct ldb_context *ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        int ldb_err;
        ldb_err = ldb_transaction_start(ldb_ctx);
        PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_err, ldb_ctx);
        Py_RETURN_NONE;
 }
 
-static PyObject *py_ldb_transaction_commit(PyLdbObject *self)
+static PyObject *py_ldb_transaction_commit(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_context *ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       struct ldb_context *ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        int ldb_err;
        ldb_err = ldb_transaction_commit(ldb_ctx);
        PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_err, ldb_ctx);
        Py_RETURN_NONE;
 }
 
-static PyObject *py_ldb_transaction_prepare_commit(PyLdbObject *self)
+static PyObject *py_ldb_transaction_prepare_commit(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_context *ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       struct ldb_context *ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        int ldb_err;
        ldb_err = ldb_transaction_prepare_commit(ldb_ctx);
        PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_err, ldb_ctx);
        Py_RETURN_NONE;
 }
 
-static PyObject *py_ldb_transaction_cancel(PyLdbObject *self)
+static PyObject *py_ldb_transaction_cancel(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_context *ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       struct ldb_context *ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        int ldb_err;
        ldb_err = ldb_transaction_cancel(ldb_ctx);
        PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_err, ldb_ctx);
        Py_RETURN_NONE;
 }
 
-static PyObject *py_ldb_setup_wellknown_attributes(PyLdbObject *self)
+static PyObject *py_ldb_setup_wellknown_attributes(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_context *ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       struct ldb_context *ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        int ldb_err;
        ldb_err = ldb_setup_wellknown_attributes(ldb_ctx);
        PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_err, ldb_ctx);
@@ -1074,37 +1125,41 @@ static PyObject *py_ldb_setup_wellknown_attributes(PyLdbObject *self)
 
 static PyObject *py_ldb_repr(PyLdbObject *self)
 {
-       return PyStr_FromString("<ldb connection>");
+       return PyUnicode_FromString("<ldb connection>");
 }
 
-static PyObject *py_ldb_get_root_basedn(PyLdbObject *self)
+static PyObject *py_ldb_get_root_basedn(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_dn *dn = ldb_get_root_basedn(pyldb_Ldb_AsLdbContext(self));
+       struct ldb_dn *dn = ldb_get_root_basedn(pyldb_Ldb_AS_LDBCONTEXT(self));
        if (dn == NULL)
                Py_RETURN_NONE;
        return py_ldb_dn_copy(dn);
 }
 
 
-static PyObject *py_ldb_get_schema_basedn(PyLdbObject *self)
+static PyObject *py_ldb_get_schema_basedn(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_dn *dn = ldb_get_schema_basedn(pyldb_Ldb_AsLdbContext(self));
+       struct ldb_dn *dn = ldb_get_schema_basedn(pyldb_Ldb_AS_LDBCONTEXT(self));
        if (dn == NULL)
                Py_RETURN_NONE;
        return py_ldb_dn_copy(dn);
 }
 
-static PyObject *py_ldb_get_config_basedn(PyLdbObject *self)
+static PyObject *py_ldb_get_config_basedn(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_dn *dn = ldb_get_config_basedn(pyldb_Ldb_AsLdbContext(self));
+       struct ldb_dn *dn = ldb_get_config_basedn(pyldb_Ldb_AS_LDBCONTEXT(self));
        if (dn == NULL)
                Py_RETURN_NONE;
        return py_ldb_dn_copy(dn);
 }
 
-static PyObject *py_ldb_get_default_basedn(PyLdbObject *self)
+static PyObject *py_ldb_get_default_basedn(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_dn *dn = ldb_get_default_basedn(pyldb_Ldb_AsLdbContext(self));
+       struct ldb_dn *dn = ldb_get_default_basedn(pyldb_Ldb_AS_LDBCONTEXT(self));
        if (dn == NULL)
                Py_RETURN_NONE;
        return py_ldb_dn_copy(dn);
@@ -1129,12 +1184,12 @@ static const char **PyList_AsStrList(TALLOC_CTX *mem_ctx, PyObject *list,
                const char *str = NULL;
                Py_ssize_t size;
                PyObject *item = PyList_GetItem(list, i);
-               if (!(PyStr_Check(item) || PyUnicode_Check(item))) {
+               if (!PyUnicode_Check(item)) {
                        PyErr_Format(PyExc_TypeError, "%s should be strings", paramname);
                        talloc_free(ret);
                        return NULL;
                }
-               str = PyStr_AsUTF8AndSize(item, &size);
+               str = PyUnicode_AsUTF8AndSize(item, &size);
                if (str == NULL) {
                        talloc_free(ret);
                        return NULL;
@@ -1160,7 +1215,7 @@ static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
                                         &url, &flags, &py_options))
                return -1;
 
-       ldb = pyldb_Ldb_AsLdbContext(self);
+       ldb = pyldb_Ldb_AS_LDBCONTEXT(self);
 
        if (py_options == Py_None) {
                options = NULL;
@@ -1174,8 +1229,11 @@ static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
                ret = ldb_connect(ldb, url, flags, options);
                if (ret != LDB_SUCCESS) {
                        PyErr_SetLdbError(PyExc_LdbError, ret, ldb);
+                       talloc_free(options);
                        return -1;
                }
+       } else {
+               ldb_set_flags(ldb, flags);
        }
 
        talloc_free(options);
@@ -1184,20 +1242,29 @@ static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
 
 static PyObject *py_ldb_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
 {
+       TALLOC_CTX *mem_ctx = NULL;
        PyLdbObject *ret;
        struct ldb_context *ldb;
-       ret = (PyLdbObject *)type->tp_alloc(type, 0);
-       if (ret == NULL) {
+
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               return PyErr_NoMemory();
+       }
+
+       ldb = ldb_init(mem_ctx, NULL);
+       if (ldb == NULL) {
+               talloc_free(mem_ctx);
                PyErr_NoMemory();
                return NULL;
        }
-       ret->mem_ctx = talloc_new(NULL);
-       ldb = ldb_init(ret->mem_ctx, NULL);
 
-       if (ldb == NULL) {
+       ret = (PyLdbObject *)type->tp_alloc(type, 0);
+       if (ret == NULL) {
+               talloc_free(mem_ctx);
                PyErr_NoMemory();
                return NULL;
        }
+       ret->mem_ctx = mem_ctx;
 
        ret->ldb_ctx = ldb;
        return (PyObject *)ret;
@@ -1226,7 +1293,7 @@ static PyObject *py_ldb_connect(PyLdbObject *self, PyObject *args, PyObject *kwa
                        return NULL;
        }
 
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        ret = ldb_connect(ldb_ctx, url, flags, options);
        talloc_free(options);
 
@@ -1258,7 +1325,7 @@ static PyObject *py_ldb_modify(PyLdbObject *self, PyObject *args, PyObject *kwar
                PyErr_NoMemory();
                return NULL;
        }
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
 
        if (py_controls == Py_None) {
                parsed_controls = NULL;
@@ -1269,6 +1336,11 @@ static PyObject *py_ldb_modify(PyLdbObject *self, PyObject *args, PyObject *kwar
                        return NULL;
                }
                parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
+               if (controls[0] != NULL && parsed_controls == NULL) {
+                       talloc_free(mem_ctx);
+                       PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, ldb_ctx);
+                       return NULL;
+               }
                talloc_free(controls);
        }
 
@@ -1351,31 +1423,62 @@ static struct ldb_message *PyDict_AsMessage(TALLOC_CTX *mem_ctx,
                return NULL;
        }
        msg->elements = talloc_zero_array(msg, struct ldb_message_element, PyDict_Size(py_obj));
+       if (msg->elements == NULL) {
+               PyErr_NoMemory();
+               TALLOC_FREE(msg);
+               return NULL;
+       }
 
        if (dn_value) {
                if (!pyldb_Object_AsDn(msg, dn_value, ldb_ctx, &msg->dn)) {
                        PyErr_SetString(PyExc_TypeError, "unable to import dn object");
+                       TALLOC_FREE(msg);
                        return NULL;
                }
                if (msg->dn == NULL) {
                        PyErr_SetString(PyExc_TypeError, "dn set but not found");
+                       TALLOC_FREE(msg);
                        return NULL;
                }
        } else {
                PyErr_SetString(PyExc_TypeError, "no dn set");
+               TALLOC_FREE(msg);
                return NULL;
        }
 
        while (PyDict_Next(py_obj, &dict_pos, &key, &value)) {
-               const char *key_str = PyStr_AsUTF8(key);
+               const char *key_str = PyUnicode_AsUTF8(key);
                if (ldb_attr_cmp(key_str, "dn") != 0) {
                        msg_el = PyObject_AsMessageElement(msg->elements, value,
                                                           mod_flags, key_str);
                        if (msg_el == NULL) {
                                PyErr_Format(PyExc_TypeError, "unable to import element '%s'", key_str);
+                               TALLOC_FREE(msg);
                                return NULL;
                        }
                        memcpy(&msg->elements[msg_pos], msg_el, sizeof(*msg_el));
+
+                       /*
+                        * PyObject_AsMessageElement might have returned a
+                        * reference to an existing MessageElement, and so left
+                        * the name and flags unchanged. Thus if those members
+                        * aren’t set, we’ll assume that the user forgot to
+                        * initialize them.
+                        */
+                       if (msg->elements[msg_pos].name == NULL) {
+                               /* No name was set â€” set it now. */
+                               msg->elements[msg_pos].name = talloc_strdup(msg->elements, key_str);
+                               if (msg->elements[msg_pos].name == NULL) {
+                                       PyErr_NoMemory();
+                                       TALLOC_FREE(msg);
+                                       return NULL;
+                               }
+                       }
+                       if (msg->elements[msg_pos].flags == 0) {
+                               /* No flags were set â€” set them now. */
+                               msg->elements[msg_pos].flags = mod_flags;
+                       }
+
                        msg_pos++;
                }
        }
@@ -1407,7 +1510,7 @@ static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args, PyObject *kwargs)
                PyErr_NoMemory();
                return NULL;
        }
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
 
        if (py_controls == Py_None) {
                parsed_controls = NULL;
@@ -1418,6 +1521,11 @@ static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args, PyObject *kwargs)
                        return NULL;
                }
                parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
+               if (controls[0] != NULL && parsed_controls == NULL) {
+                       talloc_free(mem_ctx);
+                       PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, ldb_ctx);
+                       return NULL;
+               }
                talloc_free(controls);
        }
 
@@ -1500,7 +1608,7 @@ static PyObject *py_ldb_delete(PyLdbObject *self, PyObject *args, PyObject *kwar
                PyErr_NoMemory();
                return NULL;
        }
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
 
        if (py_controls == Py_None) {
                parsed_controls = NULL;
@@ -1511,6 +1619,11 @@ static PyObject *py_ldb_delete(PyLdbObject *self, PyObject *args, PyObject *kwar
                        return NULL;
                }
                parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
+               if (controls[0] != NULL && parsed_controls == NULL) {
+                       talloc_free(mem_ctx);
+                       PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, ldb_ctx);
+                       return NULL;
+               }
                talloc_free(controls);
        }
 
@@ -1566,7 +1679,7 @@ static PyObject *py_ldb_rename(PyLdbObject *self, PyObject *args, PyObject *kwar
        struct ldb_request *req;
        const char * const kwnames[] = { "dn1", "dn2", "controls", NULL };
 
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
 
        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|O",
                                         discard_const_p(char *, kwnames),
@@ -1589,6 +1702,11 @@ static PyObject *py_ldb_rename(PyLdbObject *self, PyObject *args, PyObject *kwar
                        return NULL;
                }
                parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
+               if (controls[0] != NULL && parsed_controls == NULL) {
+                       talloc_free(mem_ctx);
+                       PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, ldb_ctx);
+                       return NULL;
+               }
                talloc_free(controls);
        }
 
@@ -1644,7 +1762,7 @@ static PyObject *py_ldb_schema_attribute_remove(PyLdbObject *self, PyObject *arg
        if (!PyArg_ParseTuple(args, "s", &name))
                return NULL;
 
-       ldb_schema_attribute_remove(pyldb_Ldb_AsLdbContext(self), name);
+       ldb_schema_attribute_remove(pyldb_Ldb_AS_LDBCONTEXT(self), name);
 
        Py_RETURN_NONE;
 }
@@ -1659,7 +1777,7 @@ static PyObject *py_ldb_schema_attribute_add(PyLdbObject *self, PyObject *args)
        if (!PyArg_ParseTuple(args, "sIs", &attribute, &flags, &syntax))
                return NULL;
 
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        ret = ldb_schema_attribute_add(ldb_ctx, attribute, flags, syntax);
 
        PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
@@ -1667,20 +1785,97 @@ static PyObject *py_ldb_schema_attribute_add(PyLdbObject *self, PyObject *args)
        Py_RETURN_NONE;
 }
 
-static PyObject *ldb_ldif_to_pyobject(struct ldb_ldif *ldif)
+static PyObject *ldb_ldif_to_pyobject(struct ldb_context *ldb, struct ldb_ldif *ldif)
 {
+       PyObject *obj = NULL;
+       PyObject *result = NULL;
+
        if (ldif == NULL) {
                Py_RETURN_NONE;
-       } else {
-       /* We don't want this attached to the 'ldb' any more */
-               PyObject *obj = PyLdbMessage_FromMessage(ldif->msg);
-               PyObject *result =
-                       Py_BuildValue(discard_const_p(char, "(iO)"),
-                                     ldif->changetype,
-                                     obj);
-               Py_CLEAR(obj);
-               return result;
        }
+
+       switch (ldif->changetype) {
+       case LDB_CHANGETYPE_NONE:
+       case LDB_CHANGETYPE_ADD:
+               obj = PyLdbMessage_FromMessage(ldif->msg);
+               break;
+       case LDB_CHANGETYPE_MODIFY:
+               obj = PyLdbMessage_FromMessage(ldif->msg);
+               break;
+       case LDB_CHANGETYPE_DELETE:
+               if (ldif->msg->num_elements != 0) {
+                       PyErr_Format(PyExc_ValueError,
+                                    "CHANGETYPE(DELETE) with num_elements=%u",
+                                    ldif->msg->num_elements);
+                       return NULL;
+               }
+               obj = pyldb_Dn_FromDn(ldif->msg->dn);
+               break;
+       case LDB_CHANGETYPE_MODRDN: {
+               struct ldb_dn *olddn = NULL;
+               PyObject *olddn_obj = NULL;
+               bool deleteoldrdn = false;
+               PyObject *deleteoldrdn_obj = NULL;
+               struct ldb_dn *newdn = NULL;
+               PyObject *newdn_obj = NULL;
+               int ret;
+
+               ret = ldb_ldif_parse_modrdn(ldb,
+                                           ldif,
+                                           ldif,
+                                           &olddn,
+                                           NULL,
+                                           &deleteoldrdn,
+                                           NULL,
+                                           &newdn);
+               if (ret != LDB_SUCCESS) {
+                       PyErr_Format(PyExc_ValueError,
+                                    "ldb_ldif_parse_modrdn() failed");
+                       return NULL;
+               }
+
+               olddn_obj = pyldb_Dn_FromDn(olddn);
+               if (olddn_obj == NULL) {
+                       return NULL;
+               }
+               if (deleteoldrdn) {
+                       deleteoldrdn_obj = Py_True;
+               } else {
+                       deleteoldrdn_obj = Py_False;
+               }
+               newdn_obj = pyldb_Dn_FromDn(newdn);
+               if (newdn_obj == NULL) {
+                       deleteoldrdn_obj = NULL;
+                       Py_CLEAR(olddn_obj);
+                       return NULL;
+               }
+
+               obj = Py_BuildValue(discard_const_p(char, "{s:O,s:O,s:O}"),
+                                   "olddn", olddn_obj,
+                                   "deleteoldrdn", deleteoldrdn_obj,
+                                   "newdn", newdn_obj);
+               Py_CLEAR(olddn_obj);
+               deleteoldrdn_obj = NULL;
+               Py_CLEAR(newdn_obj);
+               }
+               break;
+       default:
+               PyErr_Format(PyExc_NotImplementedError,
+                            "Unsupported LDB_CHANGETYPE(%u)",
+                            ldif->changetype);
+               return NULL;
+       }
+
+       if (obj == NULL) {
+               return NULL;
+       }
+
+       /* We don't want this being attached * to the 'ldb' any more */
+       result = Py_BuildValue(discard_const_p(char, "(iO)"),
+                              ldif->changetype,
+                              obj);
+       Py_CLEAR(obj);
+       return result;
 }
 
 
@@ -1705,14 +1900,18 @@ static PyObject *py_ldb_write_ldif(PyLdbObject *self, PyObject *args)
        ldif.changetype = changetype;
 
        mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               return PyErr_NoMemory();
+       }
 
-       string = ldb_ldif_write_string(pyldb_Ldb_AsLdbContext(self), mem_ctx, &ldif);
+       string = ldb_ldif_write_string(pyldb_Ldb_AS_LDBCONTEXT(self), mem_ctx, &ldif);
        if (!string) {
                PyErr_SetString(PyExc_KeyError, "Failed to generate LDIF");
+               talloc_free(mem_ctx);
                return NULL;
        }
 
-       ret = PyStr_FromString(string);
+       ret = PyUnicode_FromString(string);
 
        talloc_free(mem_ctx);
 
@@ -1737,15 +1936,22 @@ static PyObject *py_ldb_parse_ldif(PyLdbObject *self, PyObject *args)
        }
 
        list = PyList_New(0);
+       if (list == NULL) {
+               talloc_free(mem_ctx);
+               return NULL;
+       }
+
        while (s && *s != '\0') {
                ldif = ldb_ldif_read_string(self->ldb_ctx, &s);
                talloc_steal(mem_ctx, ldif);
                if (ldif) {
                        int res = 0;
-                       PyObject *py_ldif = ldb_ldif_to_pyobject(ldif);
+                       PyObject *py_ldif = ldb_ldif_to_pyobject(self->ldb_ctx, ldif);
                        if (py_ldif == NULL) {
                                Py_CLEAR(list);
-                               PyErr_BadArgument();
+                               if (PyErr_Occurred() == NULL) {
+                                       PyErr_BadArgument();
+                               }
                                talloc_free(mem_ctx);
                                return NULL;
                        }
@@ -1799,6 +2005,7 @@ static PyObject *py_ldb_msg_diff(PyLdbObject *self, PyObject *args)
        struct ldb_message *diff;
        struct ldb_context *ldb;
        PyObject *py_ret;
+       TALLOC_CTX *mem_ctx = NULL;
 
        if (!PyArg_ParseTuple(args, "OO", &py_msg_old, &py_msg_new))
                return NULL;
@@ -1813,19 +2020,33 @@ static PyObject *py_ldb_msg_diff(PyLdbObject *self, PyObject *args)
                return NULL;
        }
 
-       ldb = pyldb_Ldb_AsLdbContext(self);
-       ldb_ret = ldb_msg_difference(ldb, ldb,
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
+
+       ldb = pyldb_Ldb_AS_LDBCONTEXT(self);
+       ldb_ret = ldb_msg_difference(ldb, mem_ctx,
                                     pyldb_Message_AsMessage(py_msg_old),
                                     pyldb_Message_AsMessage(py_msg_new),
                                     &diff);
        if (ldb_ret != LDB_SUCCESS) {
+               talloc_free(mem_ctx);
                PyErr_SetString(PyExc_RuntimeError, "Failed to generate the Ldb Message diff");
                return NULL;
        }
 
+       diff = ldb_msg_copy(mem_ctx, diff);
+       if (diff == NULL) {
+               talloc_free(mem_ctx);
+               PyErr_NoMemory();
+               return NULL;
+       }
+
        py_ret = PyLdbMessage_FromMessage(diff);
 
-       talloc_unlink(ldb, diff);
+       talloc_free(mem_ctx);
 
        return py_ret;
 }
@@ -1853,7 +2074,7 @@ static PyObject *py_ldb_schema_format_value(PyLdbObject *self, PyObject *args)
                return NULL;
        }
 
-       a = ldb_schema_attribute_by_name(pyldb_Ldb_AsLdbContext(self), element_name);
+       a = ldb_schema_attribute_by_name(pyldb_Ldb_AS_LDBCONTEXT(self), element_name);
 
        if (a == NULL) {
                Py_RETURN_NONE;
@@ -1865,7 +2086,7 @@ static PyObject *py_ldb_schema_format_value(PyLdbObject *self, PyObject *args)
                return NULL;
        }
 
-       if (a->syntax->ldif_write_fn(pyldb_Ldb_AsLdbContext(self), mem_ctx, &old_val, &new_val) != 0) {
+       if (a->syntax->ldif_write_fn(pyldb_Ldb_AS_LDBCONTEXT(self), mem_ctx, &old_val, &new_val) != 0) {
                talloc_free(mem_ctx);
                Py_RETURN_NONE;
        }
@@ -1907,7 +2128,7 @@ static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwar
                PyErr_NoMemory();
                return NULL;
        }
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
 
        if (py_attrs == Py_None) {
                attrs = NULL;
@@ -1937,6 +2158,11 @@ static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwar
                        return NULL;
                }
                parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
+               if (controls[0] != NULL && parsed_controls == NULL) {
+                       talloc_free(mem_ctx);
+                       PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, ldb_ctx);
+                       return NULL;
+               }
                talloc_free(controls);
        }
 
@@ -1994,10 +2220,7 @@ static int py_ldb_search_iterator_reply_destructor(struct py_ldb_search_iterator
                reply->py_iter = NULL;
        }
 
-       if (reply->obj != NULL) {
-               Py_DECREF(reply->obj);
-               reply->obj = NULL;
-       }
+       Py_CLEAR(reply->obj);
 
        return 0;
 }
@@ -2040,7 +2263,7 @@ static int py_ldb_search_iterator_callback(struct ldb_request *req,
                return LDB_SUCCESS;
 
        case LDB_REPLY_REFERRAL:
-               reply->obj = PyStr_FromString(ares->referral);
+               reply->obj = PyUnicode_FromString(ares->referral);
                if (reply->obj == NULL) {
                        TALLOC_FREE(ares);
                        return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
@@ -2102,7 +2325,7 @@ static PyObject *py_ldb_search_iterator(PyLdbObject *self, PyObject *args, PyObj
                return NULL;
        }
 
-       ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
 
        if (py_attrs == Py_None) {
                attrs = NULL;
@@ -2143,7 +2366,7 @@ static PyObject *py_ldb_search_iterator(PyLdbObject *self, PyObject *args, PyObj
                                                            controls);
                if (controls[0] != NULL && parsed_controls == NULL) {
                        Py_DECREF(py_iter);
-                       PyErr_NoMemory();
+                       PyErr_SetLdbError(PyExc_LdbError, LDB_ERR_OPERATIONS_ERROR, ldb_ctx);
                        return NULL;
                }
                talloc_free(controls);
@@ -2186,63 +2409,130 @@ static PyObject *py_ldb_get_opaque(PyLdbObject *self, PyObject *args)
        if (!PyArg_ParseTuple(args, "s", &name))
                return NULL;
 
-       data = ldb_get_opaque(pyldb_Ldb_AsLdbContext(self), name);
+       data = ldb_get_opaque(pyldb_Ldb_AS_LDBCONTEXT(self), name);
 
        if (data == NULL)
                Py_RETURN_NONE;
 
-       /* FIXME: More interpretation */
+       if (data == (void *)1) {
+               /*
+                * This value is sometimes used to indicate that a opaque is
+                * set.
+                */
+               Py_RETURN_TRUE;
+       }
 
-       Py_RETURN_TRUE;
+       {
+               /*
+                * Let’s hope the opaque data is actually a talloc pointer,
+                * otherwise calling this would be Very Bad.
+                */
+               const bool *opaque = talloc_get_type(data, bool);
+               if (opaque != NULL) {
+                       return PyBool_FromLong(*opaque);
+               }
+       }
+
+       {
+               const unsigned long long *opaque = talloc_get_type(
+                       data, unsigned long long);
+               if (opaque != NULL) {
+                       return PyLong_FromUnsignedLongLong(*opaque);
+               }
+       }
+
+       {
+               const char *opaque = talloc_get_type(data, char);
+               if (opaque != NULL) {
+                       return PyUnicode_FromString(opaque);
+               }
+       }
+
+       PyErr_SetString(PyExc_ValueError, "Unsupported type for opaque");
+       return NULL;
 }
 
 static PyObject *py_ldb_set_opaque(PyLdbObject *self, PyObject *args)
 {
        char *name;
        PyObject *data;
+       void *value = NULL;
+       int ret;
 
        if (!PyArg_ParseTuple(args, "sO", &name, &data))
                return NULL;
 
-       /* FIXME: More interpretation */
-
-       ldb_set_opaque(pyldb_Ldb_AsLdbContext(self), name, data);
-
-       Py_RETURN_NONE;
-}
-
-static PyObject *py_ldb_modules(PyLdbObject *self)
-{
-       struct ldb_context *ldb = pyldb_Ldb_AsLdbContext(self);
-       PyObject *ret = PyList_New(0);
-       struct ldb_module *mod;
+       if (data == Py_None) {
+               value = NULL;
+       } else if (PyBool_Check(data)) {
+               bool *opaque = NULL;
+               bool b;
+               {
+                       const int is_true = PyObject_IsTrue(data);
+                       if (is_true == -1) {
+                               return NULL;
+                       }
+                       b = is_true;
+               }
 
-       if (ret == NULL) {
-               return PyErr_NoMemory();
-       }
-       for (mod = ldb->modules; mod; mod = mod->next) {
-               PyObject *item = PyLdbModule_FromModule(mod);
-               int res = 0;
-               if (item == NULL) {
-                       PyErr_SetString(PyExc_RuntimeError,
-                               "Failed to load LdbModule");
-                       Py_CLEAR(ret);
+               opaque = talloc(self->ldb_ctx, bool);
+               if (opaque == NULL) {
+                       return PyErr_NoMemory();
+               }
+               *opaque = b;
+               value = opaque;
+       } else if (PyLong_Check(data)) {
+               unsigned long long *opaque = NULL;
+               const unsigned long long n = PyLong_AsUnsignedLongLong(data);
+               if (n == -1 && PyErr_Occurred()) {
                        return NULL;
                }
-               res = PyList_Append(ret, item);
-               Py_CLEAR(item);
-               if (res == -1) {
-                       Py_CLEAR(ret);
+
+               opaque = talloc(self->ldb_ctx, unsigned long long);
+               if (opaque == NULL) {
+                       return PyErr_NoMemory();
+               }
+               *opaque = n;
+               value = opaque;
+       } else if (PyUnicode_Check(data)) {
+               char *opaque = NULL;
+               const char *s = PyUnicode_AsUTF8(data);
+               if (s == NULL) {
                        return NULL;
                }
+
+               opaque = talloc_strdup(self->ldb_ctx, s);
+               if (opaque == NULL) {
+                       return PyErr_NoMemory();
+               }
+
+               /*
+                * Assign the right type to the talloc pointer, so that
+                * py_ldb_get_opaque() can recognize it.
+                */
+               talloc_set_name_const(opaque, "char");
+
+               value = opaque;
+       } else {
+               PyErr_SetString(PyExc_ValueError,
+                               "Unsupported type for opaque");
+               return NULL;
        }
 
-       return ret;
+       ret = ldb_set_opaque(pyldb_Ldb_AS_LDBCONTEXT(self), name, value);
+       if (ret) {
+               PyErr_SetLdbError(PyExc_LdbError,
+                                 ret,
+                                 pyldb_Ldb_AS_LDBCONTEXT(self));
+               return NULL;
+       }
+
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_sequence_number(PyLdbObject *self, PyObject *args)
 {
-       struct ldb_context *ldb = pyldb_Ldb_AsLdbContext(self);
+       struct ldb_context *ldb = pyldb_Ldb_AS_LDBCONTEXT(self);
        int type, ret;
        uint64_t value;
 
@@ -2258,17 +2548,48 @@ static PyObject *py_ldb_sequence_number(PyLdbObject *self, PyObject *args)
        return PyLong_FromLongLong(value);
 }
 
+static PyObject *py_ldb_whoami(PyLdbObject *self, PyObject *args)
+{
+       struct ldb_context *ldb = pyldb_Ldb_AS_LDBCONTEXT(self);
+       struct ldb_result *res = NULL;
+       struct ldb_extended *ext_res = NULL;
+       size_t len = 0;
+       int ret;
 
-static const struct ldb_dn_extended_syntax test_dn_syntax = {
-       .name             = "TEST",
-       .read_fn          = ldb_handler_copy,
-       .write_clear_fn   = ldb_handler_copy,
-       .write_hex_fn     = ldb_handler_copy,
+       ret = ldb_extended(ldb, LDB_EXTENDED_WHOAMI_OID, NULL, &res);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
+
+       ext_res = res->extended;
+       if (ext_res == NULL) {
+               PyErr_SetString(PyExc_TypeError, "Got no exop reply");
+               return NULL;
+       }
+
+       if (strcmp(ext_res->oid, LDB_EXTENDED_WHOAMI_OID) != 0) {
+               PyErr_SetString(PyExc_TypeError, "Got wrong reply OID");
+               return NULL;
+       }
+
+       len = talloc_get_size(ext_res->data);
+       if (len == 0) {
+               Py_RETURN_NONE;
+       }
+
+       return PyUnicode_FromStringAndSize(ext_res->data, len);
+}
+
+
+static const struct ldb_dn_extended_syntax test_dn_syntax = {
+       .name             = "TEST",
+       .read_fn          = ldb_handler_copy,
+       .write_clear_fn   = ldb_handler_copy,
+       .write_hex_fn     = ldb_handler_copy,
 };
 
-static PyObject *py_ldb_register_test_extensions(PyLdbObject *self)
+static PyObject *py_ldb_register_test_extensions(PyLdbObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
-       struct ldb_context *ldb = pyldb_Ldb_AsLdbContext(self);
+       struct ldb_context *ldb = pyldb_Ldb_AS_LDBCONTEXT(self);
        int ret;
 
        ret = ldb_dn_extended_add_syntax(ldb, LDB_ATTR_FLAG_FIXED, &test_dn_syntax);
@@ -2280,29 +2601,29 @@ static PyObject *py_ldb_register_test_extensions(PyLdbObject *self)
 
 
 static PyMethodDef py_ldb_methods[] = {
-       { "set_debug", (PyCFunction)py_ldb_set_debug, METH_VARARGS, 
+       { "set_debug", (PyCFunction)py_ldb_set_debug, METH_VARARGS,
                "S.set_debug(callback) -> None\n"
                "Set callback for LDB debug messages.\n"
                "The callback should accept a debug level and debug text." },
-       { "set_create_perms", (PyCFunction)py_ldb_set_create_perms, METH_VARARGS, 
+       { "set_create_perms", (PyCFunction)py_ldb_set_create_perms, METH_VARARGS,
                "S.set_create_perms(mode) -> None\n"
                "Set mode to use when creating new LDB files." },
        { "set_modules_dir", (PyCFunction)py_ldb_set_modules_dir, METH_VARARGS,
                "S.set_modules_dir(path) -> None\n"
                "Set path LDB should search for modules" },
-       { "transaction_start", (PyCFunction)py_ldb_transaction_start, METH_NOARGS, 
+       { "transaction_start", (PyCFunction)py_ldb_transaction_start, METH_NOARGS,
                "S.transaction_start() -> None\n"
                "Start a new transaction." },
        { "transaction_prepare_commit", (PyCFunction)py_ldb_transaction_prepare_commit, METH_NOARGS,
                "S.transaction_prepare_commit() -> None\n"
                "prepare to commit a new transaction (2-stage commit)." },
-       { "transaction_commit", (PyCFunction)py_ldb_transaction_commit, METH_NOARGS, 
+       { "transaction_commit", (PyCFunction)py_ldb_transaction_commit, METH_NOARGS,
                "S.transaction_commit() -> None\n"
                "commit a new transaction." },
-       { "transaction_cancel", (PyCFunction)py_ldb_transaction_cancel, METH_NOARGS, 
+       { "transaction_cancel", (PyCFunction)py_ldb_transaction_cancel, METH_NOARGS,
                "S.transaction_cancel() -> None\n"
                "cancel a new transaction." },
-       { "setup_wellknown_attributes", (PyCFunction)py_ldb_setup_wellknown_attributes, METH_NOARGS, 
+       { "setup_wellknown_attributes", (PyCFunction)py_ldb_setup_wellknown_attributes, METH_NOARGS,
                NULL },
        { "get_root_basedn", (PyCFunction)py_ldb_get_root_basedn, METH_NOARGS,
                NULL },
@@ -2312,22 +2633,28 @@ static PyMethodDef py_ldb_methods[] = {
                NULL },
        { "get_config_basedn", (PyCFunction)py_ldb_get_config_basedn, METH_NOARGS,
                NULL },
-       { "connect", (PyCFunction)py_ldb_connect, METH_VARARGS|METH_KEYWORDS, 
+       { "connect", PY_DISCARD_FUNC_SIG(PyCFunction, py_ldb_connect),
+               METH_VARARGS|METH_KEYWORDS,
                "S.connect(url, flags=0, options=None) -> None\n"
                "Connect to a LDB URL." },
-       { "modify", (PyCFunction)py_ldb_modify, METH_VARARGS|METH_KEYWORDS,
+       { "modify", PY_DISCARD_FUNC_SIG(PyCFunction, py_ldb_modify),
+               METH_VARARGS|METH_KEYWORDS,
                "S.modify(message, controls=None, validate=False) -> None\n"
                "Modify an entry." },
-       { "add", (PyCFunction)py_ldb_add, METH_VARARGS|METH_KEYWORDS,
+       { "add", PY_DISCARD_FUNC_SIG(PyCFunction, py_ldb_add),
+               METH_VARARGS|METH_KEYWORDS,
                "S.add(message, controls=None) -> None\n"
                "Add an entry." },
-       { "delete", (PyCFunction)py_ldb_delete, METH_VARARGS|METH_KEYWORDS,
+       { "delete", PY_DISCARD_FUNC_SIG(PyCFunction, py_ldb_delete),
+               METH_VARARGS|METH_KEYWORDS,
                "S.delete(dn, controls=None) -> None\n"
                "Remove an entry." },
-       { "rename", (PyCFunction)py_ldb_rename, METH_VARARGS|METH_KEYWORDS,
+       { "rename", PY_DISCARD_FUNC_SIG(PyCFunction, py_ldb_rename),
+               METH_VARARGS|METH_KEYWORDS,
                "S.rename(old_dn, new_dn, controls=None) -> None\n"
                "Rename an entry." },
-       { "search", (PyCFunction)py_ldb_search, METH_VARARGS|METH_KEYWORDS,
+       { "search", PY_DISCARD_FUNC_SIG(PyCFunction, py_ldb_search),
+               METH_VARARGS|METH_KEYWORDS,
                "S.search(base=None, scope=None, expression=None, attrs=None, controls=None) -> result\n"
                "Search in a database.\n"
                "\n"
@@ -2338,7 +2665,9 @@ static PyMethodDef py_ldb_methods[] = {
                ":param controls: Optional list of controls\n"
                ":return: ldb.Result object\n"
        },
-       { "search_iterator", (PyCFunction)py_ldb_search_iterator, METH_VARARGS|METH_KEYWORDS,
+       { "search_iterator", PY_DISCARD_FUNC_SIG(PyCFunction,
+                                                py_ldb_search_iterator),
+               METH_VARARGS|METH_KEYWORDS,
                "S.search_iterator(base=None, scope=None, expression=None, attrs=None, controls=None, timeout=None) -> iterator\n"
                "Search in a database.\n"
                "\n"
@@ -2374,52 +2703,24 @@ static PyMethodDef py_ldb_methods[] = {
                "S.set_opaque(name, value) -> None\n"
                "Set an opaque value on this LDB connection. \n"
                ":note: Passing incorrect values may cause crashes." },
-       { "modules", (PyCFunction)py_ldb_modules, METH_NOARGS,
-               "S.modules() -> list\n"
-               "Return the list of modules on this LDB connection " },
        { "sequence_number", (PyCFunction)py_ldb_sequence_number, METH_VARARGS,
                "S.sequence_number(type) -> value\n"
                "Return the value of the sequence according to the requested type" },
+       { "whoami",
+         (PyCFunction)py_ldb_whoami,
+         METH_NOARGS,
+         "S.whoami() -> value\n"
+         "Return the RFC4532 whoami string",
+       },
        { "_register_test_extensions", (PyCFunction)py_ldb_register_test_extensions, METH_NOARGS,
                "S._register_test_extensions() -> None\n"
                "Register internal extensions used in testing" },
-       { NULL },
-};
-
-static PyObject *PyLdbModule_FromModule(struct ldb_module *mod)
-{
-       PyLdbModuleObject *ret;
-
-       ret = (PyLdbModuleObject *)PyLdbModule.tp_alloc(&PyLdbModule, 0);
-       if (ret == NULL) {
-               PyErr_NoMemory();
-               return NULL;
-       }
-       ret->mem_ctx = talloc_new(NULL);
-       ret->mod = talloc_reference(ret->mem_ctx, mod);
-       return (PyObject *)ret;
-}
-
-static PyObject *py_ldb_get_firstmodule(PyLdbObject *self, void *closure)
-{
-       struct ldb_module *mod = pyldb_Ldb_AsLdbContext(self)->modules;
-       if (mod == NULL) {
-               Py_RETURN_NONE;
-       }
-       return PyLdbModule_FromModule(mod);
-}
-
-static PyGetSetDef py_ldb_getset[] = {
-       {
-               .name = discard_const_p(char, "firstmodule"),
-               .get  = (getter)py_ldb_get_firstmodule,
-       },
-       { .name = NULL },
+       {0},
 };
 
 static int py_ldb_contains(PyLdbObject *self, PyObject *obj)
 {
-       struct ldb_context *ldb_ctx = pyldb_Ldb_AsLdbContext(self);
+       struct ldb_context *ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self);
        struct ldb_dn *dn;
        struct ldb_result *result;
        unsigned int count;
@@ -2455,20 +2756,6 @@ static PySequenceMethods py_ldb_seq = {
        .sq_contains = (objobjproc)py_ldb_contains,
 };
 
-static PyObject *PyLdb_FromLdbContext(struct ldb_context *ldb_ctx)
-{
-       PyLdbObject *ret;
-
-       ret = (PyLdbObject *)PyLdb.tp_alloc(&PyLdb, 0);
-       if (ret == NULL) {
-               PyErr_NoMemory();
-               return NULL;
-       }
-       ret->mem_ctx = talloc_new(NULL);
-       ret->ldb_ctx = talloc_reference(ret->mem_ctx, ldb_ctx);
-       return (PyObject *)ret;
-}
-
 static void py_ldb_dealloc(PyLdbObject *self)
 {
        talloc_free(self->mem_ctx);
@@ -2482,7 +2769,6 @@ static PyTypeObject PyLdb = {
        .tp_new = py_ldb_new,
        .tp_init = (initproc)py_ldb_init,
        .tp_dealloc = (destructor)py_ldb_dealloc,
-       .tp_getset = py_ldb_getset,
        .tp_getattro = PyObject_GenericGetAttr,
        .tp_basicsize = sizeof(PyLdbObject),
        .tp_doc = "Connection to a LDB database.",
@@ -2493,9 +2779,9 @@ static PyTypeObject PyLdb = {
 static void py_ldb_result_dealloc(PyLdbResultObject *self)
 {
        talloc_free(self->mem_ctx);
-       Py_DECREF(self->msgs);
-       Py_DECREF(self->referals);
-       Py_DECREF(self->controls);
+       Py_CLEAR(self->msgs);
+       Py_CLEAR(self->referals);
+       Py_CLEAR(self->controls);
        Py_TYPE(self)->tp_free(self);
 }
 
@@ -2525,7 +2811,7 @@ static PyObject *py_ldb_result_get_count(PyLdbResultObject *self, void *closure)
                return NULL;
        }
        size = PyList_Size(self->msgs);
-       return PyInt_FromLong(size);
+       return PyLong_FromLong(size);
 }
 
 static PyGetSetDef py_ldb_result_getset[] = {
@@ -2570,7 +2856,7 @@ static PySequenceMethods py_ldb_result_seq = {
 
 static PyObject *py_ldb_result_repr(PyLdbObject *self)
 {
-       return PyStr_FromString("<ldb result>");
+       return PyUnicode_FromString("<ldb result>");
 }
 
 
@@ -2589,10 +2875,10 @@ static PyTypeObject PyLdbResult = {
 
 static void py_ldb_search_iterator_dealloc(PyLdbSearchIteratorObject *self)
 {
-       Py_XDECREF(self->state.exception);
+       Py_CLEAR(self->state.exception);
        TALLOC_FREE(self->mem_ctx);
        ZERO_STRUCT(self->state);
-       Py_DECREF(self->ldb);
+       Py_CLEAR(self->ldb);
        Py_TYPE(self)->tp_free(self);
 }
 
@@ -2635,7 +2921,7 @@ static PyObject *py_ldb_search_iterator_next(PyLdbSearchIteratorObject *self)
                if (ret != LDB_SUCCESS) {
                        struct ldb_context *ldb_ctx;
                        TALLOC_FREE(self->state.req);
-                       ldb_ctx = pyldb_Ldb_AsLdbContext(self->ldb);
+                       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(self->ldb);
                        /*
                         * We stop the iteration and let
                         * py_ldb_search_iterator_result() will deliver
@@ -2655,7 +2941,8 @@ static PyObject *py_ldb_search_iterator_next(PyLdbSearchIteratorObject *self)
        return py_ret;
 }
 
-static PyObject *py_ldb_search_iterator_result(PyLdbSearchIteratorObject *self)
+static PyObject *py_ldb_search_iterator_result(PyLdbSearchIteratorObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        PyObject *py_ret = NULL;
 
@@ -2673,6 +2960,7 @@ static PyObject *py_ldb_search_iterator_result(PyLdbSearchIteratorObject *self)
 
        if (self->state.exception != NULL) {
                PyErr_SetObject(PyExc_LdbError, self->state.exception);
+               Py_DECREF(self->state.exception);
                self->state.exception = NULL;
                return NULL;
        }
@@ -2689,7 +2977,8 @@ static PyObject *py_ldb_search_iterator_result(PyLdbSearchIteratorObject *self)
        return py_ret;
 }
 
-static PyObject *py_ldb_search_iterator_abandon(PyLdbSearchIteratorObject *self)
+static PyObject *py_ldb_search_iterator_abandon(PyLdbSearchIteratorObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        if (self->state.req == NULL) {
                PyErr_SetString(PyExc_RuntimeError,
@@ -2697,7 +2986,7 @@ static PyObject *py_ldb_search_iterator_abandon(PyLdbSearchIteratorObject *self)
                return NULL;
        }
 
-       Py_XDECREF(self->state.exception);
+       Py_CLEAR(self->state.exception);
        TALLOC_FREE(self->mem_ctx);
        ZERO_STRUCT(self->state);
        Py_RETURN_NONE;
@@ -2708,12 +2997,12 @@ static PyMethodDef py_ldb_search_iterator_methods[] = {
                "S.result() -> ldb.Result (without msgs and referrals)\n" },
        { "abandon", (PyCFunction)py_ldb_search_iterator_abandon, METH_NOARGS,
                "S.abandon()\n" },
-       { NULL }
+       {0}
 };
 
 static PyObject *py_ldb_search_iterator_repr(PyLdbSearchIteratorObject *self)
 {
-       return PyStr_FromString("<ldb search iterator>");
+       return PyUnicode_FromString("<ldb search iterator>");
 }
 
 static PyTypeObject PyLdbSearchIterator = {
@@ -2728,210 +3017,18 @@ static PyTypeObject PyLdbSearchIterator = {
        .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
 };
 
-static PyObject *py_ldb_module_repr(PyLdbModuleObject *self)
-{
-       return PyStr_FromFormat("<ldb module '%s'>",
-               pyldb_Module_AsModule(self)->ops->name);
-}
-
-static PyObject *py_ldb_module_str(PyLdbModuleObject *self)
-{
-       return PyStr_FromString(pyldb_Module_AsModule(self)->ops->name);
-}
-
-static PyObject *py_ldb_module_start_transaction(PyLdbModuleObject *self)
-{
-       pyldb_Module_AsModule(self)->ops->start_transaction(pyldb_Module_AsModule(self));
-       Py_RETURN_NONE;
-}
-
-static PyObject *py_ldb_module_end_transaction(PyLdbModuleObject *self)
-{
-       pyldb_Module_AsModule(self)->ops->end_transaction(pyldb_Module_AsModule(self));
-       Py_RETURN_NONE;
-}
-
-static PyObject *py_ldb_module_del_transaction(PyLdbModuleObject *self)
-{
-       pyldb_Module_AsModule(self)->ops->del_transaction(pyldb_Module_AsModule(self));
-       Py_RETURN_NONE;
-}
-
-static PyObject *py_ldb_module_search(PyLdbModuleObject *self, PyObject *args, PyObject *kwargs)
-{
-       PyObject *py_base, *py_tree, *py_attrs, *py_ret;
-       int ret, scope;
-       struct ldb_request *req;
-       const char * const kwnames[] = { "base", "scope", "tree", "attrs", NULL };
-       struct ldb_module *mod;
-       const char * const*attrs;
-
-       /* type "int" rather than "enum" for "scope" is intentional */
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!iOO",
-                                        discard_const_p(char *, kwnames),
-                                        &PyLdbDn, &py_base, &scope, &py_tree, &py_attrs))
-               return NULL;
-
-       mod = self->mod;
-
-       if (py_attrs == Py_None) {
-               attrs = NULL;
-       } else {
-               attrs = PyList_AsStrList(NULL, py_attrs, "attrs");
-               if (attrs == NULL)
-                       return NULL;
-       }
-
-       ret = ldb_build_search_req(&req, mod->ldb, NULL, pyldb_Dn_AsDn(py_base), 
-                            scope, NULL /* expr */, attrs,
-                            NULL /* controls */, NULL, NULL, NULL);
-
-       talloc_steal(req, attrs);
-
-       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
-
-       req->op.search.res = NULL;
-
-       ret = mod->ops->search(mod, req);
-
-       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
-
-       py_ret = PyLdbResult_FromResult(req->op.search.res);
-
-       talloc_free(req);
-
-       return py_ret;
-}
-
-
-static PyObject *py_ldb_module_add(PyLdbModuleObject *self, PyObject *args)
-{
-       struct ldb_request *req;
-       PyObject *py_message;
-       int ret;
-       struct ldb_module *mod;
-
-       if (!PyArg_ParseTuple(args, "O!", &PyLdbMessage, &py_message))
-               return NULL;
-
-       req = talloc_zero(NULL, struct ldb_request);
-       req->operation = LDB_ADD;
-       req->op.add.message = pyldb_Message_AsMessage(py_message);
-
-       mod = pyldb_Module_AsModule(self);
-       ret = mod->ops->add(mod, req);
-
-       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
-
-       Py_RETURN_NONE;
-}
-
-static PyObject *py_ldb_module_modify(PyLdbModuleObject *self, PyObject *args) 
-{
-       int ret;
-       struct ldb_request *req;
-       PyObject *py_message;
-       struct ldb_module *mod;
-
-       if (!PyArg_ParseTuple(args, "O!", &PyLdbMessage, &py_message))
-               return NULL;
-
-       req = talloc_zero(NULL, struct ldb_request);
-       req->operation = LDB_MODIFY;
-       req->op.mod.message = pyldb_Message_AsMessage(py_message);
-
-       mod = pyldb_Module_AsModule(self);
-       ret = mod->ops->modify(mod, req);
-
-       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
-
-       Py_RETURN_NONE;
-}
-
-static PyObject *py_ldb_module_delete(PyLdbModuleObject *self, PyObject *args) 
-{
-       int ret;
-       struct ldb_request *req;
-       PyObject *py_dn;
-
-       if (!PyArg_ParseTuple(args, "O!", &PyLdbDn, &py_dn))
-               return NULL;
-
-       req = talloc_zero(NULL, struct ldb_request);
-       req->operation = LDB_DELETE;
-       req->op.del.dn = pyldb_Dn_AsDn(py_dn);
-
-       ret = pyldb_Module_AsModule(self)->ops->del(pyldb_Module_AsModule(self), req);
-
-       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
-
-       Py_RETURN_NONE;
-}
-
-static PyObject *py_ldb_module_rename(PyLdbModuleObject *self, PyObject *args)
-{
-       int ret;
-       struct ldb_request *req;
-       PyObject *py_dn1, *py_dn2;
-
-       if (!PyArg_ParseTuple(args, "O!O!", &PyLdbDn, &py_dn1, &PyLdbDn, &py_dn2))
-               return NULL;
-
-       req = talloc_zero(NULL, struct ldb_request);
-
-       req->operation = LDB_RENAME;
-       req->op.rename.olddn = pyldb_Dn_AsDn(py_dn1);
-       req->op.rename.newdn = pyldb_Dn_AsDn(py_dn2);
-
-       ret = pyldb_Module_AsModule(self)->ops->rename(pyldb_Module_AsModule(self), req);
-
-       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
-
-       Py_RETURN_NONE;
-}
-
-static PyMethodDef py_ldb_module_methods[] = {
-       { "search", (PyCFunction)py_ldb_module_search, METH_VARARGS|METH_KEYWORDS, NULL },
-       { "add", (PyCFunction)py_ldb_module_add, METH_VARARGS, NULL },
-       { "modify", (PyCFunction)py_ldb_module_modify, METH_VARARGS, NULL },
-       { "rename", (PyCFunction)py_ldb_module_rename, METH_VARARGS, NULL },
-       { "delete", (PyCFunction)py_ldb_module_delete, METH_VARARGS, NULL },
-       { "start_transaction", (PyCFunction)py_ldb_module_start_transaction, METH_NOARGS, NULL },
-       { "end_transaction", (PyCFunction)py_ldb_module_end_transaction, METH_NOARGS, NULL },
-       { "del_transaction", (PyCFunction)py_ldb_module_del_transaction, METH_NOARGS, NULL },
-       { NULL },
-};
-
-static void py_ldb_module_dealloc(PyLdbModuleObject *self)
-{
-       talloc_free(self->mem_ctx);
-       PyObject_Del(self);
-}
-
-static PyTypeObject PyLdbModule = {
-       .tp_name = "ldb.LdbModule",
-       .tp_methods = py_ldb_module_methods,
-       .tp_repr = (reprfunc)py_ldb_module_repr,
-       .tp_str = (reprfunc)py_ldb_module_str,
-       .tp_basicsize = sizeof(PyLdbModuleObject),
-       .tp_dealloc = (destructor)py_ldb_module_dealloc,
-       .tp_flags = Py_TPFLAGS_DEFAULT,
-       .tp_doc = "LDB module (extension)",
-};
-
-
 /**
  * Create a ldb_message_element from a Python object.
  *
- * This will accept any sequence objects that contains strings, or 
+ * This will accept any sequence objects that contains strings, or
  * a string object.
  *
- * A reference to set_obj will be borrowed. 
+ * A reference to set_obj might be borrowed.
  *
  * @param mem_ctx Memory context
  * @param set_obj Python object to convert
- * @param flags ldb_message_element flags to set
- * @param attr_name Name of the attribute
+ * @param flags ldb_message_element flags to set, if a new element is returned
+ * @param attr_name Name of the attribute to set, if a new element is returned
  * @return New ldb_message_element, allocated as child of mem_ctx
  */
 static struct ldb_message_element *PyObject_AsMessageElement(
@@ -2962,6 +3059,11 @@ static struct ldb_message_element *PyObject_AsMessageElement(
        }
 
        me->name = talloc_strdup(me, attr_name);
+       if (me->name == NULL) {
+               PyErr_NoMemory();
+               talloc_free(me);
+               return NULL;
+       }
        me->flags = flags;
        if (PyBytes_Check(set_obj) || PyUnicode_Check(set_obj)) {
                me->num_values = 1;
@@ -2975,7 +3077,7 @@ static struct ldb_message_element *PyObject_AsMessageElement(
                        }
                        msg = _msg;
                } else {
-                       msg = PyStr_AsUTF8AndSize(set_obj, &size);
+                       msg = PyUnicode_AsUTF8AndSize(set_obj, &size);
                        if (msg == NULL) {
                                talloc_free(me);
                                return NULL;
@@ -3000,7 +3102,7 @@ static struct ldb_message_element *PyObject_AsMessageElement(
                                }
                                msg = _msg;
                        } else if (PyUnicode_Check(obj)) {
-                               msg = PyStr_AsUTF8AndSize(obj, &size);
+                               msg = PyUnicode_AsUTF8AndSize(obj, &size);
                                if (msg == NULL) {
                                        talloc_free(me);
                                        return NULL;
@@ -3035,10 +3137,26 @@ static PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx,
 
        /* Python << 2.5 doesn't have PySet_New and PySet_Add. */
        result = PyList_New(me->num_values);
+       if (result == NULL) {
+               return NULL;
+       }
 
        for (i = 0; i < me->num_values; i++) {
-               PyList_SetItem(result, i,
-                       PyObject_FromLdbValue(&me->values[i]));
+               PyObject *obj = NULL;
+               int ret;
+
+               obj = PyObject_FromLdbValue(&me->values[i]);
+               if (obj == NULL) {
+                       Py_DECREF(result);
+                       return NULL;
+               }
+
+               ret = PyList_SetItem(result, i, obj);
+               if (ret) {
+                       Py_DECREF(obj);
+                       Py_DECREF(result);
+                       return NULL;
+               }
        }
 
        return result;
@@ -3058,7 +3176,7 @@ static PyObject *py_ldb_msg_element_get(PyLdbMessageElementObject *self, PyObjec
 static PyObject *py_ldb_msg_element_flags(PyLdbMessageElementObject *self, PyObject *args)
 {
        struct ldb_message_element *el = pyldb_MessageElement_AsMessageElement(self);
-       return PyInt_FromLong(el->flags);
+       return PyLong_FromLong(el->flags);
 }
 
 static PyObject *py_ldb_msg_element_set_flags(PyLdbMessageElementObject *self, PyObject *args)
@@ -3077,7 +3195,7 @@ static PyMethodDef py_ldb_msg_element_methods[] = {
        { "get", (PyCFunction)py_ldb_msg_element_get, METH_VARARGS, NULL },
        { "set_flags", (PyCFunction)py_ldb_msg_element_set_flags, METH_VARARGS, NULL },
        { "flags", (PyCFunction)py_ldb_msg_element_flags, METH_NOARGS, NULL },
-       { NULL },
+       {0},
 };
 
 static Py_ssize_t py_ldb_msg_element_len(PyLdbMessageElementObject *self)
@@ -3123,17 +3241,27 @@ static PyObject *py_ldb_msg_element_iter(PyLdbMessageElementObject *self)
 
 static PyObject *PyLdbMessageElement_FromMessageElement(struct ldb_message_element *el, TALLOC_CTX *mem_ctx)
 {
+       TALLOC_CTX *ret_mem_ctx = NULL;
        PyLdbMessageElementObject *ret;
-       ret = PyObject_New(PyLdbMessageElementObject, &PyLdbMessageElement);
-       if (ret == NULL) {
+
+       ret_mem_ctx = talloc_new(NULL);
+       if (ret_mem_ctx == NULL) {
+               return PyErr_NoMemory();
+       }
+
+       if (talloc_reference(ret_mem_ctx, mem_ctx) == NULL) {
+               talloc_free(ret_mem_ctx);
                PyErr_NoMemory();
                return NULL;
        }
-       ret->mem_ctx = talloc_new(NULL);
-       if (talloc_reference(ret->mem_ctx, mem_ctx) == NULL) {
+
+       ret = PyObject_New(PyLdbMessageElementObject, &PyLdbMessageElement);
+       if (ret == NULL) {
+               talloc_free(ret_mem_ctx);
                PyErr_NoMemory();
                return NULL;
        }
+       ret->mem_ctx = ret_mem_ctx;
        ret->el = el;
        return (PyObject *)ret;
 }
@@ -3184,14 +3312,14 @@ static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyOb
                                result = PyBytes_AsStringAndSize(py_elements, &_msg, &size);
                                msg = _msg;
                        } else {
-                               msg = PyStr_AsUTF8AndSize(py_elements, &size);
+                               msg = PyUnicode_AsUTF8AndSize(py_elements, &size);
                                result = (msg == NULL) ? -1 : 0;
                        }
                        if (result != 0) {
                                talloc_free(mem_ctx);
                                return NULL;
                        }
-                       el->values[0].data = talloc_memdup(el->values, 
+                       el->values[0].data = talloc_memdup(el->values,
                                (const uint8_t *)msg, size + 1);
                        el->values[0].length = size;
                } else if (PySequence_Check(py_elements)) {
@@ -3213,10 +3341,10 @@ static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyOb
                                        result = PyBytes_AsStringAndSize(item, &_msg, &size);
                                        msg = _msg;
                                } else if (PyUnicode_Check(item)) {
-                                       msg = PyStr_AsUTF8AndSize(item, &size);
+                                       msg = PyUnicode_AsUTF8AndSize(item, &size);
                                        result = (msg == NULL) ? -1 : 0;
                                } else {
-                                       PyErr_Format(PyExc_TypeError, 
+                                       PyErr_Format(PyExc_TypeError,
                                                     "Expected string as element %zd in list", i);
                                        result = -1;
                                }
@@ -3229,7 +3357,7 @@ static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyOb
                                el->values[i].length = size;
                        }
                } else {
-                       PyErr_SetString(PyExc_TypeError, 
+                       PyErr_SetString(PyExc_TypeError,
                                        "Expected string or list");
                        talloc_free(mem_ctx);
                        return NULL;
@@ -3237,7 +3365,13 @@ static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyOb
        }
 
        el->flags = flags;
-       el->name = talloc_strdup(el, name);
+       if (name != NULL) {
+               el->name = talloc_strdup(el, name);
+               if (el->name == NULL) {
+                       talloc_free(mem_ctx);
+                       return PyErr_NoMemory();
+               }
+       }
 
        ret = PyObject_New(PyLdbMessageElementObject, type);
        if (ret == NULL) {
@@ -3261,17 +3395,21 @@ static PyObject *py_ldb_msg_element_repr(PyLdbMessageElementObject *self)
                PyObject *o = py_ldb_msg_element_find(self, i);
                repr = PyObject_Repr(o);
                if (element_str == NULL)
-                       element_str = talloc_strdup(NULL, PyStr_AsUTF8(repr));
+                       element_str = talloc_strdup(NULL, PyUnicode_AsUTF8(repr));
                else
-                       element_str = talloc_asprintf_append(element_str, ",%s", PyStr_AsUTF8(repr));
+                       element_str = talloc_asprintf_append(element_str, ",%s", PyUnicode_AsUTF8(repr));
                Py_DECREF(repr);
+
+               if (element_str == NULL) {
+                       return PyErr_NoMemory();
+               }
        }
 
        if (element_str != NULL) {
-               ret = PyStr_FromFormat("MessageElement([%s])", element_str);
+               ret = PyUnicode_FromFormat("MessageElement([%s])", element_str);
                talloc_free(element_str);
        } else {
-               ret = PyStr_FromString("MessageElement([])");
+               ret = PyUnicode_FromString("MessageElement([])");
        }
 
        return ret;
@@ -3282,7 +3420,7 @@ static PyObject *py_ldb_msg_element_str(PyLdbMessageElementObject *self)
        struct ldb_message_element *el = pyldb_MessageElement_AsMessageElement(self);
 
        if (el->num_values == 1)
-               return PyStr_FromStringAndSize((char *)el->values[0].data, el->values[0].length);
+               return PyUnicode_FromStringAndSize((char *)el->values[0].data, el->values[0].length);
        else
                Py_RETURN_NONE;
 }
@@ -3338,11 +3476,6 @@ static PyObject *py_ldb_msg_from_dict(PyTypeObject *type, PyObject *args)
                return NULL;
        }
 
-       if (!PyLdb_Check(py_ldb)) {
-               PyErr_SetString(PyExc_TypeError, "Expected Ldb");
-               return NULL;
-       }
-
        /* mask only flags we are going to use */
        mod_flags = LDB_FLAG_MOD_TYPE(mod_flags);
        if (!mod_flags) {
@@ -3352,7 +3485,7 @@ static PyObject *py_ldb_msg_from_dict(PyTypeObject *type, PyObject *args)
                return NULL;
        }
 
-       ldb_ctx = pyldb_Ldb_AsLdbContext(py_ldb);
+       ldb_ctx = pyldb_Ldb_AS_LDBCONTEXT(py_ldb);
 
        msg = PyDict_AsMessage(ldb_ctx, py_dict, ldb_ctx, mod_flags);
        if (!msg) {
@@ -3377,49 +3510,92 @@ static PyObject *py_ldb_msg_remove_attr(PyLdbMessageObject *self, PyObject *args
        Py_RETURN_NONE;
 }
 
-static PyObject *py_ldb_msg_keys(PyLdbMessageObject *self)
+static PyObject *py_ldb_msg_keys(PyLdbMessageObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        struct ldb_message *msg = pyldb_Message_AsMessage(self);
        Py_ssize_t i, j = 0;
        PyObject *obj = PyList_New(msg->num_elements+(msg->dn != NULL?1:0));
+       if (obj == NULL) {
+               return NULL;
+       }
+
        if (msg->dn != NULL) {
-               PyList_SetItem(obj, j, PyStr_FromString("dn"));
+               PyObject *py_dn = NULL;
+               int ret;
+
+               py_dn = PyUnicode_FromString("dn");
+               if (py_dn == NULL) {
+                       Py_DECREF(obj);
+                       return NULL;
+               }
+
+               ret = PyList_SetItem(obj, j, py_dn);
+               if (ret) {
+                       Py_DECREF(py_dn);
+                       Py_DECREF(obj);
+                       return NULL;
+               }
+
                j++;
        }
        for (i = 0; i < msg->num_elements; i++) {
-               PyList_SetItem(obj, j, PyStr_FromString(msg->elements[i].name));
+               PyObject *py_name = NULL;
+               int ret;
+
+               py_name = PyUnicode_FromString(msg->elements[i].name);
+               if (py_name == NULL) {
+                       Py_DECREF(obj);
+                       return NULL;
+               }
+
+               ret = PyList_SetItem(obj, j, py_name);
+               if (ret) {
+                       Py_DECREF(py_name);
+                       Py_DECREF(obj);
+                       return NULL;
+               }
+
                j++;
        }
        return obj;
 }
 
-static PyObject *py_ldb_msg_getitem_helper(PyLdbMessageObject *self, PyObject *py_name)
+static int py_ldb_msg_contains(PyLdbMessageObject *self, PyObject *py_name)
 {
-       struct ldb_message_element *el;
-       const char *name;
+       struct ldb_message_element *el = NULL;
+       const char *name = NULL;
        struct ldb_message *msg = pyldb_Message_AsMessage(self);
-       name = PyStr_AsUTF8(py_name);
+       name = PyUnicode_AsUTF8(py_name);
        if (name == NULL) {
-               PyErr_SetNone(PyExc_TypeError);
-               return NULL;
+               return -1;
        }
-       if (!ldb_attr_cmp(name, "dn"))
-               return pyldb_Dn_FromDn(msg->dn);
-       el = ldb_msg_find_element(msg, name);
-       if (el == NULL) {
-               return NULL;
+       if (!ldb_attr_cmp(name, "dn")) {
+               return 1;
        }
-       return (PyObject *)PyLdbMessageElement_FromMessageElement(el, msg->elements);
+       el = ldb_msg_find_element(msg, name);
+       return el != NULL ? 1 : 0;
 }
 
 static PyObject *py_ldb_msg_getitem(PyLdbMessageObject *self, PyObject *py_name)
 {
-       PyObject *ret = py_ldb_msg_getitem_helper(self, py_name);
-       if (ret == NULL) {
+       struct ldb_message_element *el = NULL;
+       const char *name = NULL;
+       struct ldb_message *msg = pyldb_Message_AsMessage(self);
+       name = PyUnicode_AsUTF8(py_name);
+       if (name == NULL) {
+               return NULL;
+       }
+       if (!ldb_attr_cmp(name, "dn")) {
+               return pyldb_Dn_FromDn(msg->dn);
+       }
+       el = ldb_msg_find_element(msg, name);
+       if (el == NULL) {
                PyErr_SetString(PyExc_KeyError, "No such element");
                return NULL;
        }
-       return ret;
+
+       return PyLdbMessageElement_FromMessageElement(el, msg->elements);
 }
 
 static PyObject *py_ldb_msg_get(PyLdbMessageObject *self, PyObject *args, PyObject *kwargs)
@@ -3457,7 +3633,8 @@ static PyObject *py_ldb_msg_get(PyLdbMessageObject *self, PyObject *args, PyObje
        return PyObject_FromLdbValue(&el->values[idx]);
 }
 
-static PyObject *py_ldb_msg_items(PyLdbMessageObject *self)
+static PyObject *py_ldb_msg_items(PyLdbMessageObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        struct ldb_message *msg = pyldb_Message_AsMessage(self);
        Py_ssize_t i, j = 0;
@@ -3486,13 +3663,13 @@ static PyObject *py_ldb_msg_items(PyLdbMessageObject *self)
                PyObject *value = NULL;
                PyObject *py_el = PyLdbMessageElement_FromMessageElement(&msg->elements[i], msg->elements);
                int res = 0;
-               Py_CLEAR(py_el);
                value = Py_BuildValue("(sO)", msg->elements[i].name, py_el);
+               Py_CLEAR(py_el);
                if (value == NULL ) {
                        Py_CLEAR(l);
                        return NULL;
                }
-               res = PyList_SetItem(l, 0, value);
+               res = PyList_SetItem(l, j, value);
                if (res == -1) {
                        Py_CLEAR(l);
                        return NULL;
@@ -3501,13 +3678,31 @@ static PyObject *py_ldb_msg_items(PyLdbMessageObject *self)
        return l;
 }
 
-static PyObject *py_ldb_msg_elements(PyLdbMessageObject *self)
+static PyObject *py_ldb_msg_elements(PyLdbMessageObject *self,
+               PyObject *Py_UNUSED(ignored))
 {
        struct ldb_message *msg = pyldb_Message_AsMessage(self);
        Py_ssize_t i = 0;
        PyObject *l = PyList_New(msg->num_elements);
+       if (l == NULL) {
+               return NULL;
+       }
        for (i = 0; i < msg->num_elements; i++) {
-               PyList_SetItem(l, i, PyLdbMessageElement_FromMessageElement(&msg->elements[i], msg->elements));
+               PyObject *msg_el = NULL;
+               int ret;
+
+               msg_el = PyLdbMessageElement_FromMessageElement(&msg->elements[i], msg->elements);
+               if (msg_el == NULL) {
+                       Py_DECREF(l);
+                       return NULL;
+               }
+
+               ret = PyList_SetItem(l, i, msg_el);
+               if (ret) {
+                       Py_DECREF(msg_el);
+                       Py_DECREF(l);
+                       return NULL;
+               }
        }
        return l;
 }
@@ -3528,7 +3723,11 @@ static PyObject *py_ldb_msg_add(PyLdbMessageObject *self, PyObject *args)
                PyErr_SetString(PyExc_ValueError, "Invalid MessageElement object");
                return NULL;
        }
-
+       if (el->name == NULL) {
+               PyErr_SetString(PyExc_ValueError,
+                               "The element has no name");
+               return NULL;
+       }
        ret = ldb_msg_add_empty(msg, el->name, el->flags, &el_new);
        PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
 
@@ -3557,13 +3756,14 @@ static PyMethodDef py_ldb_msg_methods[] = {
                "Message.from_dict(ldb, dict, mod_flag=FLAG_MOD_REPLACE) -> ldb.Message\n"
                "Class method to create ldb.Message object from Dictionary.\n"
                "mod_flag is one of FLAG_MOD_ADD, FLAG_MOD_REPLACE or FLAG_MOD_DELETE."},
-       { "keys", (PyCFunction)py_ldb_msg_keys, METH_NOARGS, 
+       { "keys", (PyCFunction)py_ldb_msg_keys, METH_NOARGS,
                "S.keys() -> list\n\n"
                "Return sequence of all attribute names." },
-       { "remove", (PyCFunction)py_ldb_msg_remove_attr, METH_VARARGS, 
+       { "remove", (PyCFunction)py_ldb_msg_remove_attr, METH_VARARGS,
                "S.remove(name)\n\n"
                "Remove all entries for attributes with the specified name."},
-       { "get", (PyCFunction)py_ldb_msg_get, METH_VARARGS | METH_KEYWORDS,
+       { "get", PY_DISCARD_FUNC_SIG(PyCFunction, py_ldb_msg_get),
+               METH_VARARGS | METH_KEYWORDS,
          "msg.get(name,default=None,idx=None) -> string\n"
          "idx is the index into the values array\n"
          "if idx is None, then a list is returned\n"
@@ -3574,14 +3774,14 @@ static PyMethodDef py_ldb_msg_methods[] = {
        { "add", (PyCFunction)py_ldb_msg_add, METH_VARARGS,
                "S.add(element)\n\n"
                "Add an element to this message." },
-       { NULL },
+       {0},
 };
 
 static PyObject *py_ldb_msg_iter(PyLdbMessageObject *self)
 {
        PyObject *list, *iter;
 
-       list = py_ldb_msg_keys(self);
+       list = py_ldb_msg_keys(self, NULL);
        iter = PyObject_GetIter(list);
        Py_DECREF(list);
        return iter;
@@ -3591,7 +3791,7 @@ static int py_ldb_msg_setitem(PyLdbMessageObject *self, PyObject *name, PyObject
 {
        const char *attr_name;
 
-       attr_name = PyStr_AsUTF8(name);
+       attr_name = PyUnicode_AsUTF8(name);
        if (attr_name == NULL) {
                PyErr_SetNone(PyExc_TypeError);
                return -1;
@@ -3607,10 +3807,27 @@ static int py_ldb_msg_setitem(PyLdbMessageObject *self, PyObject *name, PyObject
                if (el == NULL) {
                        return -1;
                }
+               if (el->name == NULL) {
+                       /*
+                        * If â€˜value’ is a MessageElement,
+                        * PyObject_AsMessageElement() will have returned a
+                        * reference to it without setting the name. We don’t
+                        * want to modify the original object to set the name
+                        * ourselves, but making a copy would result in
+                        * different behaviour for a caller relying on a
+                        * reference being kept. Rather than continue with a
+                        * NULL name (and probably fail later on), let’s catch
+                        * this potential mistake early.
+                        */
+                       PyErr_SetString(PyExc_ValueError, "MessageElement has no name set");
+                       talloc_unlink(self->msg, el);
+                       return -1;
+               }
                ldb_msg_remove_attr(pyldb_Message_AsMessage(self), attr_name);
                ret = ldb_msg_add(pyldb_Message_AsMessage(self), el, el->flags);
                if (ret != LDB_SUCCESS) {
                        PyErr_SetLdbError(PyExc_LdbError, ret, NULL);
+                       talloc_unlink(self->msg, el);
                        return -1;
                }
        }
@@ -3622,6 +3839,10 @@ static Py_ssize_t py_ldb_msg_length(PyLdbMessageObject *self)
        return pyldb_Message_AsMessage(self)->num_elements;
 }
 
+static PySequenceMethods py_ldb_msg_sequence = {
+       .sq_contains = (objobjproc)py_ldb_msg_contains,
+};
+
 static PyMappingMethods py_ldb_msg_mapping = {
        .mp_length = (lenfunc)py_ldb_msg_length,
        .mp_subscript = (binaryfunc)py_ldb_msg_getitem,
@@ -3661,6 +3882,10 @@ static PyObject *py_ldb_msg_new(PyTypeObject *type, PyObject *args, PyObject *kw
                        return NULL;
                }
                ret->dn = talloc_reference(ret, dn);
+               if (ret->dn == NULL) {
+                       talloc_free(mem_ctx);
+                       return PyErr_NoMemory();
+               }
        }
 
        py_ret = (PyLdbMessageObject *)type->tp_alloc(type, 0);
@@ -3677,15 +3902,29 @@ static PyObject *py_ldb_msg_new(PyTypeObject *type, PyObject *args, PyObject *kw
 
 static PyObject *PyLdbMessage_FromMessage(struct ldb_message *msg)
 {
+       TALLOC_CTX *mem_ctx = NULL;
+       struct ldb_message *msg_ref = NULL;
        PyLdbMessageObject *ret;
 
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               return PyErr_NoMemory();
+       }
+
+       msg_ref = talloc_reference(mem_ctx, msg);
+       if (msg_ref == NULL) {
+               talloc_free(mem_ctx);
+               return PyErr_NoMemory();
+       }
+
        ret = (PyLdbMessageObject *)PyLdbMessage.tp_alloc(&PyLdbMessage, 0);
        if (ret == NULL) {
+               talloc_free(mem_ctx);
                PyErr_NoMemory();
                return NULL;
        }
-       ret->mem_ctx = talloc_new(NULL);
-       ret->msg = talloc_reference(ret->mem_ctx, msg);
+       ret->mem_ctx = mem_ctx;
+       ret->msg = msg_ref;
        return (PyObject *)ret;
 }
 
@@ -3698,12 +3937,23 @@ static PyObject *py_ldb_msg_get_dn(PyLdbMessageObject *self, void *closure)
 static int py_ldb_msg_set_dn(PyLdbMessageObject *self, PyObject *value, void *closure)
 {
        struct ldb_message *msg = pyldb_Message_AsMessage(self);
+       struct ldb_dn *dn = NULL;
+       if (value == NULL) {
+               PyErr_SetString(PyExc_AttributeError, "cannot delete dn");
+               return -1;
+       }
        if (!pyldb_Dn_Check(value)) {
                PyErr_SetString(PyExc_TypeError, "expected dn");
                return -1;
        }
 
-       msg->dn = talloc_reference(msg, pyldb_Dn_AsDn(value));
+       dn = talloc_reference(msg, pyldb_Dn_AS_DN(value));
+       if (dn == NULL) {
+               PyErr_NoMemory();
+               return -1;
+       }
+
+       msg->dn = dn;
        return 0;
 }
 
@@ -3728,14 +3978,26 @@ static PyGetSetDef py_ldb_msg_getset[] = {
 static PyObject *py_ldb_msg_repr(PyLdbMessageObject *self)
 {
        PyObject *dict = PyDict_New(), *ret, *repr;
-       if (PyDict_Update(dict, (PyObject *)self) != 0)
+       const char *repr_str = NULL;
+       if (dict == NULL) {
+               return NULL;
+       }
+       if (PyDict_Update(dict, (PyObject *)self) != 0) {
+               Py_DECREF(dict);
                return NULL;
+       }
        repr = PyObject_Repr(dict);
        if (repr == NULL) {
                Py_DECREF(dict);
                return NULL;
        }
-       ret = PyStr_FromFormat("Message(%s)", PyStr_AsUTF8(repr));
+       repr_str = PyUnicode_AsUTF8(repr);
+       if (repr_str == NULL) {
+               Py_DECREF(repr);
+               Py_DECREF(dict);
+               return NULL;
+       }
+       ret = PyUnicode_FromFormat("Message(%s)", repr_str);
        Py_DECREF(repr);
        Py_DECREF(dict);
        return ret;
@@ -3795,6 +4057,7 @@ static PyTypeObject PyLdbMessage = {
        .tp_name = "ldb.Message",
        .tp_methods = py_ldb_msg_methods,
        .tp_getset = py_ldb_msg_getset,
+       .tp_as_sequence = &py_ldb_msg_sequence,
        .tp_as_mapping = &py_ldb_msg_mapping,
        .tp_basicsize = sizeof(PyLdbMessageObject),
        .tp_dealloc = (destructor)py_ldb_msg_dealloc,
@@ -3806,21 +4069,6 @@ static PyTypeObject PyLdbMessage = {
        .tp_doc = "A LDB Message",
 };
 
-static PyObject *PyLdbTree_FromTree(struct ldb_parse_tree *tree)
-{
-       PyLdbTreeObject *ret;
-
-       ret = (PyLdbTreeObject *)PyLdbTree.tp_alloc(&PyLdbTree, 0);
-       if (ret == NULL) {
-               PyErr_NoMemory();
-               return NULL;
-       }
-
-       ret->mem_ctx = talloc_new(NULL);
-       ret->tree = talloc_reference(ret->mem_ctx, tree);
-       return (PyObject *)ret;
-}
-
 static void py_ldb_tree_dealloc(PyLdbTreeObject *self)
 {
        talloc_free(self->mem_ctx);
@@ -3835,316 +4083,6 @@ static PyTypeObject PyLdbTree = {
        .tp_doc = "A search tree",
 };
 
-/* Ldb_module */
-static int py_module_search(struct ldb_module *mod, struct ldb_request *req)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result, *py_base, *py_attrs, *py_tree;
-
-       py_base = pyldb_Dn_FromDn(req->op.search.base);
-
-       if (py_base == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       py_tree = PyLdbTree_FromTree(req->op.search.tree);
-
-       if (py_tree == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       if (req->op.search.attrs == NULL) {
-               py_attrs = Py_None;
-       } else {
-               int i, len;
-               for (len = 0; req->op.search.attrs[len]; len++);
-               py_attrs = PyList_New(len);
-               for (i = 0; i < len; i++)
-                       PyList_SetItem(py_attrs, i, PyStr_FromString(req->op.search.attrs[i]));
-       }
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "search"),
-                                       discard_const_p(char, "OiOO"),
-                                       py_base, req->op.search.scope, py_tree, py_attrs);
-
-       Py_DECREF(py_attrs);
-       Py_DECREF(py_tree);
-       Py_DECREF(py_base);
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       req->op.search.res = PyLdbResult_AsResult(NULL, py_result);
-       if (req->op.search.res == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       Py_DECREF(py_result);
-
-       return LDB_SUCCESS;
-}
-
-static int py_module_add(struct ldb_module *mod, struct ldb_request *req)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result, *py_msg;
-
-       py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.add.message));
-
-       if (py_msg == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "add"),
-                                       discard_const_p(char, "O"),
-                                       py_msg);
-
-       Py_DECREF(py_msg);
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       Py_DECREF(py_result);
-
-       return LDB_SUCCESS;
-}
-
-static int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result, *py_msg;
-
-       py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.mod.message));
-
-       if (py_msg == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
-       }
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "modify"),
-                                       discard_const_p(char, "O"),
-                                       py_msg);
-
-       Py_DECREF(py_msg);
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       Py_DECREF(py_result);
-
-       return LDB_SUCCESS;
-}
-
-static int py_module_del(struct ldb_module *mod, struct ldb_request *req)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result, *py_dn;
-
-       py_dn = pyldb_Dn_FromDn(req->op.del.dn);
-
-       if (py_dn == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "delete"),
-                                       discard_const_p(char, "O"),
-                                       py_dn);
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       Py_DECREF(py_result);
-
-       return LDB_SUCCESS;
-}
-
-static int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result, *py_olddn, *py_newdn;
-
-       py_olddn = pyldb_Dn_FromDn(req->op.rename.olddn);
-
-       if (py_olddn == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       py_newdn = pyldb_Dn_FromDn(req->op.rename.newdn);
-
-       if (py_newdn == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "rename"),
-                                       discard_const_p(char, "OO"),
-                                       py_olddn, py_newdn);
-
-       Py_DECREF(py_olddn);
-       Py_DECREF(py_newdn);
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       Py_DECREF(py_result);
-
-       return LDB_SUCCESS;
-}
-
-static int py_module_request(struct ldb_module *mod, struct ldb_request *req)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result;
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "request"),
-                                       discard_const_p(char, ""));
-
-       Py_XDECREF(py_result);
-
-       return LDB_ERR_OPERATIONS_ERROR;
-}
-
-static int py_module_extended(struct ldb_module *mod, struct ldb_request *req)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result;
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "extended"),
-                                       discard_const_p(char, ""));
-
-       Py_XDECREF(py_result);
-
-       return LDB_ERR_OPERATIONS_ERROR;
-}
-
-static int py_module_start_transaction(struct ldb_module *mod)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result;
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "start_transaction"),
-                                       discard_const_p(char, ""));
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       Py_DECREF(py_result);
-
-       return LDB_SUCCESS;
-}
-
-static int py_module_end_transaction(struct ldb_module *mod)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result;
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "end_transaction"),
-                                       discard_const_p(char, ""));
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       Py_DECREF(py_result);
-
-       return LDB_SUCCESS;
-}
-
-static int py_module_del_transaction(struct ldb_module *mod)
-{
-       PyObject *py_ldb = (PyObject *)mod->private_data;
-       PyObject *py_result;
-
-       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "del_transaction"),
-                                       discard_const_p(char, ""));
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       Py_DECREF(py_result);
-
-       return LDB_SUCCESS;
-}
-
-static int py_module_destructor(struct ldb_module *mod)
-{
-       Py_DECREF((PyObject *)mod->private_data);
-       return 0;
-}
-
-static int py_module_init(struct ldb_module *mod)
-{
-       PyObject *py_class = (PyObject *)mod->ops->private_data;
-       PyObject *py_result, *py_next, *py_ldb;
-
-       py_ldb = PyLdb_FromLdbContext(mod->ldb);
-
-       if (py_ldb == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       py_next = PyLdbModule_FromModule(mod->next);
-
-       if (py_next == NULL)
-               return LDB_ERR_OPERATIONS_ERROR;
-
-       py_result = PyObject_CallFunction(py_class, discard_const_p(char, "OO"),
-                                         py_ldb, py_next);
-
-       if (py_result == NULL) {
-               return LDB_ERR_PYTHON_EXCEPTION;
-       }
-
-       mod->private_data = py_result;
-
-       talloc_set_destructor(mod, py_module_destructor);
-
-       return ldb_next_init(mod);
-}
-
-static PyObject *py_register_module(PyObject *module, PyObject *args)
-{
-       int ret;
-       struct ldb_module_ops *ops;
-       PyObject *input;
-       PyObject *tmp;
-
-       if (!PyArg_ParseTuple(args, "O", &input))
-               return NULL;
-
-       ops = talloc_zero(NULL, struct ldb_module_ops);
-       if (ops == NULL) {
-               PyErr_NoMemory();
-               return NULL;
-       }
-
-       tmp = PyObject_GetAttrString(input, discard_const_p(char, "name"));
-       ops->name = talloc_strdup(ops, PyStr_AsUTF8(tmp));
-
-       Py_XDECREF(tmp);
-       Py_INCREF(input);
-       ops->private_data = input;
-       ops->init_context = py_module_init;
-       ops->search = py_module_search;
-       ops->add = py_module_add;
-       ops->modify = py_module_modify;
-       ops->del = py_module_del;
-       ops->rename = py_module_rename;
-       ops->request = py_module_request;
-       ops->extended = py_module_extended;
-       ops->start_transaction = py_module_start_transaction;
-       ops->end_transaction = py_module_end_transaction;
-       ops->del_transaction = py_module_del_transaction;
-
-       ret = ldb_register_module(ops);
-       if (ret != LDB_SUCCESS) {
-               TALLOC_FREE(ops);
-       }
-
-       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
-
-       Py_RETURN_NONE;
-}
-
 static PyObject *py_timestring(PyObject *module, PyObject *args)
 {
        /* most times "time_t" is a signed integer type with 32 or 64 bit:
@@ -4155,7 +4093,14 @@ static PyObject *py_timestring(PyObject *module, PyObject *args)
        if (!PyArg_ParseTuple(args, "l", &t_val))
                return NULL;
        tresult = ldb_timestring(NULL, (time_t) t_val);
-       ret = PyStr_FromString(tresult);
+       if (tresult == NULL) {
+               /*
+                * Most likely EOVERFLOW from gmtime()
+                */
+               PyErr_SetFromErrno(PyExc_OSError);
+               return NULL;
+       }
+       ret = PyUnicode_FromString(tresult);
        talloc_free(tresult);
        return ret;
 }
@@ -4163,10 +4108,17 @@ static PyObject *py_timestring(PyObject *module, PyObject *args)
 static PyObject *py_string_to_time(PyObject *module, PyObject *args)
 {
        char *str;
-       if (!PyArg_ParseTuple(args, "s", &str))
+       time_t t;
+       if (!PyArg_ParseTuple(args, "s", &str)) {
                return NULL;
+       }
+       t = ldb_string_to_time(str);
 
-       return PyInt_FromLong(ldb_string_to_time(str));
+       if (t == 0 && errno != 0) {
+               PyErr_SetFromErrno(PyExc_ValueError);
+               return NULL;
+       }
+       return PyLong_FromLong(t);
 }
 
 static PyObject *py_valid_attr_name(PyObject *self, PyObject *args)
@@ -4197,7 +4149,7 @@ static PyObject *py_binary_encode(PyObject *self, PyObject *args)
                PyErr_SetString(PyExc_TypeError, "unable to encode binary string");
                return NULL;
        }
-       ret = PyStr_FromString(encoded);
+       ret = PyUnicode_FromString(encoded);
        talloc_free(encoded);
        return ret;
 }
@@ -4225,33 +4177,26 @@ static PyObject *py_binary_decode(PyObject *self, PyObject *args)
 }
 
 static PyMethodDef py_ldb_global_methods[] = {
-       { "register_module", py_register_module, METH_VARARGS, 
-               "S.register_module(module) -> None\n\n"
-               "Register a LDB module."},
-       { "timestring", py_timestring, METH_VARARGS, 
+       { "timestring", py_timestring, METH_VARARGS,
                "S.timestring(int) -> string\n\n"
                "Generate a LDAP time string from a UNIX timestamp" },
        { "string_to_time", py_string_to_time, METH_VARARGS,
                "S.string_to_time(string) -> int\n\n"
                "Parse a LDAP time string into a UNIX timestamp." },
        { "valid_attr_name", py_valid_attr_name, METH_VARARGS,
-               "S.valid_attr_name(name) -> bool\n\nn"
+               "S.valid_attr_name(name) -> bool\n\n"
                "Check whether the supplied name is a valid attribute name." },
-       { "open", (PyCFunction)py_ldb_new, METH_VARARGS|METH_KEYWORDS,
-               "S.open() -> Ldb\n\n"
-               "Open a new LDB context." },
        { "binary_encode", py_binary_encode, METH_VARARGS,
                "S.binary_encode(string) -> string\n\n"
                "Perform a RFC2254 binary encoding on a string" },
        { "binary_decode", py_binary_decode, METH_VARARGS,
                "S.binary_decode(string) -> string\n\n"
                "Perform a RFC2254 binary decode on a string" },
-       { NULL }
+       {0}
 };
 
 #define MODULE_DOC "An interface to LDB, a LDAP-like API that can either to talk an embedded database (TDB-based) or a standards-compliant LDAP server."
 
-#if PY_MAJOR_VERSION >= 3
 static struct PyModuleDef moduledef = {
        PyModuleDef_HEAD_INIT,
        .m_name = "ldb",
@@ -4259,7 +4204,6 @@ static struct PyModuleDef moduledef = {
        .m_size = -1,
        .m_methods = py_ldb_global_methods,
 };
-#endif
 
 static PyObject* module_init(void)
 {
@@ -4282,9 +4226,6 @@ static PyObject* module_init(void)
        if (PyType_Ready(&PyLdb) < 0)
                return NULL;
 
-       if (PyType_Ready(&PyLdbModule) < 0)
-               return NULL;
-
        if (PyType_Ready(&PyLdbTree) < 0)
                return NULL;
 
@@ -4297,11 +4238,7 @@ static PyObject* module_init(void)
        if (PyType_Ready(&PyLdbControl) < 0)
                return NULL;
 
-#if PY_MAJOR_VERSION >= 3
        m = PyModule_Create(&moduledef);
-#else
-       m = Py_InitModule3("ldb", py_ldb_global_methods, MODULE_DOC);
-#endif
        if (m == NULL)
                return NULL;
 
@@ -4319,10 +4256,12 @@ static PyObject* module_init(void)
        ADD_LDB_INT(CHANGETYPE_ADD);
        ADD_LDB_INT(CHANGETYPE_DELETE);
        ADD_LDB_INT(CHANGETYPE_MODIFY);
+       ADD_LDB_INT(CHANGETYPE_MODRDN);
 
        ADD_LDB_INT(FLAG_MOD_ADD);
        ADD_LDB_INT(FLAG_MOD_REPLACE);
        ADD_LDB_INT(FLAG_MOD_DELETE);
+       ADD_LDB_INT(FLAG_FORCE_NO_BASE64_LDIF);
 
        ADD_LDB_INT(ATTR_FLAG_HIDDEN);
        ADD_LDB_INT(ATTR_FLAG_UNIQUE_INDEX);
@@ -4377,6 +4316,8 @@ static PyObject* module_init(void)
        ADD_LDB_INT(FLG_ENABLE_TRACING);
        ADD_LDB_INT(FLG_DONT_CREATE_DB);
 
+       ADD_LDB_INT(PACKING_FORMAT);
+       ADD_LDB_INT(PACKING_FORMAT_V2);
 
        /* Historical misspelling */
        PyModule_AddIntConstant(m, "ERR_ALIAS_DEREFERINCING_PROBLEM", LDB_ERR_ALIAS_DEREFERENCING_PROBLEM);
@@ -4388,7 +4329,6 @@ static PyObject* module_init(void)
 
        Py_INCREF(&PyLdb);
        Py_INCREF(&PyLdbDn);
-       Py_INCREF(&PyLdbModule);
        Py_INCREF(&PyLdbMessage);
        Py_INCREF(&PyLdbMessageElement);
        Py_INCREF(&PyLdbTree);
@@ -4399,8 +4339,8 @@ static PyObject* module_init(void)
        PyModule_AddObject(m, "Dn", (PyObject *)&PyLdbDn);
        PyModule_AddObject(m, "Message", (PyObject *)&PyLdbMessage);
        PyModule_AddObject(m, "MessageElement", (PyObject *)&PyLdbMessageElement);
-       PyModule_AddObject(m, "Module", (PyObject *)&PyLdbModule);
        PyModule_AddObject(m, "Tree", (PyObject *)&PyLdbTree);
+       PyModule_AddObject(m, "Result", (PyObject *)&PyLdbResult);
        PyModule_AddObject(m, "Control", (PyObject *)&PyLdbControl);
 
        PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION);
@@ -4420,16 +4360,8 @@ static PyObject* module_init(void)
        return m;
 }
 
-#if PY_MAJOR_VERSION >= 3
 PyMODINIT_FUNC PyInit_ldb(void);
 PyMODINIT_FUNC PyInit_ldb(void)
 {
        return module_init();
 }
-#else
-void initldb(void);
-void initldb(void)
-{
-       module_init();
-}
-#endif