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