c374d2e574324f5e2e5fbd19d25e40b905055506
[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 /*! \li \ref logger.c uses the configuration file \ref logger.conf
29  * \addtogroup configuration_file Configuration Files
30  */
31
32 /*!
33  * \page logger.conf logger.conf
34  * \verbinclude logger.conf.sample
35  */
36
37 /*** MODULEINFO
38         <support_level>core</support_level>
39  ***/
40
41 #include "asterisk.h"
42
43 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
44
45 /* When we include logger.h again it will trample on some stuff in syslog.h, but
46  * nothing we care about in here. */
47 #include <syslog.h>
48 #include <signal.h>
49 #include <time.h>
50 #include <sys/stat.h>
51 #include <fcntl.h>
52
53 #include "asterisk/_private.h"
54 #include "asterisk/paths.h"     /* use ast_config_AST_LOG_DIR */
55 #include "asterisk/logger.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/channel.h"
58 #include "asterisk/config.h"
59 #include "asterisk/term.h"
60 #include "asterisk/cli.h"
61 #include "asterisk/utils.h"
62 #include "asterisk/manager.h"
63 #include "asterisk/astobj2.h"
64 #include "asterisk/threadstorage.h"
65 #include "asterisk/strings.h"
66 #include "asterisk/pbx.h"
67 #include "asterisk/app.h"
68 #include "asterisk/syslog.h"
69 #include "asterisk/buildinfo.h"
70 #include "asterisk/ast_version.h"
71 #include "asterisk/backtrace.h"
72
73 /*** DOCUMENTATION
74  ***/
75
76 static char dateformat[256] = "%b %e %T";               /* Original Asterisk Format */
77
78 static char queue_log_name[256] = QUEUELOG;
79 static char exec_after_rotate[256] = "";
80
81 static int filesize_reload_needed;
82 static unsigned int global_logmask = 0xFFFF;
83 static int queuelog_init;
84 static int logger_initialized;
85 static volatile int next_unique_callid; /* Used to assign unique call_ids to calls */
86 static int display_callids;
87 static void unique_callid_cleanup(void *data);
88
89 struct ast_callid {
90     int call_identifier; /* Numerical value of the call displayed in the logs */
91 };
92
93 AST_THREADSTORAGE_CUSTOM(unique_callid, NULL, unique_callid_cleanup);
94
95 static enum rotatestrategy {
96         NONE = 0,                /* Do not rotate log files at all, instead rely on external mechanisms */
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 queue_log_to_file:1;
105         unsigned int queue_adaptive_realtime:1;
106         unsigned int queue_log_realtime_use_gmt:1;
107 } logfiles = { 1 };
108
109 static char hostname[MAXHOSTNAMELEN];
110
111 enum logtypes {
112         LOGTYPE_SYSLOG,
113         LOGTYPE_FILE,
114         LOGTYPE_CONSOLE,
115 };
116
117 struct logchannel {
118         /*! What to log to this channel */
119         unsigned int logmask;
120         /*! If this channel is disabled or not */
121         int disabled;
122         /*! syslog facility */
123         int facility;
124         /*! Verbosity level */
125         int verbosity;
126         /*! Type of log channel */
127         enum logtypes type;
128         /*! logfile logging file pointer */
129         FILE *fileptr;
130         /*! Filename */
131         char filename[PATH_MAX];
132         /*! field for linking to list */
133         AST_LIST_ENTRY(logchannel) list;
134         /*! Line number from configuration file */
135         int lineno;
136         /*! Components (levels) from last config load */
137         char components[0];
138 };
139
140 static AST_RWLIST_HEAD_STATIC(logchannels, logchannel);
141
142 enum logmsgtypes {
143         LOGMSG_NORMAL = 0,
144         LOGMSG_VERBOSE,
145 };
146
147 struct logmsg {
148         enum logmsgtypes type;
149         int level;
150         int line;
151         int lwp;
152         struct ast_callid *callid;
153         AST_DECLARE_STRING_FIELDS(
154                 AST_STRING_FIELD(date);
155                 AST_STRING_FIELD(file);
156                 AST_STRING_FIELD(function);
157                 AST_STRING_FIELD(message);
158                 AST_STRING_FIELD(level_name);
159         );
160         AST_LIST_ENTRY(logmsg) list;
161 };
162
163 static void logmsg_free(struct logmsg *msg)
164 {
165         if (msg->callid) {
166                 ast_callid_unref(msg->callid);
167         }
168         ast_free(msg);
169 }
170
171 static AST_LIST_HEAD_STATIC(logmsgs, logmsg);
172 static pthread_t logthread = AST_PTHREADT_NULL;
173 static ast_cond_t logcond;
174 static int close_logger_thread = 0;
175
176 static FILE *qlog;
177
178 /*! \brief Logging channels used in the Asterisk logging system
179  *
180  * The first 16 levels are reserved for system usage, and the remaining
181  * levels are reserved for usage by dynamic levels registered via
182  * ast_logger_register_level.
183  */
184
185 /* Modifications to this array are protected by the rwlock in the
186  * logchannels list.
187  */
188
189 static char *levels[NUMLOGLEVELS] = {
190         "DEBUG",
191         "---EVENT---",          /* no longer used */
192         "NOTICE",
193         "WARNING",
194         "ERROR",
195         "VERBOSE",
196         "DTMF",
197 };
198
199 /*! \brief Colors used in the console for logging */
200 static const int colors[NUMLOGLEVELS] = {
201         COLOR_BRGREEN,
202         COLOR_BRBLUE,           /* no longer used */
203         COLOR_YELLOW,
204         COLOR_BRRED,
205         COLOR_RED,
206         COLOR_GREEN,
207         COLOR_BRGREEN,
208         0,
209         0,
210         0,
211         0,
212         0,
213         0,
214         0,
215         0,
216         0,
217         COLOR_BRBLUE,
218         COLOR_BRBLUE,
219         COLOR_BRBLUE,
220         COLOR_BRBLUE,
221         COLOR_BRBLUE,
222         COLOR_BRBLUE,
223         COLOR_BRBLUE,
224         COLOR_BRBLUE,
225         COLOR_BRBLUE,
226         COLOR_BRBLUE,
227         COLOR_BRBLUE,
228         COLOR_BRBLUE,
229         COLOR_BRBLUE,
230         COLOR_BRBLUE,
231         COLOR_BRBLUE,
232         COLOR_BRBLUE,
233 };
234
235 AST_THREADSTORAGE(verbose_buf);
236 #define VERBOSE_BUF_INIT_SIZE   256
237
238 AST_THREADSTORAGE(log_buf);
239 #define LOG_BUF_INIT_SIZE       256
240
241 static void logger_queue_init(void);
242
243 static unsigned int make_components(const char *s, int lineno, int *verbosity)
244 {
245         char *w;
246         unsigned int res = 0;
247         char *stringp = ast_strdupa(s);
248         unsigned int x;
249
250         *verbosity = 3;
251
252         while ((w = strsep(&stringp, ","))) {
253                 w = ast_skip_blanks(w);
254
255                 if (!strcmp(w, "*")) {
256                         res = 0xFFFFFFFF;
257                         break;
258                 } else if (!strncasecmp(w, "verbose(", 8) && sscanf(w + 8, "%d)", verbosity) == 1) {
259                         res |= (1 << __LOG_VERBOSE);
260                         break;
261                 } else for (x = 0; x < ARRAY_LEN(levels); x++) {
262                         if (levels[x] && !strcasecmp(w, levels[x])) {
263                                 res |= (1 << x);
264                                 break;
265                         }
266                 }
267         }
268
269         return res;
270 }
271
272 static struct logchannel *make_logchannel(const char *channel, const char *components, int lineno)
273 {
274         struct logchannel *chan;
275         char *facility;
276         struct ast_tm tm;
277         struct timeval now = ast_tvnow();
278         char datestring[256];
279
280         if (ast_strlen_zero(channel) || !(chan = ast_calloc(1, sizeof(*chan) + strlen(components) + 1)))
281                 return NULL;
282
283         strcpy(chan->components, components);
284         chan->lineno = lineno;
285
286         if (!strcasecmp(channel, "console")) {
287                 chan->type = LOGTYPE_CONSOLE;
288         } else if (!strncasecmp(channel, "syslog", 6)) {
289                 /*
290                 * syntax is:
291                 *  syslog.facility => level,level,level
292                 */
293                 facility = strchr(channel, '.');
294                 if (!facility++ || !facility) {
295                         facility = "local0";
296                 }
297
298                 chan->facility = ast_syslog_facility(facility);
299
300                 if (chan->facility < 0) {
301                         fprintf(stderr, "Logger Warning: bad syslog facility in logger.conf\n");
302                         ast_free(chan);
303                         return NULL;
304                 }
305
306                 chan->type = LOGTYPE_SYSLOG;
307                 ast_copy_string(chan->filename, channel, sizeof(chan->filename));
308                 openlog("asterisk", LOG_PID, chan->facility);
309         } else {
310                 if (!ast_strlen_zero(hostname)) {
311                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s.%s",
312                                  channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel, hostname);
313                 } else {
314                         snprintf(chan->filename, sizeof(chan->filename), "%s/%s",
315                                  channel[0] != '/' ? ast_config_AST_LOG_DIR : "", channel);
316                 }
317                 if (!(chan->fileptr = fopen(chan->filename, "a"))) {
318                         /* Can't do real logging here since we're called with a lock
319                          * so log to any attached consoles */
320                         ast_console_puts_mutable("ERROR: Unable to open log file '", __LOG_ERROR);
321                         ast_console_puts_mutable(chan->filename, __LOG_ERROR);
322                         ast_console_puts_mutable("': ", __LOG_ERROR);
323                         ast_console_puts_mutable(strerror(errno), __LOG_ERROR);
324                         ast_console_puts_mutable("'\n", __LOG_ERROR);
325                         ast_free(chan);
326                         return NULL;
327                 } else {
328                         /* Create our date/time */
329                         ast_localtime(&now, &tm, NULL);
330                         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
331
332                         fprintf(chan->fileptr, "[%s] Asterisk %s built by %s @ %s on a %s running %s on %s\n",
333                                 datestring, ast_get_version(), ast_build_user, ast_build_hostname,
334                                 ast_build_machine, ast_build_os, ast_build_date);
335                         fflush(chan->fileptr);
336                 }
337                 chan->type = LOGTYPE_FILE;
338         }
339         chan->logmask = make_components(chan->components, lineno, &chan->verbosity);
340
341         return chan;
342 }
343
344 static void init_logger_chain(int locked, const char *altconf)
345 {
346         struct logchannel *chan;
347         struct ast_config *cfg;
348         struct ast_variable *var;
349         const char *s;
350         struct ast_flags config_flags = { 0 };
351
352         display_callids = 1;
353
354         if (!(cfg = ast_config_load2(S_OR(altconf, "logger.conf"), "logger", config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) {
355                 return;
356         }
357
358         /* delete our list of log channels */
359         if (!locked) {
360                 AST_RWLIST_WRLOCK(&logchannels);
361         }
362         while ((chan = AST_RWLIST_REMOVE_HEAD(&logchannels, list))) {
363                 ast_free(chan);
364         }
365         global_logmask = 0;
366         if (!locked) {
367                 AST_RWLIST_UNLOCK(&logchannels);
368         }
369
370         errno = 0;
371         /* close syslog */
372         closelog();
373
374         /* If no config file, we're fine, set default options. */
375         if (!cfg) {
376                 if (errno) {
377                         fprintf(stderr, "Unable to open logger.conf: %s; default settings will be used.\n", strerror(errno));
378                 } else {
379                         fprintf(stderr, "Errors detected in logger.conf: see above; default settings will be used.\n");
380                 }
381                 if (!(chan = ast_calloc(1, sizeof(*chan)))) {
382                         return;
383                 }
384                 chan->type = LOGTYPE_CONSOLE;
385                 chan->logmask = __LOG_WARNING | __LOG_NOTICE | __LOG_ERROR;
386                 if (!locked) {
387                         AST_RWLIST_WRLOCK(&logchannels);
388                 }
389                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
390                 global_logmask |= chan->logmask;
391                 if (!locked) {
392                         AST_RWLIST_UNLOCK(&logchannels);
393                 }
394                 return;
395         }
396
397         if ((s = ast_variable_retrieve(cfg, "general", "appendhostname"))) {
398                 if (ast_true(s)) {
399                         if (gethostname(hostname, sizeof(hostname) - 1)) {
400                                 ast_copy_string(hostname, "unknown", sizeof(hostname));
401                                 fprintf(stderr, "What box has no hostname???\n");
402                         }
403                 } else
404                         hostname[0] = '\0';
405         } else
406                 hostname[0] = '\0';
407         if ((s = ast_variable_retrieve(cfg, "general", "display_callids"))) {
408                 display_callids = ast_true(s);
409         }
410         if ((s = ast_variable_retrieve(cfg, "general", "dateformat")))
411                 ast_copy_string(dateformat, s, sizeof(dateformat));
412         else
413                 ast_copy_string(dateformat, "%b %e %T", sizeof(dateformat));
414         if ((s = ast_variable_retrieve(cfg, "general", "queue_log"))) {
415                 logfiles.queue_log = ast_true(s);
416         }
417         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_to_file"))) {
418                 logfiles.queue_log_to_file = ast_true(s);
419         }
420         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_name"))) {
421                 ast_copy_string(queue_log_name, s, sizeof(queue_log_name));
422         }
423         if ((s = ast_variable_retrieve(cfg, "general", "queue_log_realtime_use_gmt"))) {
424                 logfiles.queue_log_realtime_use_gmt = ast_true(s);
425         }
426         if ((s = ast_variable_retrieve(cfg, "general", "exec_after_rotate"))) {
427                 ast_copy_string(exec_after_rotate, s, sizeof(exec_after_rotate));
428         }
429         if ((s = ast_variable_retrieve(cfg, "general", "rotatestrategy"))) {
430                 if (strcasecmp(s, "timestamp") == 0) {
431                         rotatestrategy = TIMESTAMP;
432                 } else if (strcasecmp(s, "rotate") == 0) {
433                         rotatestrategy = ROTATE;
434                 } else if (strcasecmp(s, "sequential") == 0) {
435                         rotatestrategy = SEQUENTIAL;
436                 } else if (strcasecmp(s, "none") == 0) {
437                         rotatestrategy = NONE;
438                 } else {
439                         fprintf(stderr, "Unknown rotatestrategy: %s\n", s);
440                 }
441         } else {
442                 if ((s = ast_variable_retrieve(cfg, "general", "rotatetimestamp"))) {
443                         rotatestrategy = ast_true(s) ? TIMESTAMP : SEQUENTIAL;
444                         fprintf(stderr, "rotatetimestamp option has been deprecated.  Please use rotatestrategy instead.\n");
445                 }
446         }
447
448         if (!locked) {
449                 AST_RWLIST_WRLOCK(&logchannels);
450         }
451         var = ast_variable_browse(cfg, "logfiles");
452         for (; var; var = var->next) {
453                 if (!(chan = make_logchannel(var->name, var->value, var->lineno))) {
454                         /* Print error message directly to the consoles since the lock is held
455                          * and we don't want to unlock with the list partially built */
456                         ast_console_puts_mutable("ERROR: Unable to create log channel '", __LOG_ERROR);
457                         ast_console_puts_mutable(var->name, __LOG_ERROR);
458                         ast_console_puts_mutable("'\n", __LOG_ERROR);
459                         continue;
460                 }
461                 AST_RWLIST_INSERT_HEAD(&logchannels, chan, list);
462                 global_logmask |= chan->logmask;
463         }
464
465         if (qlog) {
466                 fclose(qlog);
467                 qlog = NULL;
468         }
469
470         if (!locked) {
471                 AST_RWLIST_UNLOCK(&logchannels);
472         }
473
474         ast_config_destroy(cfg);
475 }
476
477 void ast_child_verbose(int level, const char *fmt, ...)
478 {
479         char *msg = NULL, *emsg = NULL, *sptr, *eptr;
480         va_list ap, aq;
481         int size;
482
483         va_start(ap, fmt);
484         va_copy(aq, ap);
485         if ((size = vsnprintf(msg, 0, fmt, ap)) < 0) {
486                 va_end(ap);
487                 va_end(aq);
488                 return;
489         }
490         va_end(ap);
491
492         if (!(msg = ast_malloc(size + 1))) {
493                 va_end(aq);
494                 return;
495         }
496
497         vsnprintf(msg, size + 1, fmt, aq);
498         va_end(aq);
499
500         if (!(emsg = ast_malloc(size * 2 + 1))) {
501                 ast_free(msg);
502                 return;
503         }
504
505         for (sptr = msg, eptr = emsg; ; sptr++) {
506                 if (*sptr == '"') {
507                         *eptr++ = '\\';
508                 }
509                 *eptr++ = *sptr;
510                 if (*sptr == '\0') {
511                         break;
512                 }
513         }
514         ast_free(msg);
515
516         fprintf(stdout, "verbose \"%s\" %d\n", emsg, level);
517         fflush(stdout);
518         ast_free(emsg);
519 }
520
521 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
522 {
523         va_list ap;
524         struct timeval tv;
525         struct ast_tm tm;
526         char qlog_msg[8192];
527         int qlog_len;
528         char time_str[30];
529
530         if (!logger_initialized) {
531                 /* You are too early.  We are not open yet! */
532                 return;
533         }
534         if (!queuelog_init) {
535                 AST_RWLIST_WRLOCK(&logchannels);
536                 if (!queuelog_init) {
537                         /*
538                          * We have delayed initializing the queue logging system so
539                          * preloaded realtime modules can get up.  We must initialize
540                          * now since someone is trying to log something.
541                          */
542                         logger_queue_init();
543                         queuelog_init = 1;
544                         AST_RWLIST_UNLOCK(&logchannels);
545                         ast_queue_log("NONE", "NONE", "NONE", "QUEUESTART", "%s", "");
546                 } else {
547                         AST_RWLIST_UNLOCK(&logchannels);
548                 }
549         }
550
551         if (ast_check_realtime("queue_log")) {
552                 tv = ast_tvnow();
553                 ast_localtime(&tv, &tm, logfiles.queue_log_realtime_use_gmt ? "GMT" : NULL);
554                 ast_strftime(time_str, sizeof(time_str), "%F %T.%6q", &tm);
555                 va_start(ap, fmt);
556                 vsnprintf(qlog_msg, sizeof(qlog_msg), fmt, ap);
557                 va_end(ap);
558                 if (logfiles.queue_adaptive_realtime) {
559                         AST_DECLARE_APP_ARGS(args,
560                                 AST_APP_ARG(data)[5];
561                         );
562                         AST_NONSTANDARD_APP_ARGS(args, qlog_msg, '|');
563                         /* Ensure fields are large enough to receive data */
564                         ast_realtime_require_field("queue_log",
565                                 "data1", RQ_CHAR, strlen(S_OR(args.data[0], "")),
566                                 "data2", RQ_CHAR, strlen(S_OR(args.data[1], "")),
567                                 "data3", RQ_CHAR, strlen(S_OR(args.data[2], "")),
568                                 "data4", RQ_CHAR, strlen(S_OR(args.data[3], "")),
569                                 "data5", RQ_CHAR, strlen(S_OR(args.data[4], "")),
570                                 SENTINEL);
571
572                         /* Store the log */
573                         ast_store_realtime("queue_log", "time", time_str,
574                                 "callid", callid,
575                                 "queuename", queuename,
576                                 "agent", agent,
577                                 "event", event,
578                                 "data1", S_OR(args.data[0], ""),
579                                 "data2", S_OR(args.data[1], ""),
580                                 "data3", S_OR(args.data[2], ""),
581                                 "data4", S_OR(args.data[3], ""),
582                                 "data5", S_OR(args.data[4], ""),
583                                 SENTINEL);
584                 } else {
585                         ast_store_realtime("queue_log", "time", time_str,
586                                 "callid", callid,
587                                 "queuename", queuename,
588                                 "agent", agent,
589                                 "event", event,
590                                 "data", qlog_msg,
591                                 SENTINEL);
592                 }
593
594                 if (!logfiles.queue_log_to_file) {
595                         return;
596                 }
597         }
598
599         if (qlog) {
600                 va_start(ap, fmt);
601                 qlog_len = snprintf(qlog_msg, sizeof(qlog_msg), "%ld|%s|%s|%s|%s|", (long)time(NULL), callid, queuename, agent, event);
602                 vsnprintf(qlog_msg + qlog_len, sizeof(qlog_msg) - qlog_len, fmt, ap);
603                 va_end(ap);
604                 AST_RWLIST_RDLOCK(&logchannels);
605                 if (qlog) {
606                         fprintf(qlog, "%s\n", qlog_msg);
607                         fflush(qlog);
608                 }
609                 AST_RWLIST_UNLOCK(&logchannels);
610         }
611 }
612
613 static int rotate_file(const char *filename)
614 {
615         char old[PATH_MAX];
616         char new[PATH_MAX];
617         int x, y, which, found, res = 0, fd;
618         char *suffixes[4] = { "", ".gz", ".bz2", ".Z" };
619
620         switch (rotatestrategy) {
621         case NONE:
622                 /* No rotation */
623                 break;
624         case SEQUENTIAL:
625                 for (x = 0; ; x++) {
626                         snprintf(new, sizeof(new), "%s.%d", filename, x);
627                         fd = open(new, O_RDONLY);
628                         if (fd > -1)
629                                 close(fd);
630                         else
631                                 break;
632                 }
633                 if (rename(filename, new)) {
634                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
635                         res = -1;
636                 } else {
637                         filename = new;
638                 }
639                 break;
640         case TIMESTAMP:
641                 snprintf(new, sizeof(new), "%s.%ld", filename, (long)time(NULL));
642                 if (rename(filename, new)) {
643                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
644                         res = -1;
645                 } else {
646                         filename = new;
647                 }
648                 break;
649         case ROTATE:
650                 /* Find the next empty slot, including a possible suffix */
651                 for (x = 0; ; x++) {
652                         found = 0;
653                         for (which = 0; which < ARRAY_LEN(suffixes); which++) {
654                                 snprintf(new, sizeof(new), "%s.%d%s", filename, x, suffixes[which]);
655                                 fd = open(new, O_RDONLY);
656                                 if (fd > -1) {
657                                         close(fd);
658                                         found = 1;
659                                         break;
660                                 }
661                         }
662                         if (!found) {
663                                 break;
664                         }
665                 }
666
667                 /* Found an empty slot */
668                 for (y = x; y > 0; y--) {
669                         for (which = 0; which < ARRAY_LEN(suffixes); which++) {
670                                 snprintf(old, sizeof(old), "%s.%d%s", filename, y - 1, suffixes[which]);
671                                 fd = open(old, O_RDONLY);
672                                 if (fd > -1) {
673                                         /* Found the right suffix */
674                                         close(fd);
675                                         snprintf(new, sizeof(new), "%s.%d%s", filename, y, suffixes[which]);
676                                         if (rename(old, new)) {
677                                                 fprintf(stderr, "Unable to rename file '%s' to '%s'\n", old, new);
678                                                 res = -1;
679                                         }
680                                         break;
681                                 }
682                         }
683                 }
684
685                 /* Finally, rename the current file */
686                 snprintf(new, sizeof(new), "%s.0", filename);
687                 if (rename(filename, new)) {
688                         fprintf(stderr, "Unable to rename file '%s' to '%s'\n", filename, new);
689                         res = -1;
690                 } else {
691                         filename = new;
692                 }
693         }
694
695         if (!ast_strlen_zero(exec_after_rotate)) {
696                 struct ast_channel *c = ast_dummy_channel_alloc();
697                 char buf[512];
698
699                 pbx_builtin_setvar_helper(c, "filename", filename);
700                 pbx_substitute_variables_helper(c, exec_after_rotate, buf, sizeof(buf));
701                 if (c) {
702                         c = ast_channel_unref(c);
703                 }
704                 if (ast_safe_system(buf) == -1) {
705                         ast_log(LOG_WARNING, "error executing '%s'\n", buf);
706                 }
707         }
708         return res;
709 }
710
711 /*!
712  * \internal
713  * \brief Start the realtime queue logging if configured.
714  *
715  * \retval TRUE if not to open queue log file.
716  */
717 static int logger_queue_rt_start(void)
718 {
719         if (ast_check_realtime("queue_log")) {
720                 if (!ast_realtime_require_field("queue_log",
721                         "time", RQ_DATETIME, 26,
722                         "data1", RQ_CHAR, 20,
723                         "data2", RQ_CHAR, 20,
724                         "data3", RQ_CHAR, 20,
725                         "data4", RQ_CHAR, 20,
726                         "data5", RQ_CHAR, 20,
727                         SENTINEL)) {
728                         logfiles.queue_adaptive_realtime = 1;
729                 } else {
730                         logfiles.queue_adaptive_realtime = 0;
731                 }
732
733                 if (!logfiles.queue_log_to_file) {
734                         /* Don't open the log file. */
735                         return 1;
736                 }
737         }
738         return 0;
739 }
740
741 /*!
742  * \internal
743  * \brief Rotate the queue log file and restart.
744  *
745  * \param queue_rotate Log queue rotation mode.
746  *
747  * \note Assumes logchannels is write locked on entry.
748  *
749  * \retval 0 on success.
750  * \retval -1 on error.
751  */
752 static int logger_queue_restart(int queue_rotate)
753 {
754         int res = 0;
755         char qfname[PATH_MAX];
756
757         if (logger_queue_rt_start()) {
758                 return res;
759         }
760
761         snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR, queue_log_name);
762         if (qlog) {
763                 /* Just in case it was still open. */
764                 fclose(qlog);
765                 qlog = NULL;
766         }
767         if (queue_rotate) {
768                 rotate_file(qfname);
769         }
770
771         /* Open the log file. */
772         qlog = fopen(qfname, "a");
773         if (!qlog) {
774                 ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
775                 res = -1;
776         }
777         return res;
778 }
779
780 static int reload_logger(int rotate, const char *altconf)
781 {
782         int queue_rotate = rotate;
783         struct logchannel *f;
784         int res = 0;
785
786         AST_RWLIST_WRLOCK(&logchannels);
787
788         if (qlog) {
789                 if (rotate < 0) {
790                         /* Check filesize - this one typically doesn't need an auto-rotate */
791                         if (ftello(qlog) > 0x40000000) { /* Arbitrarily, 1 GB */
792                                 fclose(qlog);
793                                 qlog = NULL;
794                         } else {
795                                 queue_rotate = 0;
796                         }
797                 } else {
798                         fclose(qlog);
799                         qlog = NULL;
800                 }
801         } else {
802                 queue_rotate = 0;
803         }
804
805         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
806
807         AST_RWLIST_TRAVERSE(&logchannels, f, list) {
808                 if (f->disabled) {
809                         f->disabled = 0;        /* Re-enable logging at reload */
810                         /*** DOCUMENTATION
811                                 <managerEventInstance>
812                                         <synopsis>Raised when a logging channel is re-enabled after a reload operation.</synopsis>
813                                         <syntax>
814                                                 <parameter name="Channel">
815                                                         <para>The name of the logging channel.</para>
816                                                 </parameter>
817                                         </syntax>
818                                 </managerEventInstance>
819                         ***/
820                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: Yes\r\n", f->filename);
821                 }
822                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
823                         int rotate_this = 0;
824                         if (rotatestrategy != NONE && ftello(f->fileptr) > 0x40000000) { /* Arbitrarily, 1 GB */
825                                 /* Be more proactive about rotating massive log files */
826                                 rotate_this = 1;
827                         }
828                         fclose(f->fileptr);     /* Close file */
829                         f->fileptr = NULL;
830                         if (rotate || rotate_this) {
831                                 rotate_file(f->filename);
832                         }
833                 }
834         }
835
836         filesize_reload_needed = 0;
837
838         init_logger_chain(1 /* locked */, altconf);
839
840         ast_unload_realtime("queue_log");
841         if (logfiles.queue_log) {
842                 res = logger_queue_restart(queue_rotate);
843                 AST_RWLIST_UNLOCK(&logchannels);
844                 ast_queue_log("NONE", "NONE", "NONE", "CONFIGRELOAD", "%s", "");
845                 ast_verb(1, "Asterisk Queue Logger restarted\n");
846         } else {
847                 AST_RWLIST_UNLOCK(&logchannels);
848         }
849
850         return res;
851 }
852
853 /*! \brief Reload the logger module without rotating log files (also used from loader.c during
854         a full Asterisk reload) */
855 int logger_reload(void)
856 {
857         if (reload_logger(0, NULL)) {
858                 return RESULT_FAILURE;
859         }
860         return RESULT_SUCCESS;
861 }
862
863 static char *handle_logger_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
864 {
865         switch (cmd) {
866         case CLI_INIT:
867                 e->command = "logger reload";
868                 e->usage =
869                         "Usage: logger reload [<alt-conf>]\n"
870                         "       Reloads the logger subsystem state.  Use after restarting syslogd(8) if you are using syslog logging.\n";
871                 return NULL;
872         case CLI_GENERATE:
873                 return NULL;
874         }
875         if (reload_logger(0, a->argc == 3 ? a->argv[2] : NULL)) {
876                 ast_cli(a->fd, "Failed to reload the logger\n");
877                 return CLI_FAILURE;
878         }
879         return CLI_SUCCESS;
880 }
881
882 static char *handle_logger_rotate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
883 {
884         switch (cmd) {
885         case CLI_INIT:
886                 e->command = "logger rotate";
887                 e->usage =
888                         "Usage: logger rotate\n"
889                         "       Rotates and Reopens the log files.\n";
890                 return NULL;
891         case CLI_GENERATE:
892                 return NULL;
893         }
894         if (reload_logger(1, NULL)) {
895                 ast_cli(a->fd, "Failed to reload the logger and rotate log files\n");
896                 return CLI_FAILURE;
897         }
898         return CLI_SUCCESS;
899 }
900
901 static char *handle_logger_set_level(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
902 {
903         int x;
904         int state;
905         int level = -1;
906
907         switch (cmd) {
908         case CLI_INIT:
909                 e->command = "logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}";
910                 e->usage =
911                         "Usage: logger set level {DEBUG|NOTICE|WARNING|ERROR|VERBOSE|DTMF} {on|off}\n"
912                         "       Set a specific log level to enabled/disabled for this console.\n";
913                 return NULL;
914         case CLI_GENERATE:
915                 return NULL;
916         }
917
918         if (a->argc < 5)
919                 return CLI_SHOWUSAGE;
920
921         AST_RWLIST_WRLOCK(&logchannels);
922
923         for (x = 0; x < ARRAY_LEN(levels); x++) {
924                 if (levels[x] && !strcasecmp(a->argv[3], levels[x])) {
925                         level = x;
926                         break;
927                 }
928         }
929
930         AST_RWLIST_UNLOCK(&logchannels);
931
932         state = ast_true(a->argv[4]) ? 1 : 0;
933
934         if (level != -1) {
935                 ast_console_toggle_loglevel(a->fd, level, state);
936                 ast_cli(a->fd, "Logger status for '%s' has been set to '%s'.\n", levels[level], state ? "on" : "off");
937         } else
938                 return CLI_SHOWUSAGE;
939
940         return CLI_SUCCESS;
941 }
942
943 /*! \brief CLI command to show logging system configuration */
944 static char *handle_logger_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
945 {
946 #define FORMATL "%-35.35s %-8.8s %-9.9s "
947         struct logchannel *chan;
948         switch (cmd) {
949         case CLI_INIT:
950                 e->command = "logger show channels";
951                 e->usage =
952                         "Usage: logger show channels\n"
953                         "       List configured logger channels.\n";
954                 return NULL;
955         case CLI_GENERATE:
956                 return NULL;
957         }
958         ast_cli(a->fd, FORMATL, "Channel", "Type", "Status");
959         ast_cli(a->fd, "Configuration\n");
960         ast_cli(a->fd, FORMATL, "-------", "----", "------");
961         ast_cli(a->fd, "-------------\n");
962         AST_RWLIST_RDLOCK(&logchannels);
963         AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
964                 unsigned int level;
965
966                 ast_cli(a->fd, FORMATL, chan->filename, chan->type == LOGTYPE_CONSOLE ? "Console" : (chan->type == LOGTYPE_SYSLOG ? "Syslog" : "File"),
967                         chan->disabled ? "Disabled" : "Enabled");
968                 ast_cli(a->fd, " - ");
969                 for (level = 0; level < ARRAY_LEN(levels); level++) {
970                         if ((chan->logmask & (1 << level)) && levels[level]) {
971                                 ast_cli(a->fd, "%s ", levels[level]);
972                         }
973                 }
974                 ast_cli(a->fd, "\n");
975         }
976         AST_RWLIST_UNLOCK(&logchannels);
977         ast_cli(a->fd, "\n");
978
979         return CLI_SUCCESS;
980 }
981
982 struct verb {
983         void (*verboser)(const char *string);
984         AST_LIST_ENTRY(verb) list;
985 };
986
987 static AST_RWLIST_HEAD_STATIC(verbosers, verb);
988
989 static struct ast_cli_entry cli_logger[] = {
990         AST_CLI_DEFINE(handle_logger_show_channels, "List configured log channels"),
991         AST_CLI_DEFINE(handle_logger_reload, "Reopens the log files"),
992         AST_CLI_DEFINE(handle_logger_rotate, "Rotates and reopens the log files"),
993         AST_CLI_DEFINE(handle_logger_set_level, "Enables/Disables a specific logging level for this console")
994 };
995
996 static void _handle_SIGXFSZ(int sig)
997 {
998         /* Indicate need to reload */
999         filesize_reload_needed = 1;
1000 }
1001
1002 static struct sigaction handle_SIGXFSZ = {
1003         .sa_handler = _handle_SIGXFSZ,
1004         .sa_flags = SA_RESTART,
1005 };
1006
1007 static void ast_log_vsyslog(struct logmsg *msg)
1008 {
1009         char buf[BUFSIZ];
1010         int syslog_level = ast_syslog_priority_from_loglevel(msg->level);
1011         char call_identifier_str[13];
1012
1013         if (msg->callid) {
1014                 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", msg->callid->call_identifier);
1015         } else {
1016                 call_identifier_str[0] = '\0';
1017         }
1018
1019         if (syslog_level < 0) {
1020                 /* we are locked here, so cannot ast_log() */
1021                 fprintf(stderr, "ast_log_vsyslog called with bogus level: %d\n", msg->level);
1022                 return;
1023         }
1024
1025         snprintf(buf, sizeof(buf), "%s[%d]%s: %s:%d in %s: %s",
1026                  levels[msg->level], msg->lwp, call_identifier_str, msg->file, msg->line, msg->function, msg->message);
1027
1028         term_strip(buf, buf, strlen(buf) + 1);
1029         syslog(syslog_level, "%s", buf);
1030 }
1031
1032 /* These gymnastics are due to platforms which designate char as unsigned by
1033  * default. Level is the negative character -- offset by 1, because \0 is the
1034  * EOS delimiter. */
1035 #define VERBOSE_MAGIC2LEVEL(x) (((char) -*(signed char *) (x)) - 1)
1036 #define VERBOSE_HASMAGIC(x)     (*(signed char *) (x) < 0)
1037
1038 /*! \brief Print a normal log message to the channels */
1039 static void logger_print_normal(struct logmsg *logmsg)
1040 {
1041         struct logchannel *chan = NULL;
1042         char buf[BUFSIZ];
1043         struct verb *v = NULL;
1044         int level = 0;
1045
1046         if (logmsg->level == __LOG_VERBOSE) {
1047                 char *tmpmsg = ast_strdupa(logmsg->message + 1);
1048                 level = VERBOSE_MAGIC2LEVEL(logmsg->message);
1049                 /* Iterate through the list of verbosers and pass them the log message string */
1050                 AST_RWLIST_RDLOCK(&verbosers);
1051                 AST_RWLIST_TRAVERSE(&verbosers, v, list)
1052                         v->verboser(logmsg->message);
1053                 AST_RWLIST_UNLOCK(&verbosers);
1054                 ast_string_field_set(logmsg, message, tmpmsg);
1055         }
1056
1057         AST_RWLIST_RDLOCK(&logchannels);
1058
1059         if (!AST_RWLIST_EMPTY(&logchannels)) {
1060                 AST_RWLIST_TRAVERSE(&logchannels, chan, list) {
1061                         char call_identifier_str[13];
1062
1063                         if (logmsg->callid) {
1064                                 snprintf(call_identifier_str, sizeof(call_identifier_str), "[C-%08x]", logmsg->callid->call_identifier);
1065                         } else {
1066                                 call_identifier_str[0] = '\0';
1067                         }
1068
1069
1070                         /* If the channel is disabled, then move on to the next one */
1071                         if (chan->disabled) {
1072                                 continue;
1073                         }
1074                         if (logmsg->level == __LOG_VERBOSE && level > chan->verbosity) {
1075                                 continue;
1076                         }
1077
1078                         /* Check syslog channels */
1079                         if (chan->type == LOGTYPE_SYSLOG && (chan->logmask & (1 << logmsg->level))) {
1080                                 ast_log_vsyslog(logmsg);
1081                         /* Console channels */
1082                         } else if (chan->type == LOGTYPE_CONSOLE && (chan->logmask & (1 << logmsg->level))) {
1083                                 char linestr[128];
1084
1085                                 /* If the level is verbose, then skip it */
1086                                 if (logmsg->level == __LOG_VERBOSE)
1087                                         continue;
1088
1089                                 /* Turn the numerical line number into a string */
1090                                 snprintf(linestr, sizeof(linestr), "%d", logmsg->line);
1091                                 /* Build string to print out */
1092                                 snprintf(buf, sizeof(buf), "[%s] " COLORIZE_FMT "[%d]%s: " COLORIZE_FMT ":" COLORIZE_FMT " " COLORIZE_FMT ": %s",
1093                                          logmsg->date,
1094                                          COLORIZE(colors[logmsg->level], 0, logmsg->level_name),
1095                                          logmsg->lwp,
1096                                          call_identifier_str,
1097                                          COLORIZE(COLOR_BRWHITE, 0, logmsg->file),
1098                                          COLORIZE(COLOR_BRWHITE, 0, linestr),
1099                                          COLORIZE(COLOR_BRWHITE, 0, logmsg->function),
1100                                          logmsg->message);
1101                                 /* Print out */
1102                                 ast_console_puts_mutable(buf, logmsg->level);
1103                         /* File channels */
1104                         } else if (chan->type == LOGTYPE_FILE && (chan->logmask & (1 << logmsg->level))) {
1105                                 int res = 0;
1106
1107                                 /* If no file pointer exists, skip it */
1108                                 if (!chan->fileptr) {
1109                                         continue;
1110                                 }
1111
1112                                 /* Print out to the file */
1113                                 res = fprintf(chan->fileptr, "[%s] %s[%d]%s %s: %s",
1114                                               logmsg->date, logmsg->level_name, logmsg->lwp, call_identifier_str,
1115                                               logmsg->file, term_strip(buf, logmsg->message, BUFSIZ));
1116                                 if (res <= 0 && !ast_strlen_zero(logmsg->message)) {
1117                                         fprintf(stderr, "**** Asterisk Logging Error: ***********\n");
1118                                         if (errno == ENOMEM || errno == ENOSPC)
1119                                                 fprintf(stderr, "Asterisk logging error: Out of disk space, can't log to log file %s\n", chan->filename);
1120                                         else
1121                                                 fprintf(stderr, "Logger Warning: Unable to write to log file '%s': %s (disabled)\n", chan->filename, strerror(errno));
1122                                         /*** DOCUMENTATION
1123                                                 <managerEventInstance>
1124                                                         <synopsis>Raised when a logging channel is disabled.</synopsis>
1125                                                         <syntax>
1126                                                                 <parameter name="Channel">
1127                                                                         <para>The name of the logging channel.</para>
1128                                                                 </parameter>
1129                                                         </syntax>
1130                                                 </managerEventInstance>
1131                                         ***/
1132                                         manager_event(EVENT_FLAG_SYSTEM, "LogChannel", "Channel: %s\r\nEnabled: No\r\nReason: %d - %s\r\n", chan->filename, errno, strerror(errno));
1133                                         chan->disabled = 1;
1134                                 } else if (res > 0) {
1135                                         fflush(chan->fileptr);
1136                                 }
1137                         }
1138                 }
1139         } else if (logmsg->level != __LOG_VERBOSE) {
1140                 fputs(logmsg->message, stdout);
1141         }
1142
1143         AST_RWLIST_UNLOCK(&logchannels);
1144
1145         /* If we need to reload because of the file size, then do so */
1146         if (filesize_reload_needed) {
1147                 reload_logger(-1, NULL);
1148                 ast_verb(1, "Rotated Logs Per SIGXFSZ (Exceeded file size limit)\n");
1149         }
1150
1151         return;
1152 }
1153
1154 /*! \brief Actual logging thread */
1155 static void *logger_thread(void *data)
1156 {
1157         struct logmsg *next = NULL, *msg = NULL;
1158
1159         for (;;) {
1160                 /* We lock the message list, and see if any message exists... if not we wait on the condition to be signalled */
1161                 AST_LIST_LOCK(&logmsgs);
1162                 if (AST_LIST_EMPTY(&logmsgs)) {
1163                         if (close_logger_thread) {
1164                                 AST_LIST_UNLOCK(&logmsgs);
1165                                 break;
1166                         } else {
1167                                 ast_cond_wait(&logcond, &logmsgs.lock);
1168                         }
1169                 }
1170                 next = AST_LIST_FIRST(&logmsgs);
1171                 AST_LIST_HEAD_INIT_NOLOCK(&logmsgs);
1172                 AST_LIST_UNLOCK(&logmsgs);
1173
1174                 /* Otherwise go through and process each message in the order added */
1175                 while ((msg = next)) {
1176                         /* Get the next entry now so that we can free our current structure later */
1177                         next = AST_LIST_NEXT(msg, list);
1178
1179                         /* Depending on the type, send it to the proper function */
1180                         logger_print_normal(msg);
1181
1182                         /* Free the data since we are done */
1183                         logmsg_free(msg);
1184                 }
1185         }
1186
1187         return NULL;
1188 }
1189
1190 /*!
1191  * \internal
1192  * \brief Initialize the logger queue.
1193  *
1194  * \note Assumes logchannels is write locked on entry.
1195  *
1196  * \return Nothing
1197  */
1198 static void logger_queue_init(void)
1199 {
1200         ast_unload_realtime("queue_log");
1201         if (logfiles.queue_log) {
1202                 char qfname[PATH_MAX];
1203
1204                 if (logger_queue_rt_start()) {
1205                         return;
1206                 }
1207
1208                 /* Open the log file. */
1209                 snprintf(qfname, sizeof(qfname), "%s/%s", ast_config_AST_LOG_DIR,
1210                         queue_log_name);
1211                 if (qlog) {
1212                         /* Just in case it was already open. */
1213                         fclose(qlog);
1214                 }
1215                 qlog = fopen(qfname, "a");
1216                 if (!qlog) {
1217                         ast_log(LOG_ERROR, "Unable to create queue log: %s\n", strerror(errno));
1218                 }
1219         }
1220 }
1221
1222 int init_logger(void)
1223 {
1224         /* auto rotate if sig SIGXFSZ comes a-knockin */
1225         sigaction(SIGXFSZ, &handle_SIGXFSZ, NULL);
1226
1227         /* Re-initialize the logmsgs mutex.  The recursive mutex can be accessed prior
1228          * to Asterisk being forked into the background, which can cause the thread
1229          * ID tracked by the underlying pthread mutex to be different than the ID of
1230          * the thread that unlocks the mutex.  Since init_logger is called after the
1231          * fork, it is safe to initialize the mutex here for future accesses.
1232          */
1233         ast_mutex_destroy(&logmsgs.lock);
1234         ast_mutex_init(&logmsgs.lock);
1235         ast_cond_init(&logcond, NULL);
1236
1237         /* start logger thread */
1238         if (ast_pthread_create(&logthread, NULL, logger_thread, NULL) < 0) {
1239                 ast_cond_destroy(&logcond);
1240                 return -1;
1241         }
1242
1243         /* register the logger cli commands */
1244         ast_cli_register_multiple(cli_logger, ARRAY_LEN(cli_logger));
1245
1246         ast_mkdir(ast_config_AST_LOG_DIR, 0777);
1247
1248         /* create log channels */
1249         init_logger_chain(0 /* locked */, NULL);
1250         logger_initialized = 1;
1251
1252         return 0;
1253 }
1254
1255 void close_logger(void)
1256 {
1257         struct logchannel *f = NULL;
1258         struct verb *cur = NULL;
1259
1260         ast_cli_unregister_multiple(cli_logger, ARRAY_LEN(cli_logger));
1261
1262         logger_initialized = 0;
1263
1264         /* Stop logger thread */
1265         AST_LIST_LOCK(&logmsgs);
1266         close_logger_thread = 1;
1267         ast_cond_signal(&logcond);
1268         AST_LIST_UNLOCK(&logmsgs);
1269
1270         if (logthread != AST_PTHREADT_NULL)
1271                 pthread_join(logthread, NULL);
1272
1273         AST_RWLIST_WRLOCK(&verbosers);
1274         while ((cur = AST_LIST_REMOVE_HEAD(&verbosers, list))) {
1275                 ast_free(cur);
1276         }
1277         AST_RWLIST_UNLOCK(&verbosers);
1278
1279         AST_RWLIST_WRLOCK(&logchannels);
1280
1281         if (qlog) {
1282                 fclose(qlog);
1283                 qlog = NULL;
1284         }
1285
1286         while ((f = AST_LIST_REMOVE_HEAD(&logchannels, list))) {
1287                 if (f->fileptr && (f->fileptr != stdout) && (f->fileptr != stderr)) {
1288                         fclose(f->fileptr);
1289                         f->fileptr = NULL;
1290                 }
1291                 ast_free(f);
1292         }
1293
1294         closelog(); /* syslog */
1295
1296         AST_RWLIST_UNLOCK(&logchannels);
1297 }
1298
1299 void ast_callid_strnprint(char *buffer, size_t buffer_size, struct ast_callid *callid)
1300 {
1301         snprintf(buffer, buffer_size, "[C-%08x]", callid->call_identifier);
1302 }
1303
1304 struct ast_callid *ast_create_callid(void)
1305 {
1306         struct ast_callid *call;
1307
1308         call = ao2_alloc_options(sizeof(struct ast_callid), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
1309         if (!call) {
1310                 ast_log(LOG_ERROR, "Could not allocate callid struct.\n");
1311                 return NULL;
1312         }
1313
1314         call->call_identifier = ast_atomic_fetchadd_int(&next_unique_callid, +1);
1315 #ifdef TEST_FRAMEWORK
1316         ast_debug(3, "CALL_ID [C-%08x] created by thread.\n", call->call_identifier);
1317 #endif
1318         return call;
1319 }
1320
1321 struct ast_callid *ast_read_threadstorage_callid(void)
1322 {
1323         struct ast_callid **callid;
1324         callid = ast_threadstorage_get(&unique_callid, sizeof(struct ast_callid **));
1325         if (callid && *callid) {
1326                 ast_callid_ref(*callid);
1327                 return *callid;
1328         }
1329
1330         return NULL;
1331
1332 }
1333
1334 int ast_callid_threadassoc_change(struct ast_callid *callid)
1335 {
1336         struct ast_callid **id =
1337                 ast_threadstorage_get(&unique_callid, sizeof(struct ast_callid **));
1338
1339         if (!id) {
1340                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1341                 return -1;
1342         }
1343
1344         if (*id && (*id != callid)) {
1345 #ifdef TEST_FRAMEWORK
1346                 ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", (*id)->call_identifier);
1347 #endif
1348                 *id = ast_callid_unref(*id);
1349                 *id = NULL;
1350         }
1351
1352         if (!(*id) && callid) {
1353                 /* callid will be unreffed at thread destruction */
1354                 ast_callid_ref(callid);
1355                 *id = callid;
1356 #ifdef TEST_FRAMEWORK
1357                 ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", callid->call_identifier);
1358 #endif
1359         }
1360
1361         return 0;
1362 }
1363
1364 int ast_callid_threadassoc_add(struct ast_callid *callid)
1365 {
1366         struct ast_callid **pointing;
1367         pointing = ast_threadstorage_get(&unique_callid, sizeof(struct ast_callid **));
1368         if (!(pointing)) {
1369                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1370                 return -1;
1371         }
1372
1373         if (!(*pointing)) {
1374                 /* callid will be unreffed at thread destruction */
1375                 ast_callid_ref(callid);
1376                 *pointing = callid;
1377 #ifdef TEST_FRAMEWORK
1378                 ast_debug(3, "CALL_ID [C-%08x] bound to thread.\n", callid->call_identifier);
1379 #endif
1380         } else {
1381                 ast_log(LOG_WARNING, "Attempted to ast_callid_threadassoc_add on thread already associated with a callid.\n");
1382                 return 1;
1383         }
1384
1385         return 0;
1386 }
1387
1388 int ast_callid_threadassoc_remove(void)
1389 {
1390         struct ast_callid **pointing;
1391         pointing = ast_threadstorage_get(&unique_callid, sizeof(struct ast_callid **));
1392         if (!(pointing)) {
1393                 ast_log(LOG_ERROR, "Failed to allocate thread storage.\n");
1394                 return -1;
1395         }
1396
1397         if (!(*pointing)) {
1398                 ast_log(LOG_ERROR, "Tried to clean callid thread storage with no callid in thread storage.\n");
1399                 return -1;
1400         } else {
1401 #ifdef TEST_FRAMEWORK
1402                 ast_debug(3, "CALL_ID [C-%08x] being removed from thread.\n", (*pointing)->call_identifier);
1403 #endif
1404                 *pointing = ast_callid_unref(*pointing);
1405                 return 0;
1406         }
1407 }
1408
1409 int ast_callid_threadstorage_auto(struct ast_callid **callid)
1410 {
1411         struct ast_callid *tmp;
1412
1413         /* Start by trying to see if a callid is available from thread storage */
1414         tmp = ast_read_threadstorage_callid();
1415         if (tmp) {
1416                 *callid = tmp;
1417                 return 0;
1418         }
1419
1420         /* If that failed, try to create a new one and bind it. */
1421         tmp = ast_create_callid();
1422         if (tmp) {
1423                 ast_callid_threadassoc_add(tmp);
1424                 *callid = tmp;
1425                 return 1;
1426         }
1427
1428         /* If neither worked, then something must have gone wrong. */
1429         return -1;
1430 }
1431
1432 void ast_callid_threadstorage_auto_clean(struct ast_callid *callid, int callid_created)
1433 {
1434         if (callid) {
1435                 /* If the callid was created rather than simply grabbed from the thread storage, we need to unbind here. */
1436                 if (callid_created == 1) {
1437                         ast_callid_threadassoc_remove();
1438                 }
1439                 callid = ast_callid_unref(callid);
1440         }
1441 }
1442
1443 /*!
1444  * \internal
1445  * \brief thread storage cleanup function for unique_callid
1446  */
1447 static void unique_callid_cleanup(void *data)
1448 {
1449         struct ast_callid **callid = data;
1450
1451         if (*callid) {
1452                 ast_callid_unref(*callid);
1453         }
1454
1455         ast_free(data);
1456 }
1457
1458 /*!
1459  * \brief send log messages to syslog and/or the console
1460  */
1461 static void __attribute__((format(printf, 6, 0))) ast_log_full(int level, const char *file, int line, const char *function, struct ast_callid *callid, const char *fmt, va_list ap)
1462 {
1463         struct logmsg *logmsg = NULL;
1464         struct ast_str *buf = NULL;
1465         struct ast_tm tm;
1466         struct timeval now = ast_tvnow();
1467         int res = 0;
1468         char datestring[256];
1469
1470         if (!(buf = ast_str_thread_get(&log_buf, LOG_BUF_INIT_SIZE)))
1471                 return;
1472
1473         if (level != __LOG_VERBOSE && AST_RWLIST_EMPTY(&logchannels)) {
1474                 /*
1475                  * we don't have the logger chain configured yet,
1476                  * so just log to stdout
1477                  */
1478                 int result;
1479                 result = ast_str_set_va(&buf, BUFSIZ, fmt, ap); /* XXX BUFSIZ ? */
1480                 if (result != AST_DYNSTR_BUILD_FAILED) {
1481                         term_filter_escapes(ast_str_buffer(buf));
1482                         fputs(ast_str_buffer(buf), stdout);
1483                 }
1484                 return;
1485         }
1486
1487         /* Ignore anything that never gets logged anywhere */
1488         if (level != __LOG_VERBOSE && !(global_logmask & (1 << level)))
1489                 return;
1490
1491         /* Build string */
1492         res = ast_str_set_va(&buf, BUFSIZ, fmt, ap);
1493
1494         /* If the build failed, then abort and free this structure */
1495         if (res == AST_DYNSTR_BUILD_FAILED)
1496                 return;
1497
1498         /* Create a new logging message */
1499         if (!(logmsg = ast_calloc_with_stringfields(1, struct logmsg, res + 128)))
1500                 return;
1501
1502         /* Copy string over */
1503         ast_string_field_set(logmsg, message, ast_str_buffer(buf));
1504
1505         /* Set type */
1506         if (level == __LOG_VERBOSE) {
1507                 logmsg->type = LOGMSG_VERBOSE;
1508         } else {
1509                 logmsg->type = LOGMSG_NORMAL;
1510         }
1511
1512         if (display_callids && callid) {
1513                 logmsg->callid = ast_callid_ref(callid);
1514                 /* callid will be unreffed at logmsg destruction */
1515         }
1516
1517         /* Create our date/time */
1518         ast_localtime(&now, &tm, NULL);
1519         ast_strftime(datestring, sizeof(datestring), dateformat, &tm);
1520         ast_string_field_set(logmsg, date, datestring);
1521
1522         /* Copy over data */
1523         logmsg->level = level;
1524         logmsg->line = line;
1525         ast_string_field_set(logmsg, level_name, levels[level]);
1526         ast_string_field_set(logmsg, file, file);
1527         ast_string_field_set(logmsg, function, function);
1528         logmsg->lwp = ast_get_tid();
1529
1530         /* If the logger thread is active, append it to the tail end of the list - otherwise skip that step */
1531         if (logthread != AST_PTHREADT_NULL) {
1532                 AST_LIST_LOCK(&logmsgs);
1533                 if (close_logger_thread) {
1534                         /* Logger is either closing or closed.  We cannot log this message. */
1535                         logmsg_free(logmsg);
1536                 } else {
1537                         AST_LIST_INSERT_TAIL(&logmsgs, logmsg, list);
1538                         ast_cond_signal(&logcond);
1539                 }
1540                 AST_LIST_UNLOCK(&logmsgs);
1541         } else {
1542                 logger_print_normal(logmsg);
1543                 logmsg_free(logmsg);
1544         }
1545 }
1546
1547 void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
1548 {
1549         struct ast_callid *callid;
1550         va_list ap;
1551
1552         callid = ast_read_threadstorage_callid();
1553
1554         va_start(ap, fmt);
1555         ast_log_full(level, file, line, function, callid, fmt, ap);
1556         va_end(ap);
1557
1558         if (callid) {
1559                 ast_callid_unref(callid);
1560         }
1561 }
1562
1563 void ast_log_callid(int level, const char *file, int line, const char *function, struct ast_callid *callid, const char *fmt, ...)
1564 {
1565         va_list ap;
1566         va_start(ap, fmt);
1567         ast_log_full(level, file, line, function, callid, fmt, ap);
1568         va_end(ap);
1569 }
1570
1571
1572 void ast_log_backtrace(void)
1573 {
1574 #ifdef HAVE_BKTR
1575         struct ast_bt *bt;
1576         int i = 0;
1577         char **strings;
1578
1579         if (!(bt = ast_bt_create())) {
1580                 ast_log(LOG_WARNING, "Unable to allocate space for backtrace structure\n");
1581                 return;
1582         }
1583
1584         if ((strings = ast_bt_get_symbols(bt->addresses, bt->num_frames))) {
1585                 ast_debug(1, "Got %d backtrace record%c\n", bt->num_frames, bt->num_frames != 1 ? 's' : ' ');
1586                 for (i = 3; i < bt->num_frames - 2; i++) {
1587                         ast_debug(1, "#%d: [%p] %s\n", i - 3, bt->addresses[i], strings[i]);
1588                 }
1589
1590                 ast_std_free(strings);
1591         } else {
1592                 ast_debug(1, "Could not allocate memory for backtrace\n");
1593         }
1594         ast_bt_destroy(bt);
1595 #else
1596         ast_log(LOG_WARNING, "Must run configure with '--with-execinfo' for stack backtraces.\n");
1597 #endif /* defined(HAVE_BKTR) */
1598 }
1599
1600 void __ast_verbose_ap(const char *file, int line, const char *func, int level, struct ast_callid *callid, const char *fmt, va_list ap)
1601 {
1602         struct ast_str *buf = NULL;
1603         int res = 0;
1604         const char *prefix = level >= 4 ? VERBOSE_PREFIX_4 : level == 3 ? VERBOSE_PREFIX_3 : level == 2 ? VERBOSE_PREFIX_2 : level == 1 ? VERBOSE_PREFIX_1 : "";
1605         signed char magic = level > 127 ? -128 : -level - 1; /* 0 => -1, 1 => -2, etc.  Can't pass NUL, as it is EOS-delimiter */
1606
1607         /* For compatibility with modules still calling ast_verbose() directly instead of using ast_verb() */
1608         if (level < 0) {
1609                 if (!strncmp(fmt, VERBOSE_PREFIX_4, strlen(VERBOSE_PREFIX_4))) {
1610                         magic = -5;
1611                 } else if (!strncmp(fmt, VERBOSE_PREFIX_3, strlen(VERBOSE_PREFIX_3))) {
1612                         magic = -4;
1613                 } else if (!strncmp(fmt, VERBOSE_PREFIX_2, strlen(VERBOSE_PREFIX_2))) {
1614                         magic = -3;
1615                 } else if (!strncmp(fmt, VERBOSE_PREFIX_1, strlen(VERBOSE_PREFIX_1))) {
1616                         magic = -2;
1617                 } else {
1618                         magic = -1;
1619                 }
1620         }
1621
1622         if (!(buf = ast_str_thread_get(&verbose_buf, VERBOSE_BUF_INIT_SIZE))) {
1623                 return;
1624         }
1625
1626         if (ast_opt_timestamp) {
1627                 struct timeval now;
1628                 struct ast_tm tm;
1629                 char date[40];
1630                 char *datefmt;
1631
1632                 now = ast_tvnow();
1633                 ast_localtime(&now, &tm, NULL);
1634                 ast_strftime(date, sizeof(date), dateformat, &tm);
1635                 datefmt = ast_alloca(strlen(date) + 3 + strlen(prefix) + strlen(fmt) + 1);
1636                 sprintf(datefmt, "%c[%s] %s%s", (char) magic, date, prefix, fmt);
1637                 fmt = datefmt;
1638         } else {
1639                 char *tmp = ast_alloca(strlen(prefix) + strlen(fmt) + 2);
1640                 sprintf(tmp, "%c%s%s", (char) magic, prefix, fmt);
1641                 fmt = tmp;
1642         }
1643
1644         /* Build string */
1645         res = ast_str_set_va(&buf, 0, fmt, ap);
1646
1647         /* If the build failed then we can drop this allocated message */
1648         if (res == AST_DYNSTR_BUILD_FAILED) {
1649                 return;
1650         }
1651
1652         ast_log_callid(__LOG_VERBOSE, file, line, func, callid, "%s", ast_str_buffer(buf));
1653 }
1654
1655 void __ast_verbose(const char *file, int line, const char *func, int level, const char *fmt, ...)
1656 {
1657         struct ast_callid *callid;
1658         va_list ap;
1659
1660         callid = ast_read_threadstorage_callid();
1661
1662         va_start(ap, fmt);
1663         __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
1664         va_end(ap);
1665
1666         if (callid) {
1667                 ast_callid_unref(callid);
1668         }
1669 }
1670
1671 void __ast_verbose_callid(const char *file, int line, const char *func, int level, struct ast_callid *callid, const char *fmt, ...)
1672 {
1673         va_list ap;
1674         va_start(ap, fmt);
1675         __ast_verbose_ap(file, line, func, level, callid, fmt, ap);
1676         va_end(ap);
1677 }
1678
1679 /* No new code should use this directly, but we have the ABI for backwards compat */
1680 #undef ast_verbose
1681 void __attribute__((format(printf, 1,2))) ast_verbose(const char *fmt, ...);
1682 void ast_verbose(const char *fmt, ...)
1683 {
1684         struct ast_callid *callid;
1685         va_list ap;
1686
1687         callid = ast_read_threadstorage_callid();
1688
1689         va_start(ap, fmt);
1690         __ast_verbose_ap("", 0, "", 0, callid, fmt, ap);
1691         va_end(ap);
1692
1693         if (callid) {
1694                 ast_callid_unref(callid);
1695         }
1696 }
1697
1698 int ast_register_verbose(void (*v)(const char *string))
1699 {
1700         struct verb *verb;
1701
1702         if (!(verb = ast_malloc(sizeof(*verb))))
1703                 return -1;
1704
1705         verb->verboser = v;
1706
1707         AST_RWLIST_WRLOCK(&verbosers);
1708         AST_RWLIST_INSERT_HEAD(&verbosers, verb, list);
1709         AST_RWLIST_UNLOCK(&verbosers);
1710
1711         return 0;
1712 }
1713
1714 int ast_unregister_verbose(void (*v)(const char *string))
1715 {
1716         struct verb *cur;
1717
1718         AST_RWLIST_WRLOCK(&verbosers);
1719         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&verbosers, cur, list) {
1720                 if (cur->verboser == v) {
1721                         AST_RWLIST_REMOVE_CURRENT(list);
1722                         ast_free(cur);
1723                         break;
1724                 }
1725         }
1726         AST_RWLIST_TRAVERSE_SAFE_END;
1727         AST_RWLIST_UNLOCK(&verbosers);
1728
1729         return cur ? 0 : -1;
1730 }
1731
1732 static void update_logchannels(void)
1733 {
1734         struct logchannel *cur;
1735
1736         AST_RWLIST_WRLOCK(&logchannels);
1737
1738         global_logmask = 0;
1739
1740         AST_RWLIST_TRAVERSE(&logchannels, cur, list) {
1741                 cur->logmask = make_components(cur->components, cur->lineno, &cur->verbosity);
1742                 global_logmask |= cur->logmask;
1743         }
1744
1745         AST_RWLIST_UNLOCK(&logchannels);
1746 }
1747
1748 int ast_logger_register_level(const char *name)
1749 {
1750         unsigned int level;
1751         unsigned int available = 0;
1752
1753         AST_RWLIST_WRLOCK(&logchannels);
1754
1755         for (level = 0; level < ARRAY_LEN(levels); level++) {
1756                 if ((level >= 16) && !available && !levels[level]) {
1757                         available = level;
1758                         continue;
1759                 }
1760
1761                 if (levels[level] && !strcasecmp(levels[level], name)) {
1762                         ast_log(LOG_WARNING,
1763                                 "Unable to register dynamic logger level '%s': a standard logger level uses that name.\n",
1764                                 name);
1765                         AST_RWLIST_UNLOCK(&logchannels);
1766
1767                         return -1;
1768                 }
1769         }
1770
1771         if (!available) {
1772                 ast_log(LOG_WARNING,
1773                         "Unable to register dynamic logger level '%s'; maximum number of levels registered.\n",
1774                         name);
1775                 AST_RWLIST_UNLOCK(&logchannels);
1776
1777                 return -1;
1778         }
1779
1780         levels[available] = ast_strdup(name);
1781
1782         AST_RWLIST_UNLOCK(&logchannels);
1783
1784         ast_debug(1, "Registered dynamic logger level '%s' with index %d.\n", name, available);
1785
1786         update_logchannels();
1787
1788         return available;
1789 }
1790
1791 void ast_logger_unregister_level(const char *name)
1792 {
1793         unsigned int found = 0;
1794         unsigned int x;
1795
1796         AST_RWLIST_WRLOCK(&logchannels);
1797
1798         for (x = 16; x < ARRAY_LEN(levels); x++) {
1799                 if (!levels[x]) {
1800                         continue;
1801                 }
1802
1803                 if (strcasecmp(levels[x], name)) {
1804                         continue;
1805                 }
1806
1807                 found = 1;
1808                 break;
1809         }
1810
1811         if (found) {
1812                 /* take this level out of the global_logmask, to ensure that no new log messages
1813                  * will be queued for it
1814                  */
1815
1816                 global_logmask &= ~(1 << x);
1817
1818                 ast_free(levels[x]);
1819                 levels[x] = NULL;
1820                 AST_RWLIST_UNLOCK(&logchannels);
1821
1822                 ast_debug(1, "Unregistered dynamic logger level '%s' with index %d.\n", name, x);
1823
1824                 update_logchannels();
1825         } else {
1826                 AST_RWLIST_UNLOCK(&logchannels);
1827         }
1828 }
1829