Merge branch 'maint-0.3.1' into maint-0.3.2
[tor/appveyor.git] / src / or / main.c
blob036ef1efd4f67a81d6c988284ec9acf3b5777237
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-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file main.c
9 * \brief Toplevel module. Handles signals, multiplexes between
10 * connections, implements main loop, and drives scheduled events.
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.
17 * Most events in Tor are driven from these callbacks:
18 * <ul>
19 * <li>conn_read_callback() and conn_write_callback() here, which are
20 * invoked when a socket is ready to read or write respectively.
21 * <li>signal_callback(), which handles incoming signals.
22 * </ul>
23 * Other events are used for specific purposes, or for building more complex
24 * control structures. If you search for usage of tor_libevent_new(), you
25 * will find all the events that we construct in Tor.
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().
34 * <li>The next most frequent operations happen after each invocation of the
35 * main loop, in run_main_loop_once().
37 * <li>Once per second, we run all of the operations listed in
38 * second_elapsed_callback(), and in its child, run_scheduled_events().
40 * <li>Once-a-second operations are handled in second_elapsed_callback().
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>
47 **/
49 #define MAIN_PRIVATE
50 #include "or.h"
51 #include "addressmap.h"
52 #include "backtrace.h"
53 #include "bridges.h"
54 #include "buffers.h"
55 #include "buffers_tls.h"
56 #include "channel.h"
57 #include "channeltls.h"
58 #include "channelpadding.h"
59 #include "circuitbuild.h"
60 #include "circuitlist.h"
61 #include "circuituse.h"
62 #include "command.h"
63 #include "compat_rust.h"
64 #include "compress.h"
65 #include "config.h"
66 #include "confparse.h"
67 #include "connection.h"
68 #include "connection_edge.h"
69 #include "connection_or.h"
70 #include "consdiffmgr.h"
71 #include "control.h"
72 #include "cpuworker.h"
73 #include "crypto_s2k.h"
74 #include "directory.h"
75 #include "dirserv.h"
76 #include "dirvote.h"
77 #include "dns.h"
78 #include "dnsserv.h"
79 #include "dos.h"
80 #include "entrynodes.h"
81 #include "geoip.h"
82 #include "hibernate.h"
83 #include "hs_cache.h"
84 #include "hs_circuitmap.h"
85 #include "hs_client.h"
86 #include "keypin.h"
87 #include "main.h"
88 #include "microdesc.h"
89 #include "networkstatus.h"
90 #include "nodelist.h"
91 #include "ntmain.h"
92 #include "onion.h"
93 #include "periodic.h"
94 #include "policies.h"
95 #include "protover.h"
96 #include "transports.h"
97 #include "relay.h"
98 #include "rendclient.h"
99 #include "rendcommon.h"
100 #include "rendservice.h"
101 #include "rephist.h"
102 #include "router.h"
103 #include "routerkeys.h"
104 #include "routerlist.h"
105 #include "routerparse.h"
106 #include "scheduler.h"
107 #include "shared_random.h"
108 #include "statefile.h"
109 #include "status.h"
110 #include "util_process.h"
111 #include "ext_orport.h"
112 #ifdef USE_DMALLOC
113 #include <dmalloc.h>
114 #endif
115 #include "memarea.h"
116 #include "sandbox.h"
118 #include <event2/event.h>
120 #ifdef HAVE_SYSTEMD
121 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
122 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
123 * Coverity. Here's a kludge to unconfuse it.
125 # define __INCLUDE_LEVEL__ 2
126 #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
127 #include <systemd/sd-daemon.h>
128 #endif /* defined(HAVE_SYSTEMD) */
130 void evdns_shutdown(int);
132 /********* PROTOTYPES **********/
134 static void dumpmemusage(int severity);
135 static void dumpstats(int severity); /* log stats */
136 static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
137 static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
138 static void second_elapsed_callback(periodic_timer_t *timer, void *args);
139 static int conn_close_if_marked(int i);
140 static void connection_start_reading_from_linked_conn(connection_t *conn);
141 static int connection_should_read_from_linked_conn(connection_t *conn);
142 static int run_main_loop_until_done(void);
143 static void process_signal(int sig);
145 /********* START VARIABLES **********/
146 int global_read_bucket; /**< Max number of bytes I can read this second. */
147 int global_write_bucket; /**< Max number of bytes I can write this second. */
149 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
150 int global_relayed_read_bucket;
151 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
152 int global_relayed_write_bucket;
153 /** What was the read bucket before the last second_elapsed_callback() call?
154 * (used to determine how many bytes we've read). */
155 static int stats_prev_global_read_bucket;
156 /** What was the write bucket before the last second_elapsed_callback() call?
157 * (used to determine how many bytes we've written). */
158 static int stats_prev_global_write_bucket;
160 /* DOCDOC stats_prev_n_read */
161 static uint64_t stats_prev_n_read = 0;
162 /* DOCDOC stats_prev_n_written */
163 static uint64_t stats_prev_n_written = 0;
165 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
166 /** How many bytes have we read since we started the process? */
167 static uint64_t stats_n_bytes_read = 0;
168 /** How many bytes have we written since we started the process? */
169 static uint64_t stats_n_bytes_written = 0;
170 /** What time did this process start up? */
171 time_t time_of_process_start = 0;
172 /** How many seconds have we been running? */
173 long stats_n_seconds_working = 0;
175 /** How often will we honor SIGNEWNYM requests? */
176 #define MAX_SIGNEWNYM_RATE 10
177 /** When did we last process a SIGNEWNYM request? */
178 static time_t time_of_last_signewnym = 0;
179 /** Is there a signewnym request we're currently waiting to handle? */
180 static int signewnym_is_pending = 0;
181 /** How many times have we called newnym? */
182 static unsigned newnym_epoch = 0;
184 /** Smartlist of all open connections. */
185 STATIC smartlist_t *connection_array = NULL;
186 /** List of connections that have been marked for close and need to be freed
187 * and removed from connection_array. */
188 static smartlist_t *closeable_connection_lst = NULL;
189 /** List of linked connections that are currently reading data into their
190 * inbuf from their partner's outbuf. */
191 static smartlist_t *active_linked_connection_lst = NULL;
192 /** Flag: Set to true iff we entered the current libevent main loop via
193 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
194 * to handle linked connections. */
195 static int called_loop_once = 0;
197 /** We set this to 1 when we've opened a circuit, so we can print a log
198 * entry to inform the user that Tor is working. We set it to 0 when
199 * we think the fact that we once opened a circuit doesn't mean we can do so
200 * any longer (a big time jump happened, when we notice our directory is
201 * heinously out-of-date, etc.
203 static int can_complete_circuits = 0;
205 /** How often do we check for router descriptors that we should download
206 * when we have too little directory info? */
207 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
208 /** How often do we check for router descriptors that we should download
209 * when we have enough directory info? */
210 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
212 /** Decides our behavior when no logs are configured/before any
213 * logs have been configured. For 0, we log notice to stdout as normal.
214 * For 1, we log warnings only. For 2, we log nothing.
216 int quiet_level = 0;
218 /********* END VARIABLES ************/
220 /****************************************************************************
222 * This section contains accessors and other methods on the connection_array
223 * variables (which are global within this file and unavailable outside it).
225 ****************************************************************************/
227 /** Return 1 if we have successfully built a circuit, and nothing has changed
228 * to make us think that maybe we can't.
231 have_completed_a_circuit(void)
233 return can_complete_circuits;
236 /** Note that we have successfully built a circuit, so that reachability
237 * testing and introduction points and so on may be attempted. */
238 void
239 note_that_we_completed_a_circuit(void)
241 can_complete_circuits = 1;
244 /** Note that something has happened (like a clock jump, or DisableNetwork) to
245 * make us think that maybe we can't complete circuits. */
246 void
247 note_that_we_maybe_cant_complete_circuits(void)
249 can_complete_circuits = 0;
252 /** Add <b>conn</b> to the array of connections that we can poll on. The
253 * connection's socket must be set; the connection starts out
254 * non-reading and non-writing.
257 connection_add_impl(connection_t *conn, int is_connecting)
259 tor_assert(conn);
260 tor_assert(SOCKET_OK(conn->s) ||
261 conn->linked ||
262 (conn->type == CONN_TYPE_AP &&
263 TO_EDGE_CONN(conn)->is_dns_request));
265 tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
266 conn->conn_array_index = smartlist_len(connection_array);
267 smartlist_add(connection_array, conn);
269 (void) is_connecting;
271 if (SOCKET_OK(conn->s) || conn->linked) {
272 conn->read_event = tor_event_new(tor_libevent_get_base(),
273 conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
274 conn->write_event = tor_event_new(tor_libevent_get_base(),
275 conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
276 /* XXXX CHECK FOR NULL RETURN! */
279 log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
280 conn_type_to_string(conn->type), (int)conn->s, conn->address,
281 smartlist_len(connection_array));
283 return 0;
286 /** Tell libevent that we don't care about <b>conn</b> any more. */
287 void
288 connection_unregister_events(connection_t *conn)
290 if (conn->read_event) {
291 if (event_del(conn->read_event))
292 log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
293 tor_free(conn->read_event);
295 if (conn->write_event) {
296 if (event_del(conn->write_event))
297 log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
298 tor_free(conn->write_event);
300 if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
301 dnsserv_close_listener(conn);
305 /** Remove the connection from the global list, and remove the
306 * corresponding poll entry. Calling this function will shift the last
307 * connection (if any) into the position occupied by conn.
310 connection_remove(connection_t *conn)
312 int current_index;
313 connection_t *tmp;
315 tor_assert(conn);
317 log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
318 (int)conn->s, conn_type_to_string(conn->type),
319 smartlist_len(connection_array));
321 if (conn->type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
322 log_info(LD_NET, "Closing SOCKS SocksSocket connection");
325 control_event_conn_bandwidth(conn);
327 tor_assert(conn->conn_array_index >= 0);
328 current_index = conn->conn_array_index;
329 connection_unregister_events(conn); /* This is redundant, but cheap. */
330 if (current_index == smartlist_len(connection_array)-1) { /* at the end */
331 smartlist_del(connection_array, current_index);
332 return 0;
335 /* replace this one with the one at the end */
336 smartlist_del(connection_array, current_index);
337 tmp = smartlist_get(connection_array, current_index);
338 tmp->conn_array_index = current_index;
340 return 0;
343 /** If <b>conn</b> is an edge conn, remove it from the list
344 * of conn's on this circuit. If it's not on an edge,
345 * flush and send destroys for all circuits on this conn.
347 * Remove it from connection_array (if applicable) and
348 * from closeable_connection_list.
350 * Then free it.
352 static void
353 connection_unlink(connection_t *conn)
355 connection_about_to_close_connection(conn);
356 if (conn->conn_array_index >= 0) {
357 connection_remove(conn);
359 if (conn->linked_conn) {
360 conn->linked_conn->linked_conn = NULL;
361 if (! conn->linked_conn->marked_for_close &&
362 conn->linked_conn->reading_from_linked_conn)
363 connection_start_reading(conn->linked_conn);
364 conn->linked_conn = NULL;
366 smartlist_remove(closeable_connection_lst, conn);
367 smartlist_remove(active_linked_connection_lst, conn);
368 if (conn->type == CONN_TYPE_EXIT) {
369 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
371 if (conn->type == CONN_TYPE_OR) {
372 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
373 connection_or_clear_identity(TO_OR_CONN(conn));
374 /* connection_unlink() can only get called if the connection
375 * was already on the closeable list, and it got there by
376 * connection_mark_for_close(), which was called from
377 * connection_or_close_normally() or
378 * connection_or_close_for_error(), so the channel should
379 * already be in CHANNEL_STATE_CLOSING, and then the
380 * connection_about_to_close_connection() goes to
381 * connection_or_about_to_close(), which calls channel_closed()
382 * to notify the channel_t layer, and closed the channel, so
383 * nothing more to do here to deal with the channel associated
384 * with an orconn.
387 connection_free(conn);
390 /** Initialize the global connection list, closeable connection list,
391 * and active connection list. */
392 STATIC void
393 init_connection_lists(void)
395 if (!connection_array)
396 connection_array = smartlist_new();
397 if (!closeable_connection_lst)
398 closeable_connection_lst = smartlist_new();
399 if (!active_linked_connection_lst)
400 active_linked_connection_lst = smartlist_new();
403 /** Schedule <b>conn</b> to be closed. **/
404 void
405 add_connection_to_closeable_list(connection_t *conn)
407 tor_assert(!smartlist_contains(closeable_connection_lst, conn));
408 tor_assert(conn->marked_for_close);
409 assert_connection_ok(conn, time(NULL));
410 smartlist_add(closeable_connection_lst, conn);
413 /** Return 1 if conn is on the closeable list, else return 0. */
415 connection_is_on_closeable_list(connection_t *conn)
417 return smartlist_contains(closeable_connection_lst, conn);
420 /** Return true iff conn is in the current poll array. */
422 connection_in_array(connection_t *conn)
424 return smartlist_contains(connection_array, conn);
427 /** Set <b>*array</b> to an array of all connections. <b>*array</b> must not
428 * be modified.
430 MOCK_IMPL(smartlist_t *,
431 get_connection_array, (void))
433 if (!connection_array)
434 connection_array = smartlist_new();
435 return connection_array;
438 /** Provides the traffic read and written over the life of the process. */
440 MOCK_IMPL(uint64_t,
441 get_bytes_read,(void))
443 return stats_n_bytes_read;
446 /* DOCDOC get_bytes_written */
447 MOCK_IMPL(uint64_t,
448 get_bytes_written,(void))
450 return stats_n_bytes_written;
453 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
454 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
456 void
457 connection_watch_events(connection_t *conn, watchable_events_t events)
459 if (events & READ_EVENT)
460 connection_start_reading(conn);
461 else
462 connection_stop_reading(conn);
464 if (events & WRITE_EVENT)
465 connection_start_writing(conn);
466 else
467 connection_stop_writing(conn);
470 /** Return true iff <b>conn</b> is listening for read events. */
472 connection_is_reading(connection_t *conn)
474 tor_assert(conn);
476 return conn->reading_from_linked_conn ||
477 (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
480 /** Check whether <b>conn</b> is correct in having (or not having) a
481 * read/write event (passed in <b>ev</b>). On success, return 0. On failure,
482 * log a warning and return -1. */
483 static int
484 connection_check_event(connection_t *conn, struct event *ev)
486 int bad;
488 if (conn->type == CONN_TYPE_AP && TO_EDGE_CONN(conn)->is_dns_request) {
489 /* DNS requests which we launch through the dnsserv.c module do not have
490 * any underlying socket or any underlying linked connection, so they
491 * shouldn't have any attached events either.
493 bad = ev != NULL;
494 } else {
495 /* Everything else should have an underlying socket, or a linked
496 * connection (which is also tracked with a read_event/write_event pair).
498 bad = ev == NULL;
501 if (bad) {
502 log_warn(LD_BUG, "Event missing on connection %p [%s;%s]. "
503 "socket=%d. linked=%d. "
504 "is_dns_request=%d. Marked_for_close=%s:%d",
505 conn,
506 conn_type_to_string(conn->type),
507 conn_state_to_string(conn->type, conn->state),
508 (int)conn->s, (int)conn->linked,
509 (conn->type == CONN_TYPE_AP &&
510 TO_EDGE_CONN(conn)->is_dns_request),
511 conn->marked_for_close_file ? conn->marked_for_close_file : "-",
512 conn->marked_for_close
514 log_backtrace(LOG_WARN, LD_BUG, "Backtrace attached.");
515 return -1;
517 return 0;
520 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
521 MOCK_IMPL(void,
522 connection_stop_reading,(connection_t *conn))
524 tor_assert(conn);
526 if (connection_check_event(conn, conn->read_event) < 0) {
527 return;
530 if (conn->linked) {
531 conn->reading_from_linked_conn = 0;
532 connection_stop_reading_from_linked_conn(conn);
533 } else {
534 if (event_del(conn->read_event))
535 log_warn(LD_NET, "Error from libevent setting read event state for %d "
536 "to unwatched: %s",
537 (int)conn->s,
538 tor_socket_strerror(tor_socket_errno(conn->s)));
542 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
543 MOCK_IMPL(void,
544 connection_start_reading,(connection_t *conn))
546 tor_assert(conn);
548 if (connection_check_event(conn, conn->read_event) < 0) {
549 return;
552 if (conn->linked) {
553 conn->reading_from_linked_conn = 1;
554 if (connection_should_read_from_linked_conn(conn))
555 connection_start_reading_from_linked_conn(conn);
556 } else {
557 if (event_add(conn->read_event, NULL))
558 log_warn(LD_NET, "Error from libevent setting read event state for %d "
559 "to watched: %s",
560 (int)conn->s,
561 tor_socket_strerror(tor_socket_errno(conn->s)));
565 /** Return true iff <b>conn</b> is listening for write events. */
567 connection_is_writing(connection_t *conn)
569 tor_assert(conn);
571 return conn->writing_to_linked_conn ||
572 (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
575 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
576 MOCK_IMPL(void,
577 connection_stop_writing,(connection_t *conn))
579 tor_assert(conn);
581 if (connection_check_event(conn, conn->write_event) < 0) {
582 return;
585 if (conn->linked) {
586 conn->writing_to_linked_conn = 0;
587 if (conn->linked_conn)
588 connection_stop_reading_from_linked_conn(conn->linked_conn);
589 } else {
590 if (event_del(conn->write_event))
591 log_warn(LD_NET, "Error from libevent setting write event state for %d "
592 "to unwatched: %s",
593 (int)conn->s,
594 tor_socket_strerror(tor_socket_errno(conn->s)));
598 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
599 MOCK_IMPL(void,
600 connection_start_writing,(connection_t *conn))
602 tor_assert(conn);
604 if (connection_check_event(conn, conn->write_event) < 0) {
605 return;
608 if (conn->linked) {
609 conn->writing_to_linked_conn = 1;
610 if (conn->linked_conn &&
611 connection_should_read_from_linked_conn(conn->linked_conn))
612 connection_start_reading_from_linked_conn(conn->linked_conn);
613 } else {
614 if (event_add(conn->write_event, NULL))
615 log_warn(LD_NET, "Error from libevent setting write event state for %d "
616 "to watched: %s",
617 (int)conn->s,
618 tor_socket_strerror(tor_socket_errno(conn->s)));
622 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
623 * linked to it would be good and feasible. (Reading is "feasible" if the
624 * other conn exists and has data in its outbuf, and is "good" if we have our
625 * reading_from_linked_conn flag set and the other conn has its
626 * writing_to_linked_conn flag set.)*/
627 static int
628 connection_should_read_from_linked_conn(connection_t *conn)
630 if (conn->linked && conn->reading_from_linked_conn) {
631 if (! conn->linked_conn ||
632 (conn->linked_conn->writing_to_linked_conn &&
633 buf_datalen(conn->linked_conn->outbuf)))
634 return 1;
636 return 0;
639 /** If we called event_base_loop() and told it to never stop until it
640 * runs out of events, now we've changed our mind: tell it we want it to
641 * finish. */
642 void
643 tell_event_loop_to_finish(void)
645 if (!called_loop_once) {
646 struct timeval tv = { 0, 0 };
647 tor_event_base_loopexit(tor_libevent_get_base(), &tv);
648 called_loop_once = 1; /* hack to avoid adding more exit events */
652 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
653 * its linked connection, if it is not doing so already. Called by
654 * connection_start_reading and connection_start_writing as appropriate. */
655 static void
656 connection_start_reading_from_linked_conn(connection_t *conn)
658 tor_assert(conn);
659 tor_assert(conn->linked == 1);
661 if (!conn->active_on_link) {
662 conn->active_on_link = 1;
663 smartlist_add(active_linked_connection_lst, conn);
664 /* make sure that the event_base_loop() function exits at
665 * the end of its run through the current connections, so we can
666 * activate read events for linked connections. */
667 tell_event_loop_to_finish();
668 } else {
669 tor_assert(smartlist_contains(active_linked_connection_lst, conn));
673 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
674 * connection, if is currently doing so. Called by connection_stop_reading,
675 * connection_stop_writing, and connection_read. */
676 void
677 connection_stop_reading_from_linked_conn(connection_t *conn)
679 tor_assert(conn);
680 tor_assert(conn->linked == 1);
682 if (conn->active_on_link) {
683 conn->active_on_link = 0;
684 /* FFFF We could keep an index here so we can smartlist_del
685 * cleanly. On the other hand, this doesn't show up on profiles,
686 * so let's leave it alone for now. */
687 smartlist_remove(active_linked_connection_lst, conn);
688 } else {
689 tor_assert(!smartlist_contains(active_linked_connection_lst, conn));
693 /** Close all connections that have been scheduled to get closed. */
694 STATIC void
695 close_closeable_connections(void)
697 int i;
698 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
699 connection_t *conn = smartlist_get(closeable_connection_lst, i);
700 if (conn->conn_array_index < 0) {
701 connection_unlink(conn); /* blow it away right now */
702 } else {
703 if (!conn_close_if_marked(conn->conn_array_index))
704 ++i;
709 /** Count moribund connections for the OOS handler */
710 MOCK_IMPL(int,
711 connection_count_moribund, (void))
713 int moribund = 0;
716 * Count things we'll try to kill when close_closeable_connections()
717 * runs next.
719 SMARTLIST_FOREACH_BEGIN(closeable_connection_lst, connection_t *, conn) {
720 if (SOCKET_OK(conn->s) && connection_is_moribund(conn)) ++moribund;
721 } SMARTLIST_FOREACH_END(conn);
723 return moribund;
726 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
727 * some data to read. */
728 static void
729 conn_read_callback(evutil_socket_t fd, short event, void *_conn)
731 connection_t *conn = _conn;
732 (void)fd;
733 (void)event;
735 log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
737 /* assert_connection_ok(conn, time(NULL)); */
739 if (connection_handle_read(conn) < 0) {
740 if (!conn->marked_for_close) {
741 #ifndef _WIN32
742 log_warn(LD_BUG,"Unhandled error on read for %s connection "
743 "(fd %d); removing",
744 conn_type_to_string(conn->type), (int)conn->s);
745 tor_fragile_assert();
746 #endif /* !defined(_WIN32) */
747 if (CONN_IS_EDGE(conn))
748 connection_edge_end_errno(TO_EDGE_CONN(conn));
749 connection_mark_for_close(conn);
752 assert_connection_ok(conn, time(NULL));
754 if (smartlist_len(closeable_connection_lst))
755 close_closeable_connections();
758 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
759 * some data to write. */
760 static void
761 conn_write_callback(evutil_socket_t fd, short events, void *_conn)
763 connection_t *conn = _conn;
764 (void)fd;
765 (void)events;
767 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
768 (int)conn->s));
770 /* assert_connection_ok(conn, time(NULL)); */
772 if (connection_handle_write(conn, 0) < 0) {
773 if (!conn->marked_for_close) {
774 /* this connection is broken. remove it. */
775 log_fn(LOG_WARN,LD_BUG,
776 "unhandled error on write for %s connection (fd %d); removing",
777 conn_type_to_string(conn->type), (int)conn->s);
778 tor_fragile_assert();
779 if (CONN_IS_EDGE(conn)) {
780 /* otherwise we cry wolf about duplicate close */
781 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
782 if (!edge_conn->end_reason)
783 edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
784 edge_conn->edge_has_sent_end = 1;
786 connection_close_immediate(conn); /* So we don't try to flush. */
787 connection_mark_for_close(conn);
790 assert_connection_ok(conn, time(NULL));
792 if (smartlist_len(closeable_connection_lst))
793 close_closeable_connections();
796 /** If the connection at connection_array[i] is marked for close, then:
797 * - If it has data that it wants to flush, try to flush it.
798 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
799 * true, then leave the connection open and return.
800 * - Otherwise, remove the connection from connection_array and from
801 * all other lists, close it, and free it.
802 * Returns 1 if the connection was closed, 0 otherwise.
804 static int
805 conn_close_if_marked(int i)
807 connection_t *conn;
808 int retval;
809 time_t now;
811 conn = smartlist_get(connection_array, i);
812 if (!conn->marked_for_close)
813 return 0; /* nothing to see here, move along */
814 now = time(NULL);
815 assert_connection_ok(conn, now);
816 /* assert_all_pending_dns_resolves_ok(); */
818 log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
819 conn->s);
821 /* If the connection we are about to close was trying to connect to
822 a proxy server and failed, the client won't be able to use that
823 proxy. We should warn the user about this. */
824 if (conn->proxy_state == PROXY_INFANT)
825 log_failed_proxy_connection(conn);
827 if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
828 connection_wants_to_flush(conn)) {
829 /* s == -1 means it's an incomplete edge connection, or that the socket
830 * has already been closed as unflushable. */
831 ssize_t sz = connection_bucket_write_limit(conn, now);
832 if (!conn->hold_open_until_flushed)
833 log_info(LD_NET,
834 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
835 "to flush %d bytes. (Marked at %s:%d)",
836 escaped_safe_str_client(conn->address),
837 (int)conn->s, conn_type_to_string(conn->type), conn->state,
838 (int)conn->outbuf_flushlen,
839 conn->marked_for_close_file, conn->marked_for_close);
840 if (conn->linked_conn) {
841 retval = buf_move_to_buf(conn->linked_conn->inbuf, conn->outbuf,
842 &conn->outbuf_flushlen);
843 if (retval >= 0) {
844 /* The linked conn will notice that it has data when it notices that
845 * we're gone. */
846 connection_start_reading_from_linked_conn(conn->linked_conn);
848 log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
849 "%d left; flushlen %d; wants-to-flush==%d", retval,
850 (int)connection_get_outbuf_len(conn),
851 (int)conn->outbuf_flushlen,
852 connection_wants_to_flush(conn));
853 } else if (connection_speaks_cells(conn)) {
854 if (conn->state == OR_CONN_STATE_OPEN) {
855 retval = buf_flush_to_tls(conn->outbuf, TO_OR_CONN(conn)->tls, sz,
856 &conn->outbuf_flushlen);
857 } else
858 retval = -1; /* never flush non-open broken tls connections */
859 } else {
860 retval = buf_flush_to_socket(conn->outbuf, conn->s, sz,
861 &conn->outbuf_flushlen);
863 if (retval >= 0 && /* Technically, we could survive things like
864 TLS_WANT_WRITE here. But don't bother for now. */
865 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
866 if (retval > 0) {
867 LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
868 "Holding conn (fd %d) open for more flushing.",
869 (int)conn->s));
870 conn->timestamp_lastwritten = now; /* reset so we can flush more */
871 } else if (sz == 0) {
872 /* Also, retval==0. If we get here, we didn't want to write anything
873 * (because of rate-limiting) and we didn't. */
875 /* Connection must flush before closing, but it's being rate-limited.
876 * Let's remove from Libevent, and mark it as blocked on bandwidth
877 * so it will be re-added on next token bucket refill. Prevents
878 * busy Libevent loops where we keep ending up here and returning
879 * 0 until we are no longer blocked on bandwidth.
881 if (connection_is_writing(conn)) {
882 conn->write_blocked_on_bw = 1;
883 connection_stop_writing(conn);
885 if (connection_is_reading(conn)) {
886 /* XXXX+ We should make this code unreachable; if a connection is
887 * marked for close and flushing, there is no point in reading to it
888 * at all. Further, checking at this point is a bit of a hack: it
889 * would make much more sense to react in
890 * connection_handle_read_impl, or to just stop reading in
891 * mark_and_flush */
892 conn->read_blocked_on_bw = 1;
893 connection_stop_reading(conn);
896 return 0;
898 if (connection_wants_to_flush(conn)) {
899 log_fn(LOG_INFO, LD_NET, "We stalled too much while trying to write %d "
900 "bytes to address %s. If this happens a lot, either "
901 "something is wrong with your network connection, or "
902 "something is wrong with theirs. "
903 "(fd %d, type %s, state %d, marked at %s:%d).",
904 (int)connection_get_outbuf_len(conn),
905 escaped_safe_str_client(conn->address),
906 (int)conn->s, conn_type_to_string(conn->type), conn->state,
907 conn->marked_for_close_file,
908 conn->marked_for_close);
912 connection_unlink(conn); /* unlink, remove, free */
913 return 1;
916 /** Implementation for directory_all_unreachable. This is done in a callback,
917 * since otherwise it would complicate Tor's control-flow graph beyond all
918 * reason.
920 static void
921 directory_all_unreachable_cb(evutil_socket_t fd, short event, void *arg)
923 (void)fd;
924 (void)event;
925 (void)arg;
927 connection_t *conn;
929 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
930 AP_CONN_STATE_CIRCUIT_WAIT))) {
931 entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
932 log_notice(LD_NET,
933 "Is your network connection down? "
934 "Failing connection to '%s:%d'.",
935 safe_str_client(entry_conn->socks_request->address),
936 entry_conn->socks_request->port);
937 connection_mark_unattached_ap(entry_conn,
938 END_STREAM_REASON_NET_UNREACHABLE);
940 control_event_general_error("DIR_ALL_UNREACHABLE");
943 static struct event *directory_all_unreachable_cb_event = NULL;
945 /** We've just tried every dirserver we know about, and none of
946 * them were reachable. Assume the network is down. Change state
947 * so next time an application connection arrives we'll delay it
948 * and try another directory fetch. Kill off all the circuit_wait
949 * streams that are waiting now, since they will all timeout anyway.
951 void
952 directory_all_unreachable(time_t now)
954 (void)now;
956 stats_n_seconds_working=0; /* reset it */
958 if (!directory_all_unreachable_cb_event) {
959 directory_all_unreachable_cb_event =
960 tor_event_new(tor_libevent_get_base(),
961 -1, EV_READ, directory_all_unreachable_cb, NULL);
962 tor_assert(directory_all_unreachable_cb_event);
965 event_active(directory_all_unreachable_cb_event, EV_READ, 1);
968 /** This function is called whenever we successfully pull down some new
969 * network statuses or server descriptors. */
970 void
971 directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
973 const or_options_t *options = get_options();
975 /* if we have enough dir info, then update our guard status with
976 * whatever we just learned. */
977 int invalidate_circs = guards_update_all();
979 if (invalidate_circs) {
980 circuit_mark_all_unused_circs();
981 circuit_mark_all_dirty_circs_as_unusable();
984 if (!router_have_minimum_dir_info()) {
985 int quiet = suppress_logs || from_cache ||
986 directory_too_idle_to_fetch_descriptors(options, now);
987 tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
988 "I learned some more directory information, but not enough to "
989 "build a circuit: %s", get_dir_info_status_string());
990 update_all_descriptor_downloads(now);
991 return;
992 } else {
993 if (directory_fetches_from_authorities(options)) {
994 update_all_descriptor_downloads(now);
997 /* Don't even bother trying to get extrainfo until the rest of our
998 * directory info is up-to-date */
999 if (options->DownloadExtraInfo)
1000 update_extrainfo_downloads(now);
1003 if (server_mode(options) && !net_is_disabled() && !from_cache &&
1004 (have_completed_a_circuit() || !any_predicted_circuits(now)))
1005 consider_testing_reachability(1, 1);
1008 /** Perform regular maintenance tasks for a single connection. This
1009 * function gets run once per second per connection by run_scheduled_events.
1011 static void
1012 run_connection_housekeeping(int i, time_t now)
1014 cell_t cell;
1015 connection_t *conn = smartlist_get(connection_array, i);
1016 const or_options_t *options = get_options();
1017 or_connection_t *or_conn;
1018 channel_t *chan = NULL;
1019 int have_any_circuits;
1020 int past_keepalive =
1021 now >= conn->timestamp_lastwritten + options->KeepalivePeriod;
1023 if (conn->outbuf && !connection_get_outbuf_len(conn) &&
1024 conn->type == CONN_TYPE_OR)
1025 TO_OR_CONN(conn)->timestamp_lastempty = now;
1027 if (conn->marked_for_close) {
1028 /* nothing to do here */
1029 return;
1032 /* Expire any directory connections that haven't been active (sent
1033 * if a server or received if a client) for 5 min */
1034 if (conn->type == CONN_TYPE_DIR &&
1035 ((DIR_CONN_IS_SERVER(conn) &&
1036 conn->timestamp_lastwritten
1037 + options->TestingDirConnectionMaxStall < now) ||
1038 (!DIR_CONN_IS_SERVER(conn) &&
1039 conn->timestamp_lastread
1040 + options->TestingDirConnectionMaxStall < now))) {
1041 log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
1042 (int)conn->s, conn->purpose);
1043 /* This check is temporary; it's to let us know whether we should consider
1044 * parsing partial serverdesc responses. */
1045 if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
1046 connection_get_inbuf_len(conn) >= 1024) {
1047 log_info(LD_DIR,"Trying to extract information from wedged server desc "
1048 "download.");
1049 connection_dir_reached_eof(TO_DIR_CONN(conn));
1050 } else {
1051 connection_mark_for_close(conn);
1053 return;
1056 if (!connection_speaks_cells(conn))
1057 return; /* we're all done here, the rest is just for OR conns */
1059 /* If we haven't written to an OR connection for a while, then either nuke
1060 the connection or send a keepalive, depending. */
1062 or_conn = TO_OR_CONN(conn);
1063 tor_assert(conn->outbuf);
1065 chan = TLS_CHAN_TO_BASE(or_conn->chan);
1066 tor_assert(chan);
1068 if (channel_num_circuits(chan) != 0) {
1069 have_any_circuits = 1;
1070 chan->timestamp_last_had_circuits = now;
1071 } else {
1072 have_any_circuits = 0;
1075 if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan)) &&
1076 ! have_any_circuits) {
1077 /* It's bad for new circuits, and has no unmarked circuits on it:
1078 * mark it now. */
1079 log_info(LD_OR,
1080 "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1081 (int)conn->s, conn->address, conn->port);
1082 if (conn->state == OR_CONN_STATE_CONNECTING)
1083 connection_or_connect_failed(TO_OR_CONN(conn),
1084 END_OR_CONN_REASON_TIMEOUT,
1085 "Tor gave up on the connection");
1086 connection_or_close_normally(TO_OR_CONN(conn), 1);
1087 } else if (!connection_state_is_open(conn)) {
1088 if (past_keepalive) {
1089 /* We never managed to actually get this connection open and happy. */
1090 log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
1091 (int)conn->s,conn->address, conn->port);
1092 connection_or_close_normally(TO_OR_CONN(conn), 0);
1094 } else if (we_are_hibernating() &&
1095 ! have_any_circuits &&
1096 !connection_get_outbuf_len(conn)) {
1097 /* We're hibernating, there's no circuits, and nothing to flush.*/
1098 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
1099 "[Hibernating or exiting].",
1100 (int)conn->s,conn->address, conn->port);
1101 connection_or_close_normally(TO_OR_CONN(conn), 1);
1102 } else if (!have_any_circuits &&
1103 now - or_conn->idle_timeout >=
1104 chan->timestamp_last_had_circuits) {
1105 log_info(LD_OR,"Expiring non-used OR connection "U64_FORMAT" to fd %d "
1106 "(%s:%d) [no circuits for %d; timeout %d; %scanonical].",
1107 U64_PRINTF_ARG(chan->global_identifier),
1108 (int)conn->s, conn->address, conn->port,
1109 (int)(now - chan->timestamp_last_had_circuits),
1110 or_conn->idle_timeout,
1111 or_conn->is_canonical ? "" : "non");
1112 connection_or_close_normally(TO_OR_CONN(conn), 0);
1113 } else if (
1114 now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
1115 now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
1116 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
1117 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1118 "flush; %d seconds since last write)",
1119 (int)conn->s, conn->address, conn->port,
1120 (int)connection_get_outbuf_len(conn),
1121 (int)(now-conn->timestamp_lastwritten));
1122 connection_or_close_normally(TO_OR_CONN(conn), 0);
1123 } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
1124 /* send a padding cell */
1125 log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
1126 conn->address, conn->port);
1127 memset(&cell,0,sizeof(cell_t));
1128 cell.command = CELL_PADDING;
1129 connection_or_write_cell_to_buf(&cell, or_conn);
1130 } else {
1131 channelpadding_decide_to_pad_channel(chan);
1135 /** Honor a NEWNYM request: make future requests unlinkable to past
1136 * requests. */
1137 static void
1138 signewnym_impl(time_t now)
1140 const or_options_t *options = get_options();
1141 if (!proxy_mode(options)) {
1142 log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
1143 "is disabled.");
1144 return;
1147 circuit_mark_all_dirty_circs_as_unusable();
1148 addressmap_clear_transient();
1149 hs_client_purge_state();
1150 time_of_last_signewnym = now;
1151 signewnym_is_pending = 0;
1153 ++newnym_epoch;
1155 control_event_signal(SIGNEWNYM);
1158 /** Return the number of times that signewnym has been called. */
1159 unsigned
1160 get_signewnym_epoch(void)
1162 return newnym_epoch;
1165 /** True iff we have initialized all the members of <b>periodic_events</b>.
1166 * Used to prevent double-initialization. */
1167 static int periodic_events_initialized = 0;
1169 /* Declare all the timer callback functions... */
1170 #undef CALLBACK
1171 #define CALLBACK(name) \
1172 static int name ## _callback(time_t, const or_options_t *)
1173 CALLBACK(rotate_onion_key);
1174 CALLBACK(check_onion_keys_expiry_time);
1175 CALLBACK(check_ed_keys);
1176 CALLBACK(launch_descriptor_fetches);
1177 CALLBACK(rotate_x509_certificate);
1178 CALLBACK(add_entropy);
1179 CALLBACK(launch_reachability_tests);
1180 CALLBACK(downrate_stability);
1181 CALLBACK(save_stability);
1182 CALLBACK(check_authority_cert);
1183 CALLBACK(check_expired_networkstatus);
1184 CALLBACK(write_stats_file);
1185 CALLBACK(record_bridge_stats);
1186 CALLBACK(clean_caches);
1187 CALLBACK(rend_cache_failure_clean);
1188 CALLBACK(retry_dns);
1189 CALLBACK(check_descriptor);
1190 CALLBACK(check_for_reachability_bw);
1191 CALLBACK(fetch_networkstatus);
1192 CALLBACK(retry_listeners);
1193 CALLBACK(expire_old_ciruits_serverside);
1194 CALLBACK(check_dns_honesty);
1195 CALLBACK(write_bridge_ns);
1196 CALLBACK(check_fw_helper_app);
1197 CALLBACK(heartbeat);
1198 CALLBACK(clean_consdiffmgr);
1199 CALLBACK(reset_padding_counts);
1200 CALLBACK(check_canonical_channels);
1201 CALLBACK(hs_service);
1203 #undef CALLBACK
1205 /* Now we declare an array of periodic_event_item_t for each periodic event */
1206 #define CALLBACK(name) PERIODIC_EVENT(name)
1208 static periodic_event_item_t periodic_events[] = {
1209 CALLBACK(rotate_onion_key),
1210 CALLBACK(check_onion_keys_expiry_time),
1211 CALLBACK(check_ed_keys),
1212 CALLBACK(launch_descriptor_fetches),
1213 CALLBACK(rotate_x509_certificate),
1214 CALLBACK(add_entropy),
1215 CALLBACK(launch_reachability_tests),
1216 CALLBACK(downrate_stability),
1217 CALLBACK(save_stability),
1218 CALLBACK(check_authority_cert),
1219 CALLBACK(check_expired_networkstatus),
1220 CALLBACK(write_stats_file),
1221 CALLBACK(record_bridge_stats),
1222 CALLBACK(clean_caches),
1223 CALLBACK(rend_cache_failure_clean),
1224 CALLBACK(retry_dns),
1225 CALLBACK(check_descriptor),
1226 CALLBACK(check_for_reachability_bw),
1227 CALLBACK(fetch_networkstatus),
1228 CALLBACK(retry_listeners),
1229 CALLBACK(expire_old_ciruits_serverside),
1230 CALLBACK(check_dns_honesty),
1231 CALLBACK(write_bridge_ns),
1232 CALLBACK(check_fw_helper_app),
1233 CALLBACK(heartbeat),
1234 CALLBACK(clean_consdiffmgr),
1235 CALLBACK(reset_padding_counts),
1236 CALLBACK(check_canonical_channels),
1237 CALLBACK(hs_service),
1238 END_OF_PERIODIC_EVENTS
1240 #undef CALLBACK
1242 /* These are pointers to members of periodic_events[] that are used to
1243 * implement particular callbacks. We keep them separate here so that we
1244 * can access them by name. We also keep them inside periodic_events[]
1245 * so that we can implement "reset all timers" in a reasonable way. */
1246 static periodic_event_item_t *check_descriptor_event=NULL;
1247 static periodic_event_item_t *fetch_networkstatus_event=NULL;
1248 static periodic_event_item_t *launch_descriptor_fetches_event=NULL;
1249 static periodic_event_item_t *check_dns_honesty_event=NULL;
1251 /** Reset all the periodic events so we'll do all our actions again as if we
1252 * just started up.
1253 * Useful if our clock just moved back a long time from the future,
1254 * so we don't wait until that future arrives again before acting.
1256 void
1257 reset_all_main_loop_timers(void)
1259 int i;
1260 for (i = 0; periodic_events[i].name; ++i) {
1261 periodic_event_reschedule(&periodic_events[i]);
1265 /** Return the member of periodic_events[] whose name is <b>name</b>.
1266 * Return NULL if no such event is found.
1268 static periodic_event_item_t *
1269 find_periodic_event(const char *name)
1271 int i;
1272 for (i = 0; periodic_events[i].name; ++i) {
1273 if (strcmp(name, periodic_events[i].name) == 0)
1274 return &periodic_events[i];
1276 return NULL;
1279 /** Helper, run one second after setup:
1280 * Initializes all members of periodic_events and starts them running.
1282 * (We do this one second after setup for backward-compatibility reasons;
1283 * it might not actually be necessary.) */
1284 static void
1285 initialize_periodic_events_cb(evutil_socket_t fd, short events, void *data)
1287 (void) fd;
1288 (void) events;
1289 (void) data;
1290 int i;
1291 for (i = 0; periodic_events[i].name; ++i) {
1292 periodic_event_launch(&periodic_events[i]);
1296 /** Set up all the members of periodic_events[], and configure them all to be
1297 * launched from a callback. */
1298 STATIC void
1299 initialize_periodic_events(void)
1301 tor_assert(periodic_events_initialized == 0);
1302 periodic_events_initialized = 1;
1304 int i;
1305 for (i = 0; periodic_events[i].name; ++i) {
1306 periodic_event_setup(&periodic_events[i]);
1309 #define NAMED_CALLBACK(name) \
1310 STMT_BEGIN name ## _event = find_periodic_event( #name ); STMT_END
1312 NAMED_CALLBACK(check_descriptor);
1313 NAMED_CALLBACK(fetch_networkstatus);
1314 NAMED_CALLBACK(launch_descriptor_fetches);
1315 NAMED_CALLBACK(check_dns_honesty);
1317 struct timeval one_second = { 1, 0 };
1318 event_base_once(tor_libevent_get_base(), -1, EV_TIMEOUT,
1319 initialize_periodic_events_cb, NULL,
1320 &one_second);
1323 STATIC void
1324 teardown_periodic_events(void)
1326 int i;
1327 for (i = 0; periodic_events[i].name; ++i) {
1328 periodic_event_destroy(&periodic_events[i]);
1333 * Update our schedule so that we'll check whether we need to update our
1334 * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
1335 * seconds.
1337 void
1338 reschedule_descriptor_update_check(void)
1340 tor_assert(check_descriptor_event);
1341 periodic_event_reschedule(check_descriptor_event);
1345 * Update our schedule so that we'll check whether we need to fetch directory
1346 * info immediately.
1348 void
1349 reschedule_directory_downloads(void)
1351 tor_assert(fetch_networkstatus_event);
1352 tor_assert(launch_descriptor_fetches_event);
1354 periodic_event_reschedule(fetch_networkstatus_event);
1355 periodic_event_reschedule(launch_descriptor_fetches_event);
1358 #define LONGEST_TIMER_PERIOD (30 * 86400)
1359 /** Helper: Return the number of seconds between <b>now</b> and <b>next</b>,
1360 * clipped to the range [1 second, LONGEST_TIMER_PERIOD]. */
1361 static inline int
1362 safe_timer_diff(time_t now, time_t next)
1364 if (next > now) {
1365 /* There were no computers at signed TIME_MIN (1902 on 32-bit systems),
1366 * and nothing that could run Tor. It's a bug if 'next' is around then.
1367 * On 64-bit systems with signed TIME_MIN, TIME_MIN is before the Big
1368 * Bang. We cannot extrapolate past a singularity, but there was probably
1369 * nothing that could run Tor then, either.
1371 tor_assert(next > TIME_MIN + LONGEST_TIMER_PERIOD);
1373 if (next - LONGEST_TIMER_PERIOD > now)
1374 return LONGEST_TIMER_PERIOD;
1375 return (int)(next - now);
1376 } else {
1377 return 1;
1381 /** Perform regular maintenance tasks. This function gets run once per
1382 * second by second_elapsed_callback().
1384 static void
1385 run_scheduled_events(time_t now)
1387 const or_options_t *options = get_options();
1389 /* 0. See if we've been asked to shut down and our timeout has
1390 * expired; or if our bandwidth limits are exhausted and we
1391 * should hibernate; or if it's time to wake up from hibernation.
1393 consider_hibernation(now);
1395 /* 0b. If we've deferred a signewnym, make sure it gets handled
1396 * eventually. */
1397 if (signewnym_is_pending &&
1398 time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
1399 log_info(LD_CONTROL, "Honoring delayed NEWNYM request");
1400 signewnym_impl(now);
1403 /* 0c. If we've deferred log messages for the controller, handle them now */
1404 flush_pending_log_callbacks();
1406 /* Maybe enough time elapsed for us to reconsider a circuit. */
1407 circuit_upgrade_circuits_from_guard_wait();
1409 if (options->UseBridges && !options->DisableNetwork) {
1410 fetch_bridge_descriptors(options, now);
1413 if (accounting_is_enabled(options)) {
1414 accounting_run_housekeeping(now);
1417 if (authdir_mode_v3(options)) {
1418 dirvote_act(options, now);
1421 /* 3a. Every second, we examine pending circuits and prune the
1422 * ones which have been pending for more than a few seconds.
1423 * We do this before step 4, so it can try building more if
1424 * it's not comfortable with the number of available circuits.
1426 /* (If our circuit build timeout can ever become lower than a second (which
1427 * it can't, currently), we should do this more often.) */
1428 circuit_expire_building();
1429 circuit_expire_waiting_for_better_guard();
1431 /* 3b. Also look at pending streams and prune the ones that 'began'
1432 * a long time ago but haven't gotten a 'connected' yet.
1433 * Do this before step 4, so we can put them back into pending
1434 * state to be picked up by the new circuit.
1436 connection_ap_expire_beginning();
1438 /* 3c. And expire connections that we've held open for too long.
1440 connection_expire_held_open();
1442 /* 4. Every second, we try a new circuit if there are no valid
1443 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1444 * that became dirty more than MaxCircuitDirtiness seconds ago,
1445 * and we make a new circ if there are no clean circuits.
1447 const int have_dir_info = router_have_minimum_dir_info();
1448 if (have_dir_info && !net_is_disabled()) {
1449 circuit_build_needed_circs(now);
1450 } else {
1451 circuit_expire_old_circs_as_needed(now);
1454 if (!net_is_disabled()) {
1455 /* This is usually redundant with circuit_build_needed_circs() above,
1456 * but it is very fast when there is no work to do. */
1457 connection_ap_attach_pending(0);
1460 /* 5. We do housekeeping for each connection... */
1461 channel_update_bad_for_new_circs(NULL, 0);
1462 int i;
1463 for (i=0;i<smartlist_len(connection_array);i++) {
1464 run_connection_housekeeping(i, now);
1467 /* 6. And remove any marked circuits... */
1468 circuit_close_all_marked();
1470 /* 8. and blow away any connections that need to die. have to do this now,
1471 * because if we marked a conn for close and left its socket -1, then
1472 * we'll pass it to poll/select and bad things will happen.
1474 close_closeable_connections();
1476 /* 8b. And if anything in our state is ready to get flushed to disk, we
1477 * flush it. */
1478 or_state_save(now);
1480 /* 8c. Do channel cleanup just like for connections */
1481 channel_run_cleanup();
1482 channel_listener_run_cleanup();
1484 /* 11b. check pending unconfigured managed proxies */
1485 if (!net_is_disabled() && pt_proxies_configuration_pending())
1486 pt_configure_remaining_proxies();
1488 /* 12. launch diff computations. (This is free if there are none to
1489 * launch.) */
1490 if (dir_server_mode(options)) {
1491 consdiffmgr_rescan();
1495 /* Periodic callback: rotate the onion keys after the period defined by the
1496 * "onion-key-rotation-days" consensus parameter, shut down and restart all
1497 * cpuworkers, and update our descriptor if necessary.
1499 static int
1500 rotate_onion_key_callback(time_t now, const or_options_t *options)
1502 if (server_mode(options)) {
1503 int onion_key_lifetime = get_onion_key_lifetime();
1504 time_t rotation_time = get_onion_key_set_at()+onion_key_lifetime;
1505 if (rotation_time > now) {
1506 return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
1509 log_info(LD_GENERAL,"Rotating onion key.");
1510 rotate_onion_key();
1511 cpuworkers_rotate_keyinfo();
1512 if (router_rebuild_descriptor(1)<0) {
1513 log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
1515 if (advertised_server_mode() && !options->DisableNetwork)
1516 router_upload_dir_desc_to_dirservers(0);
1517 return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
1519 return PERIODIC_EVENT_NO_UPDATE;
1522 /* Period callback: Check if our old onion keys are still valid after the
1523 * period of time defined by the consensus parameter
1524 * "onion-key-grace-period-days", otherwise expire them by setting them to
1525 * NULL.
1527 static int
1528 check_onion_keys_expiry_time_callback(time_t now, const or_options_t *options)
1530 if (server_mode(options)) {
1531 int onion_key_grace_period = get_onion_key_grace_period();
1532 time_t expiry_time = get_onion_key_set_at()+onion_key_grace_period;
1533 if (expiry_time > now) {
1534 return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
1537 log_info(LD_GENERAL, "Expiring old onion keys.");
1538 expire_old_onion_keys();
1539 cpuworkers_rotate_keyinfo();
1540 return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
1543 return PERIODIC_EVENT_NO_UPDATE;
1546 /* Periodic callback: Every 30 seconds, check whether it's time to make new
1547 * Ed25519 subkeys.
1549 static int
1550 check_ed_keys_callback(time_t now, const or_options_t *options)
1552 if (server_mode(options)) {
1553 if (should_make_new_ed_keys(options, now)) {
1554 int new_signing_key = load_ed_keys(options, now);
1555 if (new_signing_key < 0 ||
1556 generate_ed_link_cert(options, now, new_signing_key > 0)) {
1557 log_err(LD_OR, "Unable to update Ed25519 keys! Exiting.");
1558 tor_cleanup();
1559 exit(1);
1562 return 30;
1564 return PERIODIC_EVENT_NO_UPDATE;
1568 * Periodic callback: Every {LAZY,GREEDY}_DESCRIPTOR_RETRY_INTERVAL,
1569 * see about fetching descriptors, microdescriptors, and extrainfo
1570 * documents.
1572 static int
1573 launch_descriptor_fetches_callback(time_t now, const or_options_t *options)
1575 if (should_delay_dir_fetches(options, NULL))
1576 return PERIODIC_EVENT_NO_UPDATE;
1578 update_all_descriptor_downloads(now);
1579 update_extrainfo_downloads(now);
1580 if (router_have_minimum_dir_info())
1581 return LAZY_DESCRIPTOR_RETRY_INTERVAL;
1582 else
1583 return GREEDY_DESCRIPTOR_RETRY_INTERVAL;
1587 * Periodic event: Rotate our X.509 certificates and TLS keys once every
1588 * MAX_SSL_KEY_LIFETIME_INTERNAL.
1590 static int
1591 rotate_x509_certificate_callback(time_t now, const or_options_t *options)
1593 static int first = 1;
1594 (void)now;
1595 (void)options;
1596 if (first) {
1597 first = 0;
1598 return MAX_SSL_KEY_LIFETIME_INTERNAL;
1601 /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1602 * TLS context. */
1603 log_info(LD_GENERAL,"Rotating tls context.");
1604 if (router_initialize_tls_context() < 0) {
1605 log_err(LD_BUG, "Error reinitializing TLS context");
1606 tor_assert_unreached();
1608 if (generate_ed_link_cert(options, now, 1)) {
1609 log_err(LD_OR, "Unable to update Ed25519->TLS link certificate for "
1610 "new TLS context.");
1611 tor_assert_unreached();
1614 /* We also make sure to rotate the TLS connections themselves if they've
1615 * been up for too long -- but that's done via is_bad_for_new_circs in
1616 * run_connection_housekeeping() above. */
1617 return MAX_SSL_KEY_LIFETIME_INTERNAL;
1621 * Periodic callback: once an hour, grab some more entropy from the
1622 * kernel and feed it to our CSPRNG.
1624 static int
1625 add_entropy_callback(time_t now, const or_options_t *options)
1627 (void)now;
1628 (void)options;
1629 /* We already seeded once, so don't die on failure. */
1630 if (crypto_seed_rng() < 0) {
1631 log_warn(LD_GENERAL, "Tried to re-seed RNG, but failed. We already "
1632 "seeded once, though, so we won't exit here.");
1635 /** How often do we add more entropy to OpenSSL's RNG pool? */
1636 #define ENTROPY_INTERVAL (60*60)
1637 return ENTROPY_INTERVAL;
1641 * Periodic callback: if we're an authority, make sure we test
1642 * the routers on the network for reachability.
1644 static int
1645 launch_reachability_tests_callback(time_t now, const or_options_t *options)
1647 if (authdir_mode_tests_reachability(options) &&
1648 !net_is_disabled()) {
1649 /* try to determine reachability of the other Tor relays */
1650 dirserv_test_reachability(now);
1652 return REACHABILITY_TEST_INTERVAL;
1656 * Periodic callback: if we're an authority, discount the stability
1657 * information (and other rephist information) that's older.
1659 static int
1660 downrate_stability_callback(time_t now, const or_options_t *options)
1662 (void)options;
1663 /* 1d. Periodically, we discount older stability information so that new
1664 * stability info counts more, and save the stability information to disk as
1665 * appropriate. */
1666 time_t next = rep_hist_downrate_old_runs(now);
1667 return safe_timer_diff(now, next);
1671 * Periodic callback: if we're an authority, record our measured stability
1672 * information from rephist in an mtbf file.
1674 static int
1675 save_stability_callback(time_t now, const or_options_t *options)
1677 if (authdir_mode_tests_reachability(options)) {
1678 if (rep_hist_record_mtbf_data(now, 1)<0) {
1679 log_warn(LD_GENERAL, "Couldn't store mtbf data.");
1682 #define SAVE_STABILITY_INTERVAL (30*60)
1683 return SAVE_STABILITY_INTERVAL;
1687 * Periodic callback: if we're an authority, check on our authority
1688 * certificate (the one that authenticates our authority signing key).
1690 static int
1691 check_authority_cert_callback(time_t now, const or_options_t *options)
1693 (void)now;
1694 (void)options;
1695 /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
1696 * close to expiring and warn the admin if it is. */
1697 v3_authority_check_key_expiry();
1698 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
1699 return CHECK_V3_CERTIFICATE_INTERVAL;
1703 * Periodic callback: If our consensus is too old, recalculate whether
1704 * we can actually use it.
1706 static int
1707 check_expired_networkstatus_callback(time_t now, const or_options_t *options)
1709 (void)options;
1710 /* Check whether our networkstatus has expired. */
1711 networkstatus_t *ns = networkstatus_get_latest_consensus();
1712 /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
1713 * networkstatus_get_reasonably_live_consensus(), but that value is way
1714 * way too high. Arma: is the bridge issue there resolved yet? -NM */
1715 #define NS_EXPIRY_SLOP (24*60*60)
1716 if (ns && ns->valid_until < (now - NS_EXPIRY_SLOP) &&
1717 router_have_minimum_dir_info()) {
1718 router_dir_info_changed();
1720 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1721 return CHECK_EXPIRED_NS_INTERVAL;
1725 * Periodic callback: Write statistics to disk if appropriate.
1727 static int
1728 write_stats_file_callback(time_t now, const or_options_t *options)
1730 /* 1g. Check whether we should write statistics to disk.
1732 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1733 time_t next_time_to_write_stats_files = now + CHECK_WRITE_STATS_INTERVAL;
1734 if (options->CellStatistics) {
1735 time_t next_write =
1736 rep_hist_buffer_stats_write(now);
1737 if (next_write && next_write < next_time_to_write_stats_files)
1738 next_time_to_write_stats_files = next_write;
1740 if (options->DirReqStatistics) {
1741 time_t next_write = geoip_dirreq_stats_write(now);
1742 if (next_write && next_write < next_time_to_write_stats_files)
1743 next_time_to_write_stats_files = next_write;
1745 if (options->EntryStatistics) {
1746 time_t next_write = geoip_entry_stats_write(now);
1747 if (next_write && next_write < next_time_to_write_stats_files)
1748 next_time_to_write_stats_files = next_write;
1750 if (options->HiddenServiceStatistics) {
1751 time_t next_write = rep_hist_hs_stats_write(now);
1752 if (next_write && next_write < next_time_to_write_stats_files)
1753 next_time_to_write_stats_files = next_write;
1755 if (options->ExitPortStatistics) {
1756 time_t next_write = rep_hist_exit_stats_write(now);
1757 if (next_write && next_write < next_time_to_write_stats_files)
1758 next_time_to_write_stats_files = next_write;
1760 if (options->ConnDirectionStatistics) {
1761 time_t next_write = rep_hist_conn_stats_write(now);
1762 if (next_write && next_write < next_time_to_write_stats_files)
1763 next_time_to_write_stats_files = next_write;
1765 if (options->BridgeAuthoritativeDir) {
1766 time_t next_write = rep_hist_desc_stats_write(now);
1767 if (next_write && next_write < next_time_to_write_stats_files)
1768 next_time_to_write_stats_files = next_write;
1771 return safe_timer_diff(now, next_time_to_write_stats_files);
1774 #define CHANNEL_CHECK_INTERVAL (60*60)
1775 static int
1776 check_canonical_channels_callback(time_t now, const or_options_t *options)
1778 (void)now;
1779 if (public_server_mode(options))
1780 channel_check_for_duplicates();
1782 return CHANNEL_CHECK_INTERVAL;
1785 static int
1786 reset_padding_counts_callback(time_t now, const or_options_t *options)
1788 if (options->PaddingStatistics) {
1789 rep_hist_prep_published_padding_counts(now);
1792 rep_hist_reset_padding_counts();
1793 return REPHIST_CELL_PADDING_COUNTS_INTERVAL;
1797 * Periodic callback: Write bridge statistics to disk if appropriate.
1799 static int
1800 record_bridge_stats_callback(time_t now, const or_options_t *options)
1802 static int should_init_bridge_stats = 1;
1804 /* 1h. Check whether we should write bridge statistics to disk.
1806 if (should_record_bridge_info(options)) {
1807 if (should_init_bridge_stats) {
1808 /* (Re-)initialize bridge statistics. */
1809 geoip_bridge_stats_init(now);
1810 should_init_bridge_stats = 0;
1811 return WRITE_STATS_INTERVAL;
1812 } else {
1813 /* Possibly write bridge statistics to disk and ask when to write
1814 * them next time. */
1815 time_t next = geoip_bridge_stats_write(now);
1816 return safe_timer_diff(now, next);
1818 } else if (!should_init_bridge_stats) {
1819 /* Bridge mode was turned off. Ensure that stats are re-initialized
1820 * next time bridge mode is turned on. */
1821 should_init_bridge_stats = 1;
1823 return PERIODIC_EVENT_NO_UPDATE;
1827 * Periodic callback: Clean in-memory caches every once in a while
1829 static int
1830 clean_caches_callback(time_t now, const or_options_t *options)
1832 /* Remove old information from rephist and the rend cache. */
1833 rep_history_clean(now - options->RephistTrackTime);
1834 rend_cache_clean(now, REND_CACHE_TYPE_SERVICE);
1835 hs_cache_clean_as_client(now);
1836 hs_cache_clean_as_dir(now);
1837 microdesc_cache_rebuild(NULL, 0);
1838 #define CLEAN_CACHES_INTERVAL (30*60)
1839 return CLEAN_CACHES_INTERVAL;
1843 * Periodic callback: Clean the cache of failed hidden service lookups
1844 * frequently.
1846 static int
1847 rend_cache_failure_clean_callback(time_t now, const or_options_t *options)
1849 (void)options;
1850 /* We don't keep entries that are more than five minutes old so we try to
1851 * clean it as soon as we can since we want to make sure the client waits
1852 * as little as possible for reachability reasons. */
1853 rend_cache_failure_clean(now);
1854 hs_cache_client_intro_state_clean(now);
1855 return 30;
1859 * Periodic callback: If we're a server and initializing dns failed, retry.
1861 static int
1862 retry_dns_callback(time_t now, const or_options_t *options)
1864 (void)now;
1865 #define RETRY_DNS_INTERVAL (10*60)
1866 if (server_mode(options) && has_dns_init_failed())
1867 dns_init();
1868 return RETRY_DNS_INTERVAL;
1871 /** Periodic callback: consider rebuilding or and re-uploading our descriptor
1872 * (if we've passed our internal checks). */
1873 static int
1874 check_descriptor_callback(time_t now, const or_options_t *options)
1876 /** How often do we check whether part of our router info has changed in a
1877 * way that would require an upload? That includes checking whether our IP
1878 * address has changed. */
1879 #define CHECK_DESCRIPTOR_INTERVAL (60)
1881 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1882 * one is inaccurate. */
1883 if (!options->DisableNetwork) {
1884 check_descriptor_bandwidth_changed(now);
1885 check_descriptor_ipaddress_changed(now);
1886 mark_my_descriptor_dirty_if_too_old(now);
1887 consider_publishable_server(0);
1888 /* If any networkstatus documents are no longer recent, we need to
1889 * update all the descriptors' running status. */
1890 /* Remove dead routers. */
1891 /* XXXX This doesn't belong here, but it was here in the pre-
1892 * XXXX refactoring code. */
1893 routerlist_remove_old_routers();
1896 return CHECK_DESCRIPTOR_INTERVAL;
1900 * Periodic callback: check whether we're reachable (as a relay), and
1901 * whether our bandwidth has changed enough that we need to
1902 * publish a new descriptor.
1904 static int
1905 check_for_reachability_bw_callback(time_t now, const or_options_t *options)
1907 /* XXXX This whole thing was stuck in the middle of what is now
1908 * XXXX check_descriptor_callback. I'm not sure it's right. */
1910 static int dirport_reachability_count = 0;
1911 /* also, check religiously for reachability, if it's within the first
1912 * 20 minutes of our uptime. */
1913 if (server_mode(options) &&
1914 (have_completed_a_circuit() || !any_predicted_circuits(now)) &&
1915 !we_are_hibernating()) {
1916 if (stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1917 consider_testing_reachability(1, dirport_reachability_count==0);
1918 if (++dirport_reachability_count > 5)
1919 dirport_reachability_count = 0;
1920 return 1;
1921 } else {
1922 /* If we haven't checked for 12 hours and our bandwidth estimate is
1923 * low, do another bandwidth test. This is especially important for
1924 * bridges, since they might go long periods without much use. */
1925 const routerinfo_t *me = router_get_my_routerinfo();
1926 static int first_time = 1;
1927 if (!first_time && me &&
1928 me->bandwidthcapacity < me->bandwidthrate &&
1929 me->bandwidthcapacity < 51200) {
1930 reset_bandwidth_test();
1932 first_time = 0;
1933 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1934 return BANDWIDTH_RECHECK_INTERVAL;
1937 return CHECK_DESCRIPTOR_INTERVAL;
1941 * Periodic event: once a minute, (or every second if TestingTorNetwork, or
1942 * during client bootstrap), check whether we want to download any
1943 * networkstatus documents. */
1944 static int
1945 fetch_networkstatus_callback(time_t now, const or_options_t *options)
1947 /* How often do we check whether we should download network status
1948 * documents? */
1949 const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
1950 now);
1951 const int prefer_mirrors = !directory_fetches_from_authorities(
1952 get_options());
1953 int networkstatus_dl_check_interval = 60;
1954 /* check more often when testing, or when bootstrapping from mirrors
1955 * (connection limits prevent too many connections being made) */
1956 if (options->TestingTorNetwork
1957 || (we_are_bootstrapping && prefer_mirrors)) {
1958 networkstatus_dl_check_interval = 1;
1961 if (should_delay_dir_fetches(options, NULL))
1962 return PERIODIC_EVENT_NO_UPDATE;
1964 update_networkstatus_downloads(now);
1965 return networkstatus_dl_check_interval;
1969 * Periodic callback: Every 60 seconds, we relaunch listeners if any died. */
1970 static int
1971 retry_listeners_callback(time_t now, const or_options_t *options)
1973 (void)now;
1974 (void)options;
1975 if (!net_is_disabled()) {
1976 retry_all_listeners(NULL, NULL, 0);
1977 return 60;
1979 return PERIODIC_EVENT_NO_UPDATE;
1983 * Periodic callback: as a server, see if we have any old unused circuits
1984 * that should be expired */
1985 static int
1986 expire_old_ciruits_serverside_callback(time_t now, const or_options_t *options)
1988 (void)options;
1989 /* every 11 seconds, so not usually the same second as other such events */
1990 circuit_expire_old_circuits_serverside(now);
1991 return 11;
1995 * Periodic event: if we're an exit, see if our DNS server is telling us
1996 * obvious lies.
1998 static int
1999 check_dns_honesty_callback(time_t now, const or_options_t *options)
2001 (void)now;
2002 /* 9. and if we're an exit node, check whether our DNS is telling stories
2003 * to us. */
2004 if (net_is_disabled() ||
2005 ! public_server_mode(options) ||
2006 router_my_exit_policy_is_reject_star())
2007 return PERIODIC_EVENT_NO_UPDATE;
2009 static int first_time = 1;
2010 if (first_time) {
2011 /* Don't launch right when we start */
2012 first_time = 0;
2013 return crypto_rand_int_range(60, 180);
2016 dns_launch_correctness_checks();
2017 return 12*3600 + crypto_rand_int(12*3600);
2021 * Periodic callback: if we're the bridge authority, write a networkstatus
2022 * file to disk.
2024 static int
2025 write_bridge_ns_callback(time_t now, const or_options_t *options)
2027 /* 10. write bridge networkstatus file to disk */
2028 if (options->BridgeAuthoritativeDir) {
2029 networkstatus_dump_bridge_status_to_file(now);
2030 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
2031 return BRIDGE_STATUSFILE_INTERVAL;
2033 return PERIODIC_EVENT_NO_UPDATE;
2037 * Periodic callback: poke the tor-fw-helper app if we're using one.
2039 static int
2040 check_fw_helper_app_callback(time_t now, const or_options_t *options)
2042 if (net_is_disabled() ||
2043 ! server_mode(options) ||
2044 ! options->PortForwarding ||
2045 options->NoExec) {
2046 return PERIODIC_EVENT_NO_UPDATE;
2048 /* 11. check the port forwarding app */
2050 #define PORT_FORWARDING_CHECK_INTERVAL 5
2051 smartlist_t *ports_to_forward = get_list_of_ports_to_forward();
2052 if (ports_to_forward) {
2053 tor_check_port_forwarding(options->PortForwardingHelper,
2054 ports_to_forward,
2055 now);
2057 SMARTLIST_FOREACH(ports_to_forward, char *, cp, tor_free(cp));
2058 smartlist_free(ports_to_forward);
2060 return PORT_FORWARDING_CHECK_INTERVAL;
2064 * Periodic callback: write the heartbeat message in the logs.
2066 * If writing the heartbeat message to the logs fails for some reason, retry
2067 * again after <b>MIN_HEARTBEAT_PERIOD</b> seconds.
2069 static int
2070 heartbeat_callback(time_t now, const or_options_t *options)
2072 static int first = 1;
2074 /* Check if heartbeat is disabled */
2075 if (!options->HeartbeatPeriod) {
2076 return PERIODIC_EVENT_NO_UPDATE;
2079 /* Skip the first one. */
2080 if (first) {
2081 first = 0;
2082 return options->HeartbeatPeriod;
2085 /* Write the heartbeat message */
2086 if (log_heartbeat(now) == 0) {
2087 return options->HeartbeatPeriod;
2088 } else {
2089 /* If we couldn't write the heartbeat log message, try again in the minimum
2090 * interval of time. */
2091 return MIN_HEARTBEAT_PERIOD;
2095 #define CDM_CLEAN_CALLBACK_INTERVAL 600
2096 static int
2097 clean_consdiffmgr_callback(time_t now, const or_options_t *options)
2099 (void)now;
2100 if (server_mode(options)) {
2101 consdiffmgr_cleanup();
2103 return CDM_CLEAN_CALLBACK_INTERVAL;
2107 * Periodic callback: Run scheduled events for HS service. This is called
2108 * every second.
2110 static int
2111 hs_service_callback(time_t now, const or_options_t *options)
2113 (void) options;
2115 /* We need to at least be able to build circuits and that we actually have
2116 * a working network. */
2117 if (!have_completed_a_circuit() || net_is_disabled() ||
2118 networkstatus_get_live_consensus(now) == NULL) {
2119 goto end;
2122 hs_service_run_scheduled_events(now);
2124 end:
2125 /* Every 1 second. */
2126 return 1;
2129 /** Timer: used to invoke second_elapsed_callback() once per second. */
2130 static periodic_timer_t *second_timer = NULL;
2131 /** Number of libevent errors in the last second: we die if we get too many. */
2132 static int n_libevent_errors = 0;
2134 /** Libevent callback: invoked once every second. */
2135 static void
2136 second_elapsed_callback(periodic_timer_t *timer, void *arg)
2138 /* XXXX This could be sensibly refactored into multiple callbacks, and we
2139 * could use Libevent's timers for this rather than checking the current
2140 * time against a bunch of timeouts every second. */
2141 static time_t current_second = 0;
2142 time_t now;
2143 size_t bytes_written;
2144 size_t bytes_read;
2145 int seconds_elapsed;
2146 const or_options_t *options = get_options();
2147 (void)timer;
2148 (void)arg;
2150 n_libevent_errors = 0;
2152 /* log_notice(LD_GENERAL, "Tick."); */
2153 now = time(NULL);
2154 update_approx_time(now);
2156 /* the second has rolled over. check more stuff. */
2157 seconds_elapsed = current_second ? (int)(now - current_second) : 0;
2158 bytes_read = (size_t)(stats_n_bytes_read - stats_prev_n_read);
2159 bytes_written = (size_t)(stats_n_bytes_written - stats_prev_n_written);
2160 stats_prev_n_read = stats_n_bytes_read;
2161 stats_prev_n_written = stats_n_bytes_written;
2163 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
2164 control_event_stream_bandwidth_used();
2165 control_event_conn_bandwidth_used();
2166 control_event_circ_bandwidth_used();
2167 control_event_circuit_cell_stats();
2169 if (server_mode(options) &&
2170 !net_is_disabled() &&
2171 seconds_elapsed > 0 &&
2172 have_completed_a_circuit() &&
2173 stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
2174 (stats_n_seconds_working+seconds_elapsed) /
2175 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
2176 /* every 20 minutes, check and complain if necessary */
2177 const routerinfo_t *me = router_get_my_routerinfo();
2178 if (me && !check_whether_orport_reachable(options)) {
2179 char *address = tor_dup_ip(me->addr);
2180 log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
2181 "its ORPort is reachable. Relays do not publish descriptors "
2182 "until their ORPort and DirPort are reachable. Please check "
2183 "your firewalls, ports, address, /etc/hosts file, etc.",
2184 address, me->or_port);
2185 control_event_server_status(LOG_WARN,
2186 "REACHABILITY_FAILED ORADDRESS=%s:%d",
2187 address, me->or_port);
2188 tor_free(address);
2191 if (me && !check_whether_dirport_reachable(options)) {
2192 char *address = tor_dup_ip(me->addr);
2193 log_warn(LD_CONFIG,
2194 "Your server (%s:%d) has not managed to confirm that its "
2195 "DirPort is reachable. Relays do not publish descriptors "
2196 "until their ORPort and DirPort are reachable. Please check "
2197 "your firewalls, ports, address, /etc/hosts file, etc.",
2198 address, me->dir_port);
2199 control_event_server_status(LOG_WARN,
2200 "REACHABILITY_FAILED DIRADDRESS=%s:%d",
2201 address, me->dir_port);
2202 tor_free(address);
2206 /** If more than this many seconds have elapsed, probably the clock
2207 * jumped: doesn't count. */
2208 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
2209 if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
2210 seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
2211 circuit_note_clock_jumped(seconds_elapsed);
2212 } else if (seconds_elapsed > 0)
2213 stats_n_seconds_working += seconds_elapsed;
2215 run_scheduled_events(now);
2217 current_second = now; /* remember which second it is, for next time */
2220 #ifdef HAVE_SYSTEMD_209
2221 static periodic_timer_t *systemd_watchdog_timer = NULL;
2223 /** Libevent callback: invoked to reset systemd watchdog. */
2224 static void
2225 systemd_watchdog_callback(periodic_timer_t *timer, void *arg)
2227 (void)timer;
2228 (void)arg;
2229 sd_notify(0, "WATCHDOG=1");
2231 #endif /* defined(HAVE_SYSTEMD_209) */
2233 /** Timer: used to invoke refill_callback(). */
2234 static periodic_timer_t *refill_timer = NULL;
2236 /** Libevent callback: invoked periodically to refill token buckets
2237 * and count r/w bytes. */
2238 static void
2239 refill_callback(periodic_timer_t *timer, void *arg)
2241 static struct timeval current_millisecond;
2242 struct timeval now;
2244 size_t bytes_written;
2245 size_t bytes_read;
2246 int milliseconds_elapsed = 0;
2247 int seconds_rolled_over = 0;
2249 const or_options_t *options = get_options();
2251 (void)timer;
2252 (void)arg;
2254 tor_gettimeofday(&now);
2256 /* If this is our first time, no time has passed. */
2257 if (current_millisecond.tv_sec) {
2258 long mdiff = tv_mdiff(&current_millisecond, &now);
2259 if (mdiff > INT_MAX)
2260 mdiff = INT_MAX;
2261 milliseconds_elapsed = (int)mdiff;
2262 seconds_rolled_over = (int)(now.tv_sec - current_millisecond.tv_sec);
2265 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
2266 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
2268 stats_n_bytes_read += bytes_read;
2269 stats_n_bytes_written += bytes_written;
2270 if (accounting_is_enabled(options) && milliseconds_elapsed >= 0)
2271 accounting_add_bytes(bytes_read, bytes_written, seconds_rolled_over);
2273 if (milliseconds_elapsed > 0)
2274 connection_bucket_refill(milliseconds_elapsed, (time_t)now.tv_sec);
2276 stats_prev_global_read_bucket = global_read_bucket;
2277 stats_prev_global_write_bucket = global_write_bucket;
2279 current_millisecond = now; /* remember what time it is, for next time */
2282 #ifndef _WIN32
2283 /** Called when a possibly ignorable libevent error occurs; ensures that we
2284 * don't get into an infinite loop by ignoring too many errors from
2285 * libevent. */
2286 static int
2287 got_libevent_error(void)
2289 if (++n_libevent_errors > 8) {
2290 log_err(LD_NET, "Too many libevent errors in one second; dying");
2291 return -1;
2293 return 0;
2295 #endif /* !defined(_WIN32) */
2297 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
2299 /** Called when our IP address seems to have changed. <b>at_interface</b>
2300 * should be true if we detected a change in our interface, and false if we
2301 * detected a change in our published address. */
2302 void
2303 ip_address_changed(int at_interface)
2305 const or_options_t *options = get_options();
2306 int server = server_mode(options);
2307 int exit_reject_interfaces = (server && options->ExitRelay
2308 && options->ExitPolicyRejectLocalInterfaces);
2310 if (at_interface) {
2311 if (! server) {
2312 /* Okay, change our keys. */
2313 if (init_keys_client() < 0)
2314 log_warn(LD_GENERAL, "Unable to rotate keys after IP change!");
2316 } else {
2317 if (server) {
2318 if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
2319 reset_bandwidth_test();
2320 stats_n_seconds_working = 0;
2321 router_reset_reachability();
2325 /* Exit relays incorporate interface addresses in their exit policies when
2326 * ExitPolicyRejectLocalInterfaces is set */
2327 if (exit_reject_interfaces || (server && !at_interface)) {
2328 mark_my_descriptor_dirty("IP address changed");
2331 dns_servers_relaunch_checks();
2334 /** Forget what we've learned about the correctness of our DNS servers, and
2335 * start learning again. */
2336 void
2337 dns_servers_relaunch_checks(void)
2339 if (server_mode(get_options())) {
2340 dns_reset_correctness_checks();
2341 if (periodic_events_initialized) {
2342 tor_assert(check_dns_honesty_event);
2343 periodic_event_reschedule(check_dns_honesty_event);
2348 /** Called when we get a SIGHUP: reload configuration files and keys,
2349 * retry all connections, and so on. */
2350 static int
2351 do_hup(void)
2353 const or_options_t *options = get_options();
2355 #ifdef USE_DMALLOC
2356 dmalloc_log_stats();
2357 dmalloc_log_changed(0, 1, 0, 0);
2358 #endif
2360 log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
2361 "resetting internal state.");
2362 if (accounting_is_enabled(options))
2363 accounting_record_bandwidth_usage(time(NULL), get_or_state());
2365 router_reset_warnings();
2366 routerlist_reset_warnings();
2367 /* first, reload config variables, in case they've changed */
2368 if (options->ReloadTorrcOnSIGHUP) {
2369 /* no need to provide argc/v, they've been cached in init_from_config */
2370 if (options_init_from_torrc(0, NULL) < 0) {
2371 log_err(LD_CONFIG,"Reading config failed--see warnings above. "
2372 "For usage, try -h.");
2373 return -1;
2375 options = get_options(); /* they have changed now */
2376 /* Logs are only truncated the first time they are opened, but were
2377 probably intended to be cleaned up on signal. */
2378 if (options->TruncateLogFile)
2379 truncate_logs();
2380 } else {
2381 char *msg = NULL;
2382 log_notice(LD_GENERAL, "Not reloading config file: the controller told "
2383 "us not to.");
2384 /* Make stuff get rescanned, reloaded, etc. */
2385 if (set_options((or_options_t*)options, &msg) < 0) {
2386 if (!msg)
2387 msg = tor_strdup("Unknown error");
2388 log_warn(LD_GENERAL, "Unable to re-set previous options: %s", msg);
2389 tor_free(msg);
2392 if (authdir_mode(options)) {
2393 /* reload the approved-routers file */
2394 if (dirserv_load_fingerprint_file() < 0) {
2395 /* warnings are logged from dirserv_load_fingerprint_file() directly */
2396 log_info(LD_GENERAL, "Error reloading fingerprints. "
2397 "Continuing with old list.");
2401 /* Rotate away from the old dirty circuits. This has to be done
2402 * after we've read the new options, but before we start using
2403 * circuits for directory fetches. */
2404 circuit_mark_all_dirty_circs_as_unusable();
2406 /* retry appropriate downloads */
2407 router_reset_status_download_failures();
2408 router_reset_descriptor_download_failures();
2409 if (!options->DisableNetwork)
2410 update_networkstatus_downloads(time(NULL));
2412 /* We'll retry routerstatus downloads in about 10 seconds; no need to
2413 * force a retry there. */
2415 if (server_mode(options)) {
2416 /* Maybe we've been given a new ed25519 key or certificate?
2418 time_t now = approx_time();
2419 int new_signing_key = load_ed_keys(options, now);
2420 if (new_signing_key < 0 ||
2421 generate_ed_link_cert(options, now, new_signing_key > 0)) {
2422 log_warn(LD_OR, "Problem reloading Ed25519 keys; still using old keys.");
2425 /* Update cpuworker and dnsworker processes, so they get up-to-date
2426 * configuration options. */
2427 cpuworkers_rotate_keyinfo();
2428 dns_reset();
2430 return 0;
2433 /** Tor main loop. */
2435 do_main_loop(void)
2437 time_t now;
2439 /* initialize the periodic events first, so that code that depends on the
2440 * events being present does not assert.
2442 if (! periodic_events_initialized) {
2443 initialize_periodic_events();
2446 /* initialize dns resolve map, spawn workers if needed */
2447 if (dns_init() < 0) {
2448 if (get_options()->ServerDNSAllowBrokenConfig)
2449 log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
2450 "Network not up yet? Will try again soon.");
2451 else {
2452 log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
2453 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
2457 handle_signals(1);
2458 monotime_init();
2459 timers_initialize();
2461 /* load the private keys, if we're supposed to have them, and set up the
2462 * TLS context. */
2463 if (! client_identity_key_is_set()) {
2464 if (init_keys() < 0) {
2465 log_err(LD_OR, "Error initializing keys; exiting");
2466 return -1;
2470 /* Set up our buckets */
2471 connection_bucket_init();
2472 stats_prev_global_read_bucket = global_read_bucket;
2473 stats_prev_global_write_bucket = global_write_bucket;
2475 /* initialize the bootstrap status events to know we're starting up */
2476 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
2478 /* Initialize the keypinning log. */
2479 if (authdir_mode_v3(get_options())) {
2480 char *fname = get_datadir_fname("key-pinning-journal");
2481 int r = 0;
2482 if (keypin_load_journal(fname)<0) {
2483 log_err(LD_DIR, "Error loading key-pinning journal: %s",strerror(errno));
2484 r = -1;
2486 if (keypin_open_journal(fname)<0) {
2487 log_err(LD_DIR, "Error opening key-pinning journal: %s",strerror(errno));
2488 r = -1;
2490 tor_free(fname);
2491 if (r)
2492 return r;
2495 /* This is the old name for key-pinning-journal. These got corrupted
2496 * in a couple of cases by #16530, so we started over. See #16580 for
2497 * the rationale and for other options we didn't take. We can remove
2498 * this code once all the authorities that ran 0.2.7.1-alpha-dev are
2499 * upgraded.
2501 char *fname = get_datadir_fname("key-pinning-entries");
2502 unlink(fname);
2503 tor_free(fname);
2506 if (trusted_dirs_reload_certs()) {
2507 log_warn(LD_DIR,
2508 "Couldn't load all cached v3 certificates. Starting anyway.");
2510 if (router_reload_consensus_networkstatus()) {
2511 return -1;
2513 /* load the routers file, or assign the defaults. */
2514 if (router_reload_router_list()) {
2515 return -1;
2517 /* load the networkstatuses. (This launches a download for new routers as
2518 * appropriate.)
2520 now = time(NULL);
2521 directory_info_has_arrived(now, 1, 0);
2523 if (server_mode(get_options())) {
2524 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
2525 cpu_init();
2527 consdiffmgr_enable_background_compression();
2529 /* Setup shared random protocol subsystem. */
2530 if (authdir_mode_v3(get_options())) {
2531 if (sr_init(1) < 0) {
2532 return -1;
2536 /* set up once-a-second callback. */
2537 if (! second_timer) {
2538 struct timeval one_second;
2539 one_second.tv_sec = 1;
2540 one_second.tv_usec = 0;
2542 second_timer = periodic_timer_new(tor_libevent_get_base(),
2543 &one_second,
2544 second_elapsed_callback,
2545 NULL);
2546 tor_assert(second_timer);
2549 #ifdef HAVE_SYSTEMD_209
2550 uint64_t watchdog_delay;
2551 /* set up systemd watchdog notification. */
2552 if (sd_watchdog_enabled(1, &watchdog_delay) > 0) {
2553 if (! systemd_watchdog_timer) {
2554 struct timeval watchdog;
2555 /* The manager will "act on" us if we don't send them a notification
2556 * every 'watchdog_delay' microseconds. So, send notifications twice
2557 * that often. */
2558 watchdog_delay /= 2;
2559 watchdog.tv_sec = watchdog_delay / 1000000;
2560 watchdog.tv_usec = watchdog_delay % 1000000;
2562 systemd_watchdog_timer = periodic_timer_new(tor_libevent_get_base(),
2563 &watchdog,
2564 systemd_watchdog_callback,
2565 NULL);
2566 tor_assert(systemd_watchdog_timer);
2569 #endif /* defined(HAVE_SYSTEMD_209) */
2571 if (!refill_timer) {
2572 struct timeval refill_interval;
2573 int msecs = get_options()->TokenBucketRefillInterval;
2575 refill_interval.tv_sec = msecs/1000;
2576 refill_interval.tv_usec = (msecs%1000)*1000;
2578 refill_timer = periodic_timer_new(tor_libevent_get_base(),
2579 &refill_interval,
2580 refill_callback,
2581 NULL);
2582 tor_assert(refill_timer);
2585 #ifdef HAVE_SYSTEMD
2587 const int r = sd_notify(0, "READY=1");
2588 if (r < 0) {
2589 log_warn(LD_GENERAL, "Unable to send readiness to systemd: %s",
2590 strerror(r));
2591 } else if (r > 0) {
2592 log_notice(LD_GENERAL, "Signaled readiness to systemd");
2593 } else {
2594 log_info(LD_GENERAL, "Systemd NOTIFY_SOCKET not present.");
2597 #endif /* defined(HAVE_SYSTEMD) */
2599 return run_main_loop_until_done();
2603 * Run the main loop a single time. Return 0 for "exit"; -1 for "exit with
2604 * error", and 1 for "run this again."
2606 static int
2607 run_main_loop_once(void)
2609 int loop_result;
2611 if (nt_service_is_stopping())
2612 return 0;
2614 #ifndef _WIN32
2615 /* Make it easier to tell whether libevent failure is our fault or not. */
2616 errno = 0;
2617 #endif
2619 /* All active linked conns should get their read events activated,
2620 * so that libevent knows to run their callbacks. */
2621 SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
2622 event_active(conn->read_event, EV_READ, 1));
2623 called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
2625 /* Make sure we know (about) what time it is. */
2626 update_approx_time(time(NULL));
2628 /* Here it is: the main loop. Here we tell Libevent to poll until we have
2629 * an event, or the second ends, or until we have some active linked
2630 * connections to trigger events for. Libevent will wait till one
2631 * of these happens, then run all the appropriate callbacks. */
2632 loop_result = event_base_loop(tor_libevent_get_base(),
2633 called_loop_once ? EVLOOP_ONCE : 0);
2635 /* Oh, the loop failed. That might be an error that we need to
2636 * catch, but more likely, it's just an interrupted poll() call or something,
2637 * and we should try again. */
2638 if (loop_result < 0) {
2639 int e = tor_socket_errno(-1);
2640 /* let the program survive things like ^z */
2641 if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
2642 log_err(LD_NET,"libevent call with %s failed: %s [%d]",
2643 tor_libevent_get_method(), tor_socket_strerror(e), e);
2644 return -1;
2645 #ifndef _WIN32
2646 } else if (e == EINVAL) {
2647 log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
2648 if (got_libevent_error())
2649 return -1;
2650 #endif /* !defined(_WIN32) */
2651 } else {
2652 tor_assert_nonfatal_once(! ERRNO_IS_EINPROGRESS(e));
2653 log_debug(LD_NET,"libevent call interrupted.");
2654 /* You can't trust the results of this poll(). Go back to the
2655 * top of the big for loop. */
2656 return 1;
2660 /* And here is where we put callbacks that happen "every time the event loop
2661 * runs." They must be very fast, or else the whole Tor process will get
2662 * slowed down.
2664 * Note that this gets called once per libevent loop, which will make it
2665 * happen once per group of events that fire, or once per second. */
2667 /* If there are any pending client connections, try attaching them to
2668 * circuits (if we can.) This will be pretty fast if nothing new is
2669 * pending.
2671 connection_ap_attach_pending(0);
2673 return 1;
2676 /** Run the run_main_loop_once() function until it declares itself done,
2677 * and return its final return value.
2679 * Shadow won't invoke this function, so don't fill it up with things.
2681 static int
2682 run_main_loop_until_done(void)
2684 int loop_result = 1;
2685 do {
2686 loop_result = run_main_loop_once();
2687 } while (loop_result == 1);
2688 return loop_result;
2691 /** Libevent callback: invoked when we get a signal.
2693 static void
2694 signal_callback(evutil_socket_t fd, short events, void *arg)
2696 const int *sigptr = arg;
2697 const int sig = *sigptr;
2698 (void)fd;
2699 (void)events;
2701 process_signal(sig);
2704 /** Do the work of acting on a signal received in <b>sig</b> */
2705 static void
2706 process_signal(int sig)
2708 switch (sig)
2710 case SIGTERM:
2711 log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
2712 tor_cleanup();
2713 exit(0);
2714 break;
2715 case SIGINT:
2716 if (!server_mode(get_options())) { /* do it now */
2717 log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
2718 tor_cleanup();
2719 exit(0);
2721 #ifdef HAVE_SYSTEMD
2722 sd_notify(0, "STOPPING=1");
2723 #endif
2724 hibernate_begin_shutdown();
2725 break;
2726 #ifdef SIGPIPE
2727 case SIGPIPE:
2728 log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
2729 break;
2730 #endif
2731 case SIGUSR1:
2732 /* prefer to log it at INFO, but make sure we always see it */
2733 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
2734 control_event_signal(sig);
2735 break;
2736 case SIGUSR2:
2737 switch_logs_debug();
2738 log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
2739 "Send HUP to change back.");
2740 control_event_signal(sig);
2741 break;
2742 case SIGHUP:
2743 #ifdef HAVE_SYSTEMD
2744 sd_notify(0, "RELOADING=1");
2745 #endif
2746 if (do_hup() < 0) {
2747 log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
2748 tor_cleanup();
2749 exit(1);
2751 #ifdef HAVE_SYSTEMD
2752 sd_notify(0, "READY=1");
2753 #endif
2754 control_event_signal(sig);
2755 break;
2756 #ifdef SIGCHLD
2757 case SIGCHLD:
2758 notify_pending_waitpid_callbacks();
2759 break;
2760 #endif
2761 case SIGNEWNYM: {
2762 time_t now = time(NULL);
2763 if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
2764 signewnym_is_pending = 1;
2765 log_notice(LD_CONTROL,
2766 "Rate limiting NEWNYM request: delaying by %d second(s)",
2767 (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
2768 } else {
2769 signewnym_impl(now);
2771 break;
2773 case SIGCLEARDNSCACHE:
2774 addressmap_clear_transient();
2775 control_event_signal(sig);
2776 break;
2777 case SIGHEARTBEAT:
2778 log_heartbeat(time(NULL));
2779 control_event_signal(sig);
2780 break;
2784 /** Returns Tor's uptime. */
2785 MOCK_IMPL(long,
2786 get_uptime,(void))
2788 return stats_n_seconds_working;
2792 * Write current memory usage information to the log.
2794 static void
2795 dumpmemusage(int severity)
2797 connection_dump_buffer_mem_stats(severity);
2798 tor_log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
2799 U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
2800 dump_routerlist_mem_usage(severity);
2801 dump_cell_pool_usage(severity);
2802 dump_dns_mem_usage(severity);
2803 tor_log_mallinfo(severity);
2806 /** Write all statistics to the log, with log level <b>severity</b>. Called
2807 * in response to a SIGUSR1. */
2808 static void
2809 dumpstats(int severity)
2811 time_t now = time(NULL);
2812 time_t elapsed;
2813 size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
2815 tor_log(severity, LD_GENERAL, "Dumping stats:");
2817 SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
2818 int i = conn_sl_idx;
2819 tor_log(severity, LD_GENERAL,
2820 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
2821 i, (int)conn->s, conn->type, conn_type_to_string(conn->type),
2822 conn->state, conn_state_to_string(conn->type, conn->state),
2823 (int)(now - conn->timestamp_created));
2824 if (!connection_is_listener(conn)) {
2825 tor_log(severity,LD_GENERAL,
2826 "Conn %d is to %s:%d.", i,
2827 safe_str_client(conn->address),
2828 conn->port);
2829 tor_log(severity,LD_GENERAL,
2830 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
2832 (int)connection_get_inbuf_len(conn),
2833 (int)buf_allocation(conn->inbuf),
2834 (int)(now - conn->timestamp_lastread));
2835 tor_log(severity,LD_GENERAL,
2836 "Conn %d: %d bytes waiting on outbuf "
2837 "(len %d, last written %d secs ago)",i,
2838 (int)connection_get_outbuf_len(conn),
2839 (int)buf_allocation(conn->outbuf),
2840 (int)(now - conn->timestamp_lastwritten));
2841 if (conn->type == CONN_TYPE_OR) {
2842 or_connection_t *or_conn = TO_OR_CONN(conn);
2843 if (or_conn->tls) {
2844 if (tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
2845 &wbuf_cap, &wbuf_len) == 0) {
2846 tor_log(severity, LD_GENERAL,
2847 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
2848 "%d/%d bytes used on write buffer.",
2849 i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
2854 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
2855 * using this conn */
2856 } SMARTLIST_FOREACH_END(conn);
2858 channel_dumpstats(severity);
2859 channel_listener_dumpstats(severity);
2861 tor_log(severity, LD_NET,
2862 "Cells processed: "U64_FORMAT" padding\n"
2863 " "U64_FORMAT" create\n"
2864 " "U64_FORMAT" created\n"
2865 " "U64_FORMAT" relay\n"
2866 " ("U64_FORMAT" relayed)\n"
2867 " ("U64_FORMAT" delivered)\n"
2868 " "U64_FORMAT" destroy",
2869 U64_PRINTF_ARG(stats_n_padding_cells_processed),
2870 U64_PRINTF_ARG(stats_n_create_cells_processed),
2871 U64_PRINTF_ARG(stats_n_created_cells_processed),
2872 U64_PRINTF_ARG(stats_n_relay_cells_processed),
2873 U64_PRINTF_ARG(stats_n_relay_cells_relayed),
2874 U64_PRINTF_ARG(stats_n_relay_cells_delivered),
2875 U64_PRINTF_ARG(stats_n_destroy_cells_processed));
2876 if (stats_n_data_cells_packaged)
2877 tor_log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
2878 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
2879 U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
2880 if (stats_n_data_cells_received)
2881 tor_log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
2882 100*(U64_TO_DBL(stats_n_data_bytes_received) /
2883 U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
2885 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_TAP, "TAP");
2886 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_NTOR,"ntor");
2888 if (now - time_of_process_start >= 0)
2889 elapsed = now - time_of_process_start;
2890 else
2891 elapsed = 0;
2893 if (elapsed) {
2894 tor_log(severity, LD_NET,
2895 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
2896 U64_PRINTF_ARG(stats_n_bytes_read),
2897 (int)elapsed,
2898 (int) (stats_n_bytes_read/elapsed));
2899 tor_log(severity, LD_NET,
2900 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
2901 U64_PRINTF_ARG(stats_n_bytes_written),
2902 (int)elapsed,
2903 (int) (stats_n_bytes_written/elapsed));
2906 tor_log(severity, LD_NET, "--------------- Dumping memory information:");
2907 dumpmemusage(severity);
2909 rep_hist_dump_stats(now,severity);
2910 rend_service_dump_stats(severity);
2911 dump_distinct_digest_count(severity);
2914 /** Called by exit() as we shut down the process.
2916 static void
2917 exit_function(void)
2919 /* NOTE: If we ever daemonize, this gets called immediately. That's
2920 * okay for now, because we only use this on Windows. */
2921 #ifdef _WIN32
2922 WSACleanup();
2923 #endif
2926 #ifdef _WIN32
2927 #define UNIX_ONLY 0
2928 #else
2929 #define UNIX_ONLY 1
2930 #endif
2931 static struct {
2932 int signal_value;
2933 int try_to_register;
2934 struct event *signal_event;
2935 } signal_handlers[] = {
2936 #ifdef SIGINT
2937 { SIGINT, UNIX_ONLY, NULL }, /* do a controlled slow shutdown */
2938 #endif
2939 #ifdef SIGTERM
2940 { SIGTERM, UNIX_ONLY, NULL }, /* to terminate now */
2941 #endif
2942 #ifdef SIGPIPE
2943 { SIGPIPE, UNIX_ONLY, NULL }, /* otherwise SIGPIPE kills us */
2944 #endif
2945 #ifdef SIGUSR1
2946 { SIGUSR1, UNIX_ONLY, NULL }, /* dump stats */
2947 #endif
2948 #ifdef SIGUSR2
2949 { SIGUSR2, UNIX_ONLY, NULL }, /* go to loglevel debug */
2950 #endif
2951 #ifdef SIGHUP
2952 { SIGHUP, UNIX_ONLY, NULL }, /* to reload config, retry conns, etc */
2953 #endif
2954 #ifdef SIGXFSZ
2955 { SIGXFSZ, UNIX_ONLY, NULL }, /* handle file-too-big resource exhaustion */
2956 #endif
2957 #ifdef SIGCHLD
2958 { SIGCHLD, UNIX_ONLY, NULL }, /* handle dns/cpu workers that exit */
2959 #endif
2960 /* These are controller-only */
2961 { SIGNEWNYM, 0, NULL },
2962 { SIGCLEARDNSCACHE, 0, NULL },
2963 { SIGHEARTBEAT, 0, NULL },
2964 { -1, -1, NULL }
2967 /** Set up the signal handlers for either parent or child process */
2968 void
2969 handle_signals(int is_parent)
2971 int i;
2972 if (is_parent) {
2973 for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
2974 if (signal_handlers[i].try_to_register) {
2975 signal_handlers[i].signal_event =
2976 tor_evsignal_new(tor_libevent_get_base(),
2977 signal_handlers[i].signal_value,
2978 signal_callback,
2979 &signal_handlers[i].signal_value);
2980 if (event_add(signal_handlers[i].signal_event, NULL))
2981 log_warn(LD_BUG, "Error from libevent when adding "
2982 "event for signal %d",
2983 signal_handlers[i].signal_value);
2984 } else {
2985 signal_handlers[i].signal_event =
2986 tor_event_new(tor_libevent_get_base(), -1,
2987 EV_SIGNAL, signal_callback,
2988 &signal_handlers[i].signal_value);
2991 } else {
2992 #ifndef _WIN32
2993 struct sigaction action;
2994 action.sa_flags = 0;
2995 sigemptyset(&action.sa_mask);
2996 action.sa_handler = SIG_IGN;
2997 sigaction(SIGINT, &action, NULL);
2998 sigaction(SIGTERM, &action, NULL);
2999 sigaction(SIGPIPE, &action, NULL);
3000 sigaction(SIGUSR1, &action, NULL);
3001 sigaction(SIGUSR2, &action, NULL);
3002 sigaction(SIGHUP, &action, NULL);
3003 #ifdef SIGXFSZ
3004 sigaction(SIGXFSZ, &action, NULL);
3005 #endif
3006 #endif /* !defined(_WIN32) */
3010 /* Make sure the signal handler for signal_num will be called. */
3011 void
3012 activate_signal(int signal_num)
3014 int i;
3015 for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
3016 if (signal_handlers[i].signal_value == signal_num) {
3017 event_active(signal_handlers[i].signal_event, EV_SIGNAL, 1);
3018 return;
3023 /** Main entry point for the Tor command-line client.
3026 tor_init(int argc, char *argv[])
3028 char progname[256];
3029 int quiet = 0;
3031 time_of_process_start = time(NULL);
3032 init_connection_lists();
3033 /* Have the log set up with our application name. */
3034 tor_snprintf(progname, sizeof(progname), "Tor %s", get_version());
3035 log_set_application_name(progname);
3037 /* Set up the crypto nice and early */
3038 if (crypto_early_init() < 0) {
3039 log_err(LD_GENERAL, "Unable to initialize the crypto subsystem!");
3040 return -1;
3043 /* Initialize the history structures. */
3044 rep_hist_init();
3045 /* Initialize the service cache. */
3046 rend_cache_init();
3047 addressmap_init(); /* Init the client dns cache. Do it always, since it's
3048 * cheap. */
3049 /* Initialize the HS subsystem. */
3050 hs_init();
3053 /* We search for the "quiet" option first, since it decides whether we
3054 * will log anything at all to the command line. */
3055 config_line_t *opts = NULL, *cmdline_opts = NULL;
3056 const config_line_t *cl;
3057 (void) config_parse_commandline(argc, argv, 1, &opts, &cmdline_opts);
3058 for (cl = cmdline_opts; cl; cl = cl->next) {
3059 if (!strcmp(cl->key, "--hush"))
3060 quiet = 1;
3061 if (!strcmp(cl->key, "--quiet") ||
3062 !strcmp(cl->key, "--dump-config"))
3063 quiet = 2;
3064 /* The following options imply --hush */
3065 if (!strcmp(cl->key, "--version") || !strcmp(cl->key, "--digests") ||
3066 !strcmp(cl->key, "--list-torrc-options") ||
3067 !strcmp(cl->key, "--library-versions") ||
3068 !strcmp(cl->key, "--hash-password") ||
3069 !strcmp(cl->key, "-h") || !strcmp(cl->key, "--help")) {
3070 if (quiet < 1)
3071 quiet = 1;
3074 config_free_lines(opts);
3075 config_free_lines(cmdline_opts);
3078 /* give it somewhere to log to initially */
3079 switch (quiet) {
3080 case 2:
3081 /* no initial logging */
3082 break;
3083 case 1:
3084 add_temp_log(LOG_WARN);
3085 break;
3086 default:
3087 add_temp_log(LOG_NOTICE);
3089 quiet_level = quiet;
3092 const char *version = get_version();
3094 log_notice(LD_GENERAL, "Tor %s running on %s with Libevent %s, "
3095 "OpenSSL %s, Zlib %s, Liblzma %s, and Libzstd %s.", version,
3096 get_uname(),
3097 tor_libevent_get_version_str(),
3098 crypto_openssl_get_version_str(),
3099 tor_compress_supports_method(ZLIB_METHOD) ?
3100 tor_compress_version_str(ZLIB_METHOD) : "N/A",
3101 tor_compress_supports_method(LZMA_METHOD) ?
3102 tor_compress_version_str(LZMA_METHOD) : "N/A",
3103 tor_compress_supports_method(ZSTD_METHOD) ?
3104 tor_compress_version_str(ZSTD_METHOD) : "N/A");
3106 log_notice(LD_GENERAL, "Tor can't help you if you use it wrong! "
3107 "Learn how to be safe at "
3108 "https://www.torproject.org/download/download#warning");
3110 if (strstr(version, "alpha") || strstr(version, "beta"))
3111 log_notice(LD_GENERAL, "This version is not a stable Tor release. "
3112 "Expect more bugs than usual.");
3116 rust_str_t rust_str = rust_welcome_string();
3117 const char *s = rust_str_get(rust_str);
3118 if (strlen(s) > 0) {
3119 log_notice(LD_GENERAL, "%s", s);
3121 rust_str_free(rust_str);
3124 if (network_init()<0) {
3125 log_err(LD_BUG,"Error initializing network; exiting.");
3126 return -1;
3128 atexit(exit_function);
3130 if (options_init_from_torrc(argc,argv) < 0) {
3131 log_err(LD_CONFIG,"Reading config failed--see warnings above.");
3132 return -1;
3135 /* The options are now initialised */
3136 const or_options_t *options = get_options();
3138 /* Initialize channelpadding parameters to defaults until we get
3139 * a consensus */
3140 channelpadding_new_consensus_params(NULL);
3142 /* Initialize predicted ports list after loading options */
3143 predicted_ports_init();
3145 #ifndef _WIN32
3146 if (geteuid()==0)
3147 log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
3148 "and you probably shouldn't.");
3149 #endif
3151 if (crypto_global_init(options->HardwareAccel,
3152 options->AccelName,
3153 options->AccelDir)) {
3154 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
3155 return -1;
3157 stream_choice_seed_weak_rng();
3158 if (tor_init_libevent_rng() < 0) {
3159 log_warn(LD_NET, "Problem initializing libevent RNG.");
3162 /* Scan/clean unparseable descroptors; after reading config */
3163 routerparse_init();
3165 return 0;
3168 /** A lockfile structure, used to prevent two Tors from messing with the
3169 * data directory at once. If this variable is non-NULL, we're holding
3170 * the lockfile. */
3171 static tor_lockfile_t *lockfile = NULL;
3173 /** Try to grab the lock file described in <b>options</b>, if we do not
3174 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
3175 * holding the lock, and exit if we can't get it after waiting. Otherwise,
3176 * return -1 if we can't get the lockfile. Return 0 on success.
3179 try_locking(const or_options_t *options, int err_if_locked)
3181 if (lockfile)
3182 return 0;
3183 else {
3184 char *fname = options_get_datadir_fname2_suffix(options, "lock",NULL,NULL);
3185 int already_locked = 0;
3186 tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
3187 tor_free(fname);
3188 if (!lf) {
3189 if (err_if_locked && already_locked) {
3190 int r;
3191 log_warn(LD_GENERAL, "It looks like another Tor process is running "
3192 "with the same data directory. Waiting 5 seconds to see "
3193 "if it goes away.");
3194 #ifndef _WIN32
3195 sleep(5);
3196 #else
3197 Sleep(5000);
3198 #endif
3199 r = try_locking(options, 0);
3200 if (r<0) {
3201 log_err(LD_GENERAL, "No, it's still there. Exiting.");
3202 exit(1);
3204 return r;
3206 return -1;
3208 lockfile = lf;
3209 return 0;
3213 /** Return true iff we've successfully acquired the lock file. */
3215 have_lockfile(void)
3217 return lockfile != NULL;
3220 /** If we have successfully acquired the lock file, release it. */
3221 void
3222 release_lockfile(void)
3224 if (lockfile) {
3225 tor_lockfile_unlock(lockfile);
3226 lockfile = NULL;
3230 /** Free all memory that we might have allocated somewhere.
3231 * If <b>postfork</b>, we are a worker process and we want to free
3232 * only the parts of memory that we won't touch. If !<b>postfork</b>,
3233 * Tor is shutting down and we should free everything.
3235 * Helps us find the real leaks with dmalloc and the like. Also valgrind
3236 * should then report 0 reachable in its leak report (in an ideal world --
3237 * in practice libevent, SSL, libc etc never quite free everything). */
3238 void
3239 tor_free_all(int postfork)
3241 if (!postfork) {
3242 evdns_shutdown(1);
3244 geoip_free_all();
3245 dirvote_free_all();
3246 routerlist_free_all();
3247 networkstatus_free_all();
3248 addressmap_free_all();
3249 dirserv_free_all();
3250 rend_cache_free_all();
3251 rend_service_authorization_free_all();
3252 rep_hist_free_all();
3253 dns_free_all();
3254 clear_pending_onions();
3255 circuit_free_all();
3256 entry_guards_free_all();
3257 pt_free_all();
3258 channel_tls_free_all();
3259 channel_free_all();
3260 connection_free_all();
3261 connection_edge_free_all();
3262 scheduler_free_all();
3263 nodelist_free_all();
3264 microdesc_free_all();
3265 routerparse_free_all();
3266 ext_orport_free_all();
3267 control_free_all();
3268 sandbox_free_getaddrinfo_cache();
3269 protover_free_all();
3270 bridges_free_all();
3271 consdiffmgr_free_all();
3272 hs_free_all();
3273 dos_free_all();
3274 if (!postfork) {
3275 config_free_all();
3276 or_state_free_all();
3277 router_free_all();
3278 routerkeys_free_all();
3279 policies_free_all();
3281 if (!postfork) {
3282 tor_tls_free_all();
3283 #ifndef _WIN32
3284 tor_getpwnam(NULL);
3285 #endif
3287 /* stuff in main.c */
3289 smartlist_free(connection_array);
3290 smartlist_free(closeable_connection_lst);
3291 smartlist_free(active_linked_connection_lst);
3292 periodic_timer_free(second_timer);
3293 teardown_periodic_events();
3294 periodic_timer_free(refill_timer);
3296 if (!postfork) {
3297 release_lockfile();
3299 /* Stuff in util.c and address.c*/
3300 if (!postfork) {
3301 escaped(NULL);
3302 esc_router_info(NULL);
3303 clean_up_backtrace_handler();
3304 logs_free_all(); /* free log strings. do this last so logs keep working. */
3308 /** Do whatever cleanup is necessary before shutting Tor down. */
3309 void
3310 tor_cleanup(void)
3312 const or_options_t *options = get_options();
3313 if (options->command == CMD_RUN_TOR) {
3314 time_t now = time(NULL);
3315 /* Remove our pid file. We don't care if there was an error when we
3316 * unlink, nothing we could do about it anyways. */
3317 if (options->PidFile) {
3318 if (unlink(options->PidFile) != 0) {
3319 log_warn(LD_FS, "Couldn't unlink pid file %s: %s",
3320 options->PidFile, strerror(errno));
3323 if (options->ControlPortWriteToFile) {
3324 if (unlink(options->ControlPortWriteToFile) != 0) {
3325 log_warn(LD_FS, "Couldn't unlink control port file %s: %s",
3326 options->ControlPortWriteToFile,
3327 strerror(errno));
3330 if (accounting_is_enabled(options))
3331 accounting_record_bandwidth_usage(now, get_or_state());
3332 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
3333 or_state_save(now);
3334 if (authdir_mode(options)) {
3335 sr_save_and_cleanup();
3337 if (authdir_mode_tests_reachability(options))
3338 rep_hist_record_mtbf_data(now, 0);
3339 keypin_close_journal();
3342 timers_shutdown();
3344 #ifdef USE_DMALLOC
3345 dmalloc_log_stats();
3346 #endif
3347 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
3348 later, if it makes shutdown unacceptably slow. But for
3349 now, leave it here: it's helped us catch bugs in the
3350 past. */
3351 crypto_global_cleanup();
3352 #ifdef USE_DMALLOC
3353 dmalloc_log_unfreed();
3354 dmalloc_shutdown();
3355 #endif
3358 /** Read/create keys as needed, and echo our fingerprint to stdout. */
3359 static int
3360 do_list_fingerprint(void)
3362 char buf[FINGERPRINT_LEN+1];
3363 crypto_pk_t *k;
3364 const char *nickname = get_options()->Nickname;
3365 sandbox_disable_getaddrinfo_cache();
3366 if (!server_mode(get_options())) {
3367 log_err(LD_GENERAL,
3368 "Clients don't have long-term identity keys. Exiting.");
3369 return -1;
3371 tor_assert(nickname);
3372 if (init_keys() < 0) {
3373 log_err(LD_GENERAL,"Error initializing keys; exiting.");
3374 return -1;
3376 if (!(k = get_server_identity_key())) {
3377 log_err(LD_GENERAL,"Error: missing identity key.");
3378 return -1;
3380 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
3381 log_err(LD_BUG, "Error computing fingerprint");
3382 return -1;
3384 printf("%s %s\n", nickname, buf);
3385 return 0;
3388 /** Entry point for password hashing: take the desired password from
3389 * the command line, and print its salted hash to stdout. **/
3390 static void
3391 do_hash_password(void)
3394 char output[256];
3395 char key[S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN];
3397 crypto_rand(key, S2K_RFC2440_SPECIFIER_LEN-1);
3398 key[S2K_RFC2440_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
3399 secret_to_key_rfc2440(key+S2K_RFC2440_SPECIFIER_LEN, DIGEST_LEN,
3400 get_options()->command_arg, strlen(get_options()->command_arg),
3401 key);
3402 base16_encode(output, sizeof(output), key, sizeof(key));
3403 printf("16:%s\n",output);
3406 /** Entry point for configuration dumping: write the configuration to
3407 * stdout. */
3408 static int
3409 do_dump_config(void)
3411 const or_options_t *options = get_options();
3412 const char *arg = options->command_arg;
3413 int how;
3414 char *opts;
3416 if (!strcmp(arg, "short")) {
3417 how = OPTIONS_DUMP_MINIMAL;
3418 } else if (!strcmp(arg, "non-builtin")) {
3419 how = OPTIONS_DUMP_DEFAULTS;
3420 } else if (!strcmp(arg, "full")) {
3421 how = OPTIONS_DUMP_ALL;
3422 } else {
3423 fprintf(stderr, "No valid argument to --dump-config found!\n");
3424 fprintf(stderr, "Please select 'short', 'non-builtin', or 'full'.\n");
3426 return -1;
3429 opts = options_dump(options, how);
3430 printf("%s", opts);
3431 tor_free(opts);
3433 return 0;
3436 static void
3437 init_addrinfo(void)
3439 if (! server_mode(get_options()) ||
3440 (get_options()->Address && strlen(get_options()->Address) > 0)) {
3441 /* We don't need to seed our own hostname, because we won't be calling
3442 * resolve_my_address on it.
3444 return;
3446 char hname[256];
3448 // host name to sandbox
3449 gethostname(hname, sizeof(hname));
3450 sandbox_add_addrinfo(hname);
3453 static sandbox_cfg_t*
3454 sandbox_init_filter(void)
3456 const or_options_t *options = get_options();
3457 sandbox_cfg_t *cfg = sandbox_cfg_new();
3458 int i;
3460 sandbox_cfg_allow_openat_filename(&cfg,
3461 get_datadir_fname("cached-status"));
3463 #define OPEN(name) \
3464 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
3466 #define OPEN_DATADIR(name) \
3467 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
3469 #define OPEN_DATADIR2(name, name2) \
3470 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
3472 #define OPEN_DATADIR_SUFFIX(name, suffix) do { \
3473 OPEN_DATADIR(name); \
3474 OPEN_DATADIR(name suffix); \
3475 } while (0)
3477 #define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
3478 OPEN_DATADIR2(name, name2); \
3479 OPEN_DATADIR2(name, name2 suffix); \
3480 } while (0)
3482 OPEN(options->DataDirectory);
3483 OPEN_DATADIR("keys");
3484 OPEN_DATADIR_SUFFIX("cached-certs", ".tmp");
3485 OPEN_DATADIR_SUFFIX("cached-consensus", ".tmp");
3486 OPEN_DATADIR_SUFFIX("unverified-consensus", ".tmp");
3487 OPEN_DATADIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
3488 OPEN_DATADIR_SUFFIX("cached-microdesc-consensus", ".tmp");
3489 OPEN_DATADIR_SUFFIX("cached-microdescs", ".tmp");
3490 OPEN_DATADIR_SUFFIX("cached-microdescs.new", ".tmp");
3491 OPEN_DATADIR_SUFFIX("cached-descriptors", ".tmp");
3492 OPEN_DATADIR_SUFFIX("cached-descriptors.new", ".tmp");
3493 OPEN_DATADIR("cached-descriptors.tmp.tmp");
3494 OPEN_DATADIR_SUFFIX("cached-extrainfo", ".tmp");
3495 OPEN_DATADIR_SUFFIX("cached-extrainfo.new", ".tmp");
3496 OPEN_DATADIR("cached-extrainfo.tmp.tmp");
3497 OPEN_DATADIR_SUFFIX("state", ".tmp");
3498 OPEN_DATADIR_SUFFIX("sr-state", ".tmp");
3499 OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
3500 OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
3501 OPEN_DATADIR("key-pinning-journal");
3502 OPEN("/dev/srandom");
3503 OPEN("/dev/urandom");
3504 OPEN("/dev/random");
3505 OPEN("/etc/hosts");
3506 OPEN("/proc/meminfo");
3508 if (options->BridgeAuthoritativeDir)
3509 OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
3511 if (authdir_mode(options))
3512 OPEN_DATADIR("approved-routers");
3514 if (options->ServerDNSResolvConfFile)
3515 sandbox_cfg_allow_open_filename(&cfg,
3516 tor_strdup(options->ServerDNSResolvConfFile));
3517 else
3518 sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
3520 for (i = 0; i < 2; ++i) {
3521 if (get_torrc_fname(i)) {
3522 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(get_torrc_fname(i)));
3526 #define RENAME_SUFFIX(name, suffix) \
3527 sandbox_cfg_allow_rename(&cfg, \
3528 get_datadir_fname(name suffix), \
3529 get_datadir_fname(name))
3531 #define RENAME_SUFFIX2(prefix, name, suffix) \
3532 sandbox_cfg_allow_rename(&cfg, \
3533 get_datadir_fname2(prefix, name suffix), \
3534 get_datadir_fname2(prefix, name))
3536 RENAME_SUFFIX("cached-certs", ".tmp");
3537 RENAME_SUFFIX("cached-consensus", ".tmp");
3538 RENAME_SUFFIX("unverified-consensus", ".tmp");
3539 RENAME_SUFFIX("unverified-microdesc-consensus", ".tmp");
3540 RENAME_SUFFIX("cached-microdesc-consensus", ".tmp");
3541 RENAME_SUFFIX("cached-microdescs", ".tmp");
3542 RENAME_SUFFIX("cached-microdescs", ".new");
3543 RENAME_SUFFIX("cached-microdescs.new", ".tmp");
3544 RENAME_SUFFIX("cached-descriptors", ".tmp");
3545 RENAME_SUFFIX("cached-descriptors", ".new");
3546 RENAME_SUFFIX("cached-descriptors.new", ".tmp");
3547 RENAME_SUFFIX("cached-extrainfo", ".tmp");
3548 RENAME_SUFFIX("cached-extrainfo", ".new");
3549 RENAME_SUFFIX("cached-extrainfo.new", ".tmp");
3550 RENAME_SUFFIX("state", ".tmp");
3551 RENAME_SUFFIX("sr-state", ".tmp");
3552 RENAME_SUFFIX("unparseable-desc", ".tmp");
3553 RENAME_SUFFIX("v3-status-votes", ".tmp");
3555 if (options->BridgeAuthoritativeDir)
3556 RENAME_SUFFIX("networkstatus-bridges", ".tmp");
3558 #define STAT_DATADIR(name) \
3559 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
3561 #define STAT_DATADIR2(name, name2) \
3562 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
3564 STAT_DATADIR(NULL);
3565 STAT_DATADIR("lock");
3566 STAT_DATADIR("state");
3567 STAT_DATADIR("router-stability");
3568 STAT_DATADIR("cached-extrainfo.new");
3571 smartlist_t *files = smartlist_new();
3572 tor_log_get_logfile_names(files);
3573 SMARTLIST_FOREACH(files, char *, file_name, {
3574 /* steals reference */
3575 sandbox_cfg_allow_open_filename(&cfg, file_name);
3577 smartlist_free(files);
3581 smartlist_t *files = smartlist_new();
3582 smartlist_t *dirs = smartlist_new();
3583 hs_service_lists_fnames_for_sandbox(files, dirs);
3584 SMARTLIST_FOREACH(files, char *, file_name, {
3585 char *tmp_name = NULL;
3586 tor_asprintf(&tmp_name, "%s.tmp", file_name);
3587 sandbox_cfg_allow_rename(&cfg,
3588 tor_strdup(tmp_name), tor_strdup(file_name));
3589 /* steals references */
3590 sandbox_cfg_allow_open_filename(&cfg, file_name);
3591 sandbox_cfg_allow_open_filename(&cfg, tmp_name);
3593 SMARTLIST_FOREACH(dirs, char *, dir, {
3594 /* steals reference */
3595 sandbox_cfg_allow_stat_filename(&cfg, dir);
3597 smartlist_free(files);
3598 smartlist_free(dirs);
3602 char *fname;
3603 if ((fname = get_controller_cookie_file_name())) {
3604 sandbox_cfg_allow_open_filename(&cfg, fname);
3606 if ((fname = get_ext_or_auth_cookie_file_name())) {
3607 sandbox_cfg_allow_open_filename(&cfg, fname);
3611 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), port_cfg_t *, port) {
3612 if (!port->is_unix_addr)
3613 continue;
3614 /* When we open an AF_UNIX address, we want permission to open the
3615 * directory that holds it. */
3616 char *dirname = tor_strdup(port->unix_addr);
3617 if (get_parent_directory(dirname) == 0) {
3618 OPEN(dirname);
3620 tor_free(dirname);
3621 sandbox_cfg_allow_chmod_filename(&cfg, tor_strdup(port->unix_addr));
3622 sandbox_cfg_allow_chown_filename(&cfg, tor_strdup(port->unix_addr));
3623 } SMARTLIST_FOREACH_END(port);
3625 if (options->DirPortFrontPage) {
3626 sandbox_cfg_allow_open_filename(&cfg,
3627 tor_strdup(options->DirPortFrontPage));
3630 // orport
3631 if (server_mode(get_options())) {
3633 OPEN_DATADIR2_SUFFIX("keys", "secret_id_key", ".tmp");
3634 OPEN_DATADIR2_SUFFIX("keys", "secret_onion_key", ".tmp");
3635 OPEN_DATADIR2_SUFFIX("keys", "secret_onion_key_ntor", ".tmp");
3636 OPEN_DATADIR2("keys", "secret_id_key.old");
3637 OPEN_DATADIR2("keys", "secret_onion_key.old");
3638 OPEN_DATADIR2("keys", "secret_onion_key_ntor.old");
3640 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_secret_key", ".tmp");
3641 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_secret_key_encrypted",
3642 ".tmp");
3643 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_public_key", ".tmp");
3644 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_secret_key", ".tmp");
3645 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_secret_key_encrypted",
3646 ".tmp");
3647 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_public_key", ".tmp");
3648 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_cert", ".tmp");
3650 OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
3651 OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
3653 OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
3654 OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
3655 OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
3656 OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
3657 OPEN_DATADIR2_SUFFIX("stats", "hidserv-stats", ".tmp");
3659 OPEN_DATADIR("approved-routers");
3660 OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
3661 OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
3662 OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
3664 OPEN("/etc/resolv.conf");
3666 RENAME_SUFFIX("fingerprint", ".tmp");
3667 RENAME_SUFFIX2("keys", "secret_onion_key_ntor", ".tmp");
3668 RENAME_SUFFIX2("keys", "secret_id_key", ".tmp");
3669 RENAME_SUFFIX2("keys", "secret_id_key.old", ".tmp");
3670 RENAME_SUFFIX2("keys", "secret_onion_key", ".tmp");
3671 RENAME_SUFFIX2("keys", "secret_onion_key.old", ".tmp");
3672 RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
3673 RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
3674 RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
3675 RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
3676 RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
3677 RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
3678 RENAME_SUFFIX2("stats", "hidserv-stats", ".tmp");
3679 RENAME_SUFFIX("hashed-fingerprint", ".tmp");
3680 RENAME_SUFFIX("router-stability", ".tmp");
3682 RENAME_SUFFIX2("keys", "ed25519_master_id_secret_key", ".tmp");
3683 RENAME_SUFFIX2("keys", "ed25519_master_id_secret_key_encrypted", ".tmp");
3684 RENAME_SUFFIX2("keys", "ed25519_master_id_public_key", ".tmp");
3685 RENAME_SUFFIX2("keys", "ed25519_signing_secret_key", ".tmp");
3686 RENAME_SUFFIX2("keys", "ed25519_signing_cert", ".tmp");
3688 sandbox_cfg_allow_rename(&cfg,
3689 get_datadir_fname2("keys", "secret_onion_key"),
3690 get_datadir_fname2("keys", "secret_onion_key.old"));
3691 sandbox_cfg_allow_rename(&cfg,
3692 get_datadir_fname2("keys", "secret_onion_key_ntor"),
3693 get_datadir_fname2("keys", "secret_onion_key_ntor.old"));
3695 STAT_DATADIR("keys");
3696 OPEN_DATADIR("stats");
3697 STAT_DATADIR("stats");
3698 STAT_DATADIR2("stats", "dirreq-stats");
3700 consdiffmgr_register_with_sandbox(&cfg);
3703 init_addrinfo();
3705 return cfg;
3708 /** Main entry point for the Tor process. Called from main(). */
3709 /* This function is distinct from main() only so we can link main.c into
3710 * the unittest binary without conflicting with the unittests' main. */
3712 tor_main(int argc, char *argv[])
3714 int result = 0;
3716 #ifdef _WIN32
3717 #ifndef HeapEnableTerminationOnCorruption
3718 #define HeapEnableTerminationOnCorruption 1
3719 #endif
3720 /* On heap corruption, just give up; don't try to play along. */
3721 HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
3722 /* Call SetProcessDEPPolicy to permanently enable DEP.
3723 The function will not resolve on earlier versions of Windows,
3724 and failure is not dangerous. */
3725 HMODULE hMod = GetModuleHandleA("Kernel32.dll");
3726 if (hMod) {
3727 typedef BOOL (WINAPI *PSETDEP)(DWORD);
3728 PSETDEP setdeppolicy = (PSETDEP)GetProcAddress(hMod,
3729 "SetProcessDEPPolicy");
3730 if (setdeppolicy) {
3731 /* PROCESS_DEP_ENABLE | PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION */
3732 setdeppolicy(3);
3735 #endif /* defined(_WIN32) */
3737 configure_backtrace_handler(get_version());
3739 update_approx_time(time(NULL));
3740 tor_threads_init();
3741 tor_compress_init();
3742 init_logging(0);
3743 monotime_init();
3744 #ifdef USE_DMALLOC
3746 /* Instruct OpenSSL to use our internal wrappers for malloc,
3747 realloc and free. */
3748 int r = crypto_use_tor_alloc_functions();
3749 tor_assert(r == 0);
3751 #endif /* defined(USE_DMALLOC) */
3752 #ifdef NT_SERVICE
3754 int done = 0;
3755 result = nt_service_parse_options(argc, argv, &done);
3756 if (done) return result;
3758 #endif /* defined(NT_SERVICE) */
3759 if (tor_init(argc, argv)<0)
3760 return -1;
3762 if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
3763 sandbox_cfg_t* cfg = sandbox_init_filter();
3765 if (sandbox_init(cfg)) {
3766 log_err(LD_BUG,"Failed to create syscall sandbox filter");
3767 return -1;
3770 // registering libevent rng
3771 #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
3772 evutil_secure_rng_set_urandom_device_file(
3773 (char*) sandbox_intern_string("/dev/urandom"));
3774 #endif
3777 switch (get_options()->command) {
3778 case CMD_RUN_TOR:
3779 #ifdef NT_SERVICE
3780 nt_service_set_state(SERVICE_RUNNING);
3781 #endif
3782 result = do_main_loop();
3783 break;
3784 case CMD_KEYGEN:
3785 result = load_ed_keys(get_options(), time(NULL)) < 0;
3786 break;
3787 case CMD_KEY_EXPIRATION:
3788 init_keys();
3789 result = log_cert_expiration();
3790 break;
3791 case CMD_LIST_FINGERPRINT:
3792 result = do_list_fingerprint();
3793 break;
3794 case CMD_HASH_PASSWORD:
3795 do_hash_password();
3796 result = 0;
3797 break;
3798 case CMD_VERIFY_CONFIG:
3799 if (quiet_level == 0)
3800 printf("Configuration was valid\n");
3801 result = 0;
3802 break;
3803 case CMD_DUMP_CONFIG:
3804 result = do_dump_config();
3805 break;
3806 case CMD_RUN_UNITTESTS: /* only set by test.c */
3807 default:
3808 log_warn(LD_BUG,"Illegal command number %d: internal error.",
3809 get_options()->command);
3810 result = -1;
3812 tor_cleanup();
3813 return result;