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