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