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