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