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-2016, 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"
49 #include "transports.h"
51 #include "rendclient.h"
52 #include "rendcommon.h"
53 #include "rendservice.h"
56 #include "routerkeys.h"
57 #include "routerlist.h"
58 #include "routerparse.h"
59 #include "scheduler.h"
60 #include "shared_random.h"
61 #include "statefile.h"
63 #include "util_process.h"
64 #include "ext_orport.h"
67 #include <openssl/crypto.h>
72 #include <event2/event.h>
75 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
76 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
77 * Coverity. Here's a kludge to unconfuse it.
79 # define __INCLUDE_LEVEL__ 2
81 #include <systemd/sd-daemon.h>
84 void evdns_shutdown(int);
86 /********* PROTOTYPES **********/
88 static void dumpmemusage(int severity
);
89 static void dumpstats(int severity
); /* log stats */
90 static void conn_read_callback(evutil_socket_t fd
, short event
, void *_conn
);
91 static void conn_write_callback(evutil_socket_t fd
, short event
, void *_conn
);
92 static void second_elapsed_callback(periodic_timer_t
*timer
, void *args
);
93 static int conn_close_if_marked(int i
);
94 static void connection_start_reading_from_linked_conn(connection_t
*conn
);
95 static int connection_should_read_from_linked_conn(connection_t
*conn
);
96 static int run_main_loop_until_done(void);
97 static void process_signal(int sig
);
99 /********* START VARIABLES **********/
100 int global_read_bucket
; /**< Max number of bytes I can read this second. */
101 int global_write_bucket
; /**< Max number of bytes I can write this second. */
103 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
104 int global_relayed_read_bucket
;
105 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
106 int global_relayed_write_bucket
;
107 /** What was the read bucket before the last second_elapsed_callback() call?
108 * (used to determine how many bytes we've read). */
109 static int stats_prev_global_read_bucket
;
110 /** What was the write bucket before the last second_elapsed_callback() call?
111 * (used to determine how many bytes we've written). */
112 static int stats_prev_global_write_bucket
;
114 /* DOCDOC stats_prev_n_read */
115 static uint64_t stats_prev_n_read
= 0;
116 /* DOCDOC stats_prev_n_written */
117 static uint64_t stats_prev_n_written
= 0;
119 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
120 /** How many bytes have we read since we started the process? */
121 static uint64_t stats_n_bytes_read
= 0;
122 /** How many bytes have we written since we started the process? */
123 static uint64_t stats_n_bytes_written
= 0;
124 /** What time did this process start up? */
125 time_t time_of_process_start
= 0;
126 /** How many seconds have we been running? */
127 long stats_n_seconds_working
= 0;
129 /** How often will we honor SIGNEWNYM requests? */
130 #define MAX_SIGNEWNYM_RATE 10
131 /** When did we last process a SIGNEWNYM request? */
132 static time_t time_of_last_signewnym
= 0;
133 /** Is there a signewnym request we're currently waiting to handle? */
134 static int signewnym_is_pending
= 0;
135 /** How many times have we called newnym? */
136 static unsigned newnym_epoch
= 0;
138 /** Smartlist of all open connections. */
139 static smartlist_t
*connection_array
= NULL
;
140 /** List of connections that have been marked for close and need to be freed
141 * and removed from connection_array. */
142 static smartlist_t
*closeable_connection_lst
= NULL
;
143 /** List of linked connections that are currently reading data into their
144 * inbuf from their partner's outbuf. */
145 static smartlist_t
*active_linked_connection_lst
= NULL
;
146 /** Flag: Set to true iff we entered the current libevent main loop via
147 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
148 * to handle linked connections. */
149 static int called_loop_once
= 0;
151 /** We set this to 1 when we've opened a circuit, so we can print a log
152 * entry to inform the user that Tor is working. We set it to 0 when
153 * we think the fact that we once opened a circuit doesn't mean we can do so
154 * any longer (a big time jump happened, when we notice our directory is
155 * heinously out-of-date, etc.
157 static int can_complete_circuits
= 0;
159 /** How often do we check for router descriptors that we should download
160 * when we have too little directory info? */
161 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
162 /** How often do we check for router descriptors that we should download
163 * when we have enough directory info? */
164 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
166 /** Decides our behavior when no logs are configured/before any
167 * logs have been configured. For 0, we log notice to stdout as normal.
168 * For 1, we log warnings only. For 2, we log nothing.
172 /********* END VARIABLES ************/
174 /****************************************************************************
176 * This section contains accessors and other methods on the connection_array
177 * variables (which are global within this file and unavailable outside it).
179 ****************************************************************************/
181 /** Return 1 if we have successfully built a circuit, and nothing has changed
182 * to make us think that maybe we can't.
185 have_completed_a_circuit(void)
187 return can_complete_circuits
;
190 /** Note that we have successfully built a circuit, so that reachability
191 * testing and introduction points and so on may be attempted. */
193 note_that_we_completed_a_circuit(void)
195 can_complete_circuits
= 1;
198 /** Note that something has happened (like a clock jump, or DisableNetwork) to
199 * make us think that maybe we can't complete circuits. */
201 note_that_we_maybe_cant_complete_circuits(void)
203 can_complete_circuits
= 0;
206 /** Add <b>conn</b> to the array of connections that we can poll on. The
207 * connection's socket must be set; the connection starts out
208 * non-reading and non-writing.
211 connection_add_impl(connection_t
*conn
, int is_connecting
)
214 tor_assert(SOCKET_OK(conn
->s
) ||
216 (conn
->type
== CONN_TYPE_AP
&&
217 TO_EDGE_CONN(conn
)->is_dns_request
));
219 tor_assert(conn
->conn_array_index
== -1); /* can only connection_add once */
220 conn
->conn_array_index
= smartlist_len(connection_array
);
221 smartlist_add(connection_array
, conn
);
223 (void) is_connecting
;
225 if (SOCKET_OK(conn
->s
) || conn
->linked
) {
226 conn
->read_event
= tor_event_new(tor_libevent_get_base(),
227 conn
->s
, EV_READ
|EV_PERSIST
, conn_read_callback
, conn
);
228 conn
->write_event
= tor_event_new(tor_libevent_get_base(),
229 conn
->s
, EV_WRITE
|EV_PERSIST
, conn_write_callback
, conn
);
230 /* XXXX CHECK FOR NULL RETURN! */
233 log_debug(LD_NET
,"new conn type %s, socket %d, address %s, n_conns %d.",
234 conn_type_to_string(conn
->type
), (int)conn
->s
, conn
->address
,
235 smartlist_len(connection_array
));
240 /** Tell libevent that we don't care about <b>conn</b> any more. */
242 connection_unregister_events(connection_t
*conn
)
244 if (conn
->read_event
) {
245 if (event_del(conn
->read_event
))
246 log_warn(LD_BUG
, "Error removing read event for %d", (int)conn
->s
);
247 tor_free(conn
->read_event
);
249 if (conn
->write_event
) {
250 if (event_del(conn
->write_event
))
251 log_warn(LD_BUG
, "Error removing write event for %d", (int)conn
->s
);
252 tor_free(conn
->write_event
);
254 if (conn
->type
== CONN_TYPE_AP_DNS_LISTENER
) {
255 dnsserv_close_listener(conn
);
259 /** Remove the connection from the global list, and remove the
260 * corresponding poll entry. Calling this function will shift the last
261 * connection (if any) into the position occupied by conn.
264 connection_remove(connection_t
*conn
)
271 log_debug(LD_NET
,"removing socket %d (type %s), n_conns now %d",
272 (int)conn
->s
, conn_type_to_string(conn
->type
),
273 smartlist_len(connection_array
));
275 if (conn
->type
== CONN_TYPE_AP
&& conn
->socket_family
== AF_UNIX
) {
276 log_info(LD_NET
, "Closing SOCKS SocksSocket connection");
279 control_event_conn_bandwidth(conn
);
281 tor_assert(conn
->conn_array_index
>= 0);
282 current_index
= conn
->conn_array_index
;
283 connection_unregister_events(conn
); /* This is redundant, but cheap. */
284 if (current_index
== smartlist_len(connection_array
)-1) { /* at the end */
285 smartlist_del(connection_array
, current_index
);
289 /* replace this one with the one at the end */
290 smartlist_del(connection_array
, current_index
);
291 tmp
= smartlist_get(connection_array
, current_index
);
292 tmp
->conn_array_index
= current_index
;
297 /** If <b>conn</b> is an edge conn, remove it from the list
298 * of conn's on this circuit. If it's not on an edge,
299 * flush and send destroys for all circuits on this conn.
301 * Remove it from connection_array (if applicable) and
302 * from closeable_connection_list.
307 connection_unlink(connection_t
*conn
)
309 connection_about_to_close_connection(conn
);
310 if (conn
->conn_array_index
>= 0) {
311 connection_remove(conn
);
313 if (conn
->linked_conn
) {
314 conn
->linked_conn
->linked_conn
= NULL
;
315 if (! conn
->linked_conn
->marked_for_close
&&
316 conn
->linked_conn
->reading_from_linked_conn
)
317 connection_start_reading(conn
->linked_conn
);
318 conn
->linked_conn
= NULL
;
320 smartlist_remove(closeable_connection_lst
, conn
);
321 smartlist_remove(active_linked_connection_lst
, conn
);
322 if (conn
->type
== CONN_TYPE_EXIT
) {
323 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn
));
325 if (conn
->type
== CONN_TYPE_OR
) {
326 if (!tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
))
327 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
328 /* connection_unlink() can only get called if the connection
329 * was already on the closeable list, and it got there by
330 * connection_mark_for_close(), which was called from
331 * connection_or_close_normally() or
332 * connection_or_close_for_error(), so the channel should
333 * already be in CHANNEL_STATE_CLOSING, and then the
334 * connection_about_to_close_connection() goes to
335 * connection_or_about_to_close(), which calls channel_closed()
336 * to notify the channel_t layer, and closed the channel, so
337 * nothing more to do here to deal with the channel associated
341 connection_free(conn
);
344 /** Initialize the global connection list, closeable connection list,
345 * and active connection list. */
347 init_connection_lists(void)
349 if (!connection_array
)
350 connection_array
= smartlist_new();
351 if (!closeable_connection_lst
)
352 closeable_connection_lst
= smartlist_new();
353 if (!active_linked_connection_lst
)
354 active_linked_connection_lst
= smartlist_new();
357 /** Schedule <b>conn</b> to be closed. **/
359 add_connection_to_closeable_list(connection_t
*conn
)
361 tor_assert(!smartlist_contains(closeable_connection_lst
, conn
));
362 tor_assert(conn
->marked_for_close
);
363 assert_connection_ok(conn
, time(NULL
));
364 smartlist_add(closeable_connection_lst
, conn
);
367 /** Return 1 if conn is on the closeable list, else return 0. */
369 connection_is_on_closeable_list(connection_t
*conn
)
371 return smartlist_contains(closeable_connection_lst
, conn
);
374 /** Return true iff conn is in the current poll array. */
376 connection_in_array(connection_t
*conn
)
378 return smartlist_contains(connection_array
, conn
);
381 /** Set <b>*array</b> to an array of all connections. <b>*array</b> must not
384 MOCK_IMPL(smartlist_t
*,
385 get_connection_array
, (void))
387 if (!connection_array
)
388 connection_array
= smartlist_new();
389 return connection_array
;
392 /** Provides the traffic read and written over the life of the process. */
395 get_bytes_read
,(void))
397 return stats_n_bytes_read
;
400 /* DOCDOC get_bytes_written */
402 get_bytes_written
,(void))
404 return stats_n_bytes_written
;
407 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
408 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
411 connection_watch_events(connection_t
*conn
, watchable_events_t events
)
413 if (events
& READ_EVENT
)
414 connection_start_reading(conn
);
416 connection_stop_reading(conn
);
418 if (events
& WRITE_EVENT
)
419 connection_start_writing(conn
);
421 connection_stop_writing(conn
);
424 /** Return true iff <b>conn</b> is listening for read events. */
426 connection_is_reading(connection_t
*conn
)
430 return conn
->reading_from_linked_conn
||
431 (conn
->read_event
&& event_pending(conn
->read_event
, EV_READ
, NULL
));
434 /** Check whether <b>conn</b> is correct in having (or not having) a
435 * read/write event (passed in <b>ev</b>). On success, return 0. On failure,
436 * log a warning and return -1. */
438 connection_check_event(connection_t
*conn
, struct event
*ev
)
442 if (conn
->type
== CONN_TYPE_AP
&& TO_EDGE_CONN(conn
)->is_dns_request
) {
443 /* DNS requests which we launch through the dnsserv.c module do not have
444 * any underlying socket or any underlying linked connection, so they
445 * shouldn't have any attached events either.
449 /* Everytyhing else should have an underlying socket, or a linked
450 * connection (which is also tracked with a read_event/write_event pair).
456 log_warn(LD_BUG
, "Event missing on connection %p [%s;%s]. "
457 "socket=%d. linked=%d. "
458 "is_dns_request=%d. Marked_for_close=%s:%d",
460 conn_type_to_string(conn
->type
),
461 conn_state_to_string(conn
->type
, conn
->state
),
462 (int)conn
->s
, (int)conn
->linked
,
463 (conn
->type
== CONN_TYPE_AP
&&
464 TO_EDGE_CONN(conn
)->is_dns_request
),
465 conn
->marked_for_close_file
? conn
->marked_for_close_file
: "-",
466 conn
->marked_for_close
468 log_backtrace(LOG_WARN
, LD_BUG
, "Backtrace attached.");
474 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
476 connection_stop_reading
,(connection_t
*conn
))
480 if (connection_check_event(conn
, conn
->read_event
) < 0) {
485 conn
->reading_from_linked_conn
= 0;
486 connection_stop_reading_from_linked_conn(conn
);
488 if (event_del(conn
->read_event
))
489 log_warn(LD_NET
, "Error from libevent setting read event state for %d "
492 tor_socket_strerror(tor_socket_errno(conn
->s
)));
496 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
498 connection_start_reading
,(connection_t
*conn
))
502 if (connection_check_event(conn
, conn
->read_event
) < 0) {
507 conn
->reading_from_linked_conn
= 1;
508 if (connection_should_read_from_linked_conn(conn
))
509 connection_start_reading_from_linked_conn(conn
);
511 if (event_add(conn
->read_event
, NULL
))
512 log_warn(LD_NET
, "Error from libevent setting read event state for %d "
515 tor_socket_strerror(tor_socket_errno(conn
->s
)));
519 /** Return true iff <b>conn</b> is listening for write events. */
521 connection_is_writing(connection_t
*conn
)
525 return conn
->writing_to_linked_conn
||
526 (conn
->write_event
&& event_pending(conn
->write_event
, EV_WRITE
, NULL
));
529 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
531 connection_stop_writing
,(connection_t
*conn
))
535 if (connection_check_event(conn
, conn
->write_event
) < 0) {
540 conn
->writing_to_linked_conn
= 0;
541 if (conn
->linked_conn
)
542 connection_stop_reading_from_linked_conn(conn
->linked_conn
);
544 if (event_del(conn
->write_event
))
545 log_warn(LD_NET
, "Error from libevent setting write event state for %d "
548 tor_socket_strerror(tor_socket_errno(conn
->s
)));
552 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
554 connection_start_writing
,(connection_t
*conn
))
558 if (connection_check_event(conn
, conn
->write_event
) < 0) {
563 conn
->writing_to_linked_conn
= 1;
564 if (conn
->linked_conn
&&
565 connection_should_read_from_linked_conn(conn
->linked_conn
))
566 connection_start_reading_from_linked_conn(conn
->linked_conn
);
568 if (event_add(conn
->write_event
, NULL
))
569 log_warn(LD_NET
, "Error from libevent setting write event state for %d "
572 tor_socket_strerror(tor_socket_errno(conn
->s
)));
576 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
577 * linked to it would be good and feasible. (Reading is "feasible" if the
578 * other conn exists and has data in its outbuf, and is "good" if we have our
579 * reading_from_linked_conn flag set and the other conn has its
580 * writing_to_linked_conn flag set.)*/
582 connection_should_read_from_linked_conn(connection_t
*conn
)
584 if (conn
->linked
&& conn
->reading_from_linked_conn
) {
585 if (! conn
->linked_conn
||
586 (conn
->linked_conn
->writing_to_linked_conn
&&
587 buf_datalen(conn
->linked_conn
->outbuf
)))
593 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
594 * its linked connection, if it is not doing so already. Called by
595 * connection_start_reading and connection_start_writing as appropriate. */
597 connection_start_reading_from_linked_conn(connection_t
*conn
)
600 tor_assert(conn
->linked
== 1);
602 if (!conn
->active_on_link
) {
603 conn
->active_on_link
= 1;
604 smartlist_add(active_linked_connection_lst
, conn
);
605 if (!called_loop_once
) {
606 /* This is the first event on the list; we won't be in LOOP_ONCE mode,
607 * so we need to make sure that the event_base_loop() actually exits at
608 * the end of its run through the current connections and lets us
609 * activate read events for linked connections. */
610 struct timeval tv
= { 0, 0 };
611 tor_event_base_loopexit(tor_libevent_get_base(), &tv
);
614 tor_assert(smartlist_contains(active_linked_connection_lst
, conn
));
618 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
619 * connection, if is currently doing so. Called by connection_stop_reading,
620 * connection_stop_writing, and connection_read. */
622 connection_stop_reading_from_linked_conn(connection_t
*conn
)
625 tor_assert(conn
->linked
== 1);
627 if (conn
->active_on_link
) {
628 conn
->active_on_link
= 0;
629 /* FFFF We could keep an index here so we can smartlist_del
630 * cleanly. On the other hand, this doesn't show up on profiles,
631 * so let's leave it alone for now. */
632 smartlist_remove(active_linked_connection_lst
, conn
);
634 tor_assert(!smartlist_contains(active_linked_connection_lst
, conn
));
638 /** Close all connections that have been scheduled to get closed. */
640 close_closeable_connections(void)
643 for (i
= 0; i
< smartlist_len(closeable_connection_lst
); ) {
644 connection_t
*conn
= smartlist_get(closeable_connection_lst
, i
);
645 if (conn
->conn_array_index
< 0) {
646 connection_unlink(conn
); /* blow it away right now */
648 if (!conn_close_if_marked(conn
->conn_array_index
))
654 /** Count moribund connections for the OOS handler */
656 connection_count_moribund
, (void))
661 * Count things we'll try to kill when close_closeable_connections()
664 SMARTLIST_FOREACH_BEGIN(closeable_connection_lst
, connection_t
*, conn
) {
665 if (SOCKET_OK(conn
->s
) && connection_is_moribund(conn
)) ++moribund
;
666 } SMARTLIST_FOREACH_END(conn
);
671 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
672 * some data to read. */
674 conn_read_callback(evutil_socket_t fd
, short event
, void *_conn
)
676 connection_t
*conn
= _conn
;
680 log_debug(LD_NET
,"socket %d wants to read.",(int)conn
->s
);
682 /* assert_connection_ok(conn, time(NULL)); */
684 if (connection_handle_read(conn
) < 0) {
685 if (!conn
->marked_for_close
) {
687 log_warn(LD_BUG
,"Unhandled error on read for %s connection "
689 conn_type_to_string(conn
->type
), (int)conn
->s
);
690 tor_fragile_assert();
692 if (CONN_IS_EDGE(conn
))
693 connection_edge_end_errno(TO_EDGE_CONN(conn
));
694 connection_mark_for_close(conn
);
697 assert_connection_ok(conn
, time(NULL
));
699 if (smartlist_len(closeable_connection_lst
))
700 close_closeable_connections();
703 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
704 * some data to write. */
706 conn_write_callback(evutil_socket_t fd
, short events
, void *_conn
)
708 connection_t
*conn
= _conn
;
712 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "socket %d wants to write.",
715 /* assert_connection_ok(conn, time(NULL)); */
717 if (connection_handle_write(conn
, 0) < 0) {
718 if (!conn
->marked_for_close
) {
719 /* this connection is broken. remove it. */
720 log_fn(LOG_WARN
,LD_BUG
,
721 "unhandled error on write for %s connection (fd %d); removing",
722 conn_type_to_string(conn
->type
), (int)conn
->s
);
723 tor_fragile_assert();
724 if (CONN_IS_EDGE(conn
)) {
725 /* otherwise we cry wolf about duplicate close */
726 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
727 if (!edge_conn
->end_reason
)
728 edge_conn
->end_reason
= END_STREAM_REASON_INTERNAL
;
729 edge_conn
->edge_has_sent_end
= 1;
731 connection_close_immediate(conn
); /* So we don't try to flush. */
732 connection_mark_for_close(conn
);
735 assert_connection_ok(conn
, time(NULL
));
737 if (smartlist_len(closeable_connection_lst
))
738 close_closeable_connections();
741 /** If the connection at connection_array[i] is marked for close, then:
742 * - If it has data that it wants to flush, try to flush it.
743 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
744 * true, then leave the connection open and return.
745 * - Otherwise, remove the connection from connection_array and from
746 * all other lists, close it, and free it.
747 * Returns 1 if the connection was closed, 0 otherwise.
750 conn_close_if_marked(int i
)
756 conn
= smartlist_get(connection_array
, i
);
757 if (!conn
->marked_for_close
)
758 return 0; /* nothing to see here, move along */
760 assert_connection_ok(conn
, now
);
761 /* assert_all_pending_dns_resolves_ok(); */
763 log_debug(LD_NET
,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT
").",
766 /* If the connection we are about to close was trying to connect to
767 a proxy server and failed, the client won't be able to use that
768 proxy. We should warn the user about this. */
769 if (conn
->proxy_state
== PROXY_INFANT
)
770 log_failed_proxy_connection(conn
);
772 if ((SOCKET_OK(conn
->s
) || conn
->linked_conn
) &&
773 connection_wants_to_flush(conn
)) {
774 /* s == -1 means it's an incomplete edge connection, or that the socket
775 * has already been closed as unflushable. */
776 ssize_t sz
= connection_bucket_write_limit(conn
, now
);
777 if (!conn
->hold_open_until_flushed
)
779 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
780 "to flush %d bytes. (Marked at %s:%d)",
781 escaped_safe_str_client(conn
->address
),
782 (int)conn
->s
, conn_type_to_string(conn
->type
), conn
->state
,
783 (int)conn
->outbuf_flushlen
,
784 conn
->marked_for_close_file
, conn
->marked_for_close
);
785 if (conn
->linked_conn
) {
786 retval
= move_buf_to_buf(conn
->linked_conn
->inbuf
, conn
->outbuf
,
787 &conn
->outbuf_flushlen
);
789 /* The linked conn will notice that it has data when it notices that
791 connection_start_reading_from_linked_conn(conn
->linked_conn
);
793 log_debug(LD_GENERAL
, "Flushed last %d bytes from a linked conn; "
794 "%d left; flushlen %d; wants-to-flush==%d", retval
,
795 (int)connection_get_outbuf_len(conn
),
796 (int)conn
->outbuf_flushlen
,
797 connection_wants_to_flush(conn
));
798 } else if (connection_speaks_cells(conn
)) {
799 if (conn
->state
== OR_CONN_STATE_OPEN
) {
800 retval
= flush_buf_tls(TO_OR_CONN(conn
)->tls
, conn
->outbuf
, sz
,
801 &conn
->outbuf_flushlen
);
803 retval
= -1; /* never flush non-open broken tls connections */
805 retval
= flush_buf(conn
->s
, conn
->outbuf
, sz
, &conn
->outbuf_flushlen
);
807 if (retval
>= 0 && /* Technically, we could survive things like
808 TLS_WANT_WRITE here. But don't bother for now. */
809 conn
->hold_open_until_flushed
&& connection_wants_to_flush(conn
)) {
811 LOG_FN_CONN(conn
, (LOG_INFO
,LD_NET
,
812 "Holding conn (fd %d) open for more flushing.",
814 conn
->timestamp_lastwritten
= now
; /* reset so we can flush more */
815 } else if (sz
== 0) {
816 /* Also, retval==0. If we get here, we didn't want to write anything
817 * (because of rate-limiting) and we didn't. */
819 /* Connection must flush before closing, but it's being rate-limited.
820 * Let's remove from Libevent, and mark it as blocked on bandwidth
821 * so it will be re-added on next token bucket refill. Prevents
822 * busy Libevent loops where we keep ending up here and returning
823 * 0 until we are no longer blocked on bandwidth.
825 if (connection_is_writing(conn
)) {
826 conn
->write_blocked_on_bw
= 1;
827 connection_stop_writing(conn
);
829 if (connection_is_reading(conn
)) {
830 /* XXXX+ We should make this code unreachable; if a connection is
831 * marked for close and flushing, there is no point in reading to it
832 * at all. Further, checking at this point is a bit of a hack: it
833 * would make much more sense to react in
834 * connection_handle_read_impl, or to just stop reading in
836 conn
->read_blocked_on_bw
= 1;
837 connection_stop_reading(conn
);
842 if (connection_wants_to_flush(conn
)) {
843 log_fn(LOG_INFO
, LD_NET
, "We stalled too much while trying to write %d "
844 "bytes to address %s. If this happens a lot, either "
845 "something is wrong with your network connection, or "
846 "something is wrong with theirs. "
847 "(fd %d, type %s, state %d, marked at %s:%d).",
848 (int)connection_get_outbuf_len(conn
),
849 escaped_safe_str_client(conn
->address
),
850 (int)conn
->s
, conn_type_to_string(conn
->type
), conn
->state
,
851 conn
->marked_for_close_file
,
852 conn
->marked_for_close
);
856 connection_unlink(conn
); /* unlink, remove, free */
860 /** Implementation for directory_all_unreachable. This is done in a callback,
861 * since otherwise it would complicate Tor's control-flow graph beyond all
865 directory_all_unreachable_cb(evutil_socket_t fd
, short event
, void *arg
)
873 while ((conn
= connection_get_by_type_state(CONN_TYPE_AP
,
874 AP_CONN_STATE_CIRCUIT_WAIT
))) {
875 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(conn
);
877 "Is your network connection down? "
878 "Failing connection to '%s:%d'.",
879 safe_str_client(entry_conn
->socks_request
->address
),
880 entry_conn
->socks_request
->port
);
881 connection_mark_unattached_ap(entry_conn
,
882 END_STREAM_REASON_NET_UNREACHABLE
);
884 control_event_general_error("DIR_ALL_UNREACHABLE");
887 static struct event
*directory_all_unreachable_cb_event
= NULL
;
889 /** We've just tried every dirserver we know about, and none of
890 * them were reachable. Assume the network is down. Change state
891 * so next time an application connection arrives we'll delay it
892 * and try another directory fetch. Kill off all the circuit_wait
893 * streams that are waiting now, since they will all timeout anyway.
896 directory_all_unreachable(time_t now
)
900 stats_n_seconds_working
=0; /* reset it */
902 if (!directory_all_unreachable_cb_event
) {
903 directory_all_unreachable_cb_event
=
904 tor_event_new(tor_libevent_get_base(),
905 -1, EV_READ
, directory_all_unreachable_cb
, NULL
);
906 tor_assert(directory_all_unreachable_cb_event
);
909 event_active(directory_all_unreachable_cb_event
, EV_READ
, 1);
912 /** This function is called whenever we successfully pull down some new
913 * network statuses or server descriptors. */
915 directory_info_has_arrived(time_t now
, int from_cache
, int suppress_logs
)
917 const or_options_t
*options
= get_options();
919 if (!router_have_minimum_dir_info()) {
920 int quiet
= suppress_logs
|| from_cache
||
921 directory_too_idle_to_fetch_descriptors(options
, now
);
922 tor_log(quiet
? LOG_INFO
: LOG_NOTICE
, LD_DIR
,
923 "I learned some more directory information, but not enough to "
924 "build a circuit: %s", get_dir_info_status_string());
925 update_all_descriptor_downloads(now
);
928 if (directory_fetches_from_authorities(options
)) {
929 update_all_descriptor_downloads(now
);
932 /* if we have enough dir info, then update our guard status with
933 * whatever we just learned. */
934 entry_guards_compute_status(options
, now
);
935 /* Don't even bother trying to get extrainfo until the rest of our
936 * directory info is up-to-date */
937 if (options
->DownloadExtraInfo
)
938 update_extrainfo_downloads(now
);
941 if (server_mode(options
) && !net_is_disabled() && !from_cache
&&
942 (have_completed_a_circuit() || !any_predicted_circuits(now
)))
943 consider_testing_reachability(1, 1);
946 /** Perform regular maintenance tasks for a single connection. This
947 * function gets run once per second per connection by run_scheduled_events.
950 run_connection_housekeeping(int i
, time_t now
)
953 connection_t
*conn
= smartlist_get(connection_array
, i
);
954 const or_options_t
*options
= get_options();
955 or_connection_t
*or_conn
;
956 channel_t
*chan
= NULL
;
957 int have_any_circuits
;
959 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
;
961 if (conn
->outbuf
&& !connection_get_outbuf_len(conn
) &&
962 conn
->type
== CONN_TYPE_OR
)
963 TO_OR_CONN(conn
)->timestamp_lastempty
= now
;
965 if (conn
->marked_for_close
) {
966 /* nothing to do here */
970 /* Expire any directory connections that haven't been active (sent
971 * if a server or received if a client) for 5 min */
972 if (conn
->type
== CONN_TYPE_DIR
&&
973 ((DIR_CONN_IS_SERVER(conn
) &&
974 conn
->timestamp_lastwritten
975 + options
->TestingDirConnectionMaxStall
< now
) ||
976 (!DIR_CONN_IS_SERVER(conn
) &&
977 conn
->timestamp_lastread
978 + options
->TestingDirConnectionMaxStall
< now
))) {
979 log_info(LD_DIR
,"Expiring wedged directory conn (fd %d, purpose %d)",
980 (int)conn
->s
, conn
->purpose
);
981 /* This check is temporary; it's to let us know whether we should consider
982 * parsing partial serverdesc responses. */
983 if (conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
984 connection_get_inbuf_len(conn
) >= 1024) {
985 log_info(LD_DIR
,"Trying to extract information from wedged server desc "
987 connection_dir_reached_eof(TO_DIR_CONN(conn
));
989 connection_mark_for_close(conn
);
994 if (!connection_speaks_cells(conn
))
995 return; /* we're all done here, the rest is just for OR conns */
997 /* If we haven't written to an OR connection for a while, then either nuke
998 the connection or send a keepalive, depending. */
1000 or_conn
= TO_OR_CONN(conn
);
1001 tor_assert(conn
->outbuf
);
1003 chan
= TLS_CHAN_TO_BASE(or_conn
->chan
);
1006 if (channel_num_circuits(chan
) != 0) {
1007 have_any_circuits
= 1;
1008 chan
->timestamp_last_had_circuits
= now
;
1010 have_any_circuits
= 0;
1013 if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn
->chan
)) &&
1014 ! have_any_circuits
) {
1015 /* It's bad for new circuits, and has no unmarked circuits on it:
1018 "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1019 (int)conn
->s
, conn
->address
, conn
->port
);
1020 if (conn
->state
== OR_CONN_STATE_CONNECTING
)
1021 connection_or_connect_failed(TO_OR_CONN(conn
),
1022 END_OR_CONN_REASON_TIMEOUT
,
1023 "Tor gave up on the connection");
1024 connection_or_close_normally(TO_OR_CONN(conn
), 1);
1025 } else if (!connection_state_is_open(conn
)) {
1026 if (past_keepalive
) {
1027 /* We never managed to actually get this connection open and happy. */
1028 log_info(LD_OR
,"Expiring non-open OR connection to fd %d (%s:%d).",
1029 (int)conn
->s
,conn
->address
, conn
->port
);
1030 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1032 } else if (we_are_hibernating() &&
1033 ! have_any_circuits
&&
1034 !connection_get_outbuf_len(conn
)) {
1035 /* We're hibernating, there's no circuits, and nothing to flush.*/
1036 log_info(LD_OR
,"Expiring non-used OR connection to fd %d (%s:%d) "
1037 "[Hibernating or exiting].",
1038 (int)conn
->s
,conn
->address
, conn
->port
);
1039 connection_or_close_normally(TO_OR_CONN(conn
), 1);
1040 } else if (!have_any_circuits
&&
1041 now
- or_conn
->idle_timeout
>=
1042 chan
->timestamp_last_had_circuits
) {
1043 log_info(LD_OR
,"Expiring non-used OR connection to fd %d (%s:%d) "
1044 "[no circuits for %d; timeout %d; %scanonical].",
1045 (int)conn
->s
, conn
->address
, conn
->port
,
1046 (int)(now
- chan
->timestamp_last_had_circuits
),
1047 or_conn
->idle_timeout
,
1048 or_conn
->is_canonical
? "" : "non");
1049 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1051 now
>= or_conn
->timestamp_lastempty
+ options
->KeepalivePeriod
*10 &&
1052 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
*10) {
1053 log_fn(LOG_PROTOCOL_WARN
,LD_PROTOCOL
,
1054 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1055 "flush; %d seconds since last write)",
1056 (int)conn
->s
, conn
->address
, conn
->port
,
1057 (int)connection_get_outbuf_len(conn
),
1058 (int)(now
-conn
->timestamp_lastwritten
));
1059 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1060 } else if (past_keepalive
&& !connection_get_outbuf_len(conn
)) {
1061 /* send a padding cell */
1062 log_fn(LOG_DEBUG
,LD_OR
,"Sending keepalive to (%s:%d)",
1063 conn
->address
, conn
->port
);
1064 memset(&cell
,0,sizeof(cell_t
));
1065 cell
.command
= CELL_PADDING
;
1066 connection_or_write_cell_to_buf(&cell
, or_conn
);
1070 /** Honor a NEWNYM request: make future requests unlinkable to past
1073 signewnym_impl(time_t now
)
1075 const or_options_t
*options
= get_options();
1076 if (!proxy_mode(options
)) {
1077 log_info(LD_CONTROL
, "Ignoring SIGNAL NEWNYM because client functionality "
1082 circuit_mark_all_dirty_circs_as_unusable();
1083 addressmap_clear_transient();
1084 rend_client_purge_state();
1085 time_of_last_signewnym
= now
;
1086 signewnym_is_pending
= 0;
1090 control_event_signal(SIGNEWNYM
);
1093 /** Return the number of times that signewnym has been called. */
1095 get_signewnym_epoch(void)
1097 return newnym_epoch
;
1100 /** True iff we have initialized all the members of <b>periodic_events</b>.
1101 * Used to prevent double-initialization. */
1102 static int periodic_events_initialized
= 0;
1104 /* Declare all the timer callback functions... */
1106 #define CALLBACK(name) \
1107 static int name ## _callback(time_t, const or_options_t *)
1108 CALLBACK(rotate_onion_key
);
1109 CALLBACK(check_ed_keys
);
1110 CALLBACK(launch_descriptor_fetches
);
1111 CALLBACK(rotate_x509_certificate
);
1112 CALLBACK(add_entropy
);
1113 CALLBACK(launch_reachability_tests
);
1114 CALLBACK(downrate_stability
);
1115 CALLBACK(save_stability
);
1116 CALLBACK(check_authority_cert
);
1117 CALLBACK(check_expired_networkstatus
);
1118 CALLBACK(write_stats_file
);
1119 CALLBACK(record_bridge_stats
);
1120 CALLBACK(clean_caches
);
1121 CALLBACK(rend_cache_failure_clean
);
1122 CALLBACK(retry_dns
);
1123 CALLBACK(check_descriptor
);
1124 CALLBACK(check_for_reachability_bw
);
1125 CALLBACK(fetch_networkstatus
);
1126 CALLBACK(retry_listeners
);
1127 CALLBACK(expire_old_ciruits_serverside
);
1128 CALLBACK(check_dns_honesty
);
1129 CALLBACK(write_bridge_ns
);
1130 CALLBACK(check_fw_helper_app
);
1131 CALLBACK(heartbeat
);
1135 /* Now we declare an array of periodic_event_item_t for each periodic event */
1136 #define CALLBACK(name) PERIODIC_EVENT(name)
1138 static periodic_event_item_t periodic_events
[] = {
1139 CALLBACK(rotate_onion_key
),
1140 CALLBACK(check_ed_keys
),
1141 CALLBACK(launch_descriptor_fetches
),
1142 CALLBACK(rotate_x509_certificate
),
1143 CALLBACK(add_entropy
),
1144 CALLBACK(launch_reachability_tests
),
1145 CALLBACK(downrate_stability
),
1146 CALLBACK(save_stability
),
1147 CALLBACK(check_authority_cert
),
1148 CALLBACK(check_expired_networkstatus
),
1149 CALLBACK(write_stats_file
),
1150 CALLBACK(record_bridge_stats
),
1151 CALLBACK(clean_caches
),
1152 CALLBACK(rend_cache_failure_clean
),
1153 CALLBACK(retry_dns
),
1154 CALLBACK(check_descriptor
),
1155 CALLBACK(check_for_reachability_bw
),
1156 CALLBACK(fetch_networkstatus
),
1157 CALLBACK(retry_listeners
),
1158 CALLBACK(expire_old_ciruits_serverside
),
1159 CALLBACK(check_dns_honesty
),
1160 CALLBACK(write_bridge_ns
),
1161 CALLBACK(check_fw_helper_app
),
1162 CALLBACK(heartbeat
),
1163 END_OF_PERIODIC_EVENTS
1167 /* These are pointers to members of periodic_events[] that are used to
1168 * implement particular callbacks. We keep them separate here so that we
1169 * can access them by name. We also keep them inside periodic_events[]
1170 * so that we can implement "reset all timers" in a reasonable way. */
1171 static periodic_event_item_t
*check_descriptor_event
=NULL
;
1172 static periodic_event_item_t
*fetch_networkstatus_event
=NULL
;
1173 static periodic_event_item_t
*launch_descriptor_fetches_event
=NULL
;
1174 static periodic_event_item_t
*check_dns_honesty_event
=NULL
;
1176 /** Reset all the periodic events so we'll do all our actions again as if we
1178 * Useful if our clock just moved back a long time from the future,
1179 * so we don't wait until that future arrives again before acting.
1182 reset_all_main_loop_timers(void)
1185 for (i
= 0; periodic_events
[i
].name
; ++i
) {
1186 periodic_event_reschedule(&periodic_events
[i
]);
1190 /** Return the member of periodic_events[] whose name is <b>name</b>.
1191 * Return NULL if no such event is found.
1193 static periodic_event_item_t
*
1194 find_periodic_event(const char *name
)
1197 for (i
= 0; periodic_events
[i
].name
; ++i
) {
1198 if (strcmp(name
, periodic_events
[i
].name
) == 0)
1199 return &periodic_events
[i
];
1204 /** Helper, run one second after setup:
1205 * Initializes all members of periodic_events and starts them running.
1207 * (We do this one second after setup for backward-compatibility reasons;
1208 * it might not actually be necessary.) */
1210 initialize_periodic_events_cb(evutil_socket_t fd
, short events
, void *data
)
1216 for (i
= 0; periodic_events
[i
].name
; ++i
) {
1217 periodic_event_launch(&periodic_events
[i
]);
1221 /** Set up all the members of periodic_events[], and configure them all to be
1222 * launched from a callback. */
1224 initialize_periodic_events(void)
1226 tor_assert(periodic_events_initialized
== 0);
1227 periodic_events_initialized
= 1;
1230 for (i
= 0; periodic_events
[i
].name
; ++i
) {
1231 periodic_event_setup(&periodic_events
[i
]);
1234 #define NAMED_CALLBACK(name) \
1235 STMT_BEGIN name ## _event = find_periodic_event( #name ); STMT_END
1237 NAMED_CALLBACK(check_descriptor
);
1238 NAMED_CALLBACK(fetch_networkstatus
);
1239 NAMED_CALLBACK(launch_descriptor_fetches
);
1240 NAMED_CALLBACK(check_dns_honesty
);
1242 struct timeval one_second
= { 1, 0 };
1243 event_base_once(tor_libevent_get_base(), -1, EV_TIMEOUT
,
1244 initialize_periodic_events_cb
, NULL
,
1249 teardown_periodic_events(void)
1252 for (i
= 0; periodic_events
[i
].name
; ++i
) {
1253 periodic_event_destroy(&periodic_events
[i
]);
1258 * Update our schedule so that we'll check whether we need to update our
1259 * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
1263 reschedule_descriptor_update_check(void)
1265 tor_assert(check_descriptor_event
);
1266 periodic_event_reschedule(check_descriptor_event
);
1270 * Update our schedule so that we'll check whether we need to fetch directory
1274 reschedule_directory_downloads(void)
1276 tor_assert(fetch_networkstatus_event
);
1277 tor_assert(launch_descriptor_fetches_event
);
1279 periodic_event_reschedule(fetch_networkstatus_event
);
1280 periodic_event_reschedule(launch_descriptor_fetches_event
);
1283 #define LONGEST_TIMER_PERIOD (30 * 86400)
1284 /** Helper: Return the number of seconds between <b>now</b> and <b>next</b>,
1285 * clipped to the range [1 second, LONGEST_TIMER_PERIOD]. */
1287 safe_timer_diff(time_t now
, time_t next
)
1290 /* There were no computers at signed TIME_MIN (1902 on 32-bit systems),
1291 * and nothing that could run Tor. It's a bug if 'next' is around then.
1292 * On 64-bit systems with signed TIME_MIN, TIME_MIN is before the Big
1293 * Bang. We cannot extrapolate past a singularity, but there was probably
1294 * nothing that could run Tor then, either.
1296 tor_assert(next
> TIME_MIN
+ LONGEST_TIMER_PERIOD
);
1298 if (next
- LONGEST_TIMER_PERIOD
> now
)
1299 return LONGEST_TIMER_PERIOD
;
1300 return (int)(next
- now
);
1306 /** Perform regular maintenance tasks. This function gets run once per
1307 * second by second_elapsed_callback().
1310 run_scheduled_events(time_t now
)
1312 const or_options_t
*options
= get_options();
1314 /* 0. See if we've been asked to shut down and our timeout has
1315 * expired; or if our bandwidth limits are exhausted and we
1316 * should hibernate; or if it's time to wake up from hibernation.
1318 consider_hibernation(now
);
1320 /* 0b. If we've deferred a signewnym, make sure it gets handled
1322 if (signewnym_is_pending
&&
1323 time_of_last_signewnym
+ MAX_SIGNEWNYM_RATE
<= now
) {
1324 log_info(LD_CONTROL
, "Honoring delayed NEWNYM request");
1325 signewnym_impl(now
);
1328 /* 0c. If we've deferred log messages for the controller, handle them now */
1329 flush_pending_log_callbacks();
1331 if (options
->UseBridges
&& !options
->DisableNetwork
) {
1332 fetch_bridge_descriptors(options
, now
);
1335 if (accounting_is_enabled(options
)) {
1336 accounting_run_housekeeping(now
);
1339 if (authdir_mode_v3(options
)) {
1340 dirvote_act(options
, now
);
1343 /* 3a. Every second, we examine pending circuits and prune the
1344 * ones which have been pending for more than a few seconds.
1345 * We do this before step 4, so it can try building more if
1346 * it's not comfortable with the number of available circuits.
1348 /* (If our circuit build timeout can ever become lower than a second (which
1349 * it can't, currently), we should do this more often.) */
1350 circuit_expire_building();
1352 /* 3b. Also look at pending streams and prune the ones that 'began'
1353 * a long time ago but haven't gotten a 'connected' yet.
1354 * Do this before step 4, so we can put them back into pending
1355 * state to be picked up by the new circuit.
1357 connection_ap_expire_beginning();
1359 /* 3c. And expire connections that we've held open for too long.
1361 connection_expire_held_open();
1363 /* 4. Every second, we try a new circuit if there are no valid
1364 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1365 * that became dirty more than MaxCircuitDirtiness seconds ago,
1366 * and we make a new circ if there are no clean circuits.
1368 const int have_dir_info
= router_have_minimum_dir_info();
1369 if (have_dir_info
&& !net_is_disabled()) {
1370 circuit_build_needed_circs(now
);
1372 circuit_expire_old_circs_as_needed(now
);
1375 /* 5. We do housekeeping for each connection... */
1376 connection_or_set_bad_connections(NULL
, 0);
1378 for (i
=0;i
<smartlist_len(connection_array
);i
++) {
1379 run_connection_housekeeping(i
, now
);
1382 /* 6. And remove any marked circuits... */
1383 circuit_close_all_marked();
1385 /* 7. And upload service descriptors if necessary. */
1386 if (have_completed_a_circuit() && !net_is_disabled()) {
1387 rend_consider_services_upload(now
);
1388 rend_consider_descriptor_republication();
1391 /* 8. and blow away any connections that need to die. have to do this now,
1392 * because if we marked a conn for close and left its socket -1, then
1393 * we'll pass it to poll/select and bad things will happen.
1395 close_closeable_connections();
1397 /* 8b. And if anything in our state is ready to get flushed to disk, we
1401 /* 8c. Do channel cleanup just like for connections */
1402 channel_run_cleanup();
1403 channel_listener_run_cleanup();
1405 /* 11b. check pending unconfigured managed proxies */
1406 if (!net_is_disabled() && pt_proxies_configuration_pending())
1407 pt_configure_remaining_proxies();
1411 rotate_onion_key_callback(time_t now
, const or_options_t
*options
)
1413 /* 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
1414 * shut down and restart all cpuworkers, and update the directory if
1417 if (server_mode(options
)) {
1418 time_t rotation_time
= get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME
;
1419 if (rotation_time
> now
) {
1420 return safe_timer_diff(now
, rotation_time
);
1423 log_info(LD_GENERAL
,"Rotating onion key.");
1425 cpuworkers_rotate_keyinfo();
1426 if (router_rebuild_descriptor(1)<0) {
1427 log_info(LD_CONFIG
, "Couldn't rebuild router descriptor");
1429 if (advertised_server_mode() && !options
->DisableNetwork
)
1430 router_upload_dir_desc_to_dirservers(0);
1431 return MIN_ONION_KEY_LIFETIME
;
1433 return PERIODIC_EVENT_NO_UPDATE
;
1437 check_ed_keys_callback(time_t now
, const or_options_t
*options
)
1439 if (server_mode(options
)) {
1440 if (should_make_new_ed_keys(options
, now
)) {
1441 if (load_ed_keys(options
, now
) < 0 ||
1442 generate_ed_link_cert(options
, now
)) {
1443 log_err(LD_OR
, "Unable to update Ed25519 keys! Exiting.");
1450 return PERIODIC_EVENT_NO_UPDATE
;
1454 launch_descriptor_fetches_callback(time_t now
, const or_options_t
*options
)
1456 if (should_delay_dir_fetches(options
, NULL
))
1457 return PERIODIC_EVENT_NO_UPDATE
;
1459 update_all_descriptor_downloads(now
);
1460 update_extrainfo_downloads(now
);
1461 if (router_have_minimum_dir_info())
1462 return LAZY_DESCRIPTOR_RETRY_INTERVAL
;
1464 return GREEDY_DESCRIPTOR_RETRY_INTERVAL
;
1468 rotate_x509_certificate_callback(time_t now
, const or_options_t
*options
)
1470 static int first
= 1;
1475 return MAX_SSL_KEY_LIFETIME_INTERNAL
;
1478 /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1480 log_info(LD_GENERAL
,"Rotating tls context.");
1481 if (router_initialize_tls_context() < 0) {
1482 log_err(LD_BUG
, "Error reinitializing TLS context");
1483 tor_assert_unreached();
1486 /* We also make sure to rotate the TLS connections themselves if they've
1487 * been up for too long -- but that's done via is_bad_for_new_circs in
1488 * run_connection_housekeeping() above. */
1489 return MAX_SSL_KEY_LIFETIME_INTERNAL
;
1493 add_entropy_callback(time_t now
, const or_options_t
*options
)
1497 /* We already seeded once, so don't die on failure. */
1498 if (crypto_seed_rng() < 0) {
1499 log_warn(LD_GENERAL
, "Tried to re-seed RNG, but failed. We already "
1500 "seeded once, though, so we won't exit here.");
1503 /** How often do we add more entropy to OpenSSL's RNG pool? */
1504 #define ENTROPY_INTERVAL (60*60)
1505 return ENTROPY_INTERVAL
;
1509 launch_reachability_tests_callback(time_t now
, const or_options_t
*options
)
1511 if (authdir_mode_tests_reachability(options
) &&
1512 !net_is_disabled()) {
1513 /* try to determine reachability of the other Tor relays */
1514 dirserv_test_reachability(now
);
1516 return REACHABILITY_TEST_INTERVAL
;
1520 downrate_stability_callback(time_t now
, const or_options_t
*options
)
1523 /* 1d. Periodically, we discount older stability information so that new
1524 * stability info counts more, and save the stability information to disk as
1526 time_t next
= rep_hist_downrate_old_runs(now
);
1527 return safe_timer_diff(now
, next
);
1531 save_stability_callback(time_t now
, const or_options_t
*options
)
1533 if (authdir_mode_tests_reachability(options
)) {
1534 if (rep_hist_record_mtbf_data(now
, 1)<0) {
1535 log_warn(LD_GENERAL
, "Couldn't store mtbf data.");
1538 #define SAVE_STABILITY_INTERVAL (30*60)
1539 return SAVE_STABILITY_INTERVAL
;
1543 check_authority_cert_callback(time_t now
, const or_options_t
*options
)
1547 /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
1548 * close to expiring and warn the admin if it is. */
1549 v3_authority_check_key_expiry();
1550 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
1551 return CHECK_V3_CERTIFICATE_INTERVAL
;
1555 check_expired_networkstatus_callback(time_t now
, const or_options_t
*options
)
1558 /* 1f. Check whether our networkstatus has expired.
1560 networkstatus_t
*ns
= networkstatus_get_latest_consensus();
1561 /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
1562 * networkstatus_get_reasonably_live_consensus(), but that value is way
1563 * way too high. Arma: is the bridge issue there resolved yet? -NM */
1564 #define NS_EXPIRY_SLOP (24*60*60)
1565 if (ns
&& ns
->valid_until
< now
+NS_EXPIRY_SLOP
&&
1566 router_have_minimum_dir_info()) {
1567 router_dir_info_changed();
1569 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1570 return CHECK_EXPIRED_NS_INTERVAL
;
1574 write_stats_file_callback(time_t now
, const or_options_t
*options
)
1576 /* 1g. Check whether we should write statistics to disk.
1578 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1579 time_t next_time_to_write_stats_files
= now
+ CHECK_WRITE_STATS_INTERVAL
;
1580 if (options
->CellStatistics
) {
1582 rep_hist_buffer_stats_write(now
);
1583 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1584 next_time_to_write_stats_files
= next_write
;
1586 if (options
->DirReqStatistics
) {
1587 time_t next_write
= geoip_dirreq_stats_write(now
);
1588 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1589 next_time_to_write_stats_files
= next_write
;
1591 if (options
->EntryStatistics
) {
1592 time_t next_write
= geoip_entry_stats_write(now
);
1593 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1594 next_time_to_write_stats_files
= next_write
;
1596 if (options
->HiddenServiceStatistics
) {
1597 time_t next_write
= rep_hist_hs_stats_write(now
);
1598 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1599 next_time_to_write_stats_files
= next_write
;
1601 if (options
->ExitPortStatistics
) {
1602 time_t next_write
= rep_hist_exit_stats_write(now
);
1603 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1604 next_time_to_write_stats_files
= next_write
;
1606 if (options
->ConnDirectionStatistics
) {
1607 time_t next_write
= rep_hist_conn_stats_write(now
);
1608 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1609 next_time_to_write_stats_files
= next_write
;
1611 if (options
->BridgeAuthoritativeDir
) {
1612 time_t next_write
= rep_hist_desc_stats_write(now
);
1613 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1614 next_time_to_write_stats_files
= next_write
;
1617 return safe_timer_diff(now
, next_time_to_write_stats_files
);
1621 record_bridge_stats_callback(time_t now
, const or_options_t
*options
)
1623 static int should_init_bridge_stats
= 1;
1625 /* 1h. Check whether we should write bridge statistics to disk.
1627 if (should_record_bridge_info(options
)) {
1628 if (should_init_bridge_stats
) {
1629 /* (Re-)initialize bridge statistics. */
1630 geoip_bridge_stats_init(now
);
1631 should_init_bridge_stats
= 0;
1632 return WRITE_STATS_INTERVAL
;
1634 /* Possibly write bridge statistics to disk and ask when to write
1635 * them next time. */
1636 time_t next
= geoip_bridge_stats_write(now
);
1637 return safe_timer_diff(now
, next
);
1639 } else if (!should_init_bridge_stats
) {
1640 /* Bridge mode was turned off. Ensure that stats are re-initialized
1641 * next time bridge mode is turned on. */
1642 should_init_bridge_stats
= 1;
1644 return PERIODIC_EVENT_NO_UPDATE
;
1648 clean_caches_callback(time_t now
, const or_options_t
*options
)
1650 /* Remove old information from rephist and the rend cache. */
1651 rep_history_clean(now
- options
->RephistTrackTime
);
1652 rend_cache_clean(now
, REND_CACHE_TYPE_CLIENT
);
1653 rend_cache_clean(now
, REND_CACHE_TYPE_SERVICE
);
1654 rend_cache_clean_v2_descs_as_dir(now
, 0);
1655 microdesc_cache_rebuild(NULL
, 0);
1656 #define CLEAN_CACHES_INTERVAL (30*60)
1657 return CLEAN_CACHES_INTERVAL
;
1661 rend_cache_failure_clean_callback(time_t now
, const or_options_t
*options
)
1664 /* We don't keep entries that are more than five minutes old so we try to
1665 * clean it as soon as we can since we want to make sure the client waits
1666 * as little as possible for reachability reasons. */
1667 rend_cache_failure_clean(now
);
1672 retry_dns_callback(time_t now
, const or_options_t
*options
)
1675 #define RETRY_DNS_INTERVAL (10*60)
1676 /* If we're a server and initializing dns failed, retry periodically. */
1677 if (server_mode(options
) && has_dns_init_failed())
1679 return RETRY_DNS_INTERVAL
;
1682 /* 2. Periodically, we consider force-uploading our descriptor
1683 * (if we've passed our internal checks). */
1686 check_descriptor_callback(time_t now
, const or_options_t
*options
)
1688 /** How often do we check whether part of our router info has changed in a
1689 * way that would require an upload? That includes checking whether our IP
1690 * address has changed. */
1691 #define CHECK_DESCRIPTOR_INTERVAL (60)
1693 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1694 * one is inaccurate. */
1695 if (!options
->DisableNetwork
) {
1696 check_descriptor_bandwidth_changed(now
);
1697 check_descriptor_ipaddress_changed(now
);
1698 mark_my_descriptor_dirty_if_too_old(now
);
1699 consider_publishable_server(0);
1700 /* If any networkstatus documents are no longer recent, we need to
1701 * update all the descriptors' running status. */
1702 /* Remove dead routers. */
1703 /* XXXX This doesn't belong here, but it was here in the pre-
1704 * XXXX refactoring code. */
1705 routerlist_remove_old_routers();
1708 return CHECK_DESCRIPTOR_INTERVAL
;
1712 check_for_reachability_bw_callback(time_t now
, const or_options_t
*options
)
1714 /* XXXX This whole thing was stuck in the middle of what is now
1715 * XXXX check_descriptor_callback. I'm not sure it's right. */
1717 static int dirport_reachability_count
= 0;
1718 /* also, check religiously for reachability, if it's within the first
1719 * 20 minutes of our uptime. */
1720 if (server_mode(options
) &&
1721 (have_completed_a_circuit() || !any_predicted_circuits(now
)) &&
1722 !we_are_hibernating()) {
1723 if (stats_n_seconds_working
< TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
) {
1724 consider_testing_reachability(1, dirport_reachability_count
==0);
1725 if (++dirport_reachability_count
> 5)
1726 dirport_reachability_count
= 0;
1729 /* If we haven't checked for 12 hours and our bandwidth estimate is
1730 * low, do another bandwidth test. This is especially important for
1731 * bridges, since they might go long periods without much use. */
1732 const routerinfo_t
*me
= router_get_my_routerinfo();
1733 static int first_time
= 1;
1734 if (!first_time
&& me
&&
1735 me
->bandwidthcapacity
< me
->bandwidthrate
&&
1736 me
->bandwidthcapacity
< 51200) {
1737 reset_bandwidth_test();
1740 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1741 return BANDWIDTH_RECHECK_INTERVAL
;
1744 return CHECK_DESCRIPTOR_INTERVAL
;
1748 fetch_networkstatus_callback(time_t now
, const or_options_t
*options
)
1750 /* 2c. Every minute (or every second if TestingTorNetwork, or during
1751 * client bootstrap), check whether we want to download any networkstatus
1754 /* How often do we check whether we should download network status
1756 const int we_are_bootstrapping
= networkstatus_consensus_is_bootstrapping(
1758 const int prefer_mirrors
= !directory_fetches_from_authorities(
1760 int networkstatus_dl_check_interval
= 60;
1761 /* check more often when testing, or when bootstrapping from mirrors
1762 * (connection limits prevent too many connections being made) */
1763 if (options
->TestingTorNetwork
1764 || (we_are_bootstrapping
&& prefer_mirrors
)) {
1765 networkstatus_dl_check_interval
= 1;
1768 if (should_delay_dir_fetches(options
, NULL
))
1769 return PERIODIC_EVENT_NO_UPDATE
;
1771 update_networkstatus_downloads(now
);
1772 return networkstatus_dl_check_interval
;
1776 retry_listeners_callback(time_t now
, const or_options_t
*options
)
1780 /* 3d. And every 60 seconds, we relaunch listeners if any died. */
1781 if (!net_is_disabled()) {
1782 retry_all_listeners(NULL
, NULL
, 0);
1785 return PERIODIC_EVENT_NO_UPDATE
;
1789 expire_old_ciruits_serverside_callback(time_t now
, const or_options_t
*options
)
1792 /* every 11 seconds, so not usually the same second as other such events */
1793 circuit_expire_old_circuits_serverside(now
);
1798 check_dns_honesty_callback(time_t now
, const or_options_t
*options
)
1801 /* 9. and if we're an exit node, check whether our DNS is telling stories
1803 if (net_is_disabled() ||
1804 ! public_server_mode(options
) ||
1805 router_my_exit_policy_is_reject_star())
1806 return PERIODIC_EVENT_NO_UPDATE
;
1808 static int first_time
= 1;
1810 /* Don't launch right when we start */
1812 return crypto_rand_int_range(60, 180);
1815 dns_launch_correctness_checks();
1816 return 12*3600 + crypto_rand_int(12*3600);
1820 write_bridge_ns_callback(time_t now
, const or_options_t
*options
)
1822 /* 10. write bridge networkstatus file to disk */
1823 if (options
->BridgeAuthoritativeDir
) {
1824 networkstatus_dump_bridge_status_to_file(now
);
1825 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
1826 return BRIDGE_STATUSFILE_INTERVAL
;
1828 return PERIODIC_EVENT_NO_UPDATE
;
1832 check_fw_helper_app_callback(time_t now
, const or_options_t
*options
)
1834 if (net_is_disabled() ||
1835 ! server_mode(options
) ||
1836 ! options
->PortForwarding
) {
1837 return PERIODIC_EVENT_NO_UPDATE
;
1839 /* 11. check the port forwarding app */
1841 #define PORT_FORWARDING_CHECK_INTERVAL 5
1842 smartlist_t
*ports_to_forward
= get_list_of_ports_to_forward();
1843 if (ports_to_forward
) {
1844 tor_check_port_forwarding(options
->PortForwardingHelper
,
1848 SMARTLIST_FOREACH(ports_to_forward
, char *, cp
, tor_free(cp
));
1849 smartlist_free(ports_to_forward
);
1851 return PORT_FORWARDING_CHECK_INTERVAL
;
1854 /** Callback to write heartbeat message in the logs. */
1856 heartbeat_callback(time_t now
, const or_options_t
*options
)
1858 static int first
= 1;
1860 /* Check if heartbeat is disabled */
1861 if (!options
->HeartbeatPeriod
) {
1862 return PERIODIC_EVENT_NO_UPDATE
;
1865 /* Write the heartbeat message */
1867 first
= 0; /* Skip the first one. */
1872 return options
->HeartbeatPeriod
;
1875 /** Timer: used to invoke second_elapsed_callback() once per second. */
1876 static periodic_timer_t
*second_timer
= NULL
;
1877 /** Number of libevent errors in the last second: we die if we get too many. */
1878 static int n_libevent_errors
= 0;
1880 /** Libevent callback: invoked once every second. */
1882 second_elapsed_callback(periodic_timer_t
*timer
, void *arg
)
1884 /* XXXX This could be sensibly refactored into multiple callbacks, and we
1885 * could use Libevent's timers for this rather than checking the current
1886 * time against a bunch of timeouts every second. */
1887 static time_t current_second
= 0;
1889 size_t bytes_written
;
1891 int seconds_elapsed
;
1892 const or_options_t
*options
= get_options();
1896 n_libevent_errors
= 0;
1898 /* log_notice(LD_GENERAL, "Tick."); */
1900 update_approx_time(now
);
1902 /* the second has rolled over. check more stuff. */
1903 seconds_elapsed
= current_second
? (int)(now
- current_second
) : 0;
1904 bytes_read
= (size_t)(stats_n_bytes_read
- stats_prev_n_read
);
1905 bytes_written
= (size_t)(stats_n_bytes_written
- stats_prev_n_written
);
1906 stats_prev_n_read
= stats_n_bytes_read
;
1907 stats_prev_n_written
= stats_n_bytes_written
;
1909 control_event_bandwidth_used((uint32_t)bytes_read
,(uint32_t)bytes_written
);
1910 control_event_stream_bandwidth_used();
1911 control_event_conn_bandwidth_used();
1912 control_event_circ_bandwidth_used();
1913 control_event_circuit_cell_stats();
1915 if (server_mode(options
) &&
1916 !net_is_disabled() &&
1917 seconds_elapsed
> 0 &&
1918 have_completed_a_circuit() &&
1919 stats_n_seconds_working
/ TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
!=
1920 (stats_n_seconds_working
+seconds_elapsed
) /
1921 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
) {
1922 /* every 20 minutes, check and complain if necessary */
1923 const routerinfo_t
*me
= router_get_my_routerinfo();
1924 if (me
&& !check_whether_orport_reachable(options
)) {
1925 char *address
= tor_dup_ip(me
->addr
);
1926 log_warn(LD_CONFIG
,"Your server (%s:%d) has not managed to confirm that "
1927 "its ORPort is reachable. Relays do not publish descriptors "
1928 "until their ORPort and DirPort are reachable. Please check "
1929 "your firewalls, ports, address, /etc/hosts file, etc.",
1930 address
, me
->or_port
);
1931 control_event_server_status(LOG_WARN
,
1932 "REACHABILITY_FAILED ORADDRESS=%s:%d",
1933 address
, me
->or_port
);
1937 if (me
&& !check_whether_dirport_reachable(options
)) {
1938 char *address
= tor_dup_ip(me
->addr
);
1940 "Your server (%s:%d) has not managed to confirm that its "
1941 "DirPort is reachable. Relays do not publish descriptors "
1942 "until their ORPort and DirPort are reachable. Please check "
1943 "your firewalls, ports, address, /etc/hosts file, etc.",
1944 address
, me
->dir_port
);
1945 control_event_server_status(LOG_WARN
,
1946 "REACHABILITY_FAILED DIRADDRESS=%s:%d",
1947 address
, me
->dir_port
);
1952 /** If more than this many seconds have elapsed, probably the clock
1953 * jumped: doesn't count. */
1954 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
1955 if (seconds_elapsed
< -NUM_JUMPED_SECONDS_BEFORE_WARN
||
1956 seconds_elapsed
>= NUM_JUMPED_SECONDS_BEFORE_WARN
) {
1957 circuit_note_clock_jumped(seconds_elapsed
);
1958 } else if (seconds_elapsed
> 0)
1959 stats_n_seconds_working
+= seconds_elapsed
;
1961 run_scheduled_events(now
);
1963 current_second
= now
; /* remember which second it is, for next time */
1966 #ifdef HAVE_SYSTEMD_209
1967 static periodic_timer_t
*systemd_watchdog_timer
= NULL
;
1969 /** Libevent callback: invoked to reset systemd watchdog. */
1971 systemd_watchdog_callback(periodic_timer_t
*timer
, void *arg
)
1975 sd_notify(0, "WATCHDOG=1");
1979 /** Timer: used to invoke refill_callback(). */
1980 static periodic_timer_t
*refill_timer
= NULL
;
1982 /** Libevent callback: invoked periodically to refill token buckets
1983 * and count r/w bytes. */
1985 refill_callback(periodic_timer_t
*timer
, void *arg
)
1987 static struct timeval current_millisecond
;
1990 size_t bytes_written
;
1992 int milliseconds_elapsed
= 0;
1993 int seconds_rolled_over
= 0;
1995 const or_options_t
*options
= get_options();
2000 tor_gettimeofday(&now
);
2002 /* If this is our first time, no time has passed. */
2003 if (current_millisecond
.tv_sec
) {
2004 long mdiff
= tv_mdiff(¤t_millisecond
, &now
);
2005 if (mdiff
> INT_MAX
)
2007 milliseconds_elapsed
= (int)mdiff
;
2008 seconds_rolled_over
= (int)(now
.tv_sec
- current_millisecond
.tv_sec
);
2011 bytes_written
= stats_prev_global_write_bucket
- global_write_bucket
;
2012 bytes_read
= stats_prev_global_read_bucket
- global_read_bucket
;
2014 stats_n_bytes_read
+= bytes_read
;
2015 stats_n_bytes_written
+= bytes_written
;
2016 if (accounting_is_enabled(options
) && milliseconds_elapsed
>= 0)
2017 accounting_add_bytes(bytes_read
, bytes_written
, seconds_rolled_over
);
2019 if (milliseconds_elapsed
> 0)
2020 connection_bucket_refill(milliseconds_elapsed
, (time_t)now
.tv_sec
);
2022 stats_prev_global_read_bucket
= global_read_bucket
;
2023 stats_prev_global_write_bucket
= global_write_bucket
;
2025 current_millisecond
= now
; /* remember what time it is, for next time */
2029 /** Called when a possibly ignorable libevent error occurs; ensures that we
2030 * don't get into an infinite loop by ignoring too many errors from
2033 got_libevent_error(void)
2035 if (++n_libevent_errors
> 8) {
2036 log_err(LD_NET
, "Too many libevent errors in one second; dying");
2043 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
2045 /** Called when our IP address seems to have changed. <b>at_interface</b>
2046 * should be true if we detected a change in our interface, and false if we
2047 * detected a change in our published address. */
2049 ip_address_changed(int at_interface
)
2051 const or_options_t
*options
= get_options();
2052 int server
= server_mode(options
);
2053 int exit_reject_interfaces
= (server
&& options
->ExitRelay
2054 && options
->ExitPolicyRejectLocalInterfaces
);
2058 /* Okay, change our keys. */
2059 if (init_keys_client() < 0)
2060 log_warn(LD_GENERAL
, "Unable to rotate keys after IP change!");
2064 if (stats_n_seconds_working
> UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST
)
2065 reset_bandwidth_test();
2066 stats_n_seconds_working
= 0;
2067 router_reset_reachability();
2071 /* Exit relays incorporate interface addresses in their exit policies when
2072 * ExitPolicyRejectLocalInterfaces is set */
2073 if (exit_reject_interfaces
|| (server
&& !at_interface
)) {
2074 mark_my_descriptor_dirty("IP address changed");
2077 dns_servers_relaunch_checks();
2080 /** Forget what we've learned about the correctness of our DNS servers, and
2081 * start learning again. */
2083 dns_servers_relaunch_checks(void)
2085 if (server_mode(get_options())) {
2086 dns_reset_correctness_checks();
2087 if (periodic_events_initialized
) {
2088 tor_assert(check_dns_honesty_event
);
2089 periodic_event_reschedule(check_dns_honesty_event
);
2094 /** Called when we get a SIGHUP: reload configuration files and keys,
2095 * retry all connections, and so on. */
2099 const or_options_t
*options
= get_options();
2102 dmalloc_log_stats();
2103 dmalloc_log_changed(0, 1, 0, 0);
2106 log_notice(LD_GENERAL
,"Received reload signal (hup). Reloading config and "
2107 "resetting internal state.");
2108 if (accounting_is_enabled(options
))
2109 accounting_record_bandwidth_usage(time(NULL
), get_or_state());
2111 router_reset_warnings();
2112 routerlist_reset_warnings();
2113 /* first, reload config variables, in case they've changed */
2114 if (options
->ReloadTorrcOnSIGHUP
) {
2115 /* no need to provide argc/v, they've been cached in init_from_config */
2116 if (options_init_from_torrc(0, NULL
) < 0) {
2117 log_err(LD_CONFIG
,"Reading config failed--see warnings above. "
2118 "For usage, try -h.");
2121 options
= get_options(); /* they have changed now */
2122 /* Logs are only truncated the first time they are opened, but were
2123 probably intended to be cleaned up on signal. */
2124 if (options
->TruncateLogFile
)
2128 log_notice(LD_GENERAL
, "Not reloading config file: the controller told "
2130 /* Make stuff get rescanned, reloaded, etc. */
2131 if (set_options((or_options_t
*)options
, &msg
) < 0) {
2133 msg
= tor_strdup("Unknown error");
2134 log_warn(LD_GENERAL
, "Unable to re-set previous options: %s", msg
);
2138 if (authdir_mode_handles_descs(options
, -1)) {
2139 /* reload the approved-routers file */
2140 if (dirserv_load_fingerprint_file() < 0) {
2141 /* warnings are logged from dirserv_load_fingerprint_file() directly */
2142 log_info(LD_GENERAL
, "Error reloading fingerprints. "
2143 "Continuing with old list.");
2147 /* Rotate away from the old dirty circuits. This has to be done
2148 * after we've read the new options, but before we start using
2149 * circuits for directory fetches. */
2150 circuit_mark_all_dirty_circs_as_unusable();
2152 /* retry appropriate downloads */
2153 router_reset_status_download_failures();
2154 router_reset_descriptor_download_failures();
2155 if (!options
->DisableNetwork
)
2156 update_networkstatus_downloads(time(NULL
));
2158 /* We'll retry routerstatus downloads in about 10 seconds; no need to
2159 * force a retry there. */
2161 if (server_mode(options
)) {
2162 /* Maybe we've been given a new ed25519 key or certificate?
2164 time_t now
= approx_time();
2165 if (load_ed_keys(options
, now
) < 0 ||
2166 generate_ed_link_cert(options
, now
)) {
2167 log_warn(LD_OR
, "Problem reloading Ed25519 keys; still using old keys.");
2170 /* Update cpuworker and dnsworker processes, so they get up-to-date
2171 * configuration options. */
2172 cpuworkers_rotate_keyinfo();
2178 /** Tor main loop. */
2184 /* initialize the periodic events first, so that code that depends on the
2185 * events being present does not assert.
2187 if (! periodic_events_initialized
) {
2188 initialize_periodic_events();
2191 /* initialize dns resolve map, spawn workers if needed */
2192 if (dns_init() < 0) {
2193 if (get_options()->ServerDNSAllowBrokenConfig
)
2194 log_warn(LD_GENERAL
, "Couldn't set up any working nameservers. "
2195 "Network not up yet? Will try again soon.");
2197 log_err(LD_GENERAL
,"Error initializing dns subsystem; exiting. To "
2198 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
2204 /* load the private keys, if we're supposed to have them, and set up the
2206 if (! client_identity_key_is_set()) {
2207 if (init_keys() < 0) {
2208 log_err(LD_OR
, "Error initializing keys; exiting");
2213 /* Set up our buckets */
2214 connection_bucket_init();
2215 stats_prev_global_read_bucket
= global_read_bucket
;
2216 stats_prev_global_write_bucket
= global_write_bucket
;
2218 /* initialize the bootstrap status events to know we're starting up */
2219 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING
, 0);
2221 /* Initialize the keypinning log. */
2222 if (authdir_mode_v3(get_options())) {
2223 char *fname
= get_datadir_fname("key-pinning-journal");
2225 if (keypin_load_journal(fname
)<0) {
2226 log_err(LD_DIR
, "Error loading key-pinning journal: %s",strerror(errno
));
2229 if (keypin_open_journal(fname
)<0) {
2230 log_err(LD_DIR
, "Error opening key-pinning journal: %s",strerror(errno
));
2238 /* This is the old name for key-pinning-journal. These got corrupted
2239 * in a couple of cases by #16530, so we started over. See #16580 for
2240 * the rationale and for other options we didn't take. We can remove
2241 * this code once all the authorities that ran 0.2.7.1-alpha-dev are
2244 char *fname
= get_datadir_fname("key-pinning-entries");
2249 if (trusted_dirs_reload_certs()) {
2251 "Couldn't load all cached v3 certificates. Starting anyway.");
2253 if (router_reload_consensus_networkstatus()) {
2256 /* load the routers file, or assign the defaults. */
2257 if (router_reload_router_list()) {
2260 /* load the networkstatuses. (This launches a download for new routers as
2264 directory_info_has_arrived(now
, 1, 0);
2266 if (server_mode(get_options())) {
2267 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
2271 /* Setup shared random protocol subsystem. */
2272 if (authdir_mode_publishes_statuses(get_options())) {
2273 if (sr_init(1) < 0) {
2278 /* set up once-a-second callback. */
2279 if (! second_timer
) {
2280 struct timeval one_second
;
2281 one_second
.tv_sec
= 1;
2282 one_second
.tv_usec
= 0;
2284 second_timer
= periodic_timer_new(tor_libevent_get_base(),
2286 second_elapsed_callback
,
2288 tor_assert(second_timer
);
2291 #ifdef HAVE_SYSTEMD_209
2292 uint64_t watchdog_delay
;
2293 /* set up systemd watchdog notification. */
2294 if (sd_watchdog_enabled(1, &watchdog_delay
) > 0) {
2295 if (! systemd_watchdog_timer
) {
2296 struct timeval watchdog
;
2297 /* The manager will "act on" us if we don't send them a notification
2298 * every 'watchdog_delay' microseconds. So, send notifications twice
2300 watchdog_delay
/= 2;
2301 watchdog
.tv_sec
= watchdog_delay
/ 1000000;
2302 watchdog
.tv_usec
= watchdog_delay
% 1000000;
2304 systemd_watchdog_timer
= periodic_timer_new(tor_libevent_get_base(),
2306 systemd_watchdog_callback
,
2308 tor_assert(systemd_watchdog_timer
);
2313 if (!refill_timer
) {
2314 struct timeval refill_interval
;
2315 int msecs
= get_options()->TokenBucketRefillInterval
;
2317 refill_interval
.tv_sec
= msecs
/1000;
2318 refill_interval
.tv_usec
= (msecs
%1000)*1000;
2320 refill_timer
= periodic_timer_new(tor_libevent_get_base(),
2324 tor_assert(refill_timer
);
2329 const int r
= sd_notify(0, "READY=1");
2331 log_warn(LD_GENERAL
, "Unable to send readiness to systemd: %s",
2334 log_notice(LD_GENERAL
, "Signaled readiness to systemd");
2336 log_info(LD_GENERAL
, "Systemd NOTIFY_SOCKET not present.");
2341 return run_main_loop_until_done();
2345 * Run the main loop a single time. Return 0 for "exit"; -1 for "exit with
2346 * error", and 1 for "run this again."
2349 run_main_loop_once(void)
2353 if (nt_service_is_stopping())
2357 /* Make it easier to tell whether libevent failure is our fault or not. */
2360 /* All active linked conns should get their read events activated. */
2361 SMARTLIST_FOREACH(active_linked_connection_lst
, connection_t
*, conn
,
2362 event_active(conn
->read_event
, EV_READ
, 1));
2363 called_loop_once
= smartlist_len(active_linked_connection_lst
) ? 1 : 0;
2365 update_approx_time(time(NULL
));
2367 /* poll until we have an event, or the second ends, or until we have
2368 * some active linked connections to trigger events for. */
2369 loop_result
= event_base_loop(tor_libevent_get_base(),
2370 called_loop_once
? EVLOOP_ONCE
: 0);
2372 /* let catch() handle things like ^c, and otherwise don't worry about it */
2373 if (loop_result
< 0) {
2374 int e
= tor_socket_errno(-1);
2375 /* let the program survive things like ^z */
2376 if (e
!= EINTR
&& !ERRNO_IS_EINPROGRESS(e
)) {
2377 log_err(LD_NET
,"libevent call with %s failed: %s [%d]",
2378 tor_libevent_get_method(), tor_socket_strerror(e
), e
);
2381 } else if (e
== EINVAL
) {
2382 log_warn(LD_NET
, "EINVAL from libevent: should you upgrade libevent?");
2383 if (got_libevent_error())
2387 tor_assert_nonfatal_once(! ERRNO_IS_EINPROGRESS(e
));
2388 log_debug(LD_NET
,"libevent call interrupted.");
2389 /* You can't trust the results of this poll(). Go back to the
2390 * top of the big for loop. */
2395 /* This will be pretty fast if nothing new is pending. Note that this gets
2396 * called once per libevent loop, which will make it happen once per group
2397 * of events that fire, or once per second. */
2398 connection_ap_attach_pending(0);
2403 /** Run the run_main_loop_once() function until it declares itself done,
2404 * and return its final return value.
2406 * Shadow won't invoke this function, so don't fill it up with things.
2409 run_main_loop_until_done(void)
2411 int loop_result
= 1;
2413 loop_result
= run_main_loop_once();
2414 } while (loop_result
== 1);
2418 /** Libevent callback: invoked when we get a signal.
2421 signal_callback(evutil_socket_t fd
, short events
, void *arg
)
2423 const int *sigptr
= arg
;
2424 const int sig
= *sigptr
;
2428 process_signal(sig
);
2431 /** Do the work of acting on a signal received in <b>sig</b> */
2433 process_signal(int sig
)
2438 log_notice(LD_GENERAL
,"Catching signal TERM, exiting cleanly.");
2443 if (!server_mode(get_options())) { /* do it now */
2444 log_notice(LD_GENERAL
,"Interrupt: exiting cleanly.");
2449 sd_notify(0, "STOPPING=1");
2451 hibernate_begin_shutdown();
2455 log_debug(LD_GENERAL
,"Caught SIGPIPE. Ignoring.");
2459 /* prefer to log it at INFO, but make sure we always see it */
2460 dumpstats(get_min_log_level()<LOG_INFO
? get_min_log_level() : LOG_INFO
);
2461 control_event_signal(sig
);
2464 switch_logs_debug();
2465 log_debug(LD_GENERAL
,"Caught USR2, going to loglevel debug. "
2466 "Send HUP to change back.");
2467 control_event_signal(sig
);
2471 sd_notify(0, "RELOADING=1");
2474 log_warn(LD_CONFIG
,"Restart failed (config error?). Exiting.");
2479 sd_notify(0, "READY=1");
2481 control_event_signal(sig
);
2485 notify_pending_waitpid_callbacks();
2489 time_t now
= time(NULL
);
2490 if (time_of_last_signewnym
+ MAX_SIGNEWNYM_RATE
> now
) {
2491 signewnym_is_pending
= 1;
2492 log_notice(LD_CONTROL
,
2493 "Rate limiting NEWNYM request: delaying by %d second(s)",
2494 (int)(MAX_SIGNEWNYM_RATE
+time_of_last_signewnym
-now
));
2496 signewnym_impl(now
);
2500 case SIGCLEARDNSCACHE
:
2501 addressmap_clear_transient();
2502 control_event_signal(sig
);
2505 log_heartbeat(time(NULL
));
2506 control_event_signal(sig
);
2511 /** Returns Tor's uptime. */
2515 return stats_n_seconds_working
;
2519 * Write current memory usage information to the log.
2522 dumpmemusage(int severity
)
2524 connection_dump_buffer_mem_stats(severity
);
2525 tor_log(severity
, LD_GENERAL
, "In rephist: "U64_FORMAT
" used by %d Tors.",
2526 U64_PRINTF_ARG(rephist_total_alloc
), rephist_total_num
);
2527 dump_routerlist_mem_usage(severity
);
2528 dump_cell_pool_usage(severity
);
2529 dump_dns_mem_usage(severity
);
2530 tor_log_mallinfo(severity
);
2533 /** Write all statistics to the log, with log level <b>severity</b>. Called
2534 * in response to a SIGUSR1. */
2536 dumpstats(int severity
)
2538 time_t now
= time(NULL
);
2540 size_t rbuf_cap
, wbuf_cap
, rbuf_len
, wbuf_len
;
2542 tor_log(severity
, LD_GENERAL
, "Dumping stats:");
2544 SMARTLIST_FOREACH_BEGIN(connection_array
, connection_t
*, conn
) {
2545 int i
= conn_sl_idx
;
2546 tor_log(severity
, LD_GENERAL
,
2547 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
2548 i
, (int)conn
->s
, conn
->type
, conn_type_to_string(conn
->type
),
2549 conn
->state
, conn_state_to_string(conn
->type
, conn
->state
),
2550 (int)(now
- conn
->timestamp_created
));
2551 if (!connection_is_listener(conn
)) {
2552 tor_log(severity
,LD_GENERAL
,
2553 "Conn %d is to %s:%d.", i
,
2554 safe_str_client(conn
->address
),
2556 tor_log(severity
,LD_GENERAL
,
2557 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
2559 (int)connection_get_inbuf_len(conn
),
2560 (int)buf_allocation(conn
->inbuf
),
2561 (int)(now
- conn
->timestamp_lastread
));
2562 tor_log(severity
,LD_GENERAL
,
2563 "Conn %d: %d bytes waiting on outbuf "
2564 "(len %d, last written %d secs ago)",i
,
2565 (int)connection_get_outbuf_len(conn
),
2566 (int)buf_allocation(conn
->outbuf
),
2567 (int)(now
- conn
->timestamp_lastwritten
));
2568 if (conn
->type
== CONN_TYPE_OR
) {
2569 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2571 if (tor_tls_get_buffer_sizes(or_conn
->tls
, &rbuf_cap
, &rbuf_len
,
2572 &wbuf_cap
, &wbuf_len
) == 0) {
2573 tor_log(severity
, LD_GENERAL
,
2574 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
2575 "%d/%d bytes used on write buffer.",
2576 i
, (int)rbuf_len
, (int)rbuf_cap
, (int)wbuf_len
, (int)wbuf_cap
);
2581 circuit_dump_by_conn(conn
, severity
); /* dump info about all the circuits
2582 * using this conn */
2583 } SMARTLIST_FOREACH_END(conn
);
2585 channel_dumpstats(severity
);
2586 channel_listener_dumpstats(severity
);
2588 tor_log(severity
, LD_NET
,
2589 "Cells processed: "U64_FORMAT
" padding\n"
2590 " "U64_FORMAT
" create\n"
2591 " "U64_FORMAT
" created\n"
2592 " "U64_FORMAT
" relay\n"
2593 " ("U64_FORMAT
" relayed)\n"
2594 " ("U64_FORMAT
" delivered)\n"
2595 " "U64_FORMAT
" destroy",
2596 U64_PRINTF_ARG(stats_n_padding_cells_processed
),
2597 U64_PRINTF_ARG(stats_n_create_cells_processed
),
2598 U64_PRINTF_ARG(stats_n_created_cells_processed
),
2599 U64_PRINTF_ARG(stats_n_relay_cells_processed
),
2600 U64_PRINTF_ARG(stats_n_relay_cells_relayed
),
2601 U64_PRINTF_ARG(stats_n_relay_cells_delivered
),
2602 U64_PRINTF_ARG(stats_n_destroy_cells_processed
));
2603 if (stats_n_data_cells_packaged
)
2604 tor_log(severity
,LD_NET
,"Average packaged cell fullness: %2.3f%%",
2605 100*(U64_TO_DBL(stats_n_data_bytes_packaged
) /
2606 U64_TO_DBL(stats_n_data_cells_packaged
*RELAY_PAYLOAD_SIZE
)) );
2607 if (stats_n_data_cells_received
)
2608 tor_log(severity
,LD_NET
,"Average delivered cell fullness: %2.3f%%",
2609 100*(U64_TO_DBL(stats_n_data_bytes_received
) /
2610 U64_TO_DBL(stats_n_data_cells_received
*RELAY_PAYLOAD_SIZE
)) );
2612 cpuworker_log_onionskin_overhead(severity
, ONION_HANDSHAKE_TYPE_TAP
, "TAP");
2613 cpuworker_log_onionskin_overhead(severity
, ONION_HANDSHAKE_TYPE_NTOR
,"ntor");
2615 if (now
- time_of_process_start
>= 0)
2616 elapsed
= now
- time_of_process_start
;
2621 tor_log(severity
, LD_NET
,
2622 "Average bandwidth: "U64_FORMAT
"/%d = %d bytes/sec reading",
2623 U64_PRINTF_ARG(stats_n_bytes_read
),
2625 (int) (stats_n_bytes_read
/elapsed
));
2626 tor_log(severity
, LD_NET
,
2627 "Average bandwidth: "U64_FORMAT
"/%d = %d bytes/sec writing",
2628 U64_PRINTF_ARG(stats_n_bytes_written
),
2630 (int) (stats_n_bytes_written
/elapsed
));
2633 tor_log(severity
, LD_NET
, "--------------- Dumping memory information:");
2634 dumpmemusage(severity
);
2636 rep_hist_dump_stats(now
,severity
);
2637 rend_service_dump_stats(severity
);
2638 dump_pk_ops(severity
);
2639 dump_distinct_digest_count(severity
);
2642 /** Called by exit() as we shut down the process.
2647 /* NOTE: If we ever daemonize, this gets called immediately. That's
2648 * okay for now, because we only use this on Windows. */
2661 int try_to_register
;
2662 struct event
*signal_event
;
2663 } signal_handlers
[] = {
2665 { SIGINT
, UNIX_ONLY
, NULL
}, /* do a controlled slow shutdown */
2668 { SIGTERM
, UNIX_ONLY
, NULL
}, /* to terminate now */
2671 { SIGPIPE
, UNIX_ONLY
, NULL
}, /* otherwise SIGPIPE kills us */
2674 { SIGUSR1
, UNIX_ONLY
, NULL
}, /* dump stats */
2677 { SIGUSR2
, UNIX_ONLY
, NULL
}, /* go to loglevel debug */
2680 { SIGHUP
, UNIX_ONLY
, NULL
}, /* to reload config, retry conns, etc */
2683 { SIGXFSZ
, UNIX_ONLY
, NULL
}, /* handle file-too-big resource exhaustion */
2686 { SIGCHLD
, UNIX_ONLY
, NULL
}, /* handle dns/cpu workers that exit */
2688 /* These are controller-only */
2689 { SIGNEWNYM
, 0, NULL
},
2690 { SIGCLEARDNSCACHE
, 0, NULL
},
2691 { SIGHEARTBEAT
, 0, NULL
},
2695 /** Set up the signal handlers for either parent or child process */
2697 handle_signals(int is_parent
)
2701 for (i
= 0; signal_handlers
[i
].signal_value
>= 0; ++i
) {
2702 if (signal_handlers
[i
].try_to_register
) {
2703 signal_handlers
[i
].signal_event
=
2704 tor_evsignal_new(tor_libevent_get_base(),
2705 signal_handlers
[i
].signal_value
,
2707 &signal_handlers
[i
].signal_value
);
2708 if (event_add(signal_handlers
[i
].signal_event
, NULL
))
2709 log_warn(LD_BUG
, "Error from libevent when adding "
2710 "event for signal %d",
2711 signal_handlers
[i
].signal_value
);
2713 signal_handlers
[i
].signal_event
=
2714 tor_event_new(tor_libevent_get_base(), -1,
2715 EV_SIGNAL
, signal_callback
,
2716 &signal_handlers
[i
].signal_value
);
2721 struct sigaction action
;
2722 action
.sa_flags
= 0;
2723 sigemptyset(&action
.sa_mask
);
2724 action
.sa_handler
= SIG_IGN
;
2725 sigaction(SIGINT
, &action
, NULL
);
2726 sigaction(SIGTERM
, &action
, NULL
);
2727 sigaction(SIGPIPE
, &action
, NULL
);
2728 sigaction(SIGUSR1
, &action
, NULL
);
2729 sigaction(SIGUSR2
, &action
, NULL
);
2730 sigaction(SIGHUP
, &action
, NULL
);
2732 sigaction(SIGXFSZ
, &action
, NULL
);
2738 /* Make sure the signal handler for signal_num will be called. */
2740 activate_signal(int signal_num
)
2743 for (i
= 0; signal_handlers
[i
].signal_value
>= 0; ++i
) {
2744 if (signal_handlers
[i
].signal_value
== signal_num
) {
2745 event_active(signal_handlers
[i
].signal_event
, EV_SIGNAL
, 1);
2751 /** Main entry point for the Tor command-line client.
2754 tor_init(int argc
, char *argv
[])
2759 time_of_process_start
= time(NULL
);
2760 init_connection_lists();
2761 /* Have the log set up with our application name. */
2762 tor_snprintf(progname
, sizeof(progname
), "Tor %s", get_version());
2763 log_set_application_name(progname
);
2765 /* Set up the crypto nice and early */
2766 if (crypto_early_init() < 0) {
2767 log_err(LD_GENERAL
, "Unable to initialize the crypto subsystem!");
2771 /* Initialize the history structures. */
2773 /* Initialize the service cache. */
2775 addressmap_init(); /* Init the client dns cache. Do it always, since it's
2779 /* We search for the "quiet" option first, since it decides whether we
2780 * will log anything at all to the command line. */
2781 config_line_t
*opts
= NULL
, *cmdline_opts
= NULL
;
2782 const config_line_t
*cl
;
2783 (void) config_parse_commandline(argc
, argv
, 1, &opts
, &cmdline_opts
);
2784 for (cl
= cmdline_opts
; cl
; cl
= cl
->next
) {
2785 if (!strcmp(cl
->key
, "--hush"))
2787 if (!strcmp(cl
->key
, "--quiet") ||
2788 !strcmp(cl
->key
, "--dump-config"))
2790 /* The following options imply --hush */
2791 if (!strcmp(cl
->key
, "--version") || !strcmp(cl
->key
, "--digests") ||
2792 !strcmp(cl
->key
, "--list-torrc-options") ||
2793 !strcmp(cl
->key
, "--library-versions") ||
2794 !strcmp(cl
->key
, "--hash-password") ||
2795 !strcmp(cl
->key
, "-h") || !strcmp(cl
->key
, "--help")) {
2800 config_free_lines(opts
);
2801 config_free_lines(cmdline_opts
);
2804 /* give it somewhere to log to initially */
2807 /* no initial logging */
2810 add_temp_log(LOG_WARN
);
2813 add_temp_log(LOG_NOTICE
);
2815 quiet_level
= quiet
;
2818 const char *version
= get_version();
2820 log_notice(LD_GENERAL
, "Tor %s running on %s with Libevent %s, "
2821 "OpenSSL %s and Zlib %s.", version
,
2823 tor_libevent_get_version_str(),
2824 crypto_openssl_get_version_str(),
2825 tor_zlib_get_version_str());
2827 log_notice(LD_GENERAL
, "Tor can't help you if you use it wrong! "
2828 "Learn how to be safe at "
2829 "https://www.torproject.org/download/download#warning");
2831 if (strstr(version
, "alpha") || strstr(version
, "beta"))
2832 log_notice(LD_GENERAL
, "This version is not a stable Tor release. "
2833 "Expect more bugs than usual.");
2836 if (network_init()<0) {
2837 log_err(LD_BUG
,"Error initializing network; exiting.");
2840 atexit(exit_function
);
2842 if (options_init_from_torrc(argc
,argv
) < 0) {
2843 log_err(LD_CONFIG
,"Reading config failed--see warnings above.");
2847 /* The options are now initialised */
2848 const or_options_t
*options
= get_options();
2850 if (rend_non_anonymous_mode_enabled(options
)) {
2851 log_warn(LD_GENERAL
, "This copy of Tor was compiled or configured to run "
2852 "in a non-anonymous mode. It will provide NO ANONYMITY.");
2857 log_warn(LD_GENERAL
,"You are running Tor as root. You don't need to, "
2858 "and you probably shouldn't.");
2861 if (crypto_global_init(get_options()->HardwareAccel
,
2862 get_options()->AccelName
,
2863 get_options()->AccelDir
)) {
2864 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
2867 stream_choice_seed_weak_rng();
2868 if (tor_init_libevent_rng() < 0) {
2869 log_warn(LD_NET
, "Problem initializing libevent RNG.");
2872 /* Scan/clean unparseable descroptors; after reading config */
2878 /** A lockfile structure, used to prevent two Tors from messing with the
2879 * data directory at once. If this variable is non-NULL, we're holding
2881 static tor_lockfile_t
*lockfile
= NULL
;
2883 /** Try to grab the lock file described in <b>options</b>, if we do not
2884 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
2885 * holding the lock, and exit if we can't get it after waiting. Otherwise,
2886 * return -1 if we can't get the lockfile. Return 0 on success.
2889 try_locking(const or_options_t
*options
, int err_if_locked
)
2894 char *fname
= options_get_datadir_fname2_suffix(options
, "lock",NULL
,NULL
);
2895 int already_locked
= 0;
2896 tor_lockfile_t
*lf
= tor_lockfile_lock(fname
, 0, &already_locked
);
2899 if (err_if_locked
&& already_locked
) {
2901 log_warn(LD_GENERAL
, "It looks like another Tor process is running "
2902 "with the same data directory. Waiting 5 seconds to see "
2903 "if it goes away.");
2909 r
= try_locking(options
, 0);
2911 log_err(LD_GENERAL
, "No, it's still there. Exiting.");
2923 /** Return true iff we've successfully acquired the lock file. */
2927 return lockfile
!= NULL
;
2930 /** If we have successfully acquired the lock file, release it. */
2932 release_lockfile(void)
2935 tor_lockfile_unlock(lockfile
);
2940 /** Free all memory that we might have allocated somewhere.
2941 * If <b>postfork</b>, we are a worker process and we want to free
2942 * only the parts of memory that we won't touch. If !<b>postfork</b>,
2943 * Tor is shutting down and we should free everything.
2945 * Helps us find the real leaks with dmalloc and the like. Also valgrind
2946 * should then report 0 reachable in its leak report (in an ideal world --
2947 * in practice libevent, SSL, libc etc never quite free everything). */
2949 tor_free_all(int postfork
)
2956 routerlist_free_all();
2957 networkstatus_free_all();
2958 addressmap_free_all();
2960 rend_service_free_all();
2961 rend_cache_free_all();
2962 rend_service_authorization_free_all();
2963 rep_hist_free_all();
2965 clear_pending_onions();
2967 entry_guards_free_all();
2969 channel_tls_free_all();
2971 connection_free_all();
2972 connection_edge_free_all();
2973 scheduler_free_all();
2974 nodelist_free_all();
2975 microdesc_free_all();
2976 routerparse_free_all();
2977 ext_orport_free_all();
2979 sandbox_free_getaddrinfo_cache();
2982 or_state_free_all();
2984 routerkeys_free_all();
2985 policies_free_all();
2993 /* stuff in main.c */
2995 smartlist_free(connection_array
);
2996 smartlist_free(closeable_connection_lst
);
2997 smartlist_free(active_linked_connection_lst
);
2998 periodic_timer_free(second_timer
);
2999 teardown_periodic_events();
3000 periodic_timer_free(refill_timer
);
3005 /* Stuff in util.c and address.c*/
3008 esc_router_info(NULL
);
3009 logs_free_all(); /* free log strings. do this last so logs keep working. */
3013 /** Do whatever cleanup is necessary before shutting Tor down. */
3017 const or_options_t
*options
= get_options();
3018 if (options
->command
== CMD_RUN_TOR
) {
3019 time_t now
= time(NULL
);
3020 /* Remove our pid file. We don't care if there was an error when we
3021 * unlink, nothing we could do about it anyways. */
3022 if (options
->PidFile
) {
3023 if (unlink(options
->PidFile
) != 0) {
3024 log_warn(LD_FS
, "Couldn't unlink pid file %s: %s",
3025 options
->PidFile
, strerror(errno
));
3028 if (options
->ControlPortWriteToFile
) {
3029 if (unlink(options
->ControlPortWriteToFile
) != 0) {
3030 log_warn(LD_FS
, "Couldn't unlink control port file %s: %s",
3031 options
->ControlPortWriteToFile
,
3035 if (accounting_is_enabled(options
))
3036 accounting_record_bandwidth_usage(now
, get_or_state());
3037 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
3039 if (authdir_mode(options
)) {
3040 sr_save_and_cleanup();
3042 if (authdir_mode_tests_reachability(options
))
3043 rep_hist_record_mtbf_data(now
, 0);
3044 keypin_close_journal();
3047 dmalloc_log_stats();
3049 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
3050 later, if it makes shutdown unacceptably slow. But for
3051 now, leave it here: it's helped us catch bugs in the
3053 crypto_global_cleanup();
3055 dmalloc_log_unfreed();
3060 /** Read/create keys as needed, and echo our fingerprint to stdout. */
3062 do_list_fingerprint(void)
3064 char buf
[FINGERPRINT_LEN
+1];
3066 const char *nickname
= get_options()->Nickname
;
3067 sandbox_disable_getaddrinfo_cache();
3068 if (!server_mode(get_options())) {
3070 "Clients don't have long-term identity keys. Exiting.");
3073 tor_assert(nickname
);
3074 if (init_keys() < 0) {
3075 log_err(LD_GENERAL
,"Error initializing keys; exiting.");
3078 if (!(k
= get_server_identity_key())) {
3079 log_err(LD_GENERAL
,"Error: missing identity key.");
3082 if (crypto_pk_get_fingerprint(k
, buf
, 1)<0) {
3083 log_err(LD_BUG
, "Error computing fingerprint");
3086 printf("%s %s\n", nickname
, buf
);
3090 /** Entry point for password hashing: take the desired password from
3091 * the command line, and print its salted hash to stdout. **/
3093 do_hash_password(void)
3097 char key
[S2K_RFC2440_SPECIFIER_LEN
+DIGEST_LEN
];
3099 crypto_rand(key
, S2K_RFC2440_SPECIFIER_LEN
-1);
3100 key
[S2K_RFC2440_SPECIFIER_LEN
-1] = (uint8_t)96; /* Hash 64 K of data. */
3101 secret_to_key_rfc2440(key
+S2K_RFC2440_SPECIFIER_LEN
, DIGEST_LEN
,
3102 get_options()->command_arg
, strlen(get_options()->command_arg
),
3104 base16_encode(output
, sizeof(output
), key
, sizeof(key
));
3105 printf("16:%s\n",output
);
3108 /** Entry point for configuration dumping: write the configuration to
3111 do_dump_config(void)
3113 const or_options_t
*options
= get_options();
3114 const char *arg
= options
->command_arg
;
3118 if (!strcmp(arg
, "short")) {
3119 how
= OPTIONS_DUMP_MINIMAL
;
3120 } else if (!strcmp(arg
, "non-builtin")) {
3121 how
= OPTIONS_DUMP_DEFAULTS
;
3122 } else if (!strcmp(arg
, "full")) {
3123 how
= OPTIONS_DUMP_ALL
;
3125 fprintf(stderr
, "No valid argument to --dump-config found!\n");
3126 fprintf(stderr
, "Please select 'short', 'non-builtin', or 'full'.\n");
3131 opts
= options_dump(options
, how
);
3141 if (! server_mode(get_options()) ||
3142 (get_options()->Address
&& strlen(get_options()->Address
) > 0)) {
3143 /* We don't need to seed our own hostname, because we won't be calling
3144 * resolve_my_address on it.
3150 // host name to sandbox
3151 gethostname(hname
, sizeof(hname
));
3152 sandbox_add_addrinfo(hname
);
3155 static sandbox_cfg_t
*
3156 sandbox_init_filter(void)
3158 const or_options_t
*options
= get_options();
3159 sandbox_cfg_t
*cfg
= sandbox_cfg_new();
3162 sandbox_cfg_allow_openat_filename(&cfg
,
3163 get_datadir_fname("cached-status"));
3165 #define OPEN(name) \
3166 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
3168 #define OPEN_DATADIR(name) \
3169 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
3171 #define OPEN_DATADIR2(name, name2) \
3172 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
3174 #define OPEN_DATADIR_SUFFIX(name, suffix) do { \
3175 OPEN_DATADIR(name); \
3176 OPEN_DATADIR(name suffix); \
3179 #define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
3180 OPEN_DATADIR2(name, name2); \
3181 OPEN_DATADIR2(name, name2 suffix); \
3184 OPEN(options
->DataDirectory
);
3185 OPEN_DATADIR("keys");
3186 OPEN_DATADIR_SUFFIX("cached-certs", ".tmp");
3187 OPEN_DATADIR_SUFFIX("cached-consensus", ".tmp");
3188 OPEN_DATADIR_SUFFIX("unverified-consensus", ".tmp");
3189 OPEN_DATADIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
3190 OPEN_DATADIR_SUFFIX("cached-microdesc-consensus", ".tmp");
3191 OPEN_DATADIR_SUFFIX("cached-microdescs", ".tmp");
3192 OPEN_DATADIR_SUFFIX("cached-microdescs.new", ".tmp");
3193 OPEN_DATADIR_SUFFIX("cached-descriptors", ".tmp");
3194 OPEN_DATADIR_SUFFIX("cached-descriptors.new", ".tmp");
3195 OPEN_DATADIR("cached-descriptors.tmp.tmp");
3196 OPEN_DATADIR_SUFFIX("cached-extrainfo", ".tmp");
3197 OPEN_DATADIR_SUFFIX("cached-extrainfo.new", ".tmp");
3198 OPEN_DATADIR("cached-extrainfo.tmp.tmp");
3199 OPEN_DATADIR_SUFFIX("state", ".tmp");
3200 OPEN_DATADIR_SUFFIX("sr-state", ".tmp");
3201 OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
3202 OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
3203 OPEN_DATADIR("key-pinning-journal");
3204 OPEN("/dev/srandom");
3205 OPEN("/dev/urandom");
3206 OPEN("/dev/random");
3208 OPEN("/proc/meminfo");
3210 if (options
->BridgeAuthoritativeDir
)
3211 OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
3213 if (authdir_mode_handles_descs(options
, -1))
3214 OPEN_DATADIR("approved-routers");
3216 if (options
->ServerDNSResolvConfFile
)
3217 sandbox_cfg_allow_open_filename(&cfg
,
3218 tor_strdup(options
->ServerDNSResolvConfFile
));
3220 sandbox_cfg_allow_open_filename(&cfg
, tor_strdup("/etc/resolv.conf"));
3222 for (i
= 0; i
< 2; ++i
) {
3223 if (get_torrc_fname(i
)) {
3224 sandbox_cfg_allow_open_filename(&cfg
, tor_strdup(get_torrc_fname(i
)));
3228 #define RENAME_SUFFIX(name, suffix) \
3229 sandbox_cfg_allow_rename(&cfg, \
3230 get_datadir_fname(name suffix), \
3231 get_datadir_fname(name))
3233 #define RENAME_SUFFIX2(prefix, name, suffix) \
3234 sandbox_cfg_allow_rename(&cfg, \
3235 get_datadir_fname2(prefix, name suffix), \
3236 get_datadir_fname2(prefix, name))
3238 RENAME_SUFFIX("cached-certs", ".tmp");
3239 RENAME_SUFFIX("cached-consensus", ".tmp");
3240 RENAME_SUFFIX("unverified-consensus", ".tmp");
3241 RENAME_SUFFIX("unverified-microdesc-consensus", ".tmp");
3242 RENAME_SUFFIX("cached-microdesc-consensus", ".tmp");
3243 RENAME_SUFFIX("cached-microdescs", ".tmp");
3244 RENAME_SUFFIX("cached-microdescs", ".new");
3245 RENAME_SUFFIX("cached-microdescs.new", ".tmp");
3246 RENAME_SUFFIX("cached-descriptors", ".tmp");
3247 RENAME_SUFFIX("cached-descriptors", ".new");
3248 RENAME_SUFFIX("cached-descriptors.new", ".tmp");
3249 RENAME_SUFFIX("cached-extrainfo", ".tmp");
3250 RENAME_SUFFIX("cached-extrainfo", ".new");
3251 RENAME_SUFFIX("cached-extrainfo.new", ".tmp");
3252 RENAME_SUFFIX("state", ".tmp");
3253 RENAME_SUFFIX("sr-state", ".tmp");
3254 RENAME_SUFFIX("unparseable-desc", ".tmp");
3255 RENAME_SUFFIX("v3-status-votes", ".tmp");
3257 if (options
->BridgeAuthoritativeDir
)
3258 RENAME_SUFFIX("networkstatus-bridges", ".tmp");
3260 #define STAT_DATADIR(name) \
3261 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
3263 #define STAT_DATADIR2(name, name2) \
3264 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
3267 STAT_DATADIR("lock");
3268 STAT_DATADIR("state");
3269 STAT_DATADIR("router-stability");
3270 STAT_DATADIR("cached-extrainfo.new");
3273 smartlist_t
*files
= smartlist_new();
3274 tor_log_get_logfile_names(files
);
3275 SMARTLIST_FOREACH(files
, char *, file_name
, {
3276 /* steals reference */
3277 sandbox_cfg_allow_open_filename(&cfg
, file_name
);
3279 smartlist_free(files
);
3283 smartlist_t
*files
= smartlist_new();
3284 smartlist_t
*dirs
= smartlist_new();
3285 rend_services_add_filenames_to_lists(files
, dirs
);
3286 SMARTLIST_FOREACH(files
, char *, file_name
, {
3287 char *tmp_name
= NULL
;
3288 tor_asprintf(&tmp_name
, "%s.tmp", file_name
);
3289 sandbox_cfg_allow_rename(&cfg
,
3290 tor_strdup(tmp_name
), tor_strdup(file_name
));
3291 /* steals references */
3292 sandbox_cfg_allow_open_filename(&cfg
, file_name
);
3293 sandbox_cfg_allow_open_filename(&cfg
, tmp_name
);
3295 SMARTLIST_FOREACH(dirs
, char *, dir
, {
3296 /* steals reference */
3297 sandbox_cfg_allow_stat_filename(&cfg
, dir
);
3299 smartlist_free(files
);
3300 smartlist_free(dirs
);
3305 if ((fname
= get_controller_cookie_file_name())) {
3306 sandbox_cfg_allow_open_filename(&cfg
, fname
);
3308 if ((fname
= get_ext_or_auth_cookie_file_name())) {
3309 sandbox_cfg_allow_open_filename(&cfg
, fname
);
3313 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), port_cfg_t
*, port
) {
3314 if (!port
->is_unix_addr
)
3316 /* When we open an AF_UNIX address, we want permission to open the
3317 * directory that holds it. */
3318 char *dirname
= tor_strdup(port
->unix_addr
);
3319 if (get_parent_directory(dirname
) == 0) {
3323 sandbox_cfg_allow_chmod_filename(&cfg
, tor_strdup(port
->unix_addr
));
3324 sandbox_cfg_allow_chown_filename(&cfg
, tor_strdup(port
->unix_addr
));
3325 } SMARTLIST_FOREACH_END(port
);
3327 if (options
->DirPortFrontPage
) {
3328 sandbox_cfg_allow_open_filename(&cfg
,
3329 tor_strdup(options
->DirPortFrontPage
));
3333 if (server_mode(get_options())) {
3335 OPEN_DATADIR2_SUFFIX("keys", "secret_id_key", ".tmp");
3336 OPEN_DATADIR2_SUFFIX("keys", "secret_onion_key", ".tmp");
3337 OPEN_DATADIR2_SUFFIX("keys", "secret_onion_key_ntor", ".tmp");
3338 OPEN_DATADIR2("keys", "secret_id_key.old");
3339 OPEN_DATADIR2("keys", "secret_onion_key.old");
3340 OPEN_DATADIR2("keys", "secret_onion_key_ntor.old");
3342 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_secret_key", ".tmp");
3343 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_secret_key_encrypted",
3345 OPEN_DATADIR2_SUFFIX("keys", "ed25519_master_id_public_key", ".tmp");
3346 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_secret_key", ".tmp");
3347 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_secret_key_encrypted",
3349 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_public_key", ".tmp");
3350 OPEN_DATADIR2_SUFFIX("keys", "ed25519_signing_cert", ".tmp");
3352 OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
3353 OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
3355 OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
3356 OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
3357 OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
3358 OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
3359 OPEN_DATADIR2_SUFFIX("stats", "hidserv-stats", ".tmp");
3361 OPEN_DATADIR("approved-routers");
3362 OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
3363 OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
3364 OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
3366 OPEN("/etc/resolv.conf");
3368 RENAME_SUFFIX("fingerprint", ".tmp");
3369 RENAME_SUFFIX2("keys", "secret_onion_key_ntor", ".tmp");
3370 RENAME_SUFFIX2("keys", "secret_id_key", ".tmp");
3371 RENAME_SUFFIX2("keys", "secret_id_key.old", ".tmp");
3372 RENAME_SUFFIX2("keys", "secret_onion_key", ".tmp");
3373 RENAME_SUFFIX2("keys", "secret_onion_key.old", ".tmp");
3374 RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
3375 RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
3376 RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
3377 RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
3378 RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
3379 RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
3380 RENAME_SUFFIX2("stats", "hidserv-stats", ".tmp");
3381 RENAME_SUFFIX("hashed-fingerprint", ".tmp");
3382 RENAME_SUFFIX("router-stability", ".tmp");
3384 RENAME_SUFFIX2("keys", "ed25519_master_id_secret_key", ".tmp");
3385 RENAME_SUFFIX2("keys", "ed25519_master_id_secret_key_encrypted", ".tmp");
3386 RENAME_SUFFIX2("keys", "ed25519_master_id_public_key", ".tmp");
3387 RENAME_SUFFIX2("keys", "ed25519_signing_secret_key", ".tmp");
3388 RENAME_SUFFIX2("keys", "ed25519_signing_cert", ".tmp");
3390 sandbox_cfg_allow_rename(&cfg
,
3391 get_datadir_fname2("keys", "secret_onion_key"),
3392 get_datadir_fname2("keys", "secret_onion_key.old"));
3393 sandbox_cfg_allow_rename(&cfg
,
3394 get_datadir_fname2("keys", "secret_onion_key_ntor"),
3395 get_datadir_fname2("keys", "secret_onion_key_ntor.old"));
3397 STAT_DATADIR("keys");
3398 OPEN_DATADIR("stats");
3399 STAT_DATADIR("stats");
3400 STAT_DATADIR2("stats", "dirreq-stats");
3408 /** Main entry point for the Tor process. Called from main(). */
3409 /* This function is distinct from main() only so we can link main.c into
3410 * the unittest binary without conflicting with the unittests' main. */
3412 tor_main(int argc
, char *argv
[])
3417 /* Call SetProcessDEPPolicy to permanently enable DEP.
3418 The function will not resolve on earlier versions of Windows,
3419 and failure is not dangerous. */
3420 HMODULE hMod
= GetModuleHandleA("Kernel32.dll");
3422 typedef BOOL (WINAPI
*PSETDEP
)(DWORD
);
3423 PSETDEP setdeppolicy
= (PSETDEP
)GetProcAddress(hMod
,
3424 "SetProcessDEPPolicy");
3425 if (setdeppolicy
) setdeppolicy(1); /* PROCESS_DEP_ENABLE */
3429 configure_backtrace_handler(get_version());
3431 update_approx_time(time(NULL
));
3436 /* Instruct OpenSSL to use our internal wrappers for malloc,
3437 realloc and free. */
3438 int r
= CRYPTO_set_mem_ex_functions(tor_malloc_
, tor_realloc_
, tor_free_
);
3445 result
= nt_service_parse_options(argc
, argv
, &done
);
3446 if (done
) return result
;
3449 if (tor_init(argc
, argv
)<0)
3452 if (get_options()->Sandbox
&& get_options()->command
== CMD_RUN_TOR
) {
3453 sandbox_cfg_t
* cfg
= sandbox_init_filter();
3455 if (sandbox_init(cfg
)) {
3456 log_err(LD_BUG
,"Failed to create syscall sandbox filter");
3460 // registering libevent rng
3461 #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
3462 evutil_secure_rng_set_urandom_device_file(
3463 (char*) sandbox_intern_string("/dev/urandom"));
3469 switch (get_options()->command
) {
3472 nt_service_set_state(SERVICE_RUNNING
);
3474 result
= do_main_loop();
3477 result
= load_ed_keys(get_options(), time(NULL
));
3479 case CMD_LIST_FINGERPRINT
:
3480 result
= do_list_fingerprint();
3482 case CMD_HASH_PASSWORD
:
3486 case CMD_VERIFY_CONFIG
:
3487 if (quiet_level
== 0)
3488 printf("Configuration was valid\n");
3491 case CMD_DUMP_CONFIG
:
3492 result
= do_dump_config();
3494 case CMD_RUN_UNITTESTS
: /* only set by test.c */
3496 log_warn(LD_BUG
,"Illegal command number %d: internal error.",
3497 get_options()->command
);