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