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