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