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