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