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