Tor  0.4.5.0-alpha-dev
mainloop.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 mainloop.c
9  * \brief Toplevel module. Handles signals, multiplexes between
10  * connections, implements main loop, and drives scheduled events.
11  *
12  * For the main loop itself; see run_main_loop_once(). It invokes the rest of
13  * Tor mostly through Libevent callbacks. Libevent callbacks can happen when
14  * a timer elapses, a signal is received, a socket is ready to read or write,
15  * or an event is manually activated.
16  *
17  * Most events in Tor are driven from these callbacks:
18  * <ul>
19  * <li>conn_read_callback() and conn_write_callback() here, which are
20  * invoked when a socket is ready to read or write respectively.
21  * <li>signal_callback(), which handles incoming signals.
22  * </ul>
23  * Other events are used for specific purposes, or for building more complex
24  * control structures. If you search for usage of tor_libevent_new(), you
25  * will find all the events that we construct in Tor.
26  *
27  * Tor has numerous housekeeping operations that need to happen
28  * regularly. They are handled in different ways:
29  * <ul>
30  * <li>The most frequent operations are handled after every read or write
31  * event, at the end of connection_handle_read() and
32  * connection_handle_write().
33  *
34  * <li>The next most frequent operations happen after each invocation of the
35  * main loop, in run_main_loop_once().
36  *
37  * <li>Once per second, we run all of the operations listed in
38  * second_elapsed_callback(), and in its child, run_scheduled_events().
39  *
40  * <li>Once-a-second operations are handled in second_elapsed_callback().
41  *
42  * <li>More infrequent operations take place based on the periodic event
43  * driver in periodic.c . These are stored in the periodic_events[]
44  * table.
45  * </ul>
46  *
47  **/
48 
49 #define MAINLOOP_PRIVATE
50 #include "core/or/or.h"
51 
52 #include "app/config/config.h"
53 #include "app/config/statefile.h"
54 #include "app/main/ntmain.h"
57 #include "core/mainloop/mainloop.h"
59 #include "core/mainloop/periodic.h"
60 #include "core/or/channel.h"
61 #include "core/or/channelpadding.h"
62 #include "core/or/channeltls.h"
63 #include "core/or/circuitbuild.h"
64 #include "core/or/circuitlist.h"
65 #include "core/or/circuituse.h"
67 #include "core/or/connection_or.h"
68 #include "core/or/dos.h"
69 #include "core/or/status.h"
71 #include "feature/client/bridges.h"
72 #include "feature/client/dnsserv.h"
83 #include "feature/hs/hs_cache.h"
84 #include "feature/hs/hs_client.h"
85 #include "feature/hs/hs_service.h"
90 #include "feature/relay/dns.h"
93 #include "feature/relay/selftest.h"
94 #include "feature/rend/rendcache.h"
99 #include "feature/stats/rephist.h"
100 #include "lib/buf/buffers.h"
102 #include "lib/err/backtrace.h"
103 #include "lib/tls/buffers_tls.h"
104 
105 #include "lib/net/buffers_net.h"
107 
108 #include <event2/event.h>
109 
110 #include "core/or/cell_st.h"
114 #include "app/config/or_state_st.h"
117 
118 #ifdef HAVE_UNISTD_H
119 #include <unistd.h>
120 #endif
121 
122 #ifdef HAVE_SYSTEMD
123 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
124 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
125  * Coverity. Here's a kludge to unconfuse it.
126  */
127 # define __INCLUDE_LEVEL__ 2
128 #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
129 #include <systemd/sd-daemon.h>
130 #endif /* defined(HAVE_SYSTEMD) */
131 
132 /* Token bucket for all traffic. */
133 token_bucket_rw_t global_bucket;
134 
135 /* Token bucket for relayed traffic. */
136 token_bucket_rw_t global_relayed_bucket;
137 
138 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
139 /** How many bytes have we read since we started the process? */
140 static uint64_t stats_n_bytes_read = 0;
141 /** How many bytes have we written since we started the process? */
142 static uint64_t stats_n_bytes_written = 0;
143 /** What time did this process start up? */
145 /** How many seconds have we been running? */
146 static long stats_n_seconds_working = 0;
147 /** How many times have we returned from the main loop successfully? */
148 static uint64_t stats_n_main_loop_successes = 0;
149 /** How many times have we received an error from the main loop? */
150 static uint64_t stats_n_main_loop_errors = 0;
151 /** How many times have we returned from the main loop with no events. */
152 static uint64_t stats_n_main_loop_idle = 0;
153 
154 /** How often will we honor SIGNEWNYM requests? */
155 #define MAX_SIGNEWNYM_RATE 10
156 /** When did we last process a SIGNEWNYM request? */
157 static time_t time_of_last_signewnym = 0;
158 /** Is there a signewnym request we're currently waiting to handle? */
159 static int signewnym_is_pending = 0;
160 /** Mainloop event for the deferred signewnym call. */
162 /** How many times have we called newnym? */
163 static unsigned newnym_epoch = 0;
164 
165 /** Smartlist of all open connections. */
167 /** List of connections that have been marked for close and need to be freed
168  * and removed from connection_array. */
170 /** List of linked connections that are currently reading data into their
171  * inbuf from their partner's outbuf. */
173 /** Flag: Set to true iff we entered the current libevent main loop via
174  * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
175  * to handle linked connections. */
176 static int called_loop_once = 0;
177 /** Flag: if true, it's time to shut down, so the main loop should exit as
178  * soon as possible.
179  */
180 static int main_loop_should_exit = 0;
181 /** The return value that the main loop should yield when it exits, if
182  * main_loop_should_exit is true.
183  */
184 static int main_loop_exit_value = 0;
185 
186 /** We set this to 1 when we've opened a circuit, so we can print a log
187  * entry to inform the user that Tor is working. We set it to 0 when
188  * we think the fact that we once opened a circuit doesn't mean we can do so
189  * any longer (a big time jump happened, when we notice our directory is
190  * heinously out-of-date, etc.
191  */
192 static int can_complete_circuits = 0;
193 
194 /** How often do we check for router descriptors that we should download
195  * when we have too little directory info? */
196 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
197 /** How often do we check for router descriptors that we should download
198  * when we have enough directory info? */
199 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
200 
201 static int conn_close_if_marked(int i);
204 static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
205 static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
206 static void shutdown_did_not_work_callback(evutil_socket_t fd, short event,
207  void *arg) ATTR_NORETURN;
208 
209 /****************************************************************************
210  *
211  * This section contains accessors and other methods on the connection_array
212  * variables (which are global within this file and unavailable outside it).
213  *
214  ****************************************************************************/
215 
216 /** Return 1 if we have successfully built a circuit, and nothing has changed
217  * to make us think that maybe we can't.
218  */
219 int
221 {
222  return can_complete_circuits;
223 }
224 
225 /** Note that we have successfully built a circuit, so that reachability
226  * testing and introduction points and so on may be attempted. */
227 void
229 {
231 }
232 
233 /** Note that something has happened (like a clock jump, or DisableNetwork) to
234  * make us think that maybe we can't complete circuits. */
235 void
237 {
239 }
240 
241 /** Add <b>conn</b> to the array of connections that we can poll on. The
242  * connection's socket must be set; the connection starts out
243  * non-reading and non-writing.
244  */
245 int
246 connection_add_impl(connection_t *conn, int is_connecting)
247 {
248  tor_assert(conn);
249  tor_assert(SOCKET_OK(conn->s) ||
250  conn->linked ||
251  (conn->type == CONN_TYPE_AP &&
252  TO_EDGE_CONN(conn)->is_dns_request));
253 
254  tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
255  conn->conn_array_index = smartlist_len(connection_array);
257 
258  (void) is_connecting;
259 
260  if (SOCKET_OK(conn->s) || conn->linked) {
261  conn->read_event = tor_event_new(tor_libevent_get_base(),
262  conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
263  conn->write_event = tor_event_new(tor_libevent_get_base(),
264  conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
265  /* XXXX CHECK FOR NULL RETURN! */
266  }
267 
268  log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
269  conn_type_to_string(conn->type), (int)conn->s, conn->address,
270  smartlist_len(connection_array));
271 
272  return 0;
273 }
274 
275 /** Tell libevent that we don't care about <b>conn</b> any more. */
276 void
278 {
279  if (conn->read_event) {
280  if (event_del(conn->read_event))
281  log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
282  tor_free(conn->read_event);
283  }
284  if (conn->write_event) {
285  if (event_del(conn->write_event))
286  log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
287  tor_free(conn->write_event);
288  }
289  if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
291  }
292 }
293 
294 /** Remove the connection from the global list, and remove the
295  * corresponding poll entry. Calling this function will shift the last
296  * connection (if any) into the position occupied by conn.
297  */
298 int
300 {
301  int current_index;
302  connection_t *tmp;
303 
304  tor_assert(conn);
305 
306  log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
307  (int)conn->s, conn_type_to_string(conn->type),
308  smartlist_len(connection_array));
309 
310  if (conn->type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
311  log_info(LD_NET, "Closing SOCKS Unix socket connection");
312  }
313 
315 
316  tor_assert(conn->conn_array_index >= 0);
317  current_index = conn->conn_array_index;
318  connection_unregister_events(conn); /* This is redundant, but cheap. */
319  if (current_index == smartlist_len(connection_array)-1) { /* at the end */
320  smartlist_del(connection_array, current_index);
321  return 0;
322  }
323 
324  /* replace this one with the one at the end */
325  smartlist_del(connection_array, current_index);
326  tmp = smartlist_get(connection_array, current_index);
327  tmp->conn_array_index = current_index;
328 
329  return 0;
330 }
331 
332 /** If <b>conn</b> is an edge conn, remove it from the list
333  * of conn's on this circuit. If it's not on an edge,
334  * flush and send destroys for all circuits on this conn.
335  *
336  * Remove it from connection_array (if applicable) and
337  * from closeable_connection_list.
338  *
339  * Then free it.
340  */
341 static void
343 {
345  if (conn->conn_array_index >= 0) {
346  connection_remove(conn);
347  }
348  if (conn->linked_conn) {
349  conn->linked_conn->linked_conn = NULL;
350  if (! conn->linked_conn->marked_for_close &&
353  conn->linked_conn = NULL;
354  }
357  if (conn->type == CONN_TYPE_EXIT) {
359  }
360  if (conn->type == CONN_TYPE_OR) {
361  if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
363  /* connection_unlink() can only get called if the connection
364  * was already on the closeable list, and it got there by
365  * connection_mark_for_close(), which was called from
366  * connection_or_close_normally() or
367  * connection_or_close_for_error(), so the channel should
368  * already be in CHANNEL_STATE_CLOSING, and then the
369  * connection_about_to_close_connection() goes to
370  * connection_or_about_to_close(), which calls channel_closed()
371  * to notify the channel_t layer, and closed the channel, so
372  * nothing more to do here to deal with the channel associated
373  * with an orconn.
374  */
375  }
376  connection_free(conn);
377 }
378 
379 /** Event that invokes schedule_active_linked_connections_cb. */
381 
382 /**
383  * Callback: used to activate read events for all linked connections, so
384  * libevent knows to call their read callbacks. This callback run as a
385  * postloop event, so that the events _it_ activates don't happen until
386  * Libevent has a chance to check for other events.
387  */
388 static void
390 {
391  (void)event;
392  (void)arg;
393 
394  /* All active linked conns should get their read events activated,
395  * so that libevent knows to run their callbacks. */
397  event_active(conn->read_event, EV_READ, 1));
398 
399  /* Reactivate the event if we still have connections in the active list.
400  *
401  * A linked connection doesn't get woken up by I/O but rather artificially
402  * by this event callback. It has directory data spooled in it and it is
403  * sent incrementally by small chunks unless spool_eagerly is true. For that
404  * to happen, we need to induce the activation of the read event so it can
405  * be flushed. */
406  if (smartlist_len(active_linked_connection_lst)) {
408  }
409 }
410 
411 /** Initialize the global connection list, closeable connection list,
412  * and active connection list. */
413 void
415 {
416  if (!connection_array)
422 }
423 
424 /** Schedule <b>conn</b> to be closed. **/
425 void
427 {
430  assert_connection_ok(conn, time(NULL));
433 }
434 
435 /** Return 1 if conn is on the closeable list, else return 0. */
436 int
438 {
440 }
441 
442 /** Return true iff conn is in the current poll array. */
443 int
445 {
446  return smartlist_contains(connection_array, conn);
447 }
448 
449 /** Set <b>*array</b> to an array of all connections. <b>*array</b> must not
450  * be modified.
451  */
454 {
455  if (!connection_array)
457  return connection_array;
458 }
459 
460 /**
461  * Return the amount of network traffic read, in bytes, over the life of this
462  * process.
463  */
464 MOCK_IMPL(uint64_t,
466 {
467  return stats_n_bytes_read;
468 }
469 
470 /**
471  * Return the amount of network traffic read, in bytes, over the life of this
472  * process.
473  */
474 MOCK_IMPL(uint64_t,
476 {
477  return stats_n_bytes_written;
478 }
479 
480 /**
481  * Increment the amount of network traffic read and written, over the life of
482  * this process.
483  */
484 void
486 {
487  stats_n_bytes_read += r;
489 }
490 
491 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
492  * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
493  */
494 void
496 {
497  if (events & READ_EVENT)
499  else
501 
502  if (events & WRITE_EVENT)
504  else
506 }
507 
508 /** Return true iff <b>conn</b> is listening for read events. */
509 int
511 {
512  tor_assert(conn);
513 
514  return conn->reading_from_linked_conn ||
515  (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
516 }
517 
518 /** Reset our main loop counters. */
519 void
521 {
525 }
526 
527 /** Increment the main loop success counter. */
528 static void
530 {
532 }
533 
534 /** Get the main loop success counter. */
535 uint64_t
537 {
539 }
540 
541 /** Increment the main loop error counter. */
542 static void
544 {
546 }
547 
548 /** Get the main loop error counter. */
549 uint64_t
551 {
553 }
554 
555 /** Increment the main loop idle counter. */
556 static void
558 {
560 }
561 
562 /** Get the main loop idle counter. */
563 uint64_t
565 {
566  return stats_n_main_loop_idle;
567 }
568 
569 /** Check whether <b>conn</b> is correct in having (or not having) a
570  * read/write event (passed in <b>ev</b>). On success, return 0. On failure,
571  * log a warning and return -1. */
572 static int
573 connection_check_event(connection_t *conn, struct event *ev)
574 {
575  int bad;
576 
577  if (conn->type == CONN_TYPE_AP && TO_EDGE_CONN(conn)->is_dns_request) {
578  /* DNS requests which we launch through the dnsserv.c module do not have
579  * any underlying socket or any underlying linked connection, so they
580  * shouldn't have any attached events either.
581  */
582  bad = ev != NULL;
583  } else {
584  /* Everything else should have an underlying socket, or a linked
585  * connection (which is also tracked with a read_event/write_event pair).
586  */
587  bad = ev == NULL;
588  }
589 
590  if (bad) {
591  log_warn(LD_BUG, "Event missing on connection %p [%s;%s]. "
592  "socket=%d. linked=%d. "
593  "is_dns_request=%d. Marked_for_close=%s:%d",
594  conn,
595  conn_type_to_string(conn->type),
596  conn_state_to_string(conn->type, conn->state),
597  (int)conn->s, (int)conn->linked,
598  (conn->type == CONN_TYPE_AP &&
599  TO_EDGE_CONN(conn)->is_dns_request),
600  conn->marked_for_close_file ? conn->marked_for_close_file : "-",
601  conn->marked_for_close
602  );
603  log_backtrace(LOG_WARN, LD_BUG, "Backtrace attached.");
604  return -1;
605  }
606  return 0;
607 }
608 
609 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
610 MOCK_IMPL(void,
612 {
613  tor_assert(conn);
614 
615  if (connection_check_event(conn, conn->read_event) < 0) {
616  return;
617  }
618 
619  if (conn->linked) {
620  conn->reading_from_linked_conn = 0;
622  } else {
623  if (event_del(conn->read_event))
624  log_warn(LD_NET, "Error from libevent setting read event state for %d "
625  "to unwatched: %s",
626  (int)conn->s,
627  tor_socket_strerror(tor_socket_errno(conn->s)));
628  }
629 }
630 
631 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
632 MOCK_IMPL(void,
634 {
635  tor_assert(conn);
636 
637  if (connection_check_event(conn, conn->read_event) < 0) {
638  return;
639  }
640 
641  if (conn->linked) {
642  conn->reading_from_linked_conn = 1;
645  } else {
646  if (event_add(conn->read_event, NULL))
647  log_warn(LD_NET, "Error from libevent setting read event state for %d "
648  "to watched: %s",
649  (int)conn->s,
650  tor_socket_strerror(tor_socket_errno(conn->s)));
651  }
652 }
653 
654 /** Return true iff <b>conn</b> is listening for write events. */
655 int
657 {
658  tor_assert(conn);
659 
660  return conn->writing_to_linked_conn ||
661  (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
662 }
663 
664 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
665 MOCK_IMPL(void,
667 {
668  tor_assert(conn);
669 
670  if (connection_check_event(conn, conn->write_event) < 0) {
671  return;
672  }
673 
674  if (conn->linked) {
675  conn->writing_to_linked_conn = 0;
676  if (conn->linked_conn)
678  } else {
679  if (event_del(conn->write_event))
680  log_warn(LD_NET, "Error from libevent setting write event state for %d "
681  "to unwatched: %s",
682  (int)conn->s,
683  tor_socket_strerror(tor_socket_errno(conn->s)));
684  }
685 }
686 
687 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
688 MOCK_IMPL(void,
690 {
691  tor_assert(conn);
692 
693  if (connection_check_event(conn, conn->write_event) < 0) {
694  return;
695  }
696 
697  if (conn->linked) {
698  conn->writing_to_linked_conn = 1;
699  if (conn->linked_conn &&
702  } else {
703  if (event_add(conn->write_event, NULL))
704  log_warn(LD_NET, "Error from libevent setting write event state for %d "
705  "to watched: %s",
706  (int)conn->s,
707  tor_socket_strerror(tor_socket_errno(conn->s)));
708  }
709 }
710 
711 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
712  * linked to it would be good and feasible. (Reading is "feasible" if the
713  * other conn exists and has data in its outbuf, and is "good" if we have our
714  * reading_from_linked_conn flag set and the other conn has its
715  * writing_to_linked_conn flag set.)*/
716 static int
718 {
719  if (conn->linked && conn->reading_from_linked_conn) {
720  if (! conn->linked_conn ||
722  buf_datalen(conn->linked_conn->outbuf)))
723  return 1;
724  }
725  return 0;
726 }
727 
728 /** Event to run 'shutdown did not work callback'. */
729 static struct event *shutdown_did_not_work_event = NULL;
730 
731 /** Failsafe measure that should never actually be necessary: If
732  * tor_shutdown_event_loop_and_exit() somehow doesn't successfully exit the
733  * event loop, then this callback will kill Tor with an assertion failure
734  * seconds later
735  */
736 static void
737 shutdown_did_not_work_callback(evutil_socket_t fd, short event, void *arg)
738 {
739  // LCOV_EXCL_START
740  (void) fd;
741  (void) event;
742  (void) arg;
743  tor_assert_unreached();
744  // LCOV_EXCL_STOP
745 }
746 
747 #ifdef ENABLE_RESTART_DEBUGGING
748 static struct event *tor_shutdown_event_loop_for_restart_event = NULL;
749 static void
750 tor_shutdown_event_loop_for_restart_cb(
751  evutil_socket_t fd, short event, void *arg)
752 {
753  (void)fd;
754  (void)event;
755  (void)arg;
756  tor_event_free(tor_shutdown_event_loop_for_restart_event);
758 }
759 #endif /* defined(ENABLE_RESTART_DEBUGGING) */
760 
761 /**
762  * After finishing the current callback (if any), shut down the main loop,
763  * clean up the process, and exit with <b>exitcode</b>.
764  */
765 void
767 {
769  return; /* Ignore multiple calls to this function. */
770 
772  main_loop_exit_value = exitcode;
773 
774  if (! tor_libevent_is_initialized()) {
775  return; /* No event loop to shut down. */
776  }
777 
778  /* Die with an assertion failure in ten seconds, if for some reason we don't
779  * exit normally. */
780  /* XXXX We should consider this code if it's never used. */
781  struct timeval ten_seconds = { 10, 0 };
782  shutdown_did_not_work_event = tor_evtimer_new(
785  event_add(shutdown_did_not_work_event, &ten_seconds);
786 
787  /* Unlike exit_loop_after_delay(), exit_loop_after_callback
788  * prevents other callbacks from running. */
790 }
791 
792 /** Return true iff tor_shutdown_event_loop_and_exit() has been called. */
793 int
795 {
796  return main_loop_should_exit;
797 }
798 
799 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
800  * its linked connection, if it is not doing so already. Called by
801  * connection_start_reading and connection_start_writing as appropriate. */
802 static void
804 {
805  tor_assert(conn);
806  tor_assert(conn->linked == 1);
807 
808  if (!conn->active_on_link) {
809  conn->active_on_link = 1;
812  } else {
814  }
815 }
816 
817 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
818  * connection, if is currently doing so. Called by connection_stop_reading,
819  * connection_stop_writing, and connection_read. */
820 void
822 {
823  tor_assert(conn);
824  tor_assert(conn->linked == 1);
825 
826  if (conn->active_on_link) {
827  conn->active_on_link = 0;
828  /* FFFF We could keep an index here so we can smartlist_del
829  * cleanly. On the other hand, this doesn't show up on profiles,
830  * so let's leave it alone for now. */
832  } else {
834  }
835 }
836 
837 /** Close all connections that have been scheduled to get closed. */
838 STATIC void
840 {
841  int i;
842  for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
843  connection_t *conn = smartlist_get(closeable_connection_lst, i);
844  if (conn->conn_array_index < 0) {
845  connection_unlink(conn); /* blow it away right now */
846  } else {
848  ++i;
849  }
850  }
851 }
852 
853 /** Count moribund connections for the OOS handler */
854 MOCK_IMPL(int,
856 {
857  int moribund = 0;
858 
859  /*
860  * Count things we'll try to kill when close_closeable_connections()
861  * runs next.
862  */
864  if (SOCKET_OK(conn->s) && connection_is_moribund(conn)) ++moribund;
865  } SMARTLIST_FOREACH_END(conn);
866 
867  return moribund;
868 }
869 
870 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
871  * some data to read. */
872 static void
873 conn_read_callback(evutil_socket_t fd, short event, void *_conn)
874 {
875  connection_t *conn = _conn;
876  (void)fd;
877  (void)event;
878 
879  log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
880 
881  /* assert_connection_ok(conn, time(NULL)); */
882 
883  /* Handle marked for close connections early */
884  if (conn->marked_for_close && connection_is_reading(conn)) {
885  /* Libevent says we can read, but we are marked for close so we will never
886  * try to read again. We will try to close the connection below inside of
887  * close_closeable_connections(), but let's make sure not to cause Libevent
888  * to spin on conn_read_callback() while we wait for the socket to let us
889  * flush to it.*/
891  }
892 
893  if (connection_handle_read(conn) < 0) {
894  if (!conn->marked_for_close) {
895 #ifndef _WIN32
896  log_warn(LD_BUG,"Unhandled error on read for %s connection "
897  "(fd %d); removing",
898  conn_type_to_string(conn->type), (int)conn->s);
900 #endif /* !defined(_WIN32) */
901  if (CONN_IS_EDGE(conn))
903  connection_mark_for_close(conn);
904  }
905  }
906  assert_connection_ok(conn, time(NULL));
907 
908  if (smartlist_len(closeable_connection_lst))
910 }
911 
912 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
913  * some data to write. */
914 static void
915 conn_write_callback(evutil_socket_t fd, short events, void *_conn)
916 {
917  connection_t *conn = _conn;
918  (void)fd;
919  (void)events;
920 
921  LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
922  (int)conn->s));
923 
924  /* assert_connection_ok(conn, time(NULL)); */
925 
926  if (connection_handle_write(conn, 0) < 0) {
927  if (!conn->marked_for_close) {
928  /* this connection is broken. remove it. */
930  "unhandled error on write for %s connection (fd %d); removing",
931  conn_type_to_string(conn->type), (int)conn->s);
933  if (CONN_IS_EDGE(conn)) {
934  /* otherwise we cry wolf about duplicate close */
935  edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
936  if (!edge_conn->end_reason)
937  edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
938  edge_conn->edge_has_sent_end = 1;
939  }
940  connection_close_immediate(conn); /* So we don't try to flush. */
941  connection_mark_for_close(conn);
942  }
943  }
944  assert_connection_ok(conn, time(NULL));
945 
946  if (smartlist_len(closeable_connection_lst))
948 }
949 
950 /** If the connection at connection_array[i] is marked for close, then:
951  * - If it has data that it wants to flush, try to flush it.
952  * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
953  * true, then leave the connection open and return.
954  * - Otherwise, remove the connection from connection_array and from
955  * all other lists, close it, and free it.
956  * Returns 1 if the connection was closed, 0 otherwise.
957  */
958 static int
960 {
961  connection_t *conn;
962  int retval;
963  time_t now;
964 
965  conn = smartlist_get(connection_array, i);
966  if (!conn->marked_for_close)
967  return 0; /* nothing to see here, move along */
968  now = time(NULL);
969  assert_connection_ok(conn, now);
970 
971  log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
972  conn->s);
973 
974  /* If the connection we are about to close was trying to connect to
975  a proxy server and failed, the client won't be able to use that
976  proxy. We should warn the user about this. */
977  if (conn->proxy_state == PROXY_INFANT)
979 
980  if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
982  /* s == -1 means it's an incomplete edge connection, or that the socket
983  * has already been closed as unflushable. */
984  ssize_t sz = connection_bucket_write_limit(conn, now);
985  if (!conn->hold_open_until_flushed)
986  log_info(LD_NET,
987  "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
988  "to flush %"TOR_PRIuSZ" bytes. (Marked at %s:%d)",
990  (int)conn->s, conn_type_to_string(conn->type), conn->state,
991  connection_get_outbuf_len(conn),
993  if (conn->linked_conn) {
994  retval = (int) buf_move_all(conn->linked_conn->inbuf, conn->outbuf);
995  if (retval >= 0) {
996  /* The linked conn will notice that it has data when it notices that
997  * we're gone. */
999  }
1000  log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
1001  "%d left; wants-to-flush==%d", retval,
1002  (int)connection_get_outbuf_len(conn),
1004  } else if (connection_speaks_cells(conn)) {
1005  if (conn->state == OR_CONN_STATE_OPEN) {
1006  retval = buf_flush_to_tls(conn->outbuf, TO_OR_CONN(conn)->tls, sz);
1007  } else
1008  retval = -1; /* never flush non-open broken tls connections */
1009  } else {
1010  retval = buf_flush_to_socket(conn->outbuf, conn->s, sz);
1011  }
1012  if (retval >= 0 && /* Technically, we could survive things like
1013  TLS_WANT_WRITE here. But don't bother for now. */
1015  if (retval > 0) {
1016  LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
1017  "Holding conn (fd %d) open for more flushing.",
1018  (int)conn->s));
1019  conn->timestamp_last_write_allowed = now; /* reset so we can flush
1020  * more */
1021  } else if (sz == 0) {
1022  /* Also, retval==0. If we get here, we didn't want to write anything
1023  * (because of rate-limiting) and we didn't. */
1024 
1025  /* Connection must flush before closing, but it's being rate-limited.
1026  * Let's remove from Libevent, and mark it as blocked on bandwidth
1027  * so it will be re-added on next token bucket refill. Prevents
1028  * busy Libevent loops where we keep ending up here and returning
1029  * 0 until we are no longer blocked on bandwidth.
1030  */
1032  /* Make sure that consider_empty_buckets really disabled the
1033  * connection: */
1034  if (BUG(connection_is_writing(conn))) {
1035  connection_write_bw_exhausted(conn, true);
1036  }
1037 
1038  /* The connection is being held due to write rate limit and thus will
1039  * flush its data later. We need to stop reading because this
1040  * connection is about to be closed once flushed. It should not
1041  * process anything more coming in at this stage. */
1043  }
1044  return 0;
1045  }
1046  if (connection_wants_to_flush(conn)) {
1047  log_fn(LOG_INFO, LD_NET, "We stalled too much while trying to write %d "
1048  "bytes to address %s. If this happens a lot, either "
1049  "something is wrong with your network connection, or "
1050  "something is wrong with theirs. "
1051  "(fd %d, type %s, state %d, marked at %s:%d).",
1052  (int)connection_get_outbuf_len(conn),
1054  (int)conn->s, conn_type_to_string(conn->type), conn->state,
1055  conn->marked_for_close_file,
1056  conn->marked_for_close);
1057  }
1058  }
1059 
1060  connection_unlink(conn); /* unlink, remove, free */
1061  return 1;
1062 }
1063 
1064 /** Implementation for directory_all_unreachable. This is done in a callback,
1065  * since otherwise it would complicate Tor's control-flow graph beyond all
1066  * reason.
1067  */
1068 static void
1070 {
1071  (void)event;
1072  (void)arg;
1073 
1074  connection_t *conn;
1075 
1078  entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
1079  log_notice(LD_NET,
1080  "Is your network connection down? "
1081  "Failing connection to '%s:%d'.",
1082  safe_str_client(entry_conn->socks_request->address),
1083  entry_conn->socks_request->port);
1084  connection_mark_unattached_ap(entry_conn,
1086  }
1087  control_event_general_error("DIR_ALL_UNREACHABLE");
1088 }
1089 
1090 static mainloop_event_t *directory_all_unreachable_cb_event = NULL;
1091 
1092 /** We've just tried every dirserver we know about, and none of
1093  * them were reachable. Assume the network is down. Change state
1094  * so next time an application connection arrives we'll delay it
1095  * and try another directory fetch. Kill off all the circuit_wait
1096  * streams that are waiting now, since they will all timeout anyway.
1097  */
1098 void
1100 {
1101  (void)now;
1102 
1103  reset_uptime(); /* reset it */
1104 
1105  if (!directory_all_unreachable_cb_event) {
1106  directory_all_unreachable_cb_event =
1108  tor_assert(directory_all_unreachable_cb_event);
1109  }
1110 
1111  mainloop_event_activate(directory_all_unreachable_cb_event);
1112 }
1113 
1114 /** This function is called whenever we successfully pull down some new
1115  * network statuses or server descriptors. */
1116 void
1117 directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
1118 {
1119  const or_options_t *options = get_options();
1120 
1121  /* if we have enough dir info, then update our guard status with
1122  * whatever we just learned. */
1123  int invalidate_circs = guards_update_all();
1124 
1125  if (invalidate_circs) {
1128  }
1129 
1131  int quiet = suppress_logs || from_cache ||
1134  "I learned some more directory information, but not enough to "
1135  "build a circuit: %s", get_dir_info_status_string());
1137  return;
1138  } else {
1139  if (dirclient_fetches_from_authorities(options)) {
1141  }
1142 
1143  /* Don't even bother trying to get extrainfo until the rest of our
1144  * directory info is up-to-date */
1145  if (options->DownloadExtraInfo)
1147  }
1148 
1149  if (server_mode(options) && !net_is_disabled() && !from_cache &&
1152 }
1153 
1154 /** Perform regular maintenance tasks for a single connection. This
1155  * function gets run once per second per connection by run_scheduled_events.
1156  */
1157 static void
1159 {
1160  cell_t cell;
1161  connection_t *conn = smartlist_get(connection_array, i);
1162  const or_options_t *options = get_options();
1163  or_connection_t *or_conn;
1164  channel_t *chan = NULL;
1165  int have_any_circuits;
1166  int past_keepalive =
1167  now >= conn->timestamp_last_write_allowed + options->KeepalivePeriod;
1168 
1169  if (conn->outbuf && !connection_get_outbuf_len(conn) &&
1170  conn->type == CONN_TYPE_OR)
1171  TO_OR_CONN(conn)->timestamp_lastempty = now;
1172 
1173  if (conn->marked_for_close) {
1174  /* nothing to do here */
1175  return;
1176  }
1177 
1178  /* Expire any directory connections that haven't been active (sent
1179  * if a server or received if a client) for 5 min */
1180  if (conn->type == CONN_TYPE_DIR &&
1181  ((DIR_CONN_IS_SERVER(conn) &&
1183  + options->TestingDirConnectionMaxStall < now) ||
1184  (!DIR_CONN_IS_SERVER(conn) &&
1186  + options->TestingDirConnectionMaxStall < now))) {
1187  log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
1188  (int)conn->s, conn->purpose);
1189  /* This check is temporary; it's to let us know whether we should consider
1190  * parsing partial serverdesc responses. */
1191  if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
1192  connection_get_inbuf_len(conn) >= 1024) {
1193  log_info(LD_DIR,"Trying to extract information from wedged server desc "
1194  "download.");
1196  } else {
1197  connection_mark_for_close(conn);
1198  }
1199  return;
1200  }
1201 
1202  if (!connection_speaks_cells(conn))
1203  return; /* we're all done here, the rest is just for OR conns */
1204 
1205  /* If we haven't flushed to an OR connection for a while, then either nuke
1206  the connection or send a keepalive, depending. */
1207 
1208  or_conn = TO_OR_CONN(conn);
1209  tor_assert(conn->outbuf);
1210 
1211  chan = TLS_CHAN_TO_BASE(or_conn->chan);
1212  tor_assert(chan);
1213 
1214  if (channel_num_circuits(chan) != 0) {
1215  have_any_circuits = 1;
1216  chan->timestamp_last_had_circuits = now;
1217  } else {
1218  have_any_circuits = 0;
1219  }
1220 
1221  if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan)) &&
1222  ! have_any_circuits) {
1223  /* It's bad for new circuits, and has no unmarked circuits on it:
1224  * mark it now. */
1225  log_info(LD_OR,
1226  "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1227  (int)conn->s, conn->address, conn->port);
1228  if (conn->state == OR_CONN_STATE_CONNECTING)
1230  END_OR_CONN_REASON_TIMEOUT,
1231  "Tor gave up on the connection");
1233  } else if (!connection_state_is_open(conn)) {
1234  if (past_keepalive) {
1235  /* We never managed to actually get this connection open and happy. */
1236  log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
1237  (int)conn->s,conn->address, conn->port);
1239  }
1240  } else if (we_are_hibernating() &&
1241  ! have_any_circuits &&
1242  !connection_get_outbuf_len(conn)) {
1243  /* We're hibernating or shutting down, there's no circuits, and nothing to
1244  * flush.*/
1245  log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
1246  "[Hibernating or exiting].",
1247  (int)conn->s,conn->address, conn->port);
1249  } else if (!have_any_circuits &&
1250  now - or_conn->idle_timeout >=
1252  log_info(LD_OR,"Expiring non-used OR connection %"PRIu64" to fd %d "
1253  "(%s:%d) [no circuits for %d; timeout %d; %scanonical].",
1254  (chan->global_identifier),
1255  (int)conn->s, conn->address, conn->port,
1256  (int)(now - chan->timestamp_last_had_circuits),
1257  or_conn->idle_timeout,
1258  or_conn->is_canonical ? "" : "non");
1260  } else if (
1261  now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
1262  now >=
1263  conn->timestamp_last_write_allowed + options->KeepalivePeriod*10) {
1264  log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
1265  "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1266  "flush; %d seconds since last write)",
1267  (int)conn->s, conn->address, conn->port,
1268  (int)connection_get_outbuf_len(conn),
1269  (int)(now-conn->timestamp_last_write_allowed));
1271  } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
1272  /* send a padding cell */
1273  log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
1274  conn->address, conn->port);
1275  memset(&cell,0,sizeof(cell_t));
1276  cell.command = CELL_PADDING;
1277  connection_or_write_cell_to_buf(&cell, or_conn);
1278  } else {
1280  }
1281 }
1282 
1283 /** Honor a NEWNYM request: make future requests unlinkable to past
1284  * requests. */
1285 static void
1286 signewnym_impl(time_t now)
1287 {
1288  const or_options_t *options = get_options();
1289  if (!proxy_mode(options)) {
1290  log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
1291  "is disabled.");
1292  return;
1293  }
1294 
1298  time_of_last_signewnym = now;
1300 
1301  ++newnym_epoch;
1302 
1303  control_event_signal(SIGNEWNYM);
1304 }
1305 
1306 /** Callback: run a deferred signewnym. */
1307 static void
1309 {
1310  (void)event;
1311  (void)arg;
1312  log_info(LD_CONTROL, "Honoring delayed NEWNYM request");
1313  do_signewnym(time(NULL));
1314 }
1315 
1316 /** Either perform a signewnym or schedule one, depending on rate limiting. */
1317 void
1318 do_signewnym(time_t now)
1319 {
1321  const time_t delay_sec =
1323  if (! signewnym_is_pending) {
1328  }
1329  const struct timeval delay_tv = { delay_sec, 0 };
1331  }
1332  log_notice(LD_CONTROL,
1333  "Rate limiting NEWNYM request: delaying by %d second(s)",
1334  (int)(delay_sec));
1335  } else {
1336  signewnym_impl(now);
1337  }
1338 }
1339 
1340 /** Return the number of times that signewnym has been called. */
1341 unsigned
1343 {
1344  return newnym_epoch;
1345 }
1346 
1347 /** True iff we have initialized all the members of <b>periodic_events</b>.
1348  * Used to prevent double-initialization. */
1350 
1351 /* Declare all the timer callback functions... */
1352 #ifndef COCCI
1353 #undef CALLBACK
1354 #define CALLBACK(name) \
1355  static int name ## _callback(time_t, const or_options_t *)
1356 
1357 CALLBACK(add_entropy);
1358 CALLBACK(check_expired_networkstatus);
1359 CALLBACK(clean_caches);
1360 CALLBACK(clean_consdiffmgr);
1361 CALLBACK(fetch_networkstatus);
1362 CALLBACK(heartbeat);
1363 CALLBACK(hs_service);
1364 CALLBACK(launch_descriptor_fetches);
1365 CALLBACK(prune_old_routers);
1366 CALLBACK(record_bridge_stats);
1367 CALLBACK(rend_cache_failure_clean);
1368 CALLBACK(reset_padding_counts);
1369 CALLBACK(retry_listeners);
1370 CALLBACK(rotate_x509_certificate);
1371 CALLBACK(save_state);
1372 CALLBACK(write_stats_file);
1373 CALLBACK(control_per_second_events);
1374 CALLBACK(second_elapsed);
1375 
1376 #undef CALLBACK
1377 
1378 /* Now we declare an array of periodic_event_item_t for each periodic event */
1379 #define CALLBACK(name, r, f) \
1380  PERIODIC_EVENT(name, PERIODIC_EVENT_ROLE_ ## r, f)
1381 #define FL(name) (PERIODIC_EVENT_FLAG_ ## name)
1382 #endif /* !defined(COCCI) */
1383 
1384 STATIC periodic_event_item_t mainloop_periodic_events[] = {
1385 
1386  /* Everyone needs to run these. They need to have very long timeouts for
1387  * that to be safe. */
1388  CALLBACK(add_entropy, ALL, 0),
1389  CALLBACK(heartbeat, ALL, 0),
1390  CALLBACK(reset_padding_counts, ALL, 0),
1391 
1392  /* This is a legacy catch-all callback that runs once per second if
1393  * we are online and active. */
1394  CALLBACK(second_elapsed, NET_PARTICIPANT,
1395  FL(RUN_ON_DISABLE)),
1396 
1397  /* XXXX Do we have a reason to do this on a callback? Does it do any good at
1398  * all? For now, if we're dormant, we can let our listeners decay. */
1399  CALLBACK(retry_listeners, NET_PARTICIPANT, FL(NEED_NET)),
1400 
1401  /* We need to do these if we're participating in the Tor network. */
1402  CALLBACK(check_expired_networkstatus, NET_PARTICIPANT, 0),
1403  CALLBACK(fetch_networkstatus, NET_PARTICIPANT, 0),
1404  CALLBACK(launch_descriptor_fetches, NET_PARTICIPANT, FL(NEED_NET)),
1405  CALLBACK(rotate_x509_certificate, NET_PARTICIPANT, 0),
1406  CALLBACK(check_network_participation, NET_PARTICIPANT, 0),
1407 
1408  /* We need to do these if we're participating in the Tor network, and
1409  * immediately before we stop. */
1410  CALLBACK(clean_caches, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1411  CALLBACK(save_state, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1412  CALLBACK(write_stats_file, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1413  CALLBACK(prune_old_routers, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1414 
1415  /* Hidden Service service only. */
1416  CALLBACK(hs_service, HS_SERVICE, FL(NEED_NET)), // XXXX break this down more
1417 
1418  /* Bridge only. */
1419  CALLBACK(record_bridge_stats, BRIDGE, 0),
1420 
1421  /* Client only. */
1422  /* XXXX this could be restricted to CLIENT+NET_PARTICIPANT */
1423  CALLBACK(rend_cache_failure_clean, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1424 
1425  /* Directory server only. */
1426  CALLBACK(clean_consdiffmgr, DIRSERVER, 0),
1427 
1428  /* Controller with per-second events only. */
1429  CALLBACK(control_per_second_events, CONTROLEV, 0),
1430 
1431  END_OF_PERIODIC_EVENTS
1432 };
1433 #ifndef COCCI
1434 #undef CALLBACK
1435 #undef FL
1436 #endif
1437 
1438 /* These are pointers to members of periodic_events[] that are used to
1439  * implement particular callbacks. We keep them separate here so that we
1440  * can access them by name. We also keep them inside periodic_events[]
1441  * so that we can implement "reset all timers" in a reasonable way. */
1442 static periodic_event_item_t *fetch_networkstatus_event=NULL;
1443 static periodic_event_item_t *launch_descriptor_fetches_event=NULL;
1444 static periodic_event_item_t *check_dns_honesty_event=NULL;
1445 static periodic_event_item_t *save_state_event=NULL;
1446 static periodic_event_item_t *prune_old_routers_event=NULL;
1447 
1448 /** Reset all the periodic events so we'll do all our actions again as if we
1449  * just started up.
1450  * Useful if our clock just moved back a long time from the future,
1451  * so we don't wait until that future arrives again before acting.
1452  */
1453 void
1455 {
1457 }
1458 
1459 /** Return a bitmask of the roles this tor instance is configured for using
1460  * the given options. */
1461 STATIC int
1463 {
1464  tor_assert(options);
1465 
1466  int roles = PERIODIC_EVENT_ROLE_ALL;
1467  int is_bridge = options->BridgeRelay;
1468  int is_relay = server_mode(options);
1469  int is_dirauth = authdir_mode_v3(options);
1470  int is_bridgeauth = authdir_mode_bridge(options);
1471  int is_hidden_service = !!hs_service_get_num_services() ||
1472  !!rend_num_services();
1473  int is_dirserver = dir_server_mode(options);
1474  int sending_control_events = control_any_per_second_event_enabled();
1475 
1476  /* We also consider tor to have the role of a client if the ControlPort is
1477  * set because a lot of things can be done over the control port which
1478  * requires tor to have basic functionnalities. */
1479  int is_client = options_any_client_port_set(options) ||
1480  options->ControlPort_set ||
1481  options->OwningControllerFD != UINT64_MAX;
1482 
1483  int is_net_participant = is_participating_on_network() ||
1484  is_relay || is_hidden_service;
1485 
1486  if (is_bridge) roles |= PERIODIC_EVENT_ROLE_BRIDGE;
1487  if (is_client) roles |= PERIODIC_EVENT_ROLE_CLIENT;
1488  if (is_relay) roles |= PERIODIC_EVENT_ROLE_RELAY;
1489  if (is_dirauth) roles |= PERIODIC_EVENT_ROLE_DIRAUTH;
1490  if (is_bridgeauth) roles |= PERIODIC_EVENT_ROLE_BRIDGEAUTH;
1491  if (is_hidden_service) roles |= PERIODIC_EVENT_ROLE_HS_SERVICE;
1492  if (is_dirserver) roles |= PERIODIC_EVENT_ROLE_DIRSERVER;
1493  if (is_net_participant) roles |= PERIODIC_EVENT_ROLE_NET_PARTICIPANT;
1494  if (sending_control_events) roles |= PERIODIC_EVENT_ROLE_CONTROLEV;
1495 
1496  return roles;
1497 }
1498 
1499 /** Event to run initialize_periodic_events_cb */
1500 static struct event *initialize_periodic_events_event = NULL;
1501 
1502 /** Helper, run one second after setup:
1503  * Initializes all members of periodic_events and starts them running.
1504  *
1505  * (We do this one second after setup for backward-compatibility reasons;
1506  * it might not actually be necessary.) */
1507 static void
1508 initialize_periodic_events_cb(evutil_socket_t fd, short events, void *data)
1509 {
1510  (void) fd;
1511  (void) events;
1512  (void) data;
1513 
1514  tor_event_free(initialize_periodic_events_event);
1515 
1517 }
1518 
1519 /** Set up all the members of mainloop_periodic_events[], and configure them
1520  * all to be launched from a callback. */
1521 void
1523 {
1525  return;
1526 
1528 
1529  for (int i = 0; mainloop_periodic_events[i].name; ++i) {
1530  periodic_events_register(&mainloop_periodic_events[i]);
1531  }
1532 
1533  /* Set up all periodic events. We'll launch them by roles. */
1534 
1535 #ifndef COCCI
1536 #define NAMED_CALLBACK(name) \
1537  STMT_BEGIN name ## _event = periodic_events_find( #name ); STMT_END
1538 #endif
1539 
1540  NAMED_CALLBACK(prune_old_routers);
1541  NAMED_CALLBACK(fetch_networkstatus);
1542  NAMED_CALLBACK(launch_descriptor_fetches);
1543  NAMED_CALLBACK(check_dns_honesty);
1544  NAMED_CALLBACK(save_state);
1545 }
1546 
1547 STATIC void
1548 teardown_periodic_events(void)
1549 {
1551  fetch_networkstatus_event = NULL;
1552  launch_descriptor_fetches_event = NULL;
1553  check_dns_honesty_event = NULL;
1554  save_state_event = NULL;
1555  prune_old_routers_event = NULL;
1557 }
1558 
1559 static mainloop_event_t *rescan_periodic_events_ev = NULL;
1560 
1561 /** Callback: rescan the periodic event list. */
1562 static void
1564 {
1565  (void)event;
1566  (void)arg;
1568 }
1569 
1570 /**
1571  * Schedule an event that will rescan which periodic events should run.
1572  **/
1573 MOCK_IMPL(void,
1575 {
1576  if (!rescan_periodic_events_ev) {
1577  rescan_periodic_events_ev =
1579  }
1580  mainloop_event_activate(rescan_periodic_events_ev);
1581 }
1582 
1583 /** Do a pass at all our periodic events, disable those we don't need anymore
1584  * and enable those we need now using the given options. */
1585 void
1587 {
1588  tor_assert(options);
1589 
1591 }
1592 
1593 /* We just got new options globally set, see if we need to enabled or disable
1594  * periodic events. */
1595 void
1596 periodic_events_on_new_options(const or_options_t *options)
1597 {
1598  rescan_periodic_events(options);
1599 }
1600 
1601 /**
1602  * Update our schedule so that we'll check whether we need to fetch directory
1603  * info immediately.
1604  */
1605 void
1607 {
1608  tor_assert(fetch_networkstatus_event);
1609  tor_assert(launch_descriptor_fetches_event);
1610 
1611  periodic_event_reschedule(fetch_networkstatus_event);
1612  periodic_event_reschedule(launch_descriptor_fetches_event);
1613 }
1614 
1615 /** Mainloop callback: clean up circuits, channels, and connections
1616  * that are pending close. */
1617 static void
1619 {
1620  (void)ev;
1621  (void)arg;
1626 }
1627 
1628 /** Event to run postloop_cleanup_cb */
1630 
1631 /** Schedule a post-loop event to clean up marked channels, connections, and
1632  * circuits. */
1633 void
1635 {
1636  if (PREDICT_UNLIKELY(postloop_cleanup_ev == NULL)) {
1637  // (It's possible that we can get here if we decide to close a connection
1638  // in the earliest stages of our configuration, before we create events.)
1639  return;
1640  }
1642 }
1643 
1644 /** Event to run 'scheduled_shutdown_cb' */
1646 
1647 /** Callback: run a scheduled shutdown */
1648 static void
1650 {
1651  (void)ev;
1652  (void)arg;
1653  log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
1655 }
1656 
1657 /** Schedule the mainloop to exit after <b>delay_sec</b> seconds. */
1658 void
1660 {
1661  const struct timeval delay_tv = { delay_sec, 0 };
1662  if (! scheduled_shutdown_ev) {
1664  }
1666 }
1667 
1668 /** Perform regular maintenance tasks. This function gets run once per
1669  * second.
1670  */
1671 static int
1672 second_elapsed_callback(time_t now, const or_options_t *options)
1673 {
1674  /* 0. See if our bandwidth limits are exhausted and we should hibernate
1675  *
1676  * Note: we have redundant mechanisms to handle the case where it's
1677  * time to wake up from hibernation; or where we have a scheduled
1678  * shutdown and it's time to run it, but this will also handle those.
1679  */
1680  consider_hibernation(now);
1681 
1682  /* Maybe enough time elapsed for us to reconsider a circuit. */
1684 
1685  if (options->UseBridges && !net_is_disabled()) {
1686  /* Note: this check uses net_is_disabled(), not should_delay_dir_fetches()
1687  * -- the latter is only for fetching consensus-derived directory info. */
1688  // TODO: client
1689  // Also, schedule this rather than probing 1x / sec
1690  fetch_bridge_descriptors(options, now);
1691  }
1692 
1693  if (accounting_is_enabled(options)) {
1694  // TODO: refactor or rewrite?
1696  }
1697 
1698  /* 3a. Every second, we examine pending circuits and prune the
1699  * ones which have been pending for more than a few seconds.
1700  * We do this before step 4, so it can try building more if
1701  * it's not comfortable with the number of available circuits.
1702  */
1703  /* (If our circuit build timeout can ever become lower than a second (which
1704  * it can't, currently), we should do this more often.) */
1705  // TODO: All expire stuff can become NET_PARTICIPANT, RUN_ON_DISABLE
1708 
1709  /* 3b. Also look at pending streams and prune the ones that 'began'
1710  * a long time ago but haven't gotten a 'connected' yet.
1711  * Do this before step 4, so we can put them back into pending
1712  * state to be picked up by the new circuit.
1713  */
1715 
1716  /* 3c. And expire connections that we've held open for too long.
1717  */
1719 
1720  /* 4. Every second, we try a new circuit if there are no valid
1721  * circuits. Every NewCircuitPeriod seconds, we expire circuits
1722  * that became dirty more than MaxCircuitDirtiness seconds ago,
1723  * and we make a new circ if there are no clean circuits.
1724  */
1725  const int have_dir_info = router_have_minimum_dir_info();
1726  if (have_dir_info && !net_is_disabled()) {
1728  } else {
1730  }
1731 
1732  /* 5. We do housekeeping for each connection... */
1734  int i;
1735  for (i=0;i<smartlist_len(connection_array);i++) {
1737  }
1738 
1739  /* Run again in a second. */
1740  return 1;
1741 }
1742 
1743 /**
1744  * Periodic callback: Every {LAZY,GREEDY}_DESCRIPTOR_RETRY_INTERVAL,
1745  * see about fetching descriptors, microdescriptors, and extrainfo
1746  * documents.
1747  */
1748 static int
1750 {
1751  if (should_delay_dir_fetches(options, NULL))
1752  return PERIODIC_EVENT_NO_UPDATE;
1753 
1758  else
1760 }
1761 
1762 /**
1763  * Periodic event: Rotate our X.509 certificates and TLS keys once every
1764  * MAX_SSL_KEY_LIFETIME_INTERNAL.
1765  */
1766 static int
1768 {
1769  static int first = 1;
1770  (void)now;
1771  (void)options;
1772  if (first) {
1773  first = 0;
1775  }
1776 
1777  /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1778  * TLS context. */
1779  log_info(LD_GENERAL,"Rotating tls context.");
1780  if (router_initialize_tls_context() < 0) {
1781  log_err(LD_BUG, "Error reinitializing TLS context");
1782  tor_assert_unreached();
1783  }
1784  if (generate_ed_link_cert(options, now, 1)) {
1785  log_err(LD_OR, "Unable to update Ed25519->TLS link certificate for "
1786  "new TLS context.");
1787  tor_assert_unreached();
1788  }
1789 
1790  /* We also make sure to rotate the TLS connections themselves if they've
1791  * been up for too long -- but that's done via is_bad_for_new_circs in
1792  * run_connection_housekeeping() above. */
1794 }
1795 
1796 /**
1797  * Periodic callback: once an hour, grab some more entropy from the
1798  * kernel and feed it to our CSPRNG.
1799  **/
1800 static int
1801 add_entropy_callback(time_t now, const or_options_t *options)
1802 {
1803  (void)now;
1804  (void)options;
1805  /* We already seeded once, so don't die on failure. */
1806  if (crypto_seed_rng() < 0) {
1807  log_warn(LD_GENERAL, "Tried to re-seed RNG, but failed. We already "
1808  "seeded once, though, so we won't exit here.");
1809  }
1810 
1811  /** How often do we add more entropy to OpenSSL's RNG pool? */
1812 #define ENTROPY_INTERVAL (60*60)
1813  return ENTROPY_INTERVAL;
1814 }
1815 
1816 /** Periodic callback: if there has been no network usage in a while,
1817  * enter a dormant state. */
1818 STATIC int
1820 {
1821  /* If we're a server, we can't become dormant. */
1822  if (server_mode(options)) {
1823  goto found_activity;
1824  }
1825 
1826  /* If we're running an onion service, we can't become dormant. */
1827  /* XXXX this would be nice to change, so that we can be dormant with a
1828  * service. */
1830  goto found_activity;
1831  }
1832 
1833  /* If we have any currently open entry streams other than "linked"
1834  * connections used for directory requests, those count as user activity.
1835  */
1836  if (options->DormantTimeoutDisabledByIdleStreams) {
1838  goto found_activity;
1839  }
1840  }
1841 
1842  /* XXXX Make this configurable? */
1843 /** How often do we check whether we have had network activity? */
1844 #define CHECK_PARTICIPATION_INTERVAL (5*60)
1845 
1846  /* Become dormant if there has been no user activity in a long time.
1847  * (The funny checks below are in order to prevent overflow.) */
1848  time_t time_since_last_activity = 0;
1849  if (get_last_user_activity_time() < now)
1850  time_since_last_activity = now - get_last_user_activity_time();
1851  if (time_since_last_activity >= options->DormantClientTimeout) {
1852  log_notice(LD_GENERAL, "No user activity in a long time: becoming"
1853  " dormant.");
1855  rescan_periodic_events(options);
1856  }
1857 
1858  return CHECK_PARTICIPATION_INTERVAL;
1859 
1860  found_activity:
1861  note_user_activity(now);
1862  return CHECK_PARTICIPATION_INTERVAL;
1863 }
1864 
1865 /**
1866  * Periodic callback: If our consensus is too old, recalculate whether
1867  * we can actually use it.
1868  */
1869 static int
1871 {
1872  (void)options;
1873  /* Check whether our networkstatus has expired. */
1875  /* Use reasonably live consensuses until they are no longer reasonably live.
1876  */
1877  if (ns && !networkstatus_consensus_reasonably_live(ns, now) &&
1880  }
1881 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1882  return CHECK_EXPIRED_NS_INTERVAL;
1883 }
1884 
1885 /**
1886  * Scheduled callback: Save the state file to disk if appropriate.
1887  */
1888 static int
1889 save_state_callback(time_t now, const or_options_t *options)
1890 {
1891  (void) options;
1892  (void) or_state_save(now); // only saves if appropriate
1893  const time_t next_write = get_or_state()->next_write;
1894  if (next_write == TIME_MAX) {
1895  return 86400;
1896  }
1897  return safe_timer_diff(now, next_write);
1898 }
1899 
1900 /** Reschedule the event for saving the state file.
1901  *
1902  * Run this when the state becomes dirty. */
1903 void
1905 {
1906  if (save_state_event == NULL) {
1907  /* This can happen early on during startup. */
1908  return;
1909  }
1910  periodic_event_reschedule(save_state_event);
1911 }
1912 
1913 /**
1914  * Periodic callback: Write statistics to disk if appropriate.
1915  */
1916 static int
1917 write_stats_file_callback(time_t now, const or_options_t *options)
1918 {
1919  /* 1g. Check whether we should write statistics to disk.
1920  */
1921 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1922  time_t next_time_to_write_stats_files = now + CHECK_WRITE_STATS_INTERVAL;
1923  if (options->CellStatistics) {
1924  time_t next_write =
1926  if (next_write && next_write < next_time_to_write_stats_files)
1927  next_time_to_write_stats_files = next_write;
1928  }
1929  if (options->DirReqStatistics) {
1930  time_t next_write = geoip_dirreq_stats_write(now);
1931  if (next_write && next_write < next_time_to_write_stats_files)
1932  next_time_to_write_stats_files = next_write;
1933  }
1934  if (options->EntryStatistics) {
1935  time_t next_write = geoip_entry_stats_write(now);
1936  if (next_write && next_write < next_time_to_write_stats_files)
1937  next_time_to_write_stats_files = next_write;
1938  }
1939  if (options->HiddenServiceStatistics) {
1940  time_t next_write = rep_hist_hs_stats_write(now);
1941  if (next_write && next_write < next_time_to_write_stats_files)
1942  next_time_to_write_stats_files = next_write;
1943  }
1944  if (options->ExitPortStatistics) {
1945  time_t next_write = rep_hist_exit_stats_write(now);
1946  if (next_write && next_write < next_time_to_write_stats_files)
1947  next_time_to_write_stats_files = next_write;
1948  }
1949  if (options->ConnDirectionStatistics) {
1950  time_t next_write = conn_stats_save(now);
1951  if (next_write && next_write < next_time_to_write_stats_files)
1952  next_time_to_write_stats_files = next_write;
1953  }
1954  if (options->BridgeAuthoritativeDir) {
1955  time_t next_write = rep_hist_desc_stats_write(now);
1956  if (next_write && next_write < next_time_to_write_stats_files)
1957  next_time_to_write_stats_files = next_write;
1958  }
1959 
1960  return safe_timer_diff(now, next_time_to_write_stats_files);
1961 }
1962 
1963 static int
1964 reset_padding_counts_callback(time_t now, const or_options_t *options)
1965 {
1966  if (options->PaddingStatistics) {
1967  rep_hist_prep_published_padding_counts(now);
1968  }
1969 
1972 }
1973 
1974 static int should_init_bridge_stats = 1;
1975 
1976 /**
1977  * Periodic callback: Write bridge statistics to disk if appropriate.
1978  */
1979 static int
1980 record_bridge_stats_callback(time_t now, const or_options_t *options)
1981 {
1982  /* 1h. Check whether we should write bridge statistics to disk.
1983  */
1984  if (should_record_bridge_info(options)) {
1985  if (should_init_bridge_stats) {
1986  /* (Re-)initialize bridge statistics. */
1988  should_init_bridge_stats = 0;
1989  return WRITE_STATS_INTERVAL;
1990  } else {
1991  /* Possibly write bridge statistics to disk and ask when to write
1992  * them next time. */
1993  time_t next = geoip_bridge_stats_write(now);
1994  return safe_timer_diff(now, next);
1995  }
1996  } else if (!should_init_bridge_stats) {
1997  /* Bridge mode was turned off. Ensure that stats are re-initialized
1998  * next time bridge mode is turned on. */
1999  should_init_bridge_stats = 1;
2000  }
2001  return PERIODIC_EVENT_NO_UPDATE;
2002 }
2003 
2004 /**
2005  * Periodic callback: Clean in-memory caches every once in a while
2006  */
2007 static int
2008 clean_caches_callback(time_t now, const or_options_t *options)
2009 {
2010  /* Remove old information from rephist and the rend cache. */
2011  rep_history_clean(now - options->RephistTrackTime);
2012  rend_cache_clean(now, REND_CACHE_TYPE_SERVICE);
2014  hs_cache_clean_as_dir(now);
2015  microdesc_cache_rebuild(NULL, 0);
2016 #define CLEAN_CACHES_INTERVAL (30*60)
2017  return CLEAN_CACHES_INTERVAL;
2018 }
2019 
2020 /**
2021  * Periodic callback: Clean the cache of failed hidden service lookups
2022  * frequently.
2023  */
2024 static int
2026 {
2027  (void)options;
2028  /* We don't keep entries that are more than five minutes old so we try to
2029  * clean it as soon as we can since we want to make sure the client waits
2030  * as little as possible for reachability reasons. */
2033  return 30;
2034 }
2035 
2036 /**
2037  * Periodic callback: prune routerlist of old information about Tor network.
2038  */
2039 static int
2040 prune_old_routers_callback(time_t now, const or_options_t *options)
2041 {
2042 #define ROUTERLIST_PRUNING_INTERVAL (60*60) // 1 hour.
2043  (void)now;
2044  (void)options;
2045 
2046  if (!net_is_disabled()) {
2047  /* If any networkstatus documents are no longer recent, we need to
2048  * update all the descriptors' running status. */
2049  /* Remove dead routers. */
2050  log_debug(LD_GENERAL, "Pruning routerlist...");
2052  }
2053 
2054  return ROUTERLIST_PRUNING_INTERVAL;
2055 }
2056 
2057 /**
2058  * Periodic event: once a minute, (or every second if TestingTorNetwork, or
2059  * during client bootstrap), check whether we want to download any
2060  * networkstatus documents. */
2061 static int
2062 fetch_networkstatus_callback(time_t now, const or_options_t *options)
2063 {
2064  /* How often do we check whether we should download network status
2065  * documents? */
2066  const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
2067  now);
2068  const int prefer_mirrors = !dirclient_fetches_from_authorities(
2069  get_options());
2070  int networkstatus_dl_check_interval = 60;
2071  /* check more often when testing, or when bootstrapping from mirrors
2072  * (connection limits prevent too many connections being made) */
2073  if (options->TestingTorNetwork
2074  || (we_are_bootstrapping && prefer_mirrors)) {
2075  networkstatus_dl_check_interval = 1;
2076  }
2077 
2078  if (should_delay_dir_fetches(options, NULL))
2079  return PERIODIC_EVENT_NO_UPDATE;
2080 
2082  return networkstatus_dl_check_interval;
2083 }
2084 
2085 /**
2086  * Periodic callback: Every 60 seconds, we relaunch listeners if any died. */
2087 static int
2088 retry_listeners_callback(time_t now, const or_options_t *options)
2089 {
2090  (void)now;
2091  (void)options;
2092  if (!net_is_disabled()) {
2093  retry_all_listeners(NULL, 0);
2094  return 60;
2095  }
2096  return PERIODIC_EVENT_NO_UPDATE;
2097 }
2098 
2099 static int heartbeat_callback_first_time = 1;
2100 
2101 /**
2102  * Periodic callback: write the heartbeat message in the logs.
2103  *
2104  * If writing the heartbeat message to the logs fails for some reason, retry
2105  * again after <b>MIN_HEARTBEAT_PERIOD</b> seconds.
2106  */
2107 static int
2108 heartbeat_callback(time_t now, const or_options_t *options)
2109 {
2110  /* Check if heartbeat is disabled */
2111  if (!options->HeartbeatPeriod) {
2112  return PERIODIC_EVENT_NO_UPDATE;
2113  }
2114 
2115  /* Skip the first one. */
2116  if (heartbeat_callback_first_time) {
2117  heartbeat_callback_first_time = 0;
2118  return options->HeartbeatPeriod;
2119  }
2120 
2121  /* Write the heartbeat message */
2122  if (log_heartbeat(now) == 0) {
2123  return options->HeartbeatPeriod;
2124  } else {
2125  /* If we couldn't write the heartbeat log message, try again in the minimum
2126  * interval of time. */
2127  return MIN_HEARTBEAT_PERIOD;
2128  }
2129 }
2130 
2131 #define CDM_CLEAN_CALLBACK_INTERVAL 600
2132 static int
2133 clean_consdiffmgr_callback(time_t now, const or_options_t *options)
2134 {
2135  (void)now;
2136  if (dir_server_mode(options)) {
2138  }
2139  return CDM_CLEAN_CALLBACK_INTERVAL;
2140 }
2141 
2142 /*
2143  * Periodic callback: Run scheduled events for HS service. This is called
2144  * every second.
2145  */
2146 static int
2147 hs_service_callback(time_t now, const or_options_t *options)
2148 {
2149  (void) options;
2150 
2151  /* We need to at least be able to build circuits and that we actually have
2152  * a working network. */
2154  networkstatus_get_live_consensus(now) == NULL) {
2155  goto end;
2156  }
2157 
2159 
2160  end:
2161  /* Every 1 second. */
2162  return 1;
2163 }
2164 
2165 /*
2166  * Periodic callback: Send once-per-second events to the controller(s).
2167  * This is called every second.
2168  */
2169 static int
2170 control_per_second_events_callback(time_t now, const or_options_t *options)
2171 {
2172  (void) options;
2173  (void) now;
2174 
2176 
2177  return 1;
2178 }
2179 
2180 /** Last time that update_current_time was called. */
2181 static time_t current_second = 0;
2182 /** Last time that update_current_time updated current_second. */
2183 static monotime_coarse_t current_second_last_changed;
2184 
2185 /**
2186  * Set the current time to "now", which should be the value returned by
2187  * time(). Check for clock jumps and track the total number of seconds we
2188  * have been running.
2189  */
2190 void
2192 {
2193  if (PREDICT_LIKELY(now == current_second)) {
2194  /* We call this function a lot. Most frequently, the current second
2195  * will not have changed, so we just return. */
2196  return;
2197  }
2198 
2199  const time_t seconds_elapsed = current_second ? (now - current_second) : 0;
2200 
2201  /* Check the wall clock against the monotonic clock, so we can
2202  * better tell idleness from clock jumps and/or other shenanigans. */
2203  monotime_coarse_t last_updated;
2204  memcpy(&last_updated, &current_second_last_changed, sizeof(last_updated));
2205  monotime_coarse_get(&current_second_last_changed);
2206 
2207  /** How much clock jumping means that we should adjust our idea of when
2208  * to go dormant? */
2209 #define NUM_JUMPED_SECONDS_BEFORE_NETSTATUS_UPDATE 20
2210 
2211  /* Don't go dormant early or late just because we jumped in time. */
2212  if (ABS(seconds_elapsed) >= NUM_JUMPED_SECONDS_BEFORE_NETSTATUS_UPDATE) {
2214  netstatus_note_clock_jumped(seconds_elapsed);
2215  }
2216  }
2217 
2218  /** How much clock jumping do we tolerate? */
2219 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
2220 
2221  /** How much idleness do we tolerate? */
2222 #define NUM_IDLE_SECONDS_BEFORE_WARN 3600
2223 
2224  if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN) {
2225  // moving back in time is always a bad sign.
2226  circuit_note_clock_jumped(seconds_elapsed, false);
2227 
2228  } else if (seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
2229  /* Compare the monotonic clock to the result of time(). */
2230  const int32_t monotime_msec_passed =
2231  monotime_coarse_diff_msec32(&last_updated,
2233  const int monotime_sec_passed = monotime_msec_passed / 1000;
2234  const int discrepancy = monotime_sec_passed - (int)seconds_elapsed;
2235  /* If the monotonic clock deviates from time(NULL), we have a couple of
2236  * possibilities. On some systems, this means we have been suspended or
2237  * sleeping. Everywhere, it can mean that the wall-clock time has
2238  * been changed -- for example, with settimeofday().
2239  *
2240  * On the other hand, if the monotonic time matches with the wall-clock
2241  * time, we've probably just been idle for a while, with no events firing.
2242  * we tolerate much more of that.
2243  */
2244  const bool clock_jumped = abs(discrepancy) > 2;
2245 
2246  if (clock_jumped || seconds_elapsed >= NUM_IDLE_SECONDS_BEFORE_WARN) {
2247  circuit_note_clock_jumped(seconds_elapsed, ! clock_jumped);
2248  }
2249  } else if (seconds_elapsed > 0) {
2250  stats_n_seconds_working += seconds_elapsed;
2251  }
2252 
2253  update_approx_time(now);
2254  current_second = now;
2255 }
2256 
2257 #ifdef HAVE_SYSTEMD_209
2258 static periodic_timer_t *systemd_watchdog_timer = NULL;
2259 
2260 /** Libevent callback: invoked to reset systemd watchdog. */
2261 static void
2262 systemd_watchdog_callback(periodic_timer_t *timer, void *arg)
2263 {
2264  (void)timer;
2265  (void)arg;
2266  sd_notify(0, "WATCHDOG=1");
2267 }
2268 #endif /* defined(HAVE_SYSTEMD_209) */
2269 
2270 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
2271 
2272 /** Called when our IP address seems to have changed. <b>on_client_conn</b>
2273  * should be true if:
2274  * - we detected a change in our interface address, using an outbound
2275  * connection, and therefore
2276  * - our client TLS keys need to be rotated.
2277  * Otherwise, it should be false, and:
2278  * - we detected a change in our published address
2279  * (using some other method), and therefore
2280  * - the published addresses in our descriptor need to change.
2281  */
2282 void
2283 ip_address_changed(int on_client_conn)
2284 {
2285  const or_options_t *options = get_options();
2286  int server = server_mode(options);
2287 
2288  if (on_client_conn) {
2289  if (! server) {
2290  /* Okay, change our keys. */
2291  if (init_keys_client() < 0)
2292  log_warn(LD_GENERAL, "Unable to rotate keys after IP change!");
2293  }
2294  } else {
2295  if (server) {
2296  if (get_uptime() > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
2298  reset_uptime();
2300  /* All relays include their IP addresses as their ORPort addresses in
2301  * their descriptor.
2302  * Exit relays also incorporate interface addresses in their exit
2303  * policies, when ExitPolicyRejectLocalInterfaces is set. */
2304  mark_my_descriptor_dirty("IP address changed");
2305  }
2306  }
2307 
2309 }
2310 
2311 /** Forget what we've learned about the correctness of our DNS servers, and
2312  * start learning again. */
2313 void
2315 {
2316  if (server_mode(get_options())) {
2318  if (check_dns_honesty_event) {
2319  periodic_event_reschedule(check_dns_honesty_event);
2320  }
2321  }
2322 }
2323 
2324 /** Initialize some mainloop_event_t objects that we require. */
2325 void
2327 {
2331  }
2332  if (!postloop_cleanup_ev) {
2335  }
2336 }
2337 
2338 /** Tor main loop. */
2339 int
2341 {
2342  /* initialize the periodic events first, so that code that depends on the
2343  * events being present does not assert.
2344  */
2347 
2349 
2350  struct timeval one_second = { 1, 0 };
2351  initialize_periodic_events_event = tor_evtimer_new(
2354  event_add(initialize_periodic_events_event, &one_second);
2355 
2356 #ifdef HAVE_SYSTEMD_209
2357  uint64_t watchdog_delay;
2358  /* set up systemd watchdog notification. */
2359  if (sd_watchdog_enabled(1, &watchdog_delay) > 0) {
2360  if (! systemd_watchdog_timer) {
2361  struct timeval watchdog;
2362  /* The manager will "act on" us if we don't send them a notification
2363  * every 'watchdog_delay' microseconds. So, send notifications twice
2364  * that often. */
2365  watchdog_delay /= 2;
2366  watchdog.tv_sec = watchdog_delay / 1000000;
2367  watchdog.tv_usec = watchdog_delay % 1000000;
2368 
2369  systemd_watchdog_timer = periodic_timer_new(tor_libevent_get_base(),
2370  &watchdog,
2371  systemd_watchdog_callback,
2372  NULL);
2373  tor_assert(systemd_watchdog_timer);
2374  }
2375  }
2376 #endif /* defined(HAVE_SYSTEMD_209) */
2377 #ifdef ENABLE_RESTART_DEBUGGING
2378  {
2379  static int first_time = 1;
2380 
2381  if (first_time && getenv("TOR_DEBUG_RESTART")) {
2382  first_time = 0;
2383  const char *sec_str = getenv("TOR_DEBUG_RESTART_AFTER_SECONDS");
2384  long sec;
2385  int sec_ok=0;
2386  if (sec_str &&
2387  (sec = tor_parse_long(sec_str, 10, 0, INT_MAX, &sec_ok, NULL)) &&
2388  sec_ok) {
2389  /* Okay, we parsed the seconds. */
2390  } else {
2391  sec = 5;
2392  }
2393  struct timeval restart_after = { (time_t) sec, 0 };
2394  tor_shutdown_event_loop_for_restart_event =
2395  tor_evtimer_new(tor_libevent_get_base(),
2396  tor_shutdown_event_loop_for_restart_cb, NULL);
2397  event_add(tor_shutdown_event_loop_for_restart_event, &restart_after);
2398  }
2399  }
2400 #endif /* defined(ENABLE_RESTART_DEBUGGING) */
2401 
2402  return run_main_loop_until_done();
2403 }
2404 
2405 #ifndef _WIN32
2406 /** Rate-limiter for EINVAL-type libevent warnings. */
2407 static ratelim_t libevent_error_ratelim = RATELIM_INIT(10);
2408 #endif
2409 
2410 /**
2411  * Run the main loop a single time. Return 0 for "exit"; -1 for "exit with
2412  * error", and 1 for "run this again."
2413  */
2414 static int
2416 {
2417  int loop_result;
2418 
2419  if (nt_service_is_stopping())
2420  return 0;
2421 
2423  return 0;
2424 
2425 #ifndef _WIN32
2426  /* Make it easier to tell whether libevent failure is our fault or not. */
2427  errno = 0;
2428 #endif
2429 
2430  if (get_options()->MainloopStats) {
2431  /* We always enforce that EVLOOP_ONCE is passed to event_base_loop() if we
2432  * are collecting main loop statistics. */
2433  called_loop_once = 1;
2434  } else {
2435  called_loop_once = 0;
2436  }
2437 
2438  /* Make sure we know (about) what time it is. */
2439  update_approx_time(time(NULL));
2440 
2441  /* Here it is: the main loop. Here we tell Libevent to poll until we have
2442  * an event, or the second ends, or until we have some active linked
2443  * connections to trigger events for. Libevent will wait till one
2444  * of these happens, then run all the appropriate callbacks. */
2447 
2448  if (get_options()->MainloopStats) {
2449  /* Update our main loop counters. */
2450  if (loop_result == 0) {
2451  // The call was successful.
2453  } else if (loop_result == -1) {
2454  // The call was erroneous.
2456  } else if (loop_result == 1) {
2457  // The call didn't have any active or pending events
2458  // to handle.
2460  }
2461  }
2462 
2463  /* Oh, the loop failed. That might be an error that we need to
2464  * catch, but more likely, it's just an interrupted poll() call or something,
2465  * and we should try again. */
2466  if (loop_result < 0) {
2467  int e = tor_socket_errno(-1);
2468  /* let the program survive things like ^z */
2469  if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
2470  log_err(LD_NET,"libevent call with %s failed: %s [%d]",
2471  tor_libevent_get_method(), tor_socket_strerror(e), e);
2472  return -1;
2473 #ifndef _WIN32
2474  } else if (e == EINVAL) {
2476  "EINVAL from libevent: should you upgrade libevent?");
2477  if (libevent_error_ratelim.n_calls_since_last_time > 8) {
2478  log_err(LD_NET, "Too many libevent errors, too fast: dying");
2479  return -1;
2480  }
2481 #endif /* !defined(_WIN32) */
2482  } else {
2483  tor_assert_nonfatal_once(! ERRNO_IS_EINPROGRESS(e));
2484  log_debug(LD_NET,"libevent call interrupted.");
2485  /* You can't trust the results of this poll(). Go back to the
2486  * top of the big for loop. */
2487  return 1;
2488  }
2489  }
2490 
2492  return 0;
2493 
2494  return 1;
2495 }
2496 
2497 /** Run the run_main_loop_once() function until it declares itself done,
2498  * and return its final return value.
2499  *
2500  * Shadow won't invoke this function, so don't fill it up with things.
2501  */
2502 STATIC int
2504 {
2505  int loop_result = 1;
2506 
2509 
2510  do {
2511  loop_result = run_main_loop_once();
2512  } while (loop_result == 1);
2513 
2515  return main_loop_exit_value;
2516  else
2517  return loop_result;
2518 }
2519 
2520 /** Returns Tor's uptime. */
2521 MOCK_IMPL(long,
2522 get_uptime,(void))
2523 {
2524  return stats_n_seconds_working;
2525 }
2526 
2527 /** Reset Tor's uptime. */
2528 MOCK_IMPL(void,
2530 {
2532 }
2533 
2534 void
2535 tor_mainloop_free_all(void)
2536 {
2537  smartlist_free(connection_array);
2538  smartlist_free(closeable_connection_lst);
2539  smartlist_free(active_linked_connection_lst);
2540  teardown_periodic_events();
2541  tor_event_free(shutdown_did_not_work_event);
2542  tor_event_free(initialize_periodic_events_event);
2543  mainloop_event_free(directory_all_unreachable_cb_event);
2544  mainloop_event_free(schedule_active_linked_connections_event);
2545  mainloop_event_free(postloop_cleanup_ev);
2546  mainloop_event_free(handle_deferred_signewnym_ev);
2547  mainloop_event_free(scheduled_shutdown_ev);
2548  mainloop_event_free(rescan_periodic_events_ev);
2549 
2550 #ifdef HAVE_SYSTEMD_209
2551  periodic_timer_free(systemd_watchdog_timer);
2552 #endif
2553 
2555 
2556  memset(&global_bucket, 0, sizeof(global_bucket));
2557  memset(&global_relayed_bucket, 0, sizeof(global_relayed_bucket));
2561  newnym_epoch = 0;
2562  called_loop_once = 0;
2566  quiet_level = 0;
2567  should_init_bridge_stats = 1;
2568  heartbeat_callback_first_time = 1;
2569  current_second = 0;
2570  memset(&current_second_last_changed, 0,
2571  sizeof(current_second_last_changed));
2572 }
retry_listeners_callback
static int retry_listeners_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2088
log_fn
#define log_fn(severity, domain, args,...)
Definition: log.h:287
connection_remove
int connection_remove(connection_t *conn)
Definition: mainloop.c:299
increment_main_loop_success_count
static void increment_main_loop_success_count(void)
Definition: mainloop.c:529
selftest.h
Header file for selftest.c.
routermode.h
Header file for routermode.c.
net_is_disabled
int net_is_disabled(void)
Definition: netstatus.c:25
tor_free
#define tor_free(p)
Definition: malloc.h:52
tor_libevent_get_method
const char * tor_libevent_get_method(void)
Definition: compat_libevent.c:204
authdir_mode_bridge
int authdir_mode_bridge(const or_options_t *options)
Definition: authmode.c:76
connection_edge.h
Header file for connection_edge.c.
connection_stop_writing
void connection_stop_writing(connection_t *conn)
Definition: mainloop.c:666
hs_service.h
Header file containing service data for the HS subsytem.
LOG_DEBUG
#define LOG_DEBUG
Definition: log.h:42
periodic_event_reschedule
void periodic_event_reschedule(periodic_event_item_t *event)
Definition: periodic.c:106
tor_init_connection_lists
void tor_init_connection_lists(void)
Definition: mainloop.c:414
stats_n_bytes_read
static uint64_t stats_n_bytes_read
Definition: mainloop.c:140
buf_flush_to_socket
int buf_flush_to_socket(buf_t *buf, tor_socket_t s, size_t sz)
Definition: buffers_net.c:224
OR_CONN_STATE_CONNECTING
#define OR_CONN_STATE_CONNECTING
Definition: orconn_event.h:31
crypto_seed_rng
int crypto_seed_rng(void)
Definition: crypto_rand.c:452
connection_t::purpose
unsigned int purpose
Definition: connection_st.h:51
entry_connection_st.h
Entry connection structure.
dns_servers_relaunch_checks
void dns_servers_relaunch_checks(void)
Definition: mainloop.c:2314
connection_bucket_write_limit
ssize_t connection_bucket_write_limit(connection_t *conn, time_t now)
Definition: connection.c:3423
get_main_loop_success_count
uint64_t get_main_loop_success_count(void)
Definition: mainloop.c:536
circuit_expire_building
void circuit_expire_building(void)
Definition: circuituse.c:460
dnsserv.h
Header file for dnsserv.c.
reset_all_main_loop_timers
void reset_all_main_loop_timers(void)
Definition: mainloop.c:1454
LOG_NOTICE
#define LOG_NOTICE
Definition: log.h:50
or_options_t::BridgeRelay
int BridgeRelay
Definition: or_options_st.h:248
periodic_timer_t
Definition: compat_libevent.c:226
connection_t::address
char * address
Definition: connection_st.h:166
is_participating_on_network
bool is_participating_on_network(void)
Definition: netstatus.c:110
main_loop_exit_value
static int main_loop_exit_value
Definition: mainloop.c:184
MOCK_IMPL
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
edge_connection_t::edge_has_sent_end
unsigned int edge_has_sent_end
Definition: edge_connection_st.h:67
stats_n_seconds_working
static long stats_n_seconds_working
Definition: mainloop.c:146
or_options_t::DirReqStatistics
int DirReqStatistics
Definition: or_options_st.h:629
reschedule_directory_downloads
void reschedule_directory_downloads(void)
Definition: mainloop.c:1606
get_bytes_read
uint64_t get_bytes_read(void)
Definition: mainloop.c:465
or_options_t::ConnDirectionStatistics
int ConnDirectionStatistics
Definition: or_options_st.h:635
handle_deferred_signewnym_ev
static mainloop_event_t * handle_deferred_signewnym_ev
Definition: mainloop.c:161
AP_CONN_STATE_CIRCUIT_WAIT
#define AP_CONN_STATE_CIRCUIT_WAIT
Definition: connection_edge.h:49
netstatus.h
Header for netstatus.c.
conn_close_if_marked
static int conn_close_if_marked(int i)
Definition: mainloop.c:959
consider_hibernation
void consider_hibernation(time_t now)
Definition: hibernate.c:1098
tor_assert
#define tor_assert(expr)
Definition: util_bug.h:102
control.h
Header file for control.c.
CONN_TYPE_DIR
#define CONN_TYPE_DIR
Definition: connection.h:55
routerkeys.h
Header for routerkeys.c.
microdesc.h
Header file for microdesc.c.
LD_BUG
#define LD_BUG
Definition: log.h:86
control_per_second_events
void control_per_second_events(void)
Definition: control_events.c:364
periodic_events_rescan_by_roles
void periodic_events_rescan_by_roles(int roles, bool net_disabled)
Definition: periodic.c:291
MAX_SIGNEWNYM_RATE
#define MAX_SIGNEWNYM_RATE
Definition: mainloop.c:155
close_closeable_connections
STATIC void close_closeable_connections(void)
Definition: mainloop.c:839
guards_update_all
int guards_update_all(void)
Definition: entrynodes.c:3727
circuituse.h
Header file for circuituse.c.
channel.h
Header file for channel.c.
time_of_process_start
time_t time_of_process_start
Definition: mainloop.c:144
run_connection_housekeeping
static void run_connection_housekeeping(int i, time_t now)
Definition: mainloop.c:1158
LD_GENERAL
#define LD_GENERAL
Definition: log.h:62
connection_or_clear_identity
void connection_or_clear_identity(or_connection_t *conn)
Definition: connection_or.c:128
or_options_t::HeartbeatPeriod
int HeartbeatPeriod
Definition: or_options_st.h:415
conn_state_to_string
const char * conn_state_to_string(int type, int state)
Definition: connection.c:296
tor_fragile_assert
#define tor_fragile_assert()
Definition: util_bug.h:259
periodic_events_reset_all
void periodic_events_reset_all(void)
Definition: periodic.c:254
tor_libevent_run_event_loop
int tor_libevent_run_event_loop(struct event_base *base, int once)
Definition: compat_libevent.c:513
increment_main_loop_idle_count
static void increment_main_loop_idle_count(void)
Definition: mainloop.c:557
assert_connection_edge_not_dns_pending
void assert_connection_edge_not_dns_pending(edge_connection_t *conn)
Definition: dns.c:950
periodic.h
Header for periodic.c.
initialize_periodic_events
void initialize_periodic_events(void)
Definition: mainloop.c:1522
options_any_client_port_set
int options_any_client_port_set(const or_options_t *options)
Definition: config.c:7300
connection_start_reading_from_linked_conn
static void connection_start_reading_from_linked_conn(connection_t *conn)
Definition: mainloop.c:803
connection_t::reading_from_linked_conn
unsigned int reading_from_linked_conn
Definition: connection_st.h:81
control_any_per_second_event_enabled
int control_any_per_second_event_enabled(void)
Definition: control_events.c:322
rend_cache_clean
void rend_cache_clean(time_t now, rend_cache_type_t cache_type)
Definition: rendcache.c:289
get_dir_info_status_string
const char * get_dir_info_status_string(void)
Definition: nodelist.c:2400
or_connection_t::is_canonical
unsigned int is_canonical
Definition: or_connection_st.h:71
networkstatus_consensus_reasonably_live
int networkstatus_consensus_reasonably_live(const networkstatus_t *consensus, time_t now)
Definition: networkstatus.c:1440
networkstatus_get_live_consensus
networkstatus_t * networkstatus_get_live_consensus(time_t now)
Definition: networkstatus.c:1416
smartlist_add
void smartlist_add(smartlist_t *sl, void *element)
Definition: smartlist_core.c:117
channel_update_bad_for_new_circs
void channel_update_bad_for_new_circs(const char *digest, int force)
Definition: channel.c:3457
END_STREAM_REASON_NET_UNREACHABLE
#define END_STREAM_REASON_NET_UNREACHABLE
Definition: or.h:254
periodic_event_item_t::name
const char * name
Definition: periodic.h:68
connection_t::writing_to_linked_conn
unsigned int writing_to_linked_conn
Definition: connection_st.h:83
note_user_activity
void note_user_activity(time_t now)
Definition: netstatus.c:63
backtrace.h
Header for backtrace.c.
rend_cache_failure_clean
void rend_cache_failure_clean(time_t now)
Definition: rendcache.c:265
CONN_TYPE_AP_DNS_LISTENER
#define CONN_TYPE_AP_DNS_LISTENER
Definition: connection.h:68
READ_EVENT
@ READ_EVENT
Definition: mainloop.h:37
connection_t::linked
unsigned int linked
Definition: connection_st.h:78
we_are_hibernating
int we_are_hibernating(void)
Definition: hibernate.c:937
dns_reset_correctness_checks
void dns_reset_correctness_checks(void)
Definition: dns.c:2057
connection_stop_reading
void connection_stop_reading(connection_t *conn)
Definition: mainloop.c:611
token_bucket_rw_t
Definition: token_bucket.h:59
hs_cache_client_intro_state_clean
void hs_cache_client_intro_state_clean(time_t now)
Definition: hs_cache.c:989
reschedule_or_state_save
void reschedule_or_state_save(void)
Definition: mainloop.c:1904
libevent_error_ratelim
static ratelim_t libevent_error_ratelim
Definition: mainloop.c:2407
quiet
int quiet
Definition: config.c:2449
edge_connection_t::end_reason
uint16_t end_reason
Definition: edge_connection_st.h:54
smartlist_new
smartlist_t * smartlist_new(void)
Definition: smartlist_core.c:26
connection_is_moribund
int connection_is_moribund(connection_t *conn)
Definition: connection.c:5374
socks_request_st.h
Client request structure.
rescan_periodic_events_cb
static void rescan_periodic_events_cb(mainloop_event_t *event, void *arg)
Definition: mainloop.c:1563
or_connection_t
Definition: or_connection_st.h:22
tor_parse_long
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:59
closeable_connection_lst
static smartlist_t * closeable_connection_lst
Definition: mainloop.c:169
connection_t::port
uint16_t port
Definition: connection_st.h:146
connection_wants_to_flush
int connection_wants_to_flush(connection_t *conn)
Definition: connection.c:4191
connection_start_reading
void connection_start_reading(connection_t *conn)
Definition: mainloop.c:633
statefile.h
Header for statefile.c.
SMARTLIST_FOREACH
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: smartlist_foreach.h:112
get_or_state
or_state_t * get_or_state(void)
Definition: statefile.c:208
connection_in_array
int connection_in_array(connection_t *conn)
Definition: mainloop.c:444
netstatus_note_clock_jumped
void netstatus_note_clock_jumped(time_t seconds_diff)
Definition: netstatus.c:165
periodic_event_item_t
Definition: periodic.h:63
hs_service_run_scheduled_events
void hs_service_run_scheduled_events(time_t now)
Definition: hs_service.c:4227
safe_timer_diff
int safe_timer_diff(time_t now, time_t next)
Definition: periodic.c:351
connection_stop_reading_from_linked_conn
void connection_stop_reading_from_linked_conn(connection_t *conn)
Definition: mainloop.c:821
networkstatus.h
Header file for networkstatus.c.
second_elapsed_callback
static int second_elapsed_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1672
cell_t
Definition: cell_st.h:17
geoip_stats.h
Header file for geoip_stats.c.
hs_client_purge_state
void hs_client_purge_state(void)
Definition: hs_client.c:2582
or_connection_t::chan
channel_tls_t * chan
Definition: or_connection_st.h:50
hs_client.h
Header file containing client data for the HS subsytem.
write_stats_file_callback
static int write_stats_file_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1917
note_that_we_completed_a_circuit
void note_that_we_completed_a_circuit(void)
Definition: mainloop.c:228
routerlist_remove_old_routers
void routerlist_remove_old_routers(void)
Definition: routerlist.c:1890
escaped_safe_str_client
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1119
connection_should_read_from_linked_conn
static int connection_should_read_from_linked_conn(connection_t *conn)
Definition: mainloop.c:717
rep_history_clean
void rep_history_clean(time_t before)
Definition: rephist.c:580
update_all_descriptor_downloads
void update_all_descriptor_downloads(time_t now)
Definition: routerlist.c:2302
hs_cache.h
Header file for hs_cache.c.
get_bytes_written
uint64_t get_bytes_written(void)
Definition: mainloop.c:475
hibernate.h
Header file for hibernate.c.
buf_datalen
size_t buf_datalen(const buf_t *buf)
Definition: buffers.c:394
REPHIST_CELL_PADDING_COUNTS_INTERVAL
#define REPHIST_CELL_PADDING_COUNTS_INTERVAL
Definition: rephist.h:103
channel_run_cleanup
void channel_run_cleanup(void)
Definition: channel.c:2132
geoip_bridge_stats_write
time_t geoip_bridge_stats_write(time_t now)
Definition: geoip_stats.c:1237
circuit_note_clock_jumped
void circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
Definition: circuitbuild.c:1159
should_record_bridge_info
int should_record_bridge_info(const or_options_t *options)
Definition: geoip_stats.c:112
circuitlist.h
Header file for circuitlist.c.
mainloop.h
Header file for mainloop.c.
called_loop_once
static int called_loop_once
Definition: mainloop.c:176
or_options_t::BridgeAuthoritativeDir
int BridgeAuthoritativeDir
Definition: or_options_st.h:219
connection_add_impl
int connection_add_impl(connection_t *conn, int is_connecting)
Definition: mainloop.c:246
fetch_networkstatus_callback
static int fetch_networkstatus_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2062
CONN_TYPE_AP
#define CONN_TYPE_AP
Definition: connection.h:51
accounting_is_enabled
int accounting_is_enabled(const or_options_t *options)
Definition: hibernate.c:305
generate_ed_link_cert
int generate_ed_link_cert(const or_options_t *options, time_t now, int force)
Definition: routerkeys.c:365
OR_CONN_STATE_OPEN
#define OR_CONN_STATE_OPEN
Definition: orconn_event.h:53
or_options_t::DormantClientTimeout
int DormantClientTimeout
Definition: or_options_st.h:1047
rep_hist_reset_padding_counts
void rep_hist_reset_padding_counts(void)
Definition: rephist.c:2020
DIR_PURPOSE_FETCH_SERVERDESC
#define DIR_PURPOSE_FETCH_SERVERDESC
Definition: directory.h:39
circuit_build_needed_circs
void circuit_build_needed_circs(time_t now)
Definition: circuituse.c:1339
circuit_expire_waiting_for_better_guard
void circuit_expire_waiting_for_better_guard(void)
Definition: circuituse.c:859
bridges.h
Header file for circuitbuild.c.
stats_n_main_loop_idle
static uint64_t stats_n_main_loop_idle
Definition: mainloop.c:152
monotime_coarse_diff_msec32
static int32_t monotime_coarse_diff_msec32(const monotime_coarse_t *start, const monotime_coarse_t *end)
Definition: compat_time.h:338
connection_write_bw_exhausted
void connection_write_bw_exhausted(connection_t *conn, bool is_global_bw)
Definition: connection.c:3629
check_expired_networkstatus_callback
static int check_expired_networkstatus_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1870
or_connection_t::idle_timeout
uint16_t idle_timeout
Definition: or_connection_st.h:89
or_state_t::next_write
time_t next_write
Definition: or_state_st.h:26
TO_ENTRY_CONN
entry_connection_t * TO_ENTRY_CONN(connection_t *c)
Definition: connection_edge.c:202
connection_t::hold_open_until_flushed
unsigned int hold_open_until_flushed
Definition: connection_st.h:61
connection_is_reading
int connection_is_reading(connection_t *conn)
Definition: mainloop.c:510
proxy_mode
int proxy_mode(const or_options_t *options)
Definition: proxymode.c:21
MAX_SSL_KEY_LIFETIME_INTERNAL
#define MAX_SSL_KEY_LIFETIME_INTERNAL
Definition: or.h:154
connection_t::outbuf
struct buf_t * outbuf
Definition: connection_st.h:102
LAZY_DESCRIPTOR_RETRY_INTERVAL
#define LAZY_DESCRIPTOR_RETRY_INTERVAL
Definition: mainloop.c:199
entrynodes.h
Header file for circuitbuild.c.
DIR_CONN_IS_SERVER
#define DIR_CONN_IS_SERVER(conn)
Definition: connection_st.h:188
networkstatus_get_latest_consensus
networkstatus_t * networkstatus_get_latest_consensus(void)
Definition: networkstatus.c:1390
conn_write_callback
static void conn_write_callback(evutil_socket_t fd, short event, void *_conn)
Definition: mainloop.c:915
conn_stats_save
time_t conn_stats_save(time_t now)
Definition: connstats.c:260
mainloop_schedule_postloop_cleanup
void mainloop_schedule_postloop_cleanup(void)
Definition: mainloop.c:1634
LD_OR
#define LD_OR
Definition: log.h:92
connection_t::active_on_link
unsigned int active_on_link
Definition: connection_st.h:86
LD_CONTROL
#define LD_CONTROL
Definition: log.h:80
shutdown_did_not_work_callback
static void shutdown_did_not_work_callback(evutil_socket_t fd, short event, void *arg) ATTR_NORETURN
Definition: mainloop.c:737
retry_all_listeners
int retry_all_listeners(smartlist_t *new_conns, int close_all_noncontrol)
Definition: connection.c:3168
router_do_reachability_checks
void router_do_reachability_checks(int test_or, int test_dir)
Definition: selftest.c:323
directory.h
Header file for directory.c.
add_connection_to_closeable_list
void add_connection_to_closeable_list(connection_t *conn)
Definition: mainloop.c:426
CONN_TYPE_OR
#define CONN_TYPE_OR
Definition: connection.h:44
rep_hist_hs_stats_write
time_t rep_hist_hs_stats_write(time_t now)
Definition: rephist.c:1902
tor_digest_is_zero
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
schedule_active_linked_connections_cb
static void schedule_active_linked_connections_cb(mainloop_event_t *event, void *arg)
Definition: mainloop.c:389
buf_move_all
size_t buf_move_all(buf_t *buf_out, buf_t *buf_in)
Definition: buffers.c:691
connection_about_to_close_connection
void connection_about_to_close_connection(connection_t *conn)
Definition: connection.c:1001
or_options_t::EntryStatistics
int EntryStatistics
Definition: or_options_st.h:644
connection_t::inbuf
struct buf_t * inbuf
Definition: connection_st.h:101
control_event_signal
int control_event_signal(uintptr_t signal_num)
Definition: control_events.c:1616
smartlist_del
void smartlist_del(smartlist_t *sl, int idx)
Definition: smartlist_core.c:214
control_event_conn_bandwidth
int control_event_conn_bandwidth(connection_t *conn)
Definition: control_events.c:1101
authmode.h
Header file for directory authority mode.
do_signewnym
void do_signewnym(time_t now)
Definition: mainloop.c:1318
periodic_events_disconnect_all
void periodic_events_disconnect_all(void)
Definition: periodic.c:331
get_connection_array
smartlist_t * get_connection_array(void)
Definition: mainloop.c:453
mainloop_event_t
Definition: compat_libevent.c:320
connection_t::marked_for_close
uint16_t marked_for_close
Definition: connection_st.h:149
connection_t::conn_array_index
int conn_array_index
Definition: connection_st.h:97
microdesc_cache_rebuild
int microdesc_cache_rebuild(microdesc_cache_t *cache, int force)
Definition: microdesc.c:704
nodelist.h
Header file for nodelist.c.
or_options_t::HiddenServiceStatistics
int HiddenServiceStatistics
Definition: or_options_st.h:652
update_approx_time
void update_approx_time(time_t now)
Definition: approx_time.c:41
periodic_timer_new
periodic_timer_t * periodic_timer_new(struct event_base *base, const struct timeval *tv, void(*cb)(periodic_timer_t *timer, void *data), void *data)
Definition: compat_libevent.c:249
routerlist.h
Header file for routerlist.c.
GREEDY_DESCRIPTOR_RETRY_INTERVAL
#define GREEDY_DESCRIPTOR_RETRY_INTERVAL
Definition: mainloop.c:196
heartbeat_callback
static int heartbeat_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2108
have_completed_a_circuit
int have_completed_a_circuit(void)
Definition: mainloop.c:220
connection_unlink
static void connection_unlink(connection_t *conn)
Definition: mainloop.c:342
directory_info_has_arrived
void directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
Definition: mainloop.c:1117
rend_cache_failure_clean_callback
static int rend_cache_failure_clean_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2025
predict_ports.h
Header file for predict_ports.c.
assert_connection_ok
void assert_connection_ok(connection_t *conn, time_t now)
Definition: connection.c:5524
connection_close_immediate
void connection_close_immediate(connection_t *conn)
Definition: connection.c:1032
or_options_t::DownloadExtraInfo
int DownloadExtraInfo
Definition: or_options_st.h:622
increment_main_loop_error_count
static void increment_main_loop_error_count(void)
Definition: mainloop.c:543
do_main_loop
int do_main_loop(void)
Definition: mainloop.c:2340
connection_expire_held_open
void connection_expire_held_open(void)
Definition: connection.c:1148
routerinfo_st.h
Router descriptor structure.
stats_n_main_loop_successes
static uint64_t stats_n_main_loop_successes
Definition: mainloop.c:148
circuit_expire_old_circs_as_needed
void circuit_expire_old_circs_as_needed(time_t now)
Definition: circuituse.c:1362
rendservice.h
Header file for rendservice.c.
launch_descriptor_fetches_callback
static int launch_descriptor_fetches_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1749
buf_flush_to_tls
int buf_flush_to_tls(buf_t *buf, tor_tls_t *tls, size_t flushlen)
Definition: buffers_tls.c:138
connection_start_writing
void connection_start_writing(connection_t *conn)
Definition: mainloop.c:689
buffers.h
Header file for buffers.c.
dir_server_mode
int dir_server_mode(const or_options_t *options)
Definition: routermode.c:23
stats_n_main_loop_errors
static uint64_t stats_n_main_loop_errors
Definition: mainloop.c:150
cell_t::command
uint8_t command
Definition: cell_st.h:19
channel_t
Definition: channel.h:181
rep_hist_buffer_stats_write
time_t rep_hist_buffer_stats_write(time_t now)
Definition: rephist.c:1465
handle_deferred_signewnym_cb
static void handle_deferred_signewnym_cb(mainloop_event_t *event, void *arg)
Definition: mainloop.c:1308
geoip_entry_stats_write
time_t geoip_entry_stats_write(time_t now)
Definition: geoip_stats.c:1372
reset_main_loop_counters
void reset_main_loop_counters(void)
Definition: mainloop.c:520
connection_t
Definition: connection_st.h:45
transports.h
Headers for transports.c.
rendcache.h
Header file for rendcache.c.
connection_t::type
unsigned int type
Definition: connection_st.h:50
signewnym_is_pending
static int signewnym_is_pending
Definition: mainloop.c:159
channel_listener_run_cleanup
void channel_listener_run_cleanup(void)
Definition: channel.c:2158
or_options_t::TestingDirConnectionMaxStall
int TestingDirConnectionMaxStall
Definition: or_options_st.h:781
connection_ap_expire_beginning
void connection_ap_expire_beginning(void)
Definition: connection_edge.c:1133
LOG_INFO
#define LOG_INFO
Definition: log.h:45
crypto_rand.h
Common functions for using (pseudo-)random number generators.
entry_connection_t::socks_request
socks_request_t * socks_request
Definition: entry_connection_st.h:27
connection_check_event
static int connection_check_event(connection_t *conn, struct event *ev)
Definition: mainloop.c:573
tor_libevent_exit_loop_after_callback
void tor_libevent_exit_loop_after_callback(struct event_base *base)
Definition: compat_libevent.c:531
control_events.h
Header file for control_events.c.
conn_read_callback
static void conn_read_callback(evutil_socket_t fd, short event, void *_conn)
Definition: mainloop.c:873
can_complete_circuits
static int can_complete_circuits
Definition: mainloop.c:192
get_options
const or_options_t * get_options(void)
Definition: config.c:928
or_state_st.h
The or_state_t structure, which represents Tor's state file.
get_my_roles
STATIC int get_my_roles(const or_options_t *options)
Definition: mainloop.c:1462
geoip_bridge_stats_init
void geoip_bridge_stats_init(time_t now)
Definition: geoip_stats.c:1064
fetch_bridge_descriptors
void fetch_bridge_descriptors(const or_options_t *options, time_t now)
Definition: bridges.c:706
connection_t::read_event
struct event * read_event
Definition: connection_st.h:99
connection_array
STATIC smartlist_t * connection_array
Definition: mainloop.c:166
circuitbuild.h
Header file for circuitbuild.c.
connection_watch_events
void connection_watch_events(connection_t *conn, watchable_events_t events)
Definition: mainloop.c:495
TO_EDGE_CONN
edge_connection_t * TO_EDGE_CONN(connection_t *c)
Definition: connection_edge.c:176
connection_state_is_open
int connection_state_is_open(connection_t *conn)
Definition: connection.c:4915
addressmap.h
Header for addressmap.c.
postloop_cleanup_ev
static mainloop_event_t * postloop_cleanup_ev
Definition: mainloop.c:1629
current_second
static time_t current_second
Definition: mainloop.c:2181
watchable_events_t
watchable_events_t
Definition: mainloop.h:35
or_state_save
int or_state_save(time_t now)
Definition: statefile.c:519
tor_libevent_get_base
struct event_base * tor_libevent_get_base(void)
Definition: compat_libevent.c:196
connstats.h
Header for feature/stats/connstats.c.
or_options_t::KeepalivePeriod
int KeepalivePeriod
Definition: or_options_st.h:371
stats_n_bytes_written
static uint64_t stats_n_bytes_written
Definition: mainloop.c:142
channel_is_bad_for_new_circs
int channel_is_bad_for_new_circs(channel_t *chan)
Definition: channel.c:2869
any_predicted_circuits
int any_predicted_circuits(time_t now)
Definition: predict_ports.c:253
connection.h
Header file for connection.c.
scheduled_shutdown_cb
static void scheduled_shutdown_cb(mainloop_event_t *ev, void *arg)
Definition: mainloop.c:1649
connection_t::linked_conn
struct connection_t * linked_conn
Definition: connection_st.h:168
save_state_callback
static int save_state_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1889
update_networkstatus_downloads
void update_networkstatus_downloads(time_t now)
Definition: networkstatus.c:1303
channeltls.h
Header file for channeltls.c.
networkstatus_consensus_is_bootstrapping
int networkstatus_consensus_is_bootstrapping(time_t now)
Definition: networkstatus.c:1497
note_that_we_maybe_cant_complete_circuits
void note_that_we_maybe_cant_complete_circuits(void)
Definition: mainloop.c:236
connection_or_write_cell_to_buf
void connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
Definition: connection_or.c:2257
initialize_periodic_events_cb
static void initialize_periodic_events_cb(evutil_socket_t fd, short events, void *data)
Definition: mainloop.c:1508
MIN_HEARTBEAT_PERIOD
#define MIN_HEARTBEAT_PERIOD
Definition: config.h:25
get_signewnym_epoch
unsigned get_signewnym_epoch(void)
Definition: mainloop.c:1342
circuit_mark_all_unused_circs
void circuit_mark_all_unused_circs(void)
Definition: circuitlist.c:2103
or_options_t::ExitPortStatistics
int ExitPortStatistics
Definition: or_options_st.h:632
conn_type_to_string
const char * conn_type_to_string(int type)
Definition: connection.c:264
circuit_close_all_marked
void circuit_close_all_marked(void)
Definition: circuitlist.c:664
connection_dir_reached_eof
int connection_dir_reached_eof(dir_connection_t *conn)
Definition: dirclient.c:2995
CONN_TYPE_EXIT
#define CONN_TYPE_EXIT
Definition: connection.h:46
run_main_loop_until_done
STATIC int run_main_loop_until_done(void)
Definition: mainloop.c:2503
stats_increment_bytes_read_and_written
void stats_increment_bytes_read_and_written(uint64_t r, uint64_t w)
Definition: mainloop.c:485
ip_address_changed
void ip_address_changed(int on_client_conn)
Definition: mainloop.c:2283
server_mode
int server_mode(const or_options_t *options)
Definition: routermode.c:34
check_network_participation_callback
STATIC int check_network_participation_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1819
or_options_t::RephistTrackTime
int RephistTrackTime
Definition: or_options_st.h:570
tor_libevent_is_initialized
bool tor_libevent_is_initialized(void)
Definition: compat_libevent.c:189
update_extrainfo_downloads
void update_extrainfo_downloads(time_t now)
Definition: routerlist.c:2811
timeval
Definition: compat_time.h:151
active_linked_connection_lst
static smartlist_t * active_linked_connection_lst
Definition: mainloop.c:172
cpuworker.h
Header file for cpuworker.c.
channelpadding_decide_to_pad_channel
channelpadding_decision_t channelpadding_decide_to_pad_channel(channel_t *chan)
Definition: channelpadding.c:721
or_connection_st.h
OR connection structure.
get_main_loop_error_count
uint64_t get_main_loop_error_count(void)
Definition: mainloop.c:550
or_options_t::OwningControllerFD
uint64_t OwningControllerFD
Definition: or_options_st.h:529
connection_t::write_event
struct event * write_event
Definition: connection_st.h:100
LOG_FN_CONN
#define LOG_FN_CONN(conn, args)
Definition: control.h:33
or_options_t::PaddingStatistics
int PaddingStatistics
Definition: or_options_st.h:641
SMARTLIST_FOREACH_BEGIN
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Definition: smartlist_foreach.h:78
log_failed_proxy_connection
void log_failed_proxy_connection(connection_t *conn)
Definition: connection.c:5727
proxymode.h
Header file for proxymode.c.
log_fn_ratelim
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:292
or_options_t::TestingTorNetwork
int TestingTorNetwork
Definition: or_options_st.h:791
mainloop_schedule_shutdown
void mainloop_schedule_shutdown(int delay_sec)
Definition: mainloop.c:1659
or_options_t::DormantTimeoutDisabledByIdleStreams
int DormantTimeoutDisabledByIdleStreams
Definition: or_options_st.h:1052
connection_t::timestamp_last_write_allowed
time_t timestamp_last_write_allowed
Definition: connection_st.h:106
connection_is_writing
int connection_is_writing(connection_t *conn)
Definition: mainloop.c:656
circuit_mark_all_dirty_circs_as_unusable
void circuit_mark_all_dirty_circs_as_unusable(void)
Definition: circuitlist.c:2122
log_heartbeat
int log_heartbeat(time_t now)
Definition: status.c:120
consdiffmgr_cleanup
int consdiffmgr_cleanup(void)
Definition: consdiffmgr.c:712
scheduled_shutdown_ev
static mainloop_event_t * scheduled_shutdown_ev
Definition: mainloop.c:1645
or_options_t::UseBridges
int UseBridges
Definition: or_options_st.h:233
schedule_rescan_periodic_events
void schedule_rescan_periodic_events(void)
Definition: mainloop.c:1574
rend_num_services
int rend_num_services(void)
Definition: rendservice.c:202
mainloop_event_activate
void mainloop_event_activate(mainloop_event_t *event)
Definition: compat_libevent.c:425
LOG_WARN
#define LOG_WARN
Definition: log.h:53
router_initialize_tls_context
int router_initialize_tls_context(void)
Definition: router.c:798
prune_old_routers_callback
static int prune_old_routers_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2040
edge_connection_t
Definition: edge_connection_st.h:21
tor_shutdown_event_loop_and_exit
void tor_shutdown_event_loop_and_exit(int exitcode)
Definition: mainloop.c:766
rep_hist_desc_stats_write
time_t rep_hist_desc_stats_write(time_t now)
Definition: rephist.c:1602
cell_st.h
Fixed-size cell structure.
connection_consider_empty_write_buckets
void connection_consider_empty_write_buckets(connection_t *conn)
Definition: connection.c:3669
reset_uptime
void reset_uptime(void)
Definition: mainloop.c:2529
TO_DIR_CONN
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition: directory.c:89
postloop_cleanup_cb
static void postloop_cleanup_cb(mainloop_event_t *ev, void *arg)
Definition: mainloop.c:1618
connection_t::socket_family
int socket_family
Definition: connection_st.h:111
directory_all_unreachable_cb
static void directory_all_unreachable_cb(mainloop_event_t *event, void *arg)
Definition: mainloop.c:1069
socks_request_t::address
char address[MAX_SOCKS_ADDR_LEN]
Definition: socks_request_st.h:57
control_event_general_error
int control_event_general_error(const char *format,...)
Definition: control_events.c:1748
dirclient_too_idle_to_fetch_descriptors
int dirclient_too_idle_to_fetch_descriptors(const or_options_t *options, time_t now)
Definition: dirclient_modes.c:94
accounting_run_housekeeping
void accounting_run_housekeeping(time_t now)
Definition: hibernate.c:585
config.h
Header file for config.c.
periodic_events_register
void periodic_events_register(periodic_event_item_t *item)
Definition: periodic.c:219
or_connection_t::timestamp_lastempty
time_t timestamp_lastempty
Definition: or_connection_st.h:96
dirclient_fetches_from_authorities
int dirclient_fetches_from_authorities(const or_options_t *options)
Definition: dirclient_modes.c:40
connection_t::s
tor_socket_t s
Definition: connection_st.h:96
hs_cache_clean_as_client
void hs_cache_clean_as_client(time_t now)
Definition: hs_cache.c:928
ntmain.h
Header file for ntmain.c.
smartlist_contains
int smartlist_contains(const smartlist_t *sl, const void *element)
Definition: smartlist_core.c:201
buffers_net.h
Header file for buffers_net.c.
set_network_participation
void set_network_participation(bool participation)
Definition: netstatus.c:101
initialize_periodic_events_event
static struct event * initialize_periodic_events_event
Definition: mainloop.c:1500
channel_t::global_identifier
uint64_t global_identifier
Definition: channel.h:197
LD_NET
#define LD_NET
Definition: log.h:66
tor_log
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:628
connection_t::state
uint8_t state
Definition: connection_st.h:49
connection_get_by_type_state
connection_t * connection_get_by_type_state(int type, int state)
Definition: connection.c:4759
buffers_tls.h
Header for buffers_tls.c.
periodic_events_connect_all
void periodic_events_connect_all(void)
Definition: periodic.c:234
dnsserv_close_listener
void dnsserv_close_listener(connection_t *conn)
Definition: dnsserv.c:407
channel_t::timestamp_last_had_circuits
time_t timestamp_last_had_circuits
Definition: channel.h:447
clean_caches_callback
static int clean_caches_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2008
should_delay_dir_fetches
int should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
Definition: networkstatus.c:1253
or_options_t
Definition: or_options_st.h:45
socks_request_t::port
uint16_t port
Definition: socks_request_st.h:59
geoip_dirreq_stats_write
time_t geoip_dirreq_stats_write(time_t now)
Definition: geoip_stats.c:1029
addressmap_clear_transient
void addressmap_clear_transient(void)
Definition: addressmap.c:311
connection_or_close_normally
void connection_or_close_normally(or_connection_t *orconn, int flush)
Definition: connection_or.c:1570
get_uptime
long get_uptime(void)
Definition: mainloop.c:2522
or_options_t::CellStatistics
int CellStatistics
Definition: or_options_st.h:638
reset_bandwidth_test
void reset_bandwidth_test(void)
Definition: circuituse.c:1617
STATIC
#define STATIC
Definition: testsupport.h:32
router_reset_reachability
void router_reset_reachability(void)
Definition: selftest.c:62
ABS
#define ABS(x)
Definition: cmp.h:40
dns.h
Header file for dns.c.
channel_num_circuits
unsigned int channel_num_circuits(channel_t *chan)
Definition: channel.c:3335
rep_hist_exit_stats_write
time_t rep_hist_exit_stats_write(time_t now)
Definition: rephist.c:1188
router_have_minimum_dir_info
int router_have_minimum_dir_info(void)
Definition: nodelist.c:2346
connection_is_on_closeable_list
int connection_is_on_closeable_list(connection_t *conn)
Definition: mainloop.c:437
LD_DIR
#define LD_DIR
Definition: log.h:88
connection_unregister_events
void connection_unregister_events(connection_t *conn)
Definition: mainloop.c:277
tor_event_loop_shutdown_is_pending
int tor_event_loop_shutdown_is_pending(void)
Definition: mainloop.c:794
networkstatus_st.h
Networkstatus consensus/vote structure.
entry_connection_t
Definition: entry_connection_st.h:19
WRITE_EVENT
@ WRITE_EVENT
Definition: mainloop.h:38
periodic_events_initialized
static int periodic_events_initialized
Definition: mainloop.c:1349
run_main_loop_once
static int run_main_loop_once(void)
Definition: mainloop.c:2415
current_second_last_changed
static monotime_coarse_t current_second_last_changed
Definition: mainloop.c:2183
dirclient_modes.h
Header for feature/dirclient/dirclient_modes.c.
networkstatus_t
Definition: networkstatus_st.h:26
connection_t::timestamp_last_read_allowed
time_t timestamp_last_read_allowed
Definition: connection_st.h:104
hs_cache_clean_as_dir
void hs_cache_clean_as_dir(time_t now)
Definition: hs_cache.c:332
CONN_IS_EDGE
#define CONN_IS_EDGE(x)
Definition: connection_st.h:183
rescan_periodic_events
void rescan_periodic_events(const or_options_t *options)
Definition: mainloop.c:1586
router_dir_info_changed
void router_dir_info_changed(void)
Definition: nodelist.c:2389
shutdown_did_not_work_event
static struct event * shutdown_did_not_work_event
Definition: mainloop.c:729
schedule_active_linked_connections_event
static mainloop_event_t * schedule_active_linked_connections_event
Definition: mainloop.c:380
smartlist_t
Definition: smartlist_core.h:26
time_of_last_signewnym
static time_t time_of_last_signewnym
Definition: mainloop.c:157
smartlist_remove
void smartlist_remove(smartlist_t *sl, const void *element)
Definition: smartlist_core.c:151
TO_OR_CONN
or_connection_t * TO_OR_CONN(connection_t *c)
Definition: connection_or.c:108
add_entropy_callback
static int add_entropy_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1801
compat_libevent.h
Header for compat_libevent.c.
directory_all_unreachable
void directory_all_unreachable(time_t now)
Definition: mainloop.c:1099
record_bridge_stats_callback
static int record_bridge_stats_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1980
get_main_loop_idle_count
uint64_t get_main_loop_idle_count(void)
Definition: mainloop.c:564
mainloop_event_postloop_new
mainloop_event_t * mainloop_event_postloop_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
Definition: compat_libevent.c:410
quiet_level
quiet_level_t quiet_level
Definition: quiet_level.c:20
update_current_time
void update_current_time(time_t now)
Definition: mainloop.c:2191
connection_edge_end_errno
int connection_edge_end_errno(edge_connection_t *conn)
Definition: connection_edge.c:813
hs_service_get_num_services
unsigned int hs_service_get_num_services(void)
Definition: hs_service.c:3799
mainloop_event_schedule
int mainloop_event_schedule(mainloop_event_t *event, const struct timeval *tv)
Definition: compat_libevent.c:443
connection_t::proxy_state
unsigned int proxy_state
Definition: connection_st.h:92
status.h
Header for status.c.
rephist.h
Header file for rephist.c.
mark_my_descriptor_dirty
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2525
mainloop_event_new
mainloop_event_t * mainloop_event_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
Definition: compat_libevent.c:396
get_last_user_activity_time
time_t get_last_user_activity_time(void)
Definition: netstatus.c:91
connection_or.h
Header file for connection_or.c.
main_loop_should_exit
static int main_loop_should_exit
Definition: mainloop.c:180
connection_t::marked_for_close_file
const char * marked_for_close_file
Definition: connection_st.h:153
SOCKET_OK
#define SOCKET_OK(s)
Definition: nettypes.h:39
connection_count_moribund
int connection_count_moribund(void)
Definition: mainloop.c:855
ratelim_t
Definition: ratelim.h:42
initialize_mainloop_events
void initialize_mainloop_events(void)
Definition: mainloop.c:2326
or.h
Master header file for Tor-specific functionality.
connection_get_by_type_nonlinked
connection_t * connection_get_by_type_nonlinked(int type)
Definition: connection.c:4769
rotate_x509_certificate_callback
static int rotate_x509_certificate_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1767
consdiffmgr.h
Header for consdiffmgr.c.
signewnym_impl
static void signewnym_impl(time_t now)
Definition: mainloop.c:1286
connection_or_connect_failed
void connection_or_connect_failed(or_connection_t *conn, int reason, const char *msg)
Definition: connection_or.c:1367
newnym_epoch
static unsigned newnym_epoch
Definition: mainloop.c:163
circuit_upgrade_circuits_from_guard_wait
void circuit_upgrade_circuits_from_guard_wait(void)
Definition: circuitbuild.c:2537
LD_PROTOCOL
#define LD_PROTOCOL
Definition: log.h:72