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