s4:ldb Add hooks to get/set the flags on a ldb_message_element
[ira/wip.git] / source4 / lib / ldb / pyldb.c
index 53b4fcef3dd49149aeb54004128800c7011ba8bc..94415c8c31de11feb110781cc8ece5d77338357c 100644 (file)
@@ -1,16 +1,17 @@
 /*
    Unix SMB/CIFS implementation.
 
-   Swig interface to ldb.
+   Python interface to ldb.
 
    Copyright (C) 2005,2006 Tim Potter <tpot@samba.org>
    Copyright (C) 2006 Simo Sorce <idra@samba.org>
-   Copyright (C) 2007-2008 Jelmer Vernooij <jelmer@samba.org>
+   Copyright (C) 2007-2009 Jelmer Vernooij <jelmer@samba.org>
+   Copyright (C) 2009 Matthias Dieter Wallnöfer
 
         ** NOTE! The following LGPL license applies to the ldb
         ** library. This does NOT imply that all of Samba is released
         ** under the LGPL
-   
+
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    License along with this library; if not, see <http://www.gnu.org/licenses/>.
 */
 
-#include <stdint.h>
-#include <stdbool.h>
-#include "pyldb.h"
-#include "events.h"
-#include "ldb.h"
-#include "ldb_errors.h"
+#include "replace.h"
 #include "ldb_private.h"
+#include <Python.h>
+#include "pyldb.h"
 
-PyObject *PyExc_LdbError;
+/* There's no Py_ssize_t in 2.4, apparently */
+#if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 5
+typedef int Py_ssize_t;
+typedef inquiry lenfunc;
+typedef intargfunc ssizeargfunc;
+#endif
+
+#ifndef Py_RETURN_NONE
+#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
+#endif
 
-void PyErr_SetLdbError(int ret, struct ldb_context *ldb_ctx)
+static void PyErr_SetLdbError(PyObject *error, int ret, struct ldb_context *ldb_ctx)
 {
-       PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", ret, ldb_ctx == NULL?ldb_strerror(ret):ldb_errstring(ldb_ctx)));
+       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)));
 }
