Fix the mess with ldb includes.
[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_private.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 unsigned int ldb_get_create_perms(struct ldb_context *ldb)
485 {
486         return ldb->create_perms;
487 }
488
489 void ldb_set_event_context(struct ldb_context *ldb, struct tevent_context *ev)
490 {
491         ldb->ev_ctx = ev;
492 }
493
494 struct tevent_context * ldb_get_event_context(struct ldb_context *ldb)
495 {
496         return ldb->ev_ctx;
497 }
498
499 void ldb_request_set_state(struct ldb_request *req, int state)
500 {
501         req->handle->state = state;
502 }
503
504 int ldb_request_get_status(struct ldb_request *req)
505 {
506         return req->handle->status;
507 }
508
509 /*
510   start an ldb request
511   NOTE: the request must be a talloc context.
512   returns LDB_ERR_* on errors.
513 */
514 int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
515 {
516         struct ldb_module *module;
517         int ret;
518
519         if (req->callback == NULL) {
520                 ldb_set_errstring(ldb, "Requests MUST define callbacks");
521                 return LDB_ERR_UNWILLING_TO_PERFORM;
522         }
523
524         ldb_reset_err_string(ldb);
525
526         /* call the first module in the chain */
527         switch (req->operation) {
528         case LDB_SEARCH:
529                 FIRST_OP(ldb, search);
530                 ret = module->ops->search(module, req);
531                 break;
532         case LDB_ADD:
533                 FIRST_OP(ldb, add);
534                 ret = module->ops->add(module, req);
535                 break;
536         case LDB_MODIFY:
537                 FIRST_OP(ldb, modify);
538                 ret = module->ops->modify(module, req);
539                 break;
540         case LDB_DELETE:
541                 FIRST_OP(ldb, del);
542                 ret = module->ops->del(module, req);
543                 break;
544         case LDB_RENAME:
545                 FIRST_OP(ldb, rename);
546                 ret = module->ops->rename(module, req);
547                 break;
548         case LDB_EXTENDED:
549                 FIRST_OP(ldb, extended);
550                 ret = module->ops->extended(module, req);
551                 break;
552         default:
553                 FIRST_OP(ldb, request);
554                 ret = module->ops->request(module, req);
555                 break;
556         }
557
558         return ret;
559 }
560
561 int ldb_request_done(struct ldb_request *req, int status)
562 {
563         req->handle->state = LDB_ASYNC_DONE;
564         req->handle->status = status;
565         return status;
566 }
567
568 /*
569   search the database given a LDAP-like search expression
570
571   returns an LDB error code
572
573   Use talloc_free to free the ldb_message returned in 'res', if successful
574
575 */
576 int ldb_search_default_callback(struct ldb_request *req,
577                                 struct ldb_reply *ares)
578 {
579         struct ldb_result *res;
580         int n;
581
582         res = talloc_get_type(req->context, struct ldb_result);
583
584         if (!ares) {
585                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
586         }
587         if (ares->error != LDB_SUCCESS) {
588                 return ldb_request_done(req, ares->error);
589         }
590
591         switch (ares->type) {
592         case LDB_REPLY_ENTRY:
593                 res->msgs = talloc_realloc(res, res->msgs,
594                                         struct ldb_message *, res->count + 2);
595                 if (! res->msgs) {
596                         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
597                 }
598
599                 res->msgs[res->count + 1] = NULL;
600
601                 res->msgs[res->count] = talloc_move(res->msgs, &ares->message);
602                 res->count++;
603                 break;
604
605         case LDB_REPLY_REFERRAL:
606                 if (res->refs) {
607                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
608                 } else {
609                         n = 0;
610                 }
611
612                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
613                 if (! res->refs) {
614                         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
615                 }
616
617                 res->refs[n] = talloc_move(res->refs, &ares->referral);
618                 res->refs[n + 1] = NULL;
619                 break;
620
621         case LDB_REPLY_DONE:
622                 /* TODO: we should really support controls on entries
623                  * and referrals too! */
624                 res->controls = talloc_move(res, &ares->controls);
625
626                 /* this is the last message, and means the request is done */
627                 /* we have to signal and eventual ldb_wait() waiting that the
628                  * async request operation was completed */
629                 return ldb_request_done(req, LDB_SUCCESS);
630         }
631
632         talloc_free(ares);
633         return LDB_SUCCESS;
634 }
635
636 int ldb_op_default_callback(struct ldb_request *req, struct ldb_reply *ares)
637 {
638         int ret;
639
640         if (!ares) {
641                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
642         }
643
644         if (ares->error != LDB_SUCCESS) {
645                 ret = ares->error;
646                 talloc_free(ares);
647                 return ldb_request_done(req, ret);
648         }
649
650         if (ares->type != LDB_REPLY_DONE) {
651                 talloc_free(ares);
652                 ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
653                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
654         }
655
656         talloc_free(ares);
657         return ldb_request_done(req, LDB_SUCCESS);
658 }
659
660 int ldb_build_search_req_ex(struct ldb_request **ret_req,
661                         struct ldb_context *ldb,
662                         void *mem_ctx,
663                         struct ldb_dn *base,
664                         enum ldb_scope scope,
665                         struct ldb_parse_tree *tree,
666                         const char * const *attrs,
667                         struct ldb_control **controls,
668                         void *context,
669                         ldb_request_callback_t callback,
670                         struct ldb_request *parent)
671 {
672         struct ldb_request *req;
673
674         *ret_req = NULL;
675
676         req = talloc(mem_ctx, struct ldb_request);
677         if (req == NULL) {
678                 ldb_oom(ldb);
679                 return LDB_ERR_OPERATIONS_ERROR;
680         }
681
682         req->operation = LDB_SEARCH;
683         if (base == NULL) {
684                 req->op.search.base = ldb_dn_new(req, ldb, NULL);
685         } else {
686                 req->op.search.base = base;
687         }
688         req->op.search.scope = scope;
689
690         req->op.search.tree = tree;
691         if (req->op.search.tree == NULL) {
692                 ldb_set_errstring(ldb, "'tree' can't be NULL");
693                 talloc_free(req);
694                 return LDB_ERR_OPERATIONS_ERROR;
695         }
696
697         req->op.search.attrs = attrs;
698         req->controls = controls;
699         req->context = context;
700         req->callback = callback;
701
702         ldb_set_timeout_from_prev_req(ldb, parent, req);
703
704         req->handle = ldb_handle_new(req, ldb);
705         if (req->handle == NULL) {
706                 ldb_oom(ldb);
707                 return LDB_ERR_OPERATIONS_ERROR;
708         }
709
710         *ret_req = req;
711         return LDB_SUCCESS;
712 }
713
714 int ldb_build_search_req(struct ldb_request **ret_req,
715                         struct ldb_context *ldb,
716                         void *mem_ctx,
717                         struct ldb_dn *base,
718                         enum ldb_scope scope,
719                         const char *expression,
720                         const char * const *attrs,
721                         struct ldb_control **controls,
722                         void *context,
723                         ldb_request_callback_t callback,
724                         struct ldb_request *parent)
725 {
726         struct ldb_parse_tree *tree;
727         int ret;
728
729         tree = ldb_parse_tree(mem_ctx, expression);
730         if (tree == NULL) {
731                 ldb_set_errstring(ldb, "Unable to parse search expression");
732                 return LDB_ERR_OPERATIONS_ERROR;
733         }
734
735         ret = ldb_build_search_req_ex(ret_req, ldb, mem_ctx, base,
736                                       scope, tree, attrs, controls,
737                                       context, callback, parent);
738         if (ret == LDB_SUCCESS) {
739                 talloc_steal(*ret_req, tree);
740         }
741         return ret;
742 }
743
744 int ldb_build_add_req(struct ldb_request **ret_req,
745                         struct ldb_context *ldb,
746                         void *mem_ctx,
747                         const struct ldb_message *message,
748                         struct ldb_control **controls,
749                         void *context,
750                         ldb_request_callback_t callback,
751                         struct ldb_request *parent)
752 {
753         struct ldb_request *req;
754
755         *ret_req = NULL;
756
757         req = talloc(mem_ctx, struct ldb_request);
758         if (req == NULL) {
759                 ldb_set_errstring(ldb, "Out of Memory");
760                 return LDB_ERR_OPERATIONS_ERROR;
761         }
762
763         req->operation = LDB_ADD;
764         req->op.add.message = message;
765         req->controls = controls;
766         req->context = context;
767         req->callback = callback;
768
769         ldb_set_timeout_from_prev_req(ldb, parent, req);
770
771         req->handle = ldb_handle_new(req, ldb);
772         if (req->handle == NULL) {
773                 ldb_oom(ldb);
774                 return LDB_ERR_OPERATIONS_ERROR;
775         }
776
777         *ret_req = req;
778
779         return LDB_SUCCESS;
780 }
781
782 int ldb_build_mod_req(struct ldb_request **ret_req,
783                         struct ldb_context *ldb,
784                         void *mem_ctx,
785                         const struct ldb_message *message,
786                         struct ldb_control **controls,
787                         void *context,
788                         ldb_request_callback_t callback,
789                         struct ldb_request *parent)
790 {
791         struct ldb_request *req;
792
793         *ret_req = NULL;
794
795         req = talloc(mem_ctx, struct ldb_request);
796         if (req == NULL) {
797                 ldb_set_errstring(ldb, "Out of Memory");
798                 return LDB_ERR_OPERATIONS_ERROR;
799         }
800
801         req->operation = LDB_MODIFY;
802         req->op.mod.message = message;
803         req->controls = controls;
804         req->context = context;
805         req->callback = callback;
806
807         ldb_set_timeout_from_prev_req(ldb, parent, req);
808
809         req->handle = ldb_handle_new(req, ldb);
810         if (req->handle == NULL) {
811                 ldb_oom(ldb);
812                 return LDB_ERR_OPERATIONS_ERROR;
813         }
814
815         *ret_req = req;
816
817         return LDB_SUCCESS;
818 }
819
820 int ldb_build_del_req(struct ldb_request **ret_req,
821                         struct ldb_context *ldb,
822                         void *mem_ctx,
823                         struct ldb_dn *dn,
824                         struct ldb_control **controls,
825                         void *context,
826                         ldb_request_callback_t callback,
827                         struct ldb_request *parent)
828 {
829         struct ldb_request *req;
830
831         *ret_req = NULL;
832
833         req = talloc(mem_ctx, struct ldb_request);
834         if (req == NULL) {
835                 ldb_set_errstring(ldb, "Out of Memory");
836                 return LDB_ERR_OPERATIONS_ERROR;
837         }
838
839         req->operation = LDB_DELETE;
840         req->op.del.dn = dn;
841         req->controls = controls;
842         req->context = context;
843         req->callback = callback;
844
845         ldb_set_timeout_from_prev_req(ldb, parent, req);
846
847         req->handle = ldb_handle_new(req, ldb);
848         if (req->handle == NULL) {
849                 ldb_oom(ldb);
850                 return LDB_ERR_OPERATIONS_ERROR;
851         }
852
853         *ret_req = req;
854
855         return LDB_SUCCESS;
856 }
857
858 int ldb_build_rename_req(struct ldb_request **ret_req,
859                         struct ldb_context *ldb,
860                         void *mem_ctx,
861                         struct ldb_dn *olddn,
862                         struct ldb_dn *newdn,
863                         struct ldb_control **controls,
864                         void *context,
865                         ldb_request_callback_t callback,
866                         struct ldb_request *parent)
867 {
868         struct ldb_request *req;
869
870         *ret_req = NULL;
871
872         req = talloc(mem_ctx, struct ldb_request);
873         if (req == NULL) {
874                 ldb_set_errstring(ldb, "Out of Memory");
875                 return LDB_ERR_OPERATIONS_ERROR;
876         }
877
878         req->operation = LDB_RENAME;
879         req->op.rename.olddn = olddn;
880         req->op.rename.newdn = newdn;
881         req->controls = controls;
882         req->context = context;
883         req->callback = callback;
884
885         ldb_set_timeout_from_prev_req(ldb, parent, req);
886
887         req->handle = ldb_handle_new(req, ldb);
888         if (req->handle == NULL) {
889                 ldb_oom(ldb);
890                 return LDB_ERR_OPERATIONS_ERROR;
891         }
892
893         *ret_req = req;
894
895         return LDB_SUCCESS;
896 }
897
898 int ldb_extended_default_callback(struct ldb_request *req,
899                                   struct ldb_reply *ares)
900 {
901         struct ldb_result *res;
902
903         res = talloc_get_type(req->context, struct ldb_result);
904
905         if (!ares) {
906                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
907         }
908         if (ares->error != LDB_SUCCESS) {
909                 return ldb_request_done(req, ares->error);
910         }
911
912         if (ares->type == LDB_REPLY_DONE) {
913
914                 /* TODO: we should really support controls on entries and referrals too! */
915                 res->extended = talloc_move(res, &ares->response);
916                 res->controls = talloc_move(res, &ares->controls);
917
918                 talloc_free(ares);
919                 return ldb_request_done(req, LDB_SUCCESS);
920         }
921
922         talloc_free(ares);
923         ldb_set_errstring(req->handle->ldb, "Invalid reply type!");
924         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
925 }
926
927 int ldb_build_extended_req(struct ldb_request **ret_req,
928                            struct ldb_context *ldb,
929                            void *mem_ctx,
930                            const char *oid,
931                            void *data,
932                            struct ldb_control **controls,
933                            void *context,
934                            ldb_request_callback_t callback,
935                            struct ldb_request *parent)
936 {
937         struct ldb_request *req;
938
939         *ret_req = NULL;
940
941         req = talloc(mem_ctx, struct ldb_request);
942         if (req == NULL) {
943                 ldb_set_errstring(ldb, "Out of Memory");
944                 return LDB_ERR_OPERATIONS_ERROR;
945         }
946
947         req->operation = LDB_EXTENDED;
948         req->op.extended.oid = oid;
949         req->op.extended.data = data;
950         req->controls = controls;
951         req->context = context;
952         req->callback = callback;
953
954         ldb_set_timeout_from_prev_req(ldb, parent, req);
955
956         req->handle = ldb_handle_new(req, ldb);
957         if (req->handle == NULL) {
958                 ldb_oom(ldb);
959                 return LDB_ERR_OPERATIONS_ERROR;
960         }
961
962         *ret_req = req;
963
964         return LDB_SUCCESS;
965 }
966
967 int ldb_extended(struct ldb_context *ldb,
968                  const char *oid,
969                  void *data,
970                  struct ldb_result **_res)
971 {
972         struct ldb_request *req;
973         int ret;
974         struct ldb_result *res;
975
976         *_res = NULL;
977
978         res = talloc_zero(ldb, struct ldb_result);
979         if (!res) {
980                 return LDB_ERR_OPERATIONS_ERROR;
981         }
982
983         ret = ldb_build_extended_req(&req, ldb, ldb,
984                                      oid, data, NULL,
985                                      res, ldb_extended_default_callback,
986                                      NULL);
987         if (ret != LDB_SUCCESS) goto done;
988
989         ldb_set_timeout(ldb, req, 0); /* use default timeout */
990
991         ret = ldb_request(ldb, req);
992
993         if (ret == LDB_SUCCESS) {
994                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
995         }
996
997         talloc_free(req);
998
999 done:
1000         if (ret != LDB_SUCCESS) {
1001                 talloc_free(res);
1002         }
1003
1004         *_res = res;
1005         return ret;
1006 }
1007
1008 /*
1009   note that ldb_search() will automatically replace a NULL 'base' value
1010   with the defaultNamingContext from the rootDSE if available.
1011 */
1012 int ldb_search(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1013                 struct ldb_result **result, struct ldb_dn *base,
1014                 enum ldb_scope scope, const char * const *attrs,
1015                 const char *exp_fmt, ...)
1016 {
1017         struct ldb_request *req;
1018         struct ldb_result *res;
1019         char *expression;
1020         va_list ap;
1021         int ret;
1022
1023         expression = NULL;
1024         *result = NULL;
1025         req = NULL;
1026
1027         res = talloc_zero(mem_ctx, struct ldb_result);
1028         if (!res) {
1029                 return LDB_ERR_OPERATIONS_ERROR;
1030         }
1031
1032         if (exp_fmt) {
1033                 va_start(ap, exp_fmt);
1034                 expression = talloc_vasprintf(mem_ctx, exp_fmt, ap);
1035                 va_end(ap);
1036
1037                 if (!expression) {
1038                         talloc_free(res);
1039                         return LDB_ERR_OPERATIONS_ERROR;
1040                 }
1041         }
1042
1043         ret = ldb_build_search_req(&req, ldb, mem_ctx,
1044                                         base?base:ldb_get_default_basedn(ldb),
1045                                         scope,
1046                                         expression,
1047                                         attrs,
1048                                         NULL,
1049                                         res,
1050                                         ldb_search_default_callback,
1051                                         NULL);
1052
1053         if (ret != LDB_SUCCESS) goto done;
1054
1055         ret = ldb_request(ldb, req);
1056
1057         if (ret == LDB_SUCCESS) {
1058                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1059         }
1060
1061 done:
1062         if (ret != LDB_SUCCESS) {
1063                 talloc_free(res);
1064                 res = NULL;
1065         }
1066
1067         talloc_free(expression);
1068         talloc_free(req);
1069
1070         *result = res;
1071         return ret;
1072 }
1073
1074 /*
1075   add a record to the database. Will fail if a record with the given class
1076   and key already exists
1077 */
1078 int ldb_add(struct ldb_context *ldb,
1079             const struct ldb_message *message)
1080 {
1081         struct ldb_request *req;
1082         int ret;
1083
1084         ret = ldb_msg_sanity_check(ldb, message);
1085         if (ret != LDB_SUCCESS) {
1086                 return ret;
1087         }
1088
1089         ret = ldb_build_add_req(&req, ldb, ldb,
1090                                         message,
1091                                         NULL,
1092                                         NULL,
1093                                         ldb_op_default_callback,
1094                                         NULL);
1095
1096         if (ret != LDB_SUCCESS) return ret;
1097
1098         /* do request and autostart a transaction */
1099         ret = ldb_autotransaction_request(ldb, req);
1100
1101         talloc_free(req);
1102         return ret;
1103 }
1104
1105 /*
1106   modify the specified attributes of a record
1107 */
1108 int ldb_modify(struct ldb_context *ldb,
1109                const struct ldb_message *message)
1110 {
1111         struct ldb_request *req;
1112         int ret;
1113
1114         ret = ldb_msg_sanity_check(ldb, message);
1115         if (ret != LDB_SUCCESS) {
1116                 return ret;
1117         }
1118
1119         ret = ldb_build_mod_req(&req, ldb, ldb,
1120                                         message,
1121                                         NULL,
1122                                         NULL,
1123                                         ldb_op_default_callback,
1124                                         NULL);
1125
1126         if (ret != LDB_SUCCESS) return ret;
1127
1128         /* do request and autostart a transaction */
1129         ret = ldb_autotransaction_request(ldb, req);
1130
1131         talloc_free(req);
1132         return ret;
1133 }
1134
1135
1136 /*
1137   delete a record from the database
1138 */
1139 int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn)
1140 {
1141         struct ldb_request *req;
1142         int ret;
1143
1144         ret = ldb_build_del_req(&req, ldb, ldb,
1145                                         dn,
1146                                         NULL,
1147                                         NULL,
1148                                         ldb_op_default_callback,
1149                                         NULL);
1150
1151         if (ret != LDB_SUCCESS) return ret;
1152
1153         /* do request and autostart a transaction */
1154         ret = ldb_autotransaction_request(ldb, req);
1155
1156         talloc_free(req);
1157         return ret;
1158 }
1159
1160 /*
1161   rename a record in the database
1162 */
1163 int ldb_rename(struct ldb_context *ldb,
1164                 struct ldb_dn *olddn, struct ldb_dn *newdn)
1165 {
1166         struct ldb_request *req;
1167         int ret;
1168
1169         ret = ldb_build_rename_req(&req, ldb, ldb,
1170                                         olddn,
1171                                         newdn,
1172                                         NULL,
1173                                         NULL,
1174                                         ldb_op_default_callback,
1175                                         NULL);
1176
1177         if (ret != LDB_SUCCESS) return ret;
1178
1179         /* do request and autostart a transaction */
1180         ret = ldb_autotransaction_request(ldb, req);
1181
1182         talloc_free(req);
1183         return ret;
1184 }
1185
1186
1187 /*
1188   return the global sequence number
1189 */
1190 int ldb_sequence_number(struct ldb_context *ldb,
1191                         enum ldb_sequence_type type, uint64_t *seq_num)
1192 {
1193         struct ldb_seqnum_request *seq;
1194         struct ldb_seqnum_result *seqr;
1195         struct ldb_result *res;
1196         TALLOC_CTX *tmp_ctx;
1197         int ret;
1198
1199         *seq_num = 0;
1200
1201         tmp_ctx = talloc_zero(ldb, struct ldb_request);
1202         if (tmp_ctx == NULL) {
1203                 ldb_set_errstring(ldb, "Out of Memory");
1204                 return LDB_ERR_OPERATIONS_ERROR;
1205         }
1206         seq = talloc_zero(tmp_ctx, struct ldb_seqnum_request);
1207         if (seq == NULL) {
1208                 ldb_set_errstring(ldb, "Out of Memory");
1209                 ret = LDB_ERR_OPERATIONS_ERROR;
1210                 goto done;
1211         }
1212         seq->type = type;
1213
1214         ret = ldb_extended(ldb, LDB_EXTENDED_SEQUENCE_NUMBER, seq, &res);
1215         if (ret != LDB_SUCCESS) {
1216                 goto done;
1217         }
1218         talloc_steal(tmp_ctx, res);
1219
1220         if (strcmp(LDB_EXTENDED_SEQUENCE_NUMBER, res->extended->oid) != 0) {
1221                 ldb_set_errstring(ldb, "Invalid OID in reply");
1222                 ret = LDB_ERR_OPERATIONS_ERROR;
1223                 goto done;
1224         }
1225         seqr = talloc_get_type(res->extended->data,
1226                                 struct ldb_seqnum_result);
1227         *seq_num = seqr->seq_num;
1228
1229 done:
1230         talloc_free(tmp_ctx);
1231         return ret;
1232 }
1233
1234 /*
1235   return extended error information
1236 */
1237 const char *ldb_errstring(struct ldb_context *ldb)
1238 {
1239         if (ldb->err_string) {
1240                 return ldb->err_string;
1241         }
1242
1243         return NULL;
1244 }
1245
1246 /*
1247   return a string explaining what a ldb error constant meancs
1248 */
1249 const char *ldb_strerror(int ldb_err)
1250 {
1251         switch (ldb_err) {
1252         case LDB_SUCCESS:
1253                 return "Success";
1254         case LDB_ERR_OPERATIONS_ERROR:
1255                 return "Operations error";
1256         case LDB_ERR_PROTOCOL_ERROR:
1257                 return "Protocol error";
1258         case LDB_ERR_TIME_LIMIT_EXCEEDED:
1259                 return "Time limit exceeded";
1260         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
1261                 return "Size limit exceeded";
1262         case LDB_ERR_COMPARE_FALSE:
1263                 return "Compare false";
1264         case LDB_ERR_COMPARE_TRUE:
1265                 return "Compare true";
1266         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
1267                 return "Auth method not supported";
1268         case LDB_ERR_STRONG_AUTH_REQUIRED:
1269                 return "Strong auth required";
1270 /* 9 RESERVED */
1271         case LDB_ERR_REFERRAL:
1272                 return "Referral error";
1273         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
1274                 return "Admin limit exceeded";
1275         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
1276                 return "Unsupported critical extension";
1277         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
1278                 return "Confidentiality required";
1279         case LDB_ERR_SASL_BIND_IN_PROGRESS:
1280                 return "SASL bind in progress";
1281         case LDB_ERR_NO_SUCH_ATTRIBUTE:
1282                 return "No such attribute";
1283         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
1284                 return "Undefined attribute type";
1285         case LDB_ERR_INAPPROPRIATE_MATCHING:
1286                 return "Inappropriate matching";
1287         case LDB_ERR_CONSTRAINT_VIOLATION:
1288                 return "Constraint violation";
1289         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
1290                 return "Attribute or value exists";
1291         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
1292                 return "Invalid attribute syntax";
1293 /* 22-31 unused */
1294         case LDB_ERR_NO_SUCH_OBJECT:
1295                 return "No such object";
1296         case LDB_ERR_ALIAS_PROBLEM:
1297                 return "Alias problem";
1298         case LDB_ERR_INVALID_DN_SYNTAX:
1299                 return "Invalid DN syntax";
1300 /* 35 RESERVED */
1301         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
1302                 return "Alias dereferencing problem";
1303 /* 37-47 unused */
1304         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
1305                 return "Inappropriate authentication";
1306         case LDB_ERR_INVALID_CREDENTIALS:
1307                 return "Invalid credentials";
1308         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
1309                 return "insufficient access rights";
1310         case LDB_ERR_BUSY:
1311                 return "Busy";
1312         case LDB_ERR_UNAVAILABLE:
1313                 return "Unavailable";
1314         case LDB_ERR_UNWILLING_TO_PERFORM:
1315                 return "Unwilling to perform";
1316         case LDB_ERR_LOOP_DETECT:
1317                 return "Loop detect";
1318 /* 55-63 unused */
1319         case LDB_ERR_NAMING_VIOLATION:
1320                 return "Naming violation";
1321         case LDB_ERR_OBJECT_CLASS_VIOLATION:
1322                 return "Object class violation";
1323         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
1324                 return "Not allowed on non-leaf";
1325         case LDB_ERR_NOT_ALLOWED_ON_RDN:
1326                 return "Not allowed on RDN";
1327         case LDB_ERR_ENTRY_ALREADY_EXISTS:
1328                 return "Entry already exists";
1329         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
1330                 return "Object class mods prohibited";
1331 /* 70 RESERVED FOR CLDAP */
1332         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
1333                 return "Affects multiple DSAs";
1334 /* 72-79 unused */
1335         case LDB_ERR_OTHER:
1336                 return "Other";
1337         }
1338
1339         return "Unknown error";
1340 }
1341
1342 /*
1343   set backend specific opaque parameters
1344 */
1345 int ldb_set_opaque(struct ldb_context *ldb, const char *name, void *value)
1346 {
1347         struct ldb_opaque *o;
1348
1349         /* allow updating an existing value */
1350         for (o=ldb->opaque;o;o=o->next) {
1351                 if (strcmp(o->name, name) == 0) {
1352                         o->value = value;
1353                         return LDB_SUCCESS;
1354                 }
1355         }
1356
1357         o = talloc(ldb, struct ldb_opaque);
1358         if (o == NULL) {
1359                 ldb_oom(ldb);
1360                 return LDB_ERR_OTHER;
1361         }
1362         o->next = ldb->opaque;
1363         o->name = name;
1364         o->value = value;
1365         ldb->opaque = o;
1366         return LDB_SUCCESS;
1367 }
1368
1369 /*
1370   get a previously set opaque value
1371 */
1372 void *ldb_get_opaque(struct ldb_context *ldb, const char *name)
1373 {
1374         struct ldb_opaque *o;
1375         for (o=ldb->opaque;o;o=o->next) {
1376                 if (strcmp(o->name, name) == 0) {
1377                         return o->value;
1378                 }
1379         }
1380         return NULL;
1381 }