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