Merged revisions 8162 via svnmerge from
[asterisk/asterisk.git] / loader.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, 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  */
25
26 #include <stdio.h>
27 #include <dirent.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31
32 #include "asterisk.h"
33
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35
36 #include "asterisk/module.h"
37 #include "asterisk/options.h"
38 #include "asterisk/config.h"
39 #include "asterisk/logger.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/term.h"
42 #include "asterisk/manager.h"
43 #include "asterisk/cdr.h"
44 #include "asterisk/enum.h"
45 #include "asterisk/rtp.h"
46 #include "asterisk/lock.h"
47 #ifdef DLFCNCOMPAT
48 #include "asterisk/dlfcn-compat.h"
49 #else
50 #include <dlfcn.h>
51 #endif
52 #include "asterisk/md5.h"
53
54 #ifndef RTLD_NOW
55 #define RTLD_NOW 0
56 #endif
57
58 AST_MUTEX_DEFINE_STATIC(modlock);
59 AST_MUTEX_DEFINE_STATIC(reloadlock);
60
61 static struct module *module_list=NULL;
62 static int modlistver = 0;
63
64 static unsigned char expected_key[] =
65 { 0x8e, 0x93, 0x22, 0x83, 0xf5, 0xc3, 0xc0, 0x75,
66   0xff, 0x8b, 0xa9, 0xbe, 0x7c, 0x43, 0x74, 0x63 };
67
68 struct module {
69         int (*load_module)(void);
70         int (*unload_module)(void);
71         int (*usecount)(void);
72         char *(*description)(void);
73         char *(*key)(void);
74         int (*reload)(void);
75         void *lib;
76         char resource[256];
77         struct module *next;
78 };
79
80 static struct loadupdate {
81         int (*updater)(void);
82         struct loadupdate *next;
83 } *updaters = NULL;
84
85 static int printdigest(unsigned char *d)
86 {
87         int x;
88         char buf[256];
89         char buf2[16];
90         snprintf(buf, sizeof(buf), "Unexpected signature:");
91         for (x=0; x<16; x++) {
92                 snprintf(buf2, sizeof(buf2), " %02x", *(d++));
93                 strcat(buf, buf2);
94         }
95         strcat(buf, "\n");
96         ast_log(LOG_DEBUG, "%s", buf);
97         return 0;
98 }
99
100 static int key_matches(unsigned char *key1, unsigned char *key2)
101 {
102         int match = 1;
103         int x;
104         for (x=0; x<16; x++) {
105                 match &= (key1[x] == key2[x]);
106         }
107         return match;
108 }
109
110 static int verify_key(unsigned char *key)
111 {
112         struct MD5Context c;
113         unsigned char digest[16];
114         MD5Init(&c);
115         MD5Update(&c, key, strlen((char *)key));
116         MD5Final(digest, &c);
117         if (key_matches(expected_key, digest))
118                 return 0;
119         printdigest(digest);
120         return -1;
121 }
122
123 int ast_unload_resource(const char *resource_name, int force)
124 {
125         struct module *m, *ml = NULL;
126         int res = -1;
127         if (ast_mutex_lock(&modlock))
128                 ast_log(LOG_WARNING, "Failed to lock\n");
129         m = module_list;
130         while(m) {
131                 if (!strcasecmp(m->resource, resource_name)) {
132                         if ((res = m->usecount()) > 0)  {
133                                 if (force) 
134                                         ast_log(LOG_WARNING, "Warning:  Forcing removal of module %s with use count %d\n", resource_name, res);
135                                 else {
136                                         ast_log(LOG_WARNING, "Soft unload failed, '%s' has use count %d\n", resource_name, res);
137                                         ast_mutex_unlock(&modlock);
138                                         return -1;
139                                 }
140                         }
141                         res = m->unload_module();
142                         if (res) {
143                                 ast_log(LOG_WARNING, "Firm unload failed for %s\n", resource_name);
144                                 if (force <= AST_FORCE_FIRM) {
145                                         ast_mutex_unlock(&modlock);
146                                         return -1;
147                                 } else
148                                         ast_log(LOG_WARNING, "** Dangerous **: Unloading resource anyway, at user request\n");
149                         }
150                         if (ml)
151                                 ml->next = m->next;
152                         else
153                                 module_list = m->next;
154                         dlclose(m->lib);
155                         free(m);
156                         break;
157                 }
158                 ml = m;
159                 m = m->next;
160         }
161         modlistver = rand();
162         ast_mutex_unlock(&modlock);
163         ast_update_use_count();
164         return res;
165 }
166
167 char *ast_module_helper(char *line, char *word, int pos, int state, int rpos, int needsreload)
168 {
169         struct module *m;
170         int which=0;
171         char *ret;
172
173         if (pos != rpos)
174                 return NULL;
175         ast_mutex_lock(&modlock);
176         m = module_list;
177         while(m) {
178                 if (!strncasecmp(word, m->resource, strlen(word)) && (m->reload || !needsreload)) {
179                         if (++which > state)
180                                 break;
181                 }
182                 m = m->next;
183         }
184         if (m) {
185                 ret = strdup(m->resource);
186         } else {
187                 ret = NULL;
188                 if (!strncasecmp(word, "extconfig", strlen(word))) {
189                         if (++which > state)
190                                 ret = strdup("extconfig");
191                 } else if (!strncasecmp(word, "manager", strlen(word))) {
192                         if (++which > state)
193                                 ret = strdup("manager");
194                 } else if (!strncasecmp(word, "enum", strlen(word))) {
195                         if (++which > state)
196                                 ret = strdup("enum");
197                 } else if (!strncasecmp(word, "rtp", strlen(word))) {
198                         if (++which > state)
199                                 ret = strdup("rtp");
200                 }
201                         
202         }
203         ast_mutex_unlock(&modlock);
204         return ret;
205 }
206
207 int ast_module_reload(const char *name)
208 {
209         struct module *m;
210         int reloaded = 0;
211         int oldversion;
212         int (*reload)(void);
213         /* We'll do the logger and manager the favor of calling its reload here first */
214
215         if (ast_mutex_trylock(&reloadlock)) {
216                 ast_verbose("The previous reload command didn't finish yet\n");
217                 return -1;
218         }
219         if (!name || !strcasecmp(name, "extconfig")) {
220                 read_config_maps();
221                 reloaded = 2;
222         }
223         if (!name || !strcasecmp(name, "manager")) {
224                 reload_manager();
225                 reloaded = 2;
226         }
227         if (!name || !strcasecmp(name, "cdr")) {
228                 ast_cdr_engine_reload();
229                 reloaded = 2;
230         }
231         if (!name || !strcasecmp(name, "enum")) {
232                 ast_enum_reload();
233                 reloaded = 2;
234         }
235         if (!name || !strcasecmp(name, "rtp")) {
236                 ast_rtp_reload();
237                 reloaded = 2;
238         }
239         if (!name || !strcasecmp(name, "dnsmgr")) {
240                 dnsmgr_reload();
241                 reloaded = 2;
242         }
243         time(&ast_lastreloadtime);
244
245         ast_mutex_lock(&modlock);
246         oldversion = modlistver;
247         m = module_list;
248         while(m) {
249                 if (!name || !strcasecmp(name, m->resource)) {
250                         if (reloaded < 1)
251                                 reloaded = 1;
252                         reload = m->reload;
253                         ast_mutex_unlock(&modlock);
254                         if (reload) {
255                                 reloaded = 2;
256                                 if (option_verbose > 2) 
257                                         ast_verbose(VERBOSE_PREFIX_3 "Reloading module '%s' (%s)\n", m->resource, m->description());
258                                 reload();
259                         }
260                         ast_mutex_lock(&modlock);
261                         if (oldversion != modlistver)
262                                 break;
263                 }
264                 m = m->next;
265         }
266         ast_mutex_unlock(&modlock);
267         ast_mutex_unlock(&reloadlock);
268         return reloaded;
269 }
270
271 static int __load_resource(const char *resource_name, const struct ast_config *cfg)
272 {
273         static char fn[256];
274         int errors=0;
275         int res;
276         struct module *m;
277         int flags=RTLD_NOW;
278 #ifdef RTLD_GLOBAL
279         char *val;
280 #endif
281         unsigned char *key;
282         char tmp[80];
283
284         if (strncasecmp(resource_name, "res_", 4)) {
285 #ifdef RTLD_GLOBAL
286                 if (cfg) {
287                         if ((val = ast_variable_retrieve(cfg, "global", resource_name))
288                                         && ast_true(val))
289                                 flags |= RTLD_GLOBAL;
290                 }
291 #endif
292         } else {
293                 /* Resource modules are always loaded global and lazy */
294 #ifdef RTLD_GLOBAL
295                 flags = (RTLD_GLOBAL | RTLD_LAZY);
296 #else
297                 flags = RTLD_LAZY;
298 #endif
299         }
300         
301         if (ast_mutex_lock(&modlock))
302                 ast_log(LOG_WARNING, "Failed to lock\n");
303         m = module_list;
304         while(m) {
305                 if (!strcasecmp(m->resource, resource_name)) {
306                         ast_log(LOG_WARNING, "Module '%s' already exists\n", resource_name);
307                         ast_mutex_unlock(&modlock);
308                         return -1;
309                 }
310                 m = m->next;
311         }
312         m = malloc(sizeof(struct module));      
313         if (!m) {
314                 ast_log(LOG_WARNING, "Out of memory\n");
315                 ast_mutex_unlock(&modlock);
316                 return -1;
317         }
318         strncpy(m->resource, resource_name, sizeof(m->resource)-1);
319         if (resource_name[0] == '/') {
320                 strncpy(fn, resource_name, sizeof(fn)-1);
321         } else {
322                 snprintf(fn, sizeof(fn), "%s/%s", (char *)ast_config_AST_MODULE_DIR, resource_name);
323         }
324         m->lib = dlopen(fn, flags);
325         if (!m->lib) {
326                 ast_log(LOG_WARNING, "%s\n", dlerror());
327                 free(m);
328                 ast_mutex_unlock(&modlock);
329                 return -1;
330         }
331         m->load_module = dlsym(m->lib, "load_module");
332         if (m->load_module == NULL)
333                 m->load_module = dlsym(m->lib, "_load_module");
334         if (!m->load_module) {
335                 ast_log(LOG_WARNING, "No load_module in module %s\n", fn);
336                 errors++;
337         }
338         m->unload_module = dlsym(m->lib, "unload_module");
339         if (m->unload_module == NULL)
340                 m->unload_module = dlsym(m->lib, "_unload_module");
341         if (!m->unload_module) {
342                 ast_log(LOG_WARNING, "No unload_module in module %s\n", fn);
343                 errors++;
344         }
345         m->usecount = dlsym(m->lib, "usecount");
346         if (m->usecount == NULL)
347                 m->usecount = dlsym(m->lib, "_usecount");
348         if (!m->usecount) {
349                 ast_log(LOG_WARNING, "No usecount in module %s\n", fn);
350                 errors++;
351         }
352         m->description = dlsym(m->lib, "description");
353         if (m->description == NULL)
354                 m->description = dlsym(m->lib, "_description");
355         if (!m->description) {
356                 ast_log(LOG_WARNING, "No description in module %s\n", fn);
357                 errors++;
358         }
359         m->key = dlsym(m->lib, "key");
360         if (m->key == NULL)
361                 m->key = dlsym(m->lib, "_key");
362         if (!m->key) {
363                 ast_log(LOG_WARNING, "No key routine in module %s\n", fn);
364                 errors++;
365         }
366
367         m->reload = dlsym(m->lib, "reload");
368         if (m->reload == NULL)
369                 m->reload = dlsym(m->lib, "_reload");
370
371         if (!m->key || !(key = (unsigned char *) m->key())) {
372                 ast_log(LOG_WARNING, "Key routine returned NULL in module %s\n", fn);
373                 key = NULL;
374                 errors++;
375         }
376         if (key && verify_key(key)) {
377                 ast_log(LOG_WARNING, "Unexpected key returned by module %s\n", fn);
378                 errors++;
379         }
380         if (errors) {
381                 ast_log(LOG_WARNING, "%d error%s loading module %s, aborted\n", errors, (errors != 1) ? "s" : "", fn);
382                 dlclose(m->lib);
383                 free(m);
384                 ast_mutex_unlock(&modlock);
385                 return -1;
386         }
387         if (!ast_fully_booted) {
388                 if (option_verbose) 
389                         ast_verbose( " => (%s)\n", term_color(tmp, m->description(), COLOR_BROWN, COLOR_BLACK, sizeof(tmp)));
390                 if (ast_opt_console && !option_verbose)
391                         ast_verbose( ".");
392         } else {
393                 if (option_verbose)
394                         ast_verbose(VERBOSE_PREFIX_1 "Loaded %s => (%s)\n", fn, m->description());
395         }
396
397         /* add module 'm' to end of module_list chain
398            so reload commands will be issued in same order modules were loaded */
399         m->next = NULL;
400         if (module_list == NULL) {
401                 /* empty list so far, add at front */
402                 module_list = m;
403         }
404         else {
405                 struct module *i;
406                 /* find end of chain, and add there */
407                 for (i = module_list; i->next; i = i->next)
408                         ;
409                 i->next = m;
410         }
411         
412         modlistver = rand();
413         ast_mutex_unlock(&modlock);
414         if ((res = m->load_module())) {
415                 ast_log(LOG_WARNING, "%s: load_module failed, returning %d\n", m->resource, res);
416                 ast_unload_resource(resource_name, 0);
417                 return -1;
418         }
419         ast_update_use_count();
420         return 0;
421 }
422
423 int ast_load_resource(const char *resource_name)
424 {
425         int o;
426         struct ast_config *cfg = NULL;
427         int res;
428
429         /* Keep the module file parsing silent */
430         o = option_verbose;
431         option_verbose = 0;
432         cfg = ast_config_load(AST_MODULE_CONFIG);
433         option_verbose = o;
434         res = __load_resource(resource_name, cfg);
435         if (cfg)
436                 ast_config_destroy(cfg);
437         return res;
438 }       
439
440 static int ast_resource_exists(char *resource)
441 {
442         struct module *m;
443         if (ast_mutex_lock(&modlock))
444                 ast_log(LOG_WARNING, "Failed to lock\n");
445         m = module_list;
446         while(m) {
447                 if (!strcasecmp(resource, m->resource))
448                         break;
449                 m = m->next;
450         }
451         ast_mutex_unlock(&modlock);
452         if (m)
453                 return -1;
454         else
455                 return 0;
456 }
457
458 static const char *loadorder[] =
459 {
460         "res_",
461         "pbx_",
462         "chan_",
463         NULL,
464 };
465
466 int load_modules(const int preload_only)
467 {
468         struct ast_config *cfg;
469         struct ast_variable *v;
470         char tmp[80];
471
472         if (option_verbose) {
473                 if (preload_only)
474                         ast_verbose("Asterisk Dynamic Loader loading preload modules:\n");
475                 else
476                         ast_verbose("Asterisk Dynamic Loader Starting:\n");
477         }
478
479         cfg = ast_config_load(AST_MODULE_CONFIG);
480         if (cfg) {
481                 int doload;
482
483                 /* Load explicitly defined modules */
484                 for (v = ast_variable_browse(cfg, "modules"); v; v = v->next) {
485                         doload = 0;
486
487                         if (preload_only)
488                                 doload = !strcasecmp(v->name, "preload");
489                         else
490                                 doload = !strcasecmp(v->name, "load");
491
492                        if (doload) {
493                                 if (option_debug && !option_verbose)
494                                         ast_log(LOG_DEBUG, "Loading module %s\n", v->value);
495                                 if (option_verbose) {
496                                         ast_verbose(VERBOSE_PREFIX_1 "[%s]", term_color(tmp, v->value, COLOR_BRWHITE, 0, sizeof(tmp)));
497                                         fflush(stdout);
498                                 }
499                                 if (__load_resource(v->value, cfg)) {
500                                         ast_log(LOG_WARNING, "Loading module %s failed!\n", v->value);
501                                         ast_config_destroy(cfg);
502                                         return -1;
503                                 }
504                         }
505                 }
506         }
507
508         if (preload_only) {
509                 ast_config_destroy(cfg);
510                 return 0;
511         }
512
513         if (!cfg || ast_true(ast_variable_retrieve(cfg, "modules", "autoload"))) {
514                 /* Load all modules */
515                 DIR *mods;
516                 struct dirent *d;
517                 int x;
518
519                 /* Loop through each order */
520                 for (x=0; x<sizeof(loadorder) / sizeof(loadorder[0]); x++) {
521                         mods = opendir((char *)ast_config_AST_MODULE_DIR);
522                         if (mods) {
523                                 while((d = readdir(mods))) {
524                                         /* Must end in .so to load it.  */
525                                         if ((strlen(d->d_name) > 3) && 
526                                             (!loadorder[x] || !strncasecmp(d->d_name, loadorder[x], strlen(loadorder[x]))) && 
527                                             !strcasecmp(d->d_name + strlen(d->d_name) - 3, ".so") &&
528                                                 !ast_resource_exists(d->d_name)) {
529                                                 /* It's a shared library -- Just be sure we're allowed to load it -- kinda
530                                                    an inefficient way to do it, but oh well. */
531                                                 if (cfg) {
532                                                         v = ast_variable_browse(cfg, "modules");
533                                                         while(v) {
534                                                                 if (!strcasecmp(v->name, "noload") &&
535                                                                     !strcasecmp(v->value, d->d_name)) 
536                                                                         break;
537                                                                 v = v->next;
538                                                         }
539                                                         if (v) {
540                                                                 if (option_verbose) {
541                                                                         ast_verbose( VERBOSE_PREFIX_1 "[skipping %s]\n", d->d_name);
542                                                                         fflush(stdout);
543                                                                 }
544                                                                 continue;
545                                                         }
546                                                         
547                                                 }
548                                                 if (option_debug && !option_verbose)
549                                                         ast_log(LOG_DEBUG, "Loading module %s\n", d->d_name);
550                                                 if (option_verbose) {
551                                                         ast_verbose( VERBOSE_PREFIX_1 "[%s]", term_color(tmp, d->d_name, COLOR_BRWHITE, 0, sizeof(tmp)));
552                                                         fflush(stdout);
553                                                 }
554                                                 if (__load_resource(d->d_name, cfg)) {
555                                                         ast_log(LOG_WARNING, "Loading module %s failed!\n", d->d_name);
556                                                         if (cfg)
557                                                                 ast_config_destroy(cfg);
558                                                         return -1;
559                                                 }
560                                         }
561                                 }
562                                 closedir(mods);
563                         } else {
564                                 if (!ast_opt_quiet)
565                                         ast_log(LOG_WARNING, "Unable to open modules directory %s.\n", (char *)ast_config_AST_MODULE_DIR);
566                         }
567                 }
568         } 
569         ast_config_destroy(cfg);
570         return 0;
571 }
572
573 void ast_update_use_count(void)
574 {
575         /* Notify any module monitors that the use count for a 
576            resource has changed */
577         struct loadupdate *m;
578         if (ast_mutex_lock(&modlock))
579                 ast_log(LOG_WARNING, "Failed to lock\n");
580         m = updaters;
581         while(m) {
582                 m->updater();
583                 m = m->next;
584         }
585         ast_mutex_unlock(&modlock);
586         
587 }
588
589 int ast_update_module_list(int (*modentry)(const char *module, const char *description, int usecnt, const char *like),
590                            const char *like)
591 {
592         struct module *m;
593         int unlock = -1;
594         int total_mod_loaded = 0;
595
596         if (ast_mutex_trylock(&modlock))
597                 unlock = 0;
598         m = module_list;
599         while (m) {
600                 total_mod_loaded += modentry(m->resource, m->description(), m->usecount(), like);
601                 m = m->next;
602         }
603         if (unlock)
604                 ast_mutex_unlock(&modlock);
605
606         return total_mod_loaded;
607 }
608
609 int ast_loader_register(int (*v)(void)) 
610 {
611         struct loadupdate *tmp;
612         /* XXX Should be more flexible here, taking > 1 verboser XXX */
613         if ((tmp = malloc(sizeof (struct loadupdate)))) {
614                 tmp->updater = v;
615                 if (ast_mutex_lock(&modlock))
616                         ast_log(LOG_WARNING, "Failed to lock\n");
617                 tmp->next = updaters;
618                 updaters = tmp;
619                 ast_mutex_unlock(&modlock);
620                 return 0;
621         }
622         return -1;
623 }
624
625 int ast_loader_unregister(int (*v)(void))
626 {
627         int res = -1;
628         struct loadupdate *tmp, *tmpl=NULL;
629         if (ast_mutex_lock(&modlock))
630                 ast_log(LOG_WARNING, "Failed to lock\n");
631         tmp = updaters;
632         while(tmp) {
633                 if (tmp->updater == v)  {
634                         if (tmpl)
635                                 tmpl->next = tmp->next;
636                         else
637                                 updaters = tmp->next;
638                         break;
639                 }
640                 tmpl = tmp;
641                 tmp = tmp->next;
642         }
643         if (tmp)
644                 res = 0;
645         ast_mutex_unlock(&modlock);
646         return res;
647 }