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