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