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