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