ldb_tdb: Do not allow a modification of the GUID_index_attribute (objectGUID)
[samba.git] / 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-2008
7    Copyright (C) Matthias Dieter Wallnöfer 2009-2010
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 3 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, see <http://www.gnu.org/licenses/>.
25 */
26
27 /*
28  *  Name: ldb_tdb
29  *
30  *  Component: ldb tdb backend
31  *
32  *  Description: core functions for tdb backend
33  *
34  *  Author: Andrew Tridgell
35  *  Author: Stefan Metzmacher
36  *
37  *  Modifications:
38  *
39  *  - description: make the module use asynchronous calls
40  *    date: Feb 2006
41  *    Author: Simo Sorce
42  *
43  *  - description: make it possible to use event contexts
44  *    date: Jan 2008
45  *    Author: Simo Sorce
46  *
47  *  - description: fix up memory leaks and small bugs
48  *    date: Oct 2009
49  *    Author: Matthias Dieter Wallnöfer
50  */
51
52 #include "ldb_tdb.h"
53 #include "ldb_private.h"
54 #include <tdb.h>
55
56 /*
57   prevent memory errors on callbacks
58 */
59 struct ltdb_req_spy {
60         struct ltdb_context *ctx;
61 };
62
63 /*
64   map a tdb error code to a ldb error code
65 */
66 int ltdb_err_map(enum TDB_ERROR tdb_code)
67 {
68         switch (tdb_code) {
69         case TDB_SUCCESS:
70                 return LDB_SUCCESS;
71         case TDB_ERR_CORRUPT:
72         case TDB_ERR_OOM:
73         case TDB_ERR_EINVAL:
74                 return LDB_ERR_OPERATIONS_ERROR;
75         case TDB_ERR_IO:
76                 return LDB_ERR_PROTOCOL_ERROR;
77         case TDB_ERR_LOCK:
78         case TDB_ERR_NOLOCK:
79                 return LDB_ERR_BUSY;
80         case TDB_ERR_LOCK_TIMEOUT:
81                 return LDB_ERR_TIME_LIMIT_EXCEEDED;
82         case TDB_ERR_EXISTS:
83                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
84         case TDB_ERR_NOEXIST:
85                 return LDB_ERR_NO_SUCH_OBJECT;
86         case TDB_ERR_RDONLY:
87                 return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
88         default:
89                 break;
90         }
91         return LDB_ERR_OTHER;
92 }
93
94 /*
95   lock the database for read - use by ltdb_search and ltdb_sequence_number
96 */
97 int ltdb_lock_read(struct ldb_module *module)
98 {
99         void *data = ldb_module_get_private(module);
100         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
101         int tdb_ret = 0;
102         int ret;
103
104         if (ltdb->in_transaction == 0 &&
105             ltdb->read_lock_count == 0) {
106                 tdb_ret = tdb_lockall_read(ltdb->tdb);
107         }
108         if (tdb_ret == 0) {
109                 ltdb->read_lock_count++;
110                 return LDB_SUCCESS;
111         }
112         ret = ltdb_err_map(tdb_error(ltdb->tdb));
113         if (ret == LDB_SUCCESS) {
114                 ret = LDB_ERR_OPERATIONS_ERROR;
115         }
116         ldb_debug_set(ldb_module_get_ctx(module),
117                       LDB_DEBUG_FATAL,
118                       "Failure during ltdb_lock_read(): %s -> %s",
119                       tdb_errorstr(ltdb->tdb),
120                       ldb_strerror(ret));
121         return ret;
122 }
123
124 /*
125   unlock the database after a ltdb_lock_read()
126 */
127 int ltdb_unlock_read(struct ldb_module *module)
128 {
129         void *data = ldb_module_get_private(module);
130         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
131         if (ltdb->in_transaction == 0 && ltdb->read_lock_count == 1) {
132                 tdb_unlockall_read(ltdb->tdb);
133                 ltdb->read_lock_count--;
134                 return 0;
135         }
136         ltdb->read_lock_count--;
137         return 0;
138 }
139
140
141 /* 
142  * Determine if this key could hold a record.  We allow the new GUID
143  * index, the old DN index and a possible future ID=
144  */
145 bool ltdb_key_is_record(TDB_DATA key)
146 {
147         if (key.dsize < 4) {
148                 return false;
149         }
150
151         if (memcmp(key.dptr, "DN=", 3) == 0) {
152                 return true;
153         }
154         
155         if (memcmp(key.dptr, "ID=", 3) == 0) {
156                 return true;
157         }
158
159         if (key.dsize < 6) {
160                 return false;
161         }
162
163         if (memcmp(key.dptr, "GUID=", 5) == 0) {
164                 return true;
165         }
166         
167         return false;
168 }
169
170 /*
171   form a TDB_DATA for a record key
172   caller frees
173
174   note that the key for a record can depend on whether the
175   dn refers to a case sensitive index record or not
176 */
177 TDB_DATA ltdb_key_dn(struct ldb_module *module, struct ldb_dn *dn)
178 {
179         struct ldb_context *ldb = ldb_module_get_ctx(module);
180         TDB_DATA key;
181         char *key_str = NULL;
182         const char *dn_folded = NULL;
183
184         /*
185           most DNs are case insensitive. The exception is index DNs for
186           case sensitive attributes
187
188           there are 3 cases dealt with in this code:
189
190           1) if the dn doesn't start with @ then uppercase the attribute
191              names and the attributes values of case insensitive attributes
192           2) if the dn starts with @ then leave it alone -
193              the indexing code handles the rest
194         */
195
196         dn_folded = ldb_dn_get_casefold(dn);
197         if (!dn_folded) {
198                 goto failed;
199         }
200
201         key_str = talloc_strdup(ldb, "DN=");
202         if (!key_str) {
203                 goto failed;
204         }
205
206         key_str = talloc_strdup_append_buffer(key_str, dn_folded);
207         if (!key_str) {
208                 goto failed;
209         }
210
211         key.dptr = (uint8_t *)key_str;
212         key.dsize = strlen(key_str) + 1;
213
214         return key;
215
216 failed:
217         errno = ENOMEM;
218         key.dptr = NULL;
219         key.dsize = 0;
220         return key;
221 }
222
223 /*
224   form a TDB_DATA for a record key
225   caller frees
226
227   note that the key for a record can depend on whether the
228   dn refers to a case sensitive index record or not
229 */
230 TDB_DATA ltdb_key_msg(struct ldb_module *module,
231                       const struct ldb_message *msg)
232 {
233         return ltdb_key_dn(module, msg->dn);
234 }
235
236 /*
237   check special dn's have valid attributes
238   currently only @ATTRIBUTES is checked
239 */
240 static int ltdb_check_special_dn(struct ldb_module *module,
241                                  const struct ldb_message *msg)
242 {
243         struct ldb_context *ldb = ldb_module_get_ctx(module);
244         unsigned int i, j;
245
246         if (! ldb_dn_is_special(msg->dn) ||
247             ! ldb_dn_check_special(msg->dn, LTDB_ATTRIBUTES)) {
248                 return LDB_SUCCESS;
249         }
250
251         /* we have @ATTRIBUTES, let's check attributes are fine */
252         /* should we check that we deny multivalued attributes ? */
253         for (i = 0; i < msg->num_elements; i++) {
254                 if (ldb_attr_cmp(msg->elements[i].name, "distinguishedName") == 0) continue;
255
256                 for (j = 0; j < msg->elements[i].num_values; j++) {
257                         if (ltdb_check_at_attributes_values(&msg->elements[i].values[j]) != 0) {
258                                 ldb_set_errstring(ldb, "Invalid attribute value in an @ATTRIBUTES entry");
259                                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
260                         }
261                 }
262         }
263
264         return LDB_SUCCESS;
265 }
266
267
268 /*
269   we've made a modification to a dn - possibly reindex and
270   update sequence number
271 */
272 static int ltdb_modified(struct ldb_module *module, struct ldb_dn *dn)
273 {
274         int ret = LDB_SUCCESS;
275         struct ltdb_private *ltdb = talloc_get_type(ldb_module_get_private(module), struct ltdb_private);
276
277         /* only allow modifies inside a transaction, otherwise the
278          * ldb is unsafe */
279         if (ltdb->in_transaction == 0) {
280                 ldb_set_errstring(ldb_module_get_ctx(module), "ltdb modify without transaction");
281                 return LDB_ERR_OPERATIONS_ERROR;
282         }
283
284         if (ldb_dn_is_special(dn) &&
285             (ldb_dn_check_special(dn, LTDB_INDEXLIST) ||
286              ldb_dn_check_special(dn, LTDB_ATTRIBUTES)) )
287         {
288                 if (ltdb->warn_reindex) {
289                         ldb_debug(ldb_module_get_ctx(module),
290                                 LDB_DEBUG_ERROR, "Reindexing %s due to modification on %s",
291                                 tdb_name(ltdb->tdb), ldb_dn_get_linearized(dn));
292                 }
293                 ret = ltdb_reindex(module);
294         }
295
296         /* If the modify was to a normal record, or any special except @BASEINFO, update the seq number */
297         if (ret == LDB_SUCCESS &&
298             !(ldb_dn_is_special(dn) &&
299               ldb_dn_check_special(dn, LTDB_BASEINFO)) ) {
300                 ret = ltdb_increase_sequence_number(module);
301         }
302
303         /* If the modify was to @OPTIONS, reload the cache */
304         if (ret == LDB_SUCCESS &&
305             ldb_dn_is_special(dn) &&
306             (ldb_dn_check_special(dn, LTDB_OPTIONS)) ) {
307                 ret = ltdb_cache_reload(module);
308         }
309
310         return ret;
311 }
312
313 /*
314   store a record into the db
315 */
316 int ltdb_store(struct ldb_module *module, const struct ldb_message *msg, int flgs)
317 {
318         void *data = ldb_module_get_private(module);
319         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
320         TDB_DATA tdb_key, tdb_data;
321         struct ldb_val ldb_data;
322         int ret = LDB_SUCCESS;
323
324         if (ltdb->read_only) {
325                 return LDB_ERR_UNWILLING_TO_PERFORM;
326         }
327
328         tdb_key = ltdb_key_msg(module, msg);
329         if (tdb_key.dptr == NULL) {
330                 return LDB_ERR_OTHER;
331         }
332
333         ret = ldb_pack_data(ldb_module_get_ctx(module),
334                             msg, &ldb_data);
335         if (ret == -1) {
336                 talloc_free(tdb_key.dptr);
337                 return LDB_ERR_OTHER;
338         }
339
340         tdb_data.dptr = ldb_data.data;
341         tdb_data.dsize = ldb_data.length;
342
343         ret = tdb_store(ltdb->tdb, tdb_key, tdb_data, flgs);
344         if (ret != 0) {
345                 ret = ltdb_err_map(tdb_error(ltdb->tdb));
346                 goto done;
347         }
348
349 done:
350         talloc_free(tdb_key.dptr);
351         talloc_free(ldb_data.data);
352
353         return ret;
354 }
355
356
357 /*
358   check if a attribute is a single valued, for a given element
359  */
360 static bool ldb_tdb_single_valued(const struct ldb_schema_attribute *a,
361                                   struct ldb_message_element *el)
362 {
363         if (!a) return false;
364         if (el != NULL) {
365                 if (el->flags & LDB_FLAG_INTERNAL_FORCE_SINGLE_VALUE_CHECK) {
366                         /* override from a ldb module, for example
367                            used for the description field, which is
368                            marked multi-valued in the schema but which
369                            should not actually accept multiple
370                            values */
371                         return true;
372                 }
373                 if (el->flags & LDB_FLAG_INTERNAL_DISABLE_SINGLE_VALUE_CHECK) {
374                         /* override from a ldb module, for example used for
375                            deleted linked attribute entries */
376                         return false;
377                 }
378         }
379         if (a->flags & LDB_ATTR_FLAG_SINGLE_VALUE) {
380                 return true;
381         }
382         return false;
383 }
384
385 static int ltdb_add_internal(struct ldb_module *module,
386                              struct ltdb_private *ltdb,
387                              const struct ldb_message *msg,
388                              bool check_single_value)
389 {
390         struct ldb_context *ldb = ldb_module_get_ctx(module);
391         int ret = LDB_SUCCESS;
392         unsigned int i;
393
394         for (i=0;i<msg->num_elements;i++) {
395                 struct ldb_message_element *el = &msg->elements[i];
396                 const struct ldb_schema_attribute *a = ldb_schema_attribute_by_name(ldb, el->name);
397
398                 if (el->num_values == 0) {
399                         ldb_asprintf_errstring(ldb, "attribute '%s' on '%s' specified, but with 0 values (illegal)",
400                                                el->name, ldb_dn_get_linearized(msg->dn));
401                         return LDB_ERR_CONSTRAINT_VIOLATION;
402                 }
403                 if (check_single_value &&
404                                 el->num_values > 1 &&
405                                 ldb_tdb_single_valued(a, el)) {
406                         ldb_asprintf_errstring(ldb, "SINGLE-VALUE attribute %s on %s specified more than once",
407                                                el->name, ldb_dn_get_linearized(msg->dn));
408                         return LDB_ERR_CONSTRAINT_VIOLATION;
409                 }
410
411                 /* Do not check "@ATTRIBUTES" for duplicated values */
412                 if (ldb_dn_is_special(msg->dn) &&
413                     ldb_dn_check_special(msg->dn, LTDB_ATTRIBUTES)) {
414                         continue;
415                 }
416
417                 if (check_single_value &&
418                     !(el->flags &
419                       LDB_FLAG_INTERNAL_DISABLE_SINGLE_VALUE_CHECK)) {
420                         struct ldb_val *duplicate = NULL;
421
422                         ret = ldb_msg_find_duplicate_val(ldb, discard_const(msg),
423                                                          el, &duplicate, 0);
424                         if (ret != LDB_SUCCESS) {
425                                 return ret;
426                         }
427                         if (duplicate != NULL) {
428                                 ldb_asprintf_errstring(
429                                         ldb,
430                                         "attribute '%s': value '%.*s' on '%s' "
431                                         "provided more than once in ADD object",
432                                         el->name,
433                                         (int)duplicate->length,
434                                         duplicate->data,
435                                         ldb_dn_get_linearized(msg->dn));
436                                 return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
437                         }
438                 }
439         }
440
441         ret = ltdb_store(module, msg, TDB_INSERT);
442         if (ret != LDB_SUCCESS) {
443                 if (ret == LDB_ERR_ENTRY_ALREADY_EXISTS) {
444                         ldb_asprintf_errstring(ldb,
445                                                "Entry %s already exists",
446                                                ldb_dn_get_linearized(msg->dn));
447                 }
448                 return ret;
449         }
450
451         ret = ltdb_index_add_new(module, ltdb, msg);
452         if (ret != LDB_SUCCESS) {
453                 return ret;
454         }
455
456         ret = ltdb_modified(module, msg->dn);
457
458         return ret;
459 }
460
461 /*
462   add a record to the database
463 */
464 static int ltdb_add(struct ltdb_context *ctx)
465 {
466         struct ldb_module *module = ctx->module;
467         struct ldb_request *req = ctx->req;
468         void *data = ldb_module_get_private(module);
469         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
470         int ret = LDB_SUCCESS;
471
472         ret = ltdb_check_special_dn(module, req->op.add.message);
473         if (ret != LDB_SUCCESS) {
474                 return ret;
475         }
476
477         ldb_request_set_state(req, LDB_ASYNC_PENDING);
478
479         if (ltdb_cache_load(module) != 0) {
480                 return LDB_ERR_OPERATIONS_ERROR;
481         }
482
483         ret = ltdb_add_internal(module, ltdb,
484                                 req->op.add.message, true);
485
486         return ret;
487 }
488
489 /*
490   delete a record from the database, not updating indexes (used for deleting
491   index records)
492 */
493 int ltdb_delete_noindex(struct ldb_module *module, struct ldb_dn *dn)
494 {
495         void *data = ldb_module_get_private(module);
496         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
497         TDB_DATA tdb_key;
498         int ret;
499
500         if (ltdb->read_only) {
501                 return LDB_ERR_UNWILLING_TO_PERFORM;
502         }
503
504         tdb_key = ltdb_key_dn(module, dn);
505         if (!tdb_key.dptr) {
506                 return LDB_ERR_OTHER;
507         }
508
509         ret = tdb_delete(ltdb->tdb, tdb_key);
510         talloc_free(tdb_key.dptr);
511
512         if (ret != 0) {
513                 ret = ltdb_err_map(tdb_error(ltdb->tdb));
514         }
515
516         return ret;
517 }
518
519 static int ltdb_delete_internal(struct ldb_module *module, struct ldb_dn *dn)
520 {
521         struct ldb_message *msg;
522         int ret = LDB_SUCCESS;
523
524         msg = ldb_msg_new(module);
525         if (msg == NULL) {
526                 return LDB_ERR_OPERATIONS_ERROR;
527         }
528
529         /* in case any attribute of the message was indexed, we need
530            to fetch the old record */
531         ret = ltdb_search_dn1(module, dn, msg, LDB_UNPACK_DATA_FLAG_NO_DATA_ALLOC);
532         if (ret != LDB_SUCCESS) {
533                 /* not finding the old record is an error */
534                 goto done;
535         }
536
537         ret = ltdb_delete_noindex(module, dn);
538         if (ret != LDB_SUCCESS) {
539                 goto done;
540         }
541
542         /* remove any indexed attributes */
543         ret = ltdb_index_delete(module, msg);
544         if (ret != LDB_SUCCESS) {
545                 goto done;
546         }
547
548         ret = ltdb_modified(module, dn);
549         if (ret != LDB_SUCCESS) {
550                 goto done;
551         }
552
553 done:
554         talloc_free(msg);
555         return ret;
556 }
557
558 /*
559   delete a record from the database
560 */
561 static int ltdb_delete(struct ltdb_context *ctx)
562 {
563         struct ldb_module *module = ctx->module;
564         struct ldb_request *req = ctx->req;
565         int ret = LDB_SUCCESS;
566
567         ldb_request_set_state(req, LDB_ASYNC_PENDING);
568
569         if (ltdb_cache_load(module) != 0) {
570                 return LDB_ERR_OPERATIONS_ERROR;
571         }
572
573         ret = ltdb_delete_internal(module, req->op.del.dn);
574
575         return ret;
576 }
577
578 /*
579   find an element by attribute name. At the moment this does a linear search,
580   it should be re-coded to use a binary search once all places that modify
581   records guarantee sorted order
582
583   return the index of the first matching element if found, otherwise -1
584 */
585 static int find_element(const struct ldb_message *msg, const char *name)
586 {
587         unsigned int i;
588         for (i=0;i<msg->num_elements;i++) {
589                 if (ldb_attr_cmp(msg->elements[i].name, name) == 0) {
590                         return i;
591                 }
592         }
593         return -1;
594 }
595
596
597 /*
598   add an element to an existing record. Assumes a elements array that we
599   can call re-alloc on, and assumed that we can re-use the data pointers from
600   the passed in additional values. Use with care!
601
602   returns 0 on success, -1 on failure (and sets errno)
603 */
604 static int ltdb_msg_add_element(struct ldb_message *msg,
605                                 struct ldb_message_element *el)
606 {
607         struct ldb_message_element *e2;
608         unsigned int i;
609
610         if (el->num_values == 0) {
611                 /* nothing to do here - we don't add empty elements */
612                 return 0;
613         }
614
615         e2 = talloc_realloc(msg, msg->elements, struct ldb_message_element,
616                               msg->num_elements+1);
617         if (!e2) {
618                 errno = ENOMEM;
619                 return -1;
620         }
621
622         msg->elements = e2;
623
624         e2 = &msg->elements[msg->num_elements];
625
626         e2->name = el->name;
627         e2->flags = el->flags;
628         e2->values = talloc_array(msg->elements,
629                                   struct ldb_val, el->num_values);
630         if (!e2->values) {
631                 errno = ENOMEM;
632                 return -1;
633         }
634         for (i=0;i<el->num_values;i++) {
635                 e2->values[i] = el->values[i];
636         }
637         e2->num_values = el->num_values;
638
639         ++msg->num_elements;
640
641         return 0;
642 }
643
644 /*
645   delete all elements having a specified attribute name
646 */
647 static int msg_delete_attribute(struct ldb_module *module,
648                                 struct ltdb_private *ltdb,
649                                 struct ldb_message *msg, const char *name)
650 {
651         unsigned int i;
652         int ret;
653         struct ldb_message_element *el;
654         bool is_special = ldb_dn_is_special(msg->dn);
655
656         if (!is_special
657             && ltdb->cache->GUID_index_attribute != NULL
658             && ldb_attr_cmp(name, ltdb->cache->GUID_index_attribute) == 0) {
659                 struct ldb_context *ldb = ldb_module_get_ctx(module);
660                 ldb_asprintf_errstring(ldb, "Must not modify GUID "
661                                        "attribute %s (used as DB index)",
662                                        ltdb->cache->GUID_index_attribute);
663                 return LDB_ERR_CONSTRAINT_VIOLATION;
664         }
665
666         el = ldb_msg_find_element(msg, name);
667         if (el == NULL) {
668                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
669         }
670         i = el - msg->elements;
671
672         ret = ltdb_index_del_element(module, ltdb, msg->dn, el);
673         if (ret != LDB_SUCCESS) {
674                 return ret;
675         }
676
677         talloc_free(el->values);
678         if (msg->num_elements > (i+1)) {
679                 memmove(el, el+1, sizeof(*el) * (msg->num_elements - (i+1)));
680         }
681         msg->num_elements--;
682         msg->elements = talloc_realloc(msg, msg->elements,
683                                        struct ldb_message_element,
684                                        msg->num_elements);
685         return LDB_SUCCESS;
686 }
687
688 /*
689   delete all elements matching an attribute name/value
690
691   return LDB Error on failure
692 */
693 static int msg_delete_element(struct ldb_module *module,
694                               struct ltdb_private *ltdb,
695                               struct ldb_message *msg,
696                               const char *name,
697                               const struct ldb_val *val)
698 {
699         struct ldb_context *ldb = ldb_module_get_ctx(module);
700         unsigned int i;
701         int found, ret;
702         struct ldb_message_element *el;
703         const struct ldb_schema_attribute *a;
704
705         found = find_element(msg, name);
706         if (found == -1) {
707                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
708         }
709
710         i = (unsigned int) found;
711         el = &(msg->elements[i]);
712
713         a = ldb_schema_attribute_by_name(ldb, el->name);
714
715         for (i=0;i<el->num_values;i++) {
716                 bool matched;
717                 if (a->syntax->operator_fn) {
718                         ret = a->syntax->operator_fn(ldb, LDB_OP_EQUALITY, a,
719                                                      &el->values[i], val, &matched);
720                         if (ret != LDB_SUCCESS) return ret;
721                 } else {
722                         matched = (a->syntax->comparison_fn(ldb, ldb,
723                                                             &el->values[i], val) == 0);
724                 }
725                 if (matched) {
726                         if (el->num_values == 1) {
727                                 return msg_delete_attribute(module,
728                                                             ltdb, msg, name);
729                         }
730
731                         ret = ltdb_index_del_value(module, ltdb, msg->dn, el, i);
732                         if (ret != LDB_SUCCESS) {
733                                 return ret;
734                         }
735
736                         if (i<el->num_values-1) {
737                                 memmove(&el->values[i], &el->values[i+1],
738                                         sizeof(el->values[i])*
739                                                 (el->num_values-(i+1)));
740                         }
741                         el->num_values--;
742
743                         /* per definition we find in a canonicalised message an
744                            attribute value only once. So we are finished here */
745                         return LDB_SUCCESS;
746                 }
747         }
748
749         /* Not found */
750         return LDB_ERR_NO_SUCH_ATTRIBUTE;
751 }
752
753
754 /*
755   modify a record - internal interface
756
757   yuck - this is O(n^2). Luckily n is usually small so we probably
758   get away with it, but if we ever have really large attribute lists
759   then we'll need to look at this again
760
761   'req' is optional, and is used to specify controls if supplied
762 */
763 int ltdb_modify_internal(struct ldb_module *module,
764                          const struct ldb_message *msg,
765                          struct ldb_request *req)
766 {
767         struct ldb_context *ldb = ldb_module_get_ctx(module);
768         void *data = ldb_module_get_private(module);
769         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
770         struct ldb_message *msg2;
771         unsigned int i, j;
772         int ret = LDB_SUCCESS, idx;
773         struct ldb_control *control_permissive = NULL;
774         TALLOC_CTX *mem_ctx = talloc_new(req);
775
776         if (mem_ctx == NULL) {
777                 return ldb_module_oom(module);
778         }
779         
780         if (req) {
781                 control_permissive = ldb_request_get_control(req,
782                                         LDB_CONTROL_PERMISSIVE_MODIFY_OID);
783         }
784
785         msg2 = ldb_msg_new(mem_ctx);
786         if (msg2 == NULL) {
787                 ret = LDB_ERR_OTHER;
788                 goto done;
789         }
790
791         ret = ltdb_search_dn1(module, msg->dn,
792                               msg2,
793                               LDB_UNPACK_DATA_FLAG_NO_DATA_ALLOC);
794         if (ret != LDB_SUCCESS) {
795                 goto done;
796         }
797
798         for (i=0; i<msg->num_elements; i++) {
799                 struct ldb_message_element *el = &msg->elements[i], *el2;
800                 struct ldb_val *vals;
801                 const struct ldb_schema_attribute *a = ldb_schema_attribute_by_name(ldb, el->name);
802                 const char *dn;
803                 uint32_t options = 0;
804                 if (control_permissive != NULL) {
805                         options |= LDB_MSG_FIND_COMMON_REMOVE_DUPLICATES;
806                 }
807
808                 switch (msg->elements[i].flags & LDB_FLAG_MOD_MASK) {
809                 case LDB_FLAG_MOD_ADD:
810
811                         if (el->num_values == 0) {
812                                 ldb_asprintf_errstring(ldb,
813                                                        "attribute '%s': attribute on '%s' specified, but with 0 values (illegal)",
814                                                        el->name, ldb_dn_get_linearized(msg2->dn));
815                                 ret = LDB_ERR_CONSTRAINT_VIOLATION;
816                                 goto done;
817                         }
818
819                         /* make a copy of the array so that a permissive
820                          * control can remove duplicates without changing the
821                          * original values, but do not copy data as we do not
822                          * need to keep it around once the operation is
823                          * finished */
824                         if (control_permissive) {
825                                 el = talloc(msg2, struct ldb_message_element);
826                                 if (!el) {
827                                         ret = LDB_ERR_OTHER;
828                                         goto done;
829                                 }
830                                 *el = msg->elements[i];
831                                 el->values = talloc_array(el, struct ldb_val, el->num_values);
832                                 if (el->values == NULL) {
833                                         ret = LDB_ERR_OTHER;
834                                         goto done;
835                                 }
836                                 for (j = 0; j < el->num_values; j++) {
837                                         el->values[j] = msg->elements[i].values[j];
838                                 }
839                         }
840
841                         if (el->num_values > 1 && ldb_tdb_single_valued(a, el)) {
842                                 ldb_asprintf_errstring(ldb, "SINGLE-VALUE attribute %s on %s specified more than once",
843                                                        el->name, ldb_dn_get_linearized(msg2->dn));
844                                 ret = LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
845                                 goto done;
846                         }
847
848                         /* Checks if element already exists */
849                         idx = find_element(msg2, el->name);
850                         if (idx == -1) {
851                                 if (ltdb_msg_add_element(msg2, el) != 0) {
852                                         ret = LDB_ERR_OTHER;
853                                         goto done;
854                                 }
855                                 ret = ltdb_index_add_element(module, ltdb,
856                                                              msg2->dn,
857                                                              el);
858                                 if (ret != LDB_SUCCESS) {
859                                         goto done;
860                                 }
861                         } else {
862                                 j = (unsigned int) idx;
863                                 el2 = &(msg2->elements[j]);
864
865                                 /* We cannot add another value on a existing one
866                                    if the attribute is single-valued */
867                                 if (ldb_tdb_single_valued(a, el)) {
868                                         ldb_asprintf_errstring(ldb, "SINGLE-VALUE attribute %s on %s specified more than once",
869                                                                el->name, ldb_dn_get_linearized(msg2->dn));
870                                         ret = LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
871                                         goto done;
872                                 }
873
874                                 /* Check that values don't exist yet on multi-
875                                    valued attributes or aren't provided twice */
876                                 if (!(el->flags &
877                                       LDB_FLAG_INTERNAL_DISABLE_SINGLE_VALUE_CHECK)) {
878                                         struct ldb_val *duplicate = NULL;
879                                         ret = ldb_msg_find_common_values(ldb,
880                                                                          msg2,
881                                                                          el,
882                                                                          el2,
883                                                                          options);
884
885                                         if (ret ==
886                                             LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS) {
887                                                 ldb_asprintf_errstring(ldb,
888                                                         "attribute '%s': value "
889                                                         "#%u on '%s' already "
890                                                         "exists", el->name, j,
891                                                         ldb_dn_get_linearized(msg2->dn));
892                                                 goto done;
893                                         } else if (ret != LDB_SUCCESS) {
894                                                 goto done;
895                                         }
896
897                                         ret = ldb_msg_find_duplicate_val(
898                                                 ldb, msg2, el, &duplicate, 0);
899                                         if (ret != LDB_SUCCESS) {
900                                                 goto done;
901                                         }
902                                         if (duplicate != NULL) {
903                                                 ldb_asprintf_errstring(
904                                                         ldb,
905                                                         "attribute '%s': value "
906                                                         "'%.*s' on '%s' "
907                                                         "provided more than "
908                                                         "once in ADD",
909                                                         el->name,
910                                                         (int)duplicate->length,
911                                                         duplicate->data,
912                                                         ldb_dn_get_linearized(msg->dn));
913                                                 ret = LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
914                                                 goto done;
915                                         }
916                                 }
917
918                                 /* Now combine existing and new values to a new
919                                    attribute record */
920                                 vals = talloc_realloc(msg2->elements,
921                                                       el2->values, struct ldb_val,
922                                                       el2->num_values + el->num_values);
923                                 if (vals == NULL) {
924                                         ldb_oom(ldb);
925                                         ret = LDB_ERR_OTHER;
926                                         goto done;
927                                 }
928
929                                 for (j=0; j<el->num_values; j++) {
930                                         vals[el2->num_values + j] =
931                                                 ldb_val_dup(vals, &el->values[j]);
932                                 }
933
934                                 el2->values = vals;
935                                 el2->num_values += el->num_values;
936
937                                 ret = ltdb_index_add_element(module, ltdb,
938                                                              msg2->dn, el);
939                                 if (ret != LDB_SUCCESS) {
940                                         goto done;
941                                 }
942                         }
943
944                         break;
945
946                 case LDB_FLAG_MOD_REPLACE:
947
948                         if (el->num_values > 1 && ldb_tdb_single_valued(a, el)) {
949                                 ldb_asprintf_errstring(ldb, "SINGLE-VALUE attribute %s on %s specified more than once",
950                                                        el->name, ldb_dn_get_linearized(msg2->dn));
951                                 ret = LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
952                                 goto done;
953                         }
954
955                         /*
956                          * We don't need to check this if we have been
957                          * pre-screened by the repl_meta_data module
958                          * in Samba, or someone else who can claim to
959                          * know what they are doing. 
960                          */
961                         if (!(el->flags & LDB_FLAG_INTERNAL_DISABLE_SINGLE_VALUE_CHECK)) {
962                                 struct ldb_val *duplicate = NULL;
963
964                                 ret = ldb_msg_find_duplicate_val(ldb, msg2, el,
965                                                                  &duplicate, 0);
966                                 if (ret != LDB_SUCCESS) {
967                                         goto done;
968                                 }
969                                 if (duplicate != NULL) {
970                                         ldb_asprintf_errstring(
971                                                 ldb,
972                                                 "attribute '%s': value '%.*s' "
973                                                 "on '%s' provided more than "
974                                                 "once in REPLACE",
975                                                 el->name,
976                                                 (int)duplicate->length,
977                                                 duplicate->data,
978                                                 ldb_dn_get_linearized(msg2->dn));
979                                         ret = LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
980                                         goto done;
981                                 }
982                         }
983
984                         /* Checks if element already exists */
985                         idx = find_element(msg2, el->name);
986                         if (idx != -1) {
987                                 j = (unsigned int) idx;
988                                 el2 = &(msg2->elements[j]);
989
990                                 /* we consider two elements to be
991                                  * equal only if the order
992                                  * matches. This allows dbcheck to
993                                  * fix the ordering on attributes
994                                  * where order matters, such as
995                                  * objectClass
996                                  */
997                                 if (ldb_msg_element_equal_ordered(el, el2)) {
998                                         continue;
999                                 }
1000
1001                                 /* Delete the attribute if it exists in the DB */
1002                                 if (msg_delete_attribute(module, ltdb,
1003                                                          msg2,
1004                                                          el->name) != 0) {
1005                                         ret = LDB_ERR_OTHER;
1006                                         goto done;
1007                                 }
1008                         }
1009
1010                         /* Recreate it with the new values */
1011                         if (ltdb_msg_add_element(msg2, el) != 0) {
1012                                 ret = LDB_ERR_OTHER;
1013                                 goto done;
1014                         }
1015
1016                         ret = ltdb_index_add_element(module, ltdb,
1017                                                      msg2->dn, el);
1018                         if (ret != LDB_SUCCESS) {
1019                                 goto done;
1020                         }
1021
1022                         break;
1023
1024                 case LDB_FLAG_MOD_DELETE:
1025                         dn = ldb_dn_get_linearized(msg2->dn);
1026                         if (dn == NULL) {
1027                                 ret = LDB_ERR_OTHER;
1028                                 goto done;
1029                         }
1030
1031                         if (msg->elements[i].num_values == 0) {
1032                                 /* Delete the whole attribute */
1033                                 ret = msg_delete_attribute(module,
1034                                                            ltdb,
1035                                                            msg2,
1036                                                            msg->elements[i].name);
1037                                 if (ret == LDB_ERR_NO_SUCH_ATTRIBUTE &&
1038                                     control_permissive) {
1039                                         ret = LDB_SUCCESS;
1040                                 } else {
1041                                         ldb_asprintf_errstring(ldb,
1042                                                                "attribute '%s': no such attribute for delete on '%s'",
1043                                                                msg->elements[i].name, dn);
1044                                 }
1045                                 if (ret != LDB_SUCCESS) {
1046                                         goto done;
1047                                 }
1048                         } else {
1049                                 /* Delete specified values from an attribute */
1050                                 for (j=0; j < msg->elements[i].num_values; j++) {
1051                                         ret = msg_delete_element(module,
1052                                                                  ltdb,
1053                                                                  msg2,
1054                                                                  msg->elements[i].name,
1055                                                                  &msg->elements[i].values[j]);
1056                                         if (ret == LDB_ERR_NO_SUCH_ATTRIBUTE &&
1057                                             control_permissive) {
1058                                                 ret = LDB_SUCCESS;
1059                                         } else if (ret == LDB_ERR_NO_SUCH_ATTRIBUTE) {
1060                                                 ldb_asprintf_errstring(ldb,
1061                                                                        "attribute '%s': no matching attribute value while deleting attribute on '%s'",
1062                                                                        msg->elements[i].name, dn);
1063                                         }
1064                                         if (ret != LDB_SUCCESS) {
1065                                                 goto done;
1066                                         }
1067                                 }
1068                         }
1069                         break;
1070                 default:
1071                         ldb_asprintf_errstring(ldb,
1072                                                "attribute '%s': invalid modify flags on '%s': 0x%x",
1073                                                msg->elements[i].name, ldb_dn_get_linearized(msg->dn),
1074                                                msg->elements[i].flags & LDB_FLAG_MOD_MASK);
1075                         ret = LDB_ERR_PROTOCOL_ERROR;
1076                         goto done;
1077                 }
1078         }
1079
1080         ret = ltdb_store(module, msg2, TDB_MODIFY);
1081         if (ret != LDB_SUCCESS) {
1082                 goto done;
1083         }
1084
1085         ret = ltdb_modified(module, msg2->dn);
1086         if (ret != LDB_SUCCESS) {
1087                 goto done;
1088         }
1089
1090 done:
1091         TALLOC_FREE(mem_ctx);
1092         return ret;
1093 }
1094
1095 /*
1096   modify a record
1097 */
1098 static int ltdb_modify(struct ltdb_context *ctx)
1099 {
1100         struct ldb_module *module = ctx->module;
1101         struct ldb_request *req = ctx->req;
1102         int ret = LDB_SUCCESS;
1103
1104         ret = ltdb_check_special_dn(module, req->op.mod.message);
1105         if (ret != LDB_SUCCESS) {
1106                 return ret;
1107         }
1108
1109         ldb_request_set_state(req, LDB_ASYNC_PENDING);
1110
1111         if (ltdb_cache_load(module) != 0) {
1112                 return LDB_ERR_OPERATIONS_ERROR;
1113         }
1114
1115         ret = ltdb_modify_internal(module, req->op.mod.message, req);
1116
1117         return ret;
1118 }
1119
1120 /*
1121   rename a record
1122 */
1123 static int ltdb_rename(struct ltdb_context *ctx)
1124 {
1125         struct ldb_module *module = ctx->module;
1126         void *data = ldb_module_get_private(module);
1127         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
1128         struct ldb_request *req = ctx->req;
1129         struct ldb_message *msg;
1130         int ret = LDB_SUCCESS;
1131         TDB_DATA tdb_key, tdb_key_old;
1132
1133         ldb_request_set_state(req, LDB_ASYNC_PENDING);
1134
1135         if (ltdb_cache_load(ctx->module) != 0) {
1136                 return LDB_ERR_OPERATIONS_ERROR;
1137         }
1138
1139         msg = ldb_msg_new(ctx);
1140         if (msg == NULL) {
1141                 return LDB_ERR_OPERATIONS_ERROR;
1142         }
1143
1144         /* we need to fetch the old record to re-add under the new name */
1145         ret = ltdb_search_dn1(module, req->op.rename.olddn, msg,
1146                               LDB_UNPACK_DATA_FLAG_NO_DATA_ALLOC);
1147         if (ret != LDB_SUCCESS) {
1148                 /* not finding the old record is an error */
1149                 return ret;
1150         }
1151
1152         /* We need to, before changing the DB, check if the new DN
1153          * exists, so we can return this error to the caller with an
1154          * unmodified DB */
1155         tdb_key = ltdb_key_dn(module, req->op.rename.newdn);
1156         if (!tdb_key.dptr) {
1157                 talloc_free(msg);
1158                 return LDB_ERR_OPERATIONS_ERROR;
1159         }
1160
1161         tdb_key_old = ltdb_key_dn(module, req->op.rename.olddn);
1162         if (!tdb_key_old.dptr) {
1163                 talloc_free(msg);
1164                 talloc_free(tdb_key.dptr);
1165                 return LDB_ERR_OPERATIONS_ERROR;
1166         }
1167
1168         /* Only declare a conflict if the new DN already exists, and it isn't a case change on the old DN */
1169         if (tdb_key_old.dsize != tdb_key.dsize || memcmp(tdb_key.dptr, tdb_key_old.dptr, tdb_key.dsize) != 0) {
1170                 if (tdb_exists(ltdb->tdb, tdb_key)) {
1171                         talloc_free(tdb_key_old.dptr);
1172                         talloc_free(tdb_key.dptr);
1173                         ldb_asprintf_errstring(ldb_module_get_ctx(module),
1174                                                "Entry %s already exists",
1175                                                ldb_dn_get_linearized(req->op.rename.newdn));
1176                         /* finding the new record already in the DB is an error */
1177                         talloc_free(msg);
1178                         return LDB_ERR_ENTRY_ALREADY_EXISTS;
1179                 }
1180         }
1181         talloc_free(tdb_key_old.dptr);
1182         talloc_free(tdb_key.dptr);
1183
1184         /* Always delete first then add, to avoid conflicts with
1185          * unique indexes. We rely on the transaction to make this
1186          * atomic
1187          */
1188         ret = ltdb_delete_internal(module, msg->dn);
1189         if (ret != LDB_SUCCESS) {
1190                 talloc_free(msg);
1191                 return ret;
1192         }
1193
1194         msg->dn = ldb_dn_copy(msg, req->op.rename.newdn);
1195         if (msg->dn == NULL) {
1196                 talloc_free(msg);
1197                 return LDB_ERR_OPERATIONS_ERROR;
1198         }
1199
1200         /* We don't check single value as we can have more than 1 with
1201          * deleted attributes. We could go through all elements but that's
1202          * maybe not the most efficient way
1203          */
1204         ret = ltdb_add_internal(module, ltdb, msg, false);
1205
1206         talloc_free(msg);
1207
1208         return ret;
1209 }
1210
1211 static int ltdb_start_trans(struct ldb_module *module)
1212 {
1213         void *data = ldb_module_get_private(module);
1214         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
1215
1216         /* Do not take out the transaction lock on a read-only DB */
1217         if (ltdb->read_only) {
1218                 return LDB_ERR_UNWILLING_TO_PERFORM;
1219         }
1220
1221         if (tdb_transaction_start(ltdb->tdb) != 0) {
1222                 return ltdb_err_map(tdb_error(ltdb->tdb));
1223         }
1224
1225         ltdb->in_transaction++;
1226
1227         ltdb_index_transaction_start(module);
1228
1229         return LDB_SUCCESS;
1230 }
1231
1232 static int ltdb_prepare_commit(struct ldb_module *module)
1233 {
1234         int ret;
1235         void *data = ldb_module_get_private(module);
1236         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
1237
1238         if (ltdb->in_transaction != 1) {
1239                 return LDB_SUCCESS;
1240         }
1241
1242         ret = ltdb_index_transaction_commit(module);
1243         if (ret != LDB_SUCCESS) {
1244                 tdb_transaction_cancel(ltdb->tdb);
1245                 ltdb->in_transaction--;
1246                 return ret;
1247         }
1248
1249         if (tdb_transaction_prepare_commit(ltdb->tdb) != 0) {
1250                 ret = ltdb_err_map(tdb_error(ltdb->tdb));
1251                 ltdb->in_transaction--;
1252                 ldb_debug_set(ldb_module_get_ctx(module),
1253                               LDB_DEBUG_FATAL,
1254                               "Failure during "
1255                               "tdb_transaction_prepare_commit(): %s -> %s",
1256                               tdb_errorstr(ltdb->tdb),
1257                               ldb_strerror(ret));
1258                 return ret;
1259         }
1260
1261         ltdb->prepared_commit = true;
1262
1263         return LDB_SUCCESS;
1264 }
1265
1266 static int ltdb_end_trans(struct ldb_module *module)
1267 {
1268         int ret;
1269         void *data = ldb_module_get_private(module);
1270         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
1271
1272         if (!ltdb->prepared_commit) {
1273                 ret = ltdb_prepare_commit(module);
1274                 if (ret != LDB_SUCCESS) {
1275                         return ret;
1276                 }
1277         }
1278
1279         ltdb->in_transaction--;
1280         ltdb->prepared_commit = false;
1281
1282         if (tdb_transaction_commit(ltdb->tdb) != 0) {
1283                 ret = ltdb_err_map(tdb_error(ltdb->tdb));
1284                 ldb_asprintf_errstring(ldb_module_get_ctx(module),
1285                                        "Failure during tdb_transaction_commit(): %s -> %s",
1286                                        tdb_errorstr(ltdb->tdb),
1287                                        ldb_strerror(ret));
1288                 return ret;
1289         }
1290
1291         return LDB_SUCCESS;
1292 }
1293
1294 static int ltdb_del_trans(struct ldb_module *module)
1295 {
1296         void *data = ldb_module_get_private(module);
1297         struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
1298
1299         ltdb->in_transaction--;
1300
1301         if (ltdb_index_transaction_cancel(module) != 0) {
1302                 tdb_transaction_cancel(ltdb->tdb);
1303                 return ltdb_err_map(tdb_error(ltdb->tdb));
1304         }
1305
1306         tdb_transaction_cancel(ltdb->tdb);
1307         return LDB_SUCCESS;
1308 }
1309
1310 /*
1311   return sequenceNumber from @BASEINFO
1312 */
1313 static int ltdb_sequence_number(struct ltdb_context *ctx,
1314                                 struct ldb_extended **ext)
1315 {
1316         struct ldb_context *ldb;
1317         struct ldb_module *module = ctx->module;
1318         struct ldb_request *req = ctx->req;
1319         TALLOC_CTX *tmp_ctx = NULL;
1320         struct ldb_seqnum_request *seq;
1321         struct ldb_seqnum_result *res;
1322         struct ldb_message *msg = NULL;
1323         struct ldb_dn *dn;
1324         const char *date;
1325         int ret = LDB_SUCCESS;
1326
1327         ldb = ldb_module_get_ctx(module);
1328
1329         seq = talloc_get_type(req->op.extended.data,
1330                                 struct ldb_seqnum_request);
1331         if (seq == NULL) {
1332                 return LDB_ERR_OPERATIONS_ERROR;
1333         }
1334
1335         ldb_request_set_state(req, LDB_ASYNC_PENDING);
1336
1337         if (ltdb_lock_read(module) != 0) {
1338                 return LDB_ERR_OPERATIONS_ERROR;
1339         }
1340
1341         res = talloc_zero(req, struct ldb_seqnum_result);
1342         if (res == NULL) {
1343                 ret = LDB_ERR_OPERATIONS_ERROR;
1344                 goto done;
1345         }
1346
1347         tmp_ctx = talloc_new(req);
1348         if (tmp_ctx == NULL) {
1349                 ret = LDB_ERR_OPERATIONS_ERROR;
1350                 goto done;
1351         }
1352
1353         dn = ldb_dn_new(tmp_ctx, ldb, LTDB_BASEINFO);
1354         if (dn == NULL) {
1355                 ret = LDB_ERR_OPERATIONS_ERROR;
1356                 goto done;
1357         }
1358
1359         msg = ldb_msg_new(tmp_ctx);
1360         if (msg == NULL) {
1361                 ret = LDB_ERR_OPERATIONS_ERROR;
1362                 goto done;
1363         }
1364
1365         ret = ltdb_search_dn1(module, dn, msg, 0);
1366         if (ret != LDB_SUCCESS) {
1367                 goto done;
1368         }
1369
1370         switch (seq->type) {
1371         case LDB_SEQ_HIGHEST_SEQ:
1372                 res->seq_num = ldb_msg_find_attr_as_uint64(msg, LTDB_SEQUENCE_NUMBER, 0);
1373                 break;
1374         case LDB_SEQ_NEXT:
1375                 res->seq_num = ldb_msg_find_attr_as_uint64(msg, LTDB_SEQUENCE_NUMBER, 0);
1376                 res->seq_num++;
1377                 break;
1378         case LDB_SEQ_HIGHEST_TIMESTAMP:
1379                 date = ldb_msg_find_attr_as_string(msg, LTDB_MOD_TIMESTAMP, NULL);
1380                 if (date) {
1381                         res->seq_num = ldb_string_to_time(date);
1382                 } else {
1383                         res->seq_num = 0;
1384                         /* zero is as good as anything when we don't know */
1385                 }
1386                 break;
1387         }
1388
1389         *ext = talloc_zero(req, struct ldb_extended);
1390         if (*ext == NULL) {
1391                 ret = LDB_ERR_OPERATIONS_ERROR;
1392                 goto done;
1393         }
1394         (*ext)->oid = LDB_EXTENDED_SEQUENCE_NUMBER;
1395         (*ext)->data = talloc_steal(*ext, res);
1396
1397 done:
1398         talloc_free(tmp_ctx);
1399         ltdb_unlock_read(module);
1400         return ret;
1401 }
1402
1403 static void ltdb_request_done(struct ltdb_context *ctx, int error)
1404 {
1405         struct ldb_context *ldb;
1406         struct ldb_request *req;
1407         struct ldb_reply *ares;
1408
1409         ldb = ldb_module_get_ctx(ctx->module);
1410         req = ctx->req;
1411
1412         /* if we already returned an error just return */
1413         if (ldb_request_get_status(req) != LDB_SUCCESS) {
1414                 return;
1415         }
1416
1417         ares = talloc_zero(req, struct ldb_reply);
1418         if (!ares) {
1419                 ldb_oom(ldb);
1420                 req->callback(req, NULL);
1421                 return;
1422         }
1423         ares->type = LDB_REPLY_DONE;
1424         ares->error = error;
1425
1426         req->callback(req, ares);
1427 }
1428
1429 static void ltdb_timeout(struct tevent_context *ev,
1430                           struct tevent_timer *te,
1431                           struct timeval t,
1432                           void *private_data)
1433 {
1434         struct ltdb_context *ctx;
1435         ctx = talloc_get_type(private_data, struct ltdb_context);
1436
1437         if (!ctx->request_terminated) {
1438                 /* request is done now */
1439                 ltdb_request_done(ctx, LDB_ERR_TIME_LIMIT_EXCEEDED);
1440         }
1441
1442         if (ctx->spy) {
1443                 /* neutralize the spy */
1444                 ctx->spy->ctx = NULL;
1445                 ctx->spy = NULL;
1446         }
1447         talloc_free(ctx);
1448 }
1449
1450 static void ltdb_request_extended_done(struct ltdb_context *ctx,
1451                                         struct ldb_extended *ext,
1452                                         int error)
1453 {
1454         struct ldb_context *ldb;
1455         struct ldb_request *req;
1456         struct ldb_reply *ares;
1457
1458         ldb = ldb_module_get_ctx(ctx->module);
1459         req = ctx->req;
1460
1461         /* if we already returned an error just return */
1462         if (ldb_request_get_status(req) != LDB_SUCCESS) {
1463                 return;
1464         }
1465
1466         ares = talloc_zero(req, struct ldb_reply);
1467         if (!ares) {
1468                 ldb_oom(ldb);
1469                 req->callback(req, NULL);
1470                 return;
1471         }
1472         ares->type = LDB_REPLY_DONE;
1473         ares->response = ext;
1474         ares->error = error;
1475
1476         req->callback(req, ares);
1477 }
1478
1479 static void ltdb_handle_extended(struct ltdb_context *ctx)
1480 {
1481         struct ldb_extended *ext = NULL;
1482         int ret;
1483
1484         if (strcmp(ctx->req->op.extended.oid,
1485                    LDB_EXTENDED_SEQUENCE_NUMBER) == 0) {
1486                 /* get sequence number */
1487                 ret = ltdb_sequence_number(ctx, &ext);
1488         } else {
1489                 /* not recognized */
1490                 ret = LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
1491         }
1492
1493         ltdb_request_extended_done(ctx, ext, ret);
1494 }
1495
1496 static void ltdb_callback(struct tevent_context *ev,
1497                           struct tevent_timer *te,
1498                           struct timeval t,
1499                           void *private_data)
1500 {
1501         struct ltdb_context *ctx;
1502         int ret;
1503
1504         ctx = talloc_get_type(private_data, struct ltdb_context);
1505
1506         if (ctx->request_terminated) {
1507                 goto done;
1508         }
1509
1510         switch (ctx->req->operation) {
1511         case LDB_SEARCH:
1512                 ret = ltdb_search(ctx);
1513                 break;
1514         case LDB_ADD:
1515                 ret = ltdb_add(ctx);
1516                 break;
1517         case LDB_MODIFY:
1518                 ret = ltdb_modify(ctx);
1519                 break;
1520         case LDB_DELETE:
1521                 ret = ltdb_delete(ctx);
1522                 break;
1523         case LDB_RENAME:
1524                 ret = ltdb_rename(ctx);
1525                 break;
1526         case LDB_EXTENDED:
1527                 ltdb_handle_extended(ctx);
1528                 goto done;
1529         default:
1530                 /* no other op supported */
1531                 ret = LDB_ERR_PROTOCOL_ERROR;
1532         }
1533
1534         if (!ctx->request_terminated) {
1535                 /* request is done now */
1536                 ltdb_request_done(ctx, ret);
1537         }
1538
1539 done:
1540         if (ctx->spy) {
1541                 /* neutralize the spy */
1542                 ctx->spy->ctx = NULL;
1543                 ctx->spy = NULL;
1544         }
1545         talloc_free(ctx);
1546 }
1547
1548 static int ltdb_request_destructor(void *ptr)
1549 {
1550         struct ltdb_req_spy *spy = talloc_get_type(ptr, struct ltdb_req_spy);
1551
1552         if (spy->ctx != NULL) {
1553                 spy->ctx->spy = NULL;
1554                 spy->ctx->request_terminated = true;
1555                 spy->ctx = NULL;
1556         }
1557
1558         return 0;
1559 }
1560
1561 static int ltdb_handle_request(struct ldb_module *module,
1562                                struct ldb_request *req)
1563 {
1564         struct ldb_control *control_permissive;
1565         struct ldb_context *ldb;
1566         struct tevent_context *ev;
1567         struct ltdb_context *ac;
1568         struct tevent_timer *te;
1569         struct timeval tv;
1570         unsigned int i;
1571
1572         ldb = ldb_module_get_ctx(module);
1573
1574         control_permissive = ldb_request_get_control(req,
1575                                         LDB_CONTROL_PERMISSIVE_MODIFY_OID);
1576
1577         for (i = 0; req->controls && req->controls[i]; i++) {
1578                 if (req->controls[i]->critical &&
1579                     req->controls[i] != control_permissive) {
1580                         ldb_asprintf_errstring(ldb, "Unsupported critical extension %s",
1581                                                req->controls[i]->oid);
1582                         return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
1583                 }
1584         }
1585
1586         if (req->starttime == 0 || req->timeout == 0) {
1587                 ldb_set_errstring(ldb, "Invalid timeout settings");
1588                 return LDB_ERR_TIME_LIMIT_EXCEEDED;
1589         }
1590
1591         ev = ldb_handle_get_event_context(req->handle);
1592
1593         ac = talloc_zero(ldb, struct ltdb_context);
1594         if (ac == NULL) {
1595                 ldb_oom(ldb);
1596                 return LDB_ERR_OPERATIONS_ERROR;
1597         }
1598
1599         ac->module = module;
1600         ac->req = req;
1601
1602         tv.tv_sec = 0;
1603         tv.tv_usec = 0;
1604         te = tevent_add_timer(ev, ac, tv, ltdb_callback, ac);
1605         if (NULL == te) {
1606                 talloc_free(ac);
1607                 return LDB_ERR_OPERATIONS_ERROR;
1608         }
1609
1610         if (req->timeout > 0) {
1611                 tv.tv_sec = req->starttime + req->timeout;
1612                 tv.tv_usec = 0;
1613                 ac->timeout_event = tevent_add_timer(ev, ac, tv,
1614                                                      ltdb_timeout, ac);
1615                 if (NULL == ac->timeout_event) {
1616                         talloc_free(ac);
1617                         return LDB_ERR_OPERATIONS_ERROR;
1618                 }
1619         }
1620
1621         /* set a spy so that we do not try to use the request context
1622          * if it is freed before ltdb_callback fires */
1623         ac->spy = talloc(req, struct ltdb_req_spy);
1624         if (NULL == ac->spy) {
1625                 talloc_free(ac);
1626                 return LDB_ERR_OPERATIONS_ERROR;
1627         }
1628         ac->spy->ctx = ac;
1629
1630         talloc_set_destructor((TALLOC_CTX *)ac->spy, ltdb_request_destructor);
1631
1632         return LDB_SUCCESS;
1633 }
1634
1635 static int ltdb_init_rootdse(struct ldb_module *module)
1636 {
1637         /* ignore errors on this - we expect it for non-sam databases */
1638         ldb_mod_register_control(module, LDB_CONTROL_PERMISSIVE_MODIFY_OID);
1639
1640         /* there can be no module beyond the backend, just return */
1641         return LDB_SUCCESS;
1642 }
1643
1644 static const struct ldb_module_ops ltdb_ops = {
1645         .name              = "tdb",
1646         .init_context      = ltdb_init_rootdse,
1647         .search            = ltdb_handle_request,
1648         .add               = ltdb_handle_request,
1649         .modify            = ltdb_handle_request,
1650         .del               = ltdb_handle_request,
1651         .rename            = ltdb_handle_request,
1652         .extended          = ltdb_handle_request,
1653         .start_transaction = ltdb_start_trans,
1654         .end_transaction   = ltdb_end_trans,
1655         .prepare_commit    = ltdb_prepare_commit,
1656         .del_transaction   = ltdb_del_trans,
1657         .read_lock         = ltdb_lock_read,
1658         .read_unlock       = ltdb_unlock_read,
1659 };
1660
1661 /*
1662   connect to the database
1663 */
1664 static int ltdb_connect(struct ldb_context *ldb, const char *url,
1665                         unsigned int flags, const char *options[],
1666                         struct ldb_module **_module)
1667 {
1668         struct ldb_module *module;
1669         const char *path;
1670         int tdb_flags, open_flags;
1671         struct ltdb_private *ltdb;
1672
1673         /*
1674          * We hold locks, so we must use a private event context
1675          * on each returned handle
1676          */
1677
1678         ldb_set_require_private_event_context(ldb);
1679
1680         /* parse the url */
1681         if (strchr(url, ':')) {
1682                 if (strncmp(url, "tdb://", 6) != 0) {
1683                         ldb_debug(ldb, LDB_DEBUG_ERROR,
1684                                   "Invalid tdb URL '%s'", url);
1685                         return LDB_ERR_OPERATIONS_ERROR;
1686                 }
1687                 path = url+6;
1688         } else {
1689                 path = url;
1690         }
1691
1692         tdb_flags = TDB_DEFAULT | TDB_SEQNUM;
1693
1694         /* check for the 'nosync' option */
1695         if (flags & LDB_FLG_NOSYNC) {
1696                 tdb_flags |= TDB_NOSYNC;
1697         }
1698
1699         /* and nommap option */
1700         if (flags & LDB_FLG_NOMMAP) {
1701                 tdb_flags |= TDB_NOMMAP;
1702         }
1703
1704         ltdb = talloc_zero(ldb, struct ltdb_private);
1705         if (!ltdb) {
1706                 ldb_oom(ldb);
1707                 return LDB_ERR_OPERATIONS_ERROR;
1708         }
1709
1710         if (flags & LDB_FLG_RDONLY) {
1711                 /*
1712                  * This is weird, but because we can only have one tdb
1713                  * in this process, and the other one could be
1714                  * read-write, we can't use the tdb readonly.  Plus a
1715                  * read only tdb prohibits the all-record lock.
1716                  */
1717                 open_flags = O_RDWR;
1718
1719                 ltdb->read_only = true;
1720
1721         } else if (flags & LDB_FLG_DONT_CREATE_DB) {
1722                 /*
1723                  * This is used by ldbsearch to prevent creation of the database
1724                  * if the name is wrong
1725                  */
1726                 open_flags = O_RDWR;
1727         } else {
1728                 /*
1729                  * This is the normal case
1730                  */
1731                 open_flags = O_CREAT | O_RDWR;
1732         }
1733
1734         /* note that we use quite a large default hash size */
1735         ltdb->tdb = ltdb_wrap_open(ltdb, path, 10000,
1736                                    tdb_flags, open_flags,
1737                                    ldb_get_create_perms(ldb), ldb);
1738         if (!ltdb->tdb) {
1739                 ldb_asprintf_errstring(ldb,
1740                                        "Unable to open tdb '%s': %s", path, strerror(errno));
1741                 ldb_debug(ldb, LDB_DEBUG_ERROR,
1742                           "Unable to open tdb '%s': %s", path, strerror(errno));
1743                 talloc_free(ltdb);
1744                 if (errno == EACCES || errno == EPERM) {
1745                         return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
1746                 }
1747                 return LDB_ERR_OPERATIONS_ERROR;
1748         }
1749
1750         if (getenv("LDB_WARN_UNINDEXED")) {
1751                 ltdb->warn_unindexed = true;
1752         }
1753
1754         if (getenv("LDB_WARN_REINDEX")) {
1755                 ltdb->warn_reindex = true;
1756         }
1757
1758         ltdb->sequence_number = 0;
1759
1760         module = ldb_module_new(ldb, ldb, "ldb_tdb backend", &ltdb_ops);
1761         if (!module) {
1762                 ldb_oom(ldb);
1763                 talloc_free(ltdb);
1764                 return LDB_ERR_OPERATIONS_ERROR;
1765         }
1766         ldb_module_set_private(module, ltdb);
1767         talloc_steal(module, ltdb);
1768
1769         if (ltdb_cache_load(module) != 0) {
1770                 ldb_asprintf_errstring(ldb,
1771                                        "Unable to load ltdb cache records of tdb '%s'", path);
1772                 talloc_free(module);
1773                 return LDB_ERR_OPERATIONS_ERROR;
1774         }
1775
1776         *_module = module;
1777         return LDB_SUCCESS;
1778 }
1779
1780 int ldb_tdb_init(const char *version)
1781 {
1782         LDB_MODULE_CHECK_VERSION(version);
1783         return ldb_register_backend("tdb", ltdb_connect, false);
1784 }