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