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