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