-PyObject *PyObject_FromLdbValue(struct ldb_context *ldb_ctx, 
+
+static PyObject *PyExc_LdbError;
+
+PyAPI_DATA(PyTypeObject) PyLdbMessage;
+PyAPI_DATA(PyTypeObject) PyLdbModule;
+PyAPI_DATA(PyTypeObject) PyLdbDn;
+PyAPI_DATA(PyTypeObject) PyLdb;
+PyAPI_DATA(PyTypeObject) PyLdbMessageElement;
+PyAPI_DATA(PyTypeObject) PyLdbTree;
+
+static PyObject *PyObject_FromLdbValue(struct ldb_context *ldb_ctx, 
                                                           struct ldb_message_element *el, 
                                                           struct ldb_val *val)
 {
-       const struct ldb_schema_attribute *a;
        struct ldb_val new_val;
        TALLOC_CTX *mem_ctx = talloc_new(NULL);
        PyObject *ret;
-       
+
        new_val = *val;
-       
-       if (ldb_ctx != NULL) {          
-               a = ldb_schema_attribute_by_name(ldb_ctx, el->name);
-       
-               if (a != NULL) {
-                       if (a->syntax->ldif_write_fn(ldb_ctx, mem_ctx, val, &new_val) != 0) {
-                               talloc_free(mem_ctx);
-                               return NULL;
-                       }
-               }
-       } 
-       
+
        ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
-       
+
        talloc_free(mem_ctx);
-       
+
        return ret;
 }
 
+/**
+ * Obtain a ldb DN from a Python object.
+ *
+ * @param mem_ctx Memory context
+ * @param object Python object
+ * @param ldb_ctx LDB context
+ * @return Whether or not the conversion succeeded
+ */
 bool PyObject_AsDn(TALLOC_CTX *mem_ctx, PyObject *object, 
                   struct ldb_context *ldb_ctx, struct ldb_dn **dn)
 {
@@ -88,27 +106,41 @@ bool PyObject_AsDn(TALLOC_CTX *mem_ctx, PyObject *object,
        return false;
 }
 
+/**
+ * Create a Python object from a ldb_result.
+ *
+ * @param result LDB result to convert
+ * @return Python object with converted result (a list object)
+ */
 static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
 {
        PyObject *ret;
        int i;
        if (result == NULL) {
-               return Py_None;
+               Py_RETURN_NONE;
        } 
        ret = PyList_New(result->count);
        for (i = 0; i < result->count; i++) {
-               PyList_SetItem(ret, i, 
-                                          PyLdbMessage_FromMessage(result->msgs[i])
+               PyList_SetItem(ret, i, PyLdbMessage_FromMessage(result->msgs[i])
                );
        }
        return ret;
 }
 
-static struct ldb_result *PyLdbResult_AsResult(TALLOC_CTX *mem_ctx, PyObject *obj)
+/**
+ * Create a LDB Result from a Python object. 
+ * If conversion fails, NULL will be returned and a Python exception set.
+ *
+ * @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;
        int i;
-       
+
        if (obj == Py_None)
                return NULL;
 
@@ -124,47 +156,47 @@ static struct ldb_result *PyLdbResult_AsResult(TALLOC_CTX *mem_ctx, PyObject *ob
 
 static PyObject *py_ldb_dn_validate(PyLdbDnObject *self)
 {
-       return PyBool_FromLong(ldb_dn_validate(self->ptr));
+       return PyBool_FromLong(ldb_dn_validate(self->dn));
 }
 
 static PyObject *py_ldb_dn_is_valid(PyLdbDnObject *self)
 {
-       return PyBool_FromLong(ldb_dn_is_valid(self->ptr));
+       return PyBool_FromLong(ldb_dn_is_valid(self->dn));
 }
 
 static PyObject *py_ldb_dn_is_special(PyLdbDnObject *self)
 {
-       return PyBool_FromLong(ldb_dn_is_special(self->ptr));
+       return PyBool_FromLong(ldb_dn_is_special(self->dn));
 }
 
 static PyObject *py_ldb_dn_is_null(PyLdbDnObject *self)
 {
-       return PyBool_FromLong(ldb_dn_is_null(self->ptr));
+       return PyBool_FromLong(ldb_dn_is_null(self->dn));
 }
  
 static PyObject *py_ldb_dn_get_casefold(PyLdbDnObject *self)
 {
-       return PyString_FromString(ldb_dn_get_casefold(self->ptr));
+       return PyString_FromString(ldb_dn_get_casefold(self->dn));
 }
 
 static PyObject *py_ldb_dn_get_linearized(PyLdbDnObject *self)
 {
-       return PyString_FromString(ldb_dn_get_linearized(self->ptr));
+       return PyString_FromString(ldb_dn_get_linearized(self->dn));
 }
 
 static PyObject *py_ldb_dn_canonical_str(PyLdbDnObject *self)
 {
-       return PyString_FromString(ldb_dn_canonical_string(self->ptr, self->ptr));
+       return PyString_FromString(ldb_dn_canonical_string(self->dn, self->dn));
 }
 
 static PyObject *py_ldb_dn_canonical_ex_str(PyLdbDnObject *self)
 {
-       return PyString_FromString(ldb_dn_canonical_ex_string(self->ptr, self->ptr));
+       return PyString_FromString(ldb_dn_canonical_ex_string(self->dn, self->dn));
 }
 
 static PyObject *py_ldb_dn_repr(PyLdbDnObject *self)
 {
-       return PyString_FromFormat("Dn(%s)", PyObject_REPR(PyString_FromString(ldb_dn_get_linearized(self->ptr))));
+       return PyString_FromFormat("Dn(%s)", PyObject_REPR(PyString_FromString(ldb_dn_get_linearized(self->dn))));
 }
 
 static PyObject *py_ldb_dn_check_special(PyLdbDnObject *self, PyObject *args)
@@ -174,18 +206,40 @@ static PyObject *py_ldb_dn_check_special(PyLdbDnObject *self, PyObject *args)
        if (!PyArg_ParseTuple(args, "s", &name))
                return NULL;
 
-       return ldb_dn_check_special(self->ptr, name)?Py_True:Py_False;
+       return ldb_dn_check_special(self->dn, name)?Py_True:Py_False;
 }
 
 static int py_ldb_dn_compare(PyLdbDnObject *dn1, PyLdbDnObject *dn2)
 {
-       return ldb_dn_compare(dn1->ptr, dn2->ptr);
+       int ret;
+       ret = ldb_dn_compare(dn1->dn, dn2->dn);
+       if (ret < 0) ret = -1;
+       if (ret > 0) ret = 1;
+       return ret;
 }
 
 static PyObject *py_ldb_dn_get_parent(PyLdbDnObject *self)
 {
        struct ldb_dn *dn = PyLdbDn_AsDn((PyObject *)self);
-       return PyLdbDn_FromDn(ldb_dn_get_parent(NULL, dn));
+       struct ldb_dn *parent;
+       PyLdbDnObject *py_ret;
+       TALLOC_CTX *mem_ctx = talloc_new(NULL);
+
+       parent = ldb_dn_get_parent(mem_ctx, dn);
+       if (parent == NULL) {
+               talloc_free(mem_ctx);
+               Py_RETURN_NONE;
+       }
+
+       py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
+       if (py_ret == NULL) {
+               PyErr_NoMemory();
+               talloc_free(mem_ctx);
+               return NULL;
+       }
+       py_ret->mem_ctx = mem_ctx;
+       py_ret->dn = parent;
+       return (PyObject *)py_ret;
 }
 
 #define dn_ldb_ctx(dn) ((struct ldb_context *)dn)
@@ -266,11 +320,20 @@ static PyObject *py_ldb_dn_concat(PyLdbDnObject *self, PyObject *py_other)
 {
        struct ldb_dn *dn = PyLdbDn_AsDn((PyObject *)self), 
                                  *other;
-       struct ldb_dn *ret = ldb_dn_copy(NULL, dn);
+       PyLdbDnObject *py_ret;
+       
        if (!PyObject_AsDn(NULL, py_other, NULL, &other))
                return NULL;
-       ldb_dn_add_child(ret, other);
-       return PyLdbDn_FromDn(ret);
+
+       py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
+       if (py_ret == NULL) {
+               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_child(py_ret->dn, other);
+       return (PyObject *)py_ret;
 }
 
 static PySequenceMethods py_ldb_dn_seq = {
@@ -284,29 +347,64 @@ static PyObject *py_ldb_dn_new(PyTypeObject *type, PyObject *args, PyObject *kwa
        char *str;
        PyObject *py_ldb;
        struct ldb_context *ldb_ctx;
-       const char *kwnames[] = { "ldb", "dn", NULL };
+       TALLOC_CTX *mem_ctx;
+       PyLdbDnObject *py_ret;
+       const char * const kwnames[] = { "ldb", "dn", NULL };
 
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Os", (char **)kwnames, &py_ldb, &str))
+       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Os",
+                                        discard_const_p(char *, kwnames),
+                                        &py_ldb, &str))
                return NULL;
 
        ldb_ctx = PyLdb_AsLdbContext(py_ldb);
-       
-       ret = ldb_dn_new(ldb_ctx, ldb_ctx, str);
-       /* ldb_dn_new() doesn't accept NULL as memory context, so 
-          we do it this way... */
-       talloc_steal(NULL, ret);
+
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
+
+       ret = ldb_dn_new(mem_ctx, ldb_ctx, str);
 
        if (ret == NULL || !ldb_dn_validate(ret)) {
+               talloc_free(mem_ctx);
                PyErr_SetString(PyExc_ValueError, "unable to parse dn string");
                return NULL;
        }
 
-       return py_talloc_import(&PyLdbDn, ret);
+       py_ret = (PyLdbDnObject *)type->tp_alloc(type, 0);
+       if (ret == NULL) {
+               talloc_free(mem_ctx);
+               PyErr_NoMemory();
+               return NULL;
+       }
+       py_ret->mem_ctx = mem_ctx;
+       py_ret->dn = ret;
+       return (PyObject *)py_ret;
 }
 
 PyObject *PyLdbDn_FromDn(struct ldb_dn *dn)
 {
-       return py_talloc_import(&PyLdbDn, dn);
+       PyLdbDnObject *py_ret;
+
+       if (dn == NULL) {
+               Py_RETURN_NONE;
+       }
+
+       py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
+       if (py_ret == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
+       py_ret->mem_ctx = talloc_new(NULL);
+       py_ret->dn = talloc_reference(py_ret->mem_ctx, dn);
+       return (PyObject *)py_ret;
+}
+
+static void py_ldb_dn_dealloc(PyLdbDnObject *self)
+{
+       talloc_free(self->mem_ctx);
+       self->ob_type->tp_free(self);
 }
 
 PyTypeObject PyLdbDn = {
@@ -318,30 +416,31 @@ PyTypeObject PyLdbDn = {
        .tp_as_sequence = &py_ldb_dn_seq,
        .tp_doc = "A LDB distinguished name.",
        .tp_new = py_ldb_dn_new,
-       .tp_dealloc = py_talloc_dealloc,
+       .tp_dealloc = (destructor)py_ldb_dn_dealloc,
        .tp_basicsize = sizeof(PyLdbObject),
+       .tp_flags = Py_TPFLAGS_DEFAULT,
 };
 
 /* Debug */
 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(3, 0);
 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap)
 {
-       PyObject *fn = context;
-       PyObject_CallFunction(fn, (char *)"(i,O)", level, PyString_FromFormatV(fmt, ap));
+       PyObject *fn = (PyObject *)context;
+       PyObject_CallFunction(fn, discard_const_p(char, "(i,O)"), level, PyString_FromFormatV(fmt, ap));
 }
 
 static PyObject *py_ldb_set_debug(PyLdbObject *self, PyObject *args)
 {
        PyObject *cb;
-       
+
        if (!PyArg_ParseTuple(args, "O", &cb))
                return NULL;
 
        Py_INCREF(cb);
        /* FIXME: Where do we DECREF cb ? */
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ldb_set_debug(self->ptr, py_ldb_debug, cb), PyLdb_AsLdbContext(self));
-       
-       return Py_None;
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_set_debug(self->ldb_ctx, py_ldb_debug, cb), PyLdb_AsLdbContext(self));
+
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_set_create_perms(PyTypeObject *self, PyObject *args)
@@ -352,7 +451,7 @@ static PyObject *py_ldb_set_create_perms(PyTypeObject *self, PyObject *args)
 
        ldb_set_create_perms(PyLdb_AsLdbContext(self), perms);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_set_modules_dir(PyTypeObject *self, PyObject *args)
@@ -363,31 +462,31 @@ static PyObject *py_ldb_set_modules_dir(PyTypeObject *self, PyObject *args)
 
        ldb_set_modules_dir(PyLdb_AsLdbContext(self), modules_dir);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_transaction_start(PyLdbObject *self)
 {
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ldb_transaction_start(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
-       return Py_None;
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_start(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_transaction_commit(PyLdbObject *self)
 {
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ldb_transaction_commit(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
-       return Py_None;
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_commit(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_transaction_cancel(PyLdbObject *self)
 {
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ldb_transaction_cancel(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
-       return Py_None;
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_cancel(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_setup_wellknown_attributes(PyLdbObject *self)
 {
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ldb_setup_wellknown_attributes(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
-       return Py_None;
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_setup_wellknown_attributes(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_repr(PyLdbObject *self)
@@ -399,7 +498,7 @@ static PyObject *py_ldb_get_root_basedn(PyLdbObject *self)
 {
        struct ldb_dn *dn = ldb_get_root_basedn(PyLdb_AsLdbContext(self));
        if (dn == NULL)
-               return Py_None;
+               Py_RETURN_NONE;
        return PyLdbDn_FromDn(dn);
 }
 
@@ -408,44 +507,44 @@ static PyObject *py_ldb_get_schema_basedn(PyLdbObject *self)
 {
        struct ldb_dn *dn = ldb_get_schema_basedn(PyLdb_AsLdbContext(self));
        if (dn == NULL)
-               return Py_None;
+               Py_RETURN_NONE;
        return PyLdbDn_FromDn(dn);
 }
 
-
 static PyObject *py_ldb_get_config_basedn(PyLdbObject *self)
 {
        struct ldb_dn *dn = ldb_get_config_basedn(PyLdb_AsLdbContext(self));
        if (dn == NULL)
-               return Py_None;
+               Py_RETURN_NONE;
        return PyLdbDn_FromDn(dn);
 }
 
-
 static PyObject *py_ldb_get_default_basedn(PyLdbObject *self)
 {
        struct ldb_dn *dn = ldb_get_default_basedn(PyLdb_AsLdbContext(self));
        if (dn == NULL)
-               return Py_None;
+               Py_RETURN_NONE;
        return PyLdbDn_FromDn(dn);
 }
 
-static const char **PyList_AsStringList(TALLOC_CTX *mem_ctx, PyObject *list)
+static const char **PyList_AsStringList(TALLOC_CTX *mem_ctx, PyObject *list, 
+                                                                               const char *paramname)
 {
        const char **ret;
        int i;
        if (!PyList_Check(list)) {
-               PyErr_SetString(PyExc_TypeError, "options is not a list");
+               PyErr_Format(PyExc_TypeError, "%s is not a list", paramname);
                return NULL;
        }
        ret = talloc_array(NULL, const char *, PyList_Size(list)+1);
        for (i = 0; i < PyList_Size(list); i++) {
                PyObject *item = PyList_GetItem(list, i);
                if (!PyString_Check(item)) {
-                       PyErr_SetString(PyExc_TypeError, "options should be strings");
+                       PyErr_Format(PyExc_TypeError, "%s should be strings", paramname);
                        return NULL;
                }
-               ret[i] = PyString_AsString(item);
+               ret[i] = talloc_strndup(ret, PyString_AsString(item),
+                                                          PyString_Size(item));
        }
        ret[i] = NULL;
        return ret;
@@ -453,7 +552,7 @@ static const char **PyList_AsStringList(TALLOC_CTX *mem_ctx, PyObject *list)
 
 static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
 {
-       const char *kwnames[] = { "url", "flags", "options", NULL };
+       const char * const kwnames[] = { "url", "flags", "options", NULL };
        char *url = NULL;
        PyObject *py_options = Py_None;
        const char **options;
@@ -461,8 +560,9 @@ static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
        int ret;
        struct ldb_context *ldb;
 
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO:Ldb.__init__", (char **)kwnames,
-                                                                        &url, &flags, &py_options))
+       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO:Ldb.__init__",
+                                        discard_const_p(char *, kwnames),
+                                        &url, &flags, &py_options))
                return -1;
 
        ldb = PyLdb_AsLdbContext(self);
@@ -470,15 +570,15 @@ static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
        if (py_options == Py_None) {
                options = NULL;
        } else {
-               options = PyList_AsStringList(ldb, py_options);
+               options = PyList_AsStringList(ldb, py_options, "options");
                if (options == NULL)
                        return -1;
        }
-       
+
        if (url != NULL) {
                ret = ldb_connect(ldb, url, flags, options);
                if (ret != LDB_SUCCESS) {
-                       PyErr_SetLdbError(ret, ldb);
+                       PyErr_SetLdbError(PyExc_LdbError, ret, ldb);
                        return -1;
                }
        }
@@ -489,42 +589,53 @@ static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
 
 static PyObject *py_ldb_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
 {
+       PyLdbObject *ret;
        struct ldb_context *ldb;
-       ldb = ldb_init(NULL, event_context_init(NULL)); 
+       ret = (PyLdbObject *)type->tp_alloc(type, 0);
+       if (ret == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
+       ret->mem_ctx = talloc_new(NULL);
+       ldb = ldb_init(ret->mem_ctx, NULL);
+
        if (ldb == NULL) {
                PyErr_NoMemory();
                return NULL;
        }
 
-       return py_talloc_import(type, ldb);
+       ret->ldb_ctx = ldb;
+       return (PyObject *)ret;
 }
 
 static PyObject *py_ldb_connect(PyLdbObject *self, PyObject *args, PyObject *kwargs)
 {
        char *url;
-       int flags;
+       int flags = 0;
        PyObject *py_options = Py_None;
        int ret;
        const char **options;
-       const char *kwnames[] = { "url", "flags", "options", NULL };
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|iO", (char **)kwnames, &url, &flags,
-                                                                        &py_options))
+       const char * const kwnames[] = { "url", "flags", "options", NULL };
+
+       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO",
+                                        discard_const_p(char *, kwnames),
+                                        &url, &flags, &py_options))
                return NULL;
 
        if (py_options == Py_None) {
                options = NULL;
        } else {
-               options = PyList_AsStringList(NULL, py_options);
+               options = PyList_AsStringList(NULL, py_options, "options");
                if (options == NULL)
                        return NULL;
        }
-       
+
        ret = ldb_connect(PyLdb_AsLdbContext(self), url, flags, options);
        talloc_free(options);
 
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, PyLdb_AsLdbContext(self));
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_modify(PyLdbObject *self, PyObject *args)
@@ -540,9 +651,9 @@ static PyObject *py_ldb_modify(PyLdbObject *self, PyObject *args)
        }
 
        ret = ldb_modify(PyLdb_AsLdbContext(self), PyLdbMessage_AsMessage(py_msg));
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, PyLdb_AsLdbContext(self));
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args)
@@ -553,22 +664,27 @@ static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args)
        struct ldb_message_element *msgel;
        struct ldb_message *msg;
        PyObject *key, *value;
+       TALLOC_CTX *mem_ctx;
 
        if (!PyArg_ParseTuple(args, "O", &py_msg))
                return NULL;
 
+       mem_ctx = talloc_new(NULL);
+
        if (PyDict_Check(py_msg)) {
                PyObject *dn_value = PyDict_GetItemString(py_msg, "dn");
-               msg = ldb_msg_new(NULL);
+               msg = ldb_msg_new(mem_ctx);
                msg->elements = talloc_zero_array(msg, struct ldb_message_element, PyDict_Size(py_msg));
                msg_pos = dict_pos = 0;
                if (dn_value) {
                        if (!PyObject_AsDn(msg, dn_value, PyLdb_AsLdbContext(self), &msg->dn)) {
                                PyErr_SetString(PyExc_TypeError, "unable to import dn object");
+                               talloc_free(mem_ctx);
                                return NULL;
                        }
                        if (msg->dn == NULL) {
                                PyErr_SetString(PyExc_TypeError, "dn set but not found");
+                               talloc_free(mem_ctx);
                                return NULL;
                        }
                }
@@ -579,6 +695,7 @@ static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args)
                                msgel = PyObject_AsMessageElement(msg->elements, value, 0, key_str);
                                if (msgel == NULL) {
                                        PyErr_SetString(PyExc_TypeError, "unable to import element");
+                                       talloc_free(mem_ctx);
                                        return NULL;
                                }
                                memcpy(&msg->elements[msg_pos], msgel, sizeof(*msgel));
@@ -588,6 +705,7 @@ static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args)
 
                if (msg->dn == NULL) {
                        PyErr_SetString(PyExc_TypeError, "no dn set");
+                       talloc_free(mem_ctx);
                        return NULL;
                }
 
@@ -595,30 +713,32 @@ static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args)
        } else {
                msg = PyLdbMessage_AsMessage(py_msg);
        }
-       
+
        ret = ldb_add(PyLdb_AsLdbContext(self), msg);
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, PyLdb_AsLdbContext(self));
+       talloc_free(mem_ctx);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
-
-
 static PyObject *py_ldb_delete(PyLdbObject *self, PyObject *args)
 {
        PyObject *py_dn;
        struct ldb_dn *dn;
        int ret;
+       struct ldb_context *ldb;
        if (!PyArg_ParseTuple(args, "O", &py_dn))
                return NULL;
 
-       if (!PyObject_AsDn(NULL, py_dn, PyLdb_AsLdbContext(self), &dn))
+       ldb = PyLdb_AsLdbContext(self);
+
+       if (!PyObject_AsDn(NULL, py_dn, ldb, &dn))
                return NULL;
 
-       ret = ldb_delete(PyLdb_AsLdbContext(self), dn);
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, PyLdb_AsLdbContext(self));
+       ret = ldb_delete(ldb, dn);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_rename(PyLdbObject *self, PyObject *args)
@@ -626,24 +746,32 @@ static PyObject *py_ldb_rename(PyLdbObject *self, PyObject *args)
        PyObject *py_dn1, *py_dn2;
        struct ldb_dn *dn1, *dn2;
        int ret;
+       struct ldb_context *ldb;
+       TALLOC_CTX *mem_ctx;
        if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
                return NULL;
 
-       if (!PyLdbDn_Check(py_dn1) || !PyLdbDn_Check(py_dn2)) {
-               PyErr_SetString(PyExc_TypeError, "Expected Ldb Dn");
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               PyErr_NoMemory();
                return NULL;
        }
-
-       if (!PyObject_AsDn(NULL, py_dn1, PyLdb_AsLdbContext(self), &dn1))
+       ldb = PyLdb_AsLdbContext(self);
+       if (!PyObject_AsDn(mem_ctx, py_dn1, ldb, &dn1)) {
+               talloc_free(mem_ctx);
                return NULL;
+       }
 
-       if (!PyObject_AsDn(NULL, py_dn2, PyLdb_AsLdbContext(self), &dn2))
+       if (!PyObject_AsDn(mem_ctx, py_dn2, ldb, &dn2)) {
+               talloc_free(mem_ctx);
                return NULL;
+       }
 
-       ret = ldb_rename(PyLdb_AsLdbContext(self), dn1, dn2);
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, PyLdb_AsLdbContext(self));
+       ret = ldb_rename(ldb, dn1, dn2);
+       talloc_free(mem_ctx);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_schema_attribute_remove(PyLdbObject *self, PyObject *args)
@@ -654,7 +782,7 @@ static PyObject *py_ldb_schema_attribute_remove(PyLdbObject *self, PyObject *arg
 
        ldb_schema_attribute_remove(PyLdb_AsLdbContext(self), name);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_schema_attribute_add(PyLdbObject *self, PyObject *args)
@@ -667,20 +795,20 @@ static PyObject *py_ldb_schema_attribute_add(PyLdbObject *self, PyObject *args)
 
        ret = ldb_schema_attribute_add(PyLdb_AsLdbContext(self), attribute, flags, syntax);
 
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, PyLdb_AsLdbContext(self));
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *ldb_ldif_to_pyobject(struct ldb_ldif *ldif)
 {
        if (ldif == NULL) {
-               return Py_None;
+               Py_RETURN_NONE;
        } else {
        /* We don't want this attached to the 'ldb' any more */
-               talloc_steal(NULL, ldif);
-               return Py_BuildValue((char *)"(iO)", ldif->changetype, 
-                                                        PyLdbMessage_FromMessage(ldif->msg));
+               return Py_BuildValue(discard_const_p(char, "(iO)"),
+                                    ldif->changetype,
+                                    PyLdbMessage_FromMessage(ldif->msg));
        }
 }
 
