5280d5a50e7de132acd911b19bad5346b211b0c7
[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, 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
107 int ast_unload_resource(char *resource_name, int force)
108 {
109         struct module *m, *ml = NULL;
110         int res = -1;
111         if (ast_mutex_lock(&modlock))
112                 ast_log(LOG_WARNING, "Failed to lock\n");
113         m = module_list;
114         while(m) {
115                 if (!strcasecmp(m->resource, resource_name)) {
116                         if ((res = m->usecount()) > 0)  {
117                                 if (force) 
118                                         ast_log(LOG_WARNING, "Warning:  Forcing removal of module %s with use count %d\n", resource_name, res);
119                                 else {
120                                         ast_log(LOG_WARNING, "Soft unload failed, '%s' has use count %d\n", resource_name, res);
121                                         ast_mutex_unlock(&modlock);
122                                         return -1;
123                                 }
124                         }
125                         res = m->unload_module();
126                         if (res) {
127                                 ast_log(LOG_WARNING, "Firm unload failed for %s\n", resource_name);
128                                 if (force <= AST_FORCE_FIRM) {
129                                         ast_mutex_unlock(&modlock);
130                                         return -1;
131                                 } else
132                                         ast_log(LOG_WARNING, "** Dangerous **: Unloading resource anyway, at user request\n");
133                         }
134                         if (ml)
135                                 ml->next = m->next;
136                         else
137                                 module_list = m->next;
138                         dlclose(m->lib);
139                         free(m);
140                         break;
141                 }
142                 ml = m;
143                 m = m->next;
144         }
145         ast_mutex_unlock(&modlock);
146         ast_update_use_count();
147         return res;
148 }
149
150 char *ast_module_helper(char *line, char *word, int pos, int state, int rpos, int needsreload)
151 {
152         struct module *m;
153         int which=0;
154         char *ret;
155         if (pos != rpos)
156                 return NULL;
157         ast_mutex_lock(&modlock);
158         m = module_list;
159         while(m) {
160                 if (!strncasecmp(word, m->resource, strlen(word)) && (m->reload || !needsreload)) {
161                         if (++which > state)
162                                 break;
163                 }
164                 m = m->next;
165         }
166         if (m) {
167                 ret = strdup(m->resource);
168         } else {
169                 ret = NULL;
170                 if (!strncasecmp(word, "astconfig", strlen(word))) {
171                         if (++which > state)
172                                 ret = strdup("astconfig");
173                 } else if (!strncasecmp(word, "manager", strlen(word))) {
174                         if (++which > state)
175                                 ret = strdup("manager");
176                 } else if (!strncasecmp(word, "enum", strlen(word))) {
177                         if (++which > state)
178                                 ret = strdup("enum");
179                 } else if (!strncasecmp(word, "rtp", strlen(word))) {
180                         if (++which > state)
181                                 ret = strdup("rtp");
182                 }
183                         
184         }
185         ast_mutex_unlock(&modlock);
186         return ret;
187 }
188
189 int ast_module_reload(const char *name)
190 {
191         struct module *m;
192         int reloaded = 0;
193         /* We'll do the logger and manager the favor of calling its reload here first */
194
195         if (ast_mutex_trylock(&reloadlock)) {
196                 ast_verbose("The previous reload command didn't finish yet\n");
197                 return -1;
198         }
199         if (!name || !strcasecmp(name, "astconfig")) {
200                 read_ast_cust_config();
201                 reloaded = 2;
202         }
203         if (!name || !strcasecmp(name, "manager")) {
204                 reload_manager();
205                 reloaded = 2;
206         }
207         if (!name || !strcasecmp(name, "enum")) {
208                 ast_enum_reload();
209                 reloaded = 2;
210         }
211         if (!name || !strcasecmp(name, "rtp")) {
212                 ast_rtp_reload();
213                 reloaded = 2;
214         }
215         time(&ast_lastreloadtime);
216
217         ast_mutex_lock(&modlock);
218         m = module_list;
219         while(m) {
220                 if (!name || !strcasecmp(name, m->resource)) {
221                         if (reloaded < 1)
222                                 reloaded = 1;
223                         if (m->reload) {
224                                 reloaded = 2;
225                                 if (option_verbose > 2) 
226                                         ast_verbose(VERBOSE_PREFIX_3 "Reloading module '%s' (%s)\n", m->resource, m->description());
227                                 m->reload();
228                         }
229                 }
230                 m = m->next;
231         }
232         ast_mutex_unlock(&modlock);
233         ast_mutex_unlock(&reloadlock);
234         return reloaded;
235 }
236
237 int ast_load_resource(char *resource_name)
238 {
239         static char fn[256];
240         int errors=0;
241         int res;
242         struct module *m;
243         int flags=RTLD_NOW;
244 #ifdef RTLD_GLOBAL
245         char *val;
246 #endif
247         char *key;
248         int o;
249         struct ast_config *cfg;
250         char tmp[80];
251         /* Keep the module file parsing silent */
252         o = option_verbose;
253         if (strncasecmp(resource_name, "res_", 4)) {
254                 option_verbose = 0;
255                 cfg = ast_load(AST_MODULE_CONFIG);
256                 option_verbose = o;
257                 if (cfg) {
258 #ifdef RTLD_GLOBAL
259                         if ((val = ast_variable_retrieve(cfg, "global", resource_name))
260                                         && ast_true(val))
261                                 flags |= RTLD_GLOBAL;
262 #endif
263                         ast_destroy(cfg);
264                 }
265         } else {
266                 /* Resource modules are always loaded global and lazy */
267 #ifdef RTLD_GLOBAL
268                 flags = (RTLD_GLOBAL | RTLD_LAZY);
269 #else
270                 flags = RTLD_LAZY;
271 #endif
272         }
273         
274         if (ast_mutex_lock(&modlock))
275                 ast_log(LOG_WARNING, "Failed to lock\n");
276         m = module_list;
277         while(m) {
278                 if (!strcasecmp(m->resource, resource_name)) {
279                         ast_log(LOG_WARNING, "Module '%s' already exists\n", resource_name);
280                         ast_mutex_unlock(&modlock);
281                         return -1;
282                 }
283                 m = m->next;
284         }
285         m = malloc(sizeof(struct module));      
286         if (!m) {
287                 ast_log(LOG_WARNING, "Out of memory\n");
288                 ast_mutex_unlock(&modlock);
289                 return -1;
290         }
291         strncpy(m->resource, resource_name, sizeof(m->resource)-1);
292         if (resource_name[0] == '/') {
293                 strncpy(fn, resource_name, sizeof(fn)-1);
294         } else {
295                 snprintf(fn, sizeof(fn), "%s/%s", (char *)ast_config_AST_MODULE_DIR, resource_name);
296         }
297         m->lib = dlopen(fn, flags);
298         if (!m->lib) {
299                 ast_log(LOG_WARNING, "%s\n", dlerror());
300                 free(m);
301                 ast_mutex_unlock(&modlock);
302                 return -1;
303         }
304         m->load_module = dlsym(m->lib, "load_module");
305         if (m->load_module == NULL)
306                 m->load_module = dlsym(m->lib, "_load_module");
307         if (!m->load_module) {
308                 ast_log(LOG_WARNING, "No load_module in module %s\n", fn);
309                 errors++;
310         }
311         m->unload_module = dlsym(m->lib, "unload_module");
312         if (m->unload_module == NULL)
313                 m->unload_module = dlsym(m->lib, "_unload_module");
314         if (!m->unload_module) {
315                 ast_log(LOG_WARNING, "No unload_module in module %s\n", fn);
316                 errors++;
317         }
318         m->usecount = dlsym(m->lib, "usecount");
319         if (m->usecount == NULL)
320                 m->usecount = dlsym(m->lib, "_usecount");
321         if (!m->usecount) {
322                 ast_log(LOG_WARNING, "No usecount in module %s\n", fn);
323                 errors++;
324         }
325         m->description = dlsym(m->lib, "description");
326         if (m->description == NULL)
327                 m->description = dlsym(m->lib, "_description");
328         if (!m->description) {
329                 ast_log(LOG_WARNING, "No description in module %s\n", fn);
330                 errors++;
331         }
332         m->key = dlsym(m->lib, "key");
333         if (m->key == NULL)
334                 m->key = dlsym(m->lib, "_key");
335         if (!m->key) {
336                 ast_log(LOG_WARNING, "No key routine in module %s\n", fn);
337                 errors++;
338         }
339         m->reload = dlsym(m->lib, "reload");
340         if (m->reload == NULL)
341                 m->reload = dlsym(m->lib, "_reload");
342         if (!m->key || !(key = m->key())) {
343                 ast_log(LOG_WARNING, "Key routine returned NULL in module %s\n", fn);
344                 key = NULL;
345                 errors++;
346         }
347         if (key && verify_key(key)) {
348                 ast_log(LOG_WARNING, "Unexpected key returned by module %s\n", fn);
349                 errors++;
350         }
351         if (errors) {
352                 ast_log(LOG_WARNING, "%d error(s) loading module %s, aborted\n", errors, fn);
353                 dlclose(m->lib);
354                 free(m);
355                 ast_mutex_unlock(&modlock);
356                 return -1;
357         }
358         if (!fully_booted) {
359                 if (option_verbose) 
360                         ast_verbose( " => (%s)\n", term_color(tmp, m->description(), COLOR_BROWN, COLOR_BLACK, sizeof(tmp)));
361                 if (option_console && !option_verbose)
362                         ast_verbose( ".");
363         } else {
364                 if (option_verbose)
365                         ast_verbose(VERBOSE_PREFIX_1 "Loaded %s => (%s)\n", fn, m->description());
366         }
367
368         /* add module 'm' to end of module_list chain
369            so reload commands will be issued in same order modules were loaded */
370         m->next = NULL;
371         if (module_list == NULL) {
372                 /* empty list so far, add at front */
373                 module_list = m;
374         }
375         else {
376                 struct module *i;
377                 /* find end of chain, and add there */
378                 for (i = module_list; i->next; i = i->next)
379                         ;
380                 i->next = m;
381         }
382         
383         ast_mutex_unlock(&modlock);
384         if ((res = m->load_module())) {
385                 ast_log(LOG_WARNING, "%s: load_module failed, returning %d\n", m->resource, res);
386                 ast_unload_resource(resource_name, 0);
387                 return -1;
388         }
389         ast_update_use_count();
390         return 0;
391 }       
392
393 static int ast_resource_exists(char *resource)
394 {
395         struct module *m;
396         if (ast_mutex_lock(&modlock))
397                 ast_log(LOG_WARNING, "Failed to lock\n");
398         m = module_list;
399         while(m) {
400                 if (!strcasecmp(resource, m->resource))
401                         break;
402                 m = m->next;
403         }
404         ast_mutex_unlock(&modlock);
405         if (m)
406                 return -1;
407         else
408                 return 0;
409 }
410
411 static const char *loadorder[] =
412 {
413         "res_",
414         "chan_",
415         "pbx_",
416         NULL,
417 };
418
419 int load_modules()
420 {
421         struct ast_config *cfg;
422         struct ast_variable *v;
423         char tmp[80];
424         if (option_verbose) 
425                 ast_verbose( "Asterisk Dynamic Loader Starting:\n");
426         cfg = ast_load(AST_MODULE_CONFIG);
427         if (cfg) {
428                 /* Load explicitly defined modules */
429                 v = ast_variable_browse(cfg, "modules");
430                 while(v) {
431                         if (!strcasecmp(v->name, "load")) {
432                                 if (option_debug && !option_verbose)
433                                         ast_log(LOG_DEBUG, "Loading module %s\n", v->value);
434                                 if (option_verbose) {
435                                         ast_verbose( VERBOSE_PREFIX_1 "[%s]", term_color(tmp, v->value, COLOR_BRWHITE, 0, sizeof(tmp)));
436                                         fflush(stdout);
437                                 }
438                                 if (ast_load_resource(v->value)) {
439                                         ast_log(LOG_WARNING, "Loading module %s failed!\n", v->value);
440                                         if (cfg)
441                                                 ast_destroy(cfg);
442                                         return -1;
443                                 }
444                         }
445                         v=v->next;
446                 }
447         }
448         if (!cfg || ast_true(ast_variable_retrieve(cfg, "modules", "autoload"))) {
449                 /* Load all modules */
450                 DIR *mods;
451                 struct dirent *d;
452                 int x;
453                 /* Loop through each order */
454                 for (x=0;x<sizeof(loadorder) / sizeof(loadorder[0]);x++) {
455                         mods = opendir((char *)ast_config_AST_MODULE_DIR);
456                         if (mods) {
457                                 while((d = readdir(mods))) {
458                                         /* Must end in .so to load it.  */
459                                         if ((strlen(d->d_name) > 3) && 
460                                             (!loadorder[x] || !strncasecmp(d->d_name, loadorder[x], strlen(loadorder[x]))) && 
461                                             !strcasecmp(d->d_name + strlen(d->d_name) - 3, ".so") &&
462                                                 !ast_resource_exists(d->d_name)) {
463                                                 /* It's a shared library -- Just be sure we're allowed to load it -- kinda
464                                                    an inefficient way to do it, but oh well. */
465                                                 if (cfg) {
466                                                         v = ast_variable_browse(cfg, "modules");
467                                                         while(v) {
468                                                                 if (!strcasecmp(v->name, "noload") &&
469                                                                     !strcasecmp(v->value, d->d_name)) 
470                                                                         break;
471                                                                 v = v->next;
472                                                         }
473                                                         if (v) {
474                                                                 if (option_verbose) {
475                                                                         ast_verbose( VERBOSE_PREFIX_1 "[skipping %s]\n", d->d_name);
476                                                                         fflush(stdout);
477                                                                 }
478                                                                 continue;
479                                                         }
480                                                         
481                                                 }
482                                             if (option_debug && !option_verbose)
483                                                         ast_log(LOG_DEBUG, "Loading module %s\n", d->d_name);
484                                                 if (option_verbose) {
485                                                         ast_verbose( VERBOSE_PREFIX_1 "[%s]", term_color(tmp, d->d_name, COLOR_BRWHITE, 0, sizeof(tmp)));
486                                                         fflush(stdout);
487                                                 }
488                                                 if (ast_load_resource(d->d_name)) {
489                                                         ast_log(LOG_WARNING, "Loading module %s failed!\n", d->d_name);
490                                                         if (cfg)
491                                                                 ast_destroy(cfg);
492                                                         return -1;
493                                                 }
494                                         }
495                                 }
496                                 closedir(mods);
497                         } else {
498                                 if (!option_quiet)
499                                         ast_log(LOG_WARNING, "Unable to open modules directory %s.\n", (char *)ast_config_AST_MODULE_DIR);
500                         }
501                 }
502         } 
503         ast_destroy(cfg);
504         return 0;
505 }
506
507 void ast_update_use_count(void)
508 {
509         /* Notify any module monitors that the use count for a 
510            resource has changed */
511         struct loadupdate *m;
512         if (ast_mutex_lock(&modlock))
513                 ast_log(LOG_WARNING, "Failed to lock\n");
514         m = updaters;
515         while(m) {
516                 m->updater();
517                 m = m->next;
518         }
519         ast_mutex_unlock(&modlock);
520         
521 }
522
523 int ast_update_module_list(int (*modentry)(char *module, char *description, int usecnt, char *like), char *like)
524 {
525         struct module *m;
526         int unlock = -1;
527         int total_mod_loaded = 0;
528         if (ast_mutex_trylock(&modlock))
529                 unlock = 0;
530         m = module_list;
531         while(m) {
532                 total_mod_loaded += modentry(m->resource, m->description(), m->usecount(), like);
533                 m = m->next;
534         }
535         if (unlock)
536                 ast_mutex_unlock(&modlock);
537         return total_mod_loaded;
538 }
539
540 int ast_loader_register(int (*v)(void)) 
541 {
542         struct loadupdate *tmp;
543         /* XXX Should be more flexible here, taking > 1 verboser XXX */
544         if ((tmp = malloc(sizeof (struct loadupdate)))) {
545                 tmp->updater = v;
546                 if (ast_mutex_lock(&modlock))
547                         ast_log(LOG_WARNING, "Failed to lock\n");
548                 tmp->next = updaters;
549                 updaters = tmp;
550                 ast_mutex_unlock(&modlock);
551                 return 0;
552         }
553         return -1;
554 }
555
556 int ast_loader_unregister(int (*v)(void))
557 {
558         int res = -1;
559         struct loadupdate *tmp, *tmpl=NULL;
560         if (ast_mutex_lock(&modlock))
561                 ast_log(LOG_WARNING, "Failed to lock\n");
562         tmp = updaters;
563         while(tmp) {
564                 if (tmp->updater == v)  {
565                         if (tmpl)
566                                 tmpl->next = tmp->next;
567                         else
568                                 updaters = tmp->next;
569                         break;
570                 }
571                 tmpl = tmp;
572                 tmp = tmp->next;
573         }
574         if (tmp)
575                 res = 0;
576         ast_mutex_unlock(&modlock);
577         return res;
578 }