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