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