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