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