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