ldb:python bindings - add a context on "py_ldb_delete"
[ira/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-2009 Jelmer Vernooij <jelmer@samba.org>
9    Copyright (C) 2009 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 "replace.h"
31 #include "ldb_private.h"
32 #include "pyldb.h"
33
34 /* There's no Py_ssize_t in 2.4, apparently */
35 #if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 5
36 typedef int Py_ssize_t;
37 typedef inquiry lenfunc;
38 typedef intargfunc ssizeargfunc;
39 #endif
40
41 #ifndef Py_RETURN_NONE
42 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
43 #endif
44
45 static void PyErr_SetLdbError(PyObject *error, int ret, struct ldb_context *ldb_ctx)
46 {
47         if (ret == LDB_ERR_PYTHON_EXCEPTION)
48                 return; /* Python exception should already be set, just keep that */
49
50         PyErr_SetObject(error, 
51                                         Py_BuildValue(discard_const_p(char, "(i,s)"), ret, 
52                                   ldb_ctx == NULL?ldb_strerror(ret):ldb_errstring(ldb_ctx)));
53 }
54
55 static PyObject *PyExc_LdbError;
56
57 PyAPI_DATA(PyTypeObject) PyLdbMessage;
58 PyAPI_DATA(PyTypeObject) PyLdbModule;
59 PyAPI_DATA(PyTypeObject) PyLdbDn;
60 PyAPI_DATA(PyTypeObject) PyLdb;
61 PyAPI_DATA(PyTypeObject) PyLdbMessageElement;
62 PyAPI_DATA(PyTypeObject) PyLdbTree;
63
64 static PyObject *PyObject_FromLdbValue(struct ldb_context *ldb_ctx, 
65                                                            struct ldb_message_element *el, 
66                                                            struct ldb_val *val)
67 {
68         struct ldb_val new_val;
69         TALLOC_CTX *mem_ctx = talloc_new(NULL);
70         PyObject *ret;
71
72         new_val = *val;
73
74         ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
75
76         talloc_free(mem_ctx);
77
78         return ret;
79 }
80
81 /**
82  * Obtain a ldb DN from a Python object.
83  *
84  * @param mem_ctx Memory context
85  * @param object Python object
86  * @param ldb_ctx LDB context
87  * @return Whether or not the conversion succeeded
88  */
89 bool PyObject_AsDn(TALLOC_CTX *mem_ctx, PyObject *object, 
90                    struct ldb_context *ldb_ctx, struct ldb_dn **dn)
91 {
92         struct ldb_dn *odn;
93
94         if (ldb_ctx != NULL && PyString_Check(object)) {
95                 odn = ldb_dn_new(mem_ctx, ldb_ctx, PyString_AsString(object));
96                 *dn = odn;
97                 return true;
98         }
99
100         if (PyLdbDn_Check(object)) {
101                 *dn = PyLdbDn_AsDn(object);
102                 return true;
103         }
104
105         PyErr_SetString(PyExc_TypeError, "Expected DN");
106         return false;
107 }
108
109 /**
110  * Create a Python object from a ldb_result.
111  *
112  * @param result LDB result to convert
113  * @return Python object with converted result (a list object)
114  */
115 static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
116 {
117         PyObject *ret;
118         int i;
119         if (result == NULL) {
120                 Py_RETURN_NONE;
121         } 
122         ret = PyList_New(result->count);
123         for (i = 0; i < result->count; i++) {
124                 PyList_SetItem(ret, i, PyLdbMessage_FromMessage(result->msgs[i])
125                 );
126         }
127         return ret;
128 }
129
130 /**
131  * Create a LDB Result from a Python object. 
132  * If conversion fails, NULL will be returned and a Python exception set.
133  *
134  * @param mem_ctx Memory context in which to allocate the LDB Result
135  * @param obj Python object to convert
136  * @return a ldb_result, or NULL if the conversion failed
137  */
138 static struct ldb_result *PyLdbResult_AsResult(TALLOC_CTX *mem_ctx, 
139                                                                                            PyObject *obj)
140 {
141         struct ldb_result *res;
142         int i;
143
144         if (obj == Py_None)
145                 return NULL;
146
147         res = talloc_zero(mem_ctx, struct ldb_result);
148         res->count = PyList_Size(obj);
149         res->msgs = talloc_array(res, struct ldb_message *, res->count);
150         for (i = 0; i < res->count; i++) {
151                 PyObject *item = PyList_GetItem(obj, i);
152                 res->msgs[i] = PyLdbMessage_AsMessage(item);
153         }
154         return res;
155 }
156
157 static PyObject *py_ldb_dn_validate(PyLdbDnObject *self)
158 {
159         return PyBool_FromLong(ldb_dn_validate(self->dn));
160 }
161
162 static PyObject *py_ldb_dn_is_valid(PyLdbDnObject *self)
163 {
164         return PyBool_FromLong(ldb_dn_is_valid(self->dn));
165 }
166
167 static PyObject *py_ldb_dn_is_special(PyLdbDnObject *self)
168 {
169         return PyBool_FromLong(ldb_dn_is_special(self->dn));
170 }
171
172 static PyObject *py_ldb_dn_is_null(PyLdbDnObject *self)
173 {
174         return PyBool_FromLong(ldb_dn_is_null(self->dn));
175 }
176  
177 static PyObject *py_ldb_dn_get_casefold(PyLdbDnObject *self)
178 {
179         return PyString_FromString(ldb_dn_get_casefold(self->dn));
180 }
181
182 static PyObject *py_ldb_dn_get_linearized(PyLdbDnObject *self)
183 {
184         return PyString_FromString(ldb_dn_get_linearized(self->dn));
185 }
186
187 static PyObject *py_ldb_dn_canonical_str(PyLdbDnObject *self)
188 {
189         return PyString_FromString(ldb_dn_canonical_string(self->dn, self->dn));
190 }
191
192 static PyObject *py_ldb_dn_canonical_ex_str(PyLdbDnObject *self)
193 {
194         return PyString_FromString(ldb_dn_canonical_ex_string(self->dn, self->dn));
195 }
196
197 static PyObject *py_ldb_dn_repr(PyLdbDnObject *self)
198 {
199         return PyString_FromFormat("Dn(%s)", PyObject_REPR(PyString_FromString(ldb_dn_get_linearized(self->dn))));
200 }
201
202 static PyObject *py_ldb_dn_check_special(PyLdbDnObject *self, PyObject *args)
203 {
204         char *name;
205
206         if (!PyArg_ParseTuple(args, "s", &name))
207                 return NULL;
208
209         return ldb_dn_check_special(self->dn, name)?Py_True:Py_False;
210 }
211
212 static int py_ldb_dn_compare(PyLdbDnObject *dn1, PyLdbDnObject *dn2)
213 {
214         int ret;
215         ret = ldb_dn_compare(dn1->dn, dn2->dn);
216         if (ret < 0) ret = -1;
217         if (ret > 0) ret = 1;
218         return ret;
219 }
220
221 static PyObject *py_ldb_dn_get_parent(PyLdbDnObject *self)
222 {
223         struct ldb_dn *dn = PyLdbDn_AsDn((PyObject *)self);
224         struct ldb_dn *parent;
225         PyLdbDnObject *py_ret;
226         TALLOC_CTX *mem_ctx = talloc_new(NULL);
227
228         parent = ldb_dn_get_parent(mem_ctx, dn);
229         if (parent == NULL) {
230                 talloc_free(mem_ctx);
231                 Py_RETURN_NONE;
232         }
233
234         py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
235         if (py_ret == NULL) {
236                 PyErr_NoMemory();
237                 talloc_free(mem_ctx);
238                 return NULL;
239         }
240         py_ret->mem_ctx = mem_ctx;
241         py_ret->dn = parent;
242         return (PyObject *)py_ret;
243 }
244
245 #define dn_ldb_ctx(dn) ((struct ldb_context *)dn)
246
247 static PyObject *py_ldb_dn_add_child(PyLdbDnObject *self, PyObject *args)
248 {
249         PyObject *py_other;
250         struct ldb_dn *dn, *other;
251         if (!PyArg_ParseTuple(args, "O", &py_other))
252                 return NULL;
253
254         dn = PyLdbDn_AsDn((PyObject *)self);
255
256         if (!PyObject_AsDn(NULL, py_other, dn_ldb_ctx(dn), &other))
257                 return NULL;
258
259         return ldb_dn_add_child(dn, other)?Py_True:Py_False;
260 }
261
262 static PyObject *py_ldb_dn_add_base(PyLdbDnObject *self, PyObject *args)
263 {
264         PyObject *py_other;
265         struct ldb_dn *other, *dn;
266         if (!PyArg_ParseTuple(args, "O", &py_other))
267                 return NULL;
268
269         dn = PyLdbDn_AsDn((PyObject *)self);
270
271         if (!PyObject_AsDn(NULL, py_other, dn_ldb_ctx(dn), &other))
272                 return NULL;
273
274         return ldb_dn_add_base(dn, other)?Py_True:Py_False;
275 }
276
277 static PyMethodDef py_ldb_dn_methods[] = {
278         { "validate", (PyCFunction)py_ldb_dn_validate, METH_NOARGS, 
279                 "S.validate() -> bool\n"
280                 "Validate DN is correct." },
281         { "is_valid", (PyCFunction)py_ldb_dn_is_valid, METH_NOARGS,
282                 "S.is_valid() -> bool\n" },
283         { "is_special", (PyCFunction)py_ldb_dn_is_special, METH_NOARGS,
284                 "S.is_special() -> bool\n"
285                 "Check whether this is a special LDB DN." },
286         { "is_null", (PyCFunction)py_ldb_dn_is_null, METH_NOARGS,
287                 "Check whether this is a null DN." },
288         { "get_casefold", (PyCFunction)py_ldb_dn_get_casefold, METH_NOARGS,
289                 NULL },
290         { "get_linearized", (PyCFunction)py_ldb_dn_get_linearized, METH_NOARGS,
291                 NULL },
292         { "canonical_str", (PyCFunction)py_ldb_dn_canonical_str, METH_NOARGS,
293                 "S.canonical_str() -> string\n"
294                 "Canonical version of this DN (like a posix path)." },
295         { "canonical_ex_str", (PyCFunction)py_ldb_dn_canonical_ex_str, METH_NOARGS,
296                 "S.canonical_ex_str() -> string\n"
297                 "Canonical version of this DN (like a posix path, with terminating newline)." },
298         { "check_special", (PyCFunction)py_ldb_dn_is_special, METH_VARARGS, 
299                 NULL },
300         { "parent", (PyCFunction)py_ldb_dn_get_parent, METH_NOARGS,
301                 "S.parent() -> dn\n"
302                 "Get the parent for this DN." },
303         { "add_child", (PyCFunction)py_ldb_dn_add_child, METH_VARARGS, 
304                 "S.add_child(dn) -> None\n"
305                 "Add a child DN to this DN." },
306         { "add_base", (PyCFunction)py_ldb_dn_add_base, METH_VARARGS,
307                 "S.add_base(dn) -> None\n"
308                 "Add a base DN to this DN." },
309         { "check_special", (PyCFunction)py_ldb_dn_check_special, METH_VARARGS,
310                 NULL },
311         { NULL }
312 };
313
314 static Py_ssize_t py_ldb_dn_len(PyLdbDnObject *self)
315 {
316         return ldb_dn_get_comp_num(PyLdbDn_AsDn((PyObject *)self));
317 }
318
319 static PyObject *py_ldb_dn_concat(PyLdbDnObject *self, PyObject *py_other)
320 {
321         struct ldb_dn *dn = PyLdbDn_AsDn((PyObject *)self), 
322                                   *other;
323         PyLdbDnObject *py_ret;
324         
325         if (!PyObject_AsDn(NULL, py_other, NULL, &other))
326                 return NULL;
327
328         py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
329         if (py_ret == NULL) {
330                 PyErr_NoMemory();
331                 return NULL;
332         }
333         py_ret->mem_ctx = talloc_new(NULL);
334         py_ret->dn = ldb_dn_copy(py_ret->mem_ctx, dn);
335         ldb_dn_add_child(py_ret->dn, other);
336         return (PyObject *)py_ret;
337 }
338
339 static PySequenceMethods py_ldb_dn_seq = {
340         .sq_length = (lenfunc)py_ldb_dn_len,
341         .sq_concat = (binaryfunc)py_ldb_dn_concat,
342 };
343
344 static PyObject *py_ldb_dn_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
345 {
346         struct ldb_dn *ret;
347         char *str;
348         PyObject *py_ldb;
349         struct ldb_context *ldb_ctx;
350         TALLOC_CTX *mem_ctx;
351         PyLdbDnObject *py_ret;
352         const char * const kwnames[] = { "ldb", "dn", NULL };
353
354         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Os",
355                                          discard_const_p(char *, kwnames),
356                                          &py_ldb, &str))
357                 return NULL;
358
359         ldb_ctx = PyLdb_AsLdbContext(py_ldb);
360
361         mem_ctx = talloc_new(NULL);
362         if (mem_ctx == NULL) {
363                 PyErr_NoMemory();
364                 return NULL;
365         }
366
367         ret = ldb_dn_new(mem_ctx, ldb_ctx, str);
368
369         if (ret == NULL || !ldb_dn_validate(ret)) {
370                 talloc_free(mem_ctx);
371                 PyErr_SetString(PyExc_ValueError, "unable to parse dn string");
372                 return NULL;
373         }
374
375         py_ret = (PyLdbDnObject *)type->tp_alloc(type, 0);
376         if (ret == NULL) {
377                 talloc_free(mem_ctx);
378                 PyErr_NoMemory();
379                 return NULL;
380         }
381         py_ret->mem_ctx = mem_ctx;
382         py_ret->dn = ret;
383         return (PyObject *)py_ret;
384 }
385
386 PyObject *PyLdbDn_FromDn(struct ldb_dn *dn)
387 {
388         PyLdbDnObject *py_ret;
389
390         if (dn == NULL) {
391                 Py_RETURN_NONE;
392         }
393
394         py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
395         if (py_ret == NULL) {
396                 PyErr_NoMemory();
397                 return NULL;
398         }
399         py_ret->mem_ctx = talloc_new(NULL);
400         py_ret->dn = talloc_reference(py_ret->mem_ctx, dn);
401         return (PyObject *)py_ret;
402 }
403
404 static void py_ldb_dn_dealloc(PyLdbDnObject *self)
405 {
406         talloc_free(self->mem_ctx);
407         self->ob_type->tp_free(self);
408 }
409
410 PyTypeObject PyLdbDn = {
411         .tp_name = "Dn",
412         .tp_methods = py_ldb_dn_methods,
413         .tp_str = (reprfunc)py_ldb_dn_get_linearized,
414         .tp_repr = (reprfunc)py_ldb_dn_repr,
415         .tp_compare = (cmpfunc)py_ldb_dn_compare,
416         .tp_as_sequence = &py_ldb_dn_seq,
417         .tp_doc = "A LDB distinguished name.",
418         .tp_new = py_ldb_dn_new,
419         .tp_dealloc = (destructor)py_ldb_dn_dealloc,
420         .tp_basicsize = sizeof(PyLdbObject),
421         .tp_flags = Py_TPFLAGS_DEFAULT,
422 };
423
424 /* Debug */
425 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(3, 0);
426 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap)
427 {
428         PyObject *fn = (PyObject *)context;
429         PyObject_CallFunction(fn, discard_const_p(char, "(i,O)"), level, PyString_FromFormatV(fmt, ap));
430 }
431
432 static PyObject *py_ldb_set_debug(PyLdbObject *self, PyObject *args)
433 {
434         PyObject *cb;
435
436         if (!PyArg_ParseTuple(args, "O", &cb))
437                 return NULL;
438
439         Py_INCREF(cb);
440         /* FIXME: Where do we DECREF cb ? */
441         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_set_debug(self->ldb_ctx, py_ldb_debug, cb), PyLdb_AsLdbContext(self));
442
443         Py_RETURN_NONE;
444 }
445
446 static PyObject *py_ldb_set_create_perms(PyTypeObject *self, PyObject *args)
447 {
448         unsigned int perms;
449         if (!PyArg_ParseTuple(args, "I", &perms))
450                 return NULL;
451
452         ldb_set_create_perms(PyLdb_AsLdbContext(self), perms);
453
454         Py_RETURN_NONE;
455 }
456
457 static PyObject *py_ldb_set_modules_dir(PyTypeObject *self, PyObject *args)
458 {
459         char *modules_dir;
460         if (!PyArg_ParseTuple(args, "s", &modules_dir))
461                 return NULL;
462
463         ldb_set_modules_dir(PyLdb_AsLdbContext(self), modules_dir);
464
465         Py_RETURN_NONE;
466 }
467
468 static PyObject *py_ldb_transaction_start(PyLdbObject *self)
469 {
470         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_start(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
471         Py_RETURN_NONE;
472 }
473
474 static PyObject *py_ldb_transaction_commit(PyLdbObject *self)
475 {
476         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_commit(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
477         Py_RETURN_NONE;
478 }
479
480 static PyObject *py_ldb_transaction_cancel(PyLdbObject *self)
481 {
482         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_cancel(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
483         Py_RETURN_NONE;
484 }
485
486 static PyObject *py_ldb_setup_wellknown_attributes(PyLdbObject *self)
487 {
488         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_setup_wellknown_attributes(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
489         Py_RETURN_NONE;
490 }
491
492 static PyObject *py_ldb_repr(PyLdbObject *self)
493 {
494         return PyString_FromFormat("<ldb connection>");
495 }
496
497 static PyObject *py_ldb_get_root_basedn(PyLdbObject *self)
498 {
499         struct ldb_dn *dn = ldb_get_root_basedn(PyLdb_AsLdbContext(self));
500         if (dn == NULL)
501                 Py_RETURN_NONE;
502         return PyLdbDn_FromDn(dn);
503 }
504
505
506 static PyObject *py_ldb_get_schema_basedn(PyLdbObject *self)
507 {
508         struct ldb_dn *dn = ldb_get_schema_basedn(PyLdb_AsLdbContext(self));
509         if (dn == NULL)
510                 Py_RETURN_NONE;
511         return PyLdbDn_FromDn(dn);
512 }
513
514 static PyObject *py_ldb_get_config_basedn(PyLdbObject *self)
515 {
516         struct ldb_dn *dn = ldb_get_config_basedn(PyLdb_AsLdbContext(self));
517         if (dn == NULL)
518                 Py_RETURN_NONE;
519         return PyLdbDn_FromDn(dn);
520 }
521
522 static PyObject *py_ldb_get_default_basedn(PyLdbObject *self)
523 {
524         struct ldb_dn *dn = ldb_get_default_basedn(PyLdb_AsLdbContext(self));
525         if (dn == NULL)
526                 Py_RETURN_NONE;
527         return PyLdbDn_FromDn(dn);
528 }
529
530 static const char **PyList_AsStringList(TALLOC_CTX *mem_ctx, PyObject *list, 
531                                                                                 const char *paramname)
532 {
533         const char **ret;
534         int i;
535         if (!PyList_Check(list)) {
536                 PyErr_Format(PyExc_TypeError, "%s is not a list", paramname);
537                 return NULL;
538         }
539         ret = talloc_array(NULL, const char *, PyList_Size(list)+1);
540         for (i = 0; i < PyList_Size(list); i++) {
541                 PyObject *item = PyList_GetItem(list, i);
542                 if (!PyString_Check(item)) {
543                         PyErr_Format(PyExc_TypeError, "%s should be strings", paramname);
544                         return NULL;
545                 }
546                 ret[i] = talloc_strndup(ret, PyString_AsString(item),
547                                                            PyString_Size(item));
548         }
549         ret[i] = NULL;
550         return ret;
551 }
552
553 static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
554 {
555         const char * const kwnames[] = { "url", "flags", "options", NULL };
556         char *url = NULL;
557         PyObject *py_options = Py_None;
558         const char **options;
559         int flags = 0;
560         int ret;
561         struct ldb_context *ldb;
562
563         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO:Ldb.__init__",
564                                          discard_const_p(char *, kwnames),
565                                          &url, &flags, &py_options))
566                 return -1;
567
568         ldb = PyLdb_AsLdbContext(self);
569
570         if (py_options == Py_None) {
571                 options = NULL;
572         } else {
573                 options = PyList_AsStringList(ldb, py_options, "options");
574                 if (options == NULL)
575                         return -1;
576         }
577
578         if (url != NULL) {
579                 ret = ldb_connect(ldb, url, flags, options);
580                 if (ret != LDB_SUCCESS) {
581                         PyErr_SetLdbError(PyExc_LdbError, ret, ldb);
582                         return -1;
583                 }
584         }
585
586         talloc_free(options);
587         return 0;
588 }
589
590 static PyObject *py_ldb_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
591 {
592         PyLdbObject *ret;
593         struct ldb_context *ldb;
594         ret = (PyLdbObject *)type->tp_alloc(type, 0);
595         if (ret == NULL) {
596                 PyErr_NoMemory();
597                 return NULL;
598         }
599         ret->mem_ctx = talloc_new(NULL);
600         ldb = ldb_init(ret->mem_ctx, NULL);
601
602         if (ldb == NULL) {
603                 PyErr_NoMemory();
604                 return NULL;
605         }
606
607         ret->ldb_ctx = ldb;
608         return (PyObject *)ret;
609 }
610
611 static PyObject *py_ldb_connect(PyLdbObject *self, PyObject *args, PyObject *kwargs)
612 {
613         char *url;
614         int flags = 0;
615         PyObject *py_options = Py_None;
616         int ret;
617         const char **options;
618         const char * const kwnames[] = { "url", "flags", "options", NULL };
619
620         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO",
621                                          discard_const_p(char *, kwnames),
622                                          &url, &flags, &py_options))
623                 return NULL;
624
625         if (py_options == Py_None) {
626                 options = NULL;
627         } else {
628                 options = PyList_AsStringList(NULL, py_options, "options");
629                 if (options == NULL)
630                         return NULL;
631         }
632
633         ret = ldb_connect(PyLdb_AsLdbContext(self), url, flags, options);
634         talloc_free(options);
635
636         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
637
638         Py_RETURN_NONE;
639 }
640
641 static PyObject *py_ldb_modify(PyLdbObject *self, PyObject *args)
642 {
643         PyObject *py_msg;
644         int ret;
645         if (!PyArg_ParseTuple(args, "O", &py_msg))
646                 return NULL;
647
648         if (!PyLdbMessage_Check(py_msg)) {
649                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message");
650                 return NULL;
651         }
652
653         ret = ldb_modify(PyLdb_AsLdbContext(self), PyLdbMessage_AsMessage(py_msg));
654         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
655
656         Py_RETURN_NONE;
657 }
658
659
660 static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args)
661 {
662         PyObject *py_msg;
663         int ret;
664         Py_ssize_t dict_pos, msg_pos;
665         struct ldb_message_element *msgel;
666         struct ldb_message *msg;
667         struct ldb_context *ldb_ctx;
668         struct ldb_request *req;
669         PyObject *key, *value;
670         PyObject *py_controls = Py_None;
671         TALLOC_CTX *mem_ctx;
672         struct ldb_control **parsed_controls;
673
674         if (!PyArg_ParseTuple(args, "O|O", &py_msg, &py_controls ))
675                 return NULL;
676         ldb_ctx = PyLdb_AsLdbContext(self);
677
678         mem_ctx = talloc_new(NULL);
679         if (py_controls == Py_None) {
680                 parsed_controls = NULL;
681         } else {
682                 const char **controls = PyList_AsStringList(ldb_ctx, py_controls, "controls");
683                 parsed_controls = ldb_parse_control_strings(ldb_ctx, ldb_ctx, controls);
684                 talloc_free(controls);
685         }
686         if (PyDict_Check(py_msg)) {
687                 PyObject *dn_value = PyDict_GetItemString(py_msg, "dn");
688                 msg = ldb_msg_new(mem_ctx);
689                 msg->elements = talloc_zero_array(msg, struct ldb_message_element, PyDict_Size(py_msg));
690                 msg_pos = dict_pos = 0;
691                 if (dn_value) {
692                         if (!PyObject_AsDn(msg, dn_value, ldb_ctx, &msg->dn)) {
693                                 PyErr_SetString(PyExc_TypeError, "unable to import dn object");
694                                 talloc_free(mem_ctx);
695                                 return NULL;
696                         }
697                         if (msg->dn == NULL) {
698                                 PyErr_SetString(PyExc_TypeError, "dn set but not found");
699                                 talloc_free(mem_ctx);
700                                 return NULL;
701                         }
702                 }
703
704                 while (PyDict_Next(py_msg, &dict_pos, &key, &value)) {
705                         char *key_str = PyString_AsString(key);
706                         if (strcmp(key_str, "dn") != 0) {
707                                 msgel = PyObject_AsMessageElement(msg->elements, value, 0, key_str);
708                                 if (msgel == NULL) {
709                                         PyErr_SetString(PyExc_TypeError, "unable to import element");
710                                         talloc_free(mem_ctx);
711                                         return NULL;
712                                 }
713                                 memcpy(&msg->elements[msg_pos], msgel, sizeof(*msgel));
714                                 msg_pos++;
715                         }
716                 }
717
718                 if (msg->dn == NULL) {
719                         PyErr_SetString(PyExc_TypeError, "no dn set");
720                         talloc_free(mem_ctx);
721                         return NULL;
722                 }
723
724                 msg->num_elements = msg_pos;
725         } else {
726                 msg = PyLdbMessage_AsMessage(py_msg);
727         }
728         
729         ret = ldb_msg_sanity_check(ldb_ctx, msg);
730         if (ret != LDB_SUCCESS) {
731                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
732                 talloc_free(mem_ctx);
733                 return NULL;
734         }
735
736         ret = ldb_build_add_req(&req, ldb_ctx, ldb_ctx,
737                                         msg,
738                                         parsed_controls,
739                                         NULL,
740                                         ldb_op_default_callback,
741                                         NULL);
742
743         if (ret != LDB_SUCCESS) {
744                 PyErr_SetString(PyExc_TypeError, "failed to build request");
745                 talloc_free(mem_ctx);
746                 return NULL;
747         }
748
749         /* do request and autostart a transaction */
750         /* Then let's LDB handle the message error in case of pb as they are meaningful */
751
752         ret = ldb_transaction_start(ldb_ctx);
753         if (ret != LDB_SUCCESS) {
754                 talloc_free(req);
755                 talloc_free(mem_ctx);
756                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
757         }
758
759         ret = ldb_request(ldb_ctx, req);
760         if (ret == LDB_SUCCESS) {
761                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
762         } 
763
764         if (ret == LDB_SUCCESS) {
765                 ret = ldb_transaction_commit(ldb_ctx);
766         } else {
767                 ldb_transaction_cancel(ldb_ctx);
768                 if (ldb_ctx->err_string == NULL) {
769                         /* no error string was setup by the backend */
770                         ldb_asprintf_errstring(ldb_ctx, "%s (%d)", ldb_strerror(ret), ret);
771                 }
772         }
773         talloc_free(req);
774         talloc_free(mem_ctx);
775         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
776
777         Py_RETURN_NONE;
778 }
779
780 static PyObject *py_ldb_delete(PyLdbObject *self, PyObject *args)
781 {
782         PyObject *py_dn;
783         struct ldb_dn *dn;
784         int ret;
785         struct ldb_context *ldb;
786         TALLOC_CTX *mem_ctx;
787         if (!PyArg_ParseTuple(args, "O", &py_dn))
788                 return NULL;
789
790         mem_ctx = talloc_new(NULL);
791         if (mem_ctx == NULL) {
792                 PyErr_NoMemory();
793                 return NULL;
794         }
795         ldb = PyLdb_AsLdbContext(self);
796         if (!PyObject_AsDn(mem_ctx, py_dn, ldb, &dn)) {
797                 talloc_free(mem_ctx);
798                 return NULL;
799         }
800
801         ret = ldb_delete(ldb, dn);
802         talloc_free(mem_ctx);
803         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
804
805         Py_RETURN_NONE;
806 }
807
808 static PyObject *py_ldb_rename(PyLdbObject *self, PyObject *args)
809 {
810         PyObject *py_dn1, *py_dn2;
811         struct ldb_dn *dn1, *dn2;
812         int ret;
813         struct ldb_context *ldb;
814         TALLOC_CTX *mem_ctx;
815         if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
816                 return NULL;
817
818         mem_ctx = talloc_new(NULL);
819         if (mem_ctx == NULL) {
820                 PyErr_NoMemory();
821                 return NULL;
822         }
823         ldb = PyLdb_AsLdbContext(self);
824         if (!PyObject_AsDn(mem_ctx, py_dn1, ldb, &dn1)) {
825                 talloc_free(mem_ctx);
826                 return NULL;
827         }
828
829         if (!PyObject_AsDn(mem_ctx, py_dn2, ldb, &dn2)) {
830                 talloc_free(mem_ctx);
831                 return NULL;
832         }
833
834         ret = ldb_rename(ldb, dn1, dn2);
835         talloc_free(mem_ctx);
836         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
837
838         Py_RETURN_NONE;
839 }
840
841 static PyObject *py_ldb_schema_attribute_remove(PyLdbObject *self, PyObject *args)
842 {
843         char *name;
844         if (!PyArg_ParseTuple(args, "s", &name))
845                 return NULL;
846
847         ldb_schema_attribute_remove(PyLdb_AsLdbContext(self), name);
848
849         Py_RETURN_NONE;
850 }
851
852 static PyObject *py_ldb_schema_attribute_add(PyLdbObject *self, PyObject *args)
853 {
854         char *attribute, *syntax;
855         unsigned int flags;
856         int ret;
857         if (!PyArg_ParseTuple(args, "sIs", &attribute, &flags, &syntax))
858                 return NULL;
859
860         ret = ldb_schema_attribute_add(PyLdb_AsLdbContext(self), attribute, flags, syntax);
861
862         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
863
864         Py_RETURN_NONE;
865 }
866
867 static PyObject *ldb_ldif_to_pyobject(struct ldb_ldif *ldif)
868 {
869         if (ldif == NULL) {
870                 Py_RETURN_NONE;
871         } else {
872         /* We don't want this attached to the 'ldb' any more */
873                 return Py_BuildValue(discard_const_p(char, "(iO)"),
874                                      ldif->changetype,
875                                      PyLdbMessage_FromMessage(ldif->msg));
876         }
877 }
878
879
880 static PyObject *py_ldb_write_ldif(PyLdbMessageObject *self, PyObject *args)
881 {
882         int changetype;
883         PyObject *py_msg;
884         struct ldb_ldif ldif;
885         PyObject *ret;
886         char *string;
887         TALLOC_CTX *mem_ctx;
888
889         if (!PyArg_ParseTuple(args, "Oi", &py_msg, &changetype))
890                 return NULL;
891
892         if (!PyLdbMessage_Check(py_msg)) {
893                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for msg");
894                 return NULL;
895         }
896
897         ldif.msg = PyLdbMessage_AsMessage(py_msg);
898         ldif.changetype = changetype;
899
900         mem_ctx = talloc_new(NULL);
901
902         string = ldb_ldif_write_string(PyLdb_AsLdbContext(self), mem_ctx, &ldif);
903         if (!string) {
904                 PyErr_SetString(PyExc_KeyError, "Failed to generate LDIF");
905                 return NULL;
906         }
907
908         ret = PyString_FromString(string);
909
910         talloc_free(mem_ctx);
911
912         return ret;
913 }
914
915 static PyObject *py_ldb_parse_ldif(PyLdbObject *self, PyObject *args)
916 {
917         PyObject *list;
918         struct ldb_ldif *ldif;
919         const char *s;
920
921         TALLOC_CTX *mem_ctx;
922
923         if (!PyArg_ParseTuple(args, "s", &s))
924                 return NULL;
925
926         mem_ctx = talloc_new(NULL);
927         if (!mem_ctx) {
928                 Py_RETURN_NONE;
929         }
930
931         list = PyList_New(0);
932         while (s && *s != '\0') {
933                 ldif = ldb_ldif_read_string(self->ldb_ctx, &s);
934                 talloc_steal(mem_ctx, ldif);
935                 if (ldif) {
936                         PyList_Append(list, ldb_ldif_to_pyobject(ldif));
937                 } else {
938                         PyErr_SetString(PyExc_ValueError, "unable to parse ldif string");
939                         talloc_free(mem_ctx);
940                         return NULL;
941                 }
942         }
943         talloc_free(mem_ctx); /* The pyobject already has a reference to the things it needs */
944         return PyObject_GetIter(list);
945 }
946
947 static PyObject *py_ldb_msg_diff(PyLdbObject *self, PyObject *args)
948 {
949         PyObject *py_msg_old;
950         PyObject *py_msg_new;
951         struct ldb_message *diff;
952         PyObject *py_ret;
953
954         if (!PyArg_ParseTuple(args, "OO", &py_msg_old, &py_msg_new))
955                 return NULL;
956
957         if (!PyLdbMessage_Check(py_msg_old)) {
958                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for old message");
959                 return NULL;
960         }
961
962         if (!PyLdbMessage_Check(py_msg_new)) {
963                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for new message");
964                 return NULL;
965         }
966
967         diff = ldb_msg_diff(PyLdb_AsLdbContext(self), PyLdbMessage_AsMessage(py_msg_old), PyLdbMessage_AsMessage(py_msg_new));
968         if (!diff) {
969                 PyErr_SetString(PyExc_RuntimeError, "Failed to generate the Ldb Message diff");
970                 return NULL;
971         }
972
973         py_ret = PyLdbMessage_FromMessage(diff);
974
975         return py_ret;
976 }
977
978 static PyObject *py_ldb_schema_format_value(PyLdbObject *self, PyObject *args)
979 {
980         const struct ldb_schema_attribute *a;
981         struct ldb_val old_val;
982         struct ldb_val new_val;
983         TALLOC_CTX *mem_ctx;
984         PyObject *ret;
985         char *element_name;
986         PyObject *val;
987
988         if (!PyArg_ParseTuple(args, "sO", &element_name, &val))
989                 return NULL;
990
991         mem_ctx = talloc_new(NULL);
992
993         old_val.data = (uint8_t *)PyString_AsString(val);
994         old_val.length = PyString_Size(val);
995
996         a = ldb_schema_attribute_by_name(PyLdb_AsLdbContext(self), element_name);
997
998         if (a == NULL) {
999                 Py_RETURN_NONE;
1000         }
1001
1002         if (a->syntax->ldif_write_fn(PyLdb_AsLdbContext(self), mem_ctx, &old_val, &new_val) != 0) {
1003                 talloc_free(mem_ctx);
1004                 Py_RETURN_NONE;
1005         }
1006
1007         ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
1008
1009         talloc_free(mem_ctx);
1010
1011         return ret;
1012 }
1013
1014 static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwargs)
1015 {
1016         PyObject *py_base = Py_None;
1017         int scope = LDB_SCOPE_DEFAULT;
1018         char *expr = NULL;
1019         PyObject *py_attrs = Py_None;
1020         PyObject *py_controls = Py_None;
1021         const char * const kwnames[] = { "base", "scope", "expression", "attrs", "controls", NULL };
1022         int ret;
1023         struct ldb_result *res;
1024         struct ldb_request *req;
1025         const char **attrs;
1026         struct ldb_context *ldb_ctx;
1027         struct ldb_control **parsed_controls;
1028         struct ldb_dn *base;
1029         PyObject *py_ret;
1030
1031         /* type "int" rather than "enum" for "scope" is intentional */
1032         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OizOO",
1033                                          discard_const_p(char *, kwnames),
1034                                          &py_base, &scope, &expr, &py_attrs, &py_controls))
1035                 return NULL;
1036
1037         ldb_ctx = PyLdb_AsLdbContext(self);
1038
1039         if (py_attrs == Py_None) {
1040                 attrs = NULL;
1041         } else {
1042                 attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
1043                 if (attrs == NULL)
1044                         return NULL;
1045         }
1046
1047         if (py_base == Py_None) {
1048                 base = ldb_get_default_basedn(ldb_ctx);
1049         } else {
1050                 if (!PyObject_AsDn(ldb_ctx, py_base, ldb_ctx, &base)) {
1051                         talloc_free(attrs);
1052                         return NULL;
1053                 }
1054         }
1055
1056         if (py_controls == Py_None) {
1057                 parsed_controls = NULL;
1058         } else {
1059                 const char **controls = PyList_AsStringList(ldb_ctx, py_controls, "controls");
1060                 parsed_controls = ldb_parse_control_strings(ldb_ctx, ldb_ctx, controls);
1061                 talloc_free(controls);
1062         }
1063
1064         res = talloc_zero(ldb_ctx, struct ldb_result);
1065         if (res == NULL) {
1066                 PyErr_NoMemory();
1067                 talloc_free(attrs);
1068                 return NULL;
1069         }
1070
1071         ret = ldb_build_search_req(&req, ldb_ctx, ldb_ctx,
1072                                    base,
1073                                    scope,
1074                                    expr,
1075                                    attrs,
1076                                    parsed_controls,
1077                                    res,
1078                                    ldb_search_default_callback,
1079                                    NULL);
1080
1081         talloc_steal(req, attrs);
1082
1083         if (ret != LDB_SUCCESS) {
1084                 talloc_free(res);
1085                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1086                 return NULL;
1087         }
1088
1089         ret = ldb_request(ldb_ctx, req);
1090
1091         if (ret == LDB_SUCCESS) {
1092                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1093         }
1094
1095         talloc_free(req);
1096
1097         if (ret != LDB_SUCCESS) {
1098                 talloc_free(res);
1099                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1100                 return NULL;
1101         }
1102
1103         py_ret = PyLdbResult_FromResult(res);
1104
1105         talloc_free(res);
1106
1107         return py_ret;
1108 }
1109
1110 static PyObject *py_ldb_get_opaque(PyLdbObject *self, PyObject *args)
1111 {
1112         char *name;
1113         void *data;
1114
1115         if (!PyArg_ParseTuple(args, "s", &name))
1116                 return NULL;
1117
1118         data = ldb_get_opaque(PyLdb_AsLdbContext(self), name);
1119
1120         if (data == NULL)
1121                 Py_RETURN_NONE;
1122
1123         /* FIXME: More interpretation */
1124
1125         return Py_True;
1126 }
1127
1128 static PyObject *py_ldb_set_opaque(PyLdbObject *self, PyObject *args)
1129 {
1130         char *name;
1131         PyObject *data;
1132
1133         if (!PyArg_ParseTuple(args, "sO", &name, &data))
1134                 return NULL;
1135
1136         /* FIXME: More interpretation */
1137
1138         ldb_set_opaque(PyLdb_AsLdbContext(self), name, data);
1139
1140         Py_RETURN_NONE;
1141 }
1142
1143 static PyObject *py_ldb_modules(PyLdbObject *self)
1144 {
1145         struct ldb_context *ldb = PyLdb_AsLdbContext(self);
1146         PyObject *ret = PyList_New(0);
1147         struct ldb_module *mod;
1148
1149         for (mod = ldb->modules; mod; mod = mod->next) {
1150                 PyList_Append(ret, PyLdbModule_FromModule(mod));
1151         }
1152
1153         return ret;
1154 }
1155
1156 static PyMethodDef py_ldb_methods[] = {
1157         { "set_debug", (PyCFunction)py_ldb_set_debug, METH_VARARGS, 
1158                 "S.set_debug(callback) -> None\n"
1159                 "Set callback for LDB debug messages.\n"
1160                 "The callback should accept a debug level and debug text." },
1161         { "set_create_perms", (PyCFunction)py_ldb_set_create_perms, METH_VARARGS, 
1162                 "S.set_create_perms(mode) -> None\n"
1163                 "Set mode to use when creating new LDB files." },
1164         { "set_modules_dir", (PyCFunction)py_ldb_set_modules_dir, METH_VARARGS,
1165                 "S.set_modules_dir(path) -> None\n"
1166                 "Set path LDB should search for modules" },
1167         { "transaction_start", (PyCFunction)py_ldb_transaction_start, METH_NOARGS, 
1168                 "S.transaction_start() -> None\n"
1169                 "Start a new transaction." },
1170         { "transaction_commit", (PyCFunction)py_ldb_transaction_commit, METH_NOARGS, 
1171                 "S.transaction_commit() -> None\n"
1172                 "commit a new transaction." },
1173         { "transaction_cancel", (PyCFunction)py_ldb_transaction_cancel, METH_NOARGS, 
1174                 "S.transaction_cancel() -> None\n"
1175                 "cancel a new transaction." },
1176         { "setup_wellknown_attributes", (PyCFunction)py_ldb_setup_wellknown_attributes, METH_NOARGS, 
1177                 NULL },
1178         { "get_root_basedn", (PyCFunction)py_ldb_get_root_basedn, METH_NOARGS,
1179                 NULL },
1180         { "get_schema_basedn", (PyCFunction)py_ldb_get_schema_basedn, METH_NOARGS,
1181                 NULL },
1182         { "get_default_basedn", (PyCFunction)py_ldb_get_default_basedn, METH_NOARGS,
1183                 NULL },
1184         { "get_config_basedn", (PyCFunction)py_ldb_get_config_basedn, METH_NOARGS,
1185                 NULL },
1186         { "connect", (PyCFunction)py_ldb_connect, METH_VARARGS|METH_KEYWORDS, 
1187                 "S.connect(url, flags=0, options=None) -> None\n"
1188                 "Connect to a LDB URL." },
1189         { "modify", (PyCFunction)py_ldb_modify, METH_VARARGS, 
1190                 "S.modify(message) -> None\n"
1191                 "Modify an entry." },
1192         { "add", (PyCFunction)py_ldb_add, METH_VARARGS, 
1193                 "S.add(message) -> None\n"
1194                 "Add an entry." },
1195         { "delete", (PyCFunction)py_ldb_delete, METH_VARARGS,
1196                 "S.delete(dn) -> None\n"
1197                 "Remove an entry." },
1198         { "rename", (PyCFunction)py_ldb_rename, METH_VARARGS,
1199                 "S.rename(old_dn, new_dn) -> None\n"
1200                 "Rename an entry." },
1201         { "search", (PyCFunction)py_ldb_search, METH_VARARGS|METH_KEYWORDS,
1202                 "S.search(base=None, scope=None, expression=None, attrs=None, controls=None) -> msgs\n"
1203                 "Search in a database.\n"
1204                 "\n"
1205                 ":param base: Optional base DN to search\n"
1206                 ":param scope: Search scope (SCOPE_BASE, SCOPE_ONELEVEL or SCOPE_SUBTREE)\n"
1207                 ":param expression: Optional search expression\n"
1208                 ":param attrs: Attributes to return (defaults to all)\n"
1209                 ":param controls: Optional list of controls\n"
1210                 ":return: Iterator over Message objects\n"
1211         },
1212         { "schema_attribute_remove", (PyCFunction)py_ldb_schema_attribute_remove, METH_VARARGS,
1213                 NULL },
1214         { "schema_attribute_add", (PyCFunction)py_ldb_schema_attribute_add, METH_VARARGS,
1215                 NULL },
1216         { "schema_format_value", (PyCFunction)py_ldb_schema_format_value, METH_VARARGS,
1217                 NULL },
1218         { "parse_ldif", (PyCFunction)py_ldb_parse_ldif, METH_VARARGS,
1219                 "S.parse_ldif(ldif) -> iter(messages)\n"
1220                 "Parse a string formatted using LDIF." },
1221         { "write_ldif", (PyCFunction)py_ldb_write_ldif, METH_VARARGS,
1222                 "S.write_ldif(message, changetype) -> ldif\n"
1223                 "Print the message as a string formatted using LDIF." },
1224         { "msg_diff", (PyCFunction)py_ldb_msg_diff, METH_VARARGS,
1225                 "S.msg_diff(Message) -> Message\n"
1226                 "Return an LDB Message of the difference between two Message objects." },
1227         { "get_opaque", (PyCFunction)py_ldb_get_opaque, METH_VARARGS,
1228                 "S.get_opaque(name) -> value\n"
1229                 "Get an opaque value set on this LDB connection. \n"
1230                 ":note: The returned value may not be useful in Python."
1231         },
1232         { "set_opaque", (PyCFunction)py_ldb_set_opaque, METH_VARARGS,
1233                 "S.set_opaque(name, value) -> None\n"
1234                 "Set an opaque value on this LDB connection. \n"
1235                 ":note: Passing incorrect values may cause crashes." },
1236         { "modules", (PyCFunction)py_ldb_modules, METH_NOARGS,
1237                 "S.modules() -> list\n"
1238                 "Return the list of modules on this LDB connection " },
1239         { NULL },
1240 };
1241
1242 PyObject *PyLdbModule_FromModule(struct ldb_module *mod)
1243 {
1244         PyLdbModuleObject *ret;
1245
1246         ret = (PyLdbModuleObject *)PyLdbModule.tp_alloc(&PyLdbModule, 0);
1247         if (ret == NULL) {
1248                 PyErr_NoMemory();
1249                 return NULL;
1250         }
1251         ret->mem_ctx = talloc_new(NULL);
1252         ret->mod = talloc_reference(ret->mem_ctx, mod);
1253         return (PyObject *)ret;
1254 }
1255
1256 static PyObject *py_ldb_get_firstmodule(PyLdbObject *self, void *closure)
1257 {
1258         return PyLdbModule_FromModule(PyLdb_AsLdbContext(self)->modules);
1259 }
1260
1261 static PyGetSetDef py_ldb_getset[] = {
1262         { discard_const_p(char, "firstmodule"), (getter)py_ldb_get_firstmodule, NULL, NULL },
1263         { NULL }
1264 };
1265
1266 static int py_ldb_contains(PyLdbObject *self, PyObject *obj)
1267 {
1268         struct ldb_context *ldb_ctx = PyLdb_AsLdbContext(self);
1269         struct ldb_dn *dn;
1270         struct ldb_result *result;
1271         int ret;
1272         int count;
1273
1274         if (!PyObject_AsDn(ldb_ctx, obj, ldb_ctx, &dn))
1275                 return -1;
1276
1277         ret = ldb_search(ldb_ctx, ldb_ctx, &result, dn, LDB_SCOPE_BASE, NULL, NULL);
1278         if (ret != LDB_SUCCESS) {
1279                 PyErr_SetLdbError(PyExc_LdbError, ret, ldb_ctx);
1280                 return -1;
1281         }
1282
1283         count = result->count;
1284
1285         talloc_free(result);
1286
1287         return count;
1288 }
1289
1290 static PySequenceMethods py_ldb_seq = {
1291         .sq_contains = (objobjproc)py_ldb_contains,
1292 };
1293
1294 PyObject *PyLdb_FromLdbContext(struct ldb_context *ldb_ctx)
1295 {
1296         PyLdbObject *ret;
1297
1298         ret = (PyLdbObject *)PyLdb.tp_alloc(&PyLdb, 0);
1299         if (ret == NULL) {
1300                 PyErr_NoMemory();
1301                 return NULL;
1302         }
1303         ret->mem_ctx = talloc_new(NULL);
1304         ret->ldb_ctx = talloc_reference(ret->mem_ctx, ldb_ctx);
1305         return (PyObject *)ret;
1306 }
1307
1308 static void py_ldb_dealloc(PyLdbObject *self)
1309 {
1310         talloc_free(self->mem_ctx);
1311         self->ob_type->tp_free(self);
1312 }
1313
1314 PyTypeObject PyLdb = {
1315         .tp_name = "Ldb",
1316         .tp_methods = py_ldb_methods,
1317         .tp_repr = (reprfunc)py_ldb_repr,
1318         .tp_new = py_ldb_new,
1319         .tp_init = (initproc)py_ldb_init,
1320         .tp_dealloc = (destructor)py_ldb_dealloc,
1321         .tp_getset = py_ldb_getset,
1322         .tp_getattro = PyObject_GenericGetAttr,
1323         .tp_basicsize = sizeof(PyLdbObject),
1324         .tp_doc = "Connection to a LDB database.",
1325         .tp_as_sequence = &py_ldb_seq,
1326         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1327 };
1328
1329 static PyObject *py_ldb_module_repr(PyLdbModuleObject *self)
1330 {
1331         return PyString_FromFormat("<ldb module '%s'>", PyLdbModule_AsModule(self)->ops->name);
1332 }
1333
1334 static PyObject *py_ldb_module_str(PyLdbModuleObject *self)
1335 {
1336         return PyString_FromString(PyLdbModule_AsModule(self)->ops->name);
1337 }
1338
1339 static PyObject *py_ldb_module_start_transaction(PyLdbModuleObject *self)
1340 {
1341         PyLdbModule_AsModule(self)->ops->start_transaction(PyLdbModule_AsModule(self));
1342         Py_RETURN_NONE;
1343 }
1344
1345 static PyObject *py_ldb_module_end_transaction(PyLdbModuleObject *self)
1346 {
1347         PyLdbModule_AsModule(self)->ops->end_transaction(PyLdbModule_AsModule(self));
1348         Py_RETURN_NONE;
1349 }
1350
1351 static PyObject *py_ldb_module_del_transaction(PyLdbModuleObject *self)
1352 {
1353         PyLdbModule_AsModule(self)->ops->del_transaction(PyLdbModule_AsModule(self));
1354         Py_RETURN_NONE;
1355 }
1356
1357 static PyObject *py_ldb_module_search(PyLdbModuleObject *self, PyObject *args, PyObject *kwargs)
1358 {
1359         PyObject *py_base, *py_tree, *py_attrs, *py_ret;
1360         int ret, scope;
1361         struct ldb_request *req;
1362         const char * const kwnames[] = { "base", "scope", "tree", "attrs", NULL };
1363         struct ldb_module *mod;
1364         const char * const*attrs;
1365
1366         /* type "int" rather than "enum" for "scope" is intentional */
1367         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OiOO",
1368                                          discard_const_p(char *, kwnames),
1369                                          &py_base, &scope, &py_tree, &py_attrs))
1370                 return NULL;
1371
1372         mod = self->mod;
1373
1374         if (py_attrs == Py_None) {
1375                 attrs = NULL;
1376         } else {
1377                 attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
1378                 if (attrs == NULL)
1379                         return NULL;
1380         }
1381
1382         ret = ldb_build_search_req(&req, mod->ldb, NULL, PyLdbDn_AsDn(py_base), 
1383                              scope, NULL /* expr */, attrs,
1384                              NULL /* controls */, NULL, NULL, NULL);
1385
1386         talloc_steal(req, attrs);
1387
1388         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1389
1390         req->op.search.res = NULL;
1391
1392         ret = mod->ops->search(mod, req);
1393
1394         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1395
1396         py_ret = PyLdbResult_FromResult(req->op.search.res);
1397
1398         talloc_free(req);
1399
1400         return py_ret;  
1401 }
1402
1403
1404 static PyObject *py_ldb_module_add(PyLdbModuleObject *self, PyObject *args)
1405 {
1406         struct ldb_request *req;
1407         PyObject *py_message;
1408         int ret;
1409         struct ldb_module *mod;
1410
1411         if (!PyArg_ParseTuple(args, "O", &py_message))
1412                 return NULL;
1413
1414         req = talloc_zero(NULL, struct ldb_request);
1415         req->operation = LDB_ADD;
1416         req->op.add.message = PyLdbMessage_AsMessage(py_message);
1417
1418         mod = PyLdbModule_AsModule(self);
1419         ret = mod->ops->add(mod, req);
1420
1421         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1422
1423         Py_RETURN_NONE;
1424 }
1425
1426 static PyObject *py_ldb_module_modify(PyLdbModuleObject *self, PyObject *args) 
1427 {
1428         int ret;
1429         struct ldb_request *req;
1430         PyObject *py_message;
1431         struct ldb_module *mod;
1432
1433         if (!PyArg_ParseTuple(args, "O", &py_message))
1434                 return NULL;
1435
1436         req = talloc_zero(NULL, struct ldb_request);
1437         req->operation = LDB_MODIFY;
1438         req->op.mod.message = PyLdbMessage_AsMessage(py_message);
1439
1440         mod = PyLdbModule_AsModule(self);
1441         ret = mod->ops->modify(mod, req);
1442
1443         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1444
1445         Py_RETURN_NONE;
1446 }
1447
1448 static PyObject *py_ldb_module_delete(PyLdbModuleObject *self, PyObject *args) 
1449 {
1450         int ret;
1451         struct ldb_request *req;
1452         PyObject *py_dn;
1453
1454         if (!PyArg_ParseTuple(args, "O", &py_dn))
1455                 return NULL;
1456
1457         req = talloc_zero(NULL, struct ldb_request);
1458         req->operation = LDB_DELETE;
1459         req->op.del.dn = PyLdbDn_AsDn(py_dn);
1460
1461         ret = PyLdbModule_AsModule(self)->ops->del(PyLdbModule_AsModule(self), req);
1462
1463         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
1464
1465         Py_RETURN_NONE;
1466 }
1467
1468 static PyObject *py_ldb_module_rename(PyLdbModuleObject *self, PyObject *args)
1469 {
1470         int ret;
1471         struct ldb_request *req;
1472         PyObject *py_dn1, *py_dn2;
1473
1474         if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
1475                 return NULL;
1476
1477         req = talloc_zero(NULL, struct ldb_request);
1478
1479         req->operation = LDB_RENAME;
1480         req->op.rename.olddn = PyLdbDn_AsDn(py_dn1);
1481         req->op.rename.newdn = PyLdbDn_AsDn(py_dn2);
1482
1483         ret = PyLdbModule_AsModule(self)->ops->rename(PyLdbModule_AsModule(self), req);
1484
1485         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
1486
1487         Py_RETURN_NONE;
1488 }
1489
1490 static PyMethodDef py_ldb_module_methods[] = {
1491         { "search", (PyCFunction)py_ldb_module_search, METH_VARARGS|METH_KEYWORDS, NULL },
1492         { "add", (PyCFunction)py_ldb_module_add, METH_VARARGS, NULL },
1493         { "modify", (PyCFunction)py_ldb_module_modify, METH_VARARGS, NULL },
1494         { "rename", (PyCFunction)py_ldb_module_rename, METH_VARARGS, NULL },
1495         { "delete", (PyCFunction)py_ldb_module_delete, METH_VARARGS, NULL },
1496         { "start_transaction", (PyCFunction)py_ldb_module_start_transaction, METH_NOARGS, NULL },
1497         { "end_transaction", (PyCFunction)py_ldb_module_end_transaction, METH_NOARGS, NULL },
1498         { "del_transaction", (PyCFunction)py_ldb_module_del_transaction, METH_NOARGS, NULL },
1499         { NULL },
1500 };
1501
1502 static void py_ldb_module_dealloc(PyLdbModuleObject *self)
1503 {
1504         talloc_free(self->mem_ctx);
1505         self->ob_type->tp_free(self);
1506 }
1507
1508 PyTypeObject PyLdbModule = {
1509         .tp_name = "LdbModule",
1510         .tp_methods = py_ldb_module_methods,
1511         .tp_repr = (reprfunc)py_ldb_module_repr,
1512         .tp_str = (reprfunc)py_ldb_module_str,
1513         .tp_basicsize = sizeof(PyLdbModuleObject),
1514         .tp_dealloc = (destructor)py_ldb_module_dealloc,
1515         .tp_flags = Py_TPFLAGS_DEFAULT,
1516 };
1517
1518
1519 /**
1520  * Create a ldb_message_element from a Python object.
1521  *
1522  * This will accept any sequence objects that contains strings, or 
1523  * a string object.
1524  *
1525  * A reference to set_obj will be borrowed. 
1526  *
1527  * @param mem_ctx Memory context
1528  * @param set_obj Python object to convert
1529  * @param flags ldb_message_element flags to set
1530  * @param attr_name Name of the attribute
1531  * @return New ldb_message_element, allocated as child of mem_ctx
1532  */
1533 struct ldb_message_element *PyObject_AsMessageElement(TALLOC_CTX *mem_ctx,
1534                                                                                            PyObject *set_obj, int flags,
1535                                                                                            const char *attr_name)
1536 {
1537         struct ldb_message_element *me;
1538
1539         if (PyLdbMessageElement_Check(set_obj))
1540                 return talloc_reference(mem_ctx, 
1541                                                                 PyLdbMessageElement_AsMessageElement(set_obj));
1542
1543         me = talloc(mem_ctx, struct ldb_message_element);
1544
1545         me->name = talloc_strdup(me, attr_name);
1546         me->flags = flags;
1547         if (PyString_Check(set_obj)) {
1548                 me->num_values = 1;
1549                 me->values = talloc_array(me, struct ldb_val, me->num_values);
1550                 me->values[0].length = PyString_Size(set_obj);
1551                 me->values[0].data = talloc_memdup(me, 
1552                         (uint8_t *)PyString_AsString(set_obj), me->values[0].length);
1553         } else if (PySequence_Check(set_obj)) {
1554                 int i;
1555                 me->num_values = PySequence_Size(set_obj);
1556                 me->values = talloc_array(me, struct ldb_val, me->num_values);
1557                 for (i = 0; i < me->num_values; i++) {
1558                         PyObject *obj = PySequence_GetItem(set_obj, i);
1559
1560                         me->values[i].length = PyString_Size(obj);
1561                         me->values[i].data = talloc_memdup(me, 
1562                                 (uint8_t *)PyString_AsString(obj), me->values[i].length);
1563                 }
1564         } else {
1565                 talloc_free(me);
1566                 me = NULL;
1567         }
1568
1569         return me;
1570 }
1571
1572
1573 static PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx, 
1574                                                                  struct ldb_message_element *me)
1575 {
1576         int i;
1577         PyObject *result;
1578
1579         /* Python << 2.5 doesn't have PySet_New and PySet_Add. */
1580         result = PyList_New(me->num_values);
1581
1582         for (i = 0; i < me->num_values; i++) {
1583                 PyList_SetItem(result, i,
1584                         PyObject_FromLdbValue(ldb_ctx, me, &me->values[i]));
1585         }
1586
1587         return result;
1588 }
1589
1590 static PyObject *py_ldb_msg_element_get(PyLdbMessageElementObject *self, PyObject *args)
1591 {
1592         int i;
1593         if (!PyArg_ParseTuple(args, "i", &i))
1594                 return NULL;
1595         if (i < 0 || i >= PyLdbMessageElement_AsMessageElement(self)->num_values)
1596                 Py_RETURN_NONE;
1597
1598         return PyObject_FromLdbValue(NULL, PyLdbMessageElement_AsMessageElement(self), 
1599                                                                  &(PyLdbMessageElement_AsMessageElement(self)->values[i]));
1600 }
1601
1602 static PyObject *py_ldb_msg_element_flags(PyLdbMessageElementObject *self, PyObject *args)
1603 {
1604         struct ldb_message_element *el;
1605
1606         el = PyLdbMessageElement_AsMessageElement(self);
1607         return PyInt_FromLong(el->flags);
1608 }
1609
1610 static PyObject *py_ldb_msg_element_set_flags(PyLdbMessageElementObject *self, PyObject *args)
1611 {
1612         int flags;
1613         struct ldb_message_element *el;
1614         if (!PyArg_ParseTuple(args, "i", &flags))
1615                 return NULL;
1616
1617         el = PyLdbMessageElement_AsMessageElement(self);
1618         el->flags = flags;
1619         Py_RETURN_NONE;
1620 }
1621
1622 static PyMethodDef py_ldb_msg_element_methods[] = {
1623         { "get", (PyCFunction)py_ldb_msg_element_get, METH_VARARGS, NULL },
1624         { "set_flags", (PyCFunction)py_ldb_msg_element_set_flags, METH_VARARGS, NULL },
1625         { "flags", (PyCFunction)py_ldb_msg_element_flags, METH_NOARGS, NULL },
1626         { NULL },
1627 };
1628
1629 static Py_ssize_t py_ldb_msg_element_len(PyLdbMessageElementObject *self)
1630 {
1631         return PyLdbMessageElement_AsMessageElement(self)->num_values;
1632 }
1633
1634 static PyObject *py_ldb_msg_element_find(PyLdbMessageElementObject *self, Py_ssize_t idx)
1635 {
1636         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1637         if (idx < 0 || idx >= el->num_values) {
1638                 PyErr_SetString(PyExc_IndexError, "Out of range");
1639                 return NULL;
1640         }
1641         return PyString_FromStringAndSize((char *)el->values[idx].data, el->values[idx].length);
1642 }
1643
1644 static PySequenceMethods py_ldb_msg_element_seq = {
1645         .sq_length = (lenfunc)py_ldb_msg_element_len,
1646         .sq_item = (ssizeargfunc)py_ldb_msg_element_find,
1647 };
1648
1649 static int py_ldb_msg_element_cmp(PyLdbMessageElementObject *self, PyLdbMessageElementObject *other)
1650 {
1651         return ldb_msg_element_compare(PyLdbMessageElement_AsMessageElement(self), 
1652                                                                    PyLdbMessageElement_AsMessageElement(other));
1653 }
1654
1655 static PyObject *py_ldb_msg_element_iter(PyLdbMessageElementObject *self)
1656 {
1657         return PyObject_GetIter(ldb_msg_element_to_set(NULL, PyLdbMessageElement_AsMessageElement(self)));
1658 }
1659
1660 PyObject *PyLdbMessageElement_FromMessageElement(struct ldb_message_element *el, TALLOC_CTX *mem_ctx)
1661 {
1662         PyLdbMessageElementObject *ret;
1663         ret = (PyLdbMessageElementObject *)PyLdbMessageElement.tp_alloc(&PyLdbMessageElement, 0);
1664         if (ret == NULL) {
1665                 PyErr_NoMemory();
1666                 return NULL;
1667         }
1668         ret->mem_ctx = talloc_new(NULL);
1669         if (talloc_reference(ret->mem_ctx, mem_ctx) == NULL) {
1670                 PyErr_NoMemory();
1671                 return NULL;
1672         }
1673         ret->el = el;
1674         return (PyObject *)ret;
1675 }
1676
1677 static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1678 {
1679         PyObject *py_elements = NULL;
1680         struct ldb_message_element *el;
1681         int flags = 0;
1682         char *name = NULL;
1683         const char * const kwnames[] = { "elements", "flags", "name", NULL };
1684         PyLdbMessageElementObject *ret;
1685         TALLOC_CTX *mem_ctx;
1686
1687         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Ois",
1688                                          discard_const_p(char *, kwnames),
1689                                          &py_elements, &flags, &name))
1690                 return NULL;
1691
1692         mem_ctx = talloc_new(NULL);
1693         if (mem_ctx == NULL) {
1694                 PyErr_NoMemory();
1695                 return NULL;
1696         }
1697
1698         el = talloc_zero(mem_ctx, struct ldb_message_element);
1699
1700         if (py_elements != NULL) {
1701                 int i;
1702                 if (PyString_Check(py_elements)) {
1703                         el->num_values = 1;
1704                         el->values = talloc_array(el, struct ldb_val, 1);
1705                         el->values[0].length = PyString_Size(py_elements);
1706                         el->values[0].data = talloc_memdup(el, 
1707                                 (uint8_t *)PyString_AsString(py_elements), el->values[0].length);
1708                 } else if (PySequence_Check(py_elements)) {
1709                         el->num_values = PySequence_Size(py_elements);
1710                         el->values = talloc_array(el, struct ldb_val, el->num_values);
1711                         for (i = 0; i < el->num_values; i++) {
1712                                 PyObject *item = PySequence_GetItem(py_elements, i);
1713                                 if (!PyString_Check(item)) {
1714                                         PyErr_Format(PyExc_TypeError, 
1715                                                         "Expected string as element %d in list", 
1716                                                         i);
1717                                         talloc_free(mem_ctx);
1718                                         return NULL;
1719                                 }
1720                                 el->values[i].length = PyString_Size(item);
1721                                 el->values[i].data = talloc_memdup(el, 
1722                                         (uint8_t *)PyString_AsString(item), el->values[i].length);
1723                         }
1724                 } else {
1725                         PyErr_SetString(PyExc_TypeError, 
1726                                         "Expected string or list");
1727                         talloc_free(mem_ctx);
1728                         return NULL;
1729                 }
1730         }
1731
1732         el->flags = flags;
1733         el->name = talloc_strdup(el, name);
1734
1735         ret = (PyLdbMessageElementObject *)PyLdbMessageElement.tp_alloc(&PyLdbMessageElement, 0);
1736         if (ret == NULL) {
1737                 PyErr_NoMemory();
1738                 talloc_free(mem_ctx);
1739                 return NULL;
1740         }
1741
1742         ret->mem_ctx = mem_ctx;
1743         ret->el = el;
1744         return (PyObject *)ret;
1745 }
1746
1747 static PyObject *py_ldb_msg_element_repr(PyLdbMessageElementObject *self)
1748 {
1749         char *element_str = NULL;
1750         int i;
1751         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1752         PyObject *ret;
1753
1754         for (i = 0; i < el->num_values; i++) {
1755                 PyObject *o = py_ldb_msg_element_find(self, i);
1756                 if (element_str == NULL)
1757                         element_str = talloc_strdup(NULL, PyObject_REPR(o));
1758                 else
1759                         element_str = talloc_asprintf_append(element_str, ",%s", PyObject_REPR(o));
1760         }
1761
1762         ret = PyString_FromFormat("MessageElement([%s])", element_str);
1763
1764         talloc_free(element_str);
1765
1766         return ret;
1767 }
1768
1769 static PyObject *py_ldb_msg_element_str(PyLdbMessageElementObject *self)
1770 {
1771         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1772
1773         if (el->num_values == 1)
1774                 return PyString_FromStringAndSize((char *)el->values[0].data, el->values[0].length);
1775         else 
1776                 Py_RETURN_NONE;
1777 }
1778
1779 static void py_ldb_msg_element_dealloc(PyLdbMessageElementObject *self)
1780 {
1781         talloc_free(self->mem_ctx);
1782         self->ob_type->tp_free(self);
1783 }
1784
1785 PyTypeObject PyLdbMessageElement = {
1786         .tp_name = "MessageElement",
1787         .tp_basicsize = sizeof(PyLdbMessageElementObject),
1788         .tp_dealloc = (destructor)py_ldb_msg_element_dealloc,
1789         .tp_repr = (reprfunc)py_ldb_msg_element_repr,
1790         .tp_str = (reprfunc)py_ldb_msg_element_str,
1791         .tp_methods = py_ldb_msg_element_methods,
1792         .tp_compare = (cmpfunc)py_ldb_msg_element_cmp,
1793         .tp_iter = (getiterfunc)py_ldb_msg_element_iter,
1794         .tp_as_sequence = &py_ldb_msg_element_seq,
1795         .tp_new = py_ldb_msg_element_new,
1796         .tp_flags = Py_TPFLAGS_DEFAULT,
1797 };
1798
1799 static PyObject *py_ldb_msg_remove_attr(PyLdbMessageObject *self, PyObject *args)
1800 {
1801         char *name;
1802         if (!PyArg_ParseTuple(args, "s", &name))
1803                 return NULL;
1804
1805         ldb_msg_remove_attr(self->msg, name);
1806
1807         Py_RETURN_NONE;
1808 }
1809
1810 static PyObject *py_ldb_msg_keys(PyLdbMessageObject *self)
1811 {
1812         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1813         int i, j = 0;
1814         PyObject *obj = PyList_New(msg->num_elements+(msg->dn != NULL?1:0));
1815         if (msg->dn != NULL) {
1816                 PyList_SetItem(obj, j, PyString_FromString("dn"));
1817                 j++;
1818         }
1819         for (i = 0; i < msg->num_elements; i++) {
1820                 PyList_SetItem(obj, j, PyString_FromString(msg->elements[i].name));
1821                 j++;
1822         }
1823         return obj;
1824 }
1825
1826 static PyObject *py_ldb_msg_getitem_helper(PyLdbMessageObject *self, PyObject *py_name)
1827 {
1828         struct ldb_message_element *el;
1829         char *name;
1830         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1831         if (!PyString_Check(py_name)) {
1832                 PyErr_SetNone(PyExc_TypeError);
1833                 return NULL;
1834         }
1835         name = PyString_AsString(py_name);
1836         if (!strcmp(name, "dn"))
1837                 return PyLdbDn_FromDn(msg->dn);
1838         el = ldb_msg_find_element(msg, name);
1839         if (el == NULL) {
1840                 return NULL;
1841         }
1842         return (PyObject *)PyLdbMessageElement_FromMessageElement(el, msg);
1843 }
1844
1845 static PyObject *py_ldb_msg_getitem(PyLdbMessageObject *self, PyObject *py_name)
1846 {
1847         PyObject *ret = py_ldb_msg_getitem_helper(self, py_name);
1848         if (ret == NULL) {
1849                 PyErr_SetString(PyExc_KeyError, "No such element");
1850                 return NULL;
1851         }
1852         return ret;
1853 }
1854
1855 static PyObject *py_ldb_msg_get(PyLdbMessageObject *self, PyObject *args)
1856 {
1857         PyObject *name, *ret;
1858         if (!PyArg_ParseTuple(args, "O", &name))
1859                 return NULL;
1860
1861         ret = py_ldb_msg_getitem_helper(self, name);
1862         if (ret == NULL) {
1863                 if (PyErr_Occurred())
1864                         return NULL;
1865                 Py_RETURN_NONE;
1866         }
1867         return ret;
1868 }
1869
1870 static PyObject *py_ldb_msg_items(PyLdbMessageObject *self)
1871 {
1872         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1873         int i, j;
1874         PyObject *l = PyList_New(msg->num_elements + (msg->dn == NULL?0:1));
1875         j = 0;
1876         if (msg->dn != NULL) {
1877                 PyList_SetItem(l, 0, Py_BuildValue("(sO)", "dn", PyLdbDn_FromDn(msg->dn)));
1878                 j++;
1879         }
1880         for (i = 0; i < msg->num_elements; i++, j++) {
1881                 PyList_SetItem(l, j, Py_BuildValue("(sO)", msg->elements[i].name, PyLdbMessageElement_FromMessageElement(&msg->elements[i], self->msg)));
1882         }
1883         return l;
1884 }
1885
1886 static PyMethodDef py_ldb_msg_methods[] = { 
1887         { "keys", (PyCFunction)py_ldb_msg_keys, METH_NOARGS, NULL },
1888         { "remove", (PyCFunction)py_ldb_msg_remove_attr, METH_VARARGS, NULL },
1889         { "get", (PyCFunction)py_ldb_msg_get, METH_VARARGS, NULL },
1890         { "items", (PyCFunction)py_ldb_msg_items, METH_NOARGS, NULL },
1891         { NULL },
1892 };
1893
1894 static PyObject *py_ldb_msg_iter(PyLdbMessageObject *self)
1895 {
1896         PyObject *list, *iter;
1897
1898         list = py_ldb_msg_keys(self);
1899         iter = PyObject_GetIter(list);
1900         Py_DECREF(list);
1901         return iter;
1902 }
1903
1904 static int py_ldb_msg_setitem(PyLdbMessageObject *self, PyObject *name, PyObject *value)
1905 {
1906         char *attr_name;
1907
1908         if (!PyString_Check(name)) {
1909                 PyErr_SetNone(PyExc_TypeError);
1910                 return -1;
1911         }
1912         
1913         attr_name = PyString_AsString(name);
1914         if (value == NULL) {
1915                 /* delitem */
1916                 ldb_msg_remove_attr(self->msg, attr_name);
1917         } else {
1918                 struct ldb_message_element *el = PyObject_AsMessageElement(self->msg,
1919                                                                                         value, 0, attr_name);
1920                 if (el == NULL)
1921                         return -1;
1922                 ldb_msg_remove_attr(PyLdbMessage_AsMessage(self), attr_name);
1923                 ldb_msg_add(PyLdbMessage_AsMessage(self), el, el->flags);
1924         }
1925         return 0;
1926 }
1927
1928 static Py_ssize_t py_ldb_msg_length(PyLdbMessageObject *self)
1929 {
1930         return PyLdbMessage_AsMessage(self)->num_elements;
1931 }
1932
1933 static PyMappingMethods py_ldb_msg_mapping = {
1934         .mp_length = (lenfunc)py_ldb_msg_length,
1935         .mp_subscript = (binaryfunc)py_ldb_msg_getitem,
1936         .mp_ass_subscript = (objobjargproc)py_ldb_msg_setitem,
1937 };
1938
1939 static PyObject *py_ldb_msg_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1940 {
1941         const char * const kwnames[] = { "dn", NULL };
1942         struct ldb_message *ret;
1943         TALLOC_CTX *mem_ctx;
1944         PyObject *pydn = NULL;
1945         PyLdbMessageObject *py_ret;
1946
1947         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
1948                                          discard_const_p(char *, kwnames),
1949                                          &pydn))
1950                 return NULL;
1951
1952         mem_ctx = talloc_new(NULL);
1953         if (mem_ctx == NULL) {
1954                 PyErr_NoMemory();
1955                 return NULL;
1956         }
1957
1958         ret = ldb_msg_new(mem_ctx);
1959         if (ret == NULL) {
1960                 talloc_free(mem_ctx);
1961                 PyErr_NoMemory();
1962                 return NULL;
1963         }
1964
1965         if (pydn != NULL) {
1966                 struct ldb_dn *dn;
1967                 if (!PyObject_AsDn(NULL, pydn, NULL, &dn)) {
1968                         talloc_free(mem_ctx);
1969                         return NULL;
1970                 }
1971                 ret->dn = talloc_reference(ret, dn);
1972         }
1973
1974         py_ret = (PyLdbMessageObject *)type->tp_alloc(type, 0);
1975         if (py_ret == NULL) {
1976                 PyErr_NoMemory();
1977                 talloc_free(mem_ctx);
1978                 return NULL;
1979         }
1980
1981         py_ret->mem_ctx = mem_ctx;
1982         py_ret->msg = ret;
1983         return (PyObject *)py_ret;
1984 }
1985
1986 PyObject *PyLdbMessage_FromMessage(struct ldb_message *msg)
1987 {
1988         PyLdbMessageObject *ret;
1989
1990         ret = (PyLdbMessageObject *)PyLdbMessage.tp_alloc(&PyLdbMessage, 0);
1991         if (ret == NULL) {
1992                 PyErr_NoMemory();
1993                 return NULL;
1994         }
1995         ret->mem_ctx = talloc_new(NULL);
1996         ret->msg = talloc_reference(ret->mem_ctx, msg);
1997         return (PyObject *)ret;
1998 }
1999
2000 static PyObject *py_ldb_msg_get_dn(PyLdbMessageObject *self, void *closure)
2001 {
2002         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2003         return PyLdbDn_FromDn(msg->dn);
2004 }
2005
2006 static int py_ldb_msg_set_dn(PyLdbMessageObject *self, PyObject *value, void *closure)
2007 {
2008         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2009         if (!PyLdbDn_Check(value)) {
2010                 PyErr_SetNone(PyExc_TypeError);
2011                 return -1;
2012         }
2013
2014         msg->dn = talloc_reference(msg, PyLdbDn_AsDn(value));
2015         return 0;
2016 }
2017
2018 static PyGetSetDef py_ldb_msg_getset[] = {
2019         { discard_const_p(char, "dn"), (getter)py_ldb_msg_get_dn, (setter)py_ldb_msg_set_dn, NULL },
2020         { NULL }
2021 };
2022
2023 static PyObject *py_ldb_msg_repr(PyLdbMessageObject *self)
2024 {
2025         PyObject *dict = PyDict_New(), *ret;
2026         if (PyDict_Update(dict, (PyObject *)self) != 0)
2027                 return NULL;
2028         ret = PyString_FromFormat("Message(%s)", PyObject_REPR(dict));
2029         Py_DECREF(dict);
2030         return ret;
2031 }
2032
2033 static void py_ldb_msg_dealloc(PyLdbMessageObject *self)
2034 {
2035         talloc_free(self->mem_ctx);
2036         self->ob_type->tp_free(self);
2037 }
2038
2039 PyTypeObject PyLdbMessage = {
2040         .tp_name = "Message",
2041         .tp_methods = py_ldb_msg_methods,
2042         .tp_getset = py_ldb_msg_getset,
2043         .tp_as_mapping = &py_ldb_msg_mapping,
2044         .tp_basicsize = sizeof(PyLdbMessageObject),
2045         .tp_dealloc = (destructor)py_ldb_msg_dealloc,
2046         .tp_new = py_ldb_msg_new,
2047         .tp_repr = (reprfunc)py_ldb_msg_repr,
2048         .tp_flags = Py_TPFLAGS_DEFAULT,
2049         .tp_iter = (getiterfunc)py_ldb_msg_iter,
2050 };
2051
2052 PyObject *PyLdbTree_FromTree(struct ldb_parse_tree *tree)
2053 {
2054         PyLdbTreeObject *ret;
2055
2056         ret = (PyLdbTreeObject *)PyLdbTree.tp_alloc(&PyLdbTree, 0);
2057         if (ret == NULL) {
2058                 PyErr_NoMemory();
2059                 return NULL;
2060         }
2061
2062         ret->mem_ctx = talloc_new(NULL);
2063         ret->tree = talloc_reference(ret->mem_ctx, tree);
2064         return (PyObject *)ret;
2065 }
2066
2067 static void py_ldb_tree_dealloc(PyLdbTreeObject *self)
2068 {
2069         talloc_free(self->mem_ctx);
2070         self->ob_type->tp_free(self);
2071 }
2072
2073 PyTypeObject PyLdbTree = {
2074         .tp_name = "Tree",
2075         .tp_basicsize = sizeof(PyLdbTreeObject),
2076         .tp_dealloc = (destructor)py_ldb_tree_dealloc,
2077         .tp_flags = Py_TPFLAGS_DEFAULT,
2078 };
2079
2080 /* Ldb_module */
2081 static int py_module_search(struct ldb_module *mod, struct ldb_request *req)
2082 {
2083         PyObject *py_ldb = (PyObject *)mod->private_data;
2084         PyObject *py_result, *py_base, *py_attrs, *py_tree;
2085
2086         py_base = PyLdbDn_FromDn(req->op.search.base);
2087
2088         if (py_base == NULL)
2089                 return LDB_ERR_OPERATIONS_ERROR;
2090
2091         py_tree = PyLdbTree_FromTree(req->op.search.tree);
2092
2093         if (py_tree == NULL)
2094                 return LDB_ERR_OPERATIONS_ERROR;
2095
2096         if (req->op.search.attrs == NULL) {
2097                 py_attrs = Py_None;
2098         } else {
2099                 int i, len;
2100                 for (len = 0; req->op.search.attrs[len]; len++);
2101                 py_attrs = PyList_New(len);
2102                 for (i = 0; i < len; i++)
2103                         PyList_SetItem(py_attrs, i, PyString_FromString(req->op.search.attrs[i]));
2104         }
2105
2106         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "search"),
2107                                         discard_const_p(char, "OiOO"),
2108                                         py_base, req->op.search.scope, py_tree, py_attrs);
2109
2110         Py_DECREF(py_attrs);
2111         Py_DECREF(py_tree);
2112         Py_DECREF(py_base);
2113
2114         if (py_result == NULL) {
2115                 return LDB_ERR_PYTHON_EXCEPTION;
2116         }
2117
2118         req->op.search.res = PyLdbResult_AsResult(NULL, py_result);
2119         if (req->op.search.res == NULL) {
2120                 return LDB_ERR_PYTHON_EXCEPTION;
2121         }
2122
2123         Py_DECREF(py_result);
2124
2125         return LDB_SUCCESS;
2126 }
2127
2128 static int py_module_add(struct ldb_module *mod, struct ldb_request *req)
2129 {
2130         PyObject *py_ldb = (PyObject *)mod->private_data;
2131         PyObject *py_result, *py_msg;
2132
2133         py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.add.message));
2134
2135         if (py_msg == NULL) {
2136                 return LDB_ERR_OPERATIONS_ERROR;
2137         }
2138
2139         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "add"),
2140                                         discard_const_p(char, "O"),
2141                                         py_msg);
2142
2143         Py_DECREF(py_msg);
2144
2145         if (py_result == NULL) {
2146                 return LDB_ERR_PYTHON_EXCEPTION;
2147         }
2148
2149         Py_DECREF(py_result);
2150
2151         return LDB_SUCCESS;
2152 }
2153
2154 static int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
2155 {
2156         PyObject *py_ldb = (PyObject *)mod->private_data;
2157         PyObject *py_result, *py_msg;
2158
2159         py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.mod.message));
2160
2161         if (py_msg == NULL) {
2162                 return LDB_ERR_OPERATIONS_ERROR;
2163         }
2164
2165         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "modify"),
2166                                         discard_const_p(char, "O"),
2167                                         py_msg);
2168
2169         Py_DECREF(py_msg);
2170
2171         if (py_result == NULL) {
2172                 return LDB_ERR_PYTHON_EXCEPTION;
2173         }
2174
2175         Py_DECREF(py_result);
2176
2177         return LDB_SUCCESS;
2178 }
2179
2180 static int py_module_del(struct ldb_module *mod, struct ldb_request *req)
2181 {
2182         PyObject *py_ldb = (PyObject *)mod->private_data;
2183         PyObject *py_result, *py_dn;
2184
2185         py_dn = PyLdbDn_FromDn(req->op.del.dn);
2186
2187         if (py_dn == NULL)
2188                 return LDB_ERR_OPERATIONS_ERROR;
2189
2190         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "delete"),
2191                                         discard_const_p(char, "O"),
2192                                         py_dn);
2193
2194         if (py_result == NULL) {
2195                 return LDB_ERR_PYTHON_EXCEPTION;
2196         }
2197
2198         Py_DECREF(py_result);
2199
2200         return LDB_SUCCESS;
2201 }
2202
2203 static int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
2204 {
2205         PyObject *py_ldb = (PyObject *)mod->private_data;
2206         PyObject *py_result, *py_olddn, *py_newdn;
2207
2208         py_olddn = PyLdbDn_FromDn(req->op.rename.olddn);
2209
2210         if (py_olddn == NULL)
2211                 return LDB_ERR_OPERATIONS_ERROR;
2212
2213         py_newdn = PyLdbDn_FromDn(req->op.rename.newdn);
2214
2215         if (py_newdn == NULL)
2216                 return LDB_ERR_OPERATIONS_ERROR;
2217
2218         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "rename"),
2219                                         discard_const_p(char, "OO"),
2220                                         py_olddn, py_newdn);
2221
2222         Py_DECREF(py_olddn);
2223         Py_DECREF(py_newdn);
2224
2225         if (py_result == NULL) {
2226                 return LDB_ERR_PYTHON_EXCEPTION;
2227         }
2228
2229         Py_DECREF(py_result);
2230
2231         return LDB_SUCCESS;
2232 }
2233
2234 static int py_module_request(struct ldb_module *mod, struct ldb_request *req)
2235 {
2236         PyObject *py_ldb = (PyObject *)mod->private_data;
2237         PyObject *py_result;
2238
2239         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "request"),
2240                                         discard_const_p(char, ""));
2241
2242         return LDB_ERR_OPERATIONS_ERROR;
2243 }
2244
2245 static int py_module_extended(struct ldb_module *mod, struct ldb_request *req)
2246 {
2247         PyObject *py_ldb = (PyObject *)mod->private_data;
2248         PyObject *py_result;
2249
2250         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "extended"),
2251                                         discard_const_p(char, ""));
2252
2253         return LDB_ERR_OPERATIONS_ERROR;
2254 }
2255
2256 static int py_module_start_transaction(struct ldb_module *mod)
2257 {
2258         PyObject *py_ldb = (PyObject *)mod->private_data;
2259         PyObject *py_result;
2260
2261         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "start_transaction"),
2262                                         discard_const_p(char, ""));
2263
2264         if (py_result == NULL) {
2265                 return LDB_ERR_PYTHON_EXCEPTION;
2266         }
2267
2268         Py_DECREF(py_result);
2269
2270         return LDB_SUCCESS;
2271 }
2272
2273 static int py_module_end_transaction(struct ldb_module *mod)
2274 {
2275         PyObject *py_ldb = (PyObject *)mod->private_data;
2276         PyObject *py_result;
2277
2278         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "end_transaction"),
2279                                         discard_const_p(char, ""));
2280
2281         if (py_result == NULL) {
2282                 return LDB_ERR_PYTHON_EXCEPTION;
2283         }
2284
2285         Py_DECREF(py_result);
2286
2287         return LDB_SUCCESS;
2288 }
2289
2290 static int py_module_del_transaction(struct ldb_module *mod)
2291 {
2292         PyObject *py_ldb = (PyObject *)mod->private_data;
2293         PyObject *py_result;
2294
2295         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "del_transaction"),
2296                                         discard_const_p(char, ""));
2297
2298         if (py_result == NULL) {
2299                 return LDB_ERR_PYTHON_EXCEPTION;
2300         }
2301
2302         Py_DECREF(py_result);
2303
2304         return LDB_SUCCESS;
2305 }
2306
2307 static int py_module_destructor(struct ldb_module *mod)
2308 {
2309         Py_DECREF((PyObject *)mod->private_data);
2310         return 0;
2311 }
2312
2313 static int py_module_init(struct ldb_module *mod)
2314 {
2315         PyObject *py_class = (PyObject *)mod->ops->private_data;
2316         PyObject *py_result, *py_next, *py_ldb;
2317
2318         py_ldb = PyLdb_FromLdbContext(mod->ldb);
2319
2320         if (py_ldb == NULL)
2321                 return LDB_ERR_OPERATIONS_ERROR;
2322
2323         py_next = PyLdbModule_FromModule(mod->next);
2324
2325         if (py_next == NULL)
2326                 return LDB_ERR_OPERATIONS_ERROR;
2327
2328         py_result = PyObject_CallFunction(py_class, discard_const_p(char, "OO"),
2329                                           py_ldb, py_next);
2330
2331         if (py_result == NULL) {
2332                 return LDB_ERR_PYTHON_EXCEPTION;
2333         }
2334
2335         mod->private_data = py_result;
2336
2337         talloc_set_destructor(mod, py_module_destructor);
2338
2339         return ldb_next_init(mod);
2340 }
2341
2342 static PyObject *py_register_module(PyObject *module, PyObject *args)
2343 {
2344         int ret;
2345         struct ldb_module_ops *ops;
2346         PyObject *input;
2347
2348         if (!PyArg_ParseTuple(args, "O", &input))
2349                 return NULL;
2350
2351         ops = talloc_zero(talloc_autofree_context(), struct ldb_module_ops);
2352         if (ops == NULL) {
2353                 PyErr_NoMemory();
2354                 return NULL;
2355         }
2356
2357         ops->name = talloc_strdup(ops, PyString_AsString(PyObject_GetAttrString(input, discard_const_p(char, "name"))));
2358
2359         Py_INCREF(input);
2360         ops->private_data = input;
2361         ops->init_context = py_module_init;
2362         ops->search = py_module_search;
2363         ops->add = py_module_add;
2364         ops->modify = py_module_modify;
2365         ops->del = py_module_del;
2366         ops->rename = py_module_rename;
2367         ops->request = py_module_request;
2368         ops->extended = py_module_extended;
2369         ops->start_transaction = py_module_start_transaction;
2370         ops->end_transaction = py_module_end_transaction;
2371         ops->del_transaction = py_module_del_transaction;
2372
2373         ret = ldb_register_module(ops);
2374
2375         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
2376
2377         Py_RETURN_NONE;
2378 }
2379
2380 static PyObject *py_timestring(PyObject *module, PyObject *args)
2381 {
2382         time_t t;
2383         unsigned long val;
2384         char *tresult;
2385         PyObject *ret;
2386         if (!PyArg_ParseTuple(args, "l", &val))
2387                 return NULL;
2388         t = (time_t)val;
2389         tresult = ldb_timestring(NULL, t);
2390         ret = PyString_FromString(tresult);
2391         talloc_free(tresult);
2392         return ret;
2393 }
2394
2395 static PyObject *py_string_to_time(PyObject *module, PyObject *args)
2396 {
2397         char *str;
2398         if (!PyArg_ParseTuple(args, "s", &str))
2399                 return NULL;
2400
2401         return PyInt_FromLong(ldb_string_to_time(str));
2402 }
2403
2404 static PyObject *py_valid_attr_name(PyObject *self, PyObject *args)
2405 {
2406         char *name;
2407         if (!PyArg_ParseTuple(args, "s", &name))
2408                 return NULL;
2409         return PyBool_FromLong(ldb_valid_attr_name(name));
2410 }
2411
2412 static PyMethodDef py_ldb_global_methods[] = {
2413         { "register_module", py_register_module, METH_VARARGS, 
2414                 "S.register_module(module) -> None\n"
2415                 "Register a LDB module."},
2416         { "timestring", py_timestring, METH_VARARGS, 
2417                 "S.timestring(int) -> string\n"
2418                 "Generate a LDAP time string from a UNIX timestamp" },
2419         { "string_to_time", py_string_to_time, METH_VARARGS,
2420                 "S.string_to_time(string) -> int\n"
2421                 "Parse a LDAP time string into a UNIX timestamp." },
2422         { "valid_attr_name", py_valid_attr_name, METH_VARARGS,
2423                 "S.valid_attr_name(name) -> bool\n"
2424                 "Check whether the supplied name is a valid attribute name." },
2425         { "open", (PyCFunction)py_ldb_new, METH_VARARGS|METH_KEYWORDS,
2426                 NULL },
2427         { NULL }
2428 };
2429
2430 void initldb(void)
2431 {
2432         PyObject *m;
2433
2434         if (PyType_Ready(&PyLdbDn) < 0)
2435                 return;
2436
2437         if (PyType_Ready(&PyLdbMessage) < 0)
2438                 return;
2439
2440         if (PyType_Ready(&PyLdbMessageElement) < 0)
2441                 return;
2442
2443         if (PyType_Ready(&PyLdb) < 0)
2444                 return;
2445
2446         if (PyType_Ready(&PyLdbModule) < 0)
2447                 return;
2448
2449         if (PyType_Ready(&PyLdbTree) < 0)
2450                 return;
2451
2452         m = Py_InitModule3("ldb", py_ldb_global_methods, 
2453                 "An interface to LDB, a LDAP-like API that can either to talk an embedded database (TDB-based) or a standards-compliant LDAP server.");
2454         if (m == NULL)
2455                 return;
2456
2457         PyModule_AddObject(m, "SCOPE_DEFAULT", PyInt_FromLong(LDB_SCOPE_DEFAULT));
2458         PyModule_AddObject(m, "SCOPE_BASE", PyInt_FromLong(LDB_SCOPE_BASE));
2459         PyModule_AddObject(m, "SCOPE_ONELEVEL", PyInt_FromLong(LDB_SCOPE_ONELEVEL));
2460         PyModule_AddObject(m, "SCOPE_SUBTREE", PyInt_FromLong(LDB_SCOPE_SUBTREE));
2461
2462         PyModule_AddObject(m, "CHANGETYPE_NONE", PyInt_FromLong(LDB_CHANGETYPE_NONE));
2463         PyModule_AddObject(m, "CHANGETYPE_ADD", PyInt_FromLong(LDB_CHANGETYPE_ADD));
2464         PyModule_AddObject(m, "CHANGETYPE_DELETE", PyInt_FromLong(LDB_CHANGETYPE_DELETE));
2465         PyModule_AddObject(m, "CHANGETYPE_MODIFY", PyInt_FromLong(LDB_CHANGETYPE_MODIFY));
2466
2467         PyModule_AddObject(m, "FLAG_MOD_ADD", PyInt_FromLong(LDB_FLAG_MOD_ADD));
2468         PyModule_AddObject(m, "FLAG_MOD_REPLACE", PyInt_FromLong(LDB_FLAG_MOD_REPLACE));
2469         PyModule_AddObject(m, "FLAG_MOD_DELETE", PyInt_FromLong(LDB_FLAG_MOD_DELETE));
2470
2471         PyModule_AddObject(m, "SUCCESS", PyInt_FromLong(LDB_SUCCESS));
2472         PyModule_AddObject(m, "ERR_OPERATIONS_ERROR", PyInt_FromLong(LDB_ERR_OPERATIONS_ERROR));
2473         PyModule_AddObject(m, "ERR_PROTOCOL_ERROR", PyInt_FromLong(LDB_ERR_PROTOCOL_ERROR));
2474         PyModule_AddObject(m, "ERR_TIME_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_TIME_LIMIT_EXCEEDED));
2475         PyModule_AddObject(m, "ERR_SIZE_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_SIZE_LIMIT_EXCEEDED));
2476         PyModule_AddObject(m, "ERR_COMPARE_FALSE", PyInt_FromLong(LDB_ERR_COMPARE_FALSE));
2477         PyModule_AddObject(m, "ERR_COMPARE_TRUE", PyInt_FromLong(LDB_ERR_COMPARE_TRUE));
2478         PyModule_AddObject(m, "ERR_AUTH_METHOD_NOT_SUPPORTED", PyInt_FromLong(LDB_ERR_AUTH_METHOD_NOT_SUPPORTED));
2479         PyModule_AddObject(m, "ERR_STRONG_AUTH_REQUIRED", PyInt_FromLong(LDB_ERR_STRONG_AUTH_REQUIRED));
2480         PyModule_AddObject(m, "ERR_REFERRAL", PyInt_FromLong(LDB_ERR_REFERRAL));
2481         PyModule_AddObject(m, "ERR_ADMIN_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_ADMIN_LIMIT_EXCEEDED));
2482         PyModule_AddObject(m, "ERR_UNSUPPORTED_CRITICAL_EXTENSION", PyInt_FromLong(LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION));
2483         PyModule_AddObject(m, "ERR_CONFIDENTIALITY_REQUIRED", PyInt_FromLong(LDB_ERR_CONFIDENTIALITY_REQUIRED));
2484         PyModule_AddObject(m, "ERR_SASL_BIND_IN_PROGRESS", PyInt_FromLong(LDB_ERR_SASL_BIND_IN_PROGRESS));
2485         PyModule_AddObject(m, "ERR_NO_SUCH_ATTRIBUTE", PyInt_FromLong(LDB_ERR_NO_SUCH_ATTRIBUTE));
2486         PyModule_AddObject(m, "ERR_UNDEFINED_ATTRIBUTE_TYPE", PyInt_FromLong(LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE));
2487         PyModule_AddObject(m, "ERR_INAPPROPRIATE_MATCHING", PyInt_FromLong(LDB_ERR_INAPPROPRIATE_MATCHING));
2488         PyModule_AddObject(m, "ERR_CONSTRAINT_VIOLATION", PyInt_FromLong(LDB_ERR_CONSTRAINT_VIOLATION));
2489         PyModule_AddObject(m, "ERR_ATTRIBUTE_OR_VALUE_EXISTS", PyInt_FromLong(LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS));
2490         PyModule_AddObject(m, "ERR_INVALID_ATTRIBUTE_SYNTAX", PyInt_FromLong(LDB_ERR_INVALID_ATTRIBUTE_SYNTAX));
2491         PyModule_AddObject(m, "ERR_NO_SUCH_OBJECT", PyInt_FromLong(LDB_ERR_NO_SUCH_OBJECT));
2492         PyModule_AddObject(m, "ERR_ALIAS_PROBLEM", PyInt_FromLong(LDB_ERR_ALIAS_PROBLEM));
2493         PyModule_AddObject(m, "ERR_INVALID_DN_SYNTAX", PyInt_FromLong(LDB_ERR_INVALID_DN_SYNTAX));
2494         PyModule_AddObject(m, "ERR_ALIAS_DEREFERINCING_PROBLEM", PyInt_FromLong(LDB_ERR_ALIAS_DEREFERENCING_PROBLEM));
2495         PyModule_AddObject(m, "ERR_INAPPROPRIATE_AUTHENTICATION", PyInt_FromLong(LDB_ERR_INAPPROPRIATE_AUTHENTICATION));
2496         PyModule_AddObject(m, "ERR_INVALID_CREDENTIALS", PyInt_FromLong(LDB_ERR_INVALID_CREDENTIALS));
2497         PyModule_AddObject(m, "ERR_INSUFFICIENT_ACCESS_RIGHTS", PyInt_FromLong(LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS));
2498         PyModule_AddObject(m, "ERR_BUSY", PyInt_FromLong(LDB_ERR_BUSY));
2499         PyModule_AddObject(m, "ERR_UNAVAILABLE", PyInt_FromLong(LDB_ERR_UNAVAILABLE));
2500         PyModule_AddObject(m, "ERR_UNWILLING_TO_PERFORM", PyInt_FromLong(LDB_ERR_UNWILLING_TO_PERFORM));
2501         PyModule_AddObject(m, "ERR_LOOP_DETECT", PyInt_FromLong(LDB_ERR_LOOP_DETECT));
2502         PyModule_AddObject(m, "ERR_NAMING_VIOLATION", PyInt_FromLong(LDB_ERR_NAMING_VIOLATION));
2503         PyModule_AddObject(m, "ERR_OBJECT_CLASS_VIOLATION", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_VIOLATION));
2504         PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_NON_LEAF", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_NON_LEAF));
2505         PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_RDN", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_RDN));
2506         PyModule_AddObject(m, "ERR_ENTRY_ALREADY_EXISTS", PyInt_FromLong(LDB_ERR_ENTRY_ALREADY_EXISTS));
2507         PyModule_AddObject(m, "ERR_OBJECT_CLASS_MODS_PROHIBITED", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED));
2508         PyModule_AddObject(m, "ERR_AFFECTS_MULTIPLE_DSAS", PyInt_FromLong(LDB_ERR_AFFECTS_MULTIPLE_DSAS));
2509         PyModule_AddObject(m, "ERR_OTHER", PyInt_FromLong(LDB_ERR_OTHER));
2510
2511         PyModule_AddObject(m, "FLG_RDONLY", PyInt_FromLong(LDB_FLG_RDONLY));
2512         PyModule_AddObject(m, "FLG_NOSYNC", PyInt_FromLong(LDB_FLG_NOSYNC));
2513         PyModule_AddObject(m, "FLG_RECONNECT", PyInt_FromLong(LDB_FLG_RECONNECT));
2514         PyModule_AddObject(m, "FLG_NOMMAP", PyInt_FromLong(LDB_FLG_NOMMAP));
2515
2516
2517         PyModule_AddObject(m, "__docformat__", PyString_FromString("restructuredText"));
2518
2519         PyExc_LdbError = PyErr_NewException(discard_const_p(char, "_ldb.LdbError"), NULL, NULL);
2520         PyModule_AddObject(m, "LdbError", PyExc_LdbError);
2521
2522         Py_INCREF(&PyLdb);
2523         Py_INCREF(&PyLdbDn);
2524         Py_INCREF(&PyLdbModule);
2525         Py_INCREF(&PyLdbMessage);
2526         Py_INCREF(&PyLdbMessageElement);
2527         Py_INCREF(&PyLdbTree);
2528
2529         PyModule_AddObject(m, "Ldb", (PyObject *)&PyLdb);
2530         PyModule_AddObject(m, "Dn", (PyObject *)&PyLdbDn);
2531         PyModule_AddObject(m, "Message", (PyObject *)&PyLdbMessage);
2532         PyModule_AddObject(m, "MessageElement", (PyObject *)&PyLdbMessageElement);
2533         PyModule_AddObject(m, "Module", (PyObject *)&PyLdbModule);
2534         PyModule_AddObject(m, "Tree", (PyObject *)&PyLdbTree);
2535 }