@@ -691,16 +819,61 @@ static PyObject *py_ldb_parse_ldif(PyLdbObject *self, PyObject *args)
        struct ldb_ldif *ldif;
        const char *s;
 
+       TALLOC_CTX *mem_ctx;
+
        if (!PyArg_ParseTuple(args, "s", &s))
                return NULL;
 
+       mem_ctx = talloc_new(NULL);
+       if (!mem_ctx) {
+               Py_RETURN_NONE;
+       }
+
        list = PyList_New(0);
-       while ((ldif = ldb_ldif_read_string(self->ptr, &s)) != NULL) {
-               PyList_Append(list, ldb_ldif_to_pyobject(ldif));
+       while (s && *s != '\0') {
+               ldif = ldb_ldif_read_string(self->ldb_ctx, &s);
+               talloc_steal(mem_ctx, ldif);
+               if (ldif) {
+                       PyList_Append(list, ldb_ldif_to_pyobject(ldif));
+               } else {
+                       PyErr_SetString(PyExc_ValueError, "unable to parse ldif string");
+                       talloc_free(mem_ctx);
+                       return NULL;
+               }
        }
+       talloc_free(mem_ctx); /* The pyobject already has a reference to the things it needs */
        return PyObject_GetIter(list);
 }
 
+static PyObject *py_ldb_msg_diff(PyLdbObject *self, PyObject *args)
+{
+       PyObject *py_msg_old;
+       PyObject *py_msg_new;
+       struct ldb_message *diff;
+       PyObject *py_ret;
+
+       if (!PyArg_ParseTuple(args, "OO", &py_msg_old, &py_msg_new))
+               return NULL;
+
+       if (!PyLdbMessage_Check(py_msg_old)) {
+               PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for old message");
+               return NULL;
+       }
+
+       if (!PyLdbMessage_Check(py_msg_new)) {
+               PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for new message");
+               return NULL;
+       }
+
+       diff = ldb_msg_diff(PyLdb_AsLdbContext(self), PyLdbMessage_AsMessage(py_msg_old), PyLdbMessage_AsMessage(py_msg_new));
+       if (diff == NULL) 
+               return NULL;
+
+       py_ret = PyLdbMessage_FromMessage(diff);
+
+       return py_ret;
+}
+
 static PyObject *py_ldb_schema_format_value(PyLdbObject *self, PyObject *args)
 {
        const struct ldb_schema_attribute *a;
@@ -713,21 +886,21 @@ static PyObject *py_ldb_schema_format_value(PyLdbObject *self, PyObject *args)
 
        if (!PyArg_ParseTuple(args, "sO", &element_name, &val))
                return NULL;
-       
+
        mem_ctx = talloc_new(NULL);
-       
+
        old_val.data = (uint8_t *)PyString_AsString(val);
        old_val.length = PyString_Size(val);
-               
+
        a = ldb_schema_attribute_by_name(PyLdb_AsLdbContext(self), element_name);
 
        if (a == NULL) {
-               return Py_None;
+               Py_RETURN_NONE;
        }
-       
+
        if (a->syntax->ldif_write_fn(PyLdb_AsLdbContext(self), mem_ctx, &old_val, &new_val) != 0) {
                talloc_free(mem_ctx);
-               return Py_None;
+               Py_RETURN_NONE;
        }
 
        ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
@@ -744,7 +917,7 @@ static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwar
        char *expr = NULL;
        PyObject *py_attrs = Py_None;
        PyObject *py_controls = Py_None;
-       const char *kwnames[] = { "base", "scope", "expression", "attrs", "controls", NULL };
+       const char * const kwnames[] = { "base", "scope", "expression", "attrs", "controls", NULL };
        int ret;
        struct ldb_result *res;
        struct ldb_request *req;
@@ -752,9 +925,11 @@ static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwar
        struct ldb_context *ldb_ctx;
        struct ldb_control **parsed_controls;
        struct ldb_dn *base;
+       PyObject *py_ret;
 
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OisOO", (char **)kwnames,
-                                                                        &py_base, &scope, &expr, &py_attrs, &py_controls))
+       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OizOO",
+                                        discard_const_p(char *, kwnames),
+                                        &py_base, &scope, &expr, &py_attrs, &py_controls))
                return NULL;
 
        ldb_ctx = PyLdb_AsLdbContext(self);
