r19831: Big ldb_dn optimization and interfaces enhancement patch
[samba.git] / source4 / lib / ldb / ldb_tdb / ldb_tdb.c
1 /* 
2    ldb database library
3
4    Copyright (C) Andrew Tridgell  2004
5    Copyright (C) Stefan Metzmacher  2004
6    Copyright (C) Simo Sorce       2006
7    
8
9      ** NOTE! The following LGPL license applies to the ldb
10      ** library. This does NOT imply that all of Samba is released
11      ** under the LGPL
12    
13    This library is free software; you can redistribute it and/or
14    modify it under the terms of the GNU Lesser General Public
15    License as published by the Free Software Foundation; either
16    version 2 of the License, or (at your option) any later version.
17
18    This library is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21    Lesser General Public License for more details.
22
23    You should have received a copy of the GNU Lesser General Public
24    License along with this library; if not, write to the Free Software
25    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 */
27
28 /*
29  *  Name: ldb_tdb
30  *
31  *  Component: ldb tdb backend
32  *
33  *  Description: core functions for tdb backend
34  *
35  *  Author: Andrew Tridgell
36  *  Author: Stefan Metzmacher
37  *
38  *  Modifications:
39  *
40  *  - description: make the module use asyncronous calls
41  *    date: Feb 2006
42  *    Author: Simo Sorce
43  */
44
45 #include "includes.h"
46 #include "ldb/include/includes.h"
47
48 #include "ldb/ldb_tdb/ldb_tdb.h"
49
50
51 /*
52   map a tdb error code to a ldb error code
53 */
54 static int ltdb_err_map(enum TDB_ERROR tdb_code)
55 {
56         switch (tdb_code) {
57         case TDB_SUCCESS:
58                 return LDB_SUCCESS;
59         case TDB_ERR_CORRUPT:
60         case TDB_ERR_OOM:
61         case TDB_ERR_EINVAL:
62                 return LDB_ERR_OPERATIONS_ERROR;
63         case TDB_ERR_IO:
64                 return LDB_ERR_PROTOCOL_ERROR;
65         case TDB_ERR_LOCK:
66         case TDB_ERR_NOLOCK:
67                 return LDB_ERR_BUSY;
68         case TDB_ERR_LOCK_TIMEOUT:
69                 return LDB_ERR_TIME_LIMIT_EXCEEDED;
70         case TDB_ERR_EXISTS:
71                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
72         case TDB_ERR_NOEXIST:
73                 return LDB_ERR_NO_SUCH_OBJECT;
74         case TDB_ERR_RDONLY:
75                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
76         }
77         return LDB_ERR_OTHER;
78 }
79
80
81 struct ldb_handle *init_ltdb_handle(struct ltdb_private *ltdb, struct ldb_module *module,
82                                     struct ldb_request *req)
83 {
84         struct ltdb_context *ac;
85         struct ldb_handle *h;
86
87         h = talloc_zero(req, struct ldb_handle);
88         if (h == NULL) {
89                 ldb_set_errstring(module->ldb, "Out of Memory");
90                 return NULL;
91         }
92
93         h->module = module;
94
95         ac = talloc_zero(h, struct ltdb_context);
96         if (ac == NULL) {
97                 ldb_set_errstring(module->ldb, "Out of Memory");
98                 talloc_free(h);
99                 return NULL;
100         }
101
102         h->private_data = (void *)ac;
103
104         h->state = LDB_ASYNC_INIT;
105         h->status = LDB_SUCCESS;
106
107         ac->module = module;
108         ac->context = req->context;
109         ac->callback = req->callback;
110
111         return h;
112 }
113
114 /*
115   form a TDB_DATA for a record key
116   caller frees
117
118   note that the key for a record can depend on whether the 
119   dn refers to a case sensitive index record or not
120 */
121 struct TDB_DATA ltdb_key(struct ldb_module *module, struct ldb_dn *dn)
122 {
123         struct ldb_context *ldb = module->ldb;
124         TDB_DATA key;
125         char *key_str = NULL;
126         char *dn_folded = NULL;
127
128         /*
129           most DNs are case insensitive. The exception is index DNs for
130           case sensitive attributes
131
132           there are 3 cases dealt with in this code:
133
134           1) if the dn doesn't start with @ then uppercase the attribute
135              names and the attributes values of case insensitive attributes
136           2) if the dn starts with @ then leave it alone - the indexing code handles
137              the rest
138         */
139
140         dn_folded = ldb_dn_get_casefold(dn);
141         if (!dn_folded) {
142                 goto failed;
143         }
144
145         key_str = talloc_asprintf(ldb, "DN=%s", dn_folded);
146
147         if (!key_str) {
148                 goto failed;
149         }
150
151         key.dptr = (uint8_t *)key_str;
152         key.dsize = strlen(key_str) + 1;
153
154         return key;
155
156 failed:
157         errno = ENOMEM;
158         key.dptr = NULL;
159         key.dsize = 0;
160         return key;
161 }
162
163 /*
164   check special dn's have valid attributes
165   currently only @ATTRIBUTES is checked
166 */
167 int ltdb_check_special_dn(struct ldb_module *module, const struct ldb_message *msg)
168 {
169         int i, j;
170  
171         if (! ldb_dn_is_special(msg->dn) ||
172             ! ldb_dn_check_special(msg->dn, LTDB_ATTRIBUTES)) {
173                 return 0;
174         }
175
176         /* we have @ATTRIBUTES, let's check attributes are fine */
177         /* should we check that we deny multivalued attributes ? */
178         for (i = 0; i < msg->num_elements; i++) {
179                 for (j = 0; j < msg->elements[i].num_values; j++) {
180                         if (ltdb_check_at_attributes_values(&msg->elements[i].values[j]) != 0) {
181                                 ldb_set_errstring(module->ldb, "Invalid attribute value in an @ATTRIBUTES entry");
182                                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
183                         }
184                 }
185         }
186
187         return 0;
188 }
189
190
191 /*
192   we've made a modification to a dn - possibly reindex and 
193   update sequence number
194 */
195 static int ltdb_modified(struct ldb_module *module, struct ldb_dn *dn)
196 {
197         int ret = 0;
198
199         if (ldb_dn_is_special(dn) &&
200             (ldb_dn_check_special(dn, LTDB_INDEXLIST) ||
201              ldb_dn_check_special(dn, LTDB_ATTRIBUTES)) ) {
202                 ret = ltdb_reindex(module);
203         }
204
205         if (ret == 0 &&
206             !(ldb_dn_is_special(dn) &&
207               ldb_dn_check_special(dn, LTDB_BASEINFO)) ) {
208                 ret = ltdb_increase_sequence_number(module);
209         }
210
211         return ret;
212 }
213
214 /*
215   store a record into the db
216 */
217 int ltdb_store(struct ldb_module *module, const struct ldb_message *msg, int flgs)
218 {
219         struct ltdb_private *ltdb =
220                 talloc_get_type(module->private_data, struct ltdb_private);
221         TDB_DATA tdb_key, tdb_data;
222         int ret;
223
224         tdb_key = ltdb_key(module, msg->dn);
225         if (!tdb_key.dptr) {
226                 return LDB_ERR_OTHER;
227         }
228
229         ret = ltdb_pack_data(module, msg, &tdb_data);
230         if (ret == -1) {
231                 talloc_free(tdb_key.dptr);
232                 return LDB_ERR_OTHER;
233         }
234
235         ret = tdb_store(ltdb->tdb, tdb_key, tdb_data, flgs);
236         if (ret == -1) {
237                 ret = ltdb_err_map(tdb_error(ltdb->tdb));
238                 goto done;
239         }
240         
241         ret = ltdb_index_add(module, msg);
242         if (ret == -1) {
243                 tdb_delete(ltdb->tdb, tdb_key);
244         }
245
246 done:
247         talloc_free(tdb_key.dptr);
248         talloc_free(tdb_data.dptr);
249
250         return ret;
251 }
252
253
254 static int ltdb_add_internal(struct ldb_module *module, const struct ldb_message *msg)
255 {
256         int ret;
257         
258         ret = ltdb_check_special_dn(module, msg);
259         if (ret != LDB_SUCCESS) {
260                 return ret;
261         }
262         
263         if (ltdb_cache_load(module) != 0) {
264                 return LDB_ERR_OPERATIONS_ERROR;
265         }
266
267         ret = ltdb_store(module, msg, TDB_INSERT);
268
269         if (ret == LDB_ERR_ENTRY_ALREADY_EXISTS) {
270                 char *dn;
271
272                 dn = ldb_dn_linearize(module, msg->dn);
273                 if (!dn) {
274                         return ret;
275                 }
276                 ldb_asprintf_errstring(module->ldb, "Entry %s already exists", dn);
277                 talloc_free(dn);
278                 return ret;
279         }
280         
281         if (ret == LDB_SUCCESS) {
282                 ret = ltdb_modified(module, msg->dn);
283                 if (ret != LDB_SUCCESS) {
284                         return LDB_ERR_OPERATIONS_ERROR;
285                 }
286         }
287
288         return ret;
289 }
290
291 /*
292   add a record to the database
293 */
294 static int ltdb_add(struct ldb_module *module, struct ldb_request *req)
295 {
296         struct ltdb_private *ltdb = talloc_get_type(module->private_data, struct ltdb_private);
297         struct ltdb_context *ltdb_ac;
298         int tret, ret = LDB_SUCCESS;
299
300         if (req->controls != NULL) {
301                 ldb_debug(module->ldb, LDB_DEBUG_WARNING, "Controls should not reach the ldb_tdb backend!\n");
302                 if (check_critical_controls(req->controls)) {
303                         return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
304                 }
305         }
306         
307         req->handle = init_ltdb_handle(ltdb, module, req);
308         if (req->handle == NULL) {
309                 return LDB_ERR_OPERATIONS_ERROR;
310         }
311         ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
312
313         tret = ltdb_add_internal(module, req->op.add.message);
314         if (tret != LDB_SUCCESS) {
315                 req->handle->status = tret;
316                 goto done;
317         }
318         
319         if (ltdb_ac->callback) {
320                 ret = ltdb_ac->callback(module->ldb, ltdb_ac->context, NULL);
321         }
322 done:
323         req->handle->state = LDB_ASYNC_DONE;
324         return ret;
325 }
326
327 /*
328   delete a record from the database, not updating indexes (used for deleting
329   index records)
330 */
331 int ltdb_delete_noindex(struct ldb_module *module, struct ldb_dn *dn)
332 {
333         struct ltdb_private *ltdb =
334                 talloc_get_type(module->private_data, struct ltdb_private);
335         TDB_DATA tdb_key;
336         int ret;
337
338         tdb_key = ltdb_key(module, dn);
339         if (!tdb_key.dptr) {
340                 return LDB_ERR_OTHER;
341         }
342
343         ret = tdb_delete(ltdb->tdb, tdb_key);
344         talloc_free(tdb_key.dptr);
345
346         if (ret != 0) {
347                 ret = ltdb_err_map(tdb_error(ltdb->tdb));
348         }
349
350         return ret;
351 }
352
353 static int ltdb_delete_internal(struct ldb_module *module, struct ldb_dn *dn)
354 {
355         struct ldb_message *msg;
356         int ret;
357
358         msg = talloc(module, struct ldb_message);
359         if (msg == NULL) {
360                 return LDB_ERR_OPERATIONS_ERROR;
361         }
362
363         /* in case any attribute of the message was indexed, we need
364            to fetch the old record */
365         ret = ltdb_search_dn1(module, dn, msg);
366         if (ret != 1) {
367                 /* not finding the old record is an error */
368                 talloc_free(msg);
369                 return LDB_ERR_NO_SUCH_OBJECT;
370         }
371
372         ret = ltdb_delete_noindex(module, dn);
373         if (ret != LDB_SUCCESS) {
374                 talloc_free(msg);
375                 return LDB_ERR_NO_SUCH_OBJECT;
376         }
377
378         /* remove any indexed attributes */
379         ret = ltdb_index_del(module, msg);
380         if (ret != LDB_SUCCESS) {
381                 talloc_free(msg);
382                 return LDB_ERR_OPERATIONS_ERROR;
383         }
384
385         ret = ltdb_modified(module, dn);
386         if (ret != LDB_SUCCESS) {
387                 talloc_free(msg);
388                 return LDB_ERR_OPERATIONS_ERROR;
389         }
390
391         talloc_free(msg);
392         return LDB_SUCCESS;
393 }
394
395 /*
396   delete a record from the database
397 */
398 static int ltdb_delete(struct ldb_module *module, struct ldb_request *req)
399 {
400         struct ltdb_private *ltdb = talloc_get_type(module->private_data, struct ltdb_private);
401         struct ltdb_context *ltdb_ac;
402         int tret, ret = LDB_SUCCESS;
403
404         if (req->controls != NULL) {
405                 ldb_debug(module->ldb, LDB_DEBUG_WARNING, "Controls should not reach the ldb_tdb backend!\n");
406                 if (check_critical_controls(req->controls)) {
407                         return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
408                 }
409         }
410         
411         req->handle = NULL;
412
413         if (ltdb_cache_load(module) != 0) {
414                 return LDB_ERR_OPERATIONS_ERROR;
415         }
416
417         req->handle = init_ltdb_handle(ltdb, module, req);
418         if (req->handle == NULL) {
419                 return LDB_ERR_OPERATIONS_ERROR;
420         }
421         ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
422
423         tret = ltdb_delete_internal(module, req->op.del.dn);
424         if (tret != LDB_SUCCESS) {
425                 req->handle->status = tret; 
426                 goto done;
427         }
428
429         if (ltdb_ac->callback) {
430                 ret = ltdb_ac->callback(module->ldb, ltdb_ac->context, NULL);
431         }
432 done:
433         req->handle->state = LDB_ASYNC_DONE;
434         return ret;
435 }
436
437 /*
438   find an element by attribute name. At the moment this does a linear search, it should
439   be re-coded to use a binary search once all places that modify records guarantee
440   sorted order
441
442   return the index of the first matching element if found, otherwise -1
443 */
444 static int find_element(const struct ldb_message *msg, const char *name)
445 {
446         unsigned int i;
447         for (i=0;i<msg->num_elements;i++) {
448                 if (ldb_attr_cmp(msg->elements[i].name, name) == 0) {
449                         return i;
450                 }
451         }
452         return -1;
453 }
454
455
456 /*
457   add an element to an existing record. Assumes a elements array that we
458   can call re-alloc on, and assumed that we can re-use the data pointers from the 
459   passed in additional values. Use with care!
460
461   returns 0 on success, -1 on failure (and sets errno)
462 */
463 static int msg_add_element(struct ldb_context *ldb,
464                            struct ldb_message *msg, struct ldb_message_element *el)
465 {
466         struct ldb_message_element *e2;
467         unsigned int i;
468
469         e2 = talloc_realloc(msg, msg->elements, struct ldb_message_element, 
470                               msg->num_elements+1);
471         if (!e2) {
472                 errno = ENOMEM;
473                 return -1;
474         }
475
476         msg->elements = e2;
477
478         e2 = &msg->elements[msg->num_elements];
479
480         e2->name = el->name;
481         e2->flags = el->flags;
482         e2->values = NULL;
483         if (el->num_values != 0) {
484                 e2->values = talloc_array(msg->elements, struct ldb_val, el->num_values);
485                 if (!e2->values) {
486                         errno = ENOMEM;
487                         return -1;
488                 }
489         }
490         for (i=0;i<el->num_values;i++) {
491                 e2->values[i] = el->values[i];
492         }
493         e2->num_values = el->num_values;
494
495         msg->num_elements++;
496
497         return 0;
498 }
499
500 /*
501   delete all elements having a specified attribute name
502 */
503 static int msg_delete_attribute(struct ldb_module *module,
504                                 struct ldb_context *ldb,
505                                 struct ldb_message *msg, const char *name)
506 {
507         char *dn;
508         unsigned int i, j;
509
510         dn = ldb_dn_linearize(ldb, msg->dn);
511         if (dn == NULL) {
512                 return -1;
513         }
514
515         for (i=0;i<msg->num_elements;i++) {
516                 if (ldb_attr_cmp(msg->elements[i].name, name) == 0) {
517                         for (j=0;j<msg->elements[i].num_values;j++) {
518                                 ltdb_index_del_value(module, dn, &msg->elements[i], j);
519                         }
520                         talloc_free(msg->elements[i].values);
521                         if (msg->num_elements > (i+1)) {
522                                 memmove(&msg->elements[i], 
523                                         &msg->elements[i+1], 
524                                         sizeof(struct ldb_message_element)*
525                                         (msg->num_elements - (i+1)));
526                         }
527                         msg->num_elements--;
528                         i--;
529                         msg->elements = talloc_realloc(msg, msg->elements, 
530                                                          struct ldb_message_element, 
531                                                          msg->num_elements);
532                 }
533         }
534
535         talloc_free(dn);
536         return 0;
537 }
538
539 /*
540   delete all elements matching an attribute name/value 
541
542   return 0 on success, -1 on failure
543 */
544 static int msg_delete_element(struct ldb_module *module,
545                               struct ldb_message *msg, 
546                               const char *name,
547                               const struct ldb_val *val)
548 {
549         struct ldb_context *ldb = module->ldb;
550         unsigned int i;
551         int found;
552         struct ldb_message_element *el;
553         const struct ldb_attrib_handler *h;
554
555         found = find_element(msg, name);
556         if (found == -1) {
557                 return -1;
558         }
559
560         el = &msg->elements[found];
561
562         h = ldb_attrib_handler(ldb, el->name);
563
564         for (i=0;i<el->num_values;i++) {
565                 if (h->comparison_fn(ldb, ldb, &el->values[i], val) == 0) {
566                         if (i<el->num_values-1) {
567                                 memmove(&el->values[i], &el->values[i+1],
568                                         sizeof(el->values[i])*(el->num_values-(i+1)));
569                         }
570                         el->num_values--;
571                         if (el->num_values == 0) {
572                                 return msg_delete_attribute(module, ldb, msg, name);
573                         }
574                         return 0;
575                 }
576         }
577
578         return -1;
579 }
580
581
582 /*
583   modify a record - internal interface
584
585   yuck - this is O(n^2). Luckily n is usually small so we probably
586   get away with it, but if we ever have really large attribute lists 
587   then we'll need to look at this again
588 */
589 int ltdb_modify_internal(struct ldb_module *module, const struct ldb_message *msg)
590 {
591         struct ldb_context *ldb = module->ldb;
592         struct ltdb_private *ltdb =
593                 talloc_get_type(module->private_data, struct ltdb_private);
594         TDB_DATA tdb_key, tdb_data;
595         struct ldb_message *msg2;
596         unsigned i, j;
597         int ret;
598
599         tdb_key = ltdb_key(module, msg->dn);
600         if (!tdb_key.dptr) {
601                 return LDB_ERR_OTHER;
602         }
603
604         tdb_data = tdb_fetch(ltdb->tdb, tdb_key);
605         if (!tdb_data.dptr) {
606                 talloc_free(tdb_key.dptr);
607                 return ltdb_err_map(tdb_error(ltdb->tdb));
608         }
609
610         msg2 = talloc(tdb_key.dptr, struct ldb_message);
611         if (msg2 == NULL) {
612                 talloc_free(tdb_key.dptr);
613                 return LDB_ERR_OTHER;
614         }
615
616         ret = ltdb_unpack_data(module, &tdb_data, msg2);
617         if (ret == -1) {
618                 ret = LDB_ERR_OTHER;
619                 goto failed;
620         }
621
622         if (!msg2->dn) {
623                 msg2->dn = msg->dn;
624         }
625
626         for (i=0;i<msg->num_elements;i++) {
627                 struct ldb_message_element *el = &msg->elements[i];
628                 struct ldb_message_element *el2;
629                 struct ldb_val *vals;
630                 char *dn;
631
632                 switch (msg->elements[i].flags & LDB_FLAG_MOD_MASK) {
633
634                 case LDB_FLAG_MOD_ADD:
635                         /* add this element to the message. fail if it
636                            already exists */
637                         ret = find_element(msg2, el->name);
638
639                         if (ret == -1) {
640                                 if (msg_add_element(ldb, msg2, el) != 0) {
641                                         ret = LDB_ERR_OTHER;
642                                         goto failed;
643                                 }
644                                 continue;
645                         }
646
647                         el2 = &msg2->elements[ret];
648
649                         /* An attribute with this name already exists, add all
650                          * values if they don't already exist. */
651
652                         for (j=0;j<el->num_values;j++) {
653                                 if (ldb_msg_find_val(el2, &el->values[j])) {
654                                         ldb_set_errstring(module->ldb, "Type or value exists");
655                                         ret = LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
656                                         goto failed;
657                                 }
658                         }
659
660                         vals = talloc_realloc(msg2->elements, el2->values, struct ldb_val,
661                                                 el2->num_values + el->num_values);
662
663                         if (vals == NULL) {
664                                 ret = LDB_ERR_OTHER;
665                                 goto failed;
666                         }
667
668                         for (j=0;j<el->num_values;j++) {
669                                 vals[el2->num_values + j] =
670                                         ldb_val_dup(vals, &el->values[j]);
671                         }
672
673                         el2->values = vals;
674                         el2->num_values += el->num_values;
675
676                         break;
677
678                 case LDB_FLAG_MOD_REPLACE:
679                         /* replace all elements of this attribute name with the elements
680                            listed. The attribute not existing is not an error */
681                         msg_delete_attribute(module, ldb, msg2, msg->elements[i].name);
682
683                         /* add the replacement element, if not empty */
684                         if (msg->elements[i].num_values != 0 &&
685                             msg_add_element(ldb, msg2, &msg->elements[i]) != 0) {
686                                 ret = LDB_ERR_OTHER;
687                                 goto failed;
688                         }
689                         break;
690
691                 case LDB_FLAG_MOD_DELETE:
692
693                         dn = ldb_dn_linearize(msg2, msg->dn);
694                         if (dn == NULL) {
695                                 ret = LDB_ERR_OTHER;
696                                 goto failed;
697                         }
698
699                         /* we could be being asked to delete all
700                            values or just some values */
701                         if (msg->elements[i].num_values == 0) {
702                                 if (msg_delete_attribute(module, ldb, msg2, 
703                                                          msg->elements[i].name) != 0) {
704                                         ldb_asprintf_errstring(module->ldb, "No such attribute: %s for delete on %s", msg->elements[i].name, dn);
705                                         ret = LDB_ERR_NO_SUCH_ATTRIBUTE;
706                                         goto failed;
707                                 }
708                                 break;
709                         }
710                         for (j=0;j<msg->elements[i].num_values;j++) {
711                                 if (msg_delete_element(module,
712                                                        msg2, 
713                                                        msg->elements[i].name,
714                                                        &msg->elements[i].values[j]) != 0) {
715                                         ldb_asprintf_errstring(module->ldb, "No matching attribute value when deleting attribute: %s on %s", msg->elements[i].name, dn);
716                                         ret = LDB_ERR_NO_SUCH_ATTRIBUTE;
717                                         goto failed;
718                                 }
719                                 if (ltdb_index_del_value(module, dn, &msg->elements[i], j) != 0) {
720                                         ret = LDB_ERR_OTHER;
721                                         goto failed;
722                                 }
723                         }
724                         break;
725                 default:
726                         ldb_asprintf_errstring(module->ldb, "Invalid ldb_modify flags on %s: 0x%x", 
727                                                              msg->elements[i].name, 
728                                                              msg->elements[i].flags & LDB_FLAG_MOD_MASK);
729                         ret = LDB_ERR_PROTOCOL_ERROR;
730                         goto failed;
731                 }
732         }
733
734         /* we've made all the mods - save the modified record back into the database */
735         ret = ltdb_store(module, msg2, TDB_MODIFY);
736         if (ret != LDB_SUCCESS) {
737                 goto failed;
738         }
739
740         if (ltdb_modified(module, msg->dn) != LDB_SUCCESS) {
741                 ret = LDB_ERR_OPERATIONS_ERROR;
742                 goto failed;
743         }
744
745         talloc_free(tdb_key.dptr);
746         free(tdb_data.dptr);
747         return ret;
748
749 failed:
750         talloc_free(tdb_key.dptr);
751         free(tdb_data.dptr);
752         return ret;
753 }
754
755 /*
756   modify a record
757 */
758 static int ltdb_modify(struct ldb_module *module, struct ldb_request *req)
759 {
760         struct ltdb_private *ltdb = talloc_get_type(module->private_data, struct ltdb_private);
761         struct ltdb_context *ltdb_ac;
762         int tret, ret = LDB_SUCCESS;
763
764         if (req->controls != NULL) {
765                 ldb_debug(module->ldb, LDB_DEBUG_WARNING, "Controls should not reach the ldb_tdb backend!\n");
766                 if (check_critical_controls(req->controls)) {
767                         return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
768                 }
769         }
770         
771         req->handle = NULL;
772
773         req->handle = init_ltdb_handle(ltdb, module, req);
774         if (req->handle == NULL) {
775                 return LDB_ERR_OPERATIONS_ERROR;
776         }
777         ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
778
779         tret = ltdb_check_special_dn(module, req->op.mod.message);
780         if (tret != LDB_SUCCESS) {
781                 req->handle->status = tret;
782                 goto done;
783         }
784         
785         if (ltdb_cache_load(module) != 0) {
786                 ret = LDB_ERR_OPERATIONS_ERROR;
787                 goto done;
788         }
789
790         tret = ltdb_modify_internal(module, req->op.mod.message);
791         if (tret != LDB_SUCCESS) {
792                 req->handle->status = tret;
793                 goto done;
794         }
795
796         if (ltdb_ac->callback) {
797                 ret = ltdb_ac->callback(module->ldb, ltdb_ac->context, NULL);
798         }
799 done:
800         req->handle->state = LDB_ASYNC_DONE;
801         return ret;
802 }
803
804 /*
805   rename a record
806 */
807 static int ltdb_rename(struct ldb_module *module, struct ldb_request *req)
808 {
809         struct ltdb_private *ltdb = talloc_get_type(module->private_data, struct ltdb_private);
810         struct ltdb_context *ltdb_ac;
811         struct ldb_message *msg;
812         int tret, ret = LDB_SUCCESS;
813
814         if (req->controls != NULL) {
815                 ldb_debug(module->ldb, LDB_DEBUG_WARNING, "Controls should not reach the ldb_tdb backend!\n");
816                 if (check_critical_controls(req->controls)) {
817                         return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
818                 }
819         }
820         
821         req->handle = NULL;
822
823         if (ltdb_cache_load(module) != 0) {
824                 return LDB_ERR_OPERATIONS_ERROR;
825         }
826
827         req->handle = init_ltdb_handle(ltdb, module, req);
828         if (req->handle == NULL) {
829                 return LDB_ERR_OPERATIONS_ERROR;
830         }
831         ltdb_ac = talloc_get_type(req->handle->private_data, struct ltdb_context);
832
833         msg = talloc(ltdb_ac, struct ldb_message);
834         if (msg == NULL) {
835                 ret = LDB_ERR_OPERATIONS_ERROR;
836                 goto done;
837         }
838
839         /* in case any attribute of the message was indexed, we need
840            to fetch the old record */
841         tret = ltdb_search_dn1(module, req->op.rename.olddn, msg);
842         if (tret != 1) {
843                 /* not finding the old record is an error */
844                 req->handle->status = LDB_ERR_NO_SUCH_OBJECT;
845                 goto done;
846         }
847
848         msg->dn = ldb_dn_copy(msg, req->op.rename.newdn);
849         if (!msg->dn) {
850                 ret = LDB_ERR_OPERATIONS_ERROR;
851                 goto done;
852         }
853
854         tret = ltdb_add_internal(module, msg);
855         if (tret != LDB_SUCCESS) {
856                 ret = LDB_ERR_OPERATIONS_ERROR;
857                 goto done;
858         }
859
860         tret = ltdb_delete_internal(module, req->op.rename.olddn);
861         if (tret != LDB_SUCCESS) {
862                 ltdb_delete_internal(module, req->op.rename.newdn);
863                 ret = LDB_ERR_OPERATIONS_ERROR;
864                 goto done;
865         }
866
867         if (ltdb_ac->callback) {
868                 ret = ltdb_ac->callback(module->ldb, ltdb_ac->context, NULL);
869         }
870 done:
871         req->handle->state = LDB_ASYNC_DONE;
872         return ret;
873 }
874
875 static int ltdb_start_trans(struct ldb_module *module)
876 {
877         struct ltdb_private *ltdb =
878                 talloc_get_type(module->private_data, struct ltdb_private);
879
880         if (tdb_transaction_start(ltdb->tdb) != 0) {
881                 return ltdb_err_map(tdb_error(ltdb->tdb));
882         }
883
884         return LDB_SUCCESS;
885 }
886
887 static int ltdb_end_trans(struct ldb_module *module)
888 {
889         struct ltdb_private *ltdb =
890                 talloc_get_type(module->private_data, struct ltdb_private);
891
892         if (tdb_transaction_commit(ltdb->tdb) != 0) {
893                 return ltdb_err_map(tdb_error(ltdb->tdb));
894         }
895
896         return LDB_SUCCESS;
897 }
898
899 static int ltdb_del_trans(struct ldb_module *module)
900 {
901         struct ltdb_private *ltdb =
902                 talloc_get_type(module->private_data, struct ltdb_private);
903
904         if (tdb_transaction_cancel(ltdb->tdb) != 0) {
905                 return ltdb_err_map(tdb_error(ltdb->tdb));
906         }
907
908         return LDB_SUCCESS;
909 }
910
911 static int ltdb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
912 {
913         return handle->status;
914 }
915
916 static int ltdb_request(struct ldb_module *module, struct ldb_request *req)
917 {
918         /* check for oustanding critical controls and return an error if found */
919         if (req->controls != NULL) {
920                 ldb_debug(module->ldb, LDB_DEBUG_WARNING, "Controls should not reach the ldb_tdb backend!\n");
921                 if (check_critical_controls(req->controls)) {
922                         return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
923                 }
924         }
925         
926         /* search, add, modify, delete, rename are handled by their own, no other op supported */
927         return LDB_ERR_OPERATIONS_ERROR;
928 }
929
930 /*
931   return sequenceNumber from @BASEINFO
932 */
933 static int ltdb_sequence_number(struct ldb_module *module, struct ldb_request *req)
934 {
935         TALLOC_CTX *tmp_ctx = talloc_new(req);
936         struct ldb_message *msg = NULL;
937         struct ldb_dn *dn = ldb_dn_new(tmp_ctx, module->ldb, LTDB_BASEINFO);
938         int tret;
939
940         if (tmp_ctx == NULL) {
941                 talloc_free(tmp_ctx);
942                 return LDB_ERR_OPERATIONS_ERROR;
943         }
944
945         msg = talloc(tmp_ctx, struct ldb_message);
946         if (msg == NULL) {
947                 talloc_free(tmp_ctx);
948                 return LDB_ERR_OPERATIONS_ERROR;
949         }
950
951         req->op.seq_num.flags = 0;
952
953         tret = ltdb_search_dn1(module, dn, msg);
954         if (tret != 1) {
955                 talloc_free(tmp_ctx);
956                 req->op.seq_num.seq_num = 0;
957                 /* zero is as good as anything when we don't know */
958                 return LDB_SUCCESS;
959         }
960
961         switch (req->op.seq_num.type) {
962         case LDB_SEQ_HIGHEST_SEQ:
963                 req->op.seq_num.seq_num = ldb_msg_find_attr_as_uint64(msg, LTDB_SEQUENCE_NUMBER, 0);
964                 break;
965         case LDB_SEQ_NEXT:
966                 req->op.seq_num.seq_num = ldb_msg_find_attr_as_uint64(msg, LTDB_SEQUENCE_NUMBER, 0);
967                 req->op.seq_num.seq_num++;
968                 break;
969         case LDB_SEQ_HIGHEST_TIMESTAMP:
970         {
971                 const char *date = ldb_msg_find_attr_as_string(msg, LTDB_MOD_TIMESTAMP, NULL);
972                 if (date) {
973                         req->op.seq_num.seq_num = ldb_string_to_time(date);
974                 } else {
975                         req->op.seq_num.seq_num = 0;
976                         /* zero is as good as anything when we don't know */
977                 }
978                 break;
979         }
980         }
981         talloc_free(tmp_ctx);
982         return LDB_SUCCESS;
983 }
984
985 static const struct ldb_module_ops ltdb_ops = {
986         .name              = "tdb",
987         .search            = ltdb_search,
988         .add               = ltdb_add,
989         .modify            = ltdb_modify,
990         .del               = ltdb_delete,
991         .rename            = ltdb_rename,
992         .request           = ltdb_request,
993         .start_transaction = ltdb_start_trans,
994         .end_transaction   = ltdb_end_trans,
995         .del_transaction   = ltdb_del_trans,
996         .wait              = ltdb_wait,
997         .sequence_number   = ltdb_sequence_number
998 };
999
1000 /*
1001   connect to the database
1002 */
1003 static int ltdb_connect(struct ldb_context *ldb, const char *url, 
1004                         unsigned int flags, const char *options[],
1005                         struct ldb_module **module)
1006 {
1007         const char *path;
1008         int tdb_flags, open_flags;
1009         struct ltdb_private *ltdb;
1010
1011         /* parse the url */
1012         if (strchr(url, ':')) {
1013                 if (strncmp(url, "tdb://", 6) != 0) {
1014                         ldb_debug(ldb, LDB_DEBUG_ERROR, "Invalid tdb URL '%s'", url);
1015                         return -1;
1016                 }
1017                 path = url+6;
1018         } else {
1019                 path = url;
1020         }
1021
1022         tdb_flags = TDB_DEFAULT | TDB_SEQNUM;
1023
1024         /* check for the 'nosync' option */
1025         if (flags & LDB_FLG_NOSYNC) {
1026                 tdb_flags |= TDB_NOSYNC;
1027         }
1028
1029         if (flags & LDB_FLG_RDONLY) {
1030                 open_flags = O_RDONLY;
1031         } else {
1032                 open_flags = O_CREAT | O_RDWR;
1033         }
1034
1035         ltdb = talloc_zero(ldb, struct ltdb_private);
1036         if (!ltdb) {
1037                 ldb_oom(ldb);
1038                 return -1;
1039         }
1040
1041         /* note that we use quite a large default hash size */
1042         ltdb->tdb = ltdb_wrap_open(ltdb, path, 10000, 
1043                                    tdb_flags, open_flags, 
1044                                    ldb->create_perms, ldb);
1045         if (!ltdb->tdb) {
1046                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Unable to open tdb '%s'\n", path);
1047                 talloc_free(ltdb);
1048                 return -1;
1049         }
1050
1051         ltdb->sequence_number = 0;
1052
1053         *module = talloc(ldb, struct ldb_module);
1054         if (!module) {
1055                 ldb_oom(ldb);
1056                 talloc_free(ltdb);
1057                 return -1;
1058         }
1059         talloc_set_name_const(*module, "ldb_tdb backend");
1060         (*module)->ldb = ldb;
1061         (*module)->prev = (*module)->next = NULL;
1062         (*module)->private_data = ltdb;
1063         (*module)->ops = &ltdb_ops;
1064
1065         if (ltdb_cache_load(*module) != 0) {
1066                 talloc_free(*module);
1067                 talloc_free(ltdb);
1068                 return -1;
1069         }
1070
1071         return 0;
1072 }
1073
1074 int ldb_tdb_init(void)
1075 {
1076         return ldb_register_backend("tdb", ltdb_connect);
1077 }