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