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