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