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