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