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