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