CHANNEL(callid): Give dialplan access to the callid.
[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 /* When we include logger.h again it will trample on some stuff in syslog.h, but
44  * nothing we care about in here. */
45 #include <syslog.h>
46 #include <signal.h>
47 #include <time.h>
48 #include <sys/stat.h>
49 #include <fcntl.h>
50
51 #include "asterisk/_private.h"
52 #include "asterisk/paths.h"     /* use ast_config_AST_LOG_DIR */
53 #include "asterisk/logger.h"
54 #include "asterisk/lock.h"
55 #include "asterisk/channel.h"
56 #include "asterisk/config.h"
57 #include "asterisk/term.h"
58 #include "asterisk/cli.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/manager.h"
61 #include "asterisk/astobj2.h"
62 #include "asterisk/threadstorage.h"
63 #include "asterisk/strings.h"
64 #include "asterisk/pbx.h"
65 #include "asterisk/app.h"
66 #include "asterisk/syslog.h"
67 #include "asterisk/buildinfo.h"
68 #include "asterisk/ast_version.h"
69 #include "asterisk/backtrace.h"
70 #include "asterisk/json.h"
71
72 /*** DOCUMENTATION
73  ***/
74
75 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
76
77 static char queue_log_name[256] = QUEUELOG;
78 static char exec_after_rotate[256] = "";
79
80 static int filesize_reload_needed;
81 static unsigned int global_logmask = 0xFFFF;
82 static int queuelog_init;
83 static int logger_initialized;
84 static volatile int next_unique_callid = 1; /* Used to assign unique call_ids to calls */
85 static int display_callids;
86
87 AST_THREADSTORAGE(unique_callid);
88
89 static enum rotatestrategy {
90         NONE = 0,                /* Do not rotate log files at all, instead rely on external mechanisms */
91         SEQUENTIAL = 1 << 0,     /* Original method - create a new file, in order */
92         ROTATE = 1 << 1,         /* Rotate all files, such that the oldest file has the highest suffix */
93         TIMESTAMP = 1 << 2,      /* Append the epoch timestamp onto the end of the archived file */
94 } rotatestrategy = SEQUENTIAL;
95
96 static struct {
97         unsigned int queue_log:1;
98         unsigned int queue_log_to_file:1;
99         unsigned int queue_adaptive_realtime:1;
100         unsigned int queue_log_realtime_use_gmt:1;
101 } logfiles = { 1 };
102
103 static char hostname[MAXHOSTNAMELEN];
104 AST_THREADSTORAGE_RAW(in_safe_log);
105
106 struct logchannel;
107 struct logmsg;
108
109 struct logformatter {
110         /* The name of the log formatter */
111         const char *name;
112         /* Pointer to the function that will format the log */
113         int (* const format_log)(struct logchannel *channel, struct logmsg *msg, char *buf, size_t size);
114 };
115
116 enum logtypes {
117         LOGTYPE_SYSLOG,
118         LOGTYPE_FILE,
119         LOGTYPE_CONSOLE,
120 };
121
122 struct logchannel {
123         /*! How the logs sent to this channel will be formatted */
124         struct logformatter formatter;
125         /*! What to log to this channel */
126         unsigned int logmask;
127         /*! If this channel is disabled or not */
128         int disabled;
129         /*! syslog facility */
130         int facility;
131         /*! Verbosity level. (-1 if use option_verbose for the level.) */
132         int verbosity;
133         /*! Type of log channel */
134         enum logtypes type;
135         /*! logfile logging file pointer */
136         FILE *fileptr;
137         /*! Filename */
138         char filename[PATH_MAX];
139         /*! field for linking to list */
140         AST_LIST_ENTRY(logchannel) list;
141         /*! Line number from configuration file */
142         int lineno;
143         /*! Whether this log channel was created dynamically */
144         int dynamic;
145         /*! Components (levels) from last config load */
146         char components[0];
147 };
148
149 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
150
151 enum logmsgtypes {
152         LOGMSG_NORMAL = 0,
153         LOGMSG_VERBOSE,
154 };
155
156 struct logmsg {
157         enum logmsgtypes type;
158         int level;
159         int sublevel;
160         int line;
161         int lwp;
162         ast_callid callid;
163         AST_DECLARE_STRING_FIELDS(
164                 AST_STRING_FIELD(date);
165                 AST_STRING_FIELD(file);
166                 AST_STRING_FIELD(function);
167                 AST_STRING_FIELD(message);
168                 AST_STRING_FIELD(level_name);
169         );
170         AST_LIST_ENTRY(logmsg) list;
171 };
172
173 static void logmsg_free(struct logmsg *msg)
174 {
175         ast_string_field_free_memory(msg);
176         ast_free(msg);
177 }
178
179 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
180 static pthread_t logthread = AST_PTHREADT_NULL;
181 static ast_cond_t logcond;
182 static int close_logger_thread = 0;
183
184 static FILE *qlog;
185
186 /*! \brief Logging channels used in the Asterisk logging system
187  *
188  * The first 16 levels are reserved for system usage, and the remaining
189  * levels are reserved for usage by dynamic levels registered via
190  * ast_logger_register_level.
191  */
192
193 /* Modifications to this array are protected by the rwlock in the
194  * logchannels list.
195  */
196
197 static char *levels[NUMLOGLEVELS] = {
198         "DEBUG",
199         "---EVENT---",          /* no longer used */
200         "NOTICE",
201         "WARNING",
202         "ERROR",
203         "VERBOSE",
204         "DTMF",
205 };
206
207 /*! \brief Colors used in the console for logging */
208 static const int colors[NUMLOGLEVELS] = {
209         COLOR_BRGREEN,
210         COLOR_BRBLUE,           /* no longer used */
211         COLOR_YELLOW,
212         COLOR_BRRED,
213         COLOR_RED,
214         COLOR_GREEN,
215         COLOR_BRGREEN,
216         0,
217         0,
218         0,
219         0,
220         0,
221         0,
222         0,
223         0,
224         0,
225         COLOR_BRBLUE,
226         COLOR_BRBLUE,
227         COLOR_BRBLUE,
228         COLOR_BRBLUE,
229         COLOR_BRBLUE,
230         COLOR_BRBLUE,
231         COLOR_BRBLUE,
232         COLOR_BRBLUE,
233         COLOR_BRBLUE,
234         COLOR_BRBLUE,
235         COLOR_BRBLUE,
236         COLOR_BRBLUE,
237         COLOR_BRBLUE,
238         COLOR_BRBLUE,
239         COLOR_BRBLUE,
240         COLOR_BRBLUE,
241 };
242
243 AST_THREADSTORAGE(verbose_buf);
244 AST_THREADSTORAGE(verbose_build_buf);
245 #define VERBOSE_BUF_INIT_SIZE   256
246
247 AST_THREADSTORAGE(log_buf);
248 #define LOG_BUF_INIT_SIZE       256
249
250 static int format_log_json(struct logchannel *channel, struct logmsg *msg, char *buf, size_t size)
251 {
252         struct ast_json *json;
253         char *str;
254         char call_identifier_str[13];
255         size_t json_str_len;
256
257         if (msg->callid) {
258                 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", msg->callid);
259         } else {
260                 call_identifier_str[0] = '\0';
261         }
262
263         json = ast_json_pack("{s: s, s: s, "
264                 "s: {s: i, s: s} "
265                 "s: {s: {s: s, s: s, s: i}, "
266                 "s: s, s: s} }",
267                 "hostname", ast_config_AST_SYSTEM_NAME,
268                 "timestamp", msg->date,
269                 "identifiers",
270                 "lwp", msg->lwp,
271                 "callid", S_OR(call_identifier_str, ""),
272                 "logmsg",
273                 "location",
274                 "filename", msg->file,
275                 "function", msg->function,
276                 "line", msg->line,
277                 "level", msg->level_name,
278                 "message", msg->message);
279         if (!json) {
280                 return -1;
281         }
282
283         str = ast_json_dump_string(json);
284         if (!str) {
285                 ast_json_unref(json);
286                 return -1;
287         }
288
289         ast_copy_string(buf, str, size);
290         json_str_len = strlen(str);
291         if (json_str_len > size - 1) {
292                 json_str_len = size - 1;
293         }
294         buf[json_str_len] = '\n';
295         buf[json_str_len + 1] = '\0';
296
297         term_strip(buf, buf, size);
298
299         ast_json_free(str);
300         ast_json_unref(json);
301
302         return 0;
303 }
304
305 static struct logformatter logformatter_json = {
306         .name = "json",
307         .format_log = format_log_json
308 };
309
310 static int logger_add_verbose_magic(struct logmsg *logmsg, char *buf, size_t size)
311 {
312         const char *p;
313         const char *fmt;
314         struct ast_str *prefixed;
315         signed char magic = logmsg->sublevel > 9 ? -10 : -logmsg->sublevel - 1; /* 0 => -1, 1 => -2, etc.  Can't pass NUL, as it is EOS-delimiter */
316
317         /* For compatibility with modules still calling ast_verbose() directly instead of using ast_verb() */
318         if (logmsg->sublevel < 0) {
319                 if (!strncmp(logmsg->message, VERBOSE_PREFIX_4, strlen(VERBOSE_PREFIX_4))) {
320                         magic = -5;
321                 } else if (!strncmp(logmsg->message, VERBOSE_PREFIX_3, strlen(VERBOSE_PREFIX_3))) {
322                         magic = -4;
323                 } else if (!strncmp(logmsg->message, VERBOSE_PREFIX_2, strlen(VERBOSE_PREFIX_2))) {
324                         magic = -3;
325                 } else if (!strncmp(logmsg->message, VERBOSE_PREFIX_1, strlen(VERBOSE_PREFIX_1))) {
326                         magic = -2;
327                 } else {
328                         magic = -1;
329                 }
330         }
331
332         if (!(prefixed = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE))) {
333                 return -1;
334         }
335
336         ast_str_reset(prefixed);
337
338         /* for every newline found in the buffer add verbose prefix data */
339         fmt = logmsg->message;
340         do {
341                 if (!(p = strchr(fmt, '\n'))) {
342                         p = strchr(fmt, '\0') - 1;
343                 }
344                 ++p;
345
346                 ast_str_append(&prefixed, 0, "%c", (char)magic);
347                 ast_str_append_substr(&prefixed, 0, fmt, p - fmt);
348                 fmt = p;
349         } while (p && *p);
350
351         snprintf(buf, size, "%s", ast_str_buffer(prefixed));
352
353         return 0;
354 }
355
356 static int format_log_default(struct logchannel *chan, struct logmsg *msg, char *buf, size_t size)
357 {
358         char call_identifier_str[13];
359
360         if (msg->callid) {
361                 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", msg->callid);
362         } else {
363                 call_identifier_str[0] = '\0';
364         }
365
366         switch (chan->type) {
367         case LOGTYPE_SYSLOG:
368                 snprintf(buf, size, "%s[%d]%s: %s:%d in %s: %s",
369                      levels[msg->level], msg->lwp, call_identifier_str, msg->file,
370                      msg->line, msg->function, msg->message);
371                 term_strip(buf, buf, size);
372                 break;
373         case LOGTYPE_FILE:
374                 snprintf(buf, size, "[%s] %s[%d]%s %s: %s",
375                       msg->date, msg->level_name, msg->lwp, call_identifier_str,
376                       msg->file, msg->message);
377                 term_strip(buf, buf, size);
378                 break;
379         case LOGTYPE_CONSOLE:
380                 {
381                         char linestr[32];
382
383                         /*
384                          * Verbose messages are interpreted by console channels in their own
385                          * special way
386                          */
387                         if (msg->level == __LOG_VERBOSE) {
388                                 return logger_add_verbose_magic(msg, buf, size);
389                         }
390
391                         /* Turn the numeric line number into a string for colorization */
392                         snprintf(linestr, sizeof(linestr), "%d", msg->line);
393
394                         snprintf(buf, size, "[%s] " COLORIZE_FMT "[%d]%s: " COLORIZE_FMT ":" COLORIZE_FMT " " COLORIZE_FMT ": %s",
395                                  msg->date,
396                                  COLORIZE(colors[msg->level], 0, msg->level_name),
397                                  msg->lwp,
398                                  call_identifier_str,
399                                  COLORIZE(COLOR_BRWHITE, 0, msg->file),
400                                  COLORIZE(COLOR_BRWHITE, 0, linestr),
401                                  COLORIZE(COLOR_BRWHITE, 0, msg->function),
402                                  msg->message);
403                 }
404                 break;
405         }
406
407         return 0;
408 }
409
410 static struct logformatter logformatter_default = {
411         .name = "default",
412         .format_log = format_log_default,
413 };
414
415 static void make_components(struct logchannel *chan)
416 {
417         char *w;
418         unsigned int logmask = 0;
419         char *stringp = ast_strdupa(chan->components);
420         unsigned int x;
421         unsigned int verb_level;
422
423         /* Default to using option_verbose as the verbosity level of the logging channel.  */
424         verb_level = -1;
425
426         w = strchr(stringp, '[');
427         if (w) {
428                 char *end = strchr(w + 1, ']');
429                 if (!end) {
430                         fprintf(stderr, "Logger Warning: bad formatter definition for %s in logger.conf\n", chan->filename);
431                 } else {
432                         char *formatter_name = w + 1;
433
434                         *end = '\0';
435                         stringp = end + 1;
436
437                         if (!strcasecmp(formatter_name, "json")) {
438                                 memcpy(&chan->formatter, &logformatter_json, sizeof(chan->formatter));
439                         } else if (!strcasecmp(formatter_name, "default")) {
440                                 memcpy(&chan->formatter, &logformatter_default, sizeof(chan->formatter));
441                         } else {
442                                 fprintf(stderr, "Logger Warning: Unknown formatter definition %s for %s in logger.conf; using 'default'\n",
443                                         formatter_name, chan->filename);
444                                 memcpy(&chan->formatter, &logformatter_default, sizeof(chan->formatter));
445                         }
446                 }
447         }
448
449         if (!chan->formatter.name) {
450                 memcpy(&chan->formatter, &logformatter_default, sizeof(chan->formatter));
451         }
452
453         while ((w = strsep(&stringp, ","))) {
454                 w = ast_strip(w);
455                 if (ast_strlen_zero(w)) {
456                         continue;
457                 }
458                 if (!strcmp(w, "*")) {
459                         logmask = 0xFFFFFFFF;
460                 } else if (!strncasecmp(w, "verbose(", 8)) {
461                         if (levels[__LOG_VERBOSE] && sscanf(w + 8, "%30u)", &verb_level) == 1) {
462                                 logmask |= (1 << __LOG_VERBOSE);
463                         }
464                 } else {
465                         for (x = 0; x < ARRAY_LEN(levels); ++x) {
466                                 if (levels[x] && !strcasecmp(w, levels[x])) {
467                                         logmask |= (1 << x);
468                                         break;
469                                 }
470                         }
471                 }
472         }
473         if (chan->type == LOGTYPE_CONSOLE) {
474                 /*
475                  * Force to use the root console verbose level so if the
476                  * user specified any verbose level then it does not interfere
477                  * with calculating the ast_verb_sys_level value.
478                  */
479                 chan->verbosity = -1;
480                 logmask |= (1 << __LOG_VERBOSE);
481         } else {
482                 chan->verbosity = verb_level;
483         }
484         chan->logmask = logmask;
485 }
486
487 /*!
488  * \brief create the filename that will be used for a logger channel.
489  *
490  * \param channel The name of the logger channel
491  * \param[out] filename The filename for the logger channel
492  * \param size The size of the filename buffer
493  */
494 static void make_filename(const char *channel, char *filename, size_t size)
495 {
496         const char *log_dir_prefix = "";
497         const char *log_dir_separator = "";
498
499         *filename = '\0';
500
501         if (!strcasecmp(channel, "console")) {
502                 return;
503         }
504
505         if (!strncasecmp(channel, "syslog", 6)) {
506                 ast_copy_string(filename, channel, size);
507                 return;
508         }
509
510         /* It's a filename */
511
512         if (channel[0] != '/') {
513                 log_dir_prefix = ast_config_AST_LOG_DIR;
514                 log_dir_separator = "/";
515         }
516
517         if (!ast_strlen_zero(hostname)) {
518                 snprintf(filename, size, "%s%s%s.%s",
519                         log_dir_prefix, log_dir_separator, channel, hostname);
520         } else {
521                 snprintf(filename, size, "%s%s%s",
522                         log_dir_prefix, log_dir_separator, channel);
523         }
524 }
525
526 /*!
527  * \brief Find a particular logger channel by name
528  *
529  * \pre logchannels list is locked
530  *
531  * \param channel The name of the logger channel to find
532  * \retval non-NULL The corresponding logger channel
533  * \retval NULL Unable to find a logger channel with that particular name
534  */
535 static struct logchannel *find_logchannel(const char *channel)
536 {
537         char filename[PATH_MAX];
538         struct logchannel *chan;
539
540         make_filename(channel, filename, sizeof(filename));
541
542         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
543                 if (!strcmp(chan->filename, filename)) {
544                         return chan;
545                 }
546         }
547
548         return NULL;
549 }
550
551 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno, int dynamic)
552 {
553         struct logchannel *chan;
554         char *facility;
555         struct ast_tm tm;
556         struct timeval now = ast_tvnow();
557         char datestring[256];
558
559         if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
560                 return NULL;
561
562         strcpy(chan->components, components);
563         chan->lineno = lineno;
564         chan->dynamic = dynamic;
565
566         make_filename(channel, chan->filename, sizeof(chan->filename));
567
568         if (!strcasecmp(channel, "console")) {
569                 chan->type = LOGTYPE_CONSOLE;
570         } else if (!strncasecmp(channel, "syslog", 6)) {
571                 /*
572                 * syntax is:
573                 *  syslog.facility => level,level,level
574                 */
575                 facility = strchr(channel, '.');
576                 if (!facility++ || !facility) {
577                         facility = "local0";
578                 }
579
580                 chan->facility = ast_syslog_facility(facility);
581
582                 if (chan->facility < 0) {
583                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
584                         ast_free(chan);
585                         return NULL;
586                 }
587
588                 chan->type = LOGTYPE_SYSLOG;
589                 openlog("asterisk", LOG_PID, chan->facility);
590         } else {
591                 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
592                         /* Can't do real logging here since we're called with a lock
593                          * so log to any attached consoles */
594                         ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
595                         ast_console_puts_mutable(chan->filename, __LOG_ERROR);
596                         ast_console_puts_mutable("': ", __LOG_ERROR);
597                         ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
598                         ast_console_puts_mutable("'\n", __LOG_ERROR);
599                         ast_free(chan);
600                         return NULL;
601                 } else {
602                         /* Create our date/time */
603                         ast_localtime(&now, &tm, NULL);
604                         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
605
606                         fprintf(chan->fileptr, "[%s] Asterisk %s built by %s @ %s on a %s running %s on %s\n",
607                                 datestring, ast_get_version(), ast_build_user, ast_build_hostname,
608                                 ast_build_machine, ast_build_os, ast_build_date);
609                         fflush(chan->fileptr);
610                 }
611                 chan->type = LOGTYPE_FILE;
612         }
613         make_components(chan);
614
615         return chan;
616 }
617
618 /* \brief Read config, setup channels.
619  * \param altconf Alternate configuration file to read.
620  *
621  * \pre logchannels list is write locked
622  *
623  * \retval 0 Success
624  * \retval -1 No config found or Failed
625  */
626 static int init_logger_chain(const char *altconf)
627 {
628         struct logchannel *chan;
629         struct ast_config *cfg;
630         struct ast_variable *var;
631         const char *s;
632         struct ast_flags config_flags = { 0 };
633
634         if (!(cfg = ast_config_load2(S_OR(altconf, "logger.conf"), "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
635                 cfg = NULL;
636         }
637
638         /* Set defaults */
639         hostname[0] = '\0';
640         display_callids = 1;
641         memset(&logfiles, 0, sizeof(logfiles));
642         logfiles.queue_log = 1;
643         ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
644         ast_copy_string(queue_log_name, QUEUELOG, sizeof(queue_log_name));
645         exec_after_rotate[0] = '\0';
646         rotatestrategy = SEQUENTIAL;
647
648         /* delete our list of log channels */
649         while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
650                 ast_free(chan);
651         }
652         global_logmask = 0;
653
654         errno = 0;
655         /* close syslog */
656         closelog();
657
658         /* If no config file, we're fine, set default options. */
659         if (!cfg) {
660                 if (!(chan = ast_calloc(1, sizeof(*chan) + 1))) {
661                         fprintf(stderr, "Failed to initialize default logging\n");
662                         return -1;
663                 }
664                 chan->type = LOGTYPE_CONSOLE;
665                 chan->logmask = (1 << __LOG_WARNING) | (1 << __LOG_NOTICE) | (1 << __LOG_ERROR)
666                         | (1 << __LOG_VERBOSE);
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 || option_verbose >= logmsg->sublevel) {
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         return ast_atomic_fetchadd_int(&next_unique_callid, +1);
1766 }
1767
1768 ast_callid ast_read_threadstorage_callid(void)
1769 {
1770         ast_callid *callid;
1771
1772         callid = ast_threadstorage_get(&unique_callid, sizeof(*callid));
1773
1774         return callid ? *callid : 0;
1775 }
1776
1777 int ast_callid_threadassoc_change(ast_callid callid)
1778 {
1779         ast_callid *id = ast_threadstorage_get(&unique_callid, sizeof(*id));
1780
1781         if (!id) {
1782                 return -1;
1783         }
1784
1785         *id = callid;
1786
1787         return 0;
1788 }
1789
1790 int ast_callid_threadassoc_add(ast_callid callid)
1791 {
1792         ast_callid *pointing;
1793
1794         pointing = ast_threadstorage_get(&unique_callid, sizeof(*pointing));
1795         if (!pointing) {
1796                 return -1;
1797         }
1798
1799         if (*pointing) {
1800                 ast_log(LOG_ERROR, "ast_callid_threadassoc_add(C-%08x) on thread "
1801                         "already associated with callid [C-%08x].\n", callid, *pointing);
1802                 return 1;
1803         }
1804
1805         *pointing = callid;
1806         return 0;
1807 }
1808
1809 int ast_callid_threadassoc_remove(void)
1810 {
1811         ast_callid *pointing;
1812
1813         pointing = ast_threadstorage_get(&unique_callid, sizeof(*pointing));
1814         if (!pointing) {
1815                 return -1;
1816         }
1817
1818         if (*pointing) {
1819                 *pointing = 0;
1820                 return 0;
1821         }
1822
1823         return -1;
1824 }
1825
1826 int ast_callid_threadstorage_auto(ast_callid *callid)
1827 {
1828         ast_callid tmp;
1829
1830         /* Start by trying to see if a callid is available from thread storage */
1831         tmp = ast_read_threadstorage_callid();
1832         if (tmp) {
1833                 *callid = tmp;
1834                 return 0;
1835         }
1836
1837         /* If that failed, try to create a new one and bind it. */
1838         *callid = ast_create_callid();
1839         if (*callid) {
1840                 ast_callid_threadassoc_add(*callid);
1841                 return 1;
1842         }
1843
1844         /* If neither worked, then something must have gone wrong. */
1845         return -1;
1846 }
1847
1848 void ast_callid_threadstorage_auto_clean(ast_callid callid, int callid_created)
1849 {
1850         if (callid && callid_created) {
1851                 /* If the callid was created rather than simply grabbed from the thread storage, we need to unbind here. */
1852                 ast_callid_threadassoc_remove();
1853         }
1854 }
1855
1856 /*!
1857  * \brief send log messages to syslog and/or the console
1858  */
1859 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)
1860 {
1861         struct logmsg *logmsg = NULL;
1862         struct ast_str *buf = NULL;
1863         struct ast_tm tm;
1864         struct timeval now = ast_tvnow();
1865         int res = 0;
1866         char datestring[256];
1867
1868         if (level == __LOG_VERBOSE && ast_opt_remote && ast_opt_exec) {
1869                 return;
1870         }
1871
1872         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1873                 return;
1874
1875         if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
1876                 /*
1877                  * we don't have the logger chain configured yet,
1878                  * so just log to stdout
1879                  */
1880                 int result;
1881                 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1882                 if (result != AST_DYNSTR_BUILD_FAILED) {
1883                         term_filter_escapes(ast_str_buffer(buf));
1884                         fputs(ast_str_buffer(buf), stdout);
1885                 }
1886                 return;
1887         }
1888
1889         /* Ignore anything that never gets logged anywhere */
1890         if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
1891                 return;
1892
1893         /* Build string */
1894         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1895
1896         /* If the build failed, then abort and free this structure */
1897         if (res == AST_DYNSTR_BUILD_FAILED)
1898                 return;
1899
1900         /* Create a new logging message */
1901         if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1902                 return;
1903
1904         /* Copy string over */
1905         ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1906
1907         /* Set type */
1908         if (level == __LOG_VERBOSE) {
1909                 logmsg->type = LOGMSG_VERBOSE;
1910         } else {
1911                 logmsg->type = LOGMSG_NORMAL;
1912         }
1913
1914         if (display_callids && callid) {
1915                 logmsg->callid = callid;
1916         }
1917
1918         /* Create our date/time */
1919         ast_localtime(&now, &tm, NULL);
1920         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1921         ast_string_field_set(logmsg, date, datestring);
1922
1923         /* Copy over data */
1924         logmsg->level = level;
1925         logmsg->sublevel = sublevel;
1926         logmsg->line = line;
1927         ast_string_field_set(logmsg, level_name, levels[level]);
1928         ast_string_field_set(logmsg, file, file);
1929         ast_string_field_set(logmsg, function, function);
1930         logmsg->lwp = ast_get_tid();
1931
1932         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1933         if (logthread != AST_PTHREADT_NULL) {
1934                 AST_LIST_LOCK(&logmsgs);
1935                 if (close_logger_thread) {
1936                         /* Logger is either closing or closed.  We cannot log this message. */
1937                         logmsg_free(logmsg);
1938                 } else {
1939                         AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1940                         ast_cond_signal(&logcond);
1941                 }
1942                 AST_LIST_UNLOCK(&logmsgs);
1943         } else {
1944                 logger_print_normal(logmsg);
1945                 logmsg_free(logmsg);
1946         }
1947 }
1948
1949 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1950 {
1951         ast_callid callid;
1952         va_list ap;
1953
1954         callid = ast_read_threadstorage_callid();
1955
1956         va_start(ap, fmt);
1957         if (level == __LOG_VERBOSE) {
1958                 __ast_verbose_ap(file, line, function, 0, callid, fmt, ap);
1959         } else {
1960                 ast_log_full(level, -1, file, line, function, callid, fmt, ap);
1961         }
1962         va_end(ap);
1963 }
1964
1965 void ast_log_safe(int level, const char *file, int line, const char *function, const char *fmt, ...)
1966 {
1967         va_list ap;
1968         void *recursed = ast_threadstorage_get_ptr(&in_safe_log);
1969         ast_callid callid;
1970
1971         if (recursed) {
1972                 return;
1973         }
1974
1975         if (ast_threadstorage_set_ptr(&in_safe_log, (void*)1)) {
1976                 /* We've failed to set the flag that protects against
1977                  * recursion, so bail. */
1978                 return;
1979         }
1980
1981         callid = ast_read_threadstorage_callid();
1982
1983         va_start(ap, fmt);
1984         ast_log_full(level, -1, file, line, function, callid, fmt, ap);
1985         va_end(ap);
1986
1987         /* Clear flag so the next allocation failure can be logged. */
1988         ast_threadstorage_set_ptr(&in_safe_log, NULL);
1989 }
1990
1991 void ast_log_callid(int level, const char *file, int line, const char *function, ast_callid callid, const char *fmt, ...)
1992 {
1993         va_list ap;
1994         va_start(ap, fmt);
1995         ast_log_full(level, -1, file, line, function, callid, fmt, ap);
1996         va_end(ap);
1997 }
1998
1999
2000 void ast_log_backtrace(void)
2001 {
2002 #ifdef HAVE_BKTR
2003         struct ast_bt *bt;
2004         int i = 0;
2005         char **strings;
2006
2007         if (!(bt = ast_bt_create())) {
2008                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
2009                 return;
2010         }
2011
2012         if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
2013                 ast_verbose("Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
2014                 for (i = 3; i < bt->num_frames - 2; i++) {
2015                         ast_verbose("#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
2016                 }
2017
2018                 ast_std_free(strings);
2019         } else {
2020                 ast_verbose("Could not allocate memory for backtrace\n");
2021         }
2022         ast_bt_destroy(bt);
2023 #else
2024         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
2025 #endif /* defined(HAVE_BKTR) */
2026 }
2027
2028 void __ast_verbose_ap(const char *file, int line, const char *func, int level, ast_callid callid, const char *fmt, va_list ap)
2029 {
2030         ast_log_full(__LOG_VERBOSE, level, file, line, func, callid, fmt, ap);
2031 }
2032
2033 void __ast_verbose(const char *file, int line, const char *func, int level, const char *fmt, ...)
2034 {
2035         ast_callid callid;
2036         va_list ap;
2037
2038         callid = ast_read_threadstorage_callid();
2039
2040         va_start(ap, fmt);
2041         __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
2042         va_end(ap);
2043 }
2044
2045 void __ast_verbose_callid(const char *file, int line, const char *func, int level, ast_callid callid, const char *fmt, ...)
2046 {
2047         va_list ap;
2048         va_start(ap, fmt);
2049         __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
2050         va_end(ap);
2051 }
2052
2053 /*! Console verbosity level node. */
2054 struct verb_console {
2055         /*! List node link */
2056         AST_LIST_ENTRY(verb_console) node;
2057         /*! Console verbosity level. */
2058         int *level;
2059 };
2060
2061 /*! Registered console verbosity levels */
2062 static AST_RWLIST_HEAD_STATIC(verb_consoles, verb_console);
2063
2064 /*! ast_verb_update() reentrancy protection lock. */
2065 AST_MUTEX_DEFINE_STATIC(verb_update_lock);
2066
2067 void ast_verb_update(void)
2068 {
2069         struct logchannel *log;
2070         struct verb_console *console;
2071         int verb_level;
2072
2073         ast_mutex_lock(&verb_update_lock);
2074
2075         AST_RWLIST_RDLOCK(&verb_consoles);
2076
2077         /* Default to the root console verbosity. */
2078         verb_level = option_verbose;
2079
2080         /* Determine max remote console level. */
2081         AST_LIST_TRAVERSE(&verb_consoles, console, node) {
2082                 if (verb_level < *console->level) {
2083                         verb_level = *console->level;
2084                 }
2085         }
2086         AST_RWLIST_UNLOCK(&verb_consoles);
2087
2088         /* Determine max logger channel level. */
2089         AST_RWLIST_RDLOCK(&logchannels);
2090         AST_RWLIST_TRAVERSE(&logchannels, log, list) {
2091                 if (verb_level < log->verbosity) {
2092                         verb_level = log->verbosity;
2093                 }
2094         }
2095         AST_RWLIST_UNLOCK(&logchannels);
2096
2097         ast_verb_sys_level = verb_level;
2098
2099         ast_mutex_unlock(&verb_update_lock);
2100 }
2101
2102 /*!
2103  * \internal
2104  * \brief Unregister a console verbose level.
2105  *
2106  * \param console Which console to unregister.
2107  *
2108  * \return Nothing
2109  */
2110 static void verb_console_unregister(struct verb_console *console)
2111 {
2112         AST_RWLIST_WRLOCK(&verb_consoles);
2113         console = AST_RWLIST_REMOVE(&verb_consoles, console, node);
2114         AST_RWLIST_UNLOCK(&verb_consoles);
2115         if (console) {
2116                 ast_verb_update();
2117         }
2118 }
2119
2120 static void verb_console_free(void *v_console)
2121 {
2122         struct verb_console *console = v_console;
2123
2124         verb_console_unregister(console);
2125         ast_free(console);
2126 }
2127
2128 /*! Thread specific console verbosity level node. */
2129 AST_THREADSTORAGE_CUSTOM(my_verb_console, NULL, verb_console_free);
2130
2131 void ast_verb_console_register(int *level)
2132 {
2133         struct verb_console *console;
2134
2135         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
2136         if (!console || !level) {
2137                 return;
2138         }
2139         console->level = level;
2140
2141         AST_RWLIST_WRLOCK(&verb_consoles);
2142         AST_RWLIST_INSERT_HEAD(&verb_consoles, console, node);
2143         AST_RWLIST_UNLOCK(&verb_consoles);
2144         ast_verb_update();
2145 }
2146
2147 void ast_verb_console_unregister(void)
2148 {
2149         struct verb_console *console;
2150
2151         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
2152         if (!console) {
2153                 return;
2154         }
2155         verb_console_unregister(console);
2156 }
2157
2158 int ast_verb_console_get(void)
2159 {
2160         struct verb_console *console;
2161         int verb_level;
2162
2163         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
2164         AST_RWLIST_RDLOCK(&verb_consoles);
2165         if (!console) {
2166                 verb_level = 0;
2167         } else if (console->level) {
2168                 verb_level = *console->level;
2169         } else {
2170                 verb_level = option_verbose;
2171         }
2172         AST_RWLIST_UNLOCK(&verb_consoles);
2173         return verb_level;
2174 }
2175
2176 void ast_verb_console_set(int verb_level)
2177 {
2178         struct verb_console *console;
2179
2180         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
2181         if (!console) {
2182                 return;
2183         }
2184
2185         AST_RWLIST_WRLOCK(&verb_consoles);
2186         if (console->level) {
2187                 *console->level = verb_level;
2188         } else {
2189                 option_verbose = verb_level;
2190         }
2191         AST_RWLIST_UNLOCK(&verb_consoles);
2192         ast_verb_update();
2193 }
2194
2195 static void update_logchannels(void)
2196 {
2197         struct logchannel *cur;
2198
2199         AST_RWLIST_WRLOCK(&logchannels);
2200
2201         global_logmask = 0;
2202
2203         AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
2204                 make_components(cur);
2205                 global_logmask |= cur->logmask;
2206         }
2207
2208         AST_RWLIST_UNLOCK(&logchannels);
2209 }
2210
2211 int ast_logger_register_level(const char *name)
2212 {
2213         unsigned int level;
2214         unsigned int available = 0;
2215
2216         AST_RWLIST_WRLOCK(&logchannels);
2217
2218         for (level = 0; level < ARRAY_LEN(levels); level++) {
2219                 if ((level >= 16) && !available && !levels[level]) {
2220                         available = level;
2221                         continue;
2222                 }
2223
2224                 if (levels[level] && !strcasecmp(levels[level], name)) {
2225                         ast_log(LOG_WARNING,
2226                                 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
2227                                 name);
2228                         AST_RWLIST_UNLOCK(&logchannels);
2229
2230                         return -1;
2231                 }
2232         }
2233
2234         if (!available) {
2235                 ast_log(LOG_WARNING,
2236                         "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
2237                         name);
2238                 AST_RWLIST_UNLOCK(&logchannels);
2239
2240                 return -1;
2241         }
2242
2243         levels[available] = ast_strdup(name);
2244
2245         AST_RWLIST_UNLOCK(&logchannels);
2246
2247         ast_debug(1, "Registered dynamic logger level '%s' with index %u.\n", name, available);
2248
2249         update_logchannels();
2250
2251         return available;
2252 }
2253
2254 void ast_logger_unregister_level(const char *name)
2255 {
2256         unsigned int found = 0;
2257         unsigned int x;
2258
2259         AST_RWLIST_WRLOCK(&logchannels);
2260
2261         for (x = 16; x < ARRAY_LEN(levels); x++) {
2262                 if (!levels[x]) {
2263                         continue;
2264                 }
2265
2266                 if (strcasecmp(levels[x], name)) {
2267                         continue;
2268                 }
2269
2270                 found = 1;
2271                 break;
2272         }
2273
2274         if (found) {
2275                 /* take this level out of the global_logmask, to ensure that no new log messages
2276                  * will be queued for it
2277                  */
2278
2279                 global_logmask &= ~(1 << x);
2280
2281                 ast_free(levels[x]);
2282                 levels[x] = NULL;
2283                 AST_RWLIST_UNLOCK(&logchannels);
2284
2285                 ast_debug(1, "Unregistered dynamic logger level '%s' with index %u.\n", name, x);
2286
2287                 update_logchannels();
2288         } else {
2289                 AST_RWLIST_UNLOCK(&logchannels);
2290         }
2291 }
2292
2293 const char *ast_logger_get_dateformat(void)
2294 {
2295         return dateformat;
2296 }
2297