Disallow disabling DisableDebuggerAttachment on runnning Tor
[tor.git] / src / common / log.c
blob97400623e5440afa3ad6b5d73edfd77429309a17
1 /* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file log.c
9 * \brief Functions to send messages to log files or the console.
10 **/
12 #include "orconfig.h"
13 #include <stdarg.h>
14 #include <assert.h>
15 // #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #ifdef HAVE_SYS_TIME_H
19 #include <sys/time.h>
20 #endif
21 #ifdef HAVE_TIME_H
22 #include <time.h>
23 #endif
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #ifdef HAVE_SYS_TYPES_H
28 #include <sys/types.h>
29 #endif
30 #ifdef HAVE_FCNTL_H
31 #include <fcntl.h>
32 #endif
33 #include "compat.h"
34 #include "util.h"
35 #define LOG_PRIVATE
36 #include "torlog.h"
37 #include "container.h"
39 /** @{ */
40 /** The string we stick at the end of a log message when it is too long,
41 * and its length. */
42 #define TRUNCATED_STR "[...truncated]"
43 #define TRUNCATED_STR_LEN 14
44 /** @} */
46 /** Information for a single logfile; only used in log.c */
47 typedef struct logfile_t {
48 struct logfile_t *next; /**< Next logfile_t in the linked list. */
49 char *filename; /**< Filename to open. */
50 int fd; /**< fd to receive log messages, or -1 for none. */
51 int seems_dead; /**< Boolean: true if the stream seems to be kaput. */
52 int needs_close; /**< Boolean: true if the stream gets closed on shutdown. */
53 int is_temporary; /**< Boolean: close after initializing logging subsystem.*/
54 int is_syslog; /**< Boolean: send messages to syslog. */
55 log_callback callback; /**< If not NULL, send messages to this function. */
56 log_severity_list_t *severities; /**< Which severity of messages should we
57 * log for each log domain? */
58 } logfile_t;
60 static void log_free(logfile_t *victim);
62 /** Helper: map a log severity to descriptive string. */
63 static INLINE const char *
64 sev_to_string(int severity)
66 switch (severity) {
67 case LOG_DEBUG: return "debug";
68 case LOG_INFO: return "info";
69 case LOG_NOTICE: return "notice";
70 case LOG_WARN: return "warn";
71 case LOG_ERR: return "err";
72 default: /* Call assert, not tor_assert, since tor_assert
73 * calls log on failure. */
74 assert(0); return "UNKNOWN";
78 /** Helper: decide whether to include the function name in the log message. */
79 static INLINE int
80 should_log_function_name(log_domain_mask_t domain, int severity)
82 switch (severity) {
83 case LOG_DEBUG:
84 case LOG_INFO:
85 /* All debugging messages occur in interesting places. */
86 return 1;
87 case LOG_NOTICE:
88 case LOG_WARN:
89 case LOG_ERR:
90 /* We care about places where bugs occur. */
91 return (domain == LD_BUG);
92 default:
93 /* Call assert, not tor_assert, since tor_assert calls log on failure. */
94 assert(0); return 0;
98 /** A mutex to guard changes to logfiles and logging. */
99 static tor_mutex_t log_mutex;
100 static int log_mutex_initialized = 0;
102 /** Linked list of logfile_t. */
103 static logfile_t *logfiles = NULL;
104 /** Boolean: do we report logging domains? */
105 static int log_domains_are_logged = 0;
107 #ifdef HAVE_SYSLOG_H
108 /** The number of open syslog log handlers that we have. When this reaches 0,
109 * we can close our connection to the syslog facility. */
110 static int syslog_count = 0;
111 #endif
113 /** Represents a log message that we are going to send to callback-driven
114 * loggers once we can do so in a non-reentrant way. */
115 typedef struct pending_cb_message_t {
116 int severity; /**< The severity of the message */
117 log_domain_mask_t domain; /**< The domain of the message */
118 char *msg; /**< The content of the message */
119 } pending_cb_message_t;
121 /** Log messages waiting to be replayed onto callback-based logs */
122 static smartlist_t *pending_cb_messages = NULL;
124 /** Lock the log_mutex to prevent others from changing the logfile_t list */
125 #define LOCK_LOGS() STMT_BEGIN \
126 tor_mutex_acquire(&log_mutex); \
127 STMT_END
128 /** Unlock the log_mutex */
129 #define UNLOCK_LOGS() STMT_BEGIN tor_mutex_release(&log_mutex); STMT_END
131 /** What's the lowest log level anybody cares about? Checking this lets us
132 * bail out early from log_debug if we aren't debugging. */
133 int _log_global_min_severity = LOG_NOTICE;
135 static void delete_log(logfile_t *victim);
136 static void close_log(logfile_t *victim);
138 static char *domain_to_string(log_domain_mask_t domain,
139 char *buf, size_t buflen);
141 /** Name of the application: used to generate the message we write at the
142 * start of each new log. */
143 static char *appname = NULL;
145 /** Set the "application name" for the logs to <b>name</b>: we'll use this
146 * name in the message we write when starting up, and at the start of each new
147 * log.
149 * Tor uses this string to write the version number to the log file. */
150 void
151 log_set_application_name(const char *name)
153 tor_free(appname);
154 appname = name ? tor_strdup(name) : NULL;
157 /** Log time granularity in milliseconds. */
158 static int log_time_granularity = 1;
160 /** Define log time granularity for all logs to be <b>granularity_msec</b>
161 * milliseconds. */
162 void
163 set_log_time_granularity(int granularity_msec)
165 log_time_granularity = granularity_msec;
168 /** Helper: Write the standard prefix for log lines to a
169 * <b>buf_len</b> character buffer in <b>buf</b>.
171 static INLINE size_t
172 _log_prefix(char *buf, size_t buf_len, int severity)
174 time_t t;
175 struct timeval now;
176 struct tm tm;
177 size_t n;
178 int r, ms;
180 tor_gettimeofday(&now);
181 t = (time_t)now.tv_sec;
182 ms = (int)now.tv_usec / 1000;
183 if (log_time_granularity >= 1000) {
184 t -= t % (log_time_granularity / 1000);
185 ms = 0;
186 } else {
187 ms -= ((int)now.tv_usec / 1000) % log_time_granularity;
190 n = strftime(buf, buf_len, "%b %d %H:%M:%S", tor_localtime_r(&t, &tm));
191 r = tor_snprintf(buf+n, buf_len-n, ".%.3i [%s] ", ms,
192 sev_to_string(severity));
194 if (r<0)
195 return buf_len-1;
196 else
197 return n+r;
200 /** If lf refers to an actual file that we have just opened, and the file
201 * contains no data, log an "opening new logfile" message at the top.
203 * Return -1 if the log is broken and needs to be deleted, else return 0.
205 static int
206 log_tor_version(logfile_t *lf, int reset)
208 char buf[256];
209 size_t n;
210 int is_new;
212 if (!lf->needs_close)
213 /* If it doesn't get closed, it isn't really a file. */
214 return 0;
215 if (lf->is_temporary)
216 /* If it's temporary, it isn't really a file. */
217 return 0;
219 is_new = lf->fd >= 0 && tor_fd_getpos(lf->fd) == 0;
221 if (reset && !is_new)
222 /* We are resetting, but we aren't at the start of the file; no
223 * need to log again. */
224 return 0;
225 n = _log_prefix(buf, sizeof(buf), LOG_NOTICE);
226 if (appname) {
227 tor_snprintf(buf+n, sizeof(buf)-n,
228 "%s opening %slog file.\n", appname, is_new?"new ":"");
229 } else {
230 tor_snprintf(buf+n, sizeof(buf)-n,
231 "Tor %s opening %slog file.\n", VERSION, is_new?"new ":"");
233 if (write_all(lf->fd, buf, strlen(buf), 0) < 0) /* error */
234 return -1; /* failed */
235 return 0;
238 /** Helper: Format a log message into a fixed-sized buffer. (This is
239 * factored out of <b>logv</b> so that we never format a message more
240 * than once.) Return a pointer to the first character of the message
241 * portion of the formatted string.
243 static INLINE char *
244 format_msg(char *buf, size_t buf_len,
245 log_domain_mask_t domain, int severity, const char *funcname,
246 const char *format, va_list ap, size_t *msg_len_out)
248 size_t n;
249 int r;
250 char *end_of_prefix;
251 char *buf_end;
253 assert(buf_len >= 16); /* prevent integer underflow and general stupidity */
254 buf_len -= 2; /* subtract 2 characters so we have room for \n\0 */
255 buf_end = buf+buf_len; /* point *after* the last char we can write to */
257 n = _log_prefix(buf, buf_len, severity);
258 end_of_prefix = buf+n;
260 if (log_domains_are_logged) {
261 char *cp = buf+n;
262 if (cp == buf_end) goto format_msg_no_room_for_domains;
263 *cp++ = '{';
264 if (cp == buf_end) goto format_msg_no_room_for_domains;
265 cp = domain_to_string(domain, cp, (buf+buf_len-cp));
266 if (cp == buf_end) goto format_msg_no_room_for_domains;
267 *cp++ = '}';
268 if (cp == buf_end) goto format_msg_no_room_for_domains;
269 *cp++ = ' ';
270 if (cp == buf_end) goto format_msg_no_room_for_domains;
271 end_of_prefix = cp;
272 n = cp-buf;
273 format_msg_no_room_for_domains:
274 /* This will leave end_of_prefix and n unchanged, and thus cause
275 * whatever log domain string we had written to be clobbered. */
279 if (funcname && should_log_function_name(domain, severity)) {
280 r = tor_snprintf(buf+n, buf_len-n, "%s(): ", funcname);
281 if (r<0)
282 n = strlen(buf);
283 else
284 n += r;
287 if (domain == LD_BUG && buf_len-n > 6) {
288 memcpy(buf+n, "Bug: ", 6);
289 n += 5;
292 r = tor_vsnprintf(buf+n,buf_len-n,format,ap);
293 if (r < 0) {
294 /* The message was too long; overwrite the end of the buffer with
295 * "[...truncated]" */
296 if (buf_len >= TRUNCATED_STR_LEN) {
297 size_t offset = buf_len-TRUNCATED_STR_LEN;
298 /* We have an extra 2 characters after buf_len to hold the \n\0,
299 * so it's safe to add 1 to the size here. */
300 strlcpy(buf+offset, TRUNCATED_STR, buf_len-offset+1);
302 /* Set 'n' to the end of the buffer, where we'll be writing \n\0.
303 * Since we already subtracted 2 from buf_len, this is safe.*/
304 n = buf_len;
305 } else {
306 n += r;
308 buf[n]='\n';
309 buf[n+1]='\0';
310 *msg_len_out = n+1;
311 return end_of_prefix;
314 /** Helper: sends a message to the appropriate logfiles, at loglevel
315 * <b>severity</b>. If provided, <b>funcname</b> is prepended to the
316 * message. The actual message is derived as from tor_snprintf(format,ap).
318 static void
319 logv(int severity, log_domain_mask_t domain, const char *funcname,
320 const char *format, va_list ap)
322 char buf[10024];
323 size_t msg_len = 0;
324 int formatted = 0;
325 logfile_t *lf;
326 char *end_of_prefix=NULL;
327 int callbacks_deferred = 0;
329 /* Call assert, not tor_assert, since tor_assert calls log on failure. */
330 assert(format);
331 /* check that severity is sane. Overrunning the masks array leads to
332 * interesting and hard to diagnose effects */
333 assert(severity >= LOG_ERR && severity <= LOG_DEBUG);
334 LOCK_LOGS();
336 if ((! (domain & LD_NOCB)) && smartlist_len(pending_cb_messages))
337 flush_pending_log_callbacks();
339 lf = logfiles;
340 while (lf) {
341 if (! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
342 lf = lf->next;
343 continue;
345 if (! (lf->fd >= 0 || lf->is_syslog || lf->callback)) {
346 lf = lf->next;
347 continue;
349 if (lf->seems_dead) {
350 lf = lf->next;
351 continue;
354 if (!formatted) {
355 end_of_prefix =
356 format_msg(buf, sizeof(buf), domain, severity, funcname, format, ap,
357 &msg_len);
358 formatted = 1;
361 if (lf->is_syslog) {
362 #ifdef HAVE_SYSLOG_H
363 char *m = end_of_prefix;
364 #ifdef MAXLINE
365 /* Some syslog implementations have limits on the length of what you can
366 * pass them, and some very old ones do not detect overflow so well.
367 * Regrettably, they call their maximum line length MAXLINE. */
368 #if MAXLINE < 64
369 #warn "MAXLINE is a very low number; it might not be from syslog.h after all"
370 #endif
371 if (msg_len >= MAXLINE)
372 m = tor_strndup(end_of_prefix, MAXLINE-1);
373 #endif
374 syslog(severity, "%s", m);
375 #ifdef MAXLINE
376 if (m != end_of_prefix) {
377 tor_free(m);
379 #endif
380 #endif
381 lf = lf->next;
382 continue;
383 } else if (lf->callback) {
384 if (domain & LD_NOCB) {
385 if (!callbacks_deferred && pending_cb_messages) {
386 pending_cb_message_t *msg = tor_malloc(sizeof(pending_cb_message_t));
387 msg->severity = severity;
388 msg->domain = domain;
389 msg->msg = tor_strdup(end_of_prefix);
390 smartlist_add(pending_cb_messages, msg);
392 callbacks_deferred = 1;
394 } else {
395 lf->callback(severity, domain, end_of_prefix);
397 lf = lf->next;
398 continue;
400 if (write_all(lf->fd, buf, msg_len, 0) < 0) { /* error */
401 /* don't log the error! mark this log entry to be blown away, and
402 * continue. */
403 lf->seems_dead = 1;
405 lf = lf->next;
407 UNLOCK_LOGS();
410 /** Output a message to the log. It gets logged to all logfiles that
411 * care about messages with <b>severity</b> in <b>domain</b>. The content
412 * is formatted printf-style based on <b>format</b> and extra arguments.
413 * */
414 void
415 tor_log(int severity, log_domain_mask_t domain, const char *format, ...)
417 va_list ap;
418 if (severity > _log_global_min_severity)
419 return;
420 va_start(ap,format);
421 logv(severity, domain, NULL, format, ap);
422 va_end(ap);
425 /** Output a message to the log, prefixed with a function name <b>fn</b>. */
426 #ifdef __GNUC__
427 /** GCC-based implementation of the log_fn backend, used when we have
428 * variadic macros. All arguments are as for log_fn, except for
429 * <b>fn</b>, which is the name of the calling functions. */
430 void
431 _log_fn(int severity, log_domain_mask_t domain, const char *fn,
432 const char *format, ...)
434 va_list ap;
435 if (severity > _log_global_min_severity)
436 return;
437 va_start(ap,format);
438 logv(severity, domain, fn, format, ap);
439 va_end(ap);
441 #else
442 /** @{ */
443 /** Variant implementation of log_fn, log_debug, log_info,... for C compilers
444 * without variadic macros. In this case, the calling function sets
445 * _log_fn_function_name to the name of the function, then invokes the
446 * appropriate _log_fn, _log_debug, etc. */
447 const char *_log_fn_function_name=NULL;
448 void
449 _log_fn(int severity, log_domain_mask_t domain, const char *format, ...)
451 va_list ap;
452 if (severity > _log_global_min_severity)
453 return;
454 va_start(ap,format);
455 logv(severity, domain, _log_fn_function_name, format, ap);
456 va_end(ap);
457 _log_fn_function_name = NULL;
459 void
460 _log_debug(log_domain_mask_t domain, const char *format, ...)
462 va_list ap;
463 /* For GCC we do this check in the macro. */
464 if (PREDICT_LIKELY(LOG_DEBUG > _log_global_min_severity))
465 return;
466 va_start(ap,format);
467 logv(LOG_DEBUG, domain, _log_fn_function_name, format, ap);
468 va_end(ap);
469 _log_fn_function_name = NULL;
471 void
472 _log_info(log_domain_mask_t domain, const char *format, ...)
474 va_list ap;
475 if (LOG_INFO > _log_global_min_severity)
476 return;
477 va_start(ap,format);
478 logv(LOG_INFO, domain, _log_fn_function_name, format, ap);
479 va_end(ap);
480 _log_fn_function_name = NULL;
482 void
483 _log_notice(log_domain_mask_t domain, const char *format, ...)
485 va_list ap;
486 if (LOG_NOTICE > _log_global_min_severity)
487 return;
488 va_start(ap,format);
489 logv(LOG_NOTICE, domain, _log_fn_function_name, format, ap);
490 va_end(ap);
491 _log_fn_function_name = NULL;
493 void
494 _log_warn(log_domain_mask_t domain, const char *format, ...)
496 va_list ap;
497 if (LOG_WARN > _log_global_min_severity)
498 return;
499 va_start(ap,format);
500 logv(LOG_WARN, domain, _log_fn_function_name, format, ap);
501 va_end(ap);
502 _log_fn_function_name = NULL;
504 void
505 _log_err(log_domain_mask_t domain, const char *format, ...)
507 va_list ap;
508 if (LOG_ERR > _log_global_min_severity)
509 return;
510 va_start(ap,format);
511 logv(LOG_ERR, domain, _log_fn_function_name, format, ap);
512 va_end(ap);
513 _log_fn_function_name = NULL;
515 /** @} */
516 #endif
518 /** Free all storage held by <b>victim</b>. */
519 static void
520 log_free(logfile_t *victim)
522 if (!victim)
523 return;
524 tor_free(victim->severities);
525 tor_free(victim->filename);
526 tor_free(victim);
529 /** Close all open log files, and free other static memory. */
530 void
531 logs_free_all(void)
533 logfile_t *victim, *next;
534 smartlist_t *messages;
535 LOCK_LOGS();
536 next = logfiles;
537 logfiles = NULL;
538 messages = pending_cb_messages;
539 pending_cb_messages = NULL;
540 UNLOCK_LOGS();
541 while (next) {
542 victim = next;
543 next = next->next;
544 close_log(victim);
545 log_free(victim);
547 tor_free(appname);
549 SMARTLIST_FOREACH(messages, pending_cb_message_t *, msg, {
550 tor_free(msg->msg);
551 tor_free(msg);
553 smartlist_free(messages);
555 /* We _could_ destroy the log mutex here, but that would screw up any logs
556 * that happened between here and the end of execution. */
559 /** Remove and free the log entry <b>victim</b> from the linked-list
560 * logfiles (it is probably present, but it might not be due to thread
561 * racing issues). After this function is called, the caller shouldn't
562 * refer to <b>victim</b> anymore.
564 * Long-term, we need to do something about races in the log subsystem
565 * in general. See bug 222 for more details.
567 static void
568 delete_log(logfile_t *victim)
570 logfile_t *tmpl;
571 if (victim == logfiles)
572 logfiles = victim->next;
573 else {
574 for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
575 // tor_assert(tmpl);
576 // tor_assert(tmpl->next == victim);
577 if (!tmpl)
578 return;
579 tmpl->next = victim->next;
581 log_free(victim);
584 /** Helper: release system resources (but not memory) held by a single
585 * logfile_t. */
586 static void
587 close_log(logfile_t *victim)
589 if (victim->needs_close && victim->fd >= 0) {
590 close(victim->fd);
591 victim->fd = -1;
592 } else if (victim->is_syslog) {
593 #ifdef HAVE_SYSLOG_H
594 if (--syslog_count == 0) {
595 /* There are no other syslogs; close the logging facility. */
596 closelog();
598 #endif
602 /** Adjust a log severity configuration in <b>severity_out</b> to contain
603 * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
605 void
606 set_log_severity_config(int loglevelMin, int loglevelMax,
607 log_severity_list_t *severity_out)
609 int i;
610 tor_assert(loglevelMin >= loglevelMax);
611 tor_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
612 tor_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
613 memset(severity_out, 0, sizeof(log_severity_list_t));
614 for (i = loglevelMin; i >= loglevelMax; --i) {
615 severity_out->masks[SEVERITY_MASK_IDX(i)] = ~0u;
619 /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
620 * to <b>fd</b>. Copies <b>severity</b>. Helper: does no locking. */
621 static void
622 add_stream_log_impl(const log_severity_list_t *severity,
623 const char *name, int fd)
625 logfile_t *lf;
626 lf = tor_malloc_zero(sizeof(logfile_t));
627 lf->fd = fd;
628 lf->filename = tor_strdup(name);
629 lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
630 lf->next = logfiles;
632 logfiles = lf;
633 _log_global_min_severity = get_min_log_level();
636 /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
637 * to <b>fd</b>. Steals a reference to <b>severity</b>; the caller must
638 * not use it after calling this function. */
639 void
640 add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
642 LOCK_LOGS();
643 add_stream_log_impl(severity, name, fd);
644 UNLOCK_LOGS();
647 /** Initialize the global logging facility */
648 void
649 init_logging(void)
651 if (!log_mutex_initialized) {
652 tor_mutex_init(&log_mutex);
653 log_mutex_initialized = 1;
655 if (pending_cb_messages == NULL)
656 pending_cb_messages = smartlist_create();
659 /** Set whether we report logging domains as a part of our log messages.
661 void
662 logs_set_domain_logging(int enabled)
664 LOCK_LOGS();
665 log_domains_are_logged = enabled;
666 UNLOCK_LOGS();
669 /** Add a log handler to receive messages during startup (before the real
670 * logs are initialized).
672 void
673 add_temp_log(int min_severity)
675 log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
676 set_log_severity_config(min_severity, LOG_ERR, s);
677 LOCK_LOGS();
678 add_stream_log_impl(s, "<temp>", fileno(stdout));
679 tor_free(s);
680 logfiles->is_temporary = 1;
681 UNLOCK_LOGS();
685 * Add a log handler to send messages in <b>severity</b>
686 * to the function <b>cb</b>.
689 add_callback_log(const log_severity_list_t *severity, log_callback cb)
691 logfile_t *lf;
692 lf = tor_malloc_zero(sizeof(logfile_t));
693 lf->fd = -1;
694 lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
695 lf->filename = tor_strdup("<callback>");
696 lf->callback = cb;
697 lf->next = logfiles;
699 LOCK_LOGS();
700 logfiles = lf;
701 _log_global_min_severity = get_min_log_level();
702 UNLOCK_LOGS();
703 return 0;
706 /** Adjust the configured severity of any logs whose callback function is
707 * <b>cb</b>. */
708 void
709 change_callback_log_severity(int loglevelMin, int loglevelMax,
710 log_callback cb)
712 logfile_t *lf;
713 log_severity_list_t severities;
714 set_log_severity_config(loglevelMin, loglevelMax, &severities);
715 LOCK_LOGS();
716 for (lf = logfiles; lf; lf = lf->next) {
717 if (lf->callback == cb) {
718 memcpy(lf->severities, &severities, sizeof(severities));
721 _log_global_min_severity = get_min_log_level();
722 UNLOCK_LOGS();
725 /** If there are any log messages that were generated with LD_NOCB waiting to
726 * be sent to callback-based loggers, send them now. */
727 void
728 flush_pending_log_callbacks(void)
730 logfile_t *lf;
731 smartlist_t *messages, *messages_tmp;
733 LOCK_LOGS();
734 if (0 == smartlist_len(pending_cb_messages)) {
735 UNLOCK_LOGS();
736 return;
739 messages = pending_cb_messages;
740 pending_cb_messages = smartlist_create();
741 do {
742 SMARTLIST_FOREACH_BEGIN(messages, pending_cb_message_t *, msg) {
743 const int severity = msg->severity;
744 const int domain = msg->domain;
745 for (lf = logfiles; lf; lf = lf->next) {
746 if (! lf->callback || lf->seems_dead ||
747 ! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
748 continue;
750 lf->callback(severity, domain, msg->msg);
752 tor_free(msg->msg);
753 tor_free(msg);
754 } SMARTLIST_FOREACH_END(msg);
755 smartlist_clear(messages);
757 messages_tmp = pending_cb_messages;
758 pending_cb_messages = messages;
759 messages = messages_tmp;
760 } while (smartlist_len(messages));
762 smartlist_free(messages);
764 UNLOCK_LOGS();
767 /** Close any log handlers added by add_temp_log() or marked by
768 * mark_logs_temp(). */
769 void
770 close_temp_logs(void)
772 logfile_t *lf, **p;
774 LOCK_LOGS();
775 for (p = &logfiles; *p; ) {
776 if ((*p)->is_temporary) {
777 lf = *p;
778 /* we use *p here to handle the edge case of the head of the list */
779 *p = (*p)->next;
780 close_log(lf);
781 log_free(lf);
782 } else {
783 p = &((*p)->next);
787 _log_global_min_severity = get_min_log_level();
788 UNLOCK_LOGS();
791 /** Make all currently temporary logs (set to be closed by close_temp_logs)
792 * live again, and close all non-temporary logs. */
793 void
794 rollback_log_changes(void)
796 logfile_t *lf;
797 LOCK_LOGS();
798 for (lf = logfiles; lf; lf = lf->next)
799 lf->is_temporary = ! lf->is_temporary;
800 UNLOCK_LOGS();
801 close_temp_logs();
804 /** Configure all log handles to be closed by close_temp_logs(). */
805 void
806 mark_logs_temp(void)
808 logfile_t *lf;
809 LOCK_LOGS();
810 for (lf = logfiles; lf; lf = lf->next)
811 lf->is_temporary = 1;
812 UNLOCK_LOGS();
816 * Add a log handler to send messages to <b>filename</b>. If opening the
817 * logfile fails, -1 is returned and errno is set appropriately (by open(2)).
820 add_file_log(const log_severity_list_t *severity, const char *filename)
822 int fd;
823 logfile_t *lf;
825 fd = tor_open_cloexec(filename, O_WRONLY|O_CREAT|O_APPEND, 0644);
826 if (fd<0)
827 return -1;
828 if (tor_fd_seekend(fd)<0)
829 return -1;
831 LOCK_LOGS();
832 add_stream_log_impl(severity, filename, fd);
833 logfiles->needs_close = 1;
834 lf = logfiles;
835 _log_global_min_severity = get_min_log_level();
837 if (log_tor_version(lf, 0) < 0) {
838 delete_log(lf);
840 UNLOCK_LOGS();
842 return 0;
845 #ifdef HAVE_SYSLOG_H
847 * Add a log handler to send messages to they system log facility.
850 add_syslog_log(const log_severity_list_t *severity)
852 logfile_t *lf;
853 if (syslog_count++ == 0)
854 /* This is the first syslog. */
855 openlog("Tor", LOG_PID | LOG_NDELAY, LOGFACILITY);
857 lf = tor_malloc_zero(sizeof(logfile_t));
858 lf->fd = -1;
859 lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
860 lf->filename = tor_strdup("<syslog>");
861 lf->is_syslog = 1;
863 LOCK_LOGS();
864 lf->next = logfiles;
865 logfiles = lf;
866 _log_global_min_severity = get_min_log_level();
867 UNLOCK_LOGS();
868 return 0;
870 #endif
872 /** If <b>level</b> is a valid log severity, return the corresponding
873 * numeric value. Otherwise, return -1. */
875 parse_log_level(const char *level)
877 if (!strcasecmp(level, "err"))
878 return LOG_ERR;
879 if (!strcasecmp(level, "warn"))
880 return LOG_WARN;
881 if (!strcasecmp(level, "notice"))
882 return LOG_NOTICE;
883 if (!strcasecmp(level, "info"))
884 return LOG_INFO;
885 if (!strcasecmp(level, "debug"))
886 return LOG_DEBUG;
887 return -1;
890 /** Return the string equivalent of a given log level. */
891 const char *
892 log_level_to_string(int level)
894 return sev_to_string(level);
897 /** NULL-terminated array of names for log domains such that domain_list[dom]
898 * is a description of <b>dom</b>. */
899 static const char *domain_list[] = {
900 "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
901 "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
902 "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", "HEARTBEAT", NULL
905 /** Return a bitmask for the log domain for which <b>domain</b> is the name,
906 * or 0 if there is no such name. */
907 static log_domain_mask_t
908 parse_log_domain(const char *domain)
910 int i;
911 for (i=0; domain_list[i]; ++i) {
912 if (!strcasecmp(domain, domain_list[i]))
913 return (1u<<i);
915 return 0;
918 /** Translate a bitmask of log domains to a string. */
919 static char *
920 domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
922 char *cp = buf;
923 char *eos = buf+buflen;
925 buf[0] = '\0';
926 if (! domain)
927 return buf;
928 while (1) {
929 const char *d;
930 int bit = tor_log2(domain);
931 size_t n;
932 if (bit >= N_LOGGING_DOMAINS) {
933 tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
934 return buf+strlen(buf);
936 d = domain_list[bit];
937 n = strlcpy(cp, d, eos-cp);
938 if (n >= buflen) {
939 tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
940 return buf+strlen(buf);
942 cp += n;
943 domain &= ~(1<<bit);
945 if (domain == 0 || (eos-cp) < 2)
946 return cp;
948 memcpy(cp, ",", 2); /*Nul-terminated ,"*/
949 cp++;
953 /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
954 * the end of the severityPattern. Set the value of <b>severity_out</b> to
955 * the parsed pattern. Return 0 on success, -1 on failure.
957 * The syntax for a SeverityPattern is:
958 * <pre>
959 * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
960 * DomainSeverity = (DomainList SP)? SeverityRange
961 * SeverityRange = MinSeverity ("-" MaxSeverity )?
962 * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
963 * DomainSpec = "*" | Domain | "~" Domain
964 * </pre>
965 * A missing MaxSeverity defaults to ERR. Severities and domains are
966 * case-insensitive. "~" indicates negation for a domain; negation happens
967 * last inside a DomainList. Only one SeverityRange without a DomainList is
968 * allowed per line.
971 parse_log_severity_config(const char **cfg_ptr,
972 log_severity_list_t *severity_out)
974 const char *cfg = *cfg_ptr;
975 int got_anything = 0;
976 int got_an_unqualified_range = 0;
977 memset(severity_out, 0, sizeof(*severity_out));
979 cfg = eat_whitespace(cfg);
980 while (*cfg) {
981 const char *dash, *space;
982 char *sev_lo, *sev_hi;
983 int low, high, i;
984 log_domain_mask_t domains = ~0u;
986 if (*cfg == '[') {
987 int err = 0;
988 char *domains_str;
989 smartlist_t *domains_list;
990 log_domain_mask_t neg_domains = 0;
991 const char *closebracket = strchr(cfg, ']');
992 if (!closebracket)
993 return -1;
994 domains = 0;
995 domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
996 domains_list = smartlist_create();
997 smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
998 -1);
999 tor_free(domains_str);
1000 SMARTLIST_FOREACH(domains_list, const char *, domain,
1002 if (!strcmp(domain, "*")) {
1003 domains = ~0u;
1004 } else {
1005 int d;
1006 int negate=0;
1007 if (*domain == '~') {
1008 negate = 1;
1009 ++domain;
1011 d = parse_log_domain(domain);
1012 if (!d) {
1013 log_warn(LD_CONFIG, "No such logging domain as %s", domain);
1014 err = 1;
1015 } else {
1016 if (negate)
1017 neg_domains |= d;
1018 else
1019 domains |= d;
1023 SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
1024 smartlist_free(domains_list);
1025 if (err)
1026 return -1;
1027 if (domains == 0 && neg_domains)
1028 domains = ~neg_domains;
1029 else
1030 domains &= ~neg_domains;
1031 cfg = eat_whitespace(closebracket+1);
1032 } else {
1033 ++got_an_unqualified_range;
1035 if (!strcasecmpstart(cfg, "file") ||
1036 !strcasecmpstart(cfg, "stderr") ||
1037 !strcasecmpstart(cfg, "stdout") ||
1038 !strcasecmpstart(cfg, "syslog")) {
1039 goto done;
1041 if (got_an_unqualified_range > 1)
1042 return -1;
1044 space = strchr(cfg, ' ');
1045 dash = strchr(cfg, '-');
1046 if (!space)
1047 space = strchr(cfg, '\0');
1048 if (dash && dash < space) {
1049 sev_lo = tor_strndup(cfg, dash-cfg);
1050 sev_hi = tor_strndup(dash+1, space-(dash+1));
1051 } else {
1052 sev_lo = tor_strndup(cfg, space-cfg);
1053 sev_hi = tor_strdup("ERR");
1055 low = parse_log_level(sev_lo);
1056 high = parse_log_level(sev_hi);
1057 tor_free(sev_lo);
1058 tor_free(sev_hi);
1059 if (low == -1)
1060 return -1;
1061 if (high == -1)
1062 return -1;
1064 got_anything = 1;
1065 for (i=low; i >= high; --i)
1066 severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
1068 cfg = eat_whitespace(space);
1071 done:
1072 *cfg_ptr = cfg;
1073 return got_anything ? 0 : -1;
1076 /** Return the least severe log level that any current log is interested in. */
1078 get_min_log_level(void)
1080 logfile_t *lf;
1081 int i;
1082 int min = LOG_ERR;
1083 for (lf = logfiles; lf; lf = lf->next) {
1084 for (i = LOG_DEBUG; i > min; --i)
1085 if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
1086 min = i;
1088 return min;
1091 /** Switch all logs to output at most verbose level. */
1092 void
1093 switch_logs_debug(void)
1095 logfile_t *lf;
1096 int i;
1097 LOCK_LOGS();
1098 for (lf = logfiles; lf; lf=lf->next) {
1099 for (i = LOG_DEBUG; i >= LOG_ERR; --i)
1100 lf->severities->masks[SEVERITY_MASK_IDX(i)] = ~0u;
1102 _log_global_min_severity = get_min_log_level();
1103 UNLOCK_LOGS();
1106 #if 0
1107 static void
1108 dump_log_info(logfile_t *lf)
1110 const char *tp;
1112 if (lf->filename) {
1113 printf("=== log into \"%s\" (%s-%s) (%stemporary)\n", lf->filename,
1114 sev_to_string(lf->min_loglevel),
1115 sev_to_string(lf->max_loglevel),
1116 lf->is_temporary?"":"not ");
1117 } else if (lf->is_syslog) {
1118 printf("=== syslog (%s-%s) (%stemporary)\n",
1119 sev_to_string(lf->min_loglevel),
1120 sev_to_string(lf->max_loglevel),
1121 lf->is_temporary?"":"not ");
1122 } else {
1123 printf("=== log (%s-%s) (%stemporary)\n",
1124 sev_to_string(lf->min_loglevel),
1125 sev_to_string(lf->max_loglevel),
1126 lf->is_temporary?"":"not ");
1130 void
1131 describe_logs(void)
1133 logfile_t *lf;
1134 printf("==== BEGIN LOGS ====\n");
1135 for (lf = logfiles; lf; lf = lf->next)
1136 dump_log_info(lf);
1137 printf("==== END LOGS ====\n");
1139 #endif