4033161831fe9dbc690e9ed62eecd21848d1b597
[asterisk/asterisk.git] / logger.c
1 /*
2  * Asterisk Logger
3  * 
4  * Mark Spencer <markster@marko.net>
5  *
6  * Copyright(C)1999, Linux Support Services, Inc.
7  * 
8  * Distributed under the terms of the GNU General Public License (GPL) Version 2
9  *
10  * Logging routines
11  *
12  */
13
14 #include <signal.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <unistd.h>
18 #include <time.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <sys/stat.h>
23
24 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
25                         from <syslog.h> which is included by logger.h */
26 #include <syslog.h>
27
28 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #include "asterisk/lock.h"
33 #include "asterisk/options.h"
34 #include "asterisk/channel.h"
35 #include "asterisk/config.h"
36 #include "asterisk/term.h"
37 #include "asterisk/cli.h"
38 #include "asterisk/utils.h"
39 #include "asterisk/manager.h"
40
41 static int syslog_level_map[] = {
42         LOG_DEBUG,
43         LOG_INFO,    /* arbitrary equivalent of LOG_EVENT */
44         LOG_NOTICE,
45         LOG_WARNING,
46         LOG_ERR,
47         LOG_DEBUG
48 };
49
50 #define SYSLOG_NLEVELS 6
51
52 #include "asterisk/logger.h"
53
54 #define MAX_MSG_QUEUE 200
55
56 #if defined(__linux__) && defined(__NR_gettid)
57 #include <asm/unistd.h>
58 #define GETTID() syscall(__NR_gettid)
59 #else
60 #define GETTID() getpid()
61 #endif
62
63 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
64
65 AST_MUTEX_DEFINE_STATIC(msglist_lock);
66 AST_MUTEX_DEFINE_STATIC(loglock);
67 static int filesize_reload_needed = 0;
68 static int global_logmask = -1;
69
70 static struct {
71         unsigned int queue_log:1;
72         unsigned int event_log:1;
73 } logfiles = { 1, 1 };
74
75 static struct msglist {
76         char *msg;
77         struct msglist *next;
78 } *list = NULL, *last = NULL;
79
80 static char hostname[MAXHOSTNAMELEN];
81
82 enum logtypes {
83         LOGTYPE_SYSLOG,
84         LOGTYPE_FILE,
85         LOGTYPE_CONSOLE,
86 };
87
88 struct logchannel {
89         int logmask;                    /* What to log to this channel */
90         int disabled;                   /* If this channel is disabled or not */
91         int facility;                   /* syslog facility */
92         enum logtypes type;             /* Type of log channel */
93         FILE *fileptr;                  /* logfile logging file pointer */
94         char filename[256];             /* Filename */
95         struct logchannel *next;        /* Next channel in chain */
96 };
97
98 static struct logchannel *logchannels = NULL;
99
100 static int msgcnt = 0;
101
102 static FILE *eventlog = NULL;
103
104 static char *levels[] = {
105         "DEBUG",
106         "EVENT",
107         "NOTICE",
108         "WARNING",
109         "ERROR",
110         "VERBOSE"
111 };
112
113 static int colors[] = {
114         COLOR_BRGREEN,
115         COLOR_BRBLUE,
116         COLOR_YELLOW,
117         COLOR_BRRED,
118         COLOR_RED,
119         COLOR_GREEN
120 };
121
122 static int make_components(char *s, int lineno)
123 {
124         char *w;
125         int res = 0;
126         char *stringp=NULL;
127         stringp=s;
128         w = strsep(&stringp, ",");
129         while(w) {
130                 while(*w && (*w < 33))
131                         w++;
132                 if (!strcasecmp(w, "error")) 
133                         res |= (1 << __LOG_ERROR);
134                 else if (!strcasecmp(w, "warning"))
135                         res |= (1 << __LOG_WARNING);
136                 else if (!strcasecmp(w, "notice"))
137                         res |= (1 << __LOG_NOTICE);
138                 else if (!strcasecmp(w, "event"))
139                         res |= (1 << __LOG_EVENT);
140                 else if (!strcasecmp(w, "debug"))
141                         res |= (1 << __LOG_DEBUG);
142                 else if (!strcasecmp(w, "verbose"))
143                         res |= (1 << __LOG_VERBOSE);
144                 else {
145                         fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
146                 }
147                 w = strsep(&stringp, ",");
148         }
149         return res;
150 }
151
152 static struct logchannel *make_logchannel(char *channel, char *components, int lineno)
153 {
154         struct logchannel *chan;
155         char *facility;
156 #ifndef SOLARIS
157         CODE *cptr;
158 #endif
159
160         if (ast_strlen_zero(channel))
161                 return NULL;
162         chan = malloc(sizeof(struct logchannel));
163
164         if (!chan)      /* Can't allocate memory */
165                 return NULL;
166
167         memset(chan, 0, sizeof(struct logchannel));
168         if (!strcasecmp(channel, "console")) {
169                 chan->type = LOGTYPE_CONSOLE;
170         } else if (!strncasecmp(channel, "syslog", 6)) {
171                 /*
172                 * syntax is:
173                 *  syslog.facility => level,level,level
174                 */
175                 facility = strchr(channel, '.');
176                 if(!facility++ || !facility) {
177                         facility = "local0";
178                 }
179
180 #ifndef SOLARIS
181                 /*
182                 * Walk through the list of facilitynames (defined in sys/syslog.h)
183                 * to see if we can find the one we have been given
184                 */
185                 chan->facility = -1;
186                 cptr = facilitynames;
187                 while (cptr->c_name) {
188                         if (!strcasecmp(facility, cptr->c_name)) {
189                                 chan->facility = cptr->c_val;
190                                 break;
191                         }
192                         cptr++;
193                 }
194 #else
195                 chan->facility = -1;
196                 if (!strcasecmp(facility, "kern")) 
197                         chan->facility = LOG_KERN;
198                 else if (!strcasecmp(facility, "USER")) 
199                         chan->facility = LOG_USER;
200                 else if (!strcasecmp(facility, "MAIL")) 
201                         chan->facility = LOG_MAIL;
202                 else if (!strcasecmp(facility, "DAEMON")) 
203                         chan->facility = LOG_DAEMON;
204                 else if (!strcasecmp(facility, "AUTH")) 
205                         chan->facility = LOG_AUTH;
206                 else if (!strcasecmp(facility, "SYSLOG")) 
207                         chan->facility = LOG_SYSLOG;
208                 else if (!strcasecmp(facility, "LPR")) 
209                         chan->facility = LOG_LPR;
210                 else if (!strcasecmp(facility, "NEWS")) 
211                         chan->facility = LOG_NEWS;
212                 else if (!strcasecmp(facility, "UUCP")) 
213                         chan->facility = LOG_UUCP;
214                 else if (!strcasecmp(facility, "CRON")) 
215                         chan->facility = LOG_CRON;
216                 else if (!strcasecmp(facility, "LOCAL0")) 
217                         chan->facility = LOG_LOCAL0;
218                 else if (!strcasecmp(facility, "LOCAL1")) 
219                         chan->facility = LOG_LOCAL1;
220                 else if (!strcasecmp(facility, "LOCAL2")) 
221                         chan->facility = LOG_LOCAL2;
222                 else if (!strcasecmp(facility, "LOCAL3")) 
223                         chan->facility = LOG_LOCAL3;
224                 else if (!strcasecmp(facility, "LOCAL4")) 
225                         chan->facility = LOG_LOCAL4;
226                 else if (!strcasecmp(facility, "LOCAL5")) 
227                         chan->facility = LOG_LOCAL5;
228                 else if (!strcasecmp(facility, "LOCAL6")) 
229                         chan->facility = LOG_LOCAL6;
230                 else if (!strcasecmp(facility, "LOCAL7")) 
231                         chan->facility = LOG_LOCAL7;
232 #endif /* Solaris */
233
234                 if (0 > chan->facility) {
235                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
236                         free(chan);
237                         return NULL;
238                 }
239
240                 chan->type = LOGTYPE_SYSLOG;
241                 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
242                 openlog("asterisk", LOG_PID, chan->facility);
243         } else {
244                 if (channel[0] == '/') {
245                         if(!ast_strlen_zero(hostname)) { 
246                                 snprintf(chan->filename, sizeof(chan->filename) - 1,"%s.%s", channel, hostname);
247                         } else {
248                                 strncpy(chan->filename, channel, sizeof(chan->filename) - 1);
249                         }
250                 }                 
251                 
252                 if(!ast_strlen_zero(hostname)) {
253                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",(char *)ast_config_AST_LOG_DIR, channel, hostname);
254                 } else {
255                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s", (char *)ast_config_AST_LOG_DIR, channel);
256                 }
257                 chan->fileptr = fopen(chan->filename, "a");
258                 if (!chan->fileptr) {
259                         /* Can't log here, since we're called with a lock */
260                         fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
261                 } 
262                 chan->type = LOGTYPE_FILE;
263         }
264         chan->logmask = make_components(components, lineno);
265         return chan;
266 }
267
268 static void init_logger_chain(void)
269 {
270         struct logchannel *chan, *cur;
271         struct ast_config *cfg;
272         struct ast_variable *var;
273         char *s;
274
275         /* delete our list of log channels */
276         ast_mutex_lock(&loglock);
277         chan = logchannels;
278         while (chan) {
279                 cur = chan->next;
280                 free(chan);
281                 chan = cur;
282         }
283         logchannels = NULL;
284         ast_mutex_unlock(&loglock);
285         
286         global_logmask = 0;
287         /* close syslog */
288         closelog();
289         
290         cfg = ast_config_load("logger.conf");
291         
292         /* If no config file, we're fine */
293         if (!cfg)
294                 return;
295         
296         ast_mutex_lock(&loglock);
297         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
298                 if(ast_true(s)) {
299                         if(gethostname(hostname, sizeof(hostname)-1)) {
300                                 strncpy(hostname, "unknown", sizeof(hostname)-1);
301                                 ast_log(LOG_WARNING, "What box has no hostname???\n");
302                         }
303                 } else
304                         hostname[0] = '\0';
305         } else
306                 hostname[0] = '\0';
307         if ((s = ast_variable_retrieve(cfg, "general", "dateformat"))) {
308                 strncpy(dateformat, s, sizeof(dateformat) - 1);
309         } else
310                 strncpy(dateformat, "%b %e %T", sizeof(dateformat) - 1);
311         if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
312                 logfiles.queue_log = ast_true(s);
313         }
314         if ((s = ast_variable_retrieve(cfg, "general", "event_log"))) {
315                 logfiles.event_log = ast_true(s);
316         }
317
318         var = ast_variable_browse(cfg, "logfiles");
319         while(var) {
320                 chan = make_logchannel(var->name, var->value, var->lineno);
321                 if (chan) {
322                         chan->next = logchannels;
323                         logchannels = chan;
324                         global_logmask |= chan->logmask;
325                 }
326                 var = var->next;
327         }
328
329         ast_config_destroy(cfg);
330         ast_mutex_unlock(&loglock);
331 }
332
333 static FILE *qlog = NULL;
334 AST_MUTEX_DEFINE_STATIC(qloglock);
335
336 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
337 {
338         va_list ap;
339         ast_mutex_lock(&qloglock);
340         if (qlog) {
341                 va_start(ap, fmt);
342                 fprintf(qlog, "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
343                 vfprintf(qlog, fmt, ap);
344                 fprintf(qlog, "\n");
345                 va_end(ap);
346                 fflush(qlog);
347         }
348         ast_mutex_unlock(&qloglock);
349 }
350
351 static void queue_log_init(void)
352 {
353         char filename[256];
354         int reloaded = 0;
355
356         ast_mutex_lock(&qloglock);
357         if (qlog) {
358                 reloaded = 1;
359                 fclose(qlog);
360                 qlog = NULL;
361         }
362         snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_LOG_DIR, "queue_log");
363         if (logfiles.queue_log) {
364                 qlog = fopen(filename, "a");
365         }
366         ast_mutex_unlock(&qloglock);
367         if (reloaded) 
368                 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
369         else
370                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
371 }
372
373 int reload_logger(int rotate)
374 {
375         char old[AST_CONFIG_MAX_PATH] = "";
376         char new[AST_CONFIG_MAX_PATH];
377         struct logchannel *f;
378         FILE *myf;
379         int x;
380
381         ast_mutex_lock(&loglock);
382         if (eventlog) 
383                 fclose(eventlog);
384         else 
385                 rotate = 0;
386         eventlog = NULL;
387
388         mkdir((char *)ast_config_AST_LOG_DIR, 0755);
389         snprintf(old, sizeof(old), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
390
391         if (logfiles.event_log) {
392                 if (rotate) {
393                         for (x=0;;x++) {
394                                 snprintf(new, sizeof(new), "%s/%s.%d", (char *)ast_config_AST_LOG_DIR, EVENTLOG,x);
395                                 myf = fopen((char *)new, "r");
396                                 if (myf)        /* File exists */
397                                         fclose(myf);
398                                 else
399                                         break;
400                         }
401         
402                         /* do it */
403                         if (rename(old,new))
404                                 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
405                 }
406
407                 eventlog = fopen(old, "a");
408         }
409
410         f = logchannels;
411         while(f) {
412                 if (f->disabled) {
413                         f->disabled = 0;        /* Re-enable logging at reload */
414                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
415                 }
416                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
417                         fclose(f->fileptr);     /* Close file */
418                         f->fileptr = NULL;
419                         if(rotate) {
420                                 strncpy(old, f->filename, sizeof(old) - 1);
421         
422                                 for(x=0;;x++) {
423                                         snprintf(new, sizeof(new), "%s.%d", f->filename, x);
424                                         myf = fopen((char *)new, "r");
425                                         if (myf) {
426                                                 fclose(myf);
427                                         } else {
428                                                 break;
429                                         }
430                                 }
431             
432                                 /* do it */
433                                 if (rename(old,new))
434                                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
435                         }
436                 }
437                 f = f->next;
438         }
439
440         ast_mutex_unlock(&loglock);
441
442         filesize_reload_needed = 0;
443
444         queue_log_init();
445         init_logger_chain();
446
447         if (logfiles.event_log) {
448                 if (eventlog) {
449                         ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
450                         if (option_verbose)
451                                 ast_verbose("Asterisk Event Logger restarted\n");
452                         return 0;
453                 } else 
454                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
455         }
456         return -1;
457 }
458
459 static int handle_logger_reload(int fd, int argc, char *argv[])
460 {
461         if(reload_logger(0)) {
462                 ast_cli(fd, "Failed to reload the logger\n");
463                 return RESULT_FAILURE;
464         } else
465                 return RESULT_SUCCESS;
466 }
467
468 static int handle_logger_rotate(int fd, int argc, char *argv[])
469 {
470         if(reload_logger(1)) {
471                 ast_cli(fd, "Failed to reload the logger and rotate log files\n");
472                 return RESULT_FAILURE;
473         } else
474                 return RESULT_SUCCESS;
475 }
476
477 /*--- handle_logger_show_channels: CLI command to show logging system 
478         configuration */
479 static int handle_logger_show_channels(int fd, int argc, char *argv[])
480 {
481 #define FORMATL "%-35.35s %-8.8s %-9.9s "
482         struct logchannel *chan;
483
484         ast_mutex_lock(&loglock);
485
486         chan = logchannels;
487         ast_cli(fd,FORMATL, "Channel", "Type", "Status");
488         ast_cli(fd, "Configuration\n");
489         ast_cli(fd,FORMATL, "-------", "----", "------");
490         ast_cli(fd, "-------------\n");
491         while (chan) {
492                 ast_cli(fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
493                         chan->disabled ? "Disabled" : "Enabled");
494                 ast_cli(fd, " - ");
495                 if (chan->logmask & (1 << __LOG_DEBUG)) 
496                         ast_cli(fd, "Debug ");
497                 if (chan->logmask & (1 << __LOG_VERBOSE)) 
498                         ast_cli(fd, "Verbose ");
499                 if (chan->logmask & (1 << __LOG_WARNING)) 
500                         ast_cli(fd, "Warning ");
501                 if (chan->logmask & (1 << __LOG_NOTICE)) 
502                         ast_cli(fd, "Notice ");
503                 if (chan->logmask & (1 << __LOG_ERROR)) 
504                         ast_cli(fd, "Error ");
505                 if (chan->logmask & (1 << __LOG_EVENT)) 
506                         ast_cli(fd, "Event ");
507                 ast_cli(fd, "\n");
508                 chan = chan->next;
509         }
510         ast_cli(fd, "\n");
511
512         ast_mutex_unlock(&loglock);
513                 
514         return RESULT_SUCCESS;
515 }
516
517 static struct verb {
518         void (*verboser)(const char *string, int opos, int replacelast, int complete);
519         struct verb *next;
520 } *verboser = NULL;
521
522
523 static char logger_reload_help[] =
524 "Usage: logger reload\n"
525 "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
526
527 static char logger_rotate_help[] =
528 "Usage: logger rotate\n"
529 "       Rotates and Reopens the log files.\n";
530
531 static char logger_show_channels_help[] =
532 "Usage: logger show channels\n"
533 "       Show configured logger channels.\n";
534
535 static struct ast_cli_entry logger_show_channels_cli = 
536         { { "logger", "show", "channels", NULL }, 
537         handle_logger_show_channels, "List configured log channels",
538         logger_show_channels_help };
539
540 static struct ast_cli_entry reload_logger_cli = 
541         { { "logger", "reload", NULL }, 
542         handle_logger_reload, "Reopens the log files",
543         logger_reload_help };
544
545 static struct ast_cli_entry rotate_logger_cli = 
546         { { "logger", "rotate", NULL }, 
547         handle_logger_rotate, "Rotates and reopens the log files",
548         logger_rotate_help };
549
550 static int handle_SIGXFSZ(int sig) 
551 {
552         /* Indicate need to reload */
553         filesize_reload_needed = 1;
554         return 0;
555 }
556
557 int init_logger(void)
558 {
559         char tmp[256];
560
561         /* auto rotate if sig SIGXFSZ comes a-knockin */
562         (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
563
564         /* register the relaod logger cli command */
565         ast_cli_register(&reload_logger_cli);
566         ast_cli_register(&rotate_logger_cli);
567         ast_cli_register(&logger_show_channels_cli);
568
569         /* initialize queue logger */
570         queue_log_init();
571
572         /* create log channels */
573         init_logger_chain();
574
575         /* create the eventlog */
576         if (logfiles.event_log) {
577                 mkdir((char *)ast_config_AST_LOG_DIR, 0755);
578                 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
579                 eventlog = fopen((char *)tmp, "a");
580                 if (eventlog) {
581                         ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
582                         if (option_verbose)
583                                 ast_verbose("Asterisk Event Logger Started %s\n",(char *)tmp);
584                         return 0;
585                 } else 
586                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
587         }
588
589         return -1;
590 }
591
592 void close_logger(void)
593 {
594         struct msglist *m, *tmp;
595
596         ast_mutex_lock(&msglist_lock);
597         m = list;
598         while(m) {
599                 if (m->msg) {
600                         free(m->msg);
601                 }
602                 tmp = m->next;
603                 free(m);
604                 m = tmp;
605         }
606         list = last = NULL;
607         msgcnt = 0;
608         ast_mutex_unlock(&msglist_lock);
609         return;
610 }
611
612 static void strip_coloring(char *str)
613 {
614         char *src, *dest, *end;
615         
616         if (!str)
617                 return;
618
619         /* find the first potential escape sequence in the string */
620
621         src = strchr(str, '\033');
622         if (!src)
623                 return;
624
625         dest = src;
626         while (*src) {
627                 /* at the top of this loop, *src will always be an ESC character */
628                 if ((src[1] == '[') && ((end = strchr(src + 2, 'm'))))
629                         src = end + 1;
630                 else
631                         *dest++ = *src++;
632
633                 /* copy characters, checking for ESC as we go */
634                 while (*src && (*src != '\033'))
635                         *dest++ = *src++;
636         }
637
638         *dest = '\0';
639 }
640
641 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, const char *fmt, va_list args) 
642 {
643         char buf[BUFSIZ];
644         char *s;
645
646         if (level >= SYSLOG_NLEVELS) {
647                 /* we are locked here, so cannot ast_log() */
648                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
649                 return;
650         }
651         if (level == __LOG_VERBOSE) {
652                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: ", (long)GETTID());
653                 level = __LOG_DEBUG;
654         } else {
655                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: ",
656                          levels[level], (long)GETTID(), file, line, function);
657         }
658         s = buf + strlen(buf);
659         vsnprintf(s, sizeof(buf) - strlen(buf), fmt, args);
660         strip_coloring(s);
661         syslog(syslog_level_map[level], "%s", buf);
662 }
663
664 /*
665  * send log messages to syslog and/or the console
666  */
667 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
668 {
669         struct logchannel *chan;
670         char buf[BUFSIZ];
671         time_t t;
672         struct tm tm;
673         char date[256];
674
675         va_list ap;
676         
677         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
678            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
679            is zero, if option_verbose is non-zero (this allows for 'level zero'
680            LOG_DEBUG messages to be displayed, if the logmask on any channel
681            allows it)
682         */
683         if (!option_verbose && !option_debug && (level == __LOG_DEBUG)) {
684                 return;
685         }
686
687         /* Ignore anything that never gets logged anywhere */
688         if (!(global_logmask & (1 << level)))
689                 return;
690         
691         /* Ignore anything other than the currently debugged file if there is one */
692         if ((level == __LOG_DEBUG) && !ast_strlen_zero(debug_filename) && strcasecmp(debug_filename, file))
693                 return;
694
695         /* begin critical section */
696         ast_mutex_lock(&loglock);
697
698         time(&t);
699         localtime_r(&t, &tm);
700         strftime(date, sizeof(date), dateformat, &tm);
701
702         if (logfiles.event_log && level == __LOG_EVENT) {
703                 va_start(ap, fmt);
704
705                 fprintf(eventlog, "%s asterisk[%d]: ", date, getpid());
706                 vfprintf(eventlog, fmt, ap);
707                 fflush(eventlog);
708
709                 va_end(ap);
710                 ast_mutex_unlock(&loglock);
711                 return;
712         }
713
714         if (logchannels) {
715                 chan = logchannels;
716                 while(chan && !chan->disabled) {
717                         /* Check syslog channels */
718                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << level))) {
719                                 va_start(ap, fmt);
720                                 ast_log_vsyslog(level, file, line, function, fmt, ap);
721                                 va_end(ap);
722                         /* Console channels */
723                         } else if ((chan->logmask & (1 << level)) && (chan->type == LOGTYPE_CONSOLE)) {
724                                 char linestr[128];
725                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
726
727                                 if (level != __LOG_VERBOSE) {
728                                         sprintf(linestr, "%d", line);
729                                         snprintf(buf, sizeof(buf), option_timestamp ? "[%s] %s[%ld]: %s:%s %s: " : "%s %s[%ld]: %s:%s %s: ",
730                                                 date,
731                                                 term_color(tmp1, levels[level], colors[level], 0, sizeof(tmp1)),
732                                                 (long)GETTID(),
733                                                 term_color(tmp2, file, COLOR_BRWHITE, 0, sizeof(tmp2)),
734                                                 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
735                                                 term_color(tmp4, function, COLOR_BRWHITE, 0, sizeof(tmp4)));
736                                         
737                                         ast_console_puts(buf);
738                                         va_start(ap, fmt);
739                                         vsnprintf(buf, sizeof(buf), fmt, ap);
740                                         va_end(ap);
741                                         ast_console_puts(buf);
742                                 }
743                         /* File channels */
744                         } else if ((chan->logmask & (1 << level)) && (chan->fileptr)) {
745                                 int res;
746                                 snprintf(buf, sizeof(buf), option_timestamp ? "[%s] %s[%ld]: " : "%s %s[%ld] %s: ", date,
747                                         levels[level], (long)GETTID(), file);
748                                 res = fprintf(chan->fileptr, buf);
749                                 if (res <= 0 && buf[0] != '\0') {       /* Error, no characters printed */
750                                         fprintf(stderr,"**** Asterisk Logging Error: ***********\n");
751                                         if (errno == ENOMEM || errno == ENOSPC) {
752                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
753                                         } else
754                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
755                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
756                                         chan->disabled = 1;     
757                                 } else {
758                                         /* No error message, continue printing */
759                                         va_start(ap, fmt);
760                                         vsnprintf(buf, sizeof(buf), fmt, ap);
761                                         va_end(ap);
762                                         strip_coloring(buf);
763                                         fputs(buf, chan->fileptr);
764                                         fflush(chan->fileptr);
765                                 }
766                         }
767                         chan = chan->next;
768                 }
769         } else {
770                 /* 
771                  * we don't have the logger chain configured yet,
772                  * so just log to stdout 
773                 */
774                 if (level != __LOG_VERBOSE) {
775                         va_start(ap, fmt);
776                         vsnprintf(buf, sizeof(buf), fmt, ap);
777                         va_end(ap);
778                         fputs(buf, stdout);
779                 }
780         }
781
782         ast_mutex_unlock(&loglock);
783         /* end critical section */
784         if (filesize_reload_needed) {
785                 reload_logger(1);
786                 ast_log(LOG_EVENT,"Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
787                 if (option_verbose)
788                         ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
789         }
790 }
791
792 extern void ast_verbose(const char *fmt, ...)
793 {
794         static char stuff[4096];
795         static int pos = 0, opos;
796         static int replacelast = 0, complete;
797         struct msglist *m;
798         struct verb *v;
799         time_t t;
800         struct tm tm;
801         char date[40];
802         char *datefmt;
803         
804         va_list ap;
805         va_start(ap, fmt);
806         ast_mutex_lock(&msglist_lock);
807         time(&t);
808         localtime_r(&t, &tm);
809         strftime(date, sizeof(date), dateformat, &tm);
810
811         if (option_timestamp) {
812                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
813                 if (datefmt) {
814                         sprintf(datefmt, "[%s] %s", date, fmt);
815                         fmt = datefmt;
816                 }
817         }
818         vsnprintf(stuff + pos, sizeof(stuff) - pos, fmt, ap);
819         opos = pos;
820         pos = strlen(stuff);
821
822
823         if (stuff[strlen(stuff)-1] == '\n') 
824                 complete = 1;
825         else
826                 complete=0;
827         if (complete) {
828                 if (msgcnt < MAX_MSG_QUEUE) {
829                         /* Allocate new structure */
830                         m = malloc(sizeof(struct msglist));
831                         msgcnt++;
832                 } else {
833                         /* Recycle the oldest entry */
834                         m = list;
835                         list = list->next;
836                         free(m->msg);
837                 }
838                 if (m) {
839                         m->msg = strdup(stuff);
840                         if (m->msg) {
841                                 if (last)
842                                         last->next = m;
843                                 else
844                                         list = m;
845                                 m->next = NULL;
846                                 last = m;
847                         } else {
848                                 msgcnt--;
849                                 ast_log(LOG_ERROR, "Out of memory\n");
850                                 free(m);
851                         }
852                 }
853         }
854         if (verboser) {
855                 v = verboser;
856                 while(v) {
857                         v->verboser(stuff, opos, replacelast, complete);
858                         v = v->next;
859                 }
860         } /* else
861                 fprintf(stdout, stuff + opos); */
862         ast_log(LOG_VERBOSE, "%s", stuff);
863         if (strlen(stuff)) {
864                 if (stuff[strlen(stuff)-1] != '\n') 
865                         replacelast = 1;
866                 else 
867                         replacelast = pos = 0;
868         }
869         va_end(ap);
870
871         ast_mutex_unlock(&msglist_lock);
872 }
873
874 int ast_verbose_dmesg(void (*v)(const char *string, int opos, int replacelast, int complete))
875 {
876         struct msglist *m;
877         ast_mutex_lock(&msglist_lock);
878         m = list;
879         while(m) {
880                 /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
881                 v(m->msg, 0, 0, 1);
882                 m = m->next;
883         }
884         ast_mutex_unlock(&msglist_lock);
885         return 0;
886 }
887
888 int ast_register_verbose(void (*v)(const char *string, int opos, int replacelast, int complete)) 
889 {
890         struct msglist *m;
891         struct verb *tmp;
892         /* XXX Should be more flexible here, taking > 1 verboser XXX */
893         if ((tmp = malloc(sizeof (struct verb)))) {
894                 tmp->verboser = v;
895                 ast_mutex_lock(&msglist_lock);
896                 tmp->next = verboser;
897                 verboser = tmp;
898                 m = list;
899                 while(m) {
900                         /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
901                         v(m->msg, 0, 0, 1);
902                         m = m->next;
903                 }
904                 ast_mutex_unlock(&msglist_lock);
905                 return 0;
906         }
907         return -1;
908 }
909
910 int ast_unregister_verbose(void (*v)(const char *string, int opos, int replacelast, int complete))
911 {
912         int res = -1;
913         struct verb *tmp, *tmpl=NULL;
914         ast_mutex_lock(&msglist_lock);
915         tmp = verboser;
916         while(tmp) {
917                 if (tmp->verboser == v) {
918                         if (tmpl)
919                                 tmpl->next = tmp->next;
920                         else
921                                 verboser = tmp->next;
922                         free(tmp);
923                         break;
924                 }
925                 tmpl = tmp;
926                 tmp = tmp->next;
927         }
928         if (tmp)
929                 res = 0;
930         ast_mutex_unlock(&msglist_lock);
931         return res;
932 }