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