@@ -762,7 +937,7 @@ static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwar
        if (py_attrs == Py_None) {
                attrs = NULL;
        } else {
-               attrs = PyList_AsStringList(ldb_ctx, py_attrs);
+               attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
                if (attrs == NULL)
                        return NULL;
        }
@@ -770,14 +945,16 @@ static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwar
        if (py_base == Py_None) {
                base = ldb_get_default_basedn(ldb_ctx);
        } else {
-               if (!PyObject_AsDn(ldb_ctx, py_base, ldb_ctx, &base))
+               if (!PyObject_AsDn(ldb_ctx, py_base, ldb_ctx, &base)) {
+                       talloc_free(attrs);
                        return NULL;
+               }
        }
 
        if (py_controls == Py_None) {
                parsed_controls = NULL;
        } else {
-               const char **controls = PyList_AsStringList(ldb_ctx, py_controls);
+               const char **controls = PyList_AsStringList(ldb_ctx, py_controls, "controls");
                parsed_controls = ldb_parse_control_strings(ldb_ctx, ldb_ctx, controls);
                talloc_free(controls);
        }
@@ -785,6 +962,7 @@ static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwar
        res = talloc_zero(ldb_ctx, struct ldb_result);
        if (res == NULL) {
                PyErr_NoMemory();
+               talloc_free(attrs);
                return NULL;
        }
 
@@ -798,21 +976,33 @@ static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwar
                                   ldb_search_default_callback,
                                   NULL);
 
+       talloc_steal(req, attrs);
+
        if (ret != LDB_SUCCESS) {
                talloc_free(res);
-               PyErr_LDB_ERROR_IS_ERR_RAISE(ret, ldb_ctx);
+               PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
                return NULL;
        }
 
        ret = ldb_request(ldb_ctx, req);
-               
+
        if (ret == LDB_SUCCESS) {
                ret = ldb_wait(req->handle, LDB_WAIT_ALL);
        }
 
        talloc_free(req);
 
-       return PyLdbResult_FromResult(res);
+       if (ret != LDB_SUCCESS) {
+               talloc_free(res);
+               PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
+               return NULL;
+       }
+
+       py_ret = PyLdbResult_FromResult(res);
+
+       talloc_free(res);
+
+       return py_ret;
 }
 
 static PyObject *py_ldb_get_opaque(PyLdbObject *self, PyObject *args)
@@ -825,9 +1015,12 @@ static PyObject *py_ldb_get_opaque(PyLdbObject *self, PyObject *args)
 
        data = ldb_get_opaque(PyLdb_AsLdbContext(self), name);
 
+       if (data == NULL)
+               Py_RETURN_NONE;
+
        /* FIXME: More interpretation */
 
-       return Py_None; 
+       return Py_True;
 }
 
 static PyObject *py_ldb_set_opaque(PyLdbObject *self, PyObject *args)
@@ -842,7 +1035,20 @@ static PyObject *py_ldb_set_opaque(PyLdbObject *self, PyObject *args)
 
        ldb_set_opaque(PyLdb_AsLdbContext(self), name, data);
 
