Logger/CLI/etc.: Fix some aesthetic issues; reduce chatty verbose messages
[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 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
932 {
933         int x;
934         int state;
935         int level = -1;
936
937         switch (cmd) {
938         case CLI_INIT:
939                 e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
940                 e->usage =
941                         "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
942                         "       Set a specific log level to enabled/disabled for this console.\n";
943                 return NULL;
944         case CLI_GENERATE:
945                 return NULL;
946         }
947
948         if (a->argc < 5)
949                 return CLI_SHOWUSAGE;
950
951         AST_RWLIST_WRLOCK(&logchannels);
952
953         for (x = 0; x < ARRAY_LEN(levels); x++) {
954                 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
955                         level = x;
956                         break;
957                 }
958         }
959
960         AST_RWLIST_UNLOCK(&logchannels);
961
962         state = ast_true(a->argv[4]) ? 1 : 0;
963
964         if (level != -1) {
965                 ast_console_toggle_loglevel(a->fd, level, state);
966                 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
967         } else
968                 return CLI_SHOWUSAGE;
969
970         return CLI_SUCCESS;
971 }
972
973 /*! \brief CLI command to show logging system configuration */
974 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
975 {
976 #define FORMATL "%-35.35s %-8.8s %-9.9s "
977         struct logchannel *chan;
978         switch (cmd) {
979         case CLI_INIT:
980                 e->command = "logger show channels";
981                 e->usage =
982                         "Usage: logger show channels\n"
983                         "       List configured logger channels.\n";
984                 return NULL;
985         case CLI_GENERATE:
986                 return NULL;
987         }
988         ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
989         ast_cli(a->fd, "Configuration\n");
990         ast_cli(a->fd, FORMATL, "-------", "----", "------");
991         ast_cli(a->fd, "-------------\n");
992         AST_RWLIST_RDLOCK(&logchannels);
993         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
994                 unsigned int level;
995
996                 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
997                         chan->disabled ? "Disabled" : "Enabled");
998                 ast_cli(a->fd, " - ");
999                 for (level = 0; level < ARRAY_LEN(levels); level++) {
1000                         if ((chan->logmask & (1 << level)) && levels[level]) {
1001                                 ast_cli(a->fd, "%s ", levels[level]);
1002                         }
1003                 }
1004                 ast_cli(a->fd, "\n");
1005         }
1006         AST_RWLIST_UNLOCK(&logchannels);
1007         ast_cli(a->fd, "\n");
1008
1009         return CLI_SUCCESS;
1010 }
1011
1012 static char *handle_logger_add_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1013 {
1014         struct logchannel *chan;
1015
1016         switch (cmd) {
1017         case CLI_INIT:
1018                 e->command = "logger add channel";
1019                 e->usage =
1020                         "Usage: logger add channel <name> <levels>\n"
1021                         "       Adds a temporary logger channel. This logger channel\n"
1022                         "       will exist until removed or until Asterisk is restarted.\n"
1023                         "       <levels> is a comma-separated list of desired logger\n"
1024                         "       levels such as: verbose,warning,error\n";
1025                 return NULL;
1026         case CLI_GENERATE:
1027                 return NULL;
1028         }
1029
1030         if (a->argc < 5) {
1031                 return CLI_SHOWUSAGE;
1032         }
1033
1034         AST_RWLIST_WRLOCK(&logchannels);
1035         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1036                 if (!strcmp(chan->filename, a->argv[3])) {
1037                         break;
1038                 }
1039         }
1040
1041         if (chan) {
1042                 AST_RWLIST_UNLOCK(&logchannels);
1043                 ast_cli(a->fd, "Logger channel '%s' already exists\n", a->argv[3]);
1044                 return CLI_SUCCESS;
1045         }
1046
1047         chan = make_logchannel(a->argv[3], a->argv[4], 0, 1);
1048         if (chan) {
1049                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
1050                 global_logmask |= chan->logmask;
1051                 AST_RWLIST_UNLOCK(&logchannels);
1052                 return CLI_SUCCESS;
1053         }
1054
1055         AST_RWLIST_UNLOCK(&logchannels);
1056         ast_cli(a->fd, "ERROR: Unable to create log channel '%s'\n", a->argv[3]);
1057
1058         return CLI_FAILURE;
1059 }
1060
1061 static char *handle_logger_remove_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1062 {
1063         struct logchannel *chan;
1064         int gen_count = 0;
1065         char *gen_ret = NULL;
1066
1067         switch (cmd) {
1068         case CLI_INIT:
1069                 e->command = "logger remove channel";
1070                 e->usage =
1071                         "Usage: logger remove channel <name>\n"
1072                         "       Removes a temporary logger channel.\n";
1073                 return NULL;
1074         case CLI_GENERATE:
1075                 if (a->argc > 4 || (a->argc == 4 && a->pos > 3)) {
1076                         return NULL;
1077                 }
1078                 AST_RWLIST_RDLOCK(&logchannels);
1079                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1080                         if (chan->dynamic && (ast_strlen_zero(a->argv[3])
1081                                 || !strncmp(a->argv[3], chan->filename, strlen(a->argv[3])))) {
1082                                 if (gen_count == a->n) {
1083                                         gen_ret = ast_strdup(chan->filename);
1084                                         break;
1085                                 }
1086                                 gen_count++;
1087                         }
1088                 }
1089                 AST_RWLIST_UNLOCK(&logchannels);
1090                 return gen_ret;
1091         }
1092
1093         if (a->argc < 4) {
1094                 return CLI_SHOWUSAGE;
1095         }
1096
1097         AST_RWLIST_WRLOCK(&logchannels);
1098         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&logchannels, chan, list) {
1099                 if (chan->dynamic && !strcmp(chan->filename, a->argv[3])) {
1100                         AST_RWLIST_REMOVE_CURRENT(list);
1101                         break;
1102                 }
1103         }
1104         AST_RWLIST_TRAVERSE_SAFE_END;
1105         AST_RWLIST_UNLOCK(&logchannels);
1106
1107         if (!chan) {
1108                 ast_cli(a->fd, "Unable to find dynamic logger channel '%s'\n", a->argv[3]);
1109                 return CLI_SUCCESS;
1110         }
1111
1112         ast_cli(a->fd, "Removed dynamic logger channel '%s'\n", chan->filename);
1113         if (chan->fileptr) {
1114                 fclose(chan->fileptr);
1115                 chan->fileptr = NULL;
1116         }
1117         ast_free(chan);
1118         chan = NULL;
1119
1120         return CLI_SUCCESS;
1121 }
1122
1123 struct verb {
1124         void (*verboser)(const char *string);
1125         AST_LIST_ENTRY(verb) list;
1126 };
1127
1128 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
1129
1130 static struct ast_cli_entry cli_logger[] = {
1131         AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
1132         AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
1133         AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
1134         AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console"),
1135         AST_CLI_DEFINE(handle_logger_add_channel, "Adds a new logging channel"),
1136         AST_CLI_DEFINE(handle_logger_remove_channel, "Removes a logging channel"),
1137 };
1138
1139 static void _handle_SIGXFSZ(int sig)
1140 {
1141         /* Indicate need to reload */
1142         filesize_reload_needed = 1;
1143 }
1144
1145 static struct sigaction handle_SIGXFSZ = {
1146         .sa_handler = _handle_SIGXFSZ,
1147         .sa_flags = SA_RESTART,
1148 };
1149
1150 static void ast_log_vsyslog(struct logmsg *msg)
1151 {
1152         char buf[BUFSIZ];
1153         int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
1154         char call_identifier_str[13];
1155
1156         if (msg->callid) {
1157                 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", (unsigned)msg->callid->call_identifier);
1158         } else {
1159                 call_identifier_str[0] = '\0';
1160         }
1161
1162         if (syslog_level < 0) {
1163                 /* we are locked here, so cannot ast_log() */
1164                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
1165                 return;
1166         }
1167
1168         snprintf(buf, sizeof(buf), "%s[%d]%s: %s:%d in %s: %s",
1169                  levels[msg->level], msg->lwp, call_identifier_str, msg->file, msg->line, msg->function, msg->message);
1170
1171         term_strip(buf, buf, strlen(buf) + 1);
1172         syslog(syslog_level, "%s", buf);
1173 }
1174
1175 static char *logger_strip_verbose_magic(const char *message, int level)
1176 {
1177         char *p;
1178         char *stripped_message = ast_strdup(message);
1179         char magic = -(level + 1);
1180
1181         if (!stripped_message) {
1182                 return NULL;
1183         }
1184
1185         do {
1186                 p = strchr(stripped_message, (char)magic);
1187                 if (p) {
1188                         *p++ = ' ';
1189                 }
1190         } while (p && *p);
1191
1192         return stripped_message;
1193 }
1194
1195 /*! \brief Print a normal log message to the channels */
1196 static void logger_print_normal(struct logmsg *logmsg)
1197 {
1198         struct logchannel *chan = NULL;
1199         char buf[BUFSIZ];
1200         struct verb *v = NULL;
1201         char *tmpmsg;
1202         int level = 0;
1203
1204         if (logmsg->level == __LOG_VERBOSE) {
1205
1206                 /* Iterate through the list of verbosers and pass them the log message string */
1207                 AST_RWLIST_RDLOCK(&verbosers);
1208                 AST_RWLIST_TRAVERSE(&verbosers, v, list)
1209                         v->verboser(logmsg->message);
1210                 AST_RWLIST_UNLOCK(&verbosers);
1211
1212                 level = VERBOSE_MAGIC2LEVEL(logmsg->message);
1213
1214                 tmpmsg = logger_strip_verbose_magic(logmsg->message, level);
1215                 if (tmpmsg) {
1216                         ast_string_field_set(logmsg, message, tmpmsg);
1217                         ast_free(tmpmsg);
1218                 }
1219         }
1220
1221         AST_RWLIST_RDLOCK(&logchannels);
1222
1223         if (!AST_RWLIST_EMPTY(&logchannels)) {
1224                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1225                         char call_identifier_str[13];
1226
1227                         if (logmsg->callid) {
1228                                 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", (unsigned)logmsg->callid->call_identifier);
1229                         } else {
1230                                 call_identifier_str[0] = '\0';
1231                         }
1232
1233
1234                         /* If the channel is disabled, then move on to the next one */
1235                         if (chan->disabled) {
1236                                 continue;
1237                         }
1238                         if (logmsg->level == __LOG_VERBOSE
1239                                 && (((chan->verbosity < 0) ? option_verbose : chan->verbosity)) < level) {
1240                                 continue;
1241                         }
1242
1243                         /* Check syslog channels */
1244                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
1245                                 ast_log_vsyslog(logmsg);
1246                         /* Console channels */
1247                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
1248                                 char linestr[128];
1249
1250                                 /* If the level is verbose, then skip it */
1251                                 if (logmsg->level == __LOG_VERBOSE)
1252                                         continue;
1253
1254                                 /* Turn the numerical line number into a string */
1255                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
1256                                 /* Build string to print out */
1257                                 snprintf(buf, sizeof(buf), "[%s] " COLORIZE_FMT "[%d]%s: " COLORIZE_FMT ":" COLORIZE_FMT " " COLORIZE_FMT ": %s",
1258                                          logmsg->date,
1259                                          COLORIZE(colors[logmsg->level], 0, logmsg->level_name),
1260                                          logmsg->lwp,
1261                                          call_identifier_str,
1262                                          COLORIZE(COLOR_BRWHITE, 0, logmsg->file),
1263                                          COLORIZE(COLOR_BRWHITE, 0, linestr),
1264                                          COLORIZE(COLOR_BRWHITE, 0, logmsg->function),
1265                                          logmsg->message);
1266                                 /* Print out */
1267                                 ast_console_puts_mutable(buf, logmsg->level);
1268                         /* File channels */
1269                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
1270                                 int res = 0;
1271
1272                                 /* If no file pointer exists, skip it */
1273                                 if (!chan->fileptr) {
1274                                         continue;
1275                                 }
1276
1277                                 /* Print out to the file */
1278                                 res = fprintf(chan->fileptr, "[%s] %s[%d]%s %s: %s",
1279                                               logmsg->date, logmsg->level_name, logmsg->lwp, call_identifier_str,
1280                                               logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
1281                                 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
1282                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
1283                                         if (errno == ENOMEM || errno == ENOSPC)
1284                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
1285                                         else
1286                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
1287                                         /*** DOCUMENTATION
1288                                                 <managerEventInstance>
1289                                                         <synopsis>Raised when a logging channel is disabled.</synopsis>
1290                                                         <syntax>
1291                                                                 <parameter name="Channel">
1292                                                                         <para>The name of the logging channel.</para>
1293                                                                 </parameter>
1294                                                         </syntax>
1295                                                 </managerEventInstance>
1296                                         ***/
1297                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
1298                                         chan->disabled = 1;
1299                                 } else if (res > 0) {
1300                                         fflush(chan->fileptr);
1301                                 }
1302                         }
1303                 }
1304         } else if (logmsg->level != __LOG_VERBOSE) {
1305                 fputs(logmsg->message, stdout);
1306         }
1307
1308         AST_RWLIST_UNLOCK(&logchannels);
1309
1310         /* If we need to reload because of the file size, then do so */
1311         if (filesize_reload_needed) {
1312                 reload_logger(-1, NULL);
1313                 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
1314         }
1315
1316         return;
1317 }
1318
1319 /*! \brief Actual logging thread */
1320 static void *logger_thread(void *data)
1321 {
1322         struct logmsg *next = NULL, *msg = NULL;
1323
1324         for (;;) {
1325                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
1326                 AST_LIST_LOCK(&logmsgs);
1327                 if (AST_LIST_EMPTY(&logmsgs)) {
1328                         if (close_logger_thread) {
1329                                 AST_LIST_UNLOCK(&logmsgs);
1330                                 break;
1331                         } else {
1332                                 ast_cond_wait(&logcond, &logmsgs.lock);
1333                         }
1334                 }
1335                 next = AST_LIST_FIRST(&logmsgs);
1336                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
1337                 AST_LIST_UNLOCK(&logmsgs);
1338
1339                 /* Otherwise go through and process each message in the order added */
1340                 while ((msg = next)) {
1341                         /* Get the next entry now so that we can free our current structure later */
1342                         next = AST_LIST_NEXT(msg, list);
1343
1344                         /* Depending on the type, send it to the proper function */
1345                         logger_print_normal(msg);
1346
1347                         /* Free the data since we are done */
1348                         logmsg_free(msg);
1349                 }
1350         }
1351
1352         return NULL;
1353 }
1354
1355 /*!
1356  * \internal
1357  * \brief Initialize the logger queue.
1358  *
1359  * \note Assumes logchannels is write locked on entry.
1360  *
1361  * \return Nothing
1362  */
1363 static void logger_queue_init(void)
1364 {
1365         ast_unload_realtime("queue_log");
1366         if (logfiles.queue_log) {
1367                 char qfname[PATH_MAX];
1368
1369                 if (logger_queue_rt_start()) {
1370                         return;
1371                 }
1372
1373                 /* Open the log file. */
1374                 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
1375                         queue_log_name);
1376                 if (qlog) {
1377                         /* Just in case it was already open. */
1378                         fclose(qlog);
1379                 }
1380                 qlog = fopen(qfname, "a");
1381                 if (!qlog) {
1382                         ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
1383                 }
1384         }
1385 }
1386
1387 int init_logger(void)
1388 {
1389         /* auto rotate if sig SIGXFSZ comes a-knockin */
1390         sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
1391
1392         /* Re-initialize the logmsgs mutex.  The recursive mutex can be accessed prior
1393          * to Asterisk being forked into the background, which can cause the thread
1394          * ID tracked by the underlying pthread mutex to be different than the ID of
1395          * the thread that unlocks the mutex.  Since init_logger is called after the
1396          * fork, it is safe to initialize the mutex here for future accesses.
1397          */
1398         ast_mutex_destroy(&logmsgs.lock);
1399         ast_mutex_init(&logmsgs.lock);
1400         ast_cond_init(&logcond, NULL);
1401
1402         /* start logger thread */
1403         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1404                 ast_cond_destroy(&logcond);
1405                 return -1;
1406         }
1407
1408         /* register the logger cli commands */
1409         ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1410
1411         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1412
1413         /* create log channels */
1414         init_logger_chain(0 /* locked */, NULL);
1415         ast_verb_update();
1416         logger_initialized = 1;
1417
1418         return 0;
1419 }
1420
1421 void close_logger(void)
1422 {
1423         struct logchannel *f = NULL;
1424         struct verb *cur = NULL;
1425
1426         ast_cli_unregister_multiple(cli_logger, ARRAY_LEN(cli_logger));
1427
1428         logger_initialized = 0;
1429
1430         /* Stop logger thread */
1431         AST_LIST_LOCK(&logmsgs);
1432         close_logger_thread = 1;
1433         ast_cond_signal(&logcond);
1434         AST_LIST_UNLOCK(&logmsgs);
1435
1436         if (logthread != AST_PTHREADT_NULL)
1437                 pthread_join(logthread, NULL);
1438
1439         AST_RWLIST_WRLOCK(&verbosers);
1440         while ((cur = AST_LIST_REMOVE_HEAD(&verbosers, list))) {
1441                 ast_free(cur);
1442         }
1443         AST_RWLIST_UNLOCK(&verbosers);
1444
1445         AST_RWLIST_WRLOCK(&logchannels);
1446
1447         if (qlog) {
1448                 fclose(qlog);
1449                 qlog = NULL;
1450         }
1451
1452         while ((f = AST_LIST_REMOVE_HEAD(&logchannels, list))) {
1453                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1454                         fclose(f->fileptr);
1455                         f->fileptr = NULL;
1456                 }
1457                 ast_free(f);
1458         }
1459
1460         closelog(); /* syslog */
1461
1462         AST_RWLIST_UNLOCK(&logchannels);
1463 }
1464
1465 void ast_callid_strnprint(char *buffer, size_t buffer_size, struct ast_callid *callid)
1466 {
1467         snprintf(buffer, buffer_size, "[C-%08x]", (unsigned)callid->call_identifier);
1468 }
1469
1470 struct ast_callid *ast_create_callid(void)
1471 {
1472         struct ast_callid *call;
1473
1474         call = ao2_alloc_options(sizeof(*call), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
1475         if (!call) {
1476                 ast_log(LOG_ERROR, "Could not allocate callid struct.\n");
1477                 return NULL;
1478         }
1479
1480         call->call_identifier = ast_atomic_fetchadd_int(&next_unique_callid, +1);
1481 #ifdef TEST_FRAMEWORK
1482         ast_debug(3, "CALL_ID [C-%08x] created by thread.\n", call->call_identifier);
1483 #endif
1484         return call;
1485 }
1486
1487 struct ast_callid *ast_read_threadstorage_callid(void)
1488 {
1489         struct ast_callid **callid;
1490
1491         callid = ast_threadstorage_get(&unique_callid, sizeof(*callid));
1492         if (callid && *callid) {
1493                 ast_callid_ref(*callid);
1494                 return *callid;
1495         }
1496
1497         return NULL;
1498
1499 }
1500
1501 int ast_callid_threadassoc_change(struct ast_callid *callid)
1502 {
1503         struct ast_callid **id = ast_threadstorage_get(&unique_callid, sizeof(*id));
1504
1505         if (!id) {
1506                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1507                 return -1;
1508         }
1509
1510         if (*id && (*id != callid)) {
1511 #ifdef TEST_FRAMEWORK
1512                 ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", (*id)->call_identifier);
1513 #endif
1514                 *id = ast_callid_unref(*id);
1515                 *id = NULL;
1516         }
1517
1518         if (!(*id) && callid) {
1519                 /* callid will be unreffed at thread destruction */
1520                 ast_callid_ref(callid);
1521                 *id = callid;
1522 #ifdef TEST_FRAMEWORK
1523                 ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", callid->call_identifier);
1524 #endif
1525         }
1526
1527         return 0;
1528 }
1529
1530 int ast_callid_threadassoc_add(struct ast_callid *callid)
1531 {
1532         struct ast_callid **pointing;
1533
1534         pointing = ast_threadstorage_get(&unique_callid, sizeof(*pointing));
1535         if (!(pointing)) {
1536                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1537                 return -1;
1538         }
1539
1540         if (!(*pointing)) {
1541                 /* callid will be unreffed at thread destruction */
1542                 ast_callid_ref(callid);
1543                 *pointing = callid;
1544 #ifdef TEST_FRAMEWORK
1545                 ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", callid->call_identifier);
1546 #endif
1547         } else {
1548                 ast_log(LOG_WARNING, "Attempted to ast_callid_threadassoc_add on thread already associated with a callid.\n");
1549                 return 1;
1550         }
1551
1552         return 0;
1553 }
1554
1555 int ast_callid_threadassoc_remove(void)
1556 {
1557         struct ast_callid **pointing;
1558
1559         pointing = ast_threadstorage_get(&unique_callid, sizeof(*pointing));
1560         if (!(pointing)) {
1561                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1562                 return -1;
1563         }
1564
1565         if (!(*pointing)) {
1566                 ast_log(LOG_ERROR, "Tried to clean callid thread storage with no callid in thread storage.\n");
1567                 return -1;
1568         } else {
1569 #ifdef TEST_FRAMEWORK
1570                 ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", (*pointing)->call_identifier);
1571 #endif
1572                 *pointing = ast_callid_unref(*pointing);
1573                 return 0;
1574         }
1575 }
1576
1577 int ast_callid_threadstorage_auto(struct ast_callid **callid)
1578 {
1579         struct ast_callid *tmp;
1580
1581         /* Start by trying to see if a callid is available from thread storage */
1582         tmp = ast_read_threadstorage_callid();
1583         if (tmp) {
1584                 *callid = tmp;
1585                 return 0;
1586         }
1587
1588         /* If that failed, try to create a new one and bind it. */
1589         tmp = ast_create_callid();
1590         if (tmp) {
1591                 ast_callid_threadassoc_add(tmp);
1592                 *callid = tmp;
1593                 return 1;
1594         }
1595
1596         /* If neither worked, then something must have gone wrong. */
1597         return -1;
1598 }
1599
1600 void ast_callid_threadstorage_auto_clean(struct ast_callid *callid, int callid_created)
1601 {
1602         if (callid) {
1603                 /* If the callid was created rather than simply grabbed from the thread storage, we need to unbind here. */
1604                 if (callid_created == 1) {
1605                         ast_callid_threadassoc_remove();
1606                 }
1607                 callid = ast_callid_unref(callid);
1608         }
1609 }
1610
1611 /*!
1612  * \internal
1613  * \brief thread storage cleanup function for unique_callid
1614  */
1615 static void unique_callid_cleanup(void *data)
1616 {
1617         struct ast_callid **callid = data;
1618
1619         if (*callid) {
1620                 ast_callid_unref(*callid);
1621         }
1622
1623         ast_free(data);
1624 }
1625
1626 /*!
1627  * \brief send log messages to syslog and/or the console
1628  */
1629 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)
1630 {
1631         struct logmsg *logmsg = NULL;
1632         struct ast_str *buf = NULL;
1633         struct ast_tm tm;
1634         struct timeval now = ast_tvnow();
1635         int res = 0;
1636         char datestring[256];
1637
1638         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1639                 return;
1640
1641         if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
1642                 /*
1643                  * we don't have the logger chain configured yet,
1644                  * so just log to stdout
1645                  */
1646                 int result;
1647                 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1648                 if (result != AST_DYNSTR_BUILD_FAILED) {
1649                         term_filter_escapes(ast_str_buffer(buf));
1650                         fputs(ast_str_buffer(buf), stdout);
1651                 }
1652                 return;
1653         }
1654
1655         /* Ignore anything that never gets logged anywhere */
1656         if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
1657                 return;
1658
1659         /* Build string */
1660         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1661
1662         /* If the build failed, then abort and free this structure */
1663         if (res == AST_DYNSTR_BUILD_FAILED)
1664                 return;
1665
1666         /* Create a new logging message */
1667         if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1668                 return;
1669
1670         /* Copy string over */
1671         ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1672
1673         /* Set type */
1674         if (level == __LOG_VERBOSE) {
1675                 logmsg->type = LOGMSG_VERBOSE;
1676         } else {
1677                 logmsg->type = LOGMSG_NORMAL;
1678         }
1679
1680         if (display_callids && callid) {
1681                 logmsg->callid = ast_callid_ref(callid);
1682                 /* callid will be unreffed at logmsg destruction */
1683         }
1684
1685         /* Create our date/time */
1686         ast_localtime(&now, &tm, NULL);
1687         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1688         ast_string_field_set(logmsg, date, datestring);
1689
1690         /* Copy over data */
1691         logmsg->level = level;
1692         logmsg->line = line;
1693         ast_string_field_set(logmsg, level_name, levels[level]);
1694         ast_string_field_set(logmsg, file, file);
1695         ast_string_field_set(logmsg, function, function);
1696         logmsg->lwp = ast_get_tid();
1697
1698         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1699         if (logthread != AST_PTHREADT_NULL) {
1700                 AST_LIST_LOCK(&logmsgs);
1701                 if (close_logger_thread) {
1702                         /* Logger is either closing or closed.  We cannot log this message. */
1703                         logmsg_free(logmsg);
1704                 } else {
1705                         AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1706                         ast_cond_signal(&logcond);
1707                 }
1708                 AST_LIST_UNLOCK(&logmsgs);
1709         } else {
1710                 logger_print_normal(logmsg);
1711                 logmsg_free(logmsg);
1712         }
1713 }
1714
1715 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1716 {
1717         struct ast_callid *callid;
1718         va_list ap;
1719
1720         callid = ast_read_threadstorage_callid();
1721
1722         va_start(ap, fmt);
1723         if (level == __LOG_VERBOSE) {
1724                 __ast_verbose_ap(file, line, function, 0, callid, fmt, ap);
1725         } else {
1726                 ast_log_full(level, file, line, function, callid, fmt, ap);
1727         }
1728         va_end(ap);
1729
1730         if (callid) {
1731                 ast_callid_unref(callid);
1732         }
1733 }
1734
1735 void ast_log_callid(int level, const char *file, int line, const char *function, struct ast_callid *callid, const char *fmt, ...)
1736 {
1737         va_list ap;
1738         va_start(ap, fmt);
1739         ast_log_full(level, file, line, function, callid, fmt, ap);
1740         va_end(ap);
1741 }
1742
1743
1744 void ast_log_backtrace(void)
1745 {
1746 #ifdef HAVE_BKTR
1747         struct ast_bt *bt;
1748         int i = 0;
1749         char **strings;
1750
1751         if (!(bt = ast_bt_create())) {
1752                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1753                 return;
1754         }
1755
1756         if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
1757                 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1758                 for (i = 3; i < bt->num_frames - 2; i++) {
1759                         ast_debug(1, "#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
1760                 }
1761
1762                 ast_std_free(strings);
1763         } else {
1764                 ast_debug(1, "Could not allocate memory for backtrace\n");
1765         }
1766         ast_bt_destroy(bt);
1767 #else
1768         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1769 #endif /* defined(HAVE_BKTR) */
1770 }
1771
1772 void __ast_verbose_ap(const char *file, int line, const char *func, int level, struct ast_callid *callid, const char *fmt, va_list ap)
1773 {
1774         const char *p;
1775         struct ast_str *prefixed, *buf;
1776         int res = 0;
1777         signed char magic = level > 9 ? -10 : -level - 1; /* 0 => -1, 1 => -2, etc.  Can't pass NUL, as it is EOS-delimiter */
1778
1779         /* For compatibility with modules still calling ast_verbose() directly instead of using ast_verb() */
1780         if (level < 0) {
1781                 if (!strncmp(fmt, VERBOSE_PREFIX_4, strlen(VERBOSE_PREFIX_4))) {
1782                         magic = -5;
1783                 } else if (!strncmp(fmt, VERBOSE_PREFIX_3, strlen(VERBOSE_PREFIX_3))) {
1784                         magic = -4;
1785                 } else if (!strncmp(fmt, VERBOSE_PREFIX_2, strlen(VERBOSE_PREFIX_2))) {
1786                         magic = -3;
1787                 } else if (!strncmp(fmt, VERBOSE_PREFIX_1, strlen(VERBOSE_PREFIX_1))) {
1788                         magic = -2;
1789                 } else {
1790                         magic = -1;
1791                 }
1792         }
1793
1794         if (!(prefixed = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)) ||
1795             !(buf = ast_str_thread_get(&verbose_build_buf, VERBOSE_BUF_INIT_SIZE))) {
1796                 return;
1797         }
1798
1799         res = ast_str_set_va(&buf, 0, fmt, ap);
1800         /* If the build failed then we can drop this allocated message */
1801         if (res == AST_DYNSTR_BUILD_FAILED) {
1802                 return;
1803         }
1804
1805         ast_str_reset(prefixed);
1806
1807         /* for every newline found in the buffer add verbose prefix data */
1808         fmt = ast_str_buffer(buf);
1809         do {
1810                 if (!(p = strchr(fmt, '\n'))) {
1811                         p = strchr(fmt, '\0') - 1;
1812                 }
1813                 ++p;
1814
1815                 ast_str_append(&prefixed, 0, "%c", (char)magic);
1816                 ast_str_append_substr(&prefixed, 0, fmt, p - fmt);
1817                 fmt = p;
1818         } while (p && *p);
1819
1820         ast_log_callid(__LOG_VERBOSE, file, line, func, callid, "%s", ast_str_buffer(prefixed));
1821 }
1822
1823 void __ast_verbose(const char *file, int line, const char *func, int level, const char *fmt, ...)
1824 {
1825         struct ast_callid *callid;
1826         va_list ap;
1827
1828         callid = ast_read_threadstorage_callid();
1829
1830         va_start(ap, fmt);
1831         __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
1832         va_end(ap);
1833
1834         if (callid) {
1835                 ast_callid_unref(callid);
1836         }
1837 }
1838
1839 void __ast_verbose_callid(const char *file, int line, const char *func, int level, struct ast_callid *callid, const char *fmt, ...)
1840 {
1841         va_list ap;
1842         va_start(ap, fmt);
1843         __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
1844         va_end(ap);
1845 }
1846
1847 /* No new code should use this directly, but we have the ABI for backwards compat */
1848 #undef ast_verbose
1849 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1850 void ast_verbose(const char *fmt, ...)
1851 {
1852         struct ast_callid *callid;
1853         va_list ap;
1854
1855         callid = ast_read_threadstorage_callid();
1856
1857         va_start(ap, fmt);
1858         __ast_verbose_ap("", 0, "", 0, callid, fmt, ap);
1859         va_end(ap);
1860
1861         if (callid) {
1862                 ast_callid_unref(callid);
1863         }
1864 }
1865
1866 /*! Console verbosity level node. */
1867 struct verb_console {
1868         /*! List node link */
1869         AST_LIST_ENTRY(verb_console) node;
1870         /*! Console verbosity level. */
1871         int *level;
1872 };
1873
1874 /*! Registered console verbosity levels */
1875 static AST_RWLIST_HEAD_STATIC(verb_consoles, verb_console);
1876
1877 /*! ast_verb_update() reentrancy protection lock. */
1878 AST_MUTEX_DEFINE_STATIC(verb_update_lock);
1879
1880 void ast_verb_update(void)
1881 {
1882         struct logchannel *log;
1883         struct verb_console *console;
1884         int verb_level;
1885
1886         ast_mutex_lock(&verb_update_lock);
1887
1888         AST_RWLIST_RDLOCK(&verb_consoles);
1889
1890         /* Default to the root console verbosity. */
1891         verb_level = option_verbose;
1892
1893         /* Determine max remote console level. */
1894         AST_LIST_TRAVERSE(&verb_consoles, console, node) {
1895                 if (verb_level < *console->level) {
1896                         verb_level = *console->level;
1897                 }
1898         }
1899         AST_RWLIST_UNLOCK(&verb_consoles);
1900
1901         /* Determine max logger channel level. */
1902         AST_RWLIST_RDLOCK(&logchannels);
1903         AST_RWLIST_TRAVERSE(&logchannels, log, list) {
1904                 if (verb_level < log->verbosity) {
1905                         verb_level = log->verbosity;
1906                 }
1907         }
1908         AST_RWLIST_UNLOCK(&logchannels);
1909
1910         ast_verb_sys_level = verb_level;
1911
1912         ast_mutex_unlock(&verb_update_lock);
1913 }
1914
1915 /*!
1916  * \internal
1917  * \brief Unregister a console verbose level.
1918  *
1919  * \param console Which console to unregister.
1920  *
1921  * \return Nothing
1922  */
1923 static void verb_console_unregister(struct verb_console *console)
1924 {
1925         AST_RWLIST_WRLOCK(&verb_consoles);
1926         console = AST_RWLIST_REMOVE(&verb_consoles, console, node);
1927         AST_RWLIST_UNLOCK(&verb_consoles);
1928         if (console) {
1929                 ast_verb_update();
1930         }
1931 }
1932
1933 static void verb_console_free(void *v_console)
1934 {
1935         struct verb_console *console = v_console;
1936
1937         verb_console_unregister(console);
1938         ast_free(console);
1939 }
1940
1941 /*! Thread specific console verbosity level node. */
1942 AST_THREADSTORAGE_CUSTOM(my_verb_console, NULL, verb_console_free);
1943
1944 void ast_verb_console_register(int *level)
1945 {
1946         struct verb_console *console;
1947
1948         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
1949         if (!console || !level) {
1950                 return;
1951         }
1952         console->level = level;
1953
1954         AST_RWLIST_WRLOCK(&verb_consoles);
1955         AST_RWLIST_INSERT_HEAD(&verb_consoles, console, node);
1956         AST_RWLIST_UNLOCK(&verb_consoles);
1957         ast_verb_update();
1958 }
1959
1960 void ast_verb_console_unregister(void)
1961 {
1962         struct verb_console *console;
1963
1964         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
1965         if (!console) {
1966                 return;
1967         }
1968         verb_console_unregister(console);
1969 }
1970
1971 int ast_verb_console_get(void)
1972 {
1973         struct verb_console *console;
1974         int verb_level;
1975
1976         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
1977         AST_RWLIST_RDLOCK(&verb_consoles);
1978         if (!console) {
1979                 verb_level = 0;
1980         } else if (console->level) {
1981                 verb_level = *console->level;
1982         } else {
1983                 verb_level = option_verbose;
1984         }
1985         AST_RWLIST_UNLOCK(&verb_consoles);
1986         return verb_level;
1987 }
1988
1989 void ast_verb_console_set(int verb_level)
1990 {
1991         struct verb_console *console;
1992
1993         console = ast_threadstorage_get(&my_verb_console, sizeof(*console));
1994         if (!console) {
1995                 return;
1996         }
1997
1998         AST_RWLIST_WRLOCK(&verb_consoles);
1999         if (console->level) {
2000                 *console->level = verb_level;
2001         } else {
2002                 option_verbose = verb_level;
2003         }
2004         AST_RWLIST_UNLOCK(&verb_consoles);
2005         ast_verb_update();
2006 }
2007
2008 int ast_register_verbose(void (*v)(const char *string))
2009 {
2010         struct verb *verb;
2011
2012         if (!(verb = ast_malloc(sizeof(*verb))))
2013                 return -1;
2014
2015         verb->verboser = v;
2016
2017         AST_RWLIST_WRLOCK(&verbosers);
2018         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
2019         AST_RWLIST_UNLOCK(&verbosers);
2020
2021         return 0;
2022 }
2023
2024 int ast_unregister_verbose(void (*v)(const char *string))
2025 {
2026         struct verb *cur;
2027
2028         AST_RWLIST_WRLOCK(&verbosers);
2029         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
2030                 if (cur->verboser == v) {
2031                         AST_RWLIST_REMOVE_CURRENT(list);
2032                         ast_free(cur);
2033                         break;
2034                 }
2035         }
2036         AST_RWLIST_TRAVERSE_SAFE_END;
2037         AST_RWLIST_UNLOCK(&verbosers);
2038
2039         return cur ? 0 : -1;
2040 }
2041
2042 static void update_logchannels(void)
2043 {
2044         struct logchannel *cur;
2045
2046         AST_RWLIST_WRLOCK(&logchannels);
2047
2048         global_logmask = 0;
2049
2050         AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
2051                 make_components(cur);
2052                 global_logmask |= cur->logmask;
2053         }
2054
2055         AST_RWLIST_UNLOCK(&logchannels);
2056 }
2057
2058 int ast_logger_register_level(const char *name)
2059 {
2060         unsigned int level;
2061         unsigned int available = 0;
2062
2063         AST_RWLIST_WRLOCK(&logchannels);
2064
2065         for (level = 0; level < ARRAY_LEN(levels); level++) {
2066                 if ((level >= 16) && !available && !levels[level]) {
2067                         available = level;
2068                         continue;
2069                 }
2070
2071                 if (levels[level] && !strcasecmp(levels[level], name)) {
2072                         ast_log(LOG_WARNING,
2073                                 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
2074                                 name);
2075                         AST_RWLIST_UNLOCK(&logchannels);
2076
2077                         return -1;
2078                 }
2079         }
2080
2081         if (!available) {
2082                 ast_log(LOG_WARNING,
2083                         "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
2084                         name);
2085                 AST_RWLIST_UNLOCK(&logchannels);
2086
2087                 return -1;
2088         }
2089
2090         levels[available] = ast_strdup(name);
2091
2092         AST_RWLIST_UNLOCK(&logchannels);
2093
2094         ast_debug(1, "Registered dynamic logger level '%s' with index %u.\n", name, available);
2095
2096         update_logchannels();
2097
2098         return available;
2099 }
2100
2101 void ast_logger_unregister_level(const char *name)
2102 {
2103         unsigned int found = 0;
2104         unsigned int x;
2105
2106         AST_RWLIST_WRLOCK(&logchannels);
2107
2108         for (x = 16; x < ARRAY_LEN(levels); x++) {
2109                 if (!levels[x]) {
2110                         continue;
2111                 }
2112
2113                 if (strcasecmp(levels[x], name)) {
2114                         continue;
2115                 }
2116
2117                 found = 1;
2118                 break;
2119         }
2120
2121         if (found) {
2122                 /* take this level out of the global_logmask, to ensure that no new log messages
2123                  * will be queued for it
2124                  */
2125
2126                 global_logmask &= ~(1 << x);
2127
2128                 ast_free(levels[x]);
2129                 levels[x] = NULL;
2130                 AST_RWLIST_UNLOCK(&logchannels);
2131
2132                 ast_debug(1, "Unregistered dynamic logger level '%s' with index %u.\n", name, x);
2133
2134                 update_logchannels();
2135         } else {
2136                 AST_RWLIST_UNLOCK(&logchannels);
2137         }
2138 }
2139
2140 const char *ast_logger_get_dateformat(void)
2141 {
2142         return dateformat;
2143 }
2144