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