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