Merged revisions 91366 via svnmerge from
[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 /*
29  * define _ASTERISK_LOGGER_H to prevent the inclusion of logger.h;
30  * it redefines LOG_* which we need to define syslog_level_map.
31  * Later, we force the inclusion of logger.h again.
32  */
33 #define _ASTERISK_LOGGER_H
34 #include "asterisk.h"
35
36 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37
38 #include "asterisk/_private.h"
39 #include "asterisk/paths.h"     /* use ast_config_AST_LOG_DIR */
40 #include <signal.h>
41 #include <time.h>
42 #include <sys/stat.h>
43 #include <fcntl.h>
44 #if ((defined(AST_DEVMODE)) && (defined(linux)))
45 #include <execinfo.h>
46 #define MAX_BACKTRACE_FRAMES 20
47 #endif
48
49 #define SYSLOG_NAMES /* so we can map syslog facilities names to their numeric values,
50                         from <syslog.h> which is included by logger.h */
51 #include <syslog.h>
52
53 static int syslog_level_map[] = {
54         LOG_DEBUG,
55         LOG_INFO,    /* arbitrary equivalent of LOG_EVENT */
56         LOG_NOTICE,
57         LOG_WARNING,
58         LOG_ERR,
59         LOG_DEBUG,
60         LOG_DEBUG
61 };
62
63 #define SYSLOG_NLEVELS sizeof(syslog_level_map) / sizeof(int)
64
65 #undef _ASTERISK_LOGGER_H       /* now include logger.h */
66 #include "asterisk/logger.h"
67 #include "asterisk/lock.h"
68 #include "asterisk/channel.h"
69 #include "asterisk/config.h"
70 #include "asterisk/term.h"
71 #include "asterisk/cli.h"
72 #include "asterisk/utils.h"
73 #include "asterisk/manager.h"
74 #include "asterisk/threadstorage.h"
75 #include "asterisk/strings.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(const char *s, int lineno)
178 {
179         char *w;
180         int res = 0;
181         char *stringp = ast_strdupa(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(const char *channel, const 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 static 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(rotate ? 0 : 1 /* reload */, 1 /* locked */);
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 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
620         a full Asterisk reload) */
621 int logger_reload(void)
622 {
623         if(reload_logger(0))
624                 return RESULT_FAILURE;
625         return RESULT_SUCCESS;
626 }
627
628 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
629 {
630         switch (cmd) {
631         case CLI_INIT:
632                 e->command = "logger reload";
633                 e->usage = 
634                         "Usage: logger reload\n"
635                         "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
636                 return NULL;
637         case CLI_GENERATE:
638                 return NULL;
639         }
640         if (reload_logger(0)) {
641                 ast_cli(a->fd, "Failed to reload the logger\n");
642                 return CLI_FAILURE;
643         }
644         return CLI_SUCCESS;
645 }
646
647 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
648 {
649         switch (cmd) {
650         case CLI_INIT:
651                 e->command = "logger rotate";
652                 e->usage = 
653                         "Usage: logger rotate\n"
654                         "       Rotates and Reopens the log files.\n";
655                 return NULL;
656         case CLI_GENERATE:
657                 return NULL;    
658         }
659         if (reload_logger(1)) {
660                 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
661                 return CLI_FAILURE;
662         } 
663         return CLI_SUCCESS;
664 }
665
666 /*! \brief CLI command to show logging system configuration */
667 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
668 {
669 #define FORMATL "%-35.35s %-8.8s %-9.9s "
670         struct logchannel *chan;
671         switch (cmd) {
672         case CLI_INIT:
673                 e->command = "logger show channels";
674                 e->usage = 
675                         "Usage: logger show channels\n"
676                         "       List configured logger channels.\n";
677                 return NULL;
678         case CLI_GENERATE:
679                 return NULL;    
680         }
681         ast_cli(a->fd,FORMATL, "Channel", "Type", "Status");
682         ast_cli(a->fd, "Configuration\n");
683         ast_cli(a->fd,FORMATL, "-------", "----", "------");
684         ast_cli(a->fd, "-------------\n");
685         AST_RWLIST_RDLOCK(&logchannels);
686         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
687                 ast_cli(a->fd, FORMATL, chan->filename, chan->type==LOGTYPE_CONSOLE ? "Console" : (chan->type==LOGTYPE_SYSLOG ? "Syslog" : "File"),
688                         chan->disabled ? "Disabled" : "Enabled");
689                 ast_cli(a->fd, " - ");
690                 if (chan->logmask & (1 << __LOG_DEBUG)) 
691                         ast_cli(a->fd, "Debug ");
692                 if (chan->logmask & (1 << __LOG_DTMF)) 
693                         ast_cli(a->fd, "DTMF ");
694                 if (chan->logmask & (1 << __LOG_VERBOSE)) 
695                         ast_cli(a->fd, "Verbose ");
696                 if (chan->logmask & (1 << __LOG_WARNING)) 
697                         ast_cli(a->fd, "Warning ");
698                 if (chan->logmask & (1 << __LOG_NOTICE)) 
699                         ast_cli(a->fd, "Notice ");
700                 if (chan->logmask & (1 << __LOG_ERROR)) 
701                         ast_cli(a->fd, "Error ");
702                 if (chan->logmask & (1 << __LOG_EVENT)) 
703                         ast_cli(a->fd, "Event ");
704                 ast_cli(a->fd, "\n");
705         }
706         AST_RWLIST_UNLOCK(&logchannels);
707         ast_cli(a->fd, "\n");
708                 
709         return CLI_SUCCESS;
710 }
711
712 struct verb {
713         void (*verboser)(const char *string);
714         AST_LIST_ENTRY(verb) list;
715 };
716
717 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
718
719 static struct ast_cli_entry cli_logger[] = {
720         AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
721         AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
722         AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files")
723 };
724
725 static int handle_SIGXFSZ(int sig) 
726 {
727         /* Indicate need to reload */
728         filesize_reload_needed = 1;
729         return 0;
730 }
731
732 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str)
733 {
734         char buf[BUFSIZ];
735
736         if (level >= SYSLOG_NLEVELS) {
737                 /* we are locked here, so cannot ast_log() */
738                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
739                 return;
740         }
741
742         if (level == __LOG_VERBOSE) {
743                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", (long)GETTID(), str);
744                 level = __LOG_DEBUG;
745         } else if (level == __LOG_DTMF) {
746                 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", (long)GETTID(), str);
747                 level = __LOG_DEBUG;
748         } else {
749                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
750                          levels[level], (long)GETTID(), file, line, function, str);
751         }
752
753         term_strip(buf, buf, strlen(buf) + 1);
754         syslog(syslog_level_map[level], "%s", buf);
755 }
756
757 /* Print a normal log message to the channels */
758 static void logger_print_normal(struct logmsg *logmsg)
759 {
760         struct logchannel *chan = NULL;
761         char buf[BUFSIZ];
762
763         AST_RWLIST_RDLOCK(&logchannels);
764
765         if (logfiles.event_log && logmsg->level == __LOG_EVENT) {
766                 fprintf(eventlog, "%s asterisk[%ld]: %s", logmsg->date, (long)getpid(), logmsg->str);
767                 fflush(eventlog);
768                 AST_RWLIST_UNLOCK(&logchannels);
769                 return;
770         }
771
772         if (!AST_RWLIST_EMPTY(&logchannels)) {
773                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
774                         /* If the channel is disabled, then move on to the next one */
775                         if (chan->disabled)
776                                 continue;
777                         /* Check syslog channels */
778                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
779                                 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str);
780                         /* Console channels */
781                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
782                                 char linestr[128];
783                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
784
785                                 /* If the level is verbose, then skip it */
786                                 if (logmsg->level == __LOG_VERBOSE)
787                                         continue;
788
789                                 /* Turn the numerical line number into a string */
790                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
791                                 /* Build string to print out */
792                                 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
793                                          logmsg->date,
794                                          term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
795                                          (long)GETTID(),
796                                          term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
797                                          term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
798                                          term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
799                                          logmsg->str);
800                                 /* Print out */
801                                 ast_console_puts_mutable(buf);
802                         /* File channels */
803                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
804                                 int res = 0;
805
806                                 /* If no file pointer exists, skip it */
807                                 if (!chan->fileptr)
808                                         continue;
809                                 
810                                 /* Print out to the file */
811                                 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
812                                               logmsg->date, levels[logmsg->level], (long)GETTID(), logmsg->file, logmsg->str);
813                                 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
814                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
815                                         if (errno == ENOMEM || errno == ENOSPC)
816                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
817                                         else
818                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
819                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
820                                         chan->disabled = 1;
821                                 } else if (res > 0) {
822                                         fflush(chan->fileptr);
823                                 }
824                         }
825                 }
826         } else if (logmsg->level != __LOG_VERBOSE) {
827                 fputs(logmsg->str, stdout);
828         }
829
830         AST_RWLIST_UNLOCK(&logchannels);
831
832         /* If we need to reload because of the file size, then do so */
833         if (filesize_reload_needed) {
834                 reload_logger(-1);
835                 ast_log(LOG_EVENT, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
836                 if (option_verbose)
837                         ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
838         }
839
840         return;
841 }
842
843 /* Print a verbose message to the verbosers */
844 static void logger_print_verbose(struct logmsg *logmsg)
845 {
846         struct verb *v = NULL;
847
848         /* Iterate through the list of verbosers and pass them the log message string */
849         AST_RWLIST_RDLOCK(&verbosers);
850         AST_RWLIST_TRAVERSE(&verbosers, v, list)
851                 v->verboser(logmsg->str);
852         AST_RWLIST_UNLOCK(&verbosers);
853
854         return;
855 }
856
857 /* Actual logging thread */
858 static void *logger_thread(void *data)
859 {
860         struct logmsg *next = NULL, *msg = NULL;
861
862         for (;;) {
863                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
864                 AST_LIST_LOCK(&logmsgs);
865                 if (AST_LIST_EMPTY(&logmsgs))
866                         ast_cond_wait(&logcond, &logmsgs.lock);
867                 next = AST_LIST_FIRST(&logmsgs);
868                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
869                 AST_LIST_UNLOCK(&logmsgs);
870
871                 /* Otherwise go through and process each message in the order added */
872                 while ((msg = next)) {
873                         /* Get the next entry now so that we can free our current structure later */
874                         next = AST_LIST_NEXT(msg, list);
875
876                         /* Depending on the type, send it to the proper function */
877                         if (msg->type == LOGMSG_NORMAL)
878                                 logger_print_normal(msg);
879                         else if (msg->type == LOGMSG_VERBOSE)
880                                 logger_print_verbose(msg);
881
882                         /* Free the data since we are done */
883                         free(msg);
884                 }
885
886                 /* If we should stop, then stop */
887                 if (close_logger_thread)
888                         break;
889         }
890
891         return NULL;
892 }
893
894 int init_logger(void)
895 {
896         char tmp[256];
897         int res = 0;
898
899         /* auto rotate if sig SIGXFSZ comes a-knockin */
900         (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
901
902         /* start logger thread */
903         ast_cond_init(&logcond, NULL);
904         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
905                 ast_cond_destroy(&logcond);
906                 return -1;
907         }
908
909         /* register the logger cli commands */
910         ast_cli_register_multiple(cli_logger, sizeof(cli_logger) / sizeof(struct ast_cli_entry));
911
912         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
913   
914         /* create log channels */
915         init_logger_chain(0 /* reload */, 0 /* locked */);
916
917         /* create the eventlog */
918         if (logfiles.event_log) {
919                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
920                 eventlog = fopen(tmp, "a");
921                 if (eventlog) {
922                         ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
923                         if (option_verbose)
924                                 ast_verbose("Asterisk Event Logger Started %s\n", tmp);
925                 } else {
926                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
927                         res = -1;
928                 }
929         }
930
931         if (logfiles.queue_log) {
932                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
933                 qlog = fopen(tmp, "a");
934                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
935         }
936         return res;
937 }
938
939 void close_logger(void)
940 {
941         struct logchannel *f = NULL;
942
943         /* Stop logger thread */
944         AST_LIST_LOCK(&logmsgs);
945         close_logger_thread = 1;
946         ast_cond_signal(&logcond);
947         AST_LIST_UNLOCK(&logmsgs);
948
949         if (logthread != AST_PTHREADT_NULL)
950                 pthread_join(logthread, NULL);
951
952         AST_RWLIST_WRLOCK(&logchannels);
953
954         if (eventlog) {
955                 fclose(eventlog);
956                 eventlog = NULL;
957         }
958
959         if (qlog) {
960                 fclose(qlog);
961                 qlog = NULL;
962         }
963
964         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
965                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
966                         fclose(f->fileptr);
967                         f->fileptr = NULL;
968                 }
969         }
970
971         closelog(); /* syslog */
972
973         AST_RWLIST_UNLOCK(&logchannels);
974
975         return;
976 }
977
978 /*!
979  * \brief send log messages to syslog and/or the console
980  */
981 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
982 {
983         struct logmsg *logmsg = NULL;
984         struct ast_str *buf = NULL;
985         struct ast_tm tm;
986         struct timeval tv = ast_tvnow();
987         int res = 0;
988         va_list ap;
989
990         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
991                 return;
992
993         if (AST_RWLIST_EMPTY(&logchannels)) {
994                 /*
995                  * we don't have the logger chain configured yet,
996                  * so just log to stdout
997                  */
998                 if (level != __LOG_VERBOSE) {
999                         int res;
1000                         va_start(ap, fmt);
1001                         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1002                         va_end(ap);
1003                         if (res != AST_DYNSTR_BUILD_FAILED) {
1004                                 term_filter_escapes(buf->str);
1005                                 fputs(buf->str, stdout);
1006                         }
1007                 }
1008                 return;
1009         }
1010         
1011         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1012            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1013            is zero, if option_verbose is non-zero (this allows for 'level zero'
1014            LOG_DEBUG messages to be displayed, if the logmask on any channel
1015            allows it)
1016         */
1017         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1018                 return;
1019
1020         /* Ignore anything that never gets logged anywhere */
1021         if (!(global_logmask & (1 << level)))
1022                 return;
1023         
1024         /* Build string */
1025         va_start(ap, fmt);
1026         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1027         va_end(ap);
1028
1029         /* If the build failed, then abort and free this structure */
1030         if (res == AST_DYNSTR_BUILD_FAILED)
1031                 return;
1032
1033         /* Create a new logging message */
1034         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1035                 return;
1036         
1037         /* Copy string over */
1038         strcpy(logmsg->str, buf->str);
1039
1040         /* Set type to be normal */
1041         logmsg->type = LOGMSG_NORMAL;
1042
1043         /* Create our date/time */
1044         ast_localtime(&tv, &tm, NULL);
1045         ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1046
1047         /* Copy over data */
1048         logmsg->level = level;
1049         logmsg->file = file;
1050         logmsg->line = line;
1051         logmsg->function = function;
1052
1053         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1054         if (logthread != AST_PTHREADT_NULL) {
1055                 AST_LIST_LOCK(&logmsgs);
1056                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1057                 ast_cond_signal(&logcond);
1058                 AST_LIST_UNLOCK(&logmsgs);
1059         } else {
1060                 logger_print_normal(logmsg);
1061                 free(logmsg);
1062         }
1063
1064         return;
1065 }
1066
1067 void ast_backtrace(void)
1068 {
1069 #ifdef linux
1070 #ifdef AST_DEVMODE
1071         int count=0, i=0;
1072         void **addresses;
1073         char **strings;
1074
1075         if ((addresses = ast_calloc(MAX_BACKTRACE_FRAMES, sizeof(*addresses)))) {
1076                 count = backtrace(addresses, MAX_BACKTRACE_FRAMES);
1077                 if ((strings = backtrace_symbols(addresses, count))) {
1078                         ast_debug(1, "Got %d backtrace record%c\n", count, count != 1 ? 's' : ' ');
1079                         for (i=0; i < count ; i++) {
1080 #if __WORDSIZE == 32
1081                                 ast_log(LOG_DEBUG, "#%d: [%08X] %s\n", i, (unsigned int)addresses[i], strings[i]);
1082 #elif __WORDSIZE == 64
1083                                 ast_log(LOG_DEBUG, "#%d: [%016lX] %s\n", i, (unsigned long)addresses[i], strings[i]);
1084 #endif
1085                         }
1086                         free(strings);
1087                 } else {
1088                         ast_debug(1, "Could not allocate memory for backtrace\n");
1089                 }
1090                 free(addresses);
1091         }
1092 #else
1093         ast_log(LOG_WARNING, "Must run configure with '--enable-dev-mode' for stack backtraces.\n");
1094 #endif
1095 #else /* ndef linux */
1096         ast_log(LOG_WARNING, "Inline stack backtraces are only available on the Linux platform.\n");
1097 #endif
1098 }
1099
1100 void ast_verbose(const char *fmt, ...)
1101 {
1102         struct logmsg *logmsg = NULL;
1103         struct ast_str *buf = NULL;
1104         int res = 0;
1105         va_list ap;
1106
1107         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1108                 return;
1109
1110         if (ast_opt_timestamp) {
1111                 struct timeval tv;
1112                 struct ast_tm tm;
1113                 char date[40];
1114                 char *datefmt;
1115
1116                                 tv = ast_tvnow();
1117                 ast_localtime(&tv, &tm, NULL);
1118                 ast_strftime(date, sizeof(date), dateformat, &tm);
1119                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1120                 sprintf(datefmt, "[%s] %s", date, fmt);
1121                 fmt = datefmt;
1122         }
1123
1124         /* Build string */
1125         va_start(ap, fmt);
1126         res = ast_str_set_va(&buf, 0, fmt, ap);
1127         va_end(ap);
1128
1129         /* If the build failed then we can drop this allocated message */
1130         if (res == AST_DYNSTR_BUILD_FAILED)
1131                 return;
1132
1133         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1134                 return;
1135
1136         strcpy(logmsg->str, buf->str);
1137
1138         ast_log(LOG_VERBOSE, logmsg->str);
1139
1140         /* Set type */
1141         logmsg->type = LOGMSG_VERBOSE;
1142         
1143         /* Add to the list and poke the thread if possible */
1144         if (logthread != AST_PTHREADT_NULL) {
1145                 AST_LIST_LOCK(&logmsgs);
1146                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1147                 ast_cond_signal(&logcond);
1148                 AST_LIST_UNLOCK(&logmsgs);
1149         } else {
1150                 logger_print_verbose(logmsg);
1151                 free(logmsg);
1152         }
1153 }
1154
1155 int ast_register_verbose(void (*v)(const char *string)) 
1156 {
1157         struct verb *verb;
1158
1159         if (!(verb = ast_malloc(sizeof(*verb))))
1160                 return -1;
1161
1162         verb->verboser = v;
1163
1164         AST_RWLIST_WRLOCK(&verbosers);
1165         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1166         AST_RWLIST_UNLOCK(&verbosers);
1167         
1168         return 0;
1169 }
1170
1171 int ast_unregister_verbose(void (*v)(const char *string))
1172 {
1173         struct verb *cur;
1174
1175         AST_RWLIST_WRLOCK(&verbosers);
1176         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1177                 if (cur->verboser == v) {
1178                         AST_RWLIST_REMOVE_CURRENT(list);
1179                         free(cur);
1180                         break;
1181                 }
1182         }
1183         AST_RWLIST_TRAVERSE_SAFE_END;
1184         AST_RWLIST_UNLOCK(&verbosers);
1185         
1186         return cur ? 0 : -1;
1187 }