bceaf092f05d4b26f0782f19aa7116560eccc9f4
[asterisk/asterisk.git] / main / logger.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Asterisk Logger
22  * 
23  * Logging routines
24  *
25  * \author Mark Spencer <markster@digium.com>
26  */
27
28 /*
29  * define _ASTERISK_LOGGER_H to prevent the inclusion of logger.h;
30  * it redefines LOG_* which we need to define syslog_level_map.
31  * later, we force the inclusion of logger.h again.
32  */
33 #define _ASTERISK_LOGGER_H
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 /*
39  * WARNING: additional #include directives should NOT be placed here, they 
40  * should be placed AFTER '#undef _ASTERISK_LOGGER_H' below
41  */
42 #include "asterisk/_private.h"
43 #include "asterisk/paths.h"     /* use ast_config_AST_LOG_DIR */
44 #include <signal.h>
45 #include <time.h>
46 #include <sys/stat.h>
47 #include <fcntl.h>
48 #ifdef HAVE_BKTR
49 #include <execinfo.h>
50 #define MAX_BACKTRACE_FRAMES 20
51 #endif
52
53 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
54                         from <syslog.h> which is included by logger.h */
55 #include <syslog.h>
56
57 static int syslog_level_map[] = {
58         LOG_DEBUG,
59         LOG_INFO,    /* arbitrary equivalent of LOG_EVENT */
60         LOG_NOTICE,
61         LOG_WARNING,
62         LOG_ERR,
63         LOG_DEBUG,
64         LOG_DEBUG
65 };
66
67 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
68
69 #undef _ASTERISK_LOGGER_H       /* now include logger.h */
70 #include "asterisk/logger.h"
71 #include "asterisk/lock.h"
72 #include "asterisk/channel.h"
73 #include "asterisk/config.h"
74 #include "asterisk/term.h"
75 #include "asterisk/cli.h"
76 #include "asterisk/utils.h"
77 #include "asterisk/manager.h"
78 #include "asterisk/threadstorage.h"
79 #include "asterisk/strings.h"
80 #include "asterisk/pbx.h"
81 #include "asterisk/app.h"
82
83 #if defined(__linux__) && !defined(__NR_gettid)
84 #include <asm/unistd.h>
85 #endif
86
87 #if defined(__linux__) && defined(__NR_gettid)
88 #define GETTID() syscall(__NR_gettid)
89 #else
90 #define GETTID() getpid()
91 #endif
92
93 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
94
95 static char queue_log_name[256] = QUEUELOG;
96 static char exec_after_rotate[256] = "";
97
98 static int filesize_reload_needed;
99 static int global_logmask = -1;
100
101 enum rotatestrategy {
102         SEQUENTIAL = 1 << 0,     /* Original method - create a new file, in order */
103         ROTATE = 1 << 1,         /* Rotate all files, such that the oldest file has the highest suffix */
104         TIMESTAMP = 1 << 2,      /* Append the epoch timestamp onto the end of the archived file */
105 } rotatestrategy = SEQUENTIAL;
106
107 static struct {
108         unsigned int queue_log:1;
109 } logfiles = { 1 };
110
111 static char hostname[MAXHOSTNAMELEN];
112
113 enum logtypes {
114         LOGTYPE_SYSLOG,
115         LOGTYPE_FILE,
116         LOGTYPE_CONSOLE,
117 };
118
119 struct logchannel {
120         int logmask;                    /* What to log to this channel */
121         int disabled;                   /* If this channel is disabled or not */
122         int facility;                   /* syslog facility */
123         enum logtypes type;             /* Type of log channel */
124         FILE *fileptr;                  /* logfile logging file pointer */
125         char filename[256];             /* Filename */
126         AST_LIST_ENTRY(logchannel) list;
127 };
128
129 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
130
131 enum logmsgtypes {
132         LOGMSG_NORMAL = 0,
133         LOGMSG_VERBOSE,
134 };
135
136 struct logmsg {
137         enum logmsgtypes type;
138         char date[256];
139         int level;
140         char file[80];
141         int line;
142         char function[80];
143         long process_id;
144         AST_LIST_ENTRY(logmsg) list;
145         char str[0];
146 };
147
148 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
149 static pthread_t logthread = AST_PTHREADT_NULL;
150 static ast_cond_t logcond;
151 static int close_logger_thread;
152
153 static FILE *qlog;
154
155 /*! \brief Logging channels used in the Asterisk logging system */
156 static char *levels[] = {
157         "DEBUG",
158         "---EVENT---",          /* no longer used */
159         "NOTICE",
160         "WARNING",
161         "ERROR",
162         "VERBOSE",
163         "DTMF"
164 };
165
166 /*! \brief Colors used in the console for logging */
167 static int colors[] = {
168         COLOR_BRGREEN,
169         COLOR_BRBLUE,
170         COLOR_YELLOW,
171         COLOR_BRRED,
172         COLOR_RED,
173         COLOR_GREEN,
174         COLOR_BRGREEN
175 };
176
177 AST_THREADSTORAGE(verbose_buf);
178 #define VERBOSE_BUF_INIT_SIZE   256
179
180 AST_THREADSTORAGE(log_buf);
181 #define LOG_BUF_INIT_SIZE       256
182
183 static int make_components(const char *s, int lineno)
184 {
185         char *w;
186         int res = 0;
187         char *stringp = ast_strdupa(s);
188
189         while ((w = strsep(&stringp, ","))) {
190                 w = ast_skip_blanks(w);
191                 if (!strcasecmp(w, "error")) 
192                         res |= (1 << __LOG_ERROR);
193                 else if (!strcasecmp(w, "warning"))
194                         res |= (1 << __LOG_WARNING);
195                 else if (!strcasecmp(w, "notice"))
196                         res |= (1 << __LOG_NOTICE);
197                 else if (!strcasecmp(w, "debug"))
198                         res |= (1 << __LOG_DEBUG);
199                 else if (!strcasecmp(w, "verbose"))
200                         res |= (1 << __LOG_VERBOSE);
201                 else if (!strcasecmp(w, "dtmf"))
202                         res |= (1 << __LOG_DTMF);
203                 else {
204                         fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
205                 }
206         }
207
208         return res;
209 }
210
211 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
212 {
213         struct logchannel *chan;
214         char *facility;
215 #ifndef SOLARIS
216         CODE *cptr;
217 #endif
218
219         if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan))))
220                 return NULL;
221
222         if (!strcasecmp(channel, "console")) {
223                 chan->type = LOGTYPE_CONSOLE;
224         } else if (!strncasecmp(channel, "syslog", 6)) {
225                 /*
226                 * syntax is:
227                 *  syslog.facility => level,level,level
228                 */
229                 facility = strchr(channel, '.');
230                 if (!facility++ || !facility) {
231                         facility = "local0";
232                 }
233
234 #ifndef SOLARIS
235                 /*
236                 * Walk through the list of facilitynames (defined in sys/syslog.h)
237                 * to see if we can find the one we have been given
238                 */
239                 chan->facility = -1;
240                 cptr = facilitynames;
241                 while (cptr->c_name) {
242                         if (!strcasecmp(facility, cptr->c_name)) {
243                                 chan->facility = cptr->c_val;
244                                 break;
245                         }
246                         cptr++;
247                 }
248 #else
249                 chan->facility = -1;
250                 if (!strcasecmp(facility, "kern")) 
251                         chan->facility = LOG_KERN;
252                 else if (!strcasecmp(facility, "USER")) 
253                         chan->facility = LOG_USER;
254                 else if (!strcasecmp(facility, "MAIL")) 
255                         chan->facility = LOG_MAIL;
256                 else if (!strcasecmp(facility, "DAEMON")) 
257                         chan->facility = LOG_DAEMON;
258                 else if (!strcasecmp(facility, "AUTH")) 
259                         chan->facility = LOG_AUTH;
260                 else if (!strcasecmp(facility, "SYSLOG")) 
261                         chan->facility = LOG_SYSLOG;
262                 else if (!strcasecmp(facility, "LPR")) 
263                         chan->facility = LOG_LPR;
264                 else if (!strcasecmp(facility, "NEWS")) 
265                         chan->facility = LOG_NEWS;
266                 else if (!strcasecmp(facility, "UUCP")) 
267                         chan->facility = LOG_UUCP;
268                 else if (!strcasecmp(facility, "CRON")) 
269                         chan->facility = LOG_CRON;
270                 else if (!strcasecmp(facility, "LOCAL0")) 
271                         chan->facility = LOG_LOCAL0;
272                 else if (!strcasecmp(facility, "LOCAL1")) 
273                         chan->facility = LOG_LOCAL1;
274                 else if (!strcasecmp(facility, "LOCAL2")) 
275                         chan->facility = LOG_LOCAL2;
276                 else if (!strcasecmp(facility, "LOCAL3")) 
277                         chan->facility = LOG_LOCAL3;
278                 else if (!strcasecmp(facility, "LOCAL4")) 
279                         chan->facility = LOG_LOCAL4;
280                 else if (!strcasecmp(facility, "LOCAL5")) 
281                         chan->facility = LOG_LOCAL5;
282                 else if (!strcasecmp(facility, "LOCAL6")) 
283                         chan->facility = LOG_LOCAL6;
284                 else if (!strcasecmp(facility, "LOCAL7")) 
285                         chan->facility = LOG_LOCAL7;
286 #endif /* Solaris */
287
288                 if (0 > chan->facility) {
289                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
290                         ast_free(chan);
291                         return NULL;
292                 }
293
294                 chan->type = LOGTYPE_SYSLOG;
295                 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
296                 openlog("asterisk", LOG_PID, chan->facility);
297         } else {
298                 if (!ast_strlen_zero(hostname)) {
299                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
300                                  channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
301                 } else {
302                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
303                                  channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
304                 }
305                 chan->fileptr = fopen(chan->filename, "a");
306                 if (!chan->fileptr) {
307                         /* Can't log here, since we're called with a lock */
308                         fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
309                 } 
310                 chan->type = LOGTYPE_FILE;
311         }
312         chan->logmask = make_components(components, lineno);
313         return chan;
314 }
315
316 static void init_logger_chain(int locked)
317 {
318         struct logchannel *chan;
319         struct ast_config *cfg;
320         struct ast_variable *var;
321         const char *s;
322         struct ast_flags config_flags = { 0 };
323
324         if (!(cfg = ast_config_load2("logger.conf", "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID)
325                 return;
326
327         /* delete our list of log channels */
328         if (!locked)
329                 AST_RWLIST_WRLOCK(&logchannels);
330         while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
331                 ast_free(chan);
332         if (!locked)
333                 AST_RWLIST_UNLOCK(&logchannels);
334         
335         global_logmask = 0;
336         errno = 0;
337         /* close syslog */
338         closelog();
339         
340         /* If no config file, we're fine, set default options. */
341         if (!cfg) {
342                 if (errno)
343                         fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
344                 else
345                         fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
346                 if (!(chan = ast_calloc(1, sizeof(*chan))))
347                         return;
348                 chan->type = LOGTYPE_CONSOLE;
349                 chan->logmask = 28; /*warning,notice,error */
350                 if (!locked)
351                         AST_RWLIST_WRLOCK(&logchannels);
352                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
353                 if (!locked)
354                         AST_RWLIST_UNLOCK(&logchannels);
355                 global_logmask |= chan->logmask;
356                 return;
357         }
358         
359         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
360                 if (ast_true(s)) {
361                         if (gethostname(hostname, sizeof(hostname) - 1)) {
362                                 ast_copy_string(hostname, "unknown", sizeof(hostname));
363                                 fprintf(stderr, "What box has no hostname???\n");
364                         }
365                 } else
366                         hostname[0] = '\0';
367         } else
368                 hostname[0] = '\0';
369         if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
370                 ast_copy_string(dateformat, s, sizeof(dateformat));
371         else
372                 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
373         if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
374                 logfiles.queue_log = ast_true(s);
375         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
376                 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
377         if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
378                 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
379         if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
380                 if (strcasecmp(s, "timestamp") == 0)
381                         rotatestrategy = TIMESTAMP;
382                 else if (strcasecmp(s, "rotate") == 0)
383                         rotatestrategy = ROTATE;
384                 else if (strcasecmp(s, "sequential") == 0)
385                         rotatestrategy = SEQUENTIAL;
386                 else
387                         fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
388         } else {
389                 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
390                         rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
391                         fprintf(stderr, "rotatetimestamp option has been deprecated.  Please use rotatestrategy instead.\n");
392                 }
393         }
394
395         if (!locked)
396                 AST_RWLIST_WRLOCK(&logchannels);
397         var = ast_variable_browse(cfg, "logfiles");
398         for (; var; var = var->next) {
399                 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
400                         continue;
401                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
402                 global_logmask |= chan->logmask;
403         }
404         if (!locked)
405                 AST_RWLIST_UNLOCK(&logchannels);
406
407         ast_config_destroy(cfg);
408 }
409
410 void ast_child_verbose(int level, const char *fmt, ...)
411 {
412         char *msg = NULL, *emsg = NULL, *sptr, *eptr;
413         va_list ap, aq;
414         int size;
415
416         /* Don't bother, if the level isn't that high */
417         if (option_verbose < level) {
418                 return;
419         }
420
421         va_start(ap, fmt);
422         va_copy(aq, ap);
423         if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
424                 va_end(ap);
425                 va_end(aq);
426                 return;
427         }
428         va_end(ap);
429
430         if (!(msg = ast_malloc(size + 1))) {
431                 va_end(aq);
432                 return;
433         }
434
435         vsnprintf(msg, size + 1, fmt, aq);
436         va_end(aq);
437
438         if (!(emsg = ast_malloc(size * 2 + 1))) {
439                 ast_free(msg);
440                 return;
441         }
442
443         for (sptr = msg, eptr = emsg; ; sptr++) {
444                 if (*sptr == '"') {
445                         *eptr++ = '\\';
446                 }
447                 *eptr++ = *sptr;
448                 if (*sptr == '\0') {
449                         break;
450                 }
451         }
452         ast_free(msg);
453
454         fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
455         fflush(stdout);
456         ast_free(emsg);
457 }
458
459 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
460 {
461         va_list ap;
462         char qlog_msg[8192];
463         int qlog_len;
464         char time_str[16];
465
466         if (ast_check_realtime("queue_log")) {
467                 va_start(ap, fmt);
468                 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
469                 va_end(ap);
470                 snprintf(time_str, sizeof(time_str), "%ld", (long)time(NULL));
471                 ast_store_realtime("queue_log", "time", time_str, 
472                                                 "callid", callid, 
473                                                 "queuename", queuename, 
474                                                 "agent", agent, 
475                                                 "event", event,
476                                                 "data", qlog_msg,
477                                                 SENTINEL);
478         } else {
479                 if (qlog) {
480                         va_start(ap, fmt);
481                         qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
482                         vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
483                         va_end(ap);
484                 }
485                 AST_RWLIST_RDLOCK(&logchannels);
486                 if (qlog) {
487                         fprintf(qlog, "%s\n", qlog_msg);
488                         fflush(qlog);
489                 }
490                 AST_RWLIST_UNLOCK(&logchannels);
491         }
492 }
493
494 static int rotate_file(const char *filename)
495 {
496         char old[PATH_MAX];
497         char new[PATH_MAX];
498         int x, y, which, found, res = 0, fd;
499         char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
500
501         switch (rotatestrategy) {
502         case SEQUENTIAL:
503                 for (x = 0; ; x++) {
504                         snprintf(new, sizeof(new), "%s.%d", filename, x);
505                         fd = open(new, O_RDONLY);
506                         if (fd > -1)
507                                 close(fd);
508                         else
509                                 break;
510                 }
511                 if (rename(filename, new)) {
512                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
513                         res = -1;
514                 }
515                 break;
516         case TIMESTAMP:
517                 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
518                 if (rename(filename, new)) {
519                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
520                         res = -1;
521                 }
522                 break;
523         case ROTATE:
524                 /* Find the next empty slot, including a possible suffix */
525                 for (x = 0; ; x++) {
526                         found = 0;
527                         for (which = 0; which < ARRAY_LEN(suffixes); which++) {
528                                 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
529                                 fd = open(new, O_RDONLY);
530                                 if (fd > -1) {
531                                         close(fd);
532                                         found = 1;
533                                         break;
534                                 }
535                         }
536                         if (!found) {
537                                 break;
538                         }
539                 }
540
541                 /* Found an empty slot */
542                 for (y = x; y > 0; y--) {
543                         for (which = 0; which < ARRAY_LEN(suffixes); which++) {
544                                 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
545                                 fd = open(old, O_RDONLY);
546                                 if (fd > -1) {
547                                         /* Found the right suffix */
548                                         close(fd);
549                                         snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
550                                         if (rename(old, new)) {
551                                                 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
552                                                 res = -1;
553                                         }
554                                         break;
555                                 }
556                         }
557                 }
558
559                 /* Finally, rename the current file */
560                 snprintf(new, sizeof(new), "%s.0", filename);
561                 if (rename(filename, new)) {
562                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
563                         res = -1;
564                 }
565         }
566
567         if (!ast_strlen_zero(exec_after_rotate)) {
568                 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
569                 char buf[512];
570                 pbx_builtin_setvar_helper(c, "filename", filename);
571                 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
572                 if (ast_safe_system(buf) != -1) {
573                         ast_log(LOG_WARNING, "error executing '%s'\n", buf);
574                 }
575                 c = ast_channel_release(c);
576         }
577         return res;
578 }
579
580 static int reload_logger(int rotate)
581 {
582         char old[PATH_MAX] = "";
583         int queue_rotate = rotate;
584         struct logchannel *f;
585         int res = 0;
586         struct stat st;
587
588         AST_RWLIST_WRLOCK(&logchannels);
589
590         if (qlog) {
591                 if (rotate < 0) {
592                         /* Check filesize - this one typically doesn't need an auto-rotate */
593                         snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
594                         if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
595                                 fclose(qlog);
596                                 qlog = NULL;
597                         } else
598                                 queue_rotate = 0;
599                 } else {
600                         fclose(qlog);
601                         qlog = NULL;
602                 }
603         } else 
604                 queue_rotate = 0;
605
606         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
607
608         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
609                 if (f->disabled) {
610                         f->disabled = 0;        /* Re-enable logging at reload */
611                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
612                 }
613                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
614                         fclose(f->fileptr);     /* Close file */
615                         f->fileptr = NULL;
616                         if (rotate)
617                                 rotate_file(f->filename);
618                 }
619         }
620
621         filesize_reload_needed = 0;
622
623         init_logger_chain(1 /* locked */);
624
625         if (logfiles.queue_log) {
626                 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
627                 if (queue_rotate)
628                         rotate_file(old);
629
630                 qlog = fopen(old, "a");
631                 if (qlog) {
632                         AST_RWLIST_UNLOCK(&logchannels);
633                         ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
634                         AST_RWLIST_WRLOCK(&logchannels);
635                         ast_verb(1, "Asterisk Queue Logger restarted\n");
636                 } else {
637                         ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
638                         res = -1;
639                 }
640         }
641
642         AST_RWLIST_UNLOCK(&logchannels);
643
644         return res;
645 }
646
647 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
648         a full Asterisk reload) */
649 int logger_reload(void)
650 {
651         if(reload_logger(0))
652                 return RESULT_FAILURE;
653         return RESULT_SUCCESS;
654 }
655
656 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
657 {
658         switch (cmd) {
659         case CLI_INIT:
660                 e->command = "logger reload";
661                 e->usage = 
662                         "Usage: logger reload\n"
663                         "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
664                 return NULL;
665         case CLI_GENERATE:
666                 return NULL;
667         }
668         if (reload_logger(0)) {
669                 ast_cli(a->fd, "Failed to reload the logger\n");
670                 return CLI_FAILURE;
671         }
672         return CLI_SUCCESS;
673 }
674
675 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
676 {
677         switch (cmd) {
678         case CLI_INIT:
679                 e->command = "logger rotate";
680                 e->usage = 
681                         "Usage: logger rotate\n"
682                         "       Rotates and Reopens the log files.\n";
683                 return NULL;
684         case CLI_GENERATE:
685                 return NULL;    
686         }
687         if (reload_logger(1)) {
688                 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
689                 return CLI_FAILURE;
690         } 
691         return CLI_SUCCESS;
692 }
693
694 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
695 {
696         int x;
697         int state;
698         int level = -1;
699
700         switch (cmd) {
701         case CLI_INIT:
702                 e->command = "logger set level";
703                 e->usage = 
704                         "Usage: logger set level\n"
705                         "       Set a specific log level to enabled/disabled for this console.\n";
706                 return NULL;
707         case CLI_GENERATE:
708                 return NULL;
709         }
710
711         if (a->argc < 5)
712                 return CLI_SHOWUSAGE;
713
714         for (x = 0; x <= NUMLOGLEVELS; x++) {
715                 if (!strcasecmp(a->argv[3], levels[x])) {
716                         level = x;
717                         break;
718                 }
719         }
720
721         state = ast_true(a->argv[4]) ? 1 : 0;
722
723         if (level != -1) {
724                 ast_console_toggle_loglevel(a->fd, level, state);
725                 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
726         } else
727                 return CLI_SHOWUSAGE;
728
729         return CLI_SUCCESS;
730 }
731
732 /*! \brief CLI command to show logging system configuration */
733 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
734 {
735 #define FORMATL "%-35.35s %-8.8s %-9.9s "
736         struct logchannel *chan;
737         switch (cmd) {
738         case CLI_INIT:
739                 e->command = "logger show channels";
740                 e->usage = 
741                         "Usage: logger show channels\n"
742                         "       List configured logger channels.\n";
743                 return NULL;
744         case CLI_GENERATE:
745                 return NULL;    
746         }
747         ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
748         ast_cli(a->fd, "Configuration\n");
749         ast_cli(a->fd, FORMATL, "-------", "----", "------");
750         ast_cli(a->fd, "-------------\n");
751         AST_RWLIST_RDLOCK(&logchannels);
752         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
753                 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
754                         chan->disabled ? "Disabled" : "Enabled");
755                 ast_cli(a->fd, " - ");
756                 if (chan->logmask & (1 << __LOG_DEBUG)) 
757                         ast_cli(a->fd, "Debug ");
758                 if (chan->logmask & (1 << __LOG_DTMF)) 
759                         ast_cli(a->fd, "DTMF ");
760                 if (chan->logmask & (1 << __LOG_VERBOSE)) 
761                         ast_cli(a->fd, "Verbose ");
762                 if (chan->logmask & (1 << __LOG_WARNING)) 
763                         ast_cli(a->fd, "Warning ");
764                 if (chan->logmask & (1 << __LOG_NOTICE)) 
765                         ast_cli(a->fd, "Notice ");
766                 if (chan->logmask & (1 << __LOG_ERROR)) 
767                         ast_cli(a->fd, "Error ");
768                 ast_cli(a->fd, "\n");
769         }
770         AST_RWLIST_UNLOCK(&logchannels);
771         ast_cli(a->fd, "\n");
772                 
773         return CLI_SUCCESS;
774 }
775
776 struct verb {
777         void (*verboser)(const char *string);
778         AST_LIST_ENTRY(verb) list;
779 };
780
781 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
782
783 static struct ast_cli_entry cli_logger[] = {
784         AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
785         AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
786         AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
787         AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
788 };
789
790 static int handle_SIGXFSZ(int sig) 
791 {
792         /* Indicate need to reload */
793         filesize_reload_needed = 1;
794         return 0;
795 }
796
797 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str, long pid)
798 {
799         char buf[BUFSIZ];
800
801         if (level >= SYSLOG_NLEVELS) {
802                 /* we are locked here, so cannot ast_log() */
803                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
804                 return;
805         }
806
807         if (level == __LOG_VERBOSE) {
808                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", pid, str);
809                 level = __LOG_DEBUG;
810         } else if (level == __LOG_DTMF) {
811                 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", pid, str);
812                 level = __LOG_DEBUG;
813         } else {
814                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
815                          levels[level], pid, file, line, function, str);
816         }
817
818         term_strip(buf, buf, strlen(buf) + 1);
819         syslog(syslog_level_map[level], "%s", buf);
820 }
821
822 /*! \brief Print a normal log message to the channels */
823 static void logger_print_normal(struct logmsg *logmsg)
824 {
825         struct logchannel *chan = NULL;
826         char buf[BUFSIZ];
827
828         AST_RWLIST_RDLOCK(&logchannels);
829
830         if (!AST_RWLIST_EMPTY(&logchannels)) {
831                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
832                         /* If the channel is disabled, then move on to the next one */
833                         if (chan->disabled)
834                                 continue;
835                         /* Check syslog channels */
836                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
837                                 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str, logmsg->process_id);
838                         /* Console channels */
839                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
840                                 char linestr[128];
841                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
842
843                                 /* If the level is verbose, then skip it */
844                                 if (logmsg->level == __LOG_VERBOSE)
845                                         continue;
846
847                                 /* Turn the numerical line number into a string */
848                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
849                                 /* Build string to print out */
850                                 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
851                                          logmsg->date,
852                                          term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
853                                          logmsg->process_id,
854                                          term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
855                                          term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
856                                          term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
857                                          logmsg->str);
858                                 /* Print out */
859                                 ast_console_puts_mutable(buf, logmsg->level);
860                         /* File channels */
861                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
862                                 int res = 0;
863
864                                 /* If no file pointer exists, skip it */
865                                 if (!chan->fileptr)
866                                         continue;
867                                 
868                                 /* Print out to the file */
869                                 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
870                                               logmsg->date, levels[logmsg->level], logmsg->process_id, logmsg->file, logmsg->str);
871                                 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
872                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
873                                         if (errno == ENOMEM || errno == ENOSPC)
874                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
875                                         else
876                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
877                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
878                                         chan->disabled = 1;
879                                 } else if (res > 0) {
880                                         fflush(chan->fileptr);
881                                 }
882                         }
883                 }
884         } else if (logmsg->level != __LOG_VERBOSE) {
885                 fputs(logmsg->str, stdout);
886         }
887
888         AST_RWLIST_UNLOCK(&logchannels);
889
890         /* If we need to reload because of the file size, then do so */
891         if (filesize_reload_needed) {
892                 reload_logger(-1);
893                 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
894         }
895
896         return;
897 }
898
899 /*! \brief Print a verbose message to the verbosers */
900 static void logger_print_verbose(struct logmsg *logmsg)
901 {
902         struct verb *v = NULL;
903
904         /* Iterate through the list of verbosers and pass them the log message string */
905         AST_RWLIST_RDLOCK(&verbosers);
906         AST_RWLIST_TRAVERSE(&verbosers, v, list)
907                 v->verboser(logmsg->str);
908         AST_RWLIST_UNLOCK(&verbosers);
909
910         return;
911 }
912
913 /*! \brief Actual logging thread */
914 static void *logger_thread(void *data)
915 {
916         struct logmsg *next = NULL, *msg = NULL;
917
918         for (;;) {
919                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
920                 AST_LIST_LOCK(&logmsgs);
921                 if (AST_LIST_EMPTY(&logmsgs)) {
922                         if (close_logger_thread) {
923                                 break;
924                         } else {
925                                 ast_cond_wait(&logcond, &logmsgs.lock);
926                         }
927                 }
928                 next = AST_LIST_FIRST(&logmsgs);
929                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
930                 AST_LIST_UNLOCK(&logmsgs);
931
932                 /* Otherwise go through and process each message in the order added */
933                 while ((msg = next)) {
934                         /* Get the next entry now so that we can free our current structure later */
935                         next = AST_LIST_NEXT(msg, list);
936
937                         /* Depending on the type, send it to the proper function */
938                         if (msg->type == LOGMSG_NORMAL)
939                                 logger_print_normal(msg);
940                         else if (msg->type == LOGMSG_VERBOSE)
941                                 logger_print_verbose(msg);
942
943                         /* Free the data since we are done */
944                         ast_free(msg);
945                 }
946
947                 /* If we should stop, then stop */
948                 if (close_logger_thread)
949                         break;
950         }
951
952         return NULL;
953 }
954
955 int init_logger(void)
956 {
957         char tmp[256];
958         int res = 0;
959
960         /* auto rotate if sig SIGXFSZ comes a-knockin */
961         (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
962
963         /* start logger thread */
964         ast_cond_init(&logcond, NULL);
965         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
966                 ast_cond_destroy(&logcond);
967                 return -1;
968         }
969
970         /* register the logger cli commands */
971         ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
972
973         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
974   
975         /* create log channels */
976         init_logger_chain(0 /* locked */);
977
978         if (logfiles.queue_log) {
979                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
980                 qlog = fopen(tmp, "a");
981                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
982         }
983         return res;
984 }
985
986 void close_logger(void)
987 {
988         struct logchannel *f = NULL;
989
990         /* Stop logger thread */
991         AST_LIST_LOCK(&logmsgs);
992         close_logger_thread = 1;
993         ast_cond_signal(&logcond);
994         AST_LIST_UNLOCK(&logmsgs);
995
996         if (logthread != AST_PTHREADT_NULL)
997                 pthread_join(logthread, NULL);
998
999         AST_RWLIST_WRLOCK(&logchannels);
1000
1001         if (qlog) {
1002                 fclose(qlog);
1003                 qlog = NULL;
1004         }
1005
1006         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1007                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1008                         fclose(f->fileptr);
1009                         f->fileptr = NULL;
1010                 }
1011         }
1012
1013         closelog(); /* syslog */
1014
1015         AST_RWLIST_UNLOCK(&logchannels);
1016
1017         return;
1018 }
1019
1020 /*!
1021  * \brief send log messages to syslog and/or the console
1022  */
1023 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1024 {
1025         struct logmsg *logmsg = NULL;
1026         struct ast_str *buf = NULL;
1027         struct ast_tm tm;
1028         struct timeval now = ast_tvnow();
1029         int res = 0;
1030         va_list ap;
1031
1032         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1033                 return;
1034
1035         if (AST_RWLIST_EMPTY(&logchannels)) {
1036                 /*
1037                  * we don't have the logger chain configured yet,
1038                  * so just log to stdout
1039                  */
1040                 if (level != __LOG_VERBOSE) {
1041                         int result;
1042                         va_start(ap, fmt);
1043                         result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1044                         va_end(ap);
1045                         if (result != AST_DYNSTR_BUILD_FAILED) {
1046                                 term_filter_escapes(ast_str_buffer(buf));
1047                                 fputs(ast_str_buffer(buf), stdout);
1048                         }
1049                 }
1050                 return;
1051         }
1052         
1053         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1054            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1055            is zero, if option_verbose is non-zero (this allows for 'level zero'
1056            LOG_DEBUG messages to be displayed, if the logmask on any channel
1057            allows it)
1058         */
1059         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1060                 return;
1061
1062         /* Ignore anything that never gets logged anywhere */
1063         if (!(global_logmask & (1 << level)))
1064                 return;
1065         
1066         /* Build string */
1067         va_start(ap, fmt);
1068         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1069         va_end(ap);
1070
1071         /* If the build failed, then abort and free this structure */
1072         if (res == AST_DYNSTR_BUILD_FAILED)
1073                 return;
1074
1075         /* Create a new logging message */
1076         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1077                 return;
1078
1079         /* Copy string over */
1080         strcpy(logmsg->str, ast_str_buffer(buf));
1081
1082         /* Set type to be normal */
1083         logmsg->type = LOGMSG_NORMAL;
1084
1085         /* Create our date/time */
1086         ast_localtime(&now, &tm, NULL);
1087         ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1088
1089         /* Copy over data */
1090         logmsg->level = level;
1091         logmsg->line = line;
1092         ast_copy_string(logmsg->file, file, sizeof(logmsg->file));
1093         ast_copy_string(logmsg->function, function, sizeof(logmsg->function));
1094         logmsg->process_id = (long) GETTID();
1095
1096         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1097         if (logthread != AST_PTHREADT_NULL) {
1098                 AST_LIST_LOCK(&logmsgs);
1099                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1100                 ast_cond_signal(&logcond);
1101                 AST_LIST_UNLOCK(&logmsgs);
1102         } else {
1103                 logger_print_normal(logmsg);
1104                 ast_free(logmsg);
1105         }
1106
1107         return;
1108 }
1109
1110 #ifdef HAVE_BKTR
1111
1112 struct ast_bt *ast_bt_create(void) 
1113 {
1114         struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1115         if (!bt) {
1116                 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1117                 return NULL;
1118         }
1119
1120         bt->alloced = 1;
1121
1122         ast_bt_get_addresses(bt);
1123
1124         return bt;
1125 }
1126
1127 int ast_bt_get_addresses(struct ast_bt *bt)
1128 {
1129         bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1130
1131         return 0;
1132 }
1133
1134 void *ast_bt_destroy(struct ast_bt *bt)
1135 {
1136         if (bt->alloced) {
1137                 ast_free(bt);
1138         }
1139
1140         return NULL;
1141 }
1142
1143 #endif /* HAVE_BKTR */
1144
1145 void ast_backtrace(void)
1146 {
1147 #ifdef HAVE_BKTR
1148         struct ast_bt *bt;
1149         int i = 0;
1150         char **strings;
1151
1152         if (!(bt = ast_bt_create())) {
1153                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1154                 return;
1155         }
1156
1157         if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1158                 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1159                 for (i = 0; i < bt->num_frames; i++) {
1160                         ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1161                 }
1162                 free(strings);
1163         } else {
1164                 ast_debug(1, "Could not allocate memory for backtrace\n");
1165         }
1166         ast_bt_destroy(bt);
1167 #else
1168         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1169 #endif
1170 }
1171
1172 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1173 {
1174         struct logmsg *logmsg = NULL;
1175         struct ast_str *buf = NULL;
1176         int res = 0;
1177
1178         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1179                 return;
1180
1181         if (ast_opt_timestamp) {
1182                 struct timeval now;
1183                 struct ast_tm tm;
1184                 char date[40];
1185                 char *datefmt;
1186
1187                 now = ast_tvnow();
1188                 ast_localtime(&now, &tm, NULL);
1189                 ast_strftime(date, sizeof(date), dateformat, &tm);
1190                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1191                 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1192                 fmt = datefmt;
1193         } else {
1194                 char *tmp = alloca(strlen(fmt) + 2);
1195                 sprintf(tmp, "%c%s", 127, fmt);
1196                 fmt = tmp;
1197         }
1198
1199         /* Build string */
1200         res = ast_str_set_va(&buf, 0, fmt, ap);
1201
1202         /* If the build failed then we can drop this allocated message */
1203         if (res == AST_DYNSTR_BUILD_FAILED)
1204                 return;
1205
1206         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1207                 return;
1208
1209         strcpy(logmsg->str, ast_str_buffer(buf));
1210
1211         ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->str + 1);
1212
1213         /* Set type */
1214         logmsg->type = LOGMSG_VERBOSE;
1215         
1216         /* Add to the list and poke the thread if possible */
1217         if (logthread != AST_PTHREADT_NULL) {
1218                 AST_LIST_LOCK(&logmsgs);
1219                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1220                 ast_cond_signal(&logcond);
1221                 AST_LIST_UNLOCK(&logmsgs);
1222         } else {
1223                 logger_print_verbose(logmsg);
1224                 ast_free(logmsg);
1225         }
1226 }
1227
1228 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1229 {
1230         va_list ap;
1231         va_start(ap, fmt);
1232         __ast_verbose_ap(file, line, func, fmt, ap);
1233         va_end(ap);
1234 }
1235
1236 /* No new code should use this directly, but we have the ABI for backwards compat */
1237 #undef ast_verbose
1238 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1239 void ast_verbose(const char *fmt, ...)
1240 {
1241         va_list ap;
1242         va_start(ap, fmt);
1243         __ast_verbose_ap("", 0, "", fmt, ap);
1244         va_end(ap);
1245 }
1246
1247 int ast_register_verbose(void (*v)(const char *string)) 
1248 {
1249         struct verb *verb;
1250
1251         if (!(verb = ast_malloc(sizeof(*verb))))
1252                 return -1;
1253
1254         verb->verboser = v;
1255
1256         AST_RWLIST_WRLOCK(&verbosers);
1257         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1258         AST_RWLIST_UNLOCK(&verbosers);
1259         
1260         return 0;
1261 }
1262
1263 int ast_unregister_verbose(void (*v)(const char *string))
1264 {
1265         struct verb *cur;
1266
1267         AST_RWLIST_WRLOCK(&verbosers);
1268         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1269                 if (cur->verboser == v) {
1270                         AST_RWLIST_REMOVE_CURRENT(list);
1271                         ast_free(cur);
1272                         break;
1273                 }
1274         }
1275         AST_RWLIST_TRAVERSE_SAFE_END;
1276         AST_RWLIST_UNLOCK(&verbosers);
1277         
1278         return cur ? 0 : -1;
1279 }