86f604874b9412f3511ba7c27dc6945e94da1ab9
[bbaumbach/samba-autobuild/.git] / lib / tdb2 / pytdb.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Python interface to tdb2.  Simply modified from tdb1 version.
5
6    Copyright (C) 2004-2006 Tim Potter <tpot@samba.org>
7    Copyright (C) 2007-2008 Jelmer Vernooij <jelmer@samba.org>
8    Copyright (C) 2011 Rusty Russell <rusty@rustcorp.com.au>
9
10      ** NOTE! The following LGPL license applies to the tdb
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 #include <Python.h>
29 #include "replace.h"
30 #include "system/filesys.h"
31
32 #ifndef Py_RETURN_NONE
33 #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
34 #endif
35
36 /* Include tdb headers */
37 #include <tdb2.h>
38
39 typedef struct {
40         PyObject_HEAD
41         struct tdb_context *ctx;
42         bool closed;
43 } PyTdbObject;
44
45 staticforward PyTypeObject PyTdb;
46
47 static void PyErr_SetTDBError(enum TDB_ERROR e)
48 {
49         PyErr_SetObject(PyExc_RuntimeError,
50                 Py_BuildValue("(i,s)", e, tdb_errorstr(e)));
51 }
52
53 static TDB_DATA PyString_AsTDB_DATA(PyObject *data)
54 {
55         TDB_DATA ret;
56         ret.dptr = (unsigned char *)PyString_AsString(data);
57         ret.dsize = PyString_Size(data);
58         return ret;
59 }
60
61 static PyObject *PyString_FromTDB_DATA(TDB_DATA data)
62 {
63         PyObject *ret = PyString_FromStringAndSize((const char *)data.dptr,
64                                                    data.dsize);
65         free(data.dptr);
66         return ret;
67 }
68
69 #define PyErr_TDB_ERROR_IS_ERR_RAISE(ret) \
70         if (ret != TDB_SUCCESS) { \
71                 PyErr_SetTDBError(ret); \
72                 return NULL; \
73         }
74
75 static PyObject *py_tdb_open(PyTypeObject *type, PyObject *args, PyObject *kwargs)
76 {
77         char *name = NULL;
78         int tdb_flags = TDB_DEFAULT, flags = O_RDWR, mode = 0600;
79         struct tdb_context *ctx;
80         PyTdbObject *ret;
81         const char *kwnames[] = { "name", "tdb_flags", "flags", "mode", NULL };
82
83         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|siii", (char **)kwnames, &name, &tdb_flags, &flags, &mode))
84                 return NULL;
85
86         if (name == NULL) {
87                 tdb_flags |= TDB_INTERNAL;
88         }
89
90         ctx = tdb_open(name, tdb_flags, flags, mode, NULL);
91         if (ctx == NULL) {
92                 PyErr_SetFromErrno(PyExc_IOError);
93                 return NULL;
94         }
95
96         ret = PyObject_New(PyTdbObject, &PyTdb);
97         if (!ret) {
98                 tdb_close(ctx);
99                 return NULL;
100         }
101
102         ret->ctx = ctx;
103         ret->closed = false;
104         return (PyObject *)ret;
105 }
106
107 static PyObject *obj_transaction_cancel(PyTdbObject *self)
108 {
109         tdb_transaction_cancel(self->ctx);
110         Py_RETURN_NONE;
111 }
112
113 static PyObject *obj_transaction_commit(PyTdbObject *self)
114 {
115         enum TDB_ERROR ret = tdb_transaction_commit(self->ctx);
116         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
117         Py_RETURN_NONE;
118 }
119
120 static PyObject *obj_transaction_prepare_commit(PyTdbObject *self)
121 {
122         enum TDB_ERROR ret = tdb_transaction_prepare_commit(self->ctx);
123         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
124         Py_RETURN_NONE;
125 }
126
127 static PyObject *obj_transaction_start(PyTdbObject *self)
128 {
129         enum TDB_ERROR ret = tdb_transaction_start(self->ctx);
130         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
131         Py_RETURN_NONE;
132 }
133
134 static PyObject *obj_lockall(PyTdbObject *self)
135 {
136         enum TDB_ERROR ret = tdb_lockall(self->ctx);
137         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
138         Py_RETURN_NONE;
139 }
140
141 static PyObject *obj_unlockall(PyTdbObject *self)
142 {
143         tdb_unlockall(self->ctx);
144         Py_RETURN_NONE;
145 }
146
147 static PyObject *obj_lockall_read(PyTdbObject *self)
148 {
149         enum TDB_ERROR ret = tdb_lockall_read(self->ctx);
150         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
151         Py_RETURN_NONE;
152 }
153
154 static PyObject *obj_unlockall_read(PyTdbObject *self)
155 {
156         tdb_unlockall_read(self->ctx);
157         Py_RETURN_NONE;
158 }
159
160 static PyObject *obj_close(PyTdbObject *self)
161 {
162         enum TDB_ERROR ret;
163         if (self->closed)
164                 Py_RETURN_NONE;
165         ret = tdb_close(self->ctx);
166         self->closed = true;
167         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
168         Py_RETURN_NONE;
169 }
170
171 static PyObject *obj_get(PyTdbObject *self, PyObject *args)
172 {
173         TDB_DATA key, data;
174         PyObject *py_key;
175         enum TDB_ERROR ret;
176         if (!PyArg_ParseTuple(args, "O", &py_key))
177                 return NULL;
178
179         key = PyString_AsTDB_DATA(py_key);
180         ret = tdb_fetch(self->ctx, key, &data);
181         if (ret == TDB_ERR_NOEXIST)
182                 Py_RETURN_NONE;
183         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
184         return PyString_FromTDB_DATA(data);
185 }
186
187 static PyObject *obj_append(PyTdbObject *self, PyObject *args)
188 {
189         TDB_DATA key, data;
190         PyObject *py_key, *py_data;
191         enum TDB_ERROR ret;
192         if (!PyArg_ParseTuple(args, "OO", &py_key, &py_data))
193                 return NULL;
194
195         key = PyString_AsTDB_DATA(py_key);
196         data = PyString_AsTDB_DATA(py_data);
197
198         ret = tdb_append(self->ctx, key, data);
199         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
200         Py_RETURN_NONE;
201 }
202
203 static PyObject *obj_firstkey(PyTdbObject *self)
204 {
205         enum TDB_ERROR ret;
206         TDB_DATA key;
207
208         ret = tdb_firstkey(self->ctx, &key);
209         if (ret == TDB_ERR_NOEXIST)
210                 Py_RETURN_NONE;
211         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
212
213         return PyString_FromTDB_DATA(key);
214 }
215
216 static PyObject *obj_nextkey(PyTdbObject *self, PyObject *args)
217 {
218         TDB_DATA key;
219         PyObject *py_key;
220         enum TDB_ERROR ret;
221         if (!PyArg_ParseTuple(args, "O", &py_key))
222                 return NULL;
223
224         /* Malloc here, since tdb_nextkey frees. */
225         key.dsize = PyString_Size(py_key);
226         key.dptr = malloc(key.dsize);
227         memcpy(key.dptr, PyString_AsString(py_key), key.dsize);
228
229         ret = tdb_nextkey(self->ctx, &key);
230         if (ret == TDB_ERR_NOEXIST)
231                 Py_RETURN_NONE;
232         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
233
234         return PyString_FromTDB_DATA(key);
235 }
236
237 static PyObject *obj_delete(PyTdbObject *self, PyObject *args)
238 {
239         TDB_DATA key;
240         PyObject *py_key;
241         enum TDB_ERROR ret;
242         if (!PyArg_ParseTuple(args, "O", &py_key))
243                 return NULL;
244
245         key = PyString_AsTDB_DATA(py_key);
246         ret = tdb_delete(self->ctx, key);
247         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
248         Py_RETURN_NONE;
249 }
250
251 static PyObject *obj_has_key(PyTdbObject *self, PyObject *args)
252 {
253         TDB_DATA key;
254         enum TDB_ERROR ret;
255         PyObject *py_key;
256         if (!PyArg_ParseTuple(args, "O", &py_key))
257                 return NULL;
258
259         key = PyString_AsTDB_DATA(py_key);
260         ret = tdb_exists(self->ctx, key);
261         if (ret == TDB_ERR_NOEXIST)
262                 return Py_False;
263         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
264         return Py_True;
265 }
266
267 static PyObject *obj_store(PyTdbObject *self, PyObject *args)
268 {
269         TDB_DATA key, value;
270         enum TDB_ERROR ret;
271         int flag = TDB_REPLACE;
272         PyObject *py_key, *py_value;
273
274         if (!PyArg_ParseTuple(args, "OO|i", &py_key, &py_value, &flag))
275                 return NULL;
276
277         key = PyString_AsTDB_DATA(py_key);
278         value = PyString_AsTDB_DATA(py_value);
279
280         ret = tdb_store(self->ctx, key, value, flag);
281         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
282         Py_RETURN_NONE;
283 }
284
285 static PyObject *obj_add_flag(PyTdbObject *self, PyObject *args)
286 {
287         unsigned flag;
288
289         if (!PyArg_ParseTuple(args, "I", &flag))
290                 return NULL;
291
292         tdb_add_flag(self->ctx, flag);
293         Py_RETURN_NONE;
294 }
295
296 static PyObject *obj_remove_flag(PyTdbObject *self, PyObject *args)
297 {
298         unsigned flag;
299
300         if (!PyArg_ParseTuple(args, "I", &flag))
301                 return NULL;
302
303         tdb_remove_flag(self->ctx, flag);
304         Py_RETURN_NONE;
305 }
306
307 typedef struct {
308         PyObject_HEAD
309         TDB_DATA current;
310         bool end;
311         PyTdbObject *iteratee;
312 } PyTdbIteratorObject;
313
314 static PyObject *tdb_iter_next(PyTdbIteratorObject *self)
315 {
316         enum TDB_ERROR e;
317         PyObject *ret;
318         if (self->end)
319                 return NULL;
320         ret = PyString_FromStringAndSize((const char *)self->current.dptr,
321                                          self->current.dsize);
322         e = tdb_nextkey(self->iteratee->ctx, &self->current);
323         if (e == TDB_ERR_NOEXIST)
324                 self->end = true;
325         else
326                 PyErr_TDB_ERROR_IS_ERR_RAISE(e);
327         return ret;
328 }
329
330 static void tdb_iter_dealloc(PyTdbIteratorObject *self)
331 {
332         Py_DECREF(self->iteratee);
333         PyObject_Del(self);
334 }
335
336 PyTypeObject PyTdbIterator = {
337         .tp_name = "Iterator",
338         .tp_basicsize = sizeof(PyTdbIteratorObject),
339         .tp_iternext = (iternextfunc)tdb_iter_next,
340         .tp_dealloc = (destructor)tdb_iter_dealloc,
341         .tp_flags = Py_TPFLAGS_DEFAULT,
342         .tp_iter = PyObject_SelfIter,
343 };
344
345 static PyObject *tdb_object_iter(PyTdbObject *self)
346 {
347         PyTdbIteratorObject *ret;
348         enum TDB_ERROR e;
349
350         ret = PyObject_New(PyTdbIteratorObject, &PyTdbIterator);
351         if (!ret)
352                 return NULL;
353         e = tdb_firstkey(self->ctx, &ret->current);
354         if (e == TDB_ERR_NOEXIST) {
355                 ret->end = true;
356         } else {
357                 PyErr_TDB_ERROR_IS_ERR_RAISE(e);
358                 ret->end = false;
359         }
360         ret->iteratee = self;
361         Py_INCREF(self);
362         return (PyObject *)ret;
363 }
364
365 static PyObject *obj_clear(PyTdbObject *self)
366 {
367         enum TDB_ERROR ret = tdb_wipe_all(self->ctx);
368         PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
369         Py_RETURN_NONE;
370 }
371
372 static PyObject *obj_enable_seqnum(PyTdbObject *self)
373 {
374         tdb_add_flag(self->ctx, TDB_SEQNUM);
375         Py_RETURN_NONE;
376 }
377
378 static PyMethodDef tdb_object_methods[] = {
379         { "transaction_cancel", (PyCFunction)obj_transaction_cancel, METH_NOARGS,
380                 "S.transaction_cancel() -> None\n"
381                 "Cancel the currently active transaction." },
382         { "transaction_commit", (PyCFunction)obj_transaction_commit, METH_NOARGS,
383                 "S.transaction_commit() -> None\n"
384                 "Commit the currently active transaction." },
385         { "transaction_prepare_commit", (PyCFunction)obj_transaction_prepare_commit, METH_NOARGS,
386                 "S.transaction_prepare_commit() -> None\n"
387                 "Prepare to commit the currently active transaction" },
388         { "transaction_start", (PyCFunction)obj_transaction_start, METH_NOARGS,
389                 "S.transaction_start() -> None\n"
390                 "Start a new transaction." },
391         { "lock_all", (PyCFunction)obj_lockall, METH_NOARGS, NULL },
392         { "unlock_all", (PyCFunction)obj_unlockall, METH_NOARGS, NULL },
393         { "read_lock_all", (PyCFunction)obj_lockall_read, METH_NOARGS, NULL },
394         { "read_unlock_all", (PyCFunction)obj_unlockall_read, METH_NOARGS, NULL },
395         { "close", (PyCFunction)obj_close, METH_NOARGS, NULL },
396         { "get", (PyCFunction)obj_get, METH_VARARGS, "S.get(key) -> value\n"
397                 "Fetch a value." },
398         { "append", (PyCFunction)obj_append, METH_VARARGS, "S.append(key, value) -> None\n"
399                 "Append data to an existing key." },
400         { "firstkey", (PyCFunction)obj_firstkey, METH_NOARGS, "S.firstkey() -> data\n"
401                 "Return the first key in this database." },
402         { "nextkey", (PyCFunction)obj_nextkey, METH_NOARGS, "S.nextkey(key) -> data\n"
403                 "Return the next key in this database." },
404         { "delete", (PyCFunction)obj_delete, METH_VARARGS, "S.delete(key) -> None\n"
405                 "Delete an entry." },
406         { "has_key", (PyCFunction)obj_has_key, METH_VARARGS, "S.has_key(key) -> None\n"
407                 "Check whether key exists in this database." },
408         { "store", (PyCFunction)obj_store, METH_VARARGS, "S.store(key, data, flag=REPLACE) -> None"
409                 "Store data." },
410         { "add_flag", (PyCFunction)obj_add_flag, METH_VARARGS, "S.add_flag(flag) -> None" },
411         { "remove_flag", (PyCFunction)obj_remove_flag, METH_VARARGS, "S.remove_flag(flag) -> None" },
412         { "iterkeys", (PyCFunction)tdb_object_iter, METH_NOARGS, "S.iterkeys() -> iterator" },
413         { "clear", (PyCFunction)obj_clear, METH_NOARGS, "S.clear() -> None\n"
414                 "Wipe the entire database." },
415         { "enable_seqnum", (PyCFunction)obj_enable_seqnum, METH_NOARGS,
416                 "S.enable_seqnum() -> None" },
417         { NULL }
418 };
419
420 static PyObject *obj_get_flags(PyTdbObject *self, void *closure)
421 {
422         return PyInt_FromLong(tdb_get_flags(self->ctx));
423 }
424
425 static PyObject *obj_get_filename(PyTdbObject *self, void *closure)
426 {
427         return PyString_FromString(tdb_name(self->ctx));
428 }
429
430 static PyObject *obj_get_seqnum(PyTdbObject *self, void *closure)
431 {
432         return PyInt_FromLong(tdb_get_seqnum(self->ctx));
433 }
434
435
436 static PyGetSetDef tdb_object_getsetters[] = {
437         { (char *)"flags", (getter)obj_get_flags, NULL, NULL },
438         { (char *)"filename", (getter)obj_get_filename, NULL, (char *)"The filename of this TDB file."},
439         { (char *)"seqnum", (getter)obj_get_seqnum, NULL, NULL },
440         { NULL }
441 };
442
443 static PyObject *tdb_object_repr(PyTdbObject *self)
444 {
445         if (tdb_get_flags(self->ctx) & TDB_INTERNAL) {
446                 return PyString_FromString("Tdb(<internal>)");
447         } else {
448                 return PyString_FromFormat("Tdb('%s')", tdb_name(self->ctx));
449         }
450 }
451
452 static void tdb_object_dealloc(PyTdbObject *self)
453 {
454         if (!self->closed)
455                 tdb_close(self->ctx);
456         self->ob_type->tp_free(self);
457 }
458
459 static PyObject *obj_getitem(PyTdbObject *self, PyObject *key)
460 {
461         TDB_DATA tkey, val;
462         enum TDB_ERROR ret;
463
464         if (!PyString_Check(key)) {
465                 PyErr_SetString(PyExc_TypeError, "Expected string as key");
466                 return NULL;
467         }
468
469         tkey.dptr = (unsigned char *)PyString_AsString(key);
470         tkey.dsize = PyString_Size(key);
471
472         ret = tdb_fetch(self->ctx, tkey, &val);
473         if (ret == TDB_ERR_NOEXIST) {
474                 PyErr_SetString(PyExc_KeyError, "No such TDB entry");
475                 return NULL;
476         } else {
477                 PyErr_TDB_ERROR_IS_ERR_RAISE(ret);
478                 return PyString_FromTDB_DATA(val);
479         }
480 }
481
482 static int obj_setitem(PyTdbObject *self, PyObject *key, PyObject *value)
483 {
484         TDB_DATA tkey, tval;
485         enum TDB_ERROR ret;
486         if (!PyString_Check(key)) {
487                 PyErr_SetString(PyExc_TypeError, "Expected string as key");
488                 return -1;
489         }
490
491         tkey = PyString_AsTDB_DATA(key);
492
493         if (value == NULL) {
494                 ret = tdb_delete(self->ctx, tkey);
495         } else {
496                 if (!PyString_Check(value)) {
497                         PyErr_SetString(PyExc_TypeError, "Expected string as value");
498                         return -1;
499                 }
500
501                 tval = PyString_AsTDB_DATA(value);
502
503                 ret = tdb_store(self->ctx, tkey, tval, TDB_REPLACE);
504         }
505
506         if (ret != TDB_SUCCESS) {
507                 PyErr_SetTDBError(ret);
508                 return -1;
509         }
510
511         return ret;
512 }
513
514 static PyMappingMethods tdb_object_mapping = {
515         .mp_subscript = (binaryfunc)obj_getitem,
516         .mp_ass_subscript = (objobjargproc)obj_setitem,
517 };
518 static PyTypeObject PyTdb = {
519         .tp_name = "Tdb",
520         .tp_basicsize = sizeof(PyTdbObject),
521         .tp_methods = tdb_object_methods,
522         .tp_getset = tdb_object_getsetters,
523         .tp_new = py_tdb_open,
524         .tp_doc = "A TDB file",
525         .tp_repr = (reprfunc)tdb_object_repr,
526         .tp_dealloc = (destructor)tdb_object_dealloc,
527         .tp_as_mapping = &tdb_object_mapping,
528         .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_ITER,
529         .tp_iter = (getiterfunc)tdb_object_iter,
530 };
531
532 static PyMethodDef tdb_methods[] = {
533         { "open", (PyCFunction)py_tdb_open, METH_VARARGS|METH_KEYWORDS, "open(name, hash_size=0, tdb_flags=TDB_DEFAULT, flags=O_RDWR, mode=0600)\n"
534                 "Open a TDB file." },
535         { NULL }
536 };
537
538 void inittdb(void);
539 void inittdb(void)
540 {
541         PyObject *m;
542
543         if (PyType_Ready(&PyTdb) < 0)
544                 return;
545
546         if (PyType_Ready(&PyTdbIterator) < 0)
547                 return;
548
549         m = Py_InitModule3("tdb", tdb_methods, "TDB is a simple key-value database similar to GDBM that supports multiple writers.");
550         if (m == NULL)
551                 return;
552
553         PyModule_AddObject(m, "REPLACE", PyInt_FromLong(TDB_REPLACE));
554         PyModule_AddObject(m, "INSERT", PyInt_FromLong(TDB_INSERT));
555         PyModule_AddObject(m, "MODIFY", PyInt_FromLong(TDB_MODIFY));
556
557         PyModule_AddObject(m, "DEFAULT", PyInt_FromLong(TDB_DEFAULT));
558         PyModule_AddObject(m, "INTERNAL", PyInt_FromLong(TDB_INTERNAL));
559         PyModule_AddObject(m, "NOLOCK", PyInt_FromLong(TDB_NOLOCK));
560         PyModule_AddObject(m, "NOMMAP", PyInt_FromLong(TDB_NOMMAP));
561         PyModule_AddObject(m, "CONVERT", PyInt_FromLong(TDB_CONVERT));
562         PyModule_AddObject(m, "NOSYNC", PyInt_FromLong(TDB_NOSYNC));
563         PyModule_AddObject(m, "SEQNUM", PyInt_FromLong(TDB_SEQNUM));
564         PyModule_AddObject(m, "ALLOW_NESTING", PyInt_FromLong(TDB_ALLOW_NESTING));
565
566         PyModule_AddObject(m, "__docformat__", PyString_FromString("restructuredText"));
567
568         PyModule_AddObject(m, "__version__", PyString_FromString(PACKAGE_VERSION));
569
570         Py_INCREF(&PyTdb);
571         PyModule_AddObject(m, "Tdb", (PyObject *)&PyTdb);
572
573         Py_INCREF(&PyTdbIterator);
574 }