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