Added a comment to logger.c about where to put includes
[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                         ast_cond_wait(&logcond, &logmsgs.lock);
978                 next = AST_LIST_FIRST(&logmsgs);
979                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
980                 AST_LIST_UNLOCK(&logmsgs);
981
982                 /* Otherwise go through and process each message in the order added */
983                 while ((msg = next)) {
984                         /* Get the next entry now so that we can free our current structure later */
985                         next = AST_LIST_NEXT(msg, list);
986
987                         /* Depending on the type, send it to the proper function */
988                         if (msg->type == LOGMSG_NORMAL)
989                                 logger_print_normal(msg);
990                         else if (msg->type == LOGMSG_VERBOSE)
991                                 logger_print_verbose(msg);
992
993                         /* Free the data since we are done */
994                         ast_free(msg);
995                 }
996
997                 /* If we should stop, then stop */
998                 if (close_logger_thread)
999                         break;
1000         }
1001
1002         return NULL;
1003 }
1004
1005 int init_logger(void)
1006 {
1007         char tmp[256];
1008         int res = 0;
1009
1010         /* auto rotate if sig SIGXFSZ comes a-knockin */
1011         (void) signal(SIGXFSZ, (void *) handle_SIGXFSZ);
1012
1013         /* start logger thread */
1014         ast_cond_init(&logcond, NULL);
1015         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1016                 ast_cond_destroy(&logcond);
1017                 return -1;
1018         }
1019
1020         /* register the logger cli commands */
1021         ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1022
1023         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1024   
1025         /* create log channels */
1026         init_logger_chain(0 /* locked */);
1027
1028         /* create the eventlog */
1029         if (logfiles.event_log) {
1030                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, EVENTLOG);
1031                 eventlog = fopen(tmp, "a");
1032                 if (eventlog) {
1033                         ast_log(LOG_EVENT, "Started Asterisk Event Logger\n");
1034                         ast_verb(1, "Asterisk Event Logger Started %s\n", tmp);
1035                 } else {
1036                         ast_log(LOG_ERROR, "Unable to create event log: %s\n", strerror(errno));
1037                         res = -1;
1038                 }
1039         }
1040
1041         if (logfiles.queue_log) {
1042                 snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
1043                 qlog = fopen(tmp, "a");
1044                 ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
1045         }
1046         return res;
1047 }
1048
1049 void close_logger(void)
1050 {
1051         struct logchannel *f = NULL;
1052
1053         /* Stop logger thread */
1054         AST_LIST_LOCK(&logmsgs);
1055         close_logger_thread = 1;
1056         ast_cond_signal(&logcond);
1057         AST_LIST_UNLOCK(&logmsgs);
1058
1059         if (logthread != AST_PTHREADT_NULL)
1060                 pthread_join(logthread, NULL);
1061
1062         AST_RWLIST_WRLOCK(&logchannels);
1063
1064         if (eventlog) {
1065                 fclose(eventlog);
1066                 eventlog = NULL;
1067         }
1068
1069         if (qlog) {
1070                 fclose(qlog);
1071                 qlog = NULL;
1072         }
1073
1074         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
1075                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1076                         fclose(f->fileptr);
1077                         f->fileptr = NULL;
1078                 }
1079         }
1080
1081         closelog(); /* syslog */
1082
1083         AST_RWLIST_UNLOCK(&logchannels);
1084
1085         return;
1086 }
1087
1088 /*!
1089  * \brief send log messages to syslog and/or the console
1090  */
1091 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1092 {
1093         struct logmsg *logmsg = NULL;
1094         struct ast_str *buf = NULL;
1095         struct ast_tm tm;
1096         struct timeval now = ast_tvnow();
1097         int res = 0;
1098         va_list ap;
1099
1100         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1101                 return;
1102
1103         if (AST_RWLIST_EMPTY(&logchannels)) {
1104                 /*
1105                  * we don't have the logger chain configured yet,
1106                  * so just log to stdout
1107                  */
1108                 if (level != __LOG_VERBOSE) {
1109                         int result;
1110                         va_start(ap, fmt);
1111                         result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1112                         va_end(ap);
1113                         if (result != AST_DYNSTR_BUILD_FAILED) {
1114                                 term_filter_escapes(ast_str_buffer(buf));
1115                                 fputs(ast_str_buffer(buf), stdout);
1116                         }
1117                 }
1118                 return;
1119         }
1120         
1121         /* don't display LOG_DEBUG messages unless option_verbose _or_ option_debug
1122            are non-zero; LOG_DEBUG messages can still be displayed if option_debug
1123            is zero, if option_verbose is non-zero (this allows for 'level zero'
1124            LOG_DEBUG messages to be displayed, if the logmask on any channel
1125            allows it)
1126         */
1127         if (!option_verbose && !option_debug && (level == __LOG_DEBUG))
1128                 return;
1129
1130         /* Ignore anything that never gets logged anywhere */
1131         if (!(global_logmask & (1 << level)))
1132                 return;
1133         
1134         /* Build string */
1135         va_start(ap, fmt);
1136         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1137         va_end(ap);
1138
1139         /* If the build failed, then abort and free this structure */
1140         if (res == AST_DYNSTR_BUILD_FAILED)
1141                 return;
1142
1143         /* Create a new logging message */
1144         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1145                 return;
1146
1147         /* Copy string over */
1148         strcpy(logmsg->str, ast_str_buffer(buf));
1149
1150         /* Set type to be normal */
1151         logmsg->type = LOGMSG_NORMAL;
1152
1153         /* Create our date/time */
1154         ast_localtime(&now, &tm, NULL);
1155         ast_strftime(logmsg->date, sizeof(logmsg->date), dateformat, &tm);
1156
1157         /* Copy over data */
1158         logmsg->level = level;
1159         logmsg->line = line;
1160         ast_copy_string(logmsg->file, file, sizeof(logmsg->file));
1161         ast_copy_string(logmsg->function, function, sizeof(logmsg->function));
1162         logmsg->process_id = (long) GETTID();
1163
1164         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1165         if (logthread != AST_PTHREADT_NULL) {
1166                 AST_LIST_LOCK(&logmsgs);
1167                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1168                 ast_cond_signal(&logcond);
1169                 AST_LIST_UNLOCK(&logmsgs);
1170         } else {
1171                 logger_print_normal(logmsg);
1172                 ast_free(logmsg);
1173         }
1174
1175         return;
1176 }
1177
1178 #ifdef HAVE_BKTR
1179
1180 struct ast_bt *ast_bt_create(void) 
1181 {
1182         struct ast_bt *bt = ast_calloc(1, sizeof(*bt));
1183         if (!bt) {
1184                 ast_log(LOG_ERROR, "Unable to allocate memory for backtrace structure!\n");
1185                 return NULL;
1186         }
1187
1188         bt->alloced = 1;
1189
1190         ast_bt_get_addresses(bt);
1191
1192         return bt;
1193 }
1194
1195 int ast_bt_get_addresses(struct ast_bt *bt)
1196 {
1197         bt->num_frames = backtrace(bt->addresses, AST_MAX_BT_FRAMES);
1198
1199         return 0;
1200 }
1201
1202 void *ast_bt_destroy(struct ast_bt *bt)
1203 {
1204         if (bt->alloced) {
1205                 ast_free(bt);
1206         }
1207
1208         return NULL;
1209 }
1210
1211 #endif /* HAVE_BKTR */
1212
1213 void ast_backtrace(void)
1214 {
1215 #ifdef HAVE_BKTR
1216         struct ast_bt *bt;
1217         int i = 0;
1218         char **strings;
1219
1220         if (!(bt = ast_bt_create())) {
1221                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1222                 return;
1223         }
1224
1225         if ((strings = backtrace_symbols(bt->addresses, bt->num_frames))) {
1226                 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1227                 for (i = 0; i < bt->num_frames; i++) {
1228                         ast_log(LOG_DEBUG, "#%d: [%p] %s\n", i, bt->addresses[i], strings[i]);
1229                 }
1230                 free(strings);
1231         } else {
1232                 ast_debug(1, "Could not allocate memory for backtrace\n");
1233         }
1234         ast_bt_destroy(bt);
1235 #else
1236         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1237 #endif
1238 }
1239
1240 void __ast_verbose_ap(const char *file, int line, const char *func, const char *fmt, va_list ap)
1241 {
1242         struct logmsg *logmsg = NULL;
1243         struct ast_str *buf = NULL;
1244         int res = 0;
1245
1246         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE)))
1247                 return;
1248
1249         if (ast_opt_timestamp) {
1250                 struct timeval now;
1251                 struct ast_tm tm;
1252                 char date[40];
1253                 char *datefmt;
1254
1255                 now = ast_tvnow();
1256                 ast_localtime(&now, &tm, NULL);
1257                 ast_strftime(date, sizeof(date), dateformat, &tm);
1258                 datefmt = alloca(strlen(date) + 3 + strlen(fmt) + 1);
1259                 sprintf(datefmt, "%c[%s] %s", 127, date, fmt);
1260                 fmt = datefmt;
1261         } else {
1262                 char *tmp = alloca(strlen(fmt) + 2);
1263                 sprintf(tmp, "%c%s", 127, fmt);
1264                 fmt = tmp;
1265         }
1266
1267         /* Build string */
1268         res = ast_str_set_va(&buf, 0, fmt, ap);
1269
1270         /* If the build failed then we can drop this allocated message */
1271         if (res == AST_DYNSTR_BUILD_FAILED)
1272                 return;
1273
1274         if (!(logmsg = ast_calloc(1, sizeof(*logmsg) + res + 1)))
1275                 return;
1276
1277         strcpy(logmsg->str, ast_str_buffer(buf));
1278
1279         ast_log(__LOG_VERBOSE, file, line, func, "%s", logmsg->str + 1);
1280
1281         /* Set type */
1282         logmsg->type = LOGMSG_VERBOSE;
1283         
1284         /* Add to the list and poke the thread if possible */
1285         if (logthread != AST_PTHREADT_NULL) {
1286                 AST_LIST_LOCK(&logmsgs);
1287                 AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1288                 ast_cond_signal(&logcond);
1289                 AST_LIST_UNLOCK(&logmsgs);
1290         } else {
1291                 logger_print_verbose(logmsg);
1292                 ast_free(logmsg);
1293         }
1294 }
1295
1296 void __ast_verbose(const char *file, int line, const char *func, const char *fmt, ...)
1297 {
1298         va_list ap;
1299         va_start(ap, fmt);
1300         __ast_verbose_ap(file, line, func, fmt, ap);
1301         va_end(ap);
1302 }
1303
1304 /* No new code should use this directly, but we have the ABI for backwards compat */
1305 #undef ast_verbose
1306 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1307 void ast_verbose(const char *fmt, ...)
1308 {
1309         va_list ap;
1310         va_start(ap, fmt);
1311         __ast_verbose_ap("", 0, "", fmt, ap);
1312         va_end(ap);
1313 }
1314
1315 int ast_register_verbose(void (*v)(const char *string)) 
1316 {
1317         struct verb *verb;
1318
1319         if (!(verb = ast_malloc(sizeof(*verb))))
1320                 return -1;
1321
1322         verb->verboser = v;
1323
1324         AST_RWLIST_WRLOCK(&verbosers);
1325         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1326         AST_RWLIST_UNLOCK(&verbosers);
1327         
1328         return 0;
1329 }
1330
1331 int ast_unregister_verbose(void (*v)(const char *string))
1332 {
1333         struct verb *cur;
1334
1335         AST_RWLIST_WRLOCK(&verbosers);
1336         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1337                 if (cur->verboser == v) {
1338                         AST_RWLIST_REMOVE_CURRENT(list);
1339                         ast_free(cur);
1340                         break;
1341                 }
1342         }
1343         AST_RWLIST_TRAVERSE_SAFE_END;
1344         AST_RWLIST_UNLOCK(&verbosers);
1345         
1346         return cur ? 0 : -1;
1347 }