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