Tor  0.4.4.0-alpha-dev
log.c
Go to the documentation of this file.
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-2020, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
7 /**
8  * \file log.c
9  * \brief Functions to send messages to log files or the console.
10  **/
11 
12 #include "orconfig.h"
13 #include <stdarg.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #ifdef HAVE_SYS_TIME_H
18 #include <sys/time.h>
19 #endif
20 #ifdef HAVE_TIME_H
21 #include <time.h>
22 #endif
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26 #ifdef HAVE_SYS_TYPES_H
27 #include <sys/types.h>
28 #endif
29 #ifdef HAVE_FCNTL_H
30 #include <fcntl.h>
31 #endif
32 
33 #define LOG_PRIVATE
34 #include "lib/log/log.h"
35 #include "lib/log/log_sys.h"
37 #include "lib/log/ratelim.h"
38 #include "lib/lock/compat_mutex.h"
42 #include "lib/err/torerr.h"
43 #include "lib/intmath/bits.h"
45 #include "lib/string/printf.h"
46 #include "lib/malloc/malloc.h"
47 #include "lib/string/util_string.h"
51 #include "lib/fdio/fdio.h"
52 #include "lib/cc/ctassert.h"
53 
54 #ifdef HAVE_ANDROID_LOG_H
55 #include <android/log.h>
56 #endif // HAVE_ANDROID_LOG_H.
57 
58 /** @{ */
59 /** The string we stick at the end of a log message when it is too long,
60  * and its length. */
61 #define TRUNCATED_STR "[...truncated]"
62 #define TRUNCATED_STR_LEN 14
63 /** @} */
64 
65 /** Defining compile-time constants for Tor log levels (used by the Rust
66  * log wrapper at src/rust/tor_log) */
67 const int LOG_WARN_ = LOG_WARN;
68 const int LOG_NOTICE_ = LOG_NOTICE;
69 const log_domain_mask_t LD_GENERAL_ = LD_GENERAL;
70 const log_domain_mask_t LD_NET_ = LD_NET;
71 
72 /** Information for a single logfile; only used in log.c */
73 typedef struct logfile_t {
74  struct logfile_t *next; /**< Next logfile_t in the linked list. */
75  char *filename; /**< Filename to open. */
76  int fd; /**< fd to receive log messages, or -1 for none. */
77  int seems_dead; /**< Boolean: true if the stream seems to be kaput. */
78  int needs_close; /**< Boolean: true if the stream gets closed on shutdown. */
79  int is_temporary; /**< Boolean: close after initializing logging subsystem.*/
80  int is_syslog; /**< Boolean: send messages to syslog. */
81  int is_android; /**< Boolean: send messages to Android's log subsystem. */
82  char *android_tag; /**< Identity Tag used in Android's log subsystem. */
83  log_callback callback; /**< If not NULL, send messages to this function. */
84  log_severity_list_t *severities; /**< Which severity of messages should we
85  * log for each log domain? */
86 } logfile_t;
87 
88 static void log_free_(logfile_t *victim);
89 #define log_free(lg) \
90  FREE_AND_NULL(logfile_t, log_free_, (lg))
91 
92 /** Helper: map a log severity to descriptive string. */
93 static inline const char *
94 sev_to_string(int severity)
95 {
96  switch (severity) {
97  case LOG_DEBUG: return "debug";
98  case LOG_INFO: return "info";
99  case LOG_NOTICE: return "notice";
100  case LOG_WARN: return "warn";
101  case LOG_ERR: return "err";
102  default: /* Call raw_assert, not tor_assert, since tor_assert
103  * calls log on failure. */
104  raw_assert_unreached(); return "UNKNOWN"; // LCOV_EXCL_LINE
105  }
106 }
107 
108 /** Helper: decide whether to include the function name in the log message. */
109 static inline int
111 {
112  switch (severity) {
113  case LOG_DEBUG:
114  case LOG_INFO:
115  /* All debugging messages occur in interesting places. */
116  return (domain & LD_NOFUNCNAME) == 0;
117  case LOG_NOTICE:
118  case LOG_WARN:
119  case LOG_ERR:
120  /* We care about places where bugs occur. */
121  return (domain & (LD_BUG|LD_NOFUNCNAME)) == LD_BUG;
122  default:
123  /* Call raw_assert, not tor_assert, since tor_assert calls
124  * log on failure. */
125  raw_assert(0); return 0; // LCOV_EXCL_LINE
126  }
127 }
128 
129 #ifdef HAVE_ANDROID_LOG_H
130 /** Helper function to convert Tor's log severity into the matching
131  * Android log priority.
132  */
133 static int
134 severity_to_android_log_priority(int severity)
135 {
136  switch (severity) {
137  case LOG_DEBUG:
138  return ANDROID_LOG_VERBOSE;
139  case LOG_INFO:
140  return ANDROID_LOG_DEBUG;
141  case LOG_NOTICE:
142  return ANDROID_LOG_INFO;
143  case LOG_WARN:
144  return ANDROID_LOG_WARN;
145  case LOG_ERR:
146  return ANDROID_LOG_ERROR;
147  default:
148  // LCOV_EXCL_START
149  raw_assert(0);
150  return 0;
151  // LCOV_EXCL_STOP
152  }
153 }
154 #endif /* defined(HAVE_ANDROID_LOG_H) */
155 
156 /** A mutex to guard changes to logfiles and logging. */
158 /** True iff we have initialized log_mutex */
159 static int log_mutex_initialized = 0;
160 
161 /** Linked list of logfile_t. */
162 static logfile_t *logfiles = NULL;
163 /** Boolean: do we report logging domains? */
164 static int log_domains_are_logged = 0;
165 
166 #ifdef HAVE_SYSLOG_H
167 /** The number of open syslog log handlers that we have. When this reaches 0,
168  * we can close our connection to the syslog facility. */
169 static int syslog_count = 0;
170 #endif
171 
172 /** Represents a log message that we are going to send to callback-driven
173  * loggers once we can do so in a non-reentrant way. */
174 typedef struct pending_log_message_t {
175  int severity; /**< The severity of the message */
176  log_domain_mask_t domain; /**< The domain of the message */
177  char *fullmsg; /**< The message, with all decorations */
178  char *msg; /**< The content of the message */
180 
181 /** Log messages waiting to be replayed onto callback-based logs */
183 
184 /** Callback to invoke when pending_cb_messages becomes nonempty. */
185 static pending_callback_callback pending_cb_cb = NULL;
186 
187 /** Log messages waiting to be replayed once the logging system is initialized.
188  */
190 
191 /** Number of bytes of messages queued in pending_startup_messages. (This is
192  * the length of the messages, not the number of bytes used to store
193  * them.) */
195 
196 /** True iff we should store messages while waiting for the logs to get
197  * configured. */
198 static int queue_startup_messages = 1;
199 
200 /** True iff __PRETTY_FUNCTION__ includes parenthesized arguments. */
201 static int pretty_fn_has_parens = 0;
202 
203 /** Don't store more than this many bytes of messages while waiting for the
204  * logs to get configured. */
205 #define MAX_STARTUP_MSG_LEN (1<<16)
206 
207 /** Lock the log_mutex to prevent others from changing the logfile_t list */
208 #define LOCK_LOGS() STMT_BEGIN \
209  raw_assert(log_mutex_initialized); \
210  tor_mutex_acquire(&log_mutex); \
211  STMT_END
212 /** Unlock the log_mutex */
213 #define UNLOCK_LOGS() STMT_BEGIN \
214  raw_assert(log_mutex_initialized); \
215  tor_mutex_release(&log_mutex); \
216  STMT_END
217 
218 /** What's the lowest log level anybody cares about? Checking this lets us
219  * bail out early from log_debug if we aren't debugging. */
221 
222 static void delete_log(logfile_t *victim);
223 static void close_log(logfile_t *victim);
224 static void close_log_sigsafe(logfile_t *victim);
225 
226 static char *domain_to_string(log_domain_mask_t domain,
227  char *buf, size_t buflen);
228 static inline char *format_msg(char *buf, size_t buf_len,
229  log_domain_mask_t domain, int severity, const char *funcname,
230  const char *suffix,
231  const char *format, va_list ap, size_t *msg_len_out)
232  CHECK_PRINTF(7,0);
233 
234 /** Name of the application: used to generate the message we write at the
235  * start of each new log. */
236 static char *appname = NULL;
237 
238 /** Set the "application name" for the logs to <b>name</b>: we'll use this
239  * name in the message we write when starting up, and at the start of each new
240  * log.
241  *
242  * Tor uses this string to write the version number to the log file. */
243 void
245 {
246  tor_free(appname);
247  appname = name ? tor_strdup(name) : NULL;
248 }
249 
250 /** Return true if some of the running logs might be interested in a log
251  * message of the given severity in the given domains. If this function
252  * returns true, the log message might be ignored anyway, but if it returns
253  * false, it is definitely_ safe not to log the message. */
254 int
256 {
257  (void) domain;
258  return (severity <= log_global_min_severity_);
259 }
260 
261 /**
262  * As tor_log, but takes an optional function name, and does not treat its
263  * <b>string</b> as a printf format.
264  *
265  * For use by Rust integration.
266  */
267 void
268 tor_log_string(int severity, log_domain_mask_t domain,
269  const char *function, const char *string)
270 {
271  log_fn_(severity, domain, function, "%s", string);
272 }
273 
274 /** Log time granularity in milliseconds. */
275 static int log_time_granularity = 1;
276 
277 /** Define log time granularity for all logs to be <b>granularity_msec</b>
278  * milliseconds. */
279 MOCK_IMPL(void,
280 set_log_time_granularity,(int granularity_msec))
281 {
282  log_time_granularity = granularity_msec;
283  tor_log_sigsafe_err_set_granularity(granularity_msec);
284 }
285 
286 /** Helper: Write the standard prefix for log lines to a
287  * <b>buf_len</b> character buffer in <b>buf</b>.
288  */
289 static inline size_t
290 log_prefix_(char *buf, size_t buf_len, int severity)
291 {
292  time_t t;
293  struct timeval now;
294  struct tm tm;
295  size_t n;
296  int r, ms;
297 
298  tor_gettimeofday(&now);
299  t = (time_t)now.tv_sec;
300  ms = (int)now.tv_usec / 1000;
301  if (log_time_granularity >= 1000) {
302  t -= t % (log_time_granularity / 1000);
303  ms = 0;
304  } else {
305  ms -= ((int)now.tv_usec / 1000) % log_time_granularity;
306  }
307 
308  n = strftime(buf, buf_len, "%b %d %H:%M:%S",
309  tor_localtime_r_msg(&t, &tm, NULL));
310  r = tor_snprintf(buf+n, buf_len-n, ".%.3i [%s] ", ms,
311  sev_to_string(severity));
312 
313  if (r<0)
314  return buf_len-1;
315  else
316  return n+r;
317 }
318 
319 /** If lf refers to an actual file that we have just opened, and the file
320  * contains no data, log an "opening new logfile" message at the top.
321  *
322  * Return -1 if the log is broken and needs to be deleted, else return 0.
323  */
324 static int
325 log_tor_version(logfile_t *lf, int reset)
326 {
327  char buf[256];
328  size_t n;
329  int is_new;
330 
331  if (!lf->needs_close)
332  /* If it doesn't get closed, it isn't really a file. */
333  return 0;
334  if (lf->is_temporary)
335  /* If it's temporary, it isn't really a file. */
336  return 0;
337 
338  is_new = lf->fd >= 0 && tor_fd_getpos(lf->fd) == 0;
339 
340  if (reset && !is_new)
341  /* We are resetting, but we aren't at the start of the file; no
342  * need to log again. */
343  return 0;
344  n = log_prefix_(buf, sizeof(buf), LOG_NOTICE);
345  if (appname) {
346  tor_snprintf(buf+n, sizeof(buf)-n,
347  "%s opening %slog file.\n", appname, is_new?"new ":"");
348  } else {
349  tor_snprintf(buf+n, sizeof(buf)-n,
350  "Tor %s opening %slog file.\n", VERSION, is_new?"new ":"");
351  }
352  if (write_all_to_fd_minimal(lf->fd, buf, strlen(buf)) < 0) /* error */
353  return -1; /* failed */
354  return 0;
355 }
356 
357 /** Helper: Format a log message into a fixed-sized buffer. (This is
358  * factored out of <b>logv</b> so that we never format a message more
359  * than once.) Return a pointer to the first character of the message
360  * portion of the formatted string.
361  */
362 static inline char *
363 format_msg(char *buf, size_t buf_len,
364  log_domain_mask_t domain, int severity, const char *funcname,
365  const char *suffix,
366  const char *format, va_list ap, size_t *msg_len_out)
367 {
368  size_t n;
369  int r;
370  char *end_of_prefix;
371  char *buf_end;
372 
373  raw_assert(buf_len >= 16); /* prevent integer underflow and stupidity */
374  buf_len -= 2; /* subtract 2 characters so we have room for \n\0 */
375  buf_end = buf+buf_len; /* point *after* the last char we can write to */
376 
377  n = log_prefix_(buf, buf_len, severity);
378  end_of_prefix = buf+n;
379 
381  char *cp = buf+n;
382  if (cp == buf_end) goto format_msg_no_room_for_domains;
383  *cp++ = '{';
384  if (cp == buf_end) goto format_msg_no_room_for_domains;
385  cp = domain_to_string(domain, cp, (buf+buf_len-cp));
386  if (cp == buf_end) goto format_msg_no_room_for_domains;
387  *cp++ = '}';
388  if (cp == buf_end) goto format_msg_no_room_for_domains;
389  *cp++ = ' ';
390  if (cp == buf_end) goto format_msg_no_room_for_domains;
391  end_of_prefix = cp;
392  n = cp-buf;
393  format_msg_no_room_for_domains:
394  /* This will leave end_of_prefix and n unchanged, and thus cause
395  * whatever log domain string we had written to be clobbered. */
396  ;
397  }
398 
399  if (funcname && should_log_function_name(domain, severity)) {
400  r = tor_snprintf(buf+n, buf_len-n,
401  pretty_fn_has_parens ? "%s: " : "%s(): ",
402  funcname);
403  if (r<0)
404  n = strlen(buf);
405  else
406  n += r;
407  }
408 
409  if (domain == LD_BUG && buf_len-n > 6) {
410  memcpy(buf+n, "Bug: ", 6);
411  n += 5;
412  }
413 
414  r = tor_vsnprintf(buf+n,buf_len-n,format,ap);
415  if (r < 0) {
416  /* The message was too long; overwrite the end of the buffer with
417  * "[...truncated]" */
418  if (buf_len >= TRUNCATED_STR_LEN) {
419  size_t offset = buf_len-TRUNCATED_STR_LEN;
420  /* We have an extra 2 characters after buf_len to hold the \n\0,
421  * so it's safe to add 1 to the size here. */
422  strlcpy(buf+offset, TRUNCATED_STR, buf_len-offset+1);
423  }
424  /* Set 'n' to the end of the buffer, where we'll be writing \n\0.
425  * Since we already subtracted 2 from buf_len, this is safe.*/
426  n = buf_len;
427  } else {
428  n += r;
429  if (suffix) {
430  size_t suffix_len = strlen(suffix);
431  if (buf_len-n >= suffix_len) {
432  memcpy(buf+n, suffix, suffix_len);
433  n += suffix_len;
434  }
435  }
436  }
437 
438  if (domain == LD_BUG &&
439  buf_len - n > strlen(tor_bug_suffix)+1) {
440  memcpy(buf+n, tor_bug_suffix, strlen(tor_bug_suffix));
441  n += strlen(tor_bug_suffix);
442  }
443 
444  buf[n]='\n';
445  buf[n+1]='\0';
446  *msg_len_out = n+1;
447  return end_of_prefix;
448 }
449 
450 /* Create a new pending_log_message_t with appropriate values */
451 static pending_log_message_t *
452 pending_log_message_new(int severity, log_domain_mask_t domain,
453  const char *fullmsg, const char *shortmsg)
454 {
455  pending_log_message_t *m = tor_malloc(sizeof(pending_log_message_t));
456  m->severity = severity;
457  m->domain = domain;
458  m->fullmsg = fullmsg ? tor_strdup(fullmsg) : NULL;
459  m->msg = tor_strdup(shortmsg);
460  return m;
461 }
462 
463 #define pending_log_message_free(msg) \
464  FREE_AND_NULL(pending_log_message_t, pending_log_message_free_, (msg))
465 
466 /** Release all storage held by <b>msg</b>. */
467 static void
469 {
470  if (!msg)
471  return;
472  tor_free(msg->msg);
473  tor_free(msg->fullmsg);
474  tor_free(msg);
475 }
476 
477 /** Helper function: returns true iff the log file, given in <b>lf</b>, is
478  * handled externally via the system log API, the Android logging API, or is an
479  * external callback function. */
480 static inline int
482 {
483  raw_assert(lf);
484  return lf->is_syslog || lf->is_android || lf->callback;
485 }
486 
487 /** Return true iff <b>lf</b> would like to receive a message with the
488  * specified <b>severity</b> in the specified <b>domain</b>.
489  */
490 static inline int
491 logfile_wants_message(const logfile_t *lf, int severity,
492  log_domain_mask_t domain)
493 {
494  if (! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
495  return 0;
496  }
497  if (! (lf->fd >= 0 || logfile_is_external(lf))) {
498  return 0;
499  }
500  if (lf->seems_dead) {
501  return 0;
502  }
503 
504  return 1;
505 }
506 
507 /** Send a message to <b>lf</b>. The full message, with time prefix and
508  * severity, is in <b>buf</b>. The message itself is in
509  * <b>msg_after_prefix</b>. If <b>callbacks_deferred</b> points to true, then
510  * we already deferred this message for pending callbacks and don't need to do
511  * it again. Otherwise, if we need to do it, do it, and set
512  * <b>callbacks_deferred</b> to 1. */
513 static inline void
514 logfile_deliver(logfile_t *lf, const char *buf, size_t msg_len,
515  const char *msg_after_prefix, log_domain_mask_t domain,
516  int severity, int *callbacks_deferred)
517 {
518 
519  if (lf->is_syslog) {
520 #ifdef HAVE_SYSLOG_H
521 #ifdef MAXLINE
522  /* Some syslog implementations have limits on the length of what you can
523  * pass them, and some very old ones do not detect overflow so well.
524  * Regrettably, they call their maximum line length MAXLINE. */
525 #if MAXLINE < 64
526 #warning "MAXLINE is very low; it might not be from syslog.h."
527 #endif
528  char *m = msg_after_prefix;
529  if (msg_len >= MAXLINE)
530  m = tor_strndup(msg_after_prefix, MAXLINE-1);
531  syslog(severity, "%s", m);
532  if (m != msg_after_prefix) {
533  tor_free(m);
534  }
535 #else /* !defined(MAXLINE) */
536  /* We have syslog but not MAXLINE. That's promising! */
537  syslog(severity, "%s", msg_after_prefix);
538 #endif /* defined(MAXLINE) */
539 #endif /* defined(HAVE_SYSLOG_H) */
540  } else if (lf->is_android) {
541 #ifdef HAVE_ANDROID_LOG_H
542  int priority = severity_to_android_log_priority(severity);
543  __android_log_write(priority, lf->android_tag, msg_after_prefix);
544 #endif // HAVE_ANDROID_LOG_H.
545  } else if (lf->callback) {
546  if (domain & LD_NOCB) {
547  if (!*callbacks_deferred && pending_cb_messages) {
549  pending_log_message_new(severity,domain,NULL,msg_after_prefix));
550  *callbacks_deferred = 1;
551  if (smartlist_len(pending_cb_messages) == 1 && pending_cb_cb) {
552  pending_cb_cb();
553  }
554  }
555  } else {
556  lf->callback(severity, domain, msg_after_prefix);
557  }
558  } else {
559  if (write_all_to_fd_minimal(lf->fd, buf, msg_len) < 0) { /* error */
560  /* don't log the error! mark this log entry to be blown away, and
561  * continue. */
562  lf->seems_dead = 1;
563  }
564  }
565 }
566 
567 /** Helper: sends a message to the appropriate logfiles, at loglevel
568  * <b>severity</b>. If provided, <b>funcname</b> is prepended to the
569  * message. The actual message is derived as from tor_snprintf(format,ap).
570  */
571 MOCK_IMPL(STATIC void,
572 logv,(int severity, log_domain_mask_t domain, const char *funcname,
573  const char *suffix, const char *format, va_list ap))
574 {
575  char buf[10240];
576  size_t msg_len = 0;
577  int formatted = 0;
578  logfile_t *lf;
579  char *end_of_prefix=NULL;
580  int callbacks_deferred = 0;
581 
582  /* Call raw_assert, not tor_assert, since tor_assert calls log on failure. */
583  raw_assert(format);
584  /* check that severity is sane. Overrunning the masks array leads to
585  * interesting and hard to diagnose effects */
586  raw_assert(severity >= LOG_ERR && severity <= LOG_DEBUG);
587 
588  LOCK_LOGS();
589 
590  if ((! (domain & LD_NOCB)) && pending_cb_messages
591  && smartlist_len(pending_cb_messages))
593 
596  end_of_prefix =
597  format_msg(buf, sizeof(buf), domain, severity, funcname, suffix,
598  format, ap, &msg_len);
599  formatted = 1;
600 
602  pending_log_message_new(severity,domain,buf,end_of_prefix));
603  pending_startup_messages_len += msg_len;
604  }
605 
606  for (lf = logfiles; lf; lf = lf->next) {
607  if (! logfile_wants_message(lf, severity, domain))
608  continue;
609 
610  if (!formatted) {
611  end_of_prefix =
612  format_msg(buf, sizeof(buf), domain, severity, funcname, suffix,
613  format, ap, &msg_len);
614  formatted = 1;
615  }
616 
617  logfile_deliver(lf, buf, msg_len, end_of_prefix, domain, severity,
618  &callbacks_deferred);
619  }
620  UNLOCK_LOGS();
621 }
622 
623 /** Output a message to the log. It gets logged to all logfiles that
624  * care about messages with <b>severity</b> in <b>domain</b>. The content
625  * is formatted printf-style based on <b>format</b> and extra arguments.
626  * */
627 void
628 tor_log(int severity, log_domain_mask_t domain, const char *format, ...)
629 {
630  va_list ap;
631 
632  /* check that domain is composed of known domains and flags */
633  raw_assert((domain & (LD_ALL_DOMAINS|LD_ALL_FLAGS)) == domain);
634 
635  if (severity > log_global_min_severity_)
636  return;
637  va_start(ap,format);
638 #ifdef TOR_UNIT_TESTS
639  if (domain & LD_NO_MOCK)
640  logv__real(severity, domain, NULL, NULL, format, ap);
641  else
642 #endif
643  logv(severity, domain, NULL, NULL, format, ap);
644  va_end(ap);
645 }
646 
647 /** Helper function; return true iff the <b>n</b>-element array <b>array</b>
648  * contains <b>item</b>. */
649 static int
650 int_array_contains(const int *array, int n, int item)
651 {
652  int j;
653  for (j = 0; j < n; ++j) {
654  if (array[j] == item)
655  return 1;
656  }
657  return 0;
658 }
659 
660 /** Function to call whenever the list of logs changes to get ready to log
661  * from signal handlers. */
662 void
664 {
665  const logfile_t *lf;
666  int found_real_stderr = 0;
667 
668  /* The fds are the file descriptors of tor's stdout, stderr, and file
669  * logs. The log and err modules flush these fds during their shutdowns. */
670  int fds[TOR_SIGSAFE_LOG_MAX_FDS];
671  int n_fds;
672 
673  LOCK_LOGS();
674  /* Reserve the first one for stderr. This is safe because when we daemonize,
675  * we dup2 /dev/null to stderr. */
676  fds[0] = STDERR_FILENO;
677  n_fds = 1;
678 
679  for (lf = logfiles; lf; lf = lf->next) {
680  /* Don't try callback to the control port, syslogs, android logs, or any
681  * other non-file descriptor log: We can't call arbitrary functions from a
682  * signal handler.
683  */
684  if (lf->is_temporary || logfile_is_external(lf)
685  || lf->seems_dead || lf->fd < 0)
686  continue;
687  if (lf->severities->masks[SEVERITY_MASK_IDX(LOG_ERR)] &
688  (LD_BUG|LD_GENERAL)) {
689  if (lf->fd == STDERR_FILENO)
690  found_real_stderr = 1;
691  /* Avoid duplicates by checking the log module fd against fds */
692  if (int_array_contains(fds, n_fds, lf->fd))
693  continue;
694  /* Update fds using the log module's fd */
695  fds[n_fds] = lf->fd;
696  n_fds++;
697  if (n_fds == TOR_SIGSAFE_LOG_MAX_FDS)
698  break;
699  }
700  }
701 
702  if (!found_real_stderr &&
703  int_array_contains(fds, n_fds, STDOUT_FILENO)) {
704  /* Don't use a virtual stderr when we're also logging to stdout.
705  * If we reached max_fds logs, we'll now have (max_fds - 1) logs.
706  * That's ok, max_fds is large enough that most tor instances don't exceed
707  * it. */
708  raw_assert(n_fds >= 2); /* Don't tor_assert inside log fns */
709  --n_fds;
710  fds[0] = fds[n_fds];
711  }
712 
713  UNLOCK_LOGS();
714 
715  tor_log_set_sigsafe_err_fds(fds, n_fds);
716 }
717 
718 /** Add to <b>out</b> a copy of every currently configured log file name. Used
719  * to enable access to these filenames with the sandbox code. */
720 void
722 {
723  logfile_t *lf;
724  raw_assert(out);
725 
726  LOCK_LOGS();
727 
728  for (lf = logfiles; lf; lf = lf->next) {
729  if (lf->is_temporary || logfile_is_external(lf))
730  continue;
731  if (lf->filename == NULL)
732  continue;
733  smartlist_add_strdup(out, lf->filename);
734  }
735 
736  UNLOCK_LOGS();
737 }
738 
739 /** Implementation of the log_fn backend, used when we have
740  * variadic macros. All arguments are as for log_fn, except for
741  * <b>fn</b>, which is the name of the calling function. */
742 void
743 log_fn_(int severity, log_domain_mask_t domain, const char *fn,
744  const char *format, ...)
745 {
746  va_list ap;
747  if (severity > log_global_min_severity_)
748  return;
749  va_start(ap,format);
750  logv(severity, domain, fn, NULL, format, ap);
751  va_end(ap);
752 }
753 void
754 log_fn_ratelim_(ratelim_t *ratelim, int severity, log_domain_mask_t domain,
755  const char *fn, const char *format, ...)
756 {
757  va_list ap;
758  char *m;
759  if (severity > log_global_min_severity_)
760  return;
761  m = rate_limit_log(ratelim, approx_time());
762  if (m == NULL)
763  return;
764  va_start(ap, format);
765  logv(severity, domain, fn, m, format, ap);
766  va_end(ap);
767  tor_free(m);
768 }
769 
770 /** Free all storage held by <b>victim</b>. */
771 static void
773 {
774  if (!victim)
775  return;
776  tor_free(victim->severities);
777  tor_free(victim->filename);
778  tor_free(victim->android_tag);
779  tor_free(victim);
780 }
781 
782 /** Close all open log files, and free other static memory. */
783 void
785 {
786  logfile_t *victim, *next;
787  smartlist_t *messages, *messages2;
788  LOCK_LOGS();
789  next = logfiles;
790  logfiles = NULL;
791  messages = pending_cb_messages;
792  pending_cb_messages = NULL;
793  pending_cb_cb = NULL;
794  messages2 = pending_startup_messages;
796  UNLOCK_LOGS();
797  while (next) {
798  victim = next;
799  next = next->next;
800  close_log(victim);
801  log_free(victim);
802  }
803  tor_free(appname);
804 
805  SMARTLIST_FOREACH(messages, pending_log_message_t *, msg, {
806  pending_log_message_free(msg);
807  });
808  smartlist_free(messages);
809 
810  if (messages2) {
811  SMARTLIST_FOREACH(messages2, pending_log_message_t *, msg, {
812  pending_log_message_free(msg);
813  });
814  smartlist_free(messages2);
815  }
816 
817  /* We _could_ destroy the log mutex here, but that would screw up any logs
818  * that happened between here and the end of execution.
819  * If tor is re-initialized, log_mutex_initialized will still be 1. So we
820  * won't trigger any undefined behaviour by trying to re-initialize the
821  * log mutex. */
822 }
823 
824 /** Flush the signal-safe log files.
825  *
826  * This function is safe to call from a signal handler. It is currenly called
827  * by the BUG() macros, when terminating the process on an abnormal condition.
828  */
829 void
831 {
832  /* If we don't have fsync() in unistd.h, we can't flush the logs. */
833 #ifdef HAVE_FSYNC
834  logfile_t *victim, *next;
835  /* We can't LOCK_LOGS() in a signal handler, because it may call
836  * signal-unsafe functions. And we can't deallocate memory, either. */
837  next = logfiles;
838  logfiles = NULL;
839  while (next) {
840  victim = next;
841  next = next->next;
842  if (victim->needs_close) {
843  /* We can't do anything useful if the flush fails. */
844  (void)fsync(victim->fd);
845  }
846  }
847 #endif /* defined(HAVE_FSYNC) */
848 }
849 
850 /** Remove and free the log entry <b>victim</b> from the linked-list
851  * logfiles (it is probably present, but it might not be due to thread
852  * racing issues). After this function is called, the caller shouldn't
853  * refer to <b>victim</b> anymore.
854  */
855 static void
857 {
858  logfile_t *tmpl;
859  if (victim == logfiles)
860  logfiles = victim->next;
861  else {
862  for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
863 // raw_assert(tmpl);
864 // raw_assert(tmpl->next == victim);
865  if (!tmpl)
866  return;
867  tmpl->next = victim->next;
868  }
869  log_free(victim);
870 }
871 
872 /** Helper: release system resources (but not memory) held by a single
873  * signal-safe logfile_t. If the log's resources can not be released in
874  * a signal handler, does nothing. */
875 static void
877 {
878  if (victim->needs_close && victim->fd >= 0) {
879  /* We can't do anything useful here if close() fails: we're shutting
880  * down logging, and the err module only does fatal errors. */
881  close(victim->fd);
882  victim->fd = -1;
883  }
884 }
885 
886 /** Helper: release system resources (but not memory) held by a single
887  * logfile_t. */
888 static void
890 {
891  if (victim->needs_close) {
892  close_log_sigsafe(victim);
893  } else if (victim->is_syslog) {
894 #ifdef HAVE_SYSLOG_H
895  if (--syslog_count == 0) {
896  /* There are no other syslogs; close the logging facility. */
897  closelog();
898  }
899 #endif /* defined(HAVE_SYSLOG_H) */
900  }
901 }
902 
903 /** Adjust a log severity configuration in <b>severity_out</b> to contain
904  * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
905  */
906 void
907 set_log_severity_config(int loglevelMin, int loglevelMax,
908  log_severity_list_t *severity_out)
909 {
910  int i;
911  raw_assert(loglevelMin >= loglevelMax);
912  raw_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
913  raw_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
914  memset(severity_out, 0, sizeof(log_severity_list_t));
915  for (i = loglevelMin; i >= loglevelMax; --i) {
916  severity_out->masks[SEVERITY_MASK_IDX(i)] = LD_ALL_DOMAINS;
917  }
918 }
919 
920 /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
921  * to <b>fd</b>. Copies <b>severity</b>. Helper: does no locking. */
922 MOCK_IMPL(STATIC void,
924  const char *name, int fd))
925 {
926  logfile_t *lf;
927  lf = tor_malloc_zero(sizeof(logfile_t));
928  lf->fd = fd;
929  lf->filename = tor_strdup(name);
930  lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
931  lf->next = logfiles;
932 
933  logfiles = lf;
935 }
936 
937 /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
938  * to <b>fd</b>. Steals a reference to <b>severity</b>; the caller must
939  * not use it after calling this function. */
940 void
941 add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
942 {
943  LOCK_LOGS();
944  add_stream_log_impl(severity, name, fd);
945  UNLOCK_LOGS();
946 }
947 
948 /** Initialize the global logging facility */
949 void
950 init_logging(int disable_startup_queue)
951 {
952  if (!log_mutex_initialized) {
955  }
956 #ifdef __GNUC__
957  if (strchr(__PRETTY_FUNCTION__, '(')) {
959  }
960 #endif
961  if (pending_cb_messages == NULL)
963  if (disable_startup_queue)
967  }
968 }
969 
970 /** Set whether we report logging domains as a part of our log messages.
971  */
972 void
974 {
975  LOCK_LOGS();
976  log_domains_are_logged = enabled;
977  UNLOCK_LOGS();
978 }
979 
980 /** Add a log handler to accept messages when no other log is configured.
981  */
982 void
983 add_default_log(int min_severity)
984 {
985  log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
986  set_log_severity_config(min_severity, LOG_ERR, s);
987  LOCK_LOGS();
988  add_stream_log_impl(s, "<default>", fileno(stdout));
989  tor_free(s);
990  UNLOCK_LOGS();
991 }
992 
993 /**
994  * Register "cb" as the callback to call when there are new pending log
995  * callbacks to be flushed with flush_pending_log_callbacks().
996  *
997  * Note that this callback, if present, can be invoked from any thread.
998  *
999  * This callback must not log.
1000  *
1001  * It is intentional that this function contains the name "callback" twice: it
1002  * sets a "callback" to be called on the condition that there is a "pending
1003  * callback".
1004  **/
1005 void
1006 logs_set_pending_callback_callback(pending_callback_callback cb)
1007 {
1008  pending_cb_cb = cb;
1009 }
1010 
1011 /**
1012  * Add a log handler to send messages in <b>severity</b>
1013  * to the function <b>cb</b>.
1014  */
1015 int
1017 {
1018  logfile_t *lf;
1019  lf = tor_malloc_zero(sizeof(logfile_t));
1020  lf->fd = -1;
1021  lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
1022  lf->filename = tor_strdup("<callback>");
1023  lf->callback = cb;
1024  lf->next = logfiles;
1025 
1026  LOCK_LOGS();
1027  logfiles = lf;
1029  UNLOCK_LOGS();
1030  return 0;
1031 }
1032 
1033 /** Adjust the configured severity of any logs whose callback function is
1034  * <b>cb</b>. */
1035 void
1036 change_callback_log_severity(int loglevelMin, int loglevelMax,
1037  log_callback cb)
1038 {
1039  logfile_t *lf;
1040  log_severity_list_t severities;
1041  set_log_severity_config(loglevelMin, loglevelMax, &severities);
1042  LOCK_LOGS();
1043  for (lf = logfiles; lf; lf = lf->next) {
1044  if (lf->callback == cb) {
1045  memcpy(lf->severities, &severities, sizeof(severities));
1046  }
1047  }
1049  UNLOCK_LOGS();
1050 }
1051 
1052 /** If there are any log messages that were generated with LD_NOCB waiting to
1053  * be sent to callback-based loggers, send them now. */
1054 void
1056 {
1057  logfile_t *lf;
1058  smartlist_t *messages, *messages_tmp;
1059 
1060  LOCK_LOGS();
1061  if (!pending_cb_messages || 0 == smartlist_len(pending_cb_messages)) {
1062  UNLOCK_LOGS();
1063  return;
1064  }
1065 
1066  messages = pending_cb_messages;
1068  do {
1070  const int severity = msg->severity;
1071  const log_domain_mask_t domain = msg->domain;
1072  for (lf = logfiles; lf; lf = lf->next) {
1073  if (! lf->callback || lf->seems_dead ||
1074  ! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
1075  continue;
1076  }
1077  lf->callback(severity, domain, msg->msg);
1078  }
1079  pending_log_message_free(msg);
1080  } SMARTLIST_FOREACH_END(msg);
1081  smartlist_clear(messages);
1082 
1083  messages_tmp = pending_cb_messages;
1084  pending_cb_messages = messages;
1085  messages = messages_tmp;
1086  } while (smartlist_len(messages));
1087 
1088  smartlist_free(messages);
1089 
1090  UNLOCK_LOGS();
1091 }
1092 
1093 /** Flush all the messages we stored from startup while waiting for log
1094  * initialization.
1095  */
1096 void
1098 {
1099  logfile_t *lf;
1100 
1101  LOCK_LOGS();
1105  goto out;
1106 
1108  msg) {
1109  int callbacks_deferred = 0;
1110  for (lf = logfiles; lf; lf = lf->next) {
1111  if (! logfile_wants_message(lf, msg->severity, msg->domain))
1112  continue;
1113 
1114  /* We configure a temporary startup log that goes to stdout, so we
1115  * shouldn't replay to stdout/stderr*/
1116  if (lf->fd == STDOUT_FILENO || lf->fd == STDERR_FILENO) {
1117  continue;
1118  }
1119 
1120  logfile_deliver(lf, msg->fullmsg, strlen(msg->fullmsg), msg->msg,
1121  msg->domain, msg->severity, &callbacks_deferred);
1122  }
1123  pending_log_message_free(msg);
1124  } SMARTLIST_FOREACH_END(msg);
1125  smartlist_free(pending_startup_messages);
1126  pending_startup_messages = NULL;
1127 
1128  out:
1129  UNLOCK_LOGS();
1130 }
1131 
1132 /** Close any log handlers marked by mark_logs_temp(). */
1133 void
1135 {
1136  logfile_t *lf, **p;
1137 
1138  LOCK_LOGS();
1139  for (p = &logfiles; *p; ) {
1140  if ((*p)->is_temporary) {
1141  lf = *p;
1142  /* we use *p here to handle the edge case of the head of the list */
1143  *p = (*p)->next;
1144  close_log(lf);
1145  log_free(lf);
1146  } else {
1147  p = &((*p)->next);
1148  }
1149  }
1150 
1152  UNLOCK_LOGS();
1153 }
1154 
1155 /** Make all currently temporary logs (set to be closed by close_temp_logs)
1156  * live again, and close all non-temporary logs. */
1157 void
1159 {
1160  logfile_t *lf;
1161  LOCK_LOGS();
1162  for (lf = logfiles; lf; lf = lf->next)
1163  lf->is_temporary = ! lf->is_temporary;
1164  UNLOCK_LOGS();
1165  close_temp_logs();
1166 }
1167 
1168 /** Configure all log handles to be closed by close_temp_logs(). */
1169 void
1171 {
1172  logfile_t *lf;
1173  LOCK_LOGS();
1174  for (lf = logfiles; lf; lf = lf->next)
1175  lf->is_temporary = 1;
1176  UNLOCK_LOGS();
1177 }
1178 
1179 /**
1180  * Add a log handler to send messages to <b>filename</b> via <b>fd</b>. If
1181  * opening the logfile failed, -1 is returned and errno is set appropriately
1182  * (by open(2)). Takes ownership of fd.
1183  */
1184 MOCK_IMPL(int,
1185 add_file_log,(const log_severity_list_t *severity,
1186  const char *filename,
1187  int fd))
1188 {
1189  logfile_t *lf;
1190 
1191  if (fd<0)
1192  return -1;
1193  if (tor_fd_seekend(fd)<0) {
1194  close(fd);
1195  return -1;
1196  }
1197 
1198  LOCK_LOGS();
1199  add_stream_log_impl(severity, filename, fd);
1200  logfiles->needs_close = 1;
1201  lf = logfiles;
1203 
1204  if (log_tor_version(lf, 0) < 0) {
1205  delete_log(lf);
1206  }
1207  UNLOCK_LOGS();
1208 
1209  return 0;
1210 }
1211 
1212 #ifdef HAVE_SYSLOG_H
1213 /**
1214  * Add a log handler to send messages to they system log facility.
1215  *
1216  * If this is the first log handler, opens syslog with ident Tor or
1217  * Tor-<syslog_identity_tag> if that is not NULL.
1218  */
1219 int
1220 add_syslog_log(const log_severity_list_t *severity,
1221  const char* syslog_identity_tag)
1222 {
1223  logfile_t *lf;
1224  if (syslog_count++ == 0) {
1225  /* This is the first syslog. */
1226  static char buf[256];
1227  if (syslog_identity_tag) {
1228  tor_snprintf(buf, sizeof(buf), "Tor-%s", syslog_identity_tag);
1229  } else {
1230  tor_snprintf(buf, sizeof(buf), "Tor");
1231  }
1232  openlog(buf, LOG_PID | LOG_NDELAY, LOGFACILITY);
1233  }
1234 
1235  lf = tor_malloc_zero(sizeof(logfile_t));
1236  lf->fd = -1;
1237  lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
1238  lf->filename = tor_strdup("<syslog>");
1239  lf->is_syslog = 1;
1240 
1241  LOCK_LOGS();
1242  lf->next = logfiles;
1243  logfiles = lf;
1245  UNLOCK_LOGS();
1246  return 0;
1247 }
1248 #endif /* defined(HAVE_SYSLOG_H) */
1249 
1250 #ifdef HAVE_ANDROID_LOG_H
1251 /**
1252  * Add a log handler to send messages to the Android platform log facility.
1253  */
1254 int
1255 add_android_log(const log_severity_list_t *severity,
1256  const char *android_tag)
1257 {
1258  logfile_t *lf = NULL;
1259 
1260  lf = tor_malloc_zero(sizeof(logfile_t));
1261  lf->fd = -1;
1262  lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
1263  lf->filename = tor_strdup("<android>");
1264  lf->is_android = 1;
1265 
1266  if (android_tag == NULL)
1267  lf->android_tag = tor_strdup("Tor");
1268  else {
1269  char buf[256];
1270  tor_snprintf(buf, sizeof(buf), "Tor-%s", android_tag);
1271  lf->android_tag = tor_strdup(buf);
1272  }
1273 
1274  LOCK_LOGS();
1275  lf->next = logfiles;
1276  logfiles = lf;
1278  UNLOCK_LOGS();
1279  return 0;
1280 }
1281 #endif /* defined(HAVE_ANDROID_LOG_H) */
1282 
1283 /** If <b>level</b> is a valid log severity, return the corresponding
1284  * numeric value. Otherwise, return -1. */
1285 int
1286 parse_log_level(const char *level)
1287 {
1288  if (!strcasecmp(level, "err"))
1289  return LOG_ERR;
1290  if (!strcasecmp(level, "warn"))
1291  return LOG_WARN;
1292  if (!strcasecmp(level, "notice"))
1293  return LOG_NOTICE;
1294  if (!strcasecmp(level, "info"))
1295  return LOG_INFO;
1296  if (!strcasecmp(level, "debug"))
1297  return LOG_DEBUG;
1298  return -1;
1299 }
1300 
1301 /** Return the string equivalent of a given log level. */
1302 const char *
1304 {
1305  return sev_to_string(level);
1306 }
1307 
1308 /** NULL-terminated array of names for log domains such that domain_list[dom]
1309  * is a description of <b>dom</b>.
1310  *
1311  * Remember to update doc/tor.1.txt if you modify this list.
1312  * */
1313 static const char *domain_list[] = {
1314  "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
1315  "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
1316  "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", "HEARTBEAT", "CHANNEL",
1317  "SCHED", "GUARD", "CONSDIFF", "DOS", "PROCESS", "PT", "BTRACK", "MESG",
1318  NULL
1319 };
1320 
1322 
1326 
1327 /** Return a bitmask for the log domain for which <b>domain</b> is the name,
1328  * or 0 if there is no such name. */
1329 static log_domain_mask_t
1330 parse_log_domain(const char *domain)
1331 {
1332  int i;
1333  for (i=0; domain_list[i]; ++i) {
1334  if (!strcasecmp(domain, domain_list[i]))
1335  return (UINT64_C(1)<<i);
1336  }
1337  return 0;
1338 }
1339 
1340 /** Translate a bitmask of log domains to a string. */
1341 static char *
1342 domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
1343 {
1344  char *cp = buf;
1345  char *eos = buf+buflen;
1346 
1347  buf[0] = '\0';
1348  if (! domain)
1349  return buf;
1350  while (1) {
1351  const char *d;
1352  int bit = tor_log2(domain);
1353  size_t n;
1354  if ((unsigned)bit >= ARRAY_LENGTH(domain_list)-1 ||
1355  bit >= N_LOGGING_DOMAINS) {
1356  tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
1357  return buf+strlen(buf);
1358  }
1359  d = domain_list[bit];
1360  n = strlcpy(cp, d, eos-cp);
1361  if (n >= buflen) {
1362  tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
1363  return buf+strlen(buf);
1364  }
1365  cp += n;
1366  domain &= ~(1<<bit);
1367 
1368  if (domain == 0 || (eos-cp) < 2)
1369  return cp;
1370 
1371  memcpy(cp, ",", 2); /*Nul-terminated ,"*/
1372  cp++;
1373  }
1374 }
1375 
1376 /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
1377  * the end of the severityPattern. Set the value of <b>severity_out</b> to
1378  * the parsed pattern. Return 0 on success, -1 on failure.
1379  *
1380  * The syntax for a SeverityPattern is:
1381  * <pre>
1382  * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
1383  * DomainSeverity = (DomainList SP)? SeverityRange
1384  * SeverityRange = MinSeverity ("-" MaxSeverity )?
1385  * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
1386  * DomainSpec = "*" | Domain | "~" Domain
1387  * </pre>
1388  * A missing MaxSeverity defaults to ERR. Severities and domains are
1389  * case-insensitive. "~" indicates negation for a domain; negation happens
1390  * last inside a DomainList. Only one SeverityRange without a DomainList is
1391  * allowed per line.
1392  */
1393 int
1394 parse_log_severity_config(const char **cfg_ptr,
1395  log_severity_list_t *severity_out)
1396 {
1397  const char *cfg = *cfg_ptr;
1398  int got_anything = 0;
1399  int got_an_unqualified_range = 0;
1400  memset(severity_out, 0, sizeof(*severity_out));
1401 
1402  cfg = eat_whitespace(cfg);
1403  while (*cfg) {
1404  const char *dash, *space;
1405  char *sev_lo, *sev_hi;
1406  int low, high, i;
1408 
1409  if (*cfg == '[') {
1410  int err = 0;
1411  char *domains_str;
1412  smartlist_t *domains_list;
1413  log_domain_mask_t neg_domains = 0;
1414  const char *closebracket = strchr(cfg, ']');
1415  if (!closebracket)
1416  return -1;
1417  domains = 0;
1418  domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
1419  domains_list = smartlist_new();
1420  smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
1421  -1);
1422  tor_free(domains_str);
1423  SMARTLIST_FOREACH_BEGIN(domains_list, const char *, domain) {
1424  if (!strcmp(domain, "*")) {
1425  domains = LD_ALL_DOMAINS;
1426  } else {
1428  int negate=0;
1429  if (*domain == '~') {
1430  negate = 1;
1431  ++domain;
1432  }
1433  d = parse_log_domain(domain);
1434  if (!d) {
1435  log_warn(LD_CONFIG, "No such logging domain as %s", domain);
1436  err = 1;
1437  } else {
1438  if (negate)
1439  neg_domains |= d;
1440  else
1441  domains |= d;
1442  }
1443  }
1444  } SMARTLIST_FOREACH_END(domain);
1445  SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
1446  smartlist_free(domains_list);
1447  if (err)
1448  return -1;
1449  if (domains == 0 && neg_domains)
1450  domains = ~neg_domains;
1451  else
1452  domains &= ~neg_domains;
1453  cfg = eat_whitespace(closebracket+1);
1454  } else {
1455  ++got_an_unqualified_range;
1456  }
1457  if (!strcasecmpstart(cfg, "file") ||
1458  !strcasecmpstart(cfg, "stderr") ||
1459  !strcasecmpstart(cfg, "stdout") ||
1460  !strcasecmpstart(cfg, "syslog") ||
1461  !strcasecmpstart(cfg, "android")) {
1462  goto done;
1463  }
1464  if (got_an_unqualified_range > 1)
1465  return -1;
1466 
1467  space = find_whitespace(cfg);
1468  dash = strchr(cfg, '-');
1469  if (dash && dash < space) {
1470  sev_lo = tor_strndup(cfg, dash-cfg);
1471  sev_hi = tor_strndup(dash+1, space-(dash+1));
1472  } else {
1473  sev_lo = tor_strndup(cfg, space-cfg);
1474  sev_hi = tor_strdup("ERR");
1475  }
1476  low = parse_log_level(sev_lo);
1477  high = parse_log_level(sev_hi);
1478  tor_free(sev_lo);
1479  tor_free(sev_hi);
1480  if (low == -1)
1481  return -1;
1482  if (high == -1)
1483  return -1;
1484 
1485  got_anything = 1;
1486  for (i=low; i >= high; --i)
1487  severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
1488 
1489  cfg = eat_whitespace(space);
1490  }
1491 
1492  done:
1493  *cfg_ptr = cfg;
1494  return got_anything ? 0 : -1;
1495 }
1496 
1497 /** Return the least severe log level that any current log is interested in. */
1498 int
1500 {
1501  logfile_t *lf;
1502  int i;
1503  int min = LOG_ERR;
1504  for (lf = logfiles; lf; lf = lf->next) {
1505  for (i = LOG_DEBUG; i > min; --i)
1506  if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
1507  min = i;
1508  }
1509  return min;
1510 }
1511 
1512 /** Switch all logs to output at most verbose level. */
1513 void
1515 {
1516  logfile_t *lf;
1517  int i;
1518  LOCK_LOGS();
1519  for (lf = logfiles; lf; lf=lf->next) {
1520  for (i = LOG_DEBUG; i >= LOG_ERR; --i)
1521  lf->severities->masks[SEVERITY_MASK_IDX(i)] = LD_ALL_DOMAINS;
1522  }
1524  UNLOCK_LOGS();
1525 }
1526 
1527 /** Truncate all the log files. */
1528 void
1530 {
1531  logfile_t *lf;
1532  for (lf = logfiles; lf; lf = lf->next) {
1533  if (lf->fd >= 0) {
1534  tor_ftruncate(lf->fd);
1535  }
1536  }
1537 }
add_stream_log
void add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
Definition: log.c:941
init_logging
void init_logging(int disable_startup_queue)
Definition: log.c:950
tor_free
#define tor_free(p)
Definition: malloc.h:52
pending_log_message_t::domain
log_domain_mask_t domain
Definition: log.c:176
log_global_min_severity_
int log_global_min_severity_
Definition: log.c:220
LOG_DEBUG
#define LOG_DEBUG
Definition: log.h:42
logs_free_all
void logs_free_all(void)
Definition: log.c:784
smartlist_split_string
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
Definition: smartlist_split.c:37
set_log_severity_config
void set_log_severity_config(int loglevelMin, int loglevelMax, log_severity_list_t *severity_out)
Definition: log.c:907
name
const char * name
Definition: config.c:2440
N_LOGGING_DOMAINS
#define N_LOGGING_DOMAINS
Definition: log.h:124
HIGHEST_RESERVED_LD_DOMAIN_
#define HIGHEST_RESERVED_LD_DOMAIN_
Definition: log.h:126
pending_log_message_t::severity
int severity
Definition: log.c:175
smartlist_add_strdup
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
Definition: smartlist_core.c:137
approx_time
time_t approx_time(void)
Definition: approx_time.c:32
LOG_NOTICE
#define LOG_NOTICE
Definition: log.h:50
LOG_WARN_
const int LOG_WARN_
Definition: log.c:67
MOCK_IMPL
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
logfile_t::fd
int fd
Definition: log.c:76
LD_BUG
#define LD_BUG
Definition: log.h:86
compat_string.h
Header for compat_string.c.
set_log_time_granularity
void set_log_time_granularity(int granularity_msec)
Definition: log.c:280
close_log_sigsafe
static void close_log_sigsafe(logfile_t *victim)
Definition: log.c:876
LD_GENERAL
#define LD_GENERAL
Definition: log.h:62
sev_to_string
static const char * sev_to_string(int severity)
Definition: log.c:94
flush_pending_log_callbacks
void flush_pending_log_callbacks(void)
Definition: log.c:1055
mark_logs_temp
void mark_logs_temp(void)
Definition: log.c:1170
smartlist_add
void smartlist_add(smartlist_t *sl, void *element)
Definition: smartlist_core.c:117
logs_flush_sigsafe
void logs_flush_sigsafe(void)
Definition: log.c:830
tor_ftruncate
int tor_ftruncate(int fd)
Definition: fdio.c:92
close_log
static void close_log(logfile_t *victim)
Definition: log.c:889
log_callback
void(* log_callback)(int severity, log_domain_mask_t domain, const char *msg)
Definition: log.h:158
domain_list
static const char * domain_list[]
Definition: log.c:1313
ratelim.h
Summarize similar messages that would otherwise flood the logs.
smartlist_new
smartlist_t * smartlist_new(void)
Definition: smartlist_core.c:26
logfile_t::severities
log_severity_list_t * severities
Definition: log.c:84
tor_snprintf
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
approx_time.h
Header for approx_time.c.
parse_log_domain
static log_domain_mask_t parse_log_domain(const char *domain)
Definition: log.c:1330
rollback_log_changes
void rollback_log_changes(void)
Definition: log.c:1158
truncate_logs
void truncate_logs(void)
Definition: log.c:1529
SMARTLIST_FOREACH
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: smartlist_foreach.h:112
pretty_fn_has_parens
static int pretty_fn_has_parens
Definition: log.c:201
pending_log_message_t::fullmsg
char * fullmsg
Definition: log.c:177
pending_log_message_t
Definition: log.c:174
int_array_contains
static int int_array_contains(const int *array, int n, int item)
Definition: log.c:650
pending_startup_messages
static smartlist_t * pending_startup_messages
Definition: log.c:189
bits.h
Header for bits.c.
appname
static char * appname
Definition: log.c:236
add_stream_log_impl
STATIC void add_stream_log_impl(const log_severity_list_t *severity, const char *name, int fd)
Definition: log.c:924
smartlist_split.h
Header for smartlist_split.c.
log_sys.h
Declare subsystem object for the logging module.
write_all_to_fd_minimal
int write_all_to_fd_minimal(int fd, const char *buf, size_t count)
Definition: fdio.c:108
tor_bug_suffix
const char tor_bug_suffix[]
Definition: git_revision.c:32
get_min_log_level
int get_min_log_level(void)
Definition: log.c:1499
rate_limit_log
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:41
time_to_tm.h
Header for time_to_tm.c.
log_time_granularity
static int log_time_granularity
Definition: log.c:275
tor_mutex_t
Definition: compat_mutex.h:40
close_temp_logs
void close_temp_logs(void)
Definition: log.c:1134
log_fn_
void log_fn_(int severity, log_domain_mask_t domain, const char *fn, const char *format,...)
Definition: log.c:743
tor_log_update_sigsafe_err_fds
void tor_log_update_sigsafe_err_fds(void)
Definition: log.c:663
log_message_is_interesting
int log_message_is_interesting(int severity, log_domain_mask_t domain)
Definition: log.c:255
log_severity_list_t::masks
log_domain_mask_t masks[LOG_DEBUG-LOG_ERR+1]
Definition: log.h:154
logfile_is_external
static int logfile_is_external(const logfile_t *lf)
Definition: log.c:481
parse_log_level
int parse_log_level(const char *level)
Definition: log.c:1286
printf.h
Header for printf.c.
logfile_t::next
struct logfile_t * next
Definition: log.c:74
log_mutex_initialized
static int log_mutex_initialized
Definition: log.c:159
tor_log2
int tor_log2(uint64_t u64)
Definition: bits.c:16
parse_log_severity_config
int parse_log_severity_config(const char **cfg_ptr, log_severity_list_t *severity_out)
Definition: log.c:1394
logfiles
static logfile_t * logfiles
Definition: log.c:162
UNLOCK_LOGS
#define UNLOCK_LOGS()
Definition: log.c:213
LD_NOCB
#define LD_NOCB
Definition: log.h:144
logv
STATIC void logv(int severity, log_domain_mask_t domain, const char *funcname, const char *suffix, const char *format, va_list ap)
Definition: log.c:573
tor_log_string
void tor_log_string(int severity, log_domain_mask_t domain, const char *function, const char *string)
Definition: log.c:268
log_mutex
static tor_mutex_t log_mutex
Definition: log.c:157
time.h
Definitions for timing-related constants.
log_domain_mask_t
uint64_t log_domain_mask_t
Definition: logging_types.h:21
format_msg
static char * format_msg(char *buf, size_t buf_len, log_domain_mask_t domain, int severity, const char *funcname, const char *suffix, const char *format, va_list ap, size_t *msg_len_out)
Definition: log.c:363
pending_cb_cb
static pending_callback_callback pending_cb_cb
Definition: log.c:185
logfile_t
Definition: log.c:73
ctassert.h
Compile-time assertions: CTASSERT(expression).
tor_gettimeofday
void tor_gettimeofday(struct timeval *timeval)
Definition: tor_gettimeofday.c:42
LD_CONFIG
#define LD_CONFIG
Definition: log.h:68
should_log_function_name
static int should_log_function_name(log_domain_mask_t domain, int severity)
Definition: log.c:110
CTASSERT
#define CTASSERT(x)
Definition: ctassert.h:44
malloc.h
Headers for util_malloc.c.
tor_vsnprintf
int tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
Definition: printf.c:41
ARRAY_LENGTH
#define ARRAY_LENGTH(x)
Definition: compat_compiler.h:222
log_domains_are_logged
static int log_domains_are_logged
Definition: log.c:164
LOG_INFO
#define LOG_INFO
Definition: log.h:45
log_set_application_name
void log_set_application_name(const char *name)
Definition: log.c:244
log_prefix_
static size_t log_prefix_(char *buf, size_t buf_len, int severity)
Definition: log.c:290
git_revision.h
Header for git_revision.c.
log_tor_version
static int log_tor_version(logfile_t *lf, int reset)
Definition: log.c:325
domain_to_string
static char * domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
Definition: log.c:1342
smartlist_clear
void smartlist_clear(smartlist_t *sl)
Definition: smartlist_core.c:50
flush_log_messages_from_startup
void flush_log_messages_from_startup(void)
Definition: log.c:1097
LD_NOFUNCNAME
#define LD_NOFUNCNAME
Definition: log.h:147
logfile_t::needs_close
int needs_close
Definition: log.c:78
LD_ALL_DOMAINS
#define LD_ALL_DOMAINS
Definition: log.h:128
compat_mutex.h
Header for compat_mutex.c.
log.h
Headers for log.c.
pending_log_message_t::msg
char * msg
Definition: log.c:178
MAX_STARTUP_MSG_LEN
#define MAX_STARTUP_MSG_LEN
Definition: log.c:205
pending_cb_messages
static smartlist_t * pending_cb_messages
Definition: log.c:182
TOR_SIGSAFE_LOG_MAX_FDS
#define TOR_SIGSAFE_LOG_MAX_FDS
Definition: torerr.h:37
timeval
Definition: compat_time.h:151
tor_mutex_init
void tor_mutex_init(tor_mutex_t *m)
Definition: compat_mutex_pthreads.c:41
LOWEST_RESERVED_LD_FLAG_
#define LOWEST_RESERVED_LD_FLAG_
Definition: log.h:133
SMARTLIST_FOREACH_BEGIN
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Definition: smartlist_foreach.h:78
pending_log_message_free_
static void pending_log_message_free_(pending_log_message_t *msg)
Definition: log.c:468
fdio.h
Header for fdio.c.
logfile_wants_message
static int logfile_wants_message(const logfile_t *lf, int severity, log_domain_mask_t domain)
Definition: log.c:491
tor_fd_seekend
int tor_fd_seekend(int fd)
Definition: fdio.c:61
LD_ALL_FLAGS
#define LD_ALL_FLAGS
Definition: log.h:135
TRUNCATED_STR
#define TRUNCATED_STR
Definition: log.c:61
change_callback_log_severity
void change_callback_log_severity(int loglevelMin, int loglevelMax, log_callback cb)
Definition: log.c:1036
LOG_WARN
#define LOG_WARN
Definition: log.h:53
logfile_deliver
static void logfile_deliver(logfile_t *lf, const char *buf, size_t msg_len, const char *msg_after_prefix, log_domain_mask_t domain, int severity, int *callbacks_deferred)
Definition: log.c:514
logfile_t::is_syslog
int is_syslog
Definition: log.c:80
logs_set_domain_logging
void logs_set_domain_logging(int enabled)
Definition: log.c:973
LOG_ERR
#define LOG_ERR
Definition: log.h:56
log_free_
static void log_free_(logfile_t *victim)
Definition: log.c:772
logfile_t::is_android
int is_android
Definition: log.c:81
tor_log_sigsafe_err_set_granularity
void tor_log_sigsafe_err_set_granularity(int ms)
Definition: torerr.c:182
logfile_t::filename
char * filename
Definition: log.c:75
smartlist_foreach.h
Macros for iterating over the elements of a smartlist_t.
delete_log
static void delete_log(logfile_t *victim)
Definition: log.c:856
smartlist_core.h
Top-level declarations for the smartlist_t dynamic array type.
log_level_to_string
const char * log_level_to_string(int level)
Definition: log.c:1303
LD_NET
#define LD_NET
Definition: log.h:66
log_severity_list_t
Definition: log.h:151
tor_log
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:628
logfile_t::seems_dead
int seems_dead
Definition: log.c:77
add_default_log
void add_default_log(int min_severity)
Definition: log.c:983
logfile_t::is_temporary
int is_temporary
Definition: log.c:79
tor_localtime_r_msg
struct tm * tor_localtime_r_msg(const time_t *timep, struct tm *result, char **err_out)
Definition: time_to_tm.c:133
STATIC
#define STATIC
Definition: testsupport.h:32
add_callback_log
int add_callback_log(const log_severity_list_t *severity, log_callback cb)
Definition: log.c:1016
logfile_t::callback
log_callback callback
Definition: log.c:83
logfile_t::android_tag
char * android_tag
Definition: log.c:82
torerr.h
Headers for torerr.c.
switch_logs_debug
void switch_logs_debug(void)
Definition: log.c:1514
LOCK_LOGS
#define LOCK_LOGS()
Definition: log.c:208
smartlist_t
Definition: smartlist_core.h:26
logs_set_pending_callback_callback
void logs_set_pending_callback_callback(pending_callback_callback cb)
Definition: log.c:1006
queue_startup_messages
static int queue_startup_messages
Definition: log.c:198
pending_startup_messages_len
static size_t pending_startup_messages_len
Definition: log.c:194
tor_log_set_sigsafe_err_fds
void tor_log_set_sigsafe_err_fds(const int *fds, int n)
Definition: torerr.c:123
util_string.h
Header for util_string.c.
eat_whitespace
const char * eat_whitespace(const char *s)
Definition: util_string.c:268
strcasecmpstart
int strcasecmpstart(const char *s1, const char *s2)
Definition: util_string.c:216
ratelim_t
Definition: ratelim.h:42
find_whitespace
const char * find_whitespace(const char *s)
Definition: util_string.c:344
tor_log_get_logfile_names
void tor_log_get_logfile_names(smartlist_t *out)
Definition: log.c:721
tor_gettimeofday.h
Header for tor_gettimeofday.c.
add_file_log
int add_file_log(const log_severity_list_t *severity, const char *filename, int fd)
Definition: log.c:1187
tor_fd_getpos
off_t tor_fd_getpos(int fd)
Definition: fdio.c:48