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