make Local channel return sensible device state values
[asterisk-bristuff.git] / loader.c
blob790c678d2c61169df9479e05027a5a6810e34c83
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Module Loader
23 * \author Mark Spencer <markster@digium.com>
24 * - See ModMngMnt
27 #define MOD_LOADER /* prevent some module-specific stuff from being compiled */
28 #include "asterisk.h"
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32 #include <stdio.h>
33 #include <dirent.h>
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <string.h>
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"
59 #ifndef RTLD_NOW
60 #define RTLD_NOW 0
61 #endif
63 static int modlistver = 0; /* increase whenever the list changes, to protect reload */
65 static unsigned char expected_key[] =
66 { 0x87, 0x76, 0x79, 0x35, 0x23, 0xea, 0x3a, 0xd3,
67 0x25, 0x2a, 0xbb, 0x35, 0x87, 0xe4, 0x22, 0x24 };
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.
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 */
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.
91 * Both lists (basically, the entire loader) are protected by
92 * the lock in module_list.
94 * A second lock, reloadlock, is used to prevent concurrent reloads
96 struct module {
97 AST_LIST_ENTRY(module) next;
98 struct module_symbols *cb;
99 void *lib; /* the shared lib */
100 char resource[256];
102 enum st_t state;
103 int export_refcount; /* how many users of exported symbols */
106 struct loadupdate {
107 AST_LIST_ENTRY(loadupdate) next;
108 int (*updater)(void);
111 static AST_LIST_HEAD_STATIC(module_list, module);
112 static AST_LIST_HEAD_STATIC(updaters, loadupdate);
113 AST_MUTEX_DEFINE_STATIC(reloadlock);
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.
122 struct localuser *ast_localuser_add(struct module_symbols *me,
123 struct ast_channel *chan)
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;
138 void ast_localuser_remove(struct module_symbols *me, struct localuser *u)
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;
152 ast_mutex_unlock(&me->lock);
153 ast_atomic_fetchadd_int(&me->usecnt, -1);
154 free(u);
155 ast_update_use_count();
158 void ast_hangup_localusers(struct module_symbols *me)
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);
168 ast_mutex_unlock(&me->lock);
169 ast_update_use_count();
172 /*--- new-style loader routines ---*/
175 * For backward compatibility, we have 3 types of loadable modules:
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.
183 * MOD_1 The generic callbacks are all into a structure, mod_data.
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.
195 * helper routine to print the symbolic name associated to a state
197 static const char *st_name(enum st_t state)
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";
211 return st;
212 #undef ST
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.
222 * Must be called with the lock held.
224 static void *module_symbol_helper(const char *name,
225 int delta, struct module **src)
227 void *ret = NULL;
228 struct module *m;
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;
243 if (ret)
244 break;
246 if (ret == NULL)
247 ast_log(LOG_WARNING, "symbol %s not found\n", name);
248 return ret;
251 static void *release_module_symbol(const char *name)
253 return module_symbol_helper(name, -1, NULL);
256 static void *get_module_symbol(const char *name, struct module **src)
258 return module_symbol_helper(name, +1, src);
262 * \brief Release refcounts to all imported symbols,
263 * and change module state to MS_FAILED.
265 static void release_module(struct module *m)
267 struct symbol_entry *s;
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;
275 m->state = MS_FAILED;
278 /*! \brief check that no NULL symbols are exported - the algorithms rely on that. */
279 static int check_exported(struct module *m)
281 struct symbol_entry *es = m->cb->exported_symbols;
282 int errors = 0;
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;
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++;
301 return errors;
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.
313 static int resolve(struct module *m)
315 struct symbol_entry *s;
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.
323 m->state = MS_CANLOAD;
324 for (s = m->cb->required_symbols; s && s->name != NULL; s++) {
325 void **p = (void **)(s->value);
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;
336 if (s->src->state != MS_ACTIVE)
337 m->state = MS_RESOLVED; /* downgrade */
339 return 1;
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.
365 static int fixup(const char *caller)
367 struct module *m;
368 int total = 0, new = 0, cycle = 0;
369 static int in_fixup = 0; /* disable recursive calls */
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);
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 */
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;
410 again = 1; /* something has changed */
412 /* Modules in MS_RESOLVED mean a possible cyclic dependency.
413 * Break the indecision by setting one to CANLOAD, and repeat.
415 AST_LIST_TRAVERSE(&module_list, m, next) {
416 if (m->state == MS_RESOLVED) {
417 m->state = MS_CANLOAD;
418 again = 1;
419 break;
422 if (!again) /* we are done */
423 break;
425 ast_log(LOG_DEBUG, "---- fixup complete ---\n");
426 in_fixup--;
427 return 0;
430 /* test routines to see which modules depend on global symbols
431 * exported by other modules.
433 static void check_symbols(void)
435 struct dirent *d;
436 DIR *mods = opendir(ast_config_AST_MODULE_DIR);
437 void *lib;
438 char buf[1024];
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());
453 dlclose(lib);
456 /*--- end new-style routines ---*/
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.
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 }
477 static int printdigest(const unsigned char *d)
479 int x, pos;
480 char buf[256]; /* large enough so we don't have to worry */
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;
488 static int key_matches(const unsigned char *key1, const unsigned char *key2)
490 int x;
491 for (x=0; x<16; x++) {
492 if (key1[x] != key2[x]) /* mismatch - fail now. */
493 return 0;
495 return 1;
498 static int verify_key(const unsigned char *key)
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;
511 int ast_unload_resource(const char *resource_name, enum unload_mode force)
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;
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;
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");
542 release_module(cur); /* XXX */
543 AST_LIST_REMOVE_CURRENT(&module_list, next);
544 dlclose(cur->lib);
545 free(cur);
546 break;
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;
557 char *ast_module_helper(const char *line, const char *word, int pos, int state, int rpos, int needsreload)
559 struct module *cur;
560 int i, which=0, l = strlen(word);
561 char *ret = NULL;
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;
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);
580 return ret;
583 int ast_module_reload(const char *name)
585 struct module *cur;
586 int res = 0; /* return value. 0 = not found, others, see below */
587 int i, oldversion;
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 */
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 */
600 ast_lastreloadtime = time(NULL);
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;
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;
623 AST_LIST_UNLOCK(&module_list);
624 ast_mutex_unlock(&reloadlock);
625 return res;
628 static int resource_exists(const char *resource, int do_lock)
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;
637 if (do_lock)
638 AST_LIST_UNLOCK(&module_list);
639 return cur ? -1 : 0;
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)
645 char *n1;
646 void *s;
648 if (name[0] == '_')
649 name++;
650 n1 = alloca(strlen(name) + 2); /* room for leading '_' and final '\0' */
651 n1[0] = '_';
652 strcpy(n1+1, name);
653 s = dlsym(m->lib, n1+1); /* try without '_' */
654 if (s == NULL)
655 s = dlsym(m->lib, n1);
656 if (verbose && s == NULL)
657 ast_log(LOG_WARNING, "No symbol '%s' in module '%s\n",
658 n1, m->resource);
659 return s;
662 /* XXX cfg is only used for !res_* and #ifdef RTLD_GLOBAL */
663 static struct module * __load_resource(const char *resource_name,
664 const struct ast_config *cfg)
666 static char fn[256];
667 int errors=0;
668 int res;
669 struct module *cur;
670 struct module_symbols *m = NULL;
671 int flags = RTLD_NOW;
672 unsigned char *key;
673 char tmp[80];
675 #ifndef RTLD_GLOBAL
676 #define RTLD_GLOBAL 0 /* so it is a No-op */
677 #endif
678 if (strncasecmp(resource_name, "res_", 4) && cfg) {
679 char *val = ast_variable_retrieve(cfg, "global", resource_name);
680 if (val && ast_true(val))
681 flags |= RTLD_GLOBAL;
682 } else {
683 /* Resource modules are always loaded global and lazy */
684 flags = (RTLD_GLOBAL | RTLD_LAZY);
687 if (AST_LIST_LOCK(&module_list))
688 ast_log(LOG_WARNING, "Failed to lock\n");
689 if (resource_exists(resource_name, 0)) {
690 ast_log(LOG_WARNING, "Module '%s' already exists\n", resource_name);
691 AST_LIST_UNLOCK(&module_list);
692 return NULL;
694 if (!(cur = ast_calloc(1, sizeof(*cur)))) {
695 AST_LIST_UNLOCK(&module_list);
696 return NULL;
698 ast_copy_string(cur->resource, resource_name, sizeof(cur->resource));
699 if (resource_name[0] == '/')
700 ast_copy_string(fn, resource_name, sizeof(fn));
701 else
702 snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_MODULE_DIR, resource_name);
704 /* open in a sane way */
705 cur->lib = dlopen(fn, RTLD_NOW | RTLD_LOCAL);
706 if (cur->lib &&
707 ((m = find_symbol(cur, "mod_data", 0)) == NULL || (m->flags & MOD_MASK) == MOD_0)) {
708 /* old-style module, close and reload with standard flags */
709 dlclose(cur->lib);
710 cur->lib = NULL;
711 m = NULL;
713 if (cur->lib == NULL) /* try reopen with the old style */
714 cur->lib = dlopen(fn, flags);
716 if (!cur->lib) {
717 ast_log(LOG_WARNING, "%s\n", dlerror());
718 free(cur);
719 AST_LIST_UNLOCK(&module_list);
720 return NULL;
722 if (m == NULL) /* MOD_0 modules may still have a mod_data entry */
723 m = find_symbol(cur, "mod_data", 0);
724 if (m != NULL) { /* new style module */
725 cur->cb = m; /* use the mod_data from the module itself */
726 errors = check_exported(cur);
727 } else {
728 ast_log(LOG_WARNING, "missing mod_data for %s\n",
729 resource_name);
730 errors++;
732 if (!m->load_module)
733 errors++;
734 if (!m->unload_module && !(m->flags & NO_UNLOAD) )
735 errors++;
736 if (!m->description)
737 errors++;
738 if (!m->key)
739 errors++;
740 if (!m->key || !(key = (unsigned char *) m->key())) {
741 ast_log(LOG_WARNING, "Key routine returned NULL in module %s\n", fn);
742 key = NULL;
743 errors++;
745 if (key && verify_key(key)) {
746 ast_log(LOG_WARNING, "Unexpected key returned by module %s\n", fn);
747 errors++;
749 if (errors) {
750 ast_log(LOG_WARNING, "%d error%s loading module %s, aborted\n", errors, (errors != 1) ? "s" : "", fn);
751 dlclose(cur->lib);
752 free(cur);
753 AST_LIST_UNLOCK(&module_list);
754 return NULL;
756 /* init mutex and usecount */
757 ast_mutex_init(&cur->cb->lock);
758 cur->cb->lu_head = NULL;
760 if (!ast_fully_booted) {
761 if (option_verbose)
762 ast_verbose( " => (%s)\n", term_color(tmp, m->description(), COLOR_BROWN, COLOR_BLACK, sizeof(tmp)));
763 if (ast_opt_console && !option_verbose)
764 ast_verbose( ".");
765 } else {
766 if (option_verbose)
767 ast_verbose(VERBOSE_PREFIX_1 "Loaded %s => (%s)\n", fn, m->description());
770 AST_LIST_INSERT_TAIL(&module_list, cur, next);
771 /* add module to end of module_list chain
772 so reload commands will be issued in same order modules were loaded */
774 modlistver++;
775 if ( (m->flags & MOD_MASK) == MOD_2) {
776 ast_log(LOG_WARNING, "new-style module %s, deferring load()\n",
777 resource_name);
778 cur->state = MS_NEW;
779 } else
780 cur->state = MS_CANLOAD;
781 /* XXX make sure the usecount is 1 before releasing the lock */
782 AST_LIST_UNLOCK(&module_list);
784 if (cur->state == MS_CANLOAD && (res = m->load_module(m))) {
785 ast_log(LOG_WARNING, "%s: load_module failed, returning %d\n", resource_name, res);
786 ast_unload_resource(resource_name, 0);
787 return NULL;
789 cur->state = MS_ACTIVE;
790 ast_update_use_count();
791 return cur;
795 * \brief load a single module (API call).
796 * (recursive calls from load_module() succeed.
797 * \return Returns 0 on success, -1 on error.
799 int ast_load_resource(const char *resource_name)
801 int o = option_verbose;
802 struct ast_config *cfg = NULL;
803 struct module *m;
805 option_verbose = 0; /* Keep the module file parsing silent */
806 cfg = ast_config_load(AST_MODULE_CONFIG);
807 option_verbose = o; /* restore verbosity */
808 m = __load_resource(resource_name, cfg);
809 if (cfg)
810 ast_config_destroy(cfg);
811 return m ? 0 : -1;
814 #if 0
816 * load a single module (API call).
817 * (recursive calls from load_module() succeed.
819 int ast_load_resource(const char *resource_name)
821 struct module *m;
822 int ret;
824 ast_mutex_lock(&modlock);
825 m = __load_resource(resource_name, 0);
826 fixup(resource_name);
827 ret = (m->state == MS_FAILED) ? -1 : 0;
828 ast_mutex_unlock(&modlock);
829 return ret;
831 #endif
833 /*! \brief if enabled, log and output on console the module's name, and try load it */
834 static int print_and_load(const char *s, struct ast_config *cfg)
836 char tmp[80];
838 if (option_debug && !option_verbose)
839 ast_log(LOG_DEBUG, "Loading module %s\n", s);
840 if (option_verbose) {
841 ast_verbose(VERBOSE_PREFIX_1 "[%s]",
842 term_color(tmp, s, COLOR_BRWHITE, 0, sizeof(tmp)));
843 fflush(stdout);
845 if (__load_resource(s, cfg))
846 return 0; /* success */
847 ast_log(LOG_WARNING, "Loading module %s failed!\n", s);
848 return -1;
851 static const char *loadorder[] =
853 "res_",
854 "pbx_",
855 "chan_",
856 NULL,
859 int load_modules(const int preload_only)
861 struct ast_config *cfg;
862 int x;
864 if (option_verbose) {
865 ast_verbose(preload_only ?
866 "Asterisk Dynamic Loader loading preload modules:\n" :
867 "Asterisk Dynamic Loader Starting:\n");
870 if (0)
871 check_symbols();
873 cfg = ast_config_load(AST_MODULE_CONFIG);
875 if (cfg) {
876 const char *cmd = preload_only ? "preload" : "load";
877 struct ast_variable *v;
878 /* Load explicitly defined modules */
879 for (v = ast_variable_browse(cfg, "modules"); v; v = v->next) {
880 if (strcasecmp(v->name, cmd)) /* not what we are looking for */
881 continue;
882 if (print_and_load(v->value, cfg)) { /* XXX really fatal ? */
883 ast_config_destroy(cfg);
884 return -1;
889 if (preload_only)
890 goto done;
892 if (cfg && !ast_true(ast_variable_retrieve(cfg, "modules", "autoload")))
893 /* no autoload */
894 goto done;
896 * Load all modules. To help resolving dependencies, we load modules
897 * in the order defined by loadorder[], with the final step for
898 * all modules with other prefixes.
899 * (XXX the new loader does not need this).
902 for (x=0; x<sizeof(loadorder) / sizeof(loadorder[0]); x++) {
903 struct dirent *d;
904 DIR *mods = opendir(ast_config_AST_MODULE_DIR);
905 const char *base = loadorder[x];
906 int lx = base ? strlen(base) : 0;
908 if (!mods) {
909 if (!ast_opt_quiet)
910 ast_log(LOG_WARNING, "Unable to open modules directory %s.\n",
911 ast_config_AST_MODULE_DIR);
912 break; /* suffices to try once! */
914 while((d = readdir(mods))) {
915 int ld = strlen(d->d_name);
916 /* Must end in .so to load it. */
917 if (ld > 3 && (!base || !strncasecmp(d->d_name, base, lx)) &&
918 !strcasecmp(d->d_name + ld - 3, ".so") &&
919 !resource_exists(d->d_name, 1)) {
920 /* It's a shared library, check if we are allowed to load it
921 * (very inefficient, but oh well).
923 if (cfg) {
924 struct ast_variable *v;
925 for (v = ast_variable_browse(cfg, "modules"); v; v = v->next) {
926 if (!strcasecmp(v->name, "noload") &&
927 !strcasecmp(v->value, d->d_name))
928 break;
930 if (v) {
931 if (option_verbose) {
932 ast_verbose( VERBOSE_PREFIX_1 "[skipping %s]\n",
933 d->d_name);
934 fflush(stdout);
936 continue;
940 if (print_and_load(d->d_name, cfg)) {
941 ast_config_destroy(cfg);
942 return -1;
946 closedir(mods);
948 done:
949 fixup("load_modules");
950 ast_config_destroy(cfg);
951 return 0;
954 #include <errno.h> /* for errno... */
956 void ast_update_use_count(void)
958 /* Notify any module monitors that the use count for a
959 resource has changed */
960 struct loadupdate *m;
961 if (AST_LIST_LOCK(&module_list))
962 ast_log(LOG_WARNING, "Failed to lock, errno %d\n", errno);
963 AST_LIST_TRAVERSE(&updaters, m, next)
964 m->updater();
965 AST_LIST_UNLOCK(&module_list);
968 int ast_update_module_list(int (*modentry)(const char *module, const char *description, int usecnt, const char *like),
969 const char *like)
971 struct module *cur;
972 int unlock = -1;
973 int total_mod_loaded = 0;
975 if (ast_mutex_trylock(&module_list.lock))
976 unlock = 0;
977 AST_LIST_TRAVERSE(&module_list, cur, next) {
978 total_mod_loaded += modentry(cur->resource, cur->cb->description(), cur->cb->usecnt, like);
980 if (unlock)
981 AST_LIST_UNLOCK(&module_list);
983 return total_mod_loaded;
986 int ast_loader_register(int (*v)(void))
988 /* XXX Should be more flexible here, taking > 1 verboser XXX */
989 struct loadupdate *tmp;
990 if (!(tmp = ast_malloc(sizeof(*tmp))))
991 return -1;
992 tmp->updater = v;
993 if (AST_LIST_LOCK(&module_list))
994 ast_log(LOG_WARNING, "Failed to lock\n");
995 AST_LIST_INSERT_HEAD(&updaters, tmp, next);
996 AST_LIST_UNLOCK(&module_list);
997 return 0;
1000 int ast_loader_unregister(int (*v)(void))
1002 struct loadupdate *cur;
1004 if (AST_LIST_LOCK(&module_list))
1005 ast_log(LOG_WARNING, "Failed to lock\n");
1006 AST_LIST_TRAVERSE_SAFE_BEGIN(&updaters, cur, next) {
1007 if (cur->updater == v) {
1008 AST_LIST_REMOVE_CURRENT(&updaters, next);
1009 break;
1012 AST_LIST_TRAVERSE_SAFE_END;
1013 AST_LIST_UNLOCK(&module_list);
1014 return cur ? 0 : -1;