Tor  0.4.3.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-2019, 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 a very low number; 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  /* log_fds and err_fds contain matching entries: log_fds are the fds used by
669  * the log module, and err_fds are the fds used by the err module.
670  * For stdio logs, the log_fd and err_fd values are identical,
671  * and the err module closes the fd on shutdown.
672  * For file logs, the err_fd is a dup() of the log_fd,
673  * and the log and err modules both close their respective fds on shutdown.
674  * (Once all fds representing a file are closed, the underlying file is
675  * closed.)
676  */
677  int log_fds[TOR_SIGSAFE_LOG_MAX_FDS];
678  int err_fds[TOR_SIGSAFE_LOG_MAX_FDS];
679  int n_fds;
680 
681  LOCK_LOGS();
682  /* Reserve the first one for stderr. This is safe because when we daemonize,
683  * we dup2 /dev/null to stderr.
684  * For stderr, log_fds and err_fds are the same. */
685  log_fds[0] = err_fds[0] = STDERR_FILENO;
686  n_fds = 1;
687 
688  for (lf = logfiles; lf; lf = lf->next) {
689  /* Don't try callback to the control port, syslogs, android logs, or any
690  * other non-file descriptor log: We can't call arbitrary functions from a
691  * signal handler.
692  */
693  if (lf->is_temporary || logfile_is_external(lf)
694  || lf->seems_dead || lf->fd < 0)
695  continue;
696  if (lf->severities->masks[SEVERITY_MASK_IDX(LOG_ERR)] &
697  (LD_BUG|LD_GENERAL)) {
698  if (lf->fd == STDERR_FILENO)
699  found_real_stderr = 1;
700  /* Avoid duplicates by checking the log module fd against log_fds */
701  if (int_array_contains(log_fds, n_fds, lf->fd))
702  continue;
703  /* Update log_fds using the log module's fd */
704  log_fds[n_fds] = lf->fd;
705  if (lf->needs_close) {
706  /* File log fds are duplicated, because close_log() closes the log
707  * module's fd, and tor_log_close_sigsafe_err_fds() closes the err
708  * module's fd. Both refer to the same file. */
709  err_fds[n_fds] = dup(lf->fd);
710  } else {
711  /* stdio log fds are not closed by the log module.
712  * tor_log_close_sigsafe_err_fds() closes stdio logs. */
713  err_fds[n_fds] = lf->fd;
714  }
715  n_fds++;
716  if (n_fds == TOR_SIGSAFE_LOG_MAX_FDS)
717  break;
718  }
719  }
720 
721  if (!found_real_stderr &&
722  int_array_contains(log_fds, n_fds, STDOUT_FILENO)) {
723  /* Don't use a virtual stderr when we're also logging to stdout.
724  * If we reached max_fds logs, we'll now have (max_fds - 1) logs.
725  * That's ok, max_fds is large enough that most tor instances don't exceed
726  * it. */
727  raw_assert(n_fds >= 2); /* Don't tor_assert inside log fns */
728  --n_fds;
729  log_fds[0] = log_fds[n_fds];
730  err_fds[0] = err_fds[n_fds];
731  }
732 
733  UNLOCK_LOGS();
734 
735  tor_log_set_sigsafe_err_fds(err_fds, n_fds);
736 }
737 
738 /** Add to <b>out</b> a copy of every currently configured log file name. Used
739  * to enable access to these filenames with the sandbox code. */
740 void
742 {
743  logfile_t *lf;
744  raw_assert(out);
745 
746  LOCK_LOGS();
747 
748  for (lf = logfiles; lf; lf = lf->next) {
749  if (lf->is_temporary || logfile_is_external(lf))
750  continue;
751  if (lf->filename == NULL)
752  continue;
753  smartlist_add_strdup(out, lf->filename);
754  }
755 
756  UNLOCK_LOGS();
757 }
758 
759 /** Implementation of the log_fn backend, used when we have
760  * variadic macros. All arguments are as for log_fn, except for
761  * <b>fn</b>, which is the name of the calling function. */
762 void
763 log_fn_(int severity, log_domain_mask_t domain, const char *fn,
764  const char *format, ...)
765 {
766  va_list ap;
767  if (severity > log_global_min_severity_)
768  return;
769  va_start(ap,format);
770  logv(severity, domain, fn, NULL, format, ap);
771  va_end(ap);
772 }
773 void
774 log_fn_ratelim_(ratelim_t *ratelim, int severity, log_domain_mask_t domain,
775  const char *fn, const char *format, ...)
776 {
777  va_list ap;
778  char *m;
779  if (severity > log_global_min_severity_)
780  return;
781  m = rate_limit_log(ratelim, approx_time());
782  if (m == NULL)
783  return;
784  va_start(ap, format);
785  logv(severity, domain, fn, m, format, ap);
786  va_end(ap);
787  tor_free(m);
788 }
789 
790 /** Free all storage held by <b>victim</b>. */
791 static void
793 {
794  if (!victim)
795  return;
796  tor_free(victim->severities);
797  tor_free(victim->filename);
798  tor_free(victim->android_tag);
799  tor_free(victim);
800 }
801 
802 /** Close all open log files, and free other static memory. */
803 void
805 {
806  logfile_t *victim, *next;
807  smartlist_t *messages, *messages2;
808  LOCK_LOGS();
809  next = logfiles;
810  logfiles = NULL;
811  messages = pending_cb_messages;
812  pending_cb_messages = NULL;
813  pending_cb_cb = NULL;
814  messages2 = pending_startup_messages;
816  UNLOCK_LOGS();
817  while (next) {
818  victim = next;
819  next = next->next;
820  close_log(victim);
821  log_free(victim);
822  }
823  tor_free(appname);
824 
825  SMARTLIST_FOREACH(messages, pending_log_message_t *, msg, {
826  pending_log_message_free(msg);
827  });
828  smartlist_free(messages);
829 
830  if (messages2) {
831  SMARTLIST_FOREACH(messages2, pending_log_message_t *, msg, {
832  pending_log_message_free(msg);
833  });
834  smartlist_free(messages2);
835  }
836 
837  /* We _could_ destroy the log mutex here, but that would screw up any logs
838  * that happened between here and the end of execution.
839  * If tor is re-initialized, log_mutex_initialized will still be 1. So we
840  * won't trigger any undefined behaviour by trying to re-initialize the
841  * log mutex. */
842 }
843 
844 /** Close signal-safe log files.
845  * Closing the log files makes the process and OS flush log buffers.
846  *
847  * This function is safe to call from a signal handler. It should only be
848  * called when shutting down the log or err modules. It is currenly called
849  * by the err module, when terminating the process on an abnormal condition.
850  */
851 void
853 {
854  logfile_t *victim, *next;
855  /* We can't LOCK_LOGS() in a signal handler, because it may call
856  * signal-unsafe functions. And we can't deallocate memory, either. */
857  next = logfiles;
858  logfiles = NULL;
859  while (next) {
860  victim = next;
861  next = next->next;
862  if (victim->needs_close) {
863  close_log_sigsafe(victim);
864  }
865  }
866 }
867 
868 /** Remove and free the log entry <b>victim</b> from the linked-list
869  * logfiles (it is probably present, but it might not be due to thread
870  * racing issues). After this function is called, the caller shouldn't
871  * refer to <b>victim</b> anymore.
872  */
873 static void
875 {
876  logfile_t *tmpl;
877  if (victim == logfiles)
878  logfiles = victim->next;
879  else {
880  for (tmpl = logfiles; tmpl && tmpl->next != victim; tmpl=tmpl->next) ;
881 // raw_assert(tmpl);
882 // raw_assert(tmpl->next == victim);
883  if (!tmpl)
884  return;
885  tmpl->next = victim->next;
886  }
887  log_free(victim);
888 }
889 
890 /** Helper: release system resources (but not memory) held by a single
891  * signal-safe logfile_t. If the log's resources can not be released in
892  * a signal handler, does nothing. */
893 static void
895 {
896  if (victim->needs_close && victim->fd >= 0) {
897  /* We can't do anything useful here if close() fails: we're shutting
898  * down logging, and the err module only does fatal errors. */
899  close(victim->fd);
900  victim->fd = -1;
901  }
902 }
903 
904 /** Helper: release system resources (but not memory) held by a single
905  * logfile_t. */
906 static void
908 {
909  if (victim->needs_close) {
910  close_log_sigsafe(victim);
911  } else if (victim->is_syslog) {
912 #ifdef HAVE_SYSLOG_H
913  if (--syslog_count == 0) {
914  /* There are no other syslogs; close the logging facility. */
915  closelog();
916  }
917 #endif /* defined(HAVE_SYSLOG_H) */
918  }
919 }
920 
921 /** Adjust a log severity configuration in <b>severity_out</b> to contain
922  * every domain between <b>loglevelMin</b> and <b>loglevelMax</b>, inclusive.
923  */
924 void
925 set_log_severity_config(int loglevelMin, int loglevelMax,
926  log_severity_list_t *severity_out)
927 {
928  int i;
929  raw_assert(loglevelMin >= loglevelMax);
930  raw_assert(loglevelMin >= LOG_ERR && loglevelMin <= LOG_DEBUG);
931  raw_assert(loglevelMax >= LOG_ERR && loglevelMax <= LOG_DEBUG);
932  memset(severity_out, 0, sizeof(log_severity_list_t));
933  for (i = loglevelMin; i >= loglevelMax; --i) {
934  severity_out->masks[SEVERITY_MASK_IDX(i)] = LD_ALL_DOMAINS;
935  }
936 }
937 
938 /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
939  * to <b>fd</b>. Copies <b>severity</b>. Helper: does no locking. */
940 MOCK_IMPL(STATIC void,
942  const char *name, int fd))
943 {
944  logfile_t *lf;
945  lf = tor_malloc_zero(sizeof(logfile_t));
946  lf->fd = fd;
947  lf->filename = tor_strdup(name);
948  lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
949  lf->next = logfiles;
950 
951  logfiles = lf;
953 }
954 
955 /** Add a log handler named <b>name</b> to send all messages in <b>severity</b>
956  * to <b>fd</b>. Steals a reference to <b>severity</b>; the caller must
957  * not use it after calling this function. */
958 void
959 add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
960 {
961  LOCK_LOGS();
962  add_stream_log_impl(severity, name, fd);
963  UNLOCK_LOGS();
964 }
965 
966 /** Initialize the global logging facility */
967 void
968 init_logging(int disable_startup_queue)
969 {
970  if (!log_mutex_initialized) {
973  }
974 #ifdef __GNUC__
975  if (strchr(__PRETTY_FUNCTION__, '(')) {
977  }
978 #endif
979  if (pending_cb_messages == NULL)
981  if (disable_startup_queue)
985  }
986 }
987 
988 /** Set whether we report logging domains as a part of our log messages.
989  */
990 void
992 {
993  LOCK_LOGS();
994  log_domains_are_logged = enabled;
995  UNLOCK_LOGS();
996 }
997 
998 /** Add a log handler to accept messages when no other log is configured.
999  */
1000 void
1001 add_default_log(int min_severity)
1002 {
1003  log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
1004  set_log_severity_config(min_severity, LOG_ERR, s);
1005  LOCK_LOGS();
1006  add_stream_log_impl(s, "<default>", fileno(stdout));
1007  tor_free(s);
1008  UNLOCK_LOGS();
1009 }
1010 
1011 /**
1012  * Register "cb" as the callback to call when there are new pending log
1013  * callbacks to be flushed with flush_pending_log_callbacks().
1014  *
1015  * Note that this callback, if present, can be invoked from any thread.
1016  *
1017  * This callback must not log.
1018  *
1019  * It is intentional that this function contains the name "callback" twice: it
1020  * sets a "callback" to be called on the condition that there is a "pending
1021  * callback".
1022  **/
1023 void
1024 logs_set_pending_callback_callback(pending_callback_callback cb)
1025 {
1026  pending_cb_cb = cb;
1027 }
1028 
1029 /**
1030  * Add a log handler to send messages in <b>severity</b>
1031  * to the function <b>cb</b>.
1032  */
1033 int
1035 {
1036  logfile_t *lf;
1037  lf = tor_malloc_zero(sizeof(logfile_t));
1038  lf->fd = -1;
1039  lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
1040  lf->filename = tor_strdup("<callback>");
1041  lf->callback = cb;
1042  lf->next = logfiles;
1043 
1044  LOCK_LOGS();
1045  logfiles = lf;
1047  UNLOCK_LOGS();
1048  return 0;
1049 }
1050 
1051 /** Adjust the configured severity of any logs whose callback function is
1052  * <b>cb</b>. */
1053 void
1054 change_callback_log_severity(int loglevelMin, int loglevelMax,
1055  log_callback cb)
1056 {
1057  logfile_t *lf;
1058  log_severity_list_t severities;
1059  set_log_severity_config(loglevelMin, loglevelMax, &severities);
1060  LOCK_LOGS();
1061  for (lf = logfiles; lf; lf = lf->next) {
1062  if (lf->callback == cb) {
1063  memcpy(lf->severities, &severities, sizeof(severities));
1064  }
1065  }
1067  UNLOCK_LOGS();
1068 }
1069 
1070 /** If there are any log messages that were generated with LD_NOCB waiting to
1071  * be sent to callback-based loggers, send them now. */
1072 void
1074 {
1075  logfile_t *lf;
1076  smartlist_t *messages, *messages_tmp;
1077 
1078  LOCK_LOGS();
1079  if (!pending_cb_messages || 0 == smartlist_len(pending_cb_messages)) {
1080  UNLOCK_LOGS();
1081  return;
1082  }
1083 
1084  messages = pending_cb_messages;
1086  do {
1088  const int severity = msg->severity;
1089  const log_domain_mask_t domain = msg->domain;
1090  for (lf = logfiles; lf; lf = lf->next) {
1091  if (! lf->callback || lf->seems_dead ||
1092  ! (lf->severities->masks[SEVERITY_MASK_IDX(severity)] & domain)) {
1093  continue;
1094  }
1095  lf->callback(severity, domain, msg->msg);
1096  }
1097  pending_log_message_free(msg);
1098  } SMARTLIST_FOREACH_END(msg);
1099  smartlist_clear(messages);
1100 
1101  messages_tmp = pending_cb_messages;
1102  pending_cb_messages = messages;
1103  messages = messages_tmp;
1104  } while (smartlist_len(messages));
1105 
1106  smartlist_free(messages);
1107 
1108  UNLOCK_LOGS();
1109 }
1110 
1111 /** Flush all the messages we stored from startup while waiting for log
1112  * initialization.
1113  */
1114 void
1116 {
1117  logfile_t *lf;
1118 
1119  LOCK_LOGS();
1123  goto out;
1124 
1126  msg) {
1127  int callbacks_deferred = 0;
1128  for (lf = logfiles; lf; lf = lf->next) {
1129  if (! logfile_wants_message(lf, msg->severity, msg->domain))
1130  continue;
1131 
1132  /* We configure a temporary startup log that goes to stdout, so we
1133  * shouldn't replay to stdout/stderr*/
1134  if (lf->fd == STDOUT_FILENO || lf->fd == STDERR_FILENO) {
1135  continue;
1136  }
1137 
1138  logfile_deliver(lf, msg->fullmsg, strlen(msg->fullmsg), msg->msg,
1139  msg->domain, msg->severity, &callbacks_deferred);
1140  }
1141  pending_log_message_free(msg);
1142  } SMARTLIST_FOREACH_END(msg);
1143  smartlist_free(pending_startup_messages);
1144  pending_startup_messages = NULL;
1145 
1146  out:
1147  UNLOCK_LOGS();
1148 }
1149 
1150 /** Close any log handlers marked by mark_logs_temp(). */
1151 void
1153 {
1154  logfile_t *lf, **p;
1155 
1156  LOCK_LOGS();
1157  for (p = &logfiles; *p; ) {
1158  if ((*p)->is_temporary) {
1159  lf = *p;
1160  /* we use *p here to handle the edge case of the head of the list */
1161  *p = (*p)->next;
1162  close_log(lf);
1163  log_free(lf);
1164  } else {
1165  p = &((*p)->next);
1166  }
1167  }
1168 
1170  UNLOCK_LOGS();
1171 }
1172 
1173 /** Make all currently temporary logs (set to be closed by close_temp_logs)
1174  * live again, and close all non-temporary logs. */
1175 void
1177 {
1178  logfile_t *lf;
1179  LOCK_LOGS();
1180  for (lf = logfiles; lf; lf = lf->next)
1181  lf->is_temporary = ! lf->is_temporary;
1182  UNLOCK_LOGS();
1183  close_temp_logs();
1184 }
1185 
1186 /** Configure all log handles to be closed by close_temp_logs(). */
1187 void
1189 {
1190  logfile_t *lf;
1191  LOCK_LOGS();
1192  for (lf = logfiles; lf; lf = lf->next)
1193  lf->is_temporary = 1;
1194  UNLOCK_LOGS();
1195 }
1196 
1197 /**
1198  * Add a log handler to send messages to <b>filename</b> via <b>fd</b>. If
1199  * opening the logfile failed, -1 is returned and errno is set appropriately
1200  * (by open(2)). Takes ownership of fd.
1201  */
1202 MOCK_IMPL(int,
1203 add_file_log,(const log_severity_list_t *severity,
1204  const char *filename,
1205  int fd))
1206 {
1207  logfile_t *lf;
1208 
1209  if (fd<0)
1210  return -1;
1211  if (tor_fd_seekend(fd)<0) {
1212  close(fd);
1213  return -1;
1214  }
1215 
1216  LOCK_LOGS();
1217  add_stream_log_impl(severity, filename, fd);
1218  logfiles->needs_close = 1;
1219  lf = logfiles;
1221 
1222  if (log_tor_version(lf, 0) < 0) {
1223  delete_log(lf);
1224  }
1225  UNLOCK_LOGS();
1226 
1227  return 0;
1228 }
1229 
1230 #ifdef HAVE_SYSLOG_H
1231 /**
1232  * Add a log handler to send messages to they system log facility.
1233  *
1234  * If this is the first log handler, opens syslog with ident Tor or
1235  * Tor-<syslog_identity_tag> if that is not NULL.
1236  */
1237 int
1238 add_syslog_log(const log_severity_list_t *severity,
1239  const char* syslog_identity_tag)
1240 {
1241  logfile_t *lf;
1242  if (syslog_count++ == 0) {
1243  /* This is the first syslog. */
1244  static char buf[256];
1245  if (syslog_identity_tag) {
1246  tor_snprintf(buf, sizeof(buf), "Tor-%s", syslog_identity_tag);
1247  } else {
1248  tor_snprintf(buf, sizeof(buf), "Tor");
1249  }
1250  openlog(buf, LOG_PID | LOG_NDELAY, LOGFACILITY);
1251  }
1252 
1253  lf = tor_malloc_zero(sizeof(logfile_t));
1254  lf->fd = -1;
1255  lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
1256  lf->filename = tor_strdup("<syslog>");
1257  lf->is_syslog = 1;
1258 
1259  LOCK_LOGS();
1260  lf->next = logfiles;
1261  logfiles = lf;
1263  UNLOCK_LOGS();
1264  return 0;
1265 }
1266 #endif /* defined(HAVE_SYSLOG_H) */
1267 
1268 #ifdef HAVE_ANDROID_LOG_H
1269 /**
1270  * Add a log handler to send messages to the Android platform log facility.
1271  */
1272 int
1273 add_android_log(const log_severity_list_t *severity,
1274  const char *android_tag)
1275 {
1276  logfile_t *lf = NULL;
1277 
1278  lf = tor_malloc_zero(sizeof(logfile_t));
1279  lf->fd = -1;
1280  lf->severities = tor_memdup(severity, sizeof(log_severity_list_t));
1281  lf->filename = tor_strdup("<android>");
1282  lf->is_android = 1;
1283 
1284  if (android_tag == NULL)
1285  lf->android_tag = tor_strdup("Tor");
1286  else {
1287  char buf[256];
1288  tor_snprintf(buf, sizeof(buf), "Tor-%s", android_tag);
1289  lf->android_tag = tor_strdup(buf);
1290  }
1291 
1292  LOCK_LOGS();
1293  lf->next = logfiles;
1294  logfiles = lf;
1296  UNLOCK_LOGS();
1297  return 0;
1298 }
1299 #endif /* defined(HAVE_ANDROID_LOG_H) */
1300 
1301 /** If <b>level</b> is a valid log severity, return the corresponding
1302  * numeric value. Otherwise, return -1. */
1303 int
1304 parse_log_level(const char *level)
1305 {
1306  if (!strcasecmp(level, "err"))
1307  return LOG_ERR;
1308  if (!strcasecmp(level, "warn"))
1309  return LOG_WARN;
1310  if (!strcasecmp(level, "notice"))
1311  return LOG_NOTICE;
1312  if (!strcasecmp(level, "info"))
1313  return LOG_INFO;
1314  if (!strcasecmp(level, "debug"))
1315  return LOG_DEBUG;
1316  return -1;
1317 }
1318 
1319 /** Return the string equivalent of a given log level. */
1320 const char *
1322 {
1323  return sev_to_string(level);
1324 }
1325 
1326 /** NULL-terminated array of names for log domains such that domain_list[dom]
1327  * is a description of <b>dom</b>.
1328  *
1329  * Remember to update doc/tor.1.txt if you modify this list.
1330  * */
1331 static const char *domain_list[] = {
1332  "GENERAL", "CRYPTO", "NET", "CONFIG", "FS", "PROTOCOL", "MM",
1333  "HTTP", "APP", "CONTROL", "CIRC", "REND", "BUG", "DIR", "DIRSERV",
1334  "OR", "EDGE", "ACCT", "HIST", "HANDSHAKE", "HEARTBEAT", "CHANNEL",
1335  "SCHED", "GUARD", "CONSDIFF", "DOS", "PROCESS", "PT", "BTRACK", "MESG",
1336  NULL
1337 };
1338 
1340 
1344 
1345 /** Return a bitmask for the log domain for which <b>domain</b> is the name,
1346  * or 0 if there is no such name. */
1347 static log_domain_mask_t
1348 parse_log_domain(const char *domain)
1349 {
1350  int i;
1351  for (i=0; domain_list[i]; ++i) {
1352  if (!strcasecmp(domain, domain_list[i]))
1353  return (UINT64_C(1)<<i);
1354  }
1355  return 0;
1356 }
1357 
1358 /** Translate a bitmask of log domains to a string. */
1359 static char *
1360 domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
1361 {
1362  char *cp = buf;
1363  char *eos = buf+buflen;
1364 
1365  buf[0] = '\0';
1366  if (! domain)
1367  return buf;
1368  while (1) {
1369  const char *d;
1370  int bit = tor_log2(domain);
1371  size_t n;
1372  if ((unsigned)bit >= ARRAY_LENGTH(domain_list)-1 ||
1373  bit >= N_LOGGING_DOMAINS) {
1374  tor_snprintf(buf, buflen, "<BUG:Unknown domain %lx>", (long)domain);
1375  return buf+strlen(buf);
1376  }
1377  d = domain_list[bit];
1378  n = strlcpy(cp, d, eos-cp);
1379  if (n >= buflen) {
1380  tor_snprintf(buf, buflen, "<BUG:Truncating domain %lx>", (long)domain);
1381  return buf+strlen(buf);
1382  }
1383  cp += n;
1384  domain &= ~(1<<bit);
1385 
1386  if (domain == 0 || (eos-cp) < 2)
1387  return cp;
1388 
1389  memcpy(cp, ",", 2); /*Nul-terminated ,"*/
1390  cp++;
1391  }
1392 }
1393 
1394 /** Parse a log severity pattern in *<b>cfg_ptr</b>. Advance cfg_ptr after
1395  * the end of the severityPattern. Set the value of <b>severity_out</b> to
1396  * the parsed pattern. Return 0 on success, -1 on failure.
1397  *
1398  * The syntax for a SeverityPattern is:
1399  * <pre>
1400  * SeverityPattern = *(DomainSeverity SP)* DomainSeverity
1401  * DomainSeverity = (DomainList SP)? SeverityRange
1402  * SeverityRange = MinSeverity ("-" MaxSeverity )?
1403  * DomainList = "[" (SP? DomainSpec SP? ",") SP? DomainSpec "]"
1404  * DomainSpec = "*" | Domain | "~" Domain
1405  * </pre>
1406  * A missing MaxSeverity defaults to ERR. Severities and domains are
1407  * case-insensitive. "~" indicates negation for a domain; negation happens
1408  * last inside a DomainList. Only one SeverityRange without a DomainList is
1409  * allowed per line.
1410  */
1411 int
1412 parse_log_severity_config(const char **cfg_ptr,
1413  log_severity_list_t *severity_out)
1414 {
1415  const char *cfg = *cfg_ptr;
1416  int got_anything = 0;
1417  int got_an_unqualified_range = 0;
1418  memset(severity_out, 0, sizeof(*severity_out));
1419 
1420  cfg = eat_whitespace(cfg);
1421  while (*cfg) {
1422  const char *dash, *space;
1423  char *sev_lo, *sev_hi;
1424  int low, high, i;
1426 
1427  if (*cfg == '[') {
1428  int err = 0;
1429  char *domains_str;
1430  smartlist_t *domains_list;
1431  log_domain_mask_t neg_domains = 0;
1432  const char *closebracket = strchr(cfg, ']');
1433  if (!closebracket)
1434  return -1;
1435  domains = 0;
1436  domains_str = tor_strndup(cfg+1, closebracket-cfg-1);
1437  domains_list = smartlist_new();
1438  smartlist_split_string(domains_list, domains_str, ",", SPLIT_SKIP_SPACE,
1439  -1);
1440  tor_free(domains_str);
1441  SMARTLIST_FOREACH_BEGIN(domains_list, const char *, domain) {
1442  if (!strcmp(domain, "*")) {
1443  domains = LD_ALL_DOMAINS;
1444  } else {
1446  int negate=0;
1447  if (*domain == '~') {
1448  negate = 1;
1449  ++domain;
1450  }
1451  d = parse_log_domain(domain);
1452  if (!d) {
1453  log_warn(LD_CONFIG, "No such logging domain as %s", domain);
1454  err = 1;
1455  } else {
1456  if (negate)
1457  neg_domains |= d;
1458  else
1459  domains |= d;
1460  }
1461  }
1462  } SMARTLIST_FOREACH_END(domain);
1463  SMARTLIST_FOREACH(domains_list, char *, d, tor_free(d));
1464  smartlist_free(domains_list);
1465  if (err)
1466  return -1;
1467  if (domains == 0 && neg_domains)
1468  domains = ~neg_domains;
1469  else
1470  domains &= ~neg_domains;
1471  cfg = eat_whitespace(closebracket+1);
1472  } else {
1473  ++got_an_unqualified_range;
1474  }
1475  if (!strcasecmpstart(cfg, "file") ||
1476  !strcasecmpstart(cfg, "stderr") ||
1477  !strcasecmpstart(cfg, "stdout") ||
1478  !strcasecmpstart(cfg, "syslog") ||
1479  !strcasecmpstart(cfg, "android")) {
1480  goto done;
1481  }
1482  if (got_an_unqualified_range > 1)
1483  return -1;
1484 
1485  space = find_whitespace(cfg);
1486  dash = strchr(cfg, '-');
1487  if (dash && dash < space) {
1488  sev_lo = tor_strndup(cfg, dash-cfg);
1489  sev_hi = tor_strndup(dash+1, space-(dash+1));
1490  } else {
1491  sev_lo = tor_strndup(cfg, space-cfg);
1492  sev_hi = tor_strdup("ERR");
1493  }
1494  low = parse_log_level(sev_lo);
1495  high = parse_log_level(sev_hi);
1496  tor_free(sev_lo);
1497  tor_free(sev_hi);
1498  if (low == -1)
1499  return -1;
1500  if (high == -1)
1501  return -1;
1502 
1503  got_anything = 1;
1504  for (i=low; i >= high; --i)
1505  severity_out->masks[SEVERITY_MASK_IDX(i)] |= domains;
1506 
1507  cfg = eat_whitespace(space);
1508  }
1509 
1510  done:
1511  *cfg_ptr = cfg;
1512  return got_anything ? 0 : -1;
1513 }
1514 
1515 /** Return the least severe log level that any current log is interested in. */
1516 int
1518 {
1519  logfile_t *lf;
1520  int i;
1521  int min = LOG_ERR;
1522  for (lf = logfiles; lf; lf = lf->next) {
1523  for (i = LOG_DEBUG; i > min; --i)
1524  if (lf->severities->masks[SEVERITY_MASK_IDX(i)])
1525  min = i;
1526  }
1527  return min;
1528 }
1529 
1530 /** Switch all logs to output at most verbose level. */
1531 void
1533 {
1534  logfile_t *lf;
1535  int i;
1536  LOCK_LOGS();
1537  for (lf = logfiles; lf; lf=lf->next) {
1538  for (i = LOG_DEBUG; i >= LOG_ERR; --i)
1539  lf->severities->masks[SEVERITY_MASK_IDX(i)] = LD_ALL_DOMAINS;
1540  }
1542  UNLOCK_LOGS();
1543 }
1544 
1545 /** Truncate all the log files. */
1546 void
1548 {
1549  logfile_t *lf;
1550  for (lf = logfiles; lf; lf = lf->next) {
1551  if (lf->fd >= 0) {
1552  tor_ftruncate(lf->fd);
1553  }
1554  }
1555 }
static const char * domain_list[]
Definition: log.c:1331
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
int add_file_log(const log_severity_list_t *severity, const char *filename, int fd)
Definition: log.c:1205
int write_all_to_fd_minimal(int fd, const char *buf, size_t count)
Definition: fdio.c:108
void init_logging(int disable_startup_queue)
Definition: log.c:968
Header for printf.c.
static void delete_log(logfile_t *victim)
Definition: log.c:874
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
void logs_free_all(void)
Definition: log.c:804
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
static int queue_startup_messages
Definition: log.c:198
int tor_fd_seekend(int fd)
Definition: fdio.c:61
void rollback_log_changes(void)
Definition: log.c:1176
int add_callback_log(const log_severity_list_t *severity, log_callback cb)
Definition: log.c:1034
Summarize similar messages that would otherwise flood the logs.
static int pretty_fn_has_parens
Definition: log.c:201
Definition: log.c:73
Definitions for timing-related constants.
#define CTASSERT(x)
Definition: ctassert.h:44
const int LOG_WARN_
Definition: log.c:67
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
int fd
Definition: log.c:76
#define LD_GENERAL
Definition: log.h:62
void tor_log_sigsafe_err_set_granularity(int ms)
Definition: torerr.c:184
static void close_log(logfile_t *victim)
Definition: log.c:907
#define LOG_INFO
Definition: log.h:45
Header for fdio.c.
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:628
void smartlist_add(smartlist_t *sl, void *element)
static const char * sev_to_string(int severity)
Definition: log.c:94
static int should_log_function_name(log_domain_mask_t domain, int severity)
Definition: log.c:110
int get_min_log_level(void)
Definition: log.c:1517
log_severity_list_t * severities
Definition: log.c:84
struct tm * tor_localtime_r_msg(const time_t *timep, struct tm *result, char **err_out)
Definition: time_to_tm.c:133
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:41
void tor_log_get_logfile_names(smartlist_t *out)
Definition: log.c:741
void tor_log_string(int severity, log_domain_mask_t domain, const char *function, const char *string)
Definition: log.c:268
Header for smartlist_split.c.
const char * find_whitespace(const char *s)
Definition: util_string.c:344
void tor_log_set_sigsafe_err_fds(const int *fds, int n)
Definition: torerr.c:123
off_t tor_fd_getpos(int fd)
Definition: fdio.c:48
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) CHECK_PRINTF(7
Definition: log.c:363
int log_global_min_severity_
Definition: log.c:220
log_domain_mask_t masks[LOG_DEBUG-LOG_ERR+1]
Definition: log.h:154
void tor_gettimeofday(struct timeval *timeval)
void set_log_time_granularity(int granularity_msec)
Definition: log.c:280
#define LD_ALL_FLAGS
Definition: log.h:135
void logs_set_pending_callback_callback(pending_callback_callback cb)
Definition: log.c:1024
#define tor_free(p)
Definition: malloc.h:52
Header for util_string.c.
static size_t pending_startup_messages_len
Definition: log.c:194
const char * name
Definition: config.c:2211
#define LOG_NOTICE
Definition: log.h:50
Header for time_to_tm.c.
static char * domain_to_string(log_domain_mask_t domain, char *buf, size_t buflen)
Definition: log.c:1360
static char static char * appname
Definition: log.c:236
Headers for util_malloc.c.
smartlist_t * smartlist_new(void)
Top-level declarations for the smartlist_t dynamic array type.
static int log_time_granularity
Definition: log.c:275
char * fullmsg
Definition: log.c:177
#define STATIC
Definition: testsupport.h:32
void(* log_callback)(int severity, log_domain_mask_t domain, const char *msg)
Definition: log.h:158
void tor_log_update_sigsafe_err_fds(void)
Definition: log.c:663
#define MAX_STARTUP_MSG_LEN
Definition: log.c:205
static int logfile_is_external(const logfile_t *lf)
Definition: log.c:481
static int log_tor_version(logfile_t *lf, int reset)
Definition: log.c:325
static smartlist_t * pending_startup_messages
Definition: log.c:189
#define LD_NOFUNCNAME
Definition: log.h:147
struct logfile_t * next
Definition: log.c:74
Macros for iterating over the elements of a smartlist_t.
void flush_pending_log_callbacks(void)
Definition: log.c:1073
void mark_logs_temp(void)
Definition: log.c:1188
static logfile_t * logfiles
Definition: log.c:162
#define LD_ALL_DOMAINS
Definition: log.h:128
STATIC void add_stream_log_impl(const log_severity_list_t *severity, const char *name, int fd)
Definition: log.c:942
int tor_ftruncate(int fd)
Definition: fdio.c:92
void log_set_application_name(const char *name)
Definition: log.c:244
Header for git_revision.c.
#define TOR_SIGSAFE_LOG_MAX_FDS
Definition: torerr.h:37
static log_domain_mask_t parse_log_domain(const char *domain)
Definition: log.c:1348
#define LD_NOCB
Definition: log.h:144
void change_callback_log_severity(int loglevelMin, int loglevelMax, log_callback cb)
Definition: log.c:1054
const char * eat_whitespace(const char *s)
Definition: util_string.c:268
Declare subsystem object for the logging module.
void tor_mutex_init(tor_mutex_t *m)
#define LOG_WARN
Definition: log.h:53
void log_fn_(int severity, log_domain_mask_t domain, const char *fn, const char *format,...)
Definition: log.c:763
Header for approx_time.c.
void logs_close_sigsafe(void)
Definition: log.c:852
void flush_log_messages_from_startup(void)
Definition: log.c:1115
int parse_log_severity_config(const char **cfg_ptr, log_severity_list_t *severity_out)
Definition: log.c:1412
int needs_close
Definition: log.c:78
void truncate_logs(void)
Definition: log.c:1547
void logs_set_domain_logging(int enabled)
Definition: log.c:991
log_domain_mask_t domain
Definition: log.c:176
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
const char tor_bug_suffix[]
Definition: git_revision.c:32
static tor_mutex_t log_mutex
Definition: log.c:157
int tor_log2(uint64_t u64)
Definition: bits.c:16
#define LOG_ERR
Definition: log.h:56
static int log_domains_are_logged
Definition: log.c:164
Compile-time assertions: CTASSERT(expression).
static size_t log_prefix_(char *buf, size_t buf_len, int severity)
Definition: log.c:290
static pending_callback_callback pending_cb_cb
Definition: log.c:185
int parse_log_level(const char *level)
Definition: log.c:1304
#define LOCK_LOGS()
Definition: log.c:208
#define TRUNCATED_STR
Definition: log.c:61
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
void add_default_log(int min_severity)
Definition: log.c:1001
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Header for compat_mutex.c.
uint64_t log_domain_mask_t
Definition: logging_types.h:21
void close_temp_logs(void)
Definition: log.c:1152
int is_syslog
Definition: log.c:80
int log_message_is_interesting(int severity, log_domain_mask_t domain)
Definition: log.c:255
char * filename
Definition: log.c:75
#define ARRAY_LENGTH(x)
void add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
Definition: log.c:959
void switch_logs_debug(void)
Definition: log.c:1532
static int log_mutex_initialized
Definition: log.c:159
Header for bits.c.
const char * log_level_to_string(int level)
Definition: log.c:1321
#define UNLOCK_LOGS()
Definition: log.c:213
void set_log_severity_config(int loglevelMin, int loglevelMax, log_severity_list_t *severity_out)
Definition: log.c:925
Header for compat_string.c.
Headers for torerr.c.
time_t approx_time(void)
Definition: approx_time.c:32
#define LOG_DEBUG
Definition: log.h:42
int is_temporary
Definition: log.c:79
#define N_LOGGING_DOMAINS
Definition: log.h:124
log_callback callback
Definition: log.c:83
int is_android
Definition: log.c:81
#define LD_NET
Definition: log.h:66
static void close_log_sigsafe(logfile_t *victim)
Definition: log.c:894
Headers for log.c.
int seems_dead
Definition: log.c:77
Header for tor_gettimeofday.c.
void smartlist_clear(smartlist_t *sl)
#define HIGHEST_RESERVED_LD_DOMAIN_
Definition: log.h:126
static smartlist_t * pending_cb_messages
Definition: log.c:182
int strcasecmpstart(const char *s1, const char *s2)
Definition: util_string.c:216
int tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
Definition: printf.c:41
static void log_free_(logfile_t *victim)
Definition: log.c:792
char * android_tag
Definition: log.c:82
#define LOWEST_RESERVED_LD_FLAG_
Definition: log.h:133
#define LD_BUG
Definition: log.h:86
#define LD_CONFIG
Definition: log.h:68
static int int_array_contains(const int *array, int n, int item)
Definition: log.c:650
static void pending_log_message_free_(pending_log_message_t *msg)
Definition: log.c:468
static int logfile_wants_message(const logfile_t *lf, int severity, log_domain_mask_t domain)
Definition: log.c:491
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)