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