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