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