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