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