ldb: Add ldb_set_require_private_event_context()
[samba.git] / 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 #define TEVENT_DEPRECATED 1
36 #include "ldb_private.h"
37 #include "ldb.h"
38
39 static int ldb_context_destructor(void *ptr)
40 {
41         struct ldb_context *ldb = talloc_get_type(ptr, struct ldb_context);
42
43         if (ldb->transaction_active) {
44                 ldb_debug(ldb, LDB_DEBUG_FATAL,
45                           "A transaction is still active in ldb context [%p] on %s",
46                           ldb, (const char *)ldb_get_opaque(ldb, "ldb_url"));
47         }
48
49         return 0;
50 }
51
52 /*
53   this is used to catch debug messages from events
54 */
55 static void ldb_tevent_debug(void *context, enum tevent_debug_level level,
56                              const char *fmt, va_list ap)  PRINTF_ATTRIBUTE(3,0);
57
58 static void ldb_tevent_debug(void *context, enum tevent_debug_level level,
59                              const char *fmt, va_list ap)
60 {
61         struct ldb_context *ldb = talloc_get_type(context, struct ldb_context);
62         enum ldb_debug_level ldb_level = LDB_DEBUG_FATAL;
63
64         switch (level) {
65         case TEVENT_DEBUG_FATAL:
66                 ldb_level = LDB_DEBUG_FATAL;
67                 break;
68         case TEVENT_DEBUG_ERROR:
69                 ldb_level = LDB_DEBUG_ERROR;
70                 break;
71         case TEVENT_DEBUG_WARNING:
72                 ldb_level = LDB_DEBUG_WARNING;
73                 break;
74         case TEVENT_DEBUG_TRACE:
75                 ldb_level = LDB_DEBUG_TRACE;
76                 break;
77         };
78
79         /* There isn't a tevent: prefix here because to add it means
80          * actually printing the string, and most of the time we don't
81          * want to show it */
82         ldb_vdebug(ldb, ldb_level, fmt, ap);
83 }
84
85 /*
86    initialise a ldb context
87    The mem_ctx is required
88    The event_ctx is required
89 */
90 struct ldb_context *ldb_init(TALLOC_CTX *mem_ctx, struct tevent_context *ev_ctx)
91 {
92         struct ldb_context *ldb;
93         int ret;
94         const char *modules_path = getenv("LDB_MODULES_PATH");
95
96         if (modules_path == NULL) {
97                 modules_path = LDB_MODULESDIR;
98         }
99
100         ret = ldb_modules_load(modules_path, LDB_VERSION);
101         if (ret != LDB_SUCCESS) {
102                 return NULL;
103         }
104
105         ldb = talloc_zero(mem_ctx, struct ldb_context);
106         if (ldb == NULL) {
107                 return NULL;
108         }
109
110         /* A new event context so that callers who don't want ldb
111          * operating on thier global event context can work without
112          * having to provide their own private one explicitly */
113         if (ev_ctx == NULL) {
114                 ev_ctx = tevent_context_init(ldb);
115                 if (ev_ctx == NULL) {
116                         talloc_free(ldb);
117                         return NULL;
118                 }
119                 tevent_set_debug(ev_ctx, ldb_tevent_debug, ldb);
120                 tevent_loop_allow_nesting(ev_ctx);
121         }
122
123         ret = ldb_setup_wellknown_attributes(ldb);
124         if (ret != LDB_SUCCESS) {
125                 talloc_free(ldb);
126                 return NULL;
127         }
128
129         ldb_set_utf8_default(ldb);
130         ldb_set_create_perms(ldb, 0666);
131         ldb_set_modules_dir(ldb, LDB_MODULESDIR);
132         ldb_set_event_context(ldb, ev_ctx);
133         ret = ldb_register_extended_match_rules(ldb);
134         if (ret != LDB_SUCCESS) {
135                 talloc_free(ldb);
136                 return NULL;
137         }
138
139         /* TODO: get timeout from options if available there */
140         ldb->default_timeout = 300; /* set default to 5 minutes */
141
142         talloc_set_destructor((TALLOC_CTX *)ldb, ldb_context_destructor);
143
144         return ldb;
145 }
146
147 /*
148   try to autodetect a basedn if none specified. This fixes one of my
149   pet hates about ldapsearch, which is that you have to get a long,
150   complex basedn right to make any use of it.
151 */
152 void ldb_set_default_dns(struct ldb_context *ldb)
153 {
154         TALLOC_CTX *tmp_ctx;
155         int ret;
156         struct ldb_result *res;
157         struct ldb_dn *tmp_dn=NULL;
158         static const char *attrs[] = {
159                 "rootDomainNamingContext",
160                 "configurationNamingContext",
161                 "schemaNamingContext",
162                 "defaultNamingContext",
163                 NULL
164         };
165
166         tmp_ctx = talloc_new(ldb);
167         ret = ldb_search(ldb, tmp_ctx, &res, ldb_dn_new(tmp_ctx, ldb, NULL),
168                          LDB_SCOPE_BASE, attrs, "(objectClass=*)");
169         if (ret != LDB_SUCCESS) {
170                 talloc_free(tmp_ctx);
171                 return;
172         }
173
174         if (res->count != 1) {
175                 talloc_free(tmp_ctx);
176                 return;
177         }
178
179         if (!ldb_get_opaque(ldb, "rootDomainNamingContext")) {
180                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
181                                                  "rootDomainNamingContext");
182                 ldb_set_opaque(ldb, "rootDomainNamingContext", tmp_dn);
183         }
184
185         if (!ldb_get_opaque(ldb, "configurationNamingContext")) {
186                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
187                                                  "configurationNamingContext");
188                 ldb_set_opaque(ldb, "configurationNamingContext", tmp_dn);
189         }
190
191         if (!ldb_get_opaque(ldb, "schemaNamingContext")) {
192                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
193                                                  "schemaNamingContext");
194                 ldb_set_opaque(ldb, "schemaNamingContext", tmp_dn);
195         }
196
197         if (!ldb_get_opaque(ldb, "defaultNamingContext")) {
198                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0],
199                                                  "defaultNamingContext");
200                 ldb_set_opaque(ldb, "defaultNamingContext", tmp_dn);
201         }
202
203         talloc_free(tmp_ctx);
204 }
205
206 struct ldb_dn *ldb_get_root_basedn(struct ldb_context *ldb)
207 {
208         void *opaque = ldb_get_opaque(ldb, "rootDomainNamingContext");
209         return talloc_get_type(opaque, struct ldb_dn);
210 }
211
212 struct ldb_dn *ldb_get_config_basedn(struct ldb_context *ldb)
213 {
214         void *opaque = ldb_get_opaque(ldb, "configurationNamingContext");
215         return talloc_get_type(opaque, struct ldb_dn);
216 }
217
218 struct ldb_dn *ldb_get_schema_basedn(struct ldb_context *ldb)
219 {
220         void *opaque = ldb_get_opaque(ldb, "schemaNamingContext");
221         return talloc_get_type(opaque, struct ldb_dn);
222 }
223
224 struct ldb_dn *ldb_get_default_basedn(struct ldb_context *ldb)
225 {
226         void *opaque = ldb_get_opaque(ldb, "defaultNamingContext");
227         return talloc_get_type(opaque, struct ldb_dn);
228 }
229
230 /*
231    connect to a database. The URL can either be one of the following forms
232    ldb://path
233    ldapi://path
234
235    flags is made up of LDB_FLG_*
236
237    the options are passed uninterpreted to the backend, and are
238    backend specific
239 */
240 int ldb_connect(struct ldb_context *ldb, const char *url,
241                 unsigned int flags, const char *options[])
242 {
243         int ret;
244         char *url2;
245         /* We seem to need to do this here, or else some utilities don't
246          * get ldb backends */
247
248         ldb->flags = flags;
249
250         url2 = talloc_strdup(ldb, url);
251         if (!url2) {
252                 ldb_oom(ldb);
253                 return LDB_ERR_OPERATIONS_ERROR;
254         }
255         ret = ldb_set_opaque(ldb, "ldb_url", url2);
256         if (ret != LDB_SUCCESS) {
257                 return ret;
258         }
259
260         ret = ldb_module_connect_backend(ldb, url, options, &ldb->modules);
261         if (ret != LDB_SUCCESS) {
262                 return ret;
263         }
264
265         ret = ldb_load_modules(ldb, options);
266         if (ret != LDB_SUCCESS) {
267                 ldb_debug(ldb, LDB_DEBUG_FATAL,
268                           "Unable to load modules for %s: %s",
269                           url, ldb_errstring(ldb));
270                 return ret;
271         }
272
273         /* set the default base dn */
274         ldb_set_default_dns(ldb);
275
276         return LDB_SUCCESS;
277 }
278
279 void ldb_set_errstring(struct ldb_context *ldb, const char *err_string)
280 {
281         ldb_asprintf_errstring(ldb, "%s", err_string);
282 }
283
284 void ldb_asprintf_errstring(struct ldb_context *ldb, const char *format, ...)
285 {
286         va_list ap;
287         char *old_err_string = NULL;
288         if (ldb->err_string) {
289                 old_err_string = ldb->err_string;
290         }
291
292         va_start(ap, format);
293         ldb->err_string = talloc_vasprintf(ldb, format, ap);
294         va_end(ap);
295
296         TALLOC_FREE(old_err_string);
297         
298         if (ldb->flags & LDB_FLG_ENABLE_TRACING) {
299                 ldb_debug(ldb, LDB_DEBUG_TRACE, "ldb_asprintf/set_errstring: %s",
300                           ldb->err_string);
301         }
302 }
303
304 void ldb_reset_err_string(struct ldb_context *ldb)
305 {
306         if (ldb->err_string) {
307                 talloc_free(ldb->err_string);
308                 ldb->err_string = NULL;
309         }
310 }
311
312
313
314 /*
315   set an ldb error based on file:line
316 */
317 int ldb_error_at(struct ldb_context *ldb, int ecode,
318                  const char *reason, const char *file, int line)
319 {
320         if (reason == NULL) {
321                 reason = ldb_strerror(ecode);
322         }
323         ldb_asprintf_errstring(ldb, "%s at %s:%d", reason, file, line);
324         return ecode;
325 }
326
327
328 #define FIRST_OP_NOERR(ldb, op) do { \
329         module = ldb->modules;                                  \
330         while (module && module->ops->op == NULL) module = module->next; \
331         if ((ldb->flags & LDB_FLG_ENABLE_TRACING) && module) { \
332                 ldb_debug(ldb, LDB_DEBUG_TRACE, "ldb_trace_request: (%s)->" #op, \
333                           module->ops->name);                           \
334         }                                                               \
335 } while (0)
336
337 #define FIRST_OP(ldb, op) do { \
338         FIRST_OP_NOERR(ldb, op); \
339         if (module == NULL) {                                   \
340                 ldb_asprintf_errstring(ldb, "unable to find module or backend to handle operation: " #op); \
341                 return LDB_ERR_OPERATIONS_ERROR;                        \
342         } \
343 } while (0)
344
345
346 /*
347   start a transaction
348 */
349 int ldb_transaction_start(struct ldb_context *ldb)
350 {
351         struct ldb_module *module;
352         int status;
353
354         ldb_debug(ldb, LDB_DEBUG_TRACE,
355                   "start ldb transaction (nesting: %d)",
356                   ldb->transaction_active);
357
358         /* explicit transaction active, count nested requests */
359         if (ldb->transaction_active) {
360                 ldb->transaction_active++;
361                 return LDB_SUCCESS;
362         }
363
364         /* start a new transaction */
365         ldb->transaction_active++;
366         ldb->prepare_commit_done = false;
367
368         FIRST_OP(ldb, start_transaction);
369
370         ldb_reset_err_string(ldb);
371
372         status = module->ops->start_transaction(module);
373         if (status != LDB_SUCCESS) {
374                 if (ldb->err_string == NULL) {
375                         /* no error string was setup by the backend */
376                         ldb_asprintf_errstring(ldb,
377                                 "ldb transaction start: %s (%d)",
378                                 ldb_strerror(status),
379                                 status);
380                 }
381                 if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) {
382                         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "start ldb transaction error: %s",
383                                   ldb_errstring(module->ldb));
384                 }
385         } else {
386                 if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) {
387                         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "start ldb transaction success");
388                 }
389         }
390         return status;
391 }
392
393 /*
394   prepare for transaction commit (first phase of two phase commit)
395 */
396 int ldb_transaction_prepare_commit(struct ldb_context *ldb)
397 {
398         struct ldb_module *module;
399         int status;
400
401         if (ldb->prepare_commit_done) {
402                 return LDB_SUCCESS;
403         }
404
405         /* commit only when all nested transactions are complete */
406         if (ldb->transaction_active > 1) {
407                 return LDB_SUCCESS;
408         }
409
410         ldb->prepare_commit_done = true;
411
412         if (ldb->transaction_active < 0) {
413                 ldb_debug(ldb, LDB_DEBUG_FATAL,
414                           "prepare commit called but no ldb transactions are active!");
415                 ldb->transaction_active = 0;
416                 return LDB_ERR_OPERATIONS_ERROR;
417         }
418
419         /* call prepare transaction if available */
420         FIRST_OP_NOERR(ldb, prepare_commit);
421         if (module == NULL) {
422                 return LDB_SUCCESS;
423         }
424
425         status = module->ops->prepare_commit(module);
426         if (status != LDB_SUCCESS) {
427                 ldb->transaction_active--;
428                 /* if a module fails the prepare then we need
429                    to call the end transaction for everyone */
430                 FIRST_OP(ldb, del_transaction);
431                 module->ops->del_transaction(module);
432                 if (ldb->err_string == NULL) {
433                         /* no error string was setup by the backend */
434                         ldb_asprintf_errstring(ldb,
435                                                "ldb transaction prepare commit: %s (%d)",
436                                                ldb_strerror(status),
437                                                status);
438                 }
439                 if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) { 
440                         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "prepare commit transaction error: %s", 
441                                   ldb_errstring(module->ldb));                          
442                 }
443         }
444
445         return status;
446 }
447
448
449 /*
450   commit a transaction
451 */
452 int ldb_transaction_commit(struct ldb_context *ldb)
453 {
454         struct ldb_module *module;
455         int status;
456
457         status = ldb_transaction_prepare_commit(ldb);
458         if (status != LDB_SUCCESS) {
459                 return status;
460         }
461
462         ldb->transaction_active--;
463
464         ldb_debug(ldb, LDB_DEBUG_TRACE,
465                   "commit ldb transaction (nesting: %d)",
466                   ldb->transaction_active);
467
468         /* commit only when all nested transactions are complete */
469         if (ldb->transaction_active > 0) {
470                 return LDB_SUCCESS;
471         }
472
473         if (ldb->transaction_active < 0) {
474                 ldb_debug(ldb, LDB_DEBUG_FATAL,
475                           "commit called but no ldb transactions are active!");
476                 ldb->transaction_active = 0;
477                 return LDB_ERR_OPERATIONS_ERROR;
478         }
479
480         ldb_reset_err_string(ldb);
481
482         FIRST_OP(ldb, end_transaction);
483         status = module->ops->end_transaction(module);
484         if (status != LDB_SUCCESS) {
485                 if (ldb->err_string == NULL) {
486                         /* no error string was setup by the backend */
487                         ldb_asprintf_errstring(ldb,
488                                 "ldb transaction commit: %s (%d)",
489                                 ldb_strerror(status),
490                                 status);
491                 }
492                 if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) { 
493                         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "commit ldb transaction error: %s", 
494                                   ldb_errstring(module->ldb));                          
495                 }
496                 /* cancel the transaction */
497                 FIRST_OP(ldb, del_transaction);
498                 module->ops->del_transaction(module);
499         }
500         return status;
501 }
502
503
504 /*
505   cancel a transaction
506 */
507 int ldb_transaction_cancel(struct ldb_context *ldb)
508 {
509         struct ldb_module *module;
510         int status;
511
512         ldb->transaction_active--;
513
514         ldb_debug(ldb, LDB_DEBUG_TRACE,
515                   "cancel ldb transaction (nesting: %d)",
516                   ldb->transaction_active);
517
518         /* really cancel only if all nested transactions are complete */
519         if (ldb->transaction_active > 0) {
520                 return LDB_SUCCESS;
521         }
522
523         if (ldb->transaction_active < 0) {
524                 ldb_debug(ldb, LDB_DEBUG_FATAL,
525                           "cancel called but no ldb transactions are active!");
526                 ldb->transaction_active = 0;
527                 return LDB_ERR_OPERATIONS_ERROR;
528         }
529
530         FIRST_OP(ldb, del_transaction);
531
532         status = module->ops->del_transaction(module);
533         if (status != LDB_SUCCESS) {
534                 if (ldb->err_string == NULL) {
535                         /* no error string was setup by the backend */
536                         ldb_asprintf_errstring(ldb,
537                                 "ldb transaction cancel: %s (%d)",
538                                 ldb_strerror(status),
539                                 status);
540                 }
541                 if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) { 
542                         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "cancel ldb transaction error: %s", 
543                                   ldb_errstring(module->ldb));                          
544                 }
545         }
546         return status;
547 }
548
549 /*
550   cancel a transaction with no error if no transaction is pending
551   used when we fork() to clear any parent transactions
552 */
553 int ldb_transaction_cancel_noerr(struct ldb_context *ldb)
554 {
555         if (ldb->transaction_active > 0) {
556                 return ldb_transaction_cancel(ldb);
557         }
558         return LDB_SUCCESS;
559 }
560
561
562 /* autostarts a transaction if none active */
563 static int ldb_autotransaction_request(struct ldb_context *ldb,
564                                        struct ldb_request *req)
565 {
566         int ret;
567
568         ret = ldb_transaction_start(ldb);
569         if (ret != LDB_SUCCESS) {
570                 return ret;
571         }
572
573         ret = ldb_request(ldb, req);
574         if (ret == LDB_SUCCESS) {
575                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
576         }
577
578         if (ret == LDB_SUCCESS) {
579                 return ldb_transaction_commit(ldb);
580         }
581         ldb_transaction_cancel(ldb);
582
583         return ret;
584 }
585
586 int ldb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
587 {
588         struct tevent_context *ev;
589         int ret;
590
591         if (handle == NULL) {
592                 return LDB_ERR_UNAVAILABLE;
593         }
594
595         if (handle->state == LDB_ASYNC_DONE) {
596                 if ((handle->status != LDB_SUCCESS) &&
597                     (handle->ldb->err_string == NULL)) {
598                         /* if no error string was setup by the backend */
599                         ldb_asprintf_errstring(handle->ldb,
600                                                "ldb_wait from %s with LDB_ASYNC_DONE: %s (%d)",
601                                                handle->location,
602                                                ldb_strerror(handle->status),
603                                                handle->status);
604                 }
605                 return handle->status;
606         }
607
608         ev = ldb_get_event_context(handle->ldb);
609         if (NULL == ev) {
610                 return ldb_oom(handle->ldb);
611         }
612
613         switch (type) {
614         case LDB_WAIT_NONE:
615                 ret = tevent_loop_once(ev);
616                 if (ret != 0) {
617                         return ldb_operr(handle->ldb);
618                 }
619                 if (handle->status == LDB_SUCCESS) {
620                         return LDB_SUCCESS;
621                 }
622                 if (handle->ldb->err_string != NULL) {
623                         return handle->status;
624                 }
625                 /*
626                  * if no error string was setup by the backend
627                  */
628                 ldb_asprintf_errstring(handle->ldb,
629                                        "ldb_wait from %s with LDB_WAIT_NONE: %s (%d)",
630                                        handle->location,
631                                        ldb_strerror(handle->status),
632                                        handle->status);
633                 return handle->status;
634
635         case LDB_WAIT_ALL:
636                 while (handle->state != LDB_ASYNC_DONE) {
637                         ret = tevent_loop_once(ev);
638                         if (ret != 0) {
639                                 return ldb_operr(handle->ldb);
640                         }
641                         if (handle->status != LDB_SUCCESS) {
642                                 if (handle->ldb->err_string != NULL) {
643                                         return handle->status;
644                                 }
645                                 /*
646                                  * if no error string was setup by the
647                                  * backend
648                                  */
649                                 ldb_asprintf_errstring(handle->ldb,
650                                                        "ldb_wait from %s with "
651                                                        "LDB_WAIT_ALL: %s (%d)",
652                                                        handle->location,
653                                                        ldb_strerror(handle->status),
654                                                        handle->status);
655                                 return handle->status;
656                         }
657                 }
658                 if (handle->status == LDB_SUCCESS) {
659                         return LDB_SUCCESS;
660                 }
661                 if (handle->ldb->err_string != NULL) {
662                         return handle->status;
663                 }
664                 /*
665                  * if no error string was setup by the backend
666                  */
667                 ldb_asprintf_errstring(handle->ldb,
668                                        "ldb_wait from %s with LDB_WAIT_ALL,"
669                                        " LDB_ASYNC_DONE: %s (%d)",
670                                        handle->location,
671                                        ldb_strerror(handle->status),
672                                        handle->status);
673                 return handle->status;
674         }
675
676         return LDB_SUCCESS;
677 }
678
679 /* set the specified timeout or, if timeout is 0 set the default timeout */
680 int ldb_set_timeout(struct ldb_context *ldb,
681                     struct ldb_request *req,
682                     int timeout)
683 {
684         if (req == NULL) return LDB_ERR_OPERATIONS_ERROR;
685
686         if (timeout != 0) {
687                 req->timeout = timeout;
688         } else {
689                 req->timeout = ldb->default_timeout;
690         }
691         req->starttime = time(NULL);
692
693         return LDB_SUCCESS;
694 }
695
696 /* calculates the new timeout based on the previous starttime and timeout */
697 int ldb_set_timeout_from_prev_req(struct ldb_context *ldb,
698                                   struct ldb_request *oldreq,
699                                   struct ldb_request *newreq)
700 {
701         if (newreq == NULL) return LDB_ERR_OPERATIONS_ERROR;
702
703         if (oldreq == NULL) {
704                 return ldb_set_timeout(ldb, newreq, 0);
705         }
706
707         newreq->starttime = oldreq->starttime;
708         newreq->timeout = oldreq->timeout;
709
710         return LDB_SUCCESS;
711 }
712
713
714 /*
715    set the permissions for new files to be passed to open() in
716    backends that use local files
717  */
718 void ldb_set_create_perms(struct ldb_context *ldb, unsigned int perms)
719 {
720         ldb->create_perms = perms;
721 }
722
723 unsigned int ldb_get_create_perms(struct ldb_context *ldb)
724 {
725         return ldb->create_perms;
726 }
727
728 void ldb_set_event_context(struct ldb_context *ldb, struct tevent_context *ev)
729 {
730         ldb->ev_ctx = ev;
731 }
732
733 struct tevent_context * ldb_get_event_context(struct ldb_context *ldb)
734 {
735         return ldb->ev_ctx;
736 }
737
738 void ldb_request_set_state(struct ldb_request *req, int state)
739 {
740         req->handle->state = state;
741 }
742
743 int ldb_request_get_status(struct ldb_request *req)
744 {
745         return req->handle->status;
746 }
747
748 /*
749  * This function obtains the private event context for the handle,
750  * which may have been created to avoid nested event loops during
751  * ldb_tdb with the locks held
752  */
753 struct tevent_context *ldb_handle_get_event_context(struct ldb_handle *handle)
754 {
755         if (handle->event_context != NULL) {
756                 return handle->event_context;
757         }
758         return ldb_get_event_context(handle->ldb);
759 }
760
761 void ldb_set_require_private_event_context(struct ldb_context *ldb)
762 {
763         ldb->require_private_event_context = true;
764 }
765
766 /*
767   trace a ldb request
768 */
769 static void ldb_trace_request(struct ldb_context *ldb, struct ldb_request *req)
770 {
771         TALLOC_CTX *tmp_ctx = talloc_new(req);
772         unsigned int i;
773         struct ldb_ldif ldif;
774
775         switch (req->operation) {
776         case LDB_SEARCH:
777                 ldb_debug_add(ldb, "ldb_trace_request: SEARCH\n");
778                 ldb_debug_add(ldb, " dn: %s\n",
779                               ldb_dn_is_null(req->op.search.base)?"<rootDSE>":
780                               ldb_dn_get_linearized(req->op.search.base));
781                 ldb_debug_add(ldb, " scope: %s\n", 
782                           req->op.search.scope==LDB_SCOPE_BASE?"base":
783                           req->op.search.scope==LDB_SCOPE_ONELEVEL?"one":
784                           req->op.search.scope==LDB_SCOPE_SUBTREE?"sub":"UNKNOWN");
785                 ldb_debug_add(ldb, " expr: %s\n", 
786                           ldb_filter_from_tree(tmp_ctx, req->op.search.tree));
787                 if (req->op.search.attrs == NULL) {
788                         ldb_debug_add(ldb, " attr: <ALL>\n");
789                 } else {
790                         for (i=0; req->op.search.attrs[i]; i++) {
791                                 ldb_debug_add(ldb, " attr: %s\n", req->op.search.attrs[i]);
792                         }
793                 }
794                 break;
795         case LDB_DELETE:
796                 ldb_debug_add(ldb, "ldb_trace_request: DELETE\n");
797                 ldb_debug_add(ldb, " dn: %s\n", 
798                               ldb_dn_get_linearized(req->op.del.dn));
799                 break;
800         case LDB_RENAME:
801                 ldb_debug_add(ldb, "ldb_trace_request: RENAME\n");
802                 ldb_debug_add(ldb, " olddn: %s\n", 
803                               ldb_dn_get_linearized(req->op.rename.olddn));
804                 ldb_debug_add(ldb, " newdn: %s\n", 
805                               ldb_dn_get_linearized(req->op.rename.newdn));
806                 break;
807         case LDB_EXTENDED:
808                 ldb_debug_add(ldb, "ldb_trace_request: EXTENDED\n");
809                 ldb_debug_add(ldb, " oid: %s\n", req->op.extended.oid);
810                 ldb_debug_add(ldb, " data: %s\n", req->op.extended.data?"yes":"no");
811                 break;
812         case LDB_ADD:
813                 ldif.changetype = LDB_CHANGETYPE_ADD;
814                 ldif.msg = discard_const_p(struct ldb_message, req->op.add.message);
815
816                 ldb_debug_add(ldb, "ldb_trace_request: ADD\n");
817
818                 /* 
819                  * The choice to call
820                  * ldb_ldif_write_redacted_trace_string() is CRITICAL
821                  * for security.  It ensures that we do not output
822                  * passwords into debug logs 
823                  */
824
825                 ldb_debug_add(req->handle->ldb, "%s\n", 
826                               ldb_ldif_write_redacted_trace_string(req->handle->ldb, tmp_ctx, &ldif));
827                 break;
828         case LDB_MODIFY:
829                 ldif.changetype = LDB_CHANGETYPE_MODIFY;
830                 ldif.msg = discard_const_p(struct ldb_message, req->op.mod.message);
831
832                 ldb_debug_add(ldb, "ldb_trace_request: MODIFY\n");
833
834                 /* 
835                  * The choice to call
836                  * ldb_ldif_write_redacted_trace_string() is CRITICAL
837                  * for security.  It ensures that we do not output
838                  * passwords into debug logs 
839                  */
840
841                 ldb_debug_add(req->handle->ldb, "%s\n", 
842                               ldb_ldif_write_redacted_trace_string(req->handle->ldb, tmp_ctx, &ldif));
843                 break;
844         case LDB_REQ_REGISTER_CONTROL:
845                 ldb_debug_add(ldb, "ldb_trace_request: REGISTER_CONTROL\n");
846                 ldb_debug_add(req->handle->ldb, "%s\n", 
847                               req->op.reg_control.oid);
848                 break;
849         case LDB_REQ_REGISTER_PARTITION:
850                 ldb_debug_add(ldb, "ldb_trace_request: REGISTER_PARTITION\n");
851                 ldb_debug_add(req->handle->ldb, "%s\n", 
852                               ldb_dn_get_linearized(req->op.reg_partition.dn));
853                 break;
854         default:
855                 ldb_debug_add(ldb, "ldb_trace_request: UNKNOWN(%u)\n", 
856                               req->operation);
857                 break;
858         }
859
860         if (req->controls == NULL) {
861                 ldb_debug_add(ldb, " control: <NONE>\n");
862         } else {
863                 for (i=0; req->controls && req->controls[i]; i++) {
864                         if (req->controls[i]->oid) {
865                                 ldb_debug_add(ldb, " control: %s  crit:%u  data:%s\n",
866                                               req->controls[i]->oid,
867                                               req->controls[i]->critical,
868                                               req->controls[i]->data?"yes":"no");
869                         }
870                 }
871         }
872         
873         ldb_debug_end(ldb, LDB_DEBUG_TRACE);
874
875         talloc_free(tmp_ctx);
876 }
877
878 /*
879   check that the element flags don't have any internal bits set
880  */
881 static int ldb_msg_check_element_flags(struct ldb_context *ldb,
882                                        const struct ldb_message *message)
883 {
884         unsigned i;
885         for (i=0; i<message->num_elements; i++) {
886                 if (message->elements[i].flags & LDB_FLAG_INTERNAL_MASK) {
887                         ldb_asprintf_errstring(ldb, "Invalid element flags 0x%08x on element %s in %s\n",
888                                                message->elements[i].flags, message->elements[i].name,
889                                                ldb_dn_get_linearized(message->dn));
890                         return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
891                 }
892         }
893         return LDB_SUCCESS;
894 }
895
896
897 /*
898   start an ldb request
899   NOTE: the request must be a talloc context.
900   returns LDB_ERR_* on errors.
901 */
902 int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
903 {
904         struct ldb_module *module;
905         int ret;
906
907         if (req->callback == NULL) {
908                 ldb_set_errstring(ldb, "Requests MUST define callbacks");
909                 return LDB_ERR_UNWILLING_TO_PERFORM;
910         }
911
912         ldb_reset_err_string(ldb);
913
914         if (ldb->flags & LDB_FLG_ENABLE_TRACING) {
915                 ldb_trace_request(ldb, req);
916         }
917
918         /* call the first module in the chain */
919         switch (req->operation) {
920         case LDB_SEARCH:
921                 /* due to "ldb_build_search_req" base DN always != NULL */
922                 if (!ldb_dn_validate(req->op.search.base)) {
923                         ldb_asprintf_errstring(ldb, "ldb_search: invalid basedn '%s'",
924                                                ldb_dn_get_linearized(req->op.search.base));
925                         return LDB_ERR_INVALID_DN_SYNTAX;
926                 }
927                 FIRST_OP(ldb, search);
928                 ret = module->ops->search(module, req);
929                 break;
930         case LDB_ADD:
931                 if (!ldb_dn_validate(req->op.add.message->dn)) {
932                         ldb_asprintf_errstring(ldb, "ldb_add: invalid dn '%s'",
933                                                ldb_dn_get_linearized(req->op.add.message->dn));
934                         return LDB_ERR_INVALID_DN_SYNTAX;
935                 }
936                 /*
937                  * we have to normalize here, as so many places
938                  * in modules and backends assume we don't have two
939                  * elements with the same name
940                  */
941                 ret = ldb_msg_normalize(ldb, req, req->op.add.message,
942                                         discard_const(&req->op.add.message));
943                 if (ret != LDB_SUCCESS) {
944                         ldb_oom(ldb);
945                         return ret;
946                 }
947                 FIRST_OP(ldb, add);
948                 ret = ldb_msg_check_element_flags(ldb, req->op.add.message);
949                 if (ret != LDB_SUCCESS) {
950                         /*
951                          * "ldb_msg_check_element_flags" generates an error
952                          * string
953                          */
954                         return ret;
955                 }
956                 ret = module->ops->add(module, req);
957                 break;
958         case LDB_MODIFY:
959                 if (!ldb_dn_validate(req->op.mod.message->dn)) {
960                         ldb_asprintf_errstring(ldb, "ldb_modify: invalid dn '%s'",
961                                                ldb_dn_get_linearized(req->op.mod.message->dn));
962                         return LDB_ERR_INVALID_DN_SYNTAX;
963                 }
964                 FIRST_OP(ldb, modify);
965                 ret = ldb_msg_check_element_flags(ldb, req->op.mod.message);
966                 if (ret != LDB_SUCCESS) {
967                         /*
968                          * "ldb_msg_check_element_flags" generates an error
969                          * string
970                          */
971                         return ret;
972                 }
973                 ret = module->ops->modify(module, req);
974                 break;
975         case LDB_DELETE:
976                 if (!ldb_dn_validate(req->op.del.dn)) {
977                         ldb_asprintf_errstring(ldb, "ldb_delete: invalid dn '%s'",
978                                                ldb_dn_get_linearized(req->op.del.dn));
979                         return LDB_ERR_INVALID_DN_SYNTAX;
980                 }
981                 FIRST_OP(ldb, del);
982                 ret = module->ops->del(module, req);
983                 break;
984         case LDB_RENAME:
985                 if (!ldb_dn_validate(req->op.rename.olddn)) {
986                         ldb_asprintf_errstring(ldb, "ldb_rename: invalid olddn '%s'",
987                                                ldb_dn_get_linearized(req->op.rename.olddn));
988                         return LDB_ERR_INVALID_DN_SYNTAX;
989                 }
990                 if (!ldb_dn_validate(req->op.rename.newdn)) {
991                         ldb_asprintf_errstring(ldb, "ldb_rename: invalid newdn '%s'",
992                                                ldb_dn_get_linearized(req->op.rename.newdn));
993                         return LDB_ERR_INVALID_DN_SYNTAX;
994                 }
995                 FIRST_OP(ldb, rename);
996                 ret = module->ops->rename(module, req);
997                 break;
998         case LDB_EXTENDED:
999                 FIRST_OP(ldb, extended);
1000                 ret = module->ops->extended(module, req);
1001                 break;
1002         default:
1003                 FIRST_OP(ldb, request);
1004                 ret = module->ops->request(module, req);
1005                 break;
1006         }
1007
1008         if ((ret != LDB_SUCCESS) && (ldb->err_string == NULL)) {
1009                 /* if no error string was setup by the backend */
1010                 ldb_asprintf_errstring(ldb, "ldb_request: %s (%d)",
1011                                        ldb_strerror(ret), ret);
1012         }
1013
1014         return ret;
1015 }
1016
1017 int ldb_request_done(struct ldb_request *req, int status)
1018 {
1019         req->handle->state = LDB_ASYNC_DONE;
1020         req->handle->status = status;
1021         return status;
1022 }
1023
1024 /*
1025   search the database given a LDAP-like search expression
1026
1027   returns an LDB error code
1028
1029   Use talloc_free to free the ldb_message returned in 'res', if successful
1030
1031 */
1032 int ldb_search_default_callback(struct ldb_request *req,
1033                                 struct ldb_reply *ares)
1034 {
1035         struct ldb_result *res;
1036         unsigned int n;
1037
1038         res = talloc_get_type(req->context, struct ldb_result);
1039
1040         if (!ares) {
1041                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1042         }
1043         if (ares->error != LDB_SUCCESS) {
1044                 return ldb_request_done(req, ares->error);
1045         }
1046
1047         switch (ares->type) {
1048         case LDB_REPLY_ENTRY:
1049                 res->msgs = talloc_realloc(res, res->msgs,
1050                                         struct ldb_message *, res->count + 2);
1051                 if (! res->msgs) {
1052                         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1053                 }
1054
1055                 res->msgs[res->count + 1] = NULL;
1056
1057                 res->msgs[res->count] = talloc_move(res->msgs, &ares->message);
1058                 res->count++;
1059                 break;
1060
1061         case LDB_REPLY_REFERRAL:
1062                 if (res->refs) {
1063                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
1064                 } else {
1065                         n = 0;
1066                 }
1067
1068                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
1069                 if (! res->refs) {
1070                         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1071                 }
1072
1073                 res->refs[n] = talloc_move(res->refs, &ares->referral);
1074                 res->refs[n + 1] = NULL;
1075                 break;
1076
1077         case LDB_REPLY_DONE:
1078                 /* TODO: we should really support controls on entries
1079                  * and referrals too! */
1080                 res->controls = talloc_move(res, &ares->controls);
1081
1082                 /* this is the last message, and means the request is done */
1083                 /* we have to signal and eventual ldb_wait() waiting that the
1084                  * async request operation was completed */
1085                 talloc_free(ares);
1086                 return ldb_request_done(req, LDB_SUCCESS);
1087         }
1088
1089         talloc_free(ares);
1090
1091         return LDB_SUCCESS;
1092 }
1093
1094 int ldb_modify_default_callback(struct ldb_request *req, struct ldb_reply *ares)
1095 {
1096         struct ldb_result *res;
1097         unsigned int n;
1098         int ret;
1099
1100         res = talloc_get_type(req->context, struct ldb_result);
1101
1102         if (!ares) {
1103                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1104         }
1105
1106         if (ares->error != LDB_SUCCESS) {
1107                 ret = ares->error;
1108                 talloc_free(ares);
1109                 return ldb_request_done(req, ret);
1110         }
1111
1112         switch (ares->type) {
1113         case LDB_REPLY_REFERRAL:
1114                 if (res->refs) {
1115                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
1116                 } else {
1117                         n = 0;
1118                 }
1119
1120                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
1121                 if (! res->refs) {
1122                         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1123                 }
1124
1125                 res->refs[n] = talloc_move(res->refs, &ares->referral);
1126                 res->refs[n + 1] = NULL;
1127                 break;
1128
1129         case LDB_REPLY_DONE:
1130                 talloc_free(ares);
1131                 return ldb_request_done(req, LDB_SUCCESS);
1132         default:
1133                 talloc_free(ares);
1134                 ldb_asprintf_errstring(req->handle->ldb, "Invalid LDB reply type %d", ares->type);
1135                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1136         }
1137
1138         talloc_free(ares);
1139         return ldb_request_done(req, LDB_SUCCESS);
1140 }
1141
1142 int ldb_op_default_callback(struct ldb_request *req, struct ldb_reply *ares)
1143 {
1144         int ret;
1145
1146         if (!ares) {
1147                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1148         }
1149
1150         if (ares->error != LDB_SUCCESS) {
1151                 ret = ares->error;
1152                 talloc_free(ares);
1153                 return ldb_request_done(req, ret);
1154         }
1155
1156         if (ares->type != LDB_REPLY_DONE) {
1157                 talloc_free(ares);
1158                 ldb_asprintf_errstring(req->handle->ldb, "Invalid LDB reply type %d", ares->type);
1159                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1160         }
1161
1162         talloc_free(ares);
1163         return ldb_request_done(req, LDB_SUCCESS);
1164 }
1165
1166 static struct ldb_request *ldb_build_req_common(TALLOC_CTX *mem_ctx,
1167                                 struct ldb_context *ldb,
1168                                 struct ldb_control **controls,
1169                                 void *context,
1170                                 ldb_request_callback_t callback,
1171                                 struct ldb_request *parent)
1172 {
1173         struct ldb_request *req = NULL;
1174
1175         req = talloc_zero(mem_ctx, struct ldb_request);
1176         if (req == NULL) {
1177                 return NULL;
1178         }
1179         req->controls = controls;
1180         req->context = context;
1181         req->callback = callback;
1182
1183         ldb_set_timeout_from_prev_req(ldb, parent, req);
1184
1185         req->handle = ldb_handle_new(req, ldb);
1186         if (req->handle == NULL) {
1187                 TALLOC_FREE(req);
1188                 return NULL;
1189         }
1190
1191         if (parent != NULL) {
1192                 req->handle->nesting++;
1193                 req->handle->parent = parent;
1194                 req->handle->flags = parent->handle->flags;
1195                 req->handle->custom_flags = parent->handle->custom_flags;
1196         }
1197
1198         return req;
1199 }
1200
1201 int ldb_build_search_req_ex(struct ldb_request **ret_req,
1202                         struct ldb_context *ldb,
1203                         TALLOC_CTX *mem_ctx,
1204                         struct ldb_dn *base,
1205                         enum ldb_scope scope,
1206                         struct ldb_parse_tree *tree,
1207                         const char * const *attrs,
1208                         struct ldb_control **controls,
1209                         void *context,
1210                         ldb_request_callback_t callback,
1211                         struct ldb_request *parent)
1212 {
1213         struct ldb_request *req;
1214
1215         *ret_req = NULL;
1216
1217         req = ldb_build_req_common(mem_ctx, ldb, controls,
1218                                    context, callback, parent);
1219         if (req == NULL) {
1220                 ldb_oom(ldb);
1221                 return LDB_ERR_OPERATIONS_ERROR;
1222         }
1223
1224         req->operation = LDB_SEARCH;
1225         if (base == NULL) {
1226                 req->op.search.base = ldb_dn_new(req, ldb, NULL);
1227         } else {
1228                 req->op.search.base = base;
1229         }
1230         req->op.search.scope = scope;
1231
1232         req->op.search.tree = tree;
1233         if (req->op.search.tree == NULL) {
1234                 ldb_set_errstring(ldb, "'tree' can't be NULL");
1235                 talloc_free(req);
1236                 return LDB_ERR_OPERATIONS_ERROR;
1237         }
1238
1239         req->op.search.attrs = attrs;
1240         *ret_req = req;
1241         return LDB_SUCCESS;
1242 }
1243
1244 int ldb_build_search_req(struct ldb_request **ret_req,
1245                         struct ldb_context *ldb,
1246                         TALLOC_CTX *mem_ctx,
1247                         struct ldb_dn *base,
1248                         enum ldb_scope scope,
1249                         const char *expression,
1250                         const char * const *attrs,
1251                         struct ldb_control **controls,
1252                         void *context,
1253                         ldb_request_callback_t callback,
1254                         struct ldb_request *parent)
1255 {
1256         struct ldb_parse_tree *tree;
1257         int ret;
1258
1259         tree = ldb_parse_tree(mem_ctx, expression);
1260         if (tree == NULL) {
1261                 ldb_set_errstring(ldb, "Unable to parse search expression");
1262                 return LDB_ERR_OPERATIONS_ERROR;
1263         }
1264
1265         ret = ldb_build_search_req_ex(ret_req, ldb, mem_ctx, base,
1266                                       scope, tree, attrs, controls,
1267                                       context, callback, parent);
1268         if (ret == LDB_SUCCESS) {
1269                 talloc_steal(*ret_req, tree);
1270         }
1271         return ret;
1272 }
1273
1274 int ldb_build_add_req(struct ldb_request **ret_req,
1275                         struct ldb_context *ldb,
1276                         TALLOC_CTX *mem_ctx,
1277                         const struct ldb_message *message,
1278                         struct ldb_control **controls,
1279                         void *context,
1280                         ldb_request_callback_t callback,
1281                         struct ldb_request *parent)
1282 {
1283         struct ldb_request *req;
1284
1285         *ret_req = NULL;
1286
1287         req = ldb_build_req_common(mem_ctx, ldb, controls,
1288                                    context, callback, parent);
1289         if (req == NULL) {
1290                 ldb_set_errstring(ldb, "Out of Memory");
1291                 return LDB_ERR_OPERATIONS_ERROR;
1292         }
1293
1294         req->operation = LDB_ADD;
1295         req->op.add.message = message;
1296         *ret_req = req;
1297         return LDB_SUCCESS;
1298 }
1299
1300 int ldb_build_mod_req(struct ldb_request **ret_req,
1301                         struct ldb_context *ldb,
1302                         TALLOC_CTX *mem_ctx,
1303                         const struct ldb_message *message,
1304                         struct ldb_control **controls,
1305                         void *context,
1306                         ldb_request_callback_t callback,
1307                         struct ldb_request *parent)
1308 {
1309         struct ldb_request *req;
1310
1311         *ret_req = NULL;
1312
1313         req = ldb_build_req_common(mem_ctx, ldb, controls,
1314                                    context, callback, parent);
1315         if (req == NULL) {
1316                 ldb_set_errstring(ldb, "Out of Memory");
1317                 return LDB_ERR_OPERATIONS_ERROR;
1318         }
1319
1320         req->operation = LDB_MODIFY;
1321         req->op.mod.message = message;
1322
1323         *ret_req = req;
1324         return LDB_SUCCESS;
1325 }
1326
1327 int ldb_build_del_req(struct ldb_request **ret_req,
1328                         struct ldb_context *ldb,
1329                         TALLOC_CTX *mem_ctx,
1330                         struct ldb_dn *dn,
1331                         struct ldb_control **controls,
1332                         void *context,
1333                         ldb_request_callback_t callback,
1334                         struct ldb_request *parent)
1335 {
1336         struct ldb_request *req;
1337
1338         *ret_req = NULL;
1339
1340         req = ldb_build_req_common(mem_ctx, ldb, controls,
1341                                    context, callback, parent);
1342         if (req == NULL) {
1343                 ldb_set_errstring(ldb, "Out of Memory");
1344                 return LDB_ERR_OPERATIONS_ERROR;
1345         }
1346
1347         req->operation = LDB_DELETE;
1348         req->op.del.dn = dn;
1349         *ret_req = req;
1350         return LDB_SUCCESS;
1351 }
1352
1353 int ldb_build_rename_req(struct ldb_request **ret_req,
1354                         struct ldb_context *ldb,
1355                         TALLOC_CTX *mem_ctx,
1356                         struct ldb_dn *olddn,
1357                         struct ldb_dn *newdn,
1358                         struct ldb_control **controls,
1359                         void *context,
1360                         ldb_request_callback_t callback,
1361                         struct ldb_request *parent)
1362 {
1363         struct ldb_request *req;
1364
1365         *ret_req = NULL;
1366
1367         req = ldb_build_req_common(mem_ctx, ldb, controls,
1368                                    context, callback, parent);
1369         if (req == NULL) {
1370                 ldb_set_errstring(ldb, "Out of Memory");
1371                 return LDB_ERR_OPERATIONS_ERROR;
1372         }
1373
1374         req->operation = LDB_RENAME;
1375         req->op.rename.olddn = olddn;
1376         req->op.rename.newdn = newdn;
1377         *ret_req = req;
1378         return LDB_SUCCESS;
1379 }
1380
1381 int ldb_extended_default_callback(struct ldb_request *req,
1382                                   struct ldb_reply *ares)
1383 {
1384         struct ldb_result *res;
1385
1386         res = talloc_get_type(req->context, struct ldb_result);
1387
1388         if (!ares) {
1389                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1390         }
1391         if (ares->error != LDB_SUCCESS) {
1392                 return ldb_request_done(req, ares->error);
1393         }
1394
1395         if (ares->type == LDB_REPLY_DONE) {
1396
1397                 /* TODO: we should really support controls on entries and referrals too! */
1398                 res->extended = talloc_move(res, &ares->response);
1399                 res->controls = talloc_move(res, &ares->controls);
1400
1401                 talloc_free(ares);
1402                 return ldb_request_done(req, LDB_SUCCESS);
1403         }
1404
1405         talloc_free(ares);
1406         ldb_asprintf_errstring(req->handle->ldb, "Invalid LDB reply type %d", ares->type);
1407         return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1408 }
1409
1410 int ldb_build_extended_req(struct ldb_request **ret_req,
1411                            struct ldb_context *ldb,
1412                            TALLOC_CTX *mem_ctx,
1413                            const char *oid,
1414                            void *data,
1415                            struct ldb_control **controls,
1416                            void *context,
1417                            ldb_request_callback_t callback,
1418                            struct ldb_request *parent)
1419 {
1420         struct ldb_request *req;
1421
1422         *ret_req = NULL;
1423
1424         req = ldb_build_req_common(mem_ctx, ldb, controls,
1425                                    context, callback, parent);
1426         if (req == NULL) {
1427                 ldb_set_errstring(ldb, "Out of Memory");
1428                 return LDB_ERR_OPERATIONS_ERROR;
1429         }
1430
1431         req->operation = LDB_EXTENDED;
1432         req->op.extended.oid = oid;
1433         req->op.extended.data = data;
1434         *ret_req = req;
1435         return LDB_SUCCESS;
1436 }
1437
1438 int ldb_extended(struct ldb_context *ldb,
1439                  const char *oid,
1440                  void *data,
1441                  struct ldb_result **_res)
1442 {
1443         struct ldb_request *req;
1444         int ret;
1445         struct ldb_result *res;
1446
1447         *_res = NULL;
1448         req = NULL;
1449
1450         res = talloc_zero(ldb, struct ldb_result);
1451         if (!res) {
1452                 return LDB_ERR_OPERATIONS_ERROR;
1453         }
1454
1455         ret = ldb_build_extended_req(&req, ldb, ldb,
1456                                      oid, data, NULL,
1457                                      res, ldb_extended_default_callback,
1458                                      NULL);
1459         ldb_req_set_location(req, "ldb_extended");
1460
1461         if (ret != LDB_SUCCESS) goto done;
1462
1463         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1464
1465         ret = ldb_request(ldb, req);
1466
1467         if (ret == LDB_SUCCESS) {
1468                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1469         }
1470
1471 done:
1472         if (ret != LDB_SUCCESS) {
1473                 talloc_free(res);
1474                 res = NULL;
1475         }
1476
1477         talloc_free(req);
1478
1479         *_res = res;
1480         return ret;
1481 }
1482
1483 /*
1484   note that ldb_search() will automatically replace a NULL 'base' value
1485   with the defaultNamingContext from the rootDSE if available.
1486 */
1487 int ldb_search(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1488                 struct ldb_result **result, struct ldb_dn *base,
1489                 enum ldb_scope scope, const char * const *attrs,
1490                 const char *exp_fmt, ...)
1491 {
1492         struct ldb_request *req;
1493         struct ldb_result *res;
1494         char *expression;
1495         va_list ap;
1496         int ret;
1497
1498         expression = NULL;
1499         *result = NULL;
1500         req = NULL;
1501
1502         res = talloc_zero(mem_ctx, struct ldb_result);
1503         if (!res) {
1504                 return LDB_ERR_OPERATIONS_ERROR;
1505         }
1506
1507         if (exp_fmt) {
1508                 va_start(ap, exp_fmt);
1509                 expression = talloc_vasprintf(mem_ctx, exp_fmt, ap);
1510                 va_end(ap);
1511
1512                 if (!expression) {
1513                         talloc_free(res);
1514                         return LDB_ERR_OPERATIONS_ERROR;
1515                 }
1516         }
1517
1518         ret = ldb_build_search_req(&req, ldb, mem_ctx,
1519                                         base?base:ldb_get_default_basedn(ldb),
1520                                         scope,
1521                                         expression,
1522                                         attrs,
1523                                         NULL,
1524                                         res,
1525                                         ldb_search_default_callback,
1526                                         NULL);
1527         ldb_req_set_location(req, "ldb_search");
1528
1529         if (ret != LDB_SUCCESS) goto done;
1530
1531         ret = ldb_request(ldb, req);
1532
1533         if (ret == LDB_SUCCESS) {
1534                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1535         }
1536
1537 done:
1538         if (ret != LDB_SUCCESS) {
1539                 talloc_free(res);
1540                 res = NULL;
1541         }
1542
1543         talloc_free(expression);
1544         talloc_free(req);
1545
1546         *result = res;
1547         return ret;
1548 }
1549
1550 /*
1551   add a record to the database. Will fail if a record with the given class
1552   and key already exists
1553 */
1554 int ldb_add(struct ldb_context *ldb,
1555             const struct ldb_message *message)
1556 {
1557         struct ldb_request *req;
1558         int ret;
1559
1560         ret = ldb_msg_sanity_check(ldb, message);
1561         if (ret != LDB_SUCCESS) {
1562                 return ret;
1563         }
1564
1565         ret = ldb_build_add_req(&req, ldb, ldb,
1566                                         message,
1567                                         NULL,
1568                                         NULL,
1569                                         ldb_op_default_callback,
1570                                         NULL);
1571         ldb_req_set_location(req, "ldb_add");
1572
1573         if (ret != LDB_SUCCESS) return ret;
1574
1575         /* do request and autostart a transaction */
1576         ret = ldb_autotransaction_request(ldb, req);
1577
1578         talloc_free(req);
1579         return ret;
1580 }
1581
1582 /*
1583   modify the specified attributes of a record
1584 */
1585 int ldb_modify(struct ldb_context *ldb,
1586                const struct ldb_message *message)
1587 {
1588         struct ldb_request *req;
1589         int ret;
1590
1591         ret = ldb_msg_sanity_check(ldb, message);
1592         if (ret != LDB_SUCCESS) {
1593                 return ret;
1594         }
1595
1596         ret = ldb_build_mod_req(&req, ldb, ldb,
1597                                         message,
1598                                         NULL,
1599                                         NULL,
1600                                         ldb_op_default_callback,
1601                                         NULL);
1602         ldb_req_set_location(req, "ldb_modify");
1603
1604         if (ret != LDB_SUCCESS) return ret;
1605
1606         /* do request and autostart a transaction */
1607         ret = ldb_autotransaction_request(ldb, req);
1608
1609         talloc_free(req);
1610         return ret;
1611 }
1612
1613
1614 /*
1615   delete a record from the database
1616 */
1617 int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn)
1618 {
1619         struct ldb_request *req;
1620         int ret;
1621
1622         ret = ldb_build_del_req(&req, ldb, ldb,
1623                                         dn,
1624                                         NULL,
1625                                         NULL,
1626                                         ldb_op_default_callback,
1627                                         NULL);
1628         ldb_req_set_location(req, "ldb_delete");
1629
1630         if (ret != LDB_SUCCESS) return ret;
1631
1632         /* do request and autostart a transaction */
1633         ret = ldb_autotransaction_request(ldb, req);
1634
1635         talloc_free(req);
1636         return ret;
1637 }
1638
1639 /*
1640   rename a record in the database
1641 */
1642 int ldb_rename(struct ldb_context *ldb,
1643                 struct ldb_dn *olddn, struct ldb_dn *newdn)
1644 {
1645         struct ldb_request *req;
1646         int ret;
1647
1648         ret = ldb_build_rename_req(&req, ldb, ldb,
1649                                         olddn,
1650                                         newdn,
1651                                         NULL,
1652                                         NULL,
1653                                         ldb_op_default_callback,
1654                                         NULL);
1655         ldb_req_set_location(req, "ldb_rename");
1656
1657         if (ret != LDB_SUCCESS) return ret;
1658
1659         /* do request and autostart a transaction */
1660         ret = ldb_autotransaction_request(ldb, req);
1661
1662         talloc_free(req);
1663         return ret;
1664 }
1665
1666
1667 /*
1668   return the global sequence number
1669 */
1670 int ldb_sequence_number(struct ldb_context *ldb,
1671                         enum ldb_sequence_type type, uint64_t *seq_num)
1672 {
1673         struct ldb_seqnum_request *seq;
1674         struct ldb_seqnum_result *seqr;
1675         struct ldb_result *res;
1676         TALLOC_CTX *tmp_ctx;
1677         int ret;
1678
1679         *seq_num = 0;
1680
1681         tmp_ctx = talloc_zero(ldb, struct ldb_request);
1682         if (tmp_ctx == NULL) {
1683                 ldb_set_errstring(ldb, "Out of Memory");
1684                 return LDB_ERR_OPERATIONS_ERROR;
1685         }
1686         seq = talloc_zero(tmp_ctx, struct ldb_seqnum_request);
1687         if (seq == NULL) {
1688                 ldb_set_errstring(ldb, "Out of Memory");
1689                 ret = LDB_ERR_OPERATIONS_ERROR;
1690                 goto done;
1691         }
1692         seq->type = type;
1693
1694         ret = ldb_extended(ldb, LDB_EXTENDED_SEQUENCE_NUMBER, seq, &res);
1695         if (ret != LDB_SUCCESS) {
1696                 goto done;
1697         }
1698         talloc_steal(tmp_ctx, res);
1699
1700         if (strcmp(LDB_EXTENDED_SEQUENCE_NUMBER, res->extended->oid) != 0) {
1701                 ldb_set_errstring(ldb, "Invalid OID in reply");
1702                 ret = LDB_ERR_OPERATIONS_ERROR;
1703                 goto done;
1704         }
1705         seqr = talloc_get_type(res->extended->data,
1706                                 struct ldb_seqnum_result);
1707         *seq_num = seqr->seq_num;
1708
1709 done:
1710         talloc_free(tmp_ctx);
1711         return ret;
1712 }
1713
1714 /*
1715   return extended error information
1716 */
1717 const char *ldb_errstring(struct ldb_context *ldb)
1718 {
1719         if (ldb->err_string) {
1720                 return ldb->err_string;
1721         }
1722
1723         return NULL;
1724 }
1725
1726 /*
1727   return a string explaining what a ldb error constant meancs
1728 */
1729 const char *ldb_strerror(int ldb_err)
1730 {
1731         switch (ldb_err) {
1732         case LDB_SUCCESS:
1733                 return "Success";
1734         case LDB_ERR_OPERATIONS_ERROR:
1735                 return "Operations error";
1736         case LDB_ERR_PROTOCOL_ERROR:
1737                 return "Protocol error";
1738         case LDB_ERR_TIME_LIMIT_EXCEEDED:
1739                 return "Time limit exceeded";
1740         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
1741                 return "Size limit exceeded";
1742         case LDB_ERR_COMPARE_FALSE:
1743                 return "Compare false";
1744         case LDB_ERR_COMPARE_TRUE:
1745                 return "Compare true";
1746         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
1747                 return "Auth method not supported";
1748         case LDB_ERR_STRONG_AUTH_REQUIRED:
1749                 return "Strong auth required";
1750 /* 9 RESERVED */
1751         case LDB_ERR_REFERRAL:
1752                 return "Referral error";
1753         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
1754                 return "Admin limit exceeded";
1755         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
1756                 return "Unsupported critical extension";
1757         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
1758                 return "Confidentiality required";
1759         case LDB_ERR_SASL_BIND_IN_PROGRESS:
1760                 return "SASL bind in progress";
1761         case LDB_ERR_NO_SUCH_ATTRIBUTE:
1762                 return "No such attribute";
1763         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
1764                 return "Undefined attribute type";
1765         case LDB_ERR_INAPPROPRIATE_MATCHING:
1766                 return "Inappropriate matching";
1767         case LDB_ERR_CONSTRAINT_VIOLATION:
1768                 return "Constraint violation";
1769         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
1770                 return "Attribute or value exists";
1771         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
1772                 return "Invalid attribute syntax";
1773 /* 22-31 unused */
1774         case LDB_ERR_NO_SUCH_OBJECT:
1775                 return "No such object";
1776         case LDB_ERR_ALIAS_PROBLEM:
1777                 return "Alias problem";
1778         case LDB_ERR_INVALID_DN_SYNTAX:
1779                 return "Invalid DN syntax";
1780 /* 35 RESERVED */
1781         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
1782                 return "Alias dereferencing problem";
1783 /* 37-47 unused */
1784         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
1785                 return "Inappropriate authentication";
1786         case LDB_ERR_INVALID_CREDENTIALS:
1787                 return "Invalid credentials";
1788         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
1789                 return "insufficient access rights";
1790         case LDB_ERR_BUSY:
1791                 return "Busy";
1792         case LDB_ERR_UNAVAILABLE:
1793                 return "Unavailable";
1794         case LDB_ERR_UNWILLING_TO_PERFORM:
1795                 return "Unwilling to perform";
1796         case LDB_ERR_LOOP_DETECT:
1797                 return "Loop detect";
1798 /* 55-63 unused */
1799         case LDB_ERR_NAMING_VIOLATION:
1800                 return "Naming violation";
1801         case LDB_ERR_OBJECT_CLASS_VIOLATION:
1802                 return "Object class violation";
1803         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
1804                 return "Not allowed on non-leaf";
1805         case LDB_ERR_NOT_ALLOWED_ON_RDN:
1806                 return "Not allowed on RDN";
1807         case LDB_ERR_ENTRY_ALREADY_EXISTS:
1808                 return "Entry already exists";
1809         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
1810                 return "Object class mods prohibited";
1811 /* 70 RESERVED FOR CLDAP */
1812         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
1813                 return "Affects multiple DSAs";
1814 /* 72-79 unused */
1815         case LDB_ERR_OTHER:
1816                 return "Other";
1817         }
1818
1819         return "Unknown error";
1820 }
1821
1822 /*
1823   set backend specific opaque parameters
1824 */
1825 int ldb_set_opaque(struct ldb_context *ldb, const char *name, void *value)
1826 {
1827         struct ldb_opaque *o;
1828
1829         /* allow updating an existing value */
1830         for (o=ldb->opaque;o;o=o->next) {
1831                 if (strcmp(o->name, name) == 0) {
1832                         o->value = value;
1833                         return LDB_SUCCESS;
1834                 }
1835         }
1836
1837         o = talloc(ldb, struct ldb_opaque);
1838         if (o == NULL) {
1839                 ldb_oom(ldb);
1840                 return LDB_ERR_OTHER;
1841         }
1842         o->next = ldb->opaque;
1843         o->name = name;
1844         o->value = value;
1845         ldb->opaque = o;
1846         return LDB_SUCCESS;
1847 }
1848
1849 /*
1850   get a previously set opaque value
1851 */
1852 void *ldb_get_opaque(struct ldb_context *ldb, const char *name)
1853 {
1854         struct ldb_opaque *o;
1855         for (o=ldb->opaque;o;o=o->next) {
1856                 if (strcmp(o->name, name) == 0) {
1857                         return o->value;
1858                 }
1859         }
1860         return NULL;
1861 }
1862
1863 int ldb_global_init(void)
1864 {
1865         /* Provided for compatibility with some older versions of ldb */
1866         return 0;
1867 }
1868
1869 /* return the ldb flags */
1870 unsigned int ldb_get_flags(struct ldb_context *ldb)
1871 {
1872         return ldb->flags;
1873 }
1874
1875 /* set the ldb flags */
1876 void ldb_set_flags(struct ldb_context *ldb, unsigned flags)
1877 {
1878         ldb->flags = flags;
1879 }
1880
1881
1882 /*
1883   set the location in a ldb request. Used for debugging
1884  */
1885 void ldb_req_set_location(struct ldb_request *req, const char *location)
1886 {
1887         if (req && req->handle) {
1888                 req->handle->location = location;
1889         }
1890 }
1891
1892 /*
1893   return the location set with dsdb_req_set_location
1894  */
1895 const char *ldb_req_location(struct ldb_request *req)
1896 {
1897         return req->handle->location;
1898 }
1899
1900 /**
1901   mark a request as untrusted. This tells the rootdse module to remove
1902   unregistered controls
1903  */
1904 void ldb_req_mark_untrusted(struct ldb_request *req)
1905 {
1906         req->handle->flags |= LDB_HANDLE_FLAG_UNTRUSTED;
1907 }
1908
1909 /**
1910   mark a request as trusted.
1911  */
1912 void ldb_req_mark_trusted(struct ldb_request *req)
1913 {
1914         req->handle->flags &= ~LDB_HANDLE_FLAG_UNTRUSTED;
1915 }
1916
1917 /**
1918   set custom flags. Those flags are set by applications using ldb,
1919   they are application dependent and the same bit can have different
1920   meaning in different application.
1921  */
1922 void ldb_req_set_custom_flags(struct ldb_request *req, uint32_t flags)
1923 {
1924         if (req != NULL && req->handle != NULL) {
1925                 req->handle->custom_flags = flags;
1926         }
1927 }
1928
1929
1930 /**
1931   get custom flags. Those flags are set by applications using ldb,
1932   they are application dependent and the same bit can have different
1933   meaning in different application.
1934  */
1935 uint32_t ldb_req_get_custom_flags(struct ldb_request *req)
1936 {
1937         if (req != NULL && req->handle != NULL) {
1938                 return req->handle->custom_flags;
1939         }
1940
1941         /*
1942          * 0 is not something any better or worse than
1943          * anything else as req or the handle is NULL
1944          */
1945         return 0;
1946 }
1947
1948
1949 /**
1950  * return true if a request is untrusted
1951  */
1952 bool ldb_req_is_untrusted(struct ldb_request *req)
1953 {
1954         return (req->handle->flags & LDB_HANDLE_FLAG_UNTRUSTED) != 0;
1955 }