-       return Py_None;
+       Py_RETURN_NONE;
+}
+
+static PyObject *py_ldb_modules(PyLdbObject *self)
+{
+       struct ldb_context *ldb = PyLdb_AsLdbContext(self);
+       PyObject *ret = PyList_New(0);
+       struct ldb_module *mod;
+
+       for (mod = ldb->modules; mod; mod = mod->next) {
+               PyList_Append(ret, PyLdbModule_FromModule(mod));
+       }
+
+       return ret;
 }
 
 static PyMethodDef py_ldb_methods[] = {
@@ -910,21 +1116,36 @@ static PyMethodDef py_ldb_methods[] = {
        { "parse_ldif", (PyCFunction)py_ldb_parse_ldif, METH_VARARGS,
                "S.parse_ldif(ldif) -> iter(messages)\n"
                "Parse a string formatted using LDIF." },
-       { "get_opaque", (PyCFunction)py_ldb_set_opaque, METH_VARARGS,
+       { "msg_diff", (PyCFunction)py_ldb_msg_diff, METH_VARARGS,
+               "S.msg_diff(Message) -> Message\n"
+               "Return an LDB Message of the difference between two Message objects." },
+       { "get_opaque", (PyCFunction)py_ldb_get_opaque, METH_VARARGS,
                "S.get_opaque(name) -> value\n"
                "Get an opaque value set on this LDB connection. \n"
                ":note: The returned value may not be useful in Python."
        },
-       { "set_opaque", (PyCFunction)py_ldb_get_opaque, METH_VARARGS,
+       { "set_opaque", (PyCFunction)py_ldb_set_opaque, METH_VARARGS,
                "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 " },
        { NULL },
 };
 
 PyObject *PyLdbModule_FromModule(struct ldb_module *mod)
 {
-       return py_talloc_import(&PyLdbModule, 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)
@@ -933,7 +1154,7 @@ static PyObject *py_ldb_get_firstmodule(PyLdbObject *self, void *closure)
 }
 
 static PyGetSetDef py_ldb_getset[] = {
-       { (char *)"firstmodule", (getter)py_ldb_get_firstmodule, NULL, NULL },
+       { discard_const_p(char, "firstmodule"), (getter)py_ldb_get_firstmodule, NULL, NULL },
        { NULL }
 };
 
@@ -950,7 +1171,7 @@ static int py_ldb_contains(PyLdbObject *self, PyObject *obj)
 
        ret = ldb_search(ldb_ctx, ldb_ctx, &result, dn, LDB_SCOPE_BASE, NULL, NULL);
        if (ret != LDB_SUCCESS) {
-               PyErr_SetLdbError(ret, ldb_ctx);
+               PyErr_SetLdbError(PyExc_LdbError, ret, ldb_ctx);
                return -1;
        }
 
@@ -967,17 +1188,31 @@ static PySequenceMethods py_ldb_seq = {
 
 PyObject *PyLdb_FromLdbContext(struct ldb_context *ldb_ctx)
 {
-       return py_talloc_import(&PyLdb, 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);
+       self->ob_type->tp_free(self);
 }
 
 PyTypeObject PyLdb = {
-       PyObject_HEAD_INIT(NULL)
        .tp_name = "Ldb",
        .tp_methods = py_ldb_methods,
        .tp_repr = (reprfunc)py_ldb_repr,
        .tp_new = py_ldb_new,
        .tp_init = (initproc)py_ldb_init,
-       .tp_dealloc = py_talloc_dealloc,
+       .tp_dealloc = (destructor)py_ldb_dealloc,
        .tp_getset = py_ldb_getset,
        .tp_getattro = PyObject_GenericGetAttr,
        .tp_basicsize = sizeof(PyLdbObject),
@@ -999,54 +1234,64 @@ static PyObject *py_ldb_module_str(PyLdbModuleObject *self)
 static PyObject *py_ldb_module_start_transaction(PyLdbModuleObject *self)
 {
        PyLdbModule_AsModule(self)->ops->start_transaction(PyLdbModule_AsModule(self));
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_module_end_transaction(PyLdbModuleObject *self)
 {
        PyLdbModule_AsModule(self)->ops->end_transaction(PyLdbModule_AsModule(self));
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_module_del_transaction(PyLdbModuleObject *self)
 {
        PyLdbModule_AsModule(self)->ops->del_transaction(PyLdbModule_AsModule(self));
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_module_search(PyLdbModuleObject *self, PyObject *args, PyObject *kwargs)
 {
-       PyObject *py_base, *py_tree, *py_attrs;
+       PyObject *py_base, *py_tree, *py_attrs, *py_ret;
        int ret, scope;
        struct ldb_request *req;
-       const char *kwnames[] = { "base", "scope", "tree", "attrs", NULL };
+       const char * const kwnames[] = { "base", "scope", "tree", "attrs", NULL };
        struct ldb_module *mod;
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OiOO", (char **)kwnames, 
-                                                                        &py_base, &scope, &py_tree, &py_attrs))
+       const char * const*attrs;
+
+       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OiOO",
+                                        discard_const_p(char *, kwnames),
+                                        &py_base, &scope, &py_tree, &py_attrs))
                return NULL;
 
-       req = talloc_zero(NULL, struct ldb_request);
+       mod = self->mod;
 
-       req->operation = LDB_SEARCH;
-       req->op.search.base = PyLdbDn_AsDn(py_base);
-       req->op.search.scope = scope;
-       req->op.search.tree = PyLdbTree_AsTree(py_tree);
        if (py_attrs == Py_None) {
-               req->op.search.attrs = NULL;
+               attrs = NULL;
        } else {
-               req->op.search.attrs = PyList_AsStringList(req, py_attrs);
+               attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
+               if (attrs == NULL)
+                       return NULL;
        }
 
-       req->op.search.res = talloc_zero(NULL, struct ldb_result);
+       ret = ldb_build_search_req(&req, mod->ldb, NULL, PyLdbDn_AsDn(py_base), 
+                            scope, NULL /* expr */, attrs,
+                            NULL /* controls */, NULL, NULL, NULL);
+
+       talloc_steal(req, attrs);
 
-       mod = self->ptr;
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
+
+       req->op.search.res = NULL;
 
        ret = mod->ops->search(mod, req);
-       talloc_free(req);
 
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, NULL);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
+
+       py_ret = PyLdbResult_FromResult(req->op.search.res);
+
+       talloc_free(req);
 
-       return PyLdbResult_FromResult(req->op.search.res);
+       return py_ret;  
 }
 
 
@@ -1055,6 +1300,7 @@ 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", &py_message))
                return NULL;
@@ -1063,11 +1309,12 @@ static PyObject *py_ldb_module_add(PyLdbModuleObject *self, PyObject *args)
        req->operation = LDB_ADD;
        req->op.add.message = PyLdbMessage_AsMessage(py_message);
 
-       ret = PyLdbModule_AsModule(self)->ops->add(PyLdbModule_AsModule(self), req);
+       mod = PyLdbModule_AsModule(self);
+       ret = mod->ops->add(mod, req);
 
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, NULL);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_module_modify(PyLdbModuleObject *self, PyObject *args) 
@@ -1075,19 +1322,21 @@ 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", &py_message))
                return NULL;
-       
+
        req = talloc_zero(NULL, struct ldb_request);
        req->operation = LDB_MODIFY;
        req->op.mod.message = PyLdbMessage_AsMessage(py_message);
-       
-       ret = PyLdbModule_AsModule(self)->ops->modify(PyLdbModule_AsModule(self), req);
 
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, NULL);
+       mod = PyLdbModule_AsModule(self);
+       ret = mod->ops->modify(mod, req);
 
-       return Py_None;
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
+
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_module_delete(PyLdbModuleObject *self, PyObject *args) 
@@ -1098,16 +1347,16 @@ static PyObject *py_ldb_module_delete(PyLdbModuleObject *self, PyObject *args)
 
        if (!PyArg_ParseTuple(args, "O", &py_dn))
                return NULL;
-       
+
        req = talloc_zero(NULL, struct ldb_request);
        req->operation = LDB_DELETE;
        req->op.del.dn = PyLdbDn_AsDn(py_dn);
-       
+
        ret = PyLdbModule_AsModule(self)->ops->del(PyLdbModule_AsModule(self), req);
 
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, NULL);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_module_rename(PyLdbModuleObject *self, PyObject *args)
@@ -1118,18 +1367,18 @@ static PyObject *py_ldb_module_rename(PyLdbModuleObject *self, PyObject *args)
 
        if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
                return NULL;
-       
+
        req = talloc_zero(NULL, struct ldb_request);
 
        req->operation = LDB_RENAME;
        req->op.rename.olddn = PyLdbDn_AsDn(py_dn1);
        req->op.rename.newdn = PyLdbDn_AsDn(py_dn2);
-       
+
        ret = PyLdbModule_AsModule(self)->ops->rename(PyLdbModule_AsModule(self), req);
 
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, NULL);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyMethodDef py_ldb_module_methods[] = {
@@ -1144,15 +1393,37 @@ static PyMethodDef py_ldb_module_methods[] = {
        { NULL },
 };
 
+static void py_ldb_module_dealloc(PyLdbModuleObject *self)
+{
+       talloc_free(self->mem_ctx);
+       self->ob_type->tp_free(self);
+}
+
 PyTypeObject PyLdbModule = {
        .tp_name = "LdbModule",
        .tp_methods = py_ldb_module_methods,
        .tp_repr = (reprfunc)py_ldb_module_repr,
        .tp_str = (reprfunc)py_ldb_module_str,
-       .tp_basicsize = sizeof(py_talloc_Object),
-       .tp_dealloc = py_talloc_dealloc,
+       .tp_basicsize = sizeof(PyLdbModuleObject),
+       .tp_dealloc = (destructor)py_ldb_module_dealloc,
+       .tp_flags = Py_TPFLAGS_DEFAULT,
 };
 
+
+/**
+ * Create a ldb_message_element from a Python object.
+ *
+ * This will accept any sequence objects that contains strings, or 
+ * a string object.
+ *
+ * A reference to set_obj will 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
+ * @return New ldb_message_element, allocated as child of mem_ctx
+ */
 struct ldb_message_element *PyObject_AsMessageElement(TALLOC_CTX *mem_ctx,
                                                                                           PyObject *set_obj, int flags,
                                                                                           const char *attr_name)
@@ -1160,26 +1431,29 @@ struct ldb_message_element *PyObject_AsMessageElement(TALLOC_CTX *mem_ctx,
        struct ldb_message_element *me;
 
        if (PyLdbMessageElement_Check(set_obj))
-               return PyLdbMessageElement_AsMessageElement(set_obj);
+               return talloc_reference(mem_ctx, 
+                                                               PyLdbMessageElement_AsMessageElement(set_obj));
 
        me = talloc(mem_ctx, struct ldb_message_element);
 
-       me->name = attr_name;
+       me->name = talloc_strdup(me, attr_name);
        me->flags = flags;
        if (PyString_Check(set_obj)) {
                me->num_values = 1;
                me->values = talloc_array(me, struct ldb_val, me->num_values);
                me->values[0].length = PyString_Size(set_obj);
-               me->values[0].data = (uint8_t *)talloc_strdup(me->values
-                                                                                  PyString_AsString(set_obj));
+               me->values[0].data = talloc_memdup(me
+                       (uint8_t *)PyString_AsString(set_obj), me->values[0].length);
        } else if (PySequence_Check(set_obj)) {
                int i;
                me->num_values = PySequence_Size(set_obj);
                me->values = talloc_array(me, struct ldb_val, me->num_values);
                for (i = 0; i < me->num_values; i++) {
                        PyObject *obj = PySequence_GetItem(set_obj, i);
+
                        me->values[i].length = PyString_Size(obj);
-                       me->values[i].data = (uint8_t *)PyString_AsString(obj);
+                       me->values[i].data = talloc_memdup(me, 
+                               (uint8_t *)PyString_AsString(obj), me->values[i].length);
                }
        } else {
                talloc_free(me);
@@ -1190,7 +1464,7 @@ struct ldb_message_element *PyObject_AsMessageElement(TALLOC_CTX *mem_ctx,
 }
 
 
-PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx, 
+static PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx, 
                                                                 struct ldb_message_element *me)
 {
        int i;
@@ -1207,20 +1481,42 @@ PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx,
        return result;
 }
 
-PyObject *py_ldb_msg_element_get(PyLdbMessageElementObject *self, PyObject *args)
+static PyObject *py_ldb_msg_element_get(PyLdbMessageElementObject *self, PyObject *args)
 {
        int i;
        if (!PyArg_ParseTuple(args, "i", &i))
                return NULL;
        if (i < 0 || i >= PyLdbMessageElement_AsMessageElement(self)->num_values)
-               return Py_None;
+               Py_RETURN_NONE;
 
        return PyObject_FromLdbValue(NULL, PyLdbMessageElement_AsMessageElement(self), 
                                                                 &(PyLdbMessageElement_AsMessageElement(self)->values[i]));
 }
 
+static PyObject *py_ldb_msg_element_flags(PyLdbMessageElementObject *self, PyObject *args)
+{
+       struct ldb_message_element *el;
+
+       el = PyLdbMessageElement_AsMessageElement(self);
+       return PyInt_FromLong(el->flags);
+}
+
+static PyObject *py_ldb_msg_element_set_flags(PyLdbMessageElementObject *self, PyObject *args)
+{
+       int flags;
+       struct ldb_message_element *el;
+       if (!PyArg_ParseTuple(args, "i", &flags))
+               return NULL;
+
+       el = PyLdbMessageElement_AsMessageElement(self);
+       el->flags = flags;
+       Py_RETURN_NONE;
+}
+
 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 },
 };
 
