Thu Sep 7 01:03:01 2017

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

Generated on 7 Sep 2017 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1