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