a1f01c7bca04d52efa76ae5512f433ad32d65301
[asterisk/asterisk.git] / loader.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Module Loader
5  * 
6  * Copyright (C) 1999 - 2005, 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(const 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 static int __load_resource(const char *resource_name, const struct ast_config *cfg)
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         char tmp[80];
259
260         if (strncasecmp(resource_name, "res_", 4)) {
261 #ifdef RTLD_GLOBAL
262                 if (cfg) {
263                         if ((val = ast_variable_retrieve(cfg, "global", resource_name))
264                                         && ast_true(val))
265                                 flags |= RTLD_GLOBAL;
266                 }
267 #endif
268         } else {
269                 /* Resource modules are always loaded global and lazy */
270 #ifdef RTLD_GLOBAL
271                 flags = (RTLD_GLOBAL | RTLD_LAZY);
272 #else
273                 flags = RTLD_LAZY;
274 #endif
275         }
276         
277         if (ast_mutex_lock(&modlock))
278                 ast_log(LOG_WARNING, "Failed to lock\n");
279         m = module_list;
280         while(m) {
281                 if (!strcasecmp(m->resource, resource_name)) {
282                         ast_log(LOG_WARNING, "Module '%s' already exists\n", resource_name);
283                         ast_mutex_unlock(&modlock);
284                         return -1;
285                 }
286                 m = m->next;
287         }
288         m = malloc(sizeof(struct module));      
289         if (!m) {
290                 ast_log(LOG_WARNING, "Out of memory\n");
291                 ast_mutex_unlock(&modlock);
292                 return -1;
293         }
294         strncpy(m->resource, resource_name, sizeof(m->resource)-1);
295         if (resource_name[0] == '/') {
296                 strncpy(fn, resource_name, sizeof(fn)-1);
297         } else {
298                 snprintf(fn, sizeof(fn), "%s/%s", (char *)ast_config_AST_MODULE_DIR, resource_name);
299         }
300         m->lib = dlopen(fn, flags);
301         if (!m->lib) {
302                 ast_log(LOG_WARNING, "%s\n", dlerror());
303                 free(m);
304                 ast_mutex_unlock(&modlock);
305                 return -1;
306         }
307         m->load_module = dlsym(m->lib, "load_module");
308         if (m->load_module == NULL)
309                 m->load_module = dlsym(m->lib, "_load_module");
310         if (!m->load_module) {
311                 ast_log(LOG_WARNING, "No load_module in module %s\n", fn);
312                 errors++;
313         }
314         m->unload_module = dlsym(m->lib, "unload_module");
315         if (m->unload_module == NULL)
316                 m->unload_module = dlsym(m->lib, "_unload_module");
317         if (!m->unload_module) {
318                 ast_log(LOG_WARNING, "No unload_module in module %s\n", fn);
319                 errors++;
320         }
321         m->usecount = dlsym(m->lib, "usecount");
322         if (m->usecount == NULL)
323                 m->usecount = dlsym(m->lib, "_usecount");
324         if (!m->usecount) {
325                 ast_log(LOG_WARNING, "No usecount in module %s\n", fn);
326                 errors++;
327         }
328         m->description = dlsym(m->lib, "description");
329         if (m->description == NULL)
330                 m->description = dlsym(m->lib, "_description");
331         if (!m->description) {
332                 ast_log(LOG_WARNING, "No description in module %s\n", fn);
333                 errors++;
334         }
335         m->key = dlsym(m->lib, "key");
336         if (m->key == NULL)
337                 m->key = dlsym(m->lib, "_key");
338         if (!m->key) {
339                 ast_log(LOG_WARNING, "No key routine in module %s\n", fn);
340                 errors++;
341         }
342         m->reload = dlsym(m->lib, "reload");
343         if (m->reload == NULL)
344                 m->reload = dlsym(m->lib, "_reload");
345         if (!m->key || !(key = m->key())) {
346                 ast_log(LOG_WARNING, "Key routine returned NULL in module %s\n", fn);
347                 key = NULL;
348                 errors++;
349         }
350         if (key && verify_key(key)) {
351                 ast_log(LOG_WARNING, "Unexpected key returned by module %s\n", fn);
352                 errors++;
353         }
354         if (errors) {
355                 ast_log(LOG_WARNING, "%d error(s) loading module %s, aborted\n", errors, fn);
356                 dlclose(m->lib);
357                 free(m);
358                 ast_mutex_unlock(&modlock);
359                 return -1;
360         }
361         if (!fully_booted) {
362                 if (option_verbose) 
363                         ast_verbose( " => (%s)\n", term_color(tmp, m->description(), COLOR_BROWN, COLOR_BLACK, sizeof(tmp)));
364                 if (option_console && !option_verbose)
365                         ast_verbose( ".");
366         } else {
367                 if (option_verbose)
368                         ast_verbose(VERBOSE_PREFIX_1 "Loaded %s => (%s)\n", fn, m->description());
369         }
370
371         /* add module 'm' to end of module_list chain
372            so reload commands will be issued in same order modules were loaded */
373         m->next = NULL;
374         if (module_list == NULL) {
375                 /* empty list so far, add at front */
376                 module_list = m;
377         }
378         else {
379                 struct module *i;
380                 /* find end of chain, and add there */
381                 for (i = module_list; i->next; i = i->next)
382                         ;
383                 i->next = m;
384         }
385         
386         modlistver = rand();
387         ast_mutex_unlock(&modlock);
388         if ((res = m->load_module())) {
389                 ast_log(LOG_WARNING, "%s: load_module failed, returning %d\n", m->resource, res);
390                 ast_unload_resource(resource_name, 0);
391                 return -1;
392         }
393         ast_update_use_count();
394         return 0;
395 }
396
397 int ast_load_resource(const char *resource_name)
398 {
399         int o;
400         struct ast_config *cfg = NULL;
401         int res;
402
403         /* Keep the module file parsing silent */
404         o = option_verbose;
405         option_verbose = 0;
406         cfg = ast_load(AST_MODULE_CONFIG);
407         option_verbose = o;
408         res = __load_resource(resource_name, cfg);
409         if (cfg)
410                 ast_destroy(cfg);
411         return res;
412 }       
413
414 static int ast_resource_exists(char *resource)
415 {
416         struct module *m;
417         if (ast_mutex_lock(&modlock))
418                 ast_log(LOG_WARNING, "Failed to lock\n");
419         m = module_list;
420         while(m) {
421                 if (!strcasecmp(resource, m->resource))
422                         break;
423                 m = m->next;
424         }
425         ast_mutex_unlock(&modlock);
426         if (m)
427                 return -1;
428         else
429                 return 0;
430 }
431
432 static const char *loadorder[] =
433 {
434         "res_",
435         "chan_",
436         "pbx_",
437         NULL,
438 };
439
440 int load_modules()
441 {
442         struct ast_config *cfg;
443         struct ast_variable *v;
444         char tmp[80];
445         if (option_verbose) 
446                 ast_verbose( "Asterisk Dynamic Loader Starting:\n");
447         cfg = ast_load(AST_MODULE_CONFIG);
448         if (cfg) {
449                 /* Load explicitly defined modules */
450                 v = ast_variable_browse(cfg, "modules");
451                 while(v) {
452                         if (!strcasecmp(v->name, "load")) {
453                                 if (option_debug && !option_verbose)
454                                         ast_log(LOG_DEBUG, "Loading module %s\n", v->value);
455                                 if (option_verbose) {
456                                         ast_verbose( VERBOSE_PREFIX_1 "[%s]", term_color(tmp, v->value, COLOR_BRWHITE, 0, sizeof(tmp)));
457                                         fflush(stdout);
458                                 }
459                                 if (__load_resource(v->value, cfg)) {
460                                         ast_log(LOG_WARNING, "Loading module %s failed!\n", v->value);
461                                         if (cfg)
462                                                 ast_destroy(cfg);
463                                         return -1;
464                                 }
465                         }
466                         v=v->next;
467                 }
468         }
469         if (!cfg || ast_true(ast_variable_retrieve(cfg, "modules", "autoload"))) {
470                 /* Load all modules */
471                 DIR *mods;
472                 struct dirent *d;
473                 int x;
474                 /* Loop through each order */
475                 for (x=0;x<sizeof(loadorder) / sizeof(loadorder[0]);x++) {
476                         mods = opendir((char *)ast_config_AST_MODULE_DIR);
477                         if (mods) {
478                                 while((d = readdir(mods))) {
479                                         /* Must end in .so to load it.  */
480                                         if ((strlen(d->d_name) > 3) && 
481                                             (!loadorder[x] || !strncasecmp(d->d_name, loadorder[x], strlen(loadorder[x]))) && 
482                                             !strcasecmp(d->d_name + strlen(d->d_name) - 3, ".so") &&
483                                                 !ast_resource_exists(d->d_name)) {
484                                                 /* It's a shared library -- Just be sure we're allowed to load it -- kinda
485                                                    an inefficient way to do it, but oh well. */
486                                                 if (cfg) {
487                                                         v = ast_variable_browse(cfg, "modules");
488                                                         while(v) {
489                                                                 if (!strcasecmp(v->name, "noload") &&
490                                                                     !strcasecmp(v->value, d->d_name)) 
491                                                                         break;
492                                                                 v = v->next;
493                                                         }
494                                                         if (v) {
495                                                                 if (option_verbose) {
496                                                                         ast_verbose( VERBOSE_PREFIX_1 "[skipping %s]\n", d->d_name);
497                                                                         fflush(stdout);
498                                                                 }
499                                                                 continue;
500                                                         }
501                                                         
502                                                 }
503                                             if (option_debug && !option_verbose)
504                                                         ast_log(LOG_DEBUG, "Loading module %s\n", d->d_name);
505                                                 if (option_verbose) {
506                                                         ast_verbose( VERBOSE_PREFIX_1 "[%s]", term_color(tmp, d->d_name, COLOR_BRWHITE, 0, sizeof(tmp)));
507                                                         fflush(stdout);
508                                                 }
509                                                 if (__load_resource(d->d_name, cfg)) {
510                                                         ast_log(LOG_WARNING, "Loading module %s failed!\n", d->d_name);
511                                                         if (cfg)
512                                                                 ast_destroy(cfg);
513                                                         return -1;
514                                                 }
515                                         }
516                                 }
517                                 closedir(mods);
518                         } else {
519                                 if (!option_quiet)
520                                         ast_log(LOG_WARNING, "Unable to open modules directory %s.\n", (char *)ast_config_AST_MODULE_DIR);
521                         }
522                 }
523         } 
524         ast_destroy(cfg);
525         return 0;
526 }
527
528 void ast_update_use_count(void)
529 {
530         /* Notify any module monitors that the use count for a 
531            resource has changed */
532         struct loadupdate *m;
533         if (ast_mutex_lock(&modlock))
534                 ast_log(LOG_WARNING, "Failed to lock\n");
535         m = updaters;
536         while(m) {
537                 m->updater();
538                 m = m->next;
539         }
540         ast_mutex_unlock(&modlock);
541         
542 }
543
544 int ast_update_module_list(int (*modentry)(char *module, char *description, int usecnt, char *like), char *like)
545 {
546         struct module *m;
547         int unlock = -1;
548         int total_mod_loaded = 0;
549         if (ast_mutex_trylock(&modlock))
550                 unlock = 0;
551         m = module_list;
552         while(m) {
553                 total_mod_loaded += modentry(m->resource, m->description(), m->usecount(), like);
554                 m = m->next;
555         }
556         if (unlock)
557                 ast_mutex_unlock(&modlock);
558         return total_mod_loaded;
559 }
560
561 int ast_loader_register(int (*v)(void)) 
562 {
563         struct loadupdate *tmp;
564         /* XXX Should be more flexible here, taking > 1 verboser XXX */
565         if ((tmp = malloc(sizeof (struct loadupdate)))) {
566                 tmp->updater = v;
567                 if (ast_mutex_lock(&modlock))
568                         ast_log(LOG_WARNING, "Failed to lock\n");
569                 tmp->next = updaters;
570                 updaters = tmp;
571                 ast_mutex_unlock(&modlock);
572                 return 0;
573         }
574         return -1;
575 }
576
577 int ast_loader_unregister(int (*v)(void))
578 {
579         int res = -1;
580         struct loadupdate *tmp, *tmpl=NULL;
581         if (ast_mutex_lock(&modlock))
582                 ast_log(LOG_WARNING, "Failed to lock\n");
583         tmp = updaters;
584         while(tmp) {
585                 if (tmp->updater == v)  {
586                         if (tmpl)
587                                 tmpl->next = tmp->next;
588                         else
589                                 updaters = tmp->next;
590                         break;
591                 }
592                 tmpl = tmp;
593                 tmp = tmp->next;
594         }
595         if (tmp)
596                 res = 0;
597         ast_mutex_unlock(&modlock);
598         return res;
599 }