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-2015, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Toplevel module. Handles signals, multiplexes between
10 * connections, implements main loop, and drives scheduled events.
15 #include "addressmap.h"
16 #include "backtrace.h"
19 #include "channeltls.h"
20 #include "circuitbuild.h"
21 #include "circuitlist.h"
22 #include "circuituse.h"
25 #include "confparse.h"
26 #include "connection.h"
27 #include "connection_edge.h"
28 #include "connection_or.h"
30 #include "cpuworker.h"
31 #include "crypto_s2k.h"
32 #include "directory.h"
37 #include "entrynodes.h"
39 #include "hibernate.h"
42 #include "microdesc.h"
43 #include "networkstatus.h"
48 #include "transports.h"
50 #include "rendclient.h"
51 #include "rendcommon.h"
52 #include "rendservice.h"
55 #include "routerkeys.h"
56 #include "routerlist.h"
57 #include "routerparse.h"
58 #include "scheduler.h"
59 #include "statefile.h"
61 #include "util_process.h"
62 #include "ext_orport.h"
65 #include <openssl/crypto.h>
70 #ifdef HAVE_EVENT2_EVENT_H
71 #include <event2/event.h>
76 #ifdef USE_BUFFEREVENTS
77 #include <event2/bufferevent.h>
81 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
82 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
83 * Coverity. Here's a kludge to unconfuse it.
85 # define __INCLUDE_LEVEL__ 2
87 #include <systemd/sd-daemon.h>
90 void evdns_shutdown(int);
92 /********* PROTOTYPES **********/
94 static void dumpmemusage(int severity
);
95 static void dumpstats(int severity
); /* log stats */
96 static void conn_read_callback(evutil_socket_t fd
, short event
, void *_conn
);
97 static void conn_write_callback(evutil_socket_t fd
, short event
, void *_conn
);
98 static void second_elapsed_callback(periodic_timer_t
*timer
, void *args
);
99 static int conn_close_if_marked(int i
);
100 static void connection_start_reading_from_linked_conn(connection_t
*conn
);
101 static int connection_should_read_from_linked_conn(connection_t
*conn
);
102 static int run_main_loop_until_done(void);
103 static void process_signal(int sig
);
105 /********* START VARIABLES **********/
107 #ifndef USE_BUFFEREVENTS
108 int global_read_bucket
; /**< Max number of bytes I can read this second. */
109 int global_write_bucket
; /**< Max number of bytes I can write this second. */
111 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
112 int global_relayed_read_bucket
;
113 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
114 int global_relayed_write_bucket
;
115 /** What was the read bucket before the last second_elapsed_callback() call?
116 * (used to determine how many bytes we've read). */
117 static int stats_prev_global_read_bucket
;
118 /** What was the write bucket before the last second_elapsed_callback() call?
119 * (used to determine how many bytes we've written). */
120 static int stats_prev_global_write_bucket
;
123 /* DOCDOC stats_prev_n_read */
124 static uint64_t stats_prev_n_read
= 0;
125 /* DOCDOC stats_prev_n_written */
126 static uint64_t stats_prev_n_written
= 0;
128 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
129 /** How many bytes have we read since we started the process? */
130 static uint64_t stats_n_bytes_read
= 0;
131 /** How many bytes have we written since we started the process? */
132 static uint64_t stats_n_bytes_written
= 0;
133 /** What time did this process start up? */
134 time_t time_of_process_start
= 0;
135 /** How many seconds have we been running? */
136 long stats_n_seconds_working
= 0;
138 /** How often will we honor SIGNEWNYM requests? */
139 #define MAX_SIGNEWNYM_RATE 10
140 /** When did we last process a SIGNEWNYM request? */
141 static time_t time_of_last_signewnym
= 0;
142 /** Is there a signewnym request we're currently waiting to handle? */
143 static int signewnym_is_pending
= 0;
144 /** How many times have we called newnym? */
145 static unsigned newnym_epoch
= 0;
147 /** Smartlist of all open connections. */
148 static smartlist_t
*connection_array
= NULL
;
149 /** List of connections that have been marked for close and need to be freed
150 * and removed from connection_array. */
151 static smartlist_t
*closeable_connection_lst
= NULL
;
152 /** List of linked connections that are currently reading data into their
153 * inbuf from their partner's outbuf. */
154 static smartlist_t
*active_linked_connection_lst
= NULL
;
155 /** Flag: Set to true iff we entered the current libevent main loop via
156 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
157 * to handle linked connections. */
158 static int called_loop_once
= 0;
160 /** We set this to 1 when we've opened a circuit, so we can print a log
161 * entry to inform the user that Tor is working. We set it to 0 when
162 * we think the fact that we once opened a circuit doesn't mean we can do so
163 * any longer (a big time jump happened, when we notice our directory is
164 * heinously out-of-date, etc.
166 static int can_complete_circuits
= 0;
168 /** How often do we check for router descriptors that we should download
169 * when we have too little directory info? */
170 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
171 /** How often do we check for router descriptors that we should download
172 * when we have enough directory info? */
173 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
174 /** How often do we 'forgive' undownloadable router descriptors and attempt
175 * to download them again? */
176 #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
178 /** Decides our behavior when no logs are configured/before any
179 * logs have been configured. For 0, we log notice to stdout as normal.
180 * For 1, we log warnings only. For 2, we log nothing.
184 /********* END VARIABLES ************/
186 /****************************************************************************
188 * This section contains accessors and other methods on the connection_array
189 * variables (which are global within this file and unavailable outside it).
191 ****************************************************************************/
193 #if 0 && defined(USE_BUFFEREVENTS)
195 free_old_inbuf(connection_t
*conn
)
200 tor_assert(conn
->outbuf
);
201 tor_assert(buf_datalen(conn
->inbuf
) == 0);
202 tor_assert(buf_datalen(conn
->outbuf
) == 0);
203 buf_free(conn
->inbuf
);
204 buf_free(conn
->outbuf
);
205 conn
->inbuf
= conn
->outbuf
= NULL
;
207 if (conn
->read_event
) {
208 event_del(conn
->read_event
);
209 tor_event_free(conn
->read_event
);
211 if (conn
->write_event
) {
212 event_del(conn
->read_event
);
213 tor_event_free(conn
->write_event
);
215 conn
->read_event
= conn
->write_event
= NULL
;
219 #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
220 /** Remove the kernel-space send and receive buffers for <b>s</b>. For use
223 set_buffer_lengths_to_zero(tor_socket_t s
)
227 if (setsockopt(s
, SOL_SOCKET
, SO_SNDBUF
, (void*)&zero
, sizeof(zero
))) {
228 log_warn(LD_NET
, "Unable to clear SO_SNDBUF");
231 if (setsockopt(s
, SOL_SOCKET
, SO_RCVBUF
, (void*)&zero
, sizeof(zero
))) {
232 log_warn(LD_NET
, "Unable to clear SO_RCVBUF");
239 /** Return 1 if we have successfully built a circuit, and nothing has changed
240 * to make us think that maybe we can't.
243 have_completed_a_circuit(void)
245 return can_complete_circuits
;
248 /** Note that we have successfully built a circuit, so that reachability
249 * testing and introduction points and so on may be attempted. */
251 note_that_we_completed_a_circuit(void)
253 can_complete_circuits
= 1;
256 /** Note that something has happened (like a clock jump, or DisableNetwork) to
257 * make us think that maybe we can't complete circuits. */
259 note_that_we_maybe_cant_complete_circuits(void)
261 can_complete_circuits
= 0;
264 /** Add <b>conn</b> to the array of connections that we can poll on. The
265 * connection's socket must be set; the connection starts out
266 * non-reading and non-writing.
269 connection_add_impl(connection_t
*conn
, int is_connecting
)
272 tor_assert(SOCKET_OK(conn
->s
) ||
274 (conn
->type
== CONN_TYPE_AP
&&
275 TO_EDGE_CONN(conn
)->is_dns_request
));
277 tor_assert(conn
->conn_array_index
== -1); /* can only connection_add once */
278 conn
->conn_array_index
= smartlist_len(connection_array
);
279 smartlist_add(connection_array
, conn
);
281 #ifdef USE_BUFFEREVENTS
282 if (connection_type_uses_bufferevent(conn
)) {
283 if (SOCKET_OK(conn
->s
) && !conn
->linked
) {
286 if (tor_libevent_using_iocp_bufferevents() &&
287 get_options()->UserspaceIOCPBuffers
) {
288 set_buffer_lengths_to_zero(conn
->s
);
292 conn
->bufev
= bufferevent_socket_new(
293 tor_libevent_get_base(),
295 BEV_OPT_DEFER_CALLBACKS
);
297 log_warn(LD_BUG
, "Unable to create socket bufferevent");
298 smartlist_del(connection_array
, conn
->conn_array_index
);
299 conn
->conn_array_index
= -1;
303 /* Put the bufferevent into a "connecting" state so that we'll get
304 * a "connected" event callback on successful write. */
305 bufferevent_socket_connect(conn
->bufev
, NULL
, 0);
307 connection_configure_bufferevent_callbacks(conn
);
308 } else if (conn
->linked
&& conn
->linked_conn
&&
309 connection_type_uses_bufferevent(conn
->linked_conn
)) {
310 tor_assert(!(SOCKET_OK(conn
->s
)));
312 struct bufferevent
*pair
[2] = { NULL
, NULL
};
313 if (bufferevent_pair_new(tor_libevent_get_base(),
314 BEV_OPT_DEFER_CALLBACKS
,
316 log_warn(LD_BUG
, "Unable to create bufferevent pair");
317 smartlist_del(connection_array
, conn
->conn_array_index
);
318 conn
->conn_array_index
= -1;
322 conn
->bufev
= pair
[0];
323 conn
->linked_conn
->bufev
= pair
[1];
324 } /* else the other side already was added, and got a bufferevent_pair */
325 connection_configure_bufferevent_callbacks(conn
);
327 tor_assert(!conn
->linked
);
331 tor_assert(conn
->inbuf
== NULL
);
333 if (conn
->linked_conn
&& conn
->linked_conn
->bufev
)
334 tor_assert(conn
->linked_conn
->inbuf
== NULL
);
337 (void) is_connecting
;
340 if (!HAS_BUFFEREVENT(conn
) && (SOCKET_OK(conn
->s
) || conn
->linked
)) {
341 conn
->read_event
= tor_event_new(tor_libevent_get_base(),
342 conn
->s
, EV_READ
|EV_PERSIST
, conn_read_callback
, conn
);
343 conn
->write_event
= tor_event_new(tor_libevent_get_base(),
344 conn
->s
, EV_WRITE
|EV_PERSIST
, conn_write_callback
, conn
);
345 /* XXXX CHECK FOR NULL RETURN! */
348 log_debug(LD_NET
,"new conn type %s, socket %d, address %s, n_conns %d.",
349 conn_type_to_string(conn
->type
), (int)conn
->s
, conn
->address
,
350 smartlist_len(connection_array
));
355 /** Tell libevent that we don't care about <b>conn</b> any more. */
357 connection_unregister_events(connection_t
*conn
)
359 if (conn
->read_event
) {
360 if (event_del(conn
->read_event
))
361 log_warn(LD_BUG
, "Error removing read event for %d", (int)conn
->s
);
362 tor_free(conn
->read_event
);
364 if (conn
->write_event
) {
365 if (event_del(conn
->write_event
))
366 log_warn(LD_BUG
, "Error removing write event for %d", (int)conn
->s
);
367 tor_free(conn
->write_event
);
369 #ifdef USE_BUFFEREVENTS
371 bufferevent_free(conn
->bufev
);
375 if (conn
->type
== CONN_TYPE_AP_DNS_LISTENER
) {
376 dnsserv_close_listener(conn
);
380 /** Remove the connection from the global list, and remove the
381 * corresponding poll entry. Calling this function will shift the last
382 * connection (if any) into the position occupied by conn.
385 connection_remove(connection_t
*conn
)
392 log_debug(LD_NET
,"removing socket %d (type %s), n_conns now %d",
393 (int)conn
->s
, conn_type_to_string(conn
->type
),
394 smartlist_len(connection_array
));
396 if (conn
->type
== CONN_TYPE_AP
&& conn
->socket_family
== AF_UNIX
) {
397 log_info(LD_NET
, "Closing SOCKS SocksSocket connection");
400 control_event_conn_bandwidth(conn
);
402 tor_assert(conn
->conn_array_index
>= 0);
403 current_index
= conn
->conn_array_index
;
404 connection_unregister_events(conn
); /* This is redundant, but cheap. */
405 if (current_index
== smartlist_len(connection_array
)-1) { /* at the end */
406 smartlist_del(connection_array
, current_index
);
410 /* replace this one with the one at the end */
411 smartlist_del(connection_array
, current_index
);
412 tmp
= smartlist_get(connection_array
, current_index
);
413 tmp
->conn_array_index
= current_index
;
418 /** If <b>conn</b> is an edge conn, remove it from the list
419 * of conn's on this circuit. If it's not on an edge,
420 * flush and send destroys for all circuits on this conn.
422 * Remove it from connection_array (if applicable) and
423 * from closeable_connection_list.
428 connection_unlink(connection_t
*conn
)
430 connection_about_to_close_connection(conn
);
431 if (conn
->conn_array_index
>= 0) {
432 connection_remove(conn
);
434 if (conn
->linked_conn
) {
435 conn
->linked_conn
->linked_conn
= NULL
;
436 if (! conn
->linked_conn
->marked_for_close
&&
437 conn
->linked_conn
->reading_from_linked_conn
)
438 connection_start_reading(conn
->linked_conn
);
439 conn
->linked_conn
= NULL
;
441 smartlist_remove(closeable_connection_lst
, conn
);
442 smartlist_remove(active_linked_connection_lst
, conn
);
443 if (conn
->type
== CONN_TYPE_EXIT
) {
444 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn
));
446 if (conn
->type
== CONN_TYPE_OR
) {
447 if (!tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
))
448 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
449 /* connection_unlink() can only get called if the connection
450 * was already on the closeable list, and it got there by
451 * connection_mark_for_close(), which was called from
452 * connection_or_close_normally() or
453 * connection_or_close_for_error(), so the channel should
454 * already be in CHANNEL_STATE_CLOSING, and then the
455 * connection_about_to_close_connection() goes to
456 * connection_or_about_to_close(), which calls channel_closed()
457 * to notify the channel_t layer, and closed the channel, so
458 * nothing more to do here to deal with the channel associated
462 connection_free(conn
);
465 /** Initialize the global connection list, closeable connection list,
466 * and active connection list. */
468 init_connection_lists(void)
470 if (!connection_array
)
471 connection_array
= smartlist_new();
472 if (!closeable_connection_lst
)
473 closeable_connection_lst
= smartlist_new();
474 if (!active_linked_connection_lst
)
475 active_linked_connection_lst
= smartlist_new();
478 /** Schedule <b>conn</b> to be closed. **/
480 add_connection_to_closeable_list(connection_t
*conn
)
482 tor_assert(!smartlist_contains(closeable_connection_lst
, conn
));
483 tor_assert(conn
->marked_for_close
);
484 assert_connection_ok(conn
, time(NULL
));
485 smartlist_add(closeable_connection_lst
, conn
);
488 /** Return 1 if conn is on the closeable list, else return 0. */
490 connection_is_on_closeable_list(connection_t
*conn
)
492 return smartlist_contains(closeable_connection_lst
, conn
);
495 /** Return true iff conn is in the current poll array. */
497 connection_in_array(connection_t
*conn
)
499 return smartlist_contains(connection_array
, conn
);
502 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
503 * to the length of the array. <b>*array</b> and <b>*n</b> must not
507 get_connection_array(void)
509 if (!connection_array
)
510 connection_array
= smartlist_new();
511 return connection_array
;
514 /** Provides the traffic read and written over the life of the process. */
517 get_bytes_read
,(void))
519 return stats_n_bytes_read
;
522 /* DOCDOC get_bytes_written */
524 get_bytes_written
,(void))
526 return stats_n_bytes_written
;
529 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
530 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
533 connection_watch_events(connection_t
*conn
, watchable_events_t events
)
535 IF_HAS_BUFFEREVENT(conn
, {
536 short ev
= ((short)events
) & (EV_READ
|EV_WRITE
);
537 short old_ev
= bufferevent_get_enabled(conn
->bufev
);
538 if ((ev
& ~old_ev
) != 0) {
539 bufferevent_enable(conn
->bufev
, ev
);
541 if ((old_ev
& ~ev
) != 0) {
542 bufferevent_disable(conn
->bufev
, old_ev
& ~ev
);
546 if (events
& READ_EVENT
)
547 connection_start_reading(conn
);
549 connection_stop_reading(conn
);
551 if (events
& WRITE_EVENT
)
552 connection_start_writing(conn
);
554 connection_stop_writing(conn
);
557 /** Return true iff <b>conn</b> is listening for read events. */
559 connection_is_reading(connection_t
*conn
)
563 IF_HAS_BUFFEREVENT(conn
,
564 return (bufferevent_get_enabled(conn
->bufev
) & EV_READ
) != 0;
566 return conn
->reading_from_linked_conn
||
567 (conn
->read_event
&& event_pending(conn
->read_event
, EV_READ
, NULL
));
570 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
572 connection_stop_reading
,(connection_t
*conn
))
576 IF_HAS_BUFFEREVENT(conn
, {
577 bufferevent_disable(conn
->bufev
, EV_READ
);
581 tor_assert(conn
->read_event
);
584 conn
->reading_from_linked_conn
= 0;
585 connection_stop_reading_from_linked_conn(conn
);
587 if (event_del(conn
->read_event
))
588 log_warn(LD_NET
, "Error from libevent setting read event state for %d "
591 tor_socket_strerror(tor_socket_errno(conn
->s
)));
595 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
597 connection_start_reading
,(connection_t
*conn
))
601 IF_HAS_BUFFEREVENT(conn
, {
602 bufferevent_enable(conn
->bufev
, EV_READ
);
606 tor_assert(conn
->read_event
);
609 conn
->reading_from_linked_conn
= 1;
610 if (connection_should_read_from_linked_conn(conn
))
611 connection_start_reading_from_linked_conn(conn
);
613 if (event_add(conn
->read_event
, NULL
))
614 log_warn(LD_NET
, "Error from libevent setting read event state for %d "
617 tor_socket_strerror(tor_socket_errno(conn
->s
)));
621 /** Return true iff <b>conn</b> is listening for write events. */
623 connection_is_writing(connection_t
*conn
)
627 IF_HAS_BUFFEREVENT(conn
,
628 return (bufferevent_get_enabled(conn
->bufev
) & EV_WRITE
) != 0;
631 return conn
->writing_to_linked_conn
||
632 (conn
->write_event
&& event_pending(conn
->write_event
, EV_WRITE
, NULL
));
635 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
637 connection_stop_writing
,(connection_t
*conn
))
641 IF_HAS_BUFFEREVENT(conn
, {
642 bufferevent_disable(conn
->bufev
, EV_WRITE
);
646 tor_assert(conn
->write_event
);
649 conn
->writing_to_linked_conn
= 0;
650 if (conn
->linked_conn
)
651 connection_stop_reading_from_linked_conn(conn
->linked_conn
);
653 if (event_del(conn
->write_event
))
654 log_warn(LD_NET
, "Error from libevent setting write event state for %d "
657 tor_socket_strerror(tor_socket_errno(conn
->s
)));
661 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
663 connection_start_writing
,(connection_t
*conn
))
667 IF_HAS_BUFFEREVENT(conn
, {
668 bufferevent_enable(conn
->bufev
, EV_WRITE
);
672 tor_assert(conn
->write_event
);
675 conn
->writing_to_linked_conn
= 1;
676 if (conn
->linked_conn
&&
677 connection_should_read_from_linked_conn(conn
->linked_conn
))
678 connection_start_reading_from_linked_conn(conn
->linked_conn
);
680 if (event_add(conn
->write_event
, NULL
))
681 log_warn(LD_NET
, "Error from libevent setting write event state for %d "
684 tor_socket_strerror(tor_socket_errno(conn
->s
)));
688 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
689 * linked to it would be good and feasible. (Reading is "feasible" if the
690 * other conn exists and has data in its outbuf, and is "good" if we have our
691 * reading_from_linked_conn flag set and the other conn has its
692 * writing_to_linked_conn flag set.)*/
694 connection_should_read_from_linked_conn(connection_t
*conn
)
696 if (conn
->linked
&& conn
->reading_from_linked_conn
) {
697 if (! conn
->linked_conn
||
698 (conn
->linked_conn
->writing_to_linked_conn
&&
699 buf_datalen(conn
->linked_conn
->outbuf
)))
705 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
706 * its linked connection, if it is not doing so already. Called by
707 * connection_start_reading and connection_start_writing as appropriate. */
709 connection_start_reading_from_linked_conn(connection_t
*conn
)
712 tor_assert(conn
->linked
== 1);
714 if (!conn
->active_on_link
) {
715 conn
->active_on_link
= 1;
716 smartlist_add(active_linked_connection_lst
, conn
);
717 if (!called_loop_once
) {
718 /* This is the first event on the list; we won't be in LOOP_ONCE mode,
719 * so we need to make sure that the event_base_loop() actually exits at
720 * the end of its run through the current connections and lets us
721 * activate read events for linked connections. */
722 struct timeval tv
= { 0, 0 };
723 tor_event_base_loopexit(tor_libevent_get_base(), &tv
);
726 tor_assert(smartlist_contains(active_linked_connection_lst
, conn
));
730 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
731 * connection, if is currently doing so. Called by connection_stop_reading,
732 * connection_stop_writing, and connection_read. */
734 connection_stop_reading_from_linked_conn(connection_t
*conn
)
737 tor_assert(conn
->linked
== 1);
739 if (conn
->active_on_link
) {
740 conn
->active_on_link
= 0;
741 /* FFFF We could keep an index here so we can smartlist_del
742 * cleanly. On the other hand, this doesn't show up on profiles,
743 * so let's leave it alone for now. */
744 smartlist_remove(active_linked_connection_lst
, conn
);
746 tor_assert(!smartlist_contains(active_linked_connection_lst
, conn
));
750 /** Close all connections that have been scheduled to get closed. */
752 close_closeable_connections(void)
755 for (i
= 0; i
< smartlist_len(closeable_connection_lst
); ) {
756 connection_t
*conn
= smartlist_get(closeable_connection_lst
, i
);
757 if (conn
->conn_array_index
< 0) {
758 connection_unlink(conn
); /* blow it away right now */
760 if (!conn_close_if_marked(conn
->conn_array_index
))
766 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
767 * some data to read. */
769 conn_read_callback(evutil_socket_t fd
, short event
, void *_conn
)
771 connection_t
*conn
= _conn
;
775 log_debug(LD_NET
,"socket %d wants to read.",(int)conn
->s
);
777 /* assert_connection_ok(conn, time(NULL)); */
779 if (connection_handle_read(conn
) < 0) {
780 if (!conn
->marked_for_close
) {
782 log_warn(LD_BUG
,"Unhandled error on read for %s connection "
784 conn_type_to_string(conn
->type
), (int)conn
->s
);
785 tor_fragile_assert();
787 if (CONN_IS_EDGE(conn
))
788 connection_edge_end_errno(TO_EDGE_CONN(conn
));
789 connection_mark_for_close(conn
);
792 assert_connection_ok(conn
, time(NULL
));
794 if (smartlist_len(closeable_connection_lst
))
795 close_closeable_connections();
798 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
799 * some data to write. */
801 conn_write_callback(evutil_socket_t fd
, short events
, void *_conn
)
803 connection_t
*conn
= _conn
;
807 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "socket %d wants to write.",
810 /* assert_connection_ok(conn, time(NULL)); */
812 if (connection_handle_write(conn
, 0) < 0) {
813 if (!conn
->marked_for_close
) {
814 /* this connection is broken. remove it. */
815 log_fn(LOG_WARN
,LD_BUG
,
816 "unhandled error on write for %s connection (fd %d); removing",
817 conn_type_to_string(conn
->type
), (int)conn
->s
);
818 tor_fragile_assert();
819 if (CONN_IS_EDGE(conn
)) {
820 /* otherwise we cry wolf about duplicate close */
821 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
822 if (!edge_conn
->end_reason
)
823 edge_conn
->end_reason
= END_STREAM_REASON_INTERNAL
;
824 edge_conn
->edge_has_sent_end
= 1;
826 connection_close_immediate(conn
); /* So we don't try to flush. */
827 connection_mark_for_close(conn
);
830 assert_connection_ok(conn
, time(NULL
));
832 if (smartlist_len(closeable_connection_lst
))
833 close_closeable_connections();
836 /** If the connection at connection_array[i] is marked for close, then:
837 * - If it has data that it wants to flush, try to flush it.
838 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
839 * true, then leave the connection open and return.
840 * - Otherwise, remove the connection from connection_array and from
841 * all other lists, close it, and free it.
842 * Returns 1 if the connection was closed, 0 otherwise.
845 conn_close_if_marked(int i
)
851 conn
= smartlist_get(connection_array
, i
);
852 if (!conn
->marked_for_close
)
853 return 0; /* nothing to see here, move along */
855 assert_connection_ok(conn
, now
);
856 /* assert_all_pending_dns_resolves_ok(); */
858 #ifdef USE_BUFFEREVENTS
860 if (conn
->hold_open_until_flushed
&&
861 evbuffer_get_length(bufferevent_get_output(conn
->bufev
))) {
862 /* don't close yet. */
865 if (conn
->linked_conn
&& ! conn
->linked_conn
->marked_for_close
) {
866 /* We need to do this explicitly so that the linked connection
867 * notices that there was an EOF. */
868 bufferevent_flush(conn
->bufev
, EV_WRITE
, BEV_FINISHED
);
873 log_debug(LD_NET
,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT
").",
876 /* If the connection we are about to close was trying to connect to
877 a proxy server and failed, the client won't be able to use that
878 proxy. We should warn the user about this. */
879 if (conn
->proxy_state
== PROXY_INFANT
)
880 log_failed_proxy_connection(conn
);
882 IF_HAS_BUFFEREVENT(conn
, goto unlink
);
883 if ((SOCKET_OK(conn
->s
) || conn
->linked_conn
) &&
884 connection_wants_to_flush(conn
)) {
885 /* s == -1 means it's an incomplete edge connection, or that the socket
886 * has already been closed as unflushable. */
887 ssize_t sz
= connection_bucket_write_limit(conn
, now
);
888 if (!conn
->hold_open_until_flushed
)
890 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
891 "to flush %d bytes. (Marked at %s:%d)",
892 escaped_safe_str_client(conn
->address
),
893 (int)conn
->s
, conn_type_to_string(conn
->type
), conn
->state
,
894 (int)conn
->outbuf_flushlen
,
895 conn
->marked_for_close_file
, conn
->marked_for_close
);
896 if (conn
->linked_conn
) {
897 retval
= move_buf_to_buf(conn
->linked_conn
->inbuf
, conn
->outbuf
,
898 &conn
->outbuf_flushlen
);
900 /* The linked conn will notice that it has data when it notices that
902 connection_start_reading_from_linked_conn(conn
->linked_conn
);
904 log_debug(LD_GENERAL
, "Flushed last %d bytes from a linked conn; "
905 "%d left; flushlen %d; wants-to-flush==%d", retval
,
906 (int)connection_get_outbuf_len(conn
),
907 (int)conn
->outbuf_flushlen
,
908 connection_wants_to_flush(conn
));
909 } else if (connection_speaks_cells(conn
)) {
910 if (conn
->state
== OR_CONN_STATE_OPEN
) {
911 retval
= flush_buf_tls(TO_OR_CONN(conn
)->tls
, conn
->outbuf
, sz
,
912 &conn
->outbuf_flushlen
);
914 retval
= -1; /* never flush non-open broken tls connections */
916 retval
= flush_buf(conn
->s
, conn
->outbuf
, sz
, &conn
->outbuf_flushlen
);
918 if (retval
>= 0 && /* Technically, we could survive things like
919 TLS_WANT_WRITE here. But don't bother for now. */
920 conn
->hold_open_until_flushed
&& connection_wants_to_flush(conn
)) {
922 LOG_FN_CONN(conn
, (LOG_INFO
,LD_NET
,
923 "Holding conn (fd %d) open for more flushing.",
925 conn
->timestamp_lastwritten
= now
; /* reset so we can flush more */
926 } else if (sz
== 0) {
927 /* Also, retval==0. If we get here, we didn't want to write anything
928 * (because of rate-limiting) and we didn't. */
930 /* Connection must flush before closing, but it's being rate-limited.
931 * Let's remove from Libevent, and mark it as blocked on bandwidth
932 * so it will be re-added on next token bucket refill. Prevents
933 * busy Libevent loops where we keep ending up here and returning
934 * 0 until we are no longer blocked on bandwidth.
936 if (connection_is_writing(conn
)) {
937 conn
->write_blocked_on_bw
= 1;
938 connection_stop_writing(conn
);
940 if (connection_is_reading(conn
)) {
941 /* XXXX024 We should make this code unreachable; if a connection is
942 * marked for close and flushing, there is no point in reading to it
943 * at all. Further, checking at this point is a bit of a hack: it
944 * would make much more sense to react in
945 * connection_handle_read_impl, or to just stop reading in
948 #define MARKED_READING_RATE 180
949 static ratelim_t marked_read_lim
= RATELIM_INIT(MARKED_READING_RATE
);
951 if ((m
= rate_limit_log(&marked_read_lim
, now
))) {
952 log_warn(LD_BUG
, "Marked connection (fd %d, type %s, state %s) "
953 "is still reading; that shouldn't happen.%s",
954 (int)conn
->s
, conn_type_to_string(conn
->type
),
955 conn_state_to_string(conn
->type
, conn
->state
), m
);
959 conn
->read_blocked_on_bw
= 1;
960 connection_stop_reading(conn
);
965 if (connection_wants_to_flush(conn
)) {
966 log_fn(LOG_INFO
, LD_NET
, "We stalled too much while trying to write %d "
967 "bytes to address %s. If this happens a lot, either "
968 "something is wrong with your network connection, or "
969 "something is wrong with theirs. "
970 "(fd %d, type %s, state %d, marked at %s:%d).",
971 (int)connection_get_outbuf_len(conn
),
972 escaped_safe_str_client(conn
->address
),
973 (int)conn
->s
, conn_type_to_string(conn
->type
), conn
->state
,
974 conn
->marked_for_close_file
,
975 conn
->marked_for_close
);
979 #ifdef USE_BUFFEREVENTS
982 connection_unlink(conn
); /* unlink, remove, free */
986 /** Implementation for directory_all_unreachable. This is done in a callback,
987 * since otherwise it would complicate Tor's control-flow graph beyond all
991 directory_all_unreachable_cb(evutil_socket_t fd
, short event
, void *arg
)
999 while ((conn
= connection_get_by_type_state(CONN_TYPE_AP
,
1000 AP_CONN_STATE_CIRCUIT_WAIT
))) {
1001 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(conn
);
1003 "Is your network connection down? "
1004 "Failing connection to '%s:%d'.",
1005 safe_str_client(entry_conn
->socks_request
->address
),
1006 entry_conn
->socks_request
->port
);
1007 connection_mark_unattached_ap(entry_conn
,
1008 END_STREAM_REASON_NET_UNREACHABLE
);
1010 control_event_general_error("DIR_ALL_UNREACHABLE");
1013 static struct event
*directory_all_unreachable_cb_event
= NULL
;
1015 /** We've just tried every dirserver we know about, and none of
1016 * them were reachable. Assume the network is down. Change state
1017 * so next time an application connection arrives we'll delay it
1018 * and try another directory fetch. Kill off all the circuit_wait
1019 * streams that are waiting now, since they will all timeout anyway.
1022 directory_all_unreachable(time_t now
)
1026 stats_n_seconds_working
=0; /* reset it */
1028 if (!directory_all_unreachable_cb_event
) {
1029 directory_all_unreachable_cb_event
=
1030 tor_event_new(tor_libevent_get_base(),
1031 -1, EV_READ
, directory_all_unreachable_cb
, NULL
);
1032 tor_assert(directory_all_unreachable_cb_event
);
1035 event_active(directory_all_unreachable_cb_event
, EV_READ
, 1);
1038 /** This function is called whenever we successfully pull down some new
1039 * network statuses or server descriptors. */
1041 directory_info_has_arrived(time_t now
, int from_cache
)
1043 const or_options_t
*options
= get_options();
1045 if (!router_have_minimum_dir_info()) {
1046 int quiet
= from_cache
||
1047 directory_too_idle_to_fetch_descriptors(options
, now
);
1048 tor_log(quiet
? LOG_INFO
: LOG_NOTICE
, LD_DIR
,
1049 "I learned some more directory information, but not enough to "
1050 "build a circuit: %s", get_dir_info_status_string());
1051 update_all_descriptor_downloads(now
);
1054 if (directory_fetches_from_authorities(options
)) {
1055 update_all_descriptor_downloads(now
);
1058 /* if we have enough dir info, then update our guard status with
1059 * whatever we just learned. */
1060 entry_guards_compute_status(options
, now
);
1061 /* Don't even bother trying to get extrainfo until the rest of our
1062 * directory info is up-to-date */
1063 if (options
->DownloadExtraInfo
)
1064 update_extrainfo_downloads(now
);
1067 if (server_mode(options
) && !net_is_disabled() && !from_cache
&&
1068 (have_completed_a_circuit() || !any_predicted_circuits(now
)))
1069 consider_testing_reachability(1, 1);
1072 /** Perform regular maintenance tasks for a single connection. This
1073 * function gets run once per second per connection by run_scheduled_events.
1076 run_connection_housekeeping(int i
, time_t now
)
1079 connection_t
*conn
= smartlist_get(connection_array
, i
);
1080 const or_options_t
*options
= get_options();
1081 or_connection_t
*or_conn
;
1082 channel_t
*chan
= NULL
;
1083 int have_any_circuits
;
1084 int past_keepalive
=
1085 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
;
1087 if (conn
->outbuf
&& !connection_get_outbuf_len(conn
) &&
1088 conn
->type
== CONN_TYPE_OR
)
1089 TO_OR_CONN(conn
)->timestamp_lastempty
= now
;
1091 if (conn
->marked_for_close
) {
1092 /* nothing to do here */
1096 /* Expire any directory connections that haven't been active (sent
1097 * if a server or received if a client) for 5 min */
1098 if (conn
->type
== CONN_TYPE_DIR
&&
1099 ((DIR_CONN_IS_SERVER(conn
) &&
1100 conn
->timestamp_lastwritten
1101 + options
->TestingDirConnectionMaxStall
< now
) ||
1102 (!DIR_CONN_IS_SERVER(conn
) &&
1103 conn
->timestamp_lastread
1104 + options
->TestingDirConnectionMaxStall
< now
))) {
1105 log_info(LD_DIR
,"Expiring wedged directory conn (fd %d, purpose %d)",
1106 (int)conn
->s
, conn
->purpose
);
1107 /* This check is temporary; it's to let us know whether we should consider
1108 * parsing partial serverdesc responses. */
1109 if (conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
1110 connection_get_inbuf_len(conn
) >= 1024) {
1111 log_info(LD_DIR
,"Trying to extract information from wedged server desc "
1113 connection_dir_reached_eof(TO_DIR_CONN(conn
));
1115 connection_mark_for_close(conn
);
1120 if (!connection_speaks_cells(conn
))
1121 return; /* we're all done here, the rest is just for OR conns */
1123 /* If we haven't written to an OR connection for a while, then either nuke
1124 the connection or send a keepalive, depending. */
1126 or_conn
= TO_OR_CONN(conn
);
1127 #ifdef USE_BUFFEREVENTS
1128 tor_assert(conn
->bufev
);
1130 tor_assert(conn
->outbuf
);
1133 chan
= TLS_CHAN_TO_BASE(or_conn
->chan
);
1136 if (channel_num_circuits(chan
) != 0) {
1137 have_any_circuits
= 1;
1138 chan
->timestamp_last_had_circuits
= now
;
1140 have_any_circuits
= 0;
1143 if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn
->chan
)) &&
1144 ! have_any_circuits
) {
1145 /* It's bad for new circuits, and has no unmarked circuits on it:
1148 "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1149 (int)conn
->s
, conn
->address
, conn
->port
);
1150 if (conn
->state
== OR_CONN_STATE_CONNECTING
)
1151 connection_or_connect_failed(TO_OR_CONN(conn
),
1152 END_OR_CONN_REASON_TIMEOUT
,
1153 "Tor gave up on the connection");
1154 connection_or_close_normally(TO_OR_CONN(conn
), 1);
1155 } else if (!connection_state_is_open(conn
)) {
1156 if (past_keepalive
) {
1157 /* We never managed to actually get this connection open and happy. */
1158 log_info(LD_OR
,"Expiring non-open OR connection to fd %d (%s:%d).",
1159 (int)conn
->s
,conn
->address
, conn
->port
);
1160 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1162 } else if (we_are_hibernating() &&
1163 ! have_any_circuits
&&
1164 !connection_get_outbuf_len(conn
)) {
1165 /* We're hibernating, there's no circuits, and nothing to flush.*/
1166 log_info(LD_OR
,"Expiring non-used OR connection to fd %d (%s:%d) "
1167 "[Hibernating or exiting].",
1168 (int)conn
->s
,conn
->address
, conn
->port
);
1169 connection_or_close_normally(TO_OR_CONN(conn
), 1);
1170 } else if (!have_any_circuits
&&
1171 now
- or_conn
->idle_timeout
>=
1172 chan
->timestamp_last_had_circuits
) {
1173 log_info(LD_OR
,"Expiring non-used OR connection to fd %d (%s:%d) "
1174 "[no circuits for %d; timeout %d; %scanonical].",
1175 (int)conn
->s
, conn
->address
, conn
->port
,
1176 (int)(now
- chan
->timestamp_last_had_circuits
),
1177 or_conn
->idle_timeout
,
1178 or_conn
->is_canonical
? "" : "non");
1179 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1181 now
>= or_conn
->timestamp_lastempty
+ options
->KeepalivePeriod
*10 &&
1182 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
*10) {
1183 log_fn(LOG_PROTOCOL_WARN
,LD_PROTOCOL
,
1184 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1185 "flush; %d seconds since last write)",
1186 (int)conn
->s
, conn
->address
, conn
->port
,
1187 (int)connection_get_outbuf_len(conn
),
1188 (int)(now
-conn
->timestamp_lastwritten
));
1189 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1190 } else if (past_keepalive
&& !connection_get_outbuf_len(conn
)) {
1191 /* send a padding cell */
1192 log_fn(LOG_DEBUG
,LD_OR
,"Sending keepalive to (%s:%d)",
1193 conn
->address
, conn
->port
);
1194 memset(&cell
,0,sizeof(cell_t
));
1195 cell
.command
= CELL_PADDING
;
1196 connection_or_write_cell_to_buf(&cell
, or_conn
);
1200 /** Honor a NEWNYM request: make future requests unlinkable to past
1203 signewnym_impl(time_t now
)
1205 const or_options_t
*options
= get_options();
1206 if (!proxy_mode(options
)) {
1207 log_info(LD_CONTROL
, "Ignoring SIGNAL NEWNYM because client functionality "
1212 circuit_mark_all_dirty_circs_as_unusable();
1213 addressmap_clear_transient();
1214 rend_client_purge_state();
1215 time_of_last_signewnym
= now
;
1216 signewnym_is_pending
= 0;
1220 control_event_signal(SIGNEWNYM
);
1223 /** Return the number of times that signewnym has been called. */
1225 get_signewnym_epoch(void)
1227 return newnym_epoch
;
1231 time_t last_rotated_x509_certificate
;
1232 time_t check_v3_certificate
;
1233 time_t check_listeners
;
1234 time_t download_networkstatus
;
1235 time_t try_getting_descriptors
;
1236 time_t reset_descriptor_failures
;
1238 time_t write_bridge_status_file
;
1239 time_t downrate_stability
;
1240 time_t save_stability
;
1241 time_t clean_caches
;
1242 time_t recheck_bandwidth
;
1243 time_t check_for_expired_networkstatus
;
1244 time_t write_stats_files
;
1245 time_t write_bridge_stats
;
1246 time_t check_port_forwarding
;
1247 time_t launch_reachability_tests
;
1248 time_t retry_dns_init
;
1249 time_t next_heartbeat
;
1250 time_t check_descriptor
;
1251 /** When do we next launch DNS wildcarding checks? */
1252 time_t check_for_correct_dns
;
1253 /** When do we next make sure our Ed25519 keys aren't about to expire? */
1254 time_t check_ed_keys
;
1258 static time_to_t time_to
= {
1259 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1262 /** Reset all the time_to's so we'll do all our actions again as if we
1264 * Useful if our clock just moved back a long time from the future,
1265 * so we don't wait until that future arrives again before acting.
1268 reset_all_main_loop_timers(void)
1270 memset(&time_to
, 0, sizeof(time_to
));
1274 * Update our schedule so that we'll check whether we need to update our
1275 * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
1279 reschedule_descriptor_update_check(void)
1281 time_to
.check_descriptor
= 0;
1285 * Update our schedule so that we'll check whether we need to fetch directory
1289 reschedule_directory_downloads(void)
1291 time_to
.download_networkstatus
= 0;
1292 time_to
.try_getting_descriptors
= 0;
1295 /** Perform regular maintenance tasks. This function gets run once per
1296 * second by second_elapsed_callback().
1299 run_scheduled_events(time_t now
)
1301 static int should_init_bridge_stats
= 1;
1302 const or_options_t
*options
= get_options();
1304 int is_server
= server_mode(options
);
1308 /* 0. See if we've been asked to shut down and our timeout has
1309 * expired; or if our bandwidth limits are exhausted and we
1310 * should hibernate; or if it's time to wake up from hibernation.
1312 consider_hibernation(now
);
1314 /* 0b. If we've deferred a signewnym, make sure it gets handled
1316 if (signewnym_is_pending
&&
1317 time_of_last_signewnym
+ MAX_SIGNEWNYM_RATE
<= now
) {
1318 log_info(LD_CONTROL
, "Honoring delayed NEWNYM request");
1319 signewnym_impl(now
);
1322 /* 0c. If we've deferred log messages for the controller, handle them now */
1323 flush_pending_log_callbacks();
1325 /* 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
1326 * shut down and restart all cpuworkers, and update the directory if
1330 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME
< now
) {
1331 log_info(LD_GENERAL
,"Rotating onion key.");
1333 cpuworkers_rotate_keyinfo();
1334 if (router_rebuild_descriptor(1)<0) {
1335 log_info(LD_CONFIG
, "Couldn't rebuild router descriptor");
1337 if (advertised_server_mode() && !options
->DisableNetwork
)
1338 router_upload_dir_desc_to_dirservers(0);
1341 if (is_server
&& time_to
.check_ed_keys
< now
) {
1342 if (should_make_new_ed_keys(options
, now
)) {
1343 if (load_ed_keys(options
, now
) < 0 ||
1344 generate_ed_link_cert(options
, now
)) {
1345 log_err(LD_OR
, "Unable to update Ed25519 keys! Exiting.");
1350 time_to
.check_ed_keys
= now
+ 30;
1353 if (!should_delay_dir_fetches(options
, NULL
) &&
1354 time_to
.try_getting_descriptors
< now
) {
1355 update_all_descriptor_downloads(now
);
1356 update_extrainfo_downloads(now
);
1357 if (router_have_minimum_dir_info())
1358 time_to
.try_getting_descriptors
= now
+ LAZY_DESCRIPTOR_RETRY_INTERVAL
;
1360 time_to
.try_getting_descriptors
= now
+ GREEDY_DESCRIPTOR_RETRY_INTERVAL
;
1363 if (time_to
.reset_descriptor_failures
< now
) {
1364 router_reset_descriptor_download_failures();
1365 time_to
.reset_descriptor_failures
=
1366 now
+ DESCRIPTOR_FAILURE_RESET_INTERVAL
;
1369 if (options
->UseBridges
&& !options
->DisableNetwork
)
1370 fetch_bridge_descriptors(options
, now
);
1372 /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1374 if (!time_to
.last_rotated_x509_certificate
)
1375 time_to
.last_rotated_x509_certificate
= now
;
1376 if (time_to
.last_rotated_x509_certificate
+
1377 MAX_SSL_KEY_LIFETIME_INTERNAL
< now
) {
1378 log_info(LD_GENERAL
,"Rotating tls context.");
1379 if (router_initialize_tls_context() < 0) {
1380 log_warn(LD_BUG
, "Error reinitializing TLS context");
1381 /* XXX is it a bug here, that we just keep going? -RD */
1383 time_to
.last_rotated_x509_certificate
= now
;
1384 /* We also make sure to rotate the TLS connections themselves if they've
1385 * been up for too long -- but that's done via is_bad_for_new_circs in
1386 * connection_run_housekeeping() above. */
1389 if (time_to
.add_entropy
< now
) {
1390 if (time_to
.add_entropy
) {
1391 /* We already seeded once, so don't die on failure. */
1394 /** How often do we add more entropy to OpenSSL's RNG pool? */
1395 #define ENTROPY_INTERVAL (60*60)
1396 time_to
.add_entropy
= now
+ ENTROPY_INTERVAL
;
1399 /* 1c. If we have to change the accounting interval or record
1400 * bandwidth used in this accounting interval, do so. */
1401 if (accounting_is_enabled(options
))
1402 accounting_run_housekeeping(now
);
1404 if (time_to
.launch_reachability_tests
< now
&&
1405 (authdir_mode_tests_reachability(options
)) &&
1406 !net_is_disabled()) {
1407 time_to
.launch_reachability_tests
= now
+ REACHABILITY_TEST_INTERVAL
;
1408 /* try to determine reachability of the other Tor relays */
1409 dirserv_test_reachability(now
);
1412 /* 1d. Periodically, we discount older stability information so that new
1413 * stability info counts more, and save the stability information to disk as
1415 if (time_to
.downrate_stability
< now
)
1416 time_to
.downrate_stability
= rep_hist_downrate_old_runs(now
);
1417 if (authdir_mode_tests_reachability(options
)) {
1418 if (time_to
.save_stability
< now
) {
1419 if (time_to
.save_stability
&& rep_hist_record_mtbf_data(now
, 1)<0) {
1420 log_warn(LD_GENERAL
, "Couldn't store mtbf data.");
1422 #define SAVE_STABILITY_INTERVAL (30*60)
1423 time_to
.save_stability
= now
+ SAVE_STABILITY_INTERVAL
;
1427 /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
1428 * close to expiring and warn the admin if it is. */
1429 if (time_to
.check_v3_certificate
< now
) {
1430 v3_authority_check_key_expiry();
1431 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
1432 time_to
.check_v3_certificate
= now
+ CHECK_V3_CERTIFICATE_INTERVAL
;
1435 /* 1f. Check whether our networkstatus has expired.
1437 if (time_to
.check_for_expired_networkstatus
< now
) {
1438 networkstatus_t
*ns
= networkstatus_get_latest_consensus();
1439 /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
1440 * networkstatus_get_reasonably_live_consensus(), but that value is way
1441 * way too high. Arma: is the bridge issue there resolved yet? -NM */
1442 #define NS_EXPIRY_SLOP (24*60*60)
1443 if (ns
&& ns
->valid_until
< now
+NS_EXPIRY_SLOP
&&
1444 router_have_minimum_dir_info()) {
1445 router_dir_info_changed();
1447 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1448 time_to
.check_for_expired_networkstatus
= now
+ CHECK_EXPIRED_NS_INTERVAL
;
1451 /* 1g. Check whether we should write statistics to disk.
1453 if (time_to
.write_stats_files
< now
) {
1454 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1455 time_t next_time_to_write_stats_files
= (time_to
.write_stats_files
> 0 ?
1456 time_to
.write_stats_files
: now
) + CHECK_WRITE_STATS_INTERVAL
;
1457 if (options
->CellStatistics
) {
1459 rep_hist_buffer_stats_write(time_to
.write_stats_files
);
1460 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1461 next_time_to_write_stats_files
= next_write
;
1463 if (options
->DirReqStatistics
) {
1464 time_t next_write
= geoip_dirreq_stats_write(time_to
.write_stats_files
);
1465 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1466 next_time_to_write_stats_files
= next_write
;
1468 if (options
->EntryStatistics
) {
1469 time_t next_write
= geoip_entry_stats_write(time_to
.write_stats_files
);
1470 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1471 next_time_to_write_stats_files
= next_write
;
1473 if (options
->HiddenServiceStatistics
) {
1474 time_t next_write
= rep_hist_hs_stats_write(time_to
.write_stats_files
);
1475 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1476 next_time_to_write_stats_files
= next_write
;
1478 if (options
->ExitPortStatistics
) {
1479 time_t next_write
= rep_hist_exit_stats_write(time_to
.write_stats_files
);
1480 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1481 next_time_to_write_stats_files
= next_write
;
1483 if (options
->ConnDirectionStatistics
) {
1484 time_t next_write
= rep_hist_conn_stats_write(time_to
.write_stats_files
);
1485 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1486 next_time_to_write_stats_files
= next_write
;
1488 if (options
->BridgeAuthoritativeDir
) {
1489 time_t next_write
= rep_hist_desc_stats_write(time_to
.write_stats_files
);
1490 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1491 next_time_to_write_stats_files
= next_write
;
1493 time_to
.write_stats_files
= next_time_to_write_stats_files
;
1496 /* 1h. Check whether we should write bridge statistics to disk.
1498 if (should_record_bridge_info(options
)) {
1499 if (time_to
.write_bridge_stats
< now
) {
1500 if (should_init_bridge_stats
) {
1501 /* (Re-)initialize bridge statistics. */
1502 geoip_bridge_stats_init(now
);
1503 time_to
.write_bridge_stats
= now
+ WRITE_STATS_INTERVAL
;
1504 should_init_bridge_stats
= 0;
1506 /* Possibly write bridge statistics to disk and ask when to write
1507 * them next time. */
1508 time_to
.write_bridge_stats
= geoip_bridge_stats_write(
1509 time_to
.write_bridge_stats
);
1512 } else if (!should_init_bridge_stats
) {
1513 /* Bridge mode was turned off. Ensure that stats are re-initialized
1514 * next time bridge mode is turned on. */
1515 should_init_bridge_stats
= 1;
1518 /* Remove old information from rephist and the rend cache. */
1519 if (time_to
.clean_caches
< now
) {
1520 rep_history_clean(now
- options
->RephistTrackTime
);
1521 rend_cache_clean(now
);
1522 rend_cache_clean_v2_descs_as_dir(now
, 0);
1523 microdesc_cache_rebuild(NULL
, 0);
1524 #define CLEAN_CACHES_INTERVAL (30*60)
1525 time_to
.clean_caches
= now
+ CLEAN_CACHES_INTERVAL
;
1527 /* We don't keep entries that are more than five minutes old so we try to
1528 * clean it as soon as we can since we want to make sure the client waits
1529 * as little as possible for reachability reasons. */
1530 rend_cache_failure_clean(now
);
1532 #define RETRY_DNS_INTERVAL (10*60)
1533 /* If we're a server and initializing dns failed, retry periodically. */
1534 if (time_to
.retry_dns_init
< now
) {
1535 time_to
.retry_dns_init
= now
+ RETRY_DNS_INTERVAL
;
1536 if (is_server
&& has_dns_init_failed())
1540 /* 2. Periodically, we consider force-uploading our descriptor
1541 * (if we've passed our internal checks). */
1543 /** How often do we check whether part of our router info has changed in a
1544 * way that would require an upload? That includes checking whether our IP
1545 * address has changed. */
1546 #define CHECK_DESCRIPTOR_INTERVAL (60)
1548 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1549 * one is inaccurate. */
1550 if (time_to
.check_descriptor
< now
&& !options
->DisableNetwork
) {
1551 static int dirport_reachability_count
= 0;
1552 time_to
.check_descriptor
= now
+ CHECK_DESCRIPTOR_INTERVAL
;
1553 check_descriptor_bandwidth_changed(now
);
1554 check_descriptor_ipaddress_changed(now
);
1555 mark_my_descriptor_dirty_if_too_old(now
);
1556 consider_publishable_server(0);
1557 /* also, check religiously for reachability, if it's within the first
1558 * 20 minutes of our uptime. */
1560 (have_completed_a_circuit() || !any_predicted_circuits(now
)) &&
1561 !we_are_hibernating()) {
1562 if (stats_n_seconds_working
< TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
) {
1563 consider_testing_reachability(1, dirport_reachability_count
==0);
1564 if (++dirport_reachability_count
> 5)
1565 dirport_reachability_count
= 0;
1566 } else if (time_to
.recheck_bandwidth
< now
) {
1567 /* If we haven't checked for 12 hours and our bandwidth estimate is
1568 * low, do another bandwidth test. This is especially important for
1569 * bridges, since they might go long periods without much use. */
1570 const routerinfo_t
*me
= router_get_my_routerinfo();
1571 if (time_to
.recheck_bandwidth
&& me
&&
1572 me
->bandwidthcapacity
< me
->bandwidthrate
&&
1573 me
->bandwidthcapacity
< 51200) {
1574 reset_bandwidth_test();
1576 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1577 time_to
.recheck_bandwidth
= now
+ BANDWIDTH_RECHECK_INTERVAL
;
1581 /* If any networkstatus documents are no longer recent, we need to
1582 * update all the descriptors' running status. */
1583 /* Remove dead routers. */
1584 routerlist_remove_old_routers();
1587 /* 2c. Every minute (or every second if TestingTorNetwork), check
1588 * whether we want to download any networkstatus documents. */
1590 /* How often do we check whether we should download network status
1592 #define networkstatus_dl_check_interval(o) ((o)->TestingTorNetwork ? 1 : 60)
1594 if (!should_delay_dir_fetches(options
, NULL
) &&
1595 time_to
.download_networkstatus
< now
) {
1596 time_to
.download_networkstatus
=
1597 now
+ networkstatus_dl_check_interval(options
);
1598 update_networkstatus_downloads(now
);
1601 /* 2c. Let directory voting happen. */
1602 if (authdir_mode_v3(options
))
1603 dirvote_act(options
, now
);
1605 /* 3a. Every second, we examine pending circuits and prune the
1606 * ones which have been pending for more than a few seconds.
1607 * We do this before step 4, so it can try building more if
1608 * it's not comfortable with the number of available circuits.
1610 /* (If our circuit build timeout can ever become lower than a second (which
1611 * it can't, currently), we should do this more often.) */
1612 circuit_expire_building();
1614 /* 3b. Also look at pending streams and prune the ones that 'began'
1615 * a long time ago but haven't gotten a 'connected' yet.
1616 * Do this before step 4, so we can put them back into pending
1617 * state to be picked up by the new circuit.
1619 connection_ap_expire_beginning();
1621 /* 3c. And expire connections that we've held open for too long.
1623 connection_expire_held_open();
1625 /* 3d. And every 60 seconds, we relaunch listeners if any died. */
1626 if (!net_is_disabled() && time_to
.check_listeners
< now
) {
1627 retry_all_listeners(NULL
, NULL
, 0);
1628 time_to
.check_listeners
= now
+60;
1631 /* 4. Every second, we try a new circuit if there are no valid
1632 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1633 * that became dirty more than MaxCircuitDirtiness seconds ago,
1634 * and we make a new circ if there are no clean circuits.
1636 have_dir_info
= router_have_minimum_dir_info();
1637 if (have_dir_info
&& !net_is_disabled()) {
1638 circuit_build_needed_circs(now
);
1640 circuit_expire_old_circs_as_needed(now
);
1643 /* every 10 seconds, but not at the same second as other such events */
1645 circuit_expire_old_circuits_serverside(now
);
1647 /* 5. We do housekeeping for each connection... */
1648 connection_or_set_bad_connections(NULL
, 0);
1649 for (i
=0;i
<smartlist_len(connection_array
);i
++) {
1650 run_connection_housekeeping(i
, now
);
1653 /* 6. And remove any marked circuits... */
1654 circuit_close_all_marked();
1656 /* 7. And upload service descriptors if necessary. */
1657 if (have_completed_a_circuit() && !net_is_disabled()) {
1658 rend_consider_services_upload(now
);
1659 rend_consider_descriptor_republication();
1662 /* 8. and blow away any connections that need to die. have to do this now,
1663 * because if we marked a conn for close and left its socket -1, then
1664 * we'll pass it to poll/select and bad things will happen.
1666 close_closeable_connections();
1668 /* 8b. And if anything in our state is ready to get flushed to disk, we
1672 /* 8c. Do channel cleanup just like for connections */
1673 channel_run_cleanup();
1674 channel_listener_run_cleanup();
1676 /* 9. and if we're an exit node, check whether our DNS is telling stories
1678 if (!net_is_disabled() &&
1679 public_server_mode(options
) &&
1680 time_to
.check_for_correct_dns
< now
&&
1681 ! router_my_exit_policy_is_reject_star()) {
1682 if (!time_to
.check_for_correct_dns
) {
1683 time_to
.check_for_correct_dns
=
1684 crypto_rand_time_range(now
+ 60, now
+ 180);
1686 dns_launch_correctness_checks();
1687 time_to
.check_for_correct_dns
= now
+ 12*3600 +
1688 crypto_rand_int(12*3600);
1692 /* 10. write bridge networkstatus file to disk */
1693 if (options
->BridgeAuthoritativeDir
&&
1694 time_to
.write_bridge_status_file
< now
) {
1695 networkstatus_dump_bridge_status_to_file(now
);
1696 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
1697 time_to
.write_bridge_status_file
= now
+BRIDGE_STATUSFILE_INTERVAL
;
1700 /* 11. check the port forwarding app */
1701 if (!net_is_disabled() &&
1702 time_to
.check_port_forwarding
< now
&&
1703 options
->PortForwarding
&&
1705 #define PORT_FORWARDING_CHECK_INTERVAL 5
1706 smartlist_t
*ports_to_forward
= get_list_of_ports_to_forward();
1707 if (ports_to_forward
) {
1708 tor_check_port_forwarding(options
->PortForwardingHelper
,
1712 SMARTLIST_FOREACH(ports_to_forward
, char *, cp
, tor_free(cp
));
1713 smartlist_free(ports_to_forward
);
1715 time_to
.check_port_forwarding
= now
+PORT_FORWARDING_CHECK_INTERVAL
;
1718 /* 11b. check pending unconfigured managed proxies */
1719 if (!net_is_disabled() && pt_proxies_configuration_pending())
1720 pt_configure_remaining_proxies();
1722 /* 12. write the heartbeat message */
1723 if (options
->HeartbeatPeriod
&&
1724 time_to
.next_heartbeat
<= now
) {
1725 if (time_to
.next_heartbeat
) /* don't log the first heartbeat */
1727 time_to
.next_heartbeat
= now
+options
->HeartbeatPeriod
;
1731 /** Timer: used to invoke second_elapsed_callback() once per second. */
1732 static periodic_timer_t
*second_timer
= NULL
;
1733 /** Number of libevent errors in the last second: we die if we get too many. */
1734 static int n_libevent_errors
= 0;
1736 /** Libevent callback: invoked once every second. */
1738 second_elapsed_callback(periodic_timer_t
*timer
, void *arg
)
1740 /* XXXX This could be sensibly refactored into multiple callbacks, and we
1741 * could use Libevent's timers for this rather than checking the current
1742 * time against a bunch of timeouts every second. */
1743 static time_t current_second
= 0;
1745 size_t bytes_written
;
1747 int seconds_elapsed
;
1748 const or_options_t
*options
= get_options();
1752 n_libevent_errors
= 0;
1754 /* log_notice(LD_GENERAL, "Tick."); */
1756 update_approx_time(now
);
1758 /* the second has rolled over. check more stuff. */
1759 seconds_elapsed
= current_second
? (int)(now
- current_second
) : 0;
1760 #ifdef USE_BUFFEREVENTS
1762 uint64_t cur_read
,cur_written
;
1763 connection_get_rate_limit_totals(&cur_read
, &cur_written
);
1764 bytes_written
= (size_t)(cur_written
- stats_prev_n_written
);
1765 bytes_read
= (size_t)(cur_read
- stats_prev_n_read
);
1766 stats_n_bytes_read
+= bytes_read
;
1767 stats_n_bytes_written
+= bytes_written
;
1768 if (accounting_is_enabled(options
) && seconds_elapsed
>= 0)
1769 accounting_add_bytes(bytes_read
, bytes_written
, seconds_elapsed
);
1770 stats_prev_n_written
= cur_written
;
1771 stats_prev_n_read
= cur_read
;
1774 bytes_read
= (size_t)(stats_n_bytes_read
- stats_prev_n_read
);
1775 bytes_written
= (size_t)(stats_n_bytes_written
- stats_prev_n_written
);
1776 stats_prev_n_read
= stats_n_bytes_read
;
1777 stats_prev_n_written
= stats_n_bytes_written
;
1780 control_event_bandwidth_used((uint32_t)bytes_read
,(uint32_t)bytes_written
);
1781 control_event_stream_bandwidth_used();
1782 control_event_conn_bandwidth_used();
1783 control_event_circ_bandwidth_used();
1784 control_event_circuit_cell_stats();
1786 if (server_mode(options
) &&
1787 !net_is_disabled() &&
1788 seconds_elapsed
> 0 &&
1789 have_completed_a_circuit() &&
1790 stats_n_seconds_working
/ TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
!=
1791 (stats_n_seconds_working
+seconds_elapsed
) /
1792 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
) {
1793 /* every 20 minutes, check and complain if necessary */
1794 const routerinfo_t
*me
= router_get_my_routerinfo();
1795 if (me
&& !check_whether_orport_reachable()) {
1796 char *address
= tor_dup_ip(me
->addr
);
1797 log_warn(LD_CONFIG
,"Your server (%s:%d) has not managed to confirm that "
1798 "its ORPort is reachable. Please check your firewalls, ports, "
1799 "address, /etc/hosts file, etc.",
1800 address
, me
->or_port
);
1801 control_event_server_status(LOG_WARN
,
1802 "REACHABILITY_FAILED ORADDRESS=%s:%d",
1803 address
, me
->or_port
);
1807 if (me
&& !check_whether_dirport_reachable()) {
1808 char *address
= tor_dup_ip(me
->addr
);
1810 "Your server (%s:%d) has not managed to confirm that its "
1811 "DirPort is reachable. Please check your firewalls, ports, "
1812 "address, /etc/hosts file, etc.",
1813 address
, me
->dir_port
);
1814 control_event_server_status(LOG_WARN
,
1815 "REACHABILITY_FAILED DIRADDRESS=%s:%d",
1816 address
, me
->dir_port
);
1821 /** If more than this many seconds have elapsed, probably the clock
1822 * jumped: doesn't count. */
1823 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
1824 if (seconds_elapsed
< -NUM_JUMPED_SECONDS_BEFORE_WARN
||
1825 seconds_elapsed
>= NUM_JUMPED_SECONDS_BEFORE_WARN
) {
1826 circuit_note_clock_jumped(seconds_elapsed
);
1827 } else if (seconds_elapsed
> 0)
1828 stats_n_seconds_working
+= seconds_elapsed
;
1830 run_scheduled_events(now
);
1832 current_second
= now
; /* remember which second it is, for next time */
1835 #ifdef HAVE_SYSTEMD_209
1836 static periodic_timer_t
*systemd_watchdog_timer
= NULL
;
1838 /** Libevent callback: invoked to reset systemd watchdog. */
1840 systemd_watchdog_callback(periodic_timer_t
*timer
, void *arg
)
1844 sd_notify(0, "WATCHDOG=1");
1848 #ifndef USE_BUFFEREVENTS
1849 /** Timer: used to invoke refill_callback(). */
1850 static periodic_timer_t
*refill_timer
= NULL
;
1852 /** Libevent callback: invoked periodically to refill token buckets
1853 * and count r/w bytes. It is only used when bufferevents are disabled. */
1855 refill_callback(periodic_timer_t
*timer
, void *arg
)
1857 static struct timeval current_millisecond
;
1860 size_t bytes_written
;
1862 int milliseconds_elapsed
= 0;
1863 int seconds_rolled_over
= 0;
1865 const or_options_t
*options
= get_options();
1870 tor_gettimeofday(&now
);
1872 /* If this is our first time, no time has passed. */
1873 if (current_millisecond
.tv_sec
) {
1874 long mdiff
= tv_mdiff(¤t_millisecond
, &now
);
1875 if (mdiff
> INT_MAX
)
1877 milliseconds_elapsed
= (int)mdiff
;
1878 seconds_rolled_over
= (int)(now
.tv_sec
- current_millisecond
.tv_sec
);
1881 bytes_written
= stats_prev_global_write_bucket
- global_write_bucket
;
1882 bytes_read
= stats_prev_global_read_bucket
- global_read_bucket
;
1884 stats_n_bytes_read
+= bytes_read
;
1885 stats_n_bytes_written
+= bytes_written
;
1886 if (accounting_is_enabled(options
) && milliseconds_elapsed
>= 0)
1887 accounting_add_bytes(bytes_read
, bytes_written
, seconds_rolled_over
);
1889 if (milliseconds_elapsed
> 0)
1890 connection_bucket_refill(milliseconds_elapsed
, (time_t)now
.tv_sec
);
1892 stats_prev_global_read_bucket
= global_read_bucket
;
1893 stats_prev_global_write_bucket
= global_write_bucket
;
1895 current_millisecond
= now
; /* remember what time it is, for next time */
1900 /** Called when a possibly ignorable libevent error occurs; ensures that we
1901 * don't get into an infinite loop by ignoring too many errors from
1904 got_libevent_error(void)
1906 if (++n_libevent_errors
> 8) {
1907 log_err(LD_NET
, "Too many libevent errors in one second; dying");
1914 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
1916 /** Called when our IP address seems to have changed. <b>at_interface</b>
1917 * should be true if we detected a change in our interface, and false if we
1918 * detected a change in our published address. */
1920 ip_address_changed(int at_interface
)
1922 int server
= server_mode(get_options());
1926 /* Okay, change our keys. */
1927 if (init_keys_client() < 0)
1928 log_warn(LD_GENERAL
, "Unable to rotate keys after IP change!");
1932 if (stats_n_seconds_working
> UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST
)
1933 reset_bandwidth_test();
1934 stats_n_seconds_working
= 0;
1935 router_reset_reachability();
1936 mark_my_descriptor_dirty("IP address changed");
1940 dns_servers_relaunch_checks();
1943 /** Forget what we've learned about the correctness of our DNS servers, and
1944 * start learning again. */
1946 dns_servers_relaunch_checks(void)
1948 if (server_mode(get_options())) {
1949 dns_reset_correctness_checks();
1950 time_to
.check_for_correct_dns
= 0;
1954 /** Called when we get a SIGHUP: reload configuration files and keys,
1955 * retry all connections, and so on. */
1959 const or_options_t
*options
= get_options();
1962 dmalloc_log_stats();
1963 dmalloc_log_changed(0, 1, 0, 0);
1966 log_notice(LD_GENERAL
,"Received reload signal (hup). Reloading config and "
1967 "resetting internal state.");
1968 if (accounting_is_enabled(options
))
1969 accounting_record_bandwidth_usage(time(NULL
), get_or_state());
1971 router_reset_warnings();
1972 routerlist_reset_warnings();
1973 /* first, reload config variables, in case they've changed */
1974 if (options
->ReloadTorrcOnSIGHUP
) {
1975 /* no need to provide argc/v, they've been cached in init_from_config */
1976 if (options_init_from_torrc(0, NULL
) < 0) {
1977 log_err(LD_CONFIG
,"Reading config failed--see warnings above. "
1978 "For usage, try -h.");
1981 options
= get_options(); /* they have changed now */
1982 /* Logs are only truncated the first time they are opened, but were
1983 probably intended to be cleaned up on signal. */
1984 if (options
->TruncateLogFile
)
1988 log_notice(LD_GENERAL
, "Not reloading config file: the controller told "
1990 /* Make stuff get rescanned, reloaded, etc. */
1991 if (set_options((or_options_t
*)options
, &msg
) < 0) {
1993 msg
= tor_strdup("Unknown error");
1994 log_warn(LD_GENERAL
, "Unable to re-set previous options: %s", msg
);
1998 if (authdir_mode_handles_descs(options
, -1)) {
1999 /* reload the approved-routers file */
2000 if (dirserv_load_fingerprint_file() < 0) {
2001 /* warnings are logged from dirserv_load_fingerprint_file() directly */
2002 log_info(LD_GENERAL
, "Error reloading fingerprints. "
2003 "Continuing with old list.");
2007 /* Rotate away from the old dirty circuits. This has to be done
2008 * after we've read the new options, but before we start using
2009 * circuits for directory fetches. */
2010 circuit_mark_all_dirty_circs_as_unusable();
2012 /* retry appropriate downloads */
2013 router_reset_status_download_failures();
2014 router_reset_descriptor_download_failures();
2015 if (!options
->DisableNetwork
)
2016 update_networkstatus_downloads(time(NULL
));
2018 /* We'll retry routerstatus downloads in about 10 seconds; no need to
2019 * force a retry there. */
2021 if (server_mode(options
)) {
2022 /* Maybe we've been given a new ed25519 key or certificate?
2024 time_t now
= approx_time();
2025 if (load_ed_keys(options
, now
) < 0 ||
2026 generate_ed_link_cert(options
, now
)) {
2027 log_warn(LD_OR
, "Problem reloading Ed25519 keys; still using old keys.");
2030 /* Update cpuworker and dnsworker processes, so they get up-to-date
2031 * configuration options. */
2032 cpuworkers_rotate_keyinfo();
2038 /** Tor main loop. */
2044 /* initialize dns resolve map, spawn workers if needed */
2045 if (dns_init() < 0) {
2046 if (get_options()->ServerDNSAllowBrokenConfig
)
2047 log_warn(LD_GENERAL
, "Couldn't set up any working nameservers. "
2048 "Network not up yet? Will try again soon.");
2050 log_err(LD_GENERAL
,"Error initializing dns subsystem; exiting. To "
2051 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
2055 #ifdef USE_BUFFEREVENTS
2056 log_warn(LD_GENERAL
, "Tor was compiled with the --enable-bufferevents "
2057 "option. This is still experimental, and might cause strange "
2058 "bugs. If you want a more stable Tor, be sure to build without "
2059 "--enable-bufferevents.");
2064 /* load the private keys, if we're supposed to have them, and set up the
2066 if (! client_identity_key_is_set()) {
2067 if (init_keys() < 0) {
2068 log_err(LD_OR
, "Error initializing keys; exiting");
2073 /* Set up our buckets */
2074 connection_bucket_init();
2075 #ifndef USE_BUFFEREVENTS
2076 stats_prev_global_read_bucket
= global_read_bucket
;
2077 stats_prev_global_write_bucket
= global_write_bucket
;
2080 /* initialize the bootstrap status events to know we're starting up */
2081 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING
, 0);
2083 /* Initialize the keypinning log. */
2084 if (authdir_mode_v3(get_options())) {
2085 char *fname
= get_datadir_fname("key-pinning-journal");
2087 if (keypin_load_journal(fname
)<0) {
2088 log_err(LD_DIR
, "Error loading key-pinning journal: %s",strerror(errno
));
2091 if (keypin_open_journal(fname
)<0) {
2092 log_err(LD_DIR
, "Error opening key-pinning journal: %s",strerror(errno
));
2100 /* This is the old name for key-pinning-journal. These got corrupted
2101 * in a couple of cases by #16530, so we started over. See #16580 for
2102 * the rationale and for other options we didn't take. We can remove
2103 * this code once all the authorities that ran 0.2.7.1-alpha-dev are
2106 char *fname
= get_datadir_fname("key-pinning-entries");
2111 if (trusted_dirs_reload_certs()) {
2113 "Couldn't load all cached v3 certificates. Starting anyway.");
2115 if (router_reload_consensus_networkstatus()) {
2118 /* load the routers file, or assign the defaults. */
2119 if (router_reload_router_list()) {
2122 /* load the networkstatuses. (This launches a download for new routers as
2126 directory_info_has_arrived(now
, 1);
2128 if (server_mode(get_options())) {
2129 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
2133 /* set up once-a-second callback. */
2134 if (! second_timer
) {
2135 struct timeval one_second
;
2136 one_second
.tv_sec
= 1;
2137 one_second
.tv_usec
= 0;
2139 second_timer
= periodic_timer_new(tor_libevent_get_base(),
2141 second_elapsed_callback
,
2143 tor_assert(second_timer
);
2146 #ifdef HAVE_SYSTEMD_209
2147 uint64_t watchdog_delay
;
2148 /* set up systemd watchdog notification. */
2149 if (sd_watchdog_enabled(1, &watchdog_delay
) > 0) {
2150 if (! systemd_watchdog_timer
) {
2151 struct timeval watchdog
;
2152 /* The manager will "act on" us if we don't send them a notification
2153 * every 'watchdog_delay' microseconds. So, send notifications twice
2155 watchdog_delay
/= 2;
2156 watchdog
.tv_sec
= watchdog_delay
/ 1000000;
2157 watchdog
.tv_usec
= watchdog_delay
% 1000000;
2159 systemd_watchdog_timer
= periodic_timer_new(tor_libevent_get_base(),
2161 systemd_watchdog_callback
,
2163 tor_assert(systemd_watchdog_timer
);
2168 #ifndef USE_BUFFEREVENTS
2169 if (!refill_timer
) {
2170 struct timeval refill_interval
;
2171 int msecs
= get_options()->TokenBucketRefillInterval
;
2173 refill_interval
.tv_sec
= msecs
/1000;
2174 refill_interval
.tv_usec
= (msecs
%1000)*1000;
2176 refill_timer
= periodic_timer_new(tor_libevent_get_base(),
2180 tor_assert(refill_timer
);
2186 const int r
= sd_notify(0, "READY=1");
2188 log_warn(LD_GENERAL
, "Unable to send readiness to systemd: %s",
2191 log_notice(LD_GENERAL
, "Signaled readiness to systemd");
2193 log_info(LD_GENERAL
, "Systemd NOTIFY_SOCKET not present.");
2198 return run_main_loop_until_done();
2202 * Run the main loop a single time. Return 0 for "exit"; -1 for "exit with
2203 * error", and 1 for "run this again."
2206 run_main_loop_once(void)
2210 if (nt_service_is_stopping())
2214 /* Make it easier to tell whether libevent failure is our fault or not. */
2217 /* All active linked conns should get their read events activated. */
2218 SMARTLIST_FOREACH(active_linked_connection_lst
, connection_t
*, conn
,
2219 event_active(conn
->read_event
, EV_READ
, 1));
2220 called_loop_once
= smartlist_len(active_linked_connection_lst
) ? 1 : 0;
2222 update_approx_time(time(NULL
));
2224 /* poll until we have an event, or the second ends, or until we have
2225 * some active linked connections to trigger events for. */
2226 loop_result
= event_base_loop(tor_libevent_get_base(),
2227 called_loop_once
? EVLOOP_ONCE
: 0);
2229 /* let catch() handle things like ^c, and otherwise don't worry about it */
2230 if (loop_result
< 0) {
2231 int e
= tor_socket_errno(-1);
2232 /* let the program survive things like ^z */
2233 if (e
!= EINTR
&& !ERRNO_IS_EINPROGRESS(e
)) {
2234 log_err(LD_NET
,"libevent call with %s failed: %s [%d]",
2235 tor_libevent_get_method(), tor_socket_strerror(e
), e
);
2238 } else if (e
== EINVAL
) {
2239 log_warn(LD_NET
, "EINVAL from libevent: should you upgrade libevent?");
2240 if (got_libevent_error())
2244 if (ERRNO_IS_EINPROGRESS(e
))
2246 "libevent call returned EINPROGRESS? Please report.");
2247 log_debug(LD_NET
,"libevent call interrupted.");
2248 /* You can't trust the results of this poll(). Go back to the
2249 * top of the big for loop. */
2257 /** Run the run_main_loop_once() function until it declares itself done,
2258 * and return its final return value.
2260 * Shadow won't invoke this function, so don't fill it up with things.
2263 run_main_loop_until_done(void)
2265 int loop_result
= 1;
2267 loop_result
= run_main_loop_once();
2268 } while (loop_result
== 1);
2272 /** Libevent callback: invoked when we get a signal.
2275 signal_callback(evutil_socket_t fd
, short events
, void *arg
)
2277 const int *sigptr
= arg
;
2278 const int sig
= *sigptr
;
2282 process_signal(sig
);
2285 /** Do the work of acting on a signal received in <b>sig</b> */
2287 process_signal(int sig
)
2292 log_notice(LD_GENERAL
,"Catching signal TERM, exiting cleanly.");
2297 if (!server_mode(get_options())) { /* do it now */
2298 log_notice(LD_GENERAL
,"Interrupt: exiting cleanly.");
2303 sd_notify(0, "STOPPING=1");
2305 hibernate_begin_shutdown();
2309 log_debug(LD_GENERAL
,"Caught SIGPIPE. Ignoring.");
2313 /* prefer to log it at INFO, but make sure we always see it */
2314 dumpstats(get_min_log_level()<LOG_INFO
? get_min_log_level() : LOG_INFO
);
2315 control_event_signal(sig
);
2318 switch_logs_debug();
2319 log_debug(LD_GENERAL
,"Caught USR2, going to loglevel debug. "
2320 "Send HUP to change back.");
2321 control_event_signal(sig
);
2325 sd_notify(0, "RELOADING=1");
2328 log_warn(LD_CONFIG
,"Restart failed (config error?). Exiting.");
2333 sd_notify(0, "READY=1");
2335 control_event_signal(sig
);
2339 notify_pending_waitpid_callbacks();
2343 time_t now
= time(NULL
);
2344 if (time_of_last_signewnym
+ MAX_SIGNEWNYM_RATE
> now
) {
2345 signewnym_is_pending
= 1;
2346 log_notice(LD_CONTROL
,
2347 "Rate limiting NEWNYM request: delaying by %d second(s)",
2348 (int)(MAX_SIGNEWNYM_RATE
+time_of_last_signewnym
-now
));
2350 signewnym_impl(now
);
2354 case SIGCLEARDNSCACHE
:
2355 addressmap_clear_transient();
2356 control_event_signal(sig
);
2359 log_heartbeat(time(NULL
));
2360 control_event_signal(sig
);
2365 /** Returns Tor's uptime. */
2369 return stats_n_seconds_working
;
2372 extern uint64_t rephist_total_alloc
;
2373 extern uint32_t rephist_total_num
;
2376 * Write current memory usage information to the log.
2379 dumpmemusage(int severity
)
2381 connection_dump_buffer_mem_stats(severity
);
2382 tor_log(severity
, LD_GENERAL
, "In rephist: "U64_FORMAT
" used by %d Tors.",
2383 U64_PRINTF_ARG(rephist_total_alloc
), rephist_total_num
);
2384 dump_routerlist_mem_usage(severity
);
2385 dump_cell_pool_usage(severity
);
2386 dump_dns_mem_usage(severity
);
2387 tor_log_mallinfo(severity
);
2390 /** Write all statistics to the log, with log level <b>severity</b>. Called
2391 * in response to a SIGUSR1. */
2393 dumpstats(int severity
)
2395 time_t now
= time(NULL
);
2397 size_t rbuf_cap
, wbuf_cap
, rbuf_len
, wbuf_len
;
2399 tor_log(severity
, LD_GENERAL
, "Dumping stats:");
2401 SMARTLIST_FOREACH_BEGIN(connection_array
, connection_t
*, conn
) {
2402 int i
= conn_sl_idx
;
2403 tor_log(severity
, LD_GENERAL
,
2404 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
2405 i
, (int)conn
->s
, conn
->type
, conn_type_to_string(conn
->type
),
2406 conn
->state
, conn_state_to_string(conn
->type
, conn
->state
),
2407 (int)(now
- conn
->timestamp_created
));
2408 if (!connection_is_listener(conn
)) {
2409 tor_log(severity
,LD_GENERAL
,
2410 "Conn %d is to %s:%d.", i
,
2411 safe_str_client(conn
->address
),
2413 tor_log(severity
,LD_GENERAL
,
2414 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
2416 (int)connection_get_inbuf_len(conn
),
2417 (int)buf_allocation(conn
->inbuf
),
2418 (int)(now
- conn
->timestamp_lastread
));
2419 tor_log(severity
,LD_GENERAL
,
2420 "Conn %d: %d bytes waiting on outbuf "
2421 "(len %d, last written %d secs ago)",i
,
2422 (int)connection_get_outbuf_len(conn
),
2423 (int)buf_allocation(conn
->outbuf
),
2424 (int)(now
- conn
->timestamp_lastwritten
));
2425 if (conn
->type
== CONN_TYPE_OR
) {
2426 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2428 if (tor_tls_get_buffer_sizes(or_conn
->tls
, &rbuf_cap
, &rbuf_len
,
2429 &wbuf_cap
, &wbuf_len
) == 0) {
2430 tor_log(severity
, LD_GENERAL
,
2431 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
2432 "%d/%d bytes used on write buffer.",
2433 i
, (int)rbuf_len
, (int)rbuf_cap
, (int)wbuf_len
, (int)wbuf_cap
);
2438 circuit_dump_by_conn(conn
, severity
); /* dump info about all the circuits
2439 * using this conn */
2440 } SMARTLIST_FOREACH_END(conn
);
2442 channel_dumpstats(severity
);
2443 channel_listener_dumpstats(severity
);
2445 tor_log(severity
, LD_NET
,
2446 "Cells processed: "U64_FORMAT
" padding\n"
2447 " "U64_FORMAT
" create\n"
2448 " "U64_FORMAT
" created\n"
2449 " "U64_FORMAT
" relay\n"
2450 " ("U64_FORMAT
" relayed)\n"
2451 " ("U64_FORMAT
" delivered)\n"
2452 " "U64_FORMAT
" destroy",
2453 U64_PRINTF_ARG(stats_n_padding_cells_processed
),
2454 U64_PRINTF_ARG(stats_n_create_cells_processed
),
2455 U64_PRINTF_ARG(stats_n_created_cells_processed
),
2456 U64_PRINTF_ARG(stats_n_relay_cells_processed
),
2457 U64_PRINTF_ARG(stats_n_relay_cells_relayed
),
2458 U64_PRINTF_ARG(stats_n_relay_cells_delivered
),
2459 U64_PRINTF_ARG(stats_n_destroy_cells_processed
));
2460 if (stats_n_data_cells_packaged
)
2461 tor_log(severity
,LD_NET
,"Average packaged cell fullness: %2.3f%%",
2462 100*(U64_TO_DBL(stats_n_data_bytes_packaged
) /
2463 U64_TO_DBL(stats_n_data_cells_packaged
*RELAY_PAYLOAD_SIZE
)) );
2464 if (stats_n_data_cells_received
)
2465 tor_log(severity
,LD_NET
,"Average delivered cell fullness: %2.3f%%",
2466 100*(U64_TO_DBL(stats_n_data_bytes_received
) /
2467 U64_TO_DBL(stats_n_data_cells_received
*RELAY_PAYLOAD_SIZE
)) );
2469 cpuworker_log_onionskin_overhead(severity
, ONION_HANDSHAKE_TYPE_TAP
, "TAP");
2470 cpuworker_log_onionskin_overhead(severity
, ONION_HANDSHAKE_TYPE_NTOR
,"ntor");
2472 if (now
- time_of_process_start
>= 0)
2473 elapsed
= now
- time_of_process_start
;
2478 tor_log(severity
, LD_NET
,
2479 "Average bandwidth: "U64_FORMAT
"/%d = %d bytes/sec reading",
2480 U64_PRINTF_ARG(stats_n_bytes_read
),
2482 (int) (stats_n_bytes_read
/elapsed
));
2483 tor_log(severity
, LD_NET
,
2484 "Average bandwidth: "U64_FORMAT
"/%d = %d bytes/sec writing",
2485 U64_PRINTF_ARG(stats_n_bytes_written
),
2487 (int) (stats_n_bytes_written
/elapsed
));
2490 tor_log(severity
, LD_NET
, "--------------- Dumping memory information:");
2491 dumpmemusage(severity
);
2493 rep_hist_dump_stats(now
,severity
);
2494 rend_service_dump_stats(severity
);
2495 dump_pk_ops(severity
);
2496 dump_distinct_digest_count(severity
);
2499 /** Called by exit() as we shut down the process.
2504 /* NOTE: If we ever daemonize, this gets called immediately. That's
2505 * okay for now, because we only use this on Windows. */
2518 int try_to_register
;
2519 struct event
*signal_event
;
2520 } signal_handlers
[] = {
2522 { SIGINT
, UNIX_ONLY
, NULL
}, /* do a controlled slow shutdown */
2525 { SIGTERM
, UNIX_ONLY
, NULL
}, /* to terminate now */
2528 { SIGPIPE
, UNIX_ONLY
, NULL
}, /* otherwise SIGPIPE kills us */
2531 { SIGUSR1
, UNIX_ONLY
, NULL
}, /* dump stats */
2534 { SIGUSR2
, UNIX_ONLY
, NULL
}, /* go to loglevel debug */
2537 { SIGHUP
, UNIX_ONLY
, NULL
}, /* to reload config, retry conns, etc */
2540 { SIGXFSZ
, UNIX_ONLY
, NULL
}, /* handle file-too-big resource exhaustion */
2543 { SIGCHLD
, UNIX_ONLY
, NULL
}, /* handle dns/cpu workers that exit */
2545 /* These are controller-only */
2546 { SIGNEWNYM
, 0, NULL
},
2547 { SIGCLEARDNSCACHE
, 0, NULL
},
2548 { SIGHEARTBEAT
, 0, NULL
},
2552 /** Set up the signal handlers for either parent or child process */
2554 handle_signals(int is_parent
)
2558 for (i
= 0; signal_handlers
[i
].signal_value
>= 0; ++i
) {
2559 if (signal_handlers
[i
].try_to_register
) {
2560 signal_handlers
[i
].signal_event
=
2561 tor_evsignal_new(tor_libevent_get_base(),
2562 signal_handlers
[i
].signal_value
,
2564 &signal_handlers
[i
].signal_value
);
2565 if (event_add(signal_handlers
[i
].signal_event
, NULL
))
2566 log_warn(LD_BUG
, "Error from libevent when adding "
2567 "event for signal %d",
2568 signal_handlers
[i
].signal_value
);
2570 signal_handlers
[i
].signal_event
=
2571 tor_event_new(tor_libevent_get_base(), -1,
2572 EV_SIGNAL
, signal_callback
,
2573 &signal_handlers
[i
].signal_value
);
2578 struct sigaction action
;
2579 action
.sa_flags
= 0;
2580 sigemptyset(&action
.sa_mask
);
2581 action
.sa_handler
= SIG_IGN
;
2582 sigaction(SIGINT
, &action
, NULL
);
2583 sigaction(SIGTERM
, &action
, NULL
);
2584 sigaction(SIGPIPE
, &action
, NULL
);
2585 sigaction(SIGUSR1
, &action
, NULL
);
2586 sigaction(SIGUSR2
, &action
, NULL
);
2587 sigaction(SIGHUP
, &action
, NULL
);
2589 sigaction(SIGXFSZ
, &action
, NULL
);
2595 /* Make sure the signal handler for signal_num will be called. */
2597 activate_signal(int signal_num
)
2600 for (i
= 0; signal_handlers
[i
].signal_value
>= 0; ++i
) {
2601 if (signal_handlers
[i
].signal_value
== signal_num
) {
2602 event_active(signal_handlers
[i
].signal_event
, EV_SIGNAL
, 1);
2608 /** Main entry point for the Tor command-line client.
2611 tor_init(int argc
, char *argv
[])
2616 time_of_process_start
= time(NULL
);
2617 init_connection_lists();
2618 /* Have the log set up with our application name. */
2619 tor_snprintf(progname
, sizeof(progname
), "Tor %s", get_version());
2620 log_set_application_name(progname
);
2622 /* Set up the crypto nice and early */
2623 if (crypto_early_init() < 0) {
2624 log_err(LD_GENERAL
, "Unable to initialize the crypto subsystem!");
2628 /* Initialize the history structures. */
2630 /* Initialize the service cache. */
2632 addressmap_init(); /* Init the client dns cache. Do it always, since it's
2636 /* We search for the "quiet" option first, since it decides whether we
2637 * will log anything at all to the command line. */
2638 config_line_t
*opts
= NULL
, *cmdline_opts
= NULL
;
2639 const config_line_t
*cl
;
2640 (void) config_parse_commandline(argc
, argv
, 1, &opts
, &cmdline_opts
);
2641 for (cl
= cmdline_opts
; cl
; cl
= cl
->next
) {
2642 if (!strcmp(cl
->key
, "--hush"))
2644 if (!strcmp(cl
->key
, "--quiet") ||
2645 !strcmp(cl
->key
, "--dump-config"))
2647 /* The following options imply --hush */
2648 if (!strcmp(cl
->key
, "--version") || !strcmp(cl
->key
, "--digests") ||
2649 !strcmp(cl
->key
, "--list-torrc-options") ||
2650 !strcmp(cl
->key
, "--library-versions") ||
2651 !strcmp(cl
->key
, "--hash-password") ||
2652 !strcmp(cl
->key
, "-h") || !strcmp(cl
->key
, "--help")) {
2657 config_free_lines(opts
);
2658 config_free_lines(cmdline_opts
);
2661 /* give it somewhere to log to initially */
2664 /* no initial logging */
2667 add_temp_log(LOG_WARN
);
2670 add_temp_log(LOG_NOTICE
);
2672 quiet_level
= quiet
;
2675 const char *version
= get_version();
2676 const char *bev_str
=
2677 #ifdef USE_BUFFEREVENTS
2678 "(with bufferevents) ";
2682 log_notice(LD_GENERAL
, "Tor v%s %srunning on %s with Libevent %s, "
2683 "OpenSSL %s and Zlib %s.", version
, bev_str
,
2685 tor_libevent_get_version_str(),
2686 crypto_openssl_get_version_str(),
2687 tor_zlib_get_version_str());
2689 log_notice(LD_GENERAL
, "Tor can't help you if you use it wrong! "
2690 "Learn how to be safe at "
2691 "https://www.torproject.org/download/download#warning");
2693 if (strstr(version
, "alpha") || strstr(version
, "beta"))
2694 log_notice(LD_GENERAL
, "This version is not a stable Tor release. "
2695 "Expect more bugs than usual.");
2698 #ifdef NON_ANONYMOUS_MODE_ENABLED
2699 log_warn(LD_GENERAL
, "This copy of Tor was compiled to run in a "
2700 "non-anonymous mode. It will provide NO ANONYMITY.");
2703 if (network_init()<0) {
2704 log_err(LD_BUG
,"Error initializing network; exiting.");
2707 atexit(exit_function
);
2709 if (options_init_from_torrc(argc
,argv
) < 0) {
2710 log_err(LD_CONFIG
,"Reading config failed--see warnings above.");
2716 log_warn(LD_GENERAL
,"You are running Tor as root. You don't need to, "
2717 "and you probably shouldn't.");
2720 if (crypto_global_init(get_options()->HardwareAccel
,
2721 get_options()->AccelName
,
2722 get_options()->AccelDir
)) {
2723 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
2726 stream_choice_seed_weak_rng();
2727 if (tor_init_libevent_rng() < 0) {
2728 log_warn(LD_NET
, "Problem initializing libevent RNG.");
2734 /** A lockfile structure, used to prevent two Tors from messing with the
2735 * data directory at once. If this variable is non-NULL, we're holding
2737 static tor_lockfile_t
*lockfile
= NULL
;
2739 /** Try to grab the lock file described in <b>options</b>, if we do not
2740 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
2741 * holding the lock, and exit if we can't get it after waiting. Otherwise,
2742 * return -1 if we can't get the lockfile. Return 0 on success.
2745 try_locking(const or_options_t
*options
, int err_if_locked
)
2750 char *fname
= options_get_datadir_fname2_suffix(options
, "lock",NULL
,NULL
);
2751 int already_locked
= 0;
2752 tor_lockfile_t
*lf
= tor_lockfile_lock(fname
, 0, &already_locked
);
2755 if (err_if_locked
&& already_locked
) {
2757 log_warn(LD_GENERAL
, "It looks like another Tor process is running "
2758 "with the same data directory. Waiting 5 seconds to see "
2759 "if it goes away.");
2765 r
= try_locking(options
, 0);
2767 log_err(LD_GENERAL
, "No, it's still there. Exiting.");
2779 /** Return true iff we've successfully acquired the lock file. */
2783 return lockfile
!= NULL
;
2786 /** If we have successfully acquired the lock file, release it. */
2788 release_lockfile(void)
2791 tor_lockfile_unlock(lockfile
);
2796 /** Free all memory that we might have allocated somewhere.
2797 * If <b>postfork</b>, we are a worker process and we want to free
2798 * only the parts of memory that we won't touch. If !<b>postfork</b>,
2799 * Tor is shutting down and we should free everything.
2801 * Helps us find the real leaks with dmalloc and the like. Also valgrind
2802 * should then report 0 reachable in its leak report (in an ideal world --
2803 * in practice libevent, SSL, libc etc never quite free everything). */
2805 tor_free_all(int postfork
)
2812 routerlist_free_all();
2813 networkstatus_free_all();
2814 addressmap_free_all();
2816 rend_service_free_all();
2817 rend_cache_free_all();
2818 rend_service_authorization_free_all();
2819 rep_hist_free_all();
2821 clear_pending_onions();
2823 entry_guards_free_all();
2825 channel_tls_free_all();
2827 connection_free_all();
2828 scheduler_free_all();
2829 memarea_clear_freelist();
2830 nodelist_free_all();
2831 microdesc_free_all();
2832 ext_orport_free_all();
2834 sandbox_free_getaddrinfo_cache();
2837 or_state_free_all();
2839 routerkeys_free_all();
2840 policies_free_all();
2848 /* stuff in main.c */
2850 smartlist_free(connection_array
);
2851 smartlist_free(closeable_connection_lst
);
2852 smartlist_free(active_linked_connection_lst
);
2853 periodic_timer_free(second_timer
);
2854 #ifndef USE_BUFFEREVENTS
2855 periodic_timer_free(refill_timer
);
2861 /* Stuff in util.c and address.c*/
2864 esc_router_info(NULL
);
2865 logs_free_all(); /* free log strings. do this last so logs keep working. */
2869 /** Do whatever cleanup is necessary before shutting Tor down. */
2873 const or_options_t
*options
= get_options();
2874 if (options
->command
== CMD_RUN_TOR
) {
2875 time_t now
= time(NULL
);
2876 /* Remove our pid file. We don't care if there was an error when we
2877 * unlink, nothing we could do about it anyways. */
2878 if (options
->PidFile
) {
2879 if (unlink(options
->PidFile
) != 0) {
2880 log_warn(LD_FS
, "Couldn't unlink pid file %s: %s",
2881 options
->PidFile
, strerror(errno
));
2884 if (options
->ControlPortWriteToFile
) {
2885 if (unlink(options
->ControlPortWriteToFile
) != 0) {
2886 log_warn(LD_FS
, "Couldn't unlink control port file %s: %s",
2887 options
->ControlPortWriteToFile
,
2891 if (accounting_is_enabled(options
))
2892 accounting_record_bandwidth_usage(now
, get_or_state());
2893 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
2895 if (authdir_mode_tests_reachability(options
))
2896 rep_hist_record_mtbf_data(now
, 0);
2897 keypin_close_journal();
2900 dmalloc_log_stats();
2902 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
2903 later, if it makes shutdown unacceptably slow. But for
2904 now, leave it here: it's helped us catch bugs in the
2906 crypto_global_cleanup();
2908 dmalloc_log_unfreed();
2913 /** Read/create keys as needed, and echo our fingerprint to stdout. */
2915 do_list_fingerprint(void)
2917 char buf
[FINGERPRINT_LEN
+1];
2919 const char *nickname
= get_options()->Nickname
;
2920 if (!server_mode(get_options())) {
2922 "Clients don't have long-term identity keys. Exiting.");
2925 tor_assert(nickname
);
2926 if (init_keys() < 0) {
2927 log_err(LD_GENERAL
,"Error initializing keys; exiting.");
2930 if (!(k
= get_server_identity_key())) {
2931 log_err(LD_GENERAL
,"Error: missing identity key.");
2934 if (crypto_pk_get_fingerprint(k
, buf
, 1)<0) {
2935 log_err(LD_BUG
, "Error computing fingerprint");
2938 printf("%s %s\n", nickname
, buf
);
2942 /** Entry point for password hashing: take the desired password from
2943 * the command line, and print its salted hash to stdout. **/
2945 do_hash_password(void)
2949 char key
[S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
];
2951 crypto_rand(key
, S2K_RFC2440_SPECIFIER_LEN
-1);
2952 key
[S2K_RFC2440_SPECIFIER_LEN
-1] = (uint8_t)96; /* Hash 64 K of data. */
2953 secret_to_key_rfc2440(key
+S2K_RFC2440_SPECIFIER_LEN
, DIGEST_LEN
,
2954 get_options()->command_arg
, strlen(get_options()->command_arg
),
2956 base16_encode(output
, sizeof(output
), key
, sizeof(key
));
2957 printf("16:%s\n",output
);
2960 /** Entry point for configuration dumping: write the configuration to
2963 do_dump_config(void)
2965 const or_options_t
*options
= get_options();
2966 const char *arg
= options
->command_arg
;
2970 if (!strcmp(arg
, "short")) {
2971 how
= OPTIONS_DUMP_MINIMAL
;
2972 } else if (!strcmp(arg
, "non-builtin")) {
2973 how
= OPTIONS_DUMP_DEFAULTS
;
2974 } else if (!strcmp(arg
, "full")) {
2975 how
= OPTIONS_DUMP_ALL
;
2977 fprintf(stderr
, "No valid argument to --dump-config found!\n");
2978 fprintf(stderr
, "Please select 'short', 'non-builtin', or 'full'.\n");
2983 opts
= options_dump(options
, how
);
2995 // host name to sandbox
2996 gethostname(hname
, sizeof(hname
));
2997 sandbox_add_addrinfo(hname
);
3000 static sandbox_cfg_t
*
3001 sandbox_init_filter(void)
3003 const or_options_t
*options
= get_options();
3004 sandbox_cfg_t
*cfg
= sandbox_cfg_new();
3007 sandbox_cfg_allow_openat_filename(&cfg
,
3008 get_datadir_fname("cached-status"));
3010 #define OPEN(name) \
3011 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
3013 #define OPEN_DATADIR(name) \
3014 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
3016 #define OPEN_DATADIR2(name, name2) \
3017 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
3019 #define OPEN_DATADIR_SUFFIX(name, suffix) do { \
3020 OPEN_DATADIR(name); \
3021 OPEN_DATADIR(name suffix); \
3024 #define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
3025 OPEN_DATADIR2(name, name2); \
3026 OPEN_DATADIR2(name, name2 suffix); \
3029 OPEN_DATADIR_SUFFIX("cached-certs", ".tmp");
3030 OPEN_DATADIR_SUFFIX("cached-consensus", ".tmp");
3031 OPEN_DATADIR_SUFFIX("unverified-consensus", ".tmp");
3032 OPEN_DATADIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
3033 OPEN_DATADIR_SUFFIX("cached-microdesc-consensus", ".tmp");
3034 OPEN_DATADIR_SUFFIX("cached-microdescs", ".tmp");
3035 OPEN_DATADIR_SUFFIX("cached-microdescs.new", ".tmp");
3036 OPEN_DATADIR_SUFFIX("cached-descriptors", ".tmp");
3037 OPEN_DATADIR_SUFFIX("cached-descriptors.new", ".tmp");
3038 OPEN_DATADIR("cached-descriptors.tmp.tmp");
3039 OPEN_DATADIR_SUFFIX("cached-extrainfo", ".tmp");
3040 OPEN_DATADIR_SUFFIX("cached-extrainfo.new", ".tmp");
3041 OPEN_DATADIR("cached-extrainfo.tmp.tmp");
3042 OPEN_DATADIR_SUFFIX("state", ".tmp");
3043 OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
3044 OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
3045 OPEN_DATADIR("key-pinning-journal");
3046 OPEN("/dev/srandom");
3047 OPEN("/dev/urandom");
3048 OPEN("/dev/random");
3050 OPEN("/proc/meminfo");
3052 if (options
->BridgeAuthoritativeDir
)
3053 OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
3055 if (authdir_mode_handles_descs(options
, -1))
3056 OPEN_DATADIR("approved-routers");
3058 if (options
->ServerDNSResolvConfFile
)
3059 sandbox_cfg_allow_open_filename(&cfg
,
3060 tor_strdup(options
->ServerDNSResolvConfFile
));
3062 sandbox_cfg_allow_open_filename(&cfg
, tor_strdup("/etc/resolv.conf"));
3064 for (i
= 0; i
< 2; ++i
) {
3065 if (get_torrc_fname(i
)) {
3066 sandbox_cfg_allow_open_filename(&cfg
, tor_strdup(get_torrc_fname(i
)));
3070 #define RENAME_SUFFIX(name, suffix) \
3071 sandbox_cfg_allow_rename(&cfg, \
3072 get_datadir_fname(name suffix), \
3073 get_datadir_fname(name))
3075 #define RENAME_SUFFIX2(prefix, name, suffix) \
3076 sandbox_cfg_allow_rename(&cfg, \
3077 get_datadir_fname2(prefix, name suffix), \
3078 get_datadir_fname2(prefix, name))
3080 RENAME_SUFFIX("cached-certs", ".tmp");
3081 RENAME_SUFFIX("cached-consensus", ".tmp");
3082 RENAME_SUFFIX("unverified-consensus", ".tmp");
3083 RENAME_SUFFIX("unverified-microdesc-consensus", ".tmp");
3084 RENAME_SUFFIX("cached-microdesc-consensus", ".tmp");
3085 RENAME_SUFFIX("cached-microdescs", ".tmp");
3086 RENAME_SUFFIX("cached-microdescs", ".new");
3087 RENAME_SUFFIX("cached-microdescs.new", ".tmp");
3088 RENAME_SUFFIX("cached-descriptors", ".tmp");
3089 RENAME_SUFFIX("cached-descriptors", ".new");
3090 RENAME_SUFFIX("cached-descriptors.new", ".tmp");
3091 RENAME_SUFFIX("cached-extrainfo", ".tmp");
3092 RENAME_SUFFIX("cached-extrainfo", ".new");
3093 RENAME_SUFFIX("cached-extrainfo.new", ".tmp");
3094 RENAME_SUFFIX("state", ".tmp");
3095 RENAME_SUFFIX("unparseable-desc", ".tmp");
3096 RENAME_SUFFIX("v3-status-votes", ".tmp");
3098 if (options
->BridgeAuthoritativeDir
)
3099 RENAME_SUFFIX("networkstatus-bridges", ".tmp");
3101 #define STAT_DATADIR(name) \
3102 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
3104 #define STAT_DATADIR2(name, name2) \
3105 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
3108 STAT_DATADIR("lock");
3109 STAT_DATADIR("state");
3110 STAT_DATADIR("router-stability");
3111 STAT_DATADIR("cached-extrainfo.new");
3114 smartlist_t
*files
= smartlist_new();
3115 tor_log_get_logfile_names(files
);
3116 SMARTLIST_FOREACH(files
, char *, file_name
, {
3117 /* steals reference */
3118 sandbox_cfg_allow_open_filename(&cfg
, file_name
);
3120 smartlist_free(files
);
3124 smartlist_t
*files
= smartlist_new();
3125 smartlist_t
*dirs
= smartlist_new();
3126 rend_services_add_filenames_to_lists(files
, dirs
);
3127 SMARTLIST_FOREACH(files
, char *, file_name
, {
3128 char *tmp_name
= NULL
;
3129 tor_asprintf(&tmp_name
, "%s.tmp", file_name
);
3130 sandbox_cfg_allow_rename(&cfg
,
3131 tor_strdup(tmp_name
), tor_strdup(file_name
));
3132 /* steals references */
3133 sandbox_cfg_allow_open_filename(&cfg
, file_name
);
3134 sandbox_cfg_allow_open_filename(&cfg
, tmp_name
);
3136 SMARTLIST_FOREACH(dirs
, char *, dir
, {
3137 /* steals reference */
3138 sandbox_cfg_allow_stat_filename(&cfg
, dir
);
3140 smartlist_free(files
);
3141 smartlist_free(dirs
);
3146 if ((fname
= get_controller_cookie_file_name())) {
3147 sandbox_cfg_allow_open_filename(&cfg
, fname
);
3149 if ((fname
= get_ext_or_auth_cookie_file_name())) {
3150 sandbox_cfg_allow_open_filename(&cfg
, fname
);
3154 if (options
->DirPortFrontPage
) {
3155 sandbox_cfg_allow_open_filename(&cfg
,
3156 tor_strdup(options
->DirPortFrontPage
));
3160 if (server_mode(get_options())) {
3162 OPEN_DATADIR2_SUFFIX("keys", "secret_id_key", ".tmp");
3163 OPEN_DATADIR2_SUFFIX("keys", "secret_onion_key", ".tmp");
3164 OPEN_DATADIR2_SUFFIX("keys", "secret_onion_key_ntor", ".tmp");
3165 OPEN_DATADIR2("keys", "secret_id_key.old");
3166 OPEN_DATADIR2("keys", "secret_onion_key.old");
3167 OPEN_DATADIR2("keys", "secret_onion_key_ntor.old");
3169 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_secret_key", ".tmp");
3170 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_secret_key_encrypted",
3172 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_public_key", ".tmp");
3173 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_secret_key", ".tmp");
3174 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_cert", ".tmp");
3176 OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
3177 OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
3179 OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
3180 OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
3181 OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
3182 OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
3184 OPEN_DATADIR("approved-routers");
3185 OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
3186 OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
3187 OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
3189 OPEN("/etc/resolv.conf");
3191 RENAME_SUFFIX("fingerprint", ".tmp");
3192 RENAME_SUFFIX2("keys", "secret_onion_key_ntor", ".tmp");
3193 RENAME_SUFFIX2("keys", "secret_id_key", ".tmp");
3194 RENAME_SUFFIX2("keys", "secret_id_key.old", ".tmp");
3195 RENAME_SUFFIX2("keys", "secret_onion_key", ".tmp");
3196 RENAME_SUFFIX2("keys", "secret_onion_key.old", ".tmp");
3197 RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
3198 RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
3199 RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
3200 RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
3201 RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
3202 RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
3203 RENAME_SUFFIX2("stats", "hidserv-stats", ".tmp");
3204 RENAME_SUFFIX("hashed-fingerprint", ".tmp");
3205 RENAME_SUFFIX("router-stability", ".tmp");
3207 RENAME_SUFFIX2("keys", "ed25519_master_id_secret_key", ".tmp");
3208 RENAME_SUFFIX2("keys", "ed25519_master_id_secret_key_encrypted", ".tmp");
3209 RENAME_SUFFIX2("keys", "ed25519_master_id_public_key", ".tmp");
3210 RENAME_SUFFIX2("keys", "ed25519_signing_secret_key", ".tmp");
3211 RENAME_SUFFIX2("keys", "ed25519_signing_cert", ".tmp");
3213 sandbox_cfg_allow_rename(&cfg
,
3214 get_datadir_fname2("keys", "secret_onion_key"),
3215 get_datadir_fname2("keys", "secret_onion_key.old"));
3216 sandbox_cfg_allow_rename(&cfg
,
3217 get_datadir_fname2("keys", "secret_onion_key_ntor"),
3218 get_datadir_fname2("keys", "secret_onion_key_ntor.old"));
3220 STAT_DATADIR("keys");
3221 STAT_DATADIR("stats");
3222 STAT_DATADIR2("stats", "dirreq-stats");
3230 /** Main entry point for the Tor process. Called from main(). */
3231 /* This function is distinct from main() only so we can link main.c into
3232 * the unittest binary without conflicting with the unittests' main. */
3234 tor_main(int argc
, char *argv
[])
3239 /* Call SetProcessDEPPolicy to permanently enable DEP.
3240 The function will not resolve on earlier versions of Windows,
3241 and failure is not dangerous. */
3242 HMODULE hMod
= GetModuleHandleA("Kernel32.dll");
3244 typedef BOOL (WINAPI
*PSETDEP
)(DWORD
);
3245 PSETDEP setdeppolicy
= (PSETDEP
)GetProcAddress(hMod
,
3246 "SetProcessDEPPolicy");
3247 if (setdeppolicy
) setdeppolicy(1); /* PROCESS_DEP_ENABLE */
3251 configure_backtrace_handler(get_version());
3253 update_approx_time(time(NULL
));
3258 /* Instruct OpenSSL to use our internal wrappers for malloc,
3259 realloc and free. */
3260 int r
= CRYPTO_set_mem_ex_functions(tor_malloc_
, tor_realloc_
, tor_free_
);
3267 result
= nt_service_parse_options(argc
, argv
, &done
);
3268 if (done
) return result
;
3271 if (tor_init(argc
, argv
)<0)
3274 if (get_options()->Sandbox
&& get_options()->command
== CMD_RUN_TOR
) {
3275 sandbox_cfg_t
* cfg
= sandbox_init_filter();
3277 if (sandbox_init(cfg
)) {
3278 log_err(LD_BUG
,"Failed to create syscall sandbox filter");
3282 // registering libevent rng
3283 #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
3284 evutil_secure_rng_set_urandom_device_file(
3285 (char*) sandbox_intern_string("/dev/urandom"));
3289 switch (get_options()->command
) {
3292 nt_service_set_state(SERVICE_RUNNING
);
3294 result
= do_main_loop();
3297 result
= load_ed_keys(get_options(), time(NULL
));
3299 case CMD_LIST_FINGERPRINT
:
3300 result
= do_list_fingerprint();
3302 case CMD_HASH_PASSWORD
:
3306 case CMD_VERIFY_CONFIG
:
3307 if (quiet_level
== 0)
3308 printf("Configuration was valid\n");
3311 case CMD_DUMP_CONFIG
:
3312 result
= do_dump_config();
3314 case CMD_RUN_UNITTESTS
: /* only set by test.c */
3316 log_warn(LD_BUG
,"Illegal command number %d: internal error.",
3317 get_options()->command
);