@@ -1255,9 +1551,21 @@ static PyObject *py_ldb_msg_element_iter(PyLdbMessageElementObject *self)
        return PyObject_GetIter(ldb_msg_element_to_set(NULL, PyLdbMessageElement_AsMessageElement(self)));
 }
 
-PyObject *PyLdbMessageElement_FromMessageElement(struct ldb_message_element *el)
+PyObject *PyLdbMessageElement_FromMessageElement(struct ldb_message_element *el, TALLOC_CTX *mem_ctx)
 {
-       return py_talloc_import(&PyLdbMessageElement, el);
+       PyLdbMessageElementObject *ret;
+       ret = (PyLdbMessageElementObject *)PyLdbMessageElement.tp_alloc(&PyLdbMessageElement, 0);
+       if (ret == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
+       ret->mem_ctx = talloc_new(NULL);
+       if (talloc_reference(ret->mem_ctx, mem_ctx) == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
+       ret->el = el;
+       return (PyObject *)ret;
 }
 
 static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
@@ -1266,34 +1574,68 @@ static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyOb
        struct ldb_message_element *el;
        int flags = 0;
        char *name = NULL;
-       const char *kwnames[] = { "elements", "flags", "name", NULL };
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Ois", (char **)kwnames, &py_elements, &flags, &name))
+       const char * const kwnames[] = { "elements", "flags", "name", NULL };
+       PyLdbMessageElementObject *ret;
+       TALLOC_CTX *mem_ctx;
+
+       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Ois",
+                                        discard_const_p(char *, kwnames),
+                                        &py_elements, &flags, &name))
+               return NULL;
+
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               PyErr_NoMemory();
                return NULL;
+       }
 
-       el = talloc_zero(NULL, struct ldb_message_element);
+       el = talloc_zero(mem_ctx, struct ldb_message_element);
 
        if (py_elements != NULL) {
                int i;
-               if (!PySequence_Check(py_elements)) {
+               if (PyString_Check(py_elements)) {
                        el->num_values = 1;
                        el->values = talloc_array(el, struct ldb_val, 1);
-                       el->values[0].data = (uint8_t *)PyString_AsString(py_elements);
                        el->values[0].length = PyString_Size(py_elements);
-               } else {
+                       el->values[0].data = talloc_memdup(el, 
+                               (uint8_t *)PyString_AsString(py_elements), el->values[0].length);
+               } else if (PySequence_Check(py_elements)) {
                        el->num_values = PySequence_Size(py_elements);
                        el->values = talloc_array(el, struct ldb_val, el->num_values);
                        for (i = 0; i < el->num_values; i++) {
                                PyObject *item = PySequence_GetItem(py_elements, i);
-                               el->values[i].data = (uint8_t *)PyString_AsString(item);
+                               if (!PyString_Check(item)) {
+                                       PyErr_Format(PyExc_TypeError, 
+                                                       "Expected string as element %d in list", 
+                                                       i);
+                                       talloc_free(mem_ctx);
+                                       return NULL;
+                               }
                                el->values[i].length = PyString_Size(item);
+                               el->values[i].data = talloc_memdup(el, 
+                                       (uint8_t *)PyString_AsString(item), el->values[i].length);
                        }
+               } else {
+                       PyErr_SetString(PyExc_TypeError, 
+                                       "Expected string or list");
+                       talloc_free(mem_ctx);
+                       return NULL;
                }
        }
 
        el->flags = flags;
        el->name = talloc_strdup(el, name);
 
-       return py_talloc_import(&PyLdbMessageElement, el);
+       ret = (PyLdbMessageElementObject *)PyLdbMessageElement.tp_alloc(&PyLdbMessageElement, 0);
+       if (ret == NULL) {
+               PyErr_NoMemory();
+               talloc_free(mem_ctx);
+               return NULL;
+       }
+
+       ret->mem_ctx = mem_ctx;
+       ret->el = el;
+       return (PyObject *)ret;
 }
 
 static PyObject *py_ldb_msg_element_repr(PyLdbMessageElementObject *self)
@@ -1318,16 +1660,34 @@ static PyObject *py_ldb_msg_element_repr(PyLdbMessageElementObject *self)
        return ret;
 }
 
+static PyObject *py_ldb_msg_element_str(PyLdbMessageElementObject *self)
+{
+       struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
+
+       if (el->num_values == 1)
+               return PyString_FromStringAndSize((char *)el->values[0].data, el->values[0].length);
+       else 
+               Py_RETURN_NONE;
+}
+
+static void py_ldb_msg_element_dealloc(PyLdbMessageElementObject *self)
+{
+       talloc_free(self->mem_ctx);
+       self->ob_type->tp_free(self);
+}
+
 PyTypeObject PyLdbMessageElement = {
        .tp_name = "MessageElement",
        .tp_basicsize = sizeof(PyLdbMessageElementObject),
-       .tp_dealloc = py_talloc_dealloc,
+       .tp_dealloc = (destructor)py_ldb_msg_element_dealloc,
        .tp_repr = (reprfunc)py_ldb_msg_element_repr,
+       .tp_str = (reprfunc)py_ldb_msg_element_str,
        .tp_methods = py_ldb_msg_element_methods,
        .tp_compare = (cmpfunc)py_ldb_msg_element_cmp,
        .tp_iter = (getiterfunc)py_ldb_msg_element_iter,
        .tp_as_sequence = &py_ldb_msg_element_seq,
        .tp_new = py_ldb_msg_element_new,
+       .tp_flags = Py_TPFLAGS_DEFAULT,
 };
 
 static PyObject *py_ldb_msg_remove_attr(PyLdbMessageObject *self, PyObject *args)
@@ -1336,9 +1696,9 @@ static PyObject *py_ldb_msg_remove_attr(PyLdbMessageObject *self, PyObject *args
        if (!PyArg_ParseTuple(args, "s", &name))
                return NULL;
 
-       ldb_msg_remove_attr(self->ptr, name);
+       ldb_msg_remove_attr(self->msg, name);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_ldb_msg_keys(PyLdbMessageObject *self)
@@ -1361,13 +1721,14 @@ static PyObject *py_ldb_msg_getitem_helper(PyLdbMessageObject *self, PyObject *p
 {
        struct ldb_message_element *el;
        char *name = PyString_AsString(py_name);
+       struct ldb_message *msg = PyLdbMessage_AsMessage(self);
        if (!strcmp(name, "dn"))
-               return PyLdbDn_FromDn(PyLdbMessage_AsMessage(self)->dn);
-       el = ldb_msg_find_element(PyLdbMessage_AsMessage(self), name);
+               return PyLdbDn_FromDn(msg->dn);
+       el = ldb_msg_find_element(msg, name);
        if (el == NULL) {
                return NULL;
        }
-       return (PyObject *)PyLdbMessageElement_FromMessageElement(el);
+       return (PyObject *)PyLdbMessageElement_FromMessageElement(el, msg);
 }
 
 static PyObject *py_ldb_msg_getitem(PyLdbMessageObject *self, PyObject *py_name)
@@ -1388,7 +1749,7 @@ static PyObject *py_ldb_msg_get(PyLdbMessageObject *self, PyObject *args)
 
        ret = py_ldb_msg_getitem_helper(self, name);
        if (ret == NULL)
-               return Py_None;
+               Py_RETURN_NONE;
        return ret;
 }
 
@@ -1403,7 +1764,7 @@ static PyObject *py_ldb_msg_items(PyLdbMessageObject *self)
                j++;
        }
        for (i = 0; i < msg->num_elements; i++, j++) {
-               PyList_SetItem(l, j, Py_BuildValue("(sO)", msg->elements[i].name, PyLdbMessageElement_FromMessageElement(&msg->elements[i])));
+               PyList_SetItem(l, j, Py_BuildValue("(sO)", msg->elements[i].name, PyLdbMessageElement_FromMessageElement(&msg->elements[i], self->msg)));
        }
        return l;
 }
@@ -1416,17 +1777,34 @@ static PyMethodDef py_ldb_msg_methods[] = {
        { NULL },
 };
 
