Terry found this problem with running the expr2 parser on OSX. Make the #defines...
[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 /*! \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                 if (option_verbose)
853                         ast_verbose("Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
854         }
855
856         return;
857 }
858
859 /*! \brief Print a verbose message to the verbosers */
860 static void logger_print_verbose(struct logmsg *logmsg)
861 {
862         struct verb *v = NULL;
863
864         /* Iterate through the list of verbosers and pass them the log message string */
865         AST_RWLIST_RDLOCK(&verbosers);
866         AST_RWLIST_TRAVERSE(&verbosers, v, list)
867                 v->verboser(logmsg->str);
868         AST_RWLIST_UNLOCK(&verbosers);
869
870         return;
871 }
872
873 /*! \brief Actual logging thread */
874 static void *logger_thread(void *data)
875 {
876         struct logmsg *next = NULL, *msg = NULL;
877
878         for (;;) {
879                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
880                 AST_LIST_LOCK(&logmsgs);
881                 if (AST_LIST_EMPTY(&logmsgs))
882                         ast_cond_wait(&logcond, &logmsgs.lock);
883                 next = AST_LIST_FIRST(&logmsgs);
884                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
885                 AST_LIST_UNLOCK(&logmsgs);
886
887                 /* Otherwise go through and process each message in the order added */
888                 while ((msg = next)) {
889                         /* Get the next entry now so that we can free our current structure later */
890                         next = AST_LIST_NEXT(msg, list);
891
892                         /* Depending on the type, send it to the proper function */
893                         if (msg->type == LOGMSG_NORMAL)
894                                 logger_print_normal(msg);
895                         else if (msg->type == LOGMSG_VERBOSE)
896                                 logger_print_verbose(msg);
897
898                         /* Free the data since we are done */
899                         ast_free(msg);
900                 }
901
902                 /* If we should stop, then stop */
903                 if (close_logger_thread)
904                         break;
905         }
906
907         return NULL;
908 }
909
910 int init_logger(void)
911 {
912         char tmp[256];
913         int res = 0;
914
915         /* auto rotate if sig SIGXFSZ comes a-knockin */
916         (void) signal(SIGXFSZ,(void *) handle_SIGXFSZ);
917
918         /* start logger thread */
919         ast_cond_init(&logcond, NULL);
920         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
921                 ast_cond_destroy(&logcond);
922                 return -1;
923         }
924
925         /* register the logger cli commands */
926         ast_cli_register_multiple(cli_logger, sizeof(cli_logger) / sizeof(struct ast_cli_entry));
927
928         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
929   
930         /* create log channels */
931         init_logger_chain(0 /* reload */, 0 /* locked */);
932
933         /* create the eventlog */
934         if (logfiles.event_log) {
935                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
936                 eventlog = fopen(tmp, "a");
937                 if (eventlog) {
938                         ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
939                         if (option_verbose)
940                                 ast_verbose("Asterisk Event Logger Started %s\n", tmp);
941                 } else {
942                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
943                         res = -1;
944                 }
945         }
946
947         if (logfiles.queue_log) {
948                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
949                 qlog = fopen(tmp, "a");
950                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
951         }
952         return res;
953 }
954
955 void close_logger(void)
956 {
957         struct logchannel *f = NULL;
958
959         /* Stop logger thread */
960         AST_LIST_LOCK(&logmsgs);
961         close_logger_thread = 1;
962         ast_cond_signal(&logcond);
963         AST_LIST_UNLOCK(&logmsgs);
964
965         if (logthread != AST_PTHREADT_NULL)
966                 pthread_join(logthread, NULL);
967
968         AST_RWLIST_WRLOCK(&logchannels);
969
970         if (eventlog) {
971                 fclose(eventlog);
972                 eventlog = NULL;
973         }
974
975         if (qlog) {
976                 fclose(qlog);
977                 qlog = NULL;
978         }
979
980         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
981                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
982                         fclose(f->fileptr);
983                         f->fileptr = NULL;
984                 }
985         }
986
987         closelog(); /* syslog */
988
989         AST_RWLIST_UNLOCK(&logchannels);
990
991         return;
992 }
993
994 /*!
995  * \brief send log messages to syslog and/or the console
996  */
997 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
998 {
999         struct logmsg *logmsg = NULL;
1000         struct ast_str *buf = NULL;
1001         struct ast_tm tm;
1002         struct timeval tv = ast_tvnow();
1003         int res = 0;
1004         va_list ap;
1005
1006         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1007                 return;
1008
1009         if (AST_RWLIST_EMPTY(&logchannels)) {
1010                 /*
1011                  * we don't have the logger chain configured yet,
1012                  * so just log to stdout
1013                  */
1014                 if (level != __LOG_VERBOSE) {
1015                         int res;
1016                         va_start(ap, fmt);
1017                         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1018                         va_end(ap);
1019                         if (res != AST_DYNSTR_BUILD_FAILED) {
1020                                 term_filter_escapes(buf->str);
1021                                 fputs(buf->str, stdout);
1022                         }
1023                 }
1024                 return;
1025         }
1026         
1027         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1028            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1029            is zero, if option_verbose is non-zero (this allows for 'level zero'
1030            LOG_DEBUG messages to be displayed, if the logmask on any channel
1031            allows it)
1032         */
1033         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1034                 return;
1035
1036         /* Ignore anything that never gets logged anywhere */
1037         if (!(global_logmask & (1 << level)))
1038                 return;
1039         
1040         /* Build string */
1041         va_start(ap, fmt);
1042         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1043         va_end(ap);
1044
1045         /* If the build failed, then abort and free this structure */
1046         if (res == AST_DYNSTR_BUILD_FAILED)
1047                 return;
1048
1049         /* Create a new logging message */
1050         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1051                 return;
1052         
1053         /* Copy string over */
1054         strcpy(logmsg->str, buf->str);
1055
1056         /* Set type to be normal */
1057         logmsg->type = LOGMSG_NORMAL;
1058
1059         /* Create our date/time */
1060         ast_localtime(&tv, &tm, NULL);
1061         ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1062
1063         /* Copy over data */
1064         logmsg->level = level;
1065         logmsg->file = file;
1066         logmsg->line = line;
1067         logmsg->function = function;
1068
1069         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1070         if (logthread != AST_PTHREADT_NULL) {
1071                 AST_LIST_LOCK(&logmsgs);
1072                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1073                 ast_cond_signal(&logcond);
1074                 AST_LIST_UNLOCK(&logmsgs);
1075         } else {
1076                 logger_print_normal(logmsg);
1077                 ast_free(logmsg);
1078         }
1079
1080         return;
1081 }
1082
1083 void ast_backtrace(void)
1084 {
1085 #ifdef linux
1086 #ifdef AST_DEVMODE
1087         int count=0, i=0;
1088         void **addresses;
1089         char **strings;
1090
1091         if ((addresses = ast_calloc(MAX_BACKTRACE_FRAMES, sizeof(*addresses)))) {
1092                 count = backtrace(addresses, MAX_BACKTRACE_FRAMES);
1093                 if ((strings = backtrace_symbols(addresses, count))) {
1094                         ast_debug(1, "Got %d backtrace record%c\n", count, count != 1 ? 's' : ' ');
1095                         for (i=0; i < count ; i++) {
1096 #if __WORDSIZE == 32
1097                                 ast_log(LOG_DEBUG, "#%d: [%08X] %s\n", i, (unsigned int)addresses[i], strings[i]);
1098 #elif __WORDSIZE == 64
1099                                 ast_log(LOG_DEBUG, "#%d: [%016lX] %s\n", i, (unsigned long)addresses[i], strings[i]);
1100 #endif
1101                         }
1102                         free(strings);
1103                 } else {
1104                         ast_debug(1, "Could not allocate memory for backtrace\n");
1105                 }
1106                 ast_free(addresses);
1107         }
1108 #else
1109         ast_log(LOG_WARNING, "Must run configure with '--enable-dev-mode' for stack backtraces.\n");
1110 #endif
1111 #else /* ndef linux */
1112         ast_log(LOG_WARNING, "Inline stack backtraces are only available on the Linux platform.\n");
1113 #endif
1114 }
1115
1116 void ast_verbose(const char *fmt, ...)
1117 {
1118         struct logmsg *logmsg = NULL;
1119         struct ast_str *buf = NULL;
1120         int res = 0;
1121         va_list ap;
1122
1123         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1124                 return;
1125
1126         if (ast_opt_timestamp) {
1127                 struct timeval tv;
1128                 struct ast_tm tm;
1129                 char date[40];
1130                 char *datefmt;
1131
1132                 tv = ast_tvnow();
1133                 ast_localtime(&tv, &tm, NULL);
1134                 ast_strftime(date, sizeof(date), dateformat, &tm);
1135                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1136                 sprintf(datefmt, "[%s] %s", date, fmt);
1137                 fmt = datefmt;
1138         }
1139
1140         /* Build string */
1141         va_start(ap, fmt);
1142         res = ast_str_set_va(&buf, 0, fmt, ap);
1143         va_end(ap);
1144
1145         /* If the build failed then we can drop this allocated message */
1146         if (res == AST_DYNSTR_BUILD_FAILED)
1147                 return;
1148
1149         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1150                 return;
1151
1152         strcpy(logmsg->str, buf->str);
1153
1154         ast_log(LOG_VERBOSE, logmsg->str);
1155
1156         /* Set type */
1157         logmsg->type = LOGMSG_VERBOSE;
1158         
1159         /* Add to the list and poke the thread if possible */
1160         if (logthread != AST_PTHREADT_NULL) {
1161                 AST_LIST_LOCK(&logmsgs);
1162                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1163                 ast_cond_signal(&logcond);
1164                 AST_LIST_UNLOCK(&logmsgs);
1165         } else {
1166                 logger_print_verbose(logmsg);
1167                 ast_free(logmsg);
1168         }
1169 }
1170
1171 int ast_register_verbose(void (*v)(const char *string)) 
1172 {
1173         struct verb *verb;
1174
1175         if (!(verb = ast_malloc(sizeof(*verb))))
1176                 return -1;
1177
1178         verb->verboser = v;
1179
1180         AST_RWLIST_WRLOCK(&verbosers);
1181         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1182         AST_RWLIST_UNLOCK(&verbosers);
1183         
1184         return 0;
1185 }
1186
1187 int ast_unregister_verbose(void (*v)(const char *string))
1188 {
1189         struct verb *cur;
1190
1191         AST_RWLIST_WRLOCK(&verbosers);
1192         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1193                 if (cur->verboser == v) {
1194                         AST_RWLIST_REMOVE_CURRENT(list);
1195                         ast_free(cur);
1196                         break;
1197                 }
1198         }
1199         AST_RWLIST_TRAVERSE_SAFE_END;
1200         AST_RWLIST_UNLOCK(&verbosers);
1201         
1202         return cur ? 0 : -1;
1203 }