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