+static PyObject *py_ldb_msg_iter(PyLdbMessageObject *self)
+{
+       PyObject *list, *iter;
+
+       list = py_ldb_msg_keys(self);
+       iter = PyObject_GetIter(list);
+       Py_DECREF(list);
+       return iter;
+}
+
 static int py_ldb_msg_setitem(PyLdbMessageObject *self, PyObject *name, PyObject *value)
 {
-       char *attr_name = PyString_AsString(name);
+       char *attr_name;
+
+       if (!PyString_Check(name)) {
+               PyErr_SetNone(PyExc_TypeError);
+               return -1;
+       }
+       
+       attr_name = PyString_AsString(name);
        if (value == NULL) {
-               ldb_msg_remove_attr(self->ptr, attr_name);
+               /* delitem */
+               ldb_msg_remove_attr(self->msg, attr_name);
        } else {
-               struct ldb_message_element *el = PyObject_AsMessageElement(NULL,
+               struct ldb_message_element *el = PyObject_AsMessageElement(self->msg,
                                                                                        value, 0, attr_name);
                if (el == NULL)
                        return -1;
-               talloc_steal(self->ptr, el);
                ldb_msg_remove_attr(PyLdbMessage_AsMessage(self), attr_name);
                ldb_msg_add(PyLdbMessage_AsMessage(self), el, el->flags);
        }
@@ -1446,43 +1824,85 @@ static PyMappingMethods py_ldb_msg_mapping = {
 
 static PyObject *py_ldb_msg_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
 {
-       const char *kwnames[] = { "dn", NULL };
+       const char * const kwnames[] = { "dn", NULL };
        struct ldb_message *ret;
+       TALLOC_CTX *mem_ctx;
        PyObject *pydn = NULL;
-       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", (char **)kwnames, &pydn))
+       PyLdbMessageObject *py_ret;
+
+       if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
+                                        discard_const_p(char *, kwnames),
+                                        &pydn))
                return NULL;
 
-       ret = ldb_msg_new(NULL);
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
+
+       ret = ldb_msg_new(mem_ctx);
        if (ret == NULL) {
+               talloc_free(mem_ctx);
                PyErr_NoMemory();
                return NULL;
        }
 
-       if (pydn != NULL)
-               if (!PyObject_AsDn(NULL, pydn, NULL, &ret->dn))
+       if (pydn != NULL) {
+               struct ldb_dn *dn;
+               if (!PyObject_AsDn(NULL, pydn, NULL, &dn)) {
+                       talloc_free(mem_ctx);
                        return NULL;
+               }
+               ret->dn = talloc_reference(ret, dn);
+       }
 
-       return py_talloc_import(&PyLdbMessage, ret); 
+       py_ret = (PyLdbMessageObject *)type->tp_alloc(type, 0);
+       if (py_ret == NULL) {
+               PyErr_NoMemory();
+               talloc_free(mem_ctx);
+               return NULL;
+       }
+
+       py_ret->mem_ctx = mem_ctx;
+       py_ret->msg = ret;
+       return (PyObject *)py_ret;
 }
 
 PyObject *PyLdbMessage_FromMessage(struct ldb_message *msg)
 {
-       return py_talloc_import(&PyLdbMessage, msg);
+       PyLdbMessageObject *ret;
+
+       ret = (PyLdbMessageObject *)PyLdbMessage.tp_alloc(&PyLdbMessage, 0);
+       if (ret == NULL) {
+               PyErr_NoMemory();
+               return NULL;
+       }
+       ret->mem_ctx = talloc_new(NULL);
+       ret->msg = talloc_reference(ret->mem_ctx, msg);
+       return (PyObject *)ret;
 }
 
 static PyObject *py_ldb_msg_get_dn(PyLdbMessageObject *self, void *closure)
 {
-       return PyLdbDn_FromDn(PyLdbMessage_AsMessage(self)->dn);
+       struct ldb_message *msg = PyLdbMessage_AsMessage(self);
+       return PyLdbDn_FromDn(msg->dn);
 }
 
 static int py_ldb_msg_set_dn(PyLdbMessageObject *self, PyObject *value, void *closure)
 {
-       PyLdbMessage_AsMessage(self)->dn = PyLdbDn_AsDn(value);
+       struct ldb_message *msg = PyLdbMessage_AsMessage(self);
+       if (!PyLdbDn_Check(value)) {
+               PyErr_SetNone(PyExc_TypeError);
+               return -1;
+       }
+
+       msg->dn = talloc_reference(msg, PyLdbDn_AsDn(value));
        return 0;
 }
 
 static PyGetSetDef py_ldb_msg_getset[] = {
-       { (char *)"dn", (getter)py_ldb_msg_get_dn, (setter)py_ldb_msg_set_dn, NULL },
+       { discard_const_p(char, "dn"), (getter)py_ldb_msg_get_dn, (setter)py_ldb_msg_set_dn, NULL },
        { NULL }
 };
 
@@ -1496,32 +1916,57 @@ static PyObject *py_ldb_msg_repr(PyLdbMessageObject *self)
        return ret;
 }
 
+static void py_ldb_msg_dealloc(PyLdbMessageObject *self)
+{
+       talloc_free(self->mem_ctx);
+       self->ob_type->tp_free(self);
+}
+
 PyTypeObject PyLdbMessage = {
        .tp_name = "Message",
        .tp_methods = py_ldb_msg_methods,
        .tp_getset = py_ldb_msg_getset,
        .tp_as_mapping = &py_ldb_msg_mapping,
        .tp_basicsize = sizeof(PyLdbMessageObject),
-       .tp_dealloc = py_talloc_dealloc,
+       .tp_dealloc = (destructor)py_ldb_msg_dealloc,
        .tp_new = py_ldb_msg_new,
        .tp_repr = (reprfunc)py_ldb_msg_repr,
+       .tp_flags = Py_TPFLAGS_DEFAULT,
+       .tp_iter = (getiterfunc)py_ldb_msg_iter,
 };
 
 PyObject *PyLdbTree_FromTree(struct ldb_parse_tree *tree)
 {
-       return py_talloc_import(&PyLdbTree, 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);
+       self->ob_type->tp_free(self);
 }
 
 PyTypeObject PyLdbTree = {
        .tp_name = "Tree",
        .tp_basicsize = sizeof(PyLdbTreeObject),
-       .tp_dealloc = py_talloc_dealloc,
+       .tp_dealloc = (destructor)py_ldb_tree_dealloc,
+       .tp_flags = Py_TPFLAGS_DEFAULT,
 };
 
 /* Ldb_module */
-int py_module_search(struct ldb_module *mod, struct ldb_request *req)
+static int py_module_search(struct ldb_module *mod, struct ldb_request *req)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result, *py_base, *py_attrs, *py_tree;
 
        py_base = PyLdbDn_FromDn(req->op.search.base);
@@ -1544,19 +1989,21 @@ int py_module_search(struct ldb_module *mod, struct ldb_request *req)
                        PyList_SetItem(py_attrs, i, PyString_FromString(req->op.search.attrs[i]));
        }
 
-       py_result = PyObject_CallMethod(py_ldb, (char *)"search", (char *)"OiOO", py_base, req->op.search.scope, py_tree, py_attrs);
+       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_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        req->op.search.res = PyLdbResult_AsResult(NULL, py_result);
        if (req->op.search.res == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        Py_DECREF(py_result);
@@ -1564,23 +2011,25 @@ int py_module_search(struct ldb_module *mod, struct ldb_request *req)
        return LDB_SUCCESS;
 }
 
-int py_module_add(struct ldb_module *mod, struct ldb_request *req)
+static int py_module_add(struct ldb_module *mod, struct ldb_request *req)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result, *py_msg;
 
-       py_msg = PyLdbMessage_FromMessage((struct ldb_message *)req->op.add.message);
+       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, (char *)"add", (char *)"O", py_msg);
+       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_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        Py_DECREF(py_result);
@@ -1588,23 +2037,25 @@ int py_module_add(struct ldb_module *mod, struct ldb_request *req)
        return LDB_SUCCESS;
 }
 
-int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
+static int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result, *py_msg;
 
-       py_msg = PyLdbMessage_FromMessage((struct ldb_message *)req->op.mod.message);
+       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, (char *)"modify", (char *)"O", py_msg);
+       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_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        Py_DECREF(py_result);
@@ -1612,9 +2063,9 @@ int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
        return LDB_SUCCESS;
 }
 
-int py_module_del(struct ldb_module *mod, struct ldb_request *req)
+static int py_module_del(struct ldb_module *mod, struct ldb_request *req)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result, *py_dn;
 
        py_dn = PyLdbDn_FromDn(req->op.del.dn);
@@ -1622,10 +2073,12 @@ int py_module_del(struct ldb_module *mod, struct ldb_request *req)
        if (py_dn == NULL)
                return LDB_ERR_OPERATIONS_ERROR;
 
-       py_result = PyObject_CallMethod(py_ldb, (char *)"delete", (char *)"O", py_dn);
+       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_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        Py_DECREF(py_result);
@@ -1633,9 +2086,9 @@ int py_module_del(struct ldb_module *mod, struct ldb_request *req)
        return LDB_SUCCESS;
 }
 
-int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
+static int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result, *py_olddn, *py_newdn;
 
        py_olddn = PyLdbDn_FromDn(req->op.rename.olddn);
@@ -1648,13 +2101,15 @@ int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
        if (py_newdn == NULL)
                return LDB_ERR_OPERATIONS_ERROR;
 
-       py_result = PyObject_CallMethod(py_ldb, (char *)"rename", (char *)"OO", py_olddn, py_newdn);
+       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_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        Py_DECREF(py_result);
@@ -1662,35 +2117,38 @@ int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
        return LDB_SUCCESS;
 }
 
-int py_module_request(struct ldb_module *mod, struct ldb_request *req)
+static int py_module_request(struct ldb_module *mod, struct ldb_request *req)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result;
 
-       py_result = PyObject_CallMethod(py_ldb, (char *)"request", (char *)"");
+       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "request"),
+                                       discard_const_p(char, ""));
 
        return LDB_ERR_OPERATIONS_ERROR;
 }
 
-int py_module_extended(struct ldb_module *mod, struct ldb_request *req)
+static int py_module_extended(struct ldb_module *mod, struct ldb_request *req)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result;
 
-       py_result = PyObject_CallMethod(py_ldb, (char *)"extended", (char *)"");
+       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "extended"),
+                                       discard_const_p(char, ""));
 
        return LDB_ERR_OPERATIONS_ERROR;
 }
 
-int py_module_start_transaction(struct ldb_module *mod)
+static int py_module_start_transaction(struct ldb_module *mod)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result;
 
-       py_result = PyObject_CallMethod(py_ldb, (char *)"start_transaction", (char *)"");
+       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "start_transaction"),
+                                       discard_const_p(char, ""));
 
        if (py_result == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        Py_DECREF(py_result);
@@ -1698,15 +2156,16 @@ int py_module_start_transaction(struct ldb_module *mod)
        return LDB_SUCCESS;
 }
 
-int py_module_end_transaction(struct ldb_module *mod)
+static int py_module_end_transaction(struct ldb_module *mod)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result;
 
-       py_result = PyObject_CallMethod(py_ldb, (char *)"end_transaction", (char *)"");
+       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "end_transaction"),
+                                       discard_const_p(char, ""));
 
        if (py_result == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        Py_DECREF(py_result);
@@ -1714,15 +2173,16 @@ int py_module_end_transaction(struct ldb_module *mod)
        return LDB_SUCCESS;
 }
 
-int py_module_del_transaction(struct ldb_module *mod)
+static int py_module_del_transaction(struct ldb_module *mod)
 {
-       PyObject *py_ldb = mod->private_data;
+       PyObject *py_ldb = (PyObject *)mod->private_data;
        PyObject *py_result;
 
-       py_result = PyObject_CallMethod(py_ldb, (char *)"del_transaction", (char *)"");
+       py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "del_transaction"),
+                                       discard_const_p(char, ""));
 
        if (py_result == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        Py_DECREF(py_result);
@@ -1736,9 +2196,9 @@ static int py_module_destructor(struct ldb_module *mod)
        return 0;
 }
 
-int py_module_init (struct ldb_module *mod)
+static int py_module_init(struct ldb_module *mod)
 {
-       PyObject *py_class = mod->ops->private_data;
+       PyObject *py_class = (PyObject *)mod->ops->private_data;
        PyObject *py_result, *py_next, *py_ldb;
 
        py_ldb = PyLdb_FromLdbContext(mod->ldb);
@@ -1751,10 +2211,11 @@ int py_module_init (struct ldb_module *mod)
        if (py_next == NULL)
                return LDB_ERR_OPERATIONS_ERROR;
 
-       py_result = PyObject_CallFunction(py_class, (char *)"OO", py_ldb, py_next);
+       py_result = PyObject_CallFunction(py_class, discard_const_p(char, "OO"),
+                                         py_ldb, py_next);
 
        if (py_result == NULL) {
-               return LDB_ERR_OPERATIONS_ERROR;
+               return LDB_ERR_PYTHON_EXCEPTION;
        }
 
        mod->private_data = py_result;
@@ -1779,7 +2240,7 @@ static PyObject *py_register_module(PyObject *module, PyObject *args)
                return NULL;
        }
 
-       ops->name = talloc_strdup(ops, PyString_AsString(PyObject_GetAttrString(input, (char *)"name")));
+       ops->name = talloc_strdup(ops, PyString_AsString(PyObject_GetAttrString(input, discard_const_p(char, "name"))));
 
        Py_INCREF(input);
        ops->private_data = input;
@@ -1797,9 +2258,9 @@ static PyObject *py_register_module(PyObject *module, PyObject *args)
 
        ret = ldb_register_module(ops);
 
-       PyErr_LDB_ERROR_IS_ERR_RAISE(ret, NULL);
+       PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
 
-       return Py_None;
+       Py_RETURN_NONE;
 }
 
 static PyObject *py_timestring(PyObject *module, PyObject *args)
@@ -1887,6 +2348,10 @@ void initldb(void)
        PyModule_AddObject(m, "CHANGETYPE_DELETE", PyInt_FromLong(LDB_CHANGETYPE_DELETE));
        PyModule_AddObject(m, "CHANGETYPE_MODIFY", PyInt_FromLong(LDB_CHANGETYPE_MODIFY));
 
+       PyModule_AddObject(m, "FLAG_MOD_ADD", PyInt_FromLong(LDB_FLAG_MOD_ADD));
+       PyModule_AddObject(m, "FLAG_MOD_REPLACE", PyInt_FromLong(LDB_FLAG_MOD_REPLACE));
+       PyModule_AddObject(m, "FLAG_MOD_DELETE", PyInt_FromLong(LDB_FLAG_MOD_DELETE));
+
        PyModule_AddObject(m, "SUCCESS", PyInt_FromLong(LDB_SUCCESS));
        PyModule_AddObject(m, "ERR_OPERATIONS_ERROR", PyInt_FromLong(LDB_ERR_OPERATIONS_ERROR));
        PyModule_AddObject(m, "ERR_PROTOCOL_ERROR", PyInt_FromLong(LDB_ERR_PROTOCOL_ERROR));
@@ -1922,15 +2387,20 @@ void initldb(void)
        PyModule_AddObject(m, "ERR_OBJECT_CLASS_VIOLATION", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_VIOLATION));
        PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_NON_LEAF", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_NON_LEAF));
        PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_RDN", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_RDN));
-       PyModule_AddObject(m, "ERR_ENTYR_ALREADY_EXISTS", PyInt_FromLong(LDB_ERR_ENTRY_ALREADY_EXISTS));
+       PyModule_AddObject(m, "ERR_ENTRY_ALREADY_EXISTS", PyInt_FromLong(LDB_ERR_ENTRY_ALREADY_EXISTS));
        PyModule_AddObject(m, "ERR_OBJECT_CLASS_MODS_PROHIBITED", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED));
        PyModule_AddObject(m, "ERR_AFFECTS_MULTIPLE_DSAS", PyInt_FromLong(LDB_ERR_AFFECTS_MULTIPLE_DSAS));
-
        PyModule_AddObject(m, "ERR_OTHER", PyInt_FromLong(LDB_ERR_OTHER));
 
+        PyModule_AddObject(m, "FLG_RDONLY", PyInt_FromLong(LDB_FLG_RDONLY));
+        PyModule_AddObject(m, "FLG_NOSYNC", PyInt_FromLong(LDB_FLG_NOSYNC));
+        PyModule_AddObject(m, "FLG_RECONNECT", PyInt_FromLong(LDB_FLG_RECONNECT));
+        PyModule_AddObject(m, "FLG_NOMMAP", PyInt_FromLong(LDB_FLG_NOMMAP));
+
+
        PyModule_AddObject(m, "__docformat__", PyString_FromString("restructuredText"));
 
-       PyExc_LdbError = PyErr_NewException((char *)"_ldb.LdbError", NULL, NULL);
+       PyExc_LdbError = PyErr_NewException(discard_const_p(char, "_ldb.LdbError"), NULL, NULL);
        PyModule_AddObject(m, "LdbError", PyExc_LdbError);
 
        Py_INCREF(&PyLdb);
@@ -1947,94 +2417,3 @@ void initldb(void)
        PyModule_AddObject(m, "Module", (PyObject *)&PyLdbModule);
        PyModule_AddObject(m, "Tree", (PyObject *)&PyLdbTree);
 }
-
-#if 0
-
-/* ldb_message_element */
-%rename(MessageElement) ldb_message_element;
-%feature("docstring") ldb_message_element "Message element.";
-typedef struct ldb_message_element {
-       %extend {
-                       PyObject *__set__(void)
-               {
-                       return ldb_msg_element_to_set(NULL, $self);
-               }
-
-               ldb_message_element(PyObject *set_obj, int flags=0, const char *name = NULL)
-               {
-                       return PyObject_AsMessageElement(NULL, set_obj, flags, name);
-               }
-
-       }
-       %pythoncode {
-               def __getitem__(self, i):
-                       ret = self.get(i)
-                       if ret is None:
-                               raise KeyError("no such value")
-                       return ret
-
-               def __repr__(self):
-                       return "MessageElement([%s])" % (",".join(repr(x) for x in self.__set__()))
-       }
-} ldb_message_element;
-
-/* ldb_message */
-
-typedef struct ldb_message {
-       ldb_dn *dn;
-
-       %extend {
-               ldb_msg(ldb_dn *dn = NULL) { 
-                       ret->dn = talloc_reference(ret, dn);
-                       return ret;
-               }
-               
-               void __setitem__(const char *attr_name, ldb_message_element *val)
-               {
-                       struct ldb_message_element *el;
-                       
-                       ldb_msg_remove_attr($self, attr_name);
-
-                       el = talloc($self, struct ldb_message_element);
-                       el->name = talloc_strdup(el, attr_name);
-                       el->num_values = val->num_values;
-                       el->values = talloc_reference(el, val->values);
-
-                       ldb_msg_add($self, el, val->flags);
-               }
-
-               void __setitem__(const char *attr_name, PyObject *val)
-               {
-               }
-%pythoncode {
-       def get(self, key, default=None):
-               if key == "dn":
-                       return self.dn
-               return self.find_element(key)
-
-       def iteritems(self):
-               for k in self.keys():
-                       yield k, self[k]
-       
-       def items(self):
-               return list(self.iteritems())
-
-       def __repr__(self):
-               return "Message(%s)" % repr(dict(self.iteritems()))
-}
-       }
-} ldb_msg;
-
-typedef struct ldb_context {
-       %pythoncode {
-               def itermodules(self):
-                       m = self.firstmodule
-                       while m is not None:
-                               yield m
-                               m = m.next
-
-               def modules(self):
-                       return list(self.itermodules())
-       }
-} ldb;
-#endif