Make all transactions nested in ldb. The current samba4 code expects this
[ira/wip.git] / source4 / lib / ldb / common / ldb.c
1 /*
2    ldb database library
3
4    Copyright (C) Andrew Tridgell  2004
5    Copyright (C) Simo Sorce  2005-2008
6
7      ** NOTE! The following LGPL license applies to the ldb
8      ** library. This does NOT imply that all of Samba is released
9      ** under the LGPL
10
11    This library is free software; you can redistribute it and/or
12    modify it under the terms of the GNU Lesser General Public
13    License as published by the Free Software Foundation; either
14    version 3 of the License, or (at your option) any later version.
15
16    This library is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19    Lesser General Public License for more details.
20
21    You should have received a copy of the GNU Lesser General Public
22    License along with this library; if not, see <http://www.gnu.org/licenses/>.
23 */
24
25 /*
26  *  Name: ldb
27  *
28  *  Component: ldb core API
29  *
30  *  Description: core API routines interfacing to ldb backends
31  *
32  *  Author: Andrew Tridgell
33  */
34
35 #include "ldb_private.h"
36
37 static int ldb_context_destructor(void *ptr)
38 {
39         struct ldb_context *ldb = talloc_get_type(ptr, struct ldb_context);
40
41         if (ldb->transaction_active) {
42                 ldb_debug(ldb, LDB_DEBUG_FATAL,
43                           "A transaction is still active in ldb context [%p]",
44                           ldb);
45         }
46
47         return 0;
48 }
49
50 /*
51    initialise a ldb context
52    The mem_ctx is required
53    The event_ctx is required
54 */
55 struct ldb_context *ldb_init(TALLOC_CTX *mem_ctx, struct tevent_context *ev_ctx)
56 {
57         struct ldb_context *ldb;
58         int ret;
59
60         ldb = talloc_zero(mem_ctx, struct ldb_context);
61         /* FIXME: Hack a new event context so that CMD line utilities work
62          * until we have them all converted */
63         if (ev_ctx == NULL) {
64                 ev_ctx = tevent_context_init(talloc_autofree_context());
65         }
66
67         ret = ldb_setup_wellknown_attributes(ldb);
68         if (ret != 0) {
69                 talloc_free(ldb);
70                 return NULL;
71         }
72
73         ldb_set_utf8_default(ldb);
74         ldb_set_create_perms(ldb, 0666);
75         ldb_set_modules_dir(ldb, LDB_MODULESDIR);
76         ldb_set_event_context(ldb, ev_ctx);
77
78         /* TODO: get timeout from options if available there */
79         ldb->default_timeout = 300; /* set default to 5 minutes */
80
81         talloc_set_destructor((TALLOC_CTX *)ldb, ldb_context_destructor);
82
83         return ldb;
84 }
85
86 /*
87   try to autodetect a basedn if none specified. This fixes one of my
88   pet hates about ldapsearch, which is that you have to get a long,
89   complex basedn right to make any use of it.
90 */
91 void ldb_set_default_dns(struct ldb_context *ldb)
92 {
93         TALLOC_CTX *tmp_ctx;
94         int ret;
95         struct ldb_result *res;
96         struct ldb_dn *tmp_dn=NULL;
97         static const char *attrs[] = {
98                 "rootDomainNamingContext",
99                 "configurationNamingContext",
100                 "schemaNamingContext",
101                 "defaultNamingContext",
102                 NULL
103         };
104
105         tmp_ctx = talloc_new(ldb);
106         ret = ldb_search(ldb, tmp_ctx, &res, ldb_dn_new(tmp_ctx, ldb, NULL),
107                          LDB_SCOPE_BASE, attrs, "(objectClass=*)");
108         if (ret != LDB_SUCCESS) {
109                 talloc_free(tmp_ctx);
110                 return;
111         }
112
113         if (res->count != 1) {
114                 talloc_free(tmp_ctx);
115                 return;
116         }
117
118         if (!ldb_get_opaque(ldb, "rootDomainNamingContext")) {
119                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
120                                                  "rootDomainNamingContext");
121                 ldb_set_opaque(ldb, "rootDomainNamingContext", tmp_dn);
122         }
123
124         if (!ldb_get_opaque(ldb, "configurationNamingContext")) {
125                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
126                                                  "configurationNamingContext");
127                 ldb_set_opaque(ldb, "configurationNamingContext", tmp_dn);
128         }
129
130         if (!ldb_get_opaque(ldb, "schemaNamingContext")) {
131                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
132                                                  "schemaNamingContext");
133                 ldb_set_opaque(ldb, "schemaNamingContext", tmp_dn);
134         }
135
136         if (!ldb_get_opaque(ldb, "defaultNamingContext")) {
137                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
138                                                  "defaultNamingContext");
139                 ldb_set_opaque(ldb, "defaultNamingContext", tmp_dn);
140         }
141
142         talloc_free(tmp_ctx);
143 }
144
145 struct ldb_dn *ldb_get_root_basedn(struct ldb_context *ldb)
146 {
147         void *opaque = ldb_get_opaque(ldb, "rootDomainNamingContext");
148         return talloc_get_type(opaque, struct ldb_dn);
149 }
150
151 struct ldb_dn *ldb_get_config_basedn(struct ldb_context *ldb)
152 {
153         void *opaque = ldb_get_opaque(ldb, "configurationNamingContext");
154         return talloc_get_type(opaque, struct ldb_dn);
155 }
156
157 struct ldb_dn *ldb_get_schema_basedn(struct ldb_context *ldb)
158 {
159         void *opaque = ldb_get_opaque(ldb, "schemaNamingContext");
160         return talloc_get_type(opaque, struct ldb_dn);
161 }
162
163 struct ldb_dn *ldb_get_default_basedn(struct ldb_context *ldb)
164 {
165         void *opaque = ldb_get_opaque(ldb, "defaultNamingContext");
166         return talloc_get_type(opaque, struct ldb_dn);
167 }
168
169 /*
170    connect to a database. The URL can either be one of the following forms
171    ldb://path
172    ldapi://path
173
174    flags is made up of LDB_FLG_*
175
176    the options are passed uninterpreted to the backend, and are
177    backend specific
178 */
179 int ldb_connect(struct ldb_context *ldb, const char *url,
180                 unsigned int flags, const char *options[])
181 {
182         int ret;
183         const char *url2;
184         /* We seem to need to do this here, or else some utilities don't
185          * get ldb backends */
186
187         ldb->flags = flags;
188
189         url2 = talloc_strdup(ldb, url);
190         if (!url2) {
191                 ldb_oom(ldb);
192                 return LDB_ERR_OPERATIONS_ERROR;
193         }
194         ret = ldb_set_opaque(ldb, "ldb_url", talloc_strdup(ldb, url2));
195         if (ret != LDB_SUCCESS) {
196                 return ret;
197         }
198
199         ret = ldb_connect_backend(ldb, url, options, &ldb->modules);
200         if (ret != LDB_SUCCESS) {
201                 return ret;
202         }
203
204         if (ldb_load_modules(ldb, options) != LDB_SUCCESS) {
205                 ldb_debug(ldb, LDB_DEBUG_FATAL,
206                           "Unable to load modules for %s: %s\n",
207                           url, ldb_errstring(ldb));
208                 return LDB_ERR_OTHER;
209         }
210
211         /* set the default base dn */
212         ldb_set_default_dns(ldb);
213
214         return LDB_SUCCESS;
215 }
216
217 void ldb_set_errstring(struct ldb_context *ldb, const char *err_string)
218 {
219         if (ldb->err_string) {
220                 talloc_free(ldb->err_string);
221         }
222         ldb->err_string = talloc_strdup(ldb, err_string);
223 }
224
225 void ldb_asprintf_errstring(struct ldb_context *ldb, const char *format, ...)
226 {
227         va_list ap;
228         char *old_string = NULL;
229
230         if (ldb->err_string) {
231                 old_string = ldb->err_string;
232         }
233
234         va_start(ap, format);
235         ldb->err_string = talloc_vasprintf(ldb, format, ap);
236         va_end(ap);
237         talloc_free(old_string);
238 }
239
240 void ldb_reset_err_string(struct ldb_context *ldb)
241 {
242         if (ldb->err_string) {
243                 talloc_free(ldb->err_string);
244                 ldb->err_string = NULL;
245         }
246 }
247
248 #define FIRST_OP(ldb, op) do { \
249         module = ldb->modules;                                  \
250         while (module && module->ops->op == NULL) module = module->next; \
251         if (module == NULL) {                                           \
252                 ldb_asprintf_errstring(ldb, "unable to find module or backend to handle operation: " #op); \
253                 return LDB_ERR_OPERATIONS_ERROR;                        \
254         } \
255 } while (0)
256
257 /*
258   start a transaction
259 */
260 int ldb_transaction_start(struct ldb_context *ldb)
261 {
262         struct ldb_module *module;
263         int status;
264
265         ldb_debug(ldb, LDB_DEBUG_TRACE,
266                   "start ldb transaction (nesting: %d)",
267                   ldb->transaction_active);
268
269         /* explicit transaction active, count nested requests */
270         if (ldb->transaction_active) {
271                 ldb->transaction_active++;
272                 return LDB_SUCCESS;
273         }
274
275         /* start a new transaction */
276         ldb->transaction_active++;
277
278         FIRST_OP(ldb, start_transaction);
279
280         ldb_reset_err_string(ldb);
281
282         status = module->ops->start_transaction(module);
283         if (status != LDB_SUCCESS) {
284                 if (ldb->err_string == NULL) {
285                         /* no error string was setup by the backend */
286                         ldb_asprintf_errstring(ldb,
287                                 "ldb transaction start: %s (%d)",
288                                 ldb_strerror(status),
289                                 status);
290                 }
291         }
292         return status;
293 }
294
295 /*
296   commit a transaction
297 */
298 int ldb_transaction_commit(struct ldb_context *ldb)
299 {
300         struct ldb_module *module;
301         int status;
302
303         ldb->transaction_active--;
304
305         ldb_debug(ldb, LDB_DEBUG_TRACE,
306                   "commit ldb transaction (nesting: %d)",
307                   ldb->transaction_active);
308
309         /* commit only when all nested transactions are complete */
310         if (ldb->transaction_active > 0) {
311                 return LDB_SUCCESS;
312         }
313
314         if (ldb->transaction_active < 0) {
315                 ldb_debug(ldb, LDB_DEBUG_FATAL,
316                           "commit called but no ldb transactions are active!");
317                 ldb->transaction_active = 0;
318                 return LDB_ERR_OPERATIONS_ERROR;
319         }
320
321         FIRST_OP(ldb, end_transaction);
322
323         ldb_reset_err_string(ldb);
324
325         status = module->ops->end_transaction(module);
326         if (status != LDB_SUCCESS) {
327                 if (ldb->err_string == NULL) {
328                         /* no error string was setup by the backend */
329                         ldb_asprintf_errstring(ldb,
330                                 "ldb transaction commit: %s (%d)",
331                                 ldb_strerror(status),
332                                 status);
333                 }
334         }
335         return status;
336 }
337
338 /*
339   cancel a transaction
340 */
341 int ldb_transaction_cancel(struct ldb_context *ldb)
342 {
343         struct ldb_module *module;
344         int status;
345
346         ldb->transaction_active--;
347
348         ldb_debug(ldb, LDB_DEBUG_TRACE,
349                   "cancel ldb transaction (nesting: %d)",
350                   ldb->transaction_active);
351
352         /* really cancel only if all nested transactions are complete */
353         if (ldb->transaction_active > 0) {
354                 return LDB_SUCCESS;
355         }
356
357         if (ldb->transaction_active < 0) {
358                 ldb_debug(ldb, LDB_DEBUG_FATAL,
359                           "commit called but no ldb transactions are active!");
360                 ldb->transaction_active = 0;
361                 return LDB_ERR_OPERATIONS_ERROR;
362         }
363
364         FIRST_OP(ldb, del_transaction);
365
366         status = module->ops->del_transaction(module);
367         if (status != LDB_SUCCESS) {
368                 if (ldb->err_string == NULL) {
369                         /* no error string was setup by the backend */
370                         ldb_asprintf_errstring(ldb,
371                                 "ldb transaction cancel: %s (%d)",
372                                 ldb_strerror(status),
373                                 status);
374                 }
375         }
376         return status;
377 }
378
379 /* autostarts a transacion if none active */
380 static int ldb_autotransaction_request(struct ldb_context *ldb,
381                                        struct ldb_request *req)
382 {
383         int ret;
384
385         ret = ldb_transaction_start(ldb);
386         if (ret != LDB_SUCCESS) {
387                 return ret;
388         }
389
390         ret = ldb_request(ldb, req);
391         if (ret == LDB_SUCCESS) {
392                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
393         }
394
395         if (ret == LDB_SUCCESS) {
396                 return ldb_transaction_commit(ldb);
397         }
398         ldb_transaction_cancel(ldb);
399
400         if (ldb->err_string == NULL) {
401                 /* no error string was setup by the backend */
402                 ldb_asprintf_errstring(ldb, "%s (%d)", ldb_strerror(ret), ret);
403         }
404
405         return ret;
406 }
407
408 int ldb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
409 {
410         struct tevent_context *ev;
411         int ret;
412
413         if (!handle) {
414                 return LDB_ERR_UNAVAILABLE;
415         }
416
417         if (handle->state == LDB_ASYNC_DONE) {
418                 return handle->status;
419         }
420
421         ev = ldb_get_event_context(handle->ldb);
422         if (NULL == ev) {
423                 return LDB_ERR_OPERATIONS_ERROR;
424         }
425
426         switch (type) {
427         case LDB_WAIT_NONE:
428                 ret = tevent_loop_once(ev);
429                 if (ret != 0) {
430                         return LDB_ERR_OPERATIONS_ERROR;
431                 }
432                 if (handle->state == LDB_ASYNC_DONE ||
433                     handle->status != LDB_SUCCESS) {
434                         return handle->status;
435                 }
436                 break;
437
438         case LDB_WAIT_ALL:
439                 while (handle->state != LDB_ASYNC_DONE) {
440                         ret = tevent_loop_once(ev);
441                         if (ret != 0) {
442                                 return LDB_ERR_OPERATIONS_ERROR;
443                         }
444                         if (handle->status != LDB_SUCCESS) {
445                                 return handle->status;
446                         }
447                 }
448                 return handle->status;
449         }
450
451         return LDB_SUCCESS;
452 }
453
454 /* set the specified timeout or, if timeout is 0 set the default timeout */
455 int ldb_set_timeout(struct ldb_context *ldb,
456                     struct ldb_request *req,
457                     int timeout)
458 {
459         if (req == NULL) return LDB_ERR_OPERATIONS_ERROR;
460
461         if (timeout != 0) {
462                 req->timeout = timeout;
463         } else {
464                 req->timeout = ldb->default_timeout;
465         }
466         req->starttime = time(NULL);
467
468         return LDB_SUCCESS;
469 }
470
471 /* calculates the new timeout based on the previous starttime and timeout */
472 int ldb_set_timeout_from_prev_req(struct ldb_context *ldb,
473                                   struct ldb_request *oldreq,
474                                   struct ldb_request *newreq)
475 {
476         if (newreq == NULL) return LDB_ERR_OPERATIONS_ERROR;
477
478         if (oldreq == NULL) {
479                 return ldb_set_timeout(ldb, newreq, 0);
480         }
481
482         newreq->starttime = oldreq->starttime;
483         newreq->timeout = oldreq->timeout;
484
485         return LDB_SUCCESS;
486 }
487
488
489 /*
490    set the permissions for new files to be passed to open() in
491    backends that use local files
492  */
493 void ldb_set_create_perms(struct ldb_context *ldb, unsigned int perms)
494 {
495         ldb->create_perms = perms;
496 }
497
498 unsigned int ldb_get_create_perms(struct ldb_context *ldb)
499 {
500         return ldb->create_perms;
501 }
502
503 void ldb_set_event_context(struct ldb_context *ldb, struct tevent_context *ev)
504 {
505         ldb->ev_ctx = ev;
506 }
507
508 struct tevent_context * ldb_get_event_context(struct ldb_context *ldb)
509 {
510         return ldb->ev_ctx;
511 }
512
513 void ldb_request_set_state(struct ldb_request *req, int state)
514 {
515         req->handle->state = state;
516 }
517
518 int ldb_request_get_status(struct ldb_request *req)
519 {
520         return req->handle->status;
521 }
522
523 /*
524   start an ldb request
525   NOTE: the request must be a talloc context.
526   returns LDB_ERR_* on errors.
527 */
528 int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
529 {
530         struct ldb_module *module;
531         int ret;
532
533         if (req->callback == NULL) {
534                 ldb_set_errstring(ldb, "Requests MUST define callbacks");
535                 return LDB_ERR_UNWILLING_TO_PERFORM;
536         }
537
538         ldb_reset_err_string(ldb);
539
540         /* call the first module in the chain */
541         switch (req->operation) {
542         case LDB_SEARCH:
543                 FIRST_OP(ldb, search);
544                 ret = module->ops->search(module, req);
545                 break;
546         case LDB_ADD:
547                 FIRST_OP(ldb, add);
548                 ret = module->ops->add(module, req);
549                 break;
550         case LDB_MODIFY:
551                 FIRST_OP(ldb, modify);
552                 ret = module->ops->modify(module, req);
553                 break;
554         case LDB_DELETE:
555                 FIRST_OP(ldb, del);
556                 ret = module->ops->del(module, req);
557                 break;
558         case LDB_RENAME:
559                 FIRST_OP(ldb, rename);
560                 ret = module->ops->rename(module, req);
561                 break;
562         case LDB_EXTENDED:
563                 FIRST_OP(ldb, extended);
564                 ret = module->ops->extended(module, req);
565                 break;
566         default:
567                 FIRST_OP(ldb, request);
568                 ret = module->ops->request(module, req);
569                 break;
570         }
571
572         return ret;
573 }
574
575 int ldb_request_done(struct ldb_request *req, int status)
576 {
577         req->handle->state = LDB_ASYNC_DONE;
578         req->handle->status = status;
579         return status;
580 }
581
582 /*
583   search the database given a LDAP-like search expression
584
585   returns an LDB error code
586
587   Use talloc_free to free the ldb_message returned in 'res', if successful
588
589 */
590 int ldb_search_default_callback(struct ldb_request *req,
591                                 struct ldb_reply *ares)
592 {
593         struct ldb_result *res;
594         int n;
595
596         res = talloc_get_type(req->context, struct ldb_result);
597
598         if (!ares) {
599                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
600         }
601         if (ares->error != LDB_SUCCESS) {
602                 return ldb_request_done(req, ares->error);
603         }
604
605         switch (ares->type) {
606         case LDB_REPLY_ENTRY:
607                 res->msgs = talloc_realloc(res, res->msgs,
608                                         struct ldb_message *, res->count + 2);
609                 if (! res->msgs) {
610                         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
611                 }
612
613                 res->msgs[res->count + 1] = NULL;
614
615                 res->msgs[res->count] = talloc_move(res->msgs, &ares->message);
616                 res->count++;
617                 break;
618
619         case LDB_REPLY_REFERRAL:
620                 if (res->refs) {
621                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
622                 } else {
623                         n = 0;
624                 }
625
626                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
627                 if (! res->refs) {
628                         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
629                 }
630
631                 res->refs[n] = talloc_move(res->refs, &ares->referral);
632                 res->refs[n + 1] = NULL;
633                 break;
634
635         case LDB_REPLY_DONE:
636                 /* TODO: we should really support controls on entries
637                  * and referrals too! */
638                 res->controls = talloc_move(res, &ares->controls);
639
640                 /* this is the last message, and means the request is done */
641                 /* we have to signal and eventual ldb_wait() waiting that the
642                  * async request operation was completed */
643                 return ldb_request_done(req, LDB_SUCCESS);
644         }
645
646         talloc_free(ares);
647         return LDB_SUCCESS;
648 }
649
650 int ldb_op_default_callback(struct ldb_request *req, struct ldb_reply *ares)
651 {
652         int ret;
653
654         if (!ares) {
655                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
656         }
657
658         if (ares->error != LDB_SUCCESS) {
659                 ret = ares->error;
660                 talloc_free(ares);
661                 return ldb_request_done(req, ret);
662         }
663
664         if (ares->type != LDB_REPLY_DONE) {
665                 talloc_free(ares);
666                 ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
667                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
668         }
669
670         talloc_free(ares);
671         return ldb_request_done(req, LDB_SUCCESS);
672 }
673
674 int ldb_build_search_req_ex(struct ldb_request **ret_req,
675                         struct ldb_context *ldb,
676                         void *mem_ctx,
677                         struct ldb_dn *base,
678                         enum ldb_scope scope,
679                         struct ldb_parse_tree *tree,
680                         const char * const *attrs,
681                         struct ldb_control **controls,
682                         void *context,
683                         ldb_request_callback_t callback,
684                         struct ldb_request *parent)
685 {
686         struct ldb_request *req;
687
688         *ret_req = NULL;
689
690         req = talloc(mem_ctx, struct ldb_request);
691         if (req == NULL) {
692                 ldb_oom(ldb);
693                 return LDB_ERR_OPERATIONS_ERROR;
694         }
695
696         req->operation = LDB_SEARCH;
697         if (base == NULL) {
698                 req->op.search.base = ldb_dn_new(req, ldb, NULL);
699         } else {
700                 req->op.search.base = base;
701         }
702         req->op.search.scope = scope;
703
704         req->op.search.tree = tree;
705         if (req->op.search.tree == NULL) {
706                 ldb_set_errstring(ldb, "'tree' can't be NULL");
707                 talloc_free(req);
708                 return LDB_ERR_OPERATIONS_ERROR;
709         }
710
711         req->op.search.attrs = attrs;
712         req->controls = controls;
713         req->context = context;
714         req->callback = callback;
715
716         ldb_set_timeout_from_prev_req(ldb, parent, req);
717
718         req->handle = ldb_handle_new(req, ldb);
719         if (req->handle == NULL) {
720                 ldb_oom(ldb);
721                 return LDB_ERR_OPERATIONS_ERROR;
722         }
723
724         *ret_req = req;
725         return LDB_SUCCESS;
726 }
727
728 int ldb_build_search_req(struct ldb_request **ret_req,
729                         struct ldb_context *ldb,
730                         void *mem_ctx,
731                         struct ldb_dn *base,
732                         enum ldb_scope scope,
733                         const char *expression,
734                         const char * const *attrs,
735                         struct ldb_control **controls,
736                         void *context,
737                         ldb_request_callback_t callback,
738                         struct ldb_request *parent)
739 {
740         struct ldb_parse_tree *tree;
741         int ret;
742
743         tree = ldb_parse_tree(mem_ctx, expression);
744         if (tree == NULL) {
745                 ldb_set_errstring(ldb, "Unable to parse search expression");
746                 return LDB_ERR_OPERATIONS_ERROR;
747         }
748
749         ret = ldb_build_search_req_ex(ret_req, ldb, mem_ctx, base,
750                                       scope, tree, attrs, controls,
751                                       context, callback, parent);
752         if (ret == LDB_SUCCESS) {
753                 talloc_steal(*ret_req, tree);
754         }
755         return ret;
756 }
757
758 int ldb_build_add_req(struct ldb_request **ret_req,
759                         struct ldb_context *ldb,
760                         void *mem_ctx,
761                         const struct ldb_message *message,
762                         struct ldb_control **controls,
763                         void *context,
764                         ldb_request_callback_t callback,
765                         struct ldb_request *parent)
766 {
767         struct ldb_request *req;
768
769         *ret_req = NULL;
770
771         req = talloc(mem_ctx, struct ldb_request);
772         if (req == NULL) {
773                 ldb_set_errstring(ldb, "Out of Memory");
774                 return LDB_ERR_OPERATIONS_ERROR;
775         }
776
777         req->operation = LDB_ADD;
778         req->op.add.message = message;
779         req->controls = controls;
780         req->context = context;
781         req->callback = callback;
782
783         ldb_set_timeout_from_prev_req(ldb, parent, req);
784
785         req->handle = ldb_handle_new(req, ldb);
786         if (req->handle == NULL) {
787                 ldb_oom(ldb);
788                 return LDB_ERR_OPERATIONS_ERROR;
789         }
790
791         *ret_req = req;
792
793         return LDB_SUCCESS;
794 }
795
796 int ldb_build_mod_req(struct ldb_request **ret_req,
797                         struct ldb_context *ldb,
798                         void *mem_ctx,
799                         const struct ldb_message *message,
800                         struct ldb_control **controls,
801                         void *context,
802                         ldb_request_callback_t callback,
803                         struct ldb_request *parent)
804 {
805         struct ldb_request *req;
806
807         *ret_req = NULL;
808
809         req = talloc(mem_ctx, struct ldb_request);
810         if (req == NULL) {
811                 ldb_set_errstring(ldb, "Out of Memory");
812                 return LDB_ERR_OPERATIONS_ERROR;
813         }
814
815         req->operation = LDB_MODIFY;
816         req->op.mod.message = message;
817         req->controls = controls;
818         req->context = context;
819         req->callback = callback;
820
821         ldb_set_timeout_from_prev_req(ldb, parent, req);
822
823         req->handle = ldb_handle_new(req, ldb);
824         if (req->handle == NULL) {
825                 ldb_oom(ldb);
826                 return LDB_ERR_OPERATIONS_ERROR;
827         }
828
829         *ret_req = req;
830
831         return LDB_SUCCESS;
832 }
833
834 int ldb_build_del_req(struct ldb_request **ret_req,
835                         struct ldb_context *ldb,
836                         void *mem_ctx,
837                         struct ldb_dn *dn,
838                         struct ldb_control **controls,
839                         void *context,
840                         ldb_request_callback_t callback,
841                         struct ldb_request *parent)
842 {
843         struct ldb_request *req;
844
845         *ret_req = NULL;
846
847         req = talloc(mem_ctx, struct ldb_request);
848         if (req == NULL) {
849                 ldb_set_errstring(ldb, "Out of Memory");
850                 return LDB_ERR_OPERATIONS_ERROR;
851         }
852
853         req->operation = LDB_DELETE;
854         req->op.del.dn = dn;
855         req->controls = controls;
856         req->context = context;
857         req->callback = callback;
858
859         ldb_set_timeout_from_prev_req(ldb, parent, req);
860
861         req->handle = ldb_handle_new(req, ldb);
862         if (req->handle == NULL) {
863                 ldb_oom(ldb);
864                 return LDB_ERR_OPERATIONS_ERROR;
865         }
866
867         *ret_req = req;
868
869         return LDB_SUCCESS;
870 }
871
872 int ldb_build_rename_req(struct ldb_request **ret_req,
873                         struct ldb_context *ldb,
874                         void *mem_ctx,
875                         struct ldb_dn *olddn,
876                         struct ldb_dn *newdn,
877                         struct ldb_control **controls,
878                         void *context,
879                         ldb_request_callback_t callback,
880                         struct ldb_request *parent)
881 {
882         struct ldb_request *req;
883
884         *ret_req = NULL;
885
886         req = talloc(mem_ctx, struct ldb_request);
887         if (req == NULL) {
888                 ldb_set_errstring(ldb, "Out of Memory");
889                 return LDB_ERR_OPERATIONS_ERROR;
890         }
891
892         req->operation = LDB_RENAME;
893         req->op.rename.olddn = olddn;
894         req->op.rename.newdn = newdn;
895         req->controls = controls;
896         req->context = context;
897         req->callback = callback;
898
899         ldb_set_timeout_from_prev_req(ldb, parent, req);
900
901         req->handle = ldb_handle_new(req, ldb);
902         if (req->handle == NULL) {
903                 ldb_oom(ldb);
904                 return LDB_ERR_OPERATIONS_ERROR;
905         }
906
907         *ret_req = req;
908
909         return LDB_SUCCESS;
910 }
911
912 int ldb_extended_default_callback(struct ldb_request *req,
913                                   struct ldb_reply *ares)
914 {
915         struct ldb_result *res;
916
917         res = talloc_get_type(req->context, struct ldb_result);
918
919         if (!ares) {
920                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
921         }
922         if (ares->error != LDB_SUCCESS) {
923                 return ldb_request_done(req, ares->error);
924         }
925
926         if (ares->type == LDB_REPLY_DONE) {
927
928                 /* TODO: we should really support controls on entries and referrals too! */
929                 res->extended = talloc_move(res, &ares->response);
930                 res->controls = talloc_move(res, &ares->controls);
931
932                 talloc_free(ares);
933                 return ldb_request_done(req, LDB_SUCCESS);
934         }
935
936         talloc_free(ares);
937         ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
938         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
939 }
940
941 int ldb_build_extended_req(struct ldb_request **ret_req,
942                            struct ldb_context *ldb,
943                            void *mem_ctx,
944                            const char *oid,
945                            void *data,
946                            struct ldb_control **controls,
947                            void *context,
948                            ldb_request_callback_t callback,
949                            struct ldb_request *parent)
950 {
951         struct ldb_request *req;
952
953         *ret_req = NULL;
954
955         req = talloc(mem_ctx, struct ldb_request);
956         if (req == NULL) {
957                 ldb_set_errstring(ldb, "Out of Memory");
958                 return LDB_ERR_OPERATIONS_ERROR;
959         }
960
961         req->operation = LDB_EXTENDED;
962         req->op.extended.oid = oid;
963         req->op.extended.data = data;
964         req->controls = controls;
965         req->context = context;
966         req->callback = callback;
967
968         ldb_set_timeout_from_prev_req(ldb, parent, req);
969
970         req->handle = ldb_handle_new(req, ldb);
971         if (req->handle == NULL) {
972                 ldb_oom(ldb);
973                 return LDB_ERR_OPERATIONS_ERROR;
974         }
975
976         *ret_req = req;
977
978         return LDB_SUCCESS;
979 }
980
981 int ldb_extended(struct ldb_context *ldb,
982                  const char *oid,
983                  void *data,
984                  struct ldb_result **_res)
985 {
986         struct ldb_request *req;
987         int ret;
988         struct ldb_result *res;
989
990         *_res = NULL;
991
992         res = talloc_zero(ldb, struct ldb_result);
993         if (!res) {
994                 return LDB_ERR_OPERATIONS_ERROR;
995         }
996
997         ret = ldb_build_extended_req(&req, ldb, ldb,
998                                      oid, data, NULL,
999                                      res, ldb_extended_default_callback,
1000                                      NULL);
1001         if (ret != LDB_SUCCESS) goto done;
1002
1003         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1004
1005         ret = ldb_request(ldb, req);
1006
1007         if (ret == LDB_SUCCESS) {
1008                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1009         }
1010
1011         talloc_free(req);
1012
1013 done:
1014         if (ret != LDB_SUCCESS) {
1015                 talloc_free(res);
1016         }
1017
1018         *_res = res;
1019         return ret;
1020 }
1021
1022 /*
1023   note that ldb_search() will automatically replace a NULL 'base' value
1024   with the defaultNamingContext from the rootDSE if available.
1025 */
1026 int ldb_search(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1027                 struct ldb_result **result, struct ldb_dn *base,
1028                 enum ldb_scope scope, const char * const *attrs,
1029                 const char *exp_fmt, ...)
1030 {
1031         struct ldb_request *req;
1032         struct ldb_result *res;
1033         char *expression;
1034         va_list ap;
1035         int ret;
1036
1037         expression = NULL;
1038         *result = NULL;
1039         req = NULL;
1040
1041         res = talloc_zero(mem_ctx, struct ldb_result);
1042         if (!res) {
1043                 return LDB_ERR_OPERATIONS_ERROR;
1044         }
1045
1046         if (exp_fmt) {
1047                 va_start(ap, exp_fmt);
1048                 expression = talloc_vasprintf(mem_ctx, exp_fmt, ap);
1049                 va_end(ap);
1050
1051                 if (!expression) {
1052                         talloc_free(res);
1053                         return LDB_ERR_OPERATIONS_ERROR;
1054                 }
1055         }
1056
1057         ret = ldb_build_search_req(&req, ldb, mem_ctx,
1058                                         base?base:ldb_get_default_basedn(ldb),
1059                                         scope,
1060                                         expression,
1061                                         attrs,
1062                                         NULL,
1063                                         res,
1064                                         ldb_search_default_callback,
1065                                         NULL);
1066
1067         if (ret != LDB_SUCCESS) goto done;
1068
1069         ret = ldb_request(ldb, req);
1070
1071         if (ret == LDB_SUCCESS) {
1072                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1073         }
1074
1075 done:
1076         if (ret != LDB_SUCCESS) {
1077                 talloc_free(res);
1078                 res = NULL;
1079         }
1080
1081         talloc_free(expression);
1082         talloc_free(req);
1083
1084         *result = res;
1085         return ret;
1086 }
1087
1088 /*
1089   add a record to the database. Will fail if a record with the given class
1090   and key already exists
1091 */
1092 int ldb_add(struct ldb_context *ldb,
1093             const struct ldb_message *message)
1094 {
1095         struct ldb_request *req;
1096         int ret;
1097
1098         ret = ldb_msg_sanity_check(ldb, message);
1099         if (ret != LDB_SUCCESS) {
1100                 return ret;
1101         }
1102
1103         ret = ldb_build_add_req(&req, ldb, ldb,
1104                                         message,
1105                                         NULL,
1106                                         NULL,
1107                                         ldb_op_default_callback,
1108                                         NULL);
1109
1110         if (ret != LDB_SUCCESS) return ret;
1111
1112         /* do request and autostart a transaction */
1113         ret = ldb_autotransaction_request(ldb, req);
1114
1115         talloc_free(req);
1116         return ret;
1117 }
1118
1119 /*
1120   modify the specified attributes of a record
1121 */
1122 int ldb_modify(struct ldb_context *ldb,
1123                const struct ldb_message *message)
1124 {
1125         struct ldb_request *req;
1126         int ret;
1127
1128         ret = ldb_msg_sanity_check(ldb, message);
1129         if (ret != LDB_SUCCESS) {
1130                 return ret;
1131         }
1132
1133         ret = ldb_build_mod_req(&req, ldb, ldb,
1134                                         message,
1135                                         NULL,
1136                                         NULL,
1137                                         ldb_op_default_callback,
1138                                         NULL);
1139
1140         if (ret != LDB_SUCCESS) return ret;
1141
1142         /* do request and autostart a transaction */
1143         ret = ldb_autotransaction_request(ldb, req);
1144
1145         talloc_free(req);
1146         return ret;
1147 }
1148
1149
1150 /*
1151   delete a record from the database
1152 */
1153 int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn)
1154 {
1155         struct ldb_request *req;
1156         int ret;
1157
1158         ret = ldb_build_del_req(&req, ldb, ldb,
1159                                         dn,
1160                                         NULL,
1161                                         NULL,
1162                                         ldb_op_default_callback,
1163                                         NULL);
1164
1165         if (ret != LDB_SUCCESS) return ret;
1166
1167         /* do request and autostart a transaction */
1168         ret = ldb_autotransaction_request(ldb, req);
1169
1170         talloc_free(req);
1171         return ret;
1172 }
1173
1174 /*
1175   rename a record in the database
1176 */
1177 int ldb_rename(struct ldb_context *ldb,
1178                 struct ldb_dn *olddn, struct ldb_dn *newdn)
1179 {
1180         struct ldb_request *req;
1181         int ret;
1182
1183         ret = ldb_build_rename_req(&req, ldb, ldb,
1184                                         olddn,
1185                                         newdn,
1186                                         NULL,
1187                                         NULL,
1188                                         ldb_op_default_callback,
1189                                         NULL);
1190
1191         if (ret != LDB_SUCCESS) return ret;
1192
1193         /* do request and autostart a transaction */
1194         ret = ldb_autotransaction_request(ldb, req);
1195
1196         talloc_free(req);
1197         return ret;
1198 }
1199
1200
1201 /*
1202   return the global sequence number
1203 */
1204 int ldb_sequence_number(struct ldb_context *ldb,
1205                         enum ldb_sequence_type type, uint64_t *seq_num)
1206 {
1207         struct ldb_seqnum_request *seq;
1208         struct ldb_seqnum_result *seqr;
1209         struct ldb_result *res;
1210         TALLOC_CTX *tmp_ctx;
1211         int ret;
1212
1213         *seq_num = 0;
1214
1215         tmp_ctx = talloc_zero(ldb, struct ldb_request);
1216         if (tmp_ctx == NULL) {
1217                 ldb_set_errstring(ldb, "Out of Memory");
1218                 return LDB_ERR_OPERATIONS_ERROR;
1219         }
1220         seq = talloc_zero(tmp_ctx, struct ldb_seqnum_request);
1221         if (seq == NULL) {
1222                 ldb_set_errstring(ldb, "Out of Memory");
1223                 ret = LDB_ERR_OPERATIONS_ERROR;
1224                 goto done;
1225         }
1226         seq->type = type;
1227
1228         ret = ldb_extended(ldb, LDB_EXTENDED_SEQUENCE_NUMBER, seq, &res);
1229         if (ret != LDB_SUCCESS) {
1230                 goto done;
1231         }
1232         talloc_steal(tmp_ctx, res);
1233
1234         if (strcmp(LDB_EXTENDED_SEQUENCE_NUMBER, res->extended->oid) != 0) {
1235                 ldb_set_errstring(ldb, "Invalid OID in reply");
1236                 ret = LDB_ERR_OPERATIONS_ERROR;
1237                 goto done;
1238         }
1239         seqr = talloc_get_type(res->extended->data,
1240                                 struct ldb_seqnum_result);
1241         *seq_num = seqr->seq_num;
1242
1243 done:
1244         talloc_free(tmp_ctx);
1245         return ret;
1246 }
1247
1248 /*
1249   return extended error information
1250 */
1251 const char *ldb_errstring(struct ldb_context *ldb)
1252 {
1253         if (ldb->err_string) {
1254                 return ldb->err_string;
1255         }
1256
1257         return NULL;
1258 }
1259
1260 /*
1261   return a string explaining what a ldb error constant meancs
1262 */
1263 const char *ldb_strerror(int ldb_err)
1264 {
1265         switch (ldb_err) {
1266         case LDB_SUCCESS:
1267                 return "Success";
1268         case LDB_ERR_OPERATIONS_ERROR:
1269                 return "Operations error";
1270         case LDB_ERR_PROTOCOL_ERROR:
1271                 return "Protocol error";
1272         case LDB_ERR_TIME_LIMIT_EXCEEDED:
1273                 return "Time limit exceeded";
1274         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
1275                 return "Size limit exceeded";
1276         case LDB_ERR_COMPARE_FALSE:
1277                 return "Compare false";
1278         case LDB_ERR_COMPARE_TRUE:
1279                 return "Compare true";
1280         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
1281                 return "Auth method not supported";
1282         case LDB_ERR_STRONG_AUTH_REQUIRED:
1283                 return "Strong auth required";
1284 /* 9 RESERVED */
1285         case LDB_ERR_REFERRAL:
1286                 return "Referral error";
1287         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
1288                 return "Admin limit exceeded";
1289         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
1290                 return "Unsupported critical extension";
1291         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
1292                 return "Confidentiality required";
1293         case LDB_ERR_SASL_BIND_IN_PROGRESS:
1294                 return "SASL bind in progress";
1295         case LDB_ERR_NO_SUCH_ATTRIBUTE:
1296                 return "No such attribute";
1297         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
1298                 return "Undefined attribute type";
1299         case LDB_ERR_INAPPROPRIATE_MATCHING:
1300                 return "Inappropriate matching";
1301         case LDB_ERR_CONSTRAINT_VIOLATION:
1302                 return "Constraint violation";
1303         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
1304                 return "Attribute or value exists";
1305         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
1306                 return "Invalid attribute syntax";
1307 /* 22-31 unused */
1308         case LDB_ERR_NO_SUCH_OBJECT:
1309                 return "No such object";
1310         case LDB_ERR_ALIAS_PROBLEM:
1311                 return "Alias problem";
1312         case LDB_ERR_INVALID_DN_SYNTAX:
1313                 return "Invalid DN syntax";
1314 /* 35 RESERVED */
1315         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
1316                 return "Alias dereferencing problem";
1317 /* 37-47 unused */
1318         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
1319                 return "Inappropriate authentication";
1320         case LDB_ERR_INVALID_CREDENTIALS:
1321                 return "Invalid credentials";
1322         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
1323                 return "insufficient access rights";
1324         case LDB_ERR_BUSY:
1325                 return "Busy";
1326         case LDB_ERR_UNAVAILABLE:
1327                 return "Unavailable";
1328         case LDB_ERR_UNWILLING_TO_PERFORM:
1329                 return "Unwilling to perform";
1330         case LDB_ERR_LOOP_DETECT:
1331                 return "Loop detect";
1332 /* 55-63 unused */
1333         case LDB_ERR_NAMING_VIOLATION:
1334                 return "Naming violation";
1335         case LDB_ERR_OBJECT_CLASS_VIOLATION:
1336                 return "Object class violation";
1337         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
1338                 return "Not allowed on non-leaf";
1339         case LDB_ERR_NOT_ALLOWED_ON_RDN:
1340                 return "Not allowed on RDN";
1341         case LDB_ERR_ENTRY_ALREADY_EXISTS:
1342                 return "Entry already exists";
1343         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
1344                 return "Object class mods prohibited";
1345 /* 70 RESERVED FOR CLDAP */
1346         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
1347                 return "Affects multiple DSAs";
1348 /* 72-79 unused */
1349         case LDB_ERR_OTHER:
1350                 return "Other";
1351         }
1352
1353         return "Unknown error";
1354 }
1355
1356 /*
1357   set backend specific opaque parameters
1358 */
1359 int ldb_set_opaque(struct ldb_context *ldb, const char *name, void *value)
1360 {
1361         struct ldb_opaque *o;
1362
1363         /* allow updating an existing value */
1364         for (o=ldb->opaque;o;o=o->next) {
1365                 if (strcmp(o->name, name) == 0) {
1366                         o->value = value;
1367                         return LDB_SUCCESS;
1368                 }
1369         }
1370
1371         o = talloc(ldb, struct ldb_opaque);
1372         if (o == NULL) {
1373                 ldb_oom(ldb);
1374                 return LDB_ERR_OTHER;
1375         }
1376         o->next = ldb->opaque;
1377         o->name = name;
1378         o->value = value;
1379         ldb->opaque = o;
1380         return LDB_SUCCESS;
1381 }
1382
1383 /*
1384   get a previously set opaque value
1385 */
1386 void *ldb_get_opaque(struct ldb_context *ldb, const char *name)
1387 {
1388         struct ldb_opaque *o;
1389         for (o=ldb->opaque;o;o=o->next) {
1390                 if (strcmp(o->name, name) == 0) {
1391                         return o->value;
1392                 }
1393         }
1394         return NULL;
1395 }