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