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