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-2013, 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 "directory.h"
36 #include "entrynodes.h"
38 #include "hibernate.h"
40 #include "microdesc.h"
41 #include "networkstatus.h"
46 #include "transports.h"
48 #include "rendclient.h"
49 #include "rendcommon.h"
50 #include "rendservice.h"
53 #include "routerlist.h"
54 #include "routerparse.h"
55 #include "statefile.h"
57 #include "ext_orport.h"
60 #include <openssl/crypto.h>
63 #include "../common/sandbox.h"
65 #ifdef HAVE_EVENT2_EVENT_H
66 #include <event2/event.h>
71 #ifdef USE_BUFFEREVENTS
72 #include <event2/bufferevent.h>
75 void evdns_shutdown(int);
77 /********* PROTOTYPES **********/
79 static void dumpmemusage(int severity
);
80 static void dumpstats(int severity
); /* log stats */
81 static void conn_read_callback(evutil_socket_t fd
, short event
, void *_conn
);
82 static void conn_write_callback(evutil_socket_t fd
, short event
, void *_conn
);
83 static void second_elapsed_callback(periodic_timer_t
*timer
, void *args
);
84 static int conn_close_if_marked(int i
);
85 static void connection_start_reading_from_linked_conn(connection_t
*conn
);
86 static int connection_should_read_from_linked_conn(connection_t
*conn
);
88 /********* START VARIABLES **********/
90 #ifndef USE_BUFFEREVENTS
91 int global_read_bucket
; /**< Max number of bytes I can read this second. */
92 int global_write_bucket
; /**< Max number of bytes I can write this second. */
94 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
95 int global_relayed_read_bucket
;
96 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
97 int global_relayed_write_bucket
;
98 /** What was the read bucket before the last second_elapsed_callback() call?
99 * (used to determine how many bytes we've read). */
100 static int stats_prev_global_read_bucket
;
101 /** What was the write bucket before the last second_elapsed_callback() call?
102 * (used to determine how many bytes we've written). */
103 static int stats_prev_global_write_bucket
;
106 /* DOCDOC stats_prev_n_read */
107 static uint64_t stats_prev_n_read
= 0;
108 /* DOCDOC stats_prev_n_written */
109 static uint64_t stats_prev_n_written
= 0;
111 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
112 /** How many bytes have we read since we started the process? */
113 static uint64_t stats_n_bytes_read
= 0;
114 /** How many bytes have we written since we started the process? */
115 static uint64_t stats_n_bytes_written
= 0;
116 /** What time did this process start up? */
117 time_t time_of_process_start
= 0;
118 /** How many seconds have we been running? */
119 long stats_n_seconds_working
= 0;
120 /** When do we next launch DNS wildcarding checks? */
121 static time_t time_to_check_for_correct_dns
= 0;
123 /** How often will we honor SIGNEWNYM requests? */
124 #define MAX_SIGNEWNYM_RATE 10
125 /** When did we last process a SIGNEWNYM request? */
126 static time_t time_of_last_signewnym
= 0;
127 /** Is there a signewnym request we're currently waiting to handle? */
128 static int signewnym_is_pending
= 0;
129 /** How many times have we called newnym? */
130 static unsigned newnym_epoch
= 0;
132 /** Smartlist of all open connections. */
133 static smartlist_t
*connection_array
= NULL
;
134 /** List of connections that have been marked for close and need to be freed
135 * and removed from connection_array. */
136 static smartlist_t
*closeable_connection_lst
= NULL
;
137 /** List of linked connections that are currently reading data into their
138 * inbuf from their partner's outbuf. */
139 static smartlist_t
*active_linked_connection_lst
= NULL
;
140 /** Flag: Set to true iff we entered the current libevent main loop via
141 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
142 * to handle linked connections. */
143 static int called_loop_once
= 0;
145 /** We set this to 1 when we've opened a circuit, so we can print a log
146 * entry to inform the user that Tor is working. We set it to 0 when
147 * we think the fact that we once opened a circuit doesn't mean we can do so
148 * any longer (a big time jump happened, when we notice our directory is
149 * heinously out-of-date, etc.
151 int can_complete_circuit
=0;
153 /** How often do we check for router descriptors that we should download
154 * when we have too little directory info? */
155 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
156 /** How often do we check for router descriptors that we should download
157 * when we have enough directory info? */
158 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
159 /** How often do we 'forgive' undownloadable router descriptors and attempt
160 * to download them again? */
161 #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
163 /** Decides our behavior when no logs are configured/before any
164 * logs have been configured. For 0, we log notice to stdout as normal.
165 * For 1, we log warnings only. For 2, we log nothing.
169 /********* END VARIABLES ************/
171 /****************************************************************************
173 * This section contains accessors and other methods on the connection_array
174 * variables (which are global within this file and unavailable outside it).
176 ****************************************************************************/
178 #if 0 && defined(USE_BUFFEREVENTS)
180 free_old_inbuf(connection_t
*conn
)
185 tor_assert(conn
->outbuf
);
186 tor_assert(buf_datalen(conn
->inbuf
) == 0);
187 tor_assert(buf_datalen(conn
->outbuf
) == 0);
188 buf_free(conn
->inbuf
);
189 buf_free(conn
->outbuf
);
190 conn
->inbuf
= conn
->outbuf
= NULL
;
192 if (conn
->read_event
) {
193 event_del(conn
->read_event
);
194 tor_event_free(conn
->read_event
);
196 if (conn
->write_event
) {
197 event_del(conn
->read_event
);
198 tor_event_free(conn
->write_event
);
200 conn
->read_event
= conn
->write_event
= NULL
;
204 #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
205 /** Remove the kernel-space send and receive buffers for <b>s</b>. For use
208 set_buffer_lengths_to_zero(tor_socket_t s
)
212 if (setsockopt(s
, SOL_SOCKET
, SO_SNDBUF
, (void*)&zero
, sizeof(zero
))) {
213 log_warn(LD_NET
, "Unable to clear SO_SNDBUF");
216 if (setsockopt(s
, SOL_SOCKET
, SO_RCVBUF
, (void*)&zero
, sizeof(zero
))) {
217 log_warn(LD_NET
, "Unable to clear SO_RCVBUF");
224 /** Add <b>conn</b> to the array of connections that we can poll on. The
225 * connection's socket must be set; the connection starts out
226 * non-reading and non-writing.
229 connection_add_impl(connection_t
*conn
, int is_connecting
)
232 tor_assert(SOCKET_OK(conn
->s
) ||
234 (conn
->type
== CONN_TYPE_AP
&&
235 TO_EDGE_CONN(conn
)->is_dns_request
));
237 tor_assert(conn
->conn_array_index
== -1); /* can only connection_add once */
238 conn
->conn_array_index
= smartlist_len(connection_array
);
239 smartlist_add(connection_array
, conn
);
241 #ifdef USE_BUFFEREVENTS
242 if (connection_type_uses_bufferevent(conn
)) {
243 if (SOCKET_OK(conn
->s
) && !conn
->linked
) {
246 if (tor_libevent_using_iocp_bufferevents() &&
247 get_options()->UserspaceIOCPBuffers
) {
248 set_buffer_lengths_to_zero(conn
->s
);
252 conn
->bufev
= bufferevent_socket_new(
253 tor_libevent_get_base(),
255 BEV_OPT_DEFER_CALLBACKS
);
257 log_warn(LD_BUG
, "Unable to create socket bufferevent");
258 smartlist_del(connection_array
, conn
->conn_array_index
);
259 conn
->conn_array_index
= -1;
263 /* Put the bufferevent into a "connecting" state so that we'll get
264 * a "connected" event callback on successful write. */
265 bufferevent_socket_connect(conn
->bufev
, NULL
, 0);
267 connection_configure_bufferevent_callbacks(conn
);
268 } else if (conn
->linked
&& conn
->linked_conn
&&
269 connection_type_uses_bufferevent(conn
->linked_conn
)) {
270 tor_assert(!(SOCKET_OK(conn
->s
)));
272 struct bufferevent
*pair
[2] = { NULL
, NULL
};
273 if (bufferevent_pair_new(tor_libevent_get_base(),
274 BEV_OPT_DEFER_CALLBACKS
,
276 log_warn(LD_BUG
, "Unable to create bufferevent pair");
277 smartlist_del(connection_array
, conn
->conn_array_index
);
278 conn
->conn_array_index
= -1;
282 conn
->bufev
= pair
[0];
283 conn
->linked_conn
->bufev
= pair
[1];
284 } /* else the other side already was added, and got a bufferevent_pair */
285 connection_configure_bufferevent_callbacks(conn
);
287 tor_assert(!conn
->linked
);
291 tor_assert(conn
->inbuf
== NULL
);
293 if (conn
->linked_conn
&& conn
->linked_conn
->bufev
)
294 tor_assert(conn
->linked_conn
->inbuf
== NULL
);
297 (void) is_connecting
;
300 if (!HAS_BUFFEREVENT(conn
) && (SOCKET_OK(conn
->s
) || conn
->linked
)) {
301 conn
->read_event
= tor_event_new(tor_libevent_get_base(),
302 conn
->s
, EV_READ
|EV_PERSIST
, conn_read_callback
, conn
);
303 conn
->write_event
= tor_event_new(tor_libevent_get_base(),
304 conn
->s
, EV_WRITE
|EV_PERSIST
, conn_write_callback
, conn
);
305 /* XXXX CHECK FOR NULL RETURN! */
308 log_debug(LD_NET
,"new conn type %s, socket %d, address %s, n_conns %d.",
309 conn_type_to_string(conn
->type
), (int)conn
->s
, conn
->address
,
310 smartlist_len(connection_array
));
315 /** Tell libevent that we don't care about <b>conn</b> any more. */
317 connection_unregister_events(connection_t
*conn
)
319 if (conn
->read_event
) {
320 if (event_del(conn
->read_event
))
321 log_warn(LD_BUG
, "Error removing read event for %d", (int)conn
->s
);
322 tor_free(conn
->read_event
);
324 if (conn
->write_event
) {
325 if (event_del(conn
->write_event
))
326 log_warn(LD_BUG
, "Error removing write event for %d", (int)conn
->s
);
327 tor_free(conn
->write_event
);
329 #ifdef USE_BUFFEREVENTS
331 bufferevent_free(conn
->bufev
);
335 if (conn
->type
== CONN_TYPE_AP_DNS_LISTENER
) {
336 dnsserv_close_listener(conn
);
340 /** Remove the connection from the global list, and remove the
341 * corresponding poll entry. Calling this function will shift the last
342 * connection (if any) into the position occupied by conn.
345 connection_remove(connection_t
*conn
)
352 log_debug(LD_NET
,"removing socket %d (type %s), n_conns now %d",
353 (int)conn
->s
, conn_type_to_string(conn
->type
),
354 smartlist_len(connection_array
));
356 control_event_conn_bandwidth(conn
);
358 tor_assert(conn
->conn_array_index
>= 0);
359 current_index
= conn
->conn_array_index
;
360 connection_unregister_events(conn
); /* This is redundant, but cheap. */
361 if (current_index
== smartlist_len(connection_array
)-1) { /* at the end */
362 smartlist_del(connection_array
, current_index
);
366 /* replace this one with the one at the end */
367 smartlist_del(connection_array
, current_index
);
368 tmp
= smartlist_get(connection_array
, current_index
);
369 tmp
->conn_array_index
= current_index
;
374 /** If <b>conn</b> is an edge conn, remove it from the list
375 * of conn's on this circuit. If it's not on an edge,
376 * flush and send destroys for all circuits on this conn.
378 * Remove it from connection_array (if applicable) and
379 * from closeable_connection_list.
384 connection_unlink(connection_t
*conn
)
386 connection_about_to_close_connection(conn
);
387 if (conn
->conn_array_index
>= 0) {
388 connection_remove(conn
);
390 if (conn
->linked_conn
) {
391 conn
->linked_conn
->linked_conn
= NULL
;
392 if (! conn
->linked_conn
->marked_for_close
&&
393 conn
->linked_conn
->reading_from_linked_conn
)
394 connection_start_reading(conn
->linked_conn
);
395 conn
->linked_conn
= NULL
;
397 smartlist_remove(closeable_connection_lst
, conn
);
398 smartlist_remove(active_linked_connection_lst
, conn
);
399 if (conn
->type
== CONN_TYPE_EXIT
) {
400 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn
));
402 if (conn
->type
== CONN_TYPE_OR
) {
403 if (!tor_digest_is_zero(TO_OR_CONN(conn
)->identity_digest
))
404 connection_or_remove_from_identity_map(TO_OR_CONN(conn
));
405 /* connection_unlink() can only get called if the connection
406 * was already on the closeable list, and it got there by
407 * connection_mark_for_close(), which was called from
408 * connection_or_close_normally() or
409 * connection_or_close_for_error(), so the channel should
410 * already be in CHANNEL_STATE_CLOSING, and then the
411 * connection_about_to_close_connection() goes to
412 * connection_or_about_to_close(), which calls channel_closed()
413 * to notify the channel_t layer, and closed the channel, so
414 * nothing more to do here to deal with the channel associated
418 connection_free(conn
);
421 /** Initialize the global connection list, closeable connection list,
422 * and active connection list. */
424 init_connection_lists(void)
426 if (!connection_array
)
427 connection_array
= smartlist_new();
428 if (!closeable_connection_lst
)
429 closeable_connection_lst
= smartlist_new();
430 if (!active_linked_connection_lst
)
431 active_linked_connection_lst
= smartlist_new();
434 /** Schedule <b>conn</b> to be closed. **/
436 add_connection_to_closeable_list(connection_t
*conn
)
438 tor_assert(!smartlist_contains(closeable_connection_lst
, conn
));
439 tor_assert(conn
->marked_for_close
);
440 assert_connection_ok(conn
, time(NULL
));
441 smartlist_add(closeable_connection_lst
, conn
);
444 /** Return 1 if conn is on the closeable list, else return 0. */
446 connection_is_on_closeable_list(connection_t
*conn
)
448 return smartlist_contains(closeable_connection_lst
, conn
);
451 /** Return true iff conn is in the current poll array. */
453 connection_in_array(connection_t
*conn
)
455 return smartlist_contains(connection_array
, conn
);
458 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
459 * to the length of the array. <b>*array</b> and <b>*n</b> must not
463 get_connection_array(void)
465 if (!connection_array
)
466 connection_array
= smartlist_new();
467 return connection_array
;
470 /** Provides the traffic read and written over the life of the process. */
473 get_bytes_read
,(void))
475 return stats_n_bytes_read
;
478 /* DOCDOC get_bytes_written */
480 get_bytes_written
,(void))
482 return stats_n_bytes_written
;
485 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
486 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
489 connection_watch_events(connection_t
*conn
, watchable_events_t events
)
491 IF_HAS_BUFFEREVENT(conn
, {
492 short ev
= ((short)events
) & (EV_READ
|EV_WRITE
);
493 short old_ev
= bufferevent_get_enabled(conn
->bufev
);
494 if ((ev
& ~old_ev
) != 0) {
495 bufferevent_enable(conn
->bufev
, ev
);
497 if ((old_ev
& ~ev
) != 0) {
498 bufferevent_disable(conn
->bufev
, old_ev
& ~ev
);
502 if (events
& READ_EVENT
)
503 connection_start_reading(conn
);
505 connection_stop_reading(conn
);
507 if (events
& WRITE_EVENT
)
508 connection_start_writing(conn
);
510 connection_stop_writing(conn
);
513 /** Return true iff <b>conn</b> is listening for read events. */
515 connection_is_reading(connection_t
*conn
)
519 IF_HAS_BUFFEREVENT(conn
,
520 return (bufferevent_get_enabled(conn
->bufev
) & EV_READ
) != 0;
522 return conn
->reading_from_linked_conn
||
523 (conn
->read_event
&& event_pending(conn
->read_event
, EV_READ
, NULL
));
526 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
528 connection_stop_reading
,(connection_t
*conn
))
532 IF_HAS_BUFFEREVENT(conn
, {
533 bufferevent_disable(conn
->bufev
, EV_READ
);
537 tor_assert(conn
->read_event
);
540 conn
->reading_from_linked_conn
= 0;
541 connection_stop_reading_from_linked_conn(conn
);
543 if (event_del(conn
->read_event
))
544 log_warn(LD_NET
, "Error from libevent setting read event state for %d "
547 tor_socket_strerror(tor_socket_errno(conn
->s
)));
551 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
553 connection_start_reading
,(connection_t
*conn
))
557 IF_HAS_BUFFEREVENT(conn
, {
558 bufferevent_enable(conn
->bufev
, EV_READ
);
562 tor_assert(conn
->read_event
);
565 conn
->reading_from_linked_conn
= 1;
566 if (connection_should_read_from_linked_conn(conn
))
567 connection_start_reading_from_linked_conn(conn
);
569 if (event_add(conn
->read_event
, NULL
))
570 log_warn(LD_NET
, "Error from libevent setting read event state for %d "
573 tor_socket_strerror(tor_socket_errno(conn
->s
)));
577 /** Return true iff <b>conn</b> is listening for write events. */
579 connection_is_writing(connection_t
*conn
)
583 IF_HAS_BUFFEREVENT(conn
,
584 return (bufferevent_get_enabled(conn
->bufev
) & EV_WRITE
) != 0;
587 return conn
->writing_to_linked_conn
||
588 (conn
->write_event
&& event_pending(conn
->write_event
, EV_WRITE
, NULL
));
591 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
593 connection_stop_writing
,(connection_t
*conn
))
597 IF_HAS_BUFFEREVENT(conn
, {
598 bufferevent_disable(conn
->bufev
, EV_WRITE
);
602 tor_assert(conn
->write_event
);
605 conn
->writing_to_linked_conn
= 0;
606 if (conn
->linked_conn
)
607 connection_stop_reading_from_linked_conn(conn
->linked_conn
);
609 if (event_del(conn
->write_event
))
610 log_warn(LD_NET
, "Error from libevent setting write event state for %d "
613 tor_socket_strerror(tor_socket_errno(conn
->s
)));
617 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
619 connection_start_writing
,(connection_t
*conn
))
623 IF_HAS_BUFFEREVENT(conn
, {
624 bufferevent_enable(conn
->bufev
, EV_WRITE
);
628 tor_assert(conn
->write_event
);
631 conn
->writing_to_linked_conn
= 1;
632 if (conn
->linked_conn
&&
633 connection_should_read_from_linked_conn(conn
->linked_conn
))
634 connection_start_reading_from_linked_conn(conn
->linked_conn
);
636 if (event_add(conn
->write_event
, NULL
))
637 log_warn(LD_NET
, "Error from libevent setting write event state for %d "
640 tor_socket_strerror(tor_socket_errno(conn
->s
)));
644 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
645 * linked to it would be good and feasible. (Reading is "feasible" if the
646 * other conn exists and has data in its outbuf, and is "good" if we have our
647 * reading_from_linked_conn flag set and the other conn has its
648 * writing_to_linked_conn flag set.)*/
650 connection_should_read_from_linked_conn(connection_t
*conn
)
652 if (conn
->linked
&& conn
->reading_from_linked_conn
) {
653 if (! conn
->linked_conn
||
654 (conn
->linked_conn
->writing_to_linked_conn
&&
655 buf_datalen(conn
->linked_conn
->outbuf
)))
661 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
662 * its linked connection, if it is not doing so already. Called by
663 * connection_start_reading and connection_start_writing as appropriate. */
665 connection_start_reading_from_linked_conn(connection_t
*conn
)
668 tor_assert(conn
->linked
== 1);
670 if (!conn
->active_on_link
) {
671 conn
->active_on_link
= 1;
672 smartlist_add(active_linked_connection_lst
, conn
);
673 if (!called_loop_once
) {
674 /* This is the first event on the list; we won't be in LOOP_ONCE mode,
675 * so we need to make sure that the event_base_loop() actually exits at
676 * the end of its run through the current connections and lets us
677 * activate read events for linked connections. */
678 struct timeval tv
= { 0, 0 };
679 tor_event_base_loopexit(tor_libevent_get_base(), &tv
);
682 tor_assert(smartlist_contains(active_linked_connection_lst
, conn
));
686 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
687 * connection, if is currently doing so. Called by connection_stop_reading,
688 * connection_stop_writing, and connection_read. */
690 connection_stop_reading_from_linked_conn(connection_t
*conn
)
693 tor_assert(conn
->linked
== 1);
695 if (conn
->active_on_link
) {
696 conn
->active_on_link
= 0;
697 /* FFFF We could keep an index here so we can smartlist_del
698 * cleanly. On the other hand, this doesn't show up on profiles,
699 * so let's leave it alone for now. */
700 smartlist_remove(active_linked_connection_lst
, conn
);
702 tor_assert(!smartlist_contains(active_linked_connection_lst
, conn
));
706 /** Close all connections that have been scheduled to get closed. */
708 close_closeable_connections(void)
711 for (i
= 0; i
< smartlist_len(closeable_connection_lst
); ) {
712 connection_t
*conn
= smartlist_get(closeable_connection_lst
, i
);
713 if (conn
->conn_array_index
< 0) {
714 connection_unlink(conn
); /* blow it away right now */
716 if (!conn_close_if_marked(conn
->conn_array_index
))
722 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
723 * some data to read. */
725 conn_read_callback(evutil_socket_t fd
, short event
, void *_conn
)
727 connection_t
*conn
= _conn
;
731 log_debug(LD_NET
,"socket %d wants to read.",(int)conn
->s
);
733 /* assert_connection_ok(conn, time(NULL)); */
735 if (connection_handle_read(conn
) < 0) {
736 if (!conn
->marked_for_close
) {
738 log_warn(LD_BUG
,"Unhandled error on read for %s connection "
740 conn_type_to_string(conn
->type
), (int)conn
->s
);
741 tor_fragile_assert();
743 if (CONN_IS_EDGE(conn
))
744 connection_edge_end_errno(TO_EDGE_CONN(conn
));
745 connection_mark_for_close(conn
);
748 assert_connection_ok(conn
, time(NULL
));
750 if (smartlist_len(closeable_connection_lst
))
751 close_closeable_connections();
754 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
755 * some data to write. */
757 conn_write_callback(evutil_socket_t fd
, short events
, void *_conn
)
759 connection_t
*conn
= _conn
;
763 LOG_FN_CONN(conn
, (LOG_DEBUG
, LD_NET
, "socket %d wants to write.",
766 /* assert_connection_ok(conn, time(NULL)); */
768 if (connection_handle_write(conn
, 0) < 0) {
769 if (!conn
->marked_for_close
) {
770 /* this connection is broken. remove it. */
771 log_fn(LOG_WARN
,LD_BUG
,
772 "unhandled error on write for %s connection (fd %d); removing",
773 conn_type_to_string(conn
->type
), (int)conn
->s
);
774 tor_fragile_assert();
775 if (CONN_IS_EDGE(conn
)) {
776 /* otherwise we cry wolf about duplicate close */
777 edge_connection_t
*edge_conn
= TO_EDGE_CONN(conn
);
778 if (!edge_conn
->end_reason
)
779 edge_conn
->end_reason
= END_STREAM_REASON_INTERNAL
;
780 edge_conn
->edge_has_sent_end
= 1;
782 connection_close_immediate(conn
); /* So we don't try to flush. */
783 connection_mark_for_close(conn
);
786 assert_connection_ok(conn
, time(NULL
));
788 if (smartlist_len(closeable_connection_lst
))
789 close_closeable_connections();
792 /** If the connection at connection_array[i] is marked for close, then:
793 * - If it has data that it wants to flush, try to flush it.
794 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
795 * true, then leave the connection open and return.
796 * - Otherwise, remove the connection from connection_array and from
797 * all other lists, close it, and free it.
798 * Returns 1 if the connection was closed, 0 otherwise.
801 conn_close_if_marked(int i
)
807 conn
= smartlist_get(connection_array
, i
);
808 if (!conn
->marked_for_close
)
809 return 0; /* nothing to see here, move along */
811 assert_connection_ok(conn
, now
);
812 /* assert_all_pending_dns_resolves_ok(); */
814 #ifdef USE_BUFFEREVENTS
816 if (conn
->hold_open_until_flushed
&&
817 evbuffer_get_length(bufferevent_get_output(conn
->bufev
))) {
818 /* don't close yet. */
821 if (conn
->linked_conn
&& ! conn
->linked_conn
->marked_for_close
) {
822 /* We need to do this explicitly so that the linked connection
823 * notices that there was an EOF. */
824 bufferevent_flush(conn
->bufev
, EV_WRITE
, BEV_FINISHED
);
829 log_debug(LD_NET
,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT
").",
832 /* If the connection we are about to close was trying to connect to
833 a proxy server and failed, the client won't be able to use that
834 proxy. We should warn the user about this. */
835 if (conn
->proxy_state
== PROXY_INFANT
)
836 log_failed_proxy_connection(conn
);
838 IF_HAS_BUFFEREVENT(conn
, goto unlink
);
839 if ((SOCKET_OK(conn
->s
) || conn
->linked_conn
) &&
840 connection_wants_to_flush(conn
)) {
841 /* s == -1 means it's an incomplete edge connection, or that the socket
842 * has already been closed as unflushable. */
843 ssize_t sz
= connection_bucket_write_limit(conn
, now
);
844 if (!conn
->hold_open_until_flushed
)
846 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
847 "to flush %d bytes. (Marked at %s:%d)",
848 escaped_safe_str_client(conn
->address
),
849 (int)conn
->s
, conn_type_to_string(conn
->type
), conn
->state
,
850 (int)conn
->outbuf_flushlen
,
851 conn
->marked_for_close_file
, conn
->marked_for_close
);
852 if (conn
->linked_conn
) {
853 retval
= move_buf_to_buf(conn
->linked_conn
->inbuf
, conn
->outbuf
,
854 &conn
->outbuf_flushlen
);
856 /* The linked conn will notice that it has data when it notices that
858 connection_start_reading_from_linked_conn(conn
->linked_conn
);
860 log_debug(LD_GENERAL
, "Flushed last %d bytes from a linked conn; "
861 "%d left; flushlen %d; wants-to-flush==%d", retval
,
862 (int)connection_get_outbuf_len(conn
),
863 (int)conn
->outbuf_flushlen
,
864 connection_wants_to_flush(conn
));
865 } else if (connection_speaks_cells(conn
)) {
866 if (conn
->state
== OR_CONN_STATE_OPEN
) {
867 retval
= flush_buf_tls(TO_OR_CONN(conn
)->tls
, conn
->outbuf
, sz
,
868 &conn
->outbuf_flushlen
);
870 retval
= -1; /* never flush non-open broken tls connections */
872 retval
= flush_buf(conn
->s
, conn
->outbuf
, sz
, &conn
->outbuf_flushlen
);
874 if (retval
>= 0 && /* Technically, we could survive things like
875 TLS_WANT_WRITE here. But don't bother for now. */
876 conn
->hold_open_until_flushed
&& connection_wants_to_flush(conn
)) {
878 LOG_FN_CONN(conn
, (LOG_INFO
,LD_NET
,
879 "Holding conn (fd %d) open for more flushing.",
881 conn
->timestamp_lastwritten
= now
; /* reset so we can flush more */
882 } else if (sz
== 0) {
883 /* Also, retval==0. If we get here, we didn't want to write anything
884 * (because of rate-limiting) and we didn't. */
886 /* Connection must flush before closing, but it's being rate-limited.
887 * Let's remove from Libevent, and mark it as blocked on bandwidth
888 * so it will be re-added on next token bucket refill. Prevents
889 * busy Libevent loops where we keep ending up here and returning
890 * 0 until we are no longer blocked on bandwidth.
892 if (connection_is_writing(conn
)) {
893 conn
->write_blocked_on_bw
= 1;
894 connection_stop_writing(conn
);
896 if (connection_is_reading(conn
)) {
897 /* XXXX024 We should make this code unreachable; if a connection is
898 * marked for close and flushing, there is no point in reading to it
899 * at all. Further, checking at this point is a bit of a hack: it
900 * would make much more sense to react in
901 * connection_handle_read_impl, or to just stop reading in
904 #define MARKED_READING_RATE 180
905 static ratelim_t marked_read_lim
= RATELIM_INIT(MARKED_READING_RATE
);
907 if ((m
= rate_limit_log(&marked_read_lim
, now
))) {
908 log_warn(LD_BUG
, "Marked connection (fd %d, type %s, state %s) "
909 "is still reading; that shouldn't happen.%s",
910 (int)conn
->s
, conn_type_to_string(conn
->type
),
911 conn_state_to_string(conn
->type
, conn
->state
), m
);
915 conn
->read_blocked_on_bw
= 1;
916 connection_stop_reading(conn
);
921 if (connection_wants_to_flush(conn
)) {
922 log_fn(LOG_INFO
, LD_NET
, "We stalled too much while trying to write %d "
923 "bytes to address %s. If this happens a lot, either "
924 "something is wrong with your network connection, or "
925 "something is wrong with theirs. "
926 "(fd %d, type %s, state %d, marked at %s:%d).",
927 (int)connection_get_outbuf_len(conn
),
928 escaped_safe_str_client(conn
->address
),
929 (int)conn
->s
, conn_type_to_string(conn
->type
), conn
->state
,
930 conn
->marked_for_close_file
,
931 conn
->marked_for_close
);
935 #ifdef USE_BUFFEREVENTS
938 connection_unlink(conn
); /* unlink, remove, free */
942 /** We've just tried every dirserver we know about, and none of
943 * them were reachable. Assume the network is down. Change state
944 * so next time an application connection arrives we'll delay it
945 * and try another directory fetch. Kill off all the circuit_wait
946 * streams that are waiting now, since they will all timeout anyway.
949 directory_all_unreachable(time_t now
)
954 stats_n_seconds_working
=0; /* reset it */
956 while ((conn
= connection_get_by_type_state(CONN_TYPE_AP
,
957 AP_CONN_STATE_CIRCUIT_WAIT
))) {
958 entry_connection_t
*entry_conn
= TO_ENTRY_CONN(conn
);
960 "Is your network connection down? "
961 "Failing connection to '%s:%d'.",
962 safe_str_client(entry_conn
->socks_request
->address
),
963 entry_conn
->socks_request
->port
);
964 connection_mark_unattached_ap(entry_conn
,
965 END_STREAM_REASON_NET_UNREACHABLE
);
967 control_event_general_status(LOG_ERR
, "DIR_ALL_UNREACHABLE");
970 /** This function is called whenever we successfully pull down some new
971 * network statuses or server descriptors. */
973 directory_info_has_arrived(time_t now
, int from_cache
)
975 const or_options_t
*options
= get_options();
977 if (!router_have_minimum_dir_info()) {
978 int quiet
= from_cache
||
979 directory_too_idle_to_fetch_descriptors(options
, now
);
980 tor_log(quiet
? LOG_INFO
: LOG_NOTICE
, LD_DIR
,
981 "I learned some more directory information, but not enough to "
982 "build a circuit: %s", get_dir_info_status_string());
983 update_all_descriptor_downloads(now
);
986 if (directory_fetches_from_authorities(options
)) {
987 update_all_descriptor_downloads(now
);
990 /* if we have enough dir info, then update our guard status with
991 * whatever we just learned. */
992 entry_guards_compute_status(options
, now
);
993 /* Don't even bother trying to get extrainfo until the rest of our
994 * directory info is up-to-date */
995 if (options
->DownloadExtraInfo
)
996 update_extrainfo_downloads(now
);
999 if (server_mode(options
) && !net_is_disabled() && !from_cache
&&
1000 (can_complete_circuit
|| !any_predicted_circuits(now
)))
1001 consider_testing_reachability(1, 1);
1004 /** How long do we wait before killing OR connections with no circuits?
1005 * In Tor versions up to 0.2.1.25 and 0.2.2.12-alpha, we waited 15 minutes
1006 * before cancelling these connections, which caused fast relays to accrue
1007 * many many idle connections. Hopefully 3 minutes is low enough that
1008 * it kills most idle connections, without being so low that we cause
1009 * clients to bounce on and off.
1011 #define IDLE_OR_CONN_TIMEOUT 180
1013 /** Perform regular maintenance tasks for a single connection. This
1014 * function gets run once per second per connection by run_scheduled_events.
1017 run_connection_housekeeping(int i
, time_t now
)
1020 connection_t
*conn
= smartlist_get(connection_array
, i
);
1021 const or_options_t
*options
= get_options();
1022 or_connection_t
*or_conn
;
1023 int past_keepalive
=
1024 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
;
1026 if (conn
->outbuf
&& !connection_get_outbuf_len(conn
) &&
1027 conn
->type
== CONN_TYPE_OR
)
1028 TO_OR_CONN(conn
)->timestamp_lastempty
= now
;
1030 if (conn
->marked_for_close
) {
1031 /* nothing to do here */
1035 /* Expire any directory connections that haven't been active (sent
1036 * if a server or received if a client) for 5 min */
1037 if (conn
->type
== CONN_TYPE_DIR
&&
1038 ((DIR_CONN_IS_SERVER(conn
) &&
1039 conn
->timestamp_lastwritten
1040 + options
->TestingDirConnectionMaxStall
< now
) ||
1041 (!DIR_CONN_IS_SERVER(conn
) &&
1042 conn
->timestamp_lastread
1043 + options
->TestingDirConnectionMaxStall
< now
))) {
1044 log_info(LD_DIR
,"Expiring wedged directory conn (fd %d, purpose %d)",
1045 (int)conn
->s
, conn
->purpose
);
1046 /* This check is temporary; it's to let us know whether we should consider
1047 * parsing partial serverdesc responses. */
1048 if (conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
1049 connection_get_inbuf_len(conn
) >= 1024) {
1050 log_info(LD_DIR
,"Trying to extract information from wedged server desc "
1052 connection_dir_reached_eof(TO_DIR_CONN(conn
));
1054 connection_mark_for_close(conn
);
1059 if (!connection_speaks_cells(conn
))
1060 return; /* we're all done here, the rest is just for OR conns */
1062 /* If we haven't written to an OR connection for a while, then either nuke
1063 the connection or send a keepalive, depending. */
1065 or_conn
= TO_OR_CONN(conn
);
1066 #ifdef USE_BUFFEREVENTS
1067 tor_assert(conn
->bufev
);
1069 tor_assert(conn
->outbuf
);
1072 if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn
->chan
)) &&
1073 !connection_or_get_num_circuits(or_conn
)) {
1074 /* It's bad for new circuits, and has no unmarked circuits on it:
1077 "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1078 (int)conn
->s
, conn
->address
, conn
->port
);
1079 if (conn
->state
== OR_CONN_STATE_CONNECTING
)
1080 connection_or_connect_failed(TO_OR_CONN(conn
),
1081 END_OR_CONN_REASON_TIMEOUT
,
1082 "Tor gave up on the connection");
1083 connection_or_close_normally(TO_OR_CONN(conn
), 1);
1084 } else if (!connection_state_is_open(conn
)) {
1085 if (past_keepalive
) {
1086 /* We never managed to actually get this connection open and happy. */
1087 log_info(LD_OR
,"Expiring non-open OR connection to fd %d (%s:%d).",
1088 (int)conn
->s
,conn
->address
, conn
->port
);
1089 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1091 } else if (we_are_hibernating() &&
1092 !connection_or_get_num_circuits(or_conn
) &&
1093 !connection_get_outbuf_len(conn
)) {
1094 /* We're hibernating, there's no circuits, and nothing to flush.*/
1095 log_info(LD_OR
,"Expiring non-used OR connection to fd %d (%s:%d) "
1096 "[Hibernating or exiting].",
1097 (int)conn
->s
,conn
->address
, conn
->port
);
1098 connection_or_close_normally(TO_OR_CONN(conn
), 1);
1099 } else if (!connection_or_get_num_circuits(or_conn
) &&
1100 now
>= or_conn
->timestamp_last_added_nonpadding
+
1101 IDLE_OR_CONN_TIMEOUT
) {
1102 log_info(LD_OR
,"Expiring non-used OR connection to fd %d (%s:%d) "
1103 "[idle %d].", (int)conn
->s
,conn
->address
, conn
->port
,
1104 (int)(now
- or_conn
->timestamp_last_added_nonpadding
));
1105 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1107 now
>= or_conn
->timestamp_lastempty
+ options
->KeepalivePeriod
*10 &&
1108 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
*10) {
1109 log_fn(LOG_PROTOCOL_WARN
,LD_PROTOCOL
,
1110 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1111 "flush; %d seconds since last write)",
1112 (int)conn
->s
, conn
->address
, conn
->port
,
1113 (int)connection_get_outbuf_len(conn
),
1114 (int)(now
-conn
->timestamp_lastwritten
));
1115 connection_or_close_normally(TO_OR_CONN(conn
), 0);
1116 } else if (past_keepalive
&& !connection_get_outbuf_len(conn
)) {
1117 /* send a padding cell */
1118 log_fn(LOG_DEBUG
,LD_OR
,"Sending keepalive to (%s:%d)",
1119 conn
->address
, conn
->port
);
1120 memset(&cell
,0,sizeof(cell_t
));
1121 cell
.command
= CELL_PADDING
;
1122 connection_or_write_cell_to_buf(&cell
, or_conn
);
1126 /** Honor a NEWNYM request: make future requests unlinkable to past
1129 signewnym_impl(time_t now
)
1131 const or_options_t
*options
= get_options();
1132 if (!proxy_mode(options
)) {
1133 log_info(LD_CONTROL
, "Ignoring SIGNAL NEWNYM because client functionality "
1138 circuit_mark_all_dirty_circs_as_unusable();
1139 addressmap_clear_transient();
1140 rend_client_purge_state();
1141 time_of_last_signewnym
= now
;
1142 signewnym_is_pending
= 0;
1146 control_event_signal(SIGNEWNYM
);
1149 /** Return the number of times that signewnym has been called. */
1151 get_signewnym_epoch(void)
1153 return newnym_epoch
;
1156 static time_t time_to_check_descriptor
= 0;
1158 * Update our schedule so that we'll check whether we need to update our
1159 * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
1163 reschedule_descriptor_update_check(void)
1165 time_to_check_descriptor
= 0;
1168 /** Perform regular maintenance tasks. This function gets run once per
1169 * second by second_elapsed_callback().
1172 run_scheduled_events(time_t now
)
1174 static time_t last_rotated_x509_certificate
= 0;
1175 static time_t time_to_check_v3_certificate
= 0;
1176 static time_t time_to_check_listeners
= 0;
1177 static time_t time_to_download_networkstatus
= 0;
1178 static time_t time_to_shrink_memory
= 0;
1179 static time_t time_to_try_getting_descriptors
= 0;
1180 static time_t time_to_reset_descriptor_failures
= 0;
1181 static time_t time_to_add_entropy
= 0;
1182 static time_t time_to_write_bridge_status_file
= 0;
1183 static time_t time_to_downrate_stability
= 0;
1184 static time_t time_to_save_stability
= 0;
1185 static time_t time_to_clean_caches
= 0;
1186 static time_t time_to_recheck_bandwidth
= 0;
1187 static time_t time_to_check_for_expired_networkstatus
= 0;
1188 static time_t time_to_write_stats_files
= 0;
1189 static time_t time_to_write_bridge_stats
= 0;
1190 static time_t time_to_check_port_forwarding
= 0;
1191 static time_t time_to_launch_reachability_tests
= 0;
1192 static int should_init_bridge_stats
= 1;
1193 static time_t time_to_retry_dns_init
= 0;
1194 static time_t time_to_next_heartbeat
= 0;
1195 const or_options_t
*options
= get_options();
1197 int is_server
= server_mode(options
);
1201 /* 0. See if we've been asked to shut down and our timeout has
1202 * expired; or if our bandwidth limits are exhausted and we
1203 * should hibernate; or if it's time to wake up from hibernation.
1205 consider_hibernation(now
);
1207 /* 0b. If we've deferred a signewnym, make sure it gets handled
1209 if (signewnym_is_pending
&&
1210 time_of_last_signewnym
+ MAX_SIGNEWNYM_RATE
<= now
) {
1211 log_info(LD_CONTROL
, "Honoring delayed NEWNYM request");
1212 signewnym_impl(now
);
1215 /* 0c. If we've deferred log messages for the controller, handle them now */
1216 flush_pending_log_callbacks();
1218 /* 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
1219 * shut down and restart all cpuworkers, and update the directory if
1223 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME
< now
) {
1224 log_info(LD_GENERAL
,"Rotating onion key.");
1226 cpuworkers_rotate();
1227 if (router_rebuild_descriptor(1)<0) {
1228 log_info(LD_CONFIG
, "Couldn't rebuild router descriptor");
1230 if (advertised_server_mode() && !options
->DisableNetwork
)
1231 router_upload_dir_desc_to_dirservers(0);
1234 if (!options
->DisableNetwork
&& time_to_try_getting_descriptors
< now
) {
1235 update_all_descriptor_downloads(now
);
1236 update_extrainfo_downloads(now
);
1237 if (router_have_minimum_dir_info())
1238 time_to_try_getting_descriptors
= now
+ LAZY_DESCRIPTOR_RETRY_INTERVAL
;
1240 time_to_try_getting_descriptors
= now
+ GREEDY_DESCRIPTOR_RETRY_INTERVAL
;
1243 if (time_to_reset_descriptor_failures
< now
) {
1244 router_reset_descriptor_download_failures();
1245 time_to_reset_descriptor_failures
=
1246 now
+ DESCRIPTOR_FAILURE_RESET_INTERVAL
;
1249 if (options
->UseBridges
)
1250 fetch_bridge_descriptors(options
, now
);
1252 /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1254 if (!last_rotated_x509_certificate
)
1255 last_rotated_x509_certificate
= now
;
1256 if (last_rotated_x509_certificate
+MAX_SSL_KEY_LIFETIME_INTERNAL
< now
) {
1257 log_info(LD_GENERAL
,"Rotating tls context.");
1258 if (router_initialize_tls_context() < 0) {
1259 log_warn(LD_BUG
, "Error reinitializing TLS context");
1260 /* XXX is it a bug here, that we just keep going? -RD */
1262 last_rotated_x509_certificate
= now
;
1263 /* We also make sure to rotate the TLS connections themselves if they've
1264 * been up for too long -- but that's done via is_bad_for_new_circs in
1265 * connection_run_housekeeping() above. */
1268 if (time_to_add_entropy
< now
) {
1269 if (time_to_add_entropy
) {
1270 /* We already seeded once, so don't die on failure. */
1273 /** How often do we add more entropy to OpenSSL's RNG pool? */
1274 #define ENTROPY_INTERVAL (60*60)
1275 time_to_add_entropy
= now
+ ENTROPY_INTERVAL
;
1278 /* 1c. If we have to change the accounting interval or record
1279 * bandwidth used in this accounting interval, do so. */
1280 if (accounting_is_enabled(options
))
1281 accounting_run_housekeeping(now
);
1283 if (time_to_launch_reachability_tests
< now
&&
1284 (authdir_mode_tests_reachability(options
)) &&
1285 !net_is_disabled()) {
1286 time_to_launch_reachability_tests
= now
+ REACHABILITY_TEST_INTERVAL
;
1287 /* try to determine reachability of the other Tor relays */
1288 dirserv_test_reachability(now
);
1291 /* 1d. Periodically, we discount older stability information so that new
1292 * stability info counts more, and save the stability information to disk as
1294 if (time_to_downrate_stability
< now
)
1295 time_to_downrate_stability
= rep_hist_downrate_old_runs(now
);
1296 if (authdir_mode_tests_reachability(options
)) {
1297 if (time_to_save_stability
< now
) {
1298 if (time_to_save_stability
&& rep_hist_record_mtbf_data(now
, 1)<0) {
1299 log_warn(LD_GENERAL
, "Couldn't store mtbf data.");
1301 #define SAVE_STABILITY_INTERVAL (30*60)
1302 time_to_save_stability
= now
+ SAVE_STABILITY_INTERVAL
;
1306 /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
1307 * close to expiring and warn the admin if it is. */
1308 if (time_to_check_v3_certificate
< now
) {
1309 v3_authority_check_key_expiry();
1310 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
1311 time_to_check_v3_certificate
= now
+ CHECK_V3_CERTIFICATE_INTERVAL
;
1314 /* 1f. Check whether our networkstatus has expired.
1316 if (time_to_check_for_expired_networkstatus
< now
) {
1317 networkstatus_t
*ns
= networkstatus_get_latest_consensus();
1318 /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
1319 * networkstatus_get_reasonably_live_consensus(), but that value is way
1320 * way too high. Arma: is the bridge issue there resolved yet? -NM */
1321 #define NS_EXPIRY_SLOP (24*60*60)
1322 if (ns
&& ns
->valid_until
< now
+NS_EXPIRY_SLOP
&&
1323 router_have_minimum_dir_info()) {
1324 router_dir_info_changed();
1326 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1327 time_to_check_for_expired_networkstatus
= now
+ CHECK_EXPIRED_NS_INTERVAL
;
1330 /* 1g. Check whether we should write statistics to disk.
1332 if (time_to_write_stats_files
< now
) {
1333 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1334 time_t next_time_to_write_stats_files
= (time_to_write_stats_files
> 0 ?
1335 time_to_write_stats_files
: now
) + CHECK_WRITE_STATS_INTERVAL
;
1336 if (options
->CellStatistics
) {
1338 rep_hist_buffer_stats_write(time_to_write_stats_files
);
1339 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1340 next_time_to_write_stats_files
= next_write
;
1342 if (options
->DirReqStatistics
) {
1343 time_t next_write
= geoip_dirreq_stats_write(time_to_write_stats_files
);
1344 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1345 next_time_to_write_stats_files
= next_write
;
1347 if (options
->EntryStatistics
) {
1348 time_t next_write
= geoip_entry_stats_write(time_to_write_stats_files
);
1349 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1350 next_time_to_write_stats_files
= next_write
;
1352 if (options
->ExitPortStatistics
) {
1353 time_t next_write
= rep_hist_exit_stats_write(time_to_write_stats_files
);
1354 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1355 next_time_to_write_stats_files
= next_write
;
1357 if (options
->ConnDirectionStatistics
) {
1358 time_t next_write
= rep_hist_conn_stats_write(time_to_write_stats_files
);
1359 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1360 next_time_to_write_stats_files
= next_write
;
1362 if (options
->BridgeAuthoritativeDir
) {
1363 time_t next_write
= rep_hist_desc_stats_write(time_to_write_stats_files
);
1364 if (next_write
&& next_write
< next_time_to_write_stats_files
)
1365 next_time_to_write_stats_files
= next_write
;
1367 time_to_write_stats_files
= next_time_to_write_stats_files
;
1370 /* 1h. Check whether we should write bridge statistics to disk.
1372 if (should_record_bridge_info(options
)) {
1373 if (time_to_write_bridge_stats
< now
) {
1374 if (should_init_bridge_stats
) {
1375 /* (Re-)initialize bridge statistics. */
1376 geoip_bridge_stats_init(now
);
1377 time_to_write_bridge_stats
= now
+ WRITE_STATS_INTERVAL
;
1378 should_init_bridge_stats
= 0;
1380 /* Possibly write bridge statistics to disk and ask when to write
1381 * them next time. */
1382 time_to_write_bridge_stats
= geoip_bridge_stats_write(
1383 time_to_write_bridge_stats
);
1386 } else if (!should_init_bridge_stats
) {
1387 /* Bridge mode was turned off. Ensure that stats are re-initialized
1388 * next time bridge mode is turned on. */
1389 should_init_bridge_stats
= 1;
1392 /* Remove old information from rephist and the rend cache. */
1393 if (time_to_clean_caches
< now
) {
1394 rep_history_clean(now
- options
->RephistTrackTime
);
1395 rend_cache_clean(now
);
1396 rend_cache_clean_v2_descs_as_dir(now
);
1397 microdesc_cache_rebuild(NULL
, 0);
1398 #define CLEAN_CACHES_INTERVAL (30*60)
1399 time_to_clean_caches
= now
+ CLEAN_CACHES_INTERVAL
;
1402 #define RETRY_DNS_INTERVAL (10*60)
1403 /* If we're a server and initializing dns failed, retry periodically. */
1404 if (time_to_retry_dns_init
< now
) {
1405 time_to_retry_dns_init
= now
+ RETRY_DNS_INTERVAL
;
1406 if (is_server
&& has_dns_init_failed())
1410 /* 2. Periodically, we consider force-uploading our descriptor
1411 * (if we've passed our internal checks). */
1413 /** How often do we check whether part of our router info has changed in a
1414 * way that would require an upload? That includes checking whether our IP
1415 * address has changed. */
1416 #define CHECK_DESCRIPTOR_INTERVAL (60)
1418 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1419 * one is inaccurate. */
1420 if (time_to_check_descriptor
< now
&& !options
->DisableNetwork
) {
1421 static int dirport_reachability_count
= 0;
1422 time_to_check_descriptor
= now
+ CHECK_DESCRIPTOR_INTERVAL
;
1423 check_descriptor_bandwidth_changed(now
);
1424 check_descriptor_ipaddress_changed(now
);
1425 mark_my_descriptor_dirty_if_too_old(now
);
1426 consider_publishable_server(0);
1427 /* also, check religiously for reachability, if it's within the first
1428 * 20 minutes of our uptime. */
1430 (can_complete_circuit
|| !any_predicted_circuits(now
)) &&
1431 !we_are_hibernating()) {
1432 if (stats_n_seconds_working
< TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
) {
1433 consider_testing_reachability(1, dirport_reachability_count
==0);
1434 if (++dirport_reachability_count
> 5)
1435 dirport_reachability_count
= 0;
1436 } else if (time_to_recheck_bandwidth
< now
) {
1437 /* If we haven't checked for 12 hours and our bandwidth estimate is
1438 * low, do another bandwidth test. This is especially important for
1439 * bridges, since they might go long periods without much use. */
1440 const routerinfo_t
*me
= router_get_my_routerinfo();
1441 if (time_to_recheck_bandwidth
&& me
&&
1442 me
->bandwidthcapacity
< me
->bandwidthrate
&&
1443 me
->bandwidthcapacity
< 51200) {
1444 reset_bandwidth_test();
1446 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1447 time_to_recheck_bandwidth
= now
+ BANDWIDTH_RECHECK_INTERVAL
;
1451 /* If any networkstatus documents are no longer recent, we need to
1452 * update all the descriptors' running status. */
1453 /* Remove dead routers. */
1454 routerlist_remove_old_routers();
1457 /* 2c. Every minute (or every second if TestingTorNetwork), check
1458 * whether we want to download any networkstatus documents. */
1460 /* How often do we check whether we should download network status
1462 #define networkstatus_dl_check_interval(o) ((o)->TestingTorNetwork ? 1 : 60)
1464 if (time_to_download_networkstatus
< now
&& !options
->DisableNetwork
) {
1465 time_to_download_networkstatus
=
1466 now
+ networkstatus_dl_check_interval(options
);
1467 update_networkstatus_downloads(now
);
1470 /* 2c. Let directory voting happen. */
1471 if (authdir_mode_v3(options
))
1472 dirvote_act(options
, now
);
1474 /* 3a. Every second, we examine pending circuits and prune the
1475 * ones which have been pending for more than a few seconds.
1476 * We do this before step 4, so it can try building more if
1477 * it's not comfortable with the number of available circuits.
1479 /* (If our circuit build timeout can ever become lower than a second (which
1480 * it can't, currently), we should do this more often.) */
1481 circuit_expire_building();
1483 /* 3b. Also look at pending streams and prune the ones that 'began'
1484 * a long time ago but haven't gotten a 'connected' yet.
1485 * Do this before step 4, so we can put them back into pending
1486 * state to be picked up by the new circuit.
1488 connection_ap_expire_beginning();
1490 /* 3c. And expire connections that we've held open for too long.
1492 connection_expire_held_open();
1494 /* 3d. And every 60 seconds, we relaunch listeners if any died. */
1495 if (!net_is_disabled() && time_to_check_listeners
< now
) {
1496 retry_all_listeners(NULL
, NULL
, 0);
1497 time_to_check_listeners
= now
+60;
1500 /* 4. Every second, we try a new circuit if there are no valid
1501 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1502 * that became dirty more than MaxCircuitDirtiness seconds ago,
1503 * and we make a new circ if there are no clean circuits.
1505 have_dir_info
= router_have_minimum_dir_info();
1506 if (have_dir_info
&& !net_is_disabled())
1507 circuit_build_needed_circs(now
);
1509 /* every 10 seconds, but not at the same second as other such events */
1511 circuit_expire_old_circuits_serverside(now
);
1513 /* 5. We do housekeeping for each connection... */
1514 connection_or_set_bad_connections(NULL
, 0);
1515 for (i
=0;i
<smartlist_len(connection_array
);i
++) {
1516 run_connection_housekeeping(i
, now
);
1518 if (time_to_shrink_memory
< now
) {
1519 SMARTLIST_FOREACH(connection_array
, connection_t
*, conn
, {
1521 buf_shrink(conn
->outbuf
);
1523 buf_shrink(conn
->inbuf
);
1526 buf_shrink_freelists(0);
1527 /** How often do we check buffers and pools for empty space that can be
1529 #define MEM_SHRINK_INTERVAL (60)
1530 time_to_shrink_memory
= now
+ MEM_SHRINK_INTERVAL
;
1533 /* 6. And remove any marked circuits... */
1534 circuit_close_all_marked();
1536 /* 7. And upload service descriptors if necessary. */
1537 if (can_complete_circuit
&& !net_is_disabled()) {
1538 rend_consider_services_upload(now
);
1539 rend_consider_descriptor_republication();
1542 /* 8. and blow away any connections that need to die. have to do this now,
1543 * because if we marked a conn for close and left its socket -1, then
1544 * we'll pass it to poll/select and bad things will happen.
1546 close_closeable_connections();
1548 /* 8b. And if anything in our state is ready to get flushed to disk, we
1552 /* 8c. Do channel cleanup just like for connections */
1553 channel_run_cleanup();
1554 channel_listener_run_cleanup();
1556 /* 9. and if we're an exit node, check whether our DNS is telling stories
1558 if (!net_is_disabled() &&
1559 public_server_mode(options
) &&
1560 time_to_check_for_correct_dns
< now
&&
1561 ! router_my_exit_policy_is_reject_star()) {
1562 if (!time_to_check_for_correct_dns
) {
1563 time_to_check_for_correct_dns
= now
+ 60 + crypto_rand_int(120);
1565 dns_launch_correctness_checks();
1566 time_to_check_for_correct_dns
= now
+ 12*3600 +
1567 crypto_rand_int(12*3600);
1571 /* 10. write bridge networkstatus file to disk */
1572 if (options
->BridgeAuthoritativeDir
&&
1573 time_to_write_bridge_status_file
< now
) {
1574 networkstatus_dump_bridge_status_to_file(now
);
1575 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
1576 time_to_write_bridge_status_file
= now
+BRIDGE_STATUSFILE_INTERVAL
;
1579 /* 11. check the port forwarding app */
1580 if (!net_is_disabled() &&
1581 time_to_check_port_forwarding
< now
&&
1582 options
->PortForwarding
&&
1584 #define PORT_FORWARDING_CHECK_INTERVAL 5
1585 smartlist_t
*ports_to_forward
= get_list_of_ports_to_forward();
1586 if (ports_to_forward
) {
1587 tor_check_port_forwarding(options
->PortForwardingHelper
,
1591 SMARTLIST_FOREACH(ports_to_forward
, char *, cp
, tor_free(cp
));
1592 smartlist_free(ports_to_forward
);
1594 time_to_check_port_forwarding
= now
+PORT_FORWARDING_CHECK_INTERVAL
;
1597 /* 11b. check pending unconfigured managed proxies */
1598 if (!net_is_disabled() && pt_proxies_configuration_pending())
1599 pt_configure_remaining_proxies();
1601 /* 12. write the heartbeat message */
1602 if (options
->HeartbeatPeriod
&&
1603 time_to_next_heartbeat
<= now
) {
1604 if (time_to_next_heartbeat
) /* don't log the first heartbeat */
1606 time_to_next_heartbeat
= now
+options
->HeartbeatPeriod
;
1610 /** Timer: used to invoke second_elapsed_callback() once per second. */
1611 static periodic_timer_t
*second_timer
= NULL
;
1612 /** Number of libevent errors in the last second: we die if we get too many. */
1613 static int n_libevent_errors
= 0;
1615 /** Libevent callback: invoked once every second. */
1617 second_elapsed_callback(periodic_timer_t
*timer
, void *arg
)
1619 /* XXXX This could be sensibly refactored into multiple callbacks, and we
1620 * could use Libevent's timers for this rather than checking the current
1621 * time against a bunch of timeouts every second. */
1622 static time_t current_second
= 0;
1624 size_t bytes_written
;
1626 int seconds_elapsed
;
1627 const or_options_t
*options
= get_options();
1631 n_libevent_errors
= 0;
1633 /* log_notice(LD_GENERAL, "Tick."); */
1635 update_approx_time(now
);
1637 /* the second has rolled over. check more stuff. */
1638 seconds_elapsed
= current_second
? (int)(now
- current_second
) : 0;
1639 #ifdef USE_BUFFEREVENTS
1641 uint64_t cur_read
,cur_written
;
1642 connection_get_rate_limit_totals(&cur_read
, &cur_written
);
1643 bytes_written
= (size_t)(cur_written
- stats_prev_n_written
);
1644 bytes_read
= (size_t)(cur_read
- stats_prev_n_read
);
1645 stats_n_bytes_read
+= bytes_read
;
1646 stats_n_bytes_written
+= bytes_written
;
1647 if (accounting_is_enabled(options
) && seconds_elapsed
>= 0)
1648 accounting_add_bytes(bytes_read
, bytes_written
, seconds_elapsed
);
1649 stats_prev_n_written
= cur_written
;
1650 stats_prev_n_read
= cur_read
;
1653 bytes_read
= (size_t)(stats_n_bytes_read
- stats_prev_n_read
);
1654 bytes_written
= (size_t)(stats_n_bytes_written
- stats_prev_n_written
);
1655 stats_prev_n_read
= stats_n_bytes_read
;
1656 stats_prev_n_written
= stats_n_bytes_written
;
1659 control_event_bandwidth_used((uint32_t)bytes_read
,(uint32_t)bytes_written
);
1660 control_event_stream_bandwidth_used();
1661 control_event_conn_bandwidth_used();
1662 control_event_circ_bandwidth_used();
1663 control_event_circuit_cell_stats();
1665 if (server_mode(options
) &&
1666 !net_is_disabled() &&
1667 seconds_elapsed
> 0 &&
1668 can_complete_circuit
&&
1669 stats_n_seconds_working
/ TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
!=
1670 (stats_n_seconds_working
+seconds_elapsed
) /
1671 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
) {
1672 /* every 20 minutes, check and complain if necessary */
1673 const routerinfo_t
*me
= router_get_my_routerinfo();
1674 if (me
&& !check_whether_orport_reachable()) {
1675 char *address
= tor_dup_ip(me
->addr
);
1676 log_warn(LD_CONFIG
,"Your server (%s:%d) has not managed to confirm that "
1677 "its ORPort is reachable. Please check your firewalls, ports, "
1678 "address, /etc/hosts file, etc.",
1679 address
, me
->or_port
);
1680 control_event_server_status(LOG_WARN
,
1681 "REACHABILITY_FAILED ORADDRESS=%s:%d",
1682 address
, me
->or_port
);
1686 if (me
&& !check_whether_dirport_reachable()) {
1687 char *address
= tor_dup_ip(me
->addr
);
1689 "Your server (%s:%d) has not managed to confirm that its "
1690 "DirPort is reachable. Please check your firewalls, ports, "
1691 "address, /etc/hosts file, etc.",
1692 address
, me
->dir_port
);
1693 control_event_server_status(LOG_WARN
,
1694 "REACHABILITY_FAILED DIRADDRESS=%s:%d",
1695 address
, me
->dir_port
);
1700 /** If more than this many seconds have elapsed, probably the clock
1701 * jumped: doesn't count. */
1702 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
1703 if (seconds_elapsed
< -NUM_JUMPED_SECONDS_BEFORE_WARN
||
1704 seconds_elapsed
>= NUM_JUMPED_SECONDS_BEFORE_WARN
) {
1705 circuit_note_clock_jumped(seconds_elapsed
);
1706 /* XXX if the time jumps *back* many months, do our events in
1707 * run_scheduled_events() recover? I don't think they do. -RD */
1708 } else if (seconds_elapsed
> 0)
1709 stats_n_seconds_working
+= seconds_elapsed
;
1711 run_scheduled_events(now
);
1713 current_second
= now
; /* remember which second it is, for next time */
1716 #ifndef USE_BUFFEREVENTS
1717 /** Timer: used to invoke refill_callback(). */
1718 static periodic_timer_t
*refill_timer
= NULL
;
1720 /** Libevent callback: invoked periodically to refill token buckets
1721 * and count r/w bytes. It is only used when bufferevents are disabled. */
1723 refill_callback(periodic_timer_t
*timer
, void *arg
)
1725 static struct timeval current_millisecond
;
1728 size_t bytes_written
;
1730 int milliseconds_elapsed
= 0;
1731 int seconds_rolled_over
= 0;
1733 const or_options_t
*options
= get_options();
1738 tor_gettimeofday(&now
);
1740 /* If this is our first time, no time has passed. */
1741 if (current_millisecond
.tv_sec
) {
1742 long mdiff
= tv_mdiff(¤t_millisecond
, &now
);
1743 if (mdiff
> INT_MAX
)
1745 milliseconds_elapsed
= (int)mdiff
;
1746 seconds_rolled_over
= (int)(now
.tv_sec
- current_millisecond
.tv_sec
);
1749 bytes_written
= stats_prev_global_write_bucket
- global_write_bucket
;
1750 bytes_read
= stats_prev_global_read_bucket
- global_read_bucket
;
1752 stats_n_bytes_read
+= bytes_read
;
1753 stats_n_bytes_written
+= bytes_written
;
1754 if (accounting_is_enabled(options
) && milliseconds_elapsed
>= 0)
1755 accounting_add_bytes(bytes_read
, bytes_written
, seconds_rolled_over
);
1757 if (milliseconds_elapsed
> 0)
1758 connection_bucket_refill(milliseconds_elapsed
, (time_t)now
.tv_sec
);
1760 stats_prev_global_read_bucket
= global_read_bucket
;
1761 stats_prev_global_write_bucket
= global_write_bucket
;
1763 current_millisecond
= now
; /* remember what time it is, for next time */
1768 /** Called when a possibly ignorable libevent error occurs; ensures that we
1769 * don't get into an infinite loop by ignoring too many errors from
1772 got_libevent_error(void)
1774 if (++n_libevent_errors
> 8) {
1775 log_err(LD_NET
, "Too many libevent errors in one second; dying");
1782 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
1784 /** Called when our IP address seems to have changed. <b>at_interface</b>
1785 * should be true if we detected a change in our interface, and false if we
1786 * detected a change in our published address. */
1788 ip_address_changed(int at_interface
)
1790 int server
= server_mode(get_options());
1794 /* Okay, change our keys. */
1796 log_warn(LD_GENERAL
, "Unable to rotate keys after IP change!");
1800 if (stats_n_seconds_working
> UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST
)
1801 reset_bandwidth_test();
1802 stats_n_seconds_working
= 0;
1803 router_reset_reachability();
1804 mark_my_descriptor_dirty("IP address changed");
1808 dns_servers_relaunch_checks();
1811 /** Forget what we've learned about the correctness of our DNS servers, and
1812 * start learning again. */
1814 dns_servers_relaunch_checks(void)
1816 if (server_mode(get_options())) {
1817 dns_reset_correctness_checks();
1818 time_to_check_for_correct_dns
= 0;
1822 /** Called when we get a SIGHUP: reload configuration files and keys,
1823 * retry all connections, and so on. */
1827 const or_options_t
*options
= get_options();
1830 dmalloc_log_stats();
1831 dmalloc_log_changed(0, 1, 0, 0);
1834 log_notice(LD_GENERAL
,"Received reload signal (hup). Reloading config and "
1835 "resetting internal state.");
1836 if (accounting_is_enabled(options
))
1837 accounting_record_bandwidth_usage(time(NULL
), get_or_state());
1839 router_reset_warnings();
1840 routerlist_reset_warnings();
1841 /* first, reload config variables, in case they've changed */
1842 if (options
->ReloadTorrcOnSIGHUP
) {
1843 /* no need to provide argc/v, they've been cached in init_from_config */
1844 if (options_init_from_torrc(0, NULL
) < 0) {
1845 log_err(LD_CONFIG
,"Reading config failed--see warnings above. "
1846 "For usage, try -h.");
1849 options
= get_options(); /* they have changed now */
1852 log_notice(LD_GENERAL
, "Not reloading config file: the controller told "
1854 /* Make stuff get rescanned, reloaded, etc. */
1855 if (set_options((or_options_t
*)options
, &msg
) < 0) {
1857 msg
= tor_strdup("Unknown error");
1858 log_warn(LD_GENERAL
, "Unable to re-set previous options: %s", msg
);
1862 if (authdir_mode_handles_descs(options
, -1)) {
1863 /* reload the approved-routers file */
1864 if (dirserv_load_fingerprint_file() < 0) {
1865 /* warnings are logged from dirserv_load_fingerprint_file() directly */
1866 log_info(LD_GENERAL
, "Error reloading fingerprints. "
1867 "Continuing with old list.");
1871 /* Rotate away from the old dirty circuits. This has to be done
1872 * after we've read the new options, but before we start using
1873 * circuits for directory fetches. */
1874 circuit_mark_all_dirty_circs_as_unusable();
1876 /* retry appropriate downloads */
1877 router_reset_status_download_failures();
1878 router_reset_descriptor_download_failures();
1879 if (!options
->DisableNetwork
)
1880 update_networkstatus_downloads(time(NULL
));
1882 /* We'll retry routerstatus downloads in about 10 seconds; no need to
1883 * force a retry there. */
1885 if (server_mode(options
)) {
1886 /* Restart cpuworker and dnsworker processes, so they get up-to-date
1887 * configuration options. */
1888 cpuworkers_rotate();
1894 /** Tor main loop. */
1901 /* initialize dns resolve map, spawn workers if needed */
1902 if (dns_init() < 0) {
1903 if (get_options()->ServerDNSAllowBrokenConfig
)
1904 log_warn(LD_GENERAL
, "Couldn't set up any working nameservers. "
1905 "Network not up yet? Will try again soon.");
1907 log_err(LD_GENERAL
,"Error initializing dns subsystem; exiting. To "
1908 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
1912 #ifdef USE_BUFFEREVENTS
1913 log_warn(LD_GENERAL
, "Tor was compiled with the --enable-bufferevents "
1914 "option. This is still experimental, and might cause strange "
1915 "bugs. If you want a more stable Tor, be sure to build without "
1916 "--enable-bufferevents.");
1921 /* load the private keys, if we're supposed to have them, and set up the
1923 if (! client_identity_key_is_set()) {
1924 if (init_keys() < 0) {
1925 log_err(LD_BUG
,"Error initializing keys; exiting");
1930 /* Set up the packed_cell_t memory pool. */
1933 /* Set up our buckets */
1934 connection_bucket_init();
1935 #ifndef USE_BUFFEREVENTS
1936 stats_prev_global_read_bucket
= global_read_bucket
;
1937 stats_prev_global_write_bucket
= global_write_bucket
;
1940 /* initialize the bootstrap status events to know we're starting up */
1941 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING
, 0);
1943 if (trusted_dirs_reload_certs()) {
1945 "Couldn't load all cached v3 certificates. Starting anyway.");
1947 if (router_reload_consensus_networkstatus()) {
1950 /* load the routers file, or assign the defaults. */
1951 if (router_reload_router_list()) {
1954 /* load the networkstatuses. (This launches a download for new routers as
1958 directory_info_has_arrived(now
, 1);
1960 if (server_mode(get_options())) {
1961 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1965 /* set up once-a-second callback. */
1966 if (! second_timer
) {
1967 struct timeval one_second
;
1968 one_second
.tv_sec
= 1;
1969 one_second
.tv_usec
= 0;
1971 second_timer
= periodic_timer_new(tor_libevent_get_base(),
1973 second_elapsed_callback
,
1975 tor_assert(second_timer
);
1978 #ifndef USE_BUFFEREVENTS
1979 if (!refill_timer
) {
1980 struct timeval refill_interval
;
1981 int msecs
= get_options()->TokenBucketRefillInterval
;
1983 refill_interval
.tv_sec
= msecs
/1000;
1984 refill_interval
.tv_usec
= (msecs
%1000)*1000;
1986 refill_timer
= periodic_timer_new(tor_libevent_get_base(),
1990 tor_assert(refill_timer
);
1995 if (nt_service_is_stopping())
1999 /* Make it easier to tell whether libevent failure is our fault or not. */
2002 /* All active linked conns should get their read events activated. */
2003 SMARTLIST_FOREACH(active_linked_connection_lst
, connection_t
*, conn
,
2004 event_active(conn
->read_event
, EV_READ
, 1));
2005 called_loop_once
= smartlist_len(active_linked_connection_lst
) ? 1 : 0;
2007 update_approx_time(time(NULL
));
2009 /* poll until we have an event, or the second ends, or until we have
2010 * some active linked connections to trigger events for. */
2011 loop_result
= event_base_loop(tor_libevent_get_base(),
2012 called_loop_once
? EVLOOP_ONCE
: 0);
2014 /* let catch() handle things like ^c, and otherwise don't worry about it */
2015 if (loop_result
< 0) {
2016 int e
= tor_socket_errno(-1);
2017 /* let the program survive things like ^z */
2018 if (e
!= EINTR
&& !ERRNO_IS_EINPROGRESS(e
)) {
2019 log_err(LD_NET
,"libevent call with %s failed: %s [%d]",
2020 tor_libevent_get_method(), tor_socket_strerror(e
), e
);
2023 } else if (e
== EINVAL
) {
2024 log_warn(LD_NET
, "EINVAL from libevent: should you upgrade libevent?");
2025 if (got_libevent_error())
2029 if (ERRNO_IS_EINPROGRESS(e
))
2031 "libevent call returned EINPROGRESS? Please report.");
2032 log_debug(LD_NET
,"libevent call interrupted.");
2033 /* You can't trust the results of this poll(). Go back to the
2034 * top of the big for loop. */
2041 #ifndef _WIN32 /* Only called when we're willing to use signals */
2042 /** Libevent callback: invoked when we get a signal.
2045 signal_callback(int fd
, short events
, void *arg
)
2047 uintptr_t sig
= (uintptr_t)arg
;
2051 process_signal(sig
);
2055 /** Do the work of acting on a signal received in <b>sig</b> */
2057 process_signal(uintptr_t sig
)
2062 log_notice(LD_GENERAL
,"Catching signal TERM, exiting cleanly.");
2067 if (!server_mode(get_options())) { /* do it now */
2068 log_notice(LD_GENERAL
,"Interrupt: exiting cleanly.");
2072 hibernate_begin_shutdown();
2076 log_debug(LD_GENERAL
,"Caught SIGPIPE. Ignoring.");
2080 /* prefer to log it at INFO, but make sure we always see it */
2081 dumpstats(get_min_log_level()<LOG_INFO
? get_min_log_level() : LOG_INFO
);
2082 control_event_signal(sig
);
2085 switch_logs_debug();
2086 log_debug(LD_GENERAL
,"Caught USR2, going to loglevel debug. "
2087 "Send HUP to change back.");
2088 control_event_signal(sig
);
2092 log_warn(LD_CONFIG
,"Restart failed (config error?). Exiting.");
2096 control_event_signal(sig
);
2100 while (waitpid(-1,NULL
,WNOHANG
) > 0) ; /* keep reaping until no more
2105 time_t now
= time(NULL
);
2106 if (time_of_last_signewnym
+ MAX_SIGNEWNYM_RATE
> now
) {
2107 signewnym_is_pending
= 1;
2108 log_notice(LD_CONTROL
,
2109 "Rate limiting NEWNYM request: delaying by %d second(s)",
2110 (int)(MAX_SIGNEWNYM_RATE
+time_of_last_signewnym
-now
));
2112 signewnym_impl(now
);
2116 case SIGCLEARDNSCACHE
:
2117 addressmap_clear_transient();
2118 control_event_signal(sig
);
2123 /** Returns Tor's uptime. */
2127 return stats_n_seconds_working
;
2130 extern uint64_t rephist_total_alloc
;
2131 extern uint32_t rephist_total_num
;
2134 * Write current memory usage information to the log.
2137 dumpmemusage(int severity
)
2139 connection_dump_buffer_mem_stats(severity
);
2140 tor_log(severity
, LD_GENERAL
, "In rephist: "U64_FORMAT
" used by %d Tors.",
2141 U64_PRINTF_ARG(rephist_total_alloc
), rephist_total_num
);
2142 dump_routerlist_mem_usage(severity
);
2143 dump_cell_pool_usage(severity
);
2144 dump_dns_mem_usage(severity
);
2145 buf_dump_freelist_sizes(severity
);
2146 tor_log_mallinfo(severity
);
2149 /** Write all statistics to the log, with log level <b>severity</b>. Called
2150 * in response to a SIGUSR1. */
2152 dumpstats(int severity
)
2154 time_t now
= time(NULL
);
2156 size_t rbuf_cap
, wbuf_cap
, rbuf_len
, wbuf_len
;
2158 tor_log(severity
, LD_GENERAL
, "Dumping stats:");
2160 SMARTLIST_FOREACH_BEGIN(connection_array
, connection_t
*, conn
) {
2161 int i
= conn_sl_idx
;
2162 tor_log(severity
, LD_GENERAL
,
2163 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
2164 i
, (int)conn
->s
, conn
->type
, conn_type_to_string(conn
->type
),
2165 conn
->state
, conn_state_to_string(conn
->type
, conn
->state
),
2166 (int)(now
- conn
->timestamp_created
));
2167 if (!connection_is_listener(conn
)) {
2168 tor_log(severity
,LD_GENERAL
,
2169 "Conn %d is to %s:%d.", i
,
2170 safe_str_client(conn
->address
),
2172 tor_log(severity
,LD_GENERAL
,
2173 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
2175 (int)connection_get_inbuf_len(conn
),
2176 (int)buf_allocation(conn
->inbuf
),
2177 (int)(now
- conn
->timestamp_lastread
));
2178 tor_log(severity
,LD_GENERAL
,
2179 "Conn %d: %d bytes waiting on outbuf "
2180 "(len %d, last written %d secs ago)",i
,
2181 (int)connection_get_outbuf_len(conn
),
2182 (int)buf_allocation(conn
->outbuf
),
2183 (int)(now
- conn
->timestamp_lastwritten
));
2184 if (conn
->type
== CONN_TYPE_OR
) {
2185 or_connection_t
*or_conn
= TO_OR_CONN(conn
);
2187 tor_tls_get_buffer_sizes(or_conn
->tls
, &rbuf_cap
, &rbuf_len
,
2188 &wbuf_cap
, &wbuf_len
);
2189 tor_log(severity
, LD_GENERAL
,
2190 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
2191 "%d/%d bytes used on write buffer.",
2192 i
, (int)rbuf_len
, (int)rbuf_cap
, (int)wbuf_len
, (int)wbuf_cap
);
2196 circuit_dump_by_conn(conn
, severity
); /* dump info about all the circuits
2197 * using this conn */
2198 } SMARTLIST_FOREACH_END(conn
);
2200 channel_dumpstats(severity
);
2201 channel_listener_dumpstats(severity
);
2203 tor_log(severity
, LD_NET
,
2204 "Cells processed: "U64_FORMAT
" padding\n"
2205 " "U64_FORMAT
" create\n"
2206 " "U64_FORMAT
" created\n"
2207 " "U64_FORMAT
" relay\n"
2208 " ("U64_FORMAT
" relayed)\n"
2209 " ("U64_FORMAT
" delivered)\n"
2210 " "U64_FORMAT
" destroy",
2211 U64_PRINTF_ARG(stats_n_padding_cells_processed
),
2212 U64_PRINTF_ARG(stats_n_create_cells_processed
),
2213 U64_PRINTF_ARG(stats_n_created_cells_processed
),
2214 U64_PRINTF_ARG(stats_n_relay_cells_processed
),
2215 U64_PRINTF_ARG(stats_n_relay_cells_relayed
),
2216 U64_PRINTF_ARG(stats_n_relay_cells_delivered
),
2217 U64_PRINTF_ARG(stats_n_destroy_cells_processed
));
2218 if (stats_n_data_cells_packaged
)
2219 tor_log(severity
,LD_NET
,"Average packaged cell fullness: %2.3f%%",
2220 100*(U64_TO_DBL(stats_n_data_bytes_packaged
) /
2221 U64_TO_DBL(stats_n_data_cells_packaged
*RELAY_PAYLOAD_SIZE
)) );
2222 if (stats_n_data_cells_received
)
2223 tor_log(severity
,LD_NET
,"Average delivered cell fullness: %2.3f%%",
2224 100*(U64_TO_DBL(stats_n_data_bytes_received
) /
2225 U64_TO_DBL(stats_n_data_cells_received
*RELAY_PAYLOAD_SIZE
)) );
2227 cpuworker_log_onionskin_overhead(severity
, ONION_HANDSHAKE_TYPE_TAP
, "TAP");
2228 cpuworker_log_onionskin_overhead(severity
, ONION_HANDSHAKE_TYPE_NTOR
,"ntor");
2230 if (now
- time_of_process_start
>= 0)
2231 elapsed
= now
- time_of_process_start
;
2236 tor_log(severity
, LD_NET
,
2237 "Average bandwidth: "U64_FORMAT
"/%d = %d bytes/sec reading",
2238 U64_PRINTF_ARG(stats_n_bytes_read
),
2240 (int) (stats_n_bytes_read
/elapsed
));
2241 tor_log(severity
, LD_NET
,
2242 "Average bandwidth: "U64_FORMAT
"/%d = %d bytes/sec writing",
2243 U64_PRINTF_ARG(stats_n_bytes_written
),
2245 (int) (stats_n_bytes_written
/elapsed
));
2248 tor_log(severity
, LD_NET
, "--------------- Dumping memory information:");
2249 dumpmemusage(severity
);
2251 rep_hist_dump_stats(now
,severity
);
2252 rend_service_dump_stats(severity
);
2253 dump_pk_ops(severity
);
2254 dump_distinct_digest_count(severity
);
2257 /** Called by exit() as we shut down the process.
2262 /* NOTE: If we ever daemonize, this gets called immediately. That's
2263 * okay for now, because we only use this on Windows. */
2269 /** Set up the signal handlers for either parent or child. */
2271 handle_signals(int is_parent
)
2273 #ifndef _WIN32 /* do signal stuff only on Unix */
2275 static const int signals
[] = {
2276 SIGINT
, /* do a controlled slow shutdown */
2277 SIGTERM
, /* to terminate now */
2278 SIGPIPE
, /* otherwise SIGPIPE kills us */
2279 SIGUSR1
, /* dump stats */
2280 SIGUSR2
, /* go to loglevel debug */
2281 SIGHUP
, /* to reload config, retry conns, etc */
2283 SIGXFSZ
, /* handle file-too-big resource exhaustion */
2285 SIGCHLD
, /* handle dns/cpu workers that exit */
2287 static struct event
*signal_events
[16]; /* bigger than it has to be. */
2289 for (i
= 0; signals
[i
] >= 0; ++i
) {
2290 signal_events
[i
] = tor_evsignal_new(
2291 tor_libevent_get_base(), signals
[i
], signal_callback
,
2292 (void*)(uintptr_t)signals
[i
]);
2293 if (event_add(signal_events
[i
], NULL
))
2294 log_warn(LD_BUG
, "Error from libevent when adding event for signal %d",
2298 struct sigaction action
;
2299 action
.sa_flags
= 0;
2300 sigemptyset(&action
.sa_mask
);
2301 action
.sa_handler
= SIG_IGN
;
2302 sigaction(SIGINT
, &action
, NULL
);
2303 sigaction(SIGTERM
, &action
, NULL
);
2304 sigaction(SIGPIPE
, &action
, NULL
);
2305 sigaction(SIGUSR1
, &action
, NULL
);
2306 sigaction(SIGUSR2
, &action
, NULL
);
2307 sigaction(SIGHUP
, &action
, NULL
);
2309 sigaction(SIGXFSZ
, &action
, NULL
);
2312 #else /* MS windows */
2314 #endif /* signal stuff */
2317 /** Main entry point for the Tor command-line client.
2320 tor_init(int argc
, char *argv
[])
2325 time_of_process_start
= time(NULL
);
2326 init_connection_lists();
2327 /* Have the log set up with our application name. */
2328 tor_snprintf(progname
, sizeof(progname
), "Tor %s", get_version());
2329 log_set_application_name(progname
);
2331 /* Set up the crypto nice and early */
2332 if (crypto_early_init() < 0) {
2333 log_err(LD_GENERAL
, "Unable to initialize the crypto subsystem!");
2337 /* Initialize the history structures. */
2339 /* Initialize the service cache. */
2341 addressmap_init(); /* Init the client dns cache. Do it always, since it's
2345 /* We search for the "quiet" option first, since it decides whether we
2346 * will log anything at all to the command line. */
2347 config_line_t
*opts
= NULL
, *cmdline_opts
= NULL
;
2348 const config_line_t
*cl
;
2349 (void) config_parse_commandline(argc
, argv
, 1, &opts
, &cmdline_opts
);
2350 for (cl
= cmdline_opts
; cl
; cl
= cl
->next
) {
2351 if (!strcmp(cl
->key
, "--hush"))
2353 if (!strcmp(cl
->key
, "--quiet") ||
2354 !strcmp(cl
->key
, "--dump-config"))
2356 /* --version, --digests, and --help imply --hush */
2357 if (!strcmp(cl
->key
, "--version") || !strcmp(cl
->key
, "--digests") ||
2358 !strcmp(cl
->key
, "--list-torrc-options") ||
2359 !strcmp(cl
->key
, "--library-versions") ||
2360 !strcmp(cl
->key
, "-h") || !strcmp(cl
->key
, "--help")) {
2365 config_free_lines(opts
);
2366 config_free_lines(cmdline_opts
);
2369 /* give it somewhere to log to initially */
2372 /* no initial logging */
2375 add_temp_log(LOG_WARN
);
2378 add_temp_log(LOG_NOTICE
);
2380 quiet_level
= quiet
;
2383 const char *version
= get_version();
2384 const char *bev_str
=
2385 #ifdef USE_BUFFEREVENTS
2386 "(with bufferevents) ";
2390 log_notice(LD_GENERAL
, "Tor v%s %srunning on %s with Libevent %s, "
2391 "OpenSSL %s and Zlib %s.", version
, bev_str
,
2393 tor_libevent_get_version_str(),
2394 crypto_openssl_get_version_str(),
2395 tor_zlib_get_version_str());
2397 log_notice(LD_GENERAL
, "Tor can't help you if you use it wrong! "
2398 "Learn how to be safe at "
2399 "https://www.torproject.org/download/download#warning");
2401 if (strstr(version
, "alpha") || strstr(version
, "beta"))
2402 log_notice(LD_GENERAL
, "This version is not a stable Tor release. "
2403 "Expect more bugs than usual.");
2406 #ifdef NON_ANONYMOUS_MODE_ENABLED
2407 log_warn(LD_GENERAL
, "This copy of Tor was compiled to run in a "
2408 "non-anonymous mode. It will provide NO ANONYMITY.");
2411 if (network_init()<0) {
2412 log_err(LD_BUG
,"Error initializing network; exiting.");
2415 atexit(exit_function
);
2417 if (options_init_from_torrc(argc
,argv
) < 0) {
2418 log_err(LD_CONFIG
,"Reading config failed--see warnings above.");
2424 log_warn(LD_GENERAL
,"You are running Tor as root. You don't need to, "
2425 "and you probably shouldn't.");
2428 if (crypto_global_init(get_options()->HardwareAccel
,
2429 get_options()->AccelName
,
2430 get_options()->AccelDir
)) {
2431 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
2434 stream_choice_seed_weak_rng();
2435 if (tor_init_libevent_rng() < 0) {
2436 log_warn(LD_NET
, "Problem initializing libevent RNG.");
2442 /** A lockfile structure, used to prevent two Tors from messing with the
2443 * data directory at once. If this variable is non-NULL, we're holding
2445 static tor_lockfile_t
*lockfile
= NULL
;
2447 /** Try to grab the lock file described in <b>options</b>, if we do not
2448 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
2449 * holding the lock, and exit if we can't get it after waiting. Otherwise,
2450 * return -1 if we can't get the lockfile. Return 0 on success.
2453 try_locking(const or_options_t
*options
, int err_if_locked
)
2458 char *fname
= options_get_datadir_fname2_suffix(options
, "lock",NULL
,NULL
);
2459 int already_locked
= 0;
2460 tor_lockfile_t
*lf
= tor_lockfile_lock(fname
, 0, &already_locked
);
2463 if (err_if_locked
&& already_locked
) {
2465 log_warn(LD_GENERAL
, "It looks like another Tor process is running "
2466 "with the same data directory. Waiting 5 seconds to see "
2467 "if it goes away.");
2473 r
= try_locking(options
, 0);
2475 log_err(LD_GENERAL
, "No, it's still there. Exiting.");
2487 /** Return true iff we've successfully acquired the lock file. */
2491 return lockfile
!= NULL
;
2494 /** If we have successfully acquired the lock file, release it. */
2496 release_lockfile(void)
2499 tor_lockfile_unlock(lockfile
);
2504 /** Free all memory that we might have allocated somewhere.
2505 * If <b>postfork</b>, we are a worker process and we want to free
2506 * only the parts of memory that we won't touch. If !<b>postfork</b>,
2507 * Tor is shutting down and we should free everything.
2509 * Helps us find the real leaks with dmalloc and the like. Also valgrind
2510 * should then report 0 reachable in its leak report (in an ideal world --
2511 * in practice libevent, SSL, libc etc never quite free everything). */
2513 tor_free_all(int postfork
)
2520 routerlist_free_all();
2521 networkstatus_free_all();
2522 addressmap_free_all();
2524 rend_service_free_all();
2525 rend_cache_free_all();
2526 rend_service_authorization_free_all();
2527 rep_hist_free_all();
2529 clear_pending_onions();
2531 entry_guards_free_all();
2533 channel_tls_free_all();
2535 connection_free_all();
2536 buf_shrink_freelists(1);
2537 memarea_clear_freelist();
2538 nodelist_free_all();
2539 microdesc_free_all();
2540 ext_orport_free_all();
2544 or_state_free_all();
2546 policies_free_all();
2555 /* stuff in main.c */
2557 smartlist_free(connection_array
);
2558 smartlist_free(closeable_connection_lst
);
2559 smartlist_free(active_linked_connection_lst
);
2560 periodic_timer_free(second_timer
);
2561 #ifndef USE_BUFFEREVENTS
2562 periodic_timer_free(refill_timer
);
2568 /* Stuff in util.c and address.c*/
2571 esc_router_info(NULL
);
2572 logs_free_all(); /* free log strings. do this last so logs keep working. */
2576 /** Do whatever cleanup is necessary before shutting Tor down. */
2580 const or_options_t
*options
= get_options();
2581 if (options
->command
== CMD_RUN_TOR
) {
2582 time_t now
= time(NULL
);
2583 /* Remove our pid file. We don't care if there was an error when we
2584 * unlink, nothing we could do about it anyways. */
2585 if (options
->PidFile
) {
2586 if (unlink(options
->PidFile
) != 0) {
2587 log_warn(LD_FS
, "Couldn't unlink pid file %s: %s",
2588 options
->PidFile
, strerror(errno
));
2591 if (options
->ControlPortWriteToFile
) {
2592 if (unlink(options
->ControlPortWriteToFile
) != 0) {
2593 log_warn(LD_FS
, "Couldn't unlink control port file %s: %s",
2594 options
->ControlPortWriteToFile
,
2598 if (accounting_is_enabled(options
))
2599 accounting_record_bandwidth_usage(now
, get_or_state());
2600 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
2602 if (authdir_mode_tests_reachability(options
))
2603 rep_hist_record_mtbf_data(now
, 0);
2606 dmalloc_log_stats();
2608 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
2609 later, if it makes shutdown unacceptably slow. But for
2610 now, leave it here: it's helped us catch bugs in the
2612 crypto_global_cleanup();
2614 dmalloc_log_unfreed();
2619 /** Read/create keys as needed, and echo our fingerprint to stdout. */
2621 do_list_fingerprint(void)
2623 char buf
[FINGERPRINT_LEN
+1];
2625 const char *nickname
= get_options()->Nickname
;
2626 if (!server_mode(get_options())) {
2628 "Clients don't have long-term identity keys. Exiting.");
2631 tor_assert(nickname
);
2632 if (init_keys() < 0) {
2633 log_err(LD_BUG
,"Error initializing keys; can't display fingerprint");
2636 if (!(k
= get_server_identity_key())) {
2637 log_err(LD_GENERAL
,"Error: missing identity key.");
2640 if (crypto_pk_get_fingerprint(k
, buf
, 1)<0) {
2641 log_err(LD_BUG
, "Error computing fingerprint");
2644 printf("%s %s\n", nickname
, buf
);
2648 /** Entry point for password hashing: take the desired password from
2649 * the command line, and print its salted hash to stdout. **/
2651 do_hash_password(void)
2655 char key
[S2K_SPECIFIER_LEN
+DIGEST_LEN
];
2657 crypto_rand(key
, S2K_SPECIFIER_LEN
-1);
2658 key
[S2K_SPECIFIER_LEN
-1] = (uint8_t)96; /* Hash 64 K of data. */
2659 secret_to_key(key
+S2K_SPECIFIER_LEN
, DIGEST_LEN
,
2660 get_options()->command_arg
, strlen(get_options()->command_arg
),
2662 base16_encode(output
, sizeof(output
), key
, sizeof(key
));
2663 printf("16:%s\n",output
);
2666 /** Entry point for configuration dumping: write the configuration to
2669 do_dump_config(void)
2671 const or_options_t
*options
= get_options();
2672 const char *arg
= options
->command_arg
;
2675 if (!strcmp(arg
, "short")) {
2676 how
= OPTIONS_DUMP_MINIMAL
;
2677 } else if (!strcmp(arg
, "non-builtin")) {
2678 how
= OPTIONS_DUMP_DEFAULTS
;
2679 } else if (!strcmp(arg
, "full")) {
2680 how
= OPTIONS_DUMP_ALL
;
2682 printf("%s is not a recognized argument to --dump-config. "
2683 "Please select 'short', 'non-builtin', or 'full'", arg
);
2687 opts
= options_dump(options
, how
);
2696 find_flashcard_path(PWCHAR path
, size_t size
)
2698 WIN32_FIND_DATA d
= {0};
2704 h
= FindFirstFlashCard(&d
);
2705 if (h
== INVALID_HANDLE_VALUE
)
2708 if (wcslen(d
.cFileName
) == 0) {
2713 wcsncpy(path
,d
.cFileName
,size
);
2724 // host name to sandbox
2725 gethostname(hname
, sizeof(hname
));
2726 sandbox_add_addrinfo(hname
);
2729 static sandbox_cfg_t
*
2730 sandbox_init_filter(void)
2732 const or_options_t
*options
= get_options();
2733 sandbox_cfg_t
*cfg
= sandbox_cfg_new();
2736 sandbox_cfg_allow_openat_filename(&cfg
,
2737 get_datadir_fname("cached-status"));
2739 sandbox_cfg_allow_open_filename_array(&cfg
,
2740 get_datadir_fname("cached-certs"),
2741 get_datadir_fname("cached-certs.tmp"),
2742 get_datadir_fname("cached-consensus"),
2743 get_datadir_fname("cached-consensus.tmp"),
2744 get_datadir_fname("unverified-consensus"),
2745 get_datadir_fname("unverified-consensus.tmp"),
2746 get_datadir_fname("unverified-microdesc-consensus"),
2747 get_datadir_fname("unverified-microdesc-consensus.tmp"),
2748 get_datadir_fname("cached-microdesc-consensus"),
2749 get_datadir_fname("cached-microdesc-consensus.tmp"),
2750 get_datadir_fname("cached-microdescs"),
2751 get_datadir_fname("cached-microdescs.tmp"),
2752 get_datadir_fname("cached-microdescs.new"),
2753 get_datadir_fname("cached-microdescs.new.tmp"),
2754 get_datadir_fname("cached-descriptors"),
2755 get_datadir_fname("cached-descriptors.new"),
2756 get_datadir_fname("cached-descriptors.tmp"),
2757 get_datadir_fname("cached-descriptors.new.tmp"),
2758 get_datadir_fname("cached-descriptors.tmp.tmp"),
2759 get_datadir_fname("cached-extrainfo"),
2760 get_datadir_fname("cached-extrainfo.new"),
2761 get_datadir_fname("cached-extrainfo.tmp"),
2762 get_datadir_fname("cached-extrainfo.new.tmp"),
2763 get_datadir_fname("cached-extrainfo.tmp.tmp"),
2764 get_datadir_fname("state.tmp"),
2765 get_datadir_fname("unparseable-desc.tmp"),
2766 get_datadir_fname("unparseable-desc"),
2767 get_datadir_fname("v3-status-votes"),
2768 get_datadir_fname("v3-status-votes.tmp"),
2769 tor_strdup("/dev/srandom"),
2770 tor_strdup("/dev/urandom"),
2771 tor_strdup("/dev/random"),
2772 tor_strdup("/etc/hosts"),
2773 tor_strdup("/proc/meminfo"),
2776 if (options
->ServerDNSResolvConfFile
)
2777 sandbox_cfg_allow_open_filename(&cfg
,
2778 tor_strdup(options
->ServerDNSResolvConfFile
));
2780 sandbox_cfg_allow_open_filename(&cfg
, tor_strdup("/etc/resolv.conf"));
2782 for (i
= 0; i
< 2; ++i
) {
2783 if (get_torrc_fname(i
)) {
2784 sandbox_cfg_allow_open_filename(&cfg
, tor_strdup(get_torrc_fname(i
)));
2788 #define RENAME_SUFFIX(name, suffix) \
2789 sandbox_cfg_allow_rename(&cfg, \
2790 get_datadir_fname(name suffix), \
2791 get_datadir_fname(name))
2793 #define RENAME_SUFFIX2(prefix, name, suffix) \
2794 sandbox_cfg_allow_rename(&cfg, \
2795 get_datadir_fname2(prefix, name suffix), \
2796 get_datadir_fname2(prefix, name))
2798 RENAME_SUFFIX("cached-certs", ".tmp");
2799 RENAME_SUFFIX("cached-consensus", ".tmp");
2800 RENAME_SUFFIX("unverified-consensus", ".tmp");
2801 RENAME_SUFFIX("unverified-microdesc-consensus", ".tmp");
2802 RENAME_SUFFIX("cached-microdesc-consensus", ".tmp");
2803 RENAME_SUFFIX("cached-microdescs", ".tmp");
2804 RENAME_SUFFIX("cached-microdescs", ".new");
2805 RENAME_SUFFIX("cached-microdescs.new", ".tmp");
2806 RENAME_SUFFIX("cached-descriptors", ".tmp");
2807 RENAME_SUFFIX("cached-descriptors", ".new");
2808 RENAME_SUFFIX("cached-descriptors.new", ".tmp");
2809 RENAME_SUFFIX("cached-extrainfo", ".tmp");
2810 RENAME_SUFFIX("cached-extrainfo", ".new");
2811 RENAME_SUFFIX("cached-extrainfo.new", ".tmp");
2812 RENAME_SUFFIX("state", ".tmp");
2813 RENAME_SUFFIX("unparseable-desc", ".tmp");
2814 RENAME_SUFFIX("v3-status-votes", ".tmp");
2816 sandbox_cfg_allow_stat_filename_array(&cfg
,
2817 get_datadir_fname(NULL
),
2818 get_datadir_fname("lock"),
2819 get_datadir_fname("state"),
2820 get_datadir_fname("router-stability"),
2821 get_datadir_fname("cached-extrainfo.new"),
2826 if (server_mode(get_options())) {
2827 sandbox_cfg_allow_open_filename_array(&cfg
,
2828 get_datadir_fname2("keys", "secret_id_key"),
2829 get_datadir_fname2("keys", "secret_onion_key"),
2830 get_datadir_fname2("keys", "secret_onion_key_ntor"),
2831 get_datadir_fname2("keys", "secret_onion_key_ntor.tmp"),
2832 get_datadir_fname2("keys", "secret_id_key.old"),
2833 get_datadir_fname2("keys", "secret_onion_key.old"),
2834 get_datadir_fname2("keys", "secret_onion_key_ntor.old"),
2835 get_datadir_fname2("keys", "secret_onion_key.tmp"),
2836 get_datadir_fname2("keys", "secret_id_key.tmp"),
2837 get_datadir_fname2("stats", "bridge-stats"),
2838 get_datadir_fname2("stats", "bridge-stats.tmp"),
2839 get_datadir_fname2("stats", "dirreq-stats"),
2840 get_datadir_fname2("stats", "dirreq-stats.tmp"),
2841 get_datadir_fname("fingerprint"),
2842 get_datadir_fname("fingerprint.tmp"),
2843 get_datadir_fname("hashed-fingerprint"),
2844 get_datadir_fname("hashed-fingerprint.tmp"),
2845 get_datadir_fname("router-stability"),
2846 get_datadir_fname("router-stability.tmp"),
2847 tor_strdup("/etc/resolv.conf"),
2851 if (options
->DirPortFrontPage
) {
2852 sandbox_cfg_allow_open_filename(&cfg
,
2853 tor_strdup(options
->DirPortFrontPage
));
2856 RENAME_SUFFIX("fingerprint", ".tmp");
2857 RENAME_SUFFIX2("keys", "secret_onion_key_ntor", ".tmp");
2858 RENAME_SUFFIX2("keys", "secret_id_key", ".tmp");
2859 RENAME_SUFFIX2("keys", "secret_id_key.old", ".tmp");
2860 RENAME_SUFFIX2("keys", "secret_onion_key", ".tmp");
2861 RENAME_SUFFIX2("keys", "secret_onion_key.old", ".tmp");
2862 RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
2863 RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
2864 RENAME_SUFFIX("hashed-fingerprint", ".tmp");
2865 RENAME_SUFFIX("router-stability", ".tmp");
2867 sandbox_cfg_allow_rename(&cfg
,
2868 get_datadir_fname2("keys", "secret_onion_key"),
2869 get_datadir_fname2("keys", "secret_onion_key.old"));
2870 sandbox_cfg_allow_rename(&cfg
,
2871 get_datadir_fname2("keys", "secret_onion_key_ntor"),
2872 get_datadir_fname2("keys", "secret_onion_key_ntor.old"));
2874 sandbox_cfg_allow_stat_filename_array(&cfg
,
2875 get_datadir_fname("keys"),
2876 get_datadir_fname2("stats", "dirreq-stats"),
2886 /** Main entry point for the Tor process. Called from main(). */
2887 /* This function is distinct from main() only so we can link main.c into
2888 * the unittest binary without conflicting with the unittests' main. */
2890 tor_main(int argc
, char *argv
[])
2894 WCHAR path
[MAX_PATH
] = {0};
2895 WCHAR fullpath
[MAX_PATH
] = {0};
2898 FILE* redirdbg
= NULL
;
2900 // this is to facilitate debugging by opening
2901 // a file on a folder shared by the wm emulator.
2902 // if no flashcard (real or emulated) is present,
2903 // log files will be written in the root folder
2904 if (find_flashcard_path(path
,MAX_PATH
) == -1) {
2905 redir
= _wfreopen( L
"\\stdout.log", L
"w", stdout
);
2906 redirdbg
= _wfreopen( L
"\\stderr.log", L
"w", stderr
);
2908 swprintf(fullpath
,L
"\\%s\\tor",path
);
2909 CreateDirectory(fullpath
,NULL
);
2911 swprintf(fullpath
,L
"\\%s\\tor\\stdout.log",path
);
2912 redir
= _wfreopen( fullpath
, L
"w", stdout
);
2914 swprintf(fullpath
,L
"\\%s\\tor\\stderr.log",path
);
2915 redirdbg
= _wfreopen( fullpath
, L
"w", stderr
);
2920 /* Call SetProcessDEPPolicy to permanently enable DEP.
2921 The function will not resolve on earlier versions of Windows,
2922 and failure is not dangerous. */
2923 HMODULE hMod
= GetModuleHandleA("Kernel32.dll");
2925 typedef BOOL (WINAPI
*PSETDEP
)(DWORD
);
2926 PSETDEP setdeppolicy
= (PSETDEP
)GetProcAddress(hMod
,
2927 "SetProcessDEPPolicy");
2928 if (setdeppolicy
) setdeppolicy(1); /* PROCESS_DEP_ENABLE */
2932 configure_backtrace_handler(get_version());
2934 update_approx_time(time(NULL
));
2939 /* Instruct OpenSSL to use our internal wrappers for malloc,
2940 realloc and free. */
2941 int r
= CRYPTO_set_mem_ex_functions(tor_malloc_
, tor_realloc_
, tor_free_
);
2948 result
= nt_service_parse_options(argc
, argv
, &done
);
2949 if (done
) return result
;
2952 if (tor_init(argc
, argv
)<0)
2955 if (get_options()->Sandbox
&& get_options()->command
== CMD_RUN_TOR
) {
2956 sandbox_cfg_t
* cfg
= sandbox_init_filter();
2958 if (sandbox_init(cfg
)) {
2959 log_err(LD_BUG
,"Failed to create syscall sandbox filter");
2963 // registering libevent rng
2964 #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
2965 evutil_secure_rng_set_urandom_device_file(
2966 (char*) sandbox_intern_string("/dev/urandom"));
2970 switch (get_options()->command
) {
2973 nt_service_set_state(SERVICE_RUNNING
);
2975 result
= do_main_loop();
2977 case CMD_LIST_FINGERPRINT
:
2978 result
= do_list_fingerprint();
2980 case CMD_HASH_PASSWORD
:
2984 case CMD_VERIFY_CONFIG
:
2985 printf("Configuration was valid\n");
2988 case CMD_DUMP_CONFIG
:
2989 result
= do_dump_config();
2991 case CMD_RUN_UNITTESTS
: /* only set by test.c */
2993 log_warn(LD_BUG
,"Illegal command number %d: internal error.",
2994 get_options()->command
);