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