7831d6da606516b31b43888bc201f1fc30dd3792
[kai/samba.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 struct ldb_module ldb_module;
50 typedef int ldb_error;
51 typedef int ldb_int_error;
52
53 %}
54
55 %import "carrays.i"
56 %import "typemaps.i"
57 %include "exception.i"
58 %import "stdint.i"
59
60 /* Don't expose talloc contexts in Python code. Python does reference 
61    counting for us, so just create a new top-level talloc context.
62  */
63 %typemap(in, numinputs=0, noblock=1) TALLOC_CTX * {
64     $1 = NULL;
65 }
66
67
68
69 %constant int SCOPE_DEFAULT = LDB_SCOPE_DEFAULT;
70 %constant int SCOPE_BASE = LDB_SCOPE_BASE;
71 %constant int SCOPE_ONELEVEL = LDB_SCOPE_ONELEVEL;
72 %constant int SCOPE_SUBTREE = LDB_SCOPE_SUBTREE;
73
74 %constant int CHANGETYPE_NONE = LDB_CHANGETYPE_NONE;
75 %constant int CHANGETYPE_ADD = LDB_CHANGETYPE_ADD;
76 %constant int CHANGETYPE_DELETE = LDB_CHANGETYPE_DELETE;
77 %constant int CHANGETYPE_MODIFY = LDB_CHANGETYPE_MODIFY;
78
79 /* 
80  * Wrap struct ldb_context
81  */
82
83 /* The ldb functions will crash if a NULL ldb context is passed so
84    catch this before it happens. */
85
86 %typemap(check,noblock=1) struct ldb_context* {
87         if ($1 == NULL)
88                 SWIG_exception(SWIG_ValueError, 
89                         "ldb context must be non-NULL");
90 }
91
92 %typemap(check,noblock=1) ldb_msg * {
93         if ($1 == NULL)
94                 SWIG_exception(SWIG_ValueError, 
95                         "Message can not be None");
96 }
97
98 /*
99  * Wrap struct ldb_val
100  */
101
102 %typemap(in,noblock=1) struct ldb_val *INPUT (struct ldb_val temp) {
103         $1 = &temp;
104         if (!PyString_Check($input)) {
105                 PyErr_SetString(PyExc_TypeError, "string arg expected");
106                 return NULL;
107         }
108         $1->length = PyString_Size($input);
109         $1->data = PyString_AsString($input);
110 }
111
112 %inline %{
113 PyObject *ldb_val_to_py_object(struct ldb_context *ldb_ctx, 
114                                struct ldb_message_element *el, 
115                                struct ldb_val *val)
116 {
117         const struct ldb_schema_attribute *a;
118         struct ldb_val new_val;
119         TALLOC_CTX *mem_ctx = talloc_new(NULL);
120         PyObject *ret;
121         
122         new_val = *val;
123         
124         if (ldb_ctx != NULL) {        
125                 a = ldb_schema_attribute_by_name(ldb_ctx, el->name);
126         
127                 if (a != NULL) {
128                         if (a->syntax->ldif_write_fn(ldb_ctx, mem_ctx, val, &new_val) != 0) {
129                                 talloc_free(mem_ctx);
130                                 return NULL;
131                         }
132                 }
133         } 
134         
135         ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
136         
137         talloc_free(mem_ctx);
138         
139         return ret;
140 }
141
142 %}
143
144 %typemap(out,noblock=1) struct ldb_val * {
145         $result = PyString_FromStringAndSize((const char *)$1->data, $1->length)
146 }
147
148 %typemap(out,noblock=1) struct ldb_val {
149         $result = PyString_FromStringAndSize((const char *)$1.data, $1.length)
150 }
151
152 /*
153  * Wrap struct ldb_result
154  */
155
156 %typemap(in,noblock=1,numinputs=0) struct ldb_result ** (struct ldb_result *temp_ldb_result) {
157         $1 = &temp_ldb_result;
158 }
159
160 #ifdef SWIGPYTHON
161 %typemap(argout,noblock=1) struct ldb_result ** (int i) {
162     if ($1 == NULL) {
163         $result = Py_None;
164     } else {
165         $result = PyList_New((*$1)->count);
166         for (i = 0; i < (*$1)->count; i++) {
167             PyList_SetItem($result, i, 
168                 SWIG_NewPointerObj((*$1)->msgs[i], SWIGTYPE_p_ldb_message, 0)
169             );
170         }
171     }
172 }
173
174 %typemap(in,noblock=1,numinputs=1) const char * const *NULL_STR_LIST {
175     if ($input == Py_None) {
176         $1 = NULL;
177     } else if (PySequence_Check($input)) {
178         int i;
179         $1 = talloc_array(NULL, char *, PySequence_Size($input)+1);
180         for(i = 0; i < PySequence_Size($input); i++)
181             $1[i] = PyString_AsString(PySequence_GetItem($input, i));
182         $1[i] = NULL;
183     } else {
184         SWIG_exception(SWIG_TypeError, "expected sequence");
185     }
186 }
187
188 %typemap(freearg,noblock=1) const char * const *NULL_STR_LIST {
189     talloc_free($1);
190 }
191
192 %apply const char * const *NULL_STR_LIST { const char * const *attrs }
193 %apply const char * const *NULL_STR_LIST { const char * const *options }
194 %apply const char * const *NULL_STR_LIST { const char * const *control_strings }
195
196 #endif
197
198 %types(struct ldb_result *, struct ldb_parse_tree *);
199
200 /*
201  * Wrap struct ldb_dn
202  */
203
204 %rename(__str__) ldb_dn::get_linearized;
205 %rename(__cmp__) ldb_dn::compare;
206 %rename(__len__) ldb_dn::get_comp_num;
207 %rename(Dn) ldb_dn;
208 %feature("docstring") ldb_dn "A LDB distinguished name.";
209 typedef struct ldb_dn {
210     %extend {
211         %feature("docstring") ldb_dn "S.__init__(ldb, string)\n" \
212                  "Create a new DN.";
213         ldb_dn(ldb *ldb_ctx, const char *str)
214         {
215             ldb_dn *ret = ldb_dn_new(ldb_ctx, ldb_ctx, str);
216             /* ldb_dn_new() doesn't accept NULL as memory context, so 
217                we do it this way... */
218             talloc_steal(NULL, ret);
219
220             if (ret == NULL || !ldb_dn_validate(ret))
221                 SWIG_exception(SWIG_ValueError, 
222                                 "unable to parse dn string");
223 fail:
224             return ret;
225         }
226         ~ldb_dn() { talloc_free($self); }
227         %feature("docstring") validate "S.validate() -> bool\n" \
228                                        "Validate DN is correct.";
229         bool validate();
230         const char *get_casefold();
231         const char *get_linearized();
232         %feature("docstring") parent "S.parent() -> dn\n" \
233                                      "Get the parent for this DN.";
234         ldb_dn *parent() { return ldb_dn_get_parent(NULL, $self); }
235         int compare(ldb_dn *other);
236         bool is_valid();
237         %feature("docstring") is_special "S.is_special() -> bool\n" \
238                                          "Check whether this is a special LDB DN.";
239         bool is_special();
240         %feature("docstring") is_null "S.is_null() -> bool\n" \
241                                          "Check whether this is a null DN.";
242         bool is_null();
243         bool check_special(const char *name);
244         int get_comp_num();
245         %feature("docstring") add_child "S.add_child(dn) -> None\n" \
246                                          "Add a child DN to this DN.";
247         bool add_child(ldb_dn *child);
248         %feature("docstring") add_base "S.add_base(dn) -> None\n" \
249                                          "Add a base DN to this DN.";
250         bool add_base(ldb_dn *base);
251         %feature("docstring") canonical_str "S.canonical_str() -> string\n" \
252                                          "Canonical version of this DN (like a posix path).";
253         const char *canonical_str() {
254             return ldb_dn_canonical_string($self, $self);
255         }
256         %feature("docstring") canonical_ex_str "S.canonical_ex_str() -> string\n" \
257                                                "Canonical version of this DN (like a posix path, with terminating newline).";
258         const char *canonical_ex_str() {
259             return ldb_dn_canonical_ex_string($self, $self);
260         }
261 #ifdef SWIGPYTHON
262         char *__repr__(void)
263         {
264             char *dn = ldb_dn_get_linearized($self), *ret;
265             asprintf(&ret, "Dn('%s')", dn);
266             return ret;
267         }
268
269         ldb_dn *__add__(ldb_dn *other)
270         {
271             ldb_dn *ret = ldb_dn_copy(NULL, $self);
272             ldb_dn_add_child(ret, other);
273             return ret;
274         }
275
276         /* FIXME: implement __getslice__ */
277 #endif
278     %pythoncode {
279         def __eq__(self, other):
280             if isinstance(other, self.__class__):
281                 return self.__cmp__(other) == 0
282             if isinstance(other, str):
283                 return str(self) == other
284             return False
285     }
286     }
287 } ldb_dn;
288
289 #ifdef SWIGPYTHON
290 %{
291 struct ldb_context *ldb_context_from_py_object(PyObject *py_obj)
292 {
293         struct ldb_context *ldb_ctx;
294     if (SWIG_ConvertPtr(py_obj, (void *)&ldb_ctx, SWIGTYPE_p_ldb_context, 0 |  0 ) < 0)
295         return NULL;
296     return ldb_ctx;
297 }
298
299 int ldb_dn_from_pyobject(TALLOC_CTX *mem_ctx, PyObject *object, 
300                          struct ldb_context *ldb_ctx, ldb_dn **dn)
301 {
302     int ret;
303     struct ldb_dn *odn;
304     if (ldb_ctx != NULL && PyString_Check(object)) {
305         odn = ldb_dn_new(mem_ctx, ldb_ctx, PyString_AsString(object));
306         if (!odn) {
307                 return SWIG_ERROR;
308         }
309         *dn = odn;
310         return 0;
311     }
312     ret = SWIG_ConvertPtr(object, (void **)&odn, SWIGTYPE_p_ldb_dn, 
313                            SWIG_POINTER_EXCEPTION);
314     *dn = ldb_dn_copy(mem_ctx, odn);
315     if (odn && !*dn) {
316         return SWIG_ERROR;
317     }
318     return ret;
319 }
320
321 ldb_message_element *ldb_msg_element_from_pyobject(TALLOC_CTX *mem_ctx,
322                                                PyObject *set_obj, int flags,
323                                                const char *attr_name)
324 {
325     struct ldb_message_element *me = talloc(mem_ctx, struct ldb_message_element);
326     me->name = attr_name;
327     me->flags = flags;
328     if (PyString_Check(set_obj)) {
329         me->num_values = 1;
330         me->values = talloc_array(me, struct ldb_val, me->num_values);
331         me->values[0].length = PyString_Size(set_obj);
332         me->values[0].data = (uint8_t *)talloc_strdup(me->values, 
333                                            PyString_AsString(set_obj));
334     } else if (PySequence_Check(set_obj)) {
335         int i;
336         me->num_values = PySequence_Size(set_obj);
337         me->values = talloc_array(me, struct ldb_val, me->num_values);
338         for (i = 0; i < me->num_values; i++) {
339             PyObject *obj = PySequence_GetItem(set_obj, i);
340             me->values[i].length = PyString_Size(obj);
341             me->values[i].data = (uint8_t *)PyString_AsString(obj);
342         }
343     } else {
344         talloc_free(me);
345         me = NULL;
346     }
347
348     return me;
349 }
350
351 PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx, 
352                                  ldb_message_element *me)
353 {
354     int i;
355     PyObject *result;
356
357     /* Python << 2.5 doesn't have PySet_New and PySet_Add. */
358     result = PyList_New(me->num_values);
359
360     for (i = 0; i < me->num_values; i++) {
361         PyList_SetItem(result, i,
362             ldb_val_to_py_object(ldb_ctx, me, &me->values[i]));
363     }
364
365     return result;
366 }
367
368 %}
369 #endif
370
371 /* ldb_message_element */
372 %rename(MessageElement) ldb_message_element;
373 %feature("docstring") ldb_message_element "Message element.";
374 typedef struct ldb_message_element {
375     %extend {
376 #ifdef SWIGPYTHON
377         int __cmp__(ldb_message_element *other)
378         {
379             return ldb_msg_element_compare($self, other);
380         }
381
382         PyObject *__iter__(void)
383         {
384             return PyObject_GetIter(ldb_msg_element_to_set(NULL, $self));
385         }
386
387         PyObject *__set__(void)
388         {
389             return ldb_msg_element_to_set(NULL, $self);
390         }
391
392         ldb_message_element(PyObject *set_obj, int flags=0, const char *name = NULL)
393         {
394             return ldb_msg_element_from_pyobject(NULL, set_obj, flags, name);
395         }
396
397         int __len__()
398         {
399             return $self->num_values;
400         }
401 #endif
402
403         PyObject *get(int i)
404         {
405             if (i < 0 || i >= $self->num_values)
406                 return Py_None;
407
408             return ldb_val_to_py_object(NULL, $self, &$self->values[i]);
409         }
410
411         ~ldb_message_element() { talloc_free($self); }
412     }
413     %pythoncode {
414         def __getitem__(self, i):
415             ret = self.get(i)
416             if ret is None:
417                 raise KeyError("no such value")
418             return ret
419
420         def __repr__(self):
421             return "MessageElement([%s])" % (",".join(repr(x) for x in self.__set__()))
422
423         def __eq__(self, other):
424             if (len(self) == 1 and self.get(0) == other):
425                 return True
426             if isinstance(other, self.__class__):
427                 return self.__cmp__(other) == 0
428             o = iter(other)
429             for i in range(len(self)):
430                 if self.get(i) != o.next():
431                     return False
432             return True
433     }
434 } ldb_message_element;
435
436 /* ldb_message */
437
438 %feature("docstring") ldb_message "Message.";
439 %rename(Message) ldb_message;
440 #ifdef SWIGPYTHON
441 %rename(__delitem__) ldb_message::remove_attr;
442 %typemap(out) ldb_message_element * {
443         if ($1 == NULL)
444                 PyErr_SetString(PyExc_KeyError, "no such element");
445     else
446         $result = SWIG_NewPointerObj($1, SWIGTYPE_p_ldb_message_element, 0);
447 }
448
449 %inline {
450     PyObject *ldb_msg_list_elements(ldb_msg *msg)
451     {
452         int i, j = 0;
453         PyObject *obj = PyList_New(msg->num_elements+(msg->dn != NULL?1:0));
454         if (msg->dn != NULL) {
455             PyList_SetItem(obj, j, PyString_FromString("dn"));
456             j++;
457         }
458         for (i = 0; i < msg->num_elements; i++) {
459             PyList_SetItem(obj, j, PyString_FromString(msg->elements[i].name));
460             j++;
461         }
462         return obj;
463     }
464 }
465
466 #endif
467
468 typedef struct ldb_message {
469         ldb_dn *dn;
470
471     %extend {
472         ldb_msg(ldb_dn *dn = NULL) { 
473             ldb_msg *ret = ldb_msg_new(NULL); 
474             ret->dn = talloc_reference(ret, dn);
475             return ret;
476         }
477         ~ldb_msg() { talloc_free($self); }
478         ldb_message_element *find_element(const char *name);
479         
480 #ifdef SWIGPYTHON
481         void __setitem__(const char *attr_name, ldb_message_element *val)
482         {
483             struct ldb_message_element *el;
484             
485             ldb_msg_remove_attr($self, attr_name);
486
487             el = talloc($self, struct ldb_message_element);
488             el->name = talloc_strdup(el, attr_name);
489             el->num_values = val->num_values;
490             el->values = talloc_reference(el, val->values);
491
492             ldb_msg_add($self, el, val->flags);
493         }
494
495         void __setitem__(const char *attr_name, PyObject *val)
496         {
497             struct ldb_message_element *el = ldb_msg_element_from_pyobject(NULL,
498                                                 val, 0, attr_name);
499             talloc_steal($self, el);
500             ldb_msg_remove_attr($self, attr_name);
501             ldb_msg_add($self, el, el->flags);
502         }
503
504         unsigned int __len__() { return $self->num_elements; }
505
506         PyObject *keys(void)
507         {
508             return ldb_msg_list_elements($self);
509         }
510
511         PyObject *__iter__(void)
512         {
513             return PyObject_GetIter(ldb_msg_list_elements($self));
514         }
515 #endif
516         void remove_attr(const char *name);
517 %pythoncode {
518     def get(self, key, default=None):
519         if key == "dn":
520             return self.dn
521         return self.find_element(key)
522
523     def __getitem__(self, key):
524         ret = self.get(key, None)
525         if ret is None:
526             raise KeyError("No such element")
527         return ret
528
529     def iteritems(self):
530         for k in self.keys():
531             yield k, self[k]
532     
533     def items(self):
534         return list(self.iteritems())
535
536     def __repr__(self):
537         return "Message(%s)" % repr(dict(self.iteritems()))
538 }
539     }
540 } ldb_msg;
541
542 /* FIXME: Convert ldb_result to 3-tuple:
543    (msgs, refs, controls)
544  */
545
546 typedef struct ldb_ldif ldb_ldif;
547
548 #ifdef SWIGPYTHON
549 %{
550 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(3, 0);
551
552 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap)
553 {
554     char *text;
555     PyObject *fn = context;
556
557     vasprintf(&text, fmt, ap);
558     PyObject_CallFunction(fn, (char *)"(i,s)", level, text);
559     free(text);
560 }
561 %}
562
563 %typemap(in,numinputs=1,noblock=1) (void (*debug)(void *context, enum ldb_debug_level level, const char *fmt, va_list ap), void *context) {
564     $1 = py_ldb_debug;
565     /* FIXME: Should be decreased somewhere as well. Perhaps register a 
566        destructor and tie it to the ldb context ? */
567     Py_INCREF($input);
568     $2 = $input;
569 }
570 #endif
571
572 %inline {
573     static PyObject *ldb_ldif_to_pyobject(ldb_ldif *ldif)
574     {
575         if (ldif == NULL) {
576             return Py_None;
577         } else {
578             /* We don't want this attached to the 'ldb' any more */
579             talloc_steal(NULL, ldif);
580             return Py_BuildValue((char *)"(iO)", ldif->changetype, 
581                    SWIG_NewPointerObj(ldif->msg, SWIGTYPE_p_ldb_message, 0));
582         }
583     }
584 }
585
586 /*
587  * Wrap ldb errors
588  */
589
590 %{
591 PyObject *PyExc_LdbError;
592 %}
593
594 %pythoncode %{
595     LdbError = _ldb.LdbError
596 %}
597
598 %init %{
599     PyExc_LdbError = PyErr_NewException((char *)"_ldb.LdbError", NULL, NULL);
600     PyDict_SetItemString(d, "LdbError", PyExc_LdbError);
601 %}
602
603 %ignore _LDB_ERRORS_H_;
604 %ignore LDB_SUCCESS;
605 %include "include/ldb_errors.h"
606
607 /*
608  * Wrap ldb functions 
609  */
610
611
612 %typemap(out,noblock=1) ldb_error {
613     if ($1 != LDB_SUCCESS) {
614         PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", $1, ldb_errstring(arg1)));
615         SWIG_fail;
616     }
617     $result = Py_None;
618 };
619
620 %typemap(out,noblock=1) ldb_int_error {
621     if ($1 != LDB_SUCCESS) {
622         PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", $1, ldb_strerror($1)));
623         SWIG_fail;
624     }
625     $result = Py_None;
626 };
627
628 %typemap(out,noblock=1) struct ldb_control ** {
629     if ($1 == NULL) {
630         PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(s)", ldb_errstring(arg1)));
631         SWIG_fail;
632     }
633     $result = SWIG_NewPointerObj($1, $1_descriptor, 0);
634 }
635
636 %rename(Ldb) ldb_context;
637 %feature("docstring") ldb_context "Connection to a LDB database.";
638
639 %typemap(in,noblock=1) struct ldb_dn * {
640     if (ldb_dn_from_pyobject(NULL, $input, arg1, &$1) != 0) {
641         SWIG_fail;
642     }
643 };
644
645 %typemap(freearg,noblock=1) struct ldb_dn * {
646     talloc_free($1);
647 };
648
649 %typemap(in,numinputs=1) ldb_msg *add_msg {
650     Py_ssize_t dict_pos, msg_pos;
651     ldb_message_element *msgel;
652     PyObject *key, *value;
653
654     if (PyDict_Check($input)) {
655         PyObject *dn_value = PyDict_GetItemString($input, "dn");
656         $1 = ldb_msg_new(NULL);
657         $1->elements = talloc_zero_array($1, struct ldb_message_element, PyDict_Size($input));
658         msg_pos = dict_pos = 0;
659         if (dn_value) {
660                 /* using argp1 (magic SWIG value) here is a hack */
661                 if (ldb_dn_from_pyobject($1, dn_value, argp1, &$1->dn) != 0) {
662                     SWIG_exception(SWIG_TypeError, "unable to import dn object");
663                 }
664                 if ($1->dn == NULL) {
665                     SWIG_exception(SWIG_TypeError, "dn set but not found");
666                 }
667         }
668
669         while (PyDict_Next($input, &dict_pos, &key, &value)) {
670             char *key_str = PyString_AsString(key);
671             if (strcmp(key_str, "dn") != 0) {
672                 msgel = ldb_msg_element_from_pyobject($1->elements, value, 0, key_str);
673                 if (msgel == NULL) {
674                     SWIG_exception(SWIG_TypeError, "unable to import element");
675                 }
676                 memcpy(&$1->elements[msg_pos], msgel, sizeof(*msgel));
677                 msg_pos++;
678             }
679         }
680
681         if ($1->dn == NULL) {
682             SWIG_exception(SWIG_TypeError, "no dn set");
683         }
684
685         $1->num_elements = msg_pos;
686     } else {
687         if (SWIG_ConvertPtr($input, (void **)&$1, SWIGTYPE_p_ldb_message, 0) != 0) {
688             SWIG_exception(SWIG_TypeError, "unable to convert ldb message");
689         }
690     }
691 }
692
693 /* Top-level ldb operations */
694 typedef struct ldb_context {
695     %rename(firstmodule) modules;
696     struct ldb_module *modules;
697
698     %pythoncode {
699         def itermodules(self):
700             m = self.firstmodule
701             while m is not None:
702                 yield m
703                 m = m.next
704
705         def modules(self):
706             return list(self.itermodules())
707     }
708
709     %extend {
710         ldb(void) { 
711             return ldb_init(NULL, event_context_init(NULL)); 
712         }
713
714         %feature("docstring") connect "S.connect(url,flags=0,options=None) -> None\n" \
715                                       "Connect to a LDB URL.";
716         ldb_error connect(const char *url, unsigned int flags = 0, 
717             const char *const *options = NULL);
718
719         ~ldb() { talloc_free($self); }
720
721         ldb_error search_ex(TALLOC_CTX *mem_ctx,
722                    ldb_dn *base = NULL, 
723                    enum ldb_scope scope = LDB_SCOPE_DEFAULT, 
724                    const char *expression = NULL, 
725                    const char *const *attrs = NULL, 
726                    struct ldb_control **controls = NULL,
727                    struct ldb_result **OUT) {
728             int ret;
729             struct ldb_result *res;
730             struct ldb_request *req;
731             res = talloc_zero(mem_ctx, struct ldb_result);
732             if (!res) {
733                 return LDB_ERR_OPERATIONS_ERROR;
734             }
735
736             ret = ldb_build_search_req(&req, $self, mem_ctx,
737                            base?base:ldb_get_default_basedn($self),
738                            scope,
739                            expression,
740                            attrs,
741                            controls,
742                            res,
743                            ldb_search_default_callback,
744                            NULL);
745
746             if (ret != LDB_SUCCESS) {
747                 talloc_free(res);
748                 return ret;
749             }
750
751             ret = ldb_request($self, req);
752                 
753             if (ret == LDB_SUCCESS) {
754                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
755             }
756
757             talloc_free(req);
758
759             *OUT = res;
760             return ret;
761         }
762
763         %feature("docstring") delete "S.delete(dn) -> None\n" \
764                                      "Remove an entry.";
765         ldb_error delete(ldb_dn *dn);
766         %feature("docstring") rename "S.rename(old_dn, new_dn) -> None\n" \
767                                      "Rename an entry.";
768         ldb_error rename(ldb_dn *olddn, ldb_dn *newdn);
769         struct ldb_control **parse_control_strings(TALLOC_CTX *mem_ctx, 
770                                                    const char * const*control_strings);
771         %feature("docstring") add "S.add(message) -> None\n" \
772                                   "Add an entry.";
773         ldb_error add(ldb_msg *add_msg);
774         %feature("docstring") modify "S.modify(message) -> None\n" \
775                                   "Modify an entry.";
776         ldb_error modify(ldb_msg *message);
777         ldb_dn *get_config_basedn();
778         ldb_dn *get_root_basedn();
779         ldb_dn *get_schema_basedn();
780         ldb_dn *get_default_basedn();
781         PyObject *schema_format_value(const char *element_name, PyObject *val)
782         {
783                 const struct ldb_schema_attribute *a;
784                 struct ldb_val old_val;
785                 struct ldb_val new_val;
786                 TALLOC_CTX *mem_ctx = talloc_new(NULL);
787                 PyObject *ret;
788                 
789                 old_val.data = PyString_AsString(val);
790                 old_val.length = PyString_Size(val);
791                 
792                 a = ldb_schema_attribute_by_name($self, element_name);
793         
794                 if (a == NULL) {
795                         return Py_None;
796                 }
797                 
798                 if (a->syntax->ldif_write_fn($self, mem_ctx, &old_val, &new_val) != 0) {
799                         talloc_free(mem_ctx);
800                         return Py_None;
801                  }
802         
803                 ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
804                 
805                 talloc_free(mem_ctx);
806                 
807                 return ret;
808         }
809
810         const char *errstring();
811         %feature("docstring") set_create_perms "S.set_create_perms(mode) -> None\n" \
812                                                "Set mode to use when creating new LDB files.";
813         void set_create_perms(unsigned int perms);
814         %feature("docstring") set_modules_dir "S.set_modules_dir(path) -> None\n" \
815                                               "Set path LDB should search for modules";
816         void set_modules_dir(const char *path);
817         %feature("docstring") set_debug "S.set_debug(callback) -> None\n" \
818                                         "Set callback for LDB debug messages.\n" \
819                                         "The callback should accept a debug level and debug text.";
820         ldb_error set_debug(void (*debug)(void *context, enum ldb_debug_level level, 
821                                           const char *fmt, va_list ap),
822                             void *context);
823         %feature("docstring") set_opaque "S.set_opaque(name, value) -> None\n" \
824             "Set an opaque value on this LDB connection. \n"
825             ":note: Passing incorrect values may cause crashes.";
826         ldb_error set_opaque(const char *name, void *value);
827         %feature("docstring") get_opaque "S.get_opaque(name) -> value\n" \
828             "Get an opaque value set on this LDB connection. \n"
829             ":note: The returned value may not be useful in Python.";
830         void *get_opaque(const char *name);
831         %feature("docstring") transaction_start "S.transaction_start() -> None\n" \
832                                                 "Start a new transaction.";
833         ldb_error transaction_start();
834         %feature("docstring") transaction_commit "S.transaction_commit() -> None\n" \
835                                                  "Commit currently active transaction.";
836         ldb_error transaction_commit();
837         %feature("docstring") transaction_cancel "S.transaction_cancel() -> None\n" \
838                                                  "Cancel currently active transaction.";
839         ldb_error transaction_cancel();
840         void schema_attribute_remove(const char *name);
841         ldb_error schema_attribute_add(const char *attribute, unsigned flags, const char *syntax);
842         ldb_error setup_wellknown_attributes(void);
843  
844 #ifdef SWIGPYTHON
845         %typemap(in,numinputs=0,noblock=1) struct ldb_result **result_as_bool (struct ldb_result *tmp) { $1 = &tmp; }
846         %typemap(argout,noblock=1) struct ldb_result **result_as_bool { $result = ((*$1)->count > 0)?Py_True:Py_False; }
847         %typemap(freearg,noblock=1) struct ldb_result **result_as_bool { talloc_free(*$1); }
848         ldb_error __contains__(ldb_dn *dn, struct ldb_result **result_as_bool)
849         {
850             return ldb_search($self, $self, result_as_bool, dn, LDB_SCOPE_BASE, NULL, NULL);
851         }
852
853         %feature("docstring") parse_ldif "S.parse_ldif(ldif) -> iter(messages)\n" \
854             "Parse a string formatted using LDIF.";
855
856         PyObject *parse_ldif(const char *s)
857         {
858             PyObject *list = PyList_New(0);
859             struct ldb_ldif *ldif;
860             while ((ldif = ldb_ldif_read_string($self, &s)) != NULL) {
861                 PyList_Append(list, ldb_ldif_to_pyobject(ldif));
862             }
863             return PyObject_GetIter(list);
864         }
865
866         char *__repr__(void)
867         {
868             char *ret;
869             asprintf(&ret, "<ldb connection at 0x%x>", ret); 
870             return ret;
871         }
872 #endif
873     }
874     %pythoncode {
875         def __init__(self, url=None, flags=0, options=None):
876             """Create a new LDB object.
877
878             Will also connect to the specified URL if one was given.
879             """
880             _ldb.Ldb_swiginit(self,_ldb.new_Ldb())
881             if url is not None:
882                 self.connect(url, flags, options)
883
884         def search(self, base=None, scope=SCOPE_DEFAULT, expression=None, 
885                    attrs=None, controls=None):
886             """Search in a database.
887
888             :param base: Optional base DN to search
889             :param scope: Search scope (SCOPE_BASE, SCOPE_ONELEVEL or SCOPE_SUBTREE)
890             :param expression: Optional search expression
891             :param attrs: Attributes to return (defaults to all)
892             :param controls: Optional list of controls
893             :return: Iterator over Message objects
894             """
895             if not (attrs is None or isinstance(attrs, list)):
896                 raise TypeError("attributes not a list")
897             parsed_controls = None
898             if controls is not None:
899                 parsed_controls = self.parse_control_strings(controls)
900             return self.search_ex(base, scope, expression, attrs, 
901                                   parsed_controls)
902     }
903
904 } ldb;
905
906 %typemap(in,noblock=1) struct ldb_dn *;
907 %typemap(freearg,noblock=1) struct ldb_dn *;
908
909 %nodefault ldb_message;
910 %nodefault ldb_context;
911 %nodefault Dn;
912
913 %rename(valid_attr_name) ldb_valid_attr_name;
914 %feature("docstring") ldb_valid_attr_name "S.valid_attr_name(name) -> bool\n"
915                                           "Check whether the supplied name is a valid attribute name.";
916 int ldb_valid_attr_name(const char *s);
917
918 typedef unsigned long time_t;
919
920 %feature("docstring") timestring "S.timestring(int) -> string\n"
921                                  "Generate a LDAP time string from a UNIX timestamp";
922
923 %inline %{
924 static char *timestring(time_t t)
925 {
926     char *tresult = ldb_timestring(NULL, t);
927     char *result = strdup(tresult);
928     talloc_free(tresult);
929     return result; 
930 }
931 %}
932
933 %rename(string_to_time) ldb_string_to_time;
934 %feature("docstring") ldb_string_to_time "S.string_to_time(string) -> int\n"
935                                      "Parse a LDAP time string into a UNIX timestamp.";
936 time_t ldb_string_to_time(const char *s);
937
938 typedef struct ldb_module {
939     struct ldb_module *prev, *next;
940
941     %extend {
942 #ifdef SWIGPYTHON
943         const char *__str__() {
944             return $self->ops->name;
945         }
946         char *__repr__() {
947             char *ret;
948             asprintf(&ret, "<ldb module '%s'>", $self->ops->name);
949             return ret;
950         }
951 #endif
952         int search(struct ldb_dn *base, enum ldb_scope scope, struct ldb_parse_tree *tree, const char * const * attrs, struct ldb_result **res) {
953             int ret;
954             struct ldb_request *req = talloc_zero(NULL, struct ldb_request);
955
956             req->operation = LDB_SEARCH;
957             req->op.search.base = base;
958             req->op.search.scope = scope;
959             req->op.search.tree = tree;
960             req->op.search.attrs = attrs;
961
962             req->op.search.res = talloc_zero(NULL, struct ldb_result);
963
964             ret = $self->ops->search($self, req);
965
966             *res = req->op.search.res;
967
968             talloc_free(req);
969
970             return ret;
971         }
972         ldb_error add(struct ldb_message *message) {
973             struct ldb_request *req = talloc_zero(NULL, struct ldb_request);
974             req->operation = LDB_ADD;
975             req->op.add.message = message;
976             
977             return $self->ops->add($self, &req);
978         }
979         ldb_error modify(struct ldb_message *message) {
980             struct ldb_request *req = talloc_zero(NULL, struct ldb_request);
981             req->operation = LDB_MODIFY;
982             req->op.mod.message = message;
983             
984             return $self->ops->modify($self, &req);
985         }
986         ldb_error delete(struct ldb_dn *dn) {
987             struct ldb_request *req = talloc_zero(NULL, struct ldb_request);
988             req->operation = LDB_DELETE;
989             req->op.del.dn = dn;
990             
991             return $self->ops->del($self, &req);
992
993         }
994         ldb_error rename(struct ldb_dn *olddn, struct ldb_dn *newdn) {
995             struct ldb_request *req = talloc_zero(NULL, struct ldb_request);
996             req->operation = LDB_RENAME;
997             req->op.rename.olddn = olddn;
998             req->op.rename.olddn = newdn;
999             
1000             return $self->ops->rename($self, &req);
1001         }
1002         ldb_error start_transaction() {
1003             return $self->ops->start_transaction($self);
1004         }
1005         ldb_error end_transaction() {
1006             return $self->ops->end_transaction($self);
1007         }
1008         ldb_error del_transaction() {
1009             return $self->ops->del_transaction($self);
1010         }
1011     }
1012 } ldb_module;
1013
1014 %{
1015 int py_module_search(struct ldb_module *mod, struct ldb_request *req)
1016 {
1017     PyObject *py_ldb = mod->private_data;
1018     PyObject *py_result, *py_base, *py_attrs, *py_tree;
1019
1020     py_base = SWIG_NewPointerObj(req->op.search.base, SWIGTYPE_p_ldb_dn, 0);
1021
1022     if (py_base == NULL)
1023         return LDB_ERR_OPERATIONS_ERROR;
1024
1025     py_tree = SWIG_NewPointerObj(req->op.search.tree, SWIGTYPE_p_ldb_parse_tree, 0);
1026
1027     if (py_tree == NULL)
1028         return LDB_ERR_OPERATIONS_ERROR;
1029
1030     if (req->op.search.attrs == NULL) {
1031         py_attrs = Py_None;
1032     } else {
1033         int i, len;
1034         for (len = 0; req->op.search.attrs[len]; len++);
1035         py_attrs = PyList_New(len);
1036         for (i = 0; i < len; i++)
1037             PyList_SetItem(py_attrs, i, PyString_FromString(req->op.search.attrs[i]));
1038     }
1039
1040     py_result = PyObject_CallMethod(py_ldb, "search", "OiOO", py_base, req->op.search.scope, py_tree, py_attrs);
1041
1042     Py_DECREF(py_attrs);
1043     Py_DECREF(py_tree);
1044     Py_DECREF(py_base);
1045
1046     if (py_result == NULL) {
1047         return LDB_ERR_OPERATIONS_ERROR;
1048     }
1049
1050     if (SWIG_ConvertPtr(py_result, &req->op.search.res, SWIGTYPE_p_ldb_result, 0) != 0) {
1051         return LDB_ERR_OPERATIONS_ERROR;
1052     }
1053
1054     Py_DECREF(py_result);
1055
1056     return LDB_SUCCESS;
1057 }
1058
1059 int py_module_add(struct ldb_module *mod, struct ldb_request *req)
1060 {
1061     PyObject *py_ldb = mod->private_data;
1062     PyObject *py_result, *py_msg;
1063
1064     py_msg = SWIG_NewPointerObj(req->op.add.message, SWIGTYPE_p_ldb_message, 0);
1065
1066     if (py_msg == NULL) {
1067         return LDB_ERR_OPERATIONS_ERROR;
1068     }
1069
1070     py_result = PyObject_CallMethod(py_ldb, "add", "O", py_msg);
1071
1072     Py_DECREF(py_msg);
1073
1074     if (py_result == NULL) {
1075         return LDB_ERR_OPERATIONS_ERROR;
1076     }
1077
1078     Py_DECREF(py_result);
1079
1080     return LDB_SUCCESS;
1081 }
1082
1083 int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
1084 {
1085     PyObject *py_ldb = mod->private_data;
1086     PyObject *py_result, *py_msg;
1087
1088     py_msg = SWIG_NewPointerObj(req->op.mod.message, SWIGTYPE_p_ldb_message, 0);
1089
1090     if (py_msg == NULL) {
1091         return LDB_ERR_OPERATIONS_ERROR;
1092     }
1093
1094     py_result = PyObject_CallMethod(py_ldb, "modify", "O", py_msg);
1095
1096     Py_DECREF(py_msg);
1097
1098     if (py_result == NULL) {
1099         return LDB_ERR_OPERATIONS_ERROR;
1100     }
1101
1102     Py_DECREF(py_result);
1103
1104     return LDB_SUCCESS;
1105 }
1106
1107 int py_module_del(struct ldb_module *mod, struct ldb_request *req)
1108 {
1109     PyObject *py_ldb = mod->private_data;
1110     PyObject *py_result, *py_dn;
1111
1112     py_dn = SWIG_NewPointerObj(req->op.del.dn, SWIGTYPE_p_ldb_dn, 0);
1113
1114     if (py_dn == NULL)
1115         return LDB_ERR_OPERATIONS_ERROR;
1116
1117     py_result = PyObject_CallMethod(py_ldb, "delete", "O", py_dn);
1118
1119     if (py_result == NULL) {
1120         return LDB_ERR_OPERATIONS_ERROR;
1121     }
1122
1123     Py_DECREF(py_result);
1124
1125     return LDB_SUCCESS;
1126 }
1127
1128 int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
1129 {
1130     PyObject *py_ldb = mod->private_data;
1131     PyObject *py_result, *py_olddn, *py_newdn;
1132
1133     py_olddn = SWIG_NewPointerObj(req->op.rename.olddn, SWIGTYPE_p_ldb_dn, 0);
1134
1135     if (py_olddn == NULL)
1136         return LDB_ERR_OPERATIONS_ERROR;
1137
1138     py_newdn = SWIG_NewPointerObj(req->op.rename.newdn, SWIGTYPE_p_ldb_dn, 0);
1139
1140     if (py_newdn == NULL)
1141         return LDB_ERR_OPERATIONS_ERROR;
1142
1143     py_result = PyObject_CallMethod(py_ldb, "rename", "OO", py_olddn, py_newdn);
1144
1145     Py_DECREF(py_olddn);
1146     Py_DECREF(py_newdn);
1147
1148     if (py_result == NULL) {
1149         return LDB_ERR_OPERATIONS_ERROR;
1150     }
1151
1152     Py_DECREF(py_result);
1153
1154     return LDB_SUCCESS;
1155 }
1156
1157 int py_module_request(struct ldb_module *mod, struct ldb_request *req)
1158 {
1159     PyObject *py_ldb = mod->private_data;
1160     PyObject *py_result;
1161
1162     py_result = PyObject_CallMethod(py_ldb, "request", "");
1163
1164     return LDB_ERR_OPERATIONS_ERROR;
1165 }
1166
1167 int py_module_extended(struct ldb_module *mod, struct ldb_request *req)
1168 {
1169     PyObject *py_ldb = mod->private_data;
1170     PyObject *py_result;
1171
1172     py_result = PyObject_CallMethod(py_ldb, "extended", "");
1173
1174     return LDB_ERR_OPERATIONS_ERROR;
1175 }
1176
1177 int py_module_start_transaction(struct ldb_module *mod)
1178 {
1179     PyObject *py_ldb = mod->private_data;
1180     PyObject *py_result;
1181
1182     py_result = PyObject_CallMethod(py_ldb, "start_transaction", "");
1183
1184     if (py_result == NULL) {
1185         return LDB_ERR_OPERATIONS_ERROR;
1186     }
1187
1188     Py_DECREF(py_result);
1189
1190     return LDB_SUCCESS;
1191 }
1192
1193 int py_module_end_transaction(struct ldb_module *mod)
1194 {
1195     PyObject *py_ldb = mod->private_data;
1196     PyObject *py_result;
1197
1198     py_result = PyObject_CallMethod(py_ldb, "end_transaction", "");
1199
1200     if (py_result == NULL) {
1201         return LDB_ERR_OPERATIONS_ERROR;
1202     }
1203
1204     Py_DECREF(py_result);
1205
1206     return LDB_SUCCESS;
1207 }
1208
1209 int py_module_del_transaction(struct ldb_module *mod)
1210 {
1211     PyObject *py_ldb = mod->private_data;
1212     PyObject *py_result;
1213
1214     py_result = PyObject_CallMethod(py_ldb, "del_transaction", "");
1215
1216     if (py_result == NULL) {
1217         return LDB_ERR_OPERATIONS_ERROR;
1218     }
1219
1220     Py_DECREF(py_result);
1221
1222     return LDB_SUCCESS;
1223 }
1224
1225 static int py_module_destructor(void *_mod)
1226 {
1227     struct ldb_module *mod = _mod;
1228     Py_DECREF((PyObject *)mod->private_data);
1229     return 0;
1230 }
1231
1232 int py_module_init (struct ldb_module *mod)
1233 {
1234     PyObject *py_class = mod->ops->private_data;
1235     PyObject *py_result, *py_next, *py_ldb;
1236
1237     py_ldb = SWIG_NewPointerObj(mod->ldb, SWIGTYPE_p_ldb_context, 0);
1238
1239     if (py_ldb == NULL)
1240         return LDB_ERR_OPERATIONS_ERROR;
1241
1242     py_next = SWIG_NewPointerObj(mod->next, SWIGTYPE_p_ldb_module, 0);
1243
1244     if (py_next == NULL)
1245         return LDB_ERR_OPERATIONS_ERROR;
1246
1247     py_result = PyObject_CallFunction(py_class, "OO", py_ldb, py_next);
1248
1249     if (py_result == NULL) {
1250         return LDB_ERR_OPERATIONS_ERROR;
1251     }
1252
1253     mod->private_data = py_result;
1254
1255     talloc_set_destructor (mod, py_module_destructor);
1256
1257     return ldb_next_init(mod);
1258 }
1259 %}
1260
1261 %typemap(in,noblock=1) const struct ldb_module_ops * {
1262     $1 = talloc_zero(talloc_autofree_context(), struct ldb_module_ops);
1263
1264     $1->name = talloc_strdup($1, PyString_AsString(PyObject_GetAttrString($input, (char *)"name")));
1265
1266     Py_INCREF($input);
1267     $1->private_data = $input;
1268     $1->init_context = py_module_init;
1269     $1->search = py_module_search;
1270     $1->add = py_module_add;
1271     $1->modify = py_module_modify;
1272     $1->del = py_module_del;
1273     $1->rename = py_module_rename;
1274     $1->request = py_module_request;
1275     $1->extended = py_module_extended;
1276     $1->start_transaction = py_module_start_transaction;
1277     $1->end_transaction = py_module_end_transaction;
1278     $1->del_transaction = py_module_del_transaction;
1279 }
1280
1281 %feature("docstring") ldb_register_module "S.register_module(module) -> None\n"
1282                                           "Register a LDB module.";
1283 %rename(register_module) ldb_register_module;
1284 ldb_int_error ldb_register_module(const struct ldb_module_ops *);
1285
1286 %pythoncode {
1287 __docformat__ = "restructuredText"
1288 open = Ldb
1289 }