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