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