ldb: make ldb a top level library for Samba 4.0
[gd/samba-autobuild/.git] / lib / ldb / common / ldb_modules.c
1 /*
2    ldb database library
3
4    Copyright (C) Simo Sorce  2004-2008
5
6      ** NOTE! The following LGPL license applies to the ldb
7      ** library. This does NOT imply that all of Samba is released
8      ** under the LGPL
9
10    This library is free software; you can redistribute it and/or
11    modify it under the terms of the GNU Lesser General Public
12    License as published by the Free Software Foundation; either
13    version 3 of the License, or (at your option) any later version.
14
15    This library is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    Lesser General Public License for more details.
19
20    You should have received a copy of the GNU Lesser General Public
21    License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 */
23
24 /*
25  *  Name: ldb
26  *
27  *  Component: ldb modules core
28  *
29  *  Description: core modules routines
30  *
31  *  Author: Simo Sorce
32  */
33
34 #include "ldb_private.h"
35 #include "dlinklist.h"
36 #include "system/dir.h"
37
38 static char *ldb_modules_strdup_no_spaces(TALLOC_CTX *mem_ctx, const char *string)
39 {
40         size_t i, len;
41         char *trimmed;
42
43         trimmed = talloc_strdup(mem_ctx, string);
44         if (!trimmed) {
45                 return NULL;
46         }
47
48         len = strlen(trimmed);
49         for (i = 0; trimmed[i] != '\0'; i++) {
50                 switch (trimmed[i]) {
51                 case ' ':
52                 case '\t':
53                 case '\n':
54                         memmove(&trimmed[i], &trimmed[i + 1], len -i -1);
55                         break;
56                 }
57         }
58
59         return trimmed;
60 }
61
62
63 /* modules are called in inverse order on the stack.
64    Lets place them as an admin would think the right order is.
65    Modules order is important */
66 const char **ldb_modules_list_from_string(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *string)
67 {
68         char **modules = NULL;
69         const char **m;
70         char *modstr, *p;
71         unsigned int i;
72
73         /* spaces not admitted */
74         modstr = ldb_modules_strdup_no_spaces(mem_ctx, string);
75         if ( ! modstr) {
76                 ldb_debug(ldb, LDB_DEBUG_FATAL, "Out of Memory in ldb_modules_strdup_no_spaces()");
77                 return NULL;
78         }
79
80         modules = talloc_realloc(mem_ctx, modules, char *, 2);
81         if ( ! modules ) {
82                 ldb_debug(ldb, LDB_DEBUG_FATAL, "Out of Memory in ldb_modules_list_from_string()");
83                 talloc_free(modstr);
84                 return NULL;
85         }
86         talloc_steal(modules, modstr);
87
88         if (modstr[0] == '\0') {
89                 modules[0] = NULL;
90                 m = (const char **)modules;
91                 return m;
92         }
93
94         i = 0;
95         /* The str*r*chr walks backwards:  This is how we get the inverse order mentioned above */
96         while ((p = strrchr(modstr, ',')) != NULL) {
97                 *p = '\0';
98                 p++;
99                 modules[i] = p;
100
101                 i++;
102                 modules = talloc_realloc(mem_ctx, modules, char *, i + 2);
103                 if ( ! modules ) {
104                         ldb_debug(ldb, LDB_DEBUG_FATAL, "Out of Memory in ldb_modules_list_from_string()");
105                         return NULL;
106                 }
107
108         }
109         modules[i] = modstr;
110
111         modules[i + 1] = NULL;
112
113         m = (const char **)modules;
114
115         return m;
116 }
117
118 static struct backends_list_entry {
119         struct ldb_backend_ops *ops;
120         struct backends_list_entry *prev, *next;
121 } *ldb_backends = NULL;
122
123 static struct ops_list_entry {
124         const struct ldb_module_ops *ops;
125         struct ops_list_entry *next;
126 } *registered_modules = NULL;
127
128 static struct backends_list_entry *ldb_find_backend(const char *url_prefix)
129 {
130         struct backends_list_entry *backend;
131
132         for (backend = ldb_backends; backend; backend = backend->next) {
133                 if (strcmp(backend->ops->name, url_prefix) == 0) {
134                         return backend;
135                 }
136         }
137
138         return NULL;
139 }
140
141 /*
142   register a new ldb backend
143
144   if override is true, then override any existing backend for this prefix
145 */
146 int ldb_register_backend(const char *url_prefix, ldb_connect_fn connectfn, bool override)
147 {
148         struct backends_list_entry *be;
149
150         be = ldb_find_backend(url_prefix);
151         if (be) {
152                 if (!override) {
153                         return LDB_SUCCESS;
154                 }
155         } else {
156                 be = talloc_zero(ldb_backends, struct backends_list_entry);
157                 if (!be) {
158                         return LDB_ERR_OPERATIONS_ERROR;
159                 }
160                 be->ops = talloc_zero(be, struct ldb_backend_ops);
161                 if (!be->ops) {
162                         talloc_free(be);
163                         return LDB_ERR_OPERATIONS_ERROR;
164                 }
165                 DLIST_ADD_END(ldb_backends, be, struct backends_list_entry);
166         }
167
168         be->ops->name = url_prefix;
169         be->ops->connect_fn = connectfn;
170
171         return LDB_SUCCESS;
172 }
173
174 /*
175    Return the ldb module form of a database.
176    The URL can either be one of the following forms
177    ldb://path
178    ldapi://path
179
180    flags is made up of LDB_FLG_*
181
182    the options are passed uninterpreted to the backend, and are
183    backend specific.
184
185    This allows modules to get at only the backend module, for example where a
186    module may wish to direct certain requests at a particular backend.
187 */
188 int ldb_module_connect_backend(struct ldb_context *ldb,
189                                const char *url,
190                                const char *options[],
191                                struct ldb_module **backend_module)
192 {
193         int ret;
194         char *backend;
195         struct backends_list_entry *be;
196
197         if (strchr(url, ':') != NULL) {
198                 backend = talloc_strndup(ldb, url, strchr(url, ':')-url);
199         } else {
200                 /* Default to tdb */
201                 backend = talloc_strdup(ldb, "tdb");
202         }
203         if (backend == NULL) {
204                 return ldb_oom(ldb);
205         }
206
207         be = ldb_find_backend(backend);
208
209         talloc_free(backend);
210
211         if (be == NULL) {
212                 ldb_debug(ldb, LDB_DEBUG_FATAL,
213                           "Unable to find backend for '%s' - do you need to set LDB_MODULES_PATH?", url);
214                 return LDB_ERR_OTHER;
215         }
216
217         ret = be->ops->connect_fn(ldb, url, ldb->flags, options, backend_module);
218
219         if (ret != LDB_SUCCESS) {
220                 ldb_debug(ldb, LDB_DEBUG_ERROR,
221                           "Failed to connect to '%s' with backend '%s'", url, be->ops->name);
222                 return ret;
223         }
224         return ret;
225 }
226
227 static struct ldb_hooks {
228         struct ldb_hooks *next, *prev;
229         ldb_hook_fn hook_fn;
230 } *ldb_hooks;
231
232 /*
233   register a ldb hook function
234  */
235 int ldb_register_hook(ldb_hook_fn hook_fn)
236 {
237         struct ldb_hooks *lc;
238         lc = talloc_zero(ldb_hooks, struct ldb_hooks);
239         if (lc == NULL) {
240                 return LDB_ERR_OPERATIONS_ERROR;
241         }
242         lc->hook_fn = hook_fn;
243         DLIST_ADD_END(ldb_hooks, lc, struct ldb_hooks);
244         return LDB_SUCCESS;
245 }
246
247 /*
248   call ldb hooks of a given type
249  */
250 int ldb_modules_hook(struct ldb_context *ldb, enum ldb_module_hook_type t)
251 {
252         struct ldb_hooks *lc;
253         for (lc = ldb_hooks; lc; lc=lc->next) {
254                 int ret = lc->hook_fn(ldb, t);
255                 if (ret != LDB_SUCCESS) {
256                         return ret;
257                 }
258         }
259         return LDB_SUCCESS;
260 }
261
262
263 static const struct ldb_module_ops *ldb_find_module_ops(const char *name)
264 {
265         struct ops_list_entry *e;
266
267         for (e = registered_modules; e; e = e->next) {
268                 if (strcmp(e->ops->name, name) == 0)
269                         return e->ops;
270         }
271
272         return NULL;
273 }
274
275
276 int ldb_register_module(const struct ldb_module_ops *ops)
277 {
278         struct ops_list_entry *entry;
279
280         if (ldb_find_module_ops(ops->name) != NULL)
281                 return LDB_ERR_ENTRY_ALREADY_EXISTS;
282
283         entry = talloc(talloc_autofree_context(), struct ops_list_entry);
284         if (entry == NULL) {
285                 return LDB_ERR_OPERATIONS_ERROR;
286         }
287
288         entry->ops = ops;
289         entry->next = registered_modules;
290         registered_modules = entry;
291
292         return LDB_SUCCESS;
293 }
294
295 /*
296   load a list of modules
297  */
298 int ldb_module_load_list(struct ldb_context *ldb, const char **module_list,
299                          struct ldb_module *backend, struct ldb_module **out)
300 {
301         struct ldb_module *module;
302         unsigned int i;
303
304         module = backend;
305
306         for (i = 0; module_list && module_list[i] != NULL; i++) {
307                 struct ldb_module *current;
308                 const struct ldb_module_ops *ops;
309
310                 if (strcmp(module_list[i], "") == 0) {
311                         continue;
312                 }
313
314                 ops = ldb_find_module_ops(module_list[i]);
315
316                 if (ops == NULL) {
317                         ldb_debug(ldb, LDB_DEBUG_FATAL, "WARNING: Module [%s] not found - do you need to set LDB_MODULES_PATH?",
318                                   module_list[i]);
319                         return LDB_ERR_OPERATIONS_ERROR;
320                 }
321
322                 current = talloc_zero(ldb, struct ldb_module);
323                 if (current == NULL) {
324                         return LDB_ERR_OPERATIONS_ERROR;
325                 }
326                 talloc_set_name(current, "ldb_module: %s", module_list[i]);
327
328                 current->ldb = ldb;
329                 current->ops = ops;
330
331                 DLIST_ADD(module, current);
332         }
333         *out = module;
334         return LDB_SUCCESS;
335 }
336
337 /*
338   initialise a chain of modules
339  */
340 int ldb_module_init_chain(struct ldb_context *ldb, struct ldb_module *module)
341 {
342         while (module && module->ops->init_context == NULL)
343                 module = module->next;
344
345         /* init is different in that it is not an error if modules
346          * do not require initialization */
347
348         if (module) {
349                 int ret = module->ops->init_context(module);
350                 if (ret != LDB_SUCCESS) {
351                         ldb_debug(ldb, LDB_DEBUG_FATAL, "module %s initialization failed : %s",
352                                   module->ops->name, ldb_strerror(ret));
353                         return ret;
354                 }
355         }
356
357         return LDB_SUCCESS;
358 }
359
360 int ldb_load_modules(struct ldb_context *ldb, const char *options[])
361 {
362         const char *modules_string;
363         const char **modules = NULL;
364         int ret;
365         TALLOC_CTX *mem_ctx = talloc_new(ldb);
366         if (!mem_ctx) {
367                 return ldb_oom(ldb);
368         }
369
370         /* find out which modules we are requested to activate */
371
372         /* check if we have a custom module list passd as ldb option */
373         if (options) {
374                 modules_string = ldb_options_find(ldb, options, "modules");
375                 if (modules_string) {
376                         modules = ldb_modules_list_from_string(ldb, mem_ctx, modules_string);
377                 }
378         }
379
380         /* if not overloaded by options and the backend is not ldap try to load the modules list from ldb */
381         if ((modules == NULL) && (strcmp("ldap", ldb->modules->ops->name) != 0)) {
382                 const char * const attrs[] = { "@LIST" , NULL};
383                 struct ldb_result *res = NULL;
384                 struct ldb_dn *mods_dn;
385
386                 mods_dn = ldb_dn_new(mem_ctx, ldb, "@MODULES");
387                 if (mods_dn == NULL) {
388                         talloc_free(mem_ctx);
389                         return ldb_oom(ldb);
390                 }
391
392                 ret = ldb_search(ldb, mods_dn, &res, mods_dn, LDB_SCOPE_BASE, attrs, "@LIST=*");
393
394                 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
395                         ldb_debug(ldb, LDB_DEBUG_TRACE, "no modules required by the db");
396                 } else if (ret != LDB_SUCCESS) {
397                         ldb_debug(ldb, LDB_DEBUG_FATAL, "ldb error (%s) occurred searching for modules, bailing out", ldb_errstring(ldb));
398                         talloc_free(mem_ctx);
399                         return ret;
400                 } else {
401                         const char *module_list;
402                         if (res->count == 0) {
403                                 ldb_debug(ldb, LDB_DEBUG_TRACE, "no modules required by the db");
404                         } else if (res->count > 1) {
405                                 ldb_debug(ldb, LDB_DEBUG_FATAL, "Too many records found (%u), bailing out", res->count);
406                                 talloc_free(mem_ctx);
407                                 return LDB_ERR_OPERATIONS_ERROR;
408                         } else {
409                                 module_list = ldb_msg_find_attr_as_string(res->msgs[0], "@LIST", NULL);
410                                 if (!module_list) {
411                                         ldb_debug(ldb, LDB_DEBUG_TRACE, "no modules required by the db");
412                                 }
413                                 modules = ldb_modules_list_from_string(ldb, mem_ctx,
414                                                                module_list);
415                         }
416                 }
417
418                 talloc_free(mods_dn);
419         }
420
421         if (modules != NULL) {
422                 ret = ldb_module_load_list(ldb, modules, ldb->modules, &ldb->modules);
423                 if (ret != LDB_SUCCESS) {
424                         talloc_free(mem_ctx);
425                         return ret;
426                 }
427         } else {
428                 ldb_debug(ldb, LDB_DEBUG_TRACE, "No modules specified for this database");
429         }
430
431         ret = ldb_module_init_chain(ldb, ldb->modules);
432         talloc_free(mem_ctx);
433         return ret;
434 }
435
436 /*
437   by using this we allow ldb modules to only implement the functions they care about,
438   which makes writing a module simpler, and makes it more likely to keep working
439   when ldb is extended
440 */
441 #define FIND_OP_NOERR(module, op) do { \
442         module = module->next; \
443         while (module && module->ops->op == NULL) module = module->next; \
444         if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) { \
445                 ldb_debug(module->ldb, LDB_DEBUG_TRACE, "ldb_trace_next_request: (%s)->" #op, \
446                           module->ops->name);                           \
447         }                                                               \
448 } while (0)
449
450 #define FIND_OP(module, op) do { \
451         struct ldb_context *ldb = module->ldb; \
452         FIND_OP_NOERR(module, op); \
453         if (module == NULL) { \
454                 ldb_asprintf_errstring(ldb, "Unable to find backend operation for " #op ); \
455                 return LDB_ERR_OPERATIONS_ERROR;        \
456         }                                               \
457 } while (0)
458
459
460 struct ldb_module *ldb_module_new(TALLOC_CTX *memctx,
461                                   struct ldb_context *ldb,
462                                   const char *module_name,
463                                   const struct ldb_module_ops *ops)
464 {
465         struct ldb_module *module;
466
467         module = talloc(memctx, struct ldb_module);
468         if (!module) {
469                 ldb_oom(ldb);
470                 return NULL;
471         }
472         talloc_set_name_const(module, module_name);
473         module->ldb = ldb;
474         module->prev = module->next = NULL;
475         module->ops = ops;
476
477         return module;
478 }
479
480 const char * ldb_module_get_name(struct ldb_module *module)
481 {
482         return module->ops->name;
483 }
484
485 struct ldb_context *ldb_module_get_ctx(struct ldb_module *module)
486 {
487         return module->ldb;
488 }
489
490 const struct ldb_module_ops *ldb_module_get_ops(struct ldb_module *module)
491 {
492         return module->ops;
493 }
494
495 void *ldb_module_get_private(struct ldb_module *module)
496 {
497         return module->private_data;
498 }
499
500 void ldb_module_set_private(struct ldb_module *module, void *private_data)
501 {
502         module->private_data = private_data;
503 }
504
505 /*
506    helper functions to call the next module in chain
507 */
508
509 int ldb_next_request(struct ldb_module *module, struct ldb_request *request)
510 {
511         int ret;
512
513         if (request->callback == NULL) {
514                 ldb_set_errstring(module->ldb, "Requests MUST define callbacks");
515                 return LDB_ERR_UNWILLING_TO_PERFORM;
516         }
517
518         request->handle->nesting++;
519
520         switch (request->operation) {
521         case LDB_SEARCH:
522                 FIND_OP(module, search);
523                 ret = module->ops->search(module, request);
524                 break;
525         case LDB_ADD:
526                 FIND_OP(module, add);
527                 ret = module->ops->add(module, request);
528                 break;
529         case LDB_MODIFY:
530                 FIND_OP(module, modify);
531                 ret = module->ops->modify(module, request);
532                 break;
533         case LDB_DELETE:
534                 FIND_OP(module, del);
535                 ret = module->ops->del(module, request);
536                 break;
537         case LDB_RENAME:
538                 FIND_OP(module, rename);
539                 ret = module->ops->rename(module, request);
540                 break;
541         case LDB_EXTENDED:
542                 FIND_OP(module, extended);
543                 ret = module->ops->extended(module, request);
544                 break;
545         default:
546                 FIND_OP(module, request);
547                 ret = module->ops->request(module, request);
548                 break;
549         }
550
551         request->handle->nesting--;
552
553         if (ret == LDB_SUCCESS) {
554                 return ret;
555         }
556         if (!ldb_errstring(module->ldb)) {
557                 /* Set a default error string, to place the blame somewhere */
558                 ldb_asprintf_errstring(module->ldb, "error in module %s: %s (%d)", module->ops->name, ldb_strerror(ret), ret);
559         }
560
561         if (!(request->handle->flags & LDB_HANDLE_FLAG_DONE_CALLED)) {
562                 /* It is _extremely_ common that a module returns a
563                  * failure without calling ldb_module_done(), but that
564                  * guarantees we will end up hanging in
565                  * ldb_wait(). This fixes it without having to rewrite
566                  * all our modules, and leaves us one less sharp
567                  * corner for module developers to cut themselves on
568                  */
569                 ret = ldb_module_done(request, NULL, NULL, ret);
570         }
571         return ret;
572 }
573
574 int ldb_next_init(struct ldb_module *module)
575 {
576         module = module->next;
577
578         return ldb_module_init_chain(module->ldb, module);
579 }
580
581 int ldb_next_start_trans(struct ldb_module *module)
582 {
583         int ret;
584         FIND_OP(module, start_transaction);
585         ret = module->ops->start_transaction(module);
586         if (ret == LDB_SUCCESS) {
587                 return ret;
588         }
589         if (!ldb_errstring(module->ldb)) {
590                 /* Set a default error string, to place the blame somewhere */
591                 ldb_asprintf_errstring(module->ldb, "start_trans error in module %s: %s (%d)", module->ops->name, ldb_strerror(ret), ret);
592         }
593         if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) { 
594                 ldb_debug(module->ldb, LDB_DEBUG_TRACE, "ldb_next_start_trans error: %s", 
595                           ldb_errstring(module->ldb));                          
596         }
597         return ret;
598 }
599
600 int ldb_next_end_trans(struct ldb_module *module)
601 {
602         int ret;
603         FIND_OP(module, end_transaction);
604         ret = module->ops->end_transaction(module);
605         if (ret == LDB_SUCCESS) {
606                 return ret;
607         }
608         if (!ldb_errstring(module->ldb)) {
609                 /* Set a default error string, to place the blame somewhere */
610                 ldb_asprintf_errstring(module->ldb, "end_trans error in module %s: %s (%d)", module->ops->name, ldb_strerror(ret), ret);
611         }
612         if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) { 
613                 ldb_debug(module->ldb, LDB_DEBUG_TRACE, "ldb_next_end_trans error: %s", 
614                           ldb_errstring(module->ldb));                          
615         }
616         return ret;
617 }
618
619 int ldb_next_prepare_commit(struct ldb_module *module)
620 {
621         int ret;
622         FIND_OP_NOERR(module, prepare_commit);
623         if (module == NULL) {
624                 /* we are allowed to have no prepare commit in
625                    backends */
626                 return LDB_SUCCESS;
627         }
628         ret = module->ops->prepare_commit(module);
629         if (ret == LDB_SUCCESS) {
630                 return ret;
631         }
632         if (!ldb_errstring(module->ldb)) {
633                 /* Set a default error string, to place the blame somewhere */
634                 ldb_asprintf_errstring(module->ldb, "prepare_commit error in module %s: %s (%d)", module->ops->name, ldb_strerror(ret), ret);
635         }
636         if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) { 
637                 ldb_debug(module->ldb, LDB_DEBUG_TRACE, "ldb_next_prepare_commit error: %s", 
638                           ldb_errstring(module->ldb));                          
639         }
640         return ret;
641 }
642
643 int ldb_next_del_trans(struct ldb_module *module)
644 {
645         int ret;
646         FIND_OP(module, del_transaction);
647         ret = module->ops->del_transaction(module);
648         if (ret == LDB_SUCCESS) {
649                 return ret;
650         }
651         if (!ldb_errstring(module->ldb)) {
652                 /* Set a default error string, to place the blame somewhere */
653                 ldb_asprintf_errstring(module->ldb, "del_trans error in module %s: %s (%d)", module->ops->name, ldb_strerror(ret), ret);
654         }
655         if ((module && module->ldb->flags & LDB_FLG_ENABLE_TRACING)) { 
656                 ldb_debug(module->ldb, LDB_DEBUG_TRACE, "ldb_next_del_trans error: %s", 
657                           ldb_errstring(module->ldb));                          
658         }
659         return ret;
660 }
661
662 struct ldb_handle *ldb_handle_new(TALLOC_CTX *mem_ctx, struct ldb_context *ldb)
663 {
664         struct ldb_handle *h;
665
666         h = talloc_zero(mem_ctx, struct ldb_handle);
667         if (h == NULL) {
668                 ldb_set_errstring(ldb, "Out of Memory");
669                 return NULL;
670         }
671
672         h->status = LDB_SUCCESS;
673         h->state = LDB_ASYNC_INIT;
674         h->ldb = ldb;
675         h->flags = 0;
676         h->location = NULL;
677         h->parent = NULL;
678
679         return h;
680 }
681
682 /* calls the request callback to send an entry
683  *
684  * params:
685  *      req: the original request passed to your module
686  *      msg: reply message (must be a talloc pointer, and it will be stolen
687  *           on the ldb_reply that is sent to the callback)
688  *      ctrls: controls to send in the reply  (must be a talloc pointer, and it will be stolen
689  *           on the ldb_reply that is sent to the callback)
690  */
691
692 int ldb_module_send_entry(struct ldb_request *req,
693                           struct ldb_message *msg,
694                           struct ldb_control **ctrls)
695 {
696         struct ldb_reply *ares;
697
698         ares = talloc_zero(req, struct ldb_reply);
699         if (!ares) {
700                 ldb_oom(req->handle->ldb);
701                 req->callback(req, NULL);
702                 return LDB_ERR_OPERATIONS_ERROR;
703         }
704         ares->type = LDB_REPLY_ENTRY;
705         ares->message = talloc_steal(ares, msg);
706         ares->controls = talloc_steal(ares, ctrls);
707         ares->error = LDB_SUCCESS;
708
709         if ((req->handle->ldb->flags & LDB_FLG_ENABLE_TRACING) &&
710             req->handle->nesting == 0) {
711                 char *s;
712                 ldb_debug_add(req->handle->ldb, "ldb_trace_response: ENTRY\n");
713                 s = ldb_ldif_message_string(req->handle->ldb, msg, LDB_CHANGETYPE_NONE, msg);
714                 ldb_debug_add(req->handle->ldb, "%s\n", s);
715                 talloc_free(s);
716                 ldb_debug_end(req->handle->ldb, LDB_DEBUG_TRACE);
717         }
718
719         return req->callback(req, ares);
720 }
721
722 /* calls the request callback to send an referrals
723  *
724  * params:
725  *      req: the original request passed to your module
726  *      ref: referral string (must be a talloc pointeri, steal)
727  */
728
729 int ldb_module_send_referral(struct ldb_request *req,
730                                            char *ref)
731 {
732         struct ldb_reply *ares;
733
734         ares = talloc_zero(req, struct ldb_reply);
735         if (!ares) {
736                 ldb_oom(req->handle->ldb);
737                 req->callback(req, NULL);
738                 return LDB_ERR_OPERATIONS_ERROR;
739         }
740         ares->type = LDB_REPLY_REFERRAL;
741         ares->referral = talloc_steal(ares, ref);
742         ares->error = LDB_SUCCESS;
743
744         if ((req->handle->ldb->flags & LDB_FLG_ENABLE_TRACING) &&
745             req->handle->nesting == 0) {
746                 ldb_debug_add(req->handle->ldb, "ldb_trace_response: REFERRAL\n");
747                 ldb_debug_add(req->handle->ldb, "ref: %s\n", ref);
748                 ldb_debug_end(req->handle->ldb, LDB_DEBUG_TRACE);
749         }
750
751         return req->callback(req, ares);
752 }
753
754 /* calls the original request callback
755  *
756  * params:
757  *      req:   the original request passed to your module
758  *      ctrls: controls to send in the reply (must be a talloc pointer, steal)
759  *      response: results for extended request (steal)
760  *      error: LDB_SUCCESS for a successful return
761  *             any other ldb error otherwise
762  */
763 int ldb_module_done(struct ldb_request *req,
764                     struct ldb_control **ctrls,
765                     struct ldb_extended *response,
766                     int error)
767 {
768         struct ldb_reply *ares;
769
770         ares = talloc_zero(req, struct ldb_reply);
771         if (!ares) {
772                 ldb_oom(req->handle->ldb);
773                 req->callback(req, NULL);
774                 return LDB_ERR_OPERATIONS_ERROR;
775         }
776         ares->type = LDB_REPLY_DONE;
777         ares->controls = talloc_steal(ares, ctrls);
778         ares->response = talloc_steal(ares, response);
779         ares->error = error;
780
781         req->handle->flags |= LDB_HANDLE_FLAG_DONE_CALLED;
782
783         if ((req->handle->ldb->flags & LDB_FLG_ENABLE_TRACING) &&
784             req->handle->nesting == 0) {
785                 ldb_debug_add(req->handle->ldb, "ldb_trace_response: DONE\n");
786                 ldb_debug_add(req->handle->ldb, "error: %d\n", error);
787                 if (ldb_errstring(req->handle->ldb)) {
788                         ldb_debug_add(req->handle->ldb, "msg: %s\n",
789                                   ldb_errstring(req->handle->ldb));
790                 }
791                 ldb_debug_end(req->handle->ldb, LDB_DEBUG_TRACE);
792         }
793
794         return req->callback(req, ares);
795 }
796
797 /* to be used *only* in modules init functions.
798  * this function is synchronous and will register
799  * the requested OID in the rootdse module if present
800  * otherwise it will return an error */
801 int ldb_mod_register_control(struct ldb_module *module, const char *oid)
802 {
803         struct ldb_request *req;
804         int ret;
805
806         req = talloc_zero(module, struct ldb_request);
807         if (req == NULL) {
808                 return LDB_ERR_OPERATIONS_ERROR;
809         }
810
811         req->operation = LDB_REQ_REGISTER_CONTROL;
812         req->op.reg_control.oid = oid;
813         req->callback = ldb_op_default_callback;
814
815         ldb_set_timeout(module->ldb, req, 0);
816
817         req->handle = ldb_handle_new(req, module->ldb);
818         if (req->handle == NULL) {
819                 return LDB_ERR_OPERATIONS_ERROR;
820         }
821
822         ret = ldb_request(module->ldb, req);
823         if (ret == LDB_SUCCESS) {
824                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
825         }
826         talloc_free(req);
827
828         return ret;
829 }
830
831 static int ldb_modules_load_dir(const char *modules_dir, const char *version);
832
833
834 /*
835   load one module. A static list of loaded module inode numbers is
836   used to prevent a module being loaded twice
837
838   dlopen() is used on the module, and dlsym() is then used to look for
839   a ldb_init_module() function. If present, that function is called
840   with the ldb version number as an argument.
841
842   The ldb_init_module() function will typically call
843   ldb_register_module() and ldb_register_backend() to register a
844   module or backend, but it may also be used to register command line
845   handling functions, ldif handlers or any other local
846   modififications.
847
848   The ldb_init_module() function does not get a ldb_context passed in,
849   as modules will be used for multiple ldb context handles. The call
850   from the first ldb_init() is just a convenient way to ensure it is
851   called early enough.
852  */
853 static int ldb_modules_load_path(const char *path, const char *version)
854 {
855         void *handle;
856         int (*init_fn)(const char *);
857         int ret;
858         struct stat st;
859         static struct loaded {
860                 struct loaded *next, *prev;
861                 ino_t st_ino;
862                 dev_t st_dev;
863         } *loaded;
864         struct loaded *le;
865         int dlopen_flags;
866
867         ret = stat(path, &st);
868         if (ret != 0) {
869                 fprintf(stderr, "ldb: unable to stat module %s : %s\n", path, strerror(errno));
870                 return LDB_ERR_UNAVAILABLE;
871         }
872
873         for (le=loaded; le; le=le->next) {
874                 if (le->st_ino == st.st_ino &&
875                     le->st_dev == st.st_dev) {
876                         /* its already loaded */
877                         return LDB_SUCCESS;
878                 }
879         }
880
881         le = talloc(loaded, struct loaded);
882         if (le == NULL) {
883                 fprintf(stderr, "ldb: unable to allocated loaded entry\n");
884                 return LDB_ERR_UNAVAILABLE;
885         }
886
887         le->st_ino = st.st_ino;
888         le->st_dev = st.st_dev;
889
890         DLIST_ADD_END(loaded, le, struct loaded);
891
892         /* if it is a directory, recurse */
893         if (S_ISDIR(st.st_mode)) {
894                 return ldb_modules_load_dir(path, version);
895         }
896
897         dlopen_flags = RTLD_NOW;
898 #ifdef RTLD_DEEPBIND
899         /* use deepbind if possible, to avoid issues with different
900            system library varients, for example ldb modules may be linked
901            against Heimdal while the application may use MIT kerberos
902
903            See the dlopen manpage for details
904         */
905         dlopen_flags |= RTLD_DEEPBIND;
906 #endif
907
908         handle = dlopen(path, dlopen_flags);
909         if (handle == NULL) {
910                 fprintf(stderr, "ldb: unable to dlopen %s : %s\n", path, dlerror());
911                 return LDB_SUCCESS;
912         }
913
914         init_fn = dlsym(handle, "ldb_init_module");
915         if (init_fn == NULL) {
916                 /* ignore it, it could be an old-style
917                  * module. Once we've converted all modules we
918                  * could consider this an error */
919                 dlclose(handle);
920                 return LDB_SUCCESS;
921         }
922
923         ret = init_fn(version);
924         if (ret == LDB_ERR_ENTRY_ALREADY_EXISTS) {
925                 /* the module is already registered - ignore this, as
926                  * it can happen if LDB_MODULES_PATH points at both
927                  * the build and install directory
928                  */
929                 ret = LDB_SUCCESS;
930         }
931         return ret;
932 }
933
934 static int qsort_string(const char **s1, const char **s2)
935 {
936         return strcmp(*s1, *s2);
937 }
938
939
940 /*
941   load all modules from the given ldb modules directory. This is run once
942   during the first ldb_init() call.
943
944   Modules are loaded in alphabetical order to ensure that any module
945   load ordering dependencies are reproducible. Modules should avoid
946   relying on load order
947  */
948 static int ldb_modules_load_dir(const char *modules_dir, const char *version)
949 {
950         DIR *dir;
951         struct dirent *de;
952         const char **modlist = NULL;
953         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
954         unsigned i, num_modules = 0;
955
956         dir = opendir(modules_dir);
957         if (dir == NULL) {
958                 if (errno == ENOENT) {
959                         talloc_free(tmp_ctx);
960                         /* we don't have any modules */
961                         return LDB_SUCCESS;
962                 }
963                 talloc_free(tmp_ctx);
964                 fprintf(stderr, "ldb: unable to open modules directory '%s' - %s\n",
965                         modules_dir, strerror(errno));
966                 return LDB_ERR_UNAVAILABLE;
967         }
968
969
970         while ((de = readdir(dir))) {
971                 if (ISDOT(de->d_name) || ISDOTDOT(de->d_name))
972                         continue;
973
974                 modlist = talloc_realloc(tmp_ctx, modlist, const char *, num_modules+1);
975                 if (modlist == NULL) {
976                         talloc_free(tmp_ctx);
977                         closedir(dir);
978                         fprintf(stderr, "ldb: unable to allocate modules list\n");
979                         return LDB_ERR_UNAVAILABLE;
980                 }
981                 modlist[num_modules] = talloc_asprintf(modlist, "%s/%s", modules_dir, de->d_name);
982                 if (modlist[num_modules] == NULL) {
983                         talloc_free(tmp_ctx);
984                         closedir(dir);
985                         fprintf(stderr, "ldb: unable to allocate module list entry\n");
986                         return LDB_ERR_UNAVAILABLE;
987                 }
988                 num_modules++;
989         }
990
991         closedir(dir);
992
993         /* sort the directory, so we get consistent load ordering */
994         TYPESAFE_QSORT(modlist, num_modules, qsort_string);
995
996         for (i=0; i<num_modules; i++) {
997                 int ret = ldb_modules_load_path(modlist[i], version);
998                 if (ret != LDB_SUCCESS) {
999                         fprintf(stderr, "ldb: failed to initialise module %s : %s\n",
1000                                 modlist[i], ldb_strerror(ret));
1001                         talloc_free(tmp_ctx);
1002                         return ret;
1003                 }
1004         }
1005
1006         talloc_free(tmp_ctx);
1007
1008         return LDB_SUCCESS;
1009 }
1010
1011 /* 
1012    load any additional modules from the given directory 
1013 */
1014 void ldb_set_modules_dir(struct ldb_context *ldb, const char *path)
1015 {
1016         int ret = ldb_modules_load_path(path, LDB_VERSION);
1017         if (ret != LDB_SUCCESS) {
1018                 ldb_asprintf_errstring(ldb, "Failed to load modules from: %s\n", path);
1019         }
1020 }
1021
1022
1023 /*
1024   load all modules static (builtin) modules
1025  */
1026 static int ldb_modules_load_static(const char *version)
1027 {
1028         static bool initialised;
1029 #define _MODULE_PROTO(init) extern int init(const char *);
1030         STATIC_ldb_MODULES_PROTO;
1031         const ldb_module_init_fn static_init_functions[] = { STATIC_ldb_MODULES };
1032         unsigned i;
1033
1034         if (initialised) {
1035                 return LDB_SUCCESS;
1036         }
1037         initialised = true;
1038
1039         for (i=0; static_init_functions[i]; i++) {
1040                 int ret = static_init_functions[i](version);
1041                 if (ret != LDB_SUCCESS) {
1042                         return ret;
1043                 }
1044         }
1045         return LDB_SUCCESS;
1046 }
1047
1048 /*
1049   load all modules from the given ldb modules path, colon
1050   separated.
1051
1052   modules are loaded recursively for all subdirectories in the paths
1053  */
1054 int ldb_modules_load(const char *modules_path, const char *version)
1055 {
1056         char *tok, *path, *tok_ptr=NULL;
1057         int ret;
1058
1059         ret = ldb_modules_load_static(version);
1060         if (ret != LDB_SUCCESS) {
1061                 return ret;
1062         }
1063
1064         path = talloc_strdup(NULL, modules_path);
1065         if (path == NULL) {
1066                 fprintf(stderr, "ldb: failed to allocate modules_path\n");
1067                 return LDB_ERR_UNAVAILABLE;
1068         }
1069
1070         for (tok=strtok_r(path, ":", &tok_ptr);
1071              tok;
1072              tok=strtok_r(NULL, ":", &tok_ptr)) {
1073                 ret = ldb_modules_load_path(tok, version);
1074                 if (ret != LDB_SUCCESS) {
1075                         talloc_free(path);
1076                         return ret;
1077                 }
1078         }
1079         talloc_free(path);
1080
1081         return LDB_SUCCESS;
1082 }
1083
1084
1085 /*
1086   return a string representation of the calling chain for the given
1087   ldb request
1088  */
1089 char *ldb_module_call_chain(struct ldb_request *req, TALLOC_CTX *mem_ctx)
1090 {
1091         char *ret;
1092         unsigned int i = 0;
1093
1094         ret = talloc_strdup(mem_ctx, "");
1095         if (ret == NULL) {
1096                 return NULL;
1097         }
1098
1099         while (req && req->handle) {
1100                 char *s = talloc_asprintf_append_buffer(ret, "req[%u] %p  : %s\n",
1101                                                         i++, req, ldb_req_location(req));
1102                 if (s == NULL) {
1103                         talloc_free(ret);
1104                         return NULL;
1105                 }
1106                 ret = s;
1107                 req = req->handle->parent;
1108         }
1109         return ret;
1110 }
1111
1112
1113 /*
1114   return the next module in the chain
1115  */
1116 struct ldb_module *ldb_module_next(struct ldb_module *module)
1117 {
1118         return module->next;
1119 }
1120
1121 /*
1122   set the next module in the module chain
1123  */
1124 void ldb_module_set_next(struct ldb_module *module, struct ldb_module *next)
1125 {
1126         module->next = next;
1127 }
1128
1129
1130 /*
1131   get the popt_options pointer in the ldb structure. This allows a ldb
1132   module to change the command line parsing
1133  */
1134 struct poptOption **ldb_module_popt_options(struct ldb_context *ldb)
1135 {
1136         return &ldb->popt_options;
1137 }
1138
1139
1140 /*
1141   return the current ldb flags LDB_FLG_*
1142  */
1143 uint32_t ldb_module_flags(struct ldb_context *ldb)
1144 {
1145         return ldb->flags;
1146 }