Add some more hold music
[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 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                 strncpy(dateformat, s, sizeof(dateformat) - 1);
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) - 1);
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 {
395         /* Indicate need to reload */
396         pending_logger_reload = 1;
397         return 0;
398 }
399
400 int init_logger(void)
401 {
402         char tmp[256];
403
404         /* auto rotate if sig SIGXFSZ comes a-knockin */
405         (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
406
407         /* register the relaod logger cli command */
408         ast_cli_register(&reload_logger_cli);
409         ast_cli_register(&rotate_logger_cli);
410
411         /* initialize queue logger */
412         queue_log_init();
413
414         /* create the eventlog */
415         mkdir((char *)ast_config_AST_LOG_DIR, 0755);
416         snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_LOG_DIR, EVENTLOG);
417         eventlog = fopen((char *)tmp, "a");
418         if (eventlog) {
419                 init_logger_chain();
420                 ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
421                 if (option_verbose)
422                         ast_verbose("Asterisk Event Logger Started %s\n",(char *)tmp);
423                 return 0;
424         } else 
425                 ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
426
427         /* create log channels */
428         init_logger_chain();
429         return -1;
430 }
431
432 void close_logger(void)
433 {
434         struct msglist *m, *tmp;
435
436         m = list;
437         ast_mutex_lock(&msglist_lock);
438         while(m) {
439                 if (m->msg) {
440                         free(m->msg);
441                 }
442                 tmp = m->next;
443                 free(m);
444                 m = tmp;
445         }
446         list = last = NULL;
447         msgcnt = 0;
448         ast_mutex_unlock(&msglist_lock);
449         return;
450 }
451
452 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, const char *fmt, va_list args) 
453 {
454         char buf[BUFSIZ];
455
456         if (level >= SYSLOG_NLEVELS) {
457                 /* we are locked here, so cannot ast_log() */
458                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
459                 return;
460         }
461         if (level == __LOG_VERBOSE) {
462                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: ", (long)pthread_self());
463                 level = __LOG_DEBUG;
464         } else {
465                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: ",
466                         levels[level], (long)pthread_self(), file, line, function);
467         }
468         vsnprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), fmt, args);
469         syslog(syslog_level_map[level], "%s", buf);
470 }
471
472 /*
473  * send log messages to syslog and/or the console
474  */
475 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
476 {
477         struct logchannel *chan;
478         char buf[BUFSIZ];
479         time_t t;
480         struct tm tm;
481         char date[256];
482
483         va_list ap;
484         
485         if (!option_verbose && !option_debug && (level == __LOG_DEBUG)) {
486                 return;
487         }
488
489         /* begin critical section */
490         ast_mutex_lock(&loglock);
491
492         time(&t);
493         localtime_r(&t, &tm);
494         strftime(date, sizeof(date), dateformat, &tm);
495
496         if (level == __LOG_EVENT) {
497                 va_start(ap, fmt);
498
499                 fprintf(eventlog, "%s asterisk[%d]: ", date, getpid());
500                 vfprintf(eventlog, fmt, ap);
501                 fflush(eventlog);
502
503                 va_end(ap);
504                 ast_mutex_unlock(&loglock);
505                 return;
506         }
507
508         if (logchannels) {
509                 chan = logchannels;
510                 while(chan) {
511                         if (chan->syslog && (chan->logmask & (1 << level))) {
512                                 va_start(ap, fmt);
513                                 ast_log_vsyslog(level, file, line, function, fmt, ap);
514                                 va_end(ap);
515                         } else if ((chan->logmask & (1 << level)) && (chan->console)) {
516                                 char linestr[128];
517                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
518
519                                 if (level != __LOG_VERBOSE) {
520                                         sprintf(linestr, "%d", line);
521                                         snprintf(buf, sizeof(buf), "%s %s[%ld]: %s:%s %s: ",
522                                                 date,
523                                                 term_color(tmp1, levels[level], colors[level], 0, sizeof(tmp1)),
524                                                 (long)pthread_self(),
525                                                 term_color(tmp2, file, COLOR_BRWHITE, 0, sizeof(tmp2)),
526                                                 term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
527                                                 term_color(tmp4, function, COLOR_BRWHITE, 0, sizeof(tmp4)));
528                     
529                                         ast_console_puts(buf);
530                                         va_start(ap, fmt);
531                                         vsnprintf(buf, sizeof(buf), fmt, ap);
532                                         va_end(ap);
533                                         ast_console_puts(buf);
534                                 }
535                         } else if ((chan->logmask & (1 << level)) && (chan->fileptr)) {
536                                 snprintf(buf, sizeof(buf), "%s %s[%ld]: ", date,
537                                         levels[level], (long)pthread_self());
538                                 fprintf(chan->fileptr, buf);
539                                 va_start(ap, fmt);
540                                 vsnprintf(buf, sizeof(buf), fmt, ap);
541                                 va_end(ap);
542                                 fputs(buf, chan->fileptr);
543                                 fflush(chan->fileptr);
544                         }
545                         chan = chan->next;
546                 }
547         } else {
548                 /* 
549                  * we don't have the logger chain configured yet,
550                  * so just log to stdout 
551                 */
552                 if (level != __LOG_VERBOSE) {
553                         va_start(ap, fmt);
554                         vsnprintf(buf, sizeof(buf), fmt, ap);
555                         va_end(ap);
556                         fputs(buf, stdout);
557                 }
558         }
559
560         ast_mutex_unlock(&loglock);
561         /* end critical section */
562         if (pending_logger_reload) {
563                 reload_logger(1);
564                 ast_log(LOG_EVENT,"Rotated Logs Per SIGXFSZ\n");
565                 if (option_verbose)
566                         ast_verbose("Rotated Logs Per SIGXFSZ\n");
567         }
568 }
569
570 extern void ast_verbose(const char *fmt, ...)
571 {
572         static char stuff[4096];
573         static int pos = 0, opos;
574         static int replacelast = 0, complete;
575         struct msglist *m;
576         struct verb *v;
577         va_list ap;
578         va_start(ap, fmt);
579         ast_mutex_lock(&msglist_lock);
580         vsnprintf(stuff + pos, sizeof(stuff) - pos, fmt, ap);
581         opos = pos;
582         pos = strlen(stuff);
583         if (fmt[strlen(fmt)-1] == '\n') 
584                 complete = 1;
585         else
586                 complete=0;
587         if (complete) {
588                 if (msgcnt < MAX_MSG_QUEUE) {
589                         /* Allocate new structure */
590                         m = malloc(sizeof(struct msglist));
591                         msgcnt++;
592                 } else {
593                         /* Recycle the oldest entry */
594                         m = list;
595                         list = list->next;
596                         free(m->msg);
597                 }
598                 if (m) {
599                         m->msg = strdup(stuff);
600                         if (m->msg) {
601                                 if (last)
602                                         last->next = m;
603                                 else
604                                         list = m;
605                                 m->next = NULL;
606                                 last = m;
607                         } else {
608                                 msgcnt--;
609                                 ast_log(LOG_ERROR, "Out of memory\n");
610                                 free(m);
611                         }
612                 }
613         }
614         if (verboser) {
615                 v = verboser;
616                 while(v) {
617                         v->verboser(stuff, opos, replacelast, complete);
618                         v = v->next;
619                 }
620         } /* else
621                 fprintf(stdout, stuff + opos); */
622
623         ast_log(LOG_VERBOSE, stuff);
624
625         if (fmt[strlen(fmt)-1] != '\n') 
626                 replacelast = 1;
627         else 
628                 replacelast = pos = 0;
629         va_end(ap);
630
631         ast_mutex_unlock(&msglist_lock);
632 }
633
634 int ast_verbose_dmesg(void (*v)(const char *string, int opos, int replacelast, int complete))
635 {
636         struct msglist *m;
637         m = list;
638         ast_mutex_lock(&msglist_lock);
639         while(m) {
640                 /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
641                 v(m->msg, 0, 0, 1);
642                 m = m->next;
643         }
644         ast_mutex_unlock(&msglist_lock);
645         return 0;
646 }
647
648 int ast_register_verbose(void (*v)(const char *string, int opos, int replacelast, int complete)) 
649 {
650         struct msglist *m;
651         struct verb *tmp;
652         /* XXX Should be more flexible here, taking > 1 verboser XXX */
653         if ((tmp = malloc(sizeof (struct verb)))) {
654                 tmp->verboser = v;
655                 ast_mutex_lock(&msglist_lock);
656                 tmp->next = verboser;
657                 verboser = tmp;
658                 m = list;
659                 while(m) {
660                         /* Send all the existing entries that we have queued (i.e. they're likely to have missed) */
661                         v(m->msg, 0, 0, 1);
662                         m = m->next;
663                 }
664                 ast_mutex_unlock(&msglist_lock);
665                 return 0;
666         }
667         return -1;
668 }
669
670 int ast_unregister_verbose(void (*v)(const char *string, int opos, int replacelast, int complete))
671 {
672         int res = -1;
673         struct verb *tmp, *tmpl=NULL;
674         ast_mutex_lock(&msglist_lock);
675         tmp = verboser;
676         while(tmp) {
677                 if (tmp->verboser == v) {
678                         if (tmpl)
679                                 tmpl->next = tmp->next;
680                         else
681                                 verboser = tmp->next;
682                         free(tmp);
683                         break;
684                 }
685                 tmpl = tmp;
686                 tmp = tmp->next;
687         }
688         if (tmp)
689                 res = 0;
690         ast_mutex_unlock(&msglist_lock);
691         return res;
692 }