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