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