pyldb: create LdbResult, return value from ldb.search is now a LdbResult
[metze/samba/wip.git] / source4 / lib / ldb / pyldb.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Python interface to ldb.
5
6    Copyright (C) 2005,2006 Tim Potter <tpot@samba.org>
7    Copyright (C) 2006 Simo Sorce <idra@samba.org>
8    Copyright (C) 2007-2010 Jelmer Vernooij <jelmer@samba.org>
9    Copyright (C) 2009-2010 Matthias Dieter Wallnöfer
10
11     ** NOTE! The following LGPL license applies to the ldb
12     ** library. This does NOT imply that all of Samba is released
13     ** under the LGPL
14
15    This library is free software; you can redistribute it and/or
16    modify it under the terms of the GNU Lesser General Public
17    License as published by the Free Software Foundation; either
18    version 3 of the License, or (at your option) any later version.
19
20    This library is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23    Lesser General Public License for more details.
24
25    You should have received a copy of the GNU Lesser General Public
26    License along with this library; if not, see <http://www.gnu.org/licenses/>.
27 */
28
29 #include <Python.h>
30 #include <pytalloc.h>
31 #include "ldb_private.h"
32 #include "pyldb.h"
33
34 void initldb(void);
35 static PyObject *PyLdbMessage_FromMessage(struct ldb_message *msg);
36 static PyObject *PyExc_LdbError;
37
38 staticforward PyTypeObject PyLdbControl;
39 staticforward PyTypeObject PyLdbResult;
40 staticforward PyTypeObject PyLdbMessage;
41 staticforward PyTypeObject PyLdbModule;
42 staticforward PyTypeObject PyLdbDn;
43 staticforward PyTypeObject PyLdb;
44 staticforward PyTypeObject PyLdbMessageElement;
45 staticforward PyTypeObject PyLdbTree;
46 static PyObject *PyLdb_FromLdbContext(struct ldb_context *ldb_ctx);
47 static PyObject *PyLdbModule_FromModule(struct ldb_module *mod);
48 static struct ldb_message_element *PyObject_AsMessageElement(
49                                                       TALLOC_CTX *mem_ctx,
50                                                       PyObject *set_obj,
51                                                       int flags,
52                                                       const char *attr_name);
53
54 /* There's no Py_ssize_t in 2.4, apparently */
55 #if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 5
56 typedef int Py_ssize_t;
57 typedef inquiry lenfunc;
58 typedef intargfunc ssizeargfunc;
59 #endif
60
61 #ifndef Py_RETURN_NONE
62 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
63 #endif
64
65 #define SIGN(a) (((a) == 0)?0:((a) < 0?-1:1))
66
67
68
69 static PyObject *py_ldb_control_str(PyLdbControlObject *self)
70 {
71         if (self->data != NULL) {
72                 char* control = ldb_control_to_string(self->mem_ctx, self->data);
73                 if (control == NULL) {
74                         PyErr_NoMemory();
75                         return NULL;
76                 }
77                 return PyString_FromString(control);
78         } else {
79                 return PyString_FromFormat("ldb control");
80         }
81 }
82
83 static void py_ldb_control_dealloc(PyLdbControlObject *self)
84 {
85         if (self->mem_ctx != NULL) {
86                 talloc_free(self->mem_ctx);
87         }
88         self->ob_type->tp_free(self);
89 }
90
91 static PyObject *py_ldb_control_get_oid(PyLdbControlObject *self)
92 {
93         return PyString_FromString(self->data->oid);
94 }
95
96 static PyObject *py_ldb_control_get_critical(PyLdbControlObject *self)
97 {
98         return PyBool_FromLong(self->data->critical);
99 }
100
101 static PyObject *py_ldb_control_set_critical(PyLdbControlObject *self, PyObject *value, void *closure)
102 {
103         if (PyObject_IsTrue(value)) {
104                 self->data->critical = true;
105         } else {
106                 self->data->critical = false;
107         }
108         return 0;
109 }
110
111 static PyObject *py_ldb_control_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
112 {
113         char *data = NULL;
114         const char *array[2];
115         const char * const kwnames[] = { "ldb", "data", NULL };
116         struct ldb_control *parsed_controls;
117         PyLdbControlObject *ret;
118         PyObject *py_ldb;
119         TALLOC_CTX *mem_ctx;
120         struct ldb_context *ldb_ctx;
121
122         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Os",
123                                          discard_const_p(char *, kwnames),
124                                          &py_ldb, &data))
125                 return NULL;
126
127         mem_ctx = talloc_new(NULL);
128         if (mem_ctx == NULL) {
129                 PyErr_NoMemory();
130                 return NULL;
131         }
132
133         ldb_ctx = PyLdb_AsLdbContext(py_ldb);
134         parsed_controls = ldb_parse_control_from_string(ldb_ctx, mem_ctx, data);
135
136         if (!parsed_controls) {
137                 talloc_free(mem_ctx);
138                 PyErr_SetString(PyExc_ValueError, "unable to parse control string");
139                 return NULL;
140         }
141
142         ret = PyObject_New(PyLdbControlObject, type);
143         if (ret == NULL) {
144                 PyErr_NoMemory();
145                 talloc_free(mem_ctx);
146                 return NULL;
147         }
148
149         ret->mem_ctx = mem_ctx;
150
151         ret->data = talloc_steal(mem_ctx, parsed_controls);
152         if (ret->data == NULL) {
153                 Py_DECREF(ret);
154                 PyErr_NoMemory();
155                 talloc_free(mem_ctx);
156                 return NULL;
157         }
158
159         return (PyObject *)ret;
160 }
161
162 static PyGetSetDef py_ldb_control_getset[] = {
163         { discard_const_p(char, "oid"), (getter)py_ldb_control_get_oid, NULL, NULL },
164         { discard_const_p(char, "critical"), (getter)py_ldb_control_get_critical, (setter)py_ldb_control_set_critical, NULL },
165         { NULL }
166 };
167
168 static PyTypeObject PyLdbControl = {
169         .tp_name = "ldb.control",
170         .tp_dealloc = (destructor)py_ldb_control_dealloc,
171         .tp_getattro = PyObject_GenericGetAttr,
172         .tp_basicsize = sizeof(PyLdbControlObject),
173         .tp_getset = py_ldb_control_getset,
174         .tp_doc = "LDB control.",
175         .tp_str = (reprfunc)py_ldb_control_str,
176         .tp_new = py_ldb_control_new,
177         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
178 };
179
180 static void PyErr_SetLdbError(PyObject *error, int ret, struct ldb_context *ldb_ctx)
181 {
182         if (ret == LDB_ERR_PYTHON_EXCEPTION)
183                 return; /* Python exception should already be set, just keep that */
184
185         PyErr_SetObject(error, 
186                         Py_BuildValue(discard_const_p(char, "(i,s)"), ret,
187                                       ldb_ctx == NULL?ldb_strerror(ret):ldb_errstring(ldb_ctx)));
188 }
189
190 static PyObject *PyObject_FromLdbValue(struct ldb_val *val)
191 {
192         return PyString_FromStringAndSize((const char *)val->data, val->length);
193 }
194
195 /**
196  * Create a Python object from a ldb_result.
197  *
198  * @param result LDB result to convert
199  * @return Python object with converted result (a list object)
200  */
201 static PyObject *PyLdbControl_FromControl(struct ldb_control *control)
202 {
203         TALLOC_CTX *ctl_ctx = talloc_new(NULL);
204         PyLdbControlObject *ctrl;
205         if (ctl_ctx == NULL) {
206                 PyErr_NoMemory();
207                 return NULL;
208         }
209
210         ctrl = (PyLdbControlObject *)PyLdbControl.tp_alloc(&PyLdbControl, 0);
211         if (ctrl == NULL) {
212                 PyErr_NoMemory();
213                 return NULL;
214         }
215         ctrl->mem_ctx = ctl_ctx;
216         ctrl->data = talloc_steal(ctrl->mem_ctx, control);
217         if (ctrl->data == NULL) {
218                 Py_DECREF(ctrl);
219                 PyErr_NoMemory();
220                 return NULL;
221         }
222         return (PyObject*) ctrl;
223 }
224
225 /**
226  * Create a Python object from a ldb_result.
227  *
228  * @param result LDB result to convert
229  * @return Python object with converted result (a list object)
230  */
231 static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
232 {
233         PyLdbResultObject *ret;
234         PyObject *list, *controls, *referals;
235         Py_ssize_t i;
236
237         if (result == NULL) {
238                 Py_RETURN_NONE;
239         }
240
241         ret = (PyLdbResultObject *)PyLdbResult.tp_alloc(&PyLdbResult, 0);
242         if (ret == NULL) {
243                 PyErr_NoMemory();
244                 return NULL;
245         }
246
247         list = PyList_New(result->count);
248         if (list == NULL) {
249                 PyErr_NoMemory();
250                 Py_DECREF(ret);
251                 return NULL;
252         }
253
254         for (i = 0; i < result->count; i++) {
255                 PyList_SetItem(list, i, PyLdbMessage_FromMessage(result->msgs[i]));
256         }
257
258         ret->mem_ctx = talloc_new(NULL);
259         if (ret->mem_ctx == NULL) {
260                 Py_DECREF(list);
261                 Py_DECREF(ret);
262                 PyErr_NoMemory();
263                 return NULL;
264         }
265
266         ret->msgs = list;
267
268         if (result->controls) {
269                 controls = PyList_New(1);
270                 if (controls == NULL) {
271                         Py_DECREF(ret);
272                         PyErr_NoMemory();
273                         return NULL;
274                 }
275                 for (i=0; result->controls[i]; i++) {
276                         PyObject *ctrl = (PyObject*) PyLdbControl_FromControl(result->controls[i]);
277                         if (ctrl == NULL) {
278                                 Py_DECREF(ret);
279                                 Py_DECREF(controls);
280                                 PyErr_NoMemory();
281                                 return NULL;
282                         }
283                         PyList_SetItem(controls, i, ctrl);
284                 }
285         } else {
286                 /*
287                  * No controls so we keep an empty list
288                  */
289                 controls = PyList_New(0);
290                 if (controls == NULL) {
291                         Py_DECREF(ret);
292                         PyErr_NoMemory();
293                         return NULL;
294                 }
295         }
296
297         ret->controls = controls;
298
299         i = 0;
300
301         while (result->refs && result->refs[i]) {
302                 i++;
303         }
304
305         referals = PyList_New(i);
306         if (referals == NULL) {
307                 Py_DECREF(ret);
308                 PyErr_NoMemory();
309                 return NULL;
310         }
311
312         for (i = 0;result->refs && result->refs[i]; i++) {
313                 PyList_SetItem(referals, i, PyString_FromString(result->refs[i]));
314         }
315         ret->referals = referals;
316         return (PyObject *)ret;
317 }
318
319 /**
320  * Create a LDB Result from a Python object. 
321  * If conversion fails, NULL will be returned and a Python exception set.
322  *
323  * @param mem_ctx Memory context in which to allocate the LDB Result
324  * @param obj Python object to convert
325  * @return a ldb_result, or NULL if the conversion failed
326  */
327 static struct ldb_result *PyLdbResult_AsResult(TALLOC_CTX *mem_ctx, 
328                                                PyObject *obj)
329 {
330         struct ldb_result *res;
331         Py_ssize_t i;
332
333         if (obj == Py_None)
334                 return NULL;
335
336         res = talloc_zero(mem_ctx, struct ldb_result);
337         res->count = PyList_Size(obj);
338         res->msgs = talloc_array(res, struct ldb_message *, res->count);
339         for (i = 0; i < res->count; i++) {
340                 PyObject *item = PyList_GetItem(obj, i);
341                 res->msgs[i] = PyLdbMessage_AsMessage(item);
342         }
343         return res;
344 }
345
346 static PyObject *py_ldb_dn_validate(PyLdbDnObject *self)
347 {
348         return PyBool_FromLong(ldb_dn_validate(self->dn));
349 }
350
351 static PyObject *py_ldb_dn_is_valid(PyLdbDnObject *self)
352 {
353         return PyBool_FromLong(ldb_dn_is_valid(self->dn));
354 }
355
356 static PyObject *py_ldb_dn_is_special(PyLdbDnObject *self)
357 {
358         return PyBool_FromLong(ldb_dn_is_special(self->dn));
359 }
360
361 static PyObject *py_ldb_dn_is_null(PyLdbDnObject *self)
362 {
363         return PyBool_FromLong(ldb_dn_is_null(self->dn));
364 }
365  
366 static PyObject *py_ldb_dn_get_casefold(PyLdbDnObject *self)
367 {
368         return PyString_FromString(ldb_dn_get_casefold(self->dn));
369 }
370
371 static PyObject *py_ldb_dn_get_linearized(PyLdbDnObject *self)
372 {
373         return PyString_FromString(ldb_dn_get_linearized(self->dn));
374 }
375
376 static PyObject *py_ldb_dn_canonical_str(PyLdbDnObject *self)
377 {
378         return PyString_FromString(ldb_dn_canonical_string(self->dn, self->dn));
379 }
380
381 static PyObject *py_ldb_dn_canonical_ex_str(PyLdbDnObject *self)
382 {
383         return PyString_FromString(ldb_dn_canonical_ex_string(self->dn, self->dn));
384 }
385
386 static PyObject *py_ldb_dn_repr(PyLdbDnObject *self)
387 {
388         return PyString_FromFormat("Dn(%s)", PyObject_REPR(PyString_FromString(ldb_dn_get_linearized(self->dn))));
389 }
390
391 static PyObject *py_ldb_dn_check_special(PyLdbDnObject *self, PyObject *args)
392 {
393         char *name;
394
395         if (!PyArg_ParseTuple(args, "s", &name))
396                 return NULL;
397
398         return ldb_dn_check_special(self->dn, name)?Py_True:Py_False;
399 }
400
401 static int py_ldb_dn_compare(PyLdbDnObject *dn1, PyLdbDnObject *dn2)
402 {
403         int ret;
404         ret = ldb_dn_compare(dn1->dn, dn2->dn);
405         if (ret < 0) ret = -1;
406         if (ret > 0) ret = 1;
407         return ret;
408 }
409
410 static PyObject *py_ldb_dn_get_parent(PyLdbDnObject *self)
411 {
412         struct ldb_dn *dn = PyLdbDn_AsDn((PyObject *)self);
413         struct ldb_dn *parent;
414         PyLdbDnObject *py_ret;
415         TALLOC_CTX *mem_ctx = talloc_new(NULL);
416
417         parent = ldb_dn_get_parent(mem_ctx, dn);
418         if (parent == NULL) {
419                 talloc_free(mem_ctx);
420                 Py_RETURN_NONE;
421         }
422
423         py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
424         if (py_ret == NULL) {
425                 PyErr_NoMemory();
426                 talloc_free(mem_ctx);
427                 return NULL;
428         }
429         py_ret->mem_ctx = mem_ctx;
430         py_ret->dn = parent;
431         return (PyObject *)py_ret;
432 }
433
434 #define dn_ldb_ctx(dn) ((struct ldb_context *)dn)
435
436 static PyObject *py_ldb_dn_add_child(PyLdbDnObject *self, PyObject *args)
437 {
438         PyObject *py_other;
439         struct ldb_dn *dn, *other;
440         if (!PyArg_ParseTuple(args, "O", &py_other))
441                 return NULL;
442
443         dn = PyLdbDn_AsDn((PyObject *)self);
444
445         if (!PyObject_AsDn(NULL, py_other, dn_ldb_ctx(dn), &other))
446                 return NULL;
447
448         return ldb_dn_add_child(dn, other)?Py_True:Py_False;
449 }
450
451 static PyObject *py_ldb_dn_add_base(PyLdbDnObject *self, PyObject *args)
452 {
453         PyObject *py_other;
454         struct ldb_dn *other, *dn;
455         if (!PyArg_ParseTuple(args, "O", &py_other))
456                 return NULL;
457
458         dn = PyLdbDn_AsDn((PyObject *)self);
459
460         if (!PyObject_AsDn(NULL, py_other, dn_ldb_ctx(dn), &other))
461                 return NULL;
462
463         return ldb_dn_add_base(dn, other)?Py_True:Py_False;
464 }
465
466 static PyMethodDef py_ldb_dn_methods[] = {
467         { "validate", (PyCFunction)py_ldb_dn_validate, METH_NOARGS, 
468                 "S.validate() -> bool\n"
469                 "Validate DN is correct." },
470         { "is_valid", (PyCFunction)py_ldb_dn_is_valid, METH_NOARGS,
471                 "S.is_valid() -> bool\n" },
472         { "is_special", (PyCFunction)py_ldb_dn_is_special, METH_NOARGS,
473                 "S.is_special() -> bool\n"
474                 "Check whether this is a special LDB DN." },
475         { "is_null", (PyCFunction)py_ldb_dn_is_null, METH_NOARGS,
476                 "Check whether this is a null DN." },
477         { "get_casefold", (PyCFunction)py_ldb_dn_get_casefold, METH_NOARGS,
478                 NULL },
479         { "get_linearized", (PyCFunction)py_ldb_dn_get_linearized, METH_NOARGS,
480                 NULL },
481         { "canonical_str", (PyCFunction)py_ldb_dn_canonical_str, METH_NOARGS,
482                 "S.canonical_str() -> string\n"
483                 "Canonical version of this DN (like a posix path)." },
484         { "canonical_ex_str", (PyCFunction)py_ldb_dn_canonical_ex_str, METH_NOARGS,
485                 "S.canonical_ex_str() -> string\n"
486                 "Canonical version of this DN (like a posix path, with terminating newline)." },
487         { "parent", (PyCFunction)py_ldb_dn_get_parent, METH_NOARGS,
488                 "S.parent() -> dn\n"
489                 "Get the parent for this DN." },
490         { "add_child", (PyCFunction)py_ldb_dn_add_child, METH_VARARGS, 
491                 "S.add_child(dn) -> None\n"
492                 "Add a child DN to this DN." },
493         { "add_base", (PyCFunction)py_ldb_dn_add_base, METH_VARARGS,
494                 "S.add_base(dn) -> None\n"
495                 "Add a base DN to this DN." },
496         { "check_special", (PyCFunction)py_ldb_dn_check_special, METH_VARARGS,
497                 "S.check_special(name) -> bool\n\n"
498                 "Check if name is a special DN name"},
499         { NULL }
500 };
501
502 static Py_ssize_t py_ldb_dn_len(PyLdbDnObject *self)
503 {
504         return ldb_dn_get_comp_num(PyLdbDn_AsDn((PyObject *)self));
505 }
506
507 static PyObject *py_ldb_dn_concat(PyLdbDnObject *self, PyObject *py_other)
508 {
509         struct ldb_dn *dn = PyLdbDn_AsDn((PyObject *)self), 
510                                   *other;
511         PyLdbDnObject *py_ret;
512         
513         if (!PyObject_AsDn(NULL, py_other, NULL, &other))
514                 return NULL;
515
516         py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
517         if (py_ret == NULL) {
518                 PyErr_NoMemory();
519                 return NULL;
520         }
521         py_ret->mem_ctx = talloc_new(NULL);
522         py_ret->dn = ldb_dn_copy(py_ret->mem_ctx, dn);
523         ldb_dn_add_child(py_ret->dn, other);
524         return (PyObject *)py_ret;
525 }
526
527 static PySequenceMethods py_ldb_dn_seq = {
528         .sq_length = (lenfunc)py_ldb_dn_len,
529         .sq_concat = (binaryfunc)py_ldb_dn_concat,
530 };
531
532 static PyObject *py_ldb_dn_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
533 {
534         struct ldb_dn *ret;
535         char *str;
536         PyObject *py_ldb;
537         struct ldb_context *ldb_ctx;
538         TALLOC_CTX *mem_ctx;
539         PyLdbDnObject *py_ret;
540         const char * const kwnames[] = { "ldb", "dn", NULL };
541
542         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Os",
543                                          discard_const_p(char *, kwnames),
544                                          &py_ldb, &str))
545                 return NULL;
546
547         ldb_ctx = PyLdb_AsLdbContext(py_ldb);
548
549         mem_ctx = talloc_new(NULL);
550         if (mem_ctx == NULL) {
551                 PyErr_NoMemory();
552                 return NULL;
553         }
554
555         ret = ldb_dn_new(mem_ctx, ldb_ctx, str);
556
557         if (ret == NULL || !ldb_dn_validate(ret)) {
558                 talloc_free(mem_ctx);
559                 PyErr_SetString(PyExc_ValueError, "unable to parse dn string");
560                 return NULL;
561         }
562
563         py_ret = (PyLdbDnObject *)type->tp_alloc(type, 0);
564         if (ret == NULL) {
565                 talloc_free(mem_ctx);
566                 PyErr_NoMemory();
567                 return NULL;
568         }
569         py_ret->mem_ctx = mem_ctx;
570         py_ret->dn = ret;
571         return (PyObject *)py_ret;
572 }
573
574 static void py_ldb_dn_dealloc(PyLdbDnObject *self)
575 {
576         talloc_free(self->mem_ctx);
577         PyObject_Del(self);
578 }
579
580 static PyTypeObject PyLdbDn = {
581         .tp_name = "ldb.Dn",
582         .tp_methods = py_ldb_dn_methods,
583         .tp_str = (reprfunc)py_ldb_dn_get_linearized,
584         .tp_repr = (reprfunc)py_ldb_dn_repr,
585         .tp_compare = (cmpfunc)py_ldb_dn_compare,
586         .tp_as_sequence = &py_ldb_dn_seq,
587         .tp_doc = "A LDB distinguished name.",
588         .tp_new = py_ldb_dn_new,
589         .tp_dealloc = (destructor)py_ldb_dn_dealloc,
590         .tp_basicsize = sizeof(PyLdbDnObject),
591         .tp_flags = Py_TPFLAGS_DEFAULT,
592 };
593
594 /* Debug */
595 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(3, 0);
596 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap)
597 {
598         PyObject *fn = (PyObject *)context;
599         PyObject_CallFunction(fn, discard_const_p(char, "(i,O)"), level, PyString_FromFormatV(fmt, ap));
600 }
601
602 static PyObject *py_ldb_set_debug(PyLdbObject *self, PyObject *args)
603 {
604         PyObject *cb;
605
606         if (!PyArg_ParseTuple(args, "O", &cb))
607                 return NULL;
608
609         Py_INCREF(cb);
610         /* FIXME: Where do we DECREF cb ? */
611         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_set_debug(self->ldb_ctx, py_ldb_debug, cb), PyLdb_AsLdbContext(self));
612
613         Py_RETURN_NONE;
614 }
615
616 static PyObject *py_ldb_set_create_perms(PyTypeObject *self, PyObject *args)
617 {
618         unsigned int perms;
619         if (!PyArg_ParseTuple(args, "I", &perms))
620                 return NULL;
621
622         ldb_set_create_perms(PyLdb_AsLdbContext(self), perms);
623
624         Py_RETURN_NONE;
625 }
626
627 static PyObject *py_ldb_set_modules_dir(PyTypeObject *self, PyObject *args)
628 {
629         char *modules_dir;
630         if (!PyArg_ParseTuple(args, "s", &modules_dir))
631                 return NULL;
632
633         ldb_set_modules_dir(PyLdb_AsLdbContext(self), modules_dir);
634
635         Py_RETURN_NONE;
636 }
637
638 static PyObject *py_ldb_transaction_start(PyLdbObject *self)
639 {
640         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_start(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
641         Py_RETURN_NONE;
642 }
643
644 static PyObject *py_ldb_transaction_commit(PyLdbObject *self)
645 {
646         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_commit(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
647         Py_RETURN_NONE;
648 }
649
650 static PyObject *py_ldb_transaction_prepare_commit(PyLdbObject *self)
651 {
652         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_prepare_commit(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
653         Py_RETURN_NONE;
654 }
655
656 static PyObject *py_ldb_transaction_cancel(PyLdbObject *self)
657 {
658         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_cancel(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
659         Py_RETURN_NONE;
660 }
661
662 static PyObject *py_ldb_setup_wellknown_attributes(PyLdbObject *self)
663 {
664         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_setup_wellknown_attributes(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
665         Py_RETURN_NONE;
666 }
667
668 static PyObject *py_ldb_repr(PyLdbObject *self)
669 {
670         return PyString_FromFormat("<ldb connection>");
671 }
672
673 static PyObject *py_ldb_get_root_basedn(PyLdbObject *self)
674 {
675         struct ldb_dn *dn = ldb_get_root_basedn(PyLdb_AsLdbContext(self));
676         if (dn == NULL)
677                 Py_RETURN_NONE;
678         return PyLdbDn_FromDn(dn);
679 }
680
681
682 static PyObject *py_ldb_get_schema_basedn(PyLdbObject *self)
683 {
684         struct ldb_dn *dn = ldb_get_schema_basedn(PyLdb_AsLdbContext(self));
685         if (dn == NULL)
686                 Py_RETURN_NONE;
687         return PyLdbDn_FromDn(dn);
688 }
689
690 static PyObject *py_ldb_get_config_basedn(PyLdbObject *self)
691 {
692         struct ldb_dn *dn = ldb_get_config_basedn(PyLdb_AsLdbContext(self));
693         if (dn == NULL)
694                 Py_RETURN_NONE;
695         return PyLdbDn_FromDn(dn);
696 }
697
698 static PyObject *py_ldb_get_default_basedn(PyLdbObject *self)
699 {
700         struct ldb_dn *dn = ldb_get_default_basedn(PyLdb_AsLdbContext(self));
701         if (dn == NULL)
702                 Py_RETURN_NONE;
703         return PyLdbDn_FromDn(dn);
704 }
705
706 static const char **PyList_AsStringList(TALLOC_CTX *mem_ctx, PyObject *list, 
707                                         const char *paramname)
708 {
709         const char **ret;
710         Py_ssize_t i;
711         if (!PyList_Check(list)) {
712                 PyErr_Format(PyExc_TypeError, "%s is not a list", paramname);
713                 return NULL;
714         }
715         ret = talloc_array(NULL, const char *, PyList_Size(list)+1);
716         if (ret == NULL) {
717                 PyErr_NoMemory();
718                 return NULL;
719         }
720
721         for (i = 0; i < PyList_Size(list); i++) {
722                 PyObject *item = PyList_GetItem(list, i);
723                 if (!PyString_Check(item)) {
724                         PyErr_Format(PyExc_TypeError, "%s should be strings", paramname);
725                         return NULL;
726                 }
727                 ret[i] = talloc_strndup(ret, PyString_AsString(item),
728                                         PyString_Size(item));
729         }
730         ret[i] = NULL;
731         return ret;
732 }
733
734 static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
735 {
736         const char * const kwnames[] = { "url", "flags", "options", NULL };
737         char *url = NULL;
738         PyObject *py_options = Py_None;
739         const char **options;
740         int flags = 0;
741         int ret;
742         struct ldb_context *ldb;
743
744         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO:Ldb.__init__",
745                                          discard_const_p(char *, kwnames),
746                                          &url, &flags, &py_options))
747                 return -1;
748
749         ldb = PyLdb_AsLdbContext(self);
750
751         if (py_options == Py_None) {
752                 options = NULL;
753         } else {
754                 options = PyList_AsStringList(ldb, py_options, "options");
755                 if (options == NULL)
756                         return -1;
757         }
758
759         if (url != NULL) {
760                 ret = ldb_connect(ldb, url, flags, options);
761                 if (ret != LDB_SUCCESS) {
762                         PyErr_SetLdbError(PyExc_LdbError, ret, ldb);
763                         return -1;
764                 }
765         }
766
767         talloc_free(options);
768         return 0;
769 }
770
771 static PyObject *py_ldb_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
772 {
773         PyLdbObject *ret;
774         struct ldb_context *ldb;
775         ret = (PyLdbObject *)type->tp_alloc(type, 0);
776         if (ret == NULL) {
777                 PyErr_NoMemory();
778                 return NULL;
779         }
780         ret->mem_ctx = talloc_new(NULL);
781         ldb = ldb_init(ret->mem_ctx, NULL);
782
783         if (ldb == NULL) {
784                 PyErr_NoMemory();
785                 return NULL;
786         }
787
788         ret->ldb_ctx = ldb;
789         return (PyObject *)ret;
790 }
791
792 static PyObject *py_ldb_connect(PyLdbObject *self, PyObject *args, PyObject *kwargs)
793 {
794         char *url;
795         int flags = 0;
796         PyObject *py_options = Py_None;
797         int ret;
798         const char **options;
799         const char * const kwnames[] = { "url", "flags", "options", NULL };
800
801         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO",
802                                          discard_const_p(char *, kwnames),
803                                          &url, &flags, &py_options))
804                 return NULL;
805
806         if (py_options == Py_None) {
807                 options = NULL;
808         } else {
809                 options = PyList_AsStringList(NULL, py_options, "options");
810                 if (options == NULL)
811                         return NULL;
812         }
813
814         ret = ldb_connect(PyLdb_AsLdbContext(self), url, flags, options);
815         talloc_free(options);
816
817         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
818
819         Py_RETURN_NONE;
820 }
821
822 static PyObject *py_ldb_modify(PyLdbObject *self, PyObject *args)
823 {
824         PyObject *py_msg;
825         PyObject *py_controls = Py_None;
826         struct ldb_context *ldb_ctx;
827         struct ldb_request *req;
828         struct ldb_control **parsed_controls;
829         struct ldb_message *msg;
830         int ret;
831         TALLOC_CTX *mem_ctx;
832
833         if (!PyArg_ParseTuple(args, "O|O", &py_msg, &py_controls))
834                 return NULL;
835
836         mem_ctx = talloc_new(NULL);
837         if (mem_ctx == NULL) {
838                 PyErr_NoMemory();
839                 return NULL;
840         }
841         ldb_ctx = PyLdb_AsLdbContext(self);
842
843         if (py_controls == Py_None) {
844                 parsed_controls = NULL;
845         } else {
846                 const char **controls = PyList_AsStringList(mem_ctx, py_controls, "controls");
847                 parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
848                 talloc_free(controls);
849         }
850
851         if (!PyLdbMessage_Check(py_msg)) {
852                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message");
853                 talloc_free(mem_ctx);
854                 return NULL;
855         }
856         msg = PyLdbMessage_AsMessage(py_msg);
857
858         ret = ldb_msg_sanity_check(ldb_ctx, msg);
859         if (ret != LDB_SUCCESS) {
860                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
861                 talloc_free(mem_ctx);
862                 return NULL;
863         }
864
865         ret = ldb_build_mod_req(&req, ldb_ctx, mem_ctx, msg, parsed_controls,
866                                 NULL, ldb_op_default_callback, NULL);
867         if (ret != LDB_SUCCESS) {
868                 PyErr_SetString(PyExc_TypeError, "failed to build request");
869                 talloc_free(mem_ctx);
870                 return NULL;
871         }
872
873         /* do request and autostart a transaction */
874         /* Then let's LDB handle the message error in case of pb as they are meaningful */
875
876         ret = ldb_transaction_start(ldb_ctx);
877         if (ret != LDB_SUCCESS) {
878                 talloc_free(mem_ctx);
879                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
880         }
881
882         ret = ldb_request(ldb_ctx, req);
883         if (ret == LDB_SUCCESS) {
884                         ret = ldb_wait(req->handle, LDB_WAIT_ALL);
885         }
886
887         if (ret == LDB_SUCCESS) {
888                 ret = ldb_transaction_commit(ldb_ctx);
889         } else {
890                 ldb_transaction_cancel(ldb_ctx);
891                 if (ldb_ctx->err_string == NULL) {
892                         /* no error string was setup by the backend */
893                         ldb_asprintf_errstring(ldb_ctx, "%s (%d)", ldb_strerror(ret), ret);
894                 }
895         }
896
897         talloc_free(mem_ctx);
898         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
899
900         Py_RETURN_NONE;
901 }
902
903
904 /**
905  * Obtain a ldb message from a Python Dictionary object.
906  *
907  * @param mem_ctx Memory context
908  * @param py_obj Python Dictionary object
909  * @param ldb_ctx LDB context
910  * @param mod_flags Flags to be set on every message element
911  * @return ldb_message on success or NULL on failure
912  */
913 static struct ldb_message *PyDict_AsMessage(TALLOC_CTX *mem_ctx,
914                                             PyObject *py_obj,
915                                             struct ldb_context *ldb_ctx,
916                                             unsigned int mod_flags)
917 {
918         struct ldb_message *msg;
919         unsigned int msg_pos = 0;
920         Py_ssize_t dict_pos = 0;
921         PyObject *key, *value;
922         struct ldb_message_element *msg_el;
923         PyObject *dn_value = PyDict_GetItemString(py_obj, "dn");
924
925         msg = ldb_msg_new(mem_ctx);
926         msg->elements = talloc_zero_array(msg, struct ldb_message_element, PyDict_Size(py_obj));
927
928         if (dn_value) {
929                 if (!PyObject_AsDn(msg, dn_value, ldb_ctx, &msg->dn)) {
930                         PyErr_SetString(PyExc_TypeError, "unable to import dn object");
931                         return NULL;
932                 }
933                 if (msg->dn == NULL) {
934                         PyErr_SetString(PyExc_TypeError, "dn set but not found");
935                         return NULL;
936                 }
937         } else {
938                 PyErr_SetString(PyExc_TypeError, "no dn set");
939                 return NULL;
940         }
941
942         while (PyDict_Next(py_obj, &dict_pos, &key, &value)) {
943                 char *key_str = PyString_AsString(key);
944                 if (strcmp(key_str, "dn") != 0) {
945                         msg_el = PyObject_AsMessageElement(msg->elements, value,
946                                                            mod_flags, key_str);
947                         if (msg_el == NULL) {
948                                 PyErr_SetString(PyExc_TypeError, "unable to import element");
949                                 return NULL;
950                         }
951                         memcpy(&msg->elements[msg_pos], msg_el, sizeof(*msg_el));
952                         msg_pos++;
953                 }
954         }
955
956         msg->num_elements = msg_pos;
957
958         return msg;
959 }
960
961 static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args)
962 {
963         PyObject *py_obj;
964         int ret;
965         struct ldb_context *ldb_ctx;
966         struct ldb_request *req;
967         struct ldb_message *msg = NULL;
968         PyObject *py_controls = Py_None;
969         TALLOC_CTX *mem_ctx;
970         struct ldb_control **parsed_controls;
971
972         if (!PyArg_ParseTuple(args, "O|O", &py_obj, &py_controls ))
973                 return NULL;
974
975         mem_ctx = talloc_new(NULL);
976         if (mem_ctx == NULL) {
977                 PyErr_NoMemory();
978                 return NULL;
979         }
980         ldb_ctx = PyLdb_AsLdbContext(self);
981
982         if (py_controls == Py_None) {
983                 parsed_controls = NULL;
984         } else {
985                 const char **controls = PyList_AsStringList(mem_ctx, py_controls, "controls");
986                 parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
987                 talloc_free(controls);
988         }
989
990         if (PyLdbMessage_Check(py_obj)) {
991                 msg = PyLdbMessage_AsMessage(py_obj);
992         } else if (PyDict_Check(py_obj)) {
993                 msg = PyDict_AsMessage(mem_ctx, py_obj, ldb_ctx, LDB_FLAG_MOD_ADD);
994         } else {
995                 PyErr_SetString(PyExc_TypeError,
996                                 "Dictionary or LdbMessage object expected!");
997         }
998
999         if (!msg) {
1000                 /* we should have a PyErr already set */
1001                 talloc_free(mem_ctx);
1002                 return NULL;
1003         }
1004
1005         ret = ldb_msg_sanity_check(ldb_ctx, msg);
1006         if (ret != LDB_SUCCESS) {
1007                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1008                 talloc_free(mem_ctx);
1009                 return NULL;
1010         }
1011
1012         ret = ldb_build_add_req(&req, ldb_ctx, mem_ctx, msg, parsed_controls,
1013                                 NULL, ldb_op_default_callback, NULL);
1014         if (ret != LDB_SUCCESS) {
1015                 PyErr_SetString(PyExc_TypeError, "failed to build request");
1016                 talloc_free(mem_ctx);
1017                 return NULL;
1018         }
1019
1020         /* do request and autostart a transaction */
1021         /* Then let's LDB handle the message error in case of pb as they are meaningful */
1022
1023         ret = ldb_transaction_start(ldb_ctx);
1024         if (ret != LDB_SUCCESS) {
1025                 talloc_free(mem_ctx);
1026                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1027         }
1028
1029         ret = ldb_request(ldb_ctx, req);
1030         if (ret == LDB_SUCCESS) {
1031                         ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1032         } 
1033
1034         if (ret == LDB_SUCCESS) {
1035                         ret = ldb_transaction_commit(ldb_ctx);
1036         } else {
1037                 ldb_transaction_cancel(ldb_ctx);
1038                 if (ldb_ctx->err_string == NULL) {
1039                         /* no error string was setup by the backend */
1040                         ldb_asprintf_errstring(ldb_ctx, "%s (%d)", ldb_strerror(ret), ret);
1041                 }
1042         }
1043
1044         talloc_free(mem_ctx);
1045         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1046
1047         Py_RETURN_NONE;
1048 }
1049
1050 static PyObject *py_ldb_delete(PyLdbObject *self, PyObject *args)
1051 {
1052         PyObject *py_dn;
1053         struct ldb_dn *dn;
1054         int ret;
1055         struct ldb_context *ldb_ctx;
1056         struct ldb_request *req;
1057         PyObject *py_controls = Py_None;
1058         TALLOC_CTX *mem_ctx;
1059         struct ldb_control **parsed_controls;
1060
1061         if (!PyArg_ParseTuple(args, "O|O", &py_dn, &py_controls))
1062                 return NULL;
1063
1064         mem_ctx = talloc_new(NULL);
1065         if (mem_ctx == NULL) {
1066                 PyErr_NoMemory();
1067                 return NULL;
1068         }
1069         ldb_ctx = PyLdb_AsLdbContext(self);
1070
1071         if (py_controls == Py_None) {
1072                 parsed_controls = NULL;
1073         } else {
1074                 const char **controls = PyList_AsStringList(mem_ctx, py_controls, "controls");
1075                 parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
1076                 talloc_free(controls);
1077         }
1078
1079         if (!PyObject_AsDn(mem_ctx, py_dn, ldb_ctx, &dn)) {
1080                 talloc_free(mem_ctx);
1081                 return NULL;
1082         }
1083
1084         ret = ldb_build_del_req(&req, ldb_ctx, mem_ctx, dn, parsed_controls,
1085                                 NULL, ldb_op_default_callback, NULL);
1086         if (ret != LDB_SUCCESS) {
1087                 PyErr_SetString(PyExc_TypeError, "failed to build request");
1088                 talloc_free(mem_ctx);
1089                 return NULL;
1090         }
1091
1092         /* do request and autostart a transaction */
1093         /* Then let's LDB handle the message error in case of pb as they are meaningful */
1094
1095         ret = ldb_transaction_start(ldb_ctx);
1096         if (ret != LDB_SUCCESS) {
1097                 talloc_free(mem_ctx);
1098                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1099         }
1100
1101         ret = ldb_request(ldb_ctx, req);
1102         if (ret == LDB_SUCCESS) {
1103                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1104         }
1105
1106         if (ret == LDB_SUCCESS) {
1107                 ret = ldb_transaction_commit(ldb_ctx);
1108         } else {
1109                 ldb_transaction_cancel(ldb_ctx);
1110                 if (ldb_ctx->err_string == NULL) {
1111                         /* no error string was setup by the backend */
1112                         ldb_asprintf_errstring(ldb_ctx, "%s (%d)", ldb_strerror(ret), ret);
1113                 }
1114         }
1115
1116         talloc_free(mem_ctx);
1117         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1118
1119         Py_RETURN_NONE;
1120 }
1121
1122 static PyObject *py_ldb_rename(PyLdbObject *self, PyObject *args)
1123 {
1124         PyObject *py_dn1, *py_dn2;
1125         struct ldb_dn *dn1, *dn2;
1126         int ret;
1127         struct ldb_context *ldb;
1128         TALLOC_CTX *mem_ctx;
1129         PyObject *py_controls = Py_None;
1130         struct ldb_control **parsed_controls;
1131         struct ldb_context *ldb_ctx;
1132         struct ldb_request *req;
1133
1134         ldb_ctx = PyLdb_AsLdbContext(self);
1135
1136         if (!PyArg_ParseTuple(args, "OO|O", &py_dn1, &py_dn2, &py_controls))
1137                 return NULL;
1138
1139
1140         mem_ctx = talloc_new(NULL);
1141         if (mem_ctx == NULL) {
1142                 PyErr_NoMemory();
1143                 return NULL;
1144         }
1145         ldb = PyLdb_AsLdbContext(self);
1146
1147         if (py_controls == Py_None) {
1148                 parsed_controls = NULL;
1149         } else {
1150                 const char **controls = PyList_AsStringList(mem_ctx, py_controls, "controls");
1151                 parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
1152                 talloc_free(controls);
1153         }
1154
1155
1156         if (!PyObject_AsDn(mem_ctx, py_dn1, ldb, &dn1)) {
1157                 talloc_free(mem_ctx);
1158                 return NULL;
1159         }
1160
1161         if (!PyObject_AsDn(mem_ctx, py_dn2, ldb, &dn2)) {
1162                 talloc_free(mem_ctx);
1163                 return NULL;
1164         }
1165
1166         ret = ldb_build_rename_req(&req, ldb_ctx, mem_ctx, dn1, dn2, parsed_controls,
1167                                 NULL, ldb_op_default_callback, NULL);
1168         if (ret != LDB_SUCCESS) {
1169                 PyErr_SetString(PyExc_TypeError, "failed to build request");
1170                 talloc_free(mem_ctx);
1171                 return NULL;
1172         }
1173
1174         /* do request and autostart a transaction */
1175         /* Then let's LDB handle the message error in case of pb as they are meaningful */
1176
1177         ret = ldb_transaction_start(ldb_ctx);
1178         if (ret != LDB_SUCCESS) {
1179                 talloc_free(mem_ctx);
1180                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1181         }
1182
1183         ret = ldb_request(ldb_ctx, req);
1184         if (ret == LDB_SUCCESS) {
1185                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1186         }
1187
1188         if (ret == LDB_SUCCESS) {
1189                 ret = ldb_transaction_commit(ldb_ctx);
1190         } else {
1191                 ldb_transaction_cancel(ldb_ctx);
1192                 if (ldb_ctx->err_string == NULL) {
1193                         /* no error string was setup by the backend */
1194                         ldb_asprintf_errstring(ldb_ctx, "%s (%d)", ldb_strerror(ret), ret);
1195                 }
1196         }
1197
1198         talloc_free(mem_ctx);
1199         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1200
1201         Py_RETURN_NONE;
1202 }
1203
1204 static PyObject *py_ldb_schema_attribute_remove(PyLdbObject *self, PyObject *args)
1205 {
1206         char *name;
1207         if (!PyArg_ParseTuple(args, "s", &name))
1208                 return NULL;
1209
1210         ldb_schema_attribute_remove(PyLdb_AsLdbContext(self), name);
1211
1212         Py_RETURN_NONE;
1213 }
1214
1215 static PyObject *py_ldb_schema_attribute_add(PyLdbObject *self, PyObject *args)
1216 {
1217         char *attribute, *syntax;
1218         unsigned int flags;
1219         int ret;
1220         if (!PyArg_ParseTuple(args, "sIs", &attribute, &flags, &syntax))
1221                 return NULL;
1222
1223         ret = ldb_schema_attribute_add(PyLdb_AsLdbContext(self), attribute, flags, syntax);
1224
1225         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
1226
1227         Py_RETURN_NONE;
1228 }
1229
1230 static PyObject *ldb_ldif_to_pyobject(struct ldb_ldif *ldif)
1231 {
1232         if (ldif == NULL) {
1233                 Py_RETURN_NONE;
1234         } else {
1235         /* We don't want this attached to the 'ldb' any more */
1236                 return Py_BuildValue(discard_const_p(char, "(iO)"),
1237                                      ldif->changetype,
1238                                      PyLdbMessage_FromMessage(ldif->msg));
1239         }
1240 }
1241
1242
1243 static PyObject *py_ldb_write_ldif(PyLdbObject *self, PyObject *args)
1244 {
1245         int changetype;
1246         PyObject *py_msg;
1247         struct ldb_ldif ldif;
1248         PyObject *ret;
1249         char *string;
1250         TALLOC_CTX *mem_ctx;
1251
1252         if (!PyArg_ParseTuple(args, "Oi", &py_msg, &changetype))
1253                 return NULL;
1254
1255         if (!PyLdbMessage_Check(py_msg)) {
1256                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for msg");
1257                 return NULL;
1258         }
1259
1260         ldif.msg = PyLdbMessage_AsMessage(py_msg);
1261         ldif.changetype = changetype;
1262
1263         mem_ctx = talloc_new(NULL);
1264
1265         string = ldb_ldif_write_string(PyLdb_AsLdbContext(self), mem_ctx, &ldif);
1266         if (!string) {
1267                 PyErr_SetString(PyExc_KeyError, "Failed to generate LDIF");
1268                 return NULL;
1269         }
1270
1271         ret = PyString_FromString(string);
1272
1273         talloc_free(mem_ctx);
1274
1275         return ret;
1276 }
1277
1278 static PyObject *py_ldb_parse_ldif(PyLdbObject *self, PyObject *args)
1279 {
1280         PyObject *list;
1281         struct ldb_ldif *ldif;
1282         const char *s;
1283
1284         TALLOC_CTX *mem_ctx;
1285
1286         if (!PyArg_ParseTuple(args, "s", &s))
1287                 return NULL;
1288
1289         mem_ctx = talloc_new(NULL);
1290         if (!mem_ctx) {
1291                 Py_RETURN_NONE;
1292         }
1293
1294         list = PyList_New(0);
1295         while (s && *s != '\0') {
1296                 ldif = ldb_ldif_read_string(self->ldb_ctx, &s);
1297                 talloc_steal(mem_ctx, ldif);
1298                 if (ldif) {
1299                         PyList_Append(list, ldb_ldif_to_pyobject(ldif));
1300                 } else {
1301                         PyErr_SetString(PyExc_ValueError, "unable to parse ldif string");
1302                         talloc_free(mem_ctx);
1303                         return NULL;
1304                 }
1305         }
1306         talloc_free(mem_ctx); /* The pyobject already has a reference to the things it needs */
1307         return PyObject_GetIter(list);
1308 }
1309
1310 static PyObject *py_ldb_msg_diff(PyLdbObject *self, PyObject *args)
1311 {
1312         int ldb_ret;
1313         PyObject *py_msg_old;
1314         PyObject *py_msg_new;
1315         struct ldb_message *diff;
1316         struct ldb_context *ldb;
1317         PyObject *py_ret;
1318
1319         if (!PyArg_ParseTuple(args, "OO", &py_msg_old, &py_msg_new))
1320                 return NULL;
1321
1322         if (!PyLdbMessage_Check(py_msg_old)) {
1323                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for old message");
1324                 return NULL;
1325         }
1326
1327         if (!PyLdbMessage_Check(py_msg_new)) {
1328                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for new message");
1329                 return NULL;
1330         }
1331
1332         ldb = PyLdb_AsLdbContext(self);
1333         ldb_ret = ldb_msg_difference(ldb, ldb,
1334                                      PyLdbMessage_AsMessage(py_msg_old),
1335                                      PyLdbMessage_AsMessage(py_msg_new),
1336                                      &diff);
1337         if (ldb_ret != LDB_SUCCESS) {
1338                 PyErr_SetString(PyExc_RuntimeError, "Failed to generate the Ldb Message diff");
1339                 return NULL;
1340         }
1341
1342         py_ret = PyLdbMessage_FromMessage(diff);
1343
1344         talloc_unlink(ldb, diff);
1345
1346         return py_ret;
1347 }
1348
1349 static PyObject *py_ldb_schema_format_value(PyLdbObject *self, PyObject *args)
1350 {
1351         const struct ldb_schema_attribute *a;
1352         struct ldb_val old_val;
1353         struct ldb_val new_val;
1354         TALLOC_CTX *mem_ctx;
1355         PyObject *ret;
1356         char *element_name;
1357         PyObject *val;
1358
1359         if (!PyArg_ParseTuple(args, "sO", &element_name, &val))
1360                 return NULL;
1361
1362         mem_ctx = talloc_new(NULL);
1363
1364         old_val.data = (uint8_t *)PyString_AsString(val);
1365         old_val.length = PyString_Size(val);
1366
1367         a = ldb_schema_attribute_by_name(PyLdb_AsLdbContext(self), element_name);
1368
1369         if (a == NULL) {
1370                 Py_RETURN_NONE;
1371         }
1372
1373         if (a->syntax->ldif_write_fn(PyLdb_AsLdbContext(self), mem_ctx, &old_val, &new_val) != 0) {
1374                 talloc_free(mem_ctx);
1375                 Py_RETURN_NONE;
1376         }
1377
1378         ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
1379
1380         talloc_free(mem_ctx);
1381
1382         return ret;
1383 }
1384
1385 static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwargs)
1386 {
1387         PyObject *py_base = Py_None;
1388         int scope = LDB_SCOPE_DEFAULT;
1389         char *expr = NULL;
1390         PyObject *py_attrs = Py_None;
1391         PyObject *py_controls = Py_None;
1392         const char * const kwnames[] = { "base", "scope", "expression", "attrs", "controls", NULL };
1393         int ret;
1394         struct ldb_result *res;
1395         struct ldb_request *req;
1396         const char **attrs;
1397         struct ldb_context *ldb_ctx;
1398         struct ldb_control **parsed_controls;
1399         struct ldb_dn *base;
1400         PyObject *py_ret;
1401         TALLOC_CTX *mem_ctx;
1402
1403         /* type "int" rather than "enum" for "scope" is intentional */
1404         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OizOO",
1405                                          discard_const_p(char *, kwnames),
1406                                          &py_base, &scope, &expr, &py_attrs, &py_controls))
1407                 return NULL;
1408
1409
1410         mem_ctx = talloc_new(NULL);
1411         if (mem_ctx == NULL) {
1412                 PyErr_NoMemory();
1413                 return NULL;
1414         }
1415         ldb_ctx = PyLdb_AsLdbContext(self);
1416
1417         if (py_attrs == Py_None) {
1418                 attrs = NULL;
1419         } else {
1420                 attrs = PyList_AsStringList(mem_ctx, py_attrs, "attrs");
1421                 if (attrs == NULL) {
1422                         talloc_free(mem_ctx);
1423                         return NULL;
1424                 }
1425         }
1426
1427         if (py_base == Py_None) {
1428                 base = ldb_get_default_basedn(ldb_ctx);
1429         } else {
1430                 if (!PyObject_AsDn(ldb_ctx, py_base, ldb_ctx, &base)) {
1431                         talloc_free(attrs);
1432                         return NULL;
1433                 }
1434         }
1435
1436         if (py_controls == Py_None) {
1437                 parsed_controls = NULL;
1438         } else {
1439                 const char **controls = PyList_AsStringList(mem_ctx, py_controls, "controls");
1440                 parsed_controls = ldb_parse_control_strings(ldb_ctx, mem_ctx, controls);
1441                 talloc_free(controls);
1442         }
1443
1444         res = talloc_zero(mem_ctx, struct ldb_result);
1445         if (res == NULL) {
1446                 PyErr_NoMemory();
1447                 talloc_free(mem_ctx);
1448                 return NULL;
1449         }
1450
1451         ret = ldb_build_search_req(&req, ldb_ctx, mem_ctx,
1452                                    base,
1453                                    scope,
1454                                    expr,
1455                                    attrs,
1456                                    parsed_controls,
1457                                    res,
1458                                    ldb_search_default_callback,
1459                                    NULL);
1460
1461         if (ret != LDB_SUCCESS) {
1462                 talloc_free(mem_ctx);
1463                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1464                 return NULL;
1465         }
1466
1467         talloc_steal(req, attrs);
1468
1469         ret = ldb_request(ldb_ctx, req);
1470
1471         if (ret == LDB_SUCCESS) {
1472                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1473         }
1474
1475         if (ret != LDB_SUCCESS) {
1476                 talloc_free(mem_ctx);
1477                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1478                 return NULL;
1479         }
1480
1481         py_ret = PyLdbResult_FromResult(res);
1482
1483         talloc_free(mem_ctx);
1484
1485         return py_ret;
1486 }
1487
1488 static PyObject *py_ldb_get_opaque(PyLdbObject *self, PyObject *args)
1489 {
1490         char *name;
1491         void *data;
1492
1493         if (!PyArg_ParseTuple(args, "s", &name))
1494                 return NULL;
1495
1496         data = ldb_get_opaque(PyLdb_AsLdbContext(self), name);
1497
1498         if (data == NULL)
1499                 Py_RETURN_NONE;
1500
1501         /* FIXME: More interpretation */
1502
1503         return Py_True;
1504 }
1505
1506 static PyObject *py_ldb_set_opaque(PyLdbObject *self, PyObject *args)
1507 {
1508         char *name;
1509         PyObject *data;
1510
1511         if (!PyArg_ParseTuple(args, "sO", &name, &data))
1512                 return NULL;
1513
1514         /* FIXME: More interpretation */
1515
1516         ldb_set_opaque(PyLdb_AsLdbContext(self), name, data);
1517
1518         Py_RETURN_NONE;
1519 }
1520
1521 static PyObject *py_ldb_modules(PyLdbObject *self)
1522 {
1523         struct ldb_context *ldb = PyLdb_AsLdbContext(self);
1524         PyObject *ret = PyList_New(0);
1525         struct ldb_module *mod;
1526
1527         for (mod = ldb->modules; mod; mod = mod->next) {
1528                 PyList_Append(ret, PyLdbModule_FromModule(mod));
1529         }
1530
1531         return ret;
1532 }
1533
1534 static PyObject *py_ldb_sequence_number(PyLdbObject *self, PyObject *args)
1535 {
1536         struct ldb_context *ldb = PyLdb_AsLdbContext(self);
1537         int type, ret;
1538         uint64_t value;
1539
1540         if (!PyArg_ParseTuple(args, "i", &type))
1541                 return NULL;
1542
1543         /* FIXME: More interpretation */
1544
1545         ret = ldb_sequence_number(ldb, type, &value);
1546
1547         if (ret != LDB_SUCCESS) {
1548                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
1549                 return NULL;
1550         }
1551         return PyLong_FromLongLong(value);
1552 }
1553 static PyMethodDef py_ldb_methods[] = {
1554         { "set_debug", (PyCFunction)py_ldb_set_debug, METH_VARARGS, 
1555                 "S.set_debug(callback) -> None\n"
1556                 "Set callback for LDB debug messages.\n"
1557                 "The callback should accept a debug level and debug text." },
1558         { "set_create_perms", (PyCFunction)py_ldb_set_create_perms, METH_VARARGS, 
1559                 "S.set_create_perms(mode) -> None\n"
1560                 "Set mode to use when creating new LDB files." },
1561         { "set_modules_dir", (PyCFunction)py_ldb_set_modules_dir, METH_VARARGS,
1562                 "S.set_modules_dir(path) -> None\n"
1563                 "Set path LDB should search for modules" },
1564         { "transaction_start", (PyCFunction)py_ldb_transaction_start, METH_NOARGS, 
1565                 "S.transaction_start() -> None\n"
1566                 "Start a new transaction." },
1567         { "transaction_prepare_commit", (PyCFunction)py_ldb_transaction_prepare_commit, METH_NOARGS,
1568                 "S.transaction_prepare_commit() -> None\n"
1569                 "prepare to commit a new transaction (2-stage commit)." },
1570         { "transaction_commit", (PyCFunction)py_ldb_transaction_commit, METH_NOARGS, 
1571                 "S.transaction_commit() -> None\n"
1572                 "commit a new transaction." },
1573         { "transaction_cancel", (PyCFunction)py_ldb_transaction_cancel, METH_NOARGS, 
1574                 "S.transaction_cancel() -> None\n"
1575                 "cancel a new transaction." },
1576         { "setup_wellknown_attributes", (PyCFunction)py_ldb_setup_wellknown_attributes, METH_NOARGS, 
1577                 NULL },
1578         { "get_root_basedn", (PyCFunction)py_ldb_get_root_basedn, METH_NOARGS,
1579                 NULL },
1580         { "get_schema_basedn", (PyCFunction)py_ldb_get_schema_basedn, METH_NOARGS,
1581                 NULL },
1582         { "get_default_basedn", (PyCFunction)py_ldb_get_default_basedn, METH_NOARGS,
1583                 NULL },
1584         { "get_config_basedn", (PyCFunction)py_ldb_get_config_basedn, METH_NOARGS,
1585                 NULL },
1586         { "connect", (PyCFunction)py_ldb_connect, METH_VARARGS|METH_KEYWORDS, 
1587                 "S.connect(url, flags=0, options=None) -> None\n"
1588                 "Connect to a LDB URL." },
1589         { "modify", (PyCFunction)py_ldb_modify, METH_VARARGS, 
1590                 "S.modify(message) -> None\n"
1591                 "Modify an entry." },
1592         { "add", (PyCFunction)py_ldb_add, METH_VARARGS, 
1593                 "S.add(message) -> None\n"
1594                 "Add an entry." },
1595         { "delete", (PyCFunction)py_ldb_delete, METH_VARARGS,
1596                 "S.delete(dn) -> None\n"
1597                 "Remove an entry." },
1598         { "rename", (PyCFunction)py_ldb_rename, METH_VARARGS,
1599                 "S.rename(old_dn, new_dn) -> None\n"
1600                 "Rename an entry." },
1601         { "search", (PyCFunction)py_ldb_search, METH_VARARGS|METH_KEYWORDS,
1602                 "S.search(base=None, scope=None, expression=None, attrs=None, controls=None) -> msgs\n"
1603                 "Search in a database.\n"
1604                 "\n"
1605                 ":param base: Optional base DN to search\n"
1606                 ":param scope: Search scope (SCOPE_BASE, SCOPE_ONELEVEL or SCOPE_SUBTREE)\n"
1607                 ":param expression: Optional search expression\n"
1608                 ":param attrs: Attributes to return (defaults to all)\n"
1609                 ":param controls: Optional list of controls\n"
1610                 ":return: Iterator over Message objects\n"
1611         },
1612         { "schema_attribute_remove", (PyCFunction)py_ldb_schema_attribute_remove, METH_VARARGS,
1613                 NULL },
1614         { "schema_attribute_add", (PyCFunction)py_ldb_schema_attribute_add, METH_VARARGS,
1615                 NULL },
1616         { "schema_format_value", (PyCFunction)py_ldb_schema_format_value, METH_VARARGS,
1617                 NULL },
1618         { "parse_ldif", (PyCFunction)py_ldb_parse_ldif, METH_VARARGS,
1619                 "S.parse_ldif(ldif) -> iter(messages)\n"
1620                 "Parse a string formatted using LDIF." },
1621         { "write_ldif", (PyCFunction)py_ldb_write_ldif, METH_VARARGS,
1622                 "S.write_ldif(message, changetype) -> ldif\n"
1623                 "Print the message as a string formatted using LDIF." },
1624         { "msg_diff", (PyCFunction)py_ldb_msg_diff, METH_VARARGS,
1625                 "S.msg_diff(Message) -> Message\n"
1626                 "Return an LDB Message of the difference between two Message objects." },
1627         { "get_opaque", (PyCFunction)py_ldb_get_opaque, METH_VARARGS,
1628                 "S.get_opaque(name) -> value\n"
1629                 "Get an opaque value set on this LDB connection. \n"
1630                 ":note: The returned value may not be useful in Python."
1631         },
1632         { "set_opaque", (PyCFunction)py_ldb_set_opaque, METH_VARARGS,
1633                 "S.set_opaque(name, value) -> None\n"
1634                 "Set an opaque value on this LDB connection. \n"
1635                 ":note: Passing incorrect values may cause crashes." },
1636         { "modules", (PyCFunction)py_ldb_modules, METH_NOARGS,
1637                 "S.modules() -> list\n"
1638                 "Return the list of modules on this LDB connection " },
1639         { "sequence_number", (PyCFunction)py_ldb_sequence_number, METH_VARARGS,
1640                 "S.sequence_number(type) -> value\n"
1641                 "Return the value of the sequence according to the requested type" },
1642         { NULL },
1643 };
1644
1645 static PyObject *PyLdbModule_FromModule(struct ldb_module *mod)
1646 {
1647         PyLdbModuleObject *ret;
1648
1649         ret = (PyLdbModuleObject *)PyLdbModule.tp_alloc(&PyLdbModule, 0);
1650         if (ret == NULL) {
1651                 PyErr_NoMemory();
1652                 return NULL;
1653         }
1654         ret->mem_ctx = talloc_new(NULL);
1655         ret->mod = talloc_reference(ret->mem_ctx, mod);
1656         return (PyObject *)ret;
1657 }
1658
1659 static PyObject *py_ldb_get_firstmodule(PyLdbObject *self, void *closure)
1660 {
1661         return PyLdbModule_FromModule(PyLdb_AsLdbContext(self)->modules);
1662 }
1663
1664 static PyGetSetDef py_ldb_getset[] = {
1665         { discard_const_p(char, "firstmodule"), (getter)py_ldb_get_firstmodule, NULL, NULL },
1666         { NULL }
1667 };
1668
1669 static int py_ldb_contains(PyLdbObject *self, PyObject *obj)
1670 {
1671         struct ldb_context *ldb_ctx = PyLdb_AsLdbContext(self);
1672         struct ldb_dn *dn;
1673         struct ldb_result *result;
1674         unsigned int count;
1675         int ret;
1676
1677         if (!PyObject_AsDn(ldb_ctx, obj, ldb_ctx, &dn)) {
1678                 return -1;
1679         }
1680
1681         ret = ldb_search(ldb_ctx, ldb_ctx, &result, dn, LDB_SCOPE_BASE, NULL,
1682                          NULL);
1683         if (ret != LDB_SUCCESS) {
1684                 PyErr_SetLdbError(PyExc_LdbError, ret, ldb_ctx);
1685                 return -1;
1686         }
1687
1688         count = result->count;
1689
1690         talloc_free(result);
1691
1692         if (count > 1) {
1693                 PyErr_Format(PyExc_RuntimeError,
1694                              "Searching for [%s] dn gave %u results!",
1695                              ldb_dn_get_linearized(dn),
1696                              count);
1697                 return -1;
1698         }
1699
1700         return count;
1701 }
1702
1703 static PySequenceMethods py_ldb_seq = {
1704         .sq_contains = (objobjproc)py_ldb_contains,
1705 };
1706
1707 static PyObject *PyLdb_FromLdbContext(struct ldb_context *ldb_ctx)
1708 {
1709         PyLdbObject *ret;
1710
1711         ret = (PyLdbObject *)PyLdb.tp_alloc(&PyLdb, 0);
1712         if (ret == NULL) {
1713                 PyErr_NoMemory();
1714                 return NULL;
1715         }
1716         ret->mem_ctx = talloc_new(NULL);
1717         ret->ldb_ctx = talloc_reference(ret->mem_ctx, ldb_ctx);
1718         return (PyObject *)ret;
1719 }
1720
1721 static void py_ldb_dealloc(PyLdbObject *self)
1722 {
1723         talloc_free(self->mem_ctx);
1724         self->ob_type->tp_free(self);
1725 }
1726
1727 static PyTypeObject PyLdb = {
1728         .tp_name = "ldb.Ldb",
1729         .tp_methods = py_ldb_methods,
1730         .tp_repr = (reprfunc)py_ldb_repr,
1731         .tp_new = py_ldb_new,
1732         .tp_init = (initproc)py_ldb_init,
1733         .tp_dealloc = (destructor)py_ldb_dealloc,
1734         .tp_getset = py_ldb_getset,
1735         .tp_getattro = PyObject_GenericGetAttr,
1736         .tp_basicsize = sizeof(PyLdbObject),
1737         .tp_doc = "Connection to a LDB database.",
1738         .tp_as_sequence = &py_ldb_seq,
1739         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1740 };
1741
1742 static void py_ldb_result_dealloc(PyLdbResultObject *self)
1743 {
1744         talloc_free(self->mem_ctx);
1745         Py_DECREF(self->msgs);
1746         Py_DECREF(self->referals);
1747         Py_DECREF(self->controls);
1748         self->ob_type->tp_free(self);
1749 }
1750
1751 static PyObject *py_ldb_result_get_msgs(PyLdbResultObject *self, void *closure)
1752 {
1753         Py_INCREF(self->msgs);
1754         return self->msgs;
1755 }
1756
1757 static PyObject *py_ldb_result_get_controls(PyLdbResultObject *self, void *closure)
1758 {
1759         Py_INCREF(self->controls);
1760         return self->controls;
1761 }
1762
1763 static PyObject *py_ldb_result_get_referals(PyLdbResultObject *self, void *closure)
1764 {
1765         Py_INCREF(self->referals);
1766         return self->referals;
1767 }
1768
1769 static PyObject *py_ldb_result_get_count(PyLdbResultObject *self, void *closure)
1770 {
1771         Py_ssize_t size;
1772         if (self->msgs == NULL) {
1773                 PyErr_SetString(PyExc_AttributeError, "Count attribute is meaningless in this context");
1774                 return NULL;
1775         }
1776         size = PyList_Size(self->msgs);
1777         return PyInt_FromLong(size);
1778 }
1779
1780 static PyGetSetDef py_ldb_result_getset[] = {
1781         { discard_const_p(char, "controls"), (getter)py_ldb_result_get_controls, NULL, NULL },
1782         { discard_const_p(char, "msgs"), (getter)py_ldb_result_get_msgs, NULL, NULL },
1783         { discard_const_p(char, "referals"), (getter)py_ldb_result_get_referals, NULL, NULL },
1784         { discard_const_p(char, "count"), (getter)py_ldb_result_get_count, NULL, NULL },
1785         { NULL }
1786 };
1787
1788 static PyObject *py_ldb_result_iter(PyLdbResultObject *self)
1789 {
1790         return PyObject_GetIter(self->msgs);
1791 }
1792
1793 static Py_ssize_t py_ldb_result_len(PyLdbResultObject *self)
1794 {
1795         return PySequence_Size(self->msgs);
1796 }
1797
1798 static PyObject *py_ldb_result_find(PyLdbResultObject *self, Py_ssize_t idx)
1799 {
1800         return PySequence_GetItem(self->msgs, idx);
1801 }
1802
1803 static PySequenceMethods py_ldb_result_seq = {
1804         .sq_length = (lenfunc)py_ldb_result_len,
1805         .sq_item = (ssizeargfunc)py_ldb_result_find,
1806 };
1807
1808 static PyObject *py_ldb_result_repr(PyLdbObject *self)
1809 {
1810         return PyString_FromFormat("<ldb result>");
1811 }
1812
1813
1814 static PyTypeObject PyLdbResult = {
1815         .tp_name = "ldb.Result",
1816         .tp_repr = (reprfunc)py_ldb_result_repr,
1817         .tp_dealloc = (destructor)py_ldb_result_dealloc,
1818         .tp_iter = (getiterfunc)py_ldb_result_iter,
1819         .tp_getset = py_ldb_result_getset,
1820         .tp_getattro = PyObject_GenericGetAttr,
1821         .tp_basicsize = sizeof(PyLdbResultObject),
1822         .tp_as_sequence = &py_ldb_result_seq,
1823         .tp_doc = "LDB result.",
1824         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1825 };
1826
1827 static PyObject *py_ldb_module_repr(PyLdbModuleObject *self)
1828 {
1829         return PyString_FromFormat("<ldb module '%s'>", PyLdbModule_AsModule(self)->ops->name);
1830 }
1831
1832 static PyObject *py_ldb_module_str(PyLdbModuleObject *self)
1833 {
1834         return PyString_FromString(PyLdbModule_AsModule(self)->ops->name);
1835 }
1836
1837 static PyObject *py_ldb_module_start_transaction(PyLdbModuleObject *self)
1838 {
1839         PyLdbModule_AsModule(self)->ops->start_transaction(PyLdbModule_AsModule(self));
1840         Py_RETURN_NONE;
1841 }
1842
1843 static PyObject *py_ldb_module_end_transaction(PyLdbModuleObject *self)
1844 {
1845         PyLdbModule_AsModule(self)->ops->end_transaction(PyLdbModule_AsModule(self));
1846         Py_RETURN_NONE;
1847 }
1848
1849 static PyObject *py_ldb_module_del_transaction(PyLdbModuleObject *self)
1850 {
1851         PyLdbModule_AsModule(self)->ops->del_transaction(PyLdbModule_AsModule(self));
1852         Py_RETURN_NONE;
1853 }
1854
1855 static PyObject *py_ldb_module_search(PyLdbModuleObject *self, PyObject *args, PyObject *kwargs)
1856 {
1857         PyObject *py_base, *py_tree, *py_attrs, *py_ret;
1858         int ret, scope;
1859         struct ldb_request *req;
1860         const char * const kwnames[] = { "base", "scope", "tree", "attrs", NULL };
1861         struct ldb_module *mod;
1862         const char * const*attrs;
1863
1864         /* type "int" rather than "enum" for "scope" is intentional */
1865         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OiOO",
1866                                          discard_const_p(char *, kwnames),
1867                                          &py_base, &scope, &py_tree, &py_attrs))
1868                 return NULL;
1869
1870         mod = self->mod;
1871
1872         if (py_attrs == Py_None) {
1873                 attrs = NULL;
1874         } else {
1875                 attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
1876                 if (attrs == NULL)
1877                         return NULL;
1878         }
1879
1880         ret = ldb_build_search_req(&req, mod->ldb, NULL, PyLdbDn_AsDn(py_base), 
1881                              scope, NULL /* expr */, attrs,
1882                              NULL /* controls */, NULL, NULL, NULL);
1883
1884         talloc_steal(req, attrs);
1885
1886         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1887
1888         req->op.search.res = NULL;
1889
1890         ret = mod->ops->search(mod, req);
1891
1892         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1893
1894         py_ret = PyLdbResult_FromResult(req->op.search.res);
1895
1896         talloc_free(req);
1897
1898         return py_ret;  
1899 }
1900
1901
1902 static PyObject *py_ldb_module_add(PyLdbModuleObject *self, PyObject *args)
1903 {
1904         struct ldb_request *req;
1905         PyObject *py_message;
1906         int ret;
1907         struct ldb_module *mod;
1908
1909         if (!PyArg_ParseTuple(args, "O", &py_message))
1910                 return NULL;
1911
1912         req = talloc_zero(NULL, struct ldb_request);
1913         req->operation = LDB_ADD;
1914         req->op.add.message = PyLdbMessage_AsMessage(py_message);
1915
1916         mod = PyLdbModule_AsModule(self);
1917         ret = mod->ops->add(mod, req);
1918
1919         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1920
1921         Py_RETURN_NONE;
1922 }
1923
1924 static PyObject *py_ldb_module_modify(PyLdbModuleObject *self, PyObject *args) 
1925 {
1926         int ret;
1927         struct ldb_request *req;
1928         PyObject *py_message;
1929         struct ldb_module *mod;
1930
1931         if (!PyArg_ParseTuple(args, "O", &py_message))
1932                 return NULL;
1933
1934         req = talloc_zero(NULL, struct ldb_request);
1935         req->operation = LDB_MODIFY;
1936         req->op.mod.message = PyLdbMessage_AsMessage(py_message);
1937
1938         mod = PyLdbModule_AsModule(self);
1939         ret = mod->ops->modify(mod, req);
1940
1941         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1942
1943         Py_RETURN_NONE;
1944 }
1945
1946 static PyObject *py_ldb_module_delete(PyLdbModuleObject *self, PyObject *args) 
1947 {
1948         int ret;
1949         struct ldb_request *req;
1950         PyObject *py_dn;
1951
1952         if (!PyArg_ParseTuple(args, "O", &py_dn))
1953                 return NULL;
1954
1955         req = talloc_zero(NULL, struct ldb_request);
1956         req->operation = LDB_DELETE;
1957         req->op.del.dn = PyLdbDn_AsDn(py_dn);
1958
1959         ret = PyLdbModule_AsModule(self)->ops->del(PyLdbModule_AsModule(self), req);
1960
1961         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
1962
1963         Py_RETURN_NONE;
1964 }
1965
1966 static PyObject *py_ldb_module_rename(PyLdbModuleObject *self, PyObject *args)
1967 {
1968         int ret;
1969         struct ldb_request *req;
1970         PyObject *py_dn1, *py_dn2;
1971
1972         if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
1973                 return NULL;
1974
1975         req = talloc_zero(NULL, struct ldb_request);
1976
1977         req->operation = LDB_RENAME;
1978         req->op.rename.olddn = PyLdbDn_AsDn(py_dn1);
1979         req->op.rename.newdn = PyLdbDn_AsDn(py_dn2);
1980
1981         ret = PyLdbModule_AsModule(self)->ops->rename(PyLdbModule_AsModule(self), req);
1982
1983         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
1984
1985         Py_RETURN_NONE;
1986 }
1987
1988 static PyMethodDef py_ldb_module_methods[] = {
1989         { "search", (PyCFunction)py_ldb_module_search, METH_VARARGS|METH_KEYWORDS, NULL },
1990         { "add", (PyCFunction)py_ldb_module_add, METH_VARARGS, NULL },
1991         { "modify", (PyCFunction)py_ldb_module_modify, METH_VARARGS, NULL },
1992         { "rename", (PyCFunction)py_ldb_module_rename, METH_VARARGS, NULL },
1993         { "delete", (PyCFunction)py_ldb_module_delete, METH_VARARGS, NULL },
1994         { "start_transaction", (PyCFunction)py_ldb_module_start_transaction, METH_NOARGS, NULL },
1995         { "end_transaction", (PyCFunction)py_ldb_module_end_transaction, METH_NOARGS, NULL },
1996         { "del_transaction", (PyCFunction)py_ldb_module_del_transaction, METH_NOARGS, NULL },
1997         { NULL },
1998 };
1999
2000 static void py_ldb_module_dealloc(PyLdbModuleObject *self)
2001 {
2002         talloc_free(self->mem_ctx);
2003         PyObject_Del(self);
2004 }
2005
2006 static PyTypeObject PyLdbModule = {
2007         .tp_name = "ldb.LdbModule",
2008         .tp_methods = py_ldb_module_methods,
2009         .tp_repr = (reprfunc)py_ldb_module_repr,
2010         .tp_str = (reprfunc)py_ldb_module_str,
2011         .tp_basicsize = sizeof(PyLdbModuleObject),
2012         .tp_dealloc = (destructor)py_ldb_module_dealloc,
2013         .tp_flags = Py_TPFLAGS_DEFAULT,
2014 };
2015
2016
2017 /**
2018  * Create a ldb_message_element from a Python object.
2019  *
2020  * This will accept any sequence objects that contains strings, or 
2021  * a string object.
2022  *
2023  * A reference to set_obj will be borrowed. 
2024  *
2025  * @param mem_ctx Memory context
2026  * @param set_obj Python object to convert
2027  * @param flags ldb_message_element flags to set
2028  * @param attr_name Name of the attribute
2029  * @return New ldb_message_element, allocated as child of mem_ctx
2030  */
2031 static struct ldb_message_element *PyObject_AsMessageElement(
2032                                                       TALLOC_CTX *mem_ctx,
2033                                                       PyObject *set_obj,
2034                                                       int flags,
2035                                                       const char *attr_name)
2036 {
2037         struct ldb_message_element *me;
2038
2039         if (PyLdbMessageElement_Check(set_obj)) {
2040                 PyLdbMessageElementObject *set_obj_as_me = (PyLdbMessageElementObject *)set_obj;
2041                 /* We have to talloc_reference() the memory context, not the pointer
2042                  * which may not actually be it's own context */
2043                 if (talloc_reference(mem_ctx, set_obj_as_me->mem_ctx)) {
2044                         return PyLdbMessageElement_AsMessageElement(set_obj);
2045                 }
2046                 return NULL;
2047         }
2048
2049         me = talloc(mem_ctx, struct ldb_message_element);
2050         if (me == NULL) {
2051                 PyErr_NoMemory();
2052                 return NULL;
2053         }
2054
2055         me->name = talloc_strdup(me, attr_name);
2056         me->flags = flags;
2057         if (PyString_Check(set_obj)) {
2058                 me->num_values = 1;
2059                 me->values = talloc_array(me, struct ldb_val, me->num_values);
2060                 me->values[0].length = PyString_Size(set_obj);
2061                 me->values[0].data = talloc_memdup(me, 
2062                         (uint8_t *)PyString_AsString(set_obj), me->values[0].length+1);
2063         } else if (PySequence_Check(set_obj)) {
2064                 Py_ssize_t i;
2065                 me->num_values = PySequence_Size(set_obj);
2066                 me->values = talloc_array(me, struct ldb_val, me->num_values);
2067                 for (i = 0; i < me->num_values; i++) {
2068                         PyObject *obj = PySequence_GetItem(set_obj, i);
2069                         if (!PyString_Check(obj)) {
2070                                 PyErr_Format(PyExc_TypeError,
2071                                              "Expected string as element %zd in list", i);
2072                                 talloc_free(me);
2073                                 return NULL;
2074                         }
2075
2076                         me->values[i].length = PyString_Size(obj);
2077                         me->values[i].data = talloc_memdup(me, 
2078                                 (uint8_t *)PyString_AsString(obj), me->values[i].length+1);
2079                 }
2080         } else {
2081                 talloc_free(me);
2082                 me = NULL;
2083         }
2084
2085         return me;
2086 }
2087
2088
2089 static PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx,
2090                                         struct ldb_message_element *me)
2091 {
2092         Py_ssize_t i;
2093         PyObject *result;
2094
2095         /* Python << 2.5 doesn't have PySet_New and PySet_Add. */
2096         result = PyList_New(me->num_values);
2097
2098         for (i = 0; i < me->num_values; i++) {
2099                 PyList_SetItem(result, i,
2100                         PyObject_FromLdbValue(&me->values[i]));
2101         }
2102
2103         return result;
2104 }
2105
2106 static PyObject *py_ldb_msg_element_get(PyLdbMessageElementObject *self, PyObject *args)
2107 {
2108         unsigned int i;
2109         if (!PyArg_ParseTuple(args, "I", &i))
2110                 return NULL;
2111         if (i >= PyLdbMessageElement_AsMessageElement(self)->num_values)
2112                 Py_RETURN_NONE;
2113
2114         return PyObject_FromLdbValue(&(PyLdbMessageElement_AsMessageElement(self)->values[i]));
2115 }
2116
2117 static PyObject *py_ldb_msg_element_flags(PyLdbMessageElementObject *self, PyObject *args)
2118 {
2119         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
2120         return PyInt_FromLong(el->flags);
2121 }
2122
2123 static PyObject *py_ldb_msg_element_set_flags(PyLdbMessageElementObject *self, PyObject *args)
2124 {
2125         int flags;
2126         struct ldb_message_element *el;
2127         if (!PyArg_ParseTuple(args, "i", &flags))
2128                 return NULL;
2129
2130         el = PyLdbMessageElement_AsMessageElement(self);
2131         el->flags = flags;
2132         Py_RETURN_NONE;
2133 }
2134
2135 static PyMethodDef py_ldb_msg_element_methods[] = {
2136         { "get", (PyCFunction)py_ldb_msg_element_get, METH_VARARGS, NULL },
2137         { "set_flags", (PyCFunction)py_ldb_msg_element_set_flags, METH_VARARGS, NULL },
2138         { "flags", (PyCFunction)py_ldb_msg_element_flags, METH_NOARGS, NULL },
2139         { NULL },
2140 };
2141
2142 static Py_ssize_t py_ldb_msg_element_len(PyLdbMessageElementObject *self)
2143 {
2144         return PyLdbMessageElement_AsMessageElement(self)->num_values;
2145 }
2146
2147 static PyObject *py_ldb_msg_element_find(PyLdbMessageElementObject *self, Py_ssize_t idx)
2148 {
2149         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
2150         if (idx < 0 || idx >= el->num_values) {
2151                 PyErr_SetString(PyExc_IndexError, "Out of range");
2152                 return NULL;
2153         }
2154         return PyString_FromStringAndSize((char *)el->values[idx].data, el->values[idx].length);
2155 }
2156
2157 static PySequenceMethods py_ldb_msg_element_seq = {
2158         .sq_length = (lenfunc)py_ldb_msg_element_len,
2159         .sq_item = (ssizeargfunc)py_ldb_msg_element_find,
2160 };
2161
2162 static int py_ldb_msg_element_cmp(PyLdbMessageElementObject *self, PyLdbMessageElementObject *other)
2163 {
2164         int ret = ldb_msg_element_compare(PyLdbMessageElement_AsMessageElement(self),
2165                                                                           PyLdbMessageElement_AsMessageElement(other));
2166         return SIGN(ret);
2167 }
2168
2169 static PyObject *py_ldb_msg_element_iter(PyLdbMessageElementObject *self)
2170 {
2171         return PyObject_GetIter(ldb_msg_element_to_set(NULL, PyLdbMessageElement_AsMessageElement(self)));
2172 }
2173
2174 static PyObject *PyLdbMessageElement_FromMessageElement(struct ldb_message_element *el, TALLOC_CTX *mem_ctx)
2175 {
2176         PyLdbMessageElementObject *ret;
2177         ret = PyObject_New(PyLdbMessageElementObject, &PyLdbMessageElement);
2178         if (ret == NULL) {
2179                 PyErr_NoMemory();
2180                 return NULL;
2181         }
2182         ret->mem_ctx = talloc_new(NULL);
2183         if (talloc_reference(ret->mem_ctx, mem_ctx) == NULL) {
2184                 PyErr_NoMemory();
2185                 return NULL;
2186         }
2187         ret->el = el;
2188         return (PyObject *)ret;
2189 }
2190
2191 static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
2192 {
2193         PyObject *py_elements = NULL;
2194         struct ldb_message_element *el;
2195         int flags = 0;
2196         char *name = NULL;
2197         const char * const kwnames[] = { "elements", "flags", "name", NULL };
2198         PyLdbMessageElementObject *ret;
2199         TALLOC_CTX *mem_ctx;
2200
2201         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Ois",
2202                                          discard_const_p(char *, kwnames),
2203                                          &py_elements, &flags, &name))
2204                 return NULL;
2205
2206         mem_ctx = talloc_new(NULL);
2207         if (mem_ctx == NULL) {
2208                 PyErr_NoMemory();
2209                 return NULL;
2210         }
2211
2212         el = talloc_zero(mem_ctx, struct ldb_message_element);
2213         if (el == NULL) {
2214                 PyErr_NoMemory();
2215                 talloc_free(mem_ctx);
2216                 return NULL;
2217         }
2218
2219         if (py_elements != NULL) {
2220                 Py_ssize_t i;
2221                 if (PyString_Check(py_elements)) {
2222                         el->num_values = 1;
2223                         el->values = talloc_array(el, struct ldb_val, 1);
2224                         if (el->values == NULL) {
2225                                 talloc_free(mem_ctx);
2226                                 PyErr_NoMemory();
2227                                 return NULL;
2228                         }
2229                         el->values[0].length = PyString_Size(py_elements);
2230                         el->values[0].data = talloc_memdup(el->values, 
2231                                 (uint8_t *)PyString_AsString(py_elements), el->values[0].length+1);
2232                 } else if (PySequence_Check(py_elements)) {
2233                         el->num_values = PySequence_Size(py_elements);
2234                         el->values = talloc_array(el, struct ldb_val, el->num_values);
2235                         if (el->values == NULL) {
2236                                 talloc_free(mem_ctx);
2237                                 PyErr_NoMemory();
2238                                 return NULL;
2239                         }
2240                         for (i = 0; i < el->num_values; i++) {
2241                                 PyObject *item = PySequence_GetItem(py_elements, i);
2242                                 if (item == NULL) {
2243                                         talloc_free(mem_ctx);
2244                                         return NULL;
2245                                 }
2246                                 if (!PyString_Check(item)) {
2247                                         PyErr_Format(PyExc_TypeError, 
2248                                                      "Expected string as element %zd in list", i);
2249                                         talloc_free(mem_ctx);
2250                                         return NULL;
2251                                 }
2252                                 el->values[i].length = PyString_Size(item);
2253                                 el->values[i].data = talloc_memdup(el,
2254                                         (uint8_t *)PyString_AsString(item), el->values[i].length+1);
2255                         }
2256                 } else {
2257                         PyErr_SetString(PyExc_TypeError, 
2258                                         "Expected string or list");
2259                         talloc_free(mem_ctx);
2260                         return NULL;
2261                 }
2262         }
2263
2264         el->flags = flags;
2265         el->name = talloc_strdup(el, name);
2266
2267         ret = PyObject_New(PyLdbMessageElementObject, type);
2268         if (ret == NULL) {
2269                 talloc_free(mem_ctx);
2270                 return NULL;
2271         }
2272
2273         ret->mem_ctx = mem_ctx;
2274         ret->el = el;
2275         return (PyObject *)ret;
2276 }
2277
2278 static PyObject *py_ldb_msg_element_repr(PyLdbMessageElementObject *self)
2279 {
2280         char *element_str = NULL;
2281         Py_ssize_t i;
2282         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
2283         PyObject *ret;
2284
2285         for (i = 0; i < el->num_values; i++) {
2286                 PyObject *o = py_ldb_msg_element_find(self, i);
2287                 if (element_str == NULL)
2288                         element_str = talloc_strdup(NULL, PyObject_REPR(o));
2289                 else
2290                         element_str = talloc_asprintf_append(element_str, ",%s", PyObject_REPR(o));
2291         }
2292
2293         if (element_str != NULL) {
2294                 ret = PyString_FromFormat("MessageElement([%s])", element_str);
2295                 talloc_free(element_str);
2296         } else {
2297                 ret = PyString_FromString("MessageElement([])");
2298         }
2299
2300         return ret;
2301 }
2302
2303 static PyObject *py_ldb_msg_element_str(PyLdbMessageElementObject *self)
2304 {
2305         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
2306
2307         if (el->num_values == 1)
2308                 return PyString_FromStringAndSize((char *)el->values[0].data, el->values[0].length);
2309         else
2310                 Py_RETURN_NONE;
2311 }
2312
2313 static void py_ldb_msg_element_dealloc(PyLdbMessageElementObject *self)
2314 {
2315         talloc_free(self->mem_ctx);
2316         PyObject_Del(self);
2317 }
2318
2319 static PyTypeObject PyLdbMessageElement = {
2320         .tp_name = "ldb.MessageElement",
2321         .tp_basicsize = sizeof(PyLdbMessageElementObject),
2322         .tp_dealloc = (destructor)py_ldb_msg_element_dealloc,
2323         .tp_repr = (reprfunc)py_ldb_msg_element_repr,
2324         .tp_str = (reprfunc)py_ldb_msg_element_str,
2325         .tp_methods = py_ldb_msg_element_methods,
2326         .tp_compare = (cmpfunc)py_ldb_msg_element_cmp,
2327         .tp_iter = (getiterfunc)py_ldb_msg_element_iter,
2328         .tp_as_sequence = &py_ldb_msg_element_seq,
2329         .tp_new = py_ldb_msg_element_new,
2330         .tp_flags = Py_TPFLAGS_DEFAULT,
2331 };
2332
2333
2334 static PyObject *py_ldb_msg_from_dict(PyTypeObject *type, PyObject *args)
2335 {
2336         PyObject *py_ldb;
2337         PyObject *py_dict;
2338         PyObject *py_ret;
2339         struct ldb_message *msg;
2340         struct ldb_context *ldb_ctx;
2341         unsigned int mod_flags = LDB_FLAG_MOD_REPLACE;
2342
2343         if (!PyArg_ParseTuple(args, "O!O!|I",
2344                               &PyLdb, &py_ldb, &PyDict_Type, &py_dict,
2345                               &mod_flags)) {
2346                 return NULL;
2347         }
2348
2349         /* mask only flags we are going to use */
2350         mod_flags = LDB_FLAG_MOD_TYPE(mod_flags);
2351         if (!mod_flags) {
2352                 PyErr_SetString(PyExc_ValueError,
2353                                 "FLAG_MOD_ADD, FLAG_MOD_REPLACE or FLAG_MOD_DELETE"
2354                                 " expected as mod_flag value");
2355                 return NULL;
2356         }
2357
2358         ldb_ctx = PyLdb_AsLdbContext(py_ldb);
2359
2360         msg = PyDict_AsMessage(ldb_ctx, py_dict, ldb_ctx, mod_flags);
2361         if (!msg) {
2362                 return NULL;
2363         }
2364
2365         py_ret = PyLdbMessage_FromMessage(msg);
2366
2367         talloc_unlink(ldb_ctx, msg);
2368
2369         return py_ret;
2370 }
2371
2372 static PyObject *py_ldb_msg_remove_attr(PyLdbMessageObject *self, PyObject *args)
2373 {
2374         char *name;
2375         if (!PyArg_ParseTuple(args, "s", &name))
2376                 return NULL;
2377
2378         ldb_msg_remove_attr(self->msg, name);
2379
2380         Py_RETURN_NONE;
2381 }
2382
2383 static PyObject *py_ldb_msg_keys(PyLdbMessageObject *self)
2384 {
2385         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2386         Py_ssize_t i, j = 0;
2387         PyObject *obj = PyList_New(msg->num_elements+(msg->dn != NULL?1:0));
2388         if (msg->dn != NULL) {
2389                 PyList_SetItem(obj, j, PyString_FromString("dn"));
2390                 j++;
2391         }
2392         for (i = 0; i < msg->num_elements; i++) {
2393                 PyList_SetItem(obj, j, PyString_FromString(msg->elements[i].name));
2394                 j++;
2395         }
2396         return obj;
2397 }
2398
2399 static PyObject *py_ldb_msg_getitem_helper(PyLdbMessageObject *self, PyObject *py_name)
2400 {
2401         struct ldb_message_element *el;
2402         char *name;
2403         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2404         if (!PyString_Check(py_name)) {
2405                 PyErr_SetNone(PyExc_TypeError);
2406                 return NULL;
2407         }
2408         name = PyString_AsString(py_name);
2409         if (!strcmp(name, "dn"))
2410                 return PyLdbDn_FromDn(msg->dn);
2411         el = ldb_msg_find_element(msg, name);
2412         if (el == NULL) {
2413                 return NULL;
2414         }
2415         return (PyObject *)PyLdbMessageElement_FromMessageElement(el, msg->elements);
2416 }
2417
2418 static PyObject *py_ldb_msg_getitem(PyLdbMessageObject *self, PyObject *py_name)
2419 {
2420         PyObject *ret = py_ldb_msg_getitem_helper(self, py_name);
2421         if (ret == NULL) {
2422                 PyErr_SetString(PyExc_KeyError, "No such element");
2423                 return NULL;
2424         }
2425         return ret;
2426 }
2427
2428 static PyObject *py_ldb_msg_get(PyLdbMessageObject *self, PyObject *args)
2429 {
2430         PyObject *name, *ret;
2431         if (!PyArg_ParseTuple(args, "O", &name))
2432                 return NULL;
2433
2434         ret = py_ldb_msg_getitem_helper(self, name);
2435         if (ret == NULL) {
2436                 if (PyErr_Occurred())
2437                         return NULL;
2438                 Py_RETURN_NONE;
2439         }
2440         return ret;
2441 }
2442
2443 static PyObject *py_ldb_msg_items(PyLdbMessageObject *self)
2444 {
2445         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2446         Py_ssize_t i, j = 0;
2447         PyObject *l = PyList_New(msg->num_elements + (msg->dn == NULL?0:1));
2448         if (msg->dn != NULL) {
2449                 PyList_SetItem(l, 0, Py_BuildValue("(sO)", "dn", PyLdbDn_FromDn(msg->dn)));
2450                 j++;
2451         }
2452         for (i = 0; i < msg->num_elements; i++, j++) {
2453                 PyObject *py_el = PyLdbMessageElement_FromMessageElement(&msg->elements[i], msg->elements);
2454                 PyObject *value = Py_BuildValue("(sO)", msg->elements[i].name, py_el);
2455                 PyList_SetItem(l, j, value);
2456         }
2457         return l;
2458 }
2459
2460 static PyObject *py_ldb_msg_elements(PyLdbMessageObject *self)
2461 {
2462         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2463         Py_ssize_t i = 0;
2464         PyObject *l = PyList_New(msg->num_elements);
2465         for (i = 0; i < msg->num_elements; i++) {
2466                 PyList_SetItem(l, i, PyLdbMessageElement_FromMessageElement(&msg->elements[i], msg->elements));
2467         }
2468         return l;
2469 }
2470
2471 static PyObject *py_ldb_msg_add(PyLdbMessageObject *self, PyObject *args)
2472 {
2473         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2474         PyLdbMessageElementObject *py_element;
2475         int ret;
2476         struct ldb_message_element *el;
2477
2478         if (!PyArg_ParseTuple(args, "O!", &PyLdbMessageElement, &py_element))
2479                 return NULL;
2480
2481         el = talloc_reference(msg, py_element->el);
2482         if (el == NULL) {
2483                 PyErr_NoMemory();
2484                 return NULL;
2485         }
2486
2487         ret = ldb_msg_add(msg, el, el->flags);
2488         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
2489
2490         Py_RETURN_NONE;
2491 }
2492
2493 static PyMethodDef py_ldb_msg_methods[] = {
2494         { "from_dict", (PyCFunction)py_ldb_msg_from_dict, METH_CLASS | METH_VARARGS,
2495                 "Message.from_dict(ldb, dict, mod_flag=FLAG_MOD_REPLACE) -> ldb.Message\n"
2496                 "Class method to create ldb.Message object from Dictionary.\n"
2497                 "mod_flag is one of FLAG_MOD_ADD, FLAG_MOD_REPLACE or FLAG_MOD_DELETE."},
2498         { "keys", (PyCFunction)py_ldb_msg_keys, METH_NOARGS, 
2499                 "S.keys() -> list\n\n"
2500                 "Return sequence of all attribute names." },
2501         { "remove", (PyCFunction)py_ldb_msg_remove_attr, METH_VARARGS, 
2502                 "S.remove(name)\n\n"
2503                 "Remove all entries for attributes with the specified name."},
2504         { "get", (PyCFunction)py_ldb_msg_get, METH_VARARGS, NULL },
2505         { "items", (PyCFunction)py_ldb_msg_items, METH_NOARGS, NULL },
2506         { "elements", (PyCFunction)py_ldb_msg_elements, METH_NOARGS, NULL },
2507         { "add", (PyCFunction)py_ldb_msg_add, METH_VARARGS,
2508                 "S.append(element)\n\n"
2509                 "Add an element to this message." },
2510         { NULL },
2511 };
2512
2513 static PyObject *py_ldb_msg_iter(PyLdbMessageObject *self)
2514 {
2515         PyObject *list, *iter;
2516
2517         list = py_ldb_msg_keys(self);
2518         iter = PyObject_GetIter(list);
2519         Py_DECREF(list);
2520         return iter;
2521 }
2522
2523 static int py_ldb_msg_setitem(PyLdbMessageObject *self, PyObject *name, PyObject *value)
2524 {
2525         char *attr_name;
2526
2527         if (!PyString_Check(name)) {
2528                 PyErr_SetNone(PyExc_TypeError);
2529                 return -1;
2530         }
2531
2532         attr_name = PyString_AsString(name);
2533         if (value == NULL) {
2534                 /* delitem */
2535                 ldb_msg_remove_attr(self->msg, attr_name);
2536         } else {
2537                 struct ldb_message_element *el = PyObject_AsMessageElement(self->msg,
2538                                                                            value, 0, attr_name);
2539                 if (el == NULL)
2540                         return -1;
2541                 ldb_msg_remove_attr(PyLdbMessage_AsMessage(self), attr_name);
2542                 ldb_msg_add(PyLdbMessage_AsMessage(self), el, el->flags);
2543         }
2544         return 0;
2545 }
2546
2547 static Py_ssize_t py_ldb_msg_length(PyLdbMessageObject *self)
2548 {
2549         return PyLdbMessage_AsMessage(self)->num_elements;
2550 }
2551
2552 static PyMappingMethods py_ldb_msg_mapping = {
2553         .mp_length = (lenfunc)py_ldb_msg_length,
2554         .mp_subscript = (binaryfunc)py_ldb_msg_getitem,
2555         .mp_ass_subscript = (objobjargproc)py_ldb_msg_setitem,
2556 };
2557
2558 static PyObject *py_ldb_msg_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
2559 {
2560         const char * const kwnames[] = { "dn", NULL };
2561         struct ldb_message *ret;
2562         TALLOC_CTX *mem_ctx;
2563         PyObject *pydn = NULL;
2564         PyLdbMessageObject *py_ret;
2565
2566         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
2567                                          discard_const_p(char *, kwnames),
2568                                          &pydn))
2569                 return NULL;
2570
2571         mem_ctx = talloc_new(NULL);
2572         if (mem_ctx == NULL) {
2573                 PyErr_NoMemory();
2574                 return NULL;
2575         }
2576
2577         ret = ldb_msg_new(mem_ctx);
2578         if (ret == NULL) {
2579                 talloc_free(mem_ctx);
2580                 PyErr_NoMemory();
2581                 return NULL;
2582         }
2583
2584         if (pydn != NULL) {
2585                 struct ldb_dn *dn;
2586                 if (!PyObject_AsDn(NULL, pydn, NULL, &dn)) {
2587                         talloc_free(mem_ctx);
2588                         return NULL;
2589                 }
2590                 ret->dn = talloc_reference(ret, dn);
2591         }
2592
2593         py_ret = (PyLdbMessageObject *)type->tp_alloc(type, 0);
2594         if (py_ret == NULL) {
2595                 PyErr_NoMemory();
2596                 talloc_free(mem_ctx);
2597                 return NULL;
2598         }
2599
2600         py_ret->mem_ctx = mem_ctx;
2601         py_ret->msg = ret;
2602         return (PyObject *)py_ret;
2603 }
2604
2605 static PyObject *PyLdbMessage_FromMessage(struct ldb_message *msg)
2606 {
2607         PyLdbMessageObject *ret;
2608
2609         ret = (PyLdbMessageObject *)PyLdbMessage.tp_alloc(&PyLdbMessage, 0);
2610         if (ret == NULL) {
2611                 PyErr_NoMemory();
2612                 return NULL;
2613         }
2614         ret->mem_ctx = talloc_new(NULL);
2615         ret->msg = talloc_reference(ret->mem_ctx, msg);
2616         return (PyObject *)ret;
2617 }
2618
2619 static PyObject *py_ldb_msg_get_dn(PyLdbMessageObject *self, void *closure)
2620 {
2621         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2622         return PyLdbDn_FromDn(msg->dn);
2623 }
2624
2625 static int py_ldb_msg_set_dn(PyLdbMessageObject *self, PyObject *value, void *closure)
2626 {
2627         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2628         if (!PyLdbDn_Check(value)) {
2629                 PyErr_SetNone(PyExc_TypeError);
2630                 return -1;
2631         }
2632
2633         msg->dn = talloc_reference(msg, PyLdbDn_AsDn(value));
2634         return 0;
2635 }
2636
2637 static PyGetSetDef py_ldb_msg_getset[] = {
2638         { discard_const_p(char, "dn"), (getter)py_ldb_msg_get_dn, (setter)py_ldb_msg_set_dn, NULL },
2639         { NULL }
2640 };
2641
2642 static PyObject *py_ldb_msg_repr(PyLdbMessageObject *self)
2643 {
2644         PyObject *dict = PyDict_New(), *ret;
2645         if (PyDict_Update(dict, (PyObject *)self) != 0)
2646                 return NULL;
2647         ret = PyString_FromFormat("Message(%s)", PyObject_REPR(dict));
2648         Py_DECREF(dict);
2649         return ret;
2650 }
2651
2652 static void py_ldb_msg_dealloc(PyLdbMessageObject *self)
2653 {
2654         talloc_free(self->mem_ctx);
2655         PyObject_Del(self);
2656 }
2657
2658 static int py_ldb_msg_compare(PyLdbMessageObject *py_msg1,
2659                               PyLdbMessageObject *py_msg2)
2660 {
2661         struct ldb_message *msg1 = PyLdbMessage_AsMessage(py_msg1),
2662                            *msg2 = PyLdbMessage_AsMessage(py_msg2);
2663         unsigned int i;
2664         int ret;
2665
2666         if ((msg1->dn != NULL) || (msg2->dn != NULL)) {
2667                 ret = ldb_dn_compare(msg1->dn, msg2->dn);
2668                 if (ret != 0) {
2669                         return SIGN(ret);
2670                 }
2671         }
2672
2673         ret = msg1->num_elements - msg2->num_elements;
2674         if (ret != 0) {
2675                 return SIGN(ret);
2676         }
2677
2678         for (i = 0; i < msg1->num_elements; i++) {
2679                 ret = ldb_msg_element_compare_name(&msg1->elements[i],
2680                                                    &msg2->elements[i]);
2681                 if (ret != 0) {
2682                         return SIGN(ret);
2683                 }
2684
2685                 ret = ldb_msg_element_compare(&msg1->elements[i],
2686                                               &msg2->elements[i]);
2687                 if (ret != 0) {
2688                         return SIGN(ret);
2689                 }
2690         }
2691
2692         return 0;
2693 }
2694
2695 static PyTypeObject PyLdbMessage = {
2696         .tp_name = "ldb.Message",
2697         .tp_methods = py_ldb_msg_methods,
2698         .tp_getset = py_ldb_msg_getset,
2699         .tp_as_mapping = &py_ldb_msg_mapping,
2700         .tp_basicsize = sizeof(PyLdbMessageObject),
2701         .tp_dealloc = (destructor)py_ldb_msg_dealloc,
2702         .tp_new = py_ldb_msg_new,
2703         .tp_repr = (reprfunc)py_ldb_msg_repr,
2704         .tp_flags = Py_TPFLAGS_DEFAULT,
2705         .tp_iter = (getiterfunc)py_ldb_msg_iter,
2706         .tp_compare = (cmpfunc)py_ldb_msg_compare,
2707 };
2708
2709 static PyObject *PyLdbTree_FromTree(struct ldb_parse_tree *tree)
2710 {
2711         PyLdbTreeObject *ret;
2712
2713         ret = (PyLdbTreeObject *)PyLdbTree.tp_alloc(&PyLdbTree, 0);
2714         if (ret == NULL) {
2715                 PyErr_NoMemory();
2716                 return NULL;
2717         }
2718
2719         ret->mem_ctx = talloc_new(NULL);
2720         ret->tree = talloc_reference(ret->mem_ctx, tree);
2721         return (PyObject *)ret;
2722 }
2723
2724 static void py_ldb_tree_dealloc(PyLdbTreeObject *self)
2725 {
2726         talloc_free(self->mem_ctx);
2727         PyObject_Del(self);
2728 }
2729
2730 static PyTypeObject PyLdbTree = {
2731         .tp_name = "ldb.Tree",
2732         .tp_basicsize = sizeof(PyLdbTreeObject),
2733         .tp_dealloc = (destructor)py_ldb_tree_dealloc,
2734         .tp_flags = Py_TPFLAGS_DEFAULT,
2735 };
2736
2737 /* Ldb_module */
2738 static int py_module_search(struct ldb_module *mod, struct ldb_request *req)
2739 {
2740         PyObject *py_ldb = (PyObject *)mod->private_data;
2741         PyObject *py_result, *py_base, *py_attrs, *py_tree;
2742
2743         py_base = PyLdbDn_FromDn(req->op.search.base);
2744
2745         if (py_base == NULL)
2746                 return LDB_ERR_OPERATIONS_ERROR;
2747
2748         py_tree = PyLdbTree_FromTree(req->op.search.tree);
2749
2750         if (py_tree == NULL)
2751                 return LDB_ERR_OPERATIONS_ERROR;
2752
2753         if (req->op.search.attrs == NULL) {
2754                 py_attrs = Py_None;
2755         } else {
2756                 int i, len;
2757                 for (len = 0; req->op.search.attrs[len]; len++);
2758                 py_attrs = PyList_New(len);
2759                 for (i = 0; i < len; i++)
2760                         PyList_SetItem(py_attrs, i, PyString_FromString(req->op.search.attrs[i]));
2761         }
2762
2763         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "search"),
2764                                         discard_const_p(char, "OiOO"),
2765                                         py_base, req->op.search.scope, py_tree, py_attrs);
2766
2767         Py_DECREF(py_attrs);
2768         Py_DECREF(py_tree);
2769         Py_DECREF(py_base);
2770
2771         if (py_result == NULL) {
2772                 return LDB_ERR_PYTHON_EXCEPTION;
2773         }
2774
2775         req->op.search.res = PyLdbResult_AsResult(NULL, py_result);
2776         if (req->op.search.res == NULL) {
2777                 return LDB_ERR_PYTHON_EXCEPTION;
2778         }
2779
2780         Py_DECREF(py_result);
2781
2782         return LDB_SUCCESS;
2783 }
2784
2785 static int py_module_add(struct ldb_module *mod, struct ldb_request *req)
2786 {
2787         PyObject *py_ldb = (PyObject *)mod->private_data;
2788         PyObject *py_result, *py_msg;
2789
2790         py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.add.message));
2791
2792         if (py_msg == NULL) {
2793                 return LDB_ERR_OPERATIONS_ERROR;
2794         }
2795
2796         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "add"),
2797                                         discard_const_p(char, "O"),
2798                                         py_msg);
2799
2800         Py_DECREF(py_msg);
2801
2802         if (py_result == NULL) {
2803                 return LDB_ERR_PYTHON_EXCEPTION;
2804         }
2805
2806         Py_DECREF(py_result);
2807
2808         return LDB_SUCCESS;
2809 }
2810
2811 static int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
2812 {
2813         PyObject *py_ldb = (PyObject *)mod->private_data;
2814         PyObject *py_result, *py_msg;
2815
2816         py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.mod.message));
2817
2818         if (py_msg == NULL) {
2819                 return LDB_ERR_OPERATIONS_ERROR;
2820         }
2821
2822         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "modify"),
2823                                         discard_const_p(char, "O"),
2824                                         py_msg);
2825
2826         Py_DECREF(py_msg);
2827
2828         if (py_result == NULL) {
2829                 return LDB_ERR_PYTHON_EXCEPTION;
2830         }
2831
2832         Py_DECREF(py_result);
2833
2834         return LDB_SUCCESS;
2835 }
2836
2837 static int py_module_del(struct ldb_module *mod, struct ldb_request *req)
2838 {
2839         PyObject *py_ldb = (PyObject *)mod->private_data;
2840         PyObject *py_result, *py_dn;
2841
2842         py_dn = PyLdbDn_FromDn(req->op.del.dn);
2843
2844         if (py_dn == NULL)
2845                 return LDB_ERR_OPERATIONS_ERROR;
2846
2847         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "delete"),
2848                                         discard_const_p(char, "O"),
2849                                         py_dn);
2850
2851         if (py_result == NULL) {
2852                 return LDB_ERR_PYTHON_EXCEPTION;
2853         }
2854
2855         Py_DECREF(py_result);
2856
2857         return LDB_SUCCESS;
2858 }
2859
2860 static int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
2861 {
2862         PyObject *py_ldb = (PyObject *)mod->private_data;
2863         PyObject *py_result, *py_olddn, *py_newdn;
2864
2865         py_olddn = PyLdbDn_FromDn(req->op.rename.olddn);
2866
2867         if (py_olddn == NULL)
2868                 return LDB_ERR_OPERATIONS_ERROR;
2869
2870         py_newdn = PyLdbDn_FromDn(req->op.rename.newdn);
2871
2872         if (py_newdn == NULL)
2873                 return LDB_ERR_OPERATIONS_ERROR;
2874
2875         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "rename"),
2876                                         discard_const_p(char, "OO"),
2877                                         py_olddn, py_newdn);
2878
2879         Py_DECREF(py_olddn);
2880         Py_DECREF(py_newdn);
2881
2882         if (py_result == NULL) {
2883                 return LDB_ERR_PYTHON_EXCEPTION;
2884         }
2885
2886         Py_DECREF(py_result);
2887
2888         return LDB_SUCCESS;
2889 }
2890
2891 static int py_module_request(struct ldb_module *mod, struct ldb_request *req)
2892 {
2893         PyObject *py_ldb = (PyObject *)mod->private_data;
2894         PyObject *py_result;
2895
2896         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "request"),
2897                                         discard_const_p(char, ""));
2898
2899         return LDB_ERR_OPERATIONS_ERROR;
2900 }
2901
2902 static int py_module_extended(struct ldb_module *mod, struct ldb_request *req)
2903 {
2904         PyObject *py_ldb = (PyObject *)mod->private_data;
2905         PyObject *py_result;
2906
2907         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "extended"),
2908                                         discard_const_p(char, ""));
2909
2910         return LDB_ERR_OPERATIONS_ERROR;
2911 }
2912
2913 static int py_module_start_transaction(struct ldb_module *mod)
2914 {
2915         PyObject *py_ldb = (PyObject *)mod->private_data;
2916         PyObject *py_result;
2917
2918         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "start_transaction"),
2919                                         discard_const_p(char, ""));
2920
2921         if (py_result == NULL) {
2922                 return LDB_ERR_PYTHON_EXCEPTION;
2923         }
2924
2925         Py_DECREF(py_result);
2926
2927         return LDB_SUCCESS;
2928 }
2929
2930 static int py_module_end_transaction(struct ldb_module *mod)
2931 {
2932         PyObject *py_ldb = (PyObject *)mod->private_data;
2933         PyObject *py_result;
2934
2935         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "end_transaction"),
2936                                         discard_const_p(char, ""));
2937
2938         if (py_result == NULL) {
2939                 return LDB_ERR_PYTHON_EXCEPTION;
2940         }
2941
2942         Py_DECREF(py_result);
2943
2944         return LDB_SUCCESS;
2945 }
2946
2947 static int py_module_del_transaction(struct ldb_module *mod)
2948 {
2949         PyObject *py_ldb = (PyObject *)mod->private_data;
2950         PyObject *py_result;
2951
2952         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "del_transaction"),
2953                                         discard_const_p(char, ""));
2954
2955         if (py_result == NULL) {
2956                 return LDB_ERR_PYTHON_EXCEPTION;
2957         }
2958
2959         Py_DECREF(py_result);
2960
2961         return LDB_SUCCESS;
2962 }
2963
2964 static int py_module_destructor(struct ldb_module *mod)
2965 {
2966         Py_DECREF((PyObject *)mod->private_data);
2967         return 0;
2968 }
2969
2970 static int py_module_init(struct ldb_module *mod)
2971 {
2972         PyObject *py_class = (PyObject *)mod->ops->private_data;
2973         PyObject *py_result, *py_next, *py_ldb;
2974
2975         py_ldb = PyLdb_FromLdbContext(mod->ldb);
2976
2977         if (py_ldb == NULL)
2978                 return LDB_ERR_OPERATIONS_ERROR;
2979
2980         py_next = PyLdbModule_FromModule(mod->next);
2981
2982         if (py_next == NULL)
2983                 return LDB_ERR_OPERATIONS_ERROR;
2984
2985         py_result = PyObject_CallFunction(py_class, discard_const_p(char, "OO"),
2986                                           py_ldb, py_next);
2987
2988         if (py_result == NULL) {
2989                 return LDB_ERR_PYTHON_EXCEPTION;
2990         }
2991
2992         mod->private_data = py_result;
2993
2994         talloc_set_destructor(mod, py_module_destructor);
2995
2996         return ldb_next_init(mod);
2997 }
2998
2999 static PyObject *py_register_module(PyObject *module, PyObject *args)
3000 {
3001         int ret;
3002         struct ldb_module_ops *ops;
3003         PyObject *input;
3004
3005         if (!PyArg_ParseTuple(args, "O", &input))
3006                 return NULL;
3007
3008         ops = talloc_zero(talloc_autofree_context(), struct ldb_module_ops);
3009         if (ops == NULL) {
3010                 PyErr_NoMemory();
3011                 return NULL;
3012         }
3013
3014         ops->name = talloc_strdup(ops, PyString_AsString(PyObject_GetAttrString(input, discard_const_p(char, "name"))));
3015
3016         Py_INCREF(input);
3017         ops->private_data = input;
3018         ops->init_context = py_module_init;
3019         ops->search = py_module_search;
3020         ops->add = py_module_add;
3021         ops->modify = py_module_modify;
3022         ops->del = py_module_del;
3023         ops->rename = py_module_rename;
3024         ops->request = py_module_request;
3025         ops->extended = py_module_extended;
3026         ops->start_transaction = py_module_start_transaction;
3027         ops->end_transaction = py_module_end_transaction;
3028         ops->del_transaction = py_module_del_transaction;
3029
3030         ret = ldb_register_module(ops);
3031
3032         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
3033
3034         Py_RETURN_NONE;
3035 }
3036
3037 static PyObject *py_timestring(PyObject *module, PyObject *args)
3038 {
3039         /* most times "time_t" is a signed integer type with 32 or 64 bit:
3040          * http://stackoverflow.com/questions/471248/what-is-ultimately-a-time-t-typedef-to */
3041         long int t_val;
3042         char *tresult;
3043         PyObject *ret;
3044         if (!PyArg_ParseTuple(args, "l", &t_val))
3045                 return NULL;
3046         tresult = ldb_timestring(NULL, (time_t) t_val);
3047         ret = PyString_FromString(tresult);
3048         talloc_free(tresult);
3049         return ret;
3050 }
3051
3052 static PyObject *py_string_to_time(PyObject *module, PyObject *args)
3053 {
3054         char *str;
3055         if (!PyArg_ParseTuple(args, "s", &str))
3056                 return NULL;
3057
3058         return PyInt_FromLong(ldb_string_to_time(str));
3059 }
3060
3061 static PyObject *py_valid_attr_name(PyObject *self, PyObject *args)
3062 {
3063         char *name;
3064         if (!PyArg_ParseTuple(args, "s", &name))
3065                 return NULL;
3066         return PyBool_FromLong(ldb_valid_attr_name(name));
3067 }
3068
3069 static PyMethodDef py_ldb_global_methods[] = {
3070         { "register_module", py_register_module, METH_VARARGS, 
3071                 "S.register_module(module) -> None\n"
3072                 "Register a LDB module."},
3073         { "timestring", py_timestring, METH_VARARGS, 
3074                 "S.timestring(int) -> string\n"
3075                 "Generate a LDAP time string from a UNIX timestamp" },
3076         { "string_to_time", py_string_to_time, METH_VARARGS,
3077                 "S.string_to_time(string) -> int\n"
3078                 "Parse a LDAP time string into a UNIX timestamp." },
3079         { "valid_attr_name", py_valid_attr_name, METH_VARARGS,
3080                 "S.valid_attr_name(name) -> bool\n"
3081                 "Check whether the supplied name is a valid attribute name." },
3082         { "open", (PyCFunction)py_ldb_new, METH_VARARGS|METH_KEYWORDS,
3083                 NULL },
3084         { NULL }
3085 };
3086
3087 void initldb(void)
3088 {
3089         PyObject *m;
3090
3091         if (PyType_Ready(&PyLdbDn) < 0)
3092                 return;
3093
3094         if (PyType_Ready(&PyLdbMessage) < 0)
3095                 return;
3096
3097         if (PyType_Ready(&PyLdbMessageElement) < 0)
3098                 return;
3099
3100         if (PyType_Ready(&PyLdb) < 0)
3101                 return;
3102
3103         if (PyType_Ready(&PyLdbModule) < 0)
3104                 return;
3105
3106         if (PyType_Ready(&PyLdbTree) < 0)
3107                 return;
3108
3109         if (PyType_Ready(&PyLdbResult) < 0)
3110                 return;
3111
3112         if (PyType_Ready(&PyLdbControl) < 0)
3113                 return;
3114
3115         m = Py_InitModule3("ldb", py_ldb_global_methods, 
3116                 "An interface to LDB, a LDAP-like API that can either to talk an embedded database (TDB-based) or a standards-compliant LDAP server.");
3117         if (m == NULL)
3118                 return;
3119
3120         PyModule_AddObject(m, "SEQ_HIGHEST_SEQ", PyInt_FromLong(LDB_SEQ_HIGHEST_SEQ));
3121         PyModule_AddObject(m, "SEQ_HIGHEST_TIMESTAMP", PyInt_FromLong(LDB_SEQ_HIGHEST_TIMESTAMP));
3122         PyModule_AddObject(m, "SEQ_NEXT", PyInt_FromLong(LDB_SEQ_NEXT));
3123         PyModule_AddObject(m, "SCOPE_DEFAULT", PyInt_FromLong(LDB_SCOPE_DEFAULT));
3124         PyModule_AddObject(m, "SCOPE_BASE", PyInt_FromLong(LDB_SCOPE_BASE));
3125         PyModule_AddObject(m, "SCOPE_ONELEVEL", PyInt_FromLong(LDB_SCOPE_ONELEVEL));
3126         PyModule_AddObject(m, "SCOPE_SUBTREE", PyInt_FromLong(LDB_SCOPE_SUBTREE));
3127
3128         PyModule_AddObject(m, "CHANGETYPE_NONE", PyInt_FromLong(LDB_CHANGETYPE_NONE));
3129         PyModule_AddObject(m, "CHANGETYPE_ADD", PyInt_FromLong(LDB_CHANGETYPE_ADD));
3130         PyModule_AddObject(m, "CHANGETYPE_DELETE", PyInt_FromLong(LDB_CHANGETYPE_DELETE));
3131         PyModule_AddObject(m, "CHANGETYPE_MODIFY", PyInt_FromLong(LDB_CHANGETYPE_MODIFY));
3132
3133         PyModule_AddObject(m, "FLAG_MOD_ADD", PyInt_FromLong(LDB_FLAG_MOD_ADD));
3134         PyModule_AddObject(m, "FLAG_MOD_REPLACE", PyInt_FromLong(LDB_FLAG_MOD_REPLACE));
3135         PyModule_AddObject(m, "FLAG_MOD_DELETE", PyInt_FromLong(LDB_FLAG_MOD_DELETE));
3136
3137         PyModule_AddObject(m, "SUCCESS", PyInt_FromLong(LDB_SUCCESS));
3138         PyModule_AddObject(m, "ERR_OPERATIONS_ERROR", PyInt_FromLong(LDB_ERR_OPERATIONS_ERROR));
3139         PyModule_AddObject(m, "ERR_PROTOCOL_ERROR", PyInt_FromLong(LDB_ERR_PROTOCOL_ERROR));
3140         PyModule_AddObject(m, "ERR_TIME_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_TIME_LIMIT_EXCEEDED));
3141         PyModule_AddObject(m, "ERR_SIZE_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_SIZE_LIMIT_EXCEEDED));
3142         PyModule_AddObject(m, "ERR_COMPARE_FALSE", PyInt_FromLong(LDB_ERR_COMPARE_FALSE));
3143         PyModule_AddObject(m, "ERR_COMPARE_TRUE", PyInt_FromLong(LDB_ERR_COMPARE_TRUE));
3144         PyModule_AddObject(m, "ERR_AUTH_METHOD_NOT_SUPPORTED", PyInt_FromLong(LDB_ERR_AUTH_METHOD_NOT_SUPPORTED));
3145         PyModule_AddObject(m, "ERR_STRONG_AUTH_REQUIRED", PyInt_FromLong(LDB_ERR_STRONG_AUTH_REQUIRED));
3146         PyModule_AddObject(m, "ERR_REFERRAL", PyInt_FromLong(LDB_ERR_REFERRAL));
3147         PyModule_AddObject(m, "ERR_ADMIN_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_ADMIN_LIMIT_EXCEEDED));
3148         PyModule_AddObject(m, "ERR_UNSUPPORTED_CRITICAL_EXTENSION", PyInt_FromLong(LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION));
3149         PyModule_AddObject(m, "ERR_CONFIDENTIALITY_REQUIRED", PyInt_FromLong(LDB_ERR_CONFIDENTIALITY_REQUIRED));
3150         PyModule_AddObject(m, "ERR_SASL_BIND_IN_PROGRESS", PyInt_FromLong(LDB_ERR_SASL_BIND_IN_PROGRESS));
3151         PyModule_AddObject(m, "ERR_NO_SUCH_ATTRIBUTE", PyInt_FromLong(LDB_ERR_NO_SUCH_ATTRIBUTE));
3152         PyModule_AddObject(m, "ERR_UNDEFINED_ATTRIBUTE_TYPE", PyInt_FromLong(LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE));
3153         PyModule_AddObject(m, "ERR_INAPPROPRIATE_MATCHING", PyInt_FromLong(LDB_ERR_INAPPROPRIATE_MATCHING));
3154         PyModule_AddObject(m, "ERR_CONSTRAINT_VIOLATION", PyInt_FromLong(LDB_ERR_CONSTRAINT_VIOLATION));
3155         PyModule_AddObject(m, "ERR_ATTRIBUTE_OR_VALUE_EXISTS", PyInt_FromLong(LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS));
3156         PyModule_AddObject(m, "ERR_INVALID_ATTRIBUTE_SYNTAX", PyInt_FromLong(LDB_ERR_INVALID_ATTRIBUTE_SYNTAX));
3157         PyModule_AddObject(m, "ERR_NO_SUCH_OBJECT", PyInt_FromLong(LDB_ERR_NO_SUCH_OBJECT));
3158         PyModule_AddObject(m, "ERR_ALIAS_PROBLEM", PyInt_FromLong(LDB_ERR_ALIAS_PROBLEM));
3159         PyModule_AddObject(m, "ERR_INVALID_DN_SYNTAX", PyInt_FromLong(LDB_ERR_INVALID_DN_SYNTAX));
3160         PyModule_AddObject(m, "ERR_ALIAS_DEREFERINCING_PROBLEM", PyInt_FromLong(LDB_ERR_ALIAS_DEREFERENCING_PROBLEM));
3161         PyModule_AddObject(m, "ERR_INAPPROPRIATE_AUTHENTICATION", PyInt_FromLong(LDB_ERR_INAPPROPRIATE_AUTHENTICATION));
3162         PyModule_AddObject(m, "ERR_INVALID_CREDENTIALS", PyInt_FromLong(LDB_ERR_INVALID_CREDENTIALS));
3163         PyModule_AddObject(m, "ERR_INSUFFICIENT_ACCESS_RIGHTS", PyInt_FromLong(LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS));
3164         PyModule_AddObject(m, "ERR_BUSY", PyInt_FromLong(LDB_ERR_BUSY));
3165         PyModule_AddObject(m, "ERR_UNAVAILABLE", PyInt_FromLong(LDB_ERR_UNAVAILABLE));
3166         PyModule_AddObject(m, "ERR_UNWILLING_TO_PERFORM", PyInt_FromLong(LDB_ERR_UNWILLING_TO_PERFORM));
3167         PyModule_AddObject(m, "ERR_LOOP_DETECT", PyInt_FromLong(LDB_ERR_LOOP_DETECT));
3168         PyModule_AddObject(m, "ERR_NAMING_VIOLATION", PyInt_FromLong(LDB_ERR_NAMING_VIOLATION));
3169         PyModule_AddObject(m, "ERR_OBJECT_CLASS_VIOLATION", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_VIOLATION));
3170         PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_NON_LEAF", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_NON_LEAF));
3171         PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_RDN", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_RDN));
3172         PyModule_AddObject(m, "ERR_ENTRY_ALREADY_EXISTS", PyInt_FromLong(LDB_ERR_ENTRY_ALREADY_EXISTS));
3173         PyModule_AddObject(m, "ERR_OBJECT_CLASS_MODS_PROHIBITED", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED));
3174         PyModule_AddObject(m, "ERR_AFFECTS_MULTIPLE_DSAS", PyInt_FromLong(LDB_ERR_AFFECTS_MULTIPLE_DSAS));
3175         PyModule_AddObject(m, "ERR_OTHER", PyInt_FromLong(LDB_ERR_OTHER));
3176
3177         PyModule_AddObject(m, "FLG_RDONLY", PyInt_FromLong(LDB_FLG_RDONLY));
3178         PyModule_AddObject(m, "FLG_NOSYNC", PyInt_FromLong(LDB_FLG_NOSYNC));
3179         PyModule_AddObject(m, "FLG_RECONNECT", PyInt_FromLong(LDB_FLG_RECONNECT));
3180         PyModule_AddObject(m, "FLG_NOMMAP", PyInt_FromLong(LDB_FLG_NOMMAP));
3181
3182         PyModule_AddObject(m, "__docformat__", PyString_FromString("restructuredText"));
3183
3184         PyExc_LdbError = PyErr_NewException(discard_const_p(char, "_ldb.LdbError"), NULL, NULL);
3185         PyModule_AddObject(m, "LdbError", PyExc_LdbError);
3186
3187         Py_INCREF(&PyLdb);
3188         Py_INCREF(&PyLdbDn);
3189         Py_INCREF(&PyLdbModule);
3190         Py_INCREF(&PyLdbMessage);
3191         Py_INCREF(&PyLdbMessageElement);
3192         Py_INCREF(&PyLdbTree);
3193         Py_INCREF(&PyLdbResult);
3194         Py_INCREF(&PyLdbControl);
3195
3196         PyModule_AddObject(m, "Ldb", (PyObject *)&PyLdb);
3197         PyModule_AddObject(m, "Dn", (PyObject *)&PyLdbDn);
3198         PyModule_AddObject(m, "Message", (PyObject *)&PyLdbMessage);
3199         PyModule_AddObject(m, "MessageElement", (PyObject *)&PyLdbMessageElement);
3200         PyModule_AddObject(m, "Module", (PyObject *)&PyLdbModule);
3201         PyModule_AddObject(m, "Tree", (PyObject *)&PyLdbTree);
3202         PyModule_AddObject(m, "Control", (PyObject *)&PyLdbControl);
3203
3204         PyModule_AddObject(m, "__version__", PyString_FromString(PACKAGE_VERSION));
3205 }