fix a mostly harmless error introduced by svn merge.
[asterisk/asterisk.git] / loader.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Module Loader
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  * - See ModMngMnt
25  */
26
27 #include <stdio.h>
28 #include <dirent.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #define MOD_LOADER      /* prevent some module-specific stuff from being compiled */
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include "asterisk/linkedlists.h"
39 #include "asterisk/module.h"
40 #include "asterisk/options.h"
41 #include "asterisk/config.h"
42 #include "asterisk/logger.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/term.h"
45 #include "asterisk/manager.h"
46 #include "asterisk/cdr.h"
47 #include "asterisk/enum.h"
48 #include "asterisk/rtp.h"
49 #include "asterisk/http.h"
50 #include "asterisk/lock.h"
51 #ifdef DLFCNCOMPAT
52 #include "asterisk/dlfcn-compat.h"
53 #else
54 #include <dlfcn.h>
55 #endif
56 #include "asterisk/md5.h"
57 #include "asterisk/utils.h"
58
59 #ifndef RTLD_NOW
60 #define RTLD_NOW 0
61 #endif
62
63 static int modlistver = 0; /* increase whenever the list changes, to protect reload */
64
65 static unsigned char expected_key[] =
66 { 0x87, 0x76, 0x79, 0x35, 0x23, 0xea, 0x3a, 0xd3,
67   0x25, 0x2a, 0xbb, 0x35, 0x87, 0xe4, 0x22, 0x24 };
68
69 /*
70  * Modules can be in a number of different states, as below:
71  * MS_FAILED    attempt to load failed. This is final.
72  * MS_NEW       just added to the list, symbols unresolved.
73  * MS_RESOLVED  all symbols resolved, but supplier modules not active yet.
74  * MS_CANLOAD   all symbols resolved and suppliers are all active
75  *              (or we are in a cyclic dependency and we are breaking a loop)
76  * MS_ACTIVE    load() returned successfully.
77  */
78 enum st_t {  /* possible states of a module */
79         MS_FAILED = 0,              /*!< cannot load */
80         MS_NEW = 1,                 /*!< nothing known */
81         MS_RESOLVED = 2,            /*!< all required resolved */
82         MS_CANLOAD = 3,             /*!< as above, plus cyclic depend.*/
83         MS_ACTIVE = 4,              /*!< all done */
84 };
85
86 /*! \note
87  * All module symbols are in module_symbols.
88  * Modules are then linked in a list of struct module,
89  * whereas updaters are in a list of struct loadupdate.
90  *
91  * Both lists (basically, the entire loader) are protected by
92  * the lock in module_list.
93  *
94  * A second lock, reloadlock, is used to prevent concurrent reloads
95  */
96 struct module {
97         AST_LIST_ENTRY(module) next;
98         struct module_symbols *cb;
99         void *lib;              /* the shared lib */
100         char resource[256];
101
102         enum st_t state;
103         int export_refcount;    /* how many users of exported symbols */
104 };
105
106 struct loadupdate {
107         AST_LIST_ENTRY(loadupdate) next;
108         int (*updater)(void);
109 };
110
111 static AST_LIST_HEAD_STATIC(module_list, module);
112 static AST_LIST_HEAD_STATIC(updaters, loadupdate);
113 AST_MUTEX_DEFINE_STATIC(reloadlock);
114
115 /*! \note
116  * helper localuser routines.
117  * All of these routines are extremely expensive, so the use of
118  * macros is totally unnecessary from the point of view of performance:
119  * the extra function call will be totally negligible in all cases.
120  */
121
122 struct localuser *ast_localuser_add(struct module_symbols *me,
123         struct ast_channel *chan)
124 {
125         struct localuser *u = ast_calloc(1, sizeof(*u));
126         if (u == NULL)
127                 return NULL;
128         u->chan = chan;
129         ast_mutex_lock(&me->lock);
130         u->next = me->lu_head;
131         me->lu_head = u;
132         ast_mutex_unlock(&me->lock);
133         ast_atomic_fetchadd_int(&me->usecnt, +1);
134         ast_update_use_count();
135         return u;
136 }
137
138 void ast_localuser_remove(struct module_symbols *me, struct localuser *u)
139 {
140         struct localuser *x, *prev = NULL;
141         ast_mutex_lock(&me->lock);
142         /* unlink from the list */
143         for (x = me->lu_head; x; prev = x, x = x->next) {
144                 if (x == u) {
145                         if (prev)
146                                 prev->next = x->next;
147                         else
148                                 me->lu_head = x->next;
149                         break;
150                 }
151         }
152         ast_mutex_unlock(&me->lock);
153         ast_atomic_fetchadd_int(&me->usecnt, -1);
154         free(u);
155         ast_update_use_count();
156 }
157
158 void ast_hangup_localusers(struct module_symbols *me)
159 {
160         struct localuser *u, *next;
161         ast_mutex_lock(&me->lock);
162         for (u = me->lu_head; u; u = next) {
163                 next = u->next;
164                 ast_softhangup(u->chan, AST_SOFTHANGUP_APPUNLOAD);
165                 ast_atomic_fetchadd_int(&me->usecnt, -1);
166                 free(u);
167         }
168         ast_mutex_unlock(&me->lock);
169         ast_update_use_count();
170 }
171
172 /*--- new-style loader routines ---*/
173
174 /*
175  * For backward compatibility, we have 3 types of loadable modules:
176  *
177  * MOD_0 these are the 'old style' modules, which export a number
178  *       of callbacks, and their full interface, as globally visible
179  *       symbols. The module needs to be loaded with RTLD_LAZY and
180  *       RTLD_GLOBAL to make symbols visible to other modules, and
181  *       to avoid load failures due to cross dependencies.
182  *
183  * MOD_1 The generic callbacks are all into a structure, mod_data.
184  *
185  * MOD_2 this is the 'new style' format for modules. The module must
186  *       explictly declare which simbols are exported and which
187  *       symbols from other modules are used, and the code in this
188  *       loader will implement appropriate checks to load the modules
189  *       in the correct order. Also this allows to load modules
190  *       with RTLD_NOW and RTLD_LOCAL so there is no chance of run-time
191  *       bugs due to unresolved symbols or name conflicts.
192  */
193
194 /*
195  * helper routine to print the symbolic name associated to a state
196  */
197 static const char *st_name(enum st_t state)
198 {
199         /* try to resolve required symbols */
200         const char *st;
201         switch (state) {
202 #define ST(x)  case x: st = # x; break;
203         ST(MS_NEW);
204         ST(MS_FAILED);
205         ST(MS_RESOLVED);
206         ST(MS_ACTIVE);
207         ST(MS_CANLOAD);
208         default:
209                 st = "unknown";
210         }
211         return st;
212 #undef ST
213 }
214
215 /*! \brief
216  * Fetch/release an exported symbol - modify export_refcount by delta
217  * \param delta 1 to fetch a symbol, -1 to release it.
218  * \return on success, return symbol value.
219  * \note Note, modules in MS_FAIL will never match in a 'get' request.
220  * If src is non-NULL, on exit *src points to the source module.
221  *
222  * Must be called with the lock held.
223  */
224 static void *module_symbol_helper(const char *name,
225                 int delta, struct module **src)
226 {
227         void *ret = NULL;
228         struct module *m;
229
230         AST_LIST_TRAVERSE(&module_list, m, next) {
231                 struct symbol_entry *es;
232                 if (delta > 0 && m->state == MS_FAILED)
233                         continue; /* cannot 'get' a symbol from a failed module */
234                 for (es = m->cb->exported_symbols; ret == NULL && es && es->name; es++) {
235                         if (!strcmp(es->name, name)) {
236                                 ret = es->value;
237                                 m->export_refcount += delta;
238                                 if (src)
239                                         *src = m;
240                                 break;
241                         }
242                 }
243                 if (ret)
244                         break;
245         }
246         if (ret == NULL)
247                 ast_log(LOG_WARNING, "symbol %s not found\n", name);
248         return ret;
249 }
250
251 static void *release_module_symbol(const char *name)
252 {
253         return module_symbol_helper(name, -1, NULL);
254 }
255
256 static void *get_module_symbol(const char *name, struct module **src)
257 {
258         return module_symbol_helper(name, +1, src);
259 }
260
261 /*!
262  * \brief Release refcounts to all imported symbols,
263  * and change module state to MS_FAILED.
264  */
265 static void release_module(struct module *m)
266 {
267         struct symbol_entry *s;
268
269         for (s = m->cb->required_symbols; s && s->name != NULL; s++) {
270                 if (s->value != NULL) {
271                         release_module_symbol(s->name);
272                         s->value = NULL;
273                 }
274         }
275         m->state = MS_FAILED;
276 }
277
278 /*! \brief check that no NULL symbols are exported  - the algorithms rely on that. */
279 static int check_exported(struct module *m)
280 {
281         struct symbol_entry *es = m->cb->exported_symbols;
282         int errors = 0;
283
284         if (es == NULL)
285                 return 0;
286         ast_log(LOG_WARNING, "module %s exports the following symbols\n",
287                 es->name);
288         for (; es->name; es++) {
289                 void **p = es->value;
290                 int i;
291
292                 ast_log(LOG_WARNING, "\taddr %p size %8d %s\n",
293                         es->value, es->size, es->name);
294                 for (i = 0; i <  es->size / sizeof(void *); i++, p++) {
295                         if (*p == NULL) {
296                                 ast_log(LOG_WARNING, "\t *** null field at offset %d\n", i);
297                                         errors++;
298                         }
299                 }
300         }
301         return errors;
302 }
303
304 /*!
305  * \brief Resolve symbols and change state accordingly.
306  * \return Return 1 if state changed, 0 otherwise.
307  * \note If MS_FAILED, MS_ACTIVE or MS_CANLOAD there is nothing to do.
308  * If a symbol cannot be resolved (no supplier or supplier in MS_FAIL),
309  * move to MS_FAIL and release all symbols;
310  * If all suppliers are MS_ACTIVE, move to MS_CANLOAD
311  * otherwise move to MS_RESOLVED.
312  */
313 static int resolve(struct module *m)
314 {
315         struct symbol_entry *s;
316
317         if (m->state == MS_FAILED || m->state == MS_ACTIVE || m->state == MS_CANLOAD)
318                 return 0;       /* already decided what to do */
319         /* now it's either MS_NEW or MS_RESOLVED.
320          * Be optimistic and put it in MS_CANLOAD, then try to
321          * resolve and verify symbols, and downgrade as appropriate.
322          */
323         m->state = MS_CANLOAD;
324         for (s = m->cb->required_symbols; s && s->name != NULL; s++) {
325                 void **p = (void **)(s->value);
326
327                 if (*p == NULL)         /* symbol not resolved yet */
328                         *p = get_module_symbol(s->name, &s->src);
329                 if (*p == NULL || s->src->state == MS_FAILED) {        /* fail */
330                         ast_log(LOG_WARNING,
331                                 "Unresolved symbol %s for module %s\n",
332                                 s->name, m->resource);
333                         release_module(m); /* and set to MS_FAILED */
334                         break;
335                 }
336                 if (s->src->state != MS_ACTIVE)
337                         m->state = MS_RESOLVED; /* downgrade */
338         }
339         return 1;
340 }
341
342 /*!
343  * \brief Fixup references and load modules according to their dependency order.
344  * Called when new modules are added to the list.
345  * The algorithm is as follows:
346  * - all modules MS_FAILED are changed to MS_NEW, in case something
347  *      happened that could help them.
348  * - first try to resolve symbols. If successful, change the
349  *   module's state to MS_RESOLVED otherwise to MS_FAILED
350  * - repeat on all modules until there is progress:
351  *    - if it is MS_ACTIVE or MS_FAILED, continue (no progress)
352  *    - if one has all required modules in MS_ACTIVE, try to load it.
353  *      If successful it becomes MS_ACTIVE itself, otherwise
354  *             MS_FAILED and releases all symbols.
355  *             In any case, we have progress.
356  *    - if one of the dependencies is MS_FAILED, release and set to
357  *      MS_FAILED here too. We have progress.
358  * - if we have no progress there is a cyclic dependency.
359  *      Take first and change to MS_CANLOAD, i.e. as if all required are
360  *      MS_ACTIVE. we have progress, so repeat.
361  * \par NOTE:
362  *   - must be called with lock held
363  *   - recursive calls simply return success.
364  */
365 static int fixup(const char *caller)
366 {
367         struct module *m;
368         int total = 0, new = 0, cycle = 0;
369         static int in_fixup = 0;        /* disable recursive calls */
370
371         if (in_fixup)
372                 return 0;
373         in_fixup++;
374         AST_LIST_TRAVERSE(&module_list, m, next) {
375                 total++;
376                 if (m->state == MS_FAILED)
377                         m->state = MS_NEW;
378                 if (m->state == MS_NEW)
379                         new++;
380                 /* print some debugging info for new modules */
381                 if (m->state == MS_NEW &&
382                     (m->cb->exported_symbols || m->cb->required_symbols))
383                         ast_log(LOG_NOTICE,
384                             "module %-30s exports %p requires %p state %s(%d)\n",
385                                 m->resource, m->cb->exported_symbols,
386                                 m->cb->required_symbols,
387                                 st_name(m->state), m->state);
388         }
389         ast_log(LOG_DEBUG, "---- fixup (%s): %d modules, %d new ---\n",
390                 caller, total, new);
391         for (;;cycle++) {
392                 int again = 0;  /* set if we need another round */
393                 
394                 ast_log(LOG_DEBUG, "---- fixup: cycle %d ---\n", cycle);
395                 AST_LIST_TRAVERSE(&module_list, m, next) {
396                         if (resolve(m))
397                                 again = 1;      /* something changed */
398                         if (m->state != MS_CANLOAD)     /* for now, done with this module */
399                                 continue;
400                         /* try to run the load routine */
401                         if (m->cb->load_module(m)) { /* error */
402                                 ast_log(LOG_WARNING, "load_module %s fail\n",
403                                         m->resource);
404                                 release_module(m); /* and set to MS_FAIL */
405                         } else {
406                                 ast_log(LOG_WARNING, "load_module %s success\n",
407                                         m->resource);
408                                 m->state = MS_ACTIVE;
409                         }
410                         again = 1;      /* something has changed */
411                 }
412                 /* Modules in MS_RESOLVED mean a possible cyclic dependency.
413                  * Break the indecision by setting one to CANLOAD, and repeat.
414                  */
415                 AST_LIST_TRAVERSE(&module_list, m, next) {
416                         if (m->state == MS_RESOLVED) {
417                                 m->state = MS_CANLOAD;
418                                 again = 1;
419                                 break;
420                         }
421                 }
422                 if (!again)     /* we are done */
423                         break;
424         }
425         ast_log(LOG_DEBUG, "---- fixup complete ---\n");
426         in_fixup--;
427         return 0;
428 }
429
430 /* test routines to see which modules depend on global symbols
431  * exported by other modules.
432  */
433 static void check_symbols(void)
434 {
435         struct dirent *d;
436         DIR *mods = opendir(ast_config_AST_MODULE_DIR);
437         void *lib;
438         char buf[1024];
439
440         ast_log(LOG_WARNING, "module dir <%s>\n", ast_config_AST_MODULE_DIR);
441         if (!mods)
442                 return;
443         while((d = readdir(mods))) {
444                 int ld = strlen(d->d_name);
445                 /* Must end in .so to load it.  */
446                 if (ld <= 3 || strcasecmp(d->d_name + ld - 3, ".so"))
447                         continue;
448                 snprintf(buf, sizeof(buf), "%s/%s", ast_config_AST_MODULE_DIR, d->d_name);
449                 lib = dlopen(buf, RTLD_NOW | RTLD_LOCAL);
450                 if (lib == NULL) {
451                         ast_log(LOG_WARNING, "(notice only) module %s error %s\n", d->d_name, dlerror());
452                 }
453                 dlclose(lib);
454         }
455 }
456 /*--- end new-style routines ---*/
457
458 /*! \note
459  * In addition to modules, the reload command handles some extra keywords
460  * which are listed here together with the corresponding handlers.
461  * This table is also used by the command completion code.
462  */
463 static struct reload_classes_t {
464         const char *name;
465         int (*reload_fn)(void);
466 } reload_classes[] = {  /* list in alpha order, longest match first */
467         { "cdr",        ast_cdr_engine_reload },
468         { "dnsmgr",     dnsmgr_reload },
469         { "extconfig",  read_config_maps },
470         { "enum",       ast_enum_reload },
471         { "manager",    reload_manager },
472         { "rtp",        ast_rtp_reload },
473         { "http",       ast_http_reload },
474         { NULL, NULL }
475 };
476
477 static int printdigest(const unsigned char *d)
478 {
479         int x, pos;
480         char buf[256]; /* large enough so we don't have to worry */
481
482         for (pos = 0, x=0; x<16; x++)
483                 pos += sprintf(buf + pos, " %02x", *d++);
484         ast_log(LOG_DEBUG, "Unexpected signature:%s\n", buf);
485         return 0;
486 }
487
488 static int key_matches(const unsigned char *key1, const unsigned char *key2)
489 {
490         int x;
491         for (x=0; x<16; x++) {
492                 if (key1[x] != key2[x]) /* mismatch - fail now. */
493                         return 0;
494         }
495         return 1;
496 }
497
498 static int verify_key(const unsigned char *key)
499 {
500         struct MD5Context c;
501         unsigned char digest[16];
502         MD5Init(&c);
503         MD5Update(&c, key, strlen((char *)key));
504         MD5Final(digest, &c);
505         if (key_matches(expected_key, digest))
506                 return 0;
507         printdigest(digest);
508         return -1;
509 }
510
511 int ast_unload_resource(const char *resource_name, enum unload_mode force)
512 {
513         struct module *cur;
514         int res = -1;
515         int error = 0;
516         if (AST_LIST_LOCK(&module_list)) /* XXX should fail here ? */
517                 ast_log(LOG_WARNING, "Failed to lock\n");
518         AST_LIST_TRAVERSE_SAFE_BEGIN(&module_list, cur, next) {
519                 struct module_symbols *m = cur->cb;
520                 
521                 if (strcasecmp(cur->resource, resource_name))   /* not us */
522                         continue;
523                 if (m->usecnt > 0 || m->flags & NO_UNLOAD)  {
524                         if (force) 
525                                 ast_log(LOG_WARNING, "Warning:  Forcing removal of module %s with use count %d\n", resource_name, res);
526                         else {
527                                 ast_log(LOG_WARNING, "Soft unload failed, '%s' has use count %d\n", resource_name, res);
528                                 error = 1;
529                                 break;
530                         }
531                 }
532                 ast_hangup_localusers(m);
533                 res = m->unload_module(m);
534                 if (res) {
535                         ast_log(LOG_WARNING, "Firm unload failed for %s\n", resource_name);
536                         if (force <= AST_FORCE_FIRM) {
537                                 error = 1;
538                                 break;
539                         } else
540                                 ast_log(LOG_WARNING, "** Dangerous **: Unloading resource anyway, at user request\n");
541                 }
542                 release_module(cur);    /* XXX */
543                 AST_LIST_REMOVE_CURRENT(&module_list, next);
544                 dlclose(cur->lib);
545                 free(cur);
546                 break;
547         }
548         AST_LIST_TRAVERSE_SAFE_END;
549         if (!error)
550                 modlistver++;
551         AST_LIST_UNLOCK(&module_list);
552         if (!error)     /* XXX maybe within the lock ? */
553                 ast_update_use_count();
554         return res;
555 }
556
557 char *ast_module_helper(const char *line, const char *word, int pos, int state, int rpos, int needsreload)
558 {
559         struct module *cur;
560         int i, which=0, l = strlen(word);
561         char *ret = NULL;
562
563         if (pos != rpos)
564                 return NULL;
565         AST_LIST_LOCK(&module_list);
566         AST_LIST_TRAVERSE(&module_list, cur, next) {
567                 if (!strncasecmp(word, cur->resource, l) && (cur->cb->reload || !needsreload) &&
568                                 ++which > state) {
569                         ret = strdup(cur->resource);
570                         break;
571                 }
572         }
573         AST_LIST_UNLOCK(&module_list);
574         if (!ret) {
575                 for (i=0; !ret && reload_classes[i].name; i++) {
576                         if (!strncasecmp(word, reload_classes[i].name, l) && ++which > state)
577                                 ret = strdup(reload_classes[i].name);
578                 }
579         }
580         return ret;
581 }
582
583 int ast_module_reload(const char *name)
584 {
585         struct module *cur;
586         int res = 0; /* return value. 0 = not found, others, see below */
587         int i, oldversion;
588
589         if (ast_mutex_trylock(&reloadlock)) {
590                 ast_verbose("The previous reload command didn't finish yet\n");
591                 return -1;      /* reload already in progress */
592         }
593         /* Call "predefined" reload here first */
594         for (i = 0; reload_classes[i].name; i++) {
595                 if (!name || !strcasecmp(name, reload_classes[i].name)) {
596                         reload_classes[i].reload_fn();  /* XXX should check error ? */
597                         res = 2;        /* found and reloaded */
598                 }
599         }
600         ast_lastreloadtime = time(NULL);
601
602         AST_LIST_LOCK(&module_list);
603         oldversion = modlistver;
604         AST_LIST_TRAVERSE(&module_list, cur, next) {
605                 struct module_symbols *m = cur->cb;
606                 if (name && strcasecmp(name, cur->resource))    /* not ours */
607                         continue;
608                 if (!m->reload) {       /* cannot be reloaded */
609                         if (res < 1)    /* store result if possible */
610                                 res = 1;        /* 1 = no reload() method */
611                         continue;
612                 }
613                 /* drop the lock and try a reload. if successful, break */
614                 AST_LIST_UNLOCK(&module_list);
615                 res = 2;
616                 if (option_verbose > 2) 
617                         ast_verbose(VERBOSE_PREFIX_3 "Reloading module '%s' (%s)\n", cur->resource, m->description());
618                 m->reload(m);
619                 AST_LIST_LOCK(&module_list);
620                 if (oldversion != modlistver) /* something changed, abort */
621                         break;
622         }
623         AST_LIST_UNLOCK(&module_list);
624         ast_mutex_unlock(&reloadlock);
625         return res;
626 }
627
628 static int resource_exists(const char *resource, int do_lock)
629 {
630         struct module *cur;
631         if (do_lock && AST_LIST_LOCK(&module_list))
632                 ast_log(LOG_WARNING, "Failed to lock\n");
633         AST_LIST_TRAVERSE(&module_list, cur, next) {
634                 if (!strcasecmp(resource, cur->resource))
635                         break;
636         }
637         if (do_lock)
638                 AST_LIST_UNLOCK(&module_list);
639         return cur ? -1 : 0;
640 }
641
642 /* lookup a symbol with or without leading '_', accept either form in input */
643 static void *find_symbol(struct module *m, const char *name, int verbose)
644 {
645         char *n1;
646         void *s;
647
648         if (name[0] == '_')
649                 name++;
650         if (!(n1 = alloca(strlen(name) + 2))) /* room for leading '_' and final '\0' */
651                 return NULL;
652         n1[0] = '_';
653         strcpy(n1+1, name);
654         s = dlsym(m->lib, n1+1);        /* try without '_' */
655         if (s == NULL)
656                 s = dlsym(m->lib, n1);
657         if (verbose && s == NULL)
658                 ast_log(LOG_WARNING, "No symbol '%s' in module '%s\n",
659                         n1, m->resource);
660         return s;
661 }
662
663 /* XXX cfg is only used for !res_* and #ifdef RTLD_GLOBAL */
664 static struct module * __load_resource(const char *resource_name,
665         const struct ast_config *cfg)
666 {
667         static char fn[256];
668         int errors=0;
669         int res;
670         struct module *cur;
671         struct module_symbols *m = NULL;
672         int flags = RTLD_NOW;
673         unsigned char *key;
674         char tmp[80];
675
676 #ifndef RTLD_GLOBAL
677 #define RTLD_GLOBAL     0       /* so it is a No-op */
678 #endif
679         if (strncasecmp(resource_name, "res_", 4) && cfg) {
680                 char *val = ast_variable_retrieve(cfg, "global", resource_name);
681                 if (val && ast_true(val))
682                         flags |= RTLD_GLOBAL;
683         } else {
684                 /* Resource modules are always loaded global and lazy */
685                 flags = (RTLD_GLOBAL | RTLD_LAZY);
686         }
687         
688         if (AST_LIST_LOCK(&module_list))
689                 ast_log(LOG_WARNING, "Failed to lock\n");
690         if (resource_exists(resource_name, 0)) {
691                 ast_log(LOG_WARNING, "Module '%s' already exists\n", resource_name);
692                 AST_LIST_UNLOCK(&module_list);
693                 return NULL;
694         }
695         if (!(cur = ast_calloc(1, sizeof(*cur)))) {
696                 AST_LIST_UNLOCK(&module_list);
697                 return NULL;
698         }
699         ast_copy_string(cur->resource, resource_name, sizeof(cur->resource));
700         if (resource_name[0] == '/')
701                 ast_copy_string(fn, resource_name, sizeof(fn));
702         else
703                 snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_MODULE_DIR, resource_name);
704
705         /* open in a sane way */
706         cur->lib = dlopen(fn, RTLD_NOW | RTLD_LOCAL);
707         if (cur->lib &&
708                     ((m = find_symbol(cur, "mod_data", 0)) == NULL || (m->flags & MOD_MASK) == MOD_0)) {
709                 /* old-style module, close and reload with standard flags */
710                 dlclose(cur->lib);
711                 cur->lib = NULL;
712                 m = NULL;
713         }
714         if (cur->lib == NULL)   /* try reopen with the old style */
715                 cur->lib = dlopen(fn, flags);
716
717         if (!cur->lib) {
718                 ast_log(LOG_WARNING, "%s\n", dlerror());
719                 free(cur);
720                 AST_LIST_UNLOCK(&module_list);
721                 return NULL;
722         }
723         if (m == NULL)  /* MOD_0 modules may still have a mod_data entry */
724                 m = find_symbol(cur, "mod_data", 0);
725         if (m != NULL) {        /* new style module */
726                 ast_log(LOG_WARNING, "new style %s (0x%x) loaded RTLD_LOCAL\n",
727                         resource_name, m->flags);
728                 cur->cb = m;    /* use the mod_data from the module itself */
729                 errors = check_exported(cur);
730         } else {
731                 ast_log(LOG_WARNING, "misstng mod_data for %s\n",
732                         resource_name);
733                 errors++;
734         }
735         if (!m->load_module)
736                 errors++;
737         if (!m->unload_module && !(m->flags & NO_UNLOAD) )
738                 errors++;
739         if (!m->description)
740                 errors++;
741         if (!m->key)
742                 errors++;
743         if (!m->key || !(key = (unsigned char *) m->key())) {
744                 ast_log(LOG_WARNING, "Key routine returned NULL in module %s\n", fn);
745                 key = NULL;
746                 errors++;
747         }
748         if (key && verify_key(key)) {
749                 ast_log(LOG_WARNING, "Unexpected key returned by module %s\n", fn);
750                 errors++;
751         }
752         if (errors) {
753                 ast_log(LOG_WARNING, "%d error%s loading module %s, aborted\n", errors, (errors != 1) ? "s" : "", fn);
754                 dlclose(cur->lib);
755                 free(cur);
756                 AST_LIST_UNLOCK(&module_list);
757                 return NULL;
758         }
759         /* init mutex and usecount */
760         ast_mutex_init(&cur->cb->lock);
761         cur->cb->lu_head = NULL;
762
763         if (!ast_fully_booted) {
764                 if (option_verbose) 
765                         ast_verbose( " => (%s)\n", term_color(tmp, m->description(), COLOR_BROWN, COLOR_BLACK, sizeof(tmp)));
766                 if (ast_opt_console && !option_verbose)
767                         ast_verbose( ".");
768         } else {
769                 if (option_verbose)
770                         ast_verbose(VERBOSE_PREFIX_1 "Loaded %s => (%s)\n", fn, m->description());
771         }
772
773         AST_LIST_INSERT_TAIL(&module_list, cur, next);
774         /* add module to end of module_list chain
775            so reload commands will be issued in same order modules were loaded */
776         
777         modlistver++;
778         if ( (m->flags & MOD_MASK) == MOD_2) {
779                 ast_log(LOG_WARNING, "new-style module %s, deferring load()\n",
780                         resource_name);
781                 cur->state = MS_NEW;
782         } else
783                 cur->state = MS_CANLOAD;
784         /* XXX make sure the usecount is 1 before releasing the lock */
785         AST_LIST_UNLOCK(&module_list);
786         
787         if (cur->state == MS_CANLOAD && (res = m->load_module(m))) {
788                 ast_log(LOG_WARNING, "%s: load_module failed, returning %d\n", resource_name, res);
789                 ast_unload_resource(resource_name, 0);
790                 return NULL;
791         }
792         cur->state = MS_ACTIVE;
793         ast_update_use_count();
794         return cur;
795 }
796
797 /*!
798  * \brief load a single module (API call).
799  * (recursive calls from load_module() succeed.
800  * \return Returns 0 on success, -1 on error.
801  */
802 int ast_load_resource(const char *resource_name)
803 {
804         int o = option_verbose;
805         struct ast_config *cfg = NULL;
806         struct module *m;
807
808         option_verbose = 0;     /* Keep the module file parsing silent */
809         cfg = ast_config_load(AST_MODULE_CONFIG);
810         option_verbose = o;     /* restore verbosity */
811         m = __load_resource(resource_name, cfg);
812         if (cfg)
813                 ast_config_destroy(cfg);
814         return m ? 0 : -1;
815 }       
816
817 #if 0
818 /*
819  * load a single module (API call).
820  * (recursive calls from load_module() succeed.
821  */
822 int ast_load_resource(const char *resource_name)
823 {
824        struct module *m;
825        int ret;
826
827        ast_mutex_lock(&modlock);
828        m = __load_resource(resource_name, 0);
829        fixup(resource_name);
830        ret = (m->state == MS_FAILED) ? -1 : 0;
831        ast_mutex_unlock(&modlock);
832        return ret;
833 }
834 #endif
835
836 /*! \brief if enabled, log and output on console the module's name, and try load it */
837 static int print_and_load(const char *s, struct ast_config *cfg)
838 {
839         char tmp[80];
840
841         if (option_debug && !option_verbose)
842                 ast_log(LOG_DEBUG, "Loading module %s\n", s);
843         if (option_verbose) {
844                 ast_verbose(VERBOSE_PREFIX_1 "[%s]",
845                         term_color(tmp, s, COLOR_BRWHITE, 0, sizeof(tmp)));
846                 fflush(stdout);
847         }
848         if (__load_resource(s, cfg))
849                 return 0; /* success */
850         ast_log(LOG_WARNING, "Loading module %s failed!\n", s);
851         return -1;
852 }
853
854 static const char *loadorder[] =
855 {
856         "res_",
857         "pbx_",
858         "chan_",
859         NULL,
860 };
861
862 int load_modules(const int preload_only)
863 {
864         struct ast_config *cfg;
865         int x;
866
867         if (option_verbose) {
868                 ast_verbose(preload_only ?
869                         "Asterisk Dynamic Loader loading preload modules:\n" :
870                         "Asterisk Dynamic Loader Starting:\n");
871         }
872
873         if (0)
874                 check_symbols();
875
876         cfg = ast_config_load(AST_MODULE_CONFIG);
877
878         if (cfg) {
879                 const char *cmd = preload_only ? "preload" : "load";
880                 struct ast_variable *v;
881                 /* Load explicitly defined modules */
882                 for (v = ast_variable_browse(cfg, "modules"); v; v = v->next) {
883                         if (strcasecmp(v->name, cmd)) /* not what we are looking for */
884                                 continue;
885                         if (print_and_load(v->value, cfg)) {    /* XXX really fatal ? */
886                                 ast_config_destroy(cfg);
887                                 return -1;
888                         }
889                 }
890         }
891
892         if (preload_only)
893                 goto done;
894
895         if (cfg && !ast_true(ast_variable_retrieve(cfg, "modules", "autoload")))
896                 /* no autoload */
897                 goto done;
898         /*
899          * Load all modules. To help resolving dependencies, we load modules
900          * in the order defined by loadorder[], with the final step for
901          * all modules with other prefixes.
902          * (XXX the new loader does not need this).
903          */
904
905         for (x=0; x<sizeof(loadorder) / sizeof(loadorder[0]); x++) {
906                 struct dirent *d;
907                 DIR *mods = opendir(ast_config_AST_MODULE_DIR);
908                 const char *base = loadorder[x];
909                 int lx = base ? strlen(base) : 0;
910
911                 if (!mods) {
912                         if (!ast_opt_quiet)
913                                 ast_log(LOG_WARNING, "Unable to open modules directory %s.\n",
914                                         ast_config_AST_MODULE_DIR);
915                         break; /* suffices to try once! */
916                 }
917                 while((d = readdir(mods))) {
918                         int ld = strlen(d->d_name);
919                         /* Must end in .so to load it.  */
920                         if (ld > 3 && (!base || !strncasecmp(d->d_name, base, lx)) && 
921                                         !strcasecmp(d->d_name + ld - 3, ".so") &&
922                                         !resource_exists(d->d_name, 1)) {
923                                 /* It's a shared library, check if we are allowed to load it
924                                  * (very inefficient, but oh well).
925                                  */
926                                 if (cfg) {
927                                         struct ast_variable *v;
928                                         for (v = ast_variable_browse(cfg, "modules"); v; v = v->next) {
929                                                 if (!strcasecmp(v->name, "noload") &&
930                                                                 !strcasecmp(v->value, d->d_name)) 
931                                                         break;
932                                         }
933                                         if (v) {
934                                                 if (option_verbose) {
935                                                         ast_verbose( VERBOSE_PREFIX_1 "[skipping %s]\n",
936                                                                         d->d_name);
937                                                         fflush(stdout);
938                                                 }
939                                                 continue;
940                                         }
941                                         
942                                 }
943                                 if (print_and_load(d->d_name, cfg)) {
944                                         ast_config_destroy(cfg);
945                                         return -1;
946                                 }
947                         }
948                 }
949                 closedir(mods);
950         }
951 done:
952         fixup("load_modules");
953         ast_config_destroy(cfg);
954         return 0;
955 }
956
957 #include <errno.h>      /* for errno... */
958
959 void ast_update_use_count(void)
960 {
961         /* Notify any module monitors that the use count for a 
962            resource has changed */
963         struct loadupdate *m;
964         if (AST_LIST_LOCK(&module_list))
965                 ast_log(LOG_WARNING, "Failed to lock, errno %d\n", errno);
966         AST_LIST_TRAVERSE(&updaters, m, next)
967                 m->updater();
968         AST_LIST_UNLOCK(&module_list);
969 }
970
971 int ast_update_module_list(int (*modentry)(const char *module, const char *description, int usecnt, const char *like),
972                            const char *like)
973 {
974         struct module *cur;
975         int unlock = -1;
976         int total_mod_loaded = 0;
977
978         if (ast_mutex_trylock(&module_list.lock))
979                 unlock = 0;
980         AST_LIST_TRAVERSE(&module_list, cur, next) {
981                 total_mod_loaded += modentry(cur->resource, cur->cb->description(), cur->cb->usecnt, like);
982         }
983         if (unlock)
984                 AST_LIST_UNLOCK(&module_list);
985
986         return total_mod_loaded;
987 }
988
989 int ast_loader_register(int (*v)(void)) 
990 {
991         /* XXX Should be more flexible here, taking > 1 verboser XXX */
992         struct loadupdate *tmp; 
993         if (!(tmp = ast_malloc(sizeof(*tmp))))
994                 return -1;
995         tmp->updater = v;
996         if (AST_LIST_LOCK(&module_list))
997                 ast_log(LOG_WARNING, "Failed to lock\n");
998         AST_LIST_INSERT_HEAD(&updaters, tmp, next);
999         AST_LIST_UNLOCK(&module_list);
1000         return 0;
1001 }
1002
1003 int ast_loader_unregister(int (*v)(void))
1004 {
1005         struct loadupdate *cur;
1006
1007         if (AST_LIST_LOCK(&module_list))
1008                 ast_log(LOG_WARNING, "Failed to lock\n");
1009         AST_LIST_TRAVERSE_SAFE_BEGIN(&updaters, cur, next) {
1010                 if (cur->updater == v)  {
1011                         AST_LIST_REMOVE_CURRENT(&updaters, next);
1012                         break;
1013                 }
1014         }
1015         AST_LIST_TRAVERSE_SAFE_END;
1016         AST_LIST_UNLOCK(&module_list);
1017         return cur ? 0 : -1;
1018 }