1635489081217440032f6f90f28ae57e4ec45a0f
[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                 ast_channel_free(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                                 event_rotate = 0;
627                 } else {
628                         fclose(qlog);
629                         qlog = NULL;
630                 }
631         } else 
632                 queue_rotate = 0;
633         qlog = NULL;
634
635         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
636
637         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
638                 if (f->disabled) {
639                         f->disabled = 0;        /* Re-enable logging at reload */
640                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
641                 }
642                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
643                         fclose(f->fileptr);     /* Close file */
644                         f->fileptr = NULL;
645                         if (rotate)
646                                 rotate_file(f->filename);
647                 }
648         }
649
650         filesize_reload_needed = 0;
651
652         init_logger_chain(1 /* locked */);
653
654         if (logfiles.event_log) {
655                 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
656                 if (event_rotate)
657                         rotate_file(old);
658
659                 eventlog = fopen(old, "a");
660                 if (eventlog) {
661                         ast_log(LOG_EVENT, "Restarted Asterisk Event Logger\n");
662                         ast_verb(1, "Asterisk Event Logger restarted\n");
663                 } else {
664                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
665                         res = -1;
666                 }
667         }
668
669         if (logfiles.queue_log) {
670                 snprintf(old, sizeof(old), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
671                 if (queue_rotate)
672                         rotate_file(old);
673
674                 qlog = fopen(old, "a");
675                 if (qlog) {
676                         AST_RWLIST_UNLOCK(&logchannels);
677                         ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
678                         AST_RWLIST_WRLOCK(&logchannels);
679                         ast_log(LOG_EVENT, "Restarted Asterisk Queue Logger\n");
680                         ast_verb(1, "Asterisk Queue Logger restarted\n");
681                 } else {
682                         ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
683                         res = -1;
684                 }
685         }
686
687         AST_RWLIST_UNLOCK(&logchannels);
688
689         return res;
690 }
691
692 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
693         a full Asterisk reload) */
694 int logger_reload(void)
695 {
696         if(reload_logger(0))
697                 return RESULT_FAILURE;
698         return RESULT_SUCCESS;
699 }
700
701 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
702 {
703         switch (cmd) {
704         case CLI_INIT:
705                 e->command = "logger reload";
706                 e->usage = 
707                         "Usage: logger reload\n"
708                         "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
709                 return NULL;
710         case CLI_GENERATE:
711                 return NULL;
712         }
713         if (reload_logger(0)) {
714                 ast_cli(a->fd, "Failed to reload the logger\n");
715                 return CLI_FAILURE;
716         }
717         return CLI_SUCCESS;
718 }
719
720 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
721 {
722         switch (cmd) {
723         case CLI_INIT:
724                 e->command = "logger rotate";
725                 e->usage = 
726                         "Usage: logger rotate\n"
727                         "       Rotates and Reopens the log files.\n";
728                 return NULL;
729         case CLI_GENERATE:
730                 return NULL;    
731         }
732         if (reload_logger(1)) {
733                 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
734                 return CLI_FAILURE;
735         } 
736         return CLI_SUCCESS;
737 }
738
739 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
740 {
741         int x;
742         int state;
743         int level = -1;
744
745         switch (cmd) {
746         case CLI_INIT:
747                 e->command = "logger set level";
748                 e->usage = 
749                         "Usage: logger set level\n"
750                         "       Set a specific log level to enabled/disabled for this console.\n";
751                 return NULL;
752         case CLI_GENERATE:
753                 return NULL;
754         }
755
756         if (a->argc < 5)
757                 return CLI_SHOWUSAGE;
758
759         for (x = 0; x <= NUMLOGLEVELS; x++) {
760                 if (!strcasecmp(a->argv[3], levels[x])) {
761                         level = x;
762                         break;
763                 }
764         }
765
766         state = ast_true(a->argv[4]) ? 1 : 0;
767
768         if (level != -1) {
769                 ast_console_toggle_loglevel(a->fd, level, state);
770                 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
771         } else
772                 return CLI_SHOWUSAGE;
773
774         return CLI_SUCCESS;
775 }
776
777 /*! \brief CLI command to show logging system configuration */
778 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
779 {
780 #define FORMATL "%-35.35s %-8.8s %-9.9s "
781         struct logchannel *chan;
782         switch (cmd) {
783         case CLI_INIT:
784                 e->command = "logger show channels";
785                 e->usage = 
786                         "Usage: logger show channels\n"
787                         "       List configured logger channels.\n";
788                 return NULL;
789         case CLI_GENERATE:
790                 return NULL;    
791         }
792         ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
793         ast_cli(a->fd, "Configuration\n");
794         ast_cli(a->fd, FORMATL, "-------", "----", "------");
795         ast_cli(a->fd, "-------------\n");
796         AST_RWLIST_RDLOCK(&logchannels);
797         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
798                 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
799                         chan->disabled ? "Disabled" : "Enabled");
800                 ast_cli(a->fd, " - ");
801                 if (chan->logmask & (1 << __LOG_DEBUG)) 
802                         ast_cli(a->fd, "Debug ");
803                 if (chan->logmask & (1 << __LOG_DTMF)) 
804                         ast_cli(a->fd, "DTMF ");
805                 if (chan->logmask & (1 << __LOG_VERBOSE)) 
806                         ast_cli(a->fd, "Verbose ");
807                 if (chan->logmask & (1 << __LOG_WARNING)) 
808                         ast_cli(a->fd, "Warning ");
809                 if (chan->logmask & (1 << __LOG_NOTICE)) 
810                         ast_cli(a->fd, "Notice ");
811                 if (chan->logmask & (1 << __LOG_ERROR)) 
812                         ast_cli(a->fd, "Error ");
813                 if (chan->logmask & (1 << __LOG_EVENT)) 
814                         ast_cli(a->fd, "Event ");
815                 ast_cli(a->fd, "\n");
816         }
817         AST_RWLIST_UNLOCK(&logchannels);
818         ast_cli(a->fd, "\n");
819                 
820         return CLI_SUCCESS;
821 }
822
823 struct verb {
824         void (*verboser)(const char *string);
825         AST_LIST_ENTRY(verb) list;
826 };
827
828 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
829
830 static struct ast_cli_entry cli_logger[] = {
831         AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
832         AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
833         AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
834         AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
835 };
836
837 static int handle_SIGXFSZ(int sig) 
838 {
839         /* Indicate need to reload */
840         filesize_reload_needed = 1;
841         return 0;
842 }
843
844 static void ast_log_vsyslog(int level, const char *file, int line, const char *function, char *str, long pid)
845 {
846         char buf[BUFSIZ];
847
848         if (level >= SYSLOG_NLEVELS) {
849                 /* we are locked here, so cannot ast_log() */
850                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", level);
851                 return;
852         }
853
854         if (level == __LOG_VERBOSE) {
855                 snprintf(buf, sizeof(buf), "VERBOSE[%ld]: %s", pid, str);
856                 level = __LOG_DEBUG;
857         } else if (level == __LOG_DTMF) {
858                 snprintf(buf, sizeof(buf), "DTMF[%ld]: %s", pid, str);
859                 level = __LOG_DEBUG;
860         } else {
861                 snprintf(buf, sizeof(buf), "%s[%ld]: %s:%d in %s: %s",
862                          levels[level], pid, file, line, function, str);
863         }
864
865         term_strip(buf, buf, strlen(buf) + 1);
866         syslog(syslog_level_map[level], "%s", buf);
867 }
868
869 /*! \brief Print a normal log message to the channels */
870 static void logger_print_normal(struct logmsg *logmsg)
871 {
872         struct logchannel *chan = NULL;
873         char buf[BUFSIZ];
874
875         AST_RWLIST_RDLOCK(&logchannels);
876
877         if (logfiles.event_log && logmsg->level == __LOG_EVENT) {
878                 fprintf(eventlog, "%s asterisk[%ld]: %s", logmsg->date, (long)getpid(), logmsg->str);
879                 fflush(eventlog);
880                 AST_RWLIST_UNLOCK(&logchannels);
881                 return;
882         }
883
884         if (!AST_RWLIST_EMPTY(&logchannels)) {
885                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
886                         /* If the channel is disabled, then move on to the next one */
887                         if (chan->disabled)
888                                 continue;
889                         /* Check syslog channels */
890                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
891                                 ast_log_vsyslog(logmsg->level, logmsg->file, logmsg->line, logmsg->function, logmsg->str, logmsg->process_id);
892                         /* Console channels */
893                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
894                                 char linestr[128];
895                                 char tmp1[80], tmp2[80], tmp3[80], tmp4[80];
896
897                                 /* If the level is verbose, then skip it */
898                                 if (logmsg->level == __LOG_VERBOSE)
899                                         continue;
900
901                                 /* Turn the numerical line number into a string */
902                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
903                                 /* Build string to print out */
904                                 snprintf(buf, sizeof(buf), "[%s] %s[%ld]: %s:%s %s: %s",
905                                          logmsg->date,
906                                          term_color(tmp1, levels[logmsg->level], colors[logmsg->level], 0, sizeof(tmp1)),
907                                          logmsg->process_id,
908                                          term_color(tmp2, logmsg->file, COLOR_BRWHITE, 0, sizeof(tmp2)),
909                                          term_color(tmp3, linestr, COLOR_BRWHITE, 0, sizeof(tmp3)),
910                                          term_color(tmp4, logmsg->function, COLOR_BRWHITE, 0, sizeof(tmp4)),
911                                          logmsg->str);
912                                 /* Print out */
913                                 ast_console_puts_mutable(buf, logmsg->level);
914                         /* File channels */
915                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
916                                 int res = 0;
917
918                                 /* If no file pointer exists, skip it */
919                                 if (!chan->fileptr)
920                                         continue;
921                                 
922                                 /* Print out to the file */
923                                 res = fprintf(chan->fileptr, "[%s] %s[%ld] %s: %s",
924                                               logmsg->date, levels[logmsg->level], logmsg->process_id, logmsg->file, logmsg->str);
925                                 if (res <= 0 && !ast_strlen_zero(logmsg->str)) {
926                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
927                                         if (errno == ENOMEM || errno == ENOSPC)
928                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
929                                         else
930                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
931                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
932                                         chan->disabled = 1;
933                                 } else if (res > 0) {
934                                         fflush(chan->fileptr);
935                                 }
936                         }
937                 }
938         } else if (logmsg->level != __LOG_VERBOSE) {
939                 fputs(logmsg->str, stdout);
940         }
941
942         AST_RWLIST_UNLOCK(&logchannels);
943
944         /* If we need to reload because of the file size, then do so */
945         if (filesize_reload_needed) {
946                 reload_logger(-1);
947                 ast_log(LOG_EVENT, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
948                 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
949         }
950
951         return;
952 }
953
954 /*! \brief Print a verbose message to the verbosers */
955 static void logger_print_verbose(struct logmsg *logmsg)
956 {
957         struct verb *v = NULL;
958
959         /* Iterate through the list of verbosers and pass them the log message string */
960         AST_RWLIST_RDLOCK(&verbosers);
961         AST_RWLIST_TRAVERSE(&verbosers, v, list)
962                 v->verboser(logmsg->str);
963         AST_RWLIST_UNLOCK(&verbosers);
964
965         return;
966 }
967
968 /*! \brief Actual logging thread */
969 static void *logger_thread(void *data)
970 {
971         struct logmsg *next = NULL, *msg = NULL;
972
973         for (;;) {
974                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
975                 AST_LIST_LOCK(&logmsgs);
976                 if (AST_LIST_EMPTY(&logmsgs)) {
977                         if (close_logger_thread) {
978                                 break;
979                         } else {
980                                 ast_cond_wait(&logcond, &logmsgs.lock);
981                         }
982                 }
983                 next = AST_LIST_FIRST(&logmsgs);
984                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
985                 AST_LIST_UNLOCK(&logmsgs);
986
987                 /* Otherwise go through and process each message in the order added */
988                 while ((msg = next)) {
989                         /* Get the next entry now so that we can free our current structure later */
990                         next = AST_LIST_NEXT(msg, list);
991
992                         /* Depending on the type, send it to the proper function */
993                         if (msg->type == LOGMSG_NORMAL)
994                                 logger_print_normal(msg);
995                         else if (msg->type == LOGMSG_VERBOSE)
996                                 logger_print_verbose(msg);
997
998                         /* Free the data since we are done */
999                         ast_free(msg);
1000                 }
1001
1002                 /* If we should stop, then stop */
1003                 if (close_logger_thread)
1004                         break;
1005         }
1006
1007         return NULL;
1008 }
1009
1010 int init_logger(void)
1011 {
1012         char tmp[256];
1013         int res = 0;
1014
1015         /* auto rotate if sig SIGXFSZ comes a-knockin */
1016         (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
1017
1018         /* start logger thread */
1019         ast_cond_init(&logcond, NULL);
1020         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1021                 ast_cond_destroy(&logcond);
1022                 return -1;
1023         }
1024
1025         /* register the logger cli commands */
1026         ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1027
1028         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1029   
1030         /* create log channels */
1031         init_logger_chain(0 /* locked */);
1032
1033         /* create the eventlog */
1034         if (logfiles.event_log) {
1035                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
1036                 eventlog = fopen(tmp, "a");
1037                 if (eventlog) {
1038                         ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
1039                         ast_verb(1, "Asterisk Event Logger Started %s\n", tmp);
1040                 } else {
1041                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
1042                         res = -1;
1043                 }
1044         }
1045
1046         if (logfiles.queue_log) {
1047                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
1048                 qlog = fopen(tmp, "a");
1049                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
1050         }
1051         return res;
1052 }
1053
1054 void close_logger(void)
1055 {
1056         struct logchannel *f = NULL;
1057
1058         /* Stop logger thread */
1059         AST_LIST_LOCK(&logmsgs);
1060         close_logger_thread = 1;
1061         ast_cond_signal(&logcond);
1062         AST_LIST_UNLOCK(&logmsgs);
1063
1064         if (logthread != AST_PTHREADT_NULL)
1065                 pthread_join(logthread, NULL);
1066
1067         AST_RWLIST_WRLOCK(&logchannels);
1068
1069         if (eventlog) {
1070                 fclose(eventlog);
1071                 eventlog = NULL;
1072         }
1073
1074         if (qlog) {
1075                 fclose(qlog);
1076                 qlog = NULL;
1077         }
1078
1079         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1080                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1081                         fclose(f->fileptr);
1082                         f->fileptr = NULL;
1083                 }
1084         }
1085
1086         closelog(); /* syslog */
1087
1088         AST_RWLIST_UNLOCK(&logchannels);
1089
1090         return;
1091 }
1092
1093 /*!
1094  * \brief send log messages to syslog and/or the console
1095  */
1096 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1097 {
1098         struct logmsg *logmsg = NULL;
1099         struct ast_str *buf = NULL;
1100         struct ast_tm tm;
1101         struct timeval now = ast_tvnow();
1102         int res = 0;
1103         va_list ap;
1104
1105         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1106                 return;
1107
1108         if (AST_RWLIST_EMPTY(&logchannels)) {
1109                 /*
1110                  * we don't have the logger chain configured yet,
1111                  * so just log to stdout
1112                  */
1113                 if (level != __LOG_VERBOSE) {
1114                         int result;
1115                         va_start(ap, fmt);
1116                         result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1117                         va_end(ap);
1118                         if (result != AST_DYNSTR_BUILD_FAILED) {
1119                                 term_filter_escapes(ast_str_buffer(buf));
1120                                 fputs(ast_str_buffer(buf), stdout);
1121                         }
1122                 }
1123                 return;
1124         }
1125         
1126         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1127            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1128            is zero, if option_verbose is non-zero (this allows for 'level zero'
1129            LOG_DEBUG messages to be displayed, if the logmask on any channel
1130            allows it)
1131         */
1132         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1133                 return;
1134
1135         /* Ignore anything that never gets logged anywhere */
1136         if (!(global_logmask & (1 << level)))
1137                 return;
1138         
1139         /* Build string */
1140         va_start(ap, fmt);
1141         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1142         va_end(ap);
1143
1144         /* If the build failed, then abort and free this structure */
1145         if (res == AST_DYNSTR_BUILD_FAILED)
1146                 return;
1147
1148         /* Create a new logging message */
1149         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1150                 return;
1151
1152         /* Copy string over */
1153         strcpy(logmsg->str, ast_str_buffer(buf));
1154
1155         /* Set type to be normal */
1156         logmsg->type = LOGMSG_NORMAL;
1157
1158         /* Create our date/time */
1159         ast_localtime(&now, &tm, NULL);
1160         ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1161
1162         /* Copy over data */
1163         logmsg->level = level;
1164         logmsg->line = line;
1165         ast_copy_string(logmsg->file, file, sizeof(logmsg->file));
1166         ast_copy_string(logmsg->function, function, sizeof(logmsg->function));
1167         logmsg->process_id = (long) GETTID();
1168
1169         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1170         if (logthread != AST_PTHREADT_NULL) {
1171                 AST_LIST_LOCK(&logmsgs);
1172                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1173                 ast_cond_signal(&logcond);
1174                 AST_LIST_UNLOCK(&logmsgs);
1175         } else {
1176                 logger_print_normal(logmsg);
1177                 ast_free(logmsg);
1178         }
1179
1180         return;
1181 }
1182
1183 #ifdef HAVE_BKTR
1184
1185 struct ast_bt *ast_bt_create(void) 
1186 {
1187         struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1188         if (!bt) {
1189                 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1190                 return NULL;
1191         }
1192
1193         bt->alloced = 1;
1194
1195         ast_bt_get_addresses(bt);
1196
1197         return bt;
1198 }
1199
1200 int ast_bt_get_addresses(struct ast_bt *bt)
1201 {
1202         bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1203
1204         return 0;
1205 }
1206
1207 void *ast_bt_destroy(struct ast_bt *bt)
1208 {
1209         if (bt->alloced) {
1210                 ast_free(bt);
1211         }
1212
1213         return NULL;
1214 }
1215
1216 #endif /* HAVE_BKTR */
1217
1218 void ast_backtrace(void)
1219 {
1220 #ifdef HAVE_BKTR
1221         struct ast_bt *bt;
1222         int i = 0;
1223         char **strings;
1224
1225         if (!(bt = ast_bt_create())) {
1226                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1227                 return;
1228         }
1229
1230         if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1231                 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1232                 for (i = 0; i < bt->num_frames; i++) {
1233                         ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1234                 }
1235                 free(strings);
1236         } else {
1237                 ast_debug(1, "Could not allocate memory for backtrace\n");
1238         }
1239         ast_bt_destroy(bt);
1240 #else
1241         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1242 #endif
1243 }
1244
1245 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1246 {
1247         struct logmsg *logmsg = NULL;
1248         struct ast_str *buf = NULL;
1249         int res = 0;
1250
1251         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1252                 return;
1253
1254         if (ast_opt_timestamp) {
1255                 struct timeval now;
1256                 struct ast_tm tm;
1257                 char date[40];
1258                 char *datefmt;
1259
1260                 now = ast_tvnow();
1261                 ast_localtime(&now, &tm, NULL);
1262                 ast_strftime(date, sizeof(date), dateformat, &tm);
1263                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1264                 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1265                 fmt = datefmt;
1266         } else {
1267                 char *tmp = alloca(strlen(fmt) + 2);
1268                 sprintf(tmp, "%c%s", 127, fmt);
1269                 fmt = tmp;
1270         }
1271
1272         /* Build string */
1273         res = ast_str_set_va(&buf, 0, fmt, ap);
1274
1275         /* If the build failed then we can drop this allocated message */
1276         if (res == AST_DYNSTR_BUILD_FAILED)
1277                 return;
1278
1279         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1280                 return;
1281
1282         strcpy(logmsg->str, ast_str_buffer(buf));
1283
1284         ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->str + 1);
1285
1286         /* Set type */
1287         logmsg->type = LOGMSG_VERBOSE;
1288         
1289         /* Add to the list and poke the thread if possible */
1290         if (logthread != AST_PTHREADT_NULL) {
1291                 AST_LIST_LOCK(&logmsgs);
1292                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1293                 ast_cond_signal(&logcond);
1294                 AST_LIST_UNLOCK(&logmsgs);
1295         } else {
1296                 logger_print_verbose(logmsg);
1297                 ast_free(logmsg);
1298         }
1299 }
1300
1301 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1302 {
1303         va_list ap;
1304         va_start(ap, fmt);
1305         __ast_verbose_ap(file, line, func, fmt, ap);
1306         va_end(ap);
1307 }
1308
1309 /* No new code should use this directly, but we have the ABI for backwards compat */
1310 #undef ast_verbose
1311 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1312 void ast_verbose(const char *fmt, ...)
1313 {
1314         va_list ap;
1315         va_start(ap, fmt);
1316         __ast_verbose_ap("", 0, "", fmt, ap);
1317         va_end(ap);
1318 }
1319
1320 int ast_register_verbose(void (*v)(const char *string)) 
1321 {
1322         struct verb *verb;
1323
1324         if (!(verb = ast_malloc(sizeof(*verb))))
1325                 return -1;
1326
1327         verb->verboser = v;
1328
1329         AST_RWLIST_WRLOCK(&verbosers);
1330         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1331         AST_RWLIST_UNLOCK(&verbosers);
1332         
1333         return 0;
1334 }
1335
1336 int ast_unregister_verbose(void (*v)(const char *string))
1337 {
1338         struct verb *cur;
1339
1340         AST_RWLIST_WRLOCK(&verbosers);
1341         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1342                 if (cur->verboser == v) {
1343                         AST_RWLIST_REMOVE_CURRENT(list);
1344                         ast_free(cur);
1345                         break;
1346                 }
1347         }
1348         AST_RWLIST_TRAVERSE_SAFE_END;
1349         AST_RWLIST_UNLOCK(&verbosers);
1350         
1351         return cur ? 0 : -1;
1352 }