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