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