Sat Feb 11 06:33:18 2012

Asterisk developer's documentation


logger.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Asterisk Logger
00022  *
00023  * Logging routines
00024  *
00025  * \author Mark Spencer <markster@digium.com>
00026  */
00027 
00028 #include "asterisk.h"
00029 
00030 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 347997 $")
00031 
00032 /* When we include logger.h again it will trample on some stuff in syslog.h, but
00033  * nothing we care about in here. */
00034 #include <syslog.h>
00035 
00036 #include "asterisk/_private.h"
00037 #include "asterisk/paths.h"   /* use ast_config_AST_LOG_DIR */
00038 #include "asterisk/logger.h"
00039 #include "asterisk/lock.h"
00040 #include "asterisk/channel.h"
00041 #include "asterisk/config.h"
00042 #include "asterisk/term.h"
00043 #include "asterisk/cli.h"
00044 #include "asterisk/utils.h"
00045 #include "asterisk/manager.h"
00046 #include "asterisk/threadstorage.h"
00047 #include "asterisk/strings.h"
00048 #include "asterisk/pbx.h"
00049 #include "asterisk/app.h"
00050 #include "asterisk/syslog.h"
00051 #include "asterisk/buildinfo.h"
00052 #include "asterisk/ast_version.h"
00053 
00054 #include <signal.h>
00055 #include <time.h>
00056 #include <sys/stat.h>
00057 #include <fcntl.h>
00058 #ifdef HAVE_BKTR
00059 #include <execinfo.h>
00060 #define MAX_BACKTRACE_FRAMES 20
00061 #  if defined(HAVE_DLADDR) && defined(HAVE_BFD) && defined(BETTER_BACKTRACES)
00062 #    include <dlfcn.h>
00063 #    include <bfd.h>
00064 #  endif
00065 #endif
00066 
00067 static char dateformat[256] = "%b %e %T";    /* Original Asterisk Format */
00068 
00069 static char queue_log_name[256] = QUEUELOG;
00070 static char exec_after_rotate[256] = "";
00071 
00072 static int filesize_reload_needed;
00073 static unsigned int global_logmask = 0xFFFF;
00074 static int queuelog_init;
00075 static int logger_initialized;
00076 
00077 static enum rotatestrategy {
00078    SEQUENTIAL = 1 << 0,     /* Original method - create a new file, in order */
00079    ROTATE = 1 << 1,         /* Rotate all files, such that the oldest file has the highest suffix */
00080    TIMESTAMP = 1 << 2,      /* Append the epoch timestamp onto the end of the archived file */
00081 } rotatestrategy = SEQUENTIAL;
00082 
00083 static struct {
00084    unsigned int queue_log:1;
00085    unsigned int queue_log_to_file:1;
00086    unsigned int queue_adaptive_realtime:1;
00087 } logfiles = { 1 };
00088 
00089 static char hostname[MAXHOSTNAMELEN];
00090 
00091 enum logtypes {
00092    LOGTYPE_SYSLOG,
00093    LOGTYPE_FILE,
00094    LOGTYPE_CONSOLE,
00095 };
00096 
00097 struct logchannel {
00098    /*! What to log to this channel */
00099    unsigned int logmask;
00100    /*! If this channel is disabled or not */
00101    int disabled;
00102    /*! syslog facility */
00103    int facility;
00104    /*! Type of log channel */
00105    enum logtypes type;
00106    /*! logfile logging file pointer */
00107    FILE *fileptr;
00108    /*! Filename */
00109    char filename[PATH_MAX];
00110    /*! field for linking to list */
00111    AST_LIST_ENTRY(logchannel) list;
00112    /*! Line number from configuration file */
00113    int lineno;
00114    /*! Components (levels) from last config load */
00115    char components[0];
00116 };
00117 
00118 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
00119 
00120 enum logmsgtypes {
00121    LOGMSG_NORMAL = 0,
00122    LOGMSG_VERBOSE,
00123 };
00124 
00125 struct logmsg {
00126    enum logmsgtypes type;
00127    int level;
00128    int line;
00129    int lwp;
00130    AST_DECLARE_STRING_FIELDS(
00131       AST_STRING_FIELD(date);
00132       AST_STRING_FIELD(file);
00133       AST_STRING_FIELD(function);
00134       AST_STRING_FIELD(message);
00135       AST_STRING_FIELD(level_name);
00136    );
00137    AST_LIST_ENTRY(logmsg) list;
00138 };
00139 
00140 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
00141 static pthread_t logthread = AST_PTHREADT_NULL;
00142 static ast_cond_t logcond;
00143 static int close_logger_thread = 0;
00144 
00145 static FILE *qlog;
00146 
00147 /*! \brief Logging channels used in the Asterisk logging system
00148  *
00149  * The first 16 levels are reserved for system usage, and the remaining
00150  * levels are reserved for usage by dynamic levels registered via
00151  * ast_logger_register_level.
00152  */
00153 
00154 /* Modifications to this array are protected by the rwlock in the
00155  * logchannels list.
00156  */
00157 
00158 static char *levels[32] = {
00159    "DEBUG",
00160    "---EVENT---",    /* no longer used */
00161    "NOTICE",
00162    "WARNING",
00163    "ERROR",
00164    "VERBOSE",
00165    "DTMF",
00166 };
00167 
00168 /*! \brief Colors used in the console for logging */
00169 static const int colors[32] = {
00170    COLOR_BRGREEN,
00171    COLOR_BRBLUE,     /* no longer used */
00172    COLOR_YELLOW,
00173    COLOR_BRRED,
00174    COLOR_RED,
00175    COLOR_GREEN,
00176    COLOR_BRGREEN,
00177    0,
00178    0,
00179    0,
00180    0,
00181    0,
00182    0,
00183    0,
00184    0,
00185    0,
00186    COLOR_BRBLUE,
00187    COLOR_BRBLUE,
00188    COLOR_BRBLUE,
00189    COLOR_BRBLUE,
00190    COLOR_BRBLUE,
00191    COLOR_BRBLUE,
00192    COLOR_BRBLUE,
00193    COLOR_BRBLUE,
00194    COLOR_BRBLUE,
00195    COLOR_BRBLUE,
00196    COLOR_BRBLUE,
00197    COLOR_BRBLUE,
00198    COLOR_BRBLUE,
00199    COLOR_BRBLUE,
00200    COLOR_BRBLUE,
00201    COLOR_BRBLUE,
00202 };
00203 
00204 AST_THREADSTORAGE(verbose_buf);
00205 #define VERBOSE_BUF_INIT_SIZE   256
00206 
00207 AST_THREADSTORAGE(log_buf);
00208 #define LOG_BUF_INIT_SIZE       256
00209 
00210 static void logger_queue_init(void);
00211 
00212 static unsigned int make_components(const char *s, int lineno)
00213 {
00214    char *w;
00215    unsigned int res = 0;
00216    char *stringp = ast_strdupa(s);
00217    unsigned int x;
00218 
00219    while ((w = strsep(&stringp, ","))) {
00220       w = ast_skip_blanks(w);
00221 
00222       if (!strcmp(w, "*")) {
00223          res = 0xFFFFFFFF;
00224          break;
00225       } else for (x = 0; x < ARRAY_LEN(levels); x++) {
00226          if (levels[x] && !strcasecmp(w, levels[x])) {
00227             res |= (1 << x);
00228             break;
00229          }
00230       }
00231    }
00232 
00233    return res;
00234 }
00235 
00236 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
00237 {
00238    struct logchannel *chan;
00239    char *facility;
00240    struct ast_tm tm;
00241    struct timeval now = ast_tvnow();
00242    char datestring[256];
00243 
00244    if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
00245       return NULL;
00246 
00247    strcpy(chan->components, components);
00248    chan->lineno = lineno;
00249 
00250    if (!strcasecmp(channel, "console")) {
00251       chan->type = LOGTYPE_CONSOLE;
00252    } else if (!strncasecmp(channel, "syslog", 6)) {
00253       /*
00254       * syntax is:
00255       *  syslog.facility => level,level,level
00256       */
00257       facility = strchr(channel, '.');
00258       if (!facility++ || !facility) {
00259          facility = "local0";
00260       }
00261 
00262       chan->facility = ast_syslog_facility(facility);
00263 
00264       if (chan->facility < 0) {
00265          fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
00266          ast_free(chan);
00267          return NULL;
00268       }
00269 
00270       chan->type = LOGTYPE_SYSLOG;
00271       ast_copy_string(chan->filename, channel, sizeof(chan->filename));
00272       openlog("asterisk", LOG_PID, chan->facility);
00273    } else {
00274       if (!ast_strlen_zero(hostname)) {
00275          snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
00276              channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
00277       } else {
00278          snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
00279              channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
00280       }
00281       if (!(chan->fileptr = fopen(chan->filename, "a"))) {
00282          /* Can't do real logging here since we're called with a lock
00283           * so log to any attached consoles */
00284          ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
00285          ast_console_puts_mutable(chan->filename, __LOG_ERROR);
00286          ast_console_puts_mutable("': ", __LOG_ERROR);
00287          ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
00288          ast_console_puts_mutable("'\n", __LOG_ERROR);
00289          ast_free(chan);
00290          return NULL;
00291       } else {
00292          /* Create our date/time */
00293          ast_localtime(&now, &tm, NULL);
00294          ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
00295 
00296          fprintf(chan->fileptr, "[%s] Asterisk %s built by %s @ %s on a %s running %s on %s\n",
00297             datestring, ast_get_version(), ast_build_user, ast_build_hostname,
00298             ast_build_machine, ast_build_os, ast_build_date);
00299          fflush(chan->fileptr);
00300       }
00301       chan->type = LOGTYPE_FILE;
00302    }
00303    chan->logmask = make_components(chan->components, lineno);
00304 
00305    return chan;
00306 }
00307 
00308 static void init_logger_chain(int locked, const char *altconf)
00309 {
00310    struct logchannel *chan;
00311    struct ast_config *cfg;
00312    struct ast_variable *var;
00313    const char *s;
00314    struct ast_flags config_flags = { 0 };
00315 
00316    if (!(cfg = ast_config_load2(S_OR(altconf, "logger.conf"), "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
00317       return;
00318    }
00319 
00320    /* delete our list of log channels */
00321    if (!locked) {
00322       AST_RWLIST_WRLOCK(&logchannels);
00323    }
00324    while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
00325       ast_free(chan);
00326    }
00327    global_logmask = 0;
00328    if (!locked) {
00329       AST_RWLIST_UNLOCK(&logchannels);
00330    }
00331 
00332    errno = 0;
00333    /* close syslog */
00334    closelog();
00335 
00336    /* If no config file, we're fine, set default options. */
00337    if (!cfg) {
00338       if (errno) {
00339          fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
00340       } else {
00341          fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
00342       }
00343       if (!(chan = ast_calloc(1, sizeof(*chan)))) {
00344          return;
00345       }
00346       chan->type = LOGTYPE_CONSOLE;
00347       chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
00348       if (!locked) {
00349          AST_RWLIST_WRLOCK(&logchannels);
00350       }
00351       AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
00352       global_logmask |= chan->logmask;
00353       if (!locked) {
00354          AST_RWLIST_UNLOCK(&logchannels);
00355       }
00356       return;
00357    }
00358 
00359    if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
00360       if (ast_true(s)) {
00361          if (gethostname(hostname, sizeof(hostname) - 1)) {
00362             ast_copy_string(hostname, "unknown", sizeof(hostname));
00363             fprintf(stderr, "What box has no hostname???\n");
00364          }
00365       } else
00366          hostname[0] = '\0';
00367    } else
00368       hostname[0] = '\0';
00369    if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
00370       ast_copy_string(dateformat, s, sizeof(dateformat));
00371    else
00372       ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
00373    if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
00374       logfiles.queue_log = ast_true(s);
00375    }
00376    if ((s = ast_variable_retrieve(cfg, "general", "queue_log_to_file"))) {
00377       logfiles.queue_log_to_file = ast_true(s);
00378    }
00379    if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name"))) {
00380       ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
00381    }
00382    if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate"))) {
00383       ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
00384    }
00385    if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
00386       if (strcasecmp(s, "timestamp") == 0) {
00387          rotatestrategy = TIMESTAMP;
00388       } else if (strcasecmp(s, "rotate") == 0) {
00389          rotatestrategy = ROTATE;
00390       } else if (strcasecmp(s, "sequential") == 0) {
00391          rotatestrategy = SEQUENTIAL;
00392       } else {
00393          fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
00394       }
00395    } else {
00396       if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
00397          rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
00398          fprintf(stderr, "rotatetimestamp option has been deprecated.  Please use rotatestrategy instead.\n");
00399       }
00400    }
00401 
00402    if (!locked) {
00403       AST_RWLIST_WRLOCK(&logchannels);
00404    }
00405    var = ast_variable_browse(cfg, "logfiles");
00406    for (; var; var = var->next) {
00407       if (!(chan = make_logchannel(var->name, var->value, var->lineno))) {
00408          /* Print error message directly to the consoles since the lock is held
00409           * and we don't want to unlock with the list partially built */
00410          ast_console_puts_mutable("ERROR: Unable to create log channel '", __LOG_ERROR);
00411          ast_console_puts_mutable(var->name, __LOG_ERROR);
00412          ast_console_puts_mutable("'\n", __LOG_ERROR);
00413          continue;
00414       }
00415       AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
00416       global_logmask |= chan->logmask;
00417    }
00418 
00419    if (qlog) {
00420       fclose(qlog);
00421       qlog = NULL;
00422    }
00423 
00424    if (!locked) {
00425       AST_RWLIST_UNLOCK(&logchannels);
00426    }
00427 
00428    ast_config_destroy(cfg);
00429 }
00430 
00431 void ast_child_verbose(int level, const char *fmt, ...)
00432 {
00433    char *msg = NULL, *emsg = NULL, *sptr, *eptr;
00434    va_list ap, aq;
00435    int size;
00436 
00437    /* Don't bother, if the level isn't that high */
00438    if (option_verbose < level) {
00439       return;
00440    }
00441 
00442    va_start(ap, fmt);
00443    va_copy(aq, ap);
00444    if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
00445       va_end(ap);
00446       va_end(aq);
00447       return;
00448    }
00449    va_end(ap);
00450 
00451    if (!(msg = ast_malloc(size + 1))) {
00452       va_end(aq);
00453       return;
00454    }
00455 
00456    vsnprintf(msg, size + 1, fmt, aq);
00457    va_end(aq);
00458 
00459    if (!(emsg = ast_malloc(size * 2 + 1))) {
00460       ast_free(msg);
00461       return;
00462    }
00463 
00464    for (sptr = msg, eptr = emsg; ; sptr++) {
00465       if (*sptr == '"') {
00466          *eptr++ = '\\';
00467       }
00468       *eptr++ = *sptr;
00469       if (*sptr == '\0') {
00470          break;
00471       }
00472    }
00473    ast_free(msg);
00474 
00475    fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
00476    fflush(stdout);
00477    ast_free(emsg);
00478 }
00479 
00480 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
00481 {
00482    va_list ap;
00483    struct timeval tv;
00484    struct ast_tm tm;
00485    char qlog_msg[8192];
00486    int qlog_len;
00487    char time_str[30];
00488 
00489    if (!logger_initialized) {
00490       /* You are too early.  We are not open yet! */
00491       return;
00492    }
00493    if (!queuelog_init) {
00494       AST_RWLIST_WRLOCK(&logchannels);
00495       if (!queuelog_init) {
00496          /*
00497           * We have delayed initializing the queue logging system so
00498           * preloaded realtime modules can get up.  We must initialize
00499           * now since someone is trying to log something.
00500           */
00501          logger_queue_init();
00502          queuelog_init = 1;
00503          AST_RWLIST_UNLOCK(&logchannels);
00504          ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
00505       } else {
00506          AST_RWLIST_UNLOCK(&logchannels);
00507       }
00508    }
00509 
00510    if (ast_check_realtime("queue_log")) {
00511       tv = ast_tvnow();
00512       ast_localtime(&tv, &tm, NULL);
00513       ast_strftime(time_str, sizeof(time_str), "%F %T.%6q", &tm);
00514       va_start(ap, fmt);
00515       vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
00516       va_end(ap);
00517       if (logfiles.queue_adaptive_realtime) {
00518          AST_DECLARE_APP_ARGS(args,
00519             AST_APP_ARG(data)[5];
00520          );
00521          AST_NONSTANDARD_APP_ARGS(args, qlog_msg, '|');
00522          /* Ensure fields are large enough to receive data */
00523          ast_realtime_require_field("queue_log",
00524             "data1", RQ_CHAR, strlen(S_OR(args.data[0], "")),
00525             "data2", RQ_CHAR, strlen(S_OR(args.data[1], "")),
00526             "data3", RQ_CHAR, strlen(S_OR(args.data[2], "")),
00527             "data4", RQ_CHAR, strlen(S_OR(args.data[3], "")),
00528             "data5", RQ_CHAR, strlen(S_OR(args.data[4], "")),
00529             SENTINEL);
00530 
00531          /* Store the log */
00532          ast_store_realtime("queue_log", "time", time_str,
00533             "callid", callid,
00534             "queuename", queuename,
00535             "agent", agent,
00536             "event", event,
00537             "data1", S_OR(args.data[0], ""),
00538             "data2", S_OR(args.data[1], ""),
00539             "data3", S_OR(args.data[2], ""),
00540             "data4", S_OR(args.data[3], ""),
00541             "data5", S_OR(args.data[4], ""),
00542             SENTINEL);
00543       } else {
00544          ast_store_realtime("queue_log", "time", time_str,
00545             "callid", callid,
00546             "queuename", queuename,
00547             "agent", agent,
00548             "event", event,
00549             "data", qlog_msg,
00550             SENTINEL);
00551       }
00552 
00553       if (!logfiles.queue_log_to_file) {
00554          return;
00555       }
00556    }
00557 
00558    if (qlog) {
00559       va_start(ap, fmt);
00560       qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
00561       vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
00562       va_end(ap);
00563       AST_RWLIST_RDLOCK(&logchannels);
00564       if (qlog) {
00565          fprintf(qlog, "%s\n", qlog_msg);
00566          fflush(qlog);
00567       }
00568       AST_RWLIST_UNLOCK(&logchannels);
00569    }
00570 }
00571 
00572 static int rotate_file(const char *filename)
00573 {
00574    char old[PATH_MAX];
00575    char new[PATH_MAX];
00576    int x, y, which, found, res = 0, fd;
00577    char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
00578 
00579    switch (rotatestrategy) {
00580    case SEQUENTIAL:
00581       for (x = 0; ; x++) {
00582          snprintf(new, sizeof(new), "%s.%d", filename, x);
00583          fd = open(new, O_RDONLY);
00584          if (fd > -1)
00585             close(fd);
00586          else
00587             break;
00588       }
00589       if (rename(filename, new)) {
00590          fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
00591          res = -1;
00592       } else {
00593          filename = new;
00594       }
00595       break;
00596    case TIMESTAMP:
00597       snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
00598       if (rename(filename, new)) {
00599          fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
00600          res = -1;
00601       } else {
00602          filename = new;
00603       }
00604       break;
00605    case ROTATE:
00606       /* Find the next empty slot, including a possible suffix */
00607       for (x = 0; ; x++) {
00608          found = 0;
00609          for (which = 0; which < ARRAY_LEN(suffixes); which++) {
00610             snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
00611             fd = open(new, O_RDONLY);
00612             if (fd > -1) {
00613                close(fd);
00614                found = 1;
00615                break;
00616             }
00617          }
00618          if (!found) {
00619             break;
00620          }
00621       }
00622 
00623       /* Found an empty slot */
00624       for (y = x; y > 0; y--) {
00625          for (which = 0; which < ARRAY_LEN(suffixes); which++) {
00626             snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
00627             fd = open(old, O_RDONLY);
00628             if (fd > -1) {
00629                /* Found the right suffix */
00630                close(fd);
00631                snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
00632                if (rename(old, new)) {
00633                   fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
00634                   res = -1;
00635                }
00636                break;
00637             }
00638          }
00639       }
00640 
00641       /* Finally, rename the current file */
00642       snprintf(new, sizeof(new), "%s.0", filename);
00643       if (rename(filename, new)) {
00644          fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
00645          res = -1;
00646       } else {
00647          filename = new;
00648       }
00649    }
00650 
00651    if (!ast_strlen_zero(exec_after_rotate)) {
00652       struct ast_channel *c = ast_dummy_channel_alloc();
00653       char buf[512];
00654 
00655       pbx_builtin_setvar_helper(c, "filename", filename);
00656       pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
00657       if (c) {
00658          c = ast_channel_unref(c);
00659       }
00660       if (ast_safe_system(buf) == -1) {
00661          ast_log(LOG_WARNING, "error executing '%s'\n", buf);
00662       }
00663    }
00664    return res;
00665 }
00666 
00667 /*!
00668  * \internal
00669  * \brief Start the realtime queue logging if configured.
00670  *
00671  * \retval TRUE if not to open queue log file.
00672  */
00673 static int logger_queue_rt_start(void)
00674 {
00675    if (ast_check_realtime("queue_log")) {
00676       if (!ast_realtime_require_field("queue_log",
00677          "time", RQ_DATETIME, 26,
00678          "data1", RQ_CHAR, 20,
00679          "data2", RQ_CHAR, 20,
00680          "data3", RQ_CHAR, 20,
00681          "data4", RQ_CHAR, 20,
00682          "data5", RQ_CHAR, 20,
00683          SENTINEL)) {
00684          logfiles.queue_adaptive_realtime = 1;
00685       } else {
00686          logfiles.queue_adaptive_realtime = 0;
00687       }
00688 
00689       if (!logfiles.queue_log_to_file) {
00690          /* Don't open the log file. */
00691          return 1;
00692       }
00693    }
00694    return 0;
00695 }
00696 
00697 /*!
00698  * \internal
00699  * \brief Rotate the queue log file and restart.
00700  *
00701  * \param queue_rotate Log queue rotation mode.
00702  *
00703  * \note Assumes logchannels is write locked on entry.
00704  *
00705  * \retval 0 on success.
00706  * \retval -1 on error.
00707  */
00708 static int logger_queue_restart(int queue_rotate)
00709 {
00710    int res = 0;
00711    char qfname[PATH_MAX];
00712 
00713    if (logger_queue_rt_start()) {
00714       return res;
00715    }
00716 
00717    snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
00718    if (qlog) {
00719       /* Just in case it was still open. */
00720       fclose(qlog);
00721       qlog = NULL;
00722    }
00723    if (queue_rotate) {
00724       rotate_file(qfname);
00725    }
00726 
00727    /* Open the log file. */
00728    qlog = fopen(qfname, "a");
00729    if (!qlog) {
00730       ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
00731       res = -1;
00732    }
00733    return res;
00734 }
00735 
00736 static int reload_logger(int rotate, const char *altconf)
00737 {
00738    int queue_rotate = rotate;
00739    struct logchannel *f;
00740    int res = 0;
00741 
00742    AST_RWLIST_WRLOCK(&logchannels);
00743 
00744    if (qlog) {
00745       if (rotate < 0) {
00746          /* Check filesize - this one typically doesn't need an auto-rotate */
00747          if (ftello(qlog) > 0x40000000) { /* Arbitrarily, 1 GB */
00748             fclose(qlog);
00749             qlog = NULL;
00750          } else {
00751             queue_rotate = 0;
00752          }
00753       } else {
00754          fclose(qlog);
00755          qlog = NULL;
00756       }
00757    } else {
00758       queue_rotate = 0;
00759    }
00760 
00761    ast_mkdir(ast_config_AST_LOG_DIR, 0777);
00762 
00763    AST_RWLIST_TRAVERSE(&logchannels, f, list) {
00764       if (f->disabled) {
00765          f->disabled = 0;  /* Re-enable logging at reload */
00766          manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
00767       }
00768       if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
00769          int rotate_this = 0;
00770          if (ftello(f->fileptr) > 0x40000000) { /* Arbitrarily, 1 GB */
00771             /* Be more proactive about rotating massive log files */
00772             rotate_this = 1;
00773          }
00774          fclose(f->fileptr);  /* Close file */
00775          f->fileptr = NULL;
00776          if (rotate || rotate_this) {
00777             rotate_file(f->filename);
00778          }
00779       }
00780    }
00781 
00782    filesize_reload_needed = 0;
00783 
00784    init_logger_chain(1 /* locked */, altconf);
00785 
00786    ast_unload_realtime("queue_log");
00787    if (logfiles.queue_log) {
00788       res = logger_queue_restart(queue_rotate);
00789       AST_RWLIST_UNLOCK(&logchannels);
00790       ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
00791       ast_verb(1, "Asterisk Queue Logger restarted\n");
00792    } else {
00793       AST_RWLIST_UNLOCK(&logchannels);
00794    }
00795 
00796    return res;
00797 }
00798 
00799 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
00800    a full Asterisk reload) */
00801 int logger_reload(void)
00802 {
00803    if (reload_logger(0, NULL)) {
00804       return RESULT_FAILURE;
00805    }
00806    return RESULT_SUCCESS;
00807 }
00808 
00809 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00810 {
00811    switch (cmd) {
00812    case CLI_INIT:
00813       e->command = "logger reload";
00814       e->usage =
00815          "Usage: logger reload [<alt-conf>]\n"
00816          "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
00817       return NULL;
00818    case CLI_GENERATE:
00819       return NULL;
00820    }
00821    if (reload_logger(0, a->argc == 3 ? a->argv[2] : NULL)) {
00822       ast_cli(a->fd, "Failed to reload the logger\n");
00823       return CLI_FAILURE;
00824    }
00825    return CLI_SUCCESS;
00826 }
00827 
00828 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00829 {
00830    switch (cmd) {
00831    case CLI_INIT:
00832       e->command = "logger rotate";
00833       e->usage = 
00834          "Usage: logger rotate\n"
00835          "       Rotates and Reopens the log files.\n";
00836       return NULL;
00837    case CLI_GENERATE:
00838       return NULL;   
00839    }
00840    if (reload_logger(1, NULL)) {
00841       ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
00842       return CLI_FAILURE;
00843    } 
00844    return CLI_SUCCESS;
00845 }
00846 
00847 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00848 {
00849    int x;
00850    int state;
00851    int level = -1;
00852 
00853    switch (cmd) {
00854    case CLI_INIT:
00855       e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
00856       e->usage = 
00857          "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
00858          "       Set a specific log level to enabled/disabled for this console.\n";
00859       return NULL;
00860    case CLI_GENERATE:
00861       return NULL;
00862    }
00863 
00864    if (a->argc < 5)
00865       return CLI_SHOWUSAGE;
00866 
00867    AST_RWLIST_WRLOCK(&logchannels);
00868 
00869    for (x = 0; x < ARRAY_LEN(levels); x++) {
00870       if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
00871          level = x;
00872          break;
00873       }
00874    }
00875 
00876    AST_RWLIST_UNLOCK(&logchannels);
00877 
00878    state = ast_true(a->argv[4]) ? 1 : 0;
00879 
00880    if (level != -1) {
00881       ast_console_toggle_loglevel(a->fd, level, state);
00882       ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
00883    } else
00884       return CLI_SHOWUSAGE;
00885 
00886    return CLI_SUCCESS;
00887 }
00888 
00889 /*! \brief CLI command to show logging system configuration */
00890 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00891 {
00892 #define FORMATL   "%-35.35s %-8.8s %-9.9s "
00893    struct logchannel *chan;
00894    switch (cmd) {
00895    case CLI_INIT:
00896       e->command = "logger show channels";
00897       e->usage = 
00898          "Usage: logger show channels\n"
00899          "       List configured logger channels.\n";
00900       return NULL;
00901    case CLI_GENERATE:
00902       return NULL;   
00903    }
00904    ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
00905    ast_cli(a->fd, "Configuration\n");
00906    ast_cli(a->fd, FORMATL, "-------", "----", "------");
00907    ast_cli(a->fd, "-------------\n");
00908    AST_RWLIST_RDLOCK(&logchannels);
00909    AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
00910       unsigned int level;
00911 
00912       ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
00913          chan->disabled ? "Disabled" : "Enabled");
00914       ast_cli(a->fd, " - ");
00915       for (level = 0; level < ARRAY_LEN(levels); level++) {
00916          if ((chan->logmask & (1 << level)) && levels[level]) {
00917             ast_cli(a->fd, "%s ", levels[level]);
00918          }
00919       }
00920       ast_cli(a->fd, "\n");
00921    }
00922    AST_RWLIST_UNLOCK(&logchannels);
00923    ast_cli(a->fd, "\n");
00924 
00925    return CLI_SUCCESS;
00926 }
00927 
00928 struct verb {
00929    void (*verboser)(const char *string);
00930    AST_LIST_ENTRY(verb) list;
00931 };
00932 
00933 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
00934 
00935 static struct ast_cli_entry cli_logger[] = {
00936    AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
00937    AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
00938    AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
00939    AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
00940 };
00941 
00942 static void _handle_SIGXFSZ(int sig)
00943 {
00944    /* Indicate need to reload */
00945    filesize_reload_needed = 1;
00946 }
00947 
00948 static struct sigaction handle_SIGXFSZ = {
00949    .sa_handler = _handle_SIGXFSZ,
00950    .sa_flags = SA_RESTART,
00951 };
00952 
00953 static void ast_log_vsyslog(struct logmsg *msg)
00954 {
00955    char buf[BUFSIZ];
00956    int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
00957 
00958    if (syslog_level < 0) {
00959       /* we are locked here, so cannot ast_log() */
00960       fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
00961       return;
00962    }
00963 
00964    snprintf(buf, sizeof(buf), "%s[%d]: %s:%d in %s: %s",
00965        levels[msg->level], msg->lwp, msg->file, msg->line, msg->function, msg->message);
00966 
00967    term_strip(buf, buf, strlen(buf) + 1);
00968    syslog(syslog_level, "%s", buf);
00969 }
00970 
00971 /*! \brief Print a normal log message to the channels */
00972 static void logger_print_normal(struct logmsg *logmsg)
00973 {
00974    struct logchannel *chan = NULL;
00975    char buf[BUFSIZ];
00976    struct verb *v = NULL;
00977 
00978    if (logmsg->level == __LOG_VERBOSE) {
00979       char *tmpmsg = ast_strdupa(logmsg->message + 1);
00980       /* Iterate through the list of verbosers and pass them the log message string */
00981       AST_RWLIST_RDLOCK(&verbosers);
00982       AST_RWLIST_TRAVERSE(&verbosers, v, list)
00983          v->verboser(logmsg->message);
00984       AST_RWLIST_UNLOCK(&verbosers);
00985       ast_string_field_set(logmsg, message, tmpmsg);
00986    }
00987 
00988    AST_RWLIST_RDLOCK(&logchannels);
00989 
00990    if (!AST_RWLIST_EMPTY(&logchannels)) {
00991       AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
00992          /* If the channel is disabled, then move on to the next one */
00993          if (chan->disabled)
00994             continue;
00995          /* Check syslog channels */
00996          if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
00997             ast_log_vsyslog(logmsg);
00998          /* Console channels */
00999          } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
01000             char linestr[128];
01001             char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
01002 
01003             /* If the level is verbose, then skip it */
01004             if (logmsg->level == __LOG_VERBOSE)
01005                continue;
01006 
01007             /* Turn the numerical line number into a string */
01008             snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
01009             /* Build string to print out */
01010             snprintf(buf, sizeof(buf), "[%s] %s[%d]: %s:%s %s: %s",
01011                 logmsg->date,
01012                 term_color(tmp1, logmsg->level_name, colors[logmsg->level], 0, sizeof(tmp1)),
01013                 logmsg->lwp,
01014                 term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
01015                 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
01016                 term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
01017                 logmsg->message);
01018             /* Print out */
01019             ast_console_puts_mutable(buf, logmsg->level);
01020          /* File channels */
01021          } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
01022             int res = 0;
01023 
01024             /* If no file pointer exists, skip it */
01025             if (!chan->fileptr) {
01026                continue;
01027             }
01028 
01029             /* Print out to the file */
01030             res = fprintf(chan->fileptr, "[%s] %s[%d] %s: %s",
01031                      logmsg->date, logmsg->level_name, logmsg->lwp, logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
01032             if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
01033                fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
01034                if (errno == ENOMEM || errno == ENOSPC)
01035                   fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
01036                else
01037                   fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
01038                manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
01039                chan->disabled = 1;
01040             } else if (res > 0) {
01041                fflush(chan->fileptr);
01042             }
01043          }
01044       }
01045    } else if (logmsg->level != __LOG_VERBOSE) {
01046       fputs(logmsg->message, stdout);
01047    }
01048 
01049    AST_RWLIST_UNLOCK(&logchannels);
01050 
01051    /* If we need to reload because of the file size, then do so */
01052    if (filesize_reload_needed) {
01053       reload_logger(-1, NULL);
01054       ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
01055    }
01056 
01057    return;
01058 }
01059 
01060 /*! \brief Actual logging thread */
01061 static void *logger_thread(void *data)
01062 {
01063    struct logmsg *next = NULL, *msg = NULL;
01064 
01065    for (;;) {
01066       /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
01067       AST_LIST_LOCK(&logmsgs);
01068       if (AST_LIST_EMPTY(&logmsgs)) {
01069          if (close_logger_thread) {
01070             break;
01071          } else {
01072             ast_cond_wait(&logcond, &logmsgs.lock);
01073          }
01074       }
01075       next = AST_LIST_FIRST(&logmsgs);
01076       AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
01077       AST_LIST_UNLOCK(&logmsgs);
01078 
01079       /* Otherwise go through and process each message in the order added */
01080       while ((msg = next)) {
01081          /* Get the next entry now so that we can free our current structure later */
01082          next = AST_LIST_NEXT(msg, list);
01083 
01084          /* Depending on the type, send it to the proper function */
01085          logger_print_normal(msg);
01086 
01087          /* Free the data since we are done */
01088          ast_free(msg);
01089       }
01090 
01091       /* If we should stop, then stop */
01092       if (close_logger_thread)
01093          break;
01094    }
01095 
01096    return NULL;
01097 }
01098 
01099 /*!
01100  * \internal
01101  * \brief Initialize the logger queue.
01102  *
01103  * \note Assumes logchannels is write locked on entry.
01104  *
01105  * \return Nothing
01106  */
01107 static void logger_queue_init(void)
01108 {
01109    ast_unload_realtime("queue_log");
01110    if (logfiles.queue_log) {
01111       char qfname[PATH_MAX];
01112 
01113       if (logger_queue_rt_start()) {
01114          return;
01115       }
01116 
01117       /* Open the log file. */
01118       snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
01119          queue_log_name);
01120       if (qlog) {
01121          /* Just in case it was already open. */
01122          fclose(qlog);
01123       }
01124       qlog = fopen(qfname, "a");
01125       if (!qlog) {
01126          ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
01127       }
01128    }
01129 }
01130 
01131 int init_logger(void)
01132 {
01133    /* auto rotate if sig SIGXFSZ comes a-knockin */
01134    sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
01135 
01136    /* start logger thread */
01137    ast_cond_init(&logcond, NULL);
01138    if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
01139       ast_cond_destroy(&logcond);
01140       return -1;
01141    }
01142 
01143    /* register the logger cli commands */
01144    ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
01145 
01146    ast_mkdir(ast_config_AST_LOG_DIR, 0777);
01147 
01148    /* create log channels */
01149    init_logger_chain(0 /* locked */, NULL);
01150    logger_initialized = 1;
01151 
01152    return 0;
01153 }
01154 
01155 void close_logger(void)
01156 {
01157    struct logchannel *f = NULL;
01158 
01159    logger_initialized = 0;
01160 
01161    /* Stop logger thread */
01162    AST_LIST_LOCK(&logmsgs);
01163    close_logger_thread = 1;
01164    ast_cond_signal(&logcond);
01165    AST_LIST_UNLOCK(&logmsgs);
01166 
01167    if (logthread != AST_PTHREADT_NULL)
01168       pthread_join(logthread, NULL);
01169 
01170    AST_RWLIST_WRLOCK(&logchannels);
01171 
01172    if (qlog) {
01173       fclose(qlog);
01174       qlog = NULL;
01175    }
01176 
01177    AST_RWLIST_TRAVERSE(&logchannels, f, list) {
01178       if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
01179          fclose(f->fileptr);
01180          f->fileptr = NULL;
01181       }
01182    }
01183 
01184    closelog(); /* syslog */
01185 
01186    AST_RWLIST_UNLOCK(&logchannels);
01187 
01188    return;
01189 }
01190 
01191 /*!
01192  * \brief send log messages to syslog and/or the console
01193  */
01194 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
01195 {
01196    struct logmsg *logmsg = NULL;
01197    struct ast_str *buf = NULL;
01198    struct ast_tm tm;
01199    struct timeval now = ast_tvnow();
01200    int res = 0;
01201    va_list ap;
01202    char datestring[256];
01203 
01204    if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
01205       return;
01206 
01207    if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
01208       /*
01209        * we don't have the logger chain configured yet,
01210        * so just log to stdout
01211        */
01212       int result;
01213       va_start(ap, fmt);
01214       result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
01215       va_end(ap);
01216       if (result != AST_DYNSTR_BUILD_FAILED) {
01217          term_filter_escapes(ast_str_buffer(buf));
01218          fputs(ast_str_buffer(buf), stdout);
01219       }
01220       return;
01221    }
01222    
01223    /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
01224       are non-zero; LOG_DEBUG messages can still be displayed if option_debug
01225       is zero, if option_verbose is non-zero (this allows for 'level zero'
01226       LOG_DEBUG messages to be displayed, if the logmask on any channel
01227       allows it)
01228    */
01229    if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
01230       return;
01231 
01232    /* Ignore anything that never gets logged anywhere */
01233    if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
01234       return;
01235    
01236    /* Build string */
01237    va_start(ap, fmt);
01238    res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
01239    va_end(ap);
01240 
01241    /* If the build failed, then abort and free this structure */
01242    if (res == AST_DYNSTR_BUILD_FAILED)
01243       return;
01244 
01245    /* Create a new logging message */
01246    if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
01247       return;
01248 
01249    /* Copy string over */
01250    ast_string_field_set(logmsg, message, ast_str_buffer(buf));
01251 
01252    /* Set type */
01253    if (level == __LOG_VERBOSE) {
01254       logmsg->type = LOGMSG_VERBOSE;
01255    } else {
01256       logmsg->type = LOGMSG_NORMAL;
01257    }
01258 
01259    /* Create our date/time */
01260    ast_localtime(&now, &tm, NULL);
01261    ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
01262    ast_string_field_set(logmsg, date, datestring);
01263 
01264    /* Copy over data */
01265    logmsg->level = level;
01266    logmsg->line = line;
01267    ast_string_field_set(logmsg, level_name, levels[level]);
01268    ast_string_field_set(logmsg, file, file);
01269    ast_string_field_set(logmsg, function, function);
01270    logmsg->lwp = ast_get_tid();
01271 
01272    /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
01273    if (logthread != AST_PTHREADT_NULL) {
01274       AST_LIST_LOCK(&logmsgs);
01275       AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
01276       ast_cond_signal(&logcond);
01277       AST_LIST_UNLOCK(&logmsgs);
01278    } else {
01279       logger_print_normal(logmsg);
01280       ast_free(logmsg);
01281    }
01282 
01283    return;
01284 }
01285 
01286 #ifdef HAVE_BKTR
01287 
01288 struct ast_bt *ast_bt_create(void) 
01289 {
01290    struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
01291    if (!bt) {
01292       ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
01293       return NULL;
01294    }
01295 
01296    bt->alloced = 1;
01297 
01298    ast_bt_get_addresses(bt);
01299 
01300    return bt;
01301 }
01302 
01303 int ast_bt_get_addresses(struct ast_bt *bt)
01304 {
01305    bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
01306 
01307    return 0;
01308 }
01309 
01310 void *ast_bt_destroy(struct ast_bt *bt)
01311 {
01312    if (bt->alloced) {
01313       ast_free(bt);
01314    }
01315 
01316    return NULL;
01317 }
01318 
01319 char **ast_bt_get_symbols(void **addresses, size_t num_frames)
01320 {
01321    char **strings = NULL;
01322 #if defined(BETTER_BACKTRACES)
01323    int stackfr;
01324    bfd *bfdobj;           /* bfd.h */
01325    Dl_info dli;           /* dlfcn.h */
01326    long allocsize;
01327    asymbol **syms = NULL; /* bfd.h */
01328    bfd_vma offset;        /* bfd.h */
01329    const char *lastslash;
01330    asection *section;
01331    const char *file, *func;
01332    unsigned int line;
01333    char address_str[128];
01334    char msg[1024];
01335    size_t strings_size;
01336    size_t *eachlen;
01337 #endif
01338 
01339 #if defined(BETTER_BACKTRACES)
01340    strings_size = num_frames * sizeof(*strings);
01341    eachlen = ast_calloc(num_frames, sizeof(*eachlen));
01342 
01343    if (!(strings = ast_calloc(num_frames, sizeof(*strings)))) {
01344       return NULL;
01345    }
01346 
01347    for (stackfr = 0; stackfr < num_frames; stackfr++) {
01348       int found = 0, symbolcount;
01349 
01350       msg[0] = '\0';
01351 
01352       if (!dladdr(addresses[stackfr], &dli)) {
01353          continue;
01354       }
01355 
01356       if (strcmp(dli.dli_fname, "asterisk") == 0) {
01357          char asteriskpath[256];
01358          if (!(dli.dli_fname = ast_utils_which("asterisk", asteriskpath, sizeof(asteriskpath)))) {
01359             /* This will fail to find symbols */
01360             ast_debug(1, "Failed to find asterisk binary for debug symbols.\n");
01361             dli.dli_fname = "asterisk";
01362          }
01363       }
01364 
01365       lastslash = strrchr(dli.dli_fname, '/');
01366       if (  (bfdobj = bfd_openr(dli.dli_fname, NULL)) &&
01367             bfd_check_format(bfdobj, bfd_object) &&
01368             (allocsize = bfd_get_symtab_upper_bound(bfdobj)) > 0 &&
01369             (syms = ast_malloc(allocsize)) &&
01370             (symbolcount = bfd_canonicalize_symtab(bfdobj, syms))) {
01371 
01372          if (bfdobj->flags & DYNAMIC) {
01373             offset = addresses[stackfr] - dli.dli_fbase;
01374          } else {
01375             offset = addresses[stackfr] - (void *) 0;
01376          }
01377 
01378          for (section = bfdobj->sections; section; section = section->next) {
01379             if (  !bfd_get_section_flags(bfdobj, section) & SEC_ALLOC ||
01380                   section->vma > offset ||
01381                   section->size + section->vma < offset) {
01382                continue;
01383             }
01384 
01385             if (!bfd_find_nearest_line(bfdobj, section, syms, offset - section->vma, &file, &func, &line)) {
01386                continue;
01387             }
01388 
01389             /* Stack trace output */
01390             found++;
01391             if ((lastslash = strrchr(file, '/'))) {
01392                const char *prevslash;
01393                for (prevslash = lastslash - 1; *prevslash != '/' && prevslash >= file; prevslash--);
01394                if (prevslash >= file) {
01395                   lastslash = prevslash;
01396                }
01397             }
01398             if (dli.dli_saddr == NULL) {
01399                address_str[0] = '\0';
01400             } else {
01401                snprintf(address_str, sizeof(address_str), " (%p+%lX)",
01402                   dli.dli_saddr,
01403                   (unsigned long) (addresses[stackfr] - dli.dli_saddr));
01404             }
01405             snprintf(msg, sizeof(msg), "%s:%u %s()%s",
01406                lastslash ? lastslash + 1 : file, line,
01407                S_OR(func, "???"),
01408                address_str);
01409 
01410             break; /* out of section iteration */
01411          }
01412       }
01413       if (bfdobj) {
01414          bfd_close(bfdobj);
01415          if (syms) {
01416             ast_free(syms);
01417          }
01418       }
01419 
01420       /* Default output, if we cannot find the information within BFD */
01421       if (!found) {
01422          if (dli.dli_saddr == NULL) {
01423             address_str[0] = '\0';
01424          } else {
01425             snprintf(address_str, sizeof(address_str), " (%p+%lX)",
01426                dli.dli_saddr,
01427                (unsigned long) (addresses[stackfr] - dli.dli_saddr));
01428          }
01429          snprintf(msg, sizeof(msg), "%s %s()%s",
01430             lastslash ? lastslash + 1 : dli.dli_fname,
01431             S_OR(dli.dli_sname, "<unknown>"),
01432             address_str);
01433       }
01434 
01435       if (!ast_strlen_zero(msg)) {
01436          char **tmp;
01437          eachlen[stackfr] = strlen(msg);
01438          if (!(tmp = ast_realloc(strings, strings_size + eachlen[stackfr] + 1))) {
01439             ast_free(strings);
01440             strings = NULL;
01441             break; /* out of stack frame iteration */
01442          }
01443          strings = tmp;
01444          strings[stackfr] = (char *) strings + strings_size;
01445          ast_copy_string(strings[stackfr], msg, eachlen[stackfr] + 1);
01446          strings_size += eachlen[stackfr] + 1;
01447       }
01448    }
01449 
01450    if (strings) {
01451       /* Recalculate the offset pointers */
01452       strings[0] = (char *) strings + num_frames * sizeof(*strings);
01453       for (stackfr = 1; stackfr < num_frames; stackfr++) {
01454          strings[stackfr] = strings[stackfr - 1] + eachlen[stackfr - 1] + 1;
01455       }
01456    }
01457 #else /* !defined(BETTER_BACKTRACES) */
01458    strings = backtrace_symbols(addresses, num_frames);
01459 #endif /* defined(BETTER_BACKTRACES) */
01460    return strings;
01461 }
01462 
01463 #endif /* HAVE_BKTR */
01464 
01465 void ast_backtrace(void)
01466 {
01467 #ifdef HAVE_BKTR
01468    struct ast_bt *bt;
01469    int i = 0;
01470    char **strings;
01471 
01472    if (!(bt = ast_bt_create())) {
01473       ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
01474       return;
01475    }
01476 
01477    if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
01478       ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
01479       for (i = 3; i < bt->num_frames - 2; i++) {
01480          ast_debug(1, "#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
01481       }
01482 
01483       /* MALLOC_DEBUG will erroneously report an error here, unless we undef the macro. */
01484 #undef free
01485       free(strings);
01486    } else {
01487       ast_debug(1, "Could not allocate memory for backtrace\n");
01488    }
01489    ast_bt_destroy(bt);
01490 #else
01491    ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
01492 #endif /* defined(HAVE_BKTR) */
01493 }
01494 
01495 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
01496 {
01497    struct ast_str *buf = NULL;
01498    int res = 0;
01499 
01500    if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
01501       return;
01502 
01503    if (ast_opt_timestamp) {
01504       struct timeval now;
01505       struct ast_tm tm;
01506       char date[40];
01507       char *datefmt;
01508 
01509       now = ast_tvnow();
01510       ast_localtime(&now, &tm, NULL);
01511       ast_strftime(date, sizeof(date), dateformat, &tm);
01512       datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
01513       sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
01514       fmt = datefmt;
01515    } else {
01516       char *tmp = alloca(strlen(fmt) + 2);
01517       sprintf(tmp, "%c%s", 127, fmt);
01518       fmt = tmp;
01519    }
01520 
01521    /* Build string */
01522    res = ast_str_set_va(&buf, 0, fmt, ap);
01523 
01524    /* If the build failed then we can drop this allocated message */
01525    if (res == AST_DYNSTR_BUILD_FAILED)
01526       return;
01527 
01528    ast_log(__LOG_VERBOSE, file, line, func, "%s", ast_str_buffer(buf));
01529 }
01530 
01531 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
01532 {
01533    va_list ap;
01534 
01535    va_start(ap, fmt);
01536    __ast_verbose_ap(file, line, func, fmt, ap);
01537    va_end(ap);
01538 }
01539 
01540 /* No new code should use this directly, but we have the ABI for backwards compat */
01541 #undef ast_verbose
01542 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
01543 void ast_verbose(const char *fmt, ...)
01544 {
01545    va_list ap;
01546 
01547    va_start(ap, fmt);
01548    __ast_verbose_ap("", 0, "", fmt, ap);
01549    va_end(ap);
01550 }
01551 
01552 int ast_register_verbose(void (*v)(const char *string)) 
01553 {
01554    struct verb *verb;
01555 
01556    if (!(verb = ast_malloc(sizeof(*verb))))
01557       return -1;
01558 
01559    verb->verboser = v;
01560 
01561    AST_RWLIST_WRLOCK(&verbosers);
01562    AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
01563    AST_RWLIST_UNLOCK(&verbosers);
01564    
01565    return 0;
01566 }
01567 
01568 int ast_unregister_verbose(void (*v)(const char *string))
01569 {
01570    struct verb *cur;
01571 
01572    AST_RWLIST_WRLOCK(&verbosers);
01573    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
01574       if (cur->verboser == v) {
01575          AST_RWLIST_REMOVE_CURRENT(list);
01576          ast_free(cur);
01577          break;
01578       }
01579    }
01580    AST_RWLIST_TRAVERSE_SAFE_END;
01581    AST_RWLIST_UNLOCK(&verbosers);
01582    
01583    return cur ? 0 : -1;
01584 }
01585 
01586 static void update_logchannels(void)
01587 {
01588    struct logchannel *cur;
01589 
01590    AST_RWLIST_WRLOCK(&logchannels);
01591 
01592    global_logmask = 0;
01593 
01594    AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
01595       cur->logmask = make_components(cur->components, cur->lineno);
01596       global_logmask |= cur->logmask;
01597    }
01598 
01599    AST_RWLIST_UNLOCK(&logchannels);
01600 }
01601 
01602 int ast_logger_register_level(const char *name)
01603 {
01604    unsigned int level;
01605    unsigned int available = 0;
01606 
01607    AST_RWLIST_WRLOCK(&logchannels);
01608 
01609    for (level = 0; level < ARRAY_LEN(levels); level++) {
01610       if ((level >= 16) && !available && !levels[level]) {
01611          available = level;
01612          continue;
01613       }
01614 
01615       if (levels[level] && !strcasecmp(levels[level], name)) {
01616          ast_log(LOG_WARNING,
01617             "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
01618             name);
01619          AST_RWLIST_UNLOCK(&logchannels);
01620 
01621          return -1;
01622       }
01623    }
01624 
01625    if (!available) {
01626       ast_log(LOG_WARNING,
01627          "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
01628          name);
01629       AST_RWLIST_UNLOCK(&logchannels);
01630 
01631       return -1;
01632    }
01633 
01634    levels[available] = ast_strdup(name);
01635 
01636    AST_RWLIST_UNLOCK(&logchannels);
01637 
01638    ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
01639 
01640    update_logchannels();
01641 
01642    return available;
01643 }
01644 
01645 void ast_logger_unregister_level(const char *name)
01646 {
01647    unsigned int found = 0;
01648    unsigned int x;
01649 
01650    AST_RWLIST_WRLOCK(&logchannels);
01651 
01652    for (x = 16; x < ARRAY_LEN(levels); x++) {
01653       if (!levels[x]) {
01654          continue;
01655       }
01656 
01657       if (strcasecmp(levels[x], name)) {
01658          continue;
01659       }
01660 
01661       found = 1;
01662       break;
01663    }
01664 
01665    if (found) {
01666       /* take this level out of the global_logmask, to ensure that no new log messages
01667        * will be queued for it
01668        */
01669 
01670       global_logmask &= ~(1 << x);
01671 
01672       ast_free(levels[x]);
01673       levels[x] = NULL;
01674       AST_RWLIST_UNLOCK(&logchannels);
01675 
01676       ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
01677 
01678       update_logchannels();
01679    } else {
01680       AST_RWLIST_UNLOCK(&logchannels);
01681    }
01682 }
01683 

Generated on Sat Feb 11 06:33:18 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6