5d803377b763c4d296070c470fef6ee3a7a95597
[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/types.h>
41 #include <sys/stat.h>
42 #include <fcntl.h>
43 #if ((defined(AST_DEVMODE)) && (defined(linux)))
44 #include <execinfo.h>
45 #define MAX_BACKTRACE_FRAMES 20
46 #endif
47
48 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
49                         from <syslog.h> which is included by logger.h */
50 #include <syslog.h>
51
52 static int syslog_level_map[] = {
53         LOG_DEBUG,
54         LOG_INFO,    /* arbitrary equivalent of LOG_EVENT */
55         LOG_NOTICE,
56         LOG_WARNING,
57         LOG_ERR,
58         LOG_DEBUG,
59         LOG_DEBUG
60 };
61
62 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
63
64 #include "asterisk/logger.h"
65 #include "asterisk/lock.h"
66 #include "asterisk/options.h"
67 #include "asterisk/channel.h"
68 #include "asterisk/config.h"
69 #include "asterisk/term.h"
70 #include "asterisk/cli.h"
71 #include "asterisk/utils.h"
72 #include "asterisk/manager.h"
73 #include "asterisk/threadstorage.h"
74 #include "asterisk/strings.h"
75 #include "asterisk/channel.h"
76 #include "asterisk/pbx.h"
77
78 #if defined(__linux__) && !defined(__NR_gettid)
79 #include <asm/unistd.h>
80 #endif
81
82 #if defined(__linux__) && defined(__NR_gettid)
83 #define GETTID() syscall(__NR_gettid)
84 #else
85 #define GETTID() getpid()
86 #endif
87
88 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
89
90 static char queue_log_name[256] = QUEUELOG;
91 static char exec_after_rotate[256] = "";
92
93 static int filesize_reload_needed;
94 static int global_logmask = -1;
95
96 enum rotatestrategy {
97         SEQUENTIAL = 1 << 0,     /* Original method - create a new file, in order */
98         ROTATE = 1 << 1,         /* Rotate all files, such that the oldest file has the highest suffix */
99         TIMESTAMP = 1 << 2,      /* Append the epoch timestamp onto the end of the archived file */
100 } rotatestrategy = SEQUENTIAL;
101
102 static struct {
103         unsigned int queue_log:1;
104         unsigned int event_log:1;
105 } logfiles = { 1, 1 };
106
107 static char hostname[MAXHOSTNAMELEN];
108
109 enum logtypes {
110         LOGTYPE_SYSLOG,
111         LOGTYPE_FILE,
112         LOGTYPE_CONSOLE,
113 };
114
115 struct logchannel {
116         int logmask;                    /* What to log to this channel */
117         int disabled;                   /* If this channel is disabled or not */
118         int facility;                   /* syslog facility */
119         enum logtypes type;             /* Type of log channel */
120         FILE *fileptr;                  /* logfile logging file pointer */
121         char filename[256];             /* Filename */
122         AST_LIST_ENTRY(logchannel) list;
123 };
124
125 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
126
127 enum logmsgtypes {
128         LOGMSG_NORMAL = 0,
129         LOGMSG_VERBOSE,
130 };
131
132 struct logmsg {
133         enum logmsgtypes type;
134         char date[256];
135         int level;
136         const char *file;
137         int line;
138         const char *function;
139         AST_LIST_ENTRY(logmsg) list;
140         char str[0];
141 };
142
143 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
144 static pthread_t logthread = AST_PTHREADT_NULL;
145 static ast_cond_t logcond;
146 static int close_logger_thread;
147
148 static FILE *eventlog;
149 static FILE *qlog;
150
151 static char *levels[] = {
152         "DEBUG",
153         "EVENT",
154         "NOTICE",
155         "WARNING",
156         "ERROR",
157         "VERBOSE",
158         "DTMF"
159 };
160
161 static int colors[] = {
162         COLOR_BRGREEN,
163         COLOR_BRBLUE,
164         COLOR_YELLOW,
165         COLOR_BRRED,
166         COLOR_RED,
167         COLOR_GREEN,
168         COLOR_BRGREEN
169 };
170
171 AST_THREADSTORAGE(verbose_buf);
172 #define VERBOSE_BUF_INIT_SIZE   256
173
174 AST_THREADSTORAGE(log_buf);
175 #define LOG_BUF_INIT_SIZE       256
176
177 static int make_components(char *s, int lineno)
178 {
179         char *w;
180         int res = 0;
181         char *stringp = s;
182
183         while ((w = strsep(&stringp, ","))) {
184                 w = ast_skip_blanks(w);
185                 if (!strcasecmp(w, "error")) 
186                         res |= (1 << __LOG_ERROR);
187                 else if (!strcasecmp(w, "warning"))
188                         res |= (1 << __LOG_WARNING);
189                 else if (!strcasecmp(w, "notice"))
190                         res |= (1 << __LOG_NOTICE);
191                 else if (!strcasecmp(w, "event"))
192                         res |= (1 << __LOG_EVENT);
193                 else if (!strcasecmp(w, "debug"))
194                         res |= (1 << __LOG_DEBUG);
195                 else if (!strcasecmp(w, "verbose"))
196                         res |= (1 << __LOG_VERBOSE);
197                 else if (!strcasecmp(w, "dtmf"))
198                         res |= (1 << __LOG_DTMF);
199                 else {
200                         fprintf(stderr, "Logfile Warning: Unknown keyword '%s' at line %d of logger.conf\n", w, lineno);
201                 }
202         }
203
204         return res;
205 }
206
207 static struct logchannel *make_logchannel(char *channel, char *components, int lineno)
208 {
209         struct logchannel *chan;
210         char *facility;
211 #ifndef SOLARIS
212         CODE *cptr;
213 #endif
214
215         if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan))))
216                 return NULL;
217
218         if (!strcasecmp(channel, "console")) {
219                 chan->type = LOGTYPE_CONSOLE;
220         } else if (!strncasecmp(channel, "syslog", 6)) {
221                 /*
222                 * syntax is:
223                 *  syslog.facility => level,level,level
224                 */
225                 facility = strchr(channel, '.');
226                 if (!facility++ || !facility) {
227                         facility = "local0";
228                 }
229
230 #ifndef SOLARIS
231                 /*
232                 * Walk through the list of facilitynames (defined in sys/syslog.h)
233                 * to see if we can find the one we have been given
234                 */
235                 chan->facility = -1;
236                 cptr = facilitynames;
237                 while (cptr->c_name) {
238                         if (!strcasecmp(facility, cptr->c_name)) {
239                                 chan->facility = cptr->c_val;
240                                 break;
241                         }
242                         cptr++;
243                 }
244 #else
245                 chan->facility = -1;
246                 if (!strcasecmp(facility, "kern")) 
247                         chan->facility = LOG_KERN;
248                 else if (!strcasecmp(facility, "USER")) 
249                         chan->facility = LOG_USER;
250                 else if (!strcasecmp(facility, "MAIL")) 
251                         chan->facility = LOG_MAIL;
252                 else if (!strcasecmp(facility, "DAEMON")) 
253                         chan->facility = LOG_DAEMON;
254                 else if (!strcasecmp(facility, "AUTH")) 
255                         chan->facility = LOG_AUTH;
256                 else if (!strcasecmp(facility, "SYSLOG")) 
257                         chan->facility = LOG_SYSLOG;
258                 else if (!strcasecmp(facility, "LPR")) 
259                         chan->facility = LOG_LPR;
260                 else if (!strcasecmp(facility, "NEWS")) 
261                         chan->facility = LOG_NEWS;
262                 else if (!strcasecmp(facility, "UUCP")) 
263                         chan->facility = LOG_UUCP;
264                 else if (!strcasecmp(facility, "CRON")) 
265                         chan->facility = LOG_CRON;
266                 else if (!strcasecmp(facility, "LOCAL0")) 
267                         chan->facility = LOG_LOCAL0;
268                 else if (!strcasecmp(facility, "LOCAL1")) 
269                         chan->facility = LOG_LOCAL1;
270                 else if (!strcasecmp(facility, "LOCAL2")) 
271                         chan->facility = LOG_LOCAL2;
272                 else if (!strcasecmp(facility, "LOCAL3")) 
273                         chan->facility = LOG_LOCAL3;
274                 else if (!strcasecmp(facility, "LOCAL4")) 
275                         chan->facility = LOG_LOCAL4;
276                 else if (!strcasecmp(facility, "LOCAL5")) 
277                         chan->facility = LOG_LOCAL5;
278                 else if (!strcasecmp(facility, "LOCAL6")) 
279                         chan->facility = LOG_LOCAL6;
280                 else if (!strcasecmp(facility, "LOCAL7")) 
281                         chan->facility = LOG_LOCAL7;
282 #endif /* Solaris */
283
284                 if (0 > chan->facility) {
285                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
286                         free(chan);
287                         return NULL;
288                 }
289
290                 chan->type = LOGTYPE_SYSLOG;
291                 snprintf(chan->filename, sizeof(chan->filename), "%s", channel);
292                 openlog("asterisk", LOG_PID, chan->facility);
293         } else {
294                 if (channel[0] == '/') {
295                         if (!ast_strlen_zero(hostname)) { 
296                                 snprintf(chan->filename, sizeof(chan->filename) - 1,"%s.%s", channel, hostname);
297                         } else {
298                                 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
299                         }
300                 }                 
301                 
302                 if (!ast_strlen_zero(hostname)) {
303                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s", ast_config_AST_LOG_DIR, channel, hostname);
304                 } else {
305                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s", ast_config_AST_LOG_DIR, channel);
306                 }
307                 chan->fileptr = fopen(chan->filename, "a");
308                 if (!chan->fileptr) {
309                         /* Can't log here, since we're called with a lock */
310                         fprintf(stderr, "Logger Warning: Unable to open log file '%s': %s\n", chan->filename, strerror(errno));
311                 } 
312                 chan->type = LOGTYPE_FILE;
313         }
314         chan->logmask = make_components(components, lineno);
315         return chan;
316 }
317
318 static void init_logger_chain(int reload, int locked)
319 {
320         struct logchannel *chan;
321         struct ast_config *cfg;
322         struct ast_variable *var;
323         const char *s;
324         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
325
326         if ((cfg = ast_config_load("logger.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
327                 return;
328
329         /* delete our list of log channels */
330         if (!locked)
331                 AST_RWLIST_WRLOCK(&logchannels);
332         while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list)))
333                 free(chan);
334         if (!locked)
335                 AST_RWLIST_UNLOCK(&logchannels);
336         
337         global_logmask = 0;
338         errno = 0;
339         /* close syslog */
340         closelog();
341         
342         /* If no config file, we're fine, set default options. */
343         if (!cfg) {
344                 if (errno)
345                         fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
346                 else
347                         fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
348                 if (!(chan = ast_calloc(1, sizeof(*chan))))
349                         return;
350                 chan->type = LOGTYPE_CONSOLE;
351                 chan->logmask = 28; /*warning,notice,error */
352                 if (!locked)
353                         AST_RWLIST_WRLOCK(&logchannels);
354                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
355                 if (!locked)
356                         AST_RWLIST_UNLOCK(&logchannels);
357                 global_logmask |= chan->logmask;
358                 return;
359         }
360         
361         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
362                 if (ast_true(s)) {
363                         if (gethostname(hostname, sizeof(hostname) - 1)) {
364                                 ast_copy_string(hostname, "unknown", sizeof(hostname));
365                                 fprintf(stderr, "What box has no hostname???\n");
366                         }
367                 } else
368                         hostname[0] = '\0';
369         } else
370                 hostname[0] = '\0';
371         if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
372                 ast_copy_string(dateformat, s, sizeof(dateformat));
373         else
374                 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
375         if ((s = ast_variable_retrieve(cfg, "general", "queue_log")))
376                 logfiles.queue_log = ast_true(s);
377         if ((s = ast_variable_retrieve(cfg, "general", "event_log")))
378                 logfiles.event_log = ast_true(s);
379         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name")))
380                 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
381         if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate")))
382                 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
383         if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
384                 if (strcasecmp(s, "timestamp") == 0)
385                         rotatestrategy = TIMESTAMP;
386                 else if (strcasecmp(s, "rotate") == 0)
387                         rotatestrategy = ROTATE;
388                 else if (strcasecmp(s, "sequential") == 0)
389                         rotatestrategy = SEQUENTIAL;
390                 else
391                         fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
392         } else {
393                 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
394                         rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
395                         fprintf(stderr, "rotatetimestamp option has been deprecated.  Please use rotatestrategy instead.\n");
396                 }
397         }
398
399         if (!locked)
400                 AST_RWLIST_WRLOCK(&logchannels);
401         var = ast_variable_browse(cfg, "logfiles");
402         for (; var; var = var->next) {
403                 if (!(chan = make_logchannel(var->name, var->value, var->lineno)))
404                         continue;
405                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
406                 global_logmask |= chan->logmask;
407         }
408         if (!locked)
409                 AST_RWLIST_UNLOCK(&logchannels);
410
411         ast_config_destroy(cfg);
412 }
413
414 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
415 {
416         va_list ap;
417         char qlog_msg[8192];
418         int qlog_len;
419         if (qlog) {
420                 va_start(ap, fmt);
421                 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
422                 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
423                 va_end(ap);
424         }
425         AST_RWLIST_RDLOCK(&logchannels);
426         if (qlog) {
427                 fprintf(qlog, "%s\n", qlog_msg);
428                 fflush(qlog);
429         }
430         AST_RWLIST_UNLOCK(&logchannels);
431 }
432
433 static int rotate_file(const char *filename)
434 {
435         char old[PATH_MAX];
436         char new[PATH_MAX];
437         int x, y, which, found, res = 0, fd;
438         char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
439
440         switch (rotatestrategy) {
441         case SEQUENTIAL:
442                 for (x = 0; ; x++) {
443                         snprintf(new, sizeof(new), "%s.%d", filename, x);
444                         fd = open(new, O_RDONLY);
445                         if (fd > -1)
446                                 close(fd);
447                         else
448                                 break;
449                 }
450                 if (rename(filename, new)) {
451                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
452                         res = -1;
453                 }
454                 break;
455         case TIMESTAMP:
456                 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
457                 if (rename(filename, new)) {
458                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
459                         res = -1;
460                 }
461                 break;
462         case ROTATE:
463                 /* Find the next empty slot, including a possible suffix */
464                 for (x = 0; ; x++) {
465                         found = 0;
466                         for (which = 0; which < sizeof(suffixes) / sizeof(suffixes[0]); which++) {
467                                 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
468                                 fd = open(new, O_RDONLY);
469                                 if (fd > -1)
470                                         close(fd);
471                                 else {
472                                         found = 1;
473                                         break;
474                                 }
475                         }
476                         if (!found)
477                                 break;
478                 }
479
480                 /* Found an empty slot */
481                 for (y = x; y > -1; y--) {
482                         for (which = 0; which < sizeof(suffixes) / sizeof(suffixes[0]); which++) {
483                                 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
484                                 fd = open(old, O_RDONLY);
485                                 if (fd > -1) {
486                                         /* Found the right suffix */
487                                         close(fd);
488                                         snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
489                                         if (rename(old, new)) {
490                                                 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
491                                                 res = -1;
492                                         }
493                                         break;
494                                 }
495                         }
496                 }
497
498                 /* Finally, rename the current file */
499                 snprintf(new, sizeof(new), "%s.0", filename);
500                 if (rename(filename, new)) {
501                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
502                         res = -1;
503                 }
504         }
505
506         if (!ast_strlen_zero(exec_after_rotate)) {
507                 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Logger/rotate");
508                 char buf[512] = "";
509                 pbx_builtin_setvar_helper(c, "filename", filename);
510                 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
511                 system(buf);
512                 ast_channel_free(c);
513         }
514         return res;
515 }
516
517 int reload_logger(int rotate)
518 {
519         char old[PATH_MAX] = "";
520         int event_rotate = rotate, queue_rotate = rotate;
521         struct logchannel *f;
522         int res = 0;
523         struct stat st;
524
525         AST_RWLIST_WRLOCK(&logchannels);
526
527         if (eventlog) {
528                 if (rotate < 0) {
529                         /* Check filesize - this one typically doesn't need an auto-rotate */
530                         snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
531                         if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
532                                 fclose(eventlog);
533                                 eventlog = NULL;
534                         } else
535                                 event_rotate = 0;
536                 } else {
537                         fclose(eventlog);
538                         eventlog = NULL;
539                 }
540         } else
541                 event_rotate = 0;
542
543         if (qlog) {
544                 if (rotate < 0) {
545                         /* Check filesize - this one typically doesn't need an auto-rotate */
546                         snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
547                         if (stat(old, &st) != 0 || st.st_size > 0x40000000) { /* Arbitrarily, 1 GB */
548                                 fclose(qlog);
549                                 qlog = NULL;
550                         } else
551                                 event_rotate = 0;
552                 } else {
553                         fclose(qlog);
554                         qlog = NULL;
555                 }
556         } else 
557                 queue_rotate = 0;
558         qlog = NULL;
559
560         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
561
562         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
563                 if (f->disabled) {
564                         f->disabled = 0;        /* Re-enable logging at reload */
565                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
566                 }
567                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
568                         fclose(f->fileptr);     /* Close file */
569                         f->fileptr = NULL;
570                         if (rotate)
571                                 rotate_file(f->filename);
572                 }
573         }
574
575         filesize_reload_needed = 0;
576
577         init_logger_chain(1, 1);
578
579         if (logfiles.event_log) {
580                 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
581                 if (event_rotate)
582                         rotate_file(old);
583
584                 eventlog = fopen(old, "a");
585                 if (eventlog) {
586                         ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
587                         if (option_verbose)
588                                 ast_verbose("Asterisk Event Logger restarted\n");
589                 } else {
590                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
591                         res = -1;
592                 }
593         }
594
595         if (logfiles.queue_log) {
596                 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
597                 if (queue_rotate)
598                         rotate_file(old);
599
600                 qlog = fopen(old, "a");
601                 if (qlog) {
602                         AST_RWLIST_UNLOCK(&logchannels);
603                         ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
604                         AST_RWLIST_WRLOCK(&logchannels);
605                         ast_log(LOG_EVENT, "Restarted Asterisk Queue Logger\n");
606                         if (option_verbose)
607                                 ast_verbose("Asterisk Queue Logger restarted\n");
608                 } else {
609                         ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
610                         res = -1;
611                 }
612         }
613
614         AST_RWLIST_UNLOCK(&logchannels);
615
616         return res;
617 }
618
619 static int handle_logger_reload(int fd, int argc, char *argv[])
620 {
621         if (reload_logger(0)) {
622                 ast_cli(fd, "Failed to reload the logger\n");
623                 return RESULT_FAILURE;
624         } else
625                 return RESULT_SUCCESS;
626 }
627
628 static int handle_logger_rotate(int fd, int argc, char *argv[])
629 {
630         if (reload_logger(1)) {
631                 ast_cli(fd, "Failed to reload the logger and rotate log files\n");
632                 return RESULT_FAILURE;
633         } else
634                 return RESULT_SUCCESS;
635 }
636
637 /*! \brief CLI command to show logging system configuration */
638 static int handle_logger_show_channels(int fd, int argc, char *argv[])
639 {
640 #define FORMATL "%-35.35s %-8.8s %-9.9s "
641         struct logchannel *chan;
642
643         ast_cli(fd,FORMATL, "Channel", "Type", "Status");
644         ast_cli(fd, "Configuration\n");
645         ast_cli(fd,FORMATL, "-------", "----", "------");
646         ast_cli(fd, "-------------\n");
647         AST_RWLIST_RDLOCK(&logchannels);
648         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
649                 ast_cli(fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
650                         chan->disabled ? "Disabled" : "Enabled");
651                 ast_cli(fd, " - ");
652                 if (chan->logmask & (1 << __LOG_DEBUG)) 
653                         ast_cli(fd, "Debug ");
654                 if (chan->logmask & (1 << __LOG_DTMF)) 
655                         ast_cli(fd, "DTMF ");
656                 if (chan->logmask & (1 << __LOG_VERBOSE)) 
657                         ast_cli(fd, "Verbose ");
658                 if (chan->logmask & (1 << __LOG_WARNING)) 
659                         ast_cli(fd, "Warning ");
660                 if (chan->logmask & (1 << __LOG_NOTICE)) 
661                         ast_cli(fd, "Notice ");
662                 if (chan->logmask & (1 << __LOG_ERROR)) 
663                         ast_cli(fd, "Error ");
664                 if (chan->logmask & (1 << __LOG_EVENT)) 
665                         ast_cli(fd, "Event ");
666                 ast_cli(fd, "\n");
667         }
668         AST_RWLIST_UNLOCK(&logchannels);
669         ast_cli(fd, "\n");
670                 
671         return RESULT_SUCCESS;
672 }
673
674 struct verb {
675         void (*verboser)(const char *string);
676         AST_LIST_ENTRY(verb) list;
677 };
678
679 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
680
681 static char logger_reload_help[] =
682 "Usage: logger reload\n"
683 "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
684
685 static char logger_rotate_help[] =
686 "Usage: logger rotate\n"
687 "       Rotates and Reopens the log files.\n";
688
689 static char logger_show_channels_help[] =
690 "Usage: logger show channels\n"
691 "       List configured logger channels.\n";
692
693 static struct ast_cli_entry cli_logger[] = {
694         { { "logger", "show", "channels", NULL }, 
695         handle_logger_show_channels, "List configured log channels",
696         logger_show_channels_help },
697
698         { { "logger", "reload", NULL }, 
699         handle_logger_reload, "Reopens the log files",
700         logger_reload_help },
701
702         { { "logger", "rotate", NULL }, 
703         handle_logger_rotate, "Rotates and reopens the log files",
704         logger_rotate_help },
705 };
706
707 static int handle_SIGXFSZ(int sig) 
708 {
709         /* Indicate need to reload */
710         filesize_reload_needed = 1;
711         return 0;
712 }
713
714 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str)
715 {
716         char buf[BUFSIZ];
717
718         if (level >= SYSLOG_NLEVELS) {
719                 /* we are locked here, so cannot ast_log() */
720                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
721                 return;
722         }
723
724         if (level == __LOG_VERBOSE) {
725                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", (long)GETTID(), str);
726                 level = __LOG_DEBUG;
727         } else if (level == __LOG_DTMF) {
728                 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", (long)GETTID(), str);
729                 level = __LOG_DEBUG;
730         } else {
731                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
732                          levels[level], (long)GETTID(), file, line, function, str);
733         }
734
735         term_strip(buf, buf, strlen(buf) + 1);
736         syslog(syslog_level_map[level], "%s", buf);
737 }
738
739 /* Print a normal log message to the channels */
740 static void logger_print_normal(struct logmsg *logmsg)
741 {
742         struct logchannel *chan = NULL;
743         char buf[BUFSIZ];
744
745         AST_RWLIST_RDLOCK(&logchannels);
746
747         if (logfiles.event_log && logmsg->level == __LOG_EVENT) {
748                 fprintf(eventlog, "%s asterisk[%ld]: %s", logmsg->date, (long)getpid(), logmsg->str);
749                 fflush(eventlog);
750                 AST_RWLIST_UNLOCK(&logchannels);
751                 return;
752         }
753
754         if (!AST_RWLIST_EMPTY(&logchannels)) {
755                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
756                         /* If the channel is disabled, then move on to the next one */
757                         if (chan->disabled)
758                                 continue;
759                         /* Check syslog channels */
760                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
761                                 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str);
762                         /* Console channels */
763                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
764                                 char linestr[128];
765                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
766
767                                 /* If the level is verbose, then skip it */
768                                 if (logmsg->level == __LOG_VERBOSE)
769                                         continue;
770
771                                 /* Turn the numerical line number into a string */
772                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
773                                 /* Build string to print out */
774                                 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
775                                          logmsg->date,
776                                          term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
777                                          (long)GETTID(),
778                                          term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
779                                          term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
780                                          term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
781                                          logmsg->str);
782                                 /* Print out */
783                                 ast_console_puts_mutable(buf);
784                         /* File channels */
785                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
786                                 int res = 0;
787
788                                 /* If no file pointer exists, skip it */
789                                 if (!chan->fileptr)
790                                         continue;
791                                 
792                                 /* Print out to the file */
793                                 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
794                                               logmsg->date, levels[logmsg->level], (long)GETTID(), logmsg->file, logmsg->str);
795                                 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
796                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
797                                         if (errno == ENOMEM || errno == ENOSPC)
798                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
799                                         else
800                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
801                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
802                                         chan->disabled = 1;
803                                 } else if (res > 0) {
804                                         fflush(chan->fileptr);
805                                 }
806                         }
807                 }
808         } else if (logmsg->level != __LOG_VERBOSE) {
809                 fputs(logmsg->str, stdout);
810         }
811
812         AST_RWLIST_UNLOCK(&logchannels);
813
814         /* If we need to reload because of the file size, then do so */
815         if (filesize_reload_needed) {
816                 reload_logger(-1);
817                 ast_log(LOG_EVENT, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
818                 if (option_verbose)
819                         ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
820         }
821
822         return;
823 }
824
825 /* Print a verbose message to the verbosers */
826 static void logger_print_verbose(struct logmsg *logmsg)
827 {
828         struct verb *v = NULL;
829
830         /* Iterate through the list of verbosers and pass them the log message string */
831         AST_RWLIST_RDLOCK(&verbosers);
832         AST_RWLIST_TRAVERSE(&verbosers, v, list)
833                 v->verboser(logmsg->str);
834         AST_RWLIST_UNLOCK(&verbosers);
835
836         return;
837 }
838
839 /* Actual logging thread */
840 static void *logger_thread(void *data)
841 {
842         struct logmsg *next = NULL, *msg = NULL;
843
844         for (;;) {
845                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
846                 AST_LIST_LOCK(&logmsgs);
847                 if (AST_LIST_EMPTY(&logmsgs))
848                         ast_cond_wait(&logcond, &logmsgs.lock);
849                 next = AST_LIST_FIRST(&logmsgs);
850                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
851                 AST_LIST_UNLOCK(&logmsgs);
852
853                 /* If we should stop, then stop */
854                 if (close_logger_thread)
855                         break;
856
857                 /* Otherwise go through and process each message in the order added */
858                 while ((msg = next)) {
859                         /* Get the next entry now so that we can free our current structure later */
860                         next = AST_LIST_NEXT(msg, list);
861
862                         /* Depending on the type, send it to the proper function */
863                         if (msg->type == LOGMSG_NORMAL)
864                                 logger_print_normal(msg);
865                         else if (msg->type == LOGMSG_VERBOSE)
866                                 logger_print_verbose(msg);
867
868                         /* Free the data since we are done */
869                         free(msg);
870                 }
871         }
872
873         return NULL;
874 }
875
876 int init_logger(void)
877 {
878         char tmp[256];
879         int res = 0;
880
881         /* auto rotate if sig SIGXFSZ comes a-knockin */
882         (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
883
884         /* start logger thread */
885         ast_cond_init(&logcond, NULL);
886         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
887                 ast_cond_destroy(&logcond);
888                 return -1;
889         }
890
891         /* register the logger cli commands */
892         ast_cli_register_multiple(cli_logger, sizeof(cli_logger) / sizeof(struct ast_cli_entry));
893
894         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
895   
896         /* create log channels */
897         init_logger_chain(0, 0);
898
899         /* create the eventlog */
900         if (logfiles.event_log) {
901                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
902                 eventlog = fopen(tmp, "a");
903                 if (eventlog) {
904                         ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
905                         if (option_verbose)
906                                 ast_verbose("Asterisk Event Logger Started %s\n", tmp);
907                 } else {
908                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
909                         res = -1;
910                 }
911         }
912
913         if (logfiles.queue_log) {
914                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
915                 qlog = fopen(tmp, "a");
916                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
917         }
918         return res;
919 }
920
921 void close_logger(void)
922 {
923         struct logchannel *f = NULL;
924
925         /* Stop logger thread */
926         AST_LIST_LOCK(&logmsgs);
927         close_logger_thread = 1;
928         ast_cond_signal(&logcond);
929         AST_LIST_UNLOCK(&logmsgs);
930
931         AST_RWLIST_WRLOCK(&logchannels);
932
933         if (eventlog) {
934                 fclose(eventlog);
935                 eventlog = NULL;
936         }
937
938         if (qlog) {
939                 fclose(qlog);
940                 qlog = NULL;
941         }
942
943         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
944                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
945                         fclose(f->fileptr);
946                         f->fileptr = NULL;
947                 }
948         }
949
950         closelog(); /* syslog */
951
952         AST_RWLIST_UNLOCK(&logchannels);
953
954         return;
955 }
956
957 /*!
958  * \brief send log messages to syslog and/or the console
959  */
960 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
961 {
962         struct logmsg *logmsg = NULL;
963         struct ast_str *buf = NULL;
964         struct ast_tm tm;
965         struct timeval tv = ast_tvnow();
966         int res = 0;
967         va_list ap;
968
969         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
970                 return;
971
972         if (AST_RWLIST_EMPTY(&logchannels)) {
973                 /*
974                  * we don't have the logger chain configured yet,
975                  * so just log to stdout
976                  */
977                 if (level != __LOG_VERBOSE) {
978                         int res;
979                         va_start(ap, fmt);
980                         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
981                         va_end(ap);
982                         if (res != AST_DYNSTR_BUILD_FAILED) {
983                                 term_filter_escapes(buf->str);
984                                 fputs(buf->str, stdout);
985                         }
986                 }
987                 return;
988         }
989         
990         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
991            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
992            is zero, if option_verbose is non-zero (this allows for 'level zero'
993            LOG_DEBUG messages to be displayed, if the logmask on any channel
994            allows it)
995         */
996         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
997                 return;
998
999         /* Ignore anything that never gets logged anywhere */
1000         if (!(global_logmask & (1 << level)))
1001                 return;
1002         
1003         /* Build string */
1004         va_start(ap, fmt);
1005         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1006         va_end(ap);
1007
1008         /* If the build failed, then abort and free this structure */
1009         if (res == AST_DYNSTR_BUILD_FAILED)
1010                 return;
1011
1012         /* Create a new logging message */
1013         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1014                 return;
1015         
1016         /* Copy string over */
1017         strcpy(logmsg->str, buf->str);
1018
1019         /* Set type to be normal */
1020         logmsg->type = LOGMSG_NORMAL;
1021
1022         /* Create our date/time */
1023         ast_localtime(&tv, &tm, NULL);
1024         ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1025
1026         /* Copy over data */
1027         logmsg->level = level;
1028         logmsg->file = file;
1029         logmsg->line = line;
1030         logmsg->function = function;
1031
1032         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1033         if (logthread != AST_PTHREADT_NULL) {
1034                 AST_LIST_LOCK(&logmsgs);
1035                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1036                 ast_cond_signal(&logcond);
1037                 AST_LIST_UNLOCK(&logmsgs);
1038         } else {
1039                 logger_print_normal(logmsg);
1040                 free(logmsg);
1041         }
1042
1043         return;
1044 }
1045
1046 void ast_backtrace(void)
1047 {
1048 #ifdef linux
1049 #ifdef AST_DEVMODE
1050         int count=0, i=0;
1051         void **addresses;
1052         char **strings;
1053
1054         if ((addresses = ast_calloc(MAX_BACKTRACE_FRAMES, sizeof(*addresses)))) {
1055                 count = backtrace(addresses, MAX_BACKTRACE_FRAMES);
1056                 if ((strings = backtrace_symbols(addresses, count))) {
1057                         ast_debug(1, "Got %d backtrace record%c\n", count, count != 1 ? 's' : ' ');
1058                         for (i=0; i < count ; i++) {
1059 #if __WORDSIZE == 32
1060                                 ast_log(LOG_DEBUG, "#%d: [%08X] %s\n", i, (unsigned int)addresses[i], strings[i]);
1061 #elif __WORDSIZE == 64
1062                                 ast_log(LOG_DEBUG, "#%d: [%016lX] %s\n", i, (unsigned long)addresses[i], strings[i]);
1063 #endif
1064                         }
1065                         free(strings);
1066                 } else {
1067                         ast_debug(1, "Could not allocate memory for backtrace\n");
1068                 }
1069                 free(addresses);
1070         }
1071 #else
1072         ast_log(LOG_WARNING, "Must run configure with '--enable-dev-mode' for stack backtraces.\n");
1073 #endif
1074 #else /* ndef linux */
1075         ast_log(LOG_WARNING, "Inline stack backtraces are only available on the Linux platform.\n");
1076 #endif
1077 }
1078
1079 void ast_verbose(const char *fmt, ...)
1080 {
1081         struct logmsg *logmsg = NULL;
1082         struct ast_str *buf = NULL;
1083         int res = 0;
1084         va_list ap;
1085
1086         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1087                 return;
1088
1089         if (ast_opt_timestamp) {
1090                 struct timeval tv;
1091                 struct ast_tm tm;
1092                 char date[40];
1093                 char *datefmt;
1094
1095                                 tv = ast_tvnow();
1096                 ast_localtime(&tv, &tm, NULL);
1097                 ast_strftime(date, sizeof(date), dateformat, &tm);
1098                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1099                 sprintf(datefmt, "[%s] %s", date, fmt);
1100                 fmt = datefmt;
1101         }
1102
1103         /* Build string */
1104         va_start(ap, fmt);
1105         res = ast_str_set_va(&buf, 0, fmt, ap);
1106         va_end(ap);
1107
1108         /* If the build failed then we can drop this allocated message */
1109         if (res == AST_DYNSTR_BUILD_FAILED)
1110                 return;
1111
1112         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1113                 return;
1114
1115         strcpy(logmsg->str, buf->str);
1116
1117         ast_log(LOG_VERBOSE, logmsg->str);
1118
1119         /* Set type */
1120         logmsg->type = LOGMSG_VERBOSE;
1121         
1122         /* Add to the list and poke the thread if possible */
1123         if (logthread != AST_PTHREADT_NULL) {
1124                 AST_LIST_LOCK(&logmsgs);
1125                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1126                 ast_cond_signal(&logcond);
1127                 AST_LIST_UNLOCK(&logmsgs);
1128         } else {
1129                 logger_print_verbose(logmsg);
1130                 free(logmsg);
1131         }
1132 }
1133
1134 int ast_register_verbose(void (*v)(const char *string)) 
1135 {
1136         struct verb *verb;
1137
1138         if (!(verb = ast_malloc(sizeof(*verb))))
1139                 return -1;
1140
1141         verb->verboser = v;
1142
1143         AST_RWLIST_WRLOCK(&verbosers);
1144         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1145         AST_RWLIST_UNLOCK(&verbosers);
1146         
1147         return 0;
1148 }
1149
1150 int ast_unregister_verbose(void (*v)(const char *string))
1151 {
1152         struct verb *cur;
1153
1154         AST_RWLIST_WRLOCK(&verbosers);
1155         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1156                 if (cur->verboser == v) {
1157                         AST_RWLIST_REMOVE_CURRENT(&verbosers, list);
1158                         free(cur);
1159                         break;
1160                 }
1161         }
1162         AST_RWLIST_TRAVERSE_SAFE_END
1163         AST_RWLIST_UNLOCK(&verbosers);
1164         
1165         return cur ? 0 : -1;
1166 }