minor updates on upcoming changelog
[tor.git] / src / or / main.c
blobc340e4128ba61bdd2e46bdffb03d213c0364868f
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 "entrynodes.h"
80 #include "geoip.h"
81 #include "hibernate.h"
82 #include "hs_cache.h"
83 #include "hs_circuitmap.h"
84 #include "hs_client.h"
85 #include "keypin.h"
86 #include "main.h"
87 #include "microdesc.h"
88 #include "networkstatus.h"
89 #include "nodelist.h"
90 #include "ntmain.h"
91 #include "onion.h"
92 #include "periodic.h"
93 #include "policies.h"
94 #include "protover.h"
95 #include "transports.h"
96 #include "relay.h"
97 #include "rendclient.h"
98 #include "rendcommon.h"
99 #include "rendservice.h"
100 #include "rephist.h"
101 #include "router.h"
102 #include "routerkeys.h"
103 #include "routerlist.h"
104 #include "routerparse.h"
105 #include "scheduler.h"
106 #include "shared_random.h"
107 #include "statefile.h"
108 #include "status.h"
109 #include "util_process.h"
110 #include "ext_orport.h"
111 #ifdef USE_DMALLOC
112 #include <dmalloc.h>
113 #endif
114 #include "memarea.h"
115 #include "sandbox.h"
117 #include <event2/event.h>
119 #ifdef HAVE_SYSTEMD
120 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
121 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
122 * Coverity. Here's a kludge to unconfuse it.
124 # define __INCLUDE_LEVEL__ 2
125 #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
126 #include <systemd/sd-daemon.h>
127 #endif /* defined(HAVE_SYSTEMD) */
129 void evdns_shutdown(int);
131 /********* PROTOTYPES **********/
133 static void dumpmemusage(int severity);
134 static void dumpstats(int severity); /* log stats */
135 static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
136 static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
137 static void second_elapsed_callback(periodic_timer_t *timer, void *args);
138 static int conn_close_if_marked(int i);
139 static void connection_start_reading_from_linked_conn(connection_t *conn);
140 static int connection_should_read_from_linked_conn(connection_t *conn);
141 static int run_main_loop_until_done(void);
142 static void process_signal(int sig);
144 /********* START VARIABLES **********/
145 int global_read_bucket; /**< Max number of bytes I can read this second. */
146 int global_write_bucket; /**< Max number of bytes I can write this second. */
148 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
149 int global_relayed_read_bucket;
150 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
151 int global_relayed_write_bucket;
152 /** What was the read bucket before the last second_elapsed_callback() call?
153 * (used to determine how many bytes we've read). */
154 static int stats_prev_global_read_bucket;
155 /** What was the write bucket before the last second_elapsed_callback() call?
156 * (used to determine how many bytes we've written). */
157 static int stats_prev_global_write_bucket;
159 /* DOCDOC stats_prev_n_read */
160 static uint64_t stats_prev_n_read = 0;
161 /* DOCDOC stats_prev_n_written */
162 static uint64_t stats_prev_n_written = 0;
164 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
165 /** How many bytes have we read since we started the process? */
166 static uint64_t stats_n_bytes_read = 0;
167 /** How many bytes have we written since we started the process? */
168 static uint64_t stats_n_bytes_written = 0;
169 /** What time did this process start up? */
170 time_t time_of_process_start = 0;
171 /** How many seconds have we been running? */
172 long stats_n_seconds_working = 0;
174 /** How often will we honor SIGNEWNYM requests? */
175 #define MAX_SIGNEWNYM_RATE 10
176 /** When did we last process a SIGNEWNYM request? */
177 static time_t time_of_last_signewnym = 0;
178 /** Is there a signewnym request we're currently waiting to handle? */
179 static int signewnym_is_pending = 0;
180 /** How many times have we called newnym? */
181 static unsigned newnym_epoch = 0;
183 /** Smartlist of all open connections. */
184 STATIC smartlist_t *connection_array = NULL;
185 /** List of connections that have been marked for close and need to be freed
186 * and removed from connection_array. */
187 static smartlist_t *closeable_connection_lst = NULL;
188 /** List of linked connections that are currently reading data into their
189 * inbuf from their partner's outbuf. */
190 static smartlist_t *active_linked_connection_lst = NULL;
191 /** Flag: Set to true iff we entered the current libevent main loop via
192 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
193 * to handle linked connections. */
194 static int called_loop_once = 0;
196 /** We set this to 1 when we've opened a circuit, so we can print a log
197 * entry to inform the user that Tor is working. We set it to 0 when
198 * we think the fact that we once opened a circuit doesn't mean we can do so
199 * any longer (a big time jump happened, when we notice our directory is
200 * heinously out-of-date, etc.
202 static int can_complete_circuits = 0;
204 /** How often do we check for router descriptors that we should download
205 * when we have too little directory info? */
206 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
207 /** How often do we check for router descriptors that we should download
208 * when we have enough directory info? */
209 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
211 /** Decides our behavior when no logs are configured/before any
212 * logs have been configured. For 0, we log notice to stdout as normal.
213 * For 1, we log warnings only. For 2, we log nothing.
215 int quiet_level = 0;
217 /********* END VARIABLES ************/
219 /****************************************************************************
221 * This section contains accessors and other methods on the connection_array
222 * variables (which are global within this file and unavailable outside it).
224 ****************************************************************************/
226 /** Return 1 if we have successfully built a circuit, and nothing has changed
227 * to make us think that maybe we can't.
230 have_completed_a_circuit(void)
232 return can_complete_circuits;
235 /** Note that we have successfully built a circuit, so that reachability
236 * testing and introduction points and so on may be attempted. */
237 void
238 note_that_we_completed_a_circuit(void)
240 can_complete_circuits = 1;
243 /** Note that something has happened (like a clock jump, or DisableNetwork) to
244 * make us think that maybe we can't complete circuits. */
245 void
246 note_that_we_maybe_cant_complete_circuits(void)
248 can_complete_circuits = 0;
251 /** Add <b>conn</b> to the array of connections that we can poll on. The
252 * connection's socket must be set; the connection starts out
253 * non-reading and non-writing.
256 connection_add_impl(connection_t *conn, int is_connecting)
258 tor_assert(conn);
259 tor_assert(SOCKET_OK(conn->s) ||
260 conn->linked ||
261 (conn->type == CONN_TYPE_AP &&
262 TO_EDGE_CONN(conn)->is_dns_request));
264 tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
265 conn->conn_array_index = smartlist_len(connection_array);
266 smartlist_add(connection_array, conn);
268 (void) is_connecting;
270 if (SOCKET_OK(conn->s) || conn->linked) {
271 conn->read_event = tor_event_new(tor_libevent_get_base(),
272 conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
273 conn->write_event = tor_event_new(tor_libevent_get_base(),
274 conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
275 /* XXXX CHECK FOR NULL RETURN! */
278 log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
279 conn_type_to_string(conn->type), (int)conn->s, conn->address,
280 smartlist_len(connection_array));
282 return 0;
285 /** Tell libevent that we don't care about <b>conn</b> any more. */
286 void
287 connection_unregister_events(connection_t *conn)
289 if (conn->read_event) {
290 if (event_del(conn->read_event))
291 log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
292 tor_free(conn->read_event);
294 if (conn->write_event) {
295 if (event_del(conn->write_event))
296 log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
297 tor_free(conn->write_event);
299 if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
300 dnsserv_close_listener(conn);
304 /** Remove the connection from the global list, and remove the
305 * corresponding poll entry. Calling this function will shift the last
306 * connection (if any) into the position occupied by conn.
309 connection_remove(connection_t *conn)
311 int current_index;
312 connection_t *tmp;
314 tor_assert(conn);
316 log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
317 (int)conn->s, conn_type_to_string(conn->type),
318 smartlist_len(connection_array));
320 if (conn->type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
321 log_info(LD_NET, "Closing SOCKS SocksSocket connection");
324 control_event_conn_bandwidth(conn);
326 tor_assert(conn->conn_array_index >= 0);
327 current_index = conn->conn_array_index;
328 connection_unregister_events(conn); /* This is redundant, but cheap. */
329 if (current_index == smartlist_len(connection_array)-1) { /* at the end */
330 smartlist_del(connection_array, current_index);
331 return 0;
334 /* replace this one with the one at the end */
335 smartlist_del(connection_array, current_index);
336 tmp = smartlist_get(connection_array, current_index);
337 tmp->conn_array_index = current_index;
339 return 0;
342 /** If <b>conn</b> is an edge conn, remove it from the list
343 * of conn's on this circuit. If it's not on an edge,
344 * flush and send destroys for all circuits on this conn.
346 * Remove it from connection_array (if applicable) and
347 * from closeable_connection_list.
349 * Then free it.
351 static void
352 connection_unlink(connection_t *conn)
354 connection_about_to_close_connection(conn);
355 if (conn->conn_array_index >= 0) {
356 connection_remove(conn);
358 if (conn->linked_conn) {
359 conn->linked_conn->linked_conn = NULL;
360 if (! conn->linked_conn->marked_for_close &&
361 conn->linked_conn->reading_from_linked_conn)
362 connection_start_reading(conn->linked_conn);
363 conn->linked_conn = NULL;
365 smartlist_remove(closeable_connection_lst, conn);
366 smartlist_remove(active_linked_connection_lst, conn);
367 if (conn->type == CONN_TYPE_EXIT) {
368 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
370 if (conn->type == CONN_TYPE_OR) {
371 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
372 connection_or_clear_identity(TO_OR_CONN(conn));
373 /* connection_unlink() can only get called if the connection
374 * was already on the closeable list, and it got there by
375 * connection_mark_for_close(), which was called from
376 * connection_or_close_normally() or
377 * connection_or_close_for_error(), so the channel should
378 * already be in CHANNEL_STATE_CLOSING, and then the
379 * connection_about_to_close_connection() goes to
380 * connection_or_about_to_close(), which calls channel_closed()
381 * to notify the channel_t layer, and closed the channel, so
382 * nothing more to do here to deal with the channel associated
383 * with an orconn.
386 connection_free(conn);
389 /** Initialize the global connection list, closeable connection list,
390 * and active connection list. */
391 STATIC void
392 init_connection_lists(void)
394 if (!connection_array)
395 connection_array = smartlist_new();
396 if (!closeable_connection_lst)
397 closeable_connection_lst = smartlist_new();
398 if (!active_linked_connection_lst)
399 active_linked_connection_lst = smartlist_new();
402 /** Schedule <b>conn</b> to be closed. **/
403 void
404 add_connection_to_closeable_list(connection_t *conn)
406 tor_assert(!smartlist_contains(closeable_connection_lst, conn));
407 tor_assert(conn->marked_for_close);
408 assert_connection_ok(conn, time(NULL));
409 smartlist_add(closeable_connection_lst, conn);
412 /** Return 1 if conn is on the closeable list, else return 0. */
414 connection_is_on_closeable_list(connection_t *conn)
416 return smartlist_contains(closeable_connection_lst, conn);
419 /** Return true iff conn is in the current poll array. */
421 connection_in_array(connection_t *conn)
423 return smartlist_contains(connection_array, conn);
426 /** Set <b>*array</b> to an array of all connections. <b>*array</b> must not
427 * be modified.
429 MOCK_IMPL(smartlist_t *,
430 get_connection_array, (void))
432 if (!connection_array)
433 connection_array = smartlist_new();
434 return connection_array;
437 /** Provides the traffic read and written over the life of the process. */
439 MOCK_IMPL(uint64_t,
440 get_bytes_read,(void))
442 return stats_n_bytes_read;
445 /* DOCDOC get_bytes_written */
446 MOCK_IMPL(uint64_t,
447 get_bytes_written,(void))
449 return stats_n_bytes_written;
452 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
453 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
455 void
456 connection_watch_events(connection_t *conn, watchable_events_t events)
458 if (events & READ_EVENT)
459 connection_start_reading(conn);
460 else
461 connection_stop_reading(conn);
463 if (events & WRITE_EVENT)
464 connection_start_writing(conn);
465 else
466 connection_stop_writing(conn);
469 /** Return true iff <b>conn</b> is listening for read events. */
471 connection_is_reading(connection_t *conn)
473 tor_assert(conn);
475 return conn->reading_from_linked_conn ||
476 (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
479 /** Check whether <b>conn</b> is correct in having (or not having) a
480 * read/write event (passed in <b>ev</b>). On success, return 0. On failure,
481 * log a warning and return -1. */
482 static int
483 connection_check_event(connection_t *conn, struct event *ev)
485 int bad;
487 if (conn->type == CONN_TYPE_AP && TO_EDGE_CONN(conn)->is_dns_request) {
488 /* DNS requests which we launch through the dnsserv.c module do not have
489 * any underlying socket or any underlying linked connection, so they
490 * shouldn't have any attached events either.
492 bad = ev != NULL;
493 } else {
494 /* Everything else should have an underlying socket, or a linked
495 * connection (which is also tracked with a read_event/write_event pair).
497 bad = ev == NULL;
500 if (bad) {
501 log_warn(LD_BUG, "Event missing on connection %p [%s;%s]. "
502 "socket=%d. linked=%d. "
503 "is_dns_request=%d. Marked_for_close=%s:%d",
504 conn,
505 conn_type_to_string(conn->type),
506 conn_state_to_string(conn->type, conn->state),
507 (int)conn->s, (int)conn->linked,
508 (conn->type == CONN_TYPE_AP &&
509 TO_EDGE_CONN(conn)->is_dns_request),
510 conn->marked_for_close_file ? conn->marked_for_close_file : "-",
511 conn->marked_for_close
513 log_backtrace(LOG_WARN, LD_BUG, "Backtrace attached.");
514 return -1;
516 return 0;
519 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
520 MOCK_IMPL(void,
521 connection_stop_reading,(connection_t *conn))
523 tor_assert(conn);
525 if (connection_check_event(conn, conn->read_event) < 0) {
526 return;
529 if (conn->linked) {
530 conn->reading_from_linked_conn = 0;
531 connection_stop_reading_from_linked_conn(conn);
532 } else {
533 if (event_del(conn->read_event))
534 log_warn(LD_NET, "Error from libevent setting read event state for %d "
535 "to unwatched: %s",
536 (int)conn->s,
537 tor_socket_strerror(tor_socket_errno(conn->s)));
541 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
542 MOCK_IMPL(void,
543 connection_start_reading,(connection_t *conn))
545 tor_assert(conn);
547 if (connection_check_event(conn, conn->read_event) < 0) {
548 return;
551 if (conn->linked) {
552 conn->reading_from_linked_conn = 1;
553 if (connection_should_read_from_linked_conn(conn))
554 connection_start_reading_from_linked_conn(conn);
555 } else {
556 if (event_add(conn->read_event, NULL))
557 log_warn(LD_NET, "Error from libevent setting read event state for %d "
558 "to watched: %s",
559 (int)conn->s,
560 tor_socket_strerror(tor_socket_errno(conn->s)));
564 /** Return true iff <b>conn</b> is listening for write events. */
566 connection_is_writing(connection_t *conn)
568 tor_assert(conn);
570 return conn->writing_to_linked_conn ||
571 (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
574 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
575 MOCK_IMPL(void,
576 connection_stop_writing,(connection_t *conn))
578 tor_assert(conn);
580 if (connection_check_event(conn, conn->write_event) < 0) {
581 return;
584 if (conn->linked) {
585 conn->writing_to_linked_conn = 0;
586 if (conn->linked_conn)
587 connection_stop_reading_from_linked_conn(conn->linked_conn);
588 } else {
589 if (event_del(conn->write_event))
590 log_warn(LD_NET, "Error from libevent setting write event state for %d "
591 "to unwatched: %s",
592 (int)conn->s,
593 tor_socket_strerror(tor_socket_errno(conn->s)));
597 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
598 MOCK_IMPL(void,
599 connection_start_writing,(connection_t *conn))
601 tor_assert(conn);
603 if (connection_check_event(conn, conn->write_event) < 0) {
604 return;
607 if (conn->linked) {
608 conn->writing_to_linked_conn = 1;
609 if (conn->linked_conn &&
610 connection_should_read_from_linked_conn(conn->linked_conn))
611 connection_start_reading_from_linked_conn(conn->linked_conn);
612 } else {
613 if (event_add(conn->write_event, NULL))
614 log_warn(LD_NET, "Error from libevent setting write event state for %d "
615 "to watched: %s",
616 (int)conn->s,
617 tor_socket_strerror(tor_socket_errno(conn->s)));
621 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
622 * linked to it would be good and feasible. (Reading is "feasible" if the
623 * other conn exists and has data in its outbuf, and is "good" if we have our
624 * reading_from_linked_conn flag set and the other conn has its
625 * writing_to_linked_conn flag set.)*/
626 static int
627 connection_should_read_from_linked_conn(connection_t *conn)
629 if (conn->linked && conn->reading_from_linked_conn) {
630 if (! conn->linked_conn ||
631 (conn->linked_conn->writing_to_linked_conn &&
632 buf_datalen(conn->linked_conn->outbuf)))
633 return 1;
635 return 0;
638 /** If we called event_base_loop() and told it to never stop until it
639 * runs out of events, now we've changed our mind: tell it we want it to
640 * finish. */
641 void
642 tell_event_loop_to_finish(void)
644 if (!called_loop_once) {
645 struct timeval tv = { 0, 0 };
646 tor_event_base_loopexit(tor_libevent_get_base(), &tv);
647 called_loop_once = 1; /* hack to avoid adding more exit events */
651 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
652 * its linked connection, if it is not doing so already. Called by
653 * connection_start_reading and connection_start_writing as appropriate. */
654 static void
655 connection_start_reading_from_linked_conn(connection_t *conn)
657 tor_assert(conn);
658 tor_assert(conn->linked == 1);
660 if (!conn->active_on_link) {
661 conn->active_on_link = 1;
662 smartlist_add(active_linked_connection_lst, conn);
663 /* make sure that the event_base_loop() function exits at
664 * the end of its run through the current connections, so we can
665 * activate read events for linked connections. */
666 tell_event_loop_to_finish();
667 } else {
668 tor_assert(smartlist_contains(active_linked_connection_lst, conn));
672 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
673 * connection, if is currently doing so. Called by connection_stop_reading,
674 * connection_stop_writing, and connection_read. */
675 void
676 connection_stop_reading_from_linked_conn(connection_t *conn)
678 tor_assert(conn);
679 tor_assert(conn->linked == 1);
681 if (conn->active_on_link) {
682 conn->active_on_link = 0;
683 /* FFFF We could keep an index here so we can smartlist_del
684 * cleanly. On the other hand, this doesn't show up on profiles,
685 * so let's leave it alone for now. */
686 smartlist_remove(active_linked_connection_lst, conn);
687 } else {
688 tor_assert(!smartlist_contains(active_linked_connection_lst, conn));
692 /** Close all connections that have been scheduled to get closed. */
693 STATIC void
694 close_closeable_connections(void)
696 int i;
697 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
698 connection_t *conn = smartlist_get(closeable_connection_lst, i);
699 if (conn->conn_array_index < 0) {
700 connection_unlink(conn); /* blow it away right now */
701 } else {
702 if (!conn_close_if_marked(conn->conn_array_index))
703 ++i;
708 /** Count moribund connections for the OOS handler */
709 MOCK_IMPL(int,
710 connection_count_moribund, (void))
712 int moribund = 0;
715 * Count things we'll try to kill when close_closeable_connections()
716 * runs next.
718 SMARTLIST_FOREACH_BEGIN(closeable_connection_lst, connection_t *, conn) {
719 if (SOCKET_OK(conn->s) && connection_is_moribund(conn)) ++moribund;
720 } SMARTLIST_FOREACH_END(conn);
722 return moribund;
725 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
726 * some data to read. */
727 static void
728 conn_read_callback(evutil_socket_t fd, short event, void *_conn)
730 connection_t *conn = _conn;
731 (void)fd;
732 (void)event;
734 log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
736 /* assert_connection_ok(conn, time(NULL)); */
738 if (connection_handle_read(conn) < 0) {
739 if (!conn->marked_for_close) {
740 #ifndef _WIN32
741 log_warn(LD_BUG,"Unhandled error on read for %s connection "
742 "(fd %d); removing",
743 conn_type_to_string(conn->type), (int)conn->s);
744 tor_fragile_assert();
745 #endif /* !defined(_WIN32) */
746 if (CONN_IS_EDGE(conn))
747 connection_edge_end_errno(TO_EDGE_CONN(conn));
748 connection_mark_for_close(conn);
751 assert_connection_ok(conn, time(NULL));
753 if (smartlist_len(closeable_connection_lst))
754 close_closeable_connections();
757 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
758 * some data to write. */
759 static void
760 conn_write_callback(evutil_socket_t fd, short events, void *_conn)
762 connection_t *conn = _conn;
763 (void)fd;
764 (void)events;
766 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
767 (int)conn->s));
769 /* assert_connection_ok(conn, time(NULL)); */
771 if (connection_handle_write(conn, 0) < 0) {
772 if (!conn->marked_for_close) {
773 /* this connection is broken. remove it. */
774 log_fn(LOG_WARN,LD_BUG,
775 "unhandled error on write for %s connection (fd %d); removing",
776 conn_type_to_string(conn->type), (int)conn->s);
777 tor_fragile_assert();
778 if (CONN_IS_EDGE(conn)) {
779 /* otherwise we cry wolf about duplicate close */
780 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
781 if (!edge_conn->end_reason)
782 edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
783 edge_conn->edge_has_sent_end = 1;
785 connection_close_immediate(conn); /* So we don't try to flush. */
786 connection_mark_for_close(conn);
789 assert_connection_ok(conn, time(NULL));
791 if (smartlist_len(closeable_connection_lst))
792 close_closeable_connections();
795 /** If the connection at connection_array[i] is marked for close, then:
796 * - If it has data that it wants to flush, try to flush it.
797 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
798 * true, then leave the connection open and return.
799 * - Otherwise, remove the connection from connection_array and from
800 * all other lists, close it, and free it.
801 * Returns 1 if the connection was closed, 0 otherwise.
803 static int
804 conn_close_if_marked(int i)
806 connection_t *conn;
807 int retval;
808 time_t now;
810 conn = smartlist_get(connection_array, i);
811 if (!conn->marked_for_close)
812 return 0; /* nothing to see here, move along */
813 now = time(NULL);
814 assert_connection_ok(conn, now);
815 /* assert_all_pending_dns_resolves_ok(); */
817 log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
818 conn->s);
820 /* If the connection we are about to close was trying to connect to
821 a proxy server and failed, the client won't be able to use that
822 proxy. We should warn the user about this. */
823 if (conn->proxy_state == PROXY_INFANT)
824 log_failed_proxy_connection(conn);
826 if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
827 connection_wants_to_flush(conn)) {
828 /* s == -1 means it's an incomplete edge connection, or that the socket
829 * has already been closed as unflushable. */
830 ssize_t sz = connection_bucket_write_limit(conn, now);
831 if (!conn->hold_open_until_flushed)
832 log_info(LD_NET,
833 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
834 "to flush %d bytes. (Marked at %s:%d)",
835 escaped_safe_str_client(conn->address),
836 (int)conn->s, conn_type_to_string(conn->type), conn->state,
837 (int)conn->outbuf_flushlen,
838 conn->marked_for_close_file, conn->marked_for_close);
839 if (conn->linked_conn) {
840 retval = buf_move_to_buf(conn->linked_conn->inbuf, conn->outbuf,
841 &conn->outbuf_flushlen);
842 if (retval >= 0) {
843 /* The linked conn will notice that it has data when it notices that
844 * we're gone. */
845 connection_start_reading_from_linked_conn(conn->linked_conn);
847 log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
848 "%d left; flushlen %d; wants-to-flush==%d", retval,
849 (int)connection_get_outbuf_len(conn),
850 (int)conn->outbuf_flushlen,
851 connection_wants_to_flush(conn));
852 } else if (connection_speaks_cells(conn)) {
853 if (conn->state == OR_CONN_STATE_OPEN) {
854 retval = buf_flush_to_tls(conn->outbuf, TO_OR_CONN(conn)->tls, sz,
855 &conn->outbuf_flushlen);
856 } else
857 retval = -1; /* never flush non-open broken tls connections */
858 } else {
859 retval = buf_flush_to_socket(conn->outbuf, conn->s, sz,
860 &conn->outbuf_flushlen);
862 if (retval >= 0 && /* Technically, we could survive things like
863 TLS_WANT_WRITE here. But don't bother for now. */
864 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
865 if (retval > 0) {
866 LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
867 "Holding conn (fd %d) open for more flushing.",
868 (int)conn->s));
869 conn->timestamp_lastwritten = now; /* reset so we can flush more */
870 } else if (sz == 0) {
871 /* Also, retval==0. If we get here, we didn't want to write anything
872 * (because of rate-limiting) and we didn't. */
874 /* Connection must flush before closing, but it's being rate-limited.
875 * Let's remove from Libevent, and mark it as blocked on bandwidth
876 * so it will be re-added on next token bucket refill. Prevents
877 * busy Libevent loops where we keep ending up here and returning
878 * 0 until we are no longer blocked on bandwidth.
880 if (connection_is_writing(conn)) {
881 conn->write_blocked_on_bw = 1;
882 connection_stop_writing(conn);
884 if (connection_is_reading(conn)) {
885 /* XXXX+ We should make this code unreachable; if a connection is
886 * marked for close and flushing, there is no point in reading to it
887 * at all. Further, checking at this point is a bit of a hack: it
888 * would make much more sense to react in
889 * connection_handle_read_impl, or to just stop reading in
890 * mark_and_flush */
891 conn->read_blocked_on_bw = 1;
892 connection_stop_reading(conn);
895 return 0;
897 if (connection_wants_to_flush(conn)) {
898 log_fn(LOG_INFO, LD_NET, "We stalled too much while trying to write %d "
899 "bytes to address %s. If this happens a lot, either "
900 "something is wrong with your network connection, or "
901 "something is wrong with theirs. "
902 "(fd %d, type %s, state %d, marked at %s:%d).",
903 (int)connection_get_outbuf_len(conn),
904 escaped_safe_str_client(conn->address),
905 (int)conn->s, conn_type_to_string(conn->type), conn->state,
906 conn->marked_for_close_file,
907 conn->marked_for_close);
911 connection_unlink(conn); /* unlink, remove, free */
912 return 1;
915 /** Implementation for directory_all_unreachable. This is done in a callback,
916 * since otherwise it would complicate Tor's control-flow graph beyond all
917 * reason.
919 static void
920 directory_all_unreachable_cb(evutil_socket_t fd, short event, void *arg)
922 (void)fd;
923 (void)event;
924 (void)arg;
926 connection_t *conn;
928 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
929 AP_CONN_STATE_CIRCUIT_WAIT))) {
930 entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
931 log_notice(LD_NET,
932 "Is your network connection down? "
933 "Failing connection to '%s:%d'.",
934 safe_str_client(entry_conn->socks_request->address),
935 entry_conn->socks_request->port);
936 connection_mark_unattached_ap(entry_conn,
937 END_STREAM_REASON_NET_UNREACHABLE);
939 control_event_general_error("DIR_ALL_UNREACHABLE");
942 static struct event *directory_all_unreachable_cb_event = NULL;
944 /** We've just tried every dirserver we know about, and none of
945 * them were reachable. Assume the network is down. Change state
946 * so next time an application connection arrives we'll delay it
947 * and try another directory fetch. Kill off all the circuit_wait
948 * streams that are waiting now, since they will all timeout anyway.
950 void
951 directory_all_unreachable(time_t now)
953 (void)now;
955 stats_n_seconds_working=0; /* reset it */
957 if (!directory_all_unreachable_cb_event) {
958 directory_all_unreachable_cb_event =
959 tor_event_new(tor_libevent_get_base(),
960 -1, EV_READ, directory_all_unreachable_cb, NULL);
961 tor_assert(directory_all_unreachable_cb_event);
964 event_active(directory_all_unreachable_cb_event, EV_READ, 1);
967 /** This function is called whenever we successfully pull down some new
968 * network statuses or server descriptors. */
969 void
970 directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
972 const or_options_t *options = get_options();
974 /* if we have enough dir info, then update our guard status with
975 * whatever we just learned. */
976 int invalidate_circs = guards_update_all();
978 if (invalidate_circs) {
979 circuit_mark_all_unused_circs();
980 circuit_mark_all_dirty_circs_as_unusable();
983 if (!router_have_minimum_dir_info()) {
984 int quiet = suppress_logs || from_cache ||
985 directory_too_idle_to_fetch_descriptors(options, now);
986 tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
987 "I learned some more directory information, but not enough to "
988 "build a circuit: %s", get_dir_info_status_string());
989 update_all_descriptor_downloads(now);
990 return;
991 } else {
992 if (directory_fetches_from_authorities(options)) {
993 update_all_descriptor_downloads(now);
996 /* Don't even bother trying to get extrainfo until the rest of our
997 * directory info is up-to-date */
998 if (options->DownloadExtraInfo)
999 update_extrainfo_downloads(now);
1002 if (server_mode(options) && !net_is_disabled() && !from_cache &&
1003 (have_completed_a_circuit() || !any_predicted_circuits(now)))
1004 consider_testing_reachability(1, 1);
1007 /** Perform regular maintenance tasks for a single connection. This
1008 * function gets run once per second per connection by run_scheduled_events.
1010 static void
1011 run_connection_housekeeping(int i, time_t now)
1013 cell_t cell;
1014 connection_t *conn = smartlist_get(connection_array, i);
1015 const or_options_t *options = get_options();
1016 or_connection_t *or_conn;
1017 channel_t *chan = NULL;
1018 int have_any_circuits;
1019 int past_keepalive =
1020 now >= conn->timestamp_lastwritten + options->KeepalivePeriod;
1022 if (conn->outbuf && !connection_get_outbuf_len(conn) &&
1023 conn->type == CONN_TYPE_OR)
1024 TO_OR_CONN(conn)->timestamp_lastempty = now;
1026 if (conn->marked_for_close) {
1027 /* nothing to do here */
1028 return;
1031 /* Expire any directory connections that haven't been active (sent
1032 * if a server or received if a client) for 5 min */
1033 if (conn->type == CONN_TYPE_DIR &&
1034 ((DIR_CONN_IS_SERVER(conn) &&
1035 conn->timestamp_lastwritten
1036 + options->TestingDirConnectionMaxStall < now) ||
1037 (!DIR_CONN_IS_SERVER(conn) &&
1038 conn->timestamp_lastread
1039 + options->TestingDirConnectionMaxStall < now))) {
1040 log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
1041 (int)conn->s, conn->purpose);
1042 /* This check is temporary; it's to let us know whether we should consider
1043 * parsing partial serverdesc responses. */
1044 if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
1045 connection_get_inbuf_len(conn) >= 1024) {
1046 log_info(LD_DIR,"Trying to extract information from wedged server desc "
1047 "download.");
1048 connection_dir_reached_eof(TO_DIR_CONN(conn));
1049 } else {
1050 connection_mark_for_close(conn);
1052 return;
1055 if (!connection_speaks_cells(conn))
1056 return; /* we're all done here, the rest is just for OR conns */
1058 /* If we haven't written to an OR connection for a while, then either nuke
1059 the connection or send a keepalive, depending. */
1061 or_conn = TO_OR_CONN(conn);
1062 tor_assert(conn->outbuf);
1064 chan = TLS_CHAN_TO_BASE(or_conn->chan);
1065 tor_assert(chan);
1067 if (channel_num_circuits(chan) != 0) {
1068 have_any_circuits = 1;
1069 chan->timestamp_last_had_circuits = now;
1070 } else {
1071 have_any_circuits = 0;
1074 if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan)) &&
1075 ! have_any_circuits) {
1076 /* It's bad for new circuits, and has no unmarked circuits on it:
1077 * mark it now. */
1078 log_info(LD_OR,
1079 "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1080 (int)conn->s, conn->address, conn->port);
1081 if (conn->state == OR_CONN_STATE_CONNECTING)
1082 connection_or_connect_failed(TO_OR_CONN(conn),
1083 END_OR_CONN_REASON_TIMEOUT,
1084 "Tor gave up on the connection");
1085 connection_or_close_normally(TO_OR_CONN(conn), 1);
1086 } else if (!connection_state_is_open(conn)) {
1087 if (past_keepalive) {
1088 /* We never managed to actually get this connection open and happy. */
1089 log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
1090 (int)conn->s,conn->address, conn->port);
1091 connection_or_close_normally(TO_OR_CONN(conn), 0);
1093 } else if (we_are_hibernating() &&
1094 ! have_any_circuits &&
1095 !connection_get_outbuf_len(conn)) {
1096 /* We're hibernating, there's no circuits, and nothing to flush.*/
1097 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
1098 "[Hibernating or exiting].",
1099 (int)conn->s,conn->address, conn->port);
1100 connection_or_close_normally(TO_OR_CONN(conn), 1);
1101 } else if (!have_any_circuits &&
1102 now - or_conn->idle_timeout >=
1103 chan->timestamp_last_had_circuits) {
1104 log_info(LD_OR,"Expiring non-used OR connection "U64_FORMAT" to fd %d "
1105 "(%s:%d) [no circuits for %d; timeout %d; %scanonical].",
1106 U64_PRINTF_ARG(chan->global_identifier),
1107 (int)conn->s, conn->address, conn->port,
1108 (int)(now - chan->timestamp_last_had_circuits),
1109 or_conn->idle_timeout,
1110 or_conn->is_canonical ? "" : "non");
1111 connection_or_close_normally(TO_OR_CONN(conn), 0);
1112 } else if (
1113 now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
1114 now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
1115 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
1116 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1117 "flush; %d seconds since last write)",
1118 (int)conn->s, conn->address, conn->port,
1119 (int)connection_get_outbuf_len(conn),
1120 (int)(now-conn->timestamp_lastwritten));
1121 connection_or_close_normally(TO_OR_CONN(conn), 0);
1122 } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
1123 /* send a padding cell */
1124 log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
1125 conn->address, conn->port);
1126 memset(&cell,0,sizeof(cell_t));
1127 cell.command = CELL_PADDING;
1128 connection_or_write_cell_to_buf(&cell, or_conn);
1129 } else {
1130 channelpadding_decide_to_pad_channel(chan);
1134 /** Honor a NEWNYM request: make future requests unlinkable to past
1135 * requests. */
1136 static void
1137 signewnym_impl(time_t now)
1139 const or_options_t *options = get_options();
1140 if (!proxy_mode(options)) {
1141 log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
1142 "is disabled.");
1143 return;
1146 circuit_mark_all_dirty_circs_as_unusable();
1147 addressmap_clear_transient();
1148 hs_client_purge_state();
1149 time_of_last_signewnym = now;
1150 signewnym_is_pending = 0;
1152 ++newnym_epoch;
1154 control_event_signal(SIGNEWNYM);
1157 /** Return the number of times that signewnym has been called. */
1158 unsigned
1159 get_signewnym_epoch(void)
1161 return newnym_epoch;
1164 /** True iff we have initialized all the members of <b>periodic_events</b>.
1165 * Used to prevent double-initialization. */
1166 static int periodic_events_initialized = 0;
1168 /* Declare all the timer callback functions... */
1169 #undef CALLBACK
1170 #define CALLBACK(name) \
1171 static int name ## _callback(time_t, const or_options_t *)
1172 CALLBACK(rotate_onion_key);
1173 CALLBACK(check_onion_keys_expiry_time);
1174 CALLBACK(check_ed_keys);
1175 CALLBACK(launch_descriptor_fetches);
1176 CALLBACK(rotate_x509_certificate);
1177 CALLBACK(add_entropy);
1178 CALLBACK(launch_reachability_tests);
1179 CALLBACK(downrate_stability);
1180 CALLBACK(save_stability);
1181 CALLBACK(check_authority_cert);
1182 CALLBACK(check_expired_networkstatus);
1183 CALLBACK(write_stats_file);
1184 CALLBACK(record_bridge_stats);
1185 CALLBACK(clean_caches);
1186 CALLBACK(rend_cache_failure_clean);
1187 CALLBACK(retry_dns);
1188 CALLBACK(check_descriptor);
1189 CALLBACK(check_for_reachability_bw);
1190 CALLBACK(fetch_networkstatus);
1191 CALLBACK(retry_listeners);
1192 CALLBACK(expire_old_ciruits_serverside);
1193 CALLBACK(check_dns_honesty);
1194 CALLBACK(write_bridge_ns);
1195 CALLBACK(check_fw_helper_app);
1196 CALLBACK(heartbeat);
1197 CALLBACK(clean_consdiffmgr);
1198 CALLBACK(reset_padding_counts);
1199 CALLBACK(check_canonical_channels);
1200 CALLBACK(hs_service);
1202 #undef CALLBACK
1204 /* Now we declare an array of periodic_event_item_t for each periodic event */
1205 #define CALLBACK(name) PERIODIC_EVENT(name)
1207 static periodic_event_item_t periodic_events[] = {
1208 CALLBACK(rotate_onion_key),
1209 CALLBACK(check_onion_keys_expiry_time),
1210 CALLBACK(check_ed_keys),
1211 CALLBACK(launch_descriptor_fetches),
1212 CALLBACK(rotate_x509_certificate),
1213 CALLBACK(add_entropy),
1214 CALLBACK(launch_reachability_tests),
1215 CALLBACK(downrate_stability),
1216 CALLBACK(save_stability),
1217 CALLBACK(check_authority_cert),
1218 CALLBACK(check_expired_networkstatus),
1219 CALLBACK(write_stats_file),
1220 CALLBACK(record_bridge_stats),
1221 CALLBACK(clean_caches),
1222 CALLBACK(rend_cache_failure_clean),
1223 CALLBACK(retry_dns),
1224 CALLBACK(check_descriptor),
1225 CALLBACK(check_for_reachability_bw),
1226 CALLBACK(fetch_networkstatus),
1227 CALLBACK(retry_listeners),
1228 CALLBACK(expire_old_ciruits_serverside),
1229 CALLBACK(check_dns_honesty),
1230 CALLBACK(write_bridge_ns),
1231 CALLBACK(check_fw_helper_app),
1232 CALLBACK(heartbeat),
1233 CALLBACK(clean_consdiffmgr),
1234 CALLBACK(reset_padding_counts),
1235 CALLBACK(check_canonical_channels),
1236 CALLBACK(hs_service),
1237 END_OF_PERIODIC_EVENTS
1239 #undef CALLBACK
1241 /* These are pointers to members of periodic_events[] that are used to
1242 * implement particular callbacks. We keep them separate here so that we
1243 * can access them by name. We also keep them inside periodic_events[]
1244 * so that we can implement "reset all timers" in a reasonable way. */
1245 static periodic_event_item_t *check_descriptor_event=NULL;
1246 static periodic_event_item_t *fetch_networkstatus_event=NULL;
1247 static periodic_event_item_t *launch_descriptor_fetches_event=NULL;
1248 static periodic_event_item_t *check_dns_honesty_event=NULL;
1250 /** Reset all the periodic events so we'll do all our actions again as if we
1251 * just started up.
1252 * Useful if our clock just moved back a long time from the future,
1253 * so we don't wait until that future arrives again before acting.
1255 void
1256 reset_all_main_loop_timers(void)
1258 int i;
1259 for (i = 0; periodic_events[i].name; ++i) {
1260 periodic_event_reschedule(&periodic_events[i]);
1264 /** Return the member of periodic_events[] whose name is <b>name</b>.
1265 * Return NULL if no such event is found.
1267 static periodic_event_item_t *
1268 find_periodic_event(const char *name)
1270 int i;
1271 for (i = 0; periodic_events[i].name; ++i) {
1272 if (strcmp(name, periodic_events[i].name) == 0)
1273 return &periodic_events[i];
1275 return NULL;
1278 /** Helper, run one second after setup:
1279 * Initializes all members of periodic_events and starts them running.
1281 * (We do this one second after setup for backward-compatibility reasons;
1282 * it might not actually be necessary.) */
1283 static void
1284 initialize_periodic_events_cb(evutil_socket_t fd, short events, void *data)
1286 (void) fd;
1287 (void) events;
1288 (void) data;
1289 int i;
1290 for (i = 0; periodic_events[i].name; ++i) {
1291 periodic_event_launch(&periodic_events[i]);
1295 /** Set up all the members of periodic_events[], and configure them all to be
1296 * launched from a callback. */
1297 STATIC void
1298 initialize_periodic_events(void)
1300 tor_assert(periodic_events_initialized == 0);
1301 periodic_events_initialized = 1;
1303 int i;
1304 for (i = 0; periodic_events[i].name; ++i) {
1305 periodic_event_setup(&periodic_events[i]);
1308 #define NAMED_CALLBACK(name) \
1309 STMT_BEGIN name ## _event = find_periodic_event( #name ); STMT_END
1311 NAMED_CALLBACK(check_descriptor);
1312 NAMED_CALLBACK(fetch_networkstatus);
1313 NAMED_CALLBACK(launch_descriptor_fetches);
1314 NAMED_CALLBACK(check_dns_honesty);
1316 struct timeval one_second = { 1, 0 };
1317 event_base_once(tor_libevent_get_base(), -1, EV_TIMEOUT,
1318 initialize_periodic_events_cb, NULL,
1319 &one_second);
1322 STATIC void
1323 teardown_periodic_events(void)
1325 int i;
1326 for (i = 0; periodic_events[i].name; ++i) {
1327 periodic_event_destroy(&periodic_events[i]);
1332 * Update our schedule so that we'll check whether we need to update our
1333 * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
1334 * seconds.
1336 void
1337 reschedule_descriptor_update_check(void)
1339 tor_assert(check_descriptor_event);
1340 periodic_event_reschedule(check_descriptor_event);
1344 * Update our schedule so that we'll check whether we need to fetch directory
1345 * info immediately.
1347 void
1348 reschedule_directory_downloads(void)
1350 tor_assert(fetch_networkstatus_event);
1351 tor_assert(launch_descriptor_fetches_event);
1353 periodic_event_reschedule(fetch_networkstatus_event);
1354 periodic_event_reschedule(launch_descriptor_fetches_event);
1357 #define LONGEST_TIMER_PERIOD (30 * 86400)
1358 /** Helper: Return the number of seconds between <b>now</b> and <b>next</b>,
1359 * clipped to the range [1 second, LONGEST_TIMER_PERIOD]. */
1360 static inline int
1361 safe_timer_diff(time_t now, time_t next)
1363 if (next > now) {
1364 /* There were no computers at signed TIME_MIN (1902 on 32-bit systems),
1365 * and nothing that could run Tor. It's a bug if 'next' is around then.
1366 * On 64-bit systems with signed TIME_MIN, TIME_MIN is before the Big
1367 * Bang. We cannot extrapolate past a singularity, but there was probably
1368 * nothing that could run Tor then, either.
1370 tor_assert(next > TIME_MIN + LONGEST_TIMER_PERIOD);
1372 if (next - LONGEST_TIMER_PERIOD > now)
1373 return LONGEST_TIMER_PERIOD;
1374 return (int)(next - now);
1375 } else {
1376 return 1;
1380 /** Perform regular maintenance tasks. This function gets run once per
1381 * second by second_elapsed_callback().
1383 static void
1384 run_scheduled_events(time_t now)
1386 const or_options_t *options = get_options();
1388 /* 0. See if we've been asked to shut down and our timeout has
1389 * expired; or if our bandwidth limits are exhausted and we
1390 * should hibernate; or if it's time to wake up from hibernation.
1392 consider_hibernation(now);
1394 /* 0b. If we've deferred a signewnym, make sure it gets handled
1395 * eventually. */
1396 if (signewnym_is_pending &&
1397 time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
1398 log_info(LD_CONTROL, "Honoring delayed NEWNYM request");
1399 signewnym_impl(now);
1402 /* 0c. If we've deferred log messages for the controller, handle them now */
1403 flush_pending_log_callbacks();
1405 /* Maybe enough time elapsed for us to reconsider a circuit. */
1406 circuit_upgrade_circuits_from_guard_wait();
1408 if (options->UseBridges && !options->DisableNetwork) {
1409 fetch_bridge_descriptors(options, now);
1412 if (accounting_is_enabled(options)) {
1413 accounting_run_housekeeping(now);
1416 if (authdir_mode_v3(options)) {
1417 dirvote_act(options, now);
1420 /* 3a. Every second, we examine pending circuits and prune the
1421 * ones which have been pending for more than a few seconds.
1422 * We do this before step 4, so it can try building more if
1423 * it's not comfortable with the number of available circuits.
1425 /* (If our circuit build timeout can ever become lower than a second (which
1426 * it can't, currently), we should do this more often.) */
1427 circuit_expire_building();
1428 circuit_expire_waiting_for_better_guard();
1430 /* 3b. Also look at pending streams and prune the ones that 'began'
1431 * a long time ago but haven't gotten a 'connected' yet.
1432 * Do this before step 4, so we can put them back into pending
1433 * state to be picked up by the new circuit.
1435 connection_ap_expire_beginning();
1437 /* 3c. And expire connections that we've held open for too long.
1439 connection_expire_held_open();
1441 /* 4. Every second, we try a new circuit if there are no valid
1442 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1443 * that became dirty more than MaxCircuitDirtiness seconds ago,
1444 * and we make a new circ if there are no clean circuits.
1446 const int have_dir_info = router_have_minimum_dir_info();
1447 if (have_dir_info && !net_is_disabled()) {
1448 circuit_build_needed_circs(now);
1449 } else {
1450 circuit_expire_old_circs_as_needed(now);
1453 if (!net_is_disabled()) {
1454 /* This is usually redundant with circuit_build_needed_circs() above,
1455 * but it is very fast when there is no work to do. */
1456 connection_ap_attach_pending(0);
1459 /* 5. We do housekeeping for each connection... */
1460 channel_update_bad_for_new_circs(NULL, 0);
1461 int i;
1462 for (i=0;i<smartlist_len(connection_array);i++) {
1463 run_connection_housekeeping(i, now);
1466 /* 6. And remove any marked circuits... */
1467 circuit_close_all_marked();
1469 /* 8. and blow away any connections that need to die. have to do this now,
1470 * because if we marked a conn for close and left its socket -1, then
1471 * we'll pass it to poll/select and bad things will happen.
1473 close_closeable_connections();
1475 /* 8b. And if anything in our state is ready to get flushed to disk, we
1476 * flush it. */
1477 or_state_save(now);
1479 /* 8c. Do channel cleanup just like for connections */
1480 channel_run_cleanup();
1481 channel_listener_run_cleanup();
1483 /* 11b. check pending unconfigured managed proxies */
1484 if (!net_is_disabled() && pt_proxies_configuration_pending())
1485 pt_configure_remaining_proxies();
1487 /* 12. launch diff computations. (This is free if there are none to
1488 * launch.) */
1489 if (dir_server_mode(options)) {
1490 consdiffmgr_rescan();
1494 /* Periodic callback: rotate the onion keys after the period defined by the
1495 * "onion-key-rotation-days" consensus parameter, shut down and restart all
1496 * cpuworkers, and update our descriptor if necessary.
1498 static int
1499 rotate_onion_key_callback(time_t now, const or_options_t *options)
1501 if (server_mode(options)) {
1502 int onion_key_lifetime = get_onion_key_lifetime();
1503 time_t rotation_time = get_onion_key_set_at()+onion_key_lifetime;
1504 if (rotation_time > now) {
1505 return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
1508 log_info(LD_GENERAL,"Rotating onion key.");
1509 rotate_onion_key();
1510 cpuworkers_rotate_keyinfo();
1511 if (router_rebuild_descriptor(1)<0) {
1512 log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
1514 if (advertised_server_mode() && !options->DisableNetwork)
1515 router_upload_dir_desc_to_dirservers(0);
1516 return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
1518 return PERIODIC_EVENT_NO_UPDATE;
1521 /* Period callback: Check if our old onion keys are still valid after the
1522 * period of time defined by the consensus parameter
1523 * "onion-key-grace-period-days", otherwise expire them by setting them to
1524 * NULL.
1526 static int
1527 check_onion_keys_expiry_time_callback(time_t now, const or_options_t *options)
1529 if (server_mode(options)) {
1530 int onion_key_grace_period = get_onion_key_grace_period();
1531 time_t expiry_time = get_onion_key_set_at()+onion_key_grace_period;
1532 if (expiry_time > now) {
1533 return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
1536 log_info(LD_GENERAL, "Expiring old onion keys.");
1537 expire_old_onion_keys();
1538 cpuworkers_rotate_keyinfo();
1539 return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
1542 return PERIODIC_EVENT_NO_UPDATE;
1545 /* Periodic callback: Every 30 seconds, check whether it's time to make new
1546 * Ed25519 subkeys.
1548 static int
1549 check_ed_keys_callback(time_t now, const or_options_t *options)
1551 if (server_mode(options)) {
1552 if (should_make_new_ed_keys(options, now)) {
1553 int new_signing_key = load_ed_keys(options, now);
1554 if (new_signing_key < 0 ||
1555 generate_ed_link_cert(options, now, new_signing_key > 0)) {
1556 log_err(LD_OR, "Unable to update Ed25519 keys! Exiting.");
1557 tor_cleanup();
1558 exit(1);
1561 return 30;
1563 return PERIODIC_EVENT_NO_UPDATE;
1567 * Periodic callback: Every {LAZY,GREEDY}_DESCRIPTOR_RETRY_INTERVAL,
1568 * see about fetching descriptors, microdescriptors, and extrainfo
1569 * documents.
1571 static int
1572 launch_descriptor_fetches_callback(time_t now, const or_options_t *options)
1574 if (should_delay_dir_fetches(options, NULL))
1575 return PERIODIC_EVENT_NO_UPDATE;
1577 update_all_descriptor_downloads(now);
1578 update_extrainfo_downloads(now);
1579 if (router_have_minimum_dir_info())
1580 return LAZY_DESCRIPTOR_RETRY_INTERVAL;
1581 else
1582 return GREEDY_DESCRIPTOR_RETRY_INTERVAL;
1586 * Periodic event: Rotate our X.509 certificates and TLS keys once every
1587 * MAX_SSL_KEY_LIFETIME_INTERNAL.
1589 static int
1590 rotate_x509_certificate_callback(time_t now, const or_options_t *options)
1592 static int first = 1;
1593 (void)now;
1594 (void)options;
1595 if (first) {
1596 first = 0;
1597 return MAX_SSL_KEY_LIFETIME_INTERNAL;
1600 /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1601 * TLS context. */
1602 log_info(LD_GENERAL,"Rotating tls context.");
1603 if (router_initialize_tls_context() < 0) {
1604 log_err(LD_BUG, "Error reinitializing TLS context");
1605 tor_assert_unreached();
1607 if (generate_ed_link_cert(options, now, 1)) {
1608 log_err(LD_OR, "Unable to update Ed25519->TLS link certificate for "
1609 "new TLS context.");
1610 tor_assert_unreached();
1613 /* We also make sure to rotate the TLS connections themselves if they've
1614 * been up for too long -- but that's done via is_bad_for_new_circs in
1615 * run_connection_housekeeping() above. */
1616 return MAX_SSL_KEY_LIFETIME_INTERNAL;
1620 * Periodic callback: once an hour, grab some more entropy from the
1621 * kernel and feed it to our CSPRNG.
1623 static int
1624 add_entropy_callback(time_t now, const or_options_t *options)
1626 (void)now;
1627 (void)options;
1628 /* We already seeded once, so don't die on failure. */
1629 if (crypto_seed_rng() < 0) {
1630 log_warn(LD_GENERAL, "Tried to re-seed RNG, but failed. We already "
1631 "seeded once, though, so we won't exit here.");
1634 /** How often do we add more entropy to OpenSSL's RNG pool? */
1635 #define ENTROPY_INTERVAL (60*60)
1636 return ENTROPY_INTERVAL;
1640 * Periodic callback: if we're an authority, make sure we test
1641 * the routers on the network for reachability.
1643 static int
1644 launch_reachability_tests_callback(time_t now, const or_options_t *options)
1646 if (authdir_mode_tests_reachability(options) &&
1647 !net_is_disabled()) {
1648 /* try to determine reachability of the other Tor relays */
1649 dirserv_test_reachability(now);
1651 return REACHABILITY_TEST_INTERVAL;
1655 * Periodic callback: if we're an authority, discount the stability
1656 * information (and other rephist information) that's older.
1658 static int
1659 downrate_stability_callback(time_t now, const or_options_t *options)
1661 (void)options;
1662 /* 1d. Periodically, we discount older stability information so that new
1663 * stability info counts more, and save the stability information to disk as
1664 * appropriate. */
1665 time_t next = rep_hist_downrate_old_runs(now);
1666 return safe_timer_diff(now, next);
1670 * Periodic callback: if we're an authority, record our measured stability
1671 * information from rephist in an mtbf file.
1673 static int
1674 save_stability_callback(time_t now, const or_options_t *options)
1676 if (authdir_mode_tests_reachability(options)) {
1677 if (rep_hist_record_mtbf_data(now, 1)<0) {
1678 log_warn(LD_GENERAL, "Couldn't store mtbf data.");
1681 #define SAVE_STABILITY_INTERVAL (30*60)
1682 return SAVE_STABILITY_INTERVAL;
1686 * Periodic callback: if we're an authority, check on our authority
1687 * certificate (the one that authenticates our authority signing key).
1689 static int
1690 check_authority_cert_callback(time_t now, const or_options_t *options)
1692 (void)now;
1693 (void)options;
1694 /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
1695 * close to expiring and warn the admin if it is. */
1696 v3_authority_check_key_expiry();
1697 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
1698 return CHECK_V3_CERTIFICATE_INTERVAL;
1702 * Periodic callback: If our consensus is too old, recalculate whether
1703 * we can actually use it.
1705 static int
1706 check_expired_networkstatus_callback(time_t now, const or_options_t *options)
1708 (void)options;
1709 /* Check whether our networkstatus has expired. */
1710 networkstatus_t *ns = networkstatus_get_latest_consensus();
1711 /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
1712 * networkstatus_get_reasonably_live_consensus(), but that value is way
1713 * way too high. Arma: is the bridge issue there resolved yet? -NM */
1714 #define NS_EXPIRY_SLOP (24*60*60)
1715 if (ns && ns->valid_until < (now - NS_EXPIRY_SLOP) &&
1716 router_have_minimum_dir_info()) {
1717 router_dir_info_changed();
1719 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1720 return CHECK_EXPIRED_NS_INTERVAL;
1724 * Periodic callback: Write statistics to disk if appropriate.
1726 static int
1727 write_stats_file_callback(time_t now, const or_options_t *options)
1729 /* 1g. Check whether we should write statistics to disk.
1731 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1732 time_t next_time_to_write_stats_files = now + CHECK_WRITE_STATS_INTERVAL;
1733 if (options->CellStatistics) {
1734 time_t next_write =
1735 rep_hist_buffer_stats_write(now);
1736 if (next_write && next_write < next_time_to_write_stats_files)
1737 next_time_to_write_stats_files = next_write;
1739 if (options->DirReqStatistics) {
1740 time_t next_write = geoip_dirreq_stats_write(now);
1741 if (next_write && next_write < next_time_to_write_stats_files)
1742 next_time_to_write_stats_files = next_write;
1744 if (options->EntryStatistics) {
1745 time_t next_write = geoip_entry_stats_write(now);
1746 if (next_write && next_write < next_time_to_write_stats_files)
1747 next_time_to_write_stats_files = next_write;
1749 if (options->HiddenServiceStatistics) {
1750 time_t next_write = rep_hist_hs_stats_write(now);
1751 if (next_write && next_write < next_time_to_write_stats_files)
1752 next_time_to_write_stats_files = next_write;
1754 if (options->ExitPortStatistics) {
1755 time_t next_write = rep_hist_exit_stats_write(now);
1756 if (next_write && next_write < next_time_to_write_stats_files)
1757 next_time_to_write_stats_files = next_write;
1759 if (options->ConnDirectionStatistics) {
1760 time_t next_write = rep_hist_conn_stats_write(now);
1761 if (next_write && next_write < next_time_to_write_stats_files)
1762 next_time_to_write_stats_files = next_write;
1764 if (options->BridgeAuthoritativeDir) {
1765 time_t next_write = rep_hist_desc_stats_write(now);
1766 if (next_write && next_write < next_time_to_write_stats_files)
1767 next_time_to_write_stats_files = next_write;
1770 return safe_timer_diff(now, next_time_to_write_stats_files);
1773 #define CHANNEL_CHECK_INTERVAL (60*60)
1774 static int
1775 check_canonical_channels_callback(time_t now, const or_options_t *options)
1777 (void)now;
1778 if (public_server_mode(options))
1779 channel_check_for_duplicates();
1781 return CHANNEL_CHECK_INTERVAL;
1784 static int
1785 reset_padding_counts_callback(time_t now, const or_options_t *options)
1787 if (options->PaddingStatistics) {
1788 rep_hist_prep_published_padding_counts(now);
1791 rep_hist_reset_padding_counts();
1792 return REPHIST_CELL_PADDING_COUNTS_INTERVAL;
1796 * Periodic callback: Write bridge statistics to disk if appropriate.
1798 static int
1799 record_bridge_stats_callback(time_t now, const or_options_t *options)
1801 static int should_init_bridge_stats = 1;
1803 /* 1h. Check whether we should write bridge statistics to disk.
1805 if (should_record_bridge_info(options)) {
1806 if (should_init_bridge_stats) {
1807 /* (Re-)initialize bridge statistics. */
1808 geoip_bridge_stats_init(now);
1809 should_init_bridge_stats = 0;
1810 return WRITE_STATS_INTERVAL;
1811 } else {
1812 /* Possibly write bridge statistics to disk and ask when to write
1813 * them next time. */
1814 time_t next = geoip_bridge_stats_write(now);
1815 return safe_timer_diff(now, next);
1817 } else if (!should_init_bridge_stats) {
1818 /* Bridge mode was turned off. Ensure that stats are re-initialized
1819 * next time bridge mode is turned on. */
1820 should_init_bridge_stats = 1;
1822 return PERIODIC_EVENT_NO_UPDATE;
1826 * Periodic callback: Clean in-memory caches every once in a while
1828 static int
1829 clean_caches_callback(time_t now, const or_options_t *options)
1831 /* Remove old information from rephist and the rend cache. */
1832 rep_history_clean(now - options->RephistTrackTime);
1833 rend_cache_clean(now, REND_CACHE_TYPE_SERVICE);
1834 hs_cache_clean_as_client(now);
1835 hs_cache_clean_as_dir(now);
1836 microdesc_cache_rebuild(NULL, 0);
1837 #define CLEAN_CACHES_INTERVAL (30*60)
1838 return CLEAN_CACHES_INTERVAL;
1842 * Periodic callback: Clean the cache of failed hidden service lookups
1843 * frequently.
1845 static int
1846 rend_cache_failure_clean_callback(time_t now, const or_options_t *options)
1848 (void)options;
1849 /* We don't keep entries that are more than five minutes old so we try to
1850 * clean it as soon as we can since we want to make sure the client waits
1851 * as little as possible for reachability reasons. */
1852 rend_cache_failure_clean(now);
1853 hs_cache_client_intro_state_clean(now);
1854 return 30;
1858 * Periodic callback: If we're a server and initializing dns failed, retry.
1860 static int
1861 retry_dns_callback(time_t now, const or_options_t *options)
1863 (void)now;
1864 #define RETRY_DNS_INTERVAL (10*60)
1865 if (server_mode(options) && has_dns_init_failed())
1866 dns_init();
1867 return RETRY_DNS_INTERVAL;
1870 /** Periodic callback: consider rebuilding or and re-uploading our descriptor
1871 * (if we've passed our internal checks). */
1872 static int
1873 check_descriptor_callback(time_t now, const or_options_t *options)
1875 /** How often do we check whether part of our router info has changed in a
1876 * way that would require an upload? That includes checking whether our IP
1877 * address has changed. */
1878 #define CHECK_DESCRIPTOR_INTERVAL (60)
1880 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1881 * one is inaccurate. */
1882 if (!options->DisableNetwork) {
1883 check_descriptor_bandwidth_changed(now);
1884 check_descriptor_ipaddress_changed(now);
1885 mark_my_descriptor_dirty_if_too_old(now);
1886 consider_publishable_server(0);
1887 /* If any networkstatus documents are no longer recent, we need to
1888 * update all the descriptors' running status. */
1889 /* Remove dead routers. */
1890 /* XXXX This doesn't belong here, but it was here in the pre-
1891 * XXXX refactoring code. */
1892 routerlist_remove_old_routers();
1895 return CHECK_DESCRIPTOR_INTERVAL;
1899 * Periodic callback: check whether we're reachable (as a relay), and
1900 * whether our bandwidth has changed enough that we need to
1901 * publish a new descriptor.
1903 static int
1904 check_for_reachability_bw_callback(time_t now, const or_options_t *options)
1906 /* XXXX This whole thing was stuck in the middle of what is now
1907 * XXXX check_descriptor_callback. I'm not sure it's right. */
1909 static int dirport_reachability_count = 0;
1910 /* also, check religiously for reachability, if it's within the first
1911 * 20 minutes of our uptime. */
1912 if (server_mode(options) &&
1913 (have_completed_a_circuit() || !any_predicted_circuits(now)) &&
1914 !we_are_hibernating()) {
1915 if (stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1916 consider_testing_reachability(1, dirport_reachability_count==0);
1917 if (++dirport_reachability_count > 5)
1918 dirport_reachability_count = 0;
1919 return 1;
1920 } else {
1921 /* If we haven't checked for 12 hours and our bandwidth estimate is
1922 * low, do another bandwidth test. This is especially important for
1923 * bridges, since they might go long periods without much use. */
1924 const routerinfo_t *me = router_get_my_routerinfo();
1925 static int first_time = 1;
1926 if (!first_time && me &&
1927 me->bandwidthcapacity < me->bandwidthrate &&
1928 me->bandwidthcapacity < 51200) {
1929 reset_bandwidth_test();
1931 first_time = 0;
1932 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1933 return BANDWIDTH_RECHECK_INTERVAL;
1936 return CHECK_DESCRIPTOR_INTERVAL;
1940 * Periodic event: once a minute, (or every second if TestingTorNetwork, or
1941 * during client bootstrap), check whether we want to download any
1942 * networkstatus documents. */
1943 static int
1944 fetch_networkstatus_callback(time_t now, const or_options_t *options)
1946 /* How often do we check whether we should download network status
1947 * documents? */
1948 const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
1949 now);
1950 const int prefer_mirrors = !directory_fetches_from_authorities(
1951 get_options());
1952 int networkstatus_dl_check_interval = 60;
1953 /* check more often when testing, or when bootstrapping from mirrors
1954 * (connection limits prevent too many connections being made) */
1955 if (options->TestingTorNetwork
1956 || (we_are_bootstrapping && prefer_mirrors)) {
1957 networkstatus_dl_check_interval = 1;
1960 if (should_delay_dir_fetches(options, NULL))
1961 return PERIODIC_EVENT_NO_UPDATE;
1963 update_networkstatus_downloads(now);
1964 return networkstatus_dl_check_interval;
1968 * Periodic callback: Every 60 seconds, we relaunch listeners if any died. */
1969 static int
1970 retry_listeners_callback(time_t now, const or_options_t *options)
1972 (void)now;
1973 (void)options;
1974 if (!net_is_disabled()) {
1975 retry_all_listeners(NULL, NULL, 0);
1976 return 60;
1978 return PERIODIC_EVENT_NO_UPDATE;
1982 * Periodic callback: as a server, see if we have any old unused circuits
1983 * that should be expired */
1984 static int
1985 expire_old_ciruits_serverside_callback(time_t now, const or_options_t *options)
1987 (void)options;
1988 /* every 11 seconds, so not usually the same second as other such events */
1989 circuit_expire_old_circuits_serverside(now);
1990 return 11;
1994 * Periodic event: if we're an exit, see if our DNS server is telling us
1995 * obvious lies.
1997 static int
1998 check_dns_honesty_callback(time_t now, const or_options_t *options)
2000 (void)now;
2001 /* 9. and if we're an exit node, check whether our DNS is telling stories
2002 * to us. */
2003 if (net_is_disabled() ||
2004 ! public_server_mode(options) ||
2005 router_my_exit_policy_is_reject_star())
2006 return PERIODIC_EVENT_NO_UPDATE;
2008 static int first_time = 1;
2009 if (first_time) {
2010 /* Don't launch right when we start */
2011 first_time = 0;
2012 return crypto_rand_int_range(60, 180);
2015 dns_launch_correctness_checks();
2016 return 12*3600 + crypto_rand_int(12*3600);
2020 * Periodic callback: if we're the bridge authority, write a networkstatus
2021 * file to disk.
2023 static int
2024 write_bridge_ns_callback(time_t now, const or_options_t *options)
2026 /* 10. write bridge networkstatus file to disk */
2027 if (options->BridgeAuthoritativeDir) {
2028 networkstatus_dump_bridge_status_to_file(now);
2029 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
2030 return BRIDGE_STATUSFILE_INTERVAL;
2032 return PERIODIC_EVENT_NO_UPDATE;
2036 * Periodic callback: poke the tor-fw-helper app if we're using one.
2038 static int
2039 check_fw_helper_app_callback(time_t now, const or_options_t *options)
2041 if (net_is_disabled() ||
2042 ! server_mode(options) ||
2043 ! options->PortForwarding ||
2044 options->NoExec) {
2045 return PERIODIC_EVENT_NO_UPDATE;
2047 /* 11. check the port forwarding app */
2049 #define PORT_FORWARDING_CHECK_INTERVAL 5
2050 smartlist_t *ports_to_forward = get_list_of_ports_to_forward();
2051 if (ports_to_forward) {
2052 tor_check_port_forwarding(options->PortForwardingHelper,
2053 ports_to_forward,
2054 now);
2056 SMARTLIST_FOREACH(ports_to_forward, char *, cp, tor_free(cp));
2057 smartlist_free(ports_to_forward);
2059 return PORT_FORWARDING_CHECK_INTERVAL;
2063 * Periodic callback: write the heartbeat message in the logs.
2065 * If writing the heartbeat message to the logs fails for some reason, retry
2066 * again after <b>MIN_HEARTBEAT_PERIOD</b> seconds.
2068 static int
2069 heartbeat_callback(time_t now, const or_options_t *options)
2071 static int first = 1;
2073 /* Check if heartbeat is disabled */
2074 if (!options->HeartbeatPeriod) {
2075 return PERIODIC_EVENT_NO_UPDATE;
2078 /* Skip the first one. */
2079 if (first) {
2080 first = 0;
2081 return options->HeartbeatPeriod;
2084 /* Write the heartbeat message */
2085 if (log_heartbeat(now) == 0) {
2086 return options->HeartbeatPeriod;
2087 } else {
2088 /* If we couldn't write the heartbeat log message, try again in the minimum
2089 * interval of time. */
2090 return MIN_HEARTBEAT_PERIOD;
2094 #define CDM_CLEAN_CALLBACK_INTERVAL 600
2095 static int
2096 clean_consdiffmgr_callback(time_t now, const or_options_t *options)
2098 (void)now;
2099 if (server_mode(options)) {
2100 consdiffmgr_cleanup();
2102 return CDM_CLEAN_CALLBACK_INTERVAL;
2106 * Periodic callback: Run scheduled events for HS service. This is called
2107 * every second.
2109 static int
2110 hs_service_callback(time_t now, const or_options_t *options)
2112 (void) options;
2114 /* We need to at least be able to build circuits and that we actually have
2115 * a working network. */
2116 if (!have_completed_a_circuit() || net_is_disabled() ||
2117 networkstatus_get_live_consensus(now) == NULL) {
2118 goto end;
2121 hs_service_run_scheduled_events(now);
2123 end:
2124 /* Every 1 second. */
2125 return 1;
2128 /** Timer: used to invoke second_elapsed_callback() once per second. */
2129 static periodic_timer_t *second_timer = NULL;
2130 /** Number of libevent errors in the last second: we die if we get too many. */
2131 static int n_libevent_errors = 0;
2133 /** Libevent callback: invoked once every second. */
2134 static void
2135 second_elapsed_callback(periodic_timer_t *timer, void *arg)
2137 /* XXXX This could be sensibly refactored into multiple callbacks, and we
2138 * could use Libevent's timers for this rather than checking the current
2139 * time against a bunch of timeouts every second. */
2140 static time_t current_second = 0;
2141 time_t now;
2142 size_t bytes_written;
2143 size_t bytes_read;
2144 int seconds_elapsed;
2145 const or_options_t *options = get_options();
2146 (void)timer;
2147 (void)arg;
2149 n_libevent_errors = 0;
2151 /* log_notice(LD_GENERAL, "Tick."); */
2152 now = time(NULL);
2153 update_approx_time(now);
2155 /* the second has rolled over. check more stuff. */
2156 seconds_elapsed = current_second ? (int)(now - current_second) : 0;
2157 bytes_read = (size_t)(stats_n_bytes_read - stats_prev_n_read);
2158 bytes_written = (size_t)(stats_n_bytes_written - stats_prev_n_written);
2159 stats_prev_n_read = stats_n_bytes_read;
2160 stats_prev_n_written = stats_n_bytes_written;
2162 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
2163 control_event_stream_bandwidth_used();
2164 control_event_conn_bandwidth_used();
2165 control_event_circ_bandwidth_used();
2166 control_event_circuit_cell_stats();
2168 if (server_mode(options) &&
2169 !net_is_disabled() &&
2170 seconds_elapsed > 0 &&
2171 have_completed_a_circuit() &&
2172 stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
2173 (stats_n_seconds_working+seconds_elapsed) /
2174 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
2175 /* every 20 minutes, check and complain if necessary */
2176 const routerinfo_t *me = router_get_my_routerinfo();
2177 if (me && !check_whether_orport_reachable(options)) {
2178 char *address = tor_dup_ip(me->addr);
2179 log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
2180 "its ORPort is reachable. Relays do not publish descriptors "
2181 "until their ORPort and DirPort are reachable. Please check "
2182 "your firewalls, ports, address, /etc/hosts file, etc.",
2183 address, me->or_port);
2184 control_event_server_status(LOG_WARN,
2185 "REACHABILITY_FAILED ORADDRESS=%s:%d",
2186 address, me->or_port);
2187 tor_free(address);
2190 if (me && !check_whether_dirport_reachable(options)) {
2191 char *address = tor_dup_ip(me->addr);
2192 log_warn(LD_CONFIG,
2193 "Your server (%s:%d) has not managed to confirm that its "
2194 "DirPort is reachable. Relays do not publish descriptors "
2195 "until their ORPort and DirPort are reachable. Please check "
2196 "your firewalls, ports, address, /etc/hosts file, etc.",
2197 address, me->dir_port);
2198 control_event_server_status(LOG_WARN,
2199 "REACHABILITY_FAILED DIRADDRESS=%s:%d",
2200 address, me->dir_port);
2201 tor_free(address);
2205 /** If more than this many seconds have elapsed, probably the clock
2206 * jumped: doesn't count. */
2207 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
2208 if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
2209 seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
2210 circuit_note_clock_jumped(seconds_elapsed);
2211 } else if (seconds_elapsed > 0)
2212 stats_n_seconds_working += seconds_elapsed;
2214 run_scheduled_events(now);
2216 current_second = now; /* remember which second it is, for next time */
2219 #ifdef HAVE_SYSTEMD_209
2220 static periodic_timer_t *systemd_watchdog_timer = NULL;
2222 /** Libevent callback: invoked to reset systemd watchdog. */
2223 static void
2224 systemd_watchdog_callback(periodic_timer_t *timer, void *arg)
2226 (void)timer;
2227 (void)arg;
2228 sd_notify(0, "WATCHDOG=1");
2230 #endif /* defined(HAVE_SYSTEMD_209) */
2232 /** Timer: used to invoke refill_callback(). */
2233 static periodic_timer_t *refill_timer = NULL;
2235 /** Libevent callback: invoked periodically to refill token buckets
2236 * and count r/w bytes. */
2237 static void
2238 refill_callback(periodic_timer_t *timer, void *arg)
2240 static struct timeval current_millisecond;
2241 struct timeval now;
2243 size_t bytes_written;
2244 size_t bytes_read;
2245 int milliseconds_elapsed = 0;
2246 int seconds_rolled_over = 0;
2248 const or_options_t *options = get_options();
2250 (void)timer;
2251 (void)arg;
2253 tor_gettimeofday(&now);
2255 /* If this is our first time, no time has passed. */
2256 if (current_millisecond.tv_sec) {
2257 long mdiff = tv_mdiff(&current_millisecond, &now);
2258 if (mdiff > INT_MAX)
2259 mdiff = INT_MAX;
2260 milliseconds_elapsed = (int)mdiff;
2261 seconds_rolled_over = (int)(now.tv_sec - current_millisecond.tv_sec);
2264 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
2265 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
2267 stats_n_bytes_read += bytes_read;
2268 stats_n_bytes_written += bytes_written;
2269 if (accounting_is_enabled(options) && milliseconds_elapsed >= 0)
2270 accounting_add_bytes(bytes_read, bytes_written, seconds_rolled_over);
2272 if (milliseconds_elapsed > 0)
2273 connection_bucket_refill(milliseconds_elapsed, (time_t)now.tv_sec);
2275 stats_prev_global_read_bucket = global_read_bucket;
2276 stats_prev_global_write_bucket = global_write_bucket;
2278 current_millisecond = now; /* remember what time it is, for next time */
2281 #ifndef _WIN32
2282 /** Called when a possibly ignorable libevent error occurs; ensures that we
2283 * don't get into an infinite loop by ignoring too many errors from
2284 * libevent. */
2285 static int
2286 got_libevent_error(void)
2288 if (++n_libevent_errors > 8) {
2289 log_err(LD_NET, "Too many libevent errors in one second; dying");
2290 return -1;
2292 return 0;
2294 #endif /* !defined(_WIN32) */
2296 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
2298 /** Called when our IP address seems to have changed. <b>at_interface</b>
2299 * should be true if we detected a change in our interface, and false if we
2300 * detected a change in our published address. */
2301 void
2302 ip_address_changed(int at_interface)
2304 const or_options_t *options = get_options();
2305 int server = server_mode(options);
2306 int exit_reject_interfaces = (server && options->ExitRelay
2307 && options->ExitPolicyRejectLocalInterfaces);
2309 if (at_interface) {
2310 if (! server) {
2311 /* Okay, change our keys. */
2312 if (init_keys_client() < 0)
2313 log_warn(LD_GENERAL, "Unable to rotate keys after IP change!");
2315 } else {
2316 if (server) {
2317 if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
2318 reset_bandwidth_test();
2319 stats_n_seconds_working = 0;
2320 router_reset_reachability();
2324 /* Exit relays incorporate interface addresses in their exit policies when
2325 * ExitPolicyRejectLocalInterfaces is set */
2326 if (exit_reject_interfaces || (server && !at_interface)) {
2327 mark_my_descriptor_dirty("IP address changed");
2330 dns_servers_relaunch_checks();
2333 /** Forget what we've learned about the correctness of our DNS servers, and
2334 * start learning again. */
2335 void
2336 dns_servers_relaunch_checks(void)
2338 if (server_mode(get_options())) {
2339 dns_reset_correctness_checks();
2340 if (periodic_events_initialized) {
2341 tor_assert(check_dns_honesty_event);
2342 periodic_event_reschedule(check_dns_honesty_event);
2347 /** Called when we get a SIGHUP: reload configuration files and keys,
2348 * retry all connections, and so on. */
2349 static int
2350 do_hup(void)
2352 const or_options_t *options = get_options();
2354 #ifdef USE_DMALLOC
2355 dmalloc_log_stats();
2356 dmalloc_log_changed(0, 1, 0, 0);
2357 #endif
2359 log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
2360 "resetting internal state.");
2361 if (accounting_is_enabled(options))
2362 accounting_record_bandwidth_usage(time(NULL), get_or_state());
2364 router_reset_warnings();
2365 routerlist_reset_warnings();
2366 /* first, reload config variables, in case they've changed */
2367 if (options->ReloadTorrcOnSIGHUP) {
2368 /* no need to provide argc/v, they've been cached in init_from_config */
2369 if (options_init_from_torrc(0, NULL) < 0) {
2370 log_err(LD_CONFIG,"Reading config failed--see warnings above. "
2371 "For usage, try -h.");
2372 return -1;
2374 options = get_options(); /* they have changed now */
2375 /* Logs are only truncated the first time they are opened, but were
2376 probably intended to be cleaned up on signal. */
2377 if (options->TruncateLogFile)
2378 truncate_logs();
2379 } else {
2380 char *msg = NULL;
2381 log_notice(LD_GENERAL, "Not reloading config file: the controller told "
2382 "us not to.");
2383 /* Make stuff get rescanned, reloaded, etc. */
2384 if (set_options((or_options_t*)options, &msg) < 0) {
2385 if (!msg)
2386 msg = tor_strdup("Unknown error");
2387 log_warn(LD_GENERAL, "Unable to re-set previous options: %s", msg);
2388 tor_free(msg);
2391 if (authdir_mode(options)) {
2392 /* reload the approved-routers file */
2393 if (dirserv_load_fingerprint_file() < 0) {
2394 /* warnings are logged from dirserv_load_fingerprint_file() directly */
2395 log_info(LD_GENERAL, "Error reloading fingerprints. "
2396 "Continuing with old list.");
2400 /* Rotate away from the old dirty circuits. This has to be done
2401 * after we've read the new options, but before we start using
2402 * circuits for directory fetches. */
2403 circuit_mark_all_dirty_circs_as_unusable();
2405 /* retry appropriate downloads */
2406 router_reset_status_download_failures();
2407 router_reset_descriptor_download_failures();
2408 if (!options->DisableNetwork)
2409 update_networkstatus_downloads(time(NULL));
2411 /* We'll retry routerstatus downloads in about 10 seconds; no need to
2412 * force a retry there. */
2414 if (server_mode(options)) {
2415 /* Maybe we've been given a new ed25519 key or certificate?
2417 time_t now = approx_time();
2418 int new_signing_key = load_ed_keys(options, now);
2419 if (new_signing_key < 0 ||
2420 generate_ed_link_cert(options, now, new_signing_key > 0)) {
2421 log_warn(LD_OR, "Problem reloading Ed25519 keys; still using old keys.");
2424 /* Update cpuworker and dnsworker processes, so they get up-to-date
2425 * configuration options. */
2426 cpuworkers_rotate_keyinfo();
2427 dns_reset();
2429 return 0;
2432 /** Tor main loop. */
2434 do_main_loop(void)
2436 time_t now;
2438 /* initialize the periodic events first, so that code that depends on the
2439 * events being present does not assert.
2441 if (! periodic_events_initialized) {
2442 initialize_periodic_events();
2445 /* initialize dns resolve map, spawn workers if needed */
2446 if (dns_init() < 0) {
2447 if (get_options()->ServerDNSAllowBrokenConfig)
2448 log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
2449 "Network not up yet? Will try again soon.");
2450 else {
2451 log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
2452 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
2456 handle_signals(1);
2457 monotime_init();
2458 timers_initialize();
2460 /* load the private keys, if we're supposed to have them, and set up the
2461 * TLS context. */
2462 if (! client_identity_key_is_set()) {
2463 if (init_keys() < 0) {
2464 log_err(LD_OR, "Error initializing keys; exiting");
2465 return -1;
2469 /* Set up our buckets */
2470 connection_bucket_init();
2471 stats_prev_global_read_bucket = global_read_bucket;
2472 stats_prev_global_write_bucket = global_write_bucket;
2474 /* initialize the bootstrap status events to know we're starting up */
2475 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
2477 /* Initialize the keypinning log. */
2478 if (authdir_mode_v3(get_options())) {
2479 char *fname = get_datadir_fname("key-pinning-journal");
2480 int r = 0;
2481 if (keypin_load_journal(fname)<0) {
2482 log_err(LD_DIR, "Error loading key-pinning journal: %s",strerror(errno));
2483 r = -1;
2485 if (keypin_open_journal(fname)<0) {
2486 log_err(LD_DIR, "Error opening key-pinning journal: %s",strerror(errno));
2487 r = -1;
2489 tor_free(fname);
2490 if (r)
2491 return r;
2494 /* This is the old name for key-pinning-journal. These got corrupted
2495 * in a couple of cases by #16530, so we started over. See #16580 for
2496 * the rationale and for other options we didn't take. We can remove
2497 * this code once all the authorities that ran 0.2.7.1-alpha-dev are
2498 * upgraded.
2500 char *fname = get_datadir_fname("key-pinning-entries");
2501 unlink(fname);
2502 tor_free(fname);
2505 if (trusted_dirs_reload_certs()) {
2506 log_warn(LD_DIR,
2507 "Couldn't load all cached v3 certificates. Starting anyway.");
2509 if (router_reload_consensus_networkstatus()) {
2510 return -1;
2512 /* load the routers file, or assign the defaults. */
2513 if (router_reload_router_list()) {
2514 return -1;
2516 /* load the networkstatuses. (This launches a download for new routers as
2517 * appropriate.)
2519 now = time(NULL);
2520 directory_info_has_arrived(now, 1, 0);
2522 if (server_mode(get_options())) {
2523 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
2524 cpu_init();
2526 consdiffmgr_enable_background_compression();
2528 /* Setup shared random protocol subsystem. */
2529 if (authdir_mode_v3(get_options())) {
2530 if (sr_init(1) < 0) {
2531 return -1;
2535 /* set up once-a-second callback. */
2536 if (! second_timer) {
2537 struct timeval one_second;
2538 one_second.tv_sec = 1;
2539 one_second.tv_usec = 0;
2541 second_timer = periodic_timer_new(tor_libevent_get_base(),
2542 &one_second,
2543 second_elapsed_callback,
2544 NULL);
2545 tor_assert(second_timer);
2548 #ifdef HAVE_SYSTEMD_209
2549 uint64_t watchdog_delay;
2550 /* set up systemd watchdog notification. */
2551 if (sd_watchdog_enabled(1, &watchdog_delay) > 0) {
2552 if (! systemd_watchdog_timer) {
2553 struct timeval watchdog;
2554 /* The manager will "act on" us if we don't send them a notification
2555 * every 'watchdog_delay' microseconds. So, send notifications twice
2556 * that often. */
2557 watchdog_delay /= 2;
2558 watchdog.tv_sec = watchdog_delay / 1000000;
2559 watchdog.tv_usec = watchdog_delay % 1000000;
2561 systemd_watchdog_timer = periodic_timer_new(tor_libevent_get_base(),
2562 &watchdog,
2563 systemd_watchdog_callback,
2564 NULL);
2565 tor_assert(systemd_watchdog_timer);
2568 #endif /* defined(HAVE_SYSTEMD_209) */
2570 if (!refill_timer) {
2571 struct timeval refill_interval;
2572 int msecs = get_options()->TokenBucketRefillInterval;
2574 refill_interval.tv_sec = msecs/1000;
2575 refill_interval.tv_usec = (msecs%1000)*1000;
2577 refill_timer = periodic_timer_new(tor_libevent_get_base(),
2578 &refill_interval,
2579 refill_callback,
2580 NULL);
2581 tor_assert(refill_timer);
2584 #ifdef HAVE_SYSTEMD
2586 const int r = sd_notify(0, "READY=1");
2587 if (r < 0) {
2588 log_warn(LD_GENERAL, "Unable to send readiness to systemd: %s",
2589 strerror(r));
2590 } else if (r > 0) {
2591 log_notice(LD_GENERAL, "Signaled readiness to systemd");
2592 } else {
2593 log_info(LD_GENERAL, "Systemd NOTIFY_SOCKET not present.");
2596 #endif /* defined(HAVE_SYSTEMD) */
2598 return run_main_loop_until_done();
2602 * Run the main loop a single time. Return 0 for "exit"; -1 for "exit with
2603 * error", and 1 for "run this again."
2605 static int
2606 run_main_loop_once(void)
2608 int loop_result;
2610 if (nt_service_is_stopping())
2611 return 0;
2613 #ifndef _WIN32
2614 /* Make it easier to tell whether libevent failure is our fault or not. */
2615 errno = 0;
2616 #endif
2618 /* All active linked conns should get their read events activated,
2619 * so that libevent knows to run their callbacks. */
2620 SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
2621 event_active(conn->read_event, EV_READ, 1));
2622 called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
2624 /* Make sure we know (about) what time it is. */
2625 update_approx_time(time(NULL));
2627 /* Here it is: the main loop. Here we tell Libevent to poll until we have
2628 * an event, or the second ends, or until we have some active linked
2629 * connections to trigger events for. Libevent will wait till one
2630 * of these happens, then run all the appropriate callbacks. */
2631 loop_result = event_base_loop(tor_libevent_get_base(),
2632 called_loop_once ? EVLOOP_ONCE : 0);
2634 /* Oh, the loop failed. That might be an error that we need to
2635 * catch, but more likely, it's just an interrupted poll() call or something,
2636 * and we should try again. */
2637 if (loop_result < 0) {
2638 int e = tor_socket_errno(-1);
2639 /* let the program survive things like ^z */
2640 if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
2641 log_err(LD_NET,"libevent call with %s failed: %s [%d]",
2642 tor_libevent_get_method(), tor_socket_strerror(e), e);
2643 return -1;
2644 #ifndef _WIN32
2645 } else if (e == EINVAL) {
2646 log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
2647 if (got_libevent_error())
2648 return -1;
2649 #endif /* !defined(_WIN32) */
2650 } else {
2651 tor_assert_nonfatal_once(! ERRNO_IS_EINPROGRESS(e));
2652 log_debug(LD_NET,"libevent call interrupted.");
2653 /* You can't trust the results of this poll(). Go back to the
2654 * top of the big for loop. */
2655 return 1;
2659 /* And here is where we put callbacks that happen "every time the event loop
2660 * runs." They must be very fast, or else the whole Tor process will get
2661 * slowed down.
2663 * Note that this gets called once per libevent loop, which will make it
2664 * happen once per group of events that fire, or once per second. */
2666 /* If there are any pending client connections, try attaching them to
2667 * circuits (if we can.) This will be pretty fast if nothing new is
2668 * pending.
2670 connection_ap_attach_pending(0);
2672 return 1;
2675 /** Run the run_main_loop_once() function until it declares itself done,
2676 * and return its final return value.
2678 * Shadow won't invoke this function, so don't fill it up with things.
2680 static int
2681 run_main_loop_until_done(void)
2683 int loop_result = 1;
2684 do {
2685 loop_result = run_main_loop_once();
2686 } while (loop_result == 1);
2687 return loop_result;
2690 /** Libevent callback: invoked when we get a signal.
2692 static void
2693 signal_callback(evutil_socket_t fd, short events, void *arg)
2695 const int *sigptr = arg;
2696 const int sig = *sigptr;
2697 (void)fd;
2698 (void)events;
2700 process_signal(sig);
2703 /** Do the work of acting on a signal received in <b>sig</b> */
2704 static void
2705 process_signal(int sig)
2707 switch (sig)
2709 case SIGTERM:
2710 log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
2711 tor_cleanup();
2712 exit(0);
2713 break;
2714 case SIGINT:
2715 if (!server_mode(get_options())) { /* do it now */
2716 log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
2717 tor_cleanup();
2718 exit(0);
2720 #ifdef HAVE_SYSTEMD
2721 sd_notify(0, "STOPPING=1");
2722 #endif
2723 hibernate_begin_shutdown();
2724 break;
2725 #ifdef SIGPIPE
2726 case SIGPIPE:
2727 log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
2728 break;
2729 #endif
2730 case SIGUSR1:
2731 /* prefer to log it at INFO, but make sure we always see it */
2732 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
2733 control_event_signal(sig);
2734 break;
2735 case SIGUSR2:
2736 switch_logs_debug();
2737 log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
2738 "Send HUP to change back.");
2739 control_event_signal(sig);
2740 break;
2741 case SIGHUP:
2742 #ifdef HAVE_SYSTEMD
2743 sd_notify(0, "RELOADING=1");
2744 #endif
2745 if (do_hup() < 0) {
2746 log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
2747 tor_cleanup();
2748 exit(1);
2750 #ifdef HAVE_SYSTEMD
2751 sd_notify(0, "READY=1");
2752 #endif
2753 control_event_signal(sig);
2754 break;
2755 #ifdef SIGCHLD
2756 case SIGCHLD:
2757 notify_pending_waitpid_callbacks();
2758 break;
2759 #endif
2760 case SIGNEWNYM: {
2761 time_t now = time(NULL);
2762 if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
2763 signewnym_is_pending = 1;
2764 log_notice(LD_CONTROL,
2765 "Rate limiting NEWNYM request: delaying by %d second(s)",
2766 (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
2767 } else {
2768 signewnym_impl(now);
2770 break;
2772 case SIGCLEARDNSCACHE:
2773 addressmap_clear_transient();
2774 control_event_signal(sig);
2775 break;
2776 case SIGHEARTBEAT:
2777 log_heartbeat(time(NULL));
2778 control_event_signal(sig);
2779 break;
2783 /** Returns Tor's uptime. */
2784 MOCK_IMPL(long,
2785 get_uptime,(void))
2787 return stats_n_seconds_working;
2791 * Write current memory usage information to the log.
2793 static void
2794 dumpmemusage(int severity)
2796 connection_dump_buffer_mem_stats(severity);
2797 tor_log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
2798 U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
2799 dump_routerlist_mem_usage(severity);
2800 dump_cell_pool_usage(severity);
2801 dump_dns_mem_usage(severity);
2802 tor_log_mallinfo(severity);
2805 /** Write all statistics to the log, with log level <b>severity</b>. Called
2806 * in response to a SIGUSR1. */
2807 static void
2808 dumpstats(int severity)
2810 time_t now = time(NULL);
2811 time_t elapsed;
2812 size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
2814 tor_log(severity, LD_GENERAL, "Dumping stats:");
2816 SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
2817 int i = conn_sl_idx;
2818 tor_log(severity, LD_GENERAL,
2819 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
2820 i, (int)conn->s, conn->type, conn_type_to_string(conn->type),
2821 conn->state, conn_state_to_string(conn->type, conn->state),
2822 (int)(now - conn->timestamp_created));
2823 if (!connection_is_listener(conn)) {
2824 tor_log(severity,LD_GENERAL,
2825 "Conn %d is to %s:%d.", i,
2826 safe_str_client(conn->address),
2827 conn->port);
2828 tor_log(severity,LD_GENERAL,
2829 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
2831 (int)connection_get_inbuf_len(conn),
2832 (int)buf_allocation(conn->inbuf),
2833 (int)(now - conn->timestamp_lastread));
2834 tor_log(severity,LD_GENERAL,
2835 "Conn %d: %d bytes waiting on outbuf "
2836 "(len %d, last written %d secs ago)",i,
2837 (int)connection_get_outbuf_len(conn),
2838 (int)buf_allocation(conn->outbuf),
2839 (int)(now - conn->timestamp_lastwritten));
2840 if (conn->type == CONN_TYPE_OR) {
2841 or_connection_t *or_conn = TO_OR_CONN(conn);
2842 if (or_conn->tls) {
2843 if (tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
2844 &wbuf_cap, &wbuf_len) == 0) {
2845 tor_log(severity, LD_GENERAL,
2846 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
2847 "%d/%d bytes used on write buffer.",
2848 i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
2853 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
2854 * using this conn */
2855 } SMARTLIST_FOREACH_END(conn);
2857 channel_dumpstats(severity);
2858 channel_listener_dumpstats(severity);
2860 tor_log(severity, LD_NET,
2861 "Cells processed: "U64_FORMAT" padding\n"
2862 " "U64_FORMAT" create\n"
2863 " "U64_FORMAT" created\n"
2864 " "U64_FORMAT" relay\n"
2865 " ("U64_FORMAT" relayed)\n"
2866 " ("U64_FORMAT" delivered)\n"
2867 " "U64_FORMAT" destroy",
2868 U64_PRINTF_ARG(stats_n_padding_cells_processed),
2869 U64_PRINTF_ARG(stats_n_create_cells_processed),
2870 U64_PRINTF_ARG(stats_n_created_cells_processed),
2871 U64_PRINTF_ARG(stats_n_relay_cells_processed),
2872 U64_PRINTF_ARG(stats_n_relay_cells_relayed),
2873 U64_PRINTF_ARG(stats_n_relay_cells_delivered),
2874 U64_PRINTF_ARG(stats_n_destroy_cells_processed));
2875 if (stats_n_data_cells_packaged)
2876 tor_log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
2877 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
2878 U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
2879 if (stats_n_data_cells_received)
2880 tor_log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
2881 100*(U64_TO_DBL(stats_n_data_bytes_received) /
2882 U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
2884 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_TAP, "TAP");
2885 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_NTOR,"ntor");
2887 if (now - time_of_process_start >= 0)
2888 elapsed = now - time_of_process_start;
2889 else
2890 elapsed = 0;
2892 if (elapsed) {
2893 tor_log(severity, LD_NET,
2894 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
2895 U64_PRINTF_ARG(stats_n_bytes_read),
2896 (int)elapsed,
2897 (int) (stats_n_bytes_read/elapsed));
2898 tor_log(severity, LD_NET,
2899 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
2900 U64_PRINTF_ARG(stats_n_bytes_written),
2901 (int)elapsed,
2902 (int) (stats_n_bytes_written/elapsed));
2905 tor_log(severity, LD_NET, "--------------- Dumping memory information:");
2906 dumpmemusage(severity);
2908 rep_hist_dump_stats(now,severity);
2909 rend_service_dump_stats(severity);
2910 dump_distinct_digest_count(severity);
2913 /** Called by exit() as we shut down the process.
2915 static void
2916 exit_function(void)
2918 /* NOTE: If we ever daemonize, this gets called immediately. That's
2919 * okay for now, because we only use this on Windows. */
2920 #ifdef _WIN32
2921 WSACleanup();
2922 #endif
2925 #ifdef _WIN32
2926 #define UNIX_ONLY 0
2927 #else
2928 #define UNIX_ONLY 1
2929 #endif
2930 static struct {
2931 int signal_value;
2932 int try_to_register;
2933 struct event *signal_event;
2934 } signal_handlers[] = {
2935 #ifdef SIGINT
2936 { SIGINT, UNIX_ONLY, NULL }, /* do a controlled slow shutdown */
2937 #endif
2938 #ifdef SIGTERM
2939 { SIGTERM, UNIX_ONLY, NULL }, /* to terminate now */
2940 #endif
2941 #ifdef SIGPIPE
2942 { SIGPIPE, UNIX_ONLY, NULL }, /* otherwise SIGPIPE kills us */
2943 #endif
2944 #ifdef SIGUSR1
2945 { SIGUSR1, UNIX_ONLY, NULL }, /* dump stats */
2946 #endif
2947 #ifdef SIGUSR2
2948 { SIGUSR2, UNIX_ONLY, NULL }, /* go to loglevel debug */
2949 #endif
2950 #ifdef SIGHUP
2951 { SIGHUP, UNIX_ONLY, NULL }, /* to reload config, retry conns, etc */
2952 #endif
2953 #ifdef SIGXFSZ
2954 { SIGXFSZ, UNIX_ONLY, NULL }, /* handle file-too-big resource exhaustion */
2955 #endif
2956 #ifdef SIGCHLD
2957 { SIGCHLD, UNIX_ONLY, NULL }, /* handle dns/cpu workers that exit */
2958 #endif
2959 /* These are controller-only */
2960 { SIGNEWNYM, 0, NULL },
2961 { SIGCLEARDNSCACHE, 0, NULL },
2962 { SIGHEARTBEAT, 0, NULL },
2963 { -1, -1, NULL }
2966 /** Set up the signal handlers for either parent or child process */
2967 void
2968 handle_signals(int is_parent)
2970 int i;
2971 if (is_parent) {
2972 for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
2973 if (signal_handlers[i].try_to_register) {
2974 signal_handlers[i].signal_event =
2975 tor_evsignal_new(tor_libevent_get_base(),
2976 signal_handlers[i].signal_value,
2977 signal_callback,
2978 &signal_handlers[i].signal_value);
2979 if (event_add(signal_handlers[i].signal_event, NULL))
2980 log_warn(LD_BUG, "Error from libevent when adding "
2981 "event for signal %d",
2982 signal_handlers[i].signal_value);
2983 } else {
2984 signal_handlers[i].signal_event =
2985 tor_event_new(tor_libevent_get_base(), -1,
2986 EV_SIGNAL, signal_callback,
2987 &signal_handlers[i].signal_value);
2990 } else {
2991 #ifndef _WIN32
2992 struct sigaction action;
2993 action.sa_flags = 0;
2994 sigemptyset(&action.sa_mask);
2995 action.sa_handler = SIG_IGN;
2996 sigaction(SIGINT, &action, NULL);
2997 sigaction(SIGTERM, &action, NULL);
2998 sigaction(SIGPIPE, &action, NULL);
2999 sigaction(SIGUSR1, &action, NULL);
3000 sigaction(SIGUSR2, &action, NULL);
3001 sigaction(SIGHUP, &action, NULL);
3002 #ifdef SIGXFSZ
3003 sigaction(SIGXFSZ, &action, NULL);
3004 #endif
3005 #endif /* !defined(_WIN32) */
3009 /* Make sure the signal handler for signal_num will be called. */
3010 void
3011 activate_signal(int signal_num)
3013 int i;
3014 for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
3015 if (signal_handlers[i].signal_value == signal_num) {
3016 event_active(signal_handlers[i].signal_event, EV_SIGNAL, 1);
3017 return;
3022 /** Main entry point for the Tor command-line client.
3025 tor_init(int argc, char *argv[])
3027 char progname[256];
3028 int quiet = 0;
3030 time_of_process_start = time(NULL);
3031 init_connection_lists();
3032 /* Have the log set up with our application name. */
3033 tor_snprintf(progname, sizeof(progname), "Tor %s", get_version());
3034 log_set_application_name(progname);
3036 /* Set up the crypto nice and early */
3037 if (crypto_early_init() < 0) {
3038 log_err(LD_GENERAL, "Unable to initialize the crypto subsystem!");
3039 return -1;
3042 /* Initialize the history structures. */
3043 rep_hist_init();
3044 /* Initialize the service cache. */
3045 rend_cache_init();
3046 addressmap_init(); /* Init the client dns cache. Do it always, since it's
3047 * cheap. */
3048 /* Initialize the HS subsystem. */
3049 hs_init();
3052 /* We search for the "quiet" option first, since it decides whether we
3053 * will log anything at all to the command line. */
3054 config_line_t *opts = NULL, *cmdline_opts = NULL;
3055 const config_line_t *cl;
3056 (void) config_parse_commandline(argc, argv, 1, &opts, &cmdline_opts);
3057 for (cl = cmdline_opts; cl; cl = cl->next) {
3058 if (!strcmp(cl->key, "--hush"))
3059 quiet = 1;
3060 if (!strcmp(cl->key, "--quiet") ||
3061 !strcmp(cl->key, "--dump-config"))
3062 quiet = 2;
3063 /* The following options imply --hush */
3064 if (!strcmp(cl->key, "--version") || !strcmp(cl->key, "--digests") ||
3065 !strcmp(cl->key, "--list-torrc-options") ||
3066 !strcmp(cl->key, "--library-versions") ||
3067 !strcmp(cl->key, "--hash-password") ||
3068 !strcmp(cl->key, "-h") || !strcmp(cl->key, "--help")) {
3069 if (quiet < 1)
3070 quiet = 1;
3073 config_free_lines(opts);
3074 config_free_lines(cmdline_opts);
3077 /* give it somewhere to log to initially */
3078 switch (quiet) {
3079 case 2:
3080 /* no initial logging */
3081 break;
3082 case 1:
3083 add_temp_log(LOG_WARN);
3084 break;
3085 default:
3086 add_temp_log(LOG_NOTICE);
3088 quiet_level = quiet;
3091 const char *version = get_version();
3093 log_notice(LD_GENERAL, "Tor %s running on %s with Libevent %s, "
3094 "OpenSSL %s, Zlib %s, Liblzma %s, and Libzstd %s.", version,
3095 get_uname(),
3096 tor_libevent_get_version_str(),
3097 crypto_openssl_get_version_str(),
3098 tor_compress_supports_method(ZLIB_METHOD) ?
3099 tor_compress_version_str(ZLIB_METHOD) : "N/A",
3100 tor_compress_supports_method(LZMA_METHOD) ?
3101 tor_compress_version_str(LZMA_METHOD) : "N/A",
3102 tor_compress_supports_method(ZSTD_METHOD) ?
3103 tor_compress_version_str(ZSTD_METHOD) : "N/A");
3105 log_notice(LD_GENERAL, "Tor can't help you if you use it wrong! "
3106 "Learn how to be safe at "
3107 "https://www.torproject.org/download/download#warning");
3109 if (strstr(version, "alpha") || strstr(version, "beta"))
3110 log_notice(LD_GENERAL, "This version is not a stable Tor release. "
3111 "Expect more bugs than usual.");
3115 rust_str_t rust_str = rust_welcome_string();
3116 const char *s = rust_str_get(rust_str);
3117 if (strlen(s) > 0) {
3118 log_notice(LD_GENERAL, "%s", s);
3120 rust_str_free(rust_str);
3123 if (network_init()<0) {
3124 log_err(LD_BUG,"Error initializing network; exiting.");
3125 return -1;
3127 atexit(exit_function);
3129 if (options_init_from_torrc(argc,argv) < 0) {
3130 log_err(LD_CONFIG,"Reading config failed--see warnings above.");
3131 return -1;
3134 /* The options are now initialised */
3135 const or_options_t *options = get_options();
3137 /* Initialize channelpadding parameters to defaults until we get
3138 * a consensus */
3139 channelpadding_new_consensus_params(NULL);
3141 /* Initialize predicted ports list after loading options */
3142 predicted_ports_init();
3144 #ifndef _WIN32
3145 if (geteuid()==0)
3146 log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
3147 "and you probably shouldn't.");
3148 #endif
3150 if (crypto_global_init(options->HardwareAccel,
3151 options->AccelName,
3152 options->AccelDir)) {
3153 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
3154 return -1;
3156 stream_choice_seed_weak_rng();
3157 if (tor_init_libevent_rng() < 0) {
3158 log_warn(LD_NET, "Problem initializing libevent RNG.");
3161 /* Scan/clean unparseable descroptors; after reading config */
3162 routerparse_init();
3164 return 0;
3167 /** A lockfile structure, used to prevent two Tors from messing with the
3168 * data directory at once. If this variable is non-NULL, we're holding
3169 * the lockfile. */
3170 static tor_lockfile_t *lockfile = NULL;
3172 /** Try to grab the lock file described in <b>options</b>, if we do not
3173 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
3174 * holding the lock, and exit if we can't get it after waiting. Otherwise,
3175 * return -1 if we can't get the lockfile. Return 0 on success.
3178 try_locking(const or_options_t *options, int err_if_locked)
3180 if (lockfile)
3181 return 0;
3182 else {
3183 char *fname = options_get_datadir_fname2_suffix(options, "lock",NULL,NULL);
3184 int already_locked = 0;
3185 tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
3186 tor_free(fname);
3187 if (!lf) {
3188 if (err_if_locked && already_locked) {
3189 int r;
3190 log_warn(LD_GENERAL, "It looks like another Tor process is running "
3191 "with the same data directory. Waiting 5 seconds to see "
3192 "if it goes away.");
3193 #ifndef _WIN32
3194 sleep(5);
3195 #else
3196 Sleep(5000);
3197 #endif
3198 r = try_locking(options, 0);
3199 if (r<0) {
3200 log_err(LD_GENERAL, "No, it's still there. Exiting.");
3201 exit(1);
3203 return r;
3205 return -1;
3207 lockfile = lf;
3208 return 0;
3212 /** Return true iff we've successfully acquired the lock file. */
3214 have_lockfile(void)
3216 return lockfile != NULL;
3219 /** If we have successfully acquired the lock file, release it. */
3220 void
3221 release_lockfile(void)
3223 if (lockfile) {
3224 tor_lockfile_unlock(lockfile);
3225 lockfile = NULL;
3229 /** Free all memory that we might have allocated somewhere.
3230 * If <b>postfork</b>, we are a worker process and we want to free
3231 * only the parts of memory that we won't touch. If !<b>postfork</b>,
3232 * Tor is shutting down and we should free everything.
3234 * Helps us find the real leaks with dmalloc and the like. Also valgrind
3235 * should then report 0 reachable in its leak report (in an ideal world --
3236 * in practice libevent, SSL, libc etc never quite free everything). */
3237 void
3238 tor_free_all(int postfork)
3240 if (!postfork) {
3241 evdns_shutdown(1);
3243 geoip_free_all();
3244 dirvote_free_all();
3245 routerlist_free_all();
3246 networkstatus_free_all();
3247 addressmap_free_all();
3248 dirserv_free_all();
3249 rend_cache_free_all();
3250 rend_service_authorization_free_all();
3251 rep_hist_free_all();
3252 dns_free_all();
3253 clear_pending_onions();
3254 circuit_free_all();
3255 entry_guards_free_all();
3256 pt_free_all();
3257 channel_tls_free_all();
3258 channel_free_all();
3259 connection_free_all();
3260 connection_edge_free_all();
3261 scheduler_free_all();
3262 nodelist_free_all();
3263 microdesc_free_all();
3264 routerparse_free_all();
3265 ext_orport_free_all();
3266 control_free_all();
3267 sandbox_free_getaddrinfo_cache();
3268 protover_free_all();
3269 bridges_free_all();
3270 consdiffmgr_free_all();
3271 hs_free_all();
3272 if (!postfork) {
3273 config_free_all();
3274 or_state_free_all();
3275 router_free_all();
3276 routerkeys_free_all();
3277 policies_free_all();
3279 if (!postfork) {
3280 tor_tls_free_all();
3281 #ifndef _WIN32
3282 tor_getpwnam(NULL);
3283 #endif
3285 /* stuff in main.c */
3287 smartlist_free(connection_array);
3288 smartlist_free(closeable_connection_lst);
3289 smartlist_free(active_linked_connection_lst);
3290 periodic_timer_free(second_timer);
3291 teardown_periodic_events();
3292 periodic_timer_free(refill_timer);
3294 if (!postfork) {
3295 release_lockfile();
3297 /* Stuff in util.c and address.c*/
3298 if (!postfork) {
3299 escaped(NULL);
3300 esc_router_info(NULL);
3301 clean_up_backtrace_handler();
3302 logs_free_all(); /* free log strings. do this last so logs keep working. */
3306 /** Do whatever cleanup is necessary before shutting Tor down. */
3307 void
3308 tor_cleanup(void)
3310 const or_options_t *options = get_options();
3311 if (options->command == CMD_RUN_TOR) {
3312 time_t now = time(NULL);
3313 /* Remove our pid file. We don't care if there was an error when we
3314 * unlink, nothing we could do about it anyways. */
3315 if (options->PidFile) {
3316 if (unlink(options->PidFile) != 0) {
3317 log_warn(LD_FS, "Couldn't unlink pid file %s: %s",
3318 options->PidFile, strerror(errno));
3321 if (options->ControlPortWriteToFile) {
3322 if (unlink(options->ControlPortWriteToFile) != 0) {
3323 log_warn(LD_FS, "Couldn't unlink control port file %s: %s",
3324 options->ControlPortWriteToFile,
3325 strerror(errno));
3328 if (accounting_is_enabled(options))
3329 accounting_record_bandwidth_usage(now, get_or_state());
3330 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
3331 or_state_save(now);
3332 if (authdir_mode(options)) {
3333 sr_save_and_cleanup();
3335 if (authdir_mode_tests_reachability(options))
3336 rep_hist_record_mtbf_data(now, 0);
3337 keypin_close_journal();
3340 timers_shutdown();
3342 #ifdef USE_DMALLOC
3343 dmalloc_log_stats();
3344 #endif
3345 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
3346 later, if it makes shutdown unacceptably slow. But for
3347 now, leave it here: it's helped us catch bugs in the
3348 past. */
3349 crypto_global_cleanup();
3350 #ifdef USE_DMALLOC
3351 dmalloc_log_unfreed();
3352 dmalloc_shutdown();
3353 #endif
3356 /** Read/create keys as needed, and echo our fingerprint to stdout. */
3357 static int
3358 do_list_fingerprint(void)
3360 char buf[FINGERPRINT_LEN+1];
3361 crypto_pk_t *k;
3362 const char *nickname = get_options()->Nickname;
3363 sandbox_disable_getaddrinfo_cache();
3364 if (!server_mode(get_options())) {
3365 log_err(LD_GENERAL,
3366 "Clients don't have long-term identity keys. Exiting.");
3367 return -1;
3369 tor_assert(nickname);
3370 if (init_keys() < 0) {
3371 log_err(LD_GENERAL,"Error initializing keys; exiting.");
3372 return -1;
3374 if (!(k = get_server_identity_key())) {
3375 log_err(LD_GENERAL,"Error: missing identity key.");
3376 return -1;
3378 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
3379 log_err(LD_BUG, "Error computing fingerprint");
3380 return -1;
3382 printf("%s %s\n", nickname, buf);
3383 return 0;
3386 /** Entry point for password hashing: take the desired password from
3387 * the command line, and print its salted hash to stdout. **/
3388 static void
3389 do_hash_password(void)
3392 char output[256];
3393 char key[S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN];
3395 crypto_rand(key, S2K_RFC2440_SPECIFIER_LEN-1);
3396 key[S2K_RFC2440_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
3397 secret_to_key_rfc2440(key+S2K_RFC2440_SPECIFIER_LEN, DIGEST_LEN,
3398 get_options()->command_arg, strlen(get_options()->command_arg),
3399 key);
3400 base16_encode(output, sizeof(output), key, sizeof(key));
3401 printf("16:%s\n",output);
3404 /** Entry point for configuration dumping: write the configuration to
3405 * stdout. */
3406 static int
3407 do_dump_config(void)
3409 const or_options_t *options = get_options();
3410 const char *arg = options->command_arg;
3411 int how;
3412 char *opts;
3414 if (!strcmp(arg, "short")) {
3415 how = OPTIONS_DUMP_MINIMAL;
3416 } else if (!strcmp(arg, "non-builtin")) {
3417 how = OPTIONS_DUMP_DEFAULTS;
3418 } else if (!strcmp(arg, "full")) {
3419 how = OPTIONS_DUMP_ALL;
3420 } else {
3421 fprintf(stderr, "No valid argument to --dump-config found!\n");
3422 fprintf(stderr, "Please select 'short', 'non-builtin', or 'full'.\n");
3424 return -1;
3427 opts = options_dump(options, how);
3428 printf("%s", opts);
3429 tor_free(opts);
3431 return 0;
3434 static void
3435 init_addrinfo(void)
3437 if (! server_mode(get_options()) ||
3438 (get_options()->Address && strlen(get_options()->Address) > 0)) {
3439 /* We don't need to seed our own hostname, because we won't be calling
3440 * resolve_my_address on it.
3442 return;
3444 char hname[256];
3446 // host name to sandbox
3447 gethostname(hname, sizeof(hname));
3448 sandbox_add_addrinfo(hname);
3451 static sandbox_cfg_t*
3452 sandbox_init_filter(void)
3454 const or_options_t *options = get_options();
3455 sandbox_cfg_t *cfg = sandbox_cfg_new();
3456 int i;
3458 sandbox_cfg_allow_openat_filename(&cfg,
3459 get_datadir_fname("cached-status"));
3461 #define OPEN(name) \
3462 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
3464 #define OPEN_DATADIR(name) \
3465 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
3467 #define OPEN_DATADIR2(name, name2) \
3468 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
3470 #define OPEN_DATADIR_SUFFIX(name, suffix) do { \
3471 OPEN_DATADIR(name); \
3472 OPEN_DATADIR(name suffix); \
3473 } while (0)
3475 #define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
3476 OPEN_DATADIR2(name, name2); \
3477 OPEN_DATADIR2(name, name2 suffix); \
3478 } while (0)
3480 OPEN(options->DataDirectory);
3481 OPEN_DATADIR("keys");
3482 OPEN_DATADIR_SUFFIX("cached-certs", ".tmp");
3483 OPEN_DATADIR_SUFFIX("cached-consensus", ".tmp");
3484 OPEN_DATADIR_SUFFIX("unverified-consensus", ".tmp");
3485 OPEN_DATADIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
3486 OPEN_DATADIR_SUFFIX("cached-microdesc-consensus", ".tmp");
3487 OPEN_DATADIR_SUFFIX("cached-microdescs", ".tmp");
3488 OPEN_DATADIR_SUFFIX("cached-microdescs.new", ".tmp");
3489 OPEN_DATADIR_SUFFIX("cached-descriptors", ".tmp");
3490 OPEN_DATADIR_SUFFIX("cached-descriptors.new", ".tmp");
3491 OPEN_DATADIR("cached-descriptors.tmp.tmp");
3492 OPEN_DATADIR_SUFFIX("cached-extrainfo", ".tmp");
3493 OPEN_DATADIR_SUFFIX("cached-extrainfo.new", ".tmp");
3494 OPEN_DATADIR("cached-extrainfo.tmp.tmp");
3495 OPEN_DATADIR_SUFFIX("state", ".tmp");
3496 OPEN_DATADIR_SUFFIX("sr-state", ".tmp");
3497 OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
3498 OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
3499 OPEN_DATADIR("key-pinning-journal");
3500 OPEN("/dev/srandom");
3501 OPEN("/dev/urandom");
3502 OPEN("/dev/random");
3503 OPEN("/etc/hosts");
3504 OPEN("/proc/meminfo");
3506 if (options->BridgeAuthoritativeDir)
3507 OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
3509 if (authdir_mode(options))
3510 OPEN_DATADIR("approved-routers");
3512 if (options->ServerDNSResolvConfFile)
3513 sandbox_cfg_allow_open_filename(&cfg,
3514 tor_strdup(options->ServerDNSResolvConfFile));
3515 else
3516 sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
3518 for (i = 0; i < 2; ++i) {
3519 if (get_torrc_fname(i)) {
3520 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(get_torrc_fname(i)));
3524 #define RENAME_SUFFIX(name, suffix) \
3525 sandbox_cfg_allow_rename(&cfg, \
3526 get_datadir_fname(name suffix), \
3527 get_datadir_fname(name))
3529 #define RENAME_SUFFIX2(prefix, name, suffix) \
3530 sandbox_cfg_allow_rename(&cfg, \
3531 get_datadir_fname2(prefix, name suffix), \
3532 get_datadir_fname2(prefix, name))
3534 RENAME_SUFFIX("cached-certs", ".tmp");
3535 RENAME_SUFFIX("cached-consensus", ".tmp");
3536 RENAME_SUFFIX("unverified-consensus", ".tmp");
3537 RENAME_SUFFIX("unverified-microdesc-consensus", ".tmp");
3538 RENAME_SUFFIX("cached-microdesc-consensus", ".tmp");
3539 RENAME_SUFFIX("cached-microdescs", ".tmp");
3540 RENAME_SUFFIX("cached-microdescs", ".new");
3541 RENAME_SUFFIX("cached-microdescs.new", ".tmp");
3542 RENAME_SUFFIX("cached-descriptors", ".tmp");
3543 RENAME_SUFFIX("cached-descriptors", ".new");
3544 RENAME_SUFFIX("cached-descriptors.new", ".tmp");
3545 RENAME_SUFFIX("cached-extrainfo", ".tmp");
3546 RENAME_SUFFIX("cached-extrainfo", ".new");
3547 RENAME_SUFFIX("cached-extrainfo.new", ".tmp");
3548 RENAME_SUFFIX("state", ".tmp");
3549 RENAME_SUFFIX("sr-state", ".tmp");
3550 RENAME_SUFFIX("unparseable-desc", ".tmp");
3551 RENAME_SUFFIX("v3-status-votes", ".tmp");
3553 if (options->BridgeAuthoritativeDir)
3554 RENAME_SUFFIX("networkstatus-bridges", ".tmp");
3556 #define STAT_DATADIR(name) \
3557 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
3559 #define STAT_DATADIR2(name, name2) \
3560 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
3562 STAT_DATADIR(NULL);
3563 STAT_DATADIR("lock");
3564 STAT_DATADIR("state");
3565 STAT_DATADIR("router-stability");
3566 STAT_DATADIR("cached-extrainfo.new");
3569 smartlist_t *files = smartlist_new();
3570 tor_log_get_logfile_names(files);
3571 SMARTLIST_FOREACH(files, char *, file_name, {
3572 /* steals reference */
3573 sandbox_cfg_allow_open_filename(&cfg, file_name);
3575 smartlist_free(files);
3579 smartlist_t *files = smartlist_new();
3580 smartlist_t *dirs = smartlist_new();
3581 hs_service_lists_fnames_for_sandbox(files, dirs);
3582 SMARTLIST_FOREACH(files, char *, file_name, {
3583 char *tmp_name = NULL;
3584 tor_asprintf(&tmp_name, "%s.tmp", file_name);
3585 sandbox_cfg_allow_rename(&cfg,
3586 tor_strdup(tmp_name), tor_strdup(file_name));
3587 /* steals references */
3588 sandbox_cfg_allow_open_filename(&cfg, file_name);
3589 sandbox_cfg_allow_open_filename(&cfg, tmp_name);
3591 SMARTLIST_FOREACH(dirs, char *, dir, {
3592 /* steals reference */
3593 sandbox_cfg_allow_stat_filename(&cfg, dir);
3595 smartlist_free(files);
3596 smartlist_free(dirs);
3600 char *fname;
3601 if ((fname = get_controller_cookie_file_name())) {
3602 sandbox_cfg_allow_open_filename(&cfg, fname);
3604 if ((fname = get_ext_or_auth_cookie_file_name())) {
3605 sandbox_cfg_allow_open_filename(&cfg, fname);
3609 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), port_cfg_t *, port) {
3610 if (!port->is_unix_addr)
3611 continue;
3612 /* When we open an AF_UNIX address, we want permission to open the
3613 * directory that holds it. */
3614 char *dirname = tor_strdup(port->unix_addr);
3615 if (get_parent_directory(dirname) == 0) {
3616 OPEN(dirname);
3618 tor_free(dirname);
3619 sandbox_cfg_allow_chmod_filename(&cfg, tor_strdup(port->unix_addr));
3620 sandbox_cfg_allow_chown_filename(&cfg, tor_strdup(port->unix_addr));
3621 } SMARTLIST_FOREACH_END(port);
3623 if (options->DirPortFrontPage) {
3624 sandbox_cfg_allow_open_filename(&cfg,
3625 tor_strdup(options->DirPortFrontPage));
3628 // orport
3629 if (server_mode(get_options())) {
3631 OPEN_DATADIR2_SUFFIX("keys", "secret_id_key", ".tmp");
3632 OPEN_DATADIR2_SUFFIX("keys", "secret_onion_key", ".tmp");
3633 OPEN_DATADIR2_SUFFIX("keys", "secret_onion_key_ntor", ".tmp");
3634 OPEN_DATADIR2("keys", "secret_id_key.old");
3635 OPEN_DATADIR2("keys", "secret_onion_key.old");
3636 OPEN_DATADIR2("keys", "secret_onion_key_ntor.old");
3638 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_secret_key", ".tmp");
3639 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_secret_key_encrypted",
3640 ".tmp");
3641 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_public_key", ".tmp");
3642 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_secret_key", ".tmp");
3643 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_secret_key_encrypted",
3644 ".tmp");
3645 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_public_key", ".tmp");
3646 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_cert", ".tmp");
3648 OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
3649 OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
3651 OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
3652 OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
3653 OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
3654 OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
3655 OPEN_DATADIR2_SUFFIX("stats", "hidserv-stats", ".tmp");
3657 OPEN_DATADIR("approved-routers");
3658 OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
3659 OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
3660 OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
3662 OPEN("/etc/resolv.conf");
3664 RENAME_SUFFIX("fingerprint", ".tmp");
3665 RENAME_SUFFIX2("keys", "secret_onion_key_ntor", ".tmp");
3666 RENAME_SUFFIX2("keys", "secret_id_key", ".tmp");
3667 RENAME_SUFFIX2("keys", "secret_id_key.old", ".tmp");
3668 RENAME_SUFFIX2("keys", "secret_onion_key", ".tmp");
3669 RENAME_SUFFIX2("keys", "secret_onion_key.old", ".tmp");
3670 RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
3671 RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
3672 RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
3673 RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
3674 RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
3675 RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
3676 RENAME_SUFFIX2("stats", "hidserv-stats", ".tmp");
3677 RENAME_SUFFIX("hashed-fingerprint", ".tmp");
3678 RENAME_SUFFIX("router-stability", ".tmp");
3680 RENAME_SUFFIX2("keys", "ed25519_master_id_secret_key", ".tmp");
3681 RENAME_SUFFIX2("keys", "ed25519_master_id_secret_key_encrypted", ".tmp");
3682 RENAME_SUFFIX2("keys", "ed25519_master_id_public_key", ".tmp");
3683 RENAME_SUFFIX2("keys", "ed25519_signing_secret_key", ".tmp");
3684 RENAME_SUFFIX2("keys", "ed25519_signing_cert", ".tmp");
3686 sandbox_cfg_allow_rename(&cfg,
3687 get_datadir_fname2("keys", "secret_onion_key"),
3688 get_datadir_fname2("keys", "secret_onion_key.old"));
3689 sandbox_cfg_allow_rename(&cfg,
3690 get_datadir_fname2("keys", "secret_onion_key_ntor"),
3691 get_datadir_fname2("keys", "secret_onion_key_ntor.old"));
3693 STAT_DATADIR("keys");
3694 OPEN_DATADIR("stats");
3695 STAT_DATADIR("stats");
3696 STAT_DATADIR2("stats", "dirreq-stats");
3698 consdiffmgr_register_with_sandbox(&cfg);
3701 init_addrinfo();
3703 return cfg;
3706 /** Main entry point for the Tor process. Called from main(). */
3707 /* This function is distinct from main() only so we can link main.c into
3708 * the unittest binary without conflicting with the unittests' main. */
3710 tor_main(int argc, char *argv[])
3712 int result = 0;
3714 #ifdef _WIN32
3715 #ifndef HeapEnableTerminationOnCorruption
3716 #define HeapEnableTerminationOnCorruption 1
3717 #endif
3718 /* On heap corruption, just give up; don't try to play along. */
3719 HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
3720 /* Call SetProcessDEPPolicy to permanently enable DEP.
3721 The function will not resolve on earlier versions of Windows,
3722 and failure is not dangerous. */
3723 HMODULE hMod = GetModuleHandleA("Kernel32.dll");
3724 if (hMod) {
3725 typedef BOOL (WINAPI *PSETDEP)(DWORD);
3726 PSETDEP setdeppolicy = (PSETDEP)GetProcAddress(hMod,
3727 "SetProcessDEPPolicy");
3728 if (setdeppolicy) {
3729 /* PROCESS_DEP_ENABLE | PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION */
3730 setdeppolicy(3);
3733 #endif /* defined(_WIN32) */
3735 configure_backtrace_handler(get_version());
3737 update_approx_time(time(NULL));
3738 tor_threads_init();
3739 tor_compress_init();
3740 init_logging(0);
3741 monotime_init();
3742 #ifdef USE_DMALLOC
3744 /* Instruct OpenSSL to use our internal wrappers for malloc,
3745 realloc and free. */
3746 int r = crypto_use_tor_alloc_functions();
3747 tor_assert(r == 0);
3749 #endif /* defined(USE_DMALLOC) */
3750 #ifdef NT_SERVICE
3752 int done = 0;
3753 result = nt_service_parse_options(argc, argv, &done);
3754 if (done) return result;
3756 #endif /* defined(NT_SERVICE) */
3757 if (tor_init(argc, argv)<0)
3758 return -1;
3760 if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
3761 sandbox_cfg_t* cfg = sandbox_init_filter();
3763 if (sandbox_init(cfg)) {
3764 log_err(LD_BUG,"Failed to create syscall sandbox filter");
3765 return -1;
3768 // registering libevent rng
3769 #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
3770 evutil_secure_rng_set_urandom_device_file(
3771 (char*) sandbox_intern_string("/dev/urandom"));
3772 #endif
3775 switch (get_options()->command) {
3776 case CMD_RUN_TOR:
3777 #ifdef NT_SERVICE
3778 nt_service_set_state(SERVICE_RUNNING);
3779 #endif
3780 result = do_main_loop();
3781 break;
3782 case CMD_KEYGEN:
3783 result = load_ed_keys(get_options(), time(NULL)) < 0;
3784 break;
3785 case CMD_KEY_EXPIRATION:
3786 init_keys();
3787 result = log_cert_expiration();
3788 break;
3789 case CMD_LIST_FINGERPRINT:
3790 result = do_list_fingerprint();
3791 break;
3792 case CMD_HASH_PASSWORD:
3793 do_hash_password();
3794 result = 0;
3795 break;
3796 case CMD_VERIFY_CONFIG:
3797 if (quiet_level == 0)
3798 printf("Configuration was valid\n");
3799 result = 0;
3800 break;
3801 case CMD_DUMP_CONFIG:
3802 result = do_dump_config();
3803 break;
3804 case CMD_RUN_UNITTESTS: /* only set by test.c */
3805 default:
3806 log_warn(LD_BUG,"Illegal command number %d: internal error.",
3807 get_options()->command);
3808 result = -1;
3810 tor_cleanup();
3811 return result;