logger: Apply default console logging when configuration cannot be loaded.
[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 /*! \li \ref logger.c uses the configuration file \ref logger.conf
29  * \addtogroup configuration_file Configuration Files
30  */
31
32 /*!
33  * \page logger.conf logger.conf
34  * \verbinclude logger.conf.sample
35  */
36
37 /*** MODULEINFO
38         <support_level>core</support_level>
39  ***/
40
41 #include "asterisk.h"
42
43 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
44
45 /* When we include logger.h again it will trample on some stuff in syslog.h, but
46  * nothing we care about in here. */
47 #include <syslog.h>
48 #include <signal.h>
49 #include <time.h>
50 #include <sys/stat.h>
51 #include <fcntl.h>
52
53 #include "asterisk/_private.h"
54 #include "asterisk/paths.h"     /* use ast_config_AST_LOG_DIR */
55 #include "asterisk/logger.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/channel.h"
58 #include "asterisk/config.h"
59 #include "asterisk/term.h"
60 #include "asterisk/cli.h"
61 #include "asterisk/utils.h"
62 #include "asterisk/manager.h"
63 #include "asterisk/astobj2.h"
64 #include "asterisk/threadstorage.h"
65 #include "asterisk/strings.h"
66 #include "asterisk/pbx.h"
67 #include "asterisk/app.h"
68 #include "asterisk/syslog.h"
69 #include "asterisk/buildinfo.h"
70 #include "asterisk/ast_version.h"
71 #include "asterisk/backtrace.h"
72
73 /*** DOCUMENTATION
74  ***/
75
76 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
77
78 static char queue_log_name[256] = QUEUELOG;
79 static char exec_after_rotate[256] = "";
80
81 static int filesize_reload_needed;
82 static unsigned int global_logmask = 0xFFFF;
83 static int queuelog_init;
84 static int logger_initialized;
85 static volatile int next_unique_callid = 1; /* Used to assign unique call_ids to calls */
86 static int display_callids;
87
88 AST_THREADSTORAGE(unique_callid);
89
90 static enum rotatestrategy {
91         NONE = 0,                /* Do not rotate log files at all, instead rely on external mechanisms */
92         SEQUENTIAL = 1 << 0,     /* Original method - create a new file, in order */
93         ROTATE = 1 << 1,         /* Rotate all files, such that the oldest file has the highest suffix */
94         TIMESTAMP = 1 << 2,      /* Append the epoch timestamp onto the end of the archived file */
95 } rotatestrategy = SEQUENTIAL;
96
97 static struct {
98         unsigned int queue_log:1;
99         unsigned int queue_log_to_file:1;
100         unsigned int queue_adaptive_realtime:1;
101         unsigned int queue_log_realtime_use_gmt:1;
102 } logfiles = { 1 };
103
104 static char hostname[MAXHOSTNAMELEN];
105
106 enum logtypes {
107         LOGTYPE_SYSLOG,
108         LOGTYPE_FILE,
109         LOGTYPE_CONSOLE,
110 };
111
112 struct logchannel {
113         /*! What to log to this channel */
114         unsigned int logmask;
115         /*! If this channel is disabled or not */
116         int disabled;
117         /*! syslog facility */
118         int facility;
119         /*! Verbosity level. (-1 if use option_verbose for the level.) */
120         int verbosity;
121         /*! Type of log channel */
122         enum logtypes type;
123         /*! logfile logging file pointer */
124         FILE *fileptr;
125         /*! Filename */
126         char filename[PATH_MAX];
127         /*! field for linking to list */
128         AST_LIST_ENTRY(logchannel) list;
129         /*! Line number from configuration file */
130         int lineno;
131         /*! Whether this log channel was created dynamically */
132         int dynamic;
133         /*! Components (levels) from last config load */
134         char components[0];
135 };
136
137 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
138
139 enum logmsgtypes {
140         LOGMSG_NORMAL = 0,
141         LOGMSG_VERBOSE,
142 };
143
144 struct logmsg {
145         enum logmsgtypes type;
146         int level;
147         int line;
148         int lwp;
149         ast_callid callid;
150         AST_DECLARE_STRING_FIELDS(
151                 AST_STRING_FIELD(date);
152                 AST_STRING_FIELD(file);
153                 AST_STRING_FIELD(function);
154                 AST_STRING_FIELD(message);
155                 AST_STRING_FIELD(level_name);
156         );
157         AST_LIST_ENTRY(logmsg) list;
158 };
159
160 static void logmsg_free(struct logmsg *msg)
161 {
162         ast_free(msg);
163 }
164
165 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
166 static pthread_t logthread = AST_PTHREADT_NULL;
167 static ast_cond_t logcond;
168 static int close_logger_thread = 0;
169
170 static FILE *qlog;
171
172 /*! \brief Logging channels used in the Asterisk logging system
173  *
174  * The first 16 levels are reserved for system usage, and the remaining
175  * levels are reserved for usage by dynamic levels registered via
176  * ast_logger_register_level.
177  */
178
179 /* Modifications to this array are protected by the rwlock in the
180  * logchannels list.
181  */
182
183 static char *levels[NUMLOGLEVELS] = {
184         "DEBUG",
185         "---EVENT---",          /* no longer used */
186         "NOTICE",
187         "WARNING",
188         "ERROR",
189         "VERBOSE",
190         "DTMF",
191 };
192
193 /*! \brief Colors used in the console for logging */
194 static const int colors[NUMLOGLEVELS] = {
195         COLOR_BRGREEN,
196         COLOR_BRBLUE,           /* no longer used */
197         COLOR_YELLOW,
198         COLOR_BRRED,
199         COLOR_RED,
200         COLOR_GREEN,
201         COLOR_BRGREEN,
202         0,
203         0,
204         0,
205         0,
206         0,
207         0,
208         0,
209         0,
210         0,
211         COLOR_BRBLUE,
212         COLOR_BRBLUE,
213         COLOR_BRBLUE,
214         COLOR_BRBLUE,
215         COLOR_BRBLUE,
216         COLOR_BRBLUE,
217         COLOR_BRBLUE,
218         COLOR_BRBLUE,
219         COLOR_BRBLUE,
220         COLOR_BRBLUE,
221         COLOR_BRBLUE,
222         COLOR_BRBLUE,
223         COLOR_BRBLUE,
224         COLOR_BRBLUE,
225         COLOR_BRBLUE,
226         COLOR_BRBLUE,
227 };
228
229 AST_THREADSTORAGE(verbose_buf);
230 AST_THREADSTORAGE(verbose_build_buf);
231 #define VERBOSE_BUF_INIT_SIZE   256
232
233 AST_THREADSTORAGE(log_buf);
234 #define LOG_BUF_INIT_SIZE       256
235
236 static void make_components(struct logchannel *chan)
237 {
238         char *w;
239         unsigned int logmask = 0;
240         char *stringp = ast_strdupa(chan->components);
241         unsigned int x;
242         unsigned int verb_level;
243
244         /* Default to using option_verbose as the verbosity level of the logging channel.  */
245         verb_level = -1;
246
247         while ((w = strsep(&stringp, ","))) {
248                 w = ast_strip(w);
249                 if (ast_strlen_zero(w)) {
250                         continue;
251                 }
252                 if (!strcmp(w, "*")) {
253                         logmask = 0xFFFFFFFF;
254                 } else if (!strncasecmp(w, "verbose(", 8)) {
255                         if (levels[__LOG_VERBOSE] && sscanf(w + 8, "%30u)", &verb_level) == 1) {
256                                 logmask |= (1 << __LOG_VERBOSE);
257                         }
258                 } else {
259                         for (x = 0; x < ARRAY_LEN(levels); ++x) {
260                                 if (levels[x] && !strcasecmp(w, levels[x])) {
261                                         logmask |= (1 << x);
262                                         break;
263                                 }
264                         }
265                 }
266         }
267         if (chan->type == LOGTYPE_CONSOLE) {
268                 /*
269                  * Force to use the root console verbose level so if the
270                  * user specified any verbose level then it does not interfere
271                  * with calculating the ast_verb_sys_level value.
272                  */
273                 chan->verbosity = -1;
274         } else {
275                 chan->verbosity = verb_level;
276         }
277         chan->logmask = logmask;
278 }
279
280 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno, int dynamic)
281 {
282         struct logchannel *chan;
283         char *facility;
284         struct ast_tm tm;
285         struct timeval now = ast_tvnow();
286         char datestring[256];
287
288         if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
289                 return NULL;
290
291         strcpy(chan->components, components);
292         chan->lineno = lineno;
293         chan->dynamic = dynamic;
294
295         if (!strcasecmp(channel, "console")) {
296                 chan->type = LOGTYPE_CONSOLE;
297         } else if (!strncasecmp(channel, "syslog", 6)) {
298                 /*
299                 * syntax is:
300                 *  syslog.facility => level,level,level
301                 */
302                 facility = strchr(channel, '.');
303                 if (!facility++ || !facility) {
304                         facility = "local0";
305                 }
306
307                 chan->facility = ast_syslog_facility(facility);
308
309                 if (chan->facility < 0) {
310                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
311                         ast_free(chan);
312                         return NULL;
313                 }
314
315                 chan->type = LOGTYPE_SYSLOG;
316                 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
317                 openlog("asterisk", LOG_PID, chan->facility);
318         } else {
319                 const char *log_dir_prefix = "";
320                 const char *log_dir_separator = "";
321
322                 if (channel[0] != '/') {
323                         log_dir_prefix = ast_config_AST_LOG_DIR;
324                         log_dir_separator = "/";
325                 }
326
327                 if (!ast_strlen_zero(hostname)) {
328                         snprintf(chan->filename, sizeof(chan->filename), "%s%s%s.%s",
329                                 log_dir_prefix, log_dir_separator, channel, hostname);
330                 } else {
331                         snprintf(chan->filename, sizeof(chan->filename), "%s%s%s",
332                                 log_dir_prefix, log_dir_separator, channel);
333                 }
334
335                 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
336                         /* Can't do real logging here since we're called with a lock
337                          * so log to any attached consoles */
338                         ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
339                         ast_console_puts_mutable(chan->filename, __LOG_ERROR);
340                         ast_console_puts_mutable("': ", __LOG_ERROR);
341                         ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
342                         ast_console_puts_mutable("'\n", __LOG_ERROR);
343                         ast_free(chan);
344                         return NULL;
345                 } else {
346                         /* Create our date/time */
347                         ast_localtime(&now, &tm, NULL);
348                         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
349
350                         fprintf(chan->fileptr, "[%s] Asterisk %s built by %s @ %s on a %s running %s on %s\n",
351                                 datestring, ast_get_version(), ast_build_user, ast_build_hostname,
352                                 ast_build_machine, ast_build_os, ast_build_date);
353                         fflush(chan->fileptr);
354                 }
355                 chan->type = LOGTYPE_FILE;
356         }
357         make_components(chan);
358
359         return chan;
360 }
361
362 /* \brief Read config, setup channels.
363  * \param locked The logchannels list is locked and this is a reload
364  * \param altconf Alternate configuration file to read.
365  *
366  * \retval 0 Success
367  * \retval -1 No config found or Failed
368  */
369 static int init_logger_chain(int locked, const char *altconf)
370 {
371         struct logchannel *chan;
372         struct ast_config *cfg;
373         struct ast_variable *var;
374         const char *s;
375         struct ast_flags config_flags = { 0 };
376
377         display_callids = 1;
378
379         if (!(cfg = ast_config_load2(S_OR(altconf, "logger.conf"), "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
380                 cfg = NULL;
381         }
382
383         /* delete our list of log channels */
384         if (!locked) {
385                 AST_RWLIST_WRLOCK(&logchannels);
386         }
387         while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
388                 ast_free(chan);
389         }
390         global_logmask = 0;
391         if (!locked) {
392                 AST_RWLIST_UNLOCK(&logchannels);
393         }
394
395         errno = 0;
396         /* close syslog */
397         closelog();
398
399         /* If no config file, we're fine, set default options. */
400         if (!cfg) {
401                 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
402                         fprintf(stderr, "Failed to initialize default logging\n");
403                         return -1;
404                 }
405                 chan->type = LOGTYPE_CONSOLE;
406                 chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
407
408                 if (!locked) {
409                         AST_RWLIST_WRLOCK(&logchannels);
410                 }
411                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
412                 global_logmask |= chan->logmask;
413                 if (!locked) {
414                         AST_RWLIST_UNLOCK(&logchannels);
415                 }
416
417                 return -1;
418         }
419
420         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
421                 if (ast_true(s)) {
422                         if (gethostname(hostname, sizeof(hostname) - 1)) {
423                                 ast_copy_string(hostname, "unknown", sizeof(hostname));
424                                 fprintf(stderr, "What box has no hostname???\n");
425                         }
426                 } else
427                         hostname[0] = '\0';
428         } else
429                 hostname[0] = '\0';
430         if ((s = ast_variable_retrieve(cfg, "general", "display_callids"))) {
431                 display_callids = ast_true(s);
432         }
433         if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
434                 ast_copy_string(dateformat, s, sizeof(dateformat));
435         else
436                 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
437         if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
438                 logfiles.queue_log = ast_true(s);
439         }
440         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_to_file"))) {
441                 logfiles.queue_log_to_file = ast_true(s);
442         }
443         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name"))) {
444                 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
445         }
446         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_realtime_use_gmt"))) {
447                 logfiles.queue_log_realtime_use_gmt = ast_true(s);
448         }
449         if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate"))) {
450                 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
451         }
452         if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
453                 if (strcasecmp(s, "timestamp") == 0) {
454                         rotatestrategy = TIMESTAMP;
455                 } else if (strcasecmp(s, "rotate") == 0) {
456                         rotatestrategy = ROTATE;
457                 } else if (strcasecmp(s, "sequential") == 0) {
458                         rotatestrategy = SEQUENTIAL;
459                 } else if (strcasecmp(s, "none") == 0) {
460                         rotatestrategy = NONE;
461                 } else {
462                         fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
463                 }
464         } else {
465                 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
466                         rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
467                         fprintf(stderr, "rotatetimestamp option has been deprecated.  Please use rotatestrategy instead.\n");
468                 }
469         }
470
471         if (!locked) {
472                 AST_RWLIST_WRLOCK(&logchannels);
473         }
474         var = ast_variable_browse(cfg, "logfiles");
475         for (; var; var = var->next) {
476                 if (!(chan = make_logchannel(var->name, var->value, var->lineno, 0))) {
477                         /* Print error message directly to the consoles since the lock is held
478                          * and we don't want to unlock with the list partially built */
479                         ast_console_puts_mutable("ERROR: Unable to create log channel '", __LOG_ERROR);
480                         ast_console_puts_mutable(var->name, __LOG_ERROR);
481                         ast_console_puts_mutable("'\n", __LOG_ERROR);
482                         continue;
483                 }
484                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
485                 global_logmask |= chan->logmask;
486         }
487
488         if (qlog) {
489                 fclose(qlog);
490                 qlog = NULL;
491         }
492
493         if (!locked) {
494                 AST_RWLIST_UNLOCK(&logchannels);
495         }
496
497         ast_config_destroy(cfg);
498
499         return 0;
500 }
501
502 void ast_child_verbose(int level, const char *fmt, ...)
503 {
504         char *msg = NULL, *emsg = NULL, *sptr, *eptr;
505         va_list ap, aq;
506         int size;
507
508         va_start(ap, fmt);
509         va_copy(aq, ap);
510         if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
511                 va_end(ap);
512                 va_end(aq);
513                 return;
514         }
515         va_end(ap);
516
517         if (!(msg = ast_malloc(size + 1))) {
518                 va_end(aq);
519                 return;
520         }
521
522         vsnprintf(msg, size + 1, fmt, aq);
523         va_end(aq);
524
525         if (!(emsg = ast_malloc(size * 2 + 1))) {
526                 ast_free(msg);
527                 return;
528         }
529
530         for (sptr = msg, eptr = emsg; ; sptr++) {
531                 if (*sptr == '"') {
532                         *eptr++ = '\\';
533                 }
534                 *eptr++ = *sptr;
535                 if (*sptr == '\0') {
536                         break;
537                 }
538         }
539         ast_free(msg);
540
541         fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
542         fflush(stdout);
543         ast_free(emsg);
544 }
545
546 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
547 {
548         va_list ap;
549         struct timeval tv;
550         struct ast_tm tm;
551         char qlog_msg[8192];
552         int qlog_len;
553         char time_str[30];
554
555         if (!logger_initialized) {
556                 /* You are too early.  We are not open yet! */
557                 return;
558         }
559         if (!queuelog_init) {
560                 /* We must initialize now since someone is trying to log something. */
561                 logger_queue_start();
562         }
563
564         if (ast_check_realtime("queue_log")) {
565                 tv = ast_tvnow();
566                 ast_localtime(&tv, &tm, logfiles.queue_log_realtime_use_gmt ? "GMT" : NULL);
567                 ast_strftime(time_str, sizeof(time_str), "%F %T.%6q", &tm);
568                 va_start(ap, fmt);
569                 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
570                 va_end(ap);
571                 if (logfiles.queue_adaptive_realtime) {
572                         AST_DECLARE_APP_ARGS(args,
573                                 AST_APP_ARG(data)[5];
574                         );
575                         AST_NONSTANDARD_APP_ARGS(args, qlog_msg, '|');
576                         /* Ensure fields are large enough to receive data */
577                         ast_realtime_require_field("queue_log",
578                                 "data1", RQ_CHAR, strlen(S_OR(args.data[0], "")),
579                                 "data2", RQ_CHAR, strlen(S_OR(args.data[1], "")),
580                                 "data3", RQ_CHAR, strlen(S_OR(args.data[2], "")),
581                                 "data4", RQ_CHAR, strlen(S_OR(args.data[3], "")),
582                                 "data5", RQ_CHAR, strlen(S_OR(args.data[4], "")),
583                                 SENTINEL);
584
585                         /* Store the log */
586                         ast_store_realtime("queue_log", "time", time_str,
587                                 "callid", callid,
588                                 "queuename", queuename,
589                                 "agent", agent,
590                                 "event", event,
591                                 "data1", S_OR(args.data[0], ""),
592                                 "data2", S_OR(args.data[1], ""),
593                                 "data3", S_OR(args.data[2], ""),
594                                 "data4", S_OR(args.data[3], ""),
595                                 "data5", S_OR(args.data[4], ""),
596                                 SENTINEL);
597                 } else {
598                         ast_store_realtime("queue_log", "time", time_str,
599                                 "callid", callid,
600                                 "queuename", queuename,
601                                 "agent", agent,
602                                 "event", event,
603                                 "data", qlog_msg,
604                                 SENTINEL);
605                 }
606
607                 if (!logfiles.queue_log_to_file) {
608                         return;
609                 }
610         }
611
612         if (qlog) {
613                 va_start(ap, fmt);
614                 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
615                 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
616                 va_end(ap);
617                 AST_RWLIST_RDLOCK(&logchannels);
618                 if (qlog) {
619                         fprintf(qlog, "%s\n", qlog_msg);
620                         fflush(qlog);
621                 }
622                 AST_RWLIST_UNLOCK(&logchannels);
623         }
624 }
625
626 static int rotate_file(const char *filename)
627 {
628         char old[PATH_MAX];
629         char new[PATH_MAX];
630         int x, y, which, found, res = 0, fd;
631         char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
632
633         switch (rotatestrategy) {
634         case NONE:
635                 /* No rotation */
636                 break;
637         case SEQUENTIAL:
638                 for (x = 0; ; x++) {
639                         snprintf(new, sizeof(new), "%s.%d", filename, x);
640                         fd = open(new, O_RDONLY);
641                         if (fd > -1)
642                                 close(fd);
643                         else
644                                 break;
645                 }
646                 if (rename(filename, new)) {
647                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
648                         res = -1;
649                 } else {
650                         filename = new;
651                 }
652                 break;
653         case TIMESTAMP:
654                 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
655                 if (rename(filename, new)) {
656                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
657                         res = -1;
658                 } else {
659                         filename = new;
660                 }
661                 break;
662         case ROTATE:
663                 /* Find the next empty slot, including a possible suffix */
664                 for (x = 0; ; x++) {
665                         found = 0;
666                         for (which = 0; which < ARRAY_LEN(suffixes); which++) {
667                                 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
668                                 fd = open(new, O_RDONLY);
669                                 if (fd > -1) {
670                                         close(fd);
671                                         found = 1;
672                                         break;
673                                 }
674                         }
675                         if (!found) {
676                                 break;
677                         }
678                 }
679
680                 /* Found an empty slot */
681                 for (y = x; y > 0; y--) {
682                         for (which = 0; which < ARRAY_LEN(suffixes); which++) {
683                                 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
684                                 fd = open(old, O_RDONLY);
685                                 if (fd > -1) {
686                                         /* Found the right suffix */
687                                         close(fd);
688                                         snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
689                                         if (rename(old, new)) {
690                                                 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
691                                                 res = -1;
692                                         }
693                                         break;
694                                 }
695                         }
696                 }
697
698                 /* Finally, rename the current file */
699                 snprintf(new, sizeof(new), "%s.0", filename);
700                 if (rename(filename, new)) {
701                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
702                         res = -1;
703                 } else {
704                         filename = new;
705                 }
706         }
707
708         if (!ast_strlen_zero(exec_after_rotate)) {
709                 struct ast_channel *c = ast_dummy_channel_alloc();
710                 char buf[512];
711
712                 pbx_builtin_setvar_helper(c, "filename", filename);
713                 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
714                 if (c) {
715                         c = ast_channel_unref(c);
716                 }
717                 if (ast_safe_system(buf) == -1) {
718                         ast_log(LOG_WARNING, "error executing '%s'\n", buf);
719                 }
720         }
721         return res;
722 }
723
724 /*!
725  * \internal
726  * \brief Start the realtime queue logging if configured.
727  *
728  * \retval TRUE if not to open queue log file.
729  */
730 static int logger_queue_rt_start(void)
731 {
732         if (ast_check_realtime("queue_log")) {
733                 if (!ast_realtime_require_field("queue_log",
734                         "time", RQ_DATETIME, 26,
735                         "data1", RQ_CHAR, 20,
736                         "data2", RQ_CHAR, 20,
737                         "data3", RQ_CHAR, 20,
738                         "data4", RQ_CHAR, 20,
739                         "data5", RQ_CHAR, 20,
740                         SENTINEL)) {
741                         logfiles.queue_adaptive_realtime = 1;
742                 } else {
743                         logfiles.queue_adaptive_realtime = 0;
744                 }
745
746                 if (!logfiles.queue_log_to_file) {
747                         /* Don't open the log file. */
748                         return 1;
749                 }
750         }
751         return 0;
752 }
753
754 /*!
755  * \internal
756  * \brief Rotate the queue log file and restart.
757  *
758  * \param queue_rotate Log queue rotation mode.
759  *
760  * \note Assumes logchannels is write locked on entry.
761  *
762  * \retval 0 on success.
763  * \retval -1 on error.
764  */
765 static int logger_queue_restart(int queue_rotate)
766 {
767         int res = 0;
768         char qfname[PATH_MAX];
769
770         if (logger_queue_rt_start()) {
771                 return res;
772         }
773
774         snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
775         if (qlog) {
776                 /* Just in case it was still open. */
777                 fclose(qlog);
778                 qlog = NULL;
779         }
780         if (queue_rotate) {
781                 rotate_file(qfname);
782         }
783
784         /* Open the log file. */
785         qlog = fopen(qfname, "a");
786         if (!qlog) {
787                 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
788                 res = -1;
789         }
790         return res;
791 }
792
793 static int reload_logger(int rotate, const char *altconf)
794 {
795         int queue_rotate = rotate;
796         struct logchannel *f;
797         int res = 0;
798
799         AST_RWLIST_WRLOCK(&logchannels);
800
801         if (qlog) {
802                 if (rotate < 0) {
803                         /* Check filesize - this one typically doesn't need an auto-rotate */
804                         if (ftello(qlog) > 0x40000000) { /* Arbitrarily, 1 GB */
805                                 fclose(qlog);
806                                 qlog = NULL;
807                         } else {
808                                 queue_rotate = 0;
809                         }
810                 } else {
811                         fclose(qlog);
812                         qlog = NULL;
813                 }
814         } else {
815                 queue_rotate = 0;
816         }
817
818         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
819
820         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
821                 if (f->disabled) {
822                         f->disabled = 0;        /* Re-enable logging at reload */
823                         /*** DOCUMENTATION
824                                 <managerEventInstance>
825                                         <synopsis>Raised when a logging channel is re-enabled after a reload operation.</synopsis>
826                                         <syntax>
827                                                 <parameter name="Channel">
828                                                         <para>The name of the logging channel.</para>
829                                                 </parameter>
830                                         </syntax>
831                                 </managerEventInstance>
832                         ***/
833                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
834                 }
835                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
836                         int rotate_this = 0;
837                         if (rotatestrategy != NONE && ftello(f->fileptr) > 0x40000000) { /* Arbitrarily, 1 GB */
838                                 /* Be more proactive about rotating massive log files */
839                                 rotate_this = 1;
840                         }
841                         fclose(f->fileptr);     /* Close file */
842                         f->fileptr = NULL;
843                         if (rotate || rotate_this) {
844                                 rotate_file(f->filename);
845                         }
846                 }
847         }
848
849         filesize_reload_needed = 0;
850
851         init_logger_chain(1 /* locked */, altconf);
852
853         ast_unload_realtime("queue_log");
854         if (logfiles.queue_log) {
855                 res = logger_queue_restart(queue_rotate);
856                 AST_RWLIST_UNLOCK(&logchannels);
857                 ast_verb_update();
858                 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
859                 ast_verb(1, "Asterisk Queue Logger restarted\n");
860         } else {
861                 AST_RWLIST_UNLOCK(&logchannels);
862                 ast_verb_update();
863         }
864
865         return res;
866 }
867
868 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
869         a full Asterisk reload) */
870 int logger_reload(void)
871 {
872         if (reload_logger(0, NULL)) {
873                 return RESULT_FAILURE;
874         }
875         return RESULT_SUCCESS;
876 }
877
878 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
879 {
880         switch (cmd) {
881         case CLI_INIT:
882                 e->command = "logger reload";
883                 e->usage =
884                         "Usage: logger reload [<alt-conf>]\n"
885                         "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
886                 return NULL;
887         case CLI_GENERATE:
888                 return NULL;
889         }
890         if (reload_logger(0, a->argc == 3 ? a->argv[2] : NULL)) {
891                 ast_cli(a->fd, "Failed to reload the logger\n");
892                 return CLI_FAILURE;
893         }
894         return CLI_SUCCESS;
895 }
896
897 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
898 {
899         switch (cmd) {
900         case CLI_INIT:
901                 e->command = "logger rotate";
902                 e->usage =
903                         "Usage: logger rotate\n"
904                         "       Rotates and Reopens the log files.\n";
905                 return NULL;
906         case CLI_GENERATE:
907                 return NULL;
908         }
909         if (reload_logger(1, NULL)) {
910                 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
911                 return CLI_FAILURE;
912         }
913         return CLI_SUCCESS;
914 }
915
916 int ast_logger_rotate()
917 {
918         return reload_logger(1, NULL);
919 }
920
921 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
922 {
923         int x;
924         int state;
925         int level = -1;
926
927         switch (cmd) {
928         case CLI_INIT:
929                 e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
930                 e->usage =
931                         "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
932                         "       Set a specific log level to enabled/disabled for this console.\n";
933                 return NULL;
934         case CLI_GENERATE:
935                 return NULL;
936         }
937
938         if (a->argc < 5)
939                 return CLI_SHOWUSAGE;
940
941         AST_RWLIST_WRLOCK(&logchannels);
942
943         for (x = 0; x < ARRAY_LEN(levels); x++) {
944                 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
945                         level = x;
946                         break;
947                 }
948         }
949
950         AST_RWLIST_UNLOCK(&logchannels);
951
952         state = ast_true(a->argv[4]) ? 1 : 0;
953
954         if (level != -1) {
955                 ast_console_toggle_loglevel(a->fd, level, state);
956                 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
957         } else
958                 return CLI_SHOWUSAGE;
959
960         return CLI_SUCCESS;
961 }
962
963 /*! \brief CLI command to show logging system configuration */
964 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
965 {
966 #define FORMATL "%-35.35s %-8.8s %-9.9s "
967         struct logchannel *chan;
968         switch (cmd) {
969         case CLI_INIT:
970                 e->command = "logger show channels";
971                 e->usage =
972                         "Usage: logger show channels\n"
973                         "       List configured logger channels.\n";
974                 return NULL;
975         case CLI_GENERATE:
976                 return NULL;
977         }
978         ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
979         ast_cli(a->fd, "Configuration\n");
980         ast_cli(a->fd, FORMATL, "-------", "----", "------");
981         ast_cli(a->fd, "-------------\n");
982         AST_RWLIST_RDLOCK(&logchannels);
983         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
984                 unsigned int level;
985
986                 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
987                         chan->disabled ? "Disabled" : "Enabled");
988                 ast_cli(a->fd, " - ");
989                 for (level = 0; level < ARRAY_LEN(levels); level++) {
990                         if ((chan->logmask & (1 << level)) && levels[level]) {
991                                 ast_cli(a->fd, "%s ", levels[level]);
992                         }
993                 }
994                 ast_cli(a->fd, "\n");
995         }
996         AST_RWLIST_UNLOCK(&logchannels);
997         ast_cli(a->fd, "\n");
998
999         return CLI_SUCCESS;
1000 }
1001
1002 static char *handle_logger_add_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1003 {
1004         struct logchannel *chan;
1005
1006         switch (cmd) {
1007         case CLI_INIT:
1008                 e->command = "logger add channel";
1009                 e->usage =
1010                         "Usage: logger add channel <name> <levels>\n"
1011                         "       Adds a temporary logger channel. This logger channel\n"
1012                         "       will exist until removed or until Asterisk is restarted.\n"
1013                         "       <levels> is a comma-separated list of desired logger\n"
1014                         "       levels such as: verbose,warning,error\n";
1015                 return NULL;
1016         case CLI_GENERATE:
1017                 return NULL;
1018         }
1019
1020         if (a->argc < 5) {
1021                 return CLI_SHOWUSAGE;
1022         }
1023
1024         AST_RWLIST_WRLOCK(&logchannels);
1025         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1026                 if (!strcmp(chan->filename, a->argv[3])) {
1027                         break;
1028                 }
1029         }
1030
1031         if (chan) {
1032                 AST_RWLIST_UNLOCK(&logchannels);
1033                 ast_cli(a->fd, "Logger channel '%s' already exists\n", a->argv[3]);
1034                 return CLI_SUCCESS;
1035         }
1036
1037         chan = make_logchannel(a->argv[3], a->argv[4], 0, 1);
1038         if (chan) {
1039                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
1040                 global_logmask |= chan->logmask;
1041                 AST_RWLIST_UNLOCK(&logchannels);
1042                 return CLI_SUCCESS;
1043         }
1044
1045         AST_RWLIST_UNLOCK(&logchannels);
1046         ast_cli(a->fd, "ERROR: Unable to create log channel '%s'\n", a->argv[3]);
1047
1048         return CLI_FAILURE;
1049 }
1050
1051 static char *handle_logger_remove_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1052 {
1053         struct logchannel *chan;
1054         int gen_count = 0;
1055         char *gen_ret = NULL;
1056
1057         switch (cmd) {
1058         case CLI_INIT:
1059                 e->command = "logger remove channel";
1060                 e->usage =
1061                         "Usage: logger remove channel <name>\n"
1062                         "       Removes a temporary logger channel.\n";
1063                 return NULL;
1064         case CLI_GENERATE:
1065                 if (a->argc > 4 || (a->argc == 4 && a->pos > 3)) {
1066                         return NULL;
1067                 }
1068                 AST_RWLIST_RDLOCK(&logchannels);
1069                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1070                         if (chan->dynamic && (ast_strlen_zero(a->argv[3])
1071                                 || !strncmp(a->argv[3], chan->filename, strlen(a->argv[3])))) {
1072                                 if (gen_count == a->n) {
1073                                         gen_ret = ast_strdup(chan->filename);
1074                                         break;
1075                                 }
1076                                 gen_count++;
1077                         }
1078                 }
1079                 AST_RWLIST_UNLOCK(&logchannels);
1080                 return gen_ret;
1081         }
1082
1083         if (a->argc < 4) {
1084                 return CLI_SHOWUSAGE;
1085         }
1086
1087         AST_RWLIST_WRLOCK(&logchannels);
1088         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&logchannels, chan, list) {
1089                 if (chan->dynamic && !strcmp(chan->filename, a->argv[3])) {
1090                         AST_RWLIST_REMOVE_CURRENT(list);
1091                         break;
1092                 }
1093         }
1094         AST_RWLIST_TRAVERSE_SAFE_END;
1095         AST_RWLIST_UNLOCK(&logchannels);
1096
1097         if (!chan) {
1098                 ast_cli(a->fd, "Unable to find dynamic logger channel '%s'\n", a->argv[3]);
1099                 return CLI_SUCCESS;
1100         }
1101
1102         ast_cli(a->fd, "Removed dynamic logger channel '%s'\n", chan->filename);
1103         if (chan->fileptr) {
1104                 fclose(chan->fileptr);
1105                 chan->fileptr = NULL;
1106         }
1107         ast_free(chan);
1108         chan = NULL;
1109
1110         return CLI_SUCCESS;
1111 }
1112
1113 struct verb {
1114         void (*verboser)(const char *string);
1115         AST_LIST_ENTRY(verb) list;
1116 };
1117
1118 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
1119
1120 static struct ast_cli_entry cli_logger[] = {
1121         AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
1122         AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
1123         AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
1124         AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console"),
1125         AST_CLI_DEFINE(handle_logger_add_channel, "Adds a new logging channel"),
1126         AST_CLI_DEFINE(handle_logger_remove_channel, "Removes a logging channel"),
1127 };
1128
1129 static void _handle_SIGXFSZ(int sig)
1130 {
1131         /* Indicate need to reload */
1132         filesize_reload_needed = 1;
1133 }
1134
1135 static struct sigaction handle_SIGXFSZ = {
1136         .sa_handler = _handle_SIGXFSZ,
1137         .sa_flags = SA_RESTART,
1138 };
1139
1140 static void ast_log_vsyslog(struct logmsg *msg)
1141 {
1142         char buf[BUFSIZ];
1143         int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
1144         char call_identifier_str[13];
1145
1146         if (msg->callid) {
1147                 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", msg->callid);
1148         } else {
1149                 call_identifier_str[0] = '\0';
1150         }
1151
1152         if (syslog_level < 0) {
1153                 /* we are locked here, so cannot ast_log() */
1154                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
1155                 return;
1156         }
1157
1158         snprintf(buf, sizeof(buf), "%s[%d]%s: %s:%d in %s: %s",
1159                  levels[msg->level], msg->lwp, call_identifier_str, msg->file, msg->line, msg->function, msg->message);
1160
1161         term_strip(buf, buf, strlen(buf) + 1);
1162         syslog(syslog_level, "%s", buf);
1163 }
1164
1165 static char *logger_strip_verbose_magic(const char *message, int level)
1166 {
1167         const char *begin, *end;
1168         char *stripped_message, *dst;
1169         char magic = -(level + 1);
1170
1171         if (!(stripped_message = ast_malloc(strlen(message) + 1))) {
1172                 return NULL;
1173         }
1174
1175         begin = message;
1176         dst = stripped_message;
1177         do {
1178                 end = strchr(begin, magic);
1179                 if (end) {
1180                         size_t len = end - begin;
1181                         memcpy(dst, begin, len);
1182                         begin = end + 1;
1183                         dst += len;
1184                 } else {
1185                         strcpy(dst, begin); /* safe */
1186                         break;
1187                 }
1188         } while (1);
1189
1190         return stripped_message;
1191 }
1192
1193 /*! \brief Print a normal log message to the channels */
1194 static void logger_print_normal(struct logmsg *logmsg)
1195 {
1196         struct logchannel *chan = NULL;
1197         char buf[BUFSIZ];
1198         struct verb *v = NULL;
1199         char *tmpmsg;
1200         int level = 0;
1201
1202         if (logmsg->level == __LOG_VERBOSE) {
1203
1204                 /* Iterate through the list of verbosers and pass them the log message string */
1205                 AST_RWLIST_RDLOCK(&verbosers);
1206                 AST_RWLIST_TRAVERSE(&verbosers, v, list)
1207                         v->verboser(logmsg->message);
1208                 AST_RWLIST_UNLOCK(&verbosers);
1209
1210                 level = VERBOSE_MAGIC2LEVEL(logmsg->message);
1211
1212                 tmpmsg = logger_strip_verbose_magic(logmsg->message, level);
1213                 if (tmpmsg) {
1214                         ast_string_field_set(logmsg, message, tmpmsg);
1215                         ast_free(tmpmsg);
1216                 }
1217         }
1218
1219         AST_RWLIST_RDLOCK(&logchannels);
1220
1221         if (!AST_RWLIST_EMPTY(&logchannels)) {
1222                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1223                         char call_identifier_str[13];
1224
1225                         if (logmsg->callid) {
1226                                 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", logmsg->callid);
1227                         } else {
1228                                 call_identifier_str[0] = '\0';
1229                         }
1230
1231
1232                         /* If the channel is disabled, then move on to the next one */
1233                         if (chan->disabled) {
1234                                 continue;
1235                         }
1236                         if (logmsg->level == __LOG_VERBOSE
1237                                 && (((chan->verbosity < 0) ? option_verbose : chan->verbosity)) < level) {
1238                                 continue;
1239                         }
1240
1241                         /* Check syslog channels */
1242                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
1243                                 ast_log_vsyslog(logmsg);
1244                         /* Console channels */
1245                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
1246                                 char linestr[128];
1247
1248                                 /* If the level is verbose, then skip it */
1249                                 if (logmsg->level == __LOG_VERBOSE)
1250                                         continue;
1251
1252                                 /* Turn the numerical line number into a string */
1253                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
1254                                 /* Build string to print out */
1255                                 snprintf(buf, sizeof(buf), "[%s] " COLORIZE_FMT "[%d]%s: " COLORIZE_FMT ":" COLORIZE_FMT " " COLORIZE_FMT ": %s",
1256                                          logmsg->date,
1257                                          COLORIZE(colors[logmsg->level], 0, logmsg->level_name),
1258                                          logmsg->lwp,
1259                                          call_identifier_str,
1260                                          COLORIZE(COLOR_BRWHITE, 0, logmsg->file),
1261                                          COLORIZE(COLOR_BRWHITE, 0, linestr),
1262                                          COLORIZE(COLOR_BRWHITE, 0, logmsg->function),
1263                                          logmsg->message);
1264                                 /* Print out */
1265                                 ast_console_puts_mutable(buf, logmsg->level);
1266                         /* File channels */
1267                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
1268                                 int res = 0;
1269
1270                                 /* If no file pointer exists, skip it */
1271                                 if (!chan->fileptr) {
1272                                         continue;
1273                                 }
1274
1275                                 /* Print out to the file */
1276                                 res = fprintf(chan->fileptr, "[%s] %s[%d]%s %s: %s",
1277                                               logmsg->date, logmsg->level_name, logmsg->lwp, call_identifier_str,
1278                                               logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
1279                                 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
1280                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
1281                                         if (errno == ENOMEM || errno == ENOSPC)
1282                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
1283                                         else
1284                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
1285                                         /*** DOCUMENTATION
1286                                                 <managerEventInstance>
1287                                                         <synopsis>Raised when a logging channel is disabled.</synopsis>
1288                                                         <syntax>
1289                                                                 <parameter name="Channel">
1290                                                                         <para>The name of the logging channel.</para>
1291                                                                 </parameter>
1292                                                         </syntax>
1293                                                 </managerEventInstance>
1294                                         ***/
1295                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
1296                                         chan->disabled = 1;
1297                                 } else if (res > 0) {
1298                                         fflush(chan->fileptr);
1299                                 }
1300                         }
1301                 }
1302         } else if (logmsg->level != __LOG_VERBOSE) {
1303                 fputs(logmsg->message, stdout);
1304         }
1305
1306         AST_RWLIST_UNLOCK(&logchannels);
1307
1308         /* If we need to reload because of the file size, then do so */
1309         if (filesize_reload_needed) {
1310                 reload_logger(-1, NULL);
1311                 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
1312         }
1313
1314         return;
1315 }
1316
1317 /*! \brief Actual logging thread */
1318 static void *logger_thread(void *data)
1319 {
1320         struct logmsg *next = NULL, *msg = NULL;
1321
1322         for (;;) {
1323                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
1324                 AST_LIST_LOCK(&logmsgs);
1325                 if (AST_LIST_EMPTY(&logmsgs)) {
1326                         if (close_logger_thread) {
1327                                 AST_LIST_UNLOCK(&logmsgs);
1328                                 break;
1329                         } else {
1330                                 ast_cond_wait(&logcond, &logmsgs.lock);
1331                         }
1332                 }
1333                 next = AST_LIST_FIRST(&logmsgs);
1334                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
1335                 AST_LIST_UNLOCK(&logmsgs);
1336
1337                 /* Otherwise go through and process each message in the order added */
1338                 while ((msg = next)) {
1339                         /* Get the next entry now so that we can free our current structure later */
1340                         next = AST_LIST_NEXT(msg, list);
1341
1342                         /* Depending on the type, send it to the proper function */
1343                         logger_print_normal(msg);
1344
1345                         /* Free the data since we are done */
1346                         logmsg_free(msg);
1347                 }
1348         }
1349
1350         return NULL;
1351 }
1352
1353 /*!
1354  * \internal
1355  * \brief Initialize the logger queue.
1356  *
1357  * \note Assumes logchannels is write locked on entry.
1358  *
1359  * \return Nothing
1360  */
1361 static void logger_queue_init(void)
1362 {
1363         ast_unload_realtime("queue_log");
1364         if (logfiles.queue_log) {
1365                 char qfname[PATH_MAX];
1366
1367                 if (logger_queue_rt_start()) {
1368                         return;
1369                 }
1370
1371                 /* Open the log file. */
1372                 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
1373                         queue_log_name);
1374                 if (qlog) {
1375                         /* Just in case it was already open. */
1376                         fclose(qlog);
1377                 }
1378                 qlog = fopen(qfname, "a");
1379                 if (!qlog) {
1380                         ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
1381                 }
1382         }
1383 }
1384
1385 /*!
1386  * \brief Start the ast_queue_log() logger.
1387  *
1388  * \note Called when the system is fully booted after startup
1389  * so preloaded realtime modules can get up.
1390  *
1391  * \return Nothing
1392  */
1393 void logger_queue_start(void)
1394 {
1395         /* Must not be called before the logger is initialized. */
1396         ast_assert(logger_initialized);
1397
1398         AST_RWLIST_WRLOCK(&logchannels);
1399         if (!queuelog_init) {
1400                 logger_queue_init();
1401                 queuelog_init = 1;
1402                 AST_RWLIST_UNLOCK(&logchannels);
1403                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
1404         } else {
1405                 AST_RWLIST_UNLOCK(&logchannels);
1406         }
1407 }
1408
1409 int init_logger(void)
1410 {
1411         int res;
1412         /* auto rotate if sig SIGXFSZ comes a-knockin */
1413         sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
1414
1415         /* Re-initialize the logmsgs mutex.  The recursive mutex can be accessed prior
1416          * to Asterisk being forked into the background, which can cause the thread
1417          * ID tracked by the underlying pthread mutex to be different than the ID of
1418          * the thread that unlocks the mutex.  Since init_logger is called after the
1419          * fork, it is safe to initialize the mutex here for future accesses.
1420          */
1421         ast_mutex_destroy(&logmsgs.lock);
1422         ast_mutex_init(&logmsgs.lock);
1423         ast_cond_init(&logcond, NULL);
1424
1425         /* start logger thread */
1426         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1427                 ast_cond_destroy(&logcond);
1428                 return -1;
1429         }
1430
1431         /* register the logger cli commands */
1432         ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1433
1434         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1435
1436         /* create log channels */
1437         res = init_logger_chain(0 /* locked */, NULL);
1438         ast_verb_update();
1439         logger_initialized = 1;
1440         if (res) {
1441                 ast_log(LOG_ERROR, "Errors detected in logger.conf.  Default console logging is being used.\n");
1442         }
1443
1444         return 0;
1445 }
1446
1447 void close_logger(void)
1448 {
1449         struct logchannel *f = NULL;
1450         struct verb *cur = NULL;
1451
1452         ast_cli_unregister_multiple(cli_logger, ARRAY_LEN(cli_logger));
1453
1454         logger_initialized = 0;
1455
1456         /* Stop logger thread */
1457         AST_LIST_LOCK(&logmsgs);
1458         close_logger_thread = 1;
1459         ast_cond_signal(&logcond);
1460         AST_LIST_UNLOCK(&logmsgs);
1461
1462         if (logthread != AST_PTHREADT_NULL)
1463                 pthread_join(logthread, NULL);
1464
1465         AST_RWLIST_WRLOCK(&verbosers);
1466         while ((cur = AST_LIST_REMOVE_HEAD(&verbosers, list))) {
1467                 ast_free(cur);
1468         }
1469         AST_RWLIST_UNLOCK(&verbosers);
1470
1471         AST_RWLIST_WRLOCK(&logchannels);
1472
1473         if (qlog) {
1474                 fclose(qlog);
1475                 qlog = NULL;
1476         }
1477
1478         while ((f = AST_LIST_REMOVE_HEAD(&logchannels, list))) {
1479                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1480                         fclose(f->fileptr);
1481                         f->fileptr = NULL;
1482                 }
1483                 ast_free(f);
1484         }
1485
1486         closelog(); /* syslog */
1487
1488         AST_RWLIST_UNLOCK(&logchannels);
1489 }
1490
1491 void ast_callid_strnprint(char *buffer, size_t buffer_size, ast_callid callid)
1492 {
1493         snprintf(buffer, buffer_size, "[C-%08x]", callid);
1494 }
1495
1496 ast_callid ast_create_callid(void)
1497 {
1498         ast_callid call;
1499
1500         call = ast_atomic_fetchadd_int(&next_unique_callid, +1);
1501 #ifdef TEST_FRAMEWORK
1502         ast_debug(3, "CALL_ID [C-%08x] created by thread.\n", call);
1503 #endif
1504         return call;
1505 }
1506
1507 ast_callid ast_read_threadstorage_callid(void)
1508 {
1509         ast_callid *callid;
1510
1511         callid = ast_threadstorage_get(&unique_callid, sizeof(*callid));
1512
1513         return callid ? *callid : 0;
1514
1515 }
1516
1517 int ast_callid_threadassoc_change(ast_callid callid)
1518 {
1519         ast_callid *id = ast_threadstorage_get(&unique_callid, sizeof(*id));
1520
1521         if (!id) {
1522                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1523                 return -1;
1524         }
1525
1526         if (*id && (*id != callid)) {
1527 #ifdef TEST_FRAMEWORK
1528                 ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", *id);
1529 #endif
1530                 *id = 0;
1531         }
1532
1533         if (!(*id) && callid) {
1534                 *id = callid;
1535 #ifdef TEST_FRAMEWORK
1536                 ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", callid);
1537 #endif
1538         }
1539
1540         return 0;
1541 }
1542
1543 int ast_callid_threadassoc_add(ast_callid callid)
1544 {
1545         ast_callid *pointing;
1546
1547         pointing = ast_threadstorage_get(&unique_callid, sizeof(*pointing));
1548         if (!(pointing)) {
1549                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1550                 return -1;
1551         }
1552
1553         if (!(*pointing)) {
1554                 *pointing = callid;
1555 #ifdef TEST_FRAMEWORK
1556                 ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", callid);
1557 #endif
1558         } else {
1559                 ast_log(LOG_WARNING, "Attempted to ast_callid_threadassoc_add on thread already associated with a callid.\n");
1560                 return 1;
1561         }
1562
1563         return 0;
1564 }
1565
1566 int ast_callid_threadassoc_remove(void)
1567 {
1568         ast_callid *pointing;
1569
1570         pointing = ast_threadstorage_get(&unique_callid, sizeof(*pointing));
1571         if (!(pointing)) {
1572                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1573                 return -1;
1574         }
1575
1576         if (!(*pointing)) {
1577                 ast_log(LOG_ERROR, "Tried to clean callid thread storage with no callid in thread storage.\n");
1578                 return -1;
1579         } else {
1580 #ifdef TEST_FRAMEWORK
1581                 ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", *pointing);
1582 #endif
1583                 *pointing = 0;
1584                 return 0;
1585         }
1586 }
1587
1588 int ast_callid_threadstorage_auto(ast_callid *callid)
1589 {
1590         ast_callid tmp;
1591
1592         /* Start by trying to see if a callid is available from thread storage */
1593         tmp = ast_read_threadstorage_callid();
1594         if (tmp) {
1595                 *callid = tmp;
1596                 return 0;
1597         }
1598
1599         /* If that failed, try to create a new one and bind it. */
1600         *callid = ast_create_callid();
1601         if (*callid) {
1602                 ast_callid_threadassoc_add(*callid);
1603                 return 1;
1604         }
1605
1606         /* If neither worked, then something must have gone wrong. */
1607         return -1;
1608 }
1609
1610 void ast_callid_threadstorage_auto_clean(ast_callid callid, int callid_created)
1611 {
1612         if (callid && callid_created) {
1613                 /* If the callid was created rather than simply grabbed from the thread storage, we need to unbind here. */
1614                 ast_callid_threadassoc_remove();
1615         }
1616 }
1617
1618 /*!
1619  * \brief send log messages to syslog and/or the console
1620  */
1621 static void __attribute__((format(printf, 6, 0))) ast_log_full(int level, const char *file, int line, const char *function, ast_callid callid, const char *fmt, va_list ap)
1622 {
1623         struct logmsg *logmsg = NULL;
1624         struct ast_str *buf = NULL;
1625         struct ast_tm tm;
1626         struct timeval now = ast_tvnow();
1627         int res = 0;
1628         char datestring[256];
1629
1630         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1631                 return;
1632
1633         if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
1634                 /*
1635                  * we don't have the logger chain configured yet,
1636                  * so just log to stdout
1637                  */
1638                 int result;
1639                 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1640                 if (result != AST_DYNSTR_BUILD_FAILED) {
1641                         term_filter_escapes(ast_str_buffer(buf));
1642                         fputs(ast_str_buffer(buf), stdout);
1643                 }
1644                 return;
1645         }
1646
1647         /* Ignore anything that never gets logged anywhere */
1648         if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
1649                 return;
1650
1651         /* Build string */
1652         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1653
1654         /* If the build failed, then abort and free this structure */
1655         if (res == AST_DYNSTR_BUILD_FAILED)
1656                 return;
1657
1658         /* Create a new logging message */
1659         if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1660                 return;
1661
1662         /* Copy string over */
1663         ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1664
1665         /* Set type */
1666         if (level == __LOG_VERBOSE) {
1667                 logmsg->type = LOGMSG_VERBOSE;
1668         } else {
1669                 logmsg->type = LOGMSG_NORMAL;
1670         }
1671
1672         if (display_callids && callid) {
1673                 logmsg->callid = callid;
1674         }
1675
1676         /* Create our date/time */
1677         ast_localtime(&now, &tm, NULL);
1678         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1679         ast_string_field_set(logmsg, date, datestring);
1680
1681         /* Copy over data */
1682         logmsg->level = level;
1683         logmsg->line = line;
1684         ast_string_field_set(logmsg, level_name, levels[level]);
1685         ast_string_field_set(logmsg, file, file);
1686         ast_string_field_set(logmsg, function, function);
1687         logmsg->lwp = ast_get_tid();
1688
1689         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1690         if (logthread != AST_PTHREADT_NULL) {
1691                 AST_LIST_LOCK(&logmsgs);
1692                 if (close_logger_thread) {
1693                         /* Logger is either closing or closed.  We cannot log this message. */
1694                         logmsg_free(logmsg);
1695                 } else {
1696                         AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1697                         ast_cond_signal(&logcond);
1698                 }
1699                 AST_LIST_UNLOCK(&logmsgs);
1700         } else {
1701                 logger_print_normal(logmsg);
1702                 logmsg_free(logmsg);
1703         }
1704 }
1705
1706 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1707 {
1708         ast_callid callid;
1709         va_list ap;
1710
1711         callid = ast_read_threadstorage_callid();
1712
1713         va_start(ap, fmt);
1714         if (level == __LOG_VERBOSE) {
1715                 __ast_verbose_ap(file, line, function, 0, callid, fmt, ap);
1716         } else {
1717                 ast_log_full(level, file, line, function, callid, fmt, ap);
1718         }
1719         va_end(ap);
1720 }
1721
1722 void ast_log_callid(int level, const char *file, int line, const char *function, ast_callid callid, const char *fmt, ...)
1723 {
1724         va_list ap;
1725         va_start(ap, fmt);
1726         ast_log_full(level, file, line, function, callid, fmt, ap);
1727         va_end(ap);
1728 }
1729
1730
1731 void ast_log_backtrace(void)
1732 {
1733 #ifdef HAVE_BKTR
1734         struct ast_bt *bt;
1735         int i = 0;
1736         char **strings;
1737
1738         if (!(bt = ast_bt_create())) {
1739                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1740                 return;
1741         }
1742
1743         if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
1744                 ast_verbose("Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1745                 for (i = 3; i < bt->num_frames - 2; i++) {
1746                         ast_verbose("#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
1747                 }
1748
1749                 ast_std_free(strings);
1750         } else {
1751                 ast_verbose("Could not allocate memory for backtrace\n");
1752         }
1753         ast_bt_destroy(bt);
1754 #else
1755         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1756 #endif /* defined(HAVE_BKTR) */
1757 }
1758
1759 void __ast_verbose_ap(const char *file, int line, const char *func, int level, ast_callid callid, const char *fmt, va_list ap)
1760 {
1761         const char *p;
1762         struct ast_str *prefixed, *buf;
1763         int res = 0;
1764         signed char magic = level > 9 ? -10 : -level - 1; /* 0 => -1, 1 => -2, etc.  Can't pass NUL, as it is EOS-delimiter */
1765
1766         /* For compatibility with modules still calling ast_verbose() directly instead of using ast_verb() */
1767         if (level < 0) {
1768                 if (!strncmp(fmt, VERBOSE_PREFIX_4, strlen(VERBOSE_PREFIX_4))) {
1769                         magic = -5;
1770                 } else if (!strncmp(fmt, VERBOSE_PREFIX_3, strlen(VERBOSE_PREFIX_3))) {
1771                         magic = -4;
1772                 } else if (!strncmp(fmt, VERBOSE_PREFIX_2, strlen(VERBOSE_PREFIX_2))) {
1773                         magic = -3;
1774                 } else if (!strncmp(fmt, VERBOSE_PREFIX_1, strlen(VERBOSE_PREFIX_1))) {
1775                         magic = -2;
1776                 } else {
1777                         magic = -1;
1778                 }
1779         }
1780
1781         if (!(prefixed = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)) ||
1782             !(buf = ast_str_thread_get(&verbose_build_buf, VERBOSE_BUF_INIT_SIZE))) {
1783                 return;
1784         }
1785
1786         res = ast_str_set_va(&buf, 0, fmt, ap);
1787         /* If the build failed then we can drop this allocated message */
1788         if (res == AST_DYNSTR_BUILD_FAILED) {
1789                 return;
1790         }
1791
1792         ast_str_reset(prefixed);
1793
1794         /* for every newline found in the buffer add verbose prefix data */
1795         fmt = ast_str_buffer(buf);
1796         do {
1797                 if (!(p = strchr(fmt, '\n'))) {
1798                         p = strchr(fmt, '\0') - 1;
1799                 }
1800                 ++p;
1801
1802                 ast_str_append(&prefixed, 0, "%c", (char)magic);
1803                 ast_str_append_substr(&prefixed, 0, fmt, p - fmt);
1804                 fmt = p;
1805         } while (p && *p);
1806
1807         ast_log_callid(__LOG_VERBOSE, file, line, func, callid, "%s", ast_str_buffer(prefixed));
1808 }
1809
1810 void __ast_verbose(const char *file, int line, const char *func, int level, const char *fmt, ...)
1811 {
1812         ast_callid callid;
1813         va_list ap;
1814
1815         callid = ast_read_threadstorage_callid();
1816
1817         va_start(ap, fmt);
1818         __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
1819         va_end(ap);
1820 }
1821
1822 void __ast_verbose_callid(const char *file, int line, const char *func, int level, ast_callid callid, const char *fmt, ...)
1823 {
1824         va_list ap;
1825         va_start(ap, fmt);
1826         __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
1827         va_end(ap);
1828 }
1829
1830 /* No new code should use this directly, but we have the ABI for backwards compat */
1831 #undef ast_verbose
1832 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1833 void ast_verbose(const char *fmt, ...)
1834 {
1835         ast_callid callid;
1836         va_list ap;
1837
1838         callid = ast_read_threadstorage_callid();
1839
1840         va_start(ap, fmt);
1841         __ast_verbose_ap("", 0, "", 0, callid, fmt, ap);
1842         va_end(ap);
1843 }
1844
1845 /*! Console verbosity level node. */
1846 struct verb_console {
1847         /*! List node link */
1848         AST_LIST_ENTRY(verb_console) node;
1849         /*! Console verbosity level. */
1850         int *level;
1851 };
1852
1853 /*! Registered console verbosity levels */
1854 static AST_RWLIST_HEAD_STATIC(verb_consoles, verb_console);
1855
1856 /*! ast_verb_update() reentrancy protection lock. */
1857 AST_MUTEX_DEFINE_STATIC(verb_update_lock);
1858
1859 void ast_verb_update(void)
1860 {
1861         struct logchannel *log;
1862         struct verb_console *console;
1863         int verb_level;
1864
1865         ast_mutex_lock(&verb_update_lock);
1866
1867         AST_RWLIST_RDLOCK(&verb_consoles);
1868
1869         /* Default to the root console verbosity. */
1870         verb_level = option_verbose;
1871
1872         /* Determine max remote console level. */
1873         AST_LIST_TRAVERSE(&verb_consoles, console, node) {
1874                 if (verb_level < *console->level) {
1875                         verb_level = *console->level;
1876                 }
1877         }
1878         AST_RWLIST_UNLOCK(&verb_consoles);
1879
1880         /* Determine max logger channel level. */
1881         AST_RWLIST_RDLOCK(&logchannels);
1882         AST_RWLIST_TRAVERSE(&logchannels, log, list) {
1883                 if (verb_level < log->verbosity) {
1884                         verb_level = log->verbosity;
1885                 }
1886         }
1887         AST_RWLIST_UNLOCK(&logchannels);
1888
1889         ast_verb_sys_level = verb_level;
1890
1891         ast_mutex_unlock(&verb_update_lock);
1892 }
1893
1894 /*!
1895  * \internal
1896  * \brief Unregister a console verbose level.
1897  *
1898  * \param console Which console to unregister.
1899  *
1900  * \return Nothing
1901  */
1902 static void verb_console_unregister(struct verb_console *console)
1903 {
1904         AST_RWLIST_WRLOCK(&verb_consoles);
1905         console = AST_RWLIST_REMOVE(&verb_consoles, console, node);
1906         AST_RWLIST_UNLOCK(&verb_consoles);
1907         if (console) {
1908                 ast_verb_update();
1909         }
1910 }
1911
1912 static void verb_console_free(void *v_console)
1913 {
1914         struct verb_console *console = v_console;
1915
1916         verb_console_unregister(console);
1917         ast_free(console);
1918 }
1919
1920 /*! Thread specific console verbosity level node. */
1921 AST_THREADSTORAGE_CUSTOM(my_verb_console, NULL, verb_console_free);
1922
1923 void ast_verb_console_register(int *level)
1924 {
1925         struct verb_console *console;
1926
1927         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
1928         if (!console || !level) {
1929                 return;
1930         }
1931         console->level = level;
1932
1933         AST_RWLIST_WRLOCK(&verb_consoles);
1934         AST_RWLIST_INSERT_HEAD(&verb_consoles, console, node);
1935         AST_RWLIST_UNLOCK(&verb_consoles);
1936         ast_verb_update();
1937 }
1938
1939 void ast_verb_console_unregister(void)
1940 {
1941         struct verb_console *console;
1942
1943         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
1944         if (!console) {
1945                 return;
1946         }
1947         verb_console_unregister(console);
1948 }
1949
1950 int ast_verb_console_get(void)
1951 {
1952         struct verb_console *console;
1953         int verb_level;
1954
1955         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
1956         AST_RWLIST_RDLOCK(&verb_consoles);
1957         if (!console) {
1958                 verb_level = 0;
1959         } else if (console->level) {
1960                 verb_level = *console->level;
1961         } else {
1962                 verb_level = option_verbose;
1963         }
1964         AST_RWLIST_UNLOCK(&verb_consoles);
1965         return verb_level;
1966 }
1967
1968 void ast_verb_console_set(int verb_level)
1969 {
1970         struct verb_console *console;
1971
1972         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
1973         if (!console) {
1974                 return;
1975         }
1976
1977         AST_RWLIST_WRLOCK(&verb_consoles);
1978         if (console->level) {
1979                 *console->level = verb_level;
1980         } else {
1981                 option_verbose = verb_level;
1982         }
1983         AST_RWLIST_UNLOCK(&verb_consoles);
1984         ast_verb_update();
1985 }
1986
1987 int ast_register_verbose(void (*v)(const char *string))
1988 {
1989         struct verb *verb;
1990
1991         if (!(verb = ast_malloc(sizeof(*verb))))
1992                 return -1;
1993
1994         verb->verboser = v;
1995
1996         AST_RWLIST_WRLOCK(&verbosers);
1997         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1998         AST_RWLIST_UNLOCK(&verbosers);
1999
2000         return 0;
2001 }
2002
2003 int ast_unregister_verbose(void (*v)(const char *string))
2004 {
2005         struct verb *cur;
2006
2007         AST_RWLIST_WRLOCK(&verbosers);
2008         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
2009                 if (cur->verboser == v) {
2010                         AST_RWLIST_REMOVE_CURRENT(list);
2011                         ast_free(cur);
2012                         break;
2013                 }
2014         }
2015         AST_RWLIST_TRAVERSE_SAFE_END;
2016         AST_RWLIST_UNLOCK(&verbosers);
2017
2018         return cur ? 0 : -1;
2019 }
2020
2021 static void update_logchannels(void)
2022 {
2023         struct logchannel *cur;
2024
2025         AST_RWLIST_WRLOCK(&logchannels);
2026
2027         global_logmask = 0;
2028
2029         AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
2030                 make_components(cur);
2031                 global_logmask |= cur->logmask;
2032         }
2033
2034         AST_RWLIST_UNLOCK(&logchannels);
2035 }
2036
2037 int ast_logger_register_level(const char *name)
2038 {
2039         unsigned int level;
2040         unsigned int available = 0;
2041
2042         AST_RWLIST_WRLOCK(&logchannels);
2043
2044         for (level = 0; level < ARRAY_LEN(levels); level++) {
2045                 if ((level >= 16) && !available && !levels[level]) {
2046                         available = level;
2047                         continue;
2048                 }
2049
2050                 if (levels[level] && !strcasecmp(levels[level], name)) {
2051                         ast_log(LOG_WARNING,
2052                                 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
2053                                 name);
2054                         AST_RWLIST_UNLOCK(&logchannels);
2055
2056                         return -1;
2057                 }
2058         }
2059
2060         if (!available) {
2061                 ast_log(LOG_WARNING,
2062                         "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
2063                         name);
2064                 AST_RWLIST_UNLOCK(&logchannels);
2065
2066                 return -1;
2067         }
2068
2069         levels[available] = ast_strdup(name);
2070
2071         AST_RWLIST_UNLOCK(&logchannels);
2072
2073         ast_debug(1, "Registered dynamic logger level '%s' with index %u.\n", name, available);
2074
2075         update_logchannels();
2076
2077         return available;
2078 }
2079
2080 void ast_logger_unregister_level(const char *name)
2081 {
2082         unsigned int found = 0;
2083         unsigned int x;
2084
2085         AST_RWLIST_WRLOCK(&logchannels);
2086
2087         for (x = 16; x < ARRAY_LEN(levels); x++) {
2088                 if (!levels[x]) {
2089                         continue;
2090                 }
2091
2092                 if (strcasecmp(levels[x], name)) {
2093                         continue;
2094                 }
2095
2096                 found = 1;
2097                 break;
2098         }
2099
2100         if (found) {
2101                 /* take this level out of the global_logmask, to ensure that no new log messages
2102                  * will be queued for it
2103                  */
2104
2105                 global_logmask &= ~(1 << x);
2106
2107                 ast_free(levels[x]);
2108                 levels[x] = NULL;
2109                 AST_RWLIST_UNLOCK(&logchannels);
2110
2111                 ast_debug(1, "Unregistered dynamic logger level '%s' with index %u.\n", name, x);
2112
2113                 update_logchannels();
2114         } else {
2115                 AST_RWLIST_UNLOCK(&logchannels);
2116         }
2117 }
2118
2119 const char *ast_logger_get_dateformat(void)
2120 {
2121         return dateformat;
2122 }
2123