Add ability for modules to dynamically register logger levels
[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 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_string_field_free_memory(msg);
991                         ast_free(msg);
992                 }
993
994                 /* If we should stop, then stop */
995                 if (close_logger_thread)
996                         break;
997         }
998
999         return NULL;
1000 }
1001
1002 int init_logger(void)
1003 {
1004         char tmp[256];
1005         int res = 0;
1006
1007         /* auto rotate if sig SIGXFSZ comes a-knockin */
1008         (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
1009
1010         /* start logger thread */
1011         ast_cond_init(&logcond, NULL);
1012         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1013                 ast_cond_destroy(&logcond);
1014                 return -1;
1015         }
1016
1017         /* register the logger cli commands */
1018         ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1019
1020         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1021   
1022         /* create log channels */
1023         init_logger_chain(0 /* locked */);
1024
1025         if (logfiles.queue_log) {
1026                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
1027                 qlog = fopen(tmp, "a");
1028                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
1029         }
1030         return res;
1031 }
1032
1033 void close_logger(void)
1034 {
1035         struct logchannel *f = NULL;
1036
1037         /* Stop logger thread */
1038         AST_LIST_LOCK(&logmsgs);
1039         close_logger_thread = 1;
1040         ast_cond_signal(&logcond);
1041         AST_LIST_UNLOCK(&logmsgs);
1042
1043         if (logthread != AST_PTHREADT_NULL)
1044                 pthread_join(logthread, NULL);
1045
1046         AST_RWLIST_WRLOCK(&logchannels);
1047
1048         if (qlog) {
1049                 fclose(qlog);
1050                 qlog = NULL;
1051         }
1052
1053         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1054                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1055                         fclose(f->fileptr);
1056                         f->fileptr = NULL;
1057                 }
1058         }
1059
1060         closelog(); /* syslog */
1061
1062         AST_RWLIST_UNLOCK(&logchannels);
1063
1064         return;
1065 }
1066
1067 /*!
1068  * \brief send log messages to syslog and/or the console
1069  */
1070 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1071 {
1072         struct logmsg *logmsg = NULL;
1073         struct ast_str *buf = NULL;
1074         struct ast_tm tm;
1075         struct timeval now = ast_tvnow();
1076         int res = 0;
1077         va_list ap;
1078         char datestring[256];
1079
1080         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1081                 return;
1082
1083         if (AST_RWLIST_EMPTY(&logchannels)) {
1084                 /*
1085                  * we don't have the logger chain configured yet,
1086                  * so just log to stdout
1087                  */
1088                 if (level != __LOG_VERBOSE) {
1089                         int result;
1090                         va_start(ap, fmt);
1091                         result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1092                         va_end(ap);
1093                         if (result != AST_DYNSTR_BUILD_FAILED) {
1094                                 term_filter_escapes(ast_str_buffer(buf));
1095                                 fputs(ast_str_buffer(buf), stdout);
1096                         }
1097                 }
1098                 return;
1099         }
1100         
1101         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1102            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1103            is zero, if option_verbose is non-zero (this allows for 'level zero'
1104            LOG_DEBUG messages to be displayed, if the logmask on any channel
1105            allows it)
1106         */
1107         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1108                 return;
1109
1110         /* Ignore anything that never gets logged anywhere */
1111         if (!(global_logmask & (1 << level)))
1112                 return;
1113         
1114         /* Build string */
1115         va_start(ap, fmt);
1116         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1117         va_end(ap);
1118
1119         /* If the build failed, then abort and free this structure */
1120         if (res == AST_DYNSTR_BUILD_FAILED)
1121                 return;
1122
1123         /* Create a new logging message */
1124         if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1125                 return;
1126
1127         /* Copy string over */
1128         ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1129
1130         /* Set type to be normal */
1131         logmsg->type = LOGMSG_NORMAL;
1132
1133         /* Create our date/time */
1134         ast_localtime(&now, &tm, NULL);
1135         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1136         ast_string_field_set(logmsg, date, datestring);
1137
1138         /* Copy over data */
1139         logmsg->level = level;
1140         logmsg->line = line;
1141         ast_string_field_set(logmsg, level_name, levels[level]);
1142         ast_string_field_set(logmsg, file, file);
1143         ast_string_field_set(logmsg, function, function);
1144         logmsg->process_id = (long) GETTID();
1145
1146         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1147         if (logthread != AST_PTHREADT_NULL) {
1148                 AST_LIST_LOCK(&logmsgs);
1149                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1150                 ast_cond_signal(&logcond);
1151                 AST_LIST_UNLOCK(&logmsgs);
1152         } else {
1153                 logger_print_normal(logmsg);
1154                 ast_free(logmsg);
1155         }
1156
1157         return;
1158 }
1159
1160 #ifdef HAVE_BKTR
1161
1162 struct ast_bt *ast_bt_create(void) 
1163 {
1164         struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1165         if (!bt) {
1166                 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1167                 return NULL;
1168         }
1169
1170         bt->alloced = 1;
1171
1172         ast_bt_get_addresses(bt);
1173
1174         return bt;
1175 }
1176
1177 int ast_bt_get_addresses(struct ast_bt *bt)
1178 {
1179         bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1180
1181         return 0;
1182 }
1183
1184 void *ast_bt_destroy(struct ast_bt *bt)
1185 {
1186         if (bt->alloced) {
1187                 ast_free(bt);
1188         }
1189
1190         return NULL;
1191 }
1192
1193 #endif /* HAVE_BKTR */
1194
1195 void ast_backtrace(void)
1196 {
1197 #ifdef HAVE_BKTR
1198         struct ast_bt *bt;
1199         int i = 0;
1200         char **strings;
1201
1202         if (!(bt = ast_bt_create())) {
1203                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1204                 return;
1205         }
1206
1207         if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1208                 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1209                 for (i = 0; i < bt->num_frames; i++) {
1210                         ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1211                 }
1212
1213                 /* MALLOC_DEBUG will erroneously report an error here, unless we undef the macro. */
1214 #undef free
1215                 free(strings);
1216         } else {
1217                 ast_debug(1, "Could not allocate memory for backtrace\n");
1218         }
1219         ast_bt_destroy(bt);
1220 #else
1221         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1222 #endif
1223 }
1224
1225 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1226 {
1227         struct logmsg *logmsg = NULL;
1228         struct ast_str *buf = NULL;
1229         int res = 0;
1230
1231         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1232                 return;
1233
1234         if (ast_opt_timestamp) {
1235                 struct timeval now;
1236                 struct ast_tm tm;
1237                 char date[40];
1238                 char *datefmt;
1239
1240                 now = ast_tvnow();
1241                 ast_localtime(&now, &tm, NULL);
1242                 ast_strftime(date, sizeof(date), dateformat, &tm);
1243                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1244                 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1245                 fmt = datefmt;
1246         } else {
1247                 char *tmp = alloca(strlen(fmt) + 2);
1248                 sprintf(tmp, "%c%s", 127, fmt);
1249                 fmt = tmp;
1250         }
1251
1252         /* Build string */
1253         res = ast_str_set_va(&buf, 0, fmt, ap);
1254
1255         /* If the build failed then we can drop this allocated message */
1256         if (res == AST_DYNSTR_BUILD_FAILED)
1257                 return;
1258
1259         if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1260                 return;
1261
1262         ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1263
1264         ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->message + 1);
1265
1266         /* Set type */
1267         logmsg->type = LOGMSG_VERBOSE;
1268         
1269         /* Add to the list and poke the thread if possible */
1270         if (logthread != AST_PTHREADT_NULL) {
1271                 AST_LIST_LOCK(&logmsgs);
1272                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1273                 ast_cond_signal(&logcond);
1274                 AST_LIST_UNLOCK(&logmsgs);
1275         } else {
1276                 logger_print_verbose(logmsg);
1277                 ast_free(logmsg);
1278         }
1279 }
1280
1281 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1282 {
1283         va_list ap;
1284
1285         va_start(ap, fmt);
1286         __ast_verbose_ap(file, line, func, fmt, ap);
1287         va_end(ap);
1288 }
1289
1290 /* No new code should use this directly, but we have the ABI for backwards compat */
1291 #undef ast_verbose
1292 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1293 void ast_verbose(const char *fmt, ...)
1294 {
1295         va_list ap;
1296
1297         va_start(ap, fmt);
1298         __ast_verbose_ap("", 0, "", fmt, ap);
1299         va_end(ap);
1300 }
1301
1302 int ast_register_verbose(void (*v)(const char *string)) 
1303 {
1304         struct verb *verb;
1305
1306         if (!(verb = ast_malloc(sizeof(*verb))))
1307                 return -1;
1308
1309         verb->verboser = v;
1310
1311         AST_RWLIST_WRLOCK(&verbosers);
1312         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1313         AST_RWLIST_UNLOCK(&verbosers);
1314         
1315         return 0;
1316 }
1317
1318 int ast_unregister_verbose(void (*v)(const char *string))
1319 {
1320         struct verb *cur;
1321
1322         AST_RWLIST_WRLOCK(&verbosers);
1323         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1324                 if (cur->verboser == v) {
1325                         AST_RWLIST_REMOVE_CURRENT(list);
1326                         ast_free(cur);
1327                         break;
1328                 }
1329         }
1330         AST_RWLIST_TRAVERSE_SAFE_END;
1331         AST_RWLIST_UNLOCK(&verbosers);
1332         
1333         return cur ? 0 : -1;
1334 }
1335
1336 static void update_logchannels(void)
1337 {
1338         struct logchannel *cur;
1339
1340         AST_RWLIST_WRLOCK(&logchannels);
1341
1342         global_logmask = 0;
1343
1344         AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
1345                 cur->logmask = make_components(cur->components, cur->lineno);
1346                 global_logmask |= cur->logmask;
1347         }
1348
1349         AST_RWLIST_UNLOCK(&logchannels);
1350 }
1351
1352 int ast_logger_register_level(const char *name)
1353 {
1354         unsigned int level;
1355         unsigned int available = 0;
1356
1357         AST_RWLIST_WRLOCK(&logchannels);
1358
1359         for (level = 0; level < ARRAY_LEN(levels); level++) {
1360                 if ((level >= 16) && !available && !levels[level]) {
1361                         available = level;
1362                         continue;
1363                 }
1364
1365                 if (levels[level] && !strcasecmp(levels[level], name)) {
1366                         ast_log(LOG_WARNING,
1367                                 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
1368                                 name);
1369                         AST_RWLIST_UNLOCK(&logchannels);
1370
1371                         return -1;
1372                 }
1373         }
1374
1375         if (!available) {
1376                 ast_log(LOG_WARNING,
1377                         "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
1378                         name);
1379                 AST_RWLIST_UNLOCK(&logchannels);
1380
1381                 return -1;
1382         }
1383
1384         levels[available] = ast_strdup(name);
1385
1386         AST_RWLIST_UNLOCK(&logchannels);
1387
1388         ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
1389
1390         update_logchannels();
1391
1392         return available;
1393 }
1394
1395 void ast_logger_unregister_level(const char *name)
1396 {
1397         unsigned int found = 0;
1398         unsigned int x;
1399
1400         AST_RWLIST_WRLOCK(&logchannels);
1401
1402         for (x = 16; x < ARRAY_LEN(levels); x++) {
1403                 if (!levels[x]) {
1404                         continue;
1405                 }
1406
1407                 if (strcasecmp(levels[x], name)) {
1408                         continue;
1409                 }
1410
1411                 found = 1;
1412                 break;
1413         }
1414
1415         if (found) {
1416                 /* take this level out of the global_logmask, to ensure that no new log messages
1417                  * will be queued for it
1418                  */
1419
1420                 global_logmask &= ~(1 << x);
1421
1422                 free(levels[x]);
1423                 levels[x] = NULL;
1424                 AST_RWLIST_UNLOCK(&logchannels);
1425
1426                 ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
1427
1428                 update_logchannels();
1429         } else {
1430                 AST_RWLIST_UNLOCK(&logchannels);
1431         }
1432 }
1433