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