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