75b89f428e2cfe9b1942e64d6d67ec183fd8862e
[asterisk/asterisk.git] / main / logger.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Asterisk Logger
22  * 
23  * Logging routines
24  *
25  * \author Mark Spencer <markster@digium.com>
26  */
27
28 /*
29  * define _ASTERISK_LOGGER_H to prevent the inclusion of logger.h;
30  * it redefines LOG_* which we need to define syslog_level_map.
31  * later, we force the inclusion of logger.h again.
32  */
33 #define _ASTERISK_LOGGER_H
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 /*
39  * WARNING: additional #include directives should NOT be placed here, they 
40  * should be placed AFTER '#undef _ASTERISK_LOGGER_H' below
41  */
42 #include "asterisk/_private.h"
43 #include "asterisk/paths.h"     /* use ast_config_AST_LOG_DIR */
44 #include <signal.h>
45 #include <time.h>
46 #include <sys/stat.h>
47 #include <fcntl.h>
48 #ifdef HAVE_BKTR
49 #include <execinfo.h>
50 #define MAX_BACKTRACE_FRAMES 20
51 #endif
52
53 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
54                         from <syslog.h> which is included by logger.h */
55 #include <syslog.h>
56
57 static const int syslog_level_map[] = {
58         LOG_DEBUG,
59         LOG_INFO,    /* arbitrary equivalent of LOG_EVENT */
60         LOG_NOTICE,
61         LOG_WARNING,
62         LOG_ERR,
63         LOG_DEBUG,
64         LOG_DEBUG
65 };
66
67 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
68
69 #undef _ASTERISK_LOGGER_H       /* now include logger.h */
70 #include "asterisk/logger.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/channel.h"
73 #include "asterisk/config.h"
74 #include "asterisk/term.h"
75 #include "asterisk/cli.h"
76 #include "asterisk/utils.h"
77 #include "asterisk/manager.h"
78 #include "asterisk/threadstorage.h"
79 #include "asterisk/strings.h"
80 #include "asterisk/pbx.h"
81 #include "asterisk/app.h"
82
83 #if defined(__linux__) && !defined(__NR_gettid)
84 #include <asm/unistd.h>
85 #endif
86
87 #if defined(__linux__) && defined(__NR_gettid)
88 #define GETTID() syscall(__NR_gettid)
89 #else
90 #define GETTID() getpid()
91 #endif
92 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
93
94 static char queue_log_name[256] = QUEUELOG;
95 static char exec_after_rotate[256] = "";
96
97 static int filesize_reload_needed;
98 static unsigned int global_logmask = 0xFFFF;
99
100 static enum rotatestrategy {
101         SEQUENTIAL = 1 << 0,     /* Original method - create a new file, in order */
102         ROTATE = 1 << 1,         /* Rotate all files, such that the oldest file has the highest suffix */
103         TIMESTAMP = 1 << 2,      /* Append the epoch timestamp onto the end of the archived file */
104 } rotatestrategy = SEQUENTIAL;
105
106 static struct {
107         unsigned int queue_log:1;
108 } logfiles = { 1 };
109
110 static char hostname[MAXHOSTNAMELEN];
111
112 enum logtypes {
113         LOGTYPE_SYSLOG,
114         LOGTYPE_FILE,
115         LOGTYPE_CONSOLE,
116 };
117
118 struct logchannel {
119         /*! What to log to this channel */
120         unsigned int logmask;
121         /*! If this channel is disabled or not */
122         int disabled;
123         /*! syslog facility */
124         int facility;
125         /*! Type of log channel */
126         enum logtypes type;
127         /*! logfile logging file pointer */
128         FILE *fileptr;
129         /*! Filename */
130         char filename[PATH_MAX];
131         /*! field for linking to list */
132         AST_LIST_ENTRY(logchannel) list;
133         /*! Line number from configuration file */
134         int lineno;
135         /*! Components (levels) from last config load */
136         char components[0];
137 };
138
139 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
140
141 enum logmsgtypes {
142         LOGMSG_NORMAL = 0,
143         LOGMSG_VERBOSE,
144 };
145
146 struct logmsg {
147         enum logmsgtypes type;
148         int level;
149         int line;
150         long process_id;
151         AST_DECLARE_STRING_FIELDS(
152                 AST_STRING_FIELD(date);
153                 AST_STRING_FIELD(file);
154                 AST_STRING_FIELD(function);
155                 AST_STRING_FIELD(message);
156                 AST_STRING_FIELD(level_name);
157         );
158         AST_LIST_ENTRY(logmsg) list;
159 };
160
161 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
162 static pthread_t logthread = AST_PTHREADT_NULL;
163 static ast_cond_t logcond;
164 static int close_logger_thread;
165
166 static FILE *qlog;
167
168 /*! \brief Logging channels used in the Asterisk logging system
169  *
170  * The first 16 levels are reserved for system usage, and the remaining
171  * levels are reserved for usage by dynamic levels registered via
172  * ast_logger_register_level.
173  */
174
175 /* Modifications to this array are protected by the rwlock in the
176  * logchannels list.
177  */
178
179 static char *levels[32] = {
180         "DEBUG",
181         "---EVENT---",          /* no longer used */
182         "NOTICE",
183         "WARNING",
184         "ERROR",
185         "VERBOSE",
186         "DTMF",
187 };
188
189 /*! \brief Colors used in the console for logging */
190 static const int colors[32] = {
191         COLOR_BRGREEN,
192         COLOR_BRBLUE,           /* no longer used */
193         COLOR_YELLOW,
194         COLOR_BRRED,
195         COLOR_RED,
196         COLOR_GREEN,
197         COLOR_BRGREEN,
198         0,
199         0,
200         0,
201         0,
202         0,
203         0,
204         0,
205         0,
206         0,
207         COLOR_BRBLUE,
208         COLOR_BRBLUE,
209         COLOR_BRBLUE,
210         COLOR_BRBLUE,
211         COLOR_BRBLUE,
212         COLOR_BRBLUE,
213         COLOR_BRBLUE,
214         COLOR_BRBLUE,
215         COLOR_BRBLUE,
216         COLOR_BRBLUE,
217         COLOR_BRBLUE,
218         COLOR_BRBLUE,
219         COLOR_BRBLUE,
220         COLOR_BRBLUE,
221         COLOR_BRBLUE,
222         COLOR_BRBLUE,
223 };
224
225 AST_THREADSTORAGE(verbose_buf);
226 #define VERBOSE_BUF_INIT_SIZE   256
227
228 AST_THREADSTORAGE(log_buf);
229 #define LOG_BUF_INIT_SIZE       256
230
231 static unsigned int make_components(const char *s, int lineno)
232 {
233         char *w;
234         unsigned int res = 0;
235         char *stringp = ast_strdupa(s);
236         unsigned int x;
237
238         while ((w = strsep(&stringp, ","))) {
239                 int found = 0;
240
241                 w = ast_skip_blanks(w);
242
243                 for (x = 0; x < ARRAY_LEN(levels); x++) {
244                         if (levels[x] && !strcasecmp(w, levels[x])) {
245                                 res |= (1 << x);
246                                 found = 1;
247                                 break;
248                         }
249                 }
250         }
251
252         return res;
253 }
254
255 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
256 {
257         struct logchannel *chan;
258         char *facility;
259 #ifndef SOLARIS
260         CODE *cptr;
261 #endif
262
263         if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
264                 return NULL;
265
266         strcpy(chan->components, components);
267         chan->lineno = lineno;
268
269         if (!strcasecmp(channel, "console")) {
270                 chan->type = LOGTYPE_CONSOLE;
271         } else if (!strncasecmp(channel, "syslog", 6)) {
272                 /*
273                 * syntax is:
274                 *  syslog.facility => level,level,level
275                 */
276                 facility = strchr(channel, '.');
277                 if (!facility++ || !facility) {
278                         facility = "local0";
279                 }
280
281 #ifndef SOLARIS
282                 /*
283                 * Walk through the list of facilitynames (defined in sys/syslog.h)
284                 * to see if we can find the one we have been given
285                 */
286                 chan->facility = -1;
287                 cptr = facilitynames;
288                 while (cptr->c_name) {
289                         if (!strcasecmp(facility, cptr->c_name)) {
290                                 chan->facility = cptr->c_val;
291                                 break;
292                         }
293                         cptr++;
294                 }
295 #else
296                 chan->facility = -1;
297                 if (!strcasecmp(facility, "kern")) 
298                         chan->facility = LOG_KERN;
299                 else if (!strcasecmp(facility, "USER")) 
300                         chan->facility = LOG_USER;
301                 else if (!strcasecmp(facility, "MAIL")) 
302                         chan->facility = LOG_MAIL;
303                 else if (!strcasecmp(facility, "DAEMON")) 
304                         chan->facility = LOG_DAEMON;
305                 else if (!strcasecmp(facility, "AUTH")) 
306                         chan->facility = LOG_AUTH;
307                 else if (!strcasecmp(facility, "SYSLOG")) 
308                         chan->facility = LOG_SYSLOG;
309                 else if (!strcasecmp(facility, "LPR")) 
310                         chan->facility = LOG_LPR;
311                 else if (!strcasecmp(facility, "NEWS")) 
312                         chan->facility = LOG_NEWS;
313                 else if (!strcasecmp(facility, "UUCP")) 
314                         chan->facility = LOG_UUCP;
315                 else if (!strcasecmp(facility, "CRON")) 
316                         chan->facility = LOG_CRON;
317                 else if (!strcasecmp(facility, "LOCAL0")) 
318                         chan->facility = LOG_LOCAL0;
319                 else if (!strcasecmp(facility, "LOCAL1")) 
320                         chan->facility = LOG_LOCAL1;
321                 else if (!strcasecmp(facility, "LOCAL2")) 
322                         chan->facility = LOG_LOCAL2;
323                 else if (!strcasecmp(facility, "LOCAL3")) 
324                         chan->facility = LOG_LOCAL3;
325                 else if (!strcasecmp(facility, "LOCAL4")) 
326                         chan->facility = LOG_LOCAL4;
327                 else if (!strcasecmp(facility, "LOCAL5")) 
328                         chan->facility = LOG_LOCAL5;
329                 else if (!strcasecmp(facility, "LOCAL6")) 
330                         chan->facility = LOG_LOCAL6;
331                 else if (!strcasecmp(facility, "LOCAL7")) 
332                         chan->facility = LOG_LOCAL7;
333 #endif /* Solaris */
334
335                 if (0 > chan->facility) {
336                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
337                         ast_free(chan);
338                         return NULL;
339                 }
340
341                 chan->type = LOGTYPE_SYSLOG;
342                 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
343                 openlog("asterisk", LOG_PID, chan->facility);
344         } else {
345                 if (!ast_strlen_zero(hostname)) {
346                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
347                                  channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
348                 } else {
349                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
350                                  channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
351                 }
352                 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
353                         /* Can't log here, since we're called with a lock */
354                         fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
355                 } 
356                 chan->type = LOGTYPE_FILE;
357         }
358         chan->logmask = make_components(chan->components, lineno);
359
360         return chan;
361 }
362
363 static void init_logger_chain(int locked)
364 {
365         struct logchannel *chan;
366         struct ast_config *cfg;
367         struct ast_variable *var;
368         const char *s;
369         struct ast_flags config_flags = { 0 };
370
371         if (!(cfg = ast_config_load2("logger.conf", "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID)
372                 return;
373
374         /* delete our list of log channels */
375         if (!locked)
376                 AST_RWLIST_WRLOCK(&logchannels);
377         while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
378                 ast_free(chan);
379         global_logmask = 0;
380         if (!locked)
381                 AST_RWLIST_UNLOCK(&logchannels);
382         
383         errno = 0;
384         /* close syslog */
385         closelog();
386         
387         /* If no config file, we're fine, set default options. */
388         if (!cfg) {
389                 if (errno)
390                         fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
391                 else
392                         fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
393                 if (!(chan = ast_calloc(1, sizeof(*chan))))
394                         return;
395                 chan->type = LOGTYPE_CONSOLE;
396                 chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
397                 if (!locked)
398                         AST_RWLIST_WRLOCK(&logchannels);
399                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
400                 global_logmask |= chan->logmask;
401                 if (!locked)
402                         AST_RWLIST_UNLOCK(&logchannels);
403                 return;
404         }
405         
406         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
407                 if (ast_true(s)) {
408                         if (gethostname(hostname, sizeof(hostname) - 1)) {
409                                 ast_copy_string(hostname, "unknown", sizeof(hostname));
410                                 fprintf(stderr, "What box has no hostname???\n");
411                         }
412                 } else
413                         hostname[0] = '\0';
414         } else
415                 hostname[0] = '\0';
416         if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
417                 ast_copy_string(dateformat, s, sizeof(dateformat));
418         else
419                 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
420         if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
421                 logfiles.queue_log = ast_true(s);
422         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
423                 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
424         if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
425                 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
426         if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
427                 if (strcasecmp(s, "timestamp") == 0)
428                         rotatestrategy = TIMESTAMP;
429                 else if (strcasecmp(s, "rotate") == 0)
430                         rotatestrategy = ROTATE;
431                 else if (strcasecmp(s, "sequential") == 0)
432                         rotatestrategy = SEQUENTIAL;
433                 else
434                         fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
435         } else {
436                 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
437                         rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
438                         fprintf(stderr, "rotatetimestamp option has been deprecated.  Please use rotatestrategy instead.\n");
439                 }
440         }
441
442         if (!locked)
443                 AST_RWLIST_WRLOCK(&logchannels);
444         var = ast_variable_browse(cfg, "logfiles");
445         for (; var; var = var->next) {
446                 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
447                         continue;
448                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
449                 global_logmask |= chan->logmask;
450         }
451         if (!locked)
452                 AST_RWLIST_UNLOCK(&logchannels);
453
454         ast_config_destroy(cfg);
455 }
456
457 void ast_child_verbose(int level, const char *fmt, ...)
458 {
459         char *msg = NULL, *emsg = NULL, *sptr, *eptr;
460         va_list ap, aq;
461         int size;
462
463         /* Don't bother, if the level isn't that high */
464         if (option_verbose < level) {
465                 return;
466         }
467
468         va_start(ap, fmt);
469         va_copy(aq, ap);
470         if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
471                 va_end(ap);
472                 va_end(aq);
473                 return;
474         }
475         va_end(ap);
476
477         if (!(msg = ast_malloc(size + 1))) {
478                 va_end(aq);
479                 return;
480         }
481
482         vsnprintf(msg, size + 1, fmt, aq);
483         va_end(aq);
484
485         if (!(emsg = ast_malloc(size * 2 + 1))) {
486                 ast_free(msg);
487                 return;
488         }
489
490         for (sptr = msg, eptr = emsg; ; sptr++) {
491                 if (*sptr == '"') {
492                         *eptr++ = '\\';
493                 }
494                 *eptr++ = *sptr;
495                 if (*sptr == '\0') {
496                         break;
497                 }
498         }
499         ast_free(msg);
500
501         fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
502         fflush(stdout);
503         ast_free(emsg);
504 }
505
506 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
507 {
508         va_list ap;
509         char qlog_msg[8192];
510         int qlog_len;
511         char time_str[16];
512
513         if (ast_check_realtime("queue_log")) {
514                 va_start(ap, fmt);
515                 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
516                 va_end(ap);
517                 snprintf(time_str, sizeof(time_str), "%ld", (long)time(NULL));
518                 ast_store_realtime("queue_log", "time", time_str, 
519                                                 "callid", callid, 
520                                                 "queuename", queuename, 
521                                                 "agent", agent, 
522                                                 "event", event,
523                                                 "data", qlog_msg,
524                                                 SENTINEL);
525         } else {
526                 if (qlog) {
527                         va_start(ap, fmt);
528                         qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
529                         vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
530                         va_end(ap);
531                 }
532                 AST_RWLIST_RDLOCK(&logchannels);
533                 if (qlog) {
534                         fprintf(qlog, "%s\n", qlog_msg);
535                         fflush(qlog);
536                 }
537                 AST_RWLIST_UNLOCK(&logchannels);
538         }
539 }
540
541 static int rotate_file(const char *filename)
542 {
543         char old[PATH_MAX];
544         char new[PATH_MAX];
545         int x, y, which, found, res = 0, fd;
546         char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
547
548         switch (rotatestrategy) {
549         case SEQUENTIAL:
550                 for (x = 0; ; x++) {
551                         snprintf(new, sizeof(new), "%s.%d", filename, x);
552                         fd = open(new, O_RDONLY);
553                         if (fd > -1)
554                                 close(fd);
555                         else
556                                 break;
557                 }
558                 if (rename(filename, new)) {
559                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
560                         res = -1;
561                 }
562                 break;
563         case TIMESTAMP:
564                 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
565                 if (rename(filename, new)) {
566                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
567                         res = -1;
568                 }
569                 break;
570         case ROTATE:
571                 /* Find the next empty slot, including a possible suffix */
572                 for (x = 0; ; x++) {
573                         found = 0;
574                         for (which = 0; which < ARRAY_LEN(suffixes); which++) {
575                                 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
576                                 fd = open(new, O_RDONLY);
577                                 if (fd > -1) {
578                                         close(fd);
579                                         found = 1;
580                                         break;
581                                 }
582                         }
583                         if (!found) {
584                                 break;
585                         }
586                 }
587
588                 /* Found an empty slot */
589                 for (y = x; y > 0; y--) {
590                         for (which = 0; which < ARRAY_LEN(suffixes); which++) {
591                                 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
592                                 fd = open(old, O_RDONLY);
593                                 if (fd > -1) {
594                                         /* Found the right suffix */
595                                         close(fd);
596                                         snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
597                                         if (rename(old, new)) {
598                                                 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
599                                                 res = -1;
600                                         }
601                                         break;
602                                 }
603                         }
604                 }
605
606                 /* Finally, rename the current file */
607                 snprintf(new, sizeof(new), "%s.0", filename);
608                 if (rename(filename, new)) {
609                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
610                         res = -1;
611                 }
612         }
613
614         if (!ast_strlen_zero(exec_after_rotate)) {
615                 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
616                 char buf[512];
617                 pbx_builtin_setvar_helper(c, "filename", filename);
618                 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
619                 if (ast_safe_system(buf) != -1) {
620                         ast_log(LOG_WARNING, "error executing '%s'\n", buf);
621                 }
622                 c = ast_channel_release(c);
623         }
624         return res;
625 }
626
627 static int reload_logger(int rotate)
628 {
629         char old[PATH_MAX] = "";
630         int queue_rotate = rotate;
631         struct logchannel *f;
632         int res = 0;
633         struct stat st;
634
635         AST_RWLIST_WRLOCK(&logchannels);
636
637         if (qlog) {
638                 if (rotate < 0) {
639                         /* Check filesize - this one typically doesn't need an auto-rotate */
640                         snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
641                         if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
642                                 fclose(qlog);
643                                 qlog = NULL;
644                         } else
645                                 queue_rotate = 0;
646                 } else {
647                         fclose(qlog);
648                         qlog = NULL;
649                 }
650         } else 
651                 queue_rotate = 0;
652
653         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
654
655         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
656                 if (f->disabled) {
657                         f->disabled = 0;        /* Re-enable logging at reload */
658                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
659                 }
660                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
661                         fclose(f->fileptr);     /* Close file */
662                         f->fileptr = NULL;
663                         if (rotate)
664                                 rotate_file(f->filename);
665                 }
666         }
667
668         filesize_reload_needed = 0;
669
670         init_logger_chain(1 /* locked */);
671
672         if (logfiles.queue_log) {
673                 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
674                 if (queue_rotate)
675                         rotate_file(old);
676
677                 qlog = fopen(old, "a");
678                 if (qlog) {
679                         AST_RWLIST_UNLOCK(&logchannels);
680                         ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
681                         AST_RWLIST_WRLOCK(&logchannels);
682                         ast_verb(1, "Asterisk Queue Logger restarted\n");
683                 } else {
684                         ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
685                         res = -1;
686                 }
687         }
688
689         AST_RWLIST_UNLOCK(&logchannels);
690
691         return res;
692 }
693
694 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
695         a full Asterisk reload) */
696 int logger_reload(void)
697 {
698         if(reload_logger(0))
699                 return RESULT_FAILURE;
700         return RESULT_SUCCESS;
701 }
702
703 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
704 {
705         switch (cmd) {
706         case CLI_INIT:
707                 e->command = "logger reload";
708                 e->usage = 
709                         "Usage: logger reload\n"
710                         "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
711                 return NULL;
712         case CLI_GENERATE:
713                 return NULL;
714         }
715         if (reload_logger(0)) {
716                 ast_cli(a->fd, "Failed to reload the logger\n");
717                 return CLI_FAILURE;
718         }
719         return CLI_SUCCESS;
720 }
721
722 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
723 {
724         switch (cmd) {
725         case CLI_INIT:
726                 e->command = "logger rotate";
727                 e->usage = 
728                         "Usage: logger rotate\n"
729                         "       Rotates and Reopens the log files.\n";
730                 return NULL;
731         case CLI_GENERATE:
732                 return NULL;    
733         }
734         if (reload_logger(1)) {
735                 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
736                 return CLI_FAILURE;
737         } 
738         return CLI_SUCCESS;
739 }
740
741 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
742 {
743         int x;
744         int state;
745         int level = -1;
746
747         switch (cmd) {
748         case CLI_INIT:
749                 e->command = "logger set level";
750                 e->usage = 
751                         "Usage: logger set level\n"
752                         "       Set a specific log level to enabled/disabled for this console.\n";
753                 return NULL;
754         case CLI_GENERATE:
755                 return NULL;
756         }
757
758         if (a->argc < 5)
759                 return CLI_SHOWUSAGE;
760
761         AST_RWLIST_WRLOCK(&logchannels);
762
763         for (x = 0; x < ARRAY_LEN(levels); x++) {
764                 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
765                         level = x;
766                         break;
767                 }
768         }
769
770         AST_RWLIST_UNLOCK(&logchannels);
771
772         state = ast_true(a->argv[4]) ? 1 : 0;
773
774         if (level != -1) {
775                 ast_console_toggle_loglevel(a->fd, level, state);
776                 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
777         } else
778                 return CLI_SHOWUSAGE;
779
780         return CLI_SUCCESS;
781 }
782
783 /*! \brief CLI command to show logging system configuration */
784 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
785 {
786 #define FORMATL "%-35.35s %-8.8s %-9.9s "
787         struct logchannel *chan;
788         switch (cmd) {
789         case CLI_INIT:
790                 e->command = "logger show channels";
791                 e->usage = 
792                         "Usage: logger show channels\n"
793                         "       List configured logger channels.\n";
794                 return NULL;
795         case CLI_GENERATE:
796                 return NULL;    
797         }
798         ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
799         ast_cli(a->fd, "Configuration\n");
800         ast_cli(a->fd, FORMATL, "-------", "----", "------");
801         ast_cli(a->fd, "-------------\n");
802         AST_RWLIST_RDLOCK(&logchannels);
803         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
804                 unsigned int level;
805
806                 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
807                         chan->disabled ? "Disabled" : "Enabled");
808                 ast_cli(a->fd, " - ");
809                 for (level = 0; level < ARRAY_LEN(levels); level++) {
810                         if (chan->logmask & (1 << level)) {
811                                 ast_cli(a->fd, "%s ", levels[level]);
812                         }
813                 }
814                 ast_cli(a->fd, "\n");
815         }
816         AST_RWLIST_UNLOCK(&logchannels);
817         ast_cli(a->fd, "\n");
818                 
819         return CLI_SUCCESS;
820 }
821
822 struct verb {
823         void (*verboser)(const char *string);
824         AST_LIST_ENTRY(verb) list;
825 };
826
827 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
828
829 static struct ast_cli_entry cli_logger[] = {
830         AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
831         AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
832         AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
833         AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
834 };
835
836 static int handle_SIGXFSZ(int sig) 
837 {
838         /* Indicate need to reload */
839         filesize_reload_needed = 1;
840         return 0;
841 }
842
843 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, const char *str, long pid)
844 {
845         char buf[BUFSIZ];
846
847         if (level >= SYSLOG_NLEVELS) {
848                 /* we are locked here, so cannot ast_log() */
849                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
850                 return;
851         }
852
853         if (level == __LOG_VERBOSE) {
854                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", pid, str);
855                 level = __LOG_DEBUG;
856         } else if (level == __LOG_DTMF) {
857                 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", pid, str);
858                 level = __LOG_DEBUG;
859         } else {
860                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
861                          levels[level], pid, file, line, function, str);
862         }
863
864         term_strip(buf, buf, strlen(buf) + 1);
865         syslog(syslog_level_map[level], "%s", buf);
866 }
867
868 /*! \brief Print a normal log message to the channels */
869 static void logger_print_normal(struct logmsg *logmsg)
870 {
871         struct logchannel *chan = NULL;
872         char buf[BUFSIZ];
873
874         AST_RWLIST_RDLOCK(&logchannels);
875
876         if (!AST_RWLIST_EMPTY(&logchannels)) {
877                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
878                         /* If the channel is disabled, then move on to the next one */
879                         if (chan->disabled)
880                                 continue;
881                         /* Check syslog channels */
882                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
883                                 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->message, logmsg->process_id);
884                         /* Console channels */
885                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
886                                 char linestr[128];
887                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
888
889                                 /* If the level is verbose, then skip it */
890                                 if (logmsg->level == __LOG_VERBOSE)
891                                         continue;
892
893                                 /* Turn the numerical line number into a string */
894                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
895                                 /* Build string to print out */
896                                 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
897                                          logmsg->date,
898                                          term_color(tmp1, logmsg->level_name, colors[logmsg->level], 0, sizeof(tmp1)),
899                                          logmsg->process_id,
900                                          term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
901                                          term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
902                                          term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
903                                          logmsg->message);
904                                 /* Print out */
905                                 ast_console_puts_mutable(buf, logmsg->level);
906                         /* File channels */
907                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
908                                 int res = 0;
909
910                                 /* If no file pointer exists, skip it */
911                                 if (!chan->fileptr)
912                                         continue;
913                                 
914                                 /* Print out to the file */
915                                 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
916                                               logmsg->date, logmsg->level_name, logmsg->process_id, logmsg->file, logmsg->message);
917                                 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
918                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
919                                         if (errno == ENOMEM || errno == ENOSPC)
920                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
921                                         else
922                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
923                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
924                                         chan->disabled = 1;
925                                 } else if (res > 0) {
926                                         fflush(chan->fileptr);
927                                 }
928                         }
929                 }
930         } else if (logmsg->level != __LOG_VERBOSE) {
931                 fputs(logmsg->message, stdout);
932         }
933
934         AST_RWLIST_UNLOCK(&logchannels);
935
936         /* If we need to reload because of the file size, then do so */
937         if (filesize_reload_needed) {
938                 reload_logger(-1);
939                 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
940         }
941
942         return;
943 }
944
945 /*! \brief Print a verbose message to the verbosers */
946 static void logger_print_verbose(struct logmsg *logmsg)
947 {
948         struct verb *v = NULL;
949
950         /* Iterate through the list of verbosers and pass them the log message string */
951         AST_RWLIST_RDLOCK(&verbosers);
952         AST_RWLIST_TRAVERSE(&verbosers, v, list)
953                 v->verboser(logmsg->message);
954         AST_RWLIST_UNLOCK(&verbosers);
955
956         return;
957 }
958
959 /*! \brief Actual logging thread */
960 static void *logger_thread(void *data)
961 {
962         struct logmsg *next = NULL, *msg = NULL;
963
964         for (;;) {
965                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
966                 AST_LIST_LOCK(&logmsgs);
967                 if (AST_LIST_EMPTY(&logmsgs)) {
968                         if (close_logger_thread) {
969                                 break;
970                         } else {
971                                 ast_cond_wait(&logcond, &logmsgs.lock);
972                         }
973                 }
974                 next = AST_LIST_FIRST(&logmsgs);
975                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
976                 AST_LIST_UNLOCK(&logmsgs);
977
978                 /* Otherwise go through and process each message in the order added */
979                 while ((msg = next)) {
980                         /* Get the next entry now so that we can free our current structure later */
981                         next = AST_LIST_NEXT(msg, list);
982
983                         /* Depending on the type, send it to the proper function */
984                         if (msg->type == LOGMSG_NORMAL)
985                                 logger_print_normal(msg);
986                         else if (msg->type == LOGMSG_VERBOSE)
987                                 logger_print_verbose(msg);
988
989                         /* Free the data since we are done */
990                         ast_free(msg);
991                 }
992
993                 /* If we should stop, then stop */
994                 if (close_logger_thread)
995                         break;
996         }
997
998         return NULL;
999 }
1000
1001 int init_logger(void)
1002 {
1003         char tmp[256];
1004         int res = 0;
1005
1006         /* auto rotate if sig SIGXFSZ comes a-knockin */
1007         (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
1008
1009         /* start logger thread */
1010         ast_cond_init(&logcond, NULL);
1011         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1012                 ast_cond_destroy(&logcond);
1013                 return -1;
1014         }
1015
1016         /* register the logger cli commands */
1017         ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1018
1019         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1020   
1021         /* create log channels */
1022         init_logger_chain(0 /* locked */);
1023
1024         if (logfiles.queue_log) {
1025                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
1026                 qlog = fopen(tmp, "a");
1027                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
1028         }
1029         return res;
1030 }
1031
1032 void close_logger(void)
1033 {
1034         struct logchannel *f = NULL;
1035
1036         /* Stop logger thread */
1037         AST_LIST_LOCK(&logmsgs);
1038         close_logger_thread = 1;
1039         ast_cond_signal(&logcond);
1040         AST_LIST_UNLOCK(&logmsgs);
1041
1042         if (logthread != AST_PTHREADT_NULL)
1043                 pthread_join(logthread, NULL);
1044
1045         AST_RWLIST_WRLOCK(&logchannels);
1046
1047         if (qlog) {
1048                 fclose(qlog);
1049                 qlog = NULL;
1050         }
1051
1052         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1053                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1054                         fclose(f->fileptr);
1055                         f->fileptr = NULL;
1056                 }
1057         }
1058
1059         closelog(); /* syslog */
1060
1061         AST_RWLIST_UNLOCK(&logchannels);
1062
1063         return;
1064 }
1065
1066 /*!
1067  * \brief send log messages to syslog and/or the console
1068  */
1069 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1070 {
1071         struct logmsg *logmsg = NULL;
1072         struct ast_str *buf = NULL;
1073         struct ast_tm tm;
1074         struct timeval now = ast_tvnow();
1075         int res = 0;
1076         va_list ap;
1077         char datestring[256];
1078
1079         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1080                 return;
1081
1082         if (AST_RWLIST_EMPTY(&logchannels)) {
1083                 /*
1084                  * we don't have the logger chain configured yet,
1085                  * so just log to stdout
1086                  */
1087                 if (level != __LOG_VERBOSE) {
1088                         int result;
1089                         va_start(ap, fmt);
1090                         result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1091                         va_end(ap);
1092                         if (result != AST_DYNSTR_BUILD_FAILED) {
1093                                 term_filter_escapes(ast_str_buffer(buf));
1094                                 fputs(ast_str_buffer(buf), stdout);
1095                         }
1096                 }
1097                 return;
1098         }
1099         
1100         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1101            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1102            is zero, if option_verbose is non-zero (this allows for 'level zero'
1103            LOG_DEBUG messages to be displayed, if the logmask on any channel
1104            allows it)
1105         */
1106         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1107                 return;
1108
1109         /* Ignore anything that never gets logged anywhere */
1110         if (!(global_logmask & (1 << level)))
1111                 return;
1112         
1113         /* Build string */
1114         va_start(ap, fmt);
1115         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1116         va_end(ap);
1117
1118         /* If the build failed, then abort and free this structure */
1119         if (res == AST_DYNSTR_BUILD_FAILED)
1120                 return;
1121
1122         /* Create a new logging message */
1123         if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1124                 return;
1125
1126         /* Copy string over */
1127         ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1128
1129         /* Set type to be normal */
1130         logmsg->type = LOGMSG_NORMAL;
1131
1132         /* Create our date/time */
1133         ast_localtime(&now, &tm, NULL);
1134         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1135         ast_string_field_set(logmsg, date, datestring);
1136
1137         /* Copy over data */
1138         logmsg->level = level;
1139         logmsg->line = line;
1140         ast_string_field_set(logmsg, level_name, levels[level]);
1141         ast_string_field_set(logmsg, file, file);
1142         ast_string_field_set(logmsg, function, function);
1143         logmsg->process_id = (long) GETTID();
1144
1145         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1146         if (logthread != AST_PTHREADT_NULL) {
1147                 AST_LIST_LOCK(&logmsgs);
1148                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1149                 ast_cond_signal(&logcond);
1150                 AST_LIST_UNLOCK(&logmsgs);
1151         } else {
1152                 logger_print_normal(logmsg);
1153                 ast_free(logmsg);
1154         }
1155
1156         return;
1157 }
1158
1159 #ifdef HAVE_BKTR
1160
1161 struct ast_bt *ast_bt_create(void) 
1162 {
1163         struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1164         if (!bt) {
1165                 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1166                 return NULL;
1167         }
1168
1169         bt->alloced = 1;
1170
1171         ast_bt_get_addresses(bt);
1172
1173         return bt;
1174 }
1175
1176 int ast_bt_get_addresses(struct ast_bt *bt)
1177 {
1178         bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1179
1180         return 0;
1181 }
1182
1183 void *ast_bt_destroy(struct ast_bt *bt)
1184 {
1185         if (bt->alloced) {
1186                 ast_free(bt);
1187         }
1188
1189         return NULL;
1190 }
1191
1192 #endif /* HAVE_BKTR */
1193
1194 void ast_backtrace(void)
1195 {
1196 #ifdef HAVE_BKTR
1197         struct ast_bt *bt;
1198         int i = 0;
1199         char **strings;
1200
1201         if (!(bt = ast_bt_create())) {
1202                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1203                 return;
1204         }
1205
1206         if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1207                 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1208                 for (i = 0; i < bt->num_frames; i++) {
1209                         ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1210                 }
1211
1212                 /* MALLOC_DEBUG will erroneously report an error here, unless we undef the macro. */
1213 #undef free
1214                 free(strings);
1215         } else {
1216                 ast_debug(1, "Could not allocate memory for backtrace\n");
1217         }
1218         ast_bt_destroy(bt);
1219 #else
1220         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1221 #endif
1222 }
1223
1224 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1225 {
1226         struct logmsg *logmsg = NULL;
1227         struct ast_str *buf = NULL;
1228         int res = 0;
1229
1230         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1231                 return;
1232
1233         if (ast_opt_timestamp) {
1234                 struct timeval now;
1235                 struct ast_tm tm;
1236                 char date[40];
1237                 char *datefmt;
1238
1239                 now = ast_tvnow();
1240                 ast_localtime(&now, &tm, NULL);
1241                 ast_strftime(date, sizeof(date), dateformat, &tm);
1242                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1243                 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1244                 fmt = datefmt;
1245         } else {
1246                 char *tmp = alloca(strlen(fmt) + 2);
1247                 sprintf(tmp, "%c%s", 127, fmt);
1248                 fmt = tmp;
1249         }
1250
1251         /* Build string */
1252         res = ast_str_set_va(&buf, 0, fmt, ap);
1253
1254         /* If the build failed then we can drop this allocated message */
1255         if (res == AST_DYNSTR_BUILD_FAILED)
1256                 return;
1257
1258         if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1259                 return;
1260
1261         ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1262
1263         ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->message + 1);
1264
1265         /* Set type */
1266         logmsg->type = LOGMSG_VERBOSE;
1267         
1268         /* Add to the list and poke the thread if possible */
1269         if (logthread != AST_PTHREADT_NULL) {
1270                 AST_LIST_LOCK(&logmsgs);
1271                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1272                 ast_cond_signal(&logcond);
1273                 AST_LIST_UNLOCK(&logmsgs);
1274         } else {
1275                 logger_print_verbose(logmsg);
1276                 ast_free(logmsg);
1277         }
1278 }
1279
1280 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1281 {
1282         va_list ap;
1283
1284         va_start(ap, fmt);
1285         __ast_verbose_ap(file, line, func, fmt, ap);
1286         va_end(ap);
1287 }
1288
1289 /* No new code should use this directly, but we have the ABI for backwards compat */
1290 #undef ast_verbose
1291 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1292 void ast_verbose(const char *fmt, ...)
1293 {
1294         va_list ap;
1295
1296         va_start(ap, fmt);
1297         __ast_verbose_ap("", 0, "", fmt, ap);
1298         va_end(ap);
1299 }
1300
1301 int ast_register_verbose(void (*v)(const char *string)) 
1302 {
1303         struct verb *verb;
1304
1305         if (!(verb = ast_malloc(sizeof(*verb))))
1306                 return -1;
1307
1308         verb->verboser = v;
1309
1310         AST_RWLIST_WRLOCK(&verbosers);
1311         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1312         AST_RWLIST_UNLOCK(&verbosers);
1313         
1314         return 0;
1315 }
1316
1317 int ast_unregister_verbose(void (*v)(const char *string))
1318 {
1319         struct verb *cur;
1320
1321         AST_RWLIST_WRLOCK(&verbosers);
1322         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1323                 if (cur->verboser == v) {
1324                         AST_RWLIST_REMOVE_CURRENT(list);
1325                         ast_free(cur);
1326                         break;
1327                 }
1328         }
1329         AST_RWLIST_TRAVERSE_SAFE_END;
1330         AST_RWLIST_UNLOCK(&verbosers);
1331         
1332         return cur ? 0 : -1;
1333 }
1334
1335 static void update_logchannels(void)
1336 {
1337         struct logchannel *cur;
1338
1339         AST_RWLIST_WRLOCK(&logchannels);
1340
1341         global_logmask = 0;
1342
1343         AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
1344                 cur->logmask = make_components(cur->components, cur->lineno);
1345                 global_logmask |= cur->logmask;
1346         }
1347
1348         AST_RWLIST_UNLOCK(&logchannels);
1349 }
1350
1351 int ast_logger_register_level(const char *name)
1352 {
1353         unsigned int level;
1354         unsigned int available = 0;
1355
1356         AST_RWLIST_WRLOCK(&logchannels);
1357
1358         for (level = 0; level < ARRAY_LEN(levels); level++) {
1359                 if ((level >= 16) && !available && !levels[level]) {
1360                         available = level;
1361                         continue;
1362                 }
1363
1364                 if (levels[level] && !strcasecmp(levels[level], name)) {
1365                         ast_log(LOG_WARNING,
1366                                 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
1367                                 name);
1368                         AST_RWLIST_UNLOCK(&logchannels);
1369
1370                         return -1;
1371                 }
1372         }
1373
1374         if (!available) {
1375                 ast_log(LOG_WARNING,
1376                         "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
1377                         name);
1378                 AST_RWLIST_UNLOCK(&logchannels);
1379
1380                 return -1;
1381         }
1382
1383         levels[available] = ast_strdup(name);
1384
1385         AST_RWLIST_UNLOCK(&logchannels);
1386
1387         ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
1388
1389         update_logchannels();
1390
1391         return available;
1392 }
1393
1394 void ast_logger_unregister_level(const char *name)
1395 {
1396         unsigned int found = 0;
1397         unsigned int x;
1398
1399         AST_RWLIST_WRLOCK(&logchannels);
1400
1401         for (x = 16; x < ARRAY_LEN(levels); x++) {
1402                 if (!levels[x]) {
1403                         continue;
1404                 }
1405
1406                 if (strcasecmp(levels[x], name)) {
1407                         continue;
1408                 }
1409
1410                 found = 1;
1411                 break;
1412         }
1413
1414         if (found) {
1415                 /* take this level out of the global_logmask, to ensure that no new log messages
1416                  * will be queued for it
1417                  */
1418
1419                 global_logmask &= ~(1 << x);
1420
1421                 free(levels[x]);
1422                 levels[x] = NULL;
1423                 AST_RWLIST_UNLOCK(&logchannels);
1424
1425                 ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
1426
1427                 update_logchannels();
1428         } else {
1429                 AST_RWLIST_UNLOCK(&logchannels);
1430         }
1431 }
1432