(closes issue #10192)
[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(void)
309 {
310         struct logchannel *chan;
311         struct ast_config *cfg;
312         struct ast_variable *var;
313         const char *s;
314
315         /* delete our list of log channels */
316         AST_RWLIST_WRLOCK(&logchannels);
317         while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
318                 free(chan);
319         AST_RWLIST_UNLOCK(&logchannels);
320         
321         global_logmask = 0;
322         errno = 0;
323         /* close syslog */
324         closelog();
325         
326         cfg = ast_config_load("logger.conf");
327         
328         /* If no config file, we're fine, set default options. */
329         if (!cfg) {
330                 if (errno)
331                         fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
332                 else
333                         fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
334                 if (!(chan = ast_calloc(1, sizeof(*chan))))
335                         return;
336                 chan->type = LOGTYPE_CONSOLE;
337                 chan->logmask = 28; /*warning,notice,error */
338                 AST_RWLIST_WRLOCK(&logchannels);
339                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
340                 AST_RWLIST_UNLOCK(&logchannels);
341                 global_logmask |= chan->logmask;
342                 return;
343         }
344         
345         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
346                 if (ast_true(s)) {
347                         if (gethostname(hostname, sizeof(hostname) - 1)) {
348                                 ast_copy_string(hostname, "unknown", sizeof(hostname));
349                                 ast_log(LOG_WARNING, "What box has no hostname???\n");
350                         }
351                 } else
352                         hostname[0] = '\0';
353         } else
354                 hostname[0] = '\0';
355         if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
356                 ast_copy_string(dateformat, s, sizeof(dateformat));
357         else
358                 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
359         if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
360                 logfiles.queue_log = ast_true(s);
361         if ((s = ast_variable_retrieve(cfg, "general", "event_log")))
362                 logfiles.event_log = ast_true(s);
363         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
364                 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
365         if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp")))
366                 rotatetimestamp = ast_true(s);
367
368         AST_RWLIST_WRLOCK(&logchannels);
369         var = ast_variable_browse(cfg, "logfiles");
370         for (; var; var = var->next) {
371                 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
372                         continue;
373                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
374                 global_logmask |= chan->logmask;
375         }
376         AST_RWLIST_UNLOCK(&logchannels);
377
378         ast_config_destroy(cfg);
379 }
380
381 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
382 {
383         va_list ap;
384         char qlog_msg[8192];
385         int qlog_len;
386         if (qlog) {
387                 va_start(ap, fmt);
388                 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
389                 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
390                 va_end(ap);
391         }
392         AST_RWLIST_RDLOCK(&logchannels);
393         if (qlog) {
394                 fprintf(qlog, "%s\n", qlog_msg);
395                 fflush(qlog);
396         }
397         AST_RWLIST_UNLOCK(&logchannels);
398 }
399
400 int reload_logger(int rotate)
401 {
402         char old[PATH_MAX] = "";
403         char new[PATH_MAX];
404         int event_rotate = rotate, queue_rotate = rotate;
405         struct logchannel *f;
406         FILE *myf;
407         int x, res = 0;
408
409         AST_RWLIST_WRLOCK(&logchannels);
410
411         if (eventlog) 
412                 fclose(eventlog);
413         else 
414                 event_rotate = 0;
415         eventlog = NULL;
416
417         if (qlog) 
418                 fclose(qlog);
419         else 
420                 queue_rotate = 0;
421         qlog = NULL;
422
423         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
424
425         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
426                 if (f->disabled) {
427                         f->disabled = 0;        /* Re-enable logging at reload */
428                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
429                 }
430                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
431                         fclose(f->fileptr);     /* Close file */
432                         f->fileptr = NULL;
433                         if (rotate) {
434                                 ast_copy_string(old, f->filename, sizeof(old));
435                                 
436                                 if (!rotatetimestamp) { 
437                                         for (x = 0; ; x++) {
438                                                 snprintf(new, sizeof(new), "%s.%d", f->filename, x);
439                                                 myf = fopen(new, "r");
440                                                 if (myf)
441                                                         fclose(myf);
442                                                 else
443                                                         break;
444                                         }
445                                 } else 
446                                         snprintf(new, sizeof(new), "%s.%ld", f->filename, (long)time(NULL));
447
448                                 /* do it */
449                                 if (rename(old,new))
450                                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
451                         }
452                 }
453         }
454
455         filesize_reload_needed = 0;
456         
457         init_logger_chain();
458
459         if (logfiles.event_log) {
460                 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
461                 if (event_rotate) {
462                         if (!rotatetimestamp) { 
463                                 for (x=0;;x++) {
464                                         snprintf(new, sizeof(new), "%s/%s.%d", ast_config_AST_LOG_DIR, EVENTLOG,x);
465                                         myf = fopen(new, "r");
466                                         if (myf)        /* File exists */
467                                                 fclose(myf);
468                                         else
469                                                 break;
470                                 }
471                         } else 
472                                 snprintf(new, sizeof(new), "%s/%s.%ld", ast_config_AST_LOG_DIR, EVENTLOG,(long)time(NULL));
473         
474                         /* do it */
475                         if (rename(old,new))
476                                 ast_log(LOG_ERROR, "Unable to rename file '%s' to '%s'\n", old, new);
477                 }
478
479                 eventlog = fopen(old, "a");
480                 if (eventlog) {
481                         ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
482                         if (option_verbose)
483                                 ast_verbose("Asterisk Event Logger restarted\n");
484                 } else {
485                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
486                         res = -1;
487                 }
488         }
489
490         if (logfiles.queue_log) {
491                 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
492                 if (queue_rotate) {
493                         if (!rotatetimestamp) { 
494                                 for (x = 0; ; x++) {
495                                         snprintf(new, sizeof(new), "%s/%s.%d", ast_config_AST_LOG_DIR, queue_log_name, x);
496                                         myf = fopen(new, "r");
497                                         if (myf)        /* File exists */
498                                                 fclose(myf);
499                                         else
500                                                 break;
501                                 }
502         
503                         } else 
504                                 snprintf(new, sizeof(new), "%s/%s.%ld", ast_config_AST_LOG_DIR, queue_log_name,(long)time(NULL));
505                         /* do it */
506                         if (rename(old, new))
507                                 ast_log(LOG_ERROR, "Unable to rename file '%s' to '%s'\n", old, new);
508                 }
509
510                 qlog = fopen(old, "a");
511                 if (qlog) {
512                         ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
513                         ast_log(LOG_EVENT, "Restarted Asterisk Queue Logger\n");
514                         if (option_verbose)
515                                 ast_verbose("Asterisk Queue Logger restarted\n");
516                 } else {
517                         ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
518                         res = -1;
519                 }
520         }
521
522         AST_RWLIST_UNLOCK(&logchannels);
523
524         return res;
525 }
526
527 static int handle_logger_reload(int fd, int argc, char *argv[])
528 {
529         if (reload_logger(0)) {
530                 ast_cli(fd, "Failed to reload the logger\n");
531                 return RESULT_FAILURE;
532         } else
533                 return RESULT_SUCCESS;
534 }
535
536 static int handle_logger_rotate(int fd, int argc, char *argv[])
537 {
538         if (reload_logger(1)) {
539                 ast_cli(fd, "Failed to reload the logger and rotate log files\n");
540                 return RESULT_FAILURE;
541         } else
542                 return RESULT_SUCCESS;
543 }
544
545 /*! \brief CLI command to show logging system configuration */
546 static int handle_logger_show_channels(int fd, int argc, char *argv[])
547 {
548 #define FORMATL "%-35.35s %-8.8s %-9.9s "
549         struct logchannel *chan;
550
551         ast_cli(fd,FORMATL, "Channel", "Type", "Status");
552         ast_cli(fd, "Configuration\n");
553         ast_cli(fd,FORMATL, "-------", "----", "------");
554         ast_cli(fd, "-------------\n");
555         AST_RWLIST_RDLOCK(&logchannels);
556         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
557                 ast_cli(fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
558                         chan->disabled ? "Disabled" : "Enabled");
559                 ast_cli(fd, " - ");
560                 if (chan->logmask & (1 << __LOG_DEBUG)) 
561                         ast_cli(fd, "Debug ");
562                 if (chan->logmask & (1 << __LOG_DTMF)) 
563                         ast_cli(fd, "DTMF ");
564                 if (chan->logmask & (1 << __LOG_VERBOSE)) 
565                         ast_cli(fd, "Verbose ");
566                 if (chan->logmask & (1 << __LOG_WARNING)) 
567                         ast_cli(fd, "Warning ");
568                 if (chan->logmask & (1 << __LOG_NOTICE)) 
569                         ast_cli(fd, "Notice ");
570                 if (chan->logmask & (1 << __LOG_ERROR)) 
571                         ast_cli(fd, "Error ");
572                 if (chan->logmask & (1 << __LOG_EVENT)) 
573                         ast_cli(fd, "Event ");
574                 ast_cli(fd, "\n");
575         }
576         AST_RWLIST_UNLOCK(&logchannels);
577         ast_cli(fd, "\n");
578                 
579         return RESULT_SUCCESS;
580 }
581
582 struct verb {
583         void (*verboser)(const char *string);
584         AST_LIST_ENTRY(verb) list;
585 };
586
587 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
588
589 static char logger_reload_help[] =
590 "Usage: logger reload\n"
591 "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
592
593 static char logger_rotate_help[] =
594 "Usage: logger rotate\n"
595 "       Rotates and Reopens the log files.\n";
596
597 static char logger_show_channels_help[] =
598 "Usage: logger show channels\n"
599 "       List configured logger channels.\n";
600
601 static struct ast_cli_entry cli_logger[] = {
602         { { "logger", "show", "channels", NULL }, 
603         handle_logger_show_channels, "List configured log channels",
604         logger_show_channels_help },
605
606         { { "logger", "reload", NULL }, 
607         handle_logger_reload, "Reopens the log files",
608         logger_reload_help },
609
610         { { "logger", "rotate", NULL }, 
611         handle_logger_rotate, "Rotates and reopens the log files",
612         logger_rotate_help },
613 };
614
615 static int handle_SIGXFSZ(int sig) 
616 {
617         /* Indicate need to reload */
618         filesize_reload_needed = 1;
619         return 0;
620 }
621
622 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str)
623 {
624         char buf[BUFSIZ];
625
626         if (level >= SYSLOG_NLEVELS) {
627                 /* we are locked here, so cannot ast_log() */
628                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
629                 return;
630         }
631
632         if (level == __LOG_VERBOSE) {
633                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", (long)GETTID(), str);
634                 level = __LOG_DEBUG;
635         } else if (level == __LOG_DTMF) {
636                 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", (long)GETTID(), str);
637                 level = __LOG_DEBUG;
638         } else {
639                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
640                          levels[level], (long)GETTID(), file, line, function, str);
641         }
642
643         term_strip(buf, buf, strlen(buf) + 1);
644         syslog(syslog_level_map[level], "%s", buf);
645 }
646
647 /* Print a normal log message to the channels */
648 static void logger_print_normal(struct logmsg *logmsg)
649 {
650         struct logchannel *chan = NULL;
651         char buf[BUFSIZ];
652
653         AST_RWLIST_RDLOCK(&logchannels);
654
655         if (logfiles.event_log && logmsg->level == __LOG_EVENT) {
656                 fprintf(eventlog, "%s asterisk[%ld]: %s", logmsg->date, (long)getpid(), logmsg->str);
657                 fflush(eventlog);
658                 AST_RWLIST_UNLOCK(&logchannels);
659                 return;
660         }
661
662         if (!AST_RWLIST_EMPTY(&logchannels)) {
663                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
664                         /* If the channel is disabled, then move on to the next one */
665                         if (chan->disabled)
666                                 continue;
667                         /* Check syslog channels */
668                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
669                                 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str);
670                         /* Console channels */
671                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
672                                 char linestr[128];
673                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
674
675                                 /* If the level is verbose, then skip it */
676                                 if (logmsg->level == __LOG_VERBOSE)
677                                         continue;
678
679                                 /* Turn the numerical line number into a string */
680                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
681                                 /* Build string to print out */
682                                 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
683                                          logmsg->date,
684                                          term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
685                                          (long)GETTID(),
686                                          term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
687                                          term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
688                                          term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
689                                          logmsg->str);
690                                 /* Print out */
691                                 ast_console_puts_mutable(buf);
692                         /* File channels */
693                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
694                                 int res = 0;
695
696                                 /* If no file pointer exists, skip it */
697                                 if (!chan->fileptr)
698                                         continue;
699                                 
700                                 /* Print out to the file */
701                                 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
702                                               logmsg->date, levels[logmsg->level], (long)GETTID(), logmsg->file, logmsg->str);
703                                 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
704                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
705                                         if (errno == ENOMEM || errno == ENOSPC)
706                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
707                                         else
708                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
709                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
710                                         chan->disabled = 1;
711                                 } else if (res > 0) {
712                                         fflush(chan->fileptr);
713                                 }
714                         }
715                 }
716         } else if (logmsg->level != __LOG_VERBOSE) {
717                 fputs(logmsg->str, stdout);
718         }
719
720         AST_RWLIST_UNLOCK(&logchannels);
721
722         /* If we need to reload because of the file size, then do so */
723         if (filesize_reload_needed) {
724                 reload_logger(1);
725                 ast_log(LOG_EVENT, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
726                 if (option_verbose)
727                         ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
728         }
729
730         return;
731 }
732
733 /* Print a verbose message to the verbosers */
734 static void logger_print_verbose(struct logmsg *logmsg)
735 {
736         struct verb *v = NULL;
737
738         /* Iterate through the list of verbosers and pass them the log message string */
739         AST_RWLIST_RDLOCK(&verbosers);
740         AST_RWLIST_TRAVERSE(&verbosers, v, list)
741                 v->verboser(logmsg->str);
742         AST_RWLIST_UNLOCK(&verbosers);
743
744         return;
745 }
746
747 /* Actual logging thread */
748 static void *logger_thread(void *data)
749 {
750         struct logmsg *next = NULL, *msg = NULL;
751
752         for (;;) {
753                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
754                 AST_LIST_LOCK(&logmsgs);
755                 if (AST_LIST_EMPTY(&logmsgs))
756                         ast_cond_wait(&logcond, &logmsgs.lock);
757                 next = AST_LIST_FIRST(&logmsgs);
758                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
759                 AST_LIST_UNLOCK(&logmsgs);
760
761                 /* If we should stop, then stop */
762                 if (close_logger_thread)
763                         break;
764
765                 /* Otherwise go through and process each message in the order added */
766                 while ((msg = next)) {
767                         /* Get the next entry now so that we can free our current structure later */
768                         next = AST_LIST_NEXT(msg, list);
769
770                         /* Depending on the type, send it to the proper function */
771                         if (msg->type == LOGMSG_NORMAL)
772                                 logger_print_normal(msg);
773                         else if (msg->type == LOGMSG_VERBOSE)
774                                 logger_print_verbose(msg);
775
776                         /* Free the data since we are done */
777                         free(msg);
778                 }
779         }
780
781         return NULL;
782 }
783
784 int init_logger(void)
785 {
786         char tmp[256];
787         int res = 0;
788
789         /* auto rotate if sig SIGXFSZ comes a-knockin */
790         (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
791
792         /* start logger thread */
793         ast_cond_init(&logcond, NULL);
794         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
795                 ast_cond_destroy(&logcond);
796                 return -1;
797         }
798
799         /* register the logger cli commands */
800         ast_cli_register_multiple(cli_logger, sizeof(cli_logger) / sizeof(struct ast_cli_entry));
801
802         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
803   
804         /* create log channels */
805         init_logger_chain();
806
807         /* create the eventlog */
808         if (logfiles.event_log) {
809                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
810                 eventlog = fopen(tmp, "a");
811                 if (eventlog) {
812                         ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
813                         if (option_verbose)
814                                 ast_verbose("Asterisk Event Logger Started %s\n", tmp);
815                 } else {
816                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
817                         res = -1;
818                 }
819         }
820
821         if (logfiles.queue_log) {
822                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
823                 qlog = fopen(tmp, "a");
824                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
825         }
826         return res;
827 }
828
829 void close_logger(void)
830 {
831         struct logchannel *f = NULL;
832
833         /* Stop logger thread */
834         AST_LIST_LOCK(&logmsgs);
835         close_logger_thread = 1;
836         ast_cond_signal(&logcond);
837         AST_LIST_UNLOCK(&logmsgs);
838
839         AST_RWLIST_WRLOCK(&logchannels);
840
841         if (eventlog) {
842                 fclose(eventlog);
843                 eventlog = NULL;
844         }
845
846         if (qlog) {
847                 fclose(qlog);
848                 qlog = NULL;
849         }
850
851         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
852                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
853                         fclose(f->fileptr);
854                         f->fileptr = NULL;
855                 }
856         }
857
858         closelog(); /* syslog */
859
860         AST_RWLIST_UNLOCK(&logchannels);
861
862         return;
863 }
864
865 /*!
866  * \brief send log messages to syslog and/or the console
867  */
868 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
869 {
870         struct logmsg *logmsg = NULL;
871         struct ast_str *buf = NULL;
872         struct ast_tm tm;
873         struct timeval tv = ast_tvnow();
874         int res = 0;
875         va_list ap;
876
877         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
878                 return;
879
880         if (AST_RWLIST_EMPTY(&logchannels)) {
881                 /*
882                  * we don't have the logger chain configured yet,
883                  * so just log to stdout
884                  */
885                 if (level != __LOG_VERBOSE) {
886                         int res;
887                         va_start(ap, fmt);
888                         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
889                         va_end(ap);
890                         if (res != AST_DYNSTR_BUILD_FAILED) {
891                                 term_filter_escapes(buf->str);
892                                 fputs(buf->str, stdout);
893                         }
894                 }
895                 return;
896         }
897         
898         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
899            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
900            is zero, if option_verbose is non-zero (this allows for 'level zero'
901            LOG_DEBUG messages to be displayed, if the logmask on any channel
902            allows it)
903         */
904         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
905                 return;
906
907         /* Ignore anything that never gets logged anywhere */
908         if (!(global_logmask & (1 << level)))
909                 return;
910         
911         /* Build string */
912         va_start(ap, fmt);
913         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
914         va_end(ap);
915
916         /* If the build failed, then abort and free this structure */
917         if (res == AST_DYNSTR_BUILD_FAILED)
918                 return;
919
920         /* Create a new logging message */
921         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
922                 return;
923         
924         /* Copy string over */
925         strcpy(logmsg->str, buf->str);
926
927         /* Set type to be normal */
928         logmsg->type = LOGMSG_NORMAL;
929
930         /* Create our date/time */
931         ast_localtime(&tv, &tm, NULL);
932         ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
933
934         /* Copy over data */
935         logmsg->level = level;
936         logmsg->file = file;
937         logmsg->line = line;
938         logmsg->function = function;
939
940         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
941         if (logthread != AST_PTHREADT_NULL) {
942                 AST_LIST_LOCK(&logmsgs);
943                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
944                 ast_cond_signal(&logcond);
945                 AST_LIST_UNLOCK(&logmsgs);
946         } else {
947                 logger_print_normal(logmsg);
948                 free(logmsg);
949         }
950
951         return;
952 }
953
954 void ast_backtrace(void)
955 {
956 #ifdef Linux
957 #ifdef AST_DEVMODE
958         int count=0, i=0;
959         void **addresses;
960         char **strings;
961
962         if ((addresses = ast_calloc(MAX_BACKTRACE_FRAMES, sizeof(*addresses)))) {
963                 count = backtrace(addresses, MAX_BACKTRACE_FRAMES);
964                 if ((strings = backtrace_symbols(addresses, count))) {
965                         ast_debug(1, "Got %d backtrace record%c\n", count, count != 1 ? 's' : ' ');
966                         for (i=0; i < count ; i++) {
967                                 ast_debug(1, "#%d: [%08X] %s\n", i, (unsigned int)addresses[i], strings[i]);
968                         }
969                         free(strings);
970                 } else {
971                         ast_debug(1, "Could not allocate memory for backtrace\n");
972                 }
973                 free(addresses);
974         }
975 #else
976         ast_log(LOG_WARNING, "Must run configure with '--enable-dev-mode' for stack backtraces.\n");
977 #endif
978 #else /* ndef Linux */
979         ast_log(LOG_WARNING, "Inline stack backtraces are only available on the Linux platform.\n");
980 #endif
981 }
982
983 void ast_verbose(const char *fmt, ...)
984 {
985         struct logmsg *logmsg = NULL;
986         struct ast_str *buf = NULL;
987         int res = 0;
988         va_list ap;
989
990         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
991                 return;
992
993         if (ast_opt_timestamp) {
994                 struct timeval tv;
995                 struct ast_tm tm;
996                 char date[40];
997                 char *datefmt;
998
999                                 tv = ast_tvnow();
1000                 ast_localtime(&tv, &tm, NULL);
1001                 ast_strftime(date, sizeof(date), dateformat, &tm);
1002                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1003                 sprintf(datefmt, "[%s] %s", date, fmt);
1004                 fmt = datefmt;
1005         }
1006
1007         /* Build string */
1008         va_start(ap, fmt);
1009         res = ast_str_set_va(&buf, 0, fmt, ap);
1010         va_end(ap);
1011
1012         /* If the build failed then we can drop this allocated message */
1013         if (res == AST_DYNSTR_BUILD_FAILED)
1014                 return;
1015
1016         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1017                 return;
1018
1019         strcpy(logmsg->str, buf->str);
1020
1021         ast_log(LOG_VERBOSE, logmsg->str);
1022
1023         /* Set type */
1024         logmsg->type = LOGMSG_VERBOSE;
1025         
1026         /* Add to the list and poke the thread if possible */
1027         if (logthread != AST_PTHREADT_NULL) {
1028                 AST_LIST_LOCK(&logmsgs);
1029                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1030                 ast_cond_signal(&logcond);
1031                 AST_LIST_UNLOCK(&logmsgs);
1032         } else {
1033                 logger_print_verbose(logmsg);
1034                 free(logmsg);
1035         }
1036 }
1037
1038 int ast_register_verbose(void (*v)(const char *string)) 
1039 {
1040         struct verb *verb;
1041
1042         if (!(verb = ast_malloc(sizeof(*verb))))
1043                 return -1;
1044
1045         verb->verboser = v;
1046
1047         AST_RWLIST_WRLOCK(&verbosers);
1048         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1049         AST_RWLIST_UNLOCK(&verbosers);
1050         
1051         return 0;
1052 }
1053
1054 int ast_unregister_verbose(void (*v)(const char *string))
1055 {
1056         struct verb *cur;
1057
1058         AST_RWLIST_WRLOCK(&verbosers);
1059         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1060                 if (cur->verboser == v) {
1061                         AST_RWLIST_REMOVE_CURRENT(&verbosers, list);
1062                         free(cur);
1063                         break;
1064                 }
1065         }
1066         AST_RWLIST_TRAVERSE_SAFE_END
1067         AST_RWLIST_UNLOCK(&verbosers);
1068         
1069         return cur ? 0 : -1;
1070 }