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