s4-netlogon: implement dcesrv_netr_DsRAddressToSitenamesExW
[Samba/aatanasov.git] / source4 / lib / ldb / pyldb.c
blobb4f03dc538640e1ba909df65d30e645ae6b35a27
1 /*
2 Unix SMB/CIFS implementation.
4 Python interface to ldb.
6 Copyright (C) 2005,2006 Tim Potter <tpot@samba.org>
7 Copyright (C) 2006 Simo Sorce <idra@samba.org>
8 Copyright (C) 2007-2009 Jelmer Vernooij <jelmer@samba.org>
9 Copyright (C) 2009 Matthias Dieter Wallnöfer
11 ** NOTE! The following LGPL license applies to the ldb
12 ** library. This does NOT imply that all of Samba is released
13 ** under the LGPL
15 This library is free software; you can redistribute it and/or
16 modify it under the terms of the GNU Lesser General Public
17 License as published by the Free Software Foundation; either
18 version 3 of the License, or (at your option) any later version.
20 This library is distributed in the hope that it will be useful,
21 but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 Lesser General Public License for more details.
25 You should have received a copy of the GNU Lesser General Public
26 License along with this library; if not, see <http://www.gnu.org/licenses/>.
29 #include "replace.h"
30 #include "ldb_private.h"
31 #include <Python.h>
32 #include "pyldb.h"
34 /* There's no Py_ssize_t in 2.4, apparently */
35 #if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION < 5
36 typedef int Py_ssize_t;
37 typedef inquiry lenfunc;
38 typedef intargfunc ssizeargfunc;
39 #endif
41 #ifndef Py_RETURN_NONE
42 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
43 #endif
45 static void PyErr_SetLdbError(PyObject *error, int ret, struct ldb_context *ldb_ctx)
47 if (ret == LDB_ERR_PYTHON_EXCEPTION)
48 return; /* Python exception should already be set, just keep that */
50 PyErr_SetObject(error,
51 Py_BuildValue(discard_const_p(char, "(i,s)"), ret,
52 ldb_ctx == NULL?ldb_strerror(ret):ldb_errstring(ldb_ctx)));
55 static PyObject *PyExc_LdbError;
57 PyAPI_DATA(PyTypeObject) PyLdbMessage;
58 PyAPI_DATA(PyTypeObject) PyLdbModule;
59 PyAPI_DATA(PyTypeObject) PyLdbDn;
60 PyAPI_DATA(PyTypeObject) PyLdb;
61 PyAPI_DATA(PyTypeObject) PyLdbMessageElement;
62 PyAPI_DATA(PyTypeObject) PyLdbTree;
64 static PyObject *PyObject_FromLdbValue(struct ldb_context *ldb_ctx,
65 struct ldb_message_element *el,
66 struct ldb_val *val)
68 struct ldb_val new_val;
69 TALLOC_CTX *mem_ctx = talloc_new(NULL);
70 PyObject *ret;
72 new_val = *val;
74 ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
76 talloc_free(mem_ctx);
78 return ret;
81 /**
82 * Obtain a ldb DN from a Python object.
84 * @param mem_ctx Memory context
85 * @param object Python object
86 * @param ldb_ctx LDB context
87 * @return Whether or not the conversion succeeded
89 bool PyObject_AsDn(TALLOC_CTX *mem_ctx, PyObject *object,
90 struct ldb_context *ldb_ctx, struct ldb_dn **dn)
92 struct ldb_dn *odn;
94 if (ldb_ctx != NULL && PyString_Check(object)) {
95 odn = ldb_dn_new(mem_ctx, ldb_ctx, PyString_AsString(object));
96 *dn = odn;
97 return true;
100 if (PyLdbDn_Check(object)) {
101 *dn = PyLdbDn_AsDn(object);
102 return true;
105 PyErr_SetString(PyExc_TypeError, "Expected DN");
106 return false;
110 * Create a Python object from a ldb_result.
112 * @param result LDB result to convert
113 * @return Python object with converted result (a list object)
115 static PyObject *PyLdbResult_FromResult(struct ldb_result *result)
117 PyObject *ret;
118 int i;
119 if (result == NULL) {
120 Py_RETURN_NONE;
122 ret = PyList_New(result->count);
123 for (i = 0; i < result->count; i++) {
124 PyList_SetItem(ret, i, PyLdbMessage_FromMessage(result->msgs[i])
127 return ret;
131 * Create a LDB Result from a Python object.
132 * If conversion fails, NULL will be returned and a Python exception set.
134 * @param mem_ctx Memory context in which to allocate the LDB Result
135 * @param obj Python object to convert
136 * @return a ldb_result, or NULL if the conversion failed
138 static struct ldb_result *PyLdbResult_AsResult(TALLOC_CTX *mem_ctx,
139 PyObject *obj)
141 struct ldb_result *res;
142 int i;
144 if (obj == Py_None)
145 return NULL;
147 res = talloc_zero(mem_ctx, struct ldb_result);
148 res->count = PyList_Size(obj);
149 res->msgs = talloc_array(res, struct ldb_message *, res->count);
150 for (i = 0; i < res->count; i++) {
151 PyObject *item = PyList_GetItem(obj, i);
152 res->msgs[i] = PyLdbMessage_AsMessage(item);
154 return res;
157 static PyObject *py_ldb_dn_validate(PyLdbDnObject *self)
159 return PyBool_FromLong(ldb_dn_validate(self->dn));
162 static PyObject *py_ldb_dn_is_valid(PyLdbDnObject *self)
164 return PyBool_FromLong(ldb_dn_is_valid(self->dn));
167 static PyObject *py_ldb_dn_is_special(PyLdbDnObject *self)
169 return PyBool_FromLong(ldb_dn_is_special(self->dn));
172 static PyObject *py_ldb_dn_is_null(PyLdbDnObject *self)
174 return PyBool_FromLong(ldb_dn_is_null(self->dn));
177 static PyObject *py_ldb_dn_get_casefold(PyLdbDnObject *self)
179 return PyString_FromString(ldb_dn_get_casefold(self->dn));
182 static PyObject *py_ldb_dn_get_linearized(PyLdbDnObject *self)
184 return PyString_FromString(ldb_dn_get_linearized(self->dn));
187 static PyObject *py_ldb_dn_canonical_str(PyLdbDnObject *self)
189 return PyString_FromString(ldb_dn_canonical_string(self->dn, self->dn));
192 static PyObject *py_ldb_dn_canonical_ex_str(PyLdbDnObject *self)
194 return PyString_FromString(ldb_dn_canonical_ex_string(self->dn, self->dn));
197 static PyObject *py_ldb_dn_repr(PyLdbDnObject *self)
199 return PyString_FromFormat("Dn(%s)", PyObject_REPR(PyString_FromString(ldb_dn_get_linearized(self->dn))));
202 static PyObject *py_ldb_dn_check_special(PyLdbDnObject *self, PyObject *args)
204 char *name;
206 if (!PyArg_ParseTuple(args, "s", &name))
207 return NULL;
209 return ldb_dn_check_special(self->dn, name)?Py_True:Py_False;
212 static int py_ldb_dn_compare(PyLdbDnObject *dn1, PyLdbDnObject *dn2)
214 int ret;
215 ret = ldb_dn_compare(dn1->dn, dn2->dn);
216 if (ret < 0) ret = -1;
217 if (ret > 0) ret = 1;
218 return ret;
221 static PyObject *py_ldb_dn_get_parent(PyLdbDnObject *self)
223 struct ldb_dn *dn = PyLdbDn_AsDn((PyObject *)self);
224 struct ldb_dn *parent;
225 PyLdbDnObject *py_ret;
226 TALLOC_CTX *mem_ctx = talloc_new(NULL);
228 parent = ldb_dn_get_parent(mem_ctx, dn);
229 if (parent == NULL) {
230 talloc_free(mem_ctx);
231 Py_RETURN_NONE;
234 py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
235 if (py_ret == NULL) {
236 PyErr_NoMemory();
237 talloc_free(mem_ctx);
238 return NULL;
240 py_ret->mem_ctx = mem_ctx;
241 py_ret->dn = parent;
242 return (PyObject *)py_ret;
245 #define dn_ldb_ctx(dn) ((struct ldb_context *)dn)
247 static PyObject *py_ldb_dn_add_child(PyLdbDnObject *self, PyObject *args)
249 PyObject *py_other;
250 struct ldb_dn *dn, *other;
251 if (!PyArg_ParseTuple(args, "O", &py_other))
252 return NULL;
254 dn = PyLdbDn_AsDn((PyObject *)self);
256 if (!PyObject_AsDn(NULL, py_other, dn_ldb_ctx(dn), &other))
257 return NULL;
259 return ldb_dn_add_child(dn, other)?Py_True:Py_False;
262 static PyObject *py_ldb_dn_add_base(PyLdbDnObject *self, PyObject *args)
264 PyObject *py_other;
265 struct ldb_dn *other, *dn;
266 if (!PyArg_ParseTuple(args, "O", &py_other))
267 return NULL;
269 dn = PyLdbDn_AsDn((PyObject *)self);
271 if (!PyObject_AsDn(NULL, py_other, dn_ldb_ctx(dn), &other))
272 return NULL;
274 return ldb_dn_add_base(dn, other)?Py_True:Py_False;
277 static PyMethodDef py_ldb_dn_methods[] = {
278 { "validate", (PyCFunction)py_ldb_dn_validate, METH_NOARGS,
279 "S.validate() -> bool\n"
280 "Validate DN is correct." },
281 { "is_valid", (PyCFunction)py_ldb_dn_is_valid, METH_NOARGS,
282 "S.is_valid() -> bool\n" },
283 { "is_special", (PyCFunction)py_ldb_dn_is_special, METH_NOARGS,
284 "S.is_special() -> bool\n"
285 "Check whether this is a special LDB DN." },
286 { "is_null", (PyCFunction)py_ldb_dn_is_null, METH_NOARGS,
287 "Check whether this is a null DN." },
288 { "get_casefold", (PyCFunction)py_ldb_dn_get_casefold, METH_NOARGS,
289 NULL },
290 { "get_linearized", (PyCFunction)py_ldb_dn_get_linearized, METH_NOARGS,
291 NULL },
292 { "canonical_str", (PyCFunction)py_ldb_dn_canonical_str, METH_NOARGS,
293 "S.canonical_str() -> string\n"
294 "Canonical version of this DN (like a posix path)." },
295 { "canonical_ex_str", (PyCFunction)py_ldb_dn_canonical_ex_str, METH_NOARGS,
296 "S.canonical_ex_str() -> string\n"
297 "Canonical version of this DN (like a posix path, with terminating newline)." },
298 { "check_special", (PyCFunction)py_ldb_dn_is_special, METH_VARARGS,
299 NULL },
300 { "parent", (PyCFunction)py_ldb_dn_get_parent, METH_NOARGS,
301 "S.parent() -> dn\n"
302 "Get the parent for this DN." },
303 { "add_child", (PyCFunction)py_ldb_dn_add_child, METH_VARARGS,
304 "S.add_child(dn) -> None\n"
305 "Add a child DN to this DN." },
306 { "add_base", (PyCFunction)py_ldb_dn_add_base, METH_VARARGS,
307 "S.add_base(dn) -> None\n"
308 "Add a base DN to this DN." },
309 { "check_special", (PyCFunction)py_ldb_dn_check_special, METH_VARARGS,
310 NULL },
311 { NULL }
314 static Py_ssize_t py_ldb_dn_len(PyLdbDnObject *self)
316 return ldb_dn_get_comp_num(PyLdbDn_AsDn((PyObject *)self));
319 static PyObject *py_ldb_dn_concat(PyLdbDnObject *self, PyObject *py_other)
321 struct ldb_dn *dn = PyLdbDn_AsDn((PyObject *)self),
322 *other;
323 PyLdbDnObject *py_ret;
325 if (!PyObject_AsDn(NULL, py_other, NULL, &other))
326 return NULL;
328 py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
329 if (py_ret == NULL) {
330 PyErr_NoMemory();
331 return NULL;
333 py_ret->mem_ctx = talloc_new(NULL);
334 py_ret->dn = ldb_dn_copy(py_ret->mem_ctx, dn);
335 ldb_dn_add_child(py_ret->dn, other);
336 return (PyObject *)py_ret;
339 static PySequenceMethods py_ldb_dn_seq = {
340 .sq_length = (lenfunc)py_ldb_dn_len,
341 .sq_concat = (binaryfunc)py_ldb_dn_concat,
344 static PyObject *py_ldb_dn_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
346 struct ldb_dn *ret;
347 char *str;
348 PyObject *py_ldb;
349 struct ldb_context *ldb_ctx;
350 TALLOC_CTX *mem_ctx;
351 PyLdbDnObject *py_ret;
352 const char * const kwnames[] = { "ldb", "dn", NULL };
354 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Os",
355 discard_const_p(char *, kwnames),
356 &py_ldb, &str))
357 return NULL;
359 ldb_ctx = PyLdb_AsLdbContext(py_ldb);
361 mem_ctx = talloc_new(NULL);
362 if (mem_ctx == NULL) {
363 PyErr_NoMemory();
364 return NULL;
367 ret = ldb_dn_new(mem_ctx, ldb_ctx, str);
369 if (ret == NULL || !ldb_dn_validate(ret)) {
370 talloc_free(mem_ctx);
371 PyErr_SetString(PyExc_ValueError, "unable to parse dn string");
372 return NULL;
375 py_ret = (PyLdbDnObject *)type->tp_alloc(type, 0);
376 if (ret == NULL) {
377 talloc_free(mem_ctx);
378 PyErr_NoMemory();
379 return NULL;
381 py_ret->mem_ctx = mem_ctx;
382 py_ret->dn = ret;
383 return (PyObject *)py_ret;
386 PyObject *PyLdbDn_FromDn(struct ldb_dn *dn)
388 PyLdbDnObject *py_ret;
390 if (dn == NULL) {
391 Py_RETURN_NONE;
394 py_ret = (PyLdbDnObject *)PyLdbDn.tp_alloc(&PyLdbDn, 0);
395 if (py_ret == NULL) {
396 PyErr_NoMemory();
397 return NULL;
399 py_ret->mem_ctx = talloc_new(NULL);
400 py_ret->dn = talloc_reference(py_ret->mem_ctx, dn);
401 return (PyObject *)py_ret;
404 static void py_ldb_dn_dealloc(PyLdbDnObject *self)
406 talloc_free(self->mem_ctx);
407 self->ob_type->tp_free(self);
410 PyTypeObject PyLdbDn = {
411 .tp_name = "Dn",
412 .tp_methods = py_ldb_dn_methods,
413 .tp_str = (reprfunc)py_ldb_dn_get_linearized,
414 .tp_repr = (reprfunc)py_ldb_dn_repr,
415 .tp_compare = (cmpfunc)py_ldb_dn_compare,
416 .tp_as_sequence = &py_ldb_dn_seq,
417 .tp_doc = "A LDB distinguished name.",
418 .tp_new = py_ldb_dn_new,
419 .tp_dealloc = (destructor)py_ldb_dn_dealloc,
420 .tp_basicsize = sizeof(PyLdbObject),
421 .tp_flags = Py_TPFLAGS_DEFAULT,
424 /* Debug */
425 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(3, 0);
426 static void py_ldb_debug(void *context, enum ldb_debug_level level, const char *fmt, va_list ap)
428 PyObject *fn = (PyObject *)context;
429 PyObject_CallFunction(fn, discard_const_p(char, "(i,O)"), level, PyString_FromFormatV(fmt, ap));
432 static PyObject *py_ldb_set_debug(PyLdbObject *self, PyObject *args)
434 PyObject *cb;
436 if (!PyArg_ParseTuple(args, "O", &cb))
437 return NULL;
439 Py_INCREF(cb);
440 /* FIXME: Where do we DECREF cb ? */
441 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_set_debug(self->ldb_ctx, py_ldb_debug, cb), PyLdb_AsLdbContext(self));
443 Py_RETURN_NONE;
446 static PyObject *py_ldb_set_create_perms(PyTypeObject *self, PyObject *args)
448 unsigned int perms;
449 if (!PyArg_ParseTuple(args, "I", &perms))
450 return NULL;
452 ldb_set_create_perms(PyLdb_AsLdbContext(self), perms);
454 Py_RETURN_NONE;
457 static PyObject *py_ldb_set_modules_dir(PyTypeObject *self, PyObject *args)
459 char *modules_dir;
460 if (!PyArg_ParseTuple(args, "s", &modules_dir))
461 return NULL;
463 ldb_set_modules_dir(PyLdb_AsLdbContext(self), modules_dir);
465 Py_RETURN_NONE;
468 static PyObject *py_ldb_transaction_start(PyLdbObject *self)
470 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_start(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
471 Py_RETURN_NONE;
474 static PyObject *py_ldb_transaction_commit(PyLdbObject *self)
476 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_commit(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
477 Py_RETURN_NONE;
480 static PyObject *py_ldb_transaction_cancel(PyLdbObject *self)
482 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_transaction_cancel(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
483 Py_RETURN_NONE;
486 static PyObject *py_ldb_setup_wellknown_attributes(PyLdbObject *self)
488 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ldb_setup_wellknown_attributes(PyLdb_AsLdbContext(self)), PyLdb_AsLdbContext(self));
489 Py_RETURN_NONE;
492 static PyObject *py_ldb_repr(PyLdbObject *self)
494 return PyString_FromFormat("<ldb connection>");
497 static PyObject *py_ldb_get_root_basedn(PyLdbObject *self)
499 struct ldb_dn *dn = ldb_get_root_basedn(PyLdb_AsLdbContext(self));
500 if (dn == NULL)
501 Py_RETURN_NONE;
502 return PyLdbDn_FromDn(dn);
506 static PyObject *py_ldb_get_schema_basedn(PyLdbObject *self)
508 struct ldb_dn *dn = ldb_get_schema_basedn(PyLdb_AsLdbContext(self));
509 if (dn == NULL)
510 Py_RETURN_NONE;
511 return PyLdbDn_FromDn(dn);
514 static PyObject *py_ldb_get_config_basedn(PyLdbObject *self)
516 struct ldb_dn *dn = ldb_get_config_basedn(PyLdb_AsLdbContext(self));
517 if (dn == NULL)
518 Py_RETURN_NONE;
519 return PyLdbDn_FromDn(dn);
522 static PyObject *py_ldb_get_default_basedn(PyLdbObject *self)
524 struct ldb_dn *dn = ldb_get_default_basedn(PyLdb_AsLdbContext(self));
525 if (dn == NULL)
526 Py_RETURN_NONE;
527 return PyLdbDn_FromDn(dn);
530 static const char **PyList_AsStringList(TALLOC_CTX *mem_ctx, PyObject *list,
531 const char *paramname)
533 const char **ret;
534 int i;
535 if (!PyList_Check(list)) {
536 PyErr_Format(PyExc_TypeError, "%s is not a list", paramname);
537 return NULL;
539 ret = talloc_array(NULL, const char *, PyList_Size(list)+1);
540 for (i = 0; i < PyList_Size(list); i++) {
541 PyObject *item = PyList_GetItem(list, i);
542 if (!PyString_Check(item)) {
543 PyErr_Format(PyExc_TypeError, "%s should be strings", paramname);
544 return NULL;
546 ret[i] = talloc_strndup(ret, PyString_AsString(item),
547 PyString_Size(item));
549 ret[i] = NULL;
550 return ret;
553 static int py_ldb_init(PyLdbObject *self, PyObject *args, PyObject *kwargs)
555 const char * const kwnames[] = { "url", "flags", "options", NULL };
556 char *url = NULL;
557 PyObject *py_options = Py_None;
558 const char **options;
559 int flags = 0;
560 int ret;
561 struct ldb_context *ldb;
563 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO:Ldb.__init__",
564 discard_const_p(char *, kwnames),
565 &url, &flags, &py_options))
566 return -1;
568 ldb = PyLdb_AsLdbContext(self);
570 if (py_options == Py_None) {
571 options = NULL;
572 } else {
573 options = PyList_AsStringList(ldb, py_options, "options");
574 if (options == NULL)
575 return -1;
578 if (url != NULL) {
579 ret = ldb_connect(ldb, url, flags, options);
580 if (ret != LDB_SUCCESS) {
581 PyErr_SetLdbError(PyExc_LdbError, ret, ldb);
582 return -1;
586 talloc_free(options);
587 return 0;
590 static PyObject *py_ldb_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
592 PyLdbObject *ret;
593 struct ldb_context *ldb;
594 ret = (PyLdbObject *)type->tp_alloc(type, 0);
595 if (ret == NULL) {
596 PyErr_NoMemory();
597 return NULL;
599 ret->mem_ctx = talloc_new(NULL);
600 ldb = ldb_init(ret->mem_ctx, NULL);
602 if (ldb == NULL) {
603 PyErr_NoMemory();
604 return NULL;
607 ret->ldb_ctx = ldb;
608 return (PyObject *)ret;
611 static PyObject *py_ldb_connect(PyLdbObject *self, PyObject *args, PyObject *kwargs)
613 char *url;
614 int flags = 0;
615 PyObject *py_options = Py_None;
616 int ret;
617 const char **options;
618 const char * const kwnames[] = { "url", "flags", "options", NULL };
620 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ziO",
621 discard_const_p(char *, kwnames),
622 &url, &flags, &py_options))
623 return NULL;
625 if (py_options == Py_None) {
626 options = NULL;
627 } else {
628 options = PyList_AsStringList(NULL, py_options, "options");
629 if (options == NULL)
630 return NULL;
633 ret = ldb_connect(PyLdb_AsLdbContext(self), url, flags, options);
634 talloc_free(options);
636 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
638 Py_RETURN_NONE;
641 static PyObject *py_ldb_modify(PyLdbObject *self, PyObject *args)
643 PyObject *py_msg;
644 int ret;
645 if (!PyArg_ParseTuple(args, "O", &py_msg))
646 return NULL;
648 if (!PyLdbMessage_Check(py_msg)) {
649 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message");
650 return NULL;
653 ret = ldb_modify(PyLdb_AsLdbContext(self), PyLdbMessage_AsMessage(py_msg));
654 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
656 Py_RETURN_NONE;
659 static PyObject *py_ldb_add(PyLdbObject *self, PyObject *args)
661 PyObject *py_msg;
662 int ret;
663 Py_ssize_t dict_pos, msg_pos;
664 struct ldb_message_element *msgel;
665 struct ldb_message *msg;
666 PyObject *key, *value;
667 TALLOC_CTX *mem_ctx;
669 if (!PyArg_ParseTuple(args, "O", &py_msg))
670 return NULL;
672 mem_ctx = talloc_new(NULL);
674 if (PyDict_Check(py_msg)) {
675 PyObject *dn_value = PyDict_GetItemString(py_msg, "dn");
676 msg = ldb_msg_new(mem_ctx);
677 msg->elements = talloc_zero_array(msg, struct ldb_message_element, PyDict_Size(py_msg));
678 msg_pos = dict_pos = 0;
679 if (dn_value) {
680 if (!PyObject_AsDn(msg, dn_value, PyLdb_AsLdbContext(self), &msg->dn)) {
681 PyErr_SetString(PyExc_TypeError, "unable to import dn object");
682 talloc_free(mem_ctx);
683 return NULL;
685 if (msg->dn == NULL) {
686 PyErr_SetString(PyExc_TypeError, "dn set but not found");
687 talloc_free(mem_ctx);
688 return NULL;
692 while (PyDict_Next(py_msg, &dict_pos, &key, &value)) {
693 char *key_str = PyString_AsString(key);
694 if (strcmp(key_str, "dn") != 0) {
695 msgel = PyObject_AsMessageElement(msg->elements, value, 0, key_str);
696 if (msgel == NULL) {
697 PyErr_SetString(PyExc_TypeError, "unable to import element");
698 talloc_free(mem_ctx);
699 return NULL;
701 memcpy(&msg->elements[msg_pos], msgel, sizeof(*msgel));
702 msg_pos++;
706 if (msg->dn == NULL) {
707 PyErr_SetString(PyExc_TypeError, "no dn set");
708 talloc_free(mem_ctx);
709 return NULL;
712 msg->num_elements = msg_pos;
713 } else {
714 msg = PyLdbMessage_AsMessage(py_msg);
717 ret = ldb_add(PyLdb_AsLdbContext(self), msg);
718 talloc_free(mem_ctx);
719 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
721 Py_RETURN_NONE;
724 static PyObject *py_ldb_delete(PyLdbObject *self, PyObject *args)
726 PyObject *py_dn;
727 struct ldb_dn *dn;
728 int ret;
729 struct ldb_context *ldb;
730 if (!PyArg_ParseTuple(args, "O", &py_dn))
731 return NULL;
733 ldb = PyLdb_AsLdbContext(self);
735 if (!PyObject_AsDn(NULL, py_dn, ldb, &dn))
736 return NULL;
738 ret = ldb_delete(ldb, dn);
739 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
741 Py_RETURN_NONE;
744 static PyObject *py_ldb_rename(PyLdbObject *self, PyObject *args)
746 PyObject *py_dn1, *py_dn2;
747 struct ldb_dn *dn1, *dn2;
748 int ret;
749 struct ldb_context *ldb;
750 TALLOC_CTX *mem_ctx;
751 if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
752 return NULL;
754 mem_ctx = talloc_new(NULL);
755 if (mem_ctx == NULL) {
756 PyErr_NoMemory();
757 return NULL;
759 ldb = PyLdb_AsLdbContext(self);
760 if (!PyObject_AsDn(mem_ctx, py_dn1, ldb, &dn1)) {
761 talloc_free(mem_ctx);
762 return NULL;
765 if (!PyObject_AsDn(mem_ctx, py_dn2, ldb, &dn2)) {
766 talloc_free(mem_ctx);
767 return NULL;
770 ret = ldb_rename(ldb, dn1, dn2);
771 talloc_free(mem_ctx);
772 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb);
774 Py_RETURN_NONE;
777 static PyObject *py_ldb_schema_attribute_remove(PyLdbObject *self, PyObject *args)
779 char *name;
780 if (!PyArg_ParseTuple(args, "s", &name))
781 return NULL;
783 ldb_schema_attribute_remove(PyLdb_AsLdbContext(self), name);
785 Py_RETURN_NONE;
788 static PyObject *py_ldb_schema_attribute_add(PyLdbObject *self, PyObject *args)
790 char *attribute, *syntax;
791 unsigned int flags;
792 int ret;
793 if (!PyArg_ParseTuple(args, "sIs", &attribute, &flags, &syntax))
794 return NULL;
796 ret = ldb_schema_attribute_add(PyLdb_AsLdbContext(self), attribute, flags, syntax);
798 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, PyLdb_AsLdbContext(self));
800 Py_RETURN_NONE;
803 static PyObject *ldb_ldif_to_pyobject(struct ldb_ldif *ldif)
805 if (ldif == NULL) {
806 Py_RETURN_NONE;
807 } else {
808 /* We don't want this attached to the 'ldb' any more */
809 return Py_BuildValue(discard_const_p(char, "(iO)"),
810 ldif->changetype,
811 PyLdbMessage_FromMessage(ldif->msg));
816 static PyObject *py_ldb_write_ldif(PyLdbMessageObject *self, PyObject *args)
818 int changetype;
819 PyObject *py_msg;
820 struct ldb_ldif ldif;
821 PyObject *ret;
822 char *string;
823 TALLOC_CTX *mem_ctx;
825 if (!PyArg_ParseTuple(args, "Oi", &py_msg, &changetype))
826 return NULL;
828 if (!PyLdbMessage_Check(py_msg)) {
829 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for msg");
830 return NULL;
833 ldif.msg = PyLdbMessage_AsMessage(py_msg);
834 ldif.changetype = changetype;
836 mem_ctx = talloc_new(NULL);
838 string = ldb_ldif_write_string(PyLdb_AsLdbContext(self), mem_ctx, &ldif);
839 if (!string) {
840 PyErr_SetString(PyExc_KeyError, "Failed to generate LDIF");
841 return NULL;
844 ret = PyString_FromString(string);
846 talloc_free(mem_ctx);
848 return ret;
851 static PyObject *py_ldb_parse_ldif(PyLdbObject *self, PyObject *args)
853 PyObject *list;
854 struct ldb_ldif *ldif;
855 const char *s;
857 TALLOC_CTX *mem_ctx;
859 if (!PyArg_ParseTuple(args, "s", &s))
860 return NULL;
862 mem_ctx = talloc_new(NULL);
863 if (!mem_ctx) {
864 Py_RETURN_NONE;
867 list = PyList_New(0);
868 while (s && *s != '\0') {
869 ldif = ldb_ldif_read_string(self->ldb_ctx, &s);
870 talloc_steal(mem_ctx, ldif);
871 if (ldif) {
872 PyList_Append(list, ldb_ldif_to_pyobject(ldif));
873 } else {
874 PyErr_SetString(PyExc_ValueError, "unable to parse ldif string");
875 talloc_free(mem_ctx);
876 return NULL;
879 talloc_free(mem_ctx); /* The pyobject already has a reference to the things it needs */
880 return PyObject_GetIter(list);
883 static PyObject *py_ldb_msg_diff(PyLdbObject *self, PyObject *args)
885 PyObject *py_msg_old;
886 PyObject *py_msg_new;
887 struct ldb_message *diff;
888 PyObject *py_ret;
890 if (!PyArg_ParseTuple(args, "OO", &py_msg_old, &py_msg_new))
891 return NULL;
893 if (!PyLdbMessage_Check(py_msg_old)) {
894 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for old message");
895 return NULL;
898 if (!PyLdbMessage_Check(py_msg_new)) {
899 PyErr_SetString(PyExc_TypeError, "Expected Ldb Message for new message");
900 return NULL;
903 diff = ldb_msg_diff(PyLdb_AsLdbContext(self), PyLdbMessage_AsMessage(py_msg_old), PyLdbMessage_AsMessage(py_msg_new));
904 if (diff == NULL)
905 return NULL;
907 py_ret = PyLdbMessage_FromMessage(diff);
909 return py_ret;
912 static PyObject *py_ldb_schema_format_value(PyLdbObject *self, PyObject *args)
914 const struct ldb_schema_attribute *a;
915 struct ldb_val old_val;
916 struct ldb_val new_val;
917 TALLOC_CTX *mem_ctx;
918 PyObject *ret;
919 char *element_name;
920 PyObject *val;
922 if (!PyArg_ParseTuple(args, "sO", &element_name, &val))
923 return NULL;
925 mem_ctx = talloc_new(NULL);
927 old_val.data = (uint8_t *)PyString_AsString(val);
928 old_val.length = PyString_Size(val);
930 a = ldb_schema_attribute_by_name(PyLdb_AsLdbContext(self), element_name);
932 if (a == NULL) {
933 Py_RETURN_NONE;
936 if (a->syntax->ldif_write_fn(PyLdb_AsLdbContext(self), mem_ctx, &old_val, &new_val) != 0) {
937 talloc_free(mem_ctx);
938 Py_RETURN_NONE;
941 ret = PyString_FromStringAndSize((const char *)new_val.data, new_val.length);
943 talloc_free(mem_ctx);
945 return ret;
948 static PyObject *py_ldb_search(PyLdbObject *self, PyObject *args, PyObject *kwargs)
950 PyObject *py_base = Py_None;
951 enum ldb_scope scope = LDB_SCOPE_DEFAULT;
952 char *expr = NULL;
953 PyObject *py_attrs = Py_None;
954 PyObject *py_controls = Py_None;
955 const char * const kwnames[] = { "base", "scope", "expression", "attrs", "controls", NULL };
956 int ret;
957 struct ldb_result *res;
958 struct ldb_request *req;
959 const char **attrs;
960 struct ldb_context *ldb_ctx;
961 struct ldb_control **parsed_controls;
962 struct ldb_dn *base;
963 PyObject *py_ret;
965 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OizOO",
966 discard_const_p(char *, kwnames),
967 &py_base, &scope, &expr, &py_attrs, &py_controls))
968 return NULL;
970 ldb_ctx = PyLdb_AsLdbContext(self);
972 if (py_attrs == Py_None) {
973 attrs = NULL;
974 } else {
975 attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
976 if (attrs == NULL)
977 return NULL;
980 if (py_base == Py_None) {
981 base = ldb_get_default_basedn(ldb_ctx);
982 } else {
983 if (!PyObject_AsDn(ldb_ctx, py_base, ldb_ctx, &base)) {
984 talloc_free(attrs);
985 return NULL;
989 if (py_controls == Py_None) {
990 parsed_controls = NULL;
991 } else {
992 const char **controls = PyList_AsStringList(ldb_ctx, py_controls, "controls");
993 parsed_controls = ldb_parse_control_strings(ldb_ctx, ldb_ctx, controls);
994 talloc_free(controls);
997 res = talloc_zero(ldb_ctx, struct ldb_result);
998 if (res == NULL) {
999 PyErr_NoMemory();
1000 talloc_free(attrs);
1001 return NULL;
1004 ret = ldb_build_search_req(&req, ldb_ctx, ldb_ctx,
1005 base,
1006 scope,
1007 expr,
1008 attrs,
1009 parsed_controls,
1010 res,
1011 ldb_search_default_callback,
1012 NULL);
1014 talloc_steal(req, attrs);
1016 if (ret != LDB_SUCCESS) {
1017 talloc_free(res);
1018 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1019 return NULL;
1022 ret = ldb_request(ldb_ctx, req);
1024 if (ret == LDB_SUCCESS) {
1025 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1028 talloc_free(req);
1030 if (ret != LDB_SUCCESS) {
1031 talloc_free(res);
1032 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, ldb_ctx);
1033 return NULL;
1036 py_ret = PyLdbResult_FromResult(res);
1038 talloc_free(res);
1040 return py_ret;
1043 static PyObject *py_ldb_get_opaque(PyLdbObject *self, PyObject *args)
1045 char *name;
1046 void *data;
1048 if (!PyArg_ParseTuple(args, "s", &name))
1049 return NULL;
1051 data = ldb_get_opaque(PyLdb_AsLdbContext(self), name);
1053 if (data == NULL)
1054 Py_RETURN_NONE;
1056 /* FIXME: More interpretation */
1058 return Py_True;
1061 static PyObject *py_ldb_set_opaque(PyLdbObject *self, PyObject *args)
1063 char *name;
1064 PyObject *data;
1066 if (!PyArg_ParseTuple(args, "sO", &name, &data))
1067 return NULL;
1069 /* FIXME: More interpretation */
1071 ldb_set_opaque(PyLdb_AsLdbContext(self), name, data);
1073 Py_RETURN_NONE;
1076 static PyObject *py_ldb_modules(PyLdbObject *self)
1078 struct ldb_context *ldb = PyLdb_AsLdbContext(self);
1079 PyObject *ret = PyList_New(0);
1080 struct ldb_module *mod;
1082 for (mod = ldb->modules; mod; mod = mod->next) {
1083 PyList_Append(ret, PyLdbModule_FromModule(mod));
1086 return ret;
1089 static PyMethodDef py_ldb_methods[] = {
1090 { "set_debug", (PyCFunction)py_ldb_set_debug, METH_VARARGS,
1091 "S.set_debug(callback) -> None\n"
1092 "Set callback for LDB debug messages.\n"
1093 "The callback should accept a debug level and debug text." },
1094 { "set_create_perms", (PyCFunction)py_ldb_set_create_perms, METH_VARARGS,
1095 "S.set_create_perms(mode) -> None\n"
1096 "Set mode to use when creating new LDB files." },
1097 { "set_modules_dir", (PyCFunction)py_ldb_set_modules_dir, METH_VARARGS,
1098 "S.set_modules_dir(path) -> None\n"
1099 "Set path LDB should search for modules" },
1100 { "transaction_start", (PyCFunction)py_ldb_transaction_start, METH_NOARGS,
1101 "S.transaction_start() -> None\n"
1102 "Start a new transaction." },
1103 { "transaction_commit", (PyCFunction)py_ldb_transaction_commit, METH_NOARGS,
1104 "S.transaction_commit() -> None\n"
1105 "commit a new transaction." },
1106 { "transaction_cancel", (PyCFunction)py_ldb_transaction_cancel, METH_NOARGS,
1107 "S.transaction_cancel() -> None\n"
1108 "cancel a new transaction." },
1109 { "setup_wellknown_attributes", (PyCFunction)py_ldb_setup_wellknown_attributes, METH_NOARGS,
1110 NULL },
1111 { "get_root_basedn", (PyCFunction)py_ldb_get_root_basedn, METH_NOARGS,
1112 NULL },
1113 { "get_schema_basedn", (PyCFunction)py_ldb_get_schema_basedn, METH_NOARGS,
1114 NULL },
1115 { "get_default_basedn", (PyCFunction)py_ldb_get_default_basedn, METH_NOARGS,
1116 NULL },
1117 { "get_config_basedn", (PyCFunction)py_ldb_get_config_basedn, METH_NOARGS,
1118 NULL },
1119 { "connect", (PyCFunction)py_ldb_connect, METH_VARARGS|METH_KEYWORDS,
1120 "S.connect(url, flags=0, options=None) -> None\n"
1121 "Connect to a LDB URL." },
1122 { "modify", (PyCFunction)py_ldb_modify, METH_VARARGS,
1123 "S.modify(message) -> None\n"
1124 "Modify an entry." },
1125 { "add", (PyCFunction)py_ldb_add, METH_VARARGS,
1126 "S.add(message) -> None\n"
1127 "Add an entry." },
1128 { "delete", (PyCFunction)py_ldb_delete, METH_VARARGS,
1129 "S.delete(dn) -> None\n"
1130 "Remove an entry." },
1131 { "rename", (PyCFunction)py_ldb_rename, METH_VARARGS,
1132 "S.rename(old_dn, new_dn) -> None\n"
1133 "Rename an entry." },
1134 { "search", (PyCFunction)py_ldb_search, METH_VARARGS|METH_KEYWORDS,
1135 "S.search(base=None, scope=None, expression=None, attrs=None, controls=None) -> msgs\n"
1136 "Search in a database.\n"
1137 "\n"
1138 ":param base: Optional base DN to search\n"
1139 ":param scope: Search scope (SCOPE_BASE, SCOPE_ONELEVEL or SCOPE_SUBTREE)\n"
1140 ":param expression: Optional search expression\n"
1141 ":param attrs: Attributes to return (defaults to all)\n"
1142 ":param controls: Optional list of controls\n"
1143 ":return: Iterator over Message objects\n"
1145 { "schema_attribute_remove", (PyCFunction)py_ldb_schema_attribute_remove, METH_VARARGS,
1146 NULL },
1147 { "schema_attribute_add", (PyCFunction)py_ldb_schema_attribute_add, METH_VARARGS,
1148 NULL },
1149 { "schema_format_value", (PyCFunction)py_ldb_schema_format_value, METH_VARARGS,
1150 NULL },
1151 { "parse_ldif", (PyCFunction)py_ldb_parse_ldif, METH_VARARGS,
1152 "S.parse_ldif(ldif) -> iter(messages)\n"
1153 "Parse a string formatted using LDIF." },
1154 { "write_ldif", (PyCFunction)py_ldb_write_ldif, METH_VARARGS,
1155 "S.write_ldif(message, changetype) -> ldif\n"
1156 "Print the message as a string formatted using LDIF." },
1157 { "msg_diff", (PyCFunction)py_ldb_msg_diff, METH_VARARGS,
1158 "S.msg_diff(Message) -> Message\n"
1159 "Return an LDB Message of the difference between two Message objects." },
1160 { "get_opaque", (PyCFunction)py_ldb_get_opaque, METH_VARARGS,
1161 "S.get_opaque(name) -> value\n"
1162 "Get an opaque value set on this LDB connection. \n"
1163 ":note: The returned value may not be useful in Python."
1165 { "set_opaque", (PyCFunction)py_ldb_set_opaque, METH_VARARGS,
1166 "S.set_opaque(name, value) -> None\n"
1167 "Set an opaque value on this LDB connection. \n"
1168 ":note: Passing incorrect values may cause crashes." },
1169 { "modules", (PyCFunction)py_ldb_modules, METH_NOARGS,
1170 "S.modules() -> list\n"
1171 "Return the list of modules on this LDB connection " },
1172 { NULL },
1175 PyObject *PyLdbModule_FromModule(struct ldb_module *mod)
1177 PyLdbModuleObject *ret;
1179 ret = (PyLdbModuleObject *)PyLdbModule.tp_alloc(&PyLdbModule, 0);
1180 if (ret == NULL) {
1181 PyErr_NoMemory();
1182 return NULL;
1184 ret->mem_ctx = talloc_new(NULL);
1185 ret->mod = talloc_reference(ret->mem_ctx, mod);
1186 return (PyObject *)ret;
1189 static PyObject *py_ldb_get_firstmodule(PyLdbObject *self, void *closure)
1191 return PyLdbModule_FromModule(PyLdb_AsLdbContext(self)->modules);
1194 static PyGetSetDef py_ldb_getset[] = {
1195 { discard_const_p(char, "firstmodule"), (getter)py_ldb_get_firstmodule, NULL, NULL },
1196 { NULL }
1199 static int py_ldb_contains(PyLdbObject *self, PyObject *obj)
1201 struct ldb_context *ldb_ctx = PyLdb_AsLdbContext(self);
1202 struct ldb_dn *dn;
1203 struct ldb_result *result;
1204 int ret;
1205 int count;
1207 if (!PyObject_AsDn(ldb_ctx, obj, ldb_ctx, &dn))
1208 return -1;
1210 ret = ldb_search(ldb_ctx, ldb_ctx, &result, dn, LDB_SCOPE_BASE, NULL, NULL);
1211 if (ret != LDB_SUCCESS) {
1212 PyErr_SetLdbError(PyExc_LdbError, ret, ldb_ctx);
1213 return -1;
1216 count = result->count;
1218 talloc_free(result);
1220 return count;
1223 static PySequenceMethods py_ldb_seq = {
1224 .sq_contains = (objobjproc)py_ldb_contains,
1227 PyObject *PyLdb_FromLdbContext(struct ldb_context *ldb_ctx)
1229 PyLdbObject *ret;
1231 ret = (PyLdbObject *)PyLdb.tp_alloc(&PyLdb, 0);
1232 if (ret == NULL) {
1233 PyErr_NoMemory();
1234 return NULL;
1236 ret->mem_ctx = talloc_new(NULL);
1237 ret->ldb_ctx = talloc_reference(ret->mem_ctx, ldb_ctx);
1238 return (PyObject *)ret;
1241 static void py_ldb_dealloc(PyLdbObject *self)
1243 talloc_free(self->mem_ctx);
1244 self->ob_type->tp_free(self);
1247 PyTypeObject PyLdb = {
1248 .tp_name = "Ldb",
1249 .tp_methods = py_ldb_methods,
1250 .tp_repr = (reprfunc)py_ldb_repr,
1251 .tp_new = py_ldb_new,
1252 .tp_init = (initproc)py_ldb_init,
1253 .tp_dealloc = (destructor)py_ldb_dealloc,
1254 .tp_getset = py_ldb_getset,
1255 .tp_getattro = PyObject_GenericGetAttr,
1256 .tp_basicsize = sizeof(PyLdbObject),
1257 .tp_doc = "Connection to a LDB database.",
1258 .tp_as_sequence = &py_ldb_seq,
1259 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1262 static PyObject *py_ldb_module_repr(PyLdbModuleObject *self)
1264 return PyString_FromFormat("<ldb module '%s'>", PyLdbModule_AsModule(self)->ops->name);
1267 static PyObject *py_ldb_module_str(PyLdbModuleObject *self)
1269 return PyString_FromString(PyLdbModule_AsModule(self)->ops->name);
1272 static PyObject *py_ldb_module_start_transaction(PyLdbModuleObject *self)
1274 PyLdbModule_AsModule(self)->ops->start_transaction(PyLdbModule_AsModule(self));
1275 Py_RETURN_NONE;
1278 static PyObject *py_ldb_module_end_transaction(PyLdbModuleObject *self)
1280 PyLdbModule_AsModule(self)->ops->end_transaction(PyLdbModule_AsModule(self));
1281 Py_RETURN_NONE;
1284 static PyObject *py_ldb_module_del_transaction(PyLdbModuleObject *self)
1286 PyLdbModule_AsModule(self)->ops->del_transaction(PyLdbModule_AsModule(self));
1287 Py_RETURN_NONE;
1290 static PyObject *py_ldb_module_search(PyLdbModuleObject *self, PyObject *args, PyObject *kwargs)
1292 PyObject *py_base, *py_tree, *py_attrs, *py_ret;
1293 int ret, scope;
1294 struct ldb_request *req;
1295 const char * const kwnames[] = { "base", "scope", "tree", "attrs", NULL };
1296 struct ldb_module *mod;
1297 const char * const*attrs;
1299 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OiOO",
1300 discard_const_p(char *, kwnames),
1301 &py_base, &scope, &py_tree, &py_attrs))
1302 return NULL;
1304 mod = self->mod;
1306 if (py_attrs == Py_None) {
1307 attrs = NULL;
1308 } else {
1309 attrs = PyList_AsStringList(NULL, py_attrs, "attrs");
1310 if (attrs == NULL)
1311 return NULL;
1314 ret = ldb_build_search_req(&req, mod->ldb, NULL, PyLdbDn_AsDn(py_base),
1315 scope, NULL /* expr */, attrs,
1316 NULL /* controls */, NULL, NULL, NULL);
1318 talloc_steal(req, attrs);
1320 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1322 req->op.search.res = NULL;
1324 ret = mod->ops->search(mod, req);
1326 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1328 py_ret = PyLdbResult_FromResult(req->op.search.res);
1330 talloc_free(req);
1332 return py_ret;
1336 static PyObject *py_ldb_module_add(PyLdbModuleObject *self, PyObject *args)
1338 struct ldb_request *req;
1339 PyObject *py_message;
1340 int ret;
1341 struct ldb_module *mod;
1343 if (!PyArg_ParseTuple(args, "O", &py_message))
1344 return NULL;
1346 req = talloc_zero(NULL, struct ldb_request);
1347 req->operation = LDB_ADD;
1348 req->op.add.message = PyLdbMessage_AsMessage(py_message);
1350 mod = PyLdbModule_AsModule(self);
1351 ret = mod->ops->add(mod, req);
1353 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1355 Py_RETURN_NONE;
1358 static PyObject *py_ldb_module_modify(PyLdbModuleObject *self, PyObject *args)
1360 int ret;
1361 struct ldb_request *req;
1362 PyObject *py_message;
1363 struct ldb_module *mod;
1365 if (!PyArg_ParseTuple(args, "O", &py_message))
1366 return NULL;
1368 req = talloc_zero(NULL, struct ldb_request);
1369 req->operation = LDB_MODIFY;
1370 req->op.mod.message = PyLdbMessage_AsMessage(py_message);
1372 mod = PyLdbModule_AsModule(self);
1373 ret = mod->ops->modify(mod, req);
1375 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, mod->ldb);
1377 Py_RETURN_NONE;
1380 static PyObject *py_ldb_module_delete(PyLdbModuleObject *self, PyObject *args)
1382 int ret;
1383 struct ldb_request *req;
1384 PyObject *py_dn;
1386 if (!PyArg_ParseTuple(args, "O", &py_dn))
1387 return NULL;
1389 req = talloc_zero(NULL, struct ldb_request);
1390 req->operation = LDB_DELETE;
1391 req->op.del.dn = PyLdbDn_AsDn(py_dn);
1393 ret = PyLdbModule_AsModule(self)->ops->del(PyLdbModule_AsModule(self), req);
1395 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
1397 Py_RETURN_NONE;
1400 static PyObject *py_ldb_module_rename(PyLdbModuleObject *self, PyObject *args)
1402 int ret;
1403 struct ldb_request *req;
1404 PyObject *py_dn1, *py_dn2;
1406 if (!PyArg_ParseTuple(args, "OO", &py_dn1, &py_dn2))
1407 return NULL;
1409 req = talloc_zero(NULL, struct ldb_request);
1411 req->operation = LDB_RENAME;
1412 req->op.rename.olddn = PyLdbDn_AsDn(py_dn1);
1413 req->op.rename.newdn = PyLdbDn_AsDn(py_dn2);
1415 ret = PyLdbModule_AsModule(self)->ops->rename(PyLdbModule_AsModule(self), req);
1417 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
1419 Py_RETURN_NONE;
1422 static PyMethodDef py_ldb_module_methods[] = {
1423 { "search", (PyCFunction)py_ldb_module_search, METH_VARARGS|METH_KEYWORDS, NULL },
1424 { "add", (PyCFunction)py_ldb_module_add, METH_VARARGS, NULL },
1425 { "modify", (PyCFunction)py_ldb_module_modify, METH_VARARGS, NULL },
1426 { "rename", (PyCFunction)py_ldb_module_rename, METH_VARARGS, NULL },
1427 { "delete", (PyCFunction)py_ldb_module_delete, METH_VARARGS, NULL },
1428 { "start_transaction", (PyCFunction)py_ldb_module_start_transaction, METH_NOARGS, NULL },
1429 { "end_transaction", (PyCFunction)py_ldb_module_end_transaction, METH_NOARGS, NULL },
1430 { "del_transaction", (PyCFunction)py_ldb_module_del_transaction, METH_NOARGS, NULL },
1431 { NULL },
1434 static void py_ldb_module_dealloc(PyLdbModuleObject *self)
1436 talloc_free(self->mem_ctx);
1437 self->ob_type->tp_free(self);
1440 PyTypeObject PyLdbModule = {
1441 .tp_name = "LdbModule",
1442 .tp_methods = py_ldb_module_methods,
1443 .tp_repr = (reprfunc)py_ldb_module_repr,
1444 .tp_str = (reprfunc)py_ldb_module_str,
1445 .tp_basicsize = sizeof(PyLdbModuleObject),
1446 .tp_dealloc = (destructor)py_ldb_module_dealloc,
1447 .tp_flags = Py_TPFLAGS_DEFAULT,
1452 * Create a ldb_message_element from a Python object.
1454 * This will accept any sequence objects that contains strings, or
1455 * a string object.
1457 * A reference to set_obj will be borrowed.
1459 * @param mem_ctx Memory context
1460 * @param set_obj Python object to convert
1461 * @param flags ldb_message_element flags to set
1462 * @param attr_name Name of the attribute
1463 * @return New ldb_message_element, allocated as child of mem_ctx
1465 struct ldb_message_element *PyObject_AsMessageElement(TALLOC_CTX *mem_ctx,
1466 PyObject *set_obj, int flags,
1467 const char *attr_name)
1469 struct ldb_message_element *me;
1471 if (PyLdbMessageElement_Check(set_obj))
1472 return talloc_reference(mem_ctx,
1473 PyLdbMessageElement_AsMessageElement(set_obj));
1475 me = talloc(mem_ctx, struct ldb_message_element);
1477 me->name = talloc_strdup(me, attr_name);
1478 me->flags = flags;
1479 if (PyString_Check(set_obj)) {
1480 me->num_values = 1;
1481 me->values = talloc_array(me, struct ldb_val, me->num_values);
1482 me->values[0].length = PyString_Size(set_obj);
1483 me->values[0].data = talloc_memdup(me,
1484 (uint8_t *)PyString_AsString(set_obj), me->values[0].length);
1485 } else if (PySequence_Check(set_obj)) {
1486 int i;
1487 me->num_values = PySequence_Size(set_obj);
1488 me->values = talloc_array(me, struct ldb_val, me->num_values);
1489 for (i = 0; i < me->num_values; i++) {
1490 PyObject *obj = PySequence_GetItem(set_obj, i);
1492 me->values[i].length = PyString_Size(obj);
1493 me->values[i].data = talloc_memdup(me,
1494 (uint8_t *)PyString_AsString(obj), me->values[i].length);
1496 } else {
1497 talloc_free(me);
1498 me = NULL;
1501 return me;
1505 static PyObject *ldb_msg_element_to_set(struct ldb_context *ldb_ctx,
1506 struct ldb_message_element *me)
1508 int i;
1509 PyObject *result;
1511 /* Python << 2.5 doesn't have PySet_New and PySet_Add. */
1512 result = PyList_New(me->num_values);
1514 for (i = 0; i < me->num_values; i++) {
1515 PyList_SetItem(result, i,
1516 PyObject_FromLdbValue(ldb_ctx, me, &me->values[i]));
1519 return result;
1522 static PyObject *py_ldb_msg_element_get(PyLdbMessageElementObject *self, PyObject *args)
1524 int i;
1525 if (!PyArg_ParseTuple(args, "i", &i))
1526 return NULL;
1527 if (i < 0 || i >= PyLdbMessageElement_AsMessageElement(self)->num_values)
1528 Py_RETURN_NONE;
1530 return PyObject_FromLdbValue(NULL, PyLdbMessageElement_AsMessageElement(self),
1531 &(PyLdbMessageElement_AsMessageElement(self)->values[i]));
1534 static PyObject *py_ldb_msg_element_flags(PyLdbMessageElementObject *self, PyObject *args)
1536 struct ldb_message_element *el;
1538 el = PyLdbMessageElement_AsMessageElement(self);
1539 return PyInt_FromLong(el->flags);
1542 static PyObject *py_ldb_msg_element_set_flags(PyLdbMessageElementObject *self, PyObject *args)
1544 int flags;
1545 struct ldb_message_element *el;
1546 if (!PyArg_ParseTuple(args, "i", &flags))
1547 return NULL;
1549 el = PyLdbMessageElement_AsMessageElement(self);
1550 el->flags = flags;
1551 Py_RETURN_NONE;
1554 static PyMethodDef py_ldb_msg_element_methods[] = {
1555 { "get", (PyCFunction)py_ldb_msg_element_get, METH_VARARGS, NULL },
1556 { "set_flags", (PyCFunction)py_ldb_msg_element_set_flags, METH_VARARGS, NULL },
1557 { "flags", (PyCFunction)py_ldb_msg_element_flags, METH_NOARGS, NULL },
1558 { NULL },
1561 static Py_ssize_t py_ldb_msg_element_len(PyLdbMessageElementObject *self)
1563 return PyLdbMessageElement_AsMessageElement(self)->num_values;
1566 static PyObject *py_ldb_msg_element_find(PyLdbMessageElementObject *self, Py_ssize_t idx)
1568 struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1569 if (idx < 0 || idx >= el->num_values) {
1570 PyErr_SetString(PyExc_IndexError, "Out of range");
1571 return NULL;
1573 return PyString_FromStringAndSize((char *)el->values[idx].data, el->values[idx].length);
1576 static PySequenceMethods py_ldb_msg_element_seq = {
1577 .sq_length = (lenfunc)py_ldb_msg_element_len,
1578 .sq_item = (ssizeargfunc)py_ldb_msg_element_find,
1581 static int py_ldb_msg_element_cmp(PyLdbMessageElementObject *self, PyLdbMessageElementObject *other)
1583 return ldb_msg_element_compare(PyLdbMessageElement_AsMessageElement(self),
1584 PyLdbMessageElement_AsMessageElement(other));
1587 static PyObject *py_ldb_msg_element_iter(PyLdbMessageElementObject *self)
1589 return PyObject_GetIter(ldb_msg_element_to_set(NULL, PyLdbMessageElement_AsMessageElement(self)));
1592 PyObject *PyLdbMessageElement_FromMessageElement(struct ldb_message_element *el, TALLOC_CTX *mem_ctx)
1594 PyLdbMessageElementObject *ret;
1595 ret = (PyLdbMessageElementObject *)PyLdbMessageElement.tp_alloc(&PyLdbMessageElement, 0);
1596 if (ret == NULL) {
1597 PyErr_NoMemory();
1598 return NULL;
1600 ret->mem_ctx = talloc_new(NULL);
1601 if (talloc_reference(ret->mem_ctx, mem_ctx) == NULL) {
1602 PyErr_NoMemory();
1603 return NULL;
1605 ret->el = el;
1606 return (PyObject *)ret;
1609 static PyObject *py_ldb_msg_element_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1611 PyObject *py_elements = NULL;
1612 struct ldb_message_element *el;
1613 int flags = 0;
1614 char *name = NULL;
1615 const char * const kwnames[] = { "elements", "flags", "name", NULL };
1616 PyLdbMessageElementObject *ret;
1617 TALLOC_CTX *mem_ctx;
1619 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Ois",
1620 discard_const_p(char *, kwnames),
1621 &py_elements, &flags, &name))
1622 return NULL;
1624 mem_ctx = talloc_new(NULL);
1625 if (mem_ctx == NULL) {
1626 PyErr_NoMemory();
1627 return NULL;
1630 el = talloc_zero(mem_ctx, struct ldb_message_element);
1632 if (py_elements != NULL) {
1633 int i;
1634 if (PyString_Check(py_elements)) {
1635 el->num_values = 1;
1636 el->values = talloc_array(el, struct ldb_val, 1);
1637 el->values[0].length = PyString_Size(py_elements);
1638 el->values[0].data = talloc_memdup(el,
1639 (uint8_t *)PyString_AsString(py_elements), el->values[0].length);
1640 } else if (PySequence_Check(py_elements)) {
1641 el->num_values = PySequence_Size(py_elements);
1642 el->values = talloc_array(el, struct ldb_val, el->num_values);
1643 for (i = 0; i < el->num_values; i++) {
1644 PyObject *item = PySequence_GetItem(py_elements, i);
1645 if (!PyString_Check(item)) {
1646 PyErr_Format(PyExc_TypeError,
1647 "Expected string as element %d in list",
1649 talloc_free(mem_ctx);
1650 return NULL;
1652 el->values[i].length = PyString_Size(item);
1653 el->values[i].data = talloc_memdup(el,
1654 (uint8_t *)PyString_AsString(item), el->values[i].length);
1656 } else {
1657 PyErr_SetString(PyExc_TypeError,
1658 "Expected string or list");
1659 talloc_free(mem_ctx);
1660 return NULL;
1664 el->flags = flags;
1665 el->name = talloc_strdup(el, name);
1667 ret = (PyLdbMessageElementObject *)PyLdbMessageElement.tp_alloc(&PyLdbMessageElement, 0);
1668 if (ret == NULL) {
1669 PyErr_NoMemory();
1670 talloc_free(mem_ctx);
1671 return NULL;
1674 ret->mem_ctx = mem_ctx;
1675 ret->el = el;
1676 return (PyObject *)ret;
1679 static PyObject *py_ldb_msg_element_repr(PyLdbMessageElementObject *self)
1681 char *element_str = NULL;
1682 int i;
1683 struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1684 PyObject *ret;
1686 for (i = 0; i < el->num_values; i++) {
1687 PyObject *o = py_ldb_msg_element_find(self, i);
1688 if (element_str == NULL)
1689 element_str = talloc_strdup(NULL, PyObject_REPR(o));
1690 else
1691 element_str = talloc_asprintf_append(element_str, ",%s", PyObject_REPR(o));
1694 ret = PyString_FromFormat("MessageElement([%s])", element_str);
1696 talloc_free(element_str);
1698 return ret;
1701 static PyObject *py_ldb_msg_element_str(PyLdbMessageElementObject *self)
1703 struct ldb_message_element *el = PyLdbMessageElement_AsMessageElement(self);
1705 if (el->num_values == 1)
1706 return PyString_FromStringAndSize((char *)el->values[0].data, el->values[0].length);
1707 else
1708 Py_RETURN_NONE;
1711 static void py_ldb_msg_element_dealloc(PyLdbMessageElementObject *self)
1713 talloc_free(self->mem_ctx);
1714 self->ob_type->tp_free(self);
1717 PyTypeObject PyLdbMessageElement = {
1718 .tp_name = "MessageElement",
1719 .tp_basicsize = sizeof(PyLdbMessageElementObject),
1720 .tp_dealloc = (destructor)py_ldb_msg_element_dealloc,
1721 .tp_repr = (reprfunc)py_ldb_msg_element_repr,
1722 .tp_str = (reprfunc)py_ldb_msg_element_str,
1723 .tp_methods = py_ldb_msg_element_methods,
1724 .tp_compare = (cmpfunc)py_ldb_msg_element_cmp,
1725 .tp_iter = (getiterfunc)py_ldb_msg_element_iter,
1726 .tp_as_sequence = &py_ldb_msg_element_seq,
1727 .tp_new = py_ldb_msg_element_new,
1728 .tp_flags = Py_TPFLAGS_DEFAULT,
1731 static PyObject *py_ldb_msg_remove_attr(PyLdbMessageObject *self, PyObject *args)
1733 char *name;
1734 if (!PyArg_ParseTuple(args, "s", &name))
1735 return NULL;
1737 ldb_msg_remove_attr(self->msg, name);
1739 Py_RETURN_NONE;
1742 static PyObject *py_ldb_msg_keys(PyLdbMessageObject *self)
1744 struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1745 int i, j = 0;
1746 PyObject *obj = PyList_New(msg->num_elements+(msg->dn != NULL?1:0));
1747 if (msg->dn != NULL) {
1748 PyList_SetItem(obj, j, PyString_FromString("dn"));
1749 j++;
1751 for (i = 0; i < msg->num_elements; i++) {
1752 PyList_SetItem(obj, j, PyString_FromString(msg->elements[i].name));
1753 j++;
1755 return obj;
1758 static PyObject *py_ldb_msg_getitem_helper(PyLdbMessageObject *self, PyObject *py_name)
1760 struct ldb_message_element *el;
1761 char *name;
1762 struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1763 if (!PyString_Check(py_name)) {
1764 PyErr_SetNone(PyExc_TypeError);
1765 return NULL;
1767 name = PyString_AsString(py_name);
1768 if (!strcmp(name, "dn"))
1769 return PyLdbDn_FromDn(msg->dn);
1770 el = ldb_msg_find_element(msg, name);
1771 if (el == NULL) {
1772 return NULL;
1774 return (PyObject *)PyLdbMessageElement_FromMessageElement(el, msg);
1777 static PyObject *py_ldb_msg_getitem(PyLdbMessageObject *self, PyObject *py_name)
1779 PyObject *ret = py_ldb_msg_getitem_helper(self, py_name);
1780 if (ret == NULL) {
1781 PyErr_SetString(PyExc_KeyError, "No such element");
1782 return NULL;
1784 return ret;
1787 static PyObject *py_ldb_msg_get(PyLdbMessageObject *self, PyObject *args)
1789 PyObject *name, *ret;
1790 if (!PyArg_ParseTuple(args, "O", &name))
1791 return NULL;
1793 ret = py_ldb_msg_getitem_helper(self, name);
1794 if (ret == NULL) {
1795 if (PyErr_Occurred())
1796 return NULL;
1797 Py_RETURN_NONE;
1799 return ret;
1802 static PyObject *py_ldb_msg_items(PyLdbMessageObject *self)
1804 struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1805 int i, j;
1806 PyObject *l = PyList_New(msg->num_elements + (msg->dn == NULL?0:1));
1807 j = 0;
1808 if (msg->dn != NULL) {
1809 PyList_SetItem(l, 0, Py_BuildValue("(sO)", "dn", PyLdbDn_FromDn(msg->dn)));
1810 j++;
1812 for (i = 0; i < msg->num_elements; i++, j++) {
1813 PyList_SetItem(l, j, Py_BuildValue("(sO)", msg->elements[i].name, PyLdbMessageElement_FromMessageElement(&msg->elements[i], self->msg)));
1815 return l;
1818 static PyMethodDef py_ldb_msg_methods[] = {
1819 { "keys", (PyCFunction)py_ldb_msg_keys, METH_NOARGS, NULL },
1820 { "remove", (PyCFunction)py_ldb_msg_remove_attr, METH_VARARGS, NULL },
1821 { "get", (PyCFunction)py_ldb_msg_get, METH_VARARGS, NULL },
1822 { "items", (PyCFunction)py_ldb_msg_items, METH_NOARGS, NULL },
1823 { NULL },
1826 static PyObject *py_ldb_msg_iter(PyLdbMessageObject *self)
1828 PyObject *list, *iter;
1830 list = py_ldb_msg_keys(self);
1831 iter = PyObject_GetIter(list);
1832 Py_DECREF(list);
1833 return iter;
1836 static int py_ldb_msg_setitem(PyLdbMessageObject *self, PyObject *name, PyObject *value)
1838 char *attr_name;
1840 if (!PyString_Check(name)) {
1841 PyErr_SetNone(PyExc_TypeError);
1842 return -1;
1845 attr_name = PyString_AsString(name);
1846 if (value == NULL) {
1847 /* delitem */
1848 ldb_msg_remove_attr(self->msg, attr_name);
1849 } else {
1850 struct ldb_message_element *el = PyObject_AsMessageElement(self->msg,
1851 value, 0, attr_name);
1852 if (el == NULL)
1853 return -1;
1854 ldb_msg_remove_attr(PyLdbMessage_AsMessage(self), attr_name);
1855 ldb_msg_add(PyLdbMessage_AsMessage(self), el, el->flags);
1857 return 0;
1860 static Py_ssize_t py_ldb_msg_length(PyLdbMessageObject *self)
1862 return PyLdbMessage_AsMessage(self)->num_elements;
1865 static PyMappingMethods py_ldb_msg_mapping = {
1866 .mp_length = (lenfunc)py_ldb_msg_length,
1867 .mp_subscript = (binaryfunc)py_ldb_msg_getitem,
1868 .mp_ass_subscript = (objobjargproc)py_ldb_msg_setitem,
1871 static PyObject *py_ldb_msg_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1873 const char * const kwnames[] = { "dn", NULL };
1874 struct ldb_message *ret;
1875 TALLOC_CTX *mem_ctx;
1876 PyObject *pydn = NULL;
1877 PyLdbMessageObject *py_ret;
1879 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O",
1880 discard_const_p(char *, kwnames),
1881 &pydn))
1882 return NULL;
1884 mem_ctx = talloc_new(NULL);
1885 if (mem_ctx == NULL) {
1886 PyErr_NoMemory();
1887 return NULL;
1890 ret = ldb_msg_new(mem_ctx);
1891 if (ret == NULL) {
1892 talloc_free(mem_ctx);
1893 PyErr_NoMemory();
1894 return NULL;
1897 if (pydn != NULL) {
1898 struct ldb_dn *dn;
1899 if (!PyObject_AsDn(NULL, pydn, NULL, &dn)) {
1900 talloc_free(mem_ctx);
1901 return NULL;
1903 ret->dn = talloc_reference(ret, dn);
1906 py_ret = (PyLdbMessageObject *)type->tp_alloc(type, 0);
1907 if (py_ret == NULL) {
1908 PyErr_NoMemory();
1909 talloc_free(mem_ctx);
1910 return NULL;
1913 py_ret->mem_ctx = mem_ctx;
1914 py_ret->msg = ret;
1915 return (PyObject *)py_ret;
1918 PyObject *PyLdbMessage_FromMessage(struct ldb_message *msg)
1920 PyLdbMessageObject *ret;
1922 ret = (PyLdbMessageObject *)PyLdbMessage.tp_alloc(&PyLdbMessage, 0);
1923 if (ret == NULL) {
1924 PyErr_NoMemory();
1925 return NULL;
1927 ret->mem_ctx = talloc_new(NULL);
1928 ret->msg = talloc_reference(ret->mem_ctx, msg);
1929 return (PyObject *)ret;
1932 static PyObject *py_ldb_msg_get_dn(PyLdbMessageObject *self, void *closure)
1934 struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1935 return PyLdbDn_FromDn(msg->dn);
1938 static int py_ldb_msg_set_dn(PyLdbMessageObject *self, PyObject *value, void *closure)
1940 struct ldb_message *msg = PyLdbMessage_AsMessage(self);
1941 if (!PyLdbDn_Check(value)) {
1942 PyErr_SetNone(PyExc_TypeError);
1943 return -1;
1946 msg->dn = talloc_reference(msg, PyLdbDn_AsDn(value));
1947 return 0;
1950 static PyGetSetDef py_ldb_msg_getset[] = {
1951 { discard_const_p(char, "dn"), (getter)py_ldb_msg_get_dn, (setter)py_ldb_msg_set_dn, NULL },
1952 { NULL }
1955 static PyObject *py_ldb_msg_repr(PyLdbMessageObject *self)
1957 PyObject *dict = PyDict_New(), *ret;
1958 if (PyDict_Update(dict, (PyObject *)self) != 0)
1959 return NULL;
1960 ret = PyString_FromFormat("Message(%s)", PyObject_REPR(dict));
1961 Py_DECREF(dict);
1962 return ret;
1965 static void py_ldb_msg_dealloc(PyLdbMessageObject *self)
1967 talloc_free(self->mem_ctx);
1968 self->ob_type->tp_free(self);
1971 PyTypeObject PyLdbMessage = {
1972 .tp_name = "Message",
1973 .tp_methods = py_ldb_msg_methods,
1974 .tp_getset = py_ldb_msg_getset,
1975 .tp_as_mapping = &py_ldb_msg_mapping,
1976 .tp_basicsize = sizeof(PyLdbMessageObject),
1977 .tp_dealloc = (destructor)py_ldb_msg_dealloc,
1978 .tp_new = py_ldb_msg_new,
1979 .tp_repr = (reprfunc)py_ldb_msg_repr,
1980 .tp_flags = Py_TPFLAGS_DEFAULT,
1981 .tp_iter = (getiterfunc)py_ldb_msg_iter,
1984 PyObject *PyLdbTree_FromTree(struct ldb_parse_tree *tree)
1986 PyLdbTreeObject *ret;
1988 ret = (PyLdbTreeObject *)PyLdbTree.tp_alloc(&PyLdbTree, 0);
1989 if (ret == NULL) {
1990 PyErr_NoMemory();
1991 return NULL;
1994 ret->mem_ctx = talloc_new(NULL);
1995 ret->tree = talloc_reference(ret->mem_ctx, tree);
1996 return (PyObject *)ret;
1999 static void py_ldb_tree_dealloc(PyLdbTreeObject *self)
2001 talloc_free(self->mem_ctx);
2002 self->ob_type->tp_free(self);
2005 PyTypeObject PyLdbTree = {
2006 .tp_name = "Tree",
2007 .tp_basicsize = sizeof(PyLdbTreeObject),
2008 .tp_dealloc = (destructor)py_ldb_tree_dealloc,
2009 .tp_flags = Py_TPFLAGS_DEFAULT,
2012 /* Ldb_module */
2013 static int py_module_search(struct ldb_module *mod, struct ldb_request *req)
2015 PyObject *py_ldb = (PyObject *)mod->private_data;
2016 PyObject *py_result, *py_base, *py_attrs, *py_tree;
2018 py_base = PyLdbDn_FromDn(req->op.search.base);
2020 if (py_base == NULL)
2021 return LDB_ERR_OPERATIONS_ERROR;
2023 py_tree = PyLdbTree_FromTree(req->op.search.tree);
2025 if (py_tree == NULL)
2026 return LDB_ERR_OPERATIONS_ERROR;
2028 if (req->op.search.attrs == NULL) {
2029 py_attrs = Py_None;
2030 } else {
2031 int i, len;
2032 for (len = 0; req->op.search.attrs[len]; len++);
2033 py_attrs = PyList_New(len);
2034 for (i = 0; i < len; i++)
2035 PyList_SetItem(py_attrs, i, PyString_FromString(req->op.search.attrs[i]));
2038 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "search"),
2039 discard_const_p(char, "OiOO"),
2040 py_base, req->op.search.scope, py_tree, py_attrs);
2042 Py_DECREF(py_attrs);
2043 Py_DECREF(py_tree);
2044 Py_DECREF(py_base);
2046 if (py_result == NULL) {
2047 return LDB_ERR_PYTHON_EXCEPTION;
2050 req->op.search.res = PyLdbResult_AsResult(NULL, py_result);
2051 if (req->op.search.res == NULL) {
2052 return LDB_ERR_PYTHON_EXCEPTION;
2055 Py_DECREF(py_result);
2057 return LDB_SUCCESS;
2060 static int py_module_add(struct ldb_module *mod, struct ldb_request *req)
2062 PyObject *py_ldb = (PyObject *)mod->private_data;
2063 PyObject *py_result, *py_msg;
2065 py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.add.message));
2067 if (py_msg == NULL) {
2068 return LDB_ERR_OPERATIONS_ERROR;
2071 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "add"),
2072 discard_const_p(char, "O"),
2073 py_msg);
2075 Py_DECREF(py_msg);
2077 if (py_result == NULL) {
2078 return LDB_ERR_PYTHON_EXCEPTION;
2081 Py_DECREF(py_result);
2083 return LDB_SUCCESS;
2086 static int py_module_modify(struct ldb_module *mod, struct ldb_request *req)
2088 PyObject *py_ldb = (PyObject *)mod->private_data;
2089 PyObject *py_result, *py_msg;
2091 py_msg = PyLdbMessage_FromMessage(discard_const_p(struct ldb_message, req->op.mod.message));
2093 if (py_msg == NULL) {
2094 return LDB_ERR_OPERATIONS_ERROR;
2097 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "modify"),
2098 discard_const_p(char, "O"),
2099 py_msg);
2101 Py_DECREF(py_msg);
2103 if (py_result == NULL) {
2104 return LDB_ERR_PYTHON_EXCEPTION;
2107 Py_DECREF(py_result);
2109 return LDB_SUCCESS;
2112 static int py_module_del(struct ldb_module *mod, struct ldb_request *req)
2114 PyObject *py_ldb = (PyObject *)mod->private_data;
2115 PyObject *py_result, *py_dn;
2117 py_dn = PyLdbDn_FromDn(req->op.del.dn);
2119 if (py_dn == NULL)
2120 return LDB_ERR_OPERATIONS_ERROR;
2122 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "delete"),
2123 discard_const_p(char, "O"),
2124 py_dn);
2126 if (py_result == NULL) {
2127 return LDB_ERR_PYTHON_EXCEPTION;
2130 Py_DECREF(py_result);
2132 return LDB_SUCCESS;
2135 static int py_module_rename(struct ldb_module *mod, struct ldb_request *req)
2137 PyObject *py_ldb = (PyObject *)mod->private_data;
2138 PyObject *py_result, *py_olddn, *py_newdn;
2140 py_olddn = PyLdbDn_FromDn(req->op.rename.olddn);
2142 if (py_olddn == NULL)
2143 return LDB_ERR_OPERATIONS_ERROR;
2145 py_newdn = PyLdbDn_FromDn(req->op.rename.newdn);
2147 if (py_newdn == NULL)
2148 return LDB_ERR_OPERATIONS_ERROR;
2150 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "rename"),
2151 discard_const_p(char, "OO"),
2152 py_olddn, py_newdn);
2154 Py_DECREF(py_olddn);
2155 Py_DECREF(py_newdn);
2157 if (py_result == NULL) {
2158 return LDB_ERR_PYTHON_EXCEPTION;
2161 Py_DECREF(py_result);
2163 return LDB_SUCCESS;
2166 static int py_module_request(struct ldb_module *mod, struct ldb_request *req)
2168 PyObject *py_ldb = (PyObject *)mod->private_data;
2169 PyObject *py_result;
2171 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "request"),
2172 discard_const_p(char, ""));
2174 return LDB_ERR_OPERATIONS_ERROR;
2177 static int py_module_extended(struct ldb_module *mod, struct ldb_request *req)
2179 PyObject *py_ldb = (PyObject *)mod->private_data;
2180 PyObject *py_result;
2182 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "extended"),
2183 discard_const_p(char, ""));
2185 return LDB_ERR_OPERATIONS_ERROR;
2188 static int py_module_start_transaction(struct ldb_module *mod)
2190 PyObject *py_ldb = (PyObject *)mod->private_data;
2191 PyObject *py_result;
2193 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "start_transaction"),
2194 discard_const_p(char, ""));
2196 if (py_result == NULL) {
2197 return LDB_ERR_PYTHON_EXCEPTION;
2200 Py_DECREF(py_result);
2202 return LDB_SUCCESS;
2205 static int py_module_end_transaction(struct ldb_module *mod)
2207 PyObject *py_ldb = (PyObject *)mod->private_data;
2208 PyObject *py_result;
2210 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "end_transaction"),
2211 discard_const_p(char, ""));
2213 if (py_result == NULL) {
2214 return LDB_ERR_PYTHON_EXCEPTION;
2217 Py_DECREF(py_result);
2219 return LDB_SUCCESS;
2222 static int py_module_del_transaction(struct ldb_module *mod)
2224 PyObject *py_ldb = (PyObject *)mod->private_data;
2225 PyObject *py_result;
2227 py_result = PyObject_CallMethod(py_ldb, discard_const_p(char, "del_transaction"),
2228 discard_const_p(char, ""));
2230 if (py_result == NULL) {
2231 return LDB_ERR_PYTHON_EXCEPTION;
2234 Py_DECREF(py_result);
2236 return LDB_SUCCESS;
2239 static int py_module_destructor(struct ldb_module *mod)
2241 Py_DECREF((PyObject *)mod->private_data);
2242 return 0;
2245 static int py_module_init(struct ldb_module *mod)
2247 PyObject *py_class = (PyObject *)mod->ops->private_data;
2248 PyObject *py_result, *py_next, *py_ldb;
2250 py_ldb = PyLdb_FromLdbContext(mod->ldb);
2252 if (py_ldb == NULL)
2253 return LDB_ERR_OPERATIONS_ERROR;
2255 py_next = PyLdbModule_FromModule(mod->next);
2257 if (py_next == NULL)
2258 return LDB_ERR_OPERATIONS_ERROR;
2260 py_result = PyObject_CallFunction(py_class, discard_const_p(char, "OO"),
2261 py_ldb, py_next);
2263 if (py_result == NULL) {
2264 return LDB_ERR_PYTHON_EXCEPTION;
2267 mod->private_data = py_result;
2269 talloc_set_destructor(mod, py_module_destructor);
2271 return ldb_next_init(mod);
2274 static PyObject *py_register_module(PyObject *module, PyObject *args)
2276 int ret;
2277 struct ldb_module_ops *ops;
2278 PyObject *input;
2280 if (!PyArg_ParseTuple(args, "O", &input))
2281 return NULL;
2283 ops = talloc_zero(talloc_autofree_context(), struct ldb_module_ops);
2284 if (ops == NULL) {
2285 PyErr_NoMemory();
2286 return NULL;
2289 ops->name = talloc_strdup(ops, PyString_AsString(PyObject_GetAttrString(input, discard_const_p(char, "name"))));
2291 Py_INCREF(input);
2292 ops->private_data = input;
2293 ops->init_context = py_module_init;
2294 ops->search = py_module_search;
2295 ops->add = py_module_add;
2296 ops->modify = py_module_modify;
2297 ops->del = py_module_del;
2298 ops->rename = py_module_rename;
2299 ops->request = py_module_request;
2300 ops->extended = py_module_extended;
2301 ops->start_transaction = py_module_start_transaction;
2302 ops->end_transaction = py_module_end_transaction;
2303 ops->del_transaction = py_module_del_transaction;
2305 ret = ldb_register_module(ops);
2307 PyErr_LDB_ERROR_IS_ERR_RAISE(PyExc_LdbError, ret, NULL);
2309 Py_RETURN_NONE;
2312 static PyObject *py_timestring(PyObject *module, PyObject *args)
2314 time_t t;
2315 char *tresult;
2316 PyObject *ret;
2317 if (!PyArg_ParseTuple(args, "L", &t))
2318 return NULL;
2319 tresult = ldb_timestring(NULL, t);
2320 ret = PyString_FromString(tresult);
2321 talloc_free(tresult);
2322 return ret;
2325 static PyObject *py_string_to_time(PyObject *module, PyObject *args)
2327 char *str;
2328 if (!PyArg_ParseTuple(args, "s", &str))
2329 return NULL;
2331 return PyInt_FromLong(ldb_string_to_time(str));
2334 static PyObject *py_valid_attr_name(PyObject *self, PyObject *args)
2336 char *name;
2337 if (!PyArg_ParseTuple(args, "s", &name))
2338 return NULL;
2339 return PyBool_FromLong(ldb_valid_attr_name(name));
2342 static PyMethodDef py_ldb_global_methods[] = {
2343 { "register_module", py_register_module, METH_VARARGS,
2344 "S.register_module(module) -> None\n"
2345 "Register a LDB module."},
2346 { "timestring", py_timestring, METH_VARARGS,
2347 "S.timestring(int) -> string\n"
2348 "Generate a LDAP time string from a UNIX timestamp" },
2349 { "string_to_time", py_string_to_time, METH_VARARGS,
2350 "S.string_to_time(string) -> int\n"
2351 "Parse a LDAP time string into a UNIX timestamp." },
2352 { "valid_attr_name", py_valid_attr_name, METH_VARARGS,
2353 "S.valid_attr_name(name) -> bool\n"
2354 "Check whether the supplied name is a valid attribute name." },
2355 { "open", (PyCFunction)py_ldb_new, METH_VARARGS|METH_KEYWORDS,
2356 NULL },
2357 { NULL }
2360 void initldb(void)
2362 PyObject *m;
2364 if (PyType_Ready(&PyLdbDn) < 0)
2365 return;
2367 if (PyType_Ready(&PyLdbMessage) < 0)
2368 return;
2370 if (PyType_Ready(&PyLdbMessageElement) < 0)
2371 return;
2373 if (PyType_Ready(&PyLdb) < 0)
2374 return;
2376 if (PyType_Ready(&PyLdbModule) < 0)
2377 return;
2379 if (PyType_Ready(&PyLdbTree) < 0)
2380 return;
2382 m = Py_InitModule3("ldb", py_ldb_global_methods,
2383 "An interface to LDB, a LDAP-like API that can either to talk an embedded database (TDB-based) or a standards-compliant LDAP server.");
2384 if (m == NULL)
2385 return;
2387 PyModule_AddObject(m, "SCOPE_DEFAULT", PyInt_FromLong(LDB_SCOPE_DEFAULT));
2388 PyModule_AddObject(m, "SCOPE_BASE", PyInt_FromLong(LDB_SCOPE_BASE));
2389 PyModule_AddObject(m, "SCOPE_ONELEVEL", PyInt_FromLong(LDB_SCOPE_ONELEVEL));
2390 PyModule_AddObject(m, "SCOPE_SUBTREE", PyInt_FromLong(LDB_SCOPE_SUBTREE));
2392 PyModule_AddObject(m, "CHANGETYPE_NONE", PyInt_FromLong(LDB_CHANGETYPE_NONE));
2393 PyModule_AddObject(m, "CHANGETYPE_ADD", PyInt_FromLong(LDB_CHANGETYPE_ADD));
2394 PyModule_AddObject(m, "CHANGETYPE_DELETE", PyInt_FromLong(LDB_CHANGETYPE_DELETE));
2395 PyModule_AddObject(m, "CHANGETYPE_MODIFY", PyInt_FromLong(LDB_CHANGETYPE_MODIFY));
2397 PyModule_AddObject(m, "FLAG_MOD_ADD", PyInt_FromLong(LDB_FLAG_MOD_ADD));
2398 PyModule_AddObject(m, "FLAG_MOD_REPLACE", PyInt_FromLong(LDB_FLAG_MOD_REPLACE));
2399 PyModule_AddObject(m, "FLAG_MOD_DELETE", PyInt_FromLong(LDB_FLAG_MOD_DELETE));
2401 PyModule_AddObject(m, "SUCCESS", PyInt_FromLong(LDB_SUCCESS));
2402 PyModule_AddObject(m, "ERR_OPERATIONS_ERROR", PyInt_FromLong(LDB_ERR_OPERATIONS_ERROR));
2403 PyModule_AddObject(m, "ERR_PROTOCOL_ERROR", PyInt_FromLong(LDB_ERR_PROTOCOL_ERROR));
2404 PyModule_AddObject(m, "ERR_TIME_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_TIME_LIMIT_EXCEEDED));
2405 PyModule_AddObject(m, "ERR_SIZE_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_SIZE_LIMIT_EXCEEDED));
2406 PyModule_AddObject(m, "ERR_COMPARE_FALSE", PyInt_FromLong(LDB_ERR_COMPARE_FALSE));
2407 PyModule_AddObject(m, "ERR_COMPARE_TRUE", PyInt_FromLong(LDB_ERR_COMPARE_TRUE));
2408 PyModule_AddObject(m, "ERR_AUTH_METHOD_NOT_SUPPORTED", PyInt_FromLong(LDB_ERR_AUTH_METHOD_NOT_SUPPORTED));
2409 PyModule_AddObject(m, "ERR_STRONG_AUTH_REQUIRED", PyInt_FromLong(LDB_ERR_STRONG_AUTH_REQUIRED));
2410 PyModule_AddObject(m, "ERR_REFERRAL", PyInt_FromLong(LDB_ERR_REFERRAL));
2411 PyModule_AddObject(m, "ERR_ADMIN_LIMIT_EXCEEDED", PyInt_FromLong(LDB_ERR_ADMIN_LIMIT_EXCEEDED));
2412 PyModule_AddObject(m, "ERR_UNSUPPORTED_CRITICAL_EXTENSION", PyInt_FromLong(LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION));
2413 PyModule_AddObject(m, "ERR_CONFIDENTIALITY_REQUIRED", PyInt_FromLong(LDB_ERR_CONFIDENTIALITY_REQUIRED));
2414 PyModule_AddObject(m, "ERR_SASL_BIND_IN_PROGRESS", PyInt_FromLong(LDB_ERR_SASL_BIND_IN_PROGRESS));
2415 PyModule_AddObject(m, "ERR_NO_SUCH_ATTRIBUTE", PyInt_FromLong(LDB_ERR_NO_SUCH_ATTRIBUTE));
2416 PyModule_AddObject(m, "ERR_UNDEFINED_ATTRIBUTE_TYPE", PyInt_FromLong(LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE));
2417 PyModule_AddObject(m, "ERR_INAPPROPRIATE_MATCHING", PyInt_FromLong(LDB_ERR_INAPPROPRIATE_MATCHING));
2418 PyModule_AddObject(m, "ERR_CONSTRAINT_VIOLATION", PyInt_FromLong(LDB_ERR_CONSTRAINT_VIOLATION));
2419 PyModule_AddObject(m, "ERR_ATTRIBUTE_OR_VALUE_EXISTS", PyInt_FromLong(LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS));
2420 PyModule_AddObject(m, "ERR_INVALID_ATTRIBUTE_SYNTAX", PyInt_FromLong(LDB_ERR_INVALID_ATTRIBUTE_SYNTAX));
2421 PyModule_AddObject(m, "ERR_NO_SUCH_OBJECT", PyInt_FromLong(LDB_ERR_NO_SUCH_OBJECT));
2422 PyModule_AddObject(m, "ERR_ALIAS_PROBLEM", PyInt_FromLong(LDB_ERR_ALIAS_PROBLEM));
2423 PyModule_AddObject(m, "ERR_INVALID_DN_SYNTAX", PyInt_FromLong(LDB_ERR_INVALID_DN_SYNTAX));
2424 PyModule_AddObject(m, "ERR_ALIAS_DEREFERINCING_PROBLEM", PyInt_FromLong(LDB_ERR_ALIAS_DEREFERENCING_PROBLEM));
2425 PyModule_AddObject(m, "ERR_INAPPROPRIATE_AUTHENTICATION", PyInt_FromLong(LDB_ERR_INAPPROPRIATE_AUTHENTICATION));
2426 PyModule_AddObject(m, "ERR_INVALID_CREDENTIALS", PyInt_FromLong(LDB_ERR_INVALID_CREDENTIALS));
2427 PyModule_AddObject(m, "ERR_INSUFFICIENT_ACCESS_RIGHTS", PyInt_FromLong(LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS));
2428 PyModule_AddObject(m, "ERR_BUSY", PyInt_FromLong(LDB_ERR_BUSY));
2429 PyModule_AddObject(m, "ERR_UNAVAILABLE", PyInt_FromLong(LDB_ERR_UNAVAILABLE));
2430 PyModule_AddObject(m, "ERR_UNWILLING_TO_PERFORM", PyInt_FromLong(LDB_ERR_UNWILLING_TO_PERFORM));
2431 PyModule_AddObject(m, "ERR_LOOP_DETECT", PyInt_FromLong(LDB_ERR_LOOP_DETECT));
2432 PyModule_AddObject(m, "ERR_NAMING_VIOLATION", PyInt_FromLong(LDB_ERR_NAMING_VIOLATION));
2433 PyModule_AddObject(m, "ERR_OBJECT_CLASS_VIOLATION", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_VIOLATION));
2434 PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_NON_LEAF", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_NON_LEAF));
2435 PyModule_AddObject(m, "ERR_NOT_ALLOWED_ON_RDN", PyInt_FromLong(LDB_ERR_NOT_ALLOWED_ON_RDN));
2436 PyModule_AddObject(m, "ERR_ENTRY_ALREADY_EXISTS", PyInt_FromLong(LDB_ERR_ENTRY_ALREADY_EXISTS));
2437 PyModule_AddObject(m, "ERR_OBJECT_CLASS_MODS_PROHIBITED", PyInt_FromLong(LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED));
2438 PyModule_AddObject(m, "ERR_AFFECTS_MULTIPLE_DSAS", PyInt_FromLong(LDB_ERR_AFFECTS_MULTIPLE_DSAS));
2439 PyModule_AddObject(m, "ERR_OTHER", PyInt_FromLong(LDB_ERR_OTHER));
2441 PyModule_AddObject(m, "FLG_RDONLY", PyInt_FromLong(LDB_FLG_RDONLY));
2442 PyModule_AddObject(m, "FLG_NOSYNC", PyInt_FromLong(LDB_FLG_NOSYNC));
2443 PyModule_AddObject(m, "FLG_RECONNECT", PyInt_FromLong(LDB_FLG_RECONNECT));
2444 PyModule_AddObject(m, "FLG_NOMMAP", PyInt_FromLong(LDB_FLG_NOMMAP));
2447 PyModule_AddObject(m, "__docformat__", PyString_FromString("restructuredText"));
2449 PyExc_LdbError = PyErr_NewException(discard_const_p(char, "_ldb.LdbError"), NULL, NULL);
2450 PyModule_AddObject(m, "LdbError", PyExc_LdbError);
2452 Py_INCREF(&PyLdb);
2453 Py_INCREF(&PyLdbDn);
2454 Py_INCREF(&PyLdbModule);
2455 Py_INCREF(&PyLdbMessage);
2456 Py_INCREF(&PyLdbMessageElement);
2457 Py_INCREF(&PyLdbTree);
2459 PyModule_AddObject(m, "Ldb", (PyObject *)&PyLdb);
2460 PyModule_AddObject(m, "Dn", (PyObject *)&PyLdbDn);
2461 PyModule_AddObject(m, "Message", (PyObject *)&PyLdbMessage);
2462 PyModule_AddObject(m, "MessageElement", (PyObject *)&PyLdbMessageElement);
2463 PyModule_AddObject(m, "Module", (PyObject *)&PyLdbModule);
2464 PyModule_AddObject(m, "Tree", (PyObject *)&PyLdbTree);