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