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