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