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