Update chanelog
[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 <asterisk/lock.h>
20 #include <asterisk/options.h>
21 #include <asterisk/channel.h>
22 #include <asterisk/config.h>
23 #include <asterisk/term.h>
24 #include <asterisk/cli.h>
25 #include <asterisk/utils.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <sys/stat.h>
30 #include "asterisk.h"
31 #include "astconf.h"
32
33 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
34                         from <syslog.h> which is included by logger.h */
35 #include <syslog.h>
36 static int syslog_level_map[] = {
37         LOG_DEBUG,
38         LOG_INFO,    /* arbitrary equivalent of LOG_EVENT */
39         LOG_NOTICE,
40         LOG_WARNING,
41         LOG_ERR,
42         LOG_DEBUG
43 };
44
45 #define SYSLOG_NLEVELS 6
46
47 #include <asterisk/logger.h>
48
49 #define MAX_MSG_QUEUE 200
50
51 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
52 AST_MUTEX_DEFINE_STATIC(msglist_lock);
53 AST_MUTEX_DEFINE_STATIC(loglock);
54 static int pending_logger_reload = 0;
55
56 static struct msglist {
57         char *msg;
58         struct msglist *next;
59 } *list = NULL, *last = NULL;
60
61 static char hostname[256];
62
63 struct logchannel {
64         int logmask;
65         int facility; /* syslog */
66         int syslog; /* syslog flag */
67         int console;  /* console logging */
68         FILE *fileptr; /* logfile logging */
69         char filename[256];
70         struct logchannel *next;
71 };
72
73 static struct logchannel *logchannels = NULL;
74
75 static int msgcnt = 0;
76
77 static FILE *eventlog = NULL;
78
79 static char *levels[] = {
80         "DEBUG",
81         "EVENT",
82         "NOTICE",
83         "WARNING",
84         "ERROR",
85         "VERBOSE"
86 };
87
88 static int colors[] = {
89         COLOR_BRGREEN,
90         COLOR_BRBLUE,
91         COLOR_YELLOW,
92         COLOR_BRRED,
93         COLOR_RED,
94         COLOR_GREEN
95 };
96
97 static int make_components(char *s, int lineno)
98 {
99         char *w;
100         int res = 0;
101         char *stringp=NULL;
102         stringp=s;
103         w = strsep(&stringp, ",");
104         while(w) {
105             while(*w && (*w < 33))
106                 w++;
107             if (!strcasecmp(w, "error")) 
108                 res |= (1 << __LOG_ERROR);
109             else if (!strcasecmp(w, "warning"))
110                 res |= (1 << __LOG_WARNING);
111             else if (!strcasecmp(w, "notice"))
112                 res |= (1 << __LOG_NOTICE);
113             else if (!strcasecmp(w, "event"))
114                 res |= (1 << __LOG_EVENT);
115             else if (!strcasecmp(w, "debug"))
116                 res |= (1 << __LOG_DEBUG);
117             else if (!strcasecmp(w, "verbose"))
118                 res |= (1 << __LOG_VERBOSE);
119             else {
120                 fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
121             }
122             w = strsep(&stringp, ",");
123         }
124         return res;
125 }
126
127 static struct logchannel *make_logchannel(char *channel, char *components, int lineno)
128 {
129         struct logchannel *chan;
130         char *facility;
131         CODE *cptr;
132
133         if (ast_strlen_zero(channel))
134                 return NULL;
135         chan = malloc(sizeof(struct logchannel));
136
137         if (chan) {
138                 memset(chan, 0, sizeof(struct logchannel));
139                 if (!strcasecmp(channel, "console")) {
140                     chan->console = 1;
141                 } else if (!strncasecmp(channel, "syslog", 6)) {
142                     /*
143                      * syntax is:
144                      *  syslog.facility => level,level,level
145                      */
146                     facility = strchr(channel, '.');
147                     if(!facility++ || !facility) {
148                         facility = "local0";
149                     }
150                     /*
151                      * Walk through the list of facilitynames (defined in sys/syslog.h)
152                      * to see if we can find the one we have been given
153                      */
154                     chan->facility = -1;
155                     cptr = facilitynames;
156                     while (cptr->c_name) {
157                         if (!strncasecmp(facility, cptr->c_name, sizeof(cptr->c_name))) {
158                             chan->facility = cptr->c_val;
159                             break;
160                         }
161                         cptr++;
162                     }
163                     if (0 > chan->facility) {
164                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
165                         free(chan);
166                         return NULL;
167                     }
168
169                     chan->syslog = 1;
170                     openlog("asterisk", LOG_PID, chan->facility);
171                 } else {
172                         if (channel[0] == '/') {
173                                 if(!ast_strlen_zero(hostname)) { 
174                                         snprintf(chan->filename, sizeof(chan->filename) - 1,"%s.%s", channel, hostname);
175                                 } else {
176                                         strncpy(chan->filename, channel, sizeof(chan->filename) - 1);
177                                 }
178                         }                 
179                         
180                         if(!ast_strlen_zero(hostname)) {
181                                 snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",(char *)ast_config_AST_LOG_DIR, channel, hostname);
182                         } else {
183                                 snprintf(chan->filename, sizeof(chan->filename), "%s/%s", (char *)ast_config_AST_LOG_DIR, channel);
184                         }
185                         chan->fileptr = fopen(chan->filename, "a");
186                         if (!chan->fileptr) {
187                                 /* Can't log here, since we're called with a lock */
188                                 fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
189                         }
190                 }
191                 chan->logmask = make_components(components, lineno);
192         }
193         return chan;
194 }
195
196 static void init_logger_chain(void)
197 {
198         struct logchannel *chan, *cur;
199         struct ast_config *cfg;
200         struct ast_variable *var;
201         char *s;
202
203         /* delete our list of log channels */
204         ast_mutex_lock(&loglock);
205         chan = logchannels;
206         while (chan) {
207             cur = chan->next;
208             free(chan);
209             chan = cur;
210         }
211         logchannels = NULL;
212         ast_mutex_unlock(&loglock);
213         
214         /* close syslog */
215         closelog();
216         
217         cfg = ast_load("logger.conf");
218         
219         /* If no config file, we're fine */
220         if (!cfg)
221             return;
222         
223         ast_mutex_lock(&loglock);
224         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
225                 if(ast_true(s)) {
226                         if(gethostname(hostname, sizeof(hostname))) {
227                                 strncpy(hostname, "unknown", sizeof(hostname)-1);
228                                 ast_log(LOG_WARNING, "What box has no hostname???\n");
229                         }
230                 } else
231                         hostname[0] = '\0';
232         } else
233                 hostname[0] = '\0';
234         if ((s = ast_variable_retrieve(cfg, "general", "dateformat"))) {
235                 strncpy(dateformat, s, sizeof(dateformat) - 1);
236         } else
237                 strncpy(dateformat, "%b %e %T", sizeof(dateformat) - 1);
238         var = ast_variable_browse(cfg, "logfiles");
239         while(var) {
240                 chan = make_logchannel(var->name, var->value, var->lineno);
241                 if (chan) {
242                         chan->next = logchannels;
243                         logchannels = chan;
244                 }
245                 var = var->next;
246         }
247
248         ast_destroy(cfg);
249         ast_mutex_unlock(&loglock);
250 }
251
252 static FILE *qlog = NULL;
253 AST_MUTEX_DEFINE_STATIC(qloglock);
254
255 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
256 {
257         va_list ap;
258         ast_mutex_lock(&qloglock);
259         if (qlog) {
260                 va_start(ap, fmt);
261                 fprintf(qlog, "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
262                 vfprintf(qlog, fmt, ap);
263                 fprintf(qlog, "\n");
264                 va_end(ap);
265                 fflush(qlog);
266         }
267         ast_mutex_unlock(&qloglock);
268 }
269
270 static void queue_log_init(void)
271 {
272         char filename[256];
273         int reloaded = 0;
274         ast_mutex_lock(&qloglock);
275         if (qlog) {
276                 reloaded = 1;
277                 fclose(qlog);
278                 qlog = NULL;
279         }
280         snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_LOG_DIR, "queue_log");
281         qlog = fopen(filename, "a");
282         ast_mutex_unlock(&qloglock);
283         if (reloaded) 
284                 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
285         else
286                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
287 }
288
289 int reload_logger(int rotate)
290 {
291         char old[AST_CONFIG_MAX_PATH] = "";
292         char new[AST_CONFIG_MAX_PATH];
293         struct logchannel *f;
294         FILE *myf;
295
296         int x;
297         ast_mutex_lock(&loglock);
298         if (eventlog) 
299                 fclose(eventlog);
300         else 
301                 rotate = 0;
302         eventlog = NULL;
303
304
305
306         mkdir((char *)ast_config_AST_LOG_DIR, 0755);
307         snprintf(old, sizeof(old), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
308
309         if(rotate) {
310                 for(x=0;;x++) {
311                         snprintf(new, sizeof(new), "%s/%s.%d", (char *)ast_config_AST_LOG_DIR, EVENTLOG,x);
312                         myf = fopen((char *)new, "r");
313                         if(myf) 
314                                 fclose(myf);
315                         else
316                                 break;
317                 }
318         
319                 /* do it */
320                 if (rename(old,new))
321                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
322         }
323
324         eventlog = fopen(old, "a");
325
326         f = logchannels;
327         while(f) {
328                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
329                         fclose(f->fileptr);
330                         f->fileptr = NULL;
331                         if(rotate) {
332                                 strncpy(old, f->filename, sizeof(old) - 1);
333         
334                                 for(x=0;;x++) {
335                                         snprintf(new, sizeof(new), "%s.%d", f->filename, x);
336                                         myf = fopen((char *)new, "r");
337                                         if (myf) {
338                                                 fclose(myf);
339                                         } else {
340                                                 break;
341                                         }
342                                 }
343             
344                                 /* do it */
345                                 if (rename(old,new))
346                                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
347                         }
348                 }
349                 f = f->next;
350         }
351
352         ast_mutex_unlock(&loglock);
353
354         queue_log_init();
355
356         if (eventlog) {
357                 init_logger_chain();
358                 ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
359                 if (option_verbose)
360                         ast_verbose("Asterisk Event Logger restarted\n");
361                 return 0;
362         } else 
363                 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
364         init_logger_chain();
365         pending_logger_reload = 0;
366         return -1;
367 }
368
369 static int handle_logger_reload(int fd, int argc, char *argv[])
370 {
371         if(reload_logger(0))
372         {
373                 ast_cli(fd, "Failed to reloadthe logger\n");
374                 return RESULT_FAILURE;
375         }
376         else
377                 return RESULT_SUCCESS;
378 }
379
380 static int handle_logger_rotate(int fd, int argc, char *argv[])
381 {
382         if(reload_logger(1))
383         {
384                 ast_cli(fd, "Failed to reloadthe logger\n");
385                 return RESULT_FAILURE;
386         }
387         else
388                 return RESULT_SUCCESS;
389 }
390
391 static struct verb {
392         void (*verboser)(const char *string, int opos, int replacelast, int complete);
393         struct verb *next;
394 } *verboser = NULL;
395
396
397 static char logger_reload_help[] =
398 "Usage: logger reload\n"
399 "       Reloads the logger subsystem state.  Use after restarting syslogd(8)\n";
400
401 static char logger_rotate_help[] =
402 "Usage: logger rotate\n"
403 "       Rotates and Reopens the log files.\n";
404
405 static struct ast_cli_entry reload_logger_cli = 
406         { { "logger", "reload", NULL }, 
407         handle_logger_reload, "Reopens the log files",
408         logger_reload_help };
409
410 static struct ast_cli_entry rotate_logger_cli = 
411         { { "logger", "rotate", NULL }, 
412         handle_logger_rotate, "Rotates and reopens the log files",
413         logger_rotate_help };
414
415 static int handle_SIGXFSZ(int sig) 
416 {
417         /* Indicate need to reload */
418         pending_logger_reload = 1;
419         return 0;
420 }
421
422 int init_logger(void)
423 {
424         char tmp[256];
425
426         /* auto rotate if sig SIGXFSZ comes a-knockin */
427         (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
428
429         /* register the relaod logger cli command */
430         ast_cli_register(&reload_logger_cli);
431         ast_cli_register(&rotate_logger_cli);
432
433         /* initialize queue logger */
434         queue_log_init();
435
436         /* create the eventlog */
437         mkdir((char *)ast_config_AST_LOG_DIR, 0755);
438         snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
439         eventlog = fopen((char *)tmp, "a");
440         if (eventlog) {
441                 init_logger_chain();
442                 ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
443                 if (option_verbose)
444                         ast_verbose("Asterisk Event Logger Started %s\n",(char *)tmp);
445                 return 0;
446         } else 
447                 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
448
449         /* create log channels */
450         init_logger_chain();
451         return -1;
452 }
453
454 void close_logger(void)
455 {
456         struct msglist *m, *tmp;
457
458         ast_mutex_lock(&msglist_lock);
459         m = list;
460         while(m) {
461                 if (m->msg) {
462                         free(m->msg);
463                 }
464                 tmp = m->next;
465                 free(m);
466                 m = tmp;
467         }
468         list = last = NULL;
469         msgcnt = 0;
470         ast_mutex_unlock(&msglist_lock);
471         return;
472 }
473
474 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, const char *fmt, va_list args) 
475 {
476         char buf[BUFSIZ];
477
478         if (level >= SYSLOG_NLEVELS) {
479                 /* we are locked here, so cannot ast_log() */
480                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
481                 return;
482         }
483         if (level == __LOG_VERBOSE) {
484                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: ", (long)pthread_self());
485                 level = __LOG_DEBUG;
486         } else {
487                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: ",
488                         levels[level], (long)pthread_self(), file, line, function);
489         }
490         vsnprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), fmt, args);
491         syslog(syslog_level_map[level], "%s", buf);
492 }
493
494 /*
495  * send log messages to syslog and/or the console
496  */
497 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
498 {
499         struct logchannel *chan;
500         char buf[BUFSIZ];
501         time_t t;
502         struct tm tm;
503         char date[256];
504
505         va_list ap;
506         
507         if (!option_verbose && !option_debug && (level == __LOG_DEBUG)) {
508                 return;
509         }
510
511         /* begin critical section */
512         ast_mutex_lock(&loglock);
513
514         time(&t);
515         localtime_r(&t, &tm);
516         strftime(date, sizeof(date), dateformat, &tm);
517
518         if (level == __LOG_EVENT) {
519                 va_start(ap, fmt);
520
521                 fprintf(eventlog, "%s asterisk[%d]: ", date, getpid());
522                 vfprintf(eventlog, fmt, ap);
523                 fflush(eventlog);
524
525                 va_end(ap);
526                 ast_mutex_unlock(&loglock);
527                 return;
528         }
529
530         if (logchannels) {
531                 chan = logchannels;
532                 while(chan) {
533                         if (chan->syslog && (chan->logmask & (1 << level))) {
534                                 va_start(ap, fmt);
535                                 ast_log_vsyslog(level, file, line, function, fmt, ap);
536                                 va_end(ap);
537                         } else if ((chan->logmask & (1 << level)) && (chan->console)) {
538                                 char linestr[128];
539                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
540
541                                 if (level != __LOG_VERBOSE) {
542                                         sprintf(linestr, "%d", line);
543                                         snprintf(buf, sizeof(buf), "%s %s[%ld]: %s:%s %s: ",
544                                                 date,
545                                                 term_color(tmp1, levels[level], colors[level], 0, sizeof(tmp1)),
546                                                 (long)pthread_self(),
547                                                 term_color(tmp2, file, COLOR_BRWHITE, 0, sizeof(tmp2)),
548                                                 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
549                                                 term_color(tmp4, function, COLOR_BRWHITE, 0, sizeof(tmp4)));
550                     
551                                         ast_console_puts(buf);
552                                         va_start(ap, fmt);
553                                         vsnprintf(buf, sizeof(buf), fmt, ap);
554                                         va_end(ap);
555                                         ast_console_puts(buf);
556                                 }
557                         } else if ((chan->logmask & (1 << level)) && (chan->fileptr)) {
558                                 snprintf(buf, sizeof(buf), "%s %s[%ld]: ", date,
559                                         levels[level], (long)pthread_self());
560                                 fprintf(chan->fileptr, buf);
561                                 va_start(ap, fmt);
562                                 vsnprintf(buf, sizeof(buf), fmt, ap);
563                                 va_end(ap);
564                                 fputs(buf, chan->fileptr);
565                                 fflush(chan->fileptr);
566                         }
567                         chan = chan->next;
568                 }
569         } else {
570                 /* 
571                  * we don't have the logger chain configured yet,
572                  * so just log to stdout 
573                 */
574                 if (level != __LOG_VERBOSE) {
575                         va_start(ap, fmt);
576                         vsnprintf(buf, sizeof(buf), fmt, ap);
577                         va_end(ap);
578                         fputs(buf, stdout);
579                 }
580         }
581
582         ast_mutex_unlock(&loglock);
583         /* end critical section */
584         if (pending_logger_reload) {
585                 reload_logger(1);
586                 ast_log(LOG_EVENT,"Rotated Logs Per SIGXFSZ\n");
587                 if (option_verbose)
588                         ast_verbose("Rotated Logs Per SIGXFSZ\n");
589         }
590 }
591
592 extern void ast_verbose(const char *fmt, ...)
593 {
594         static char stuff[4096];
595         static int pos = 0, opos;
596         static int replacelast = 0, complete;
597         struct msglist *m;
598         struct verb *v;
599         va_list ap;
600         va_start(ap, fmt);
601         ast_mutex_lock(&msglist_lock);
602         vsnprintf(stuff + pos, sizeof(stuff) - pos, fmt, ap);
603         opos = pos;
604         pos = strlen(stuff);
605         if (fmt[strlen(fmt)-1] == '\n') 
606                 complete = 1;
607         else
608                 complete=0;
609         if (complete) {
610                 if (msgcnt < MAX_MSG_QUEUE) {
611                         /* Allocate new structure */
612                         m = malloc(sizeof(struct msglist));
613                         msgcnt++;
614                 } else {
615                         /* Recycle the oldest entry */
616                         m = list;
617                         list = list->next;
618                         free(m->msg);
619                 }
620                 if (m) {
621                         m->msg = strdup(stuff);
622                         if (m->msg) {
623                                 if (last)
624                                         last->next = m;
625                                 else
626                                         list = m;
627                                 m->next = NULL;
628                                 last = m;
629                         } else {
630                                 msgcnt--;
631                                 ast_log(LOG_ERROR, "Out of memory\n");
632                                 free(m);
633                         }
634                 }
635         }
636         if (verboser) {
637                 v = verboser;
638                 while(v) {
639                         v->verboser(stuff, opos, replacelast, complete);
640                         v = v->next;
641                 }
642         } /* else
643                 fprintf(stdout, stuff + opos); */
644
645         ast_log(LOG_VERBOSE, stuff);
646
647         if (fmt[strlen(fmt)-1] != '\n') 
648                 replacelast = 1;
649         else 
650                 replacelast = pos = 0;
651         va_end(ap);
652
653         ast_mutex_unlock(&msglist_lock);
654 }
655
656 int ast_verbose_dmesg(void (*v)(const char *string, int opos, int replacelast, int complete))
657 {
658         struct msglist *m;
659         ast_mutex_lock(&msglist_lock);
660         m = list;
661         while(m) {
662                 /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
663                 v(m->msg, 0, 0, 1);
664                 m = m->next;
665         }
666         ast_mutex_unlock(&msglist_lock);
667         return 0;
668 }
669
670 int ast_register_verbose(void (*v)(const char *string, int opos, int replacelast, int complete)) 
671 {
672         struct msglist *m;
673         struct verb *tmp;
674         /* XXX Should be more flexible here, taking > 1 verboser XXX */
675         if ((tmp = malloc(sizeof (struct verb)))) {
676                 tmp->verboser = v;
677                 ast_mutex_lock(&msglist_lock);
678                 tmp->next = verboser;
679                 verboser = tmp;
680                 m = list;
681                 while(m) {
682                         /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
683                         v(m->msg, 0, 0, 1);
684                         m = m->next;
685                 }
686                 ast_mutex_unlock(&msglist_lock);
687                 return 0;
688         }
689         return -1;
690 }
691
692 int ast_unregister_verbose(void (*v)(const char *string, int opos, int replacelast, int complete))
693 {
694         int res = -1;
695         struct verb *tmp, *tmpl=NULL;
696         ast_mutex_lock(&msglist_lock);
697         tmp = verboser;
698         while(tmp) {
699                 if (tmp->verboser == v) {
700                         if (tmpl)
701                                 tmpl->next = tmp->next;
702                         else
703                                 verboser = tmp->next;
704                         free(tmp);
705                         break;
706                 }
707                 tmpl = tmp;
708                 tmp = tmp->next;
709         }
710         if (tmp)
711                 res = 0;
712         ast_mutex_unlock(&msglist_lock);
713         return res;
714 }