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