tor  0.4.0.1-alpha
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-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
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"
58 #include "core/mainloop/netstatus.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"
70 #include "feature/client/addressmap.h"
71 #include "feature/client/bridges.h"
72 #include "feature/client/dnsserv.h"
78 #include "feature/dircache/consdiffmgr.h"
82 #include "feature/hs/hs_cache.h"
83 #include "feature/hs/hs_client.h"
84 #include "feature/hs/hs_service.h"
89 #include "feature/relay/dns.h"
90 #include "feature/relay/routerkeys.h"
92 #include "feature/relay/selftest.h"
93 #include "feature/rend/rendcache.h"
96 #include "feature/stats/predict_ports.h"
97 #include "feature/stats/rephist.h"
98 #include "lib/buf/buffers.h"
100 #include "lib/err/backtrace.h"
101 #include "lib/tls/buffers_tls.h"
102 
103 #include "lib/net/buffers_net.h"
105 
106 #include <event2/event.h>
107 
108 #include "feature/dirauth/dirvote.h"
110 
111 #include "core/or/cell_st.h"
112 #include "core/or/entry_connection_st.h"
113 #include "feature/nodelist/networkstatus_st.h"
114 #include "core/or/or_connection_st.h"
115 #include "app/config/or_state_st.h"
116 #include "feature/nodelist/routerinfo_st.h"
117 #include "core/or/socks_request_st.h"
118 
119 #ifdef HAVE_UNISTD_H
120 #include <unistd.h>
121 #endif
122 
123 #ifdef HAVE_SYSTEMD
124 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
125 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
126  * Coverity. Here's a kludge to unconfuse it.
127  */
128 # define __INCLUDE_LEVEL__ 2
129 #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
130 #include <systemd/sd-daemon.h>
131 #endif /* defined(HAVE_SYSTEMD) */
132 
133 /* Token bucket for all traffic. */
134 token_bucket_rw_t global_bucket;
135 
136 /* Token bucket for relayed traffic. */
137 token_bucket_rw_t global_relayed_bucket;
138 
139 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
141 static uint64_t stats_n_bytes_read = 0;
143 static uint64_t stats_n_bytes_written = 0;
147 static long stats_n_seconds_working = 0;
149 static uint64_t stats_n_main_loop_successes = 0;
151 static uint64_t stats_n_main_loop_errors = 0;
153 static uint64_t stats_n_main_loop_idle = 0;
154 
156 #define MAX_SIGNEWNYM_RATE 10
157 
158 static time_t time_of_last_signewnym = 0;
160 static int signewnym_is_pending = 0;
164 static unsigned newnym_epoch = 0;
165 
177 static int called_loop_once = 0;
181 static int main_loop_should_exit = 0;
185 static int main_loop_exit_value = 0;
186 
193 static int can_complete_circuits = 0;
194 
197 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
198 
200 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
201 
202 static int conn_close_if_marked(int i);
205 static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
206 static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
207 static void shutdown_did_not_work_callback(evutil_socket_t fd, short event,
208  void *arg) ATTR_NORETURN;
209 
210 /****************************************************************************
211  *
212  * This section contains accessors and other methods on the connection_array
213  * variables (which are global within this file and unavailable outside it).
214  *
215  ****************************************************************************/
216 
220 int
222 {
223  return can_complete_circuits;
224 }
225 
228 void
230 {
232 }
233 
236 void
238 {
240 }
241 
246 int
247 connection_add_impl(connection_t *conn, int is_connecting)
248 {
249  tor_assert(conn);
250  tor_assert(SOCKET_OK(conn->s) ||
251  conn->linked ||
252  (conn->type == CONN_TYPE_AP &&
253  TO_EDGE_CONN(conn)->is_dns_request));
254 
255  tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
256  conn->conn_array_index = smartlist_len(connection_array);
258 
259  (void) is_connecting;
260 
261  if (SOCKET_OK(conn->s) || conn->linked) {
262  conn->read_event = tor_event_new(tor_libevent_get_base(),
263  conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
264  conn->write_event = tor_event_new(tor_libevent_get_base(),
265  conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
266  /* XXXX CHECK FOR NULL RETURN! */
267  }
268 
269  log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
270  conn_type_to_string(conn->type), (int)conn->s, conn->address,
271  smartlist_len(connection_array));
272 
273  return 0;
274 }
275 
277 void
279 {
280  if (conn->read_event) {
281  if (event_del(conn->read_event))
282  log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
283  tor_free(conn->read_event);
284  }
285  if (conn->write_event) {
286  if (event_del(conn->write_event))
287  log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
288  tor_free(conn->write_event);
289  }
290  if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
292  }
293 }
294 
299 int
301 {
302  int current_index;
303  connection_t *tmp;
304 
305  tor_assert(conn);
306 
307  log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
308  (int)conn->s, conn_type_to_string(conn->type),
309  smartlist_len(connection_array));
310 
311  if (conn->type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
312  log_info(LD_NET, "Closing SOCKS Unix socket connection");
313  }
314 
316 
317  tor_assert(conn->conn_array_index >= 0);
318  current_index = conn->conn_array_index;
319  connection_unregister_events(conn); /* This is redundant, but cheap. */
320  if (current_index == smartlist_len(connection_array)-1) { /* at the end */
321  smartlist_del(connection_array, current_index);
322  return 0;
323  }
324 
325  /* replace this one with the one at the end */
326  smartlist_del(connection_array, current_index);
327  tmp = smartlist_get(connection_array, current_index);
328  tmp->conn_array_index = current_index;
329 
330  return 0;
331 }
332 
342 static void
344 {
346  if (conn->conn_array_index >= 0) {
347  connection_remove(conn);
348  }
349  if (conn->linked_conn) {
350  conn->linked_conn->linked_conn = NULL;
351  if (! conn->linked_conn->marked_for_close &&
353  connection_start_reading(conn->linked_conn);
354  conn->linked_conn = NULL;
355  }
358  if (conn->type == CONN_TYPE_EXIT) {
360  }
361  if (conn->type == CONN_TYPE_OR) {
362  if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
364  /* connection_unlink() can only get called if the connection
365  * was already on the closeable list, and it got there by
366  * connection_mark_for_close(), which was called from
367  * connection_or_close_normally() or
368  * connection_or_close_for_error(), so the channel should
369  * already be in CHANNEL_STATE_CLOSING, and then the
370  * connection_about_to_close_connection() goes to
371  * connection_or_about_to_close(), which calls channel_closed()
372  * to notify the channel_t layer, and closed the channel, so
373  * nothing more to do here to deal with the channel associated
374  * with an orconn.
375  */
376  }
377  connection_free(conn);
378 }
379 
382 
389 static void
391 {
392  (void)event;
393  (void)arg;
394 
395  /* All active linked conns should get their read events activated,
396  * so that libevent knows to run their callbacks. */
398  event_active(conn->read_event, EV_READ, 1));
399 
400  /* Reactivate the event if we still have connections in the active list.
401  *
402  * A linked connection doesn't get woken up by I/O but rather artificially
403  * by this event callback. It has directory data spooled in it and it is
404  * sent incrementally by small chunks unless spool_eagerly is true. For that
405  * to happen, we need to induce the activation of the read event so it can
406  * be flushed. */
407  if (smartlist_len(active_linked_connection_lst)) {
409  }
410 }
411 
414 void
416 {
417  if (!connection_array)
418  connection_array = smartlist_new();
420  closeable_connection_lst = smartlist_new();
422  active_linked_connection_lst = smartlist_new();
423 }
424 
426 void
428 {
431  assert_connection_ok(conn, time(NULL));
434 }
435 
437 int
439 {
441 }
442 
444 int
446 {
447  return smartlist_contains(connection_array, conn);
448 }
449 
454 get_connection_array, (void))
455 {
456  if (!connection_array)
457  connection_array = smartlist_new();
458  return connection_array;
459 }
460 
465 MOCK_IMPL(uint64_t,
466 get_bytes_read,(void))
467 {
468  return stats_n_bytes_read;
469 }
470 
475 MOCK_IMPL(uint64_t,
476 get_bytes_written,(void))
477 {
478  return stats_n_bytes_written;
479 }
480 
485 void
487 {
488  stats_n_bytes_read += r;
490 }
491 
495 void
497 {
498  if (events & READ_EVENT)
499  connection_start_reading(conn);
500  else
501  connection_stop_reading(conn);
502 
503  if (events & WRITE_EVENT)
504  connection_start_writing(conn);
505  else
506  connection_stop_writing(conn);
507 }
508 
510 int
512 {
513  tor_assert(conn);
514 
515  return conn->reading_from_linked_conn ||
516  (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
517 }
518 
520 void
522 {
526 }
527 
529 static void
531 {
533 }
534 
536 uint64_t
538 {
540 }
541 
543 static void
545 {
547 }
548 
550 uint64_t
552 {
554 }
555 
557 static void
559 {
561 }
562 
564 uint64_t
566 {
567  return stats_n_main_loop_idle;
568 }
569 
573 static int
574 connection_check_event(connection_t *conn, struct event *ev)
575 {
576  int bad;
577 
578  if (conn->type == CONN_TYPE_AP && TO_EDGE_CONN(conn)->is_dns_request) {
579  /* DNS requests which we launch through the dnsserv.c module do not have
580  * any underlying socket or any underlying linked connection, so they
581  * shouldn't have any attached events either.
582  */
583  bad = ev != NULL;
584  } else {
585  /* Everything else should have an underlying socket, or a linked
586  * connection (which is also tracked with a read_event/write_event pair).
587  */
588  bad = ev == NULL;
589  }
590 
591  if (bad) {
592  log_warn(LD_BUG, "Event missing on connection %p [%s;%s]. "
593  "socket=%d. linked=%d. "
594  "is_dns_request=%d. Marked_for_close=%s:%d",
595  conn,
596  conn_type_to_string(conn->type),
597  conn_state_to_string(conn->type, conn->state),
598  (int)conn->s, (int)conn->linked,
599  (conn->type == CONN_TYPE_AP &&
600  TO_EDGE_CONN(conn)->is_dns_request),
601  conn->marked_for_close_file ? conn->marked_for_close_file : "-",
602  conn->marked_for_close
603  );
604  log_backtrace(LOG_WARN, LD_BUG, "Backtrace attached.");
605  return -1;
606  }
607  return 0;
608 }
609 
612 connection_stop_reading,(connection_t *conn))
613 {
614  tor_assert(conn);
615 
616  if (connection_check_event(conn, conn->read_event) < 0) {
617  return;
618  }
619 
620  if (conn->linked) {
621  conn->reading_from_linked_conn = 0;
623  } else {
624  if (event_del(conn->read_event))
625  log_warn(LD_NET, "Error from libevent setting read event state for %d "
626  "to unwatched: %s",
627  (int)conn->s,
628  tor_socket_strerror(tor_socket_errno(conn->s)));
629  }
630 }
631 
634 connection_start_reading,(connection_t *conn))
635 {
636  tor_assert(conn);
637 
638  if (connection_check_event(conn, conn->read_event) < 0) {
639  return;
640  }
641 
642  if (conn->linked) {
643  conn->reading_from_linked_conn = 1;
646  } else {
647  if (event_add(conn->read_event, NULL))
648  log_warn(LD_NET, "Error from libevent setting read event state for %d "
649  "to watched: %s",
650  (int)conn->s,
651  tor_socket_strerror(tor_socket_errno(conn->s)));
652  }
653 }
654 
656 int
658 {
659  tor_assert(conn);
660 
661  return conn->writing_to_linked_conn ||
662  (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
663 }
664 
667 connection_stop_writing,(connection_t *conn))
668 {
669  tor_assert(conn);
670 
671  if (connection_check_event(conn, conn->write_event) < 0) {
672  return;
673  }
674 
675  if (conn->linked) {
676  conn->writing_to_linked_conn = 0;
677  if (conn->linked_conn)
679  } else {
680  if (event_del(conn->write_event))
681  log_warn(LD_NET, "Error from libevent setting write event state for %d "
682  "to unwatched: %s",
683  (int)conn->s,
684  tor_socket_strerror(tor_socket_errno(conn->s)));
685  }
686 }
687 
690 connection_start_writing,(connection_t *conn))
691 {
692  tor_assert(conn);
693 
694  if (connection_check_event(conn, conn->write_event) < 0) {
695  return;
696  }
697 
698  if (conn->linked) {
699  conn->writing_to_linked_conn = 1;
700  if (conn->linked_conn &&
703  } else {
704  if (event_add(conn->write_event, NULL))
705  log_warn(LD_NET, "Error from libevent setting write event state for %d "
706  "to watched: %s",
707  (int)conn->s,
708  tor_socket_strerror(tor_socket_errno(conn->s)));
709  }
710 }
711 
717 static int
719 {
720  if (conn->linked && conn->reading_from_linked_conn) {
721  if (! conn->linked_conn ||
723  buf_datalen(conn->linked_conn->outbuf)))
724  return 1;
725  }
726  return 0;
727 }
728 
730 static struct event *shutdown_did_not_work_event = NULL;
731 
737 static void
738 shutdown_did_not_work_callback(evutil_socket_t fd, short event, void *arg)
739 {
740  // LCOV_EXCL_START
741  (void) fd;
742  (void) event;
743  (void) arg;
744  tor_assert_unreached();
745  // LCOV_EXCL_STOP
746 }
747 
748 #ifdef ENABLE_RESTART_DEBUGGING
749 static struct event *tor_shutdown_event_loop_for_restart_event = NULL;
750 static void
751 tor_shutdown_event_loop_for_restart_cb(
752  evutil_socket_t fd, short event, void *arg)
753 {
754  (void)fd;
755  (void)event;
756  (void)arg;
757  tor_event_free(tor_shutdown_event_loop_for_restart_event);
759 }
760 #endif
761 
766 void
768 {
770  return; /* Ignore multiple calls to this function. */
771 
773  main_loop_exit_value = exitcode;
774 
775  /* Die with an assertion failure in ten seconds, if for some reason we don't
776  * exit normally. */
777  /* XXXX We should consider this code if it's never used. */
778  struct timeval ten_seconds = { 10, 0 };
779  shutdown_did_not_work_event = tor_evtimer_new(
780  tor_libevent_get_base(),
782  event_add(shutdown_did_not_work_event, &ten_seconds);
783 
784  /* Unlike exit_loop_after_delay(), exit_loop_after_callback
785  * prevents other callbacks from running. */
786  tor_libevent_exit_loop_after_callback(tor_libevent_get_base());
787 }
788 
790 int
792 {
793  return main_loop_should_exit;
794 }
795 
799 static void
801 {
802  tor_assert(conn);
803  tor_assert(conn->linked == 1);
804 
805  if (!conn->active_on_link) {
806  conn->active_on_link = 1;
809  } else {
811  }
812 }
813 
817 void
819 {
820  tor_assert(conn);
821  tor_assert(conn->linked == 1);
822 
823  if (conn->active_on_link) {
824  conn->active_on_link = 0;
825  /* FFFF We could keep an index here so we can smartlist_del
826  * cleanly. On the other hand, this doesn't show up on profiles,
827  * so let's leave it alone for now. */
829  } else {
831  }
832 }
833 
835 STATIC void
837 {
838  int i;
839  for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
840  connection_t *conn = smartlist_get(closeable_connection_lst, i);
841  if (conn->conn_array_index < 0) {
842  connection_unlink(conn); /* blow it away right now */
843  } else {
845  ++i;
846  }
847  }
848 }
849 
852 connection_count_moribund, (void))
853 {
854  int moribund = 0;
855 
856  /*
857  * Count things we'll try to kill when close_closeable_connections()
858  * runs next.
859  */
861  if (SOCKET_OK(conn->s) && connection_is_moribund(conn)) ++moribund;
862  } SMARTLIST_FOREACH_END(conn);
863 
864  return moribund;
865 }
866 
869 static void
870 conn_read_callback(evutil_socket_t fd, short event, void *_conn)
871 {
872  connection_t *conn = _conn;
873  (void)fd;
874  (void)event;
875 
876  log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
877 
878  /* assert_connection_ok(conn, time(NULL)); */
879 
880  if (connection_handle_read(conn) < 0) {
881  if (!conn->marked_for_close) {
882 #ifndef _WIN32
883  log_warn(LD_BUG,"Unhandled error on read for %s connection "
884  "(fd %d); removing",
885  conn_type_to_string(conn->type), (int)conn->s);
887 #endif /* !defined(_WIN32) */
888  if (CONN_IS_EDGE(conn))
890  connection_mark_for_close(conn);
891  }
892  }
893  assert_connection_ok(conn, time(NULL));
894 
895  if (smartlist_len(closeable_connection_lst))
897 }
898 
901 static void
902 conn_write_callback(evutil_socket_t fd, short events, void *_conn)
903 {
904  connection_t *conn = _conn;
905  (void)fd;
906  (void)events;
907 
908  LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
909  (int)conn->s));
910 
911  /* assert_connection_ok(conn, time(NULL)); */
912 
913  if (connection_handle_write(conn, 0) < 0) {
914  if (!conn->marked_for_close) {
915  /* this connection is broken. remove it. */
917  "unhandled error on write for %s connection (fd %d); removing",
918  conn_type_to_string(conn->type), (int)conn->s);
920  if (CONN_IS_EDGE(conn)) {
921  /* otherwise we cry wolf about duplicate close */
922  edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
923  if (!edge_conn->end_reason)
924  edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
925  edge_conn->edge_has_sent_end = 1;
926  }
927  connection_close_immediate(conn); /* So we don't try to flush. */
928  connection_mark_for_close(conn);
929  }
930  }
931  assert_connection_ok(conn, time(NULL));
932 
933  if (smartlist_len(closeable_connection_lst))
935 }
936 
945 static int
947 {
948  connection_t *conn;
949  int retval;
950  time_t now;
951 
952  conn = smartlist_get(connection_array, i);
953  if (!conn->marked_for_close)
954  return 0; /* nothing to see here, move along */
955  now = time(NULL);
956  assert_connection_ok(conn, now);
957  /* assert_all_pending_dns_resolves_ok(); */
958 
959  log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
960  conn->s);
961 
962  /* If the connection we are about to close was trying to connect to
963  a proxy server and failed, the client won't be able to use that
964  proxy. We should warn the user about this. */
965  if (conn->proxy_state == PROXY_INFANT)
967 
968  if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
970  /* s == -1 means it's an incomplete edge connection, or that the socket
971  * has already been closed as unflushable. */
972  ssize_t sz = connection_bucket_write_limit(conn, now);
973  if (!conn->hold_open_until_flushed)
974  log_info(LD_NET,
975  "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
976  "to flush %d bytes. (Marked at %s:%d)",
978  (int)conn->s, conn_type_to_string(conn->type), conn->state,
979  (int)conn->outbuf_flushlen,
981  if (conn->linked_conn) {
982  retval = buf_move_to_buf(conn->linked_conn->inbuf, conn->outbuf,
983  &conn->outbuf_flushlen);
984  if (retval >= 0) {
985  /* The linked conn will notice that it has data when it notices that
986  * we're gone. */
988  }
989  log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
990  "%d left; flushlen %d; wants-to-flush==%d", retval,
991  (int)connection_get_outbuf_len(conn),
992  (int)conn->outbuf_flushlen,
994  } else if (connection_speaks_cells(conn)) {
995  if (conn->state == OR_CONN_STATE_OPEN) {
996  retval = buf_flush_to_tls(conn->outbuf, TO_OR_CONN(conn)->tls, sz,
997  &conn->outbuf_flushlen);
998  } else
999  retval = -1; /* never flush non-open broken tls connections */
1000  } else {
1001  retval = buf_flush_to_socket(conn->outbuf, conn->s, sz,
1002  &conn->outbuf_flushlen);
1003  }
1004  if (retval >= 0 && /* Technically, we could survive things like
1005  TLS_WANT_WRITE here. But don't bother for now. */
1007  if (retval > 0) {
1008  LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
1009  "Holding conn (fd %d) open for more flushing.",
1010  (int)conn->s));
1011  conn->timestamp_last_write_allowed = now; /* reset so we can flush
1012  * more */
1013  } else if (sz == 0) {
1014  /* Also, retval==0. If we get here, we didn't want to write anything
1015  * (because of rate-limiting) and we didn't. */
1016 
1017  /* Connection must flush before closing, but it's being rate-limited.
1018  * Let's remove from Libevent, and mark it as blocked on bandwidth
1019  * so it will be re-added on next token bucket refill. Prevents
1020  * busy Libevent loops where we keep ending up here and returning
1021  * 0 until we are no longer blocked on bandwidth.
1022  */
1024  /* Make sure that consider_empty_buckets really disabled the
1025  * connection: */
1026  if (BUG(connection_is_writing(conn))) {
1027  connection_write_bw_exhausted(conn, true);
1028  }
1029 
1030  /* The connection is being held due to write rate limit and thus will
1031  * flush its data later. We need to stop reading because this
1032  * connection is about to be closed once flushed. It should not
1033  * process anything more coming in at this stage. */
1034  connection_stop_reading(conn);
1035  }
1036  return 0;
1037  }
1038  if (connection_wants_to_flush(conn)) {
1039  log_fn(LOG_INFO, LD_NET, "We stalled too much while trying to write %d "
1040  "bytes to address %s. If this happens a lot, either "
1041  "something is wrong with your network connection, or "
1042  "something is wrong with theirs. "
1043  "(fd %d, type %s, state %d, marked at %s:%d).",
1044  (int)connection_get_outbuf_len(conn),
1046  (int)conn->s, conn_type_to_string(conn->type), conn->state,
1047  conn->marked_for_close_file,
1048  conn->marked_for_close);
1049  }
1050  }
1051 
1052  connection_unlink(conn); /* unlink, remove, free */
1053  return 1;
1054 }
1055 
1060 static void
1062 {
1063  (void)event;
1064  (void)arg;
1065 
1066  connection_t *conn;
1067 
1070  entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
1071  log_notice(LD_NET,
1072  "Is your network connection down? "
1073  "Failing connection to '%s:%d'.",
1074  safe_str_client(entry_conn->socks_request->address),
1075  entry_conn->socks_request->port);
1076  connection_mark_unattached_ap(entry_conn,
1078  }
1079  control_event_general_error("DIR_ALL_UNREACHABLE");
1080 }
1081 
1082 static mainloop_event_t *directory_all_unreachable_cb_event = NULL;
1083 
1090 void
1092 {
1093  (void)now;
1094 
1095  reset_uptime(); /* reset it */
1096 
1097  if (!directory_all_unreachable_cb_event) {
1098  directory_all_unreachable_cb_event =
1100  tor_assert(directory_all_unreachable_cb_event);
1101  }
1102 
1103  mainloop_event_activate(directory_all_unreachable_cb_event);
1104 }
1105 
1108 void
1109 directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
1110 {
1111  const or_options_t *options = get_options();
1112 
1113  /* if we have enough dir info, then update our guard status with
1114  * whatever we just learned. */
1115  int invalidate_circs = guards_update_all();
1116 
1117  if (invalidate_circs) {
1120  }
1121 
1122  if (!router_have_minimum_dir_info()) {
1123  int quiet = suppress_logs || from_cache ||
1125  tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
1126  "I learned some more directory information, but not enough to "
1127  "build a circuit: %s", get_dir_info_status_string());
1129  return;
1130  } else {
1131  if (directory_fetches_from_authorities(options)) {
1133  }
1134 
1135  /* Don't even bother trying to get extrainfo until the rest of our
1136  * directory info is up-to-date */
1137  if (options->DownloadExtraInfo)
1139  }
1140 
1141  if (server_mode(options) && !net_is_disabled() && !from_cache &&
1144 }
1145 
1149 static void
1151 {
1152  cell_t cell;
1153  connection_t *conn = smartlist_get(connection_array, i);
1154  const or_options_t *options = get_options();
1155  or_connection_t *or_conn;
1156  channel_t *chan = NULL;
1157  int have_any_circuits;
1158  int past_keepalive =
1159  now >= conn->timestamp_last_write_allowed + options->KeepalivePeriod;
1160 
1161  if (conn->outbuf && !connection_get_outbuf_len(conn) &&
1162  conn->type == CONN_TYPE_OR)
1163  TO_OR_CONN(conn)->timestamp_lastempty = now;
1164 
1165  if (conn->marked_for_close) {
1166  /* nothing to do here */
1167  return;
1168  }
1169 
1170  /* Expire any directory connections that haven't been active (sent
1171  * if a server or received if a client) for 5 min */
1172  if (conn->type == CONN_TYPE_DIR &&
1173  ((DIR_CONN_IS_SERVER(conn) &&
1175  + options->TestingDirConnectionMaxStall < now) ||
1176  (!DIR_CONN_IS_SERVER(conn) &&
1178  + options->TestingDirConnectionMaxStall < now))) {
1179  log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
1180  (int)conn->s, conn->purpose);
1181  /* This check is temporary; it's to let us know whether we should consider
1182  * parsing partial serverdesc responses. */
1183  if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
1184  connection_get_inbuf_len(conn) >= 1024) {
1185  log_info(LD_DIR,"Trying to extract information from wedged server desc "
1186  "download.");
1188  } else {
1189  connection_mark_for_close(conn);
1190  }
1191  return;
1192  }
1193 
1194  if (!connection_speaks_cells(conn))
1195  return; /* we're all done here, the rest is just for OR conns */
1196 
1197  /* If we haven't flushed to an OR connection for a while, then either nuke
1198  the connection or send a keepalive, depending. */
1199 
1200  or_conn = TO_OR_CONN(conn);
1201  tor_assert(conn->outbuf);
1202 
1203  chan = TLS_CHAN_TO_BASE(or_conn->chan);
1204  tor_assert(chan);
1205 
1206  if (channel_num_circuits(chan) != 0) {
1207  have_any_circuits = 1;
1208  chan->timestamp_last_had_circuits = now;
1209  } else {
1210  have_any_circuits = 0;
1211  }
1212 
1213  if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan)) &&
1214  ! have_any_circuits) {
1215  /* It's bad for new circuits, and has no unmarked circuits on it:
1216  * mark it now. */
1217  log_info(LD_OR,
1218  "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1219  (int)conn->s, conn->address, conn->port);
1220  if (conn->state == OR_CONN_STATE_CONNECTING)
1222  END_OR_CONN_REASON_TIMEOUT,
1223  "Tor gave up on the connection");
1225  } else if (!connection_state_is_open(conn)) {
1226  if (past_keepalive) {
1227  /* We never managed to actually get this connection open and happy. */
1228  log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
1229  (int)conn->s,conn->address, conn->port);
1231  }
1232  } else if (we_are_hibernating() &&
1233  ! have_any_circuits &&
1234  !connection_get_outbuf_len(conn)) {
1235  /* We're hibernating or shutting down, there's no circuits, and nothing to
1236  * flush.*/
1237  log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
1238  "[Hibernating or exiting].",
1239  (int)conn->s,conn->address, conn->port);
1241  } else if (!have_any_circuits &&
1242  now - or_conn->idle_timeout >=
1244  log_info(LD_OR,"Expiring non-used OR connection %"PRIu64" to fd %d "
1245  "(%s:%d) [no circuits for %d; timeout %d; %scanonical].",
1246  (chan->global_identifier),
1247  (int)conn->s, conn->address, conn->port,
1248  (int)(now - chan->timestamp_last_had_circuits),
1249  or_conn->idle_timeout,
1250  or_conn->is_canonical ? "" : "non");
1252  } else if (
1253  now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
1254  now >=
1255  conn->timestamp_last_write_allowed + options->KeepalivePeriod*10) {
1256  log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
1257  "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1258  "flush; %d seconds since last write)",
1259  (int)conn->s, conn->address, conn->port,
1260  (int)connection_get_outbuf_len(conn),
1261  (int)(now-conn->timestamp_last_write_allowed));
1263  } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
1264  /* send a padding cell */
1265  log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
1266  conn->address, conn->port);
1267  memset(&cell,0,sizeof(cell_t));
1268  cell.command = CELL_PADDING;
1269  connection_or_write_cell_to_buf(&cell, or_conn);
1270  } else {
1271  channelpadding_decide_to_pad_channel(chan);
1272  }
1273 }
1274 
1277 static void
1278 signewnym_impl(time_t now)
1279 {
1280  const or_options_t *options = get_options();
1281  if (!proxy_mode(options)) {
1282  log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
1283  "is disabled.");
1284  return;
1285  }
1286 
1289  hs_client_purge_state();
1290  time_of_last_signewnym = now;
1292 
1293  ++newnym_epoch;
1294 
1295  control_event_signal(SIGNEWNYM);
1296 }
1297 
1299 static void
1301 {
1302  (void)event;
1303  (void)arg;
1304  log_info(LD_CONTROL, "Honoring delayed NEWNYM request");
1305  do_signewnym(time(NULL));
1306 }
1307 
1309 void
1310 do_signewnym(time_t now)
1311 {
1313  const time_t delay_sec =
1315  if (! signewnym_is_pending) {
1320  }
1321  const struct timeval delay_tv = { delay_sec, 0 };
1323  }
1324  log_notice(LD_CONTROL,
1325  "Rate limiting NEWNYM request: delaying by %d second(s)",
1326  (int)(delay_sec));
1327  } else {
1328  signewnym_impl(now);
1329  }
1330 }
1331 
1333 unsigned
1335 {
1336  return newnym_epoch;
1337 }
1338 
1342 
1343 /* Declare all the timer callback functions... */
1344 #undef CALLBACK
1345 #define CALLBACK(name) \
1346  static int name ## _callback(time_t, const or_options_t *)
1347 CALLBACK(add_entropy);
1348 CALLBACK(check_authority_cert);
1349 CALLBACK(check_canonical_channels);
1350 CALLBACK(check_descriptor);
1351 CALLBACK(check_dns_honesty);
1352 CALLBACK(check_ed_keys);
1353 CALLBACK(check_expired_networkstatus);
1354 CALLBACK(check_for_reachability_bw);
1355 CALLBACK(check_onion_keys_expiry_time);
1356 CALLBACK(clean_caches);
1357 CALLBACK(clean_consdiffmgr);
1358 CALLBACK(dirvote);
1359 CALLBACK(downrate_stability);
1360 CALLBACK(expire_old_ciruits_serverside);
1361 CALLBACK(fetch_networkstatus);
1362 CALLBACK(heartbeat);
1363 CALLBACK(hs_service);
1364 CALLBACK(launch_descriptor_fetches);
1365 CALLBACK(launch_reachability_tests);
1366 CALLBACK(prune_old_routers);
1367 CALLBACK(reachability_warnings);
1368 CALLBACK(record_bridge_stats);
1369 CALLBACK(rend_cache_failure_clean);
1370 CALLBACK(reset_padding_counts);
1371 CALLBACK(retry_dns);
1372 CALLBACK(retry_listeners);
1373 CALLBACK(rotate_onion_key);
1374 CALLBACK(rotate_x509_certificate);
1375 CALLBACK(save_stability);
1376 CALLBACK(save_state);
1377 CALLBACK(write_bridge_ns);
1378 CALLBACK(write_stats_file);
1379 CALLBACK(control_per_second_events);
1380 CALLBACK(second_elapsed);
1381 
1382 #undef CALLBACK
1383 
1384 /* Now we declare an array of periodic_event_item_t for each periodic event */
1385 #define CALLBACK(name, r, f) \
1386  PERIODIC_EVENT(name, PERIODIC_EVENT_ROLE_ ## r, f)
1387 #define FL(name) (PERIODIC_EVENT_FLAG_ ## name)
1388 
1389 STATIC periodic_event_item_t periodic_events[] = {
1390 
1391  /* Everyone needs to run these. They need to have very long timeouts for
1392  * that to be safe. */
1393  CALLBACK(add_entropy, ALL, 0),
1394  CALLBACK(heartbeat, ALL, 0),
1395  CALLBACK(reset_padding_counts, ALL, 0),
1396 
1397  /* This is a legacy catch-all callback that runs once per second if
1398  * we are online and active. */
1399  CALLBACK(second_elapsed, NET_PARTICIPANT,
1400  FL(NEED_NET)|FL(RUN_ON_DISABLE)),
1401 
1402  /* XXXX Do we have a reason to do this on a callback? Does it do any good at
1403  * all? For now, if we're dormant, we can let our listeners decay. */
1404  CALLBACK(retry_listeners, NET_PARTICIPANT, FL(NEED_NET)),
1405 
1406  /* We need to do these if we're participating in the Tor network. */
1407  CALLBACK(check_expired_networkstatus, NET_PARTICIPANT, 0),
1408  CALLBACK(fetch_networkstatus, NET_PARTICIPANT, 0),
1409  CALLBACK(launch_descriptor_fetches, NET_PARTICIPANT, FL(NEED_NET)),
1410  CALLBACK(rotate_x509_certificate, NET_PARTICIPANT, 0),
1411  CALLBACK(check_network_participation, NET_PARTICIPANT, 0),
1412 
1413  /* We need to do these if we're participating in the Tor network, and
1414  * immediately before we stop. */
1415  CALLBACK(clean_caches, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1416  CALLBACK(save_state, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1417  CALLBACK(write_stats_file, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1418  CALLBACK(prune_old_routers, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1419 
1420  /* Routers (bridge and relay) only. */
1421  CALLBACK(check_descriptor, ROUTER, FL(NEED_NET)),
1422  CALLBACK(check_ed_keys, ROUTER, 0),
1423  CALLBACK(check_for_reachability_bw, ROUTER, FL(NEED_NET)),
1424  CALLBACK(check_onion_keys_expiry_time, ROUTER, 0),
1425  CALLBACK(expire_old_ciruits_serverside, ROUTER, FL(NEED_NET)),
1426  CALLBACK(reachability_warnings, ROUTER, FL(NEED_NET)),
1427  CALLBACK(retry_dns, ROUTER, 0),
1428  CALLBACK(rotate_onion_key, ROUTER, 0),
1429 
1430  /* Authorities (bridge and directory) only. */
1431  CALLBACK(downrate_stability, AUTHORITIES, 0),
1432  CALLBACK(launch_reachability_tests, AUTHORITIES, FL(NEED_NET)),
1433  CALLBACK(save_stability, AUTHORITIES, 0),
1434 
1435  /* Directory authority only. */
1436  CALLBACK(check_authority_cert, DIRAUTH, 0),
1437  CALLBACK(dirvote, DIRAUTH, FL(NEED_NET)),
1438 
1439  /* Relay only. */
1440  CALLBACK(check_canonical_channels, RELAY, FL(NEED_NET)),
1441  CALLBACK(check_dns_honesty, RELAY, FL(NEED_NET)),
1442 
1443  /* Hidden Service service only. */
1444  CALLBACK(hs_service, HS_SERVICE, FL(NEED_NET)), // XXXX break this down more
1445 
1446  /* Bridge only. */
1447  CALLBACK(record_bridge_stats, BRIDGE, 0),
1448 
1449  /* Client only. */
1450  /* XXXX this could be restricted to CLIENT+NET_PARTICIPANT */
1451  CALLBACK(rend_cache_failure_clean, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
1452 
1453  /* Bridge Authority only. */
1454  CALLBACK(write_bridge_ns, BRIDGEAUTH, 0),
1455 
1456  /* Directory server only. */
1457  CALLBACK(clean_consdiffmgr, DIRSERVER, 0),
1458 
1459  /* Controller with per-second events only. */
1460  CALLBACK(control_per_second_events, CONTROLEV, 0),
1461 
1462  END_OF_PERIODIC_EVENTS
1463 };
1464 #undef CALLBACK
1465 #undef FL
1466 
1467 /* These are pointers to members of periodic_events[] that are used to
1468  * implement particular callbacks. We keep them separate here so that we
1469  * can access them by name. We also keep them inside periodic_events[]
1470  * so that we can implement "reset all timers" in a reasonable way. */
1471 static periodic_event_item_t *check_descriptor_event=NULL;
1472 static periodic_event_item_t *dirvote_event=NULL;
1473 static periodic_event_item_t *fetch_networkstatus_event=NULL;
1474 static periodic_event_item_t *launch_descriptor_fetches_event=NULL;
1475 static periodic_event_item_t *check_dns_honesty_event=NULL;
1476 static periodic_event_item_t *save_state_event=NULL;
1477 static periodic_event_item_t *prune_old_routers_event=NULL;
1478 
1484 void
1486 {
1487  int i;
1488  for (i = 0; periodic_events[i].name; ++i) {
1489  periodic_event_reschedule(&periodic_events[i]);
1490  }
1491 }
1492 
1496 static periodic_event_item_t *
1497 find_periodic_event(const char *name)
1498 {
1499  int i;
1500  for (i = 0; periodic_events[i].name; ++i) {
1501  if (strcmp(name, periodic_events[i].name) == 0)
1502  return &periodic_events[i];
1503  }
1504  return NULL;
1505 }
1506 
1509 STATIC int
1511 {
1512  tor_assert(options);
1513 
1514  int roles = PERIODIC_EVENT_ROLE_ALL;
1515  int is_bridge = options->BridgeRelay;
1516  int is_relay = server_mode(options);
1517  int is_dirauth = authdir_mode_v3(options);
1518  int is_bridgeauth = authdir_mode_bridge(options);
1519  int is_hidden_service = !!hs_service_get_num_services() ||
1520  !!rend_num_services();
1521  int is_dirserver = dir_server_mode(options);
1522  int sending_control_events = control_any_per_second_event_enabled();
1523 
1524  /* We also consider tor to have the role of a client if the ControlPort is
1525  * set because a lot of things can be done over the control port which
1526  * requires tor to have basic functionnalities. */
1527  int is_client = options_any_client_port_set(options) ||
1528  options->ControlPort_set ||
1529  options->OwningControllerFD != UINT64_MAX;
1530 
1531  int is_net_participant = is_participating_on_network() ||
1532  is_relay || is_hidden_service;
1533 
1534  if (is_bridge) roles |= PERIODIC_EVENT_ROLE_BRIDGE;
1535  if (is_client) roles |= PERIODIC_EVENT_ROLE_CLIENT;
1536  if (is_relay) roles |= PERIODIC_EVENT_ROLE_RELAY;
1537  if (is_dirauth) roles |= PERIODIC_EVENT_ROLE_DIRAUTH;
1538  if (is_bridgeauth) roles |= PERIODIC_EVENT_ROLE_BRIDGEAUTH;
1539  if (is_hidden_service) roles |= PERIODIC_EVENT_ROLE_HS_SERVICE;
1540  if (is_dirserver) roles |= PERIODIC_EVENT_ROLE_DIRSERVER;
1541  if (is_net_participant) roles |= PERIODIC_EVENT_ROLE_NET_PARTICIPANT;
1542  if (sending_control_events) roles |= PERIODIC_EVENT_ROLE_CONTROLEV;
1543 
1544  return roles;
1545 }
1546 
1548 static struct event *initialize_periodic_events_event = NULL;
1549 
1555 static void
1556 initialize_periodic_events_cb(evutil_socket_t fd, short events, void *data)
1557 {
1558  (void) fd;
1559  (void) events;
1560  (void) data;
1561 
1562  tor_event_free(initialize_periodic_events_event);
1563 
1564  rescan_periodic_events(get_options());
1565 }
1566 
1569 STATIC void
1571 {
1573  return;
1574 
1576 
1577  /* Set up all periodic events. We'll launch them by roles. */
1578  int i;
1579  for (i = 0; periodic_events[i].name; ++i) {
1580  periodic_event_setup(&periodic_events[i]);
1581  }
1582 
1583 #define NAMED_CALLBACK(name) \
1584  STMT_BEGIN name ## _event = find_periodic_event( #name ); STMT_END
1585 
1586  NAMED_CALLBACK(check_descriptor);
1587  NAMED_CALLBACK(prune_old_routers);
1588  NAMED_CALLBACK(dirvote);
1589  NAMED_CALLBACK(fetch_networkstatus);
1590  NAMED_CALLBACK(launch_descriptor_fetches);
1591  NAMED_CALLBACK(check_dns_honesty);
1592  NAMED_CALLBACK(save_state);
1593 
1594  struct timeval one_second = { 1, 0 };
1595  initialize_periodic_events_event = tor_evtimer_new(
1596  tor_libevent_get_base(),
1598  event_add(initialize_periodic_events_event, &one_second);
1599 }
1600 
1601 STATIC void
1602 teardown_periodic_events(void)
1603 {
1604  int i;
1605  for (i = 0; periodic_events[i].name; ++i) {
1606  periodic_event_destroy(&periodic_events[i]);
1607  }
1609 }
1610 
1611 static mainloop_event_t *rescan_periodic_events_ev = NULL;
1612 
1614 static void
1616 {
1617  (void)event;
1618  (void)arg;
1619  rescan_periodic_events(get_options());
1620 }
1621 
1626 schedule_rescan_periodic_events,(void))
1627 {
1628  if (!rescan_periodic_events_ev) {
1629  rescan_periodic_events_ev =
1631  }
1632  mainloop_event_activate(rescan_periodic_events_ev);
1633 }
1634 
1637 void
1639 {
1640  tor_assert(options);
1641 
1642  /* Avoid scanning the event list if we haven't initialized it yet. This is
1643  * particularly useful for unit tests in order to avoid initializing main
1644  * loop events everytime. */
1646  return;
1647  }
1648 
1649  int roles = get_my_roles(options);
1650 
1651  for (int i = 0; periodic_events[i].name; ++i) {
1652  periodic_event_item_t *item = &periodic_events[i];
1653 
1654  int enable = !!(item->roles & roles);
1655 
1656  /* Handle the event flags. */
1657  if (net_is_disabled() &&
1658  (item->flags & PERIODIC_EVENT_FLAG_NEED_NET)) {
1659  enable = 0;
1660  }
1661 
1662  /* Enable the event if needed. It is safe to enable an event that was
1663  * already enabled. Same goes for disabling it. */
1664  if (enable) {
1665  log_debug(LD_GENERAL, "Launching periodic event %s", item->name);
1666  periodic_event_enable(item);
1667  } else {
1668  log_debug(LD_GENERAL, "Disabling periodic event %s", item->name);
1669  if (item->flags & PERIODIC_EVENT_FLAG_RUN_ON_DISABLE) {
1671  } else {
1672  periodic_event_disable(item);
1673  }
1674  }
1675  }
1676 }
1677 
1678 /* We just got new options globally set, see if we need to enabled or disable
1679  * periodic events. */
1680 void
1681 periodic_events_on_new_options(const or_options_t *options)
1682 {
1683  /* Only if we've already initialized the events, rescan the list which will
1684  * enable or disable events depending on our roles. This will be called at
1685  * bootup and we don't want this function to initialize the events because
1686  * they aren't set up at this stage. */
1688  rescan_periodic_events(options);
1689  }
1690 }
1691 
1697 void
1699 {
1700  if (check_descriptor_event) {
1701  periodic_event_reschedule(check_descriptor_event);
1702  }
1703 }
1704 
1709 void
1711 {
1712  tor_assert(fetch_networkstatus_event);
1713  tor_assert(launch_descriptor_fetches_event);
1714 
1715  periodic_event_reschedule(fetch_networkstatus_event);
1716  periodic_event_reschedule(launch_descriptor_fetches_event);
1717 }
1718 
1721 static void
1723 {
1724  (void)ev;
1725  (void)arg;
1730 }
1731 
1734 
1737 void
1739 {
1740  if (PREDICT_UNLIKELY(postloop_cleanup_ev == NULL)) {
1741  // (It's possible that we can get here if we decide to close a connection
1742  // in the earliest stages of our configuration, before we create events.)
1743  return;
1744  }
1746 }
1747 
1750 
1752 static void
1754 {
1755  (void)ev;
1756  (void)arg;
1757  log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
1759 }
1760 
1762 void
1764 {
1765  const struct timeval delay_tv = { delay_sec, 0 };
1766  if (! scheduled_shutdown_ev) {
1768  }
1770 }
1771 
1772 #define LONGEST_TIMER_PERIOD (30 * 86400)
1773 
1775 static inline int
1776 safe_timer_diff(time_t now, time_t next)
1777 {
1778  if (next > now) {
1779  /* There were no computers at signed TIME_MIN (1902 on 32-bit systems),
1780  * and nothing that could run Tor. It's a bug if 'next' is around then.
1781  * On 64-bit systems with signed TIME_MIN, TIME_MIN is before the Big
1782  * Bang. We cannot extrapolate past a singularity, but there was probably
1783  * nothing that could run Tor then, either.
1784  **/
1785  tor_assert(next > TIME_MIN + LONGEST_TIMER_PERIOD);
1786 
1787  if (next - LONGEST_TIMER_PERIOD > now)
1788  return LONGEST_TIMER_PERIOD;
1789  return (int)(next - now);
1790  } else {
1791  return 1;
1792  }
1793 }
1794 
1798 static int
1799 second_elapsed_callback(time_t now, const or_options_t *options)
1800 {
1801  /* 0. See if our bandwidth limits are exhausted and we should hibernate
1802  *
1803  * Note: we have redundant mechanisms to handle the case where it's
1804  * time to wake up from hibernation; or where we have a scheduled
1805  * shutdown and it's time to run it, but this will also handle those.
1806  */
1807  consider_hibernation(now);
1808 
1809  /* Maybe enough time elapsed for us to reconsider a circuit. */
1811 
1812  if (options->UseBridges && !net_is_disabled()) {
1813  /* Note: this check uses net_is_disabled(), not should_delay_dir_fetches()
1814  * -- the latter is only for fetching consensus-derived directory info. */
1815  // TODO: client
1816  // Also, schedule this rather than probing 1x / sec
1817  fetch_bridge_descriptors(options, now);
1818  }
1819 
1820  if (accounting_is_enabled(options)) {
1821  // TODO: refactor or rewrite?
1823  }
1824 
1825  /* 3a. Every second, we examine pending circuits and prune the
1826  * ones which have been pending for more than a few seconds.
1827  * We do this before step 4, so it can try building more if
1828  * it's not comfortable with the number of available circuits.
1829  */
1830  /* (If our circuit build timeout can ever become lower than a second (which
1831  * it can't, currently), we should do this more often.) */
1832  // TODO: All expire stuff can become NET_PARTICIPANT, RUN_ON_DISABLE
1835 
1836  /* 3b. Also look at pending streams and prune the ones that 'began'
1837  * a long time ago but haven't gotten a 'connected' yet.
1838  * Do this before step 4, so we can put them back into pending
1839  * state to be picked up by the new circuit.
1840  */
1842 
1843  /* 3c. And expire connections that we've held open for too long.
1844  */
1846 
1847  /* 4. Every second, we try a new circuit if there are no valid
1848  * circuits. Every NewCircuitPeriod seconds, we expire circuits
1849  * that became dirty more than MaxCircuitDirtiness seconds ago,
1850  * and we make a new circ if there are no clean circuits.
1851  */
1852  const int have_dir_info = router_have_minimum_dir_info();
1853  if (have_dir_info && !net_is_disabled()) {
1855  } else {
1857  }
1858 
1859  /* 5. We do housekeeping for each connection... */
1861  int i;
1862  for (i=0;i<smartlist_len(connection_array);i++) {
1864  }
1865 
1866  /* Run again in a second. */
1867  return 1;
1868 }
1869 
1870 /* Periodic callback: rotate the onion keys after the period defined by the
1871  * "onion-key-rotation-days" consensus parameter, shut down and restart all
1872  * cpuworkers, and update our descriptor if necessary.
1873  */
1874 static int
1875 rotate_onion_key_callback(time_t now, const or_options_t *options)
1876 {
1877  if (server_mode(options)) {
1878  int onion_key_lifetime = get_onion_key_lifetime();
1879  time_t rotation_time = get_onion_key_set_at()+onion_key_lifetime;
1880  if (rotation_time > now) {
1882  }
1883 
1884  log_info(LD_GENERAL,"Rotating onion key.");
1885  rotate_onion_key();
1887  if (router_rebuild_descriptor(1)<0) {
1888  log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
1889  }
1890  if (advertised_server_mode() && !net_is_disabled())
1893  }
1894  return PERIODIC_EVENT_NO_UPDATE;
1895 }
1896 
1897 /* Period callback: Check if our old onion keys are still valid after the
1898  * period of time defined by the consensus parameter
1899  * "onion-key-grace-period-days", otherwise expire them by setting them to
1900  * NULL.
1901  */
1902 static int
1903 check_onion_keys_expiry_time_callback(time_t now, const or_options_t *options)
1904 {
1905  if (server_mode(options)) {
1906  int onion_key_grace_period = get_onion_key_grace_period();
1907  time_t expiry_time = get_onion_key_set_at()+onion_key_grace_period;
1908  if (expiry_time > now) {
1910  }
1911 
1912  log_info(LD_GENERAL, "Expiring old onion keys.");
1916  }
1917 
1918  return PERIODIC_EVENT_NO_UPDATE;
1919 }
1920 
1921 /* Periodic callback: Every 30 seconds, check whether it's time to make new
1922  * Ed25519 subkeys.
1923  */
1924 static int
1925 check_ed_keys_callback(time_t now, const or_options_t *options)
1926 {
1927  if (server_mode(options)) {
1928  if (should_make_new_ed_keys(options, now)) {
1929  int new_signing_key = load_ed_keys(options, now);
1930  if (new_signing_key < 0 ||
1931  generate_ed_link_cert(options, now, new_signing_key > 0)) {
1932  log_err(LD_OR, "Unable to update Ed25519 keys! Exiting.");
1934  }
1935  }
1936  return 30;
1937  }
1938  return PERIODIC_EVENT_NO_UPDATE;
1939 }
1940 
1946 static int
1948 {
1949  if (should_delay_dir_fetches(options, NULL))
1950  return PERIODIC_EVENT_NO_UPDATE;
1951 
1954  if (router_have_minimum_dir_info())
1956  else
1958 }
1959 
1964 static int
1966 {
1967  static int first = 1;
1968  (void)now;
1969  (void)options;
1970  if (first) {
1971  first = 0;
1973  }
1974 
1975  /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1976  * TLS context. */
1977  log_info(LD_GENERAL,"Rotating tls context.");
1978  if (router_initialize_tls_context() < 0) {
1979  log_err(LD_BUG, "Error reinitializing TLS context");
1980  tor_assert_unreached();
1981  }
1982  if (generate_ed_link_cert(options, now, 1)) {
1983  log_err(LD_OR, "Unable to update Ed25519->TLS link certificate for "
1984  "new TLS context.");
1985  tor_assert_unreached();
1986  }
1987 
1988  /* We also make sure to rotate the TLS connections themselves if they've
1989  * been up for too long -- but that's done via is_bad_for_new_circs in
1990  * run_connection_housekeeping() above. */
1992 }
1993 
1998 static int
1999 add_entropy_callback(time_t now, const or_options_t *options)
2000 {
2001  (void)now;
2002  (void)options;
2003  /* We already seeded once, so don't die on failure. */
2004  if (crypto_seed_rng() < 0) {
2005  log_warn(LD_GENERAL, "Tried to re-seed RNG, but failed. We already "
2006  "seeded once, though, so we won't exit here.");
2007  }
2008 
2010 #define ENTROPY_INTERVAL (60*60)
2011  return ENTROPY_INTERVAL;
2012 }
2013 
2016 STATIC int
2018 {
2019  /* If we're a server, we can't become dormant. */
2020  if (server_mode(options)) {
2021  goto found_activity;
2022  }
2023 
2024  /* If we're running an onion service, we can't become dormant. */
2025  /* XXXX this would be nice to change, so that we can be dormant with a
2026  * service. */
2027  if (hs_service_get_num_services() || rend_num_services()) {
2028  goto found_activity;
2029  }
2030 
2031  /* If we have any currently open entry streams other than "linked"
2032  * connections used for directory requests, those count as user activity.
2033  */
2034  if (options->DormantTimeoutDisabledByIdleStreams) {
2035  if (connection_get_by_type_nonlinked(CONN_TYPE_AP) != NULL) {
2036  goto found_activity;
2037  }
2038  }
2039 
2040  /* XXXX Make this configurable? */
2042 #define CHECK_PARTICIPATION_INTERVAL (5*60)
2043 
2044  /* Become dormant if there has been no user activity in a long time.
2045  * (The funny checks below are in order to prevent overflow.) */
2046  time_t time_since_last_activity = 0;
2047  if (get_last_user_activity_time() < now)
2048  time_since_last_activity = now - get_last_user_activity_time();
2049  if (time_since_last_activity >= options->DormantClientTimeout) {
2050  log_notice(LD_GENERAL, "No user activity in a long time: becoming"
2051  " dormant.");
2052  set_network_participation(false);
2053  rescan_periodic_events(options);
2054  }
2055 
2056  return CHECK_PARTICIPATION_INTERVAL;
2057 
2058  found_activity:
2059  note_user_activity(now);
2060  return CHECK_PARTICIPATION_INTERVAL;
2061 }
2062 
2067 static int
2069 {
2070  if (authdir_mode_tests_reachability(options) &&
2071  !net_is_disabled()) {
2072  /* try to determine reachability of the other Tor relays */
2074  }
2076 }
2077 
2082 static int
2083 downrate_stability_callback(time_t now, const or_options_t *options)
2084 {
2085  (void)options;
2086  /* 1d. Periodically, we discount older stability information so that new
2087  * stability info counts more, and save the stability information to disk as
2088  * appropriate. */
2089  time_t next = rep_hist_downrate_old_runs(now);
2090  return safe_timer_diff(now, next);
2091 }
2092 
2097 static int
2098 save_stability_callback(time_t now, const or_options_t *options)
2099 {
2100  if (authdir_mode_tests_reachability(options)) {
2101  if (rep_hist_record_mtbf_data(now, 1)<0) {
2102  log_warn(LD_GENERAL, "Couldn't store mtbf data.");
2103  }
2104  }
2105 #define SAVE_STABILITY_INTERVAL (30*60)
2106  return SAVE_STABILITY_INTERVAL;
2107 }
2108 
2113 static int
2114 check_authority_cert_callback(time_t now, const or_options_t *options)
2115 {
2116  (void)now;
2117  (void)options;
2118  /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
2119  * close to expiring and warn the admin if it is. */
2121 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
2122  return CHECK_V3_CERTIFICATE_INTERVAL;
2123 }
2124 
2131 static int
2132 dirvote_callback(time_t now, const or_options_t *options)
2133 {
2134  if (!authdir_mode_v3(options)) {
2135  tor_assert_nonfatal_unreached();
2136  return 3600;
2137  }
2138 
2139  time_t next = dirvote_act(options, now);
2140  if (BUG(next == TIME_MAX)) {
2141  /* This shouldn't be returned unless we called dirvote_act() without
2142  * being an authority. If it happens, maybe our configuration will
2143  * fix itself in an hour or so? */
2144  return 3600;
2145  }
2146  return safe_timer_diff(now, next);
2147 }
2148 
2151 void
2153 {
2154  if (periodic_events_initialized && authdir_mode_v3(options)) {
2155  periodic_event_reschedule(dirvote_event);
2156  }
2157 }
2158 
2163 static int
2165 {
2166  (void)options;
2167  /* Check whether our networkstatus has expired. */
2168  networkstatus_t *ns = networkstatus_get_latest_consensus();
2169  /* Use reasonably live consensuses until they are no longer reasonably live.
2170  */
2171  if (ns && !networkstatus_consensus_reasonably_live(ns, now) &&
2172  router_have_minimum_dir_info()) {
2174  }
2175 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
2176  return CHECK_EXPIRED_NS_INTERVAL;
2177 }
2178 
2182 static int
2183 save_state_callback(time_t now, const or_options_t *options)
2184 {
2185  (void) options;
2186  (void) or_state_save(now); // only saves if appropriate
2187  const time_t next_write = get_or_state()->next_write;
2188  if (next_write == TIME_MAX) {
2189  return 86400;
2190  }
2191  return safe_timer_diff(now, next_write);
2192 }
2193 
2197 void
2199 {
2200  if (save_state_event == NULL) {
2201  /* This can happen early on during startup. */
2202  return;
2203  }
2204  periodic_event_reschedule(save_state_event);
2205 }
2206 
2210 static int
2211 write_stats_file_callback(time_t now, const or_options_t *options)
2212 {
2213  /* 1g. Check whether we should write statistics to disk.
2214  */
2215 #define CHECK_WRITE_STATS_INTERVAL (60*60)
2216  time_t next_time_to_write_stats_files = now + CHECK_WRITE_STATS_INTERVAL;
2217  if (options->CellStatistics) {
2218  time_t next_write =
2220  if (next_write && next_write < next_time_to_write_stats_files)
2221  next_time_to_write_stats_files = next_write;
2222  }
2223  if (options->DirReqStatistics) {
2224  time_t next_write = geoip_dirreq_stats_write(now);
2225  if (next_write && next_write < next_time_to_write_stats_files)
2226  next_time_to_write_stats_files = next_write;
2227  }
2228  if (options->EntryStatistics) {
2229  time_t next_write = geoip_entry_stats_write(now);
2230  if (next_write && next_write < next_time_to_write_stats_files)
2231  next_time_to_write_stats_files = next_write;
2232  }
2233  if (options->HiddenServiceStatistics) {
2234  time_t next_write = rep_hist_hs_stats_write(now);
2235  if (next_write && next_write < next_time_to_write_stats_files)
2236  next_time_to_write_stats_files = next_write;
2237  }
2238  if (options->ExitPortStatistics) {
2239  time_t next_write = rep_hist_exit_stats_write(now);
2240  if (next_write && next_write < next_time_to_write_stats_files)
2241  next_time_to_write_stats_files = next_write;
2242  }
2243  if (options->ConnDirectionStatistics) {
2244  time_t next_write = rep_hist_conn_stats_write(now);
2245  if (next_write && next_write < next_time_to_write_stats_files)
2246  next_time_to_write_stats_files = next_write;
2247  }
2248  if (options->BridgeAuthoritativeDir) {
2249  time_t next_write = rep_hist_desc_stats_write(now);
2250  if (next_write && next_write < next_time_to_write_stats_files)
2251  next_time_to_write_stats_files = next_write;
2252  }
2253 
2254  return safe_timer_diff(now, next_time_to_write_stats_files);
2255 }
2256 
2257 #define CHANNEL_CHECK_INTERVAL (60*60)
2258 static int
2259 check_canonical_channels_callback(time_t now, const or_options_t *options)
2260 {
2261  (void)now;
2262  if (public_server_mode(options))
2264 
2265  return CHANNEL_CHECK_INTERVAL;
2266 }
2267 
2268 static int
2269 reset_padding_counts_callback(time_t now, const or_options_t *options)
2270 {
2271  if (options->PaddingStatistics) {
2272  rep_hist_prep_published_padding_counts(now);
2273  }
2274 
2277 }
2278 
2279 static int should_init_bridge_stats = 1;
2280 
2284 static int
2285 record_bridge_stats_callback(time_t now, const or_options_t *options)
2286 {
2287  /* 1h. Check whether we should write bridge statistics to disk.
2288  */
2289  if (should_record_bridge_info(options)) {
2290  if (should_init_bridge_stats) {
2291  /* (Re-)initialize bridge statistics. */
2293  should_init_bridge_stats = 0;
2294  return WRITE_STATS_INTERVAL;
2295  } else {
2296  /* Possibly write bridge statistics to disk and ask when to write
2297  * them next time. */
2298  time_t next = geoip_bridge_stats_write(now);
2299  return safe_timer_diff(now, next);
2300  }
2301  } else if (!should_init_bridge_stats) {
2302  /* Bridge mode was turned off. Ensure that stats are re-initialized
2303  * next time bridge mode is turned on. */
2304  should_init_bridge_stats = 1;
2305  }
2306  return PERIODIC_EVENT_NO_UPDATE;
2307 }
2308 
2312 static int
2313 clean_caches_callback(time_t now, const or_options_t *options)
2314 {
2315  /* Remove old information from rephist and the rend cache. */
2316  rep_history_clean(now - options->RephistTrackTime);
2317  rend_cache_clean(now, REND_CACHE_TYPE_SERVICE);
2318  hs_cache_clean_as_client(now);
2319  hs_cache_clean_as_dir(now);
2320  microdesc_cache_rebuild(NULL, 0);
2321 #define CLEAN_CACHES_INTERVAL (30*60)
2322  return CLEAN_CACHES_INTERVAL;
2323 }
2324 
2329 static int
2331 {
2332  (void)options;
2333  /* We don't keep entries that are more than five minutes old so we try to
2334  * clean it as soon as we can since we want to make sure the client waits
2335  * as little as possible for reachability reasons. */
2337  hs_cache_client_intro_state_clean(now);
2338  return 30;
2339 }
2340 
2344 static int
2345 retry_dns_callback(time_t now, const or_options_t *options)
2346 {
2347  (void)now;
2348 #define RETRY_DNS_INTERVAL (10*60)
2349  if (server_mode(options) && has_dns_init_failed())
2350  dns_init();
2351  return RETRY_DNS_INTERVAL;
2352 }
2353 
2357 static int
2358 prune_old_routers_callback(time_t now, const or_options_t *options)
2359 {
2360 #define ROUTERLIST_PRUNING_INTERVAL (60*60) // 1 hour.
2361  (void)now;
2362  (void)options;
2363 
2364  if (!net_is_disabled()) {
2365  /* If any networkstatus documents are no longer recent, we need to
2366  * update all the descriptors' running status. */
2367  /* Remove dead routers. */
2368  log_debug(LD_GENERAL, "Pruning routerlist...");
2370  }
2371 
2372  return ROUTERLIST_PRUNING_INTERVAL;
2373 }
2374 
2377 static int
2378 check_descriptor_callback(time_t now, const or_options_t *options)
2379 {
2383 #define CHECK_DESCRIPTOR_INTERVAL (60)
2384 
2385  (void)options;
2386 
2387  /* 2b. Once per minute, regenerate and upload the descriptor if the old
2388  * one is inaccurate. */
2389  if (!net_is_disabled()) {
2394  }
2395 
2396  return CHECK_DESCRIPTOR_INTERVAL;
2397 }
2398 
2404 static int
2406 {
2407  /* XXXX This whole thing was stuck in the middle of what is now
2408  * XXXX check_descriptor_callback. I'm not sure it's right. */
2409 
2410  static int dirport_reachability_count = 0;
2411  /* also, check religiously for reachability, if it's within the first
2412  * 20 minutes of our uptime. */
2413  if (server_mode(options) &&
2415  !net_is_disabled()) {
2416  if (get_uptime() < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
2417  router_do_reachability_checks(1, dirport_reachability_count==0);
2418  if (++dirport_reachability_count > 5)
2419  dirport_reachability_count = 0;
2420  return 1;
2421  } else {
2422  /* If we haven't checked for 12 hours and our bandwidth estimate is
2423  * low, do another bandwidth test. This is especially important for
2424  * bridges, since they might go long periods without much use. */
2425  const routerinfo_t *me = router_get_my_routerinfo();
2426  static int first_time = 1;
2427  if (!first_time && me &&
2428  me->bandwidthcapacity < me->bandwidthrate &&
2429  me->bandwidthcapacity < 51200) {
2431  }
2432  first_time = 0;
2433 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
2434  return BANDWIDTH_RECHECK_INTERVAL;
2435  }
2436  }
2437  return CHECK_DESCRIPTOR_INTERVAL;
2438 }
2439 
2444 static int
2445 fetch_networkstatus_callback(time_t now, const or_options_t *options)
2446 {
2447  /* How often do we check whether we should download network status
2448  * documents? */
2449  const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
2450  now);
2451  const int prefer_mirrors = !directory_fetches_from_authorities(
2452  get_options());
2453  int networkstatus_dl_check_interval = 60;
2454  /* check more often when testing, or when bootstrapping from mirrors
2455  * (connection limits prevent too many connections being made) */
2456  if (options->TestingTorNetwork
2457  || (we_are_bootstrapping && prefer_mirrors)) {
2458  networkstatus_dl_check_interval = 1;
2459  }
2460 
2461  if (should_delay_dir_fetches(options, NULL))
2462  return PERIODIC_EVENT_NO_UPDATE;
2463 
2465  return networkstatus_dl_check_interval;
2466 }
2467 
2470 static int
2471 retry_listeners_callback(time_t now, const or_options_t *options)
2472 {
2473  (void)now;
2474  (void)options;
2475  if (!net_is_disabled()) {
2476  retry_all_listeners(NULL, 0);
2477  return 60;
2478  }
2479  return PERIODIC_EVENT_NO_UPDATE;
2480 }
2481 
2485 static int
2487 {
2488  (void)options;
2489  /* every 11 seconds, so not usually the same second as other such events */
2491  return 11;
2492 }
2493 
2497 static int
2499 {
2500  (void) now;
2501 
2502  if (get_uptime() < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
2503  return (int)(TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT - get_uptime());
2504  }
2505 
2506  if (server_mode(options) &&
2507  !net_is_disabled() &&
2509  /* every 20 minutes, check and complain if necessary */
2510  const routerinfo_t *me = router_get_my_routerinfo();
2511  if (me && !check_whether_orport_reachable(options)) {
2512  char *address = tor_dup_ip(me->addr);
2513  log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
2514  "its ORPort is reachable. Relays do not publish descriptors "
2515  "until their ORPort and DirPort are reachable. Please check "
2516  "your firewalls, ports, address, /etc/hosts file, etc.",
2517  address, me->or_port);
2519  "REACHABILITY_FAILED ORADDRESS=%s:%d",
2520  address, me->or_port);
2521  tor_free(address);
2522  }
2523 
2524  if (me && !check_whether_dirport_reachable(options)) {
2525  char *address = tor_dup_ip(me->addr);
2526  log_warn(LD_CONFIG,
2527  "Your server (%s:%d) has not managed to confirm that its "
2528  "DirPort is reachable. Relays do not publish descriptors "
2529  "until their ORPort and DirPort are reachable. Please check "
2530  "your firewalls, ports, address, /etc/hosts file, etc.",
2531  address, me->dir_port);
2533  "REACHABILITY_FAILED DIRADDRESS=%s:%d",
2534  address, me->dir_port);
2535  tor_free(address);
2536  }
2537  }
2538 
2540 }
2541 
2542 static int dns_honesty_first_time = 1;
2543 
2548 static int
2549 check_dns_honesty_callback(time_t now, const or_options_t *options)
2550 {
2551  (void)now;
2552  /* 9. and if we're an exit node, check whether our DNS is telling stories
2553  * to us. */
2554  if (net_is_disabled() ||
2555  ! public_server_mode(options) ||
2556  router_my_exit_policy_is_reject_star())
2557  return PERIODIC_EVENT_NO_UPDATE;
2558 
2559  if (dns_honesty_first_time) {
2560  /* Don't launch right when we start */
2561  dns_honesty_first_time = 0;
2562  return crypto_rand_int_range(60, 180);
2563  }
2564 
2566  return 12*3600 + crypto_rand_int(12*3600);
2567 }
2568 
2573 static int
2574 write_bridge_ns_callback(time_t now, const or_options_t *options)
2575 {
2576  /* 10. write bridge networkstatus file to disk */
2577  if (options->BridgeAuthoritativeDir) {
2579 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
2580  return BRIDGE_STATUSFILE_INTERVAL;
2581  }
2582  return PERIODIC_EVENT_NO_UPDATE;
2583 }
2584 
2585 static int heartbeat_callback_first_time = 1;
2586 
2593 static int
2594 heartbeat_callback(time_t now, const or_options_t *options)
2595 {
2596  /* Check if heartbeat is disabled */
2597  if (!options->HeartbeatPeriod) {
2598  return PERIODIC_EVENT_NO_UPDATE;
2599  }
2600 
2601  /* Skip the first one. */
2602  if (heartbeat_callback_first_time) {
2603  heartbeat_callback_first_time = 0;
2604  return options->HeartbeatPeriod;
2605  }
2606 
2607  /* Write the heartbeat message */
2608  if (log_heartbeat(now) == 0) {
2609  return options->HeartbeatPeriod;
2610  } else {
2611  /* If we couldn't write the heartbeat log message, try again in the minimum
2612  * interval of time. */
2613  return MIN_HEARTBEAT_PERIOD;
2614  }
2615 }
2616 
2617 #define CDM_CLEAN_CALLBACK_INTERVAL 600
2618 static int
2619 clean_consdiffmgr_callback(time_t now, const or_options_t *options)
2620 {
2621  (void)now;
2622  if (dir_server_mode(options)) {
2623  consdiffmgr_cleanup();
2624  }
2625  return CDM_CLEAN_CALLBACK_INTERVAL;
2626 }
2627 
2628 /*
2629  * Periodic callback: Run scheduled events for HS service. This is called
2630  * every second.
2631  */
2632 static int
2633 hs_service_callback(time_t now, const or_options_t *options)
2634 {
2635  (void) options;
2636 
2637  /* We need to at least be able to build circuits and that we actually have
2638  * a working network. */
2639  if (!have_completed_a_circuit() || net_is_disabled() ||
2640  networkstatus_get_live_consensus(now) == NULL) {
2641  goto end;
2642  }
2643 
2644  hs_service_run_scheduled_events(now);
2645 
2646  end:
2647  /* Every 1 second. */
2648  return 1;
2649 }
2650 
2651 /*
2652  * Periodic callback: Send once-per-second events to the controller(s).
2653  * This is called every second.
2654  */
2655 static int
2656 control_per_second_events_callback(time_t now, const or_options_t *options)
2657 {
2658  (void) options;
2659  (void) now;
2660 
2662 
2663  return 1;
2664 }
2665 
2667 static time_t current_second = 0;
2669 static monotime_coarse_t current_second_last_changed;
2670 
2676 void
2678 {
2679  if (PREDICT_LIKELY(now == current_second)) {
2680  /* We call this function a lot. Most frequently, the current second
2681  * will not have changed, so we just return. */
2682  return;
2683  }
2684 
2685  const time_t seconds_elapsed = current_second ? (now - current_second) : 0;
2686 
2687  /* Check the wall clock against the monotonic clock, so we can
2688  * better tell idleness from clock jumps and/or other shenanigans. */
2689  monotime_coarse_t last_updated;
2690  memcpy(&last_updated, &current_second_last_changed, sizeof(last_updated));
2691  monotime_coarse_get(&current_second_last_changed);
2692 
2695 #define NUM_JUMPED_SECONDS_BEFORE_NETSTATUS_UPDATE 20
2696 
2697  /* Don't go dormant early or late just because we jumped in time. */
2698  if (ABS(seconds_elapsed) >= NUM_JUMPED_SECONDS_BEFORE_NETSTATUS_UPDATE) {
2699  if (is_participating_on_network()) {
2700  netstatus_note_clock_jumped(seconds_elapsed);
2701  }
2702  }
2703 
2705 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
2706 
2708 #define NUM_IDLE_SECONDS_BEFORE_WARN 3600
2709 
2710  if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN) {
2711  // moving back in time is always a bad sign.
2712  circuit_note_clock_jumped(seconds_elapsed, false);
2713 
2714  } else if (seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
2715  /* Compare the monotonic clock to the result of time(). */
2716  const int32_t monotime_msec_passed =
2717  monotime_coarse_diff_msec32(&last_updated,
2719  const int monotime_sec_passed = monotime_msec_passed / 1000;
2720  const int discrepancy = monotime_sec_passed - (int)seconds_elapsed;
2721  /* If the monotonic clock deviates from time(NULL), we have a couple of
2722  * possibilities. On some systems, this means we have been suspended or
2723  * sleeping. Everywhere, it can mean that the wall-clock time has
2724  * been changed -- for example, with settimeofday().
2725  *
2726  * On the other hand, if the monotonic time matches with the wall-clock
2727  * time, we've probably just been idle for a while, with no events firing.
2728  * we tolerate much more of that.
2729  */
2730  const bool clock_jumped = abs(discrepancy) > 2;
2731 
2732  if (clock_jumped || seconds_elapsed >= NUM_IDLE_SECONDS_BEFORE_WARN) {
2733  circuit_note_clock_jumped(seconds_elapsed, ! clock_jumped);
2734  }
2735  } else if (seconds_elapsed > 0) {
2736  stats_n_seconds_working += seconds_elapsed;
2737  }
2738 
2739  update_approx_time(now);
2740  current_second = now;
2741 }
2742 
2743 #ifdef HAVE_SYSTEMD_209
2744 static periodic_timer_t *systemd_watchdog_timer = NULL;
2745 
2747 static void
2748 systemd_watchdog_callback(periodic_timer_t *timer, void *arg)
2749 {
2750  (void)timer;
2751  (void)arg;
2752  sd_notify(0, "WATCHDOG=1");
2753 }
2754 #endif /* defined(HAVE_SYSTEMD_209) */
2755 
2756 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
2757 
2761 void
2762 ip_address_changed(int at_interface)
2763 {
2764  const or_options_t *options = get_options();
2765  int server = server_mode(options);
2766  int exit_reject_interfaces = (server && options->ExitRelay
2767  && options->ExitPolicyRejectLocalInterfaces);
2768 
2769  if (at_interface) {
2770  if (! server) {
2771  /* Okay, change our keys. */
2772  if (init_keys_client() < 0)
2773  log_warn(LD_GENERAL, "Unable to rotate keys after IP change!");
2774  }
2775  } else {
2776  if (server) {
2777  if (get_uptime() > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
2779  reset_uptime();
2781  }
2782  }
2783 
2784  /* Exit relays incorporate interface addresses in their exit policies when
2785  * ExitPolicyRejectLocalInterfaces is set */
2786  if (exit_reject_interfaces || (server && !at_interface)) {
2787  mark_my_descriptor_dirty("IP address changed");
2788  }
2789 
2791 }
2792 
2795 void
2797 {
2798  if (server_mode(get_options())) {
2801  tor_assert(check_dns_honesty_event);
2802  periodic_event_reschedule(check_dns_honesty_event);
2803  }
2804  }
2805 }
2806 
2808 void
2810 {
2812 
2816  }
2817  if (!postloop_cleanup_ev) {
2820  }
2821 }
2822 
2824 int
2826 {
2827  /* initialize the periodic events first, so that code that depends on the
2828  * events being present does not assert.
2829  */
2832 
2833 #ifdef HAVE_SYSTEMD_209
2834  uint64_t watchdog_delay;
2835  /* set up systemd watchdog notification. */
2836  if (sd_watchdog_enabled(1, &watchdog_delay) > 0) {
2837  if (! systemd_watchdog_timer) {
2838  struct timeval watchdog;
2839  /* The manager will "act on" us if we don't send them a notification
2840  * every 'watchdog_delay' microseconds. So, send notifications twice
2841  * that often. */
2842  watchdog_delay /= 2;
2843  watchdog.tv_sec = watchdog_delay / 1000000;
2844  watchdog.tv_usec = watchdog_delay % 1000000;
2845 
2846  systemd_watchdog_timer = periodic_timer_new(tor_libevent_get_base(),
2847  &watchdog,
2848  systemd_watchdog_callback,
2849  NULL);
2850  tor_assert(systemd_watchdog_timer);
2851  }
2852  }
2853 #endif /* defined(HAVE_SYSTEMD_209) */
2854 #ifdef ENABLE_RESTART_DEBUGGING
2855  {
2856  static int first_time = 1;
2857 
2858  if (first_time && getenv("TOR_DEBUG_RESTART")) {
2859  first_time = 0;
2860  const char *sec_str = getenv("TOR_DEBUG_RESTART_AFTER_SECONDS");
2861  long sec;
2862  int sec_ok=0;
2863  if (sec_str &&
2864  (sec = tor_parse_long(sec_str, 10, 0, INT_MAX, &sec_ok, NULL)) &&
2865  sec_ok) {
2866  /* Okay, we parsed the seconds. */
2867  } else {
2868  sec = 5;
2869  }
2870  struct timeval restart_after = { (time_t) sec, 0 };
2871  tor_shutdown_event_loop_for_restart_event =
2872  tor_evtimer_new(tor_libevent_get_base(),
2873  tor_shutdown_event_loop_for_restart_cb, NULL);
2874  event_add(tor_shutdown_event_loop_for_restart_event, &restart_after);
2875  }
2876  }
2877 #endif
2878 
2879  return run_main_loop_until_done();
2880 }
2881 
2882 #ifndef _WIN32
2883 
2884 static ratelim_t libevent_error_ratelim = RATELIM_INIT(10);
2885 #endif
2886 
2891 static int
2893 {
2894  int loop_result;
2895 
2896  if (nt_service_is_stopping())
2897  return 0;
2898 
2900  return 0;
2901 
2902 #ifndef _WIN32
2903  /* Make it easier to tell whether libevent failure is our fault or not. */
2904  errno = 0;
2905 #endif
2906 
2907  if (get_options()->MainloopStats) {
2908  /* We always enforce that EVLOOP_ONCE is passed to event_base_loop() if we
2909  * are collecting main loop statistics. */
2910  called_loop_once = 1;
2911  } else {
2912  called_loop_once = 0;
2913  }
2914 
2915  /* Make sure we know (about) what time it is. */
2916  update_approx_time(time(NULL));
2917 
2918  /* Here it is: the main loop. Here we tell Libevent to poll until we have
2919  * an event, or the second ends, or until we have some active linked
2920  * connections to trigger events for. Libevent will wait till one
2921  * of these happens, then run all the appropriate callbacks. */
2922  loop_result = tor_libevent_run_event_loop(tor_libevent_get_base(),
2924 
2925  if (get_options()->MainloopStats) {
2926  /* Update our main loop counters. */
2927  if (loop_result == 0) {
2928  // The call was successful.
2930  } else if (loop_result == -1) {
2931  // The call was erroneous.
2933  } else if (loop_result == 1) {
2934  // The call didn't have any active or pending events
2935  // to handle.
2937  }
2938  }
2939 
2940  /* Oh, the loop failed. That might be an error that we need to
2941  * catch, but more likely, it's just an interrupted poll() call or something,
2942  * and we should try again. */
2943  if (loop_result < 0) {
2944  int e = tor_socket_errno(-1);
2945  /* let the program survive things like ^z */
2946  if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
2947  log_err(LD_NET,"libevent call with %s failed: %s [%d]",
2948  tor_libevent_get_method(), tor_socket_strerror(e), e);
2949  return -1;
2950 #ifndef _WIN32
2951  } else if (e == EINVAL) {
2953  "EINVAL from libevent: should you upgrade libevent?");
2954  if (libevent_error_ratelim.n_calls_since_last_time > 8) {
2955  log_err(LD_NET, "Too many libevent errors, too fast: dying");
2956  return -1;
2957  }
2958 #endif /* !defined(_WIN32) */
2959  } else {
2960  tor_assert_nonfatal_once(! ERRNO_IS_EINPROGRESS(e));
2961  log_debug(LD_NET,"libevent call interrupted.");
2962  /* You can't trust the results of this poll(). Go back to the
2963  * top of the big for loop. */
2964  return 1;
2965  }
2966  }
2967 
2969  return 0;
2970 
2971  return 1;
2972 }
2973 
2979 STATIC int
2981 {
2982  int loop_result = 1;
2983 
2986 
2987  do {
2988  loop_result = run_main_loop_once();
2989  } while (loop_result == 1);
2990 
2992  return main_loop_exit_value;
2993  else
2994  return loop_result;
2995 }
2996 
2999 get_uptime,(void))
3000 {
3001  return stats_n_seconds_working;
3002 }
3003 
3006 reset_uptime,(void))
3007 {
3009 }
3010 
3011 void
3012 tor_mainloop_free_all(void)
3013 {
3014  smartlist_free(connection_array);
3015  smartlist_free(closeable_connection_lst);
3016  smartlist_free(active_linked_connection_lst);
3017  teardown_periodic_events();
3018  tor_event_free(shutdown_did_not_work_event);
3019  tor_event_free(initialize_periodic_events_event);
3020  mainloop_event_free(directory_all_unreachable_cb_event);
3021  mainloop_event_free(schedule_active_linked_connections_event);
3022  mainloop_event_free(postloop_cleanup_ev);
3023  mainloop_event_free(handle_deferred_signewnym_ev);
3024  mainloop_event_free(scheduled_shutdown_ev);
3025  mainloop_event_free(rescan_periodic_events_ev);
3026 
3027 #ifdef HAVE_SYSTEMD_209
3028  periodic_timer_free(systemd_watchdog_timer);
3029 #endif
3030 
3032 
3033  memset(&global_bucket, 0, sizeof(global_bucket));
3034  memset(&global_relayed_bucket, 0, sizeof(global_relayed_bucket));
3038  newnym_epoch = 0;
3039  called_loop_once = 0;
3043  quiet_level = 0;
3044  should_init_bridge_stats = 1;
3045  dns_honesty_first_time = 1;
3046  heartbeat_callback_first_time = 1;
3047  current_second = 0;
3048  memset(&current_second_last_changed, 0,
3049  sizeof(current_second_last_changed));
3050 }
tor_socket_t s
Definition: connection_st.h:88
static int rend_cache_failure_clean_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2330
Header file for dirserv.c.
static int connection_should_read_from_linked_conn(connection_t *conn)
Definition: mainloop.c:718
Header for statefile.c.
STATIC int run_main_loop_until_done(void)
Definition: mainloop.c:2980
static int run_main_loop_once(void)
Definition: mainloop.c:2892
time_t time_of_process_start
Definition: mainloop.c:145
void update_all_descriptor_downloads(time_t now)
Definition: routerlist.c:2211
int ExitPolicyRejectLocalInterfaces
static void handle_deferred_signewnym_cb(mainloop_event_t *event, void *arg)
Definition: mainloop.c:1300
uint64_t get_main_loop_error_count(void)
Definition: mainloop.c:551
static void connection_unlink(connection_t *conn)
Definition: mainloop.c:343
static int32_t monotime_coarse_diff_msec32(const monotime_coarse_t *start, const monotime_coarse_t *end)
Definition: compat_time.h:292
int authdir_mode_tests_reachability(const or_options_t *options)
Definition: authmode.c:59
Header file for channeltls.c.
void directory_all_unreachable(time_t now)
Definition: mainloop.c:1091
unsigned int channel_num_circuits(channel_t *chan)
Definition: channel.c:3335
void connection_or_close_normally(or_connection_t *orconn, int flush)
int router_rebuild_descriptor(int force)
Definition: router.c:2149
int rend_num_services(void)
Definition: rendservice.c:183
int connection_remove(connection_t *conn)
Definition: mainloop.c:300
int ExitPortStatistics
Header file for circuitbuild.c.
time_t rep_hist_downrate_old_runs(time_t now)
Definition: rephist.c:382
Common functions for using (pseudo-)random number generators.
int connection_is_moribund(connection_t *conn)
Definition: connection.c:5068
static void increment_main_loop_error_count(void)
Definition: mainloop.c:544
Header file containing service data for the HS subsytem.
void assert_connection_edge_not_dns_pending(edge_connection_t *conn)
Definition: dns.c:966
void periodic_event_enable(periodic_event_item_t *event)
Definition: periodic.c:144
#define ONION_KEY_CONSENSUS_CHECK_INTERVAL
Definition: or.h:152
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Header for backtrace.c.
static periodic_event_item_t * find_periodic_event(const char *name)
Definition: mainloop.c:1497
uint64_t get_main_loop_idle_count(void)
Definition: mainloop.c:565
int connection_dir_reached_eof(dir_connection_t *conn)
Definition: dirclient.c:2988
time_t dirvote_act(const or_options_t *options, time_t now)
Definition: dirvote.c:2829
void update_current_time(time_t now)
Definition: mainloop.c:2677
Header file for geoip_stats.c.
static void rescan_periodic_events_cb(mainloop_event_t *event, void *arg)
Definition: mainloop.c:1615
int dir_server_mode(const or_options_t *options)
Definition: routermode.c:20
int quiet_level
Definition: main.c:134
Header file containing client data for the HS subsytem.
Header for buffers_tls.c.
static int clean_caches_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2313
const char * name
Definition: periodic.h:63
void router_dir_info_changed(void)
Definition: nodelist.c:2234
Header file for connection.c.
static int rotate_x509_certificate_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1965
void connection_or_connect_failed(or_connection_t *conn, int reason, const char *msg)
STATIC void initialize_periodic_events(void)
Definition: mainloop.c:1570
int control_event_signal(uintptr_t signal_num)
Definition: control.c:6677
void connection_stop_reading_from_linked_conn(connection_t *conn)
Definition: mainloop.c:818
int guards_update_all(void)
Definition: entrynodes.c:3596
Definition: cell_st.h:12
#define LD_GENERAL
Definition: log.h:58
static void schedule_active_linked_connections_cb(mainloop_event_t *event, void *arg)
Definition: mainloop.c:390
int buf_flush_to_socket(buf_t *buf, tor_socket_t s, size_t sz, size_t *buf_flushlen)
Definition: buffers_net.c:231
unsigned int proxy_state
Definition: connection_st.h:84
static uint64_t stats_n_bytes_written
Definition: mainloop.c:143
uint8_t state
Definition: connection_st.h:44
#define LOG_INFO
Definition: log.h:41
Header file for nodelist.c.
void reschedule_or_state_save(void)
Definition: mainloop.c:2198
static int launch_reachability_tests_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2068
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:631
int dns_init(void)
Definition: dns.c:224
void stats_increment_bytes_read_and_written(uint64_t r, uint64_t w)
Definition: mainloop.c:486
static time_t time_of_last_signewnym
Definition: mainloop.c:158
Header file for ntmain.c.
int DormantTimeoutDisabledByIdleStreams
Header file for directory.c.
void smartlist_add(smartlist_t *sl, void *element)
static int record_bridge_stats_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2285
void note_that_we_maybe_cant_complete_circuits(void)
Definition: mainloop.c:237
int any_predicted_circuits(time_t now)
unsigned get_signewnym_epoch(void)
Definition: mainloop.c:1334
static int check_dns_honesty_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2549
void v3_authority_check_key_expiry(void)
Definition: router.c:701
#define ABS(x)
Definition: cmp.h:40
#define GREEDY_DESCRIPTOR_RETRY_INTERVAL
Definition: mainloop.c:197
char address[MAX_SOCKS_ADDR_LEN]
static int heartbeat_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2594
void note_that_we_completed_a_circuit(void)
Definition: mainloop.c:229
#define REACHABILITY_TEST_INTERVAL
Definition: reachability.h:21
int router_initialize_tls_context(void)
Definition: router.c:788
void circuit_expire_building(void)
Definition: circuituse.c:453
const char * safe_str_client(const char *address)
Definition: config.c:1059
int authdir_mode_bridge(const or_options_t *options)
Definition: authmode.c:67
int HiddenServiceStatistics
int smartlist_contains(const smartlist_t *sl, const void *element)
static smartlist_t * active_linked_connection_lst
Definition: mainloop.c:173
Header file for config.c.
static struct event * shutdown_did_not_work_event
Definition: mainloop.c:730
#define CONN_TYPE_OR
Definition: connection.h:24
void router_do_reachability_checks(int test_or, int test_dir)
Definition: selftest.c:171
const char * conn_type_to_string(int type)
Definition: connection.c:241
static int check_expired_networkstatus_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2164
int tor_libevent_run_event_loop(struct event_base *base, int once)
struct connection_t * linked_conn
Header file for microdesc.c.
int control_event_general_error(const char *format,...)
Definition: control.c:6816
unsigned int writing_to_linked_conn
Definition: connection_st.h:75
Header file for cpuworker.c.
void rep_history_clean(time_t before)
Definition: rephist.c:593
int directory_fetches_from_authorities(const or_options_t *options)
Definition: dirserv.c:77
unsigned int reading_from_linked_conn
Definition: connection_st.h:73
uint16_t port
int should_record_bridge_info(const or_options_t *options)
Definition: geoip_stats.c:112
time_t get_onion_key_set_at(void)
Definition: router.c:326
Header file for reachability.c.
void mainloop_schedule_postloop_cleanup(void)
Definition: mainloop.c:1738
int directory_too_idle_to_fetch_descriptors(const or_options_t *options, time_t now)
Definition: dirserv.c:169
#define tor_free(p)
Definition: malloc.h:52
int do_main_loop(void)
Definition: mainloop.c:2825
void rend_cache_clean(time_t now, rend_cache_type_t cache_type)
Definition: rendcache.c:276
void tor_shutdown_event_loop_and_exit(int exitcode)
Definition: mainloop.c:767
#define tor_fragile_assert()
Definition: util_bug.h:221
void initialize_mainloop_events(void)
Definition: mainloop.c:2809
#define REPHIST_CELL_PADDING_COUNTS_INTERVAL
Definition: rephist.h:125
#define END_STREAM_REASON_NET_UNREACHABLE
Definition: or.h:253
#define LOG_NOTICE
Definition: log.h:46
mainloop_event_t * mainloop_event_postloop_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
int connection_is_reading(connection_t *conn)
Definition: mainloop.c:511
time_t rep_hist_hs_stats_write(time_t now)
Definition: rephist.c:2666
void circuit_build_needed_circs(time_t now)
Definition: circuituse.c:1329
const char * conn_state_to_string(int type, int state)
Definition: connection.c:273
int crypto_rand_int(unsigned int max)
Definition: crypto_rand.c:548
int networkstatus_consensus_reasonably_live(const networkstatus_t *consensus, time_t now)
Header file for mainloop.c.
void accounting_run_housekeeping(time_t now)
Definition: hibernate.c:585
void mainloop_event_activate(mainloop_event_t *event)
void dirserv_test_reachability(time_t now)
Definition: reachability.c:179
void control_per_second_events(void)
Definition: control.c:462
uint64_t get_main_loop_success_count(void)
Definition: mainloop.c:537
void dns_reset_correctness_checks(void)
Definition: dns.c:2080
void router_reset_reachability(void)
Definition: selftest.c:48
static int retry_dns_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2345
void channel_update_bad_for_new_circs(const char *digest, int force)
Definition: channel.c:3457
unsigned int purpose
Definition: connection_st.h:46
void connection_or_clear_identity(or_connection_t *conn)
edge_connection_t * TO_EDGE_CONN(connection_t *c)
static struct event * initialize_periodic_events_event
Definition: mainloop.c:1548
or_connection_t * TO_OR_CONN(connection_t *c)
static int conn_close_if_marked(int i)
Definition: mainloop.c:946
static int dirvote_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2132
Header file for dnsserv.c.
size_t outbuf_flushlen
Definition: connection_st.h:96
time_t geoip_bridge_stats_write(time_t now)
Definition: geoip_stats.c:1237
void connection_unregister_events(connection_t *conn)
Definition: mainloop.c:278
void networkstatus_dump_bridge_status_to_file(time_t now)
unsigned int linked
Definition: connection_st.h:70
unsigned int active_on_link
Definition: connection_st.h:78
Header file for directory authority mode.
time_t timestamp_lastempty
void reset_all_main_loop_timers(void)
Definition: mainloop.c:1485
int retry_all_listeners(smartlist_t *new_conns, int close_all_noncontrol)
Definition: connection.c:2887
void check_descriptor_ipaddress_changed(time_t now)
Definition: router.c:2341
int connection_wants_to_flush(connection_t *conn)
Definition: connection.c:3897
int buf_move_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
Definition: buffers.c:654
#define SOCKET_OK(s)
Definition: nettypes.h:39
int connection_is_on_closeable_list(connection_t *conn)
Definition: mainloop.c:438
static ratelim_t libevent_error_ratelim
Definition: mainloop.c:2884
socks_request_t * socks_request
Header file for hibernate.c.
static int periodic_events_initialized
Definition: mainloop.c:1341
uint32_t bandwidthrate
Definition: routerinfo_st.h:51
time_t rep_hist_conn_stats_write(time_t now)
Definition: rephist.c:2408
static smartlist_t * closeable_connection_lst
Definition: mainloop.c:170
void consider_hibernation(time_t now)
Definition: hibernate.c:1098
#define MIN_HEARTBEAT_PERIOD
Definition: config.h:24
struct buf_t * inbuf
Definition: connection_st.h:93
void rep_hist_reset_padding_counts(void)
Definition: rephist.c:2784
Header file for channel.c.
void directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
Definition: mainloop.c:1109
static monotime_coarse_t current_second_last_changed
Definition: mainloop.c:2669
static int check_for_reachability_bw_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2405
#define DIR_PURPOSE_FETCH_SERVERDESC
Definition: directory.h:38
tor_assert(buffer)
static void initialize_periodic_events_cb(evutil_socket_t fd, short events, void *data)
Definition: mainloop.c:1556
void circuit_expire_old_circuits_serverside(time_t now)
Definition: circuituse.c:1562
#define LD_CONTROL
Definition: log.h:76
static void run_connection_housekeeping(int i, time_t now)
Definition: mainloop.c:1150
void reschedule_descriptor_update_check(void)
Definition: mainloop.c:1698
static int called_loop_once
Definition: mainloop.c:177
static int prune_old_routers_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2358
Header file for routermode.c.
int TestingDirConnectionMaxStall
int has_dns_init_failed(void)
Definition: dns.c:266
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition: directory.c:77
void reschedule_dirvote(const or_options_t *options)
Definition: mainloop.c:2152
void channel_run_cleanup(void)
Definition: channel.c:2119
int conn_array_index
Definition: connection_st.h:89
int load_ed_keys(const or_options_t *options, time_t now)
Definition: routerkeys.c:55
void channel_check_for_duplicates(void)
Definition: channel.c:748
static int downrate_stability_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2083
Header file for rendcache.c.
int log_heartbeat(time_t now)
Definition: status.c:119
Header file for circuitbuild.c.
static int save_stability_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2098
void mark_my_descriptor_dirty_if_too_old(time_t now)
Definition: router.c:2203
Master header file for Tor-specific functionality.
enum watchable_events watchable_events_t
void periodic_event_schedule_and_disable(periodic_event_item_t *event)
Definition: periodic.c:177
time_t geoip_entry_stats_write(time_t now)
Definition: geoip_stats.c:1372
periodic_timer_t * periodic_timer_new(struct event_base *base, const struct timeval *tv, void(*cb)(periodic_timer_t *timer, void *data), void *data)
void connection_close_immediate(connection_t *conn)
Definition: connection.c:841
void rend_cache_failure_clean(time_t now)
Definition: rendcache.c:252
int options_any_client_port_set(const or_options_t *options)
Definition: config.c:8468
Header file for circuitbuild.c.
int should_make_new_ed_keys(const or_options_t *options, const time_t now)
Definition: routerkeys.c:421
static int expire_old_ciruits_serverside_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2486
static int signewnym_is_pending
Definition: mainloop.c:160
time_t rep_hist_buffer_stats_write(time_t now)
Definition: rephist.c:2032
#define OR_CONN_STATE_OPEN
Definition: orconn_event.h:51
uint16_t marked_for_close
void circuit_mark_all_unused_circs(void)
Definition: circuitlist.c:2091
#define AP_CONN_STATE_CIRCUIT_WAIT
static void shutdown_did_not_work_callback(evutil_socket_t fd, short event, void *arg) ATTR_NORETURN
Definition: mainloop.c:738
static int check_authority_cert_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2114
void periodic_event_reschedule(periodic_event_item_t *event)
Definition: periodic.c:88
static long stats_n_seconds_working
Definition: mainloop.c:147
static void directory_all_unreachable_cb(mainloop_event_t *event, void *arg)
Definition: mainloop.c:1061
Header file for rephist.c.
void smartlist_remove(smartlist_t *sl, const void *element)
void connection_write_bw_exhausted(connection_t *conn, bool is_global_bw)
Definition: connection.c:3336
void add_connection_to_closeable_list(connection_t *conn)
Definition: mainloop.c:427
#define LOG_WARN
Definition: log.h:49
unsigned int type
Definition: connection_st.h:45
void periodic_event_disable(periodic_event_item_t *event)
Definition: periodic.c:161
void connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
void connection_consider_empty_write_buckets(connection_t *conn)
Definition: connection.c:3376
int ConnDirectionStatistics
const char * tor_libevent_get_method(void)
unsigned int edge_has_sent_end
void dns_servers_relaunch_checks(void)
Definition: mainloop.c:2796
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:260
Header file for circuituse.c.
int microdesc_cache_rebuild(microdesc_cache_t *cache, int force)
Definition: microdesc.c:675
Header file for buffers_net.c.
#define MAX_SIGNEWNYM_RATE
Definition: mainloop.c:156
connection_t * connection_get_by_type_state(int type, int state)
Definition: connection.c:4453
static mainloop_event_t * handle_deferred_signewnym_ev
Definition: mainloop.c:162
int connection_in_array(connection_t *conn)
Definition: mainloop.c:445
static int main_loop_exit_value
Definition: mainloop.c:185
time_t timestamp_last_had_circuits
Definition: channel.h:454
void smartlist_del(smartlist_t *sl, int idx)
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2244
void do_signewnym(time_t now)
Definition: mainloop.c:1310
Header file for circuitlist.c.
void circuit_expire_old_circs_as_needed(time_t now)
Definition: circuituse.c:1352
int BridgeAuthoritativeDir
Header file for rendservice.c.
STATIC void close_closeable_connections(void)
Definition: mainloop.c:836
void routerlist_remove_old_routers(void)
Definition: routerlist.c:1801
Headers for transports.c.
void cpuworkers_rotate_keyinfo(void)
Definition: cpuworker.c:192
int connection_state_is_open(connection_t *conn)
Definition: connection.c:4609
static void increment_main_loop_idle_count(void)
Definition: mainloop.c:558
#define LD_OR
Definition: log.h:88
int get_onion_key_grace_period(void)
Definition: router.c:774
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
void circuit_expire_waiting_for_better_guard(void)
Definition: circuituse.c:849
int channel_is_bad_for_new_circs(channel_t *chan)
Definition: channel.c:2885
void circuit_close_all_marked(void)
Definition: circuitlist.c:658
static void postloop_cleanup_cb(mainloop_event_t *ev, void *arg)
Definition: mainloop.c:1722
void channel_listener_run_cleanup(void)
Definition: channel.c:2145
void mainloop_schedule_shutdown(int delay_sec)
Definition: mainloop.c:1763
ssize_t connection_bucket_write_limit(connection_t *conn, time_t now)
Definition: connection.c:3141
static uint64_t stats_n_main_loop_successes
Definition: mainloop.c:149
int tor_event_loop_shutdown_is_pending(void)
Definition: mainloop.c:791
struct buf_t * outbuf
Definition: connection_st.h:94
const char * get_dir_info_status_string(void)
Definition: nodelist.c:2245
STATIC int check_network_participation_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2017
#define CONN_TYPE_AP_DNS_LISTENER
Definition: connection.h:48
#define LD_DIR
Definition: log.h:84
int generate_ed_link_cert(const or_options_t *options, time_t now, int force)
Definition: routerkeys.c:365
#define LAZY_DESCRIPTOR_RETRY_INTERVAL
Definition: mainloop.c:200
static mainloop_event_t * schedule_active_linked_connections_event
Definition: mainloop.c:381
struct event * write_event
Definition: connection_st.h:92
int crypto_rand_int_range(unsigned int min, unsigned int max)
Definition: crypto_rand.c:575
static int add_entropy_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1999
Header file for connection_edge.c.
void router_upload_dir_desc_to_dirservers(int force)
Definition: router.c:1496
void connection_about_to_close_connection(connection_t *conn)
Definition: connection.c:810
void geoip_bridge_stats_init(time_t now)
Definition: geoip_stats.c:1064
int control_event_server_status(int severity, const char *format,...)
Definition: control.c:6847
void assert_connection_ok(connection_t *conn, time_t now)
Definition: connection.c:5218
static int launch_descriptor_fetches_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1947
void expire_old_onion_keys(void)
Definition: router.c:233
static int main_loop_should_exit
Definition: mainloop.c:181
static int can_complete_circuits
Definition: mainloop.c:193
void circuit_mark_all_dirty_circs_as_unusable(void)
Definition: circuitlist.c:2110
STATIC int get_my_roles(const or_options_t *options)
Definition: mainloop.c:1510
void rotate_onion_key(void)
Definition: router.c:462
void tor_libevent_exit_loop_after_callback(struct event_base *base)
Header file for dirvote.c.
#define SMARTLIST_FOREACH(sl, type, var, cmd)
static uint64_t stats_n_bytes_read
Definition: mainloop.c:141
STATIC smartlist_t * connection_array
Definition: mainloop.c:167
void reset_main_loop_counters(void)
Definition: mainloop.c:521
static int save_state_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2183
mainloop_event_t * mainloop_event_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
void consider_publishable_server(int force)
Definition: router.c:1384
time_t timestamp_last_read_allowed
Definition: connection_st.h:98
static void increment_main_loop_success_count(void)
Definition: mainloop.c:530
void periodic_event_setup(periodic_event_item_t *event)
Definition: periodic.c:98
void update_networkstatus_downloads(time_t now)
uint16_t dir_port
Definition: routerinfo_st.h:21
#define log_fn(severity, domain, args,...)
Definition: log.h:255
channel_tls_t * chan
#define CONN_TYPE_EXIT
Definition: connection.h:26
void fetch_bridge_descriptors(const or_options_t *options, time_t now)
Definition: bridges.c:722
uint64_t OwningControllerFD
static int second_elapsed_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:1799
struct event * read_event
Definition: connection_st.h:91
#define LOG_FN_CONN(conn, args)
Definition: control.h:122
void update_extrainfo_downloads(time_t now)
Definition: routerlist.c:2713
Header file for control.c.
void connection_expire_held_open(void)
Definition: connection.c:952
static mainloop_event_t * postloop_cleanup_ev
Definition: mainloop.c:1733
static int write_stats_file_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2211
time_t geoip_dirreq_stats_write(time_t now)
Definition: geoip_stats.c:1029
unsigned int hold_open_until_flushed
Definition: connection_st.h:56
int connection_is_writing(connection_t *conn)
Definition: mainloop.c:657
uint32_t bandwidthcapacity
Definition: routerinfo_st.h:55
static int check_descriptor_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2378
static int safe_timer_diff(time_t now, time_t next)
Definition: mainloop.c:1776
static uint64_t stats_n_main_loop_errors
Definition: mainloop.c:151
time_t rep_hist_desc_stats_write(time_t now)
Definition: rephist.c:2169
void rescan_periodic_events(const or_options_t *options)
Definition: mainloop.c:1638
int rep_hist_record_mtbf_data(time_t now, int missing_means_down)
Definition: rephist.c:626
#define LOG_DEBUG
Definition: log.h:38
int or_state_save(time_t now)
Definition: statefile.c:493
const char * marked_for_close_file
Header file for hs_cache.c.
void periodic_event_destroy(periodic_event_item_t *event)
Definition: periodic.c:132
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:56
int get_onion_key_lifetime(void)
Definition: router.c:764
uint32_t addr
Definition: routerinfo_st.h:19
static void scheduled_shutdown_cb(mainloop_event_t *ev, void *arg)
Definition: mainloop.c:1753
int buf_flush_to_tls(buf_t *buf, tor_tls_t *tls, size_t flushlen, size_t *buf_flushlen)
Definition: buffers_tls.c:142
void reschedule_directory_downloads(void)
Definition: mainloop.c:1710
#define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
Definition: or.h:549
static unsigned newnym_epoch
Definition: mainloop.c:164
Header file for buffers.c.
Header file for selftest.c.
int mainloop_event_schedule(mainloop_event_t *event, const struct timeval *tv)
int control_any_per_second_event_enabled(void)
Definition: control.c:420
uint8_t command
Definition: cell_st.h:14
#define CONN_TYPE_DIR
Definition: connection.h:35
void log_failed_proxy_connection(connection_t *conn)
Definition: connection.c:5422
int control_event_conn_bandwidth(connection_t *conn)
Definition: control.c:6144
Header file for connection_or.c.
static mainloop_event_t * scheduled_shutdown_ev
Definition: mainloop.c:1749
void reset_bandwidth_test(void)
Definition: circuituse.c:1597
static int connection_check_event(connection_t *conn, struct event *ev)
Definition: mainloop.c:574
#define MAX_SSL_KEY_LIFETIME_INTERNAL
Definition: or.h:155
void ip_address_changed(int at_interface)
Definition: mainloop.c:2762
static uint64_t stats_n_main_loop_idle
Definition: mainloop.c:153
#define LD_NET
Definition: log.h:62
static int fetch_networkstatus_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2445
#define OR_CONN_STATE_CONNECTING
Definition: orconn_event.h:29
int crypto_seed_rng(void)
Definition: crypto_rand.c:451
void connection_watch_events(connection_t *conn, watchable_events_t events)
Definition: mainloop.c:496
static void signewnym_impl(time_t now)
Definition: mainloop.c:1278
void addressmap_clear_transient(void)
Definition: addressmap.c:312
void connection_ap_expire_beginning(void)
static int retry_listeners_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2471
int connection_add_impl(connection_t *conn, int is_connecting)
Definition: mainloop.c:247
Header for compat_libevent.c.
static void connection_start_reading_from_linked_conn(connection_t *conn)
Definition: mainloop.c:800
void dnsserv_close_listener(connection_t *conn)
Definition: dnsserv.c:407
#define CONN_TYPE_AP
Definition: connection.h:31
static void conn_read_callback(evutil_socket_t fd, short event, void *_conn)
Definition: mainloop.c:870
MOCK_IMPL(smartlist_t *, get_connection_array,(void))
Definition: mainloop.c:453
static int write_bridge_ns_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2574
void tor_init_connection_lists(void)
Definition: mainloop.c:415
#define LD_PROTOCOL
Definition: log.h:68
void check_descriptor_bandwidth_changed(time_t now)
Definition: router.c:2273
time_t rep_hist_exit_stats_write(time_t now)
Definition: rephist.c:1755
static void conn_write_callback(evutil_socket_t fd, short event, void *_conn)
Definition: mainloop.c:902
int DormantClientTimeout
int proxy_mode(const or_options_t *options)
Definition: routermode.c:30
int should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
int check_whether_orport_reachable(const or_options_t *options)
Definition: selftest.c:74
static int reachability_warnings_callback(time_t now, const or_options_t *options)
Definition: mainloop.c:2498
unsigned int is_canonical
void update_approx_time(time_t now)
Definition: approx_time.c:41
static time_t current_second
Definition: mainloop.c:2667
time_t timestamp_last_write_allowed
Header file for networkstatus.c.
#define LD_BUG
Definition: log.h:82
Header file for dns.c.
void circuit_upgrade_circuits_from_guard_wait(void)
#define LD_CONFIG
Definition: log.h:64
Header file for routerlist.c.
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1089
uint16_t or_port
Definition: routerinfo_st.h:20
void dns_launch_correctness_checks(void)
Definition: dns.c:2044
int check_whether_dirport_reachable(const or_options_t *options)
Definition: selftest.c:91
void circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
int have_completed_a_circuit(void)
Definition: mainloop.c:221
int connection_edge_end_errno(edge_connection_t *conn)
uint64_t global_identifier
Definition: channel.h:197
char * tor_dup_ip(uint32_t addr)
Definition: address.c:1879