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