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