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