python/ldb: Add __getitem__ implementation for LdbMessageElement.
[ira/wip.git] / source / 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 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 %module ldb
29
30 %{
31
32 #include <stdint.h>
33 #include <stdbool.h>
34 #include "talloc.h"
35 #include "ldb.h"
36 #include "ldb_errors.h"
37 #include "ldb_private.h"
38
39 typedef struct ldb_message ldb_msg;
40 typedef struct ldb_context ldb;
41 typedef struct ldb_dn ldb_dn;
42 typedef struct ldb_ldif ldb_ldif;
43 typedef struct ldb_message_element ldb_msg_element;
44 typedef int ldb_error;
45
46 %}
47
48 %import "carrays.i"
49 %import "typemaps.i"
50 %include "exception.i"
51 %import "stdint.i"
52
53 %constant int SCOPE_DEFAULT = LDB_SCOPE_DEFAULT;
54 %constant int SCOPE_BASE = LDB_SCOPE_BASE;
55 %constant int SCOPE_ONELEVEL = LDB_SCOPE_ONELEVEL;
56 %constant int SCOPE_SUBTREE = LDB_SCOPE_SUBTREE;
57
58 %constant int CHANGETYPE_NONE = LDB_CHANGETYPE_NONE;
59 %constant int CHANGETYPE_ADD = LDB_CHANGETYPE_ADD;
60 %constant int CHANGETYPE_DELETE = LDB_CHANGETYPE_DELETE;
61 %constant int CHANGETYPE_MODIFY = LDB_CHANGETYPE_MODIFY;
62
63 /* 
64  * Wrap struct ldb_context
65  */
66
67 /* The ldb functions will crash if a NULL ldb context is passed so
68    catch this before it happens. */
69
70 %typemap(check,noblock=1) struct ldb_context* {
71         if ($1 == NULL)
72                 SWIG_exception(SWIG_ValueError, 
73                         "ldb context must be non-NULL");
74 }
75
76 %typemap(check,noblock=1) ldb_msg * {
77         if ($1 == NULL)
78                 SWIG_exception(SWIG_ValueError, 
79                         "Message can not be None");
80 }
81
82 /*
83  * Wrap struct ldb_val
84  */
85
86 %typemap(in,noblock=1) struct ldb_val *INPUT (struct ldb_val temp) {
87         $1 = &temp;
88         if (!PyString_Check($input)) {
89                 PyErr_SetString(PyExc_TypeError, "string arg expected");
90                 return NULL;
91         }
92         $1->length = PyString_Size($input);
93         $1->data = PyString_AsString($input);
94 }
95
96 %typemap(out,noblock=1) struct ldb_val {
97         $result = PyString_FromStringAndSize((const char *)$1.data, $1.length);
98 }
99
100 /*
101  * Wrap struct ldb_result
102  */
103
104 %typemap(in,noblock=1,numinputs=0) struct ldb_result **OUT (struct ldb_result *temp_ldb_result) {
105         $1 = &temp_ldb_result;
106 }
107
108 #ifdef SWIGPYTHON
109 %typemap(argout,noblock=1) struct ldb_result ** (int i) {
110         $result = PyList_New((*$1)->count);
111     for (i = 0; i < (*$1)->count; i++) {
112         PyList_SetItem($result, i, 
113             SWIG_NewPointerObj((*$1)->msgs[i], SWIGTYPE_p_ldb_message, 0)
114         );
115     }
116 }
117
118 %typemap(in,noblock=1,numinputs=1) const char * const *attrs {
119     if ($input == Py_None) {
120         $1 = NULL;
121     } else if (PySequence_Check($input)) {
122         int i;
123         $1 = talloc_array(NULL, char *, PySequence_Size($input)+1);
124         for(i = 0; i < PySequence_Size($input); i++)
125             $1[i] = PyString_AsString(PySequence_GetItem($input, i));
126         $1[i] = NULL;
127     } else {
128         SWIG_exception(SWIG_TypeError, "expected sequence");
129     }
130 }
131
132 %typemap(freearg,noblock=1) const char * const *attrs {
133     talloc_free($1);
134 }
135 #endif
136
137 %types(struct ldb_result *);
138
139 /*
140  * Wrap struct ldb_dn
141  */
142
143 %rename(__str__) ldb_dn::get_linearized;
144 %rename(__cmp__) ldb_dn::compare;
145 %rename(__len__) ldb_dn::get_comp_num;
146 %rename(Dn) ldb_dn;
147 typedef struct ldb_dn {
148     %extend {
149         ldb_dn(ldb *ldb_ctx, const char *str)
150         {
151             ldb_dn *ret = ldb_dn_new(ldb_ctx, ldb_ctx, str);
152             /* ldb_dn_new() doesn't accept NULL as memory context, so 
153                we do it this way... */
154             talloc_steal(NULL, ret);
155
156             if (ret == NULL)
157                 SWIG_exception(SWIG_ValueError, 
158                                 "unable to parse dn string");
159 fail:
160             return ret;
161         }
162         ~ldb_dn() { talloc_free($self); }
163         bool validate();
164         const char *get_casefold();
165         const char *get_linearized();
166         ldb_dn *parent() { return ldb_dn_get_parent(NULL, $self); }
167         int compare(ldb_dn *other);
168         bool is_valid();
169         bool is_special();
170         bool is_null();
171         bool check_special(const char *name);
172         int get_comp_num();
173         bool add_child(ldb_dn *child);
174         bool add_base(ldb_dn *base);
175         const char *canonical_str() {
176             return ldb_dn_canonical_string($self, $self);
177         }
178         const char *canonical_ex_str() {
179             return ldb_dn_canonical_ex_string($self, $self);
180         }
181 #ifdef SWIGPYTHON
182         ldb_dn *__add__(ldb_dn *other)
183         {
184             ldb_dn *ret = ldb_dn_copy(NULL, $self);
185             ldb_dn_add_child(ret, other);
186             return ret;
187         }
188
189         /* FIXME: implement __getslice__ */
190 #endif
191     }
192 } ldb_dn;
193
194 #ifdef SWIGPYTHON
195 %{
196 int ldb_dn_from_pyobject(TALLOC_CTX *mem_ctx, PyObject *object, 
197                          struct ldb_context *ldb_ctx, ldb_dn **dn)
198 {
199     int ret;
200     struct ldb_dn *odn;
201     if (ldb_ctx != NULL && PyString_Check(object)) {
202         *dn = ldb_dn_new(mem_ctx, ldb_ctx, PyString_AsString(object));
203         return 0;
204     }
205     ret = SWIG_ConvertPtr(object, (void **)&odn, SWIGTYPE_p_ldb_dn, 
206                            SWIG_POINTER_EXCEPTION);
207     *dn = ldb_dn_copy(mem_ctx, odn);
208     return ret;
209 }
210
211 ldb_msg_element *ldb_msg_element_from_pyobject(TALLOC_CTX *mem_ctx,
212                                                PyObject *set_obj, int flags,
213                                                const char *attr_name)
214 {
215     struct ldb_message_element *me = talloc(mem_ctx, struct ldb_message_element);
216     me->name = attr_name;
217     me->flags = flags;
218     if (PyString_Check(set_obj)) {
219         me->num_values = 1;
220         me->values = talloc_array(me, struct ldb_val, me->num_values);
221         me->values[0].length = PyString_Size(set_obj);
222         me->values[0].data = (uint8_t *)talloc_strdup(me->values, 
223                                            PyString_AsString(set_obj));
224     } else if (PySequence_Check(set_obj)) {
225         int i;
226         me->num_values = PySequence_Size(set_obj);
227         me->values = talloc_array(me, struct ldb_val, me->num_values);
228         for (i = 0; i < me->num_values; i++) {
229             PyObject *obj = PySequence_GetItem(set_obj, i);
230             me->values[i].length = PyString_Size(obj);
231             me->values[i].data = (uint8_t *)PyString_AsString(obj);
232         }
233     } else {
234         talloc_free(me);
235         me = NULL;
236     }
237
238     return me;
239 }
240
241 PyObject *ldb_msg_element_to_set(ldb_msg_element *me)
242 {
243     int i;
244     PyObject *result;
245
246     /* Python << 2.5 doesn't have PySet_New and PySet_Add. */
247     result = PyList_New(me->num_values);
248
249     for (i = 0; i < me->num_values; i++) {
250         PyList_SetItem(result, i,
251             PyString_FromStringAndSize((const char *)me->values[i].data, 
252                                        me->values[i].length));
253     }
254
255     return result;
256 }
257
258 %}
259 #endif
260
261 /* ldb_message_element */
262 %rename(__cmp__) ldb_message_element::compare;
263 %rename(MessageElement) ldb_msg_element;
264 typedef struct ldb_message_element {
265     %extend {
266 #ifdef SWIGPYTHON
267         PyObject *__iter__(void)
268         {
269             return PyObject_GetIter(ldb_msg_element_to_set($self));
270         }
271
272         PyObject *__set__(void)
273         {
274             return ldb_msg_element_to_set($self);
275         }
276
277         ldb_msg_element(PyObject *set_obj, int flags=0, const char *name = NULL)
278         {
279             return ldb_msg_element_from_pyobject(NULL, set_obj, flags, name);
280         }
281 #endif
282
283         PyObject *get(int i)
284         {
285             if (i < 0 || i >= $self->num_values)
286                 return Py_None;
287
288             return PyString_FromStringAndSize(
289                         (const char *)$self->values[i].data, 
290                         $self->values[i].length);
291         }
292
293         ~ldb_msg_element() { talloc_free($self); }
294         int compare(ldb_msg_element *);
295     }
296     %pythoncode {
297         def __getitem__(self, i):
298             ret = self.get(i)
299             if ret is None:
300                 raise KeyError("no such value")
301             return ret
302
303         def __eq__(self, other):
304             if (isinstance(other, str) and 
305                 len(set(self)) == 1 and 
306                 set(self).pop() == other):
307                 return True
308             return self.__cmp__(other) == 0
309                 
310     }
311 } ldb_msg_element;
312
313 /* ldb_message */
314
315 %rename(Message) ldb_message;
316 #ifdef SWIGPYTHON
317 %rename(__delitem__) ldb_message::remove_attr;
318 %typemap(out) ldb_msg_element * {
319         if ($1 == NULL)
320                 PyErr_SetString(PyExc_KeyError, "no such element");
321     else
322         $result = SWIG_NewPointerObj($1, SWIGTYPE_p_ldb_message_element, 0);
323 }
324 %rename(__getitem__) ldb_message::find_element;
325 //%typemap(out) ldb_msg_element *;
326
327
328 %inline {
329     PyObject *ldb_msg_list_elements(ldb_msg *msg)
330     {
331         int i;
332         PyObject *obj = PyList_New(msg->num_elements);
333         for (i = 0; i < msg->num_elements; i++)
334             PyList_SetItem(obj, i, PyString_FromString(msg->elements[i].name));
335         return obj;
336     }
337 }
338
339 #endif
340
341 typedef struct ldb_message {
342         ldb_dn *dn;
343
344     %extend {
345         ldb_msg(ldb_dn *dn = NULL) { 
346             ldb_msg *ret = ldb_msg_new(NULL); 
347             ret->dn = talloc_reference(ret, dn);
348             return ret;
349         }
350         ~ldb_msg() { talloc_free($self); }
351         ldb_msg_element *find_element(const char *name);
352         
353 #ifdef SWIGPYTHON
354         void __setitem__(const char *attr_name, ldb_msg_element *val)
355         {
356             struct ldb_message_element *el;
357             
358             ldb_msg_remove_attr($self, attr_name);
359
360             el = talloc($self, struct ldb_message_element);
361             el->name = talloc_strdup(el, attr_name);
362             el->num_values = val->num_values;
363             el->values = talloc_reference(el, val->values);
364
365             ldb_msg_add($self, el, val->flags);
366         }
367
368         void __setitem__(const char *attr_name, PyObject *val)
369         {
370             struct ldb_message_element *el = ldb_msg_element_from_pyobject(NULL,
371                                                 val, 0, attr_name);
372             talloc_steal($self, el);
373             ldb_msg_remove_attr($self, attr_name);
374             ldb_msg_add($self, el, el->flags);
375         }
376
377         unsigned int __len__() { return $self->num_elements; }
378
379         PyObject *keys(void)
380         {
381             return ldb_msg_list_elements($self);
382         }
383
384         PyObject *__iter__(void)
385         {
386             return PyObject_GetIter(ldb_msg_list_elements($self));
387         }
388 #endif
389         void remove_attr(const char *name);
390     }
391 } ldb_msg;
392
393 /* FIXME: Convert ldb_result to 3-tuple:
394    (msgs, refs, controls)
395  */
396
397 typedef struct ldb_ldif ldb_ldif;
398
399 #ifdef SWIGPYTHON
400 %{
401 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap)
402 {
403     char *text;
404     PyObject *fn = context;
405
406     vasprintf(&text, fmt, ap);
407     PyObject_CallFunction(fn, (char *)"(i,s)", level, text);
408     free(text);
409 }
410 %}
411
412 %typemap(in,numinputs=1,noblock=1) (void (*debug)(void *context, enum ldb_debug_level level, const char *fmt, va_list ap), void *context) {
413     $1 = py_ldb_debug;
414     /* FIXME: Should be decreased somewhere as well. Perhaps register a 
415        destructor and tie it to the ldb context ? */
416     Py_INCREF($input);
417     $2 = $input;
418 }
419 #endif
420
421 %inline {
422     static PyObject *ldb_ldif_to_pyobject(ldb_ldif *ldif)
423     {
424         if (ldif == NULL) {
425             return Py_None;
426         } else {
427             return Py_BuildValue((char *)"(iO)", ldif->changetype, 
428                    SWIG_NewPointerObj(ldif->msg, SWIGTYPE_p_ldb_message, 0));
429         }
430     }
431 }
432
433 /*
434  * Wrap ldb errors
435  */
436
437 %{
438 PyObject *PyExc_LdbError;
439 %}
440
441 %pythoncode %{
442     LdbError = _ldb.LdbError
443 %}
444
445 %init %{
446     PyExc_LdbError = PyErr_NewException((char *)"_ldb.LdbError", NULL, NULL);
447     PyDict_SetItemString(d, "LdbError", PyExc_LdbError);
448 %}
449
450 %ignore _LDB_ERRORS_H_;
451 %ignore LDB_SUCCESS;
452 %include "include/ldb_errors.h"
453
454 /*
455  * Wrap ldb functions 
456  */
457
458
459 %typemap(out,noblock=1) ldb_error {
460     if ($1 != LDB_SUCCESS) {
461         PyErr_SetObject(PyExc_LdbError, Py_BuildValue((char *)"(i,s)", $1, ldb_strerror($1)));
462         SWIG_fail;
463     }
464     $result = Py_None;
465 };
466
467 %rename(Ldb) ldb_context;
468
469 %typemap(in,noblock=1) struct ldb_dn * {
470     if (ldb_dn_from_pyobject(NULL, $input, arg1, &$1) != 0) {
471         SWIG_fail;
472     }
473 };
474
475 %typemap(freearg,noblock=1) struct ldb_dn * {
476     talloc_free($1);
477 };
478
479 /* Top-level ldb operations */
480 typedef struct ldb_context {
481     %extend {
482         ldb(void) { return ldb_init(NULL); }
483
484         ldb_error connect(const char *url, unsigned int flags = 0, 
485             const char *options[] = NULL);
486
487         ~ldb() { talloc_free($self); }
488         ldb_error search(ldb_dn *base = NULL, 
489                    enum ldb_scope scope = LDB_SCOPE_DEFAULT, 
490                    const char *expression = NULL, 
491                    const char * const *attrs = NULL, 
492                    struct ldb_result **OUT);
493         ldb_error delete(ldb_dn *dn);
494         ldb_error rename(ldb_dn *olddn, ldb_dn *newdn);
495         ldb_error add(ldb_msg *add_msg);
496         ldb_error add(PyObject *py_msg) 
497         {
498             ldb_error ret;
499             int dict_pos, msg_pos;
500             PyObject *key, *value;
501             ldb_msg_element *msgel;
502             ldb_msg *msg = NULL;
503
504             if (PyDict_Check(py_msg)) {
505                 msg = ldb_msg_new(NULL);
506                 msg->elements = talloc_zero_array(msg, struct ldb_message_element, PyDict_Size(py_msg));
507                 msg_pos = dict_pos = 0;
508                 while (PyDict_Next(py_msg, &dict_pos, &key, &value)) {
509                     if (!strcmp(PyString_AsString(key), "dn")) {
510                         if (ldb_dn_from_pyobject(msg, value, $self, &msg->dn) != 0) {
511                             return LDB_ERR_OTHER;
512                         }
513                     } else {
514                         msgel = ldb_msg_element_from_pyobject(msg->elements, value, 0, PyString_AsString(key));
515                         if (msgel == NULL) {
516                             SWIG_exception(SWIG_TypeError, "unable to import element");
517                             return LDB_ERR_OTHER;
518                         }
519                         memcpy(&msg->elements[msg_pos], msgel, sizeof(*msgel));
520                         msg_pos++;
521                     }
522                 }
523
524                 if (msg->dn == NULL) {
525                     SWIG_exception(SWIG_TypeError, "no dn set");
526                     return LDB_ERR_OTHER;
527                 }
528
529                 msg->num_elements = msg_pos;
530             } else {
531                 if (SWIG_ConvertPtr(py_msg, (void **)&msg, SWIGTYPE_p_ldb_message, 0) != 0)
532                     return LDB_ERR_OTHER;
533             }
534
535             ret = ldb_add($self, msg);
536
537             talloc_free(msg);
538             return ret;
539
540             fail:
541             return LDB_ERR_OTHER;
542         }
543         ldb_error modify(ldb_msg *message);
544         ldb_dn *get_config_basedn();
545         ldb_dn *get_root_basedn();
546         ldb_dn *get_schema_basedn();
547         ldb_dn *get_default_basedn();
548         const char *errstring();
549         void set_create_perms(unsigned int perms);
550         void set_modules_dir(const char *path);
551         ldb_error set_debug(void (*debug)(void *context, enum ldb_debug_level level, 
552                                           const char *fmt, va_list ap),
553                             void *context);
554         ldb_error set_opaque(const char *name, void *value);
555         void *get_opaque(const char *name);
556         ldb_error transaction_start();
557         ldb_error transaction_commit();
558         ldb_error transaction_cancel();
559
560 #ifdef SWIGPYTHON
561         %typemap(in,numinputs=0,noblock=1) struct ldb_result **result_as_bool (struct ldb_result *tmp) { $1 = &tmp; }
562         %typemap(argout,noblock=1) struct ldb_result **result_as_bool { $result = ((*$1)->count > 0)?Py_True:Py_False; }
563         %typemap(freearg,noblock=1) struct ldb_result **result_as_bool { talloc_free(*$1); }
564         ldb_error __contains__(ldb_dn *dn, struct ldb_result **result_as_bool)
565         {
566             return ldb_search($self, dn, LDB_SCOPE_BASE, NULL, NULL, 
567                              result_as_bool);
568         }
569
570         PyObject *parse_ldif(const char *s)
571         {
572             PyObject *list = PyList_New(0);
573             struct ldb_ldif *ldif;
574             while ((ldif = ldb_ldif_read_string($self, &s)) != NULL) {
575                 PyList_Append(list, ldb_ldif_to_pyobject(ldif));
576             }
577             return PyObject_GetIter(list);
578         }
579
580 #endif
581     }
582     %pythoncode {
583         def __init__(self, url=None, flags=0, options=None):
584             _ldb.Ldb_swiginit(self,_ldb.new_Ldb())
585             if url is not None:
586                 self.connect(url, flags, options)
587     }
588
589 } ldb;
590
591 %typemap(in,noblock=1) struct ldb_dn *;
592 %typemap(freearg,noblock=1) struct ldb_dn *;
593
594 %nodefault ldb_message;
595 %nodefault ldb_context;
596 %nodefault Dn;
597
598 %rename(valid_attr_name) ldb_valid_attr_name;
599 int ldb_valid_attr_name(const char *s);
600
601 typedef unsigned long time_t;
602
603 %inline %{
604 static char *timestring(time_t t)
605 {
606     char *tresult = ldb_timestring(NULL, t);
607     char *result = strdup(tresult);
608     talloc_free(tresult);
609     return result; 
610 }
611 %}
612
613 %rename(string_to_time) ldb_string_to_time;
614 time_t ldb_string_to_time(const char *s);
615
616 %typemap(in,noblock=1) const struct ldb_module_ops * {
617     $1 = talloc_zero(talloc_autofree_context(), struct ldb_module_ops);
618
619     $1->name = (char *)PyObject_GetAttrString($input, (char *)"name");
620 }
621
622 %rename(register_module) ldb_register_module;
623 ldb_error ldb_register_module(const struct ldb_module_ops *);