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