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