Add some docstrings to ldb python module, fix MessageElement name.
[ab/samba.git/.git] / source4 / lib / ldb / ldb.i
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 %module ldb
29
30 %{
31
32 #include <stdint.h>
33 #include <stdbool.h>
34 #include "talloc.h"
35 #include "ldb.h"
36 #include "ldb_errors.h"
37 #include "ldb_private.h"
38
39 typedef struct ldb_message ldb_msg;
40 typedef struct ldb_context ldb;
41 typedef struct ldb_dn ldb_dn;
42 typedef struct ldb_ldif ldb_ldif;
43 typedef struct ldb_message_element ldb_message_element;
44 typedef int ldb_error;
45 typedef int ldb_int_error;
46
47 %}
48
49 %import "carrays.i"
50 %import "typemaps.i"
51 %include "exception.i"
52 %import "stdint.i"
53
54 /* Don't expose talloc contexts in Python code. Python does reference 
55    counting for us, so just create a new top-level talloc context.
56  */
57 %typemap(in, numinputs=0, noblock=1) TALLOC_CTX * {
58     $1 = NULL;
59 }
60
61
62
63 %constant int SCOPE_DEFAULT = LDB_SCOPE_DEFAULT;
64 %constant int SCOPE_BASE = LDB_SCOPE_BASE;
65 %constant int SCOPE_ONELEVEL = LDB_SCOPE_ONELEVEL;
66 %constant int SCOPE_SUBTREE = LDB_SCOPE_SUBTREE;
67
68 %constant int CHANGETYPE_NONE = LDB_CHANGETYPE_NONE;
69 %constant int CHANGETYPE_ADD = LDB_CHANGETYPE_ADD;
70 %constant int CHANGETYPE_DELETE = LDB_CHANGETYPE_DELETE;
71 %constant int CHANGETYPE_MODIFY = LDB_CHANGETYPE_MODIFY;
72
73 /* 
74  * Wrap struct ldb_context
75  */
76
77 /* The ldb functions will crash if a NULL ldb context is passed so
78    catch this before it happens. */
79
80 %typemap(check,noblock=1) struct ldb_context* {
81         if ($1 == NULL)
82                 SWIG_exception(SWIG_ValueError, 
83                         "ldb context must be non-NULL");
84 }
85
86 %typemap(check,noblock=1) ldb_msg * {
87         if ($1 == NULL)
88                 SWIG_exception(SWIG_ValueError, 
89                         "Message can not be None");
90 }
91
92 /*
93  * Wrap struct ldb_val
94  */
95
96 %typemap(in,noblock=1) struct ldb_val *INPUT (struct ldb_val temp) {
97         $1 = &temp;
98         if (!PyString_Check($input)) {
99                 PyErr_SetString(PyExc_TypeError, "string arg expected");
100                 return NULL;
101         }
102         $1->length = PyString_Size($input);
103         $1->data = PyString_AsString($input);
104 }
105
106 %inline %{
107 PyObject *ldb_val_to_py_object(struct ldb_context *ldb_ctx, 
108                                struct ldb_message_element *el, 
109                                struct ldb_val *val)
110 {
111         const struct ldb_schema_attribute *a;
112         struct ldb_val new_val;
113         TALLOC_CTX *mem_ctx = talloc_new(NULL);
114         PyObject *ret;
115         
116         new_val = *val;
117         
118         if (ldb_ctx != NULL) {        
119                 a = ldb_schema_attribute_by_name(ldb_ctx, el->name);
120         
121                 if (a != NULL) {
122                         if (a->syntax->ldif_write_fn(ldb_ctx, mem_ctx, val, &new_val) != 0) {
123                                 talloc_free(mem_ctx);
124                                 return NULL;
125                         }
126                 }
127         } 
128         
129         ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
130         
131         talloc_free(mem_ctx);
132         
133         return ret;
134 }
135
136 %}
137
138 %typemap(out,noblock=1) struct ldb_val * {
139         $result = PyString_FromStringAndSize((const char *)$1->data, $1->length)
140 }
141
142 %typemap(out,noblock=1) struct ldb_val {
143         $result = PyString_FromStringAndSize((const char *)$1.data, $1.length)
144 }
145
146 /*
147  * Wrap struct ldb_result
148  */
149
150 %typemap(in,noblock=1,numinputs=0) struct ldb_result **OUT (struct ldb_result *temp_ldb_result) {
151         $1 = &temp_ldb_result;
152 }
153
154 #ifdef SWIGPYTHON
155 %typemap(argout,noblock=1) struct ldb_result ** (int i) {
156         $result = PyList_New((*$1)->count);
157     for (i = 0; i < (*$1)->count; i++) {
158         PyList_SetItem($result, i, 
159             SWIG_NewPointerObj((*$1)->msgs[i], SWIGTYPE_p_ldb_message, 0)
160         );
161     }
162 }
163
164 %typemap(in,noblock=1,numinputs=1) const char * const *NULL_STR_LIST {
165     if ($input == Py_None) {
166         $1 = NULL;
167     } else if (PySequence_Check($input)) {
168         int i;
169         $1 = talloc_array(NULL, char *, PySequence_Size($input)+1);
170         for(i = 0; i < PySequence_Size($input); i++)
171             $1[i] = PyString_AsString(PySequence_GetItem($input, i));
172         $1[i] = NULL;
173     } else {
174         SWIG_exception(SWIG_TypeError, "expected sequence");
175     }
176 }
177
178 %typemap(freearg,noblock=1) const char * const *NULL_STR_LIST {
179     talloc_free($1);
180 }
181
182 %apply const char * const *NULL_STR_LIST { const char * const *attrs }
183 %apply const char * const *NULL_STR_LIST { const char * const *control_strings }
184
185 #endif
186
187 %types(struct ldb_result *);
188
189 /*
190  * Wrap struct ldb_dn
191  */
192
193 %rename(__str__) ldb_dn::get_linearized;
194 %rename(__cmp__) ldb_dn::compare;
195 %rename(__len__) ldb_dn::get_comp_num;
196 %rename(Dn) ldb_dn;
197 typedef struct ldb_dn {
198     %extend {
199         ldb_dn(ldb *ldb_ctx, const char *str)
200         {
201             ldb_dn *ret = ldb_dn_new(ldb_ctx, ldb_ctx, str);
202             /* ldb_dn_new() doesn't accept NULL as memory context, so 
203                we do it this way... */
204             talloc_steal(NULL, ret);
205
206             if (ret == NULL)
207                 SWIG_exception(SWIG_ValueError, 
208                                 "unable to parse dn string");
209 fail:
210             return ret;
211         }
212         ~ldb_dn() { talloc_free($self); }
213         %feature("docstring") validate "S.validate() -> bool\n" \
214                                        "Validate DN is correct.";
215         bool validate();
216         const char *get_casefold();
217         const char *get_linearized();
218         ldb_dn *parent() { return ldb_dn_get_parent(NULL, $self); }
219         int compare(ldb_dn *other);
220         bool is_valid();
221         %feature("docstring") is_special "S.is_special() -> bool\n" \
222                                          "Check whether this is a special LDB DN.";
223         bool is_special();
224         %feature("docstring") is_null "S.is_null() -> bool\n" \
225                                          "Check whether this is a null DN.";
226         bool is_null();
227         bool check_special(const char *name);
228         int get_comp_num();
229         %feature("docstring") add_child "S.add_child(dn) -> None\n" \
230                                          "Add a child DN to this DN.";
231         bool add_child(ldb_dn *child);
232         %feature("docstring") add_base "S.add_base(dn) -> None\n" \
233                                          "Add a base DN to this DN.";
234         bool add_base(ldb_dn *base);
235         %feature("docstring") canonical_str "S.canonical_str() -> string\n" \
236                                          "Canonical version of this DN (like a posix path).";
237         const char *canonical_str() {
238             return ldb_dn_canonical_string($self, $self);
239         }
240         %feature("docstring") canonical_ex_str "S.canonical_ex_str() -> string\n" \
241                                                "Canonical version of this DN (like a posix path, with terminating newline).";
242         const char *canonical_ex_str() {
243             return ldb_dn_canonical_ex_string($self, $self);
244         }
245 #ifdef SWIGPYTHON
246         char *__repr__(void)
247         {
248             char *dn = ldb_dn_get_linearized($self), *ret;
249             asprintf(&ret, "Dn('%s')", dn);
250             talloc_free(dn);
251             return ret;
252         }
253
254         ldb_dn *__add__(ldb_dn *other)
255         {
256             ldb_dn *ret = ldb_dn_copy(NULL, $self);
257             ldb_dn_add_child(ret, other);
258             return ret;
259         }
260
261         /* FIXME: implement __getslice__ */
262 #endif
263     %pythoncode {
264         def __eq__(self, other):
265             if isinstance(other, self.__class__):
266                 return self.__cmp__(other) == 0
267             if isinstance(other, str):
268                 return str(self) == other
269             return False
270     }
271     }
272 } ldb_dn;
273
274 #ifdef SWIGPYTHON
275 %{
276 struct ldb_context *ldb_context_from_py_object(PyObject *py_obj)
277 {
278         struct ldb_context *ldb_ctx;
279     if (SWIG_ConvertPtr(py_obj, (void *)&ldb_ctx, SWIGTYPE_p_ldb_context, 0 |  0 ) < 0)
280         return NULL;
281     return ldb_ctx;
282 }
283
284 int ldb_dn_from_pyobject(TALLOC_CTX *mem_ctx, PyObject *object, 
285                          struct ldb_context *ldb_ctx, ldb_dn **dn)
286 {
287     int ret;
288     struct ldb_dn *odn;
289     if (ldb_ctx != NULL && PyString_Check(object)) {
290         odn = ldb_dn_new(mem_ctx, ldb_ctx, PyString_AsString(object));
291         if (!odn) {
292                 return SWIG_ERROR;
293         }
294         *dn = odn;
295         return 0;
296     }
297     ret = SWIG_ConvertPtr(object, (void **)&odn, SWIGTYPE_p_ldb_dn, 
298                            SWIG_POINTER_EXCEPTION);
299     *dn = ldb_dn_copy(mem_ctx, odn);
300     if (odn && !*dn) {
301         return SWIG_ERROR;
302     }
303     return ret;
304 }
305
306 ldb_message_element *ldb_msg_element_from_pyobject(TALLOC_CTX *mem_ctx,
307                                                PyObject *set_obj, int flags,
308                                                const char *attr_name)
309 {
310     struct ldb_message_element *me = talloc(mem_ctx, struct ldb_message_element);
311     me->name = attr_name;
312     me->flags = flags;
313     if (PyString_Check(set_obj)) {
314         me->num_values = 1;
315         me->values = talloc_array(me, struct ldb_val, me->num_values);
316         me->values[0].length = PyString_Size(set_obj);
317         me->values[0].data = (uint8_t *)talloc_strdup(me->values, 
318                                            PyString_AsString(set_obj));
319     } else if (PySequence_Check(set_obj)) {
320         int i;
321         me->num_values = PySequence_Size(set_obj);
322         me->values = talloc_array(me, struct ldb_val, me->num_values);
323         for (i = 0; i < me->num_values; i++) {
324             PyObject *obj = PySequence_GetItem(set_obj, i);
325             me->values[i].length = PyString_Size(obj);
326             me->values[i].data = (uint8_t *)PyString_AsString(obj);
327         }
328     } else {
329         talloc_free(me);
330         me = NULL;
331     }
332
333     return me;
334 }
335
336 PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx, 
337                                  ldb_message_element *me)
338 {
339     int i;
340     PyObject *result;
341
342     /* Python << 2.5 doesn't have PySet_New and PySet_Add. */
343     result = PyList_New(me->num_values);
344
345     for (i = 0; i < me->num_values; i++) {
346         PyList_SetItem(result, i,
347             ldb_val_to_py_object(ldb_ctx, me, &me->values[i]));
348     }
349
350     return result;
351 }
352
353 %}
354 #endif
355
356 int ldb_msg_element_compare(ldb_message_element *, ldb_message_element *);
357 /* ldb_message_element */
358 %rename(MessageElement) ldb_message_element;
359 %rename(ldb_message_element_compare) ldb_msg_element_compare;
360 typedef struct ldb_message_element {
361     %extend {
362 #ifdef SWIGPYTHON
363         PyObject *__iter__(void)
364         {
365             return PyObject_GetIter(ldb_msg_element_to_set(NULL, $self));
366         }
367
368         PyObject *__set__(void)
369         {
370             return ldb_msg_element_to_set(NULL, $self);
371         }
372
373         ldb_message_element(PyObject *set_obj, int flags=0, const char *name = NULL)
374         {
375             return ldb_msg_element_from_pyobject(NULL, set_obj, flags, name);
376         }
377
378         int __len__()
379         {
380             return $self->num_values;
381         }
382 #endif
383
384         PyObject *get(int i)
385         {
386             if (i < 0 || i >= $self->num_values)
387                 return Py_None;
388
389             return ldb_val_to_py_object(NULL, $self, &$self->values[i]);
390         }
391
392         ~ldb_message_element() { talloc_free($self); }
393         %rename(__cmp__) ldb_msg_element_compare;
394     }
395     %pythoncode {
396         def __getitem__(self, i):
397             ret = self.get(i)
398             if ret is None:
399                 raise KeyError("no such value")
400             return ret
401
402         def __repr__(self):
403             return "MessageElement([%s])" % (",".join(repr(x) for x in self.__set__()))
404
405         def __eq__(self, other):
406             if (len(self) == 1 and self.get(0) == other):
407                 return True
408             if isinstance(other, self.__class__):
409                 return self.__cmp__(other) == 0
410             o = iter(other)
411             for i in range(len(self)):
412                 if self.get(i) != o.next():
413                     return False
414             return True
415     }
416 } ldb_message_element;
417
418 /* ldb_message */
419
420 %rename(Message) ldb_message;
421 #ifdef SWIGPYTHON
422 %rename(__delitem__) ldb_message::remove_attr;
423 %typemap(out) ldb_message_element * {
424         if ($1 == NULL)
425                 PyErr_SetString(PyExc_KeyError, "no such element");
426     else
427         $result = SWIG_NewPointerObj($1, SWIGTYPE_p_ldb_message_element, 0);
428 }
429
430 %inline {
431     PyObject *ldb_msg_list_elements(ldb_msg *msg)
432     {
433         int i, j = 0;
434         PyObject *obj = PyList_New(msg->num_elements+(msg->dn != NULL?1:0));
435         if (msg->dn != NULL) {
436             PyList_SetItem(obj, j, PyString_FromString("dn"));
437             j++;
438         }
439         for (i = 0; i < msg->num_elements; i++) {
440             PyList_SetItem(obj, j, PyString_FromString(msg->elements[i].name));
441             j++;
442         }
443         return obj;
444     }
445 }
446
447 #endif
448
449 typedef struct ldb_message {
450         ldb_dn *dn;
451
452     %extend {
453         ldb_msg(ldb_dn *dn = NULL) { 
454             ldb_msg *ret = ldb_msg_new(NULL); 
455             ret->dn = talloc_reference(ret, dn);
456             return ret;
457         }
458         ~ldb_msg() { talloc_free($self); }
459         ldb_message_element *find_element(const char *name);
460         
461 #ifdef SWIGPYTHON
462         void __setitem__(const char *attr_name, ldb_message_element *val)
463         {
464             struct ldb_message_element *el;
465             
466             ldb_msg_remove_attr($self, attr_name);
467
468             el = talloc($self, struct ldb_message_element);
469             el->name = talloc_strdup(el, attr_name);
470             el->num_values = val->num_values;
471             el->values = talloc_reference(el, val->values);
472
473             ldb_msg_add($self, el, val->flags);
474         }
475
476         void __setitem__(const char *attr_name, PyObject *val)
477         {
478             struct ldb_message_element *el = ldb_msg_element_from_pyobject(NULL,
479                                                 val, 0, attr_name);
480             talloc_steal($self, el);
481             ldb_msg_remove_attr($self, attr_name);
482             ldb_msg_add($self, el, el->flags);
483         }
484
485         unsigned int __len__() { return $self->num_elements; }
486
487         PyObject *keys(void)
488         {
489             return ldb_msg_list_elements($self);
490         }
491
492         PyObject *__iter__(void)
493         {
494             return PyObject_GetIter(ldb_msg_list_elements($self));
495         }
496 #endif
497         void remove_attr(const char *name);
498 %pythoncode {
499     def get(self, key, default=None):
500         if key == "dn":
501             return self.dn
502         return self.find_element(key)
503
504     def __getitem__(self, key):
505         ret = self.get(key, None)
506         if ret is None:
507             raise KeyError("No such element")
508         return ret
509
510     def iteritems(self):
511         for k in self.keys():
512             yield k, self[k]
513     
514     def items(self):
515         return list(self.iteritems())
516
517     def __repr__(self):
518         return "Message(%s)" % repr(dict(self.iteritems()))
519 }
520     }
521 } ldb_msg;
522
523 /* FIXME: Convert ldb_result to 3-tuple:
524    (msgs, refs, controls)
525  */
526
527 typedef struct ldb_ldif ldb_ldif;
528
529 #ifdef SWIGPYTHON
530 %{
531 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(3, 0);
532
533 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap)
534 {
535     char *text;
536     PyObject *fn = context;
537
538     vasprintf(&text, fmt, ap);
539     PyObject_CallFunction(fn, (char *)"(i,s)", level, text);
540     free(text);
541 }
542 %}
543
544 %typemap(in,numinputs=1,noblock=1) (void (*debug)(void *context, enum ldb_debug_level level, const char *fmt, va_list ap), void *context) {
545     $1 = py_ldb_debug;
546     /* FIXME: Should be decreased somewhere as well. Perhaps register a 
547        destructor and tie it to the ldb context ? */
548     Py_INCREF($input);
549     $2 = $input;
550 }
551 #endif
552
553 %inline {
554     static PyObject *ldb_ldif_to_pyobject(ldb_ldif *ldif)
555     {
556         if (ldif == NULL) {
557             return Py_None;
558         } else {
559             return Py_BuildValue((char *)"(iO)", ldif->changetype, 
560                    SWIG_NewPointerObj(ldif->msg, SWIGTYPE_p_ldb_message, 0));
561         }
562     }
563 }
564
565 /*
566  * Wrap ldb errors
567  */
568
569 %{
570 PyObject *PyExc_LdbError;
571 %}
572
573 %pythoncode %{
574     LdbError = _ldb.LdbError
575 %}
576
577 %init %{
578     PyExc_LdbError = PyErr_NewException((char *)"_ldb.LdbError", NULL, NULL);
579     PyDict_SetItemString(d, "LdbError", PyExc_LdbError);
580 %}
581
582 %ignore _LDB_ERRORS_H_;
583 %ignore LDB_SUCCESS;
584 %include "include/ldb_errors.h"
585
586 /*
587  * Wrap ldb functions 
588  */
589
590
591 %typemap(out,noblock=1) ldb_error {
592     if ($1 != LDB_SUCCESS) {
593         PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", $1, ldb_errstring(arg1)));
594         SWIG_fail;
595     }
596     $result = Py_None;
597 };
598
599 %typemap(out,noblock=1) ldb_int_error {
600     if ($1 != LDB_SUCCESS) {
601         PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", $1, ldb_strerror($1)));
602         SWIG_fail;
603     }
604     $result = Py_None;
605 };
606
607 %typemap(out,noblock=1) struct ldb_control ** {
608     if ($1 == NULL) {
609         PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(s)", ldb_errstring(arg1)));
610         SWIG_fail;
611     }
612     $result = SWIG_NewPointerObj($1, $1_descriptor, 0);
613 }
614
615 %rename(Ldb) ldb_context;
616
617 %typemap(in,noblock=1) struct ldb_dn * {
618     if (ldb_dn_from_pyobject(NULL, $input, arg1, &$1) != 0) {
619         SWIG_fail;
620     }
621 };
622
623 %typemap(freearg,noblock=1) struct ldb_dn * {
624     talloc_free($1);
625 };
626
627 %typemap(in,numinputs=1) ldb_msg *add_msg {
628     Py_ssize_t dict_pos, msg_pos;
629     ldb_message_element *msgel;
630     PyObject *key, *value;
631
632     if (PyDict_Check($input)) {
633         PyObject *dn_value = PyDict_GetItemString($input, "dn");
634         $1 = ldb_msg_new(NULL);
635         $1->elements = talloc_zero_array($1, struct ldb_message_element, PyDict_Size($input));
636         msg_pos = dict_pos = 0;
637         if (dn_value) {
638                 /* using argp1 (magic SWIG value) here is a hack */
639                 if (ldb_dn_from_pyobject($1, dn_value, argp1, &$1->dn) != 0) {
640                     SWIG_exception(SWIG_TypeError, "unable to import dn object");
641                 }
642                 if ($1->dn == NULL) {
643                     SWIG_exception(SWIG_TypeError, "dn set but not found");
644                 }
645         }
646
647         while (PyDict_Next($input, &dict_pos, &key, &value)) {
648             char *key_str = PyString_AsString(key);
649             if (strcmp(key_str, "dn") != 0) {
650                 msgel = ldb_msg_element_from_pyobject($1->elements, value, 0, key_str);
651                 if (msgel == NULL) {
652                     SWIG_exception(SWIG_TypeError, "unable to import element");
653                 }
654                 memcpy(&$1->elements[msg_pos], msgel, sizeof(*msgel));
655                 msg_pos++;
656             }
657         }
658
659         if ($1->dn == NULL) {
660             SWIG_exception(SWIG_TypeError, "no dn set");
661         }
662
663         $1->num_elements = msg_pos;
664     } else {
665         if (SWIG_ConvertPtr($input, (void **)&$1, SWIGTYPE_p_ldb_message, 0) != 0) {
666             SWIG_exception(SWIG_TypeError, "unable to convert ldb message");
667         }
668     }
669 }
670
671 /* Top-level ldb operations */
672 typedef struct ldb_context {
673     %extend {
674         ldb(void) { return ldb_init(NULL); }
675
676         %feature("docstring") connect "S.connect(url,flags=0,options=None) -> None\n" \
677                                       "Connect to a LDB URL.";
678         ldb_error connect(const char *url, unsigned int flags = 0, 
679             const char *options[] = NULL);
680
681         ~ldb() { talloc_free($self); }
682         ldb_error search_ex(TALLOC_CTX *mem_ctx,
683                    ldb_dn *base = NULL, 
684                    enum ldb_scope scope = LDB_SCOPE_DEFAULT, 
685                    const char *expression = NULL, 
686                    const char *const *attrs = NULL, 
687                    struct ldb_control **controls = NULL,
688                    struct ldb_result **OUT) {
689             int ret;
690             struct ldb_result *res;
691             struct ldb_request *req;
692             res = talloc_zero(mem_ctx, struct ldb_result);
693             if (!res) {
694                 return LDB_ERR_OPERATIONS_ERROR;
695             }
696
697             ret = ldb_build_search_req(&req, $self, mem_ctx,
698                            base?base:ldb_get_default_basedn($self),
699                            scope,
700                            expression,
701                            attrs,
702                            controls,
703                            res,
704                            ldb_search_default_callback);
705
706             if (ret != LDB_SUCCESS) {
707                 talloc_free(res);
708                 return ret;
709             }
710
711             ldb_set_timeout($self, req, 0); /* use default timeout */
712                 
713             ret = ldb_request($self, req);
714                 
715             if (ret == LDB_SUCCESS) {
716                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
717             }
718
719             talloc_free(req);
720
721             *OUT = res;
722             return ret;
723         }
724
725         %feature("docstring") delete "S.delete(dn) -> None\n" \
726                                      "Remove an entry.";
727         ldb_error delete(ldb_dn *dn);
728         %feature("docstring") rename "S.rename(old_dn, new_dn) -> None\n" \
729                                      "Rename an entry.";
730         ldb_error rename(ldb_dn *olddn, ldb_dn *newdn);
731         struct ldb_control **parse_control_strings(TALLOC_CTX *mem_ctx, 
732                                                    const char * const*control_strings);
733         %feature("docstring") add "S.add(message) -> None\n" \
734                                   "Add an entry.";
735         ldb_error add(ldb_msg *add_msg);
736         %feature("docstring") modify "S.modify(message) -> None\n" \
737                                   "Modify an entry.";
738         ldb_error modify(ldb_msg *message);
739         ldb_dn *get_config_basedn();
740         ldb_dn *get_root_basedn();
741         ldb_dn *get_schema_basedn();
742         ldb_dn *get_default_basedn();
743         PyObject *schema_format_value(const char *element_name, PyObject *val)
744         {
745                 const struct ldb_schema_attribute *a;
746                 struct ldb_val old_val;
747                 struct ldb_val new_val;
748                 TALLOC_CTX *mem_ctx = talloc_new(NULL);
749                 PyObject *ret;
750                 
751                 old_val.data = PyString_AsString(val);
752                 old_val.length = PyString_Size(val);
753                 
754                 a = ldb_schema_attribute_by_name($self, element_name);
755         
756                 if (a == NULL) {
757                         return Py_None;
758                 }
759                 
760                 if (a->syntax->ldif_write_fn($self, mem_ctx, &old_val, &new_val) != 0) {
761                         talloc_free(mem_ctx);
762                         return Py_None;
763                  }
764         
765                 ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
766                 
767                 talloc_free(mem_ctx);
768                 
769                 return ret;
770         }
771
772         const char *errstring();
773         %feature("docstring") set_create_perms "S.set_create_perms(mode) -> None\n" \
774                                                "Set mode to use when creating new LDB files.";
775         void set_create_perms(unsigned int perms);
776         %feature("docstring") set_modules_dir "S.set_modules_dir(path) -> None\n" \
777                                               "Set path LDB should search for modules";
778         void set_modules_dir(const char *path);
779         ldb_error set_debug(void (*debug)(void *context, enum ldb_debug_level level, 
780                                           const char *fmt, va_list ap),
781                             void *context);
782         %feature("docstring") set_opaque "S.set_opaque(name, value) -> None\n" \
783             "Set an opaque value on this LDB connection. \n"
784             ":note: Passing incorrect values may cause crashes.";
785         ldb_error set_opaque(const char *name, void *value);
786         %feature("docstring") get_opaque "S.get_opaque(name) -> value\n" \
787             "Get an opaque value set on this LDB connection. \n"
788             ":note: The returned value may not be useful in Python.";
789         void *get_opaque(const char *name);
790         %feature("docstring") transaction_start "S.transaction_start() -> None\n" \
791                                                 "Start a new transaction.";
792         ldb_error transaction_start();
793         %feature("docstring") transaction_commit "S.transaction_commit() -> None\n" \
794                                                  "Commit currently active transaction.";
795         ldb_error transaction_commit();
796         %feature("docstring") transaction_commit "S.transaction_cancel() -> None\n" \
797                                                  "Cancel currently active transaction.";
798         ldb_error transaction_cancel();
799         void schema_attribute_remove(const char *name);
800         ldb_error schema_attribute_add(const char *attribute, unsigned flags, const char *syntax);
801         ldb_error setup_wellknown_attributes(void);
802  
803 #ifdef SWIGPYTHON
804         %typemap(in,numinputs=0,noblock=1) struct ldb_result **result_as_bool (struct ldb_result *tmp) { $1 = &tmp; }
805         %typemap(argout,noblock=1) struct ldb_result **result_as_bool { $result = ((*$1)->count > 0)?Py_True:Py_False; }
806         %typemap(freearg,noblock=1) struct ldb_result **result_as_bool { talloc_free(*$1); }
807         ldb_error __contains__(ldb_dn *dn, struct ldb_result **result_as_bool)
808         {
809             return ldb_search($self, dn, LDB_SCOPE_BASE, NULL, NULL, 
810                              result_as_bool);
811         }
812
813         %feature("docstring") parse_ldif "S.parse_ldif(ldif) -> iter(messages)\n" \
814             "Parse a string formatted using LDIF.";
815
816         PyObject *parse_ldif(const char *s)
817         {
818             PyObject *list = PyList_New(0);
819             struct ldb_ldif *ldif;
820             while ((ldif = ldb_ldif_read_string($self, &s)) != NULL) {
821                 PyList_Append(list, ldb_ldif_to_pyobject(ldif));
822             }
823             return PyObject_GetIter(list);
824         }
825
826         char *__repr__(void)
827         {
828             char *ret;
829             asprintf(&ret, "<ldb connection at 0x%x>", ret); 
830             return ret;
831         }
832 #endif
833     }
834     %pythoncode {
835         def __init__(self, url=None, flags=0, options=None):
836             """Create a new LDB object.
837
838             Will also connect to the specified URL if one was given.
839             """
840             _ldb.Ldb_swiginit(self,_ldb.new_Ldb())
841             if url is not None:
842                 self.connect(url, flags, options)
843
844         def search(self, base=None, scope=SCOPE_DEFAULT, expression=None, 
845                    attrs=None, controls=None):
846             """Search in a database.
847
848             :param base: Optional base DN to search
849             :param scope: Search scope (SCOPE_BASE, SCOPE_ONELEVEL or SCOPE_SUBTREE)
850             :param expression: Optional search expression
851             :param attrs: Attributes to return (defaults to all)
852             :param controls: Optional list of controls
853             :return: Iterator over Message objects
854             """
855             if not (attrs is None or isinstance(attrs, list)):
856                 raise TypeError("attributes not a list")
857             parsed_controls = None
858             if controls is not None:
859                 parsed_controls = self.parse_control_strings(controls)
860             return self.search_ex(base, scope, expression, attrs, 
861                                   parsed_controls)
862     }
863
864 } ldb;
865
866 %typemap(in,noblock=1) struct ldb_dn *;
867 %typemap(freearg,noblock=1) struct ldb_dn *;
868
869 %nodefault ldb_message;
870 %nodefault ldb_context;
871 %nodefault Dn;
872
873 %rename(valid_attr_name) ldb_valid_attr_name;
874 %feature("docstring") ldb_valid_attr_name "S.valid_attr_name(name) -> bool\n"
875                                           "Check whether the supplied name is a valid attribute name.";
876 int ldb_valid_attr_name(const char *s);
877
878 typedef unsigned long time_t;
879
880 %inline %{
881 static char *timestring(time_t t)
882 {
883     char *tresult = ldb_timestring(NULL, t);
884     char *result = strdup(tresult);
885     talloc_free(tresult);
886     return result; 
887 }
888 %}
889
890 %rename(string_to_time) ldb_string_to_time;
891 time_t ldb_string_to_time(const char *s);
892
893 %typemap(in,noblock=1) const struct ldb_module_ops * {
894     $1 = talloc_zero(talloc_autofree_context(), struct ldb_module_ops);
895
896     $1->name = (char *)PyObject_GetAttrString($input, (char *)"name");
897 }
898
899 %feature("docstring") ldb_register_module "S.register_module(module) -> None\n"
900                                           "Register a LDB module.";
901 %rename(register_module) ldb_register_module;
902 ldb_int_error ldb_register_module(const struct ldb_module_ops *);