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