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