ldb python bindungs - better use the "enum ldb_scope" for the search scope rather...
[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         if (!PyArg_ParseTuple(args, "O", &py_dn))
787                 return NULL;
788
789         ldb = PyLdb_AsLdbContext(self);
790
791         if (!PyObject_AsDn(NULL, py_dn, ldb, &dn))
792                 return NULL;
793
794         ret = ldb_delete(ldb, dn);
795         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
796
797         Py_RETURN_NONE;
798 }
799
800 static PyObject *py_ldb_rename(PyLdbObject *self, PyObject *args)
801 {
802         PyObject *py_dn1, *py_dn2;
803         struct ldb_dn *dn1, *dn2;
804         int ret;
805         struct ldb_context *ldb;
806         TALLOC_CTX *mem_ctx;
807         if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
808                 return NULL;
809
810         mem_ctx = talloc_new(NULL);
811         if (mem_ctx == NULL) {
812                 PyErr_NoMemory();
813                 return NULL;
814         }
815         ldb = PyLdb_AsLdbContext(self);
816         if (!PyObject_AsDn(mem_ctx, py_dn1, ldb, &dn1)) {
817                 talloc_free(mem_ctx);
818                 return NULL;
819         }
820
821         if (!PyObject_AsDn(mem_ctx, py_dn2, ldb, &dn2)) {
822                 talloc_free(mem_ctx);
823                 return NULL;
824         }
825
826         ret = ldb_rename(ldb, dn1, dn2);
827         talloc_free(mem_ctx);
828         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
829
830         Py_RETURN_NONE;
831 }
832
833 static PyObject *py_ldb_schema_attribute_remove(PyLdbObject *self, PyObject *args)
834 {
835         char *name;
836         if (!PyArg_ParseTuple(args, "s", &name))
837                 return NULL;
838
839         ldb_schema_attribute_remove(PyLdb_AsLdbContext(self), name);
840
841         Py_RETURN_NONE;
842 }
843
844 static PyObject *py_ldb_schema_attribute_add(PyLdbObject *self, PyObject *args)
845 {
846         char *attribute, *syntax;
847         unsigned int flags;
848         int ret;
849         if (!PyArg_ParseTuple(args, "sIs", &attribute, &flags, &syntax))
850                 return NULL;
851
852         ret = ldb_schema_attribute_add(PyLdb_AsLdbContext(self), attribute, flags, syntax);
853
854         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
855
856         Py_RETURN_NONE;
857 }
858
859 static PyObject *ldb_ldif_to_pyobject(struct ldb_ldif *ldif)
860 {
861         if (ldif == NULL) {
862                 Py_RETURN_NONE;
863         } else {
864         /* We don't want this attached to the 'ldb' any more */
865                 return Py_BuildValue(discard_const_p(char, "(iO)"),
866                                      ldif->changetype,
867                                      PyLdbMessage_FromMessage(ldif->msg));
868         }
869 }
870
871
872 static PyObject *py_ldb_write_ldif(PyLdbMessageObject *self, PyObject *args)
873 {
874         int changetype;
875         PyObject *py_msg;
876         struct ldb_ldif ldif;
877         PyObject *ret;
878         char *string;
879         TALLOC_CTX *mem_ctx;
880
881         if (!PyArg_ParseTuple(args, "Oi", &py_msg, &changetype))
882                 return NULL;
883
884         if (!PyLdbMessage_Check(py_msg)) {
885                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for msg");
886                 return NULL;
887         }
888
889         ldif.msg = PyLdbMessage_AsMessage(py_msg);
890         ldif.changetype = changetype;
891
892         mem_ctx = talloc_new(NULL);
893
894         string = ldb_ldif_write_string(PyLdb_AsLdbContext(self), mem_ctx, &ldif);
895         if (!string) {
896                 PyErr_SetString(PyExc_KeyError, "Failed to generate LDIF");
897                 return NULL;
898         }
899
900         ret = PyString_FromString(string);
901
902         talloc_free(mem_ctx);
903
904         return ret;
905 }
906
907 static PyObject *py_ldb_parse_ldif(PyLdbObject *self, PyObject *args)
908 {
909         PyObject *list;
910         struct ldb_ldif *ldif;
911         const char *s;
912
913         TALLOC_CTX *mem_ctx;
914
915         if (!PyArg_ParseTuple(args, "s", &s))
916                 return NULL;
917
918         mem_ctx = talloc_new(NULL);
919         if (!mem_ctx) {
920                 Py_RETURN_NONE;
921         }
922
923         list = PyList_New(0);
924         while (s && *s != '\0') {
925                 ldif = ldb_ldif_read_string(self->ldb_ctx, &s);
926                 talloc_steal(mem_ctx, ldif);
927                 if (ldif) {
928                         PyList_Append(list, ldb_ldif_to_pyobject(ldif));
929                 } else {
930                         PyErr_SetString(PyExc_ValueError, "unable to parse ldif string");
931                         talloc_free(mem_ctx);
932                         return NULL;
933                 }
934         }
935         talloc_free(mem_ctx); /* The pyobject already has a reference to the things it needs */
936         return PyObject_GetIter(list);
937 }
938
939 static PyObject *py_ldb_msg_diff(PyLdbObject *self, PyObject *args)
940 {
941         PyObject *py_msg_old;
942         PyObject *py_msg_new;
943         struct ldb_message *diff;
944         PyObject *py_ret;
945
946         if (!PyArg_ParseTuple(args, "OO", &py_msg_old, &py_msg_new))
947                 return NULL;
948
949         if (!PyLdbMessage_Check(py_msg_old)) {
950                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for old message");
951                 return NULL;
952         }
953
954         if (!PyLdbMessage_Check(py_msg_new)) {
955                 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for new message");
956                 return NULL;
957         }
958
959         diff = ldb_msg_diff(PyLdb_AsLdbContext(self), PyLdbMessage_AsMessage(py_msg_old), PyLdbMessage_AsMessage(py_msg_new));
960         if (!diff) {
961                 PyErr_SetString(PyExc_RuntimeError, "Failed to generate the Ldb Message diff");
962                 return NULL;
963         }
964
965         py_ret = PyLdbMessage_FromMessage(diff);
966
967         return py_ret;
968 }
969
970 static PyObject *py_ldb_schema_format_value(PyLdbObject *self, PyObject *args)
971 {
972         const struct ldb_schema_attribute *a;
973         struct ldb_val old_val;
974         struct ldb_val new_val;
975         TALLOC_CTX *mem_ctx;
976         PyObject *ret;
977         char *element_name;
978         PyObject *val;
979
980         if (!PyArg_ParseTuple(args, "sO", &element_name, &val))
981                 return NULL;
982
983         mem_ctx = talloc_new(NULL);
984
985         old_val.data = (uint8_t *)PyString_AsString(val);
986         old_val.length = PyString_Size(val);
987
988         a = ldb_schema_attribute_by_name(PyLdb_AsLdbContext(self), element_name);
989
990         if (a == NULL) {
991                 Py_RETURN_NONE;
992         }
993
994         if (a->syntax->ldif_write_fn(PyLdb_AsLdbContext(self), mem_ctx, &old_val, &new_val) != 0) {
995                 talloc_free(mem_ctx);
996                 Py_RETURN_NONE;
997         }
998
999         ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
1000
1001         talloc_free(mem_ctx);
1002
1003         return ret;
1004 }
1005
1006 static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwargs)
1007 {
1008         PyObject *py_base = Py_None;
1009         enum ldb_scope scope = LDB_SCOPE_DEFAULT;
1010         char *expr = NULL;
1011         PyObject *py_attrs = Py_None;
1012         PyObject *py_controls = Py_None;
1013         const char * const kwnames[] = { "base", "scope", "expression", "attrs", "controls", NULL };
1014         int ret;
1015         struct ldb_result *res;
1016         struct ldb_request *req;
1017         const char **attrs;
1018         struct ldb_context *ldb_ctx;
1019         struct ldb_control **parsed_controls;
1020         struct ldb_dn *base;
1021         PyObject *py_ret;
1022
1023         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OizOO",
1024                                          discard_const_p(char *, kwnames),
1025                                          &py_base, &scope, &expr, &py_attrs, &py_controls))
1026                 return NULL;
1027
1028         ldb_ctx = PyLdb_AsLdbContext(self);
1029
1030         if (py_attrs == Py_None) {
1031                 attrs = NULL;
1032         } else {
1033                 attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
1034                 if (attrs == NULL)
1035                         return NULL;
1036         }
1037
1038         if (py_base == Py_None) {
1039                 base = ldb_get_default_basedn(ldb_ctx);
1040         } else {
1041                 if (!PyObject_AsDn(ldb_ctx, py_base, ldb_ctx, &base)) {
1042                         talloc_free(attrs);
1043                         return NULL;
1044                 }
1045         }
1046
1047         if (py_controls == Py_None) {
1048                 parsed_controls = NULL;
1049         } else {
1050                 const char **controls = PyList_AsStringList(ldb_ctx, py_controls, "controls");
1051                 parsed_controls = ldb_parse_control_strings(ldb_ctx, ldb_ctx, controls);
1052                 talloc_free(controls);
1053         }
1054
1055         res = talloc_zero(ldb_ctx, struct ldb_result);
1056         if (res == NULL) {
1057                 PyErr_NoMemory();
1058                 talloc_free(attrs);
1059                 return NULL;
1060         }
1061
1062         ret = ldb_build_search_req(&req, ldb_ctx, ldb_ctx,
1063                                    base,
1064                                    scope,
1065                                    expr,
1066                                    attrs,
1067                                    parsed_controls,
1068                                    res,
1069                                    ldb_search_default_callback,
1070                                    NULL);
1071
1072         talloc_steal(req, attrs);
1073
1074         if (ret != LDB_SUCCESS) {
1075                 talloc_free(res);
1076                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1077                 return NULL;
1078         }
1079
1080         ret = ldb_request(ldb_ctx, req);
1081
1082         if (ret == LDB_SUCCESS) {
1083                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1084         }
1085
1086         talloc_free(req);
1087
1088         if (ret != LDB_SUCCESS) {
1089                 talloc_free(res);
1090                 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1091                 return NULL;
1092         }
1093
1094         py_ret = PyLdbResult_FromResult(res);
1095
1096         talloc_free(res);
1097
1098         return py_ret;
1099 }
1100
1101 static PyObject *py_ldb_get_opaque(PyLdbObject *self, PyObject *args)
1102 {
1103         char *name;
1104         void *data;
1105
1106         if (!PyArg_ParseTuple(args, "s", &name))
1107                 return NULL;
1108
1109         data = ldb_get_opaque(PyLdb_AsLdbContext(self), name);
1110
1111         if (data == NULL)
1112                 Py_RETURN_NONE;
1113
1114         /* FIXME: More interpretation */
1115
1116         return Py_True;
1117 }
1118
1119 static PyObject *py_ldb_set_opaque(PyLdbObject *self, PyObject *args)
1120 {
1121         char *name;
1122         PyObject *data;
1123
1124         if (!PyArg_ParseTuple(args, "sO", &name, &data))
1125                 return NULL;
1126
1127         /* FIXME: More interpretation */
1128
1129         ldb_set_opaque(PyLdb_AsLdbContext(self), name, data);
1130
1131         Py_RETURN_NONE;
1132 }
1133
1134 static PyObject *py_ldb_modules(PyLdbObject *self)
1135 {
1136         struct ldb_context *ldb = PyLdb_AsLdbContext(self);
1137         PyObject *ret = PyList_New(0);
1138         struct ldb_module *mod;
1139
1140         for (mod = ldb->modules; mod; mod = mod->next) {
1141                 PyList_Append(ret, PyLdbModule_FromModule(mod));
1142         }
1143
1144         return ret;
1145 }
1146
1147 static PyMethodDef py_ldb_methods[] = {
1148         { "set_debug", (PyCFunction)py_ldb_set_debug, METH_VARARGS, 
1149                 "S.set_debug(callback) -> None\n"
1150                 "Set callback for LDB debug messages.\n"
1151                 "The callback should accept a debug level and debug text." },
1152         { "set_create_perms", (PyCFunction)py_ldb_set_create_perms, METH_VARARGS, 
1153                 "S.set_create_perms(mode) -> None\n"
1154                 "Set mode to use when creating new LDB files." },
1155         { "set_modules_dir", (PyCFunction)py_ldb_set_modules_dir, METH_VARARGS,
1156                 "S.set_modules_dir(path) -> None\n"
1157                 "Set path LDB should search for modules" },
1158         { "transaction_start", (PyCFunction)py_ldb_transaction_start, METH_NOARGS, 
1159                 "S.transaction_start() -> None\n"
1160                 "Start a new transaction." },
1161         { "transaction_commit", (PyCFunction)py_ldb_transaction_commit, METH_NOARGS, 
1162                 "S.transaction_commit() -> None\n"
1163                 "commit a new transaction." },
1164         { "transaction_cancel", (PyCFunction)py_ldb_transaction_cancel, METH_NOARGS, 
1165                 "S.transaction_cancel() -> None\n"
1166                 "cancel a new transaction." },
1167         { "setup_wellknown_attributes", (PyCFunction)py_ldb_setup_wellknown_attributes, METH_NOARGS, 
1168                 NULL },
1169         { "get_root_basedn", (PyCFunction)py_ldb_get_root_basedn, METH_NOARGS,
1170                 NULL },
1171         { "get_schema_basedn", (PyCFunction)py_ldb_get_schema_basedn, METH_NOARGS,
1172                 NULL },
1173         { "get_default_basedn", (PyCFunction)py_ldb_get_default_basedn, METH_NOARGS,
1174                 NULL },
1175         { "get_config_basedn", (PyCFunction)py_ldb_get_config_basedn, METH_NOARGS,
1176                 NULL },
1177         { "connect", (PyCFunction)py_ldb_connect, METH_VARARGS|METH_KEYWORDS, 
1178                 "S.connect(url, flags=0, options=None) -> None\n"
1179                 "Connect to a LDB URL." },
1180         { "modify", (PyCFunction)py_ldb_modify, METH_VARARGS, 
1181                 "S.modify(message) -> None\n"
1182                 "Modify an entry." },
1183         { "add", (PyCFunction)py_ldb_add, METH_VARARGS, 
1184                 "S.add(message) -> None\n"
1185                 "Add an entry." },
1186         { "delete", (PyCFunction)py_ldb_delete, METH_VARARGS,
1187                 "S.delete(dn) -> None\n"
1188                 "Remove an entry." },
1189         { "rename", (PyCFunction)py_ldb_rename, METH_VARARGS,
1190                 "S.rename(old_dn, new_dn) -> None\n"
1191                 "Rename an entry." },
1192         { "search", (PyCFunction)py_ldb_search, METH_VARARGS|METH_KEYWORDS,
1193                 "S.search(base=None, scope=None, expression=None, attrs=None, controls=None) -> msgs\n"
1194                 "Search in a database.\n"
1195                 "\n"
1196                 ":param base: Optional base DN to search\n"
1197                 ":param scope: Search scope (SCOPE_BASE, SCOPE_ONELEVEL or SCOPE_SUBTREE)\n"
1198                 ":param expression: Optional search expression\n"
1199                 ":param attrs: Attributes to return (defaults to all)\n"
1200                 ":param controls: Optional list of controls\n"
1201                 ":return: Iterator over Message objects\n"
1202         },
1203         { "schema_attribute_remove", (PyCFunction)py_ldb_schema_attribute_remove, METH_VARARGS,
1204                 NULL },
1205         { "schema_attribute_add", (PyCFunction)py_ldb_schema_attribute_add, METH_VARARGS,
1206                 NULL },
1207         { "schema_format_value", (PyCFunction)py_ldb_schema_format_value, METH_VARARGS,
1208                 NULL },
1209         { "parse_ldif", (PyCFunction)py_ldb_parse_ldif, METH_VARARGS,
1210                 "S.parse_ldif(ldif) -> iter(messages)\n"
1211                 "Parse a string formatted using LDIF." },
1212         { "write_ldif", (PyCFunction)py_ldb_write_ldif, METH_VARARGS,
1213                 "S.write_ldif(message, changetype) -> ldif\n"
1214                 "Print the message as a string formatted using LDIF." },
1215         { "msg_diff", (PyCFunction)py_ldb_msg_diff, METH_VARARGS,
1216                 "S.msg_diff(Message) -> Message\n"
1217                 "Return an LDB Message of the difference between two Message objects." },
1218         { "get_opaque", (PyCFunction)py_ldb_get_opaque, METH_VARARGS,
1219                 "S.get_opaque(name) -> value\n"
1220                 "Get an opaque value set on this LDB connection. \n"
1221                 ":note: The returned value may not be useful in Python."
1222         },
1223         { "set_opaque", (PyCFunction)py_ldb_set_opaque, METH_VARARGS,
1224                 "S.set_opaque(name, value) -> None\n"
1225                 "Set an opaque value on this LDB connection. \n"
1226                 ":note: Passing incorrect values may cause crashes." },
1227         { "modules", (PyCFunction)py_ldb_modules, METH_NOARGS,
1228                 "S.modules() -> list\n"
1229                 "Return the list of modules on this LDB connection " },
1230         { NULL },
1231 };
1232
1233 PyObject *PyLdbModule_FromModule(struct ldb_module *mod)
1234 {
1235         PyLdbModuleObject *ret;
1236
1237         ret = (PyLdbModuleObject *)PyLdbModule.tp_alloc(&PyLdbModule, 0);
1238         if (ret == NULL) {
1239                 PyErr_NoMemory();
1240                 return NULL;
1241         }
1242         ret->mem_ctx = talloc_new(NULL);
1243         ret->mod = talloc_reference(ret->mem_ctx, mod);
1244         return (PyObject *)ret;
1245 }
1246
1247 static PyObject *py_ldb_get_firstmodule(PyLdbObject *self, void *closure)
1248 {
1249         return PyLdbModule_FromModule(PyLdb_AsLdbContext(self)->modules);
1250 }
1251
1252 static PyGetSetDef py_ldb_getset[] = {
1253         { discard_const_p(char, "firstmodule"), (getter)py_ldb_get_firstmodule, NULL, NULL },
1254         { NULL }
1255 };
1256
1257 static int py_ldb_contains(PyLdbObject *self, PyObject *obj)
1258 {
1259         struct ldb_context *ldb_ctx = PyLdb_AsLdbContext(self);
1260         struct ldb_dn *dn;
1261         struct ldb_result *result;
1262         int ret;
1263         int count;
1264
1265         if (!PyObject_AsDn(ldb_ctx, obj, ldb_ctx, &dn))
1266                 return -1;
1267
1268         ret = ldb_search(ldb_ctx, ldb_ctx, &result, dn, LDB_SCOPE_BASE, NULL, NULL);
1269         if (ret != LDB_SUCCESS) {
1270                 PyErr_SetLdbError(PyExc_LdbError, ret, ldb_ctx);
1271                 return -1;
1272         }
1273
1274         count = result->count;
1275
1276         talloc_free(result);
1277
1278         return count;
1279 }
1280
1281 static PySequenceMethods py_ldb_seq = {
1282         .sq_contains = (objobjproc)py_ldb_contains,
1283 };
1284
1285 PyObject *PyLdb_FromLdbContext(struct ldb_context *ldb_ctx)
1286 {
1287         PyLdbObject *ret;
1288
1289         ret = (PyLdbObject *)PyLdb.tp_alloc(&PyLdb, 0);
1290         if (ret == NULL) {
1291                 PyErr_NoMemory();
1292                 return NULL;
1293         }
1294         ret->mem_ctx = talloc_new(NULL);
1295         ret->ldb_ctx = talloc_reference(ret->mem_ctx, ldb_ctx);
1296         return (PyObject *)ret;
1297 }
1298
1299 static void py_ldb_dealloc(PyLdbObject *self)
1300 {
1301         talloc_free(self->mem_ctx);
1302         self->ob_type->tp_free(self);
1303 }
1304
1305 PyTypeObject PyLdb = {
1306         .tp_name = "Ldb",
1307         .tp_methods = py_ldb_methods,
1308         .tp_repr = (reprfunc)py_ldb_repr,
1309         .tp_new = py_ldb_new,
1310         .tp_init = (initproc)py_ldb_init,
1311         .tp_dealloc = (destructor)py_ldb_dealloc,
1312         .tp_getset = py_ldb_getset,
1313         .tp_getattro = PyObject_GenericGetAttr,
1314         .tp_basicsize = sizeof(PyLdbObject),
1315         .tp_doc = "Connection to a LDB database.",
1316         .tp_as_sequence = &py_ldb_seq,
1317         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1318 };
1319
1320 static PyObject *py_ldb_module_repr(PyLdbModuleObject *self)
1321 {
1322         return PyString_FromFormat("<ldb module '%s'>", PyLdbModule_AsModule(self)->ops->name);
1323 }
1324
1325 static PyObject *py_ldb_module_str(PyLdbModuleObject *self)
1326 {
1327         return PyString_FromString(PyLdbModule_AsModule(self)->ops->name);
1328 }
1329
1330 static PyObject *py_ldb_module_start_transaction(PyLdbModuleObject *self)
1331 {
1332         PyLdbModule_AsModule(self)->ops->start_transaction(PyLdbModule_AsModule(self));
1333         Py_RETURN_NONE;
1334 }
1335
1336 static PyObject *py_ldb_module_end_transaction(PyLdbModuleObject *self)
1337 {
1338         PyLdbModule_AsModule(self)->ops->end_transaction(PyLdbModule_AsModule(self));
1339         Py_RETURN_NONE;
1340 }
1341
1342 static PyObject *py_ldb_module_del_transaction(PyLdbModuleObject *self)
1343 {
1344         PyLdbModule_AsModule(self)->ops->del_transaction(PyLdbModule_AsModule(self));
1345         Py_RETURN_NONE;
1346 }
1347
1348 static PyObject *py_ldb_module_search(PyLdbModuleObject *self, PyObject *args, PyObject *kwargs)
1349 {
1350         PyObject *py_base, *py_tree, *py_attrs, *py_ret;
1351         int ret;
1352         enum ldb_scope scope;
1353         struct ldb_request *req;
1354         const char * const kwnames[] = { "base", "scope", "tree", "attrs", NULL };
1355         struct ldb_module *mod;
1356         const char * const*attrs;
1357
1358         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OiOO",
1359                                          discard_const_p(char *, kwnames),
1360                                          &py_base, &scope, &py_tree, &py_attrs))
1361                 return NULL;
1362
1363         mod = self->mod;
1364
1365         if (py_attrs == Py_None) {
1366                 attrs = NULL;
1367         } else {
1368                 attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
1369                 if (attrs == NULL)
1370                         return NULL;
1371         }
1372
1373         ret = ldb_build_search_req(&req, mod->ldb, NULL, PyLdbDn_AsDn(py_base), 
1374                              scope, NULL /* expr */, attrs,
1375                              NULL /* controls */, NULL, NULL, NULL);
1376
1377         talloc_steal(req, attrs);
1378
1379         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1380
1381         req->op.search.res = NULL;
1382
1383         ret = mod->ops->search(mod, req);
1384
1385         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1386
1387         py_ret = PyLdbResult_FromResult(req->op.search.res);
1388
1389         talloc_free(req);
1390
1391         return py_ret;  
1392 }
1393
1394
1395 static PyObject *py_ldb_module_add(PyLdbModuleObject *self, PyObject *args)
1396 {
1397         struct ldb_request *req;
1398         PyObject *py_message;
1399         int ret;
1400         struct ldb_module *mod;
1401
1402         if (!PyArg_ParseTuple(args, "O", &py_message))
1403                 return NULL;
1404
1405         req = talloc_zero(NULL, struct ldb_request);
1406         req->operation = LDB_ADD;
1407         req->op.add.message = PyLdbMessage_AsMessage(py_message);
1408
1409         mod = PyLdbModule_AsModule(self);
1410         ret = mod->ops->add(mod, req);
1411
1412         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1413
1414         Py_RETURN_NONE;
1415 }
1416
1417 static PyObject *py_ldb_module_modify(PyLdbModuleObject *self, PyObject *args) 
1418 {
1419         int ret;
1420         struct ldb_request *req;
1421         PyObject *py_message;
1422         struct ldb_module *mod;
1423
1424         if (!PyArg_ParseTuple(args, "O", &py_message))
1425                 return NULL;
1426
1427         req = talloc_zero(NULL, struct ldb_request);
1428         req->operation = LDB_MODIFY;
1429         req->op.mod.message = PyLdbMessage_AsMessage(py_message);
1430
1431         mod = PyLdbModule_AsModule(self);
1432         ret = mod->ops->modify(mod, req);
1433
1434         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1435
1436         Py_RETURN_NONE;
1437 }
1438
1439 static PyObject *py_ldb_module_delete(PyLdbModuleObject *self, PyObject *args) 
1440 {
1441         int ret;
1442         struct ldb_request *req;
1443         PyObject *py_dn;
1444
1445         if (!PyArg_ParseTuple(args, "O", &py_dn))
1446                 return NULL;
1447
1448         req = talloc_zero(NULL, struct ldb_request);
1449         req->operation = LDB_DELETE;
1450         req->op.del.dn = PyLdbDn_AsDn(py_dn);
1451
1452         ret = PyLdbModule_AsModule(self)->ops->del(PyLdbModule_AsModule(self), req);
1453
1454         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
1455
1456         Py_RETURN_NONE;
1457 }
1458
1459 static PyObject *py_ldb_module_rename(PyLdbModuleObject *self, PyObject *args)
1460 {
1461         int ret;
1462         struct ldb_request *req;
1463         PyObject *py_dn1, *py_dn2;
1464
1465         if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
1466                 return NULL;
1467
1468         req = talloc_zero(NULL, struct ldb_request);
1469
1470         req->operation = LDB_RENAME;
1471         req->op.rename.olddn = PyLdbDn_AsDn(py_dn1);
1472         req->op.rename.newdn = PyLdbDn_AsDn(py_dn2);
1473
1474         ret = PyLdbModule_AsModule(self)->ops->rename(PyLdbModule_AsModule(self), req);
1475
1476         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
1477
1478         Py_RETURN_NONE;
1479 }
1480
1481 static PyMethodDef py_ldb_module_methods[] = {
1482         { "search", (PyCFunction)py_ldb_module_search, METH_VARARGS|METH_KEYWORDS, NULL },
1483         { "add", (PyCFunction)py_ldb_module_add, METH_VARARGS, NULL },
1484         { "modify", (PyCFunction)py_ldb_module_modify, METH_VARARGS, NULL },
1485         { "rename", (PyCFunction)py_ldb_module_rename, METH_VARARGS, NULL },
1486         { "delete", (PyCFunction)py_ldb_module_delete, METH_VARARGS, NULL },
1487         { "start_transaction", (PyCFunction)py_ldb_module_start_transaction, METH_NOARGS, NULL },
1488         { "end_transaction", (PyCFunction)py_ldb_module_end_transaction, METH_NOARGS, NULL },
1489         { "del_transaction", (PyCFunction)py_ldb_module_del_transaction, METH_NOARGS, NULL },
1490         { NULL },
1491 };
1492
1493 static void py_ldb_module_dealloc(PyLdbModuleObject *self)
1494 {
1495         talloc_free(self->mem_ctx);
1496         self->ob_type->tp_free(self);
1497 }
1498
1499 PyTypeObject PyLdbModule = {
1500         .tp_name = "LdbModule",
1501         .tp_methods = py_ldb_module_methods,
1502         .tp_repr = (reprfunc)py_ldb_module_repr,
1503         .tp_str = (reprfunc)py_ldb_module_str,
1504         .tp_basicsize = sizeof(PyLdbModuleObject),
1505         .tp_dealloc = (destructor)py_ldb_module_dealloc,
1506         .tp_flags = Py_TPFLAGS_DEFAULT,
1507 };
1508
1509
1510 /**
1511  * Create a ldb_message_element from a Python object.
1512  *
1513  * This will accept any sequence objects that contains strings, or 
1514  * a string object.
1515  *
1516  * A reference to set_obj will be borrowed. 
1517  *
1518  * @param mem_ctx Memory context
1519  * @param set_obj Python object to convert
1520  * @param flags ldb_message_element flags to set
1521  * @param attr_name Name of the attribute
1522  * @return New ldb_message_element, allocated as child of mem_ctx
1523  */
1524 struct ldb_message_element *PyObject_AsMessageElement(TALLOC_CTX *mem_ctx,
1525                                                                                            PyObject *set_obj, int flags,
1526                                                                                            const char *attr_name)
1527 {
1528         struct ldb_message_element *me;
1529
1530         if (PyLdbMessageElement_Check(set_obj))
1531                 return talloc_reference(mem_ctx, 
1532                                                                 PyLdbMessageElement_AsMessageElement(set_obj));
1533
1534         me = talloc(mem_ctx, struct ldb_message_element);
1535
1536         me->name = talloc_strdup(me, attr_name);
1537         me->flags = flags;
1538         if (PyString_Check(set_obj)) {
1539                 me->num_values = 1;
1540                 me->values = talloc_array(me, struct ldb_val, me->num_values);
1541                 me->values[0].length = PyString_Size(set_obj);
1542                 me->values[0].data = talloc_memdup(me, 
1543                         (uint8_t *)PyString_AsString(set_obj), me->values[0].length);
1544         } else if (PySequence_Check(set_obj)) {
1545                 int i;
1546                 me->num_values = PySequence_Size(set_obj);
1547                 me->values = talloc_array(me, struct ldb_val, me->num_values);
1548                 for (i = 0; i < me->num_values; i++) {
1549                         PyObject *obj = PySequence_GetItem(set_obj, i);
1550
1551                         me->values[i].length = PyString_Size(obj);
1552                         me->values[i].data = talloc_memdup(me, 
1553                                 (uint8_t *)PyString_AsString(obj), me->values[i].length);
1554                 }
1555         } else {
1556                 talloc_free(me);
1557                 me = NULL;
1558         }
1559
1560         return me;
1561 }
1562
1563
1564 static PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx, 
1565                                                                  struct ldb_message_element *me)
1566 {
1567         int i;
1568         PyObject *result;
1569
1570         /* Python << 2.5 doesn't have PySet_New and PySet_Add. */
1571         result = PyList_New(me->num_values);
1572
1573         for (i = 0; i < me->num_values; i++) {
1574                 PyList_SetItem(result, i,
1575                         PyObject_FromLdbValue(ldb_ctx, me, &me->values[i]));
1576         }
1577
1578         return result;
1579 }
1580
1581 static PyObject *py_ldb_msg_element_get(PyLdbMessageElementObject *self, PyObject *args)
1582 {
1583         int i;
1584         if (!PyArg_ParseTuple(args, "i", &i))
1585                 return NULL;
1586         if (i < 0 || i >= PyLdbMessageElement_AsMessageElement(self)->num_values)
1587                 Py_RETURN_NONE;
1588
1589         return PyObject_FromLdbValue(NULL, PyLdbMessageElement_AsMessageElement(self), 
1590                                                                  &(PyLdbMessageElement_AsMessageElement(self)->values[i]));
1591 }
1592
1593 static PyObject *py_ldb_msg_element_flags(PyLdbMessageElementObject *self, PyObject *args)
1594 {
1595         struct ldb_message_element *el;
1596
1597         el = PyLdbMessageElement_AsMessageElement(self);
1598         return PyInt_FromLong(el->flags);
1599 }
1600
1601 static PyObject *py_ldb_msg_element_set_flags(PyLdbMessageElementObject *self, PyObject *args)
1602 {
1603         int flags;
1604         struct ldb_message_element *el;
1605         if (!PyArg_ParseTuple(args, "i", &flags))
1606                 return NULL;
1607
1608         el = PyLdbMessageElement_AsMessageElement(self);
1609         el->flags = flags;
1610         Py_RETURN_NONE;
1611 }
1612
1613 static PyMethodDef py_ldb_msg_element_methods[] = {
1614         { "get", (PyCFunction)py_ldb_msg_element_get, METH_VARARGS, NULL },
1615         { "set_flags", (PyCFunction)py_ldb_msg_element_set_flags, METH_VARARGS, NULL },
1616         { "flags", (PyCFunction)py_ldb_msg_element_flags, METH_NOARGS, NULL },
1617         { NULL },
1618 };
1619
1620 static Py_ssize_t py_ldb_msg_element_len(PyLdbMessageElementObject *self)
1621 {
1622         return PyLdbMessageElement_AsMessageElement(self)->num_values;
1623 }
1624
1625 static PyObject *py_ldb_msg_element_find(PyLdbMessageElementObject *self, Py_ssize_t idx)
1626 {
1627         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1628         if (idx < 0 || idx >= el->num_values) {
1629                 PyErr_SetString(PyExc_IndexError, "Out of range");
1630                 return NULL;
1631         }
1632         return PyString_FromStringAndSize((char *)el->values[idx].data, el->values[idx].length);
1633 }
1634
1635 static PySequenceMethods py_ldb_msg_element_seq = {
1636         .sq_length = (lenfunc)py_ldb_msg_element_len,
1637         .sq_item = (ssizeargfunc)py_ldb_msg_element_find,
1638 };
1639
1640 static int py_ldb_msg_element_cmp(PyLdbMessageElementObject *self, PyLdbMessageElementObject *other)
1641 {
1642         return ldb_msg_element_compare(PyLdbMessageElement_AsMessageElement(self), 
1643                                                                    PyLdbMessageElement_AsMessageElement(other));
1644 }
1645
1646 static PyObject *py_ldb_msg_element_iter(PyLdbMessageElementObject *self)
1647 {
1648         return PyObject_GetIter(ldb_msg_element_to_set(NULL, PyLdbMessageElement_AsMessageElement(self)));
1649 }
1650
1651 PyObject *PyLdbMessageElement_FromMessageElement(struct ldb_message_element *el, TALLOC_CTX *mem_ctx)
1652 {
1653         PyLdbMessageElementObject *ret;
1654         ret = (PyLdbMessageElementObject *)PyLdbMessageElement.tp_alloc(&PyLdbMessageElement, 0);
1655         if (ret == NULL) {
1656                 PyErr_NoMemory();
1657                 return NULL;
1658         }
1659         ret->mem_ctx = talloc_new(NULL);
1660         if (talloc_reference(ret->mem_ctx, mem_ctx) == NULL) {
1661                 PyErr_NoMemory();
1662                 return NULL;
1663         }
1664         ret->el = el;
1665         return (PyObject *)ret;
1666 }
1667
1668 static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1669 {
1670         PyObject *py_elements = NULL;
1671         struct ldb_message_element *el;
1672         int flags = 0;
1673         char *name = NULL;
1674         const char * const kwnames[] = { "elements", "flags", "name", NULL };
1675         PyLdbMessageElementObject *ret;
1676         TALLOC_CTX *mem_ctx;
1677
1678         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Ois",
1679                                          discard_const_p(char *, kwnames),
1680                                          &py_elements, &flags, &name))
1681                 return NULL;
1682
1683         mem_ctx = talloc_new(NULL);
1684         if (mem_ctx == NULL) {
1685                 PyErr_NoMemory();
1686                 return NULL;
1687         }
1688
1689         el = talloc_zero(mem_ctx, struct ldb_message_element);
1690
1691         if (py_elements != NULL) {
1692                 int i;
1693                 if (PyString_Check(py_elements)) {
1694                         el->num_values = 1;
1695                         el->values = talloc_array(el, struct ldb_val, 1);
1696                         el->values[0].length = PyString_Size(py_elements);
1697                         el->values[0].data = talloc_memdup(el, 
1698                                 (uint8_t *)PyString_AsString(py_elements), el->values[0].length);
1699                 } else if (PySequence_Check(py_elements)) {
1700                         el->num_values = PySequence_Size(py_elements);
1701                         el->values = talloc_array(el, struct ldb_val, el->num_values);
1702                         for (i = 0; i < el->num_values; i++) {
1703                                 PyObject *item = PySequence_GetItem(py_elements, i);
1704                                 if (!PyString_Check(item)) {
1705                                         PyErr_Format(PyExc_TypeError, 
1706                                                         "Expected string as element %d in list", 
1707                                                         i);
1708                                         talloc_free(mem_ctx);
1709                                         return NULL;
1710                                 }
1711                                 el->values[i].length = PyString_Size(item);
1712                                 el->values[i].data = talloc_memdup(el, 
1713                                         (uint8_t *)PyString_AsString(item), el->values[i].length);
1714                         }
1715                 } else {
1716                         PyErr_SetString(PyExc_TypeError, 
1717                                         "Expected string or list");
1718                         talloc_free(mem_ctx);
1719                         return NULL;
1720                 }
1721         }
1722
1723         el->flags = flags;
1724         el->name = talloc_strdup(el, name);
1725
1726         ret = (PyLdbMessageElementObject *)PyLdbMessageElement.tp_alloc(&PyLdbMessageElement, 0);
1727         if (ret == NULL) {
1728                 PyErr_NoMemory();
1729                 talloc_free(mem_ctx);
1730                 return NULL;
1731         }
1732
1733         ret->mem_ctx = mem_ctx;
1734         ret->el = el;
1735         return (PyObject *)ret;
1736 }
1737
1738 static PyObject *py_ldb_msg_element_repr(PyLdbMessageElementObject *self)
1739 {
1740         char *element_str = NULL;
1741         int i;
1742         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1743         PyObject *ret;
1744
1745         for (i = 0; i < el->num_values; i++) {
1746                 PyObject *o = py_ldb_msg_element_find(self, i);
1747                 if (element_str == NULL)
1748                         element_str = talloc_strdup(NULL, PyObject_REPR(o));
1749                 else
1750                         element_str = talloc_asprintf_append(element_str, ",%s", PyObject_REPR(o));
1751         }
1752
1753         ret = PyString_FromFormat("MessageElement([%s])", element_str);
1754
1755         talloc_free(element_str);
1756
1757         return ret;
1758 }
1759
1760 static PyObject *py_ldb_msg_element_str(PyLdbMessageElementObject *self)
1761 {
1762         struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1763
1764         if (el->num_values == 1)
1765                 return PyString_FromStringAndSize((char *)el->values[0].data, el->values[0].length);
1766         else 
1767                 Py_RETURN_NONE;
1768 }
1769
1770 static void py_ldb_msg_element_dealloc(PyLdbMessageElementObject *self)
1771 {
1772         talloc_free(self->mem_ctx);
1773         self->ob_type->tp_free(self);
1774 }
1775
1776 PyTypeObject PyLdbMessageElement = {
1777         .tp_name = "MessageElement",
1778         .tp_basicsize = sizeof(PyLdbMessageElementObject),
1779         .tp_dealloc = (destructor)py_ldb_msg_element_dealloc,
1780         .tp_repr = (reprfunc)py_ldb_msg_element_repr,
1781         .tp_str = (reprfunc)py_ldb_msg_element_str,
1782         .tp_methods = py_ldb_msg_element_methods,
1783         .tp_compare = (cmpfunc)py_ldb_msg_element_cmp,
1784         .tp_iter = (getiterfunc)py_ldb_msg_element_iter,
1785         .tp_as_sequence = &py_ldb_msg_element_seq,
1786         .tp_new = py_ldb_msg_element_new,
1787         .tp_flags = Py_TPFLAGS_DEFAULT,
1788 };
1789
1790 static PyObject *py_ldb_msg_remove_attr(PyLdbMessageObject *self, PyObject *args)
1791 {
1792         char *name;
1793         if (!PyArg_ParseTuple(args, "s", &name))
1794                 return NULL;
1795
1796         ldb_msg_remove_attr(self->msg, name);
1797
1798         Py_RETURN_NONE;
1799 }
1800
1801 static PyObject *py_ldb_msg_keys(PyLdbMessageObject *self)
1802 {
1803         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1804         int i, j = 0;
1805         PyObject *obj = PyList_New(msg->num_elements+(msg->dn != NULL?1:0));
1806         if (msg->dn != NULL) {
1807                 PyList_SetItem(obj, j, PyString_FromString("dn"));
1808                 j++;
1809         }
1810         for (i = 0; i < msg->num_elements; i++) {
1811                 PyList_SetItem(obj, j, PyString_FromString(msg->elements[i].name));
1812                 j++;
1813         }
1814         return obj;
1815 }
1816
1817 static PyObject *py_ldb_msg_getitem_helper(PyLdbMessageObject *self, PyObject *py_name)
1818 {
1819         struct ldb_message_element *el;
1820         char *name;
1821         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1822         if (!PyString_Check(py_name)) {
1823                 PyErr_SetNone(PyExc_TypeError);
1824                 return NULL;
1825         }
1826         name = PyString_AsString(py_name);
1827         if (!strcmp(name, "dn"))
1828                 return PyLdbDn_FromDn(msg->dn);
1829         el = ldb_msg_find_element(msg, name);
1830         if (el == NULL) {
1831                 return NULL;
1832         }
1833         return (PyObject *)PyLdbMessageElement_FromMessageElement(el, msg);
1834 }
1835
1836 static PyObject *py_ldb_msg_getitem(PyLdbMessageObject *self, PyObject *py_name)
1837 {
1838         PyObject *ret = py_ldb_msg_getitem_helper(self, py_name);
1839         if (ret == NULL) {
1840                 PyErr_SetString(PyExc_KeyError, "No such element");
1841                 return NULL;
1842         }
1843         return ret;
1844 }
1845
1846 static PyObject *py_ldb_msg_get(PyLdbMessageObject *self, PyObject *args)
1847 {
1848         PyObject *name, *ret;
1849         if (!PyArg_ParseTuple(args, "O", &name))
1850                 return NULL;
1851
1852         ret = py_ldb_msg_getitem_helper(self, name);
1853         if (ret == NULL) {
1854                 if (PyErr_Occurred())
1855                         return NULL;
1856                 Py_RETURN_NONE;
1857         }
1858         return ret;
1859 }
1860
1861 static PyObject *py_ldb_msg_items(PyLdbMessageObject *self)
1862 {
1863         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1864         int i, j;
1865         PyObject *l = PyList_New(msg->num_elements + (msg->dn == NULL?0:1));
1866         j = 0;
1867         if (msg->dn != NULL) {
1868                 PyList_SetItem(l, 0, Py_BuildValue("(sO)", "dn", PyLdbDn_FromDn(msg->dn)));
1869                 j++;
1870         }
1871         for (i = 0; i < msg->num_elements; i++, j++) {
1872                 PyList_SetItem(l, j, Py_BuildValue("(sO)", msg->elements[i].name, PyLdbMessageElement_FromMessageElement(&msg->elements[i], self->msg)));
1873         }
1874         return l;
1875 }
1876
1877 static PyMethodDef py_ldb_msg_methods[] = { 
1878         { "keys", (PyCFunction)py_ldb_msg_keys, METH_NOARGS, NULL },
1879         { "remove", (PyCFunction)py_ldb_msg_remove_attr, METH_VARARGS, NULL },
1880         { "get", (PyCFunction)py_ldb_msg_get, METH_VARARGS, NULL },
1881         { "items", (PyCFunction)py_ldb_msg_items, METH_NOARGS, NULL },
1882         { NULL },
1883 };
1884
1885 static PyObject *py_ldb_msg_iter(PyLdbMessageObject *self)
1886 {
1887         PyObject *list, *iter;
1888
1889         list = py_ldb_msg_keys(self);
1890         iter = PyObject_GetIter(list);
1891         Py_DECREF(list);
1892         return iter;
1893 }
1894
1895 static int py_ldb_msg_setitem(PyLdbMessageObject *self, PyObject *name, PyObject *value)
1896 {
1897         char *attr_name;
1898
1899         if (!PyString_Check(name)) {
1900                 PyErr_SetNone(PyExc_TypeError);
1901                 return -1;
1902         }
1903         
1904         attr_name = PyString_AsString(name);
1905         if (value == NULL) {
1906                 /* delitem */
1907                 ldb_msg_remove_attr(self->msg, attr_name);
1908         } else {
1909                 struct ldb_message_element *el = PyObject_AsMessageElement(self->msg,
1910                                                                                         value, 0, attr_name);
1911                 if (el == NULL)
1912                         return -1;
1913                 ldb_msg_remove_attr(PyLdbMessage_AsMessage(self), attr_name);
1914                 ldb_msg_add(PyLdbMessage_AsMessage(self), el, el->flags);
1915         }
1916         return 0;
1917 }
1918
1919 static Py_ssize_t py_ldb_msg_length(PyLdbMessageObject *self)
1920 {
1921         return PyLdbMessage_AsMessage(self)->num_elements;
1922 }
1923
1924 static PyMappingMethods py_ldb_msg_mapping = {
1925         .mp_length = (lenfunc)py_ldb_msg_length,
1926         .mp_subscript = (binaryfunc)py_ldb_msg_getitem,
1927         .mp_ass_subscript = (objobjargproc)py_ldb_msg_setitem,
1928 };
1929
1930 static PyObject *py_ldb_msg_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1931 {
1932         const char * const kwnames[] = { "dn", NULL };
1933         struct ldb_message *ret;
1934         TALLOC_CTX *mem_ctx;
1935         PyObject *pydn = NULL;
1936         PyLdbMessageObject *py_ret;
1937
1938         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
1939                                          discard_const_p(char *, kwnames),
1940                                          &pydn))
1941                 return NULL;
1942
1943         mem_ctx = talloc_new(NULL);
1944         if (mem_ctx == NULL) {
1945                 PyErr_NoMemory();
1946                 return NULL;
1947         }
1948
1949         ret = ldb_msg_new(mem_ctx);
1950         if (ret == NULL) {
1951                 talloc_free(mem_ctx);
1952                 PyErr_NoMemory();
1953                 return NULL;
1954         }
1955
1956         if (pydn != NULL) {
1957                 struct ldb_dn *dn;
1958                 if (!PyObject_AsDn(NULL, pydn, NULL, &dn)) {
1959                         talloc_free(mem_ctx);
1960                         return NULL;
1961                 }
1962                 ret->dn = talloc_reference(ret, dn);
1963         }
1964
1965         py_ret = (PyLdbMessageObject *)type->tp_alloc(type, 0);
1966         if (py_ret == NULL) {
1967                 PyErr_NoMemory();
1968                 talloc_free(mem_ctx);
1969                 return NULL;
1970         }
1971
1972         py_ret->mem_ctx = mem_ctx;
1973         py_ret->msg = ret;
1974         return (PyObject *)py_ret;
1975 }
1976
1977 PyObject *PyLdbMessage_FromMessage(struct ldb_message *msg)
1978 {
1979         PyLdbMessageObject *ret;
1980
1981         ret = (PyLdbMessageObject *)PyLdbMessage.tp_alloc(&PyLdbMessage, 0);
1982         if (ret == NULL) {
1983                 PyErr_NoMemory();
1984                 return NULL;
1985         }
1986         ret->mem_ctx = talloc_new(NULL);
1987         ret->msg = talloc_reference(ret->mem_ctx, msg);
1988         return (PyObject *)ret;
1989 }
1990
1991 static PyObject *py_ldb_msg_get_dn(PyLdbMessageObject *self, void *closure)
1992 {
1993         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1994         return PyLdbDn_FromDn(msg->dn);
1995 }
1996
1997 static int py_ldb_msg_set_dn(PyLdbMessageObject *self, PyObject *value, void *closure)
1998 {
1999         struct ldb_message *msg = PyLdbMessage_AsMessage(self);
2000         if (!PyLdbDn_Check(value)) {
2001                 PyErr_SetNone(PyExc_TypeError);
2002                 return -1;
2003         }
2004
2005         msg->dn = talloc_reference(msg, PyLdbDn_AsDn(value));
2006         return 0;
2007 }
2008
2009 static PyGetSetDef py_ldb_msg_getset[] = {
2010         { discard_const_p(char, "dn"), (getter)py_ldb_msg_get_dn, (setter)py_ldb_msg_set_dn, NULL },
2011         { NULL }
2012 };
2013
2014 static PyObject *py_ldb_msg_repr(PyLdbMessageObject *self)
2015 {
2016         PyObject *dict = PyDict_New(), *ret;
2017         if (PyDict_Update(dict, (PyObject *)self) != 0)
2018                 return NULL;
2019         ret = PyString_FromFormat("Message(%s)", PyObject_REPR(dict));
2020         Py_DECREF(dict);
2021         return ret;
2022 }
2023
2024 static void py_ldb_msg_dealloc(PyLdbMessageObject *self)
2025 {
2026         talloc_free(self->mem_ctx);
2027         self->ob_type->tp_free(self);
2028 }
2029
2030 PyTypeObject PyLdbMessage = {
2031         .tp_name = "Message",
2032         .tp_methods = py_ldb_msg_methods,
2033         .tp_getset = py_ldb_msg_getset,
2034         .tp_as_mapping = &py_ldb_msg_mapping,
2035         .tp_basicsize = sizeof(PyLdbMessageObject),
2036         .tp_dealloc = (destructor)py_ldb_msg_dealloc,
2037         .tp_new = py_ldb_msg_new,
2038         .tp_repr = (reprfunc)py_ldb_msg_repr,
2039         .tp_flags = Py_TPFLAGS_DEFAULT,
2040         .tp_iter = (getiterfunc)py_ldb_msg_iter,
2041 };
2042
2043 PyObject *PyLdbTree_FromTree(struct ldb_parse_tree *tree)
2044 {
2045         PyLdbTreeObject *ret;
2046
2047         ret = (PyLdbTreeObject *)PyLdbTree.tp_alloc(&PyLdbTree, 0);
2048         if (ret == NULL) {
2049                 PyErr_NoMemory();
2050                 return NULL;
2051         }
2052
2053         ret->mem_ctx = talloc_new(NULL);
2054         ret->tree = talloc_reference(ret->mem_ctx, tree);
2055         return (PyObject *)ret;
2056 }
2057
2058 static void py_ldb_tree_dealloc(PyLdbTreeObject *self)
2059 {
2060         talloc_free(self->mem_ctx);
2061         self->ob_type->tp_free(self);
2062 }
2063
2064 PyTypeObject PyLdbTree = {
2065         .tp_name = "Tree",
2066         .tp_basicsize = sizeof(PyLdbTreeObject),
2067         .tp_dealloc = (destructor)py_ldb_tree_dealloc,
2068         .tp_flags = Py_TPFLAGS_DEFAULT,
2069 };
2070
2071 /* Ldb_module */
2072 static int py_module_search(struct ldb_module *mod, struct ldb_request *req)
2073 {
2074         PyObject *py_ldb = (PyObject *)mod->private_data;
2075         PyObject *py_result, *py_base, *py_attrs, *py_tree;
2076
2077         py_base = PyLdbDn_FromDn(req->op.search.base);
2078
2079         if (py_base == NULL)
2080                 return LDB_ERR_OPERATIONS_ERROR;
2081
2082         py_tree = PyLdbTree_FromTree(req->op.search.tree);
2083
2084         if (py_tree == NULL)
2085                 return LDB_ERR_OPERATIONS_ERROR;
2086
2087         if (req->op.search.attrs == NULL) {
2088                 py_attrs = Py_None;
2089         } else {
2090                 int i, len;
2091                 for (len = 0; req->op.search.attrs[len]; len++);
2092                 py_attrs = PyList_New(len);
2093                 for (i = 0; i < len; i++)
2094                         PyList_SetItem(py_attrs, i, PyString_FromString(req->op.search.attrs[i]));
2095         }
2096
2097         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "search"),
2098                                         discard_const_p(char, "OiOO"),
2099                                         py_base, req->op.search.scope, py_tree, py_attrs);
2100
2101         Py_DECREF(py_attrs);
2102         Py_DECREF(py_tree);
2103         Py_DECREF(py_base);
2104
2105         if (py_result == NULL) {
2106                 return LDB_ERR_PYTHON_EXCEPTION;
2107         }
2108
2109         req->op.search.res = PyLdbResult_AsResult(NULL, py_result);
2110         if (req->op.search.res == NULL) {
2111                 return LDB_ERR_PYTHON_EXCEPTION;
2112         }
2113
2114         Py_DECREF(py_result);
2115
2116         return LDB_SUCCESS;
2117 }
2118
2119 static int py_module_add(struct ldb_module *mod, struct ldb_request *req)
2120 {
2121         PyObject *py_ldb = (PyObject *)mod->private_data;
2122         PyObject *py_result, *py_msg;
2123
2124         py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.add.message));
2125
2126         if (py_msg == NULL) {
2127                 return LDB_ERR_OPERATIONS_ERROR;
2128         }
2129
2130         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "add"),
2131                                         discard_const_p(char, "O"),
2132                                         py_msg);
2133
2134         Py_DECREF(py_msg);
2135
2136         if (py_result == NULL) {
2137                 return LDB_ERR_PYTHON_EXCEPTION;
2138         }
2139
2140         Py_DECREF(py_result);
2141
2142         return LDB_SUCCESS;
2143 }
2144
2145 static int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
2146 {
2147         PyObject *py_ldb = (PyObject *)mod->private_data;
2148         PyObject *py_result, *py_msg;
2149
2150         py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.mod.message));
2151
2152         if (py_msg == NULL) {
2153                 return LDB_ERR_OPERATIONS_ERROR;
2154         }
2155
2156         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "modify"),
2157                                         discard_const_p(char, "O"),
2158                                         py_msg);
2159
2160         Py_DECREF(py_msg);
2161
2162         if (py_result == NULL) {
2163                 return LDB_ERR_PYTHON_EXCEPTION;
2164         }
2165
2166         Py_DECREF(py_result);
2167
2168         return LDB_SUCCESS;
2169 }
2170
2171 static int py_module_del(struct ldb_module *mod, struct ldb_request *req)
2172 {
2173         PyObject *py_ldb = (PyObject *)mod->private_data;
2174         PyObject *py_result, *py_dn;
2175
2176         py_dn = PyLdbDn_FromDn(req->op.del.dn);
2177
2178         if (py_dn == NULL)
2179                 return LDB_ERR_OPERATIONS_ERROR;
2180
2181         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "delete"),
2182                                         discard_const_p(char, "O"),
2183                                         py_dn);
2184
2185         if (py_result == NULL) {
2186                 return LDB_ERR_PYTHON_EXCEPTION;
2187         }
2188
2189         Py_DECREF(py_result);
2190
2191         return LDB_SUCCESS;
2192 }
2193
2194 static int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
2195 {
2196         PyObject *py_ldb = (PyObject *)mod->private_data;
2197         PyObject *py_result, *py_olddn, *py_newdn;
2198
2199         py_olddn = PyLdbDn_FromDn(req->op.rename.olddn);
2200
2201         if (py_olddn == NULL)
2202                 return LDB_ERR_OPERATIONS_ERROR;
2203
2204         py_newdn = PyLdbDn_FromDn(req->op.rename.newdn);
2205
2206         if (py_newdn == NULL)
2207                 return LDB_ERR_OPERATIONS_ERROR;
2208
2209         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "rename"),
2210                                         discard_const_p(char, "OO"),
2211                                         py_olddn, py_newdn);
2212
2213         Py_DECREF(py_olddn);
2214         Py_DECREF(py_newdn);
2215
2216         if (py_result == NULL) {
2217                 return LDB_ERR_PYTHON_EXCEPTION;
2218         }
2219
2220         Py_DECREF(py_result);
2221
2222         return LDB_SUCCESS;
2223 }
2224
2225 static int py_module_request(struct ldb_module *mod, struct ldb_request *req)
2226 {
2227         PyObject *py_ldb = (PyObject *)mod->private_data;
2228         PyObject *py_result;
2229
2230         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "request"),
2231                                         discard_const_p(char, ""));
2232
2233         return LDB_ERR_OPERATIONS_ERROR;
2234 }
2235
2236 static int py_module_extended(struct ldb_module *mod, struct ldb_request *req)
2237 {
2238         PyObject *py_ldb = (PyObject *)mod->private_data;
2239         PyObject *py_result;
2240
2241         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "extended"),
2242                                         discard_const_p(char, ""));
2243
2244         return LDB_ERR_OPERATIONS_ERROR;
2245 }
2246
2247 static int py_module_start_transaction(struct ldb_module *mod)
2248 {
2249         PyObject *py_ldb = (PyObject *)mod->private_data;
2250         PyObject *py_result;
2251
2252         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "start_transaction"),
2253                                         discard_const_p(char, ""));
2254
2255         if (py_result == NULL) {
2256                 return LDB_ERR_PYTHON_EXCEPTION;
2257         }
2258
2259         Py_DECREF(py_result);
2260
2261         return LDB_SUCCESS;
2262 }
2263
2264 static int py_module_end_transaction(struct ldb_module *mod)
2265 {
2266         PyObject *py_ldb = (PyObject *)mod->private_data;
2267         PyObject *py_result;
2268
2269         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "end_transaction"),
2270                                         discard_const_p(char, ""));
2271
2272         if (py_result == NULL) {
2273                 return LDB_ERR_PYTHON_EXCEPTION;
2274         }
2275
2276         Py_DECREF(py_result);
2277
2278         return LDB_SUCCESS;
2279 }
2280
2281 static int py_module_del_transaction(struct ldb_module *mod)
2282 {
2283         PyObject *py_ldb = (PyObject *)mod->private_data;
2284         PyObject *py_result;
2285
2286         py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "del_transaction"),
2287                                         discard_const_p(char, ""));
2288
2289         if (py_result == NULL) {
2290                 return LDB_ERR_PYTHON_EXCEPTION;
2291         }
2292
2293         Py_DECREF(py_result);
2294
2295         return LDB_SUCCESS;
2296 }
2297
2298 static int py_module_destructor(struct ldb_module *mod)
2299 {
2300         Py_DECREF((PyObject *)mod->private_data);
2301         return 0;
2302 }
2303
2304 static int py_module_init(struct ldb_module *mod)
2305 {
2306         PyObject *py_class = (PyObject *)mod->ops->private_data;
2307         PyObject *py_result, *py_next, *py_ldb;
2308
2309         py_ldb = PyLdb_FromLdbContext(mod->ldb);
2310
2311         if (py_ldb == NULL)
2312                 return LDB_ERR_OPERATIONS_ERROR;
2313
2314         py_next = PyLdbModule_FromModule(mod->next);
2315
2316         if (py_next == NULL)
2317                 return LDB_ERR_OPERATIONS_ERROR;
2318
2319         py_result = PyObject_CallFunction(py_class, discard_const_p(char, "OO"),
2320                                           py_ldb, py_next);
2321
2322         if (py_result == NULL) {
2323                 return LDB_ERR_PYTHON_EXCEPTION;
2324         }
2325
2326         mod->private_data = py_result;
2327
2328         talloc_set_destructor(mod, py_module_destructor);
2329
2330         return ldb_next_init(mod);
2331 }
2332
2333 static PyObject *py_register_module(PyObject *module, PyObject *args)
2334 {
2335         int ret;
2336         struct ldb_module_ops *ops;
2337         PyObject *input;
2338
2339         if (!PyArg_ParseTuple(args, "O", &input))
2340                 return NULL;
2341
2342         ops = talloc_zero(talloc_autofree_context(), struct ldb_module_ops);
2343         if (ops == NULL) {
2344                 PyErr_NoMemory();
2345                 return NULL;
2346         }
2347
2348         ops->name = talloc_strdup(ops, PyString_AsString(PyObject_GetAttrString(input, discard_const_p(char, "name"))));
2349
2350         Py_INCREF(input);
2351         ops->private_data = input;
2352         ops->init_context = py_module_init;
2353         ops->search = py_module_search;
2354         ops->add = py_module_add;
2355         ops->modify = py_module_modify;
2356         ops->del = py_module_del;
2357         ops->rename = py_module_rename;
2358         ops->request = py_module_request;
2359         ops->extended = py_module_extended;
2360         ops->start_transaction = py_module_start_transaction;
2361         ops->end_transaction = py_module_end_transaction;
2362         ops->del_transaction = py_module_del_transaction;
2363
2364         ret = ldb_register_module(ops);
2365
2366         PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
2367
2368         Py_RETURN_NONE;
2369 }
2370
2371 static PyObject *py_timestring(PyObject *module, PyObject *args)
2372 {
2373         time_t t;
2374         unsigned long val;
2375         char *tresult;
2376         PyObject *ret;
2377         if (!PyArg_ParseTuple(args, "l", &val))
2378                 return NULL;
2379         t = (time_t)val;
2380         tresult = ldb_timestring(NULL, t);
2381         ret = PyString_FromString(tresult);
2382         talloc_free(tresult);
2383         return ret;
2384 }
2385
2386 static PyObject *py_string_to_time(PyObject *module, PyObject *args)
2387 {
2388         char *str;
2389         if (!PyArg_ParseTuple(args, "s", &str))
2390                 return NULL;
2391
2392         return PyInt_FromLong(ldb_string_to_time(str));
2393 }
2394
2395 static PyObject *py_valid_attr_name(PyObject *self, PyObject *args)
2396 {
2397         char *name;
2398         if (!PyArg_ParseTuple(args, "s", &name))
2399                 return NULL;
2400         return PyBool_FromLong(ldb_valid_attr_name(name));
2401 }
2402
2403 static PyMethodDef py_ldb_global_methods[] = {
2404         { "register_module", py_register_module, METH_VARARGS, 
2405                 "S.register_module(module) -> None\n"
2406                 "Register a LDB module."},
2407         { "timestring", py_timestring, METH_VARARGS, 
2408                 "S.timestring(int) -> string\n"
2409                 "Generate a LDAP time string from a UNIX timestamp" },
2410         { "string_to_time", py_string_to_time, METH_VARARGS,
2411                 "S.string_to_time(string) -> int\n"
2412                 "Parse a LDAP time string into a UNIX timestamp." },
2413         { "valid_attr_name", py_valid_attr_name, METH_VARARGS,
2414                 "S.valid_attr_name(name) -> bool\n"
2415                 "Check whether the supplied name is a valid attribute name." },
2416         { "open", (PyCFunction)py_ldb_new, METH_VARARGS|METH_KEYWORDS,
2417                 NULL },
2418         { NULL }
2419 };
2420
2421 void initldb(void)
2422 {
2423         PyObject *m;
2424
2425         if (PyType_Ready(&PyLdbDn) < 0)
2426                 return;
2427
2428         if (PyType_Ready(&PyLdbMessage) < 0)
2429                 return;
2430
2431         if (PyType_Ready(&PyLdbMessageElement) < 0)
2432                 return;
2433
2434         if (PyType_Ready(&PyLdb) < 0)
2435                 return;
2436
2437         if (PyType_Ready(&PyLdbModule) < 0)
2438                 return;
2439
2440         if (PyType_Ready(&PyLdbTree) < 0)
2441                 return;
2442
2443         m = Py_InitModule3("ldb", py_ldb_global_methods, 
2444                 "An interface to LDB, a LDAP-like API that can either to talk an embedded database (TDB-based) or a standards-compliant LDAP server.");
2445         if (m == NULL)
2446                 return;
2447
2448         PyModule_AddObject(m, "SCOPE_DEFAULT", PyInt_FromLong(LDB_SCOPE_DEFAULT));
2449         PyModule_AddObject(m, "SCOPE_BASE", PyInt_FromLong(LDB_SCOPE_BASE));
2450         PyModule_AddObject(m, "SCOPE_ONELEVEL", PyInt_FromLong(LDB_SCOPE_ONELEVEL));
2451         PyModule_AddObject(m, "SCOPE_SUBTREE", PyInt_FromLong(LDB_SCOPE_SUBTREE));
2452
2453         PyModule_AddObject(m, "CHANGETYPE_NONE", PyInt_FromLong(LDB_CHANGETYPE_NONE));
2454         PyModule_AddObject(m, "CHANGETYPE_ADD", PyInt_FromLong(LDB_CHANGETYPE_ADD));
2455         PyModule_AddObject(m, "CHANGETYPE_DELETE", PyInt_FromLong(LDB_CHANGETYPE_DELETE));
2456         PyModule_AddObject(m, "CHANGETYPE_MODIFY", PyInt_FromLong(LDB_CHANGETYPE_MODIFY));
2457
2458         PyModule_AddObject(m, "FLAG_MOD_ADD", PyInt_FromLong(LDB_FLAG_MOD_ADD));
2459         PyModule_AddObject(m, "FLAG_MOD_REPLACE", PyInt_FromLong(LDB_FLAG_MOD_REPLACE));
2460         PyModule_AddObject(m, "FLAG_MOD_DELETE", PyInt_FromLong(LDB_FLAG_MOD_DELETE));
2461
2462         PyModule_AddObject(m, "SUCCESS", PyInt_FromLong(LDB_SUCCESS));
2463         PyModule_AddObject(m, "ERR_OPERATIONS_ERROR", PyInt_FromLong(LDB_ERR_OPERATIONS_ERROR));
2464         PyModule_AddObject(m, "ERR_PROTOCOL_ERROR", PyInt_FromLong(LDB_ERR_PROTOCOL_ERROR));
2465         PyModule_AddObject(m, "ERR_TIME_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_TIME_LIMIT_EXCEEDED));
2466         PyModule_AddObject(m, "ERR_SIZE_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_SIZE_LIMIT_EXCEEDED));
2467         PyModule_AddObject(m, "ERR_COMPARE_FALSE", PyInt_FromLong(LDB_ERR_COMPARE_FALSE));
2468         PyModule_AddObject(m, "ERR_COMPARE_TRUE", PyInt_FromLong(LDB_ERR_COMPARE_TRUE));
2469         PyModule_AddObject(m, "ERR_AUTH_METHOD_NOT_SUPPORTED", PyInt_FromLong(LDB_ERR_AUTH_METHOD_NOT_SUPPORTED));
2470         PyModule_AddObject(m, "ERR_STRONG_AUTH_REQUIRED", PyInt_FromLong(LDB_ERR_STRONG_AUTH_REQUIRED));
2471         PyModule_AddObject(m, "ERR_REFERRAL", PyInt_FromLong(LDB_ERR_REFERRAL));
2472         PyModule_AddObject(m, "ERR_ADMIN_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_ADMIN_LIMIT_EXCEEDED));
2473         PyModule_AddObject(m, "ERR_UNSUPPORTED_CRITICAL_EXTENSION", PyInt_FromLong(LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION));
2474         PyModule_AddObject(m, "ERR_CONFIDENTIALITY_REQUIRED", PyInt_FromLong(LDB_ERR_CONFIDENTIALITY_REQUIRED));
2475         PyModule_AddObject(m, "ERR_SASL_BIND_IN_PROGRESS", PyInt_FromLong(LDB_ERR_SASL_BIND_IN_PROGRESS));
2476         PyModule_AddObject(m, "ERR_NO_SUCH_ATTRIBUTE", PyInt_FromLong(LDB_ERR_NO_SUCH_ATTRIBUTE));
2477         PyModule_AddObject(m, "ERR_UNDEFINED_ATTRIBUTE_TYPE", PyInt_FromLong(LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE));
2478         PyModule_AddObject(m, "ERR_INAPPROPRIATE_MATCHING", PyInt_FromLong(LDB_ERR_INAPPROPRIATE_MATCHING));
2479         PyModule_AddObject(m, "ERR_CONSTRAINT_VIOLATION", PyInt_FromLong(LDB_ERR_CONSTRAINT_VIOLATION));
2480         PyModule_AddObject(m, "ERR_ATTRIBUTE_OR_VALUE_EXISTS", PyInt_FromLong(LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS));
2481         PyModule_AddObject(m, "ERR_INVALID_ATTRIBUTE_SYNTAX", PyInt_FromLong(LDB_ERR_INVALID_ATTRIBUTE_SYNTAX));
2482         PyModule_AddObject(m, "ERR_NO_SUCH_OBJECT", PyInt_FromLong(LDB_ERR_NO_SUCH_OBJECT));
2483         PyModule_AddObject(m, "ERR_ALIAS_PROBLEM", PyInt_FromLong(LDB_ERR_ALIAS_PROBLEM));
2484         PyModule_AddObject(m, "ERR_INVALID_DN_SYNTAX", PyInt_FromLong(LDB_ERR_INVALID_DN_SYNTAX));
2485         PyModule_AddObject(m, "ERR_ALIAS_DEREFERINCING_PROBLEM", PyInt_FromLong(LDB_ERR_ALIAS_DEREFERENCING_PROBLEM));
2486         PyModule_AddObject(m, "ERR_INAPPROPRIATE_AUTHENTICATION", PyInt_FromLong(LDB_ERR_INAPPROPRIATE_AUTHENTICATION));
2487         PyModule_AddObject(m, "ERR_INVALID_CREDENTIALS", PyInt_FromLong(LDB_ERR_INVALID_CREDENTIALS));
2488         PyModule_AddObject(m, "ERR_INSUFFICIENT_ACCESS_RIGHTS", PyInt_FromLong(LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS));
2489         PyModule_AddObject(m, "ERR_BUSY", PyInt_FromLong(LDB_ERR_BUSY));
2490         PyModule_AddObject(m, "ERR_UNAVAILABLE", PyInt_FromLong(LDB_ERR_UNAVAILABLE));
2491         PyModule_AddObject(m, "ERR_UNWILLING_TO_PERFORM", PyInt_FromLong(LDB_ERR_UNWILLING_TO_PERFORM));
2492         PyModule_AddObject(m, "ERR_LOOP_DETECT", PyInt_FromLong(LDB_ERR_LOOP_DETECT));
2493         PyModule_AddObject(m, "ERR_NAMING_VIOLATION", PyInt_FromLong(LDB_ERR_NAMING_VIOLATION));
2494         PyModule_AddObject(m, "ERR_OBJECT_CLASS_VIOLATION", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_VIOLATION));
2495         PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_NON_LEAF", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_NON_LEAF));
2496         PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_RDN", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_RDN));
2497         PyModule_AddObject(m, "ERR_ENTRY_ALREADY_EXISTS", PyInt_FromLong(LDB_ERR_ENTRY_ALREADY_EXISTS));
2498         PyModule_AddObject(m, "ERR_OBJECT_CLASS_MODS_PROHIBITED", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED));
2499         PyModule_AddObject(m, "ERR_AFFECTS_MULTIPLE_DSAS", PyInt_FromLong(LDB_ERR_AFFECTS_MULTIPLE_DSAS));
2500         PyModule_AddObject(m, "ERR_OTHER", PyInt_FromLong(LDB_ERR_OTHER));
2501
2502         PyModule_AddObject(m, "FLG_RDONLY", PyInt_FromLong(LDB_FLG_RDONLY));
2503         PyModule_AddObject(m, "FLG_NOSYNC", PyInt_FromLong(LDB_FLG_NOSYNC));
2504         PyModule_AddObject(m, "FLG_RECONNECT", PyInt_FromLong(LDB_FLG_RECONNECT));
2505         PyModule_AddObject(m, "FLG_NOMMAP", PyInt_FromLong(LDB_FLG_NOMMAP));
2506
2507
2508         PyModule_AddObject(m, "__docformat__", PyString_FromString("restructuredText"));
2509
2510         PyExc_LdbError = PyErr_NewException(discard_const_p(char, "_ldb.LdbError"), NULL, NULL);
2511         PyModule_AddObject(m, "LdbError", PyExc_LdbError);
2512
2513         Py_INCREF(&PyLdb);
2514         Py_INCREF(&PyLdbDn);
2515         Py_INCREF(&PyLdbModule);
2516         Py_INCREF(&PyLdbMessage);
2517         Py_INCREF(&PyLdbMessageElement);
2518         Py_INCREF(&PyLdbTree);
2519
2520         PyModule_AddObject(m, "Ldb", (PyObject *)&PyLdb);
2521         PyModule_AddObject(m, "Dn", (PyObject *)&PyLdbDn);
2522         PyModule_AddObject(m, "Message", (PyObject *)&PyLdbMessage);
2523         PyModule_AddObject(m, "MessageElement", (PyObject *)&PyLdbMessageElement);
2524         PyModule_AddObject(m, "Module", (PyObject *)&PyLdbModule);
2525         PyModule_AddObject(m, "Tree", (PyObject *)&PyLdbTree);
2526 }