In routerlist_assert_ok(), check r2 before taking &(r2->cache_info)
[tor.git] / src / or / main.c
blob9c1cabf03762990df14f160acf14e4f500d5708e
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 */
7 /**
8 * \file main.c
9 * \brief Toplevel module. Handles signals, multiplexes between
10 * connections, implements main loop, and drives scheduled events.
11 **/
13 #define MAIN_PRIVATE
14 #include "or.h"
15 #include "addressmap.h"
16 #include "backtrace.h"
17 #include "buffers.h"
18 #include "channel.h"
19 #include "channeltls.h"
20 #include "circuitbuild.h"
21 #include "circuitlist.h"
22 #include "circuituse.h"
23 #include "command.h"
24 #include "config.h"
25 #include "confparse.h"
26 #include "connection.h"
27 #include "connection_edge.h"
28 #include "connection_or.h"
29 #include "control.h"
30 #include "cpuworker.h"
31 #include "directory.h"
32 #include "dirserv.h"
33 #include "dirvote.h"
34 #include "dns.h"
35 #include "dnsserv.h"
36 #include "entrynodes.h"
37 #include "geoip.h"
38 #include "hibernate.h"
39 #include "main.h"
40 #include "microdesc.h"
41 #include "networkstatus.h"
42 #include "nodelist.h"
43 #include "ntmain.h"
44 #include "onion.h"
45 #include "policies.h"
46 #include "transports.h"
47 #include "relay.h"
48 #include "rendclient.h"
49 #include "rendcommon.h"
50 #include "rendservice.h"
51 #include "rephist.h"
52 #include "router.h"
53 #include "routerlist.h"
54 #include "routerparse.h"
55 #include "statefile.h"
56 #include "status.h"
57 #include "util_process.h"
58 #include "ext_orport.h"
59 #ifdef USE_DMALLOC
60 #include <dmalloc.h>
61 #include <openssl/crypto.h>
62 #endif
63 #include "memarea.h"
64 #include "../common/sandbox.h"
66 #ifdef HAVE_EVENT2_EVENT_H
67 #include <event2/event.h>
68 #else
69 #include <event.h>
70 #endif
72 #ifdef USE_BUFFEREVENTS
73 #include <event2/bufferevent.h>
74 #endif
76 void evdns_shutdown(int);
78 /********* PROTOTYPES **********/
80 static void dumpmemusage(int severity);
81 static void dumpstats(int severity); /* log stats */
82 static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
83 static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
84 static void second_elapsed_callback(periodic_timer_t *timer, void *args);
85 static int conn_close_if_marked(int i);
86 static void connection_start_reading_from_linked_conn(connection_t *conn);
87 static int connection_should_read_from_linked_conn(connection_t *conn);
89 /********* START VARIABLES **********/
91 #ifndef USE_BUFFEREVENTS
92 int global_read_bucket; /**< Max number of bytes I can read this second. */
93 int global_write_bucket; /**< Max number of bytes I can write this second. */
95 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
96 int global_relayed_read_bucket;
97 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
98 int global_relayed_write_bucket;
99 /** What was the read bucket before the last second_elapsed_callback() call?
100 * (used to determine how many bytes we've read). */
101 static int stats_prev_global_read_bucket;
102 /** What was the write bucket before the last second_elapsed_callback() call?
103 * (used to determine how many bytes we've written). */
104 static int stats_prev_global_write_bucket;
105 #endif
107 /* DOCDOC stats_prev_n_read */
108 static uint64_t stats_prev_n_read = 0;
109 /* DOCDOC stats_prev_n_written */
110 static uint64_t stats_prev_n_written = 0;
112 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
113 /** How many bytes have we read since we started the process? */
114 static uint64_t stats_n_bytes_read = 0;
115 /** How many bytes have we written since we started the process? */
116 static uint64_t stats_n_bytes_written = 0;
117 /** What time did this process start up? */
118 time_t time_of_process_start = 0;
119 /** How many seconds have we been running? */
120 long stats_n_seconds_working = 0;
121 /** When do we next launch DNS wildcarding checks? */
122 static time_t time_to_check_for_correct_dns = 0;
124 /** How often will we honor SIGNEWNYM requests? */
125 #define MAX_SIGNEWNYM_RATE 10
126 /** When did we last process a SIGNEWNYM request? */
127 static time_t time_of_last_signewnym = 0;
128 /** Is there a signewnym request we're currently waiting to handle? */
129 static int signewnym_is_pending = 0;
130 /** How many times have we called newnym? */
131 static unsigned newnym_epoch = 0;
133 /** Smartlist of all open connections. */
134 static smartlist_t *connection_array = NULL;
135 /** List of connections that have been marked for close and need to be freed
136 * and removed from connection_array. */
137 static smartlist_t *closeable_connection_lst = NULL;
138 /** List of linked connections that are currently reading data into their
139 * inbuf from their partner's outbuf. */
140 static smartlist_t *active_linked_connection_lst = NULL;
141 /** Flag: Set to true iff we entered the current libevent main loop via
142 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
143 * to handle linked connections. */
144 static int called_loop_once = 0;
146 /** We set this to 1 when we've opened a circuit, so we can print a log
147 * entry to inform the user that Tor is working. We set it to 0 when
148 * we think the fact that we once opened a circuit doesn't mean we can do so
149 * any longer (a big time jump happened, when we notice our directory is
150 * heinously out-of-date, etc.
152 int can_complete_circuit=0;
154 /** How often do we check for router descriptors that we should download
155 * when we have too little directory info? */
156 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
157 /** How often do we check for router descriptors that we should download
158 * when we have enough directory info? */
159 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
160 /** How often do we 'forgive' undownloadable router descriptors and attempt
161 * to download them again? */
162 #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
164 /** Decides our behavior when no logs are configured/before any
165 * logs have been configured. For 0, we log notice to stdout as normal.
166 * For 1, we log warnings only. For 2, we log nothing.
168 int quiet_level = 0;
170 /********* END VARIABLES ************/
172 /****************************************************************************
174 * This section contains accessors and other methods on the connection_array
175 * variables (which are global within this file and unavailable outside it).
177 ****************************************************************************/
179 #if 0 && defined(USE_BUFFEREVENTS)
180 static void
181 free_old_inbuf(connection_t *conn)
183 if (! conn->inbuf)
184 return;
186 tor_assert(conn->outbuf);
187 tor_assert(buf_datalen(conn->inbuf) == 0);
188 tor_assert(buf_datalen(conn->outbuf) == 0);
189 buf_free(conn->inbuf);
190 buf_free(conn->outbuf);
191 conn->inbuf = conn->outbuf = NULL;
193 if (conn->read_event) {
194 event_del(conn->read_event);
195 tor_event_free(conn->read_event);
197 if (conn->write_event) {
198 event_del(conn->read_event);
199 tor_event_free(conn->write_event);
201 conn->read_event = conn->write_event = NULL;
203 #endif
205 #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
206 /** Remove the kernel-space send and receive buffers for <b>s</b>. For use
207 * with IOCP only. */
208 static int
209 set_buffer_lengths_to_zero(tor_socket_t s)
211 int zero = 0;
212 int r = 0;
213 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&zero, sizeof(zero))) {
214 log_warn(LD_NET, "Unable to clear SO_SNDBUF");
215 r = -1;
217 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&zero, sizeof(zero))) {
218 log_warn(LD_NET, "Unable to clear SO_RCVBUF");
219 r = -1;
221 return r;
223 #endif
225 /** Add <b>conn</b> to the array of connections that we can poll on. The
226 * connection's socket must be set; the connection starts out
227 * non-reading and non-writing.
230 connection_add_impl(connection_t *conn, int is_connecting)
232 tor_assert(conn);
233 tor_assert(SOCKET_OK(conn->s) ||
234 conn->linked ||
235 (conn->type == CONN_TYPE_AP &&
236 TO_EDGE_CONN(conn)->is_dns_request));
238 tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
239 conn->conn_array_index = smartlist_len(connection_array);
240 smartlist_add(connection_array, conn);
242 #ifdef USE_BUFFEREVENTS
243 if (connection_type_uses_bufferevent(conn)) {
244 if (SOCKET_OK(conn->s) && !conn->linked) {
246 #ifdef _WIN32
247 if (tor_libevent_using_iocp_bufferevents() &&
248 get_options()->UserspaceIOCPBuffers) {
249 set_buffer_lengths_to_zero(conn->s);
251 #endif
253 conn->bufev = bufferevent_socket_new(
254 tor_libevent_get_base(),
255 conn->s,
256 BEV_OPT_DEFER_CALLBACKS);
257 if (!conn->bufev) {
258 log_warn(LD_BUG, "Unable to create socket bufferevent");
259 smartlist_del(connection_array, conn->conn_array_index);
260 conn->conn_array_index = -1;
261 return -1;
263 if (is_connecting) {
264 /* Put the bufferevent into a "connecting" state so that we'll get
265 * a "connected" event callback on successful write. */
266 bufferevent_socket_connect(conn->bufev, NULL, 0);
268 connection_configure_bufferevent_callbacks(conn);
269 } else if (conn->linked && conn->linked_conn &&
270 connection_type_uses_bufferevent(conn->linked_conn)) {
271 tor_assert(!(SOCKET_OK(conn->s)));
272 if (!conn->bufev) {
273 struct bufferevent *pair[2] = { NULL, NULL };
274 if (bufferevent_pair_new(tor_libevent_get_base(),
275 BEV_OPT_DEFER_CALLBACKS,
276 pair) < 0) {
277 log_warn(LD_BUG, "Unable to create bufferevent pair");
278 smartlist_del(connection_array, conn->conn_array_index);
279 conn->conn_array_index = -1;
280 return -1;
282 tor_assert(pair[0]);
283 conn->bufev = pair[0];
284 conn->linked_conn->bufev = pair[1];
285 } /* else the other side already was added, and got a bufferevent_pair */
286 connection_configure_bufferevent_callbacks(conn);
287 } else {
288 tor_assert(!conn->linked);
291 if (conn->bufev)
292 tor_assert(conn->inbuf == NULL);
294 if (conn->linked_conn && conn->linked_conn->bufev)
295 tor_assert(conn->linked_conn->inbuf == NULL);
297 #else
298 (void) is_connecting;
299 #endif
301 if (!HAS_BUFFEREVENT(conn) && (SOCKET_OK(conn->s) || conn->linked)) {
302 conn->read_event = tor_event_new(tor_libevent_get_base(),
303 conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
304 conn->write_event = tor_event_new(tor_libevent_get_base(),
305 conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
306 /* XXXX CHECK FOR NULL RETURN! */
309 log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
310 conn_type_to_string(conn->type), (int)conn->s, conn->address,
311 smartlist_len(connection_array));
313 return 0;
316 /** Tell libevent that we don't care about <b>conn</b> any more. */
317 void
318 connection_unregister_events(connection_t *conn)
320 if (conn->read_event) {
321 if (event_del(conn->read_event))
322 log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
323 tor_free(conn->read_event);
325 if (conn->write_event) {
326 if (event_del(conn->write_event))
327 log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
328 tor_free(conn->write_event);
330 #ifdef USE_BUFFEREVENTS
331 if (conn->bufev) {
332 bufferevent_free(conn->bufev);
333 conn->bufev = NULL;
335 #endif
336 if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
337 dnsserv_close_listener(conn);
341 /** Remove the connection from the global list, and remove the
342 * corresponding poll entry. Calling this function will shift the last
343 * connection (if any) into the position occupied by conn.
346 connection_remove(connection_t *conn)
348 int current_index;
349 connection_t *tmp;
351 tor_assert(conn);
353 log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
354 (int)conn->s, conn_type_to_string(conn->type),
355 smartlist_len(connection_array));
357 control_event_conn_bandwidth(conn);
359 tor_assert(conn->conn_array_index >= 0);
360 current_index = conn->conn_array_index;
361 connection_unregister_events(conn); /* This is redundant, but cheap. */
362 if (current_index == smartlist_len(connection_array)-1) { /* at the end */
363 smartlist_del(connection_array, current_index);
364 return 0;
367 /* replace this one with the one at the end */
368 smartlist_del(connection_array, current_index);
369 tmp = smartlist_get(connection_array, current_index);
370 tmp->conn_array_index = current_index;
372 return 0;
375 /** If <b>conn</b> is an edge conn, remove it from the list
376 * of conn's on this circuit. If it's not on an edge,
377 * flush and send destroys for all circuits on this conn.
379 * Remove it from connection_array (if applicable) and
380 * from closeable_connection_list.
382 * Then free it.
384 static void
385 connection_unlink(connection_t *conn)
387 connection_about_to_close_connection(conn);
388 if (conn->conn_array_index >= 0) {
389 connection_remove(conn);
391 if (conn->linked_conn) {
392 conn->linked_conn->linked_conn = NULL;
393 if (! conn->linked_conn->marked_for_close &&
394 conn->linked_conn->reading_from_linked_conn)
395 connection_start_reading(conn->linked_conn);
396 conn->linked_conn = NULL;
398 smartlist_remove(closeable_connection_lst, conn);
399 smartlist_remove(active_linked_connection_lst, conn);
400 if (conn->type == CONN_TYPE_EXIT) {
401 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
403 if (conn->type == CONN_TYPE_OR) {
404 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
405 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
406 /* connection_unlink() can only get called if the connection
407 * was already on the closeable list, and it got there by
408 * connection_mark_for_close(), which was called from
409 * connection_or_close_normally() or
410 * connection_or_close_for_error(), so the channel should
411 * already be in CHANNEL_STATE_CLOSING, and then the
412 * connection_about_to_close_connection() goes to
413 * connection_or_about_to_close(), which calls channel_closed()
414 * to notify the channel_t layer, and closed the channel, so
415 * nothing more to do here to deal with the channel associated
416 * with an orconn.
419 connection_free(conn);
422 /** Initialize the global connection list, closeable connection list,
423 * and active connection list. */
424 STATIC void
425 init_connection_lists(void)
427 if (!connection_array)
428 connection_array = smartlist_new();
429 if (!closeable_connection_lst)
430 closeable_connection_lst = smartlist_new();
431 if (!active_linked_connection_lst)
432 active_linked_connection_lst = smartlist_new();
435 /** Schedule <b>conn</b> to be closed. **/
436 void
437 add_connection_to_closeable_list(connection_t *conn)
439 tor_assert(!smartlist_contains(closeable_connection_lst, conn));
440 tor_assert(conn->marked_for_close);
441 assert_connection_ok(conn, time(NULL));
442 smartlist_add(closeable_connection_lst, conn);
445 /** Return 1 if conn is on the closeable list, else return 0. */
447 connection_is_on_closeable_list(connection_t *conn)
449 return smartlist_contains(closeable_connection_lst, conn);
452 /** Return true iff conn is in the current poll array. */
454 connection_in_array(connection_t *conn)
456 return smartlist_contains(connection_array, conn);
459 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
460 * to the length of the array. <b>*array</b> and <b>*n</b> must not
461 * be modified.
463 smartlist_t *
464 get_connection_array(void)
466 if (!connection_array)
467 connection_array = smartlist_new();
468 return connection_array;
471 /** Provides the traffic read and written over the life of the process. */
473 MOCK_IMPL(uint64_t,
474 get_bytes_read,(void))
476 return stats_n_bytes_read;
479 /* DOCDOC get_bytes_written */
480 MOCK_IMPL(uint64_t,
481 get_bytes_written,(void))
483 return stats_n_bytes_written;
486 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
487 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
489 void
490 connection_watch_events(connection_t *conn, watchable_events_t events)
492 IF_HAS_BUFFEREVENT(conn, {
493 short ev = ((short)events) & (EV_READ|EV_WRITE);
494 short old_ev = bufferevent_get_enabled(conn->bufev);
495 if ((ev & ~old_ev) != 0) {
496 bufferevent_enable(conn->bufev, ev);
498 if ((old_ev & ~ev) != 0) {
499 bufferevent_disable(conn->bufev, old_ev & ~ev);
501 return;
503 if (events & READ_EVENT)
504 connection_start_reading(conn);
505 else
506 connection_stop_reading(conn);
508 if (events & WRITE_EVENT)
509 connection_start_writing(conn);
510 else
511 connection_stop_writing(conn);
514 /** Return true iff <b>conn</b> is listening for read events. */
516 connection_is_reading(connection_t *conn)
518 tor_assert(conn);
520 IF_HAS_BUFFEREVENT(conn,
521 return (bufferevent_get_enabled(conn->bufev) & EV_READ) != 0;
523 return conn->reading_from_linked_conn ||
524 (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
527 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
528 MOCK_IMPL(void,
529 connection_stop_reading,(connection_t *conn))
531 tor_assert(conn);
533 IF_HAS_BUFFEREVENT(conn, {
534 bufferevent_disable(conn->bufev, EV_READ);
535 return;
538 tor_assert(conn->read_event);
540 if (conn->linked) {
541 conn->reading_from_linked_conn = 0;
542 connection_stop_reading_from_linked_conn(conn);
543 } else {
544 if (event_del(conn->read_event))
545 log_warn(LD_NET, "Error from libevent setting read event state for %d "
546 "to unwatched: %s",
547 (int)conn->s,
548 tor_socket_strerror(tor_socket_errno(conn->s)));
552 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
553 MOCK_IMPL(void,
554 connection_start_reading,(connection_t *conn))
556 tor_assert(conn);
558 IF_HAS_BUFFEREVENT(conn, {
559 bufferevent_enable(conn->bufev, EV_READ);
560 return;
563 tor_assert(conn->read_event);
565 if (conn->linked) {
566 conn->reading_from_linked_conn = 1;
567 if (connection_should_read_from_linked_conn(conn))
568 connection_start_reading_from_linked_conn(conn);
569 } else {
570 if (event_add(conn->read_event, NULL))
571 log_warn(LD_NET, "Error from libevent setting read event state for %d "
572 "to watched: %s",
573 (int)conn->s,
574 tor_socket_strerror(tor_socket_errno(conn->s)));
578 /** Return true iff <b>conn</b> is listening for write events. */
580 connection_is_writing(connection_t *conn)
582 tor_assert(conn);
584 IF_HAS_BUFFEREVENT(conn,
585 return (bufferevent_get_enabled(conn->bufev) & EV_WRITE) != 0;
588 return conn->writing_to_linked_conn ||
589 (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
592 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
593 MOCK_IMPL(void,
594 connection_stop_writing,(connection_t *conn))
596 tor_assert(conn);
598 IF_HAS_BUFFEREVENT(conn, {
599 bufferevent_disable(conn->bufev, EV_WRITE);
600 return;
603 tor_assert(conn->write_event);
605 if (conn->linked) {
606 conn->writing_to_linked_conn = 0;
607 if (conn->linked_conn)
608 connection_stop_reading_from_linked_conn(conn->linked_conn);
609 } else {
610 if (event_del(conn->write_event))
611 log_warn(LD_NET, "Error from libevent setting write event state for %d "
612 "to unwatched: %s",
613 (int)conn->s,
614 tor_socket_strerror(tor_socket_errno(conn->s)));
618 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
619 MOCK_IMPL(void,
620 connection_start_writing,(connection_t *conn))
622 tor_assert(conn);
624 IF_HAS_BUFFEREVENT(conn, {
625 bufferevent_enable(conn->bufev, EV_WRITE);
626 return;
629 tor_assert(conn->write_event);
631 if (conn->linked) {
632 conn->writing_to_linked_conn = 1;
633 if (conn->linked_conn &&
634 connection_should_read_from_linked_conn(conn->linked_conn))
635 connection_start_reading_from_linked_conn(conn->linked_conn);
636 } else {
637 if (event_add(conn->write_event, NULL))
638 log_warn(LD_NET, "Error from libevent setting write event state for %d "
639 "to watched: %s",
640 (int)conn->s,
641 tor_socket_strerror(tor_socket_errno(conn->s)));
645 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
646 * linked to it would be good and feasible. (Reading is "feasible" if the
647 * other conn exists and has data in its outbuf, and is "good" if we have our
648 * reading_from_linked_conn flag set and the other conn has its
649 * writing_to_linked_conn flag set.)*/
650 static int
651 connection_should_read_from_linked_conn(connection_t *conn)
653 if (conn->linked && conn->reading_from_linked_conn) {
654 if (! conn->linked_conn ||
655 (conn->linked_conn->writing_to_linked_conn &&
656 buf_datalen(conn->linked_conn->outbuf)))
657 return 1;
659 return 0;
662 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
663 * its linked connection, if it is not doing so already. Called by
664 * connection_start_reading and connection_start_writing as appropriate. */
665 static void
666 connection_start_reading_from_linked_conn(connection_t *conn)
668 tor_assert(conn);
669 tor_assert(conn->linked == 1);
671 if (!conn->active_on_link) {
672 conn->active_on_link = 1;
673 smartlist_add(active_linked_connection_lst, conn);
674 if (!called_loop_once) {
675 /* This is the first event on the list; we won't be in LOOP_ONCE mode,
676 * so we need to make sure that the event_base_loop() actually exits at
677 * the end of its run through the current connections and lets us
678 * activate read events for linked connections. */
679 struct timeval tv = { 0, 0 };
680 tor_event_base_loopexit(tor_libevent_get_base(), &tv);
682 } else {
683 tor_assert(smartlist_contains(active_linked_connection_lst, conn));
687 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
688 * connection, if is currently doing so. Called by connection_stop_reading,
689 * connection_stop_writing, and connection_read. */
690 void
691 connection_stop_reading_from_linked_conn(connection_t *conn)
693 tor_assert(conn);
694 tor_assert(conn->linked == 1);
696 if (conn->active_on_link) {
697 conn->active_on_link = 0;
698 /* FFFF We could keep an index here so we can smartlist_del
699 * cleanly. On the other hand, this doesn't show up on profiles,
700 * so let's leave it alone for now. */
701 smartlist_remove(active_linked_connection_lst, conn);
702 } else {
703 tor_assert(!smartlist_contains(active_linked_connection_lst, conn));
707 /** Close all connections that have been scheduled to get closed. */
708 STATIC void
709 close_closeable_connections(void)
711 int i;
712 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
713 connection_t *conn = smartlist_get(closeable_connection_lst, i);
714 if (conn->conn_array_index < 0) {
715 connection_unlink(conn); /* blow it away right now */
716 } else {
717 if (!conn_close_if_marked(conn->conn_array_index))
718 ++i;
723 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
724 * some data to read. */
725 static void
726 conn_read_callback(evutil_socket_t fd, short event, void *_conn)
728 connection_t *conn = _conn;
729 (void)fd;
730 (void)event;
732 log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
734 /* assert_connection_ok(conn, time(NULL)); */
736 if (connection_handle_read(conn) < 0) {
737 if (!conn->marked_for_close) {
738 #ifndef _WIN32
739 log_warn(LD_BUG,"Unhandled error on read for %s connection "
740 "(fd %d); removing",
741 conn_type_to_string(conn->type), (int)conn->s);
742 tor_fragile_assert();
743 #endif
744 if (CONN_IS_EDGE(conn))
745 connection_edge_end_errno(TO_EDGE_CONN(conn));
746 connection_mark_for_close(conn);
749 assert_connection_ok(conn, time(NULL));
751 if (smartlist_len(closeable_connection_lst))
752 close_closeable_connections();
755 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
756 * some data to write. */
757 static void
758 conn_write_callback(evutil_socket_t fd, short events, void *_conn)
760 connection_t *conn = _conn;
761 (void)fd;
762 (void)events;
764 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
765 (int)conn->s));
767 /* assert_connection_ok(conn, time(NULL)); */
769 if (connection_handle_write(conn, 0) < 0) {
770 if (!conn->marked_for_close) {
771 /* this connection is broken. remove it. */
772 log_fn(LOG_WARN,LD_BUG,
773 "unhandled error on write for %s connection (fd %d); removing",
774 conn_type_to_string(conn->type), (int)conn->s);
775 tor_fragile_assert();
776 if (CONN_IS_EDGE(conn)) {
777 /* otherwise we cry wolf about duplicate close */
778 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
779 if (!edge_conn->end_reason)
780 edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
781 edge_conn->edge_has_sent_end = 1;
783 connection_close_immediate(conn); /* So we don't try to flush. */
784 connection_mark_for_close(conn);
787 assert_connection_ok(conn, time(NULL));
789 if (smartlist_len(closeable_connection_lst))
790 close_closeable_connections();
793 /** If the connection at connection_array[i] is marked for close, then:
794 * - If it has data that it wants to flush, try to flush it.
795 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
796 * true, then leave the connection open and return.
797 * - Otherwise, remove the connection from connection_array and from
798 * all other lists, close it, and free it.
799 * Returns 1 if the connection was closed, 0 otherwise.
801 static int
802 conn_close_if_marked(int i)
804 connection_t *conn;
805 int retval;
806 time_t now;
808 conn = smartlist_get(connection_array, i);
809 if (!conn->marked_for_close)
810 return 0; /* nothing to see here, move along */
811 now = time(NULL);
812 assert_connection_ok(conn, now);
813 /* assert_all_pending_dns_resolves_ok(); */
815 #ifdef USE_BUFFEREVENTS
816 if (conn->bufev) {
817 if (conn->hold_open_until_flushed &&
818 evbuffer_get_length(bufferevent_get_output(conn->bufev))) {
819 /* don't close yet. */
820 return 0;
822 if (conn->linked_conn && ! conn->linked_conn->marked_for_close) {
823 /* We need to do this explicitly so that the linked connection
824 * notices that there was an EOF. */
825 bufferevent_flush(conn->bufev, EV_WRITE, BEV_FINISHED);
828 #endif
830 log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
831 conn->s);
833 /* If the connection we are about to close was trying to connect to
834 a proxy server and failed, the client won't be able to use that
835 proxy. We should warn the user about this. */
836 if (conn->proxy_state == PROXY_INFANT)
837 log_failed_proxy_connection(conn);
839 IF_HAS_BUFFEREVENT(conn, goto unlink);
840 if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
841 connection_wants_to_flush(conn)) {
842 /* s == -1 means it's an incomplete edge connection, or that the socket
843 * has already been closed as unflushable. */
844 ssize_t sz = connection_bucket_write_limit(conn, now);
845 if (!conn->hold_open_until_flushed)
846 log_info(LD_NET,
847 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
848 "to flush %d bytes. (Marked at %s:%d)",
849 escaped_safe_str_client(conn->address),
850 (int)conn->s, conn_type_to_string(conn->type), conn->state,
851 (int)conn->outbuf_flushlen,
852 conn->marked_for_close_file, conn->marked_for_close);
853 if (conn->linked_conn) {
854 retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
855 &conn->outbuf_flushlen);
856 if (retval >= 0) {
857 /* The linked conn will notice that it has data when it notices that
858 * we're gone. */
859 connection_start_reading_from_linked_conn(conn->linked_conn);
861 log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
862 "%d left; flushlen %d; wants-to-flush==%d", retval,
863 (int)connection_get_outbuf_len(conn),
864 (int)conn->outbuf_flushlen,
865 connection_wants_to_flush(conn));
866 } else if (connection_speaks_cells(conn)) {
867 if (conn->state == OR_CONN_STATE_OPEN) {
868 retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
869 &conn->outbuf_flushlen);
870 } else
871 retval = -1; /* never flush non-open broken tls connections */
872 } else {
873 retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
875 if (retval >= 0 && /* Technically, we could survive things like
876 TLS_WANT_WRITE here. But don't bother for now. */
877 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
878 if (retval > 0) {
879 LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
880 "Holding conn (fd %d) open for more flushing.",
881 (int)conn->s));
882 conn->timestamp_lastwritten = now; /* reset so we can flush more */
883 } else if (sz == 0) {
884 /* Also, retval==0. If we get here, we didn't want to write anything
885 * (because of rate-limiting) and we didn't. */
887 /* Connection must flush before closing, but it's being rate-limited.
888 * Let's remove from Libevent, and mark it as blocked on bandwidth
889 * so it will be re-added on next token bucket refill. Prevents
890 * busy Libevent loops where we keep ending up here and returning
891 * 0 until we are no longer blocked on bandwidth.
893 if (connection_is_writing(conn)) {
894 conn->write_blocked_on_bw = 1;
895 connection_stop_writing(conn);
897 if (connection_is_reading(conn)) {
898 /* XXXX024 We should make this code unreachable; if a connection is
899 * marked for close and flushing, there is no point in reading to it
900 * at all. Further, checking at this point is a bit of a hack: it
901 * would make much more sense to react in
902 * connection_handle_read_impl, or to just stop reading in
903 * mark_and_flush */
904 #if 0
905 #define MARKED_READING_RATE 180
906 static ratelim_t marked_read_lim = RATELIM_INIT(MARKED_READING_RATE);
907 char *m;
908 if ((m = rate_limit_log(&marked_read_lim, now))) {
909 log_warn(LD_BUG, "Marked connection (fd %d, type %s, state %s) "
910 "is still reading; that shouldn't happen.%s",
911 (int)conn->s, conn_type_to_string(conn->type),
912 conn_state_to_string(conn->type, conn->state), m);
913 tor_free(m);
915 #endif
916 conn->read_blocked_on_bw = 1;
917 connection_stop_reading(conn);
920 return 0;
922 if (connection_wants_to_flush(conn)) {
923 log_fn(LOG_INFO, LD_NET, "We stalled too much while trying to write %d "
924 "bytes to address %s. If this happens a lot, either "
925 "something is wrong with your network connection, or "
926 "something is wrong with theirs. "
927 "(fd %d, type %s, state %d, marked at %s:%d).",
928 (int)connection_get_outbuf_len(conn),
929 escaped_safe_str_client(conn->address),
930 (int)conn->s, conn_type_to_string(conn->type), conn->state,
931 conn->marked_for_close_file,
932 conn->marked_for_close);
936 #ifdef USE_BUFFEREVENTS
937 unlink:
938 #endif
939 connection_unlink(conn); /* unlink, remove, free */
940 return 1;
943 /** We've just tried every dirserver we know about, and none of
944 * them were reachable. Assume the network is down. Change state
945 * so next time an application connection arrives we'll delay it
946 * and try another directory fetch. Kill off all the circuit_wait
947 * streams that are waiting now, since they will all timeout anyway.
949 void
950 directory_all_unreachable(time_t now)
952 connection_t *conn;
953 (void)now;
955 stats_n_seconds_working=0; /* reset it */
957 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
958 AP_CONN_STATE_CIRCUIT_WAIT))) {
959 entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
960 log_notice(LD_NET,
961 "Is your network connection down? "
962 "Failing connection to '%s:%d'.",
963 safe_str_client(entry_conn->socks_request->address),
964 entry_conn->socks_request->port);
965 connection_mark_unattached_ap(entry_conn,
966 END_STREAM_REASON_NET_UNREACHABLE);
968 control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
971 /** This function is called whenever we successfully pull down some new
972 * network statuses or server descriptors. */
973 void
974 directory_info_has_arrived(time_t now, int from_cache)
976 const or_options_t *options = get_options();
978 if (!router_have_minimum_dir_info()) {
979 int quiet = from_cache ||
980 directory_too_idle_to_fetch_descriptors(options, now);
981 tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
982 "I learned some more directory information, but not enough to "
983 "build a circuit: %s", get_dir_info_status_string());
984 update_all_descriptor_downloads(now);
985 return;
986 } else {
987 if (directory_fetches_from_authorities(options)) {
988 update_all_descriptor_downloads(now);
991 /* if we have enough dir info, then update our guard status with
992 * whatever we just learned. */
993 entry_guards_compute_status(options, now);
994 /* Don't even bother trying to get extrainfo until the rest of our
995 * directory info is up-to-date */
996 if (options->DownloadExtraInfo)
997 update_extrainfo_downloads(now);
1000 if (server_mode(options) && !net_is_disabled() && !from_cache &&
1001 (can_complete_circuit || !any_predicted_circuits(now)))
1002 consider_testing_reachability(1, 1);
1005 /** Perform regular maintenance tasks for a single connection. This
1006 * function gets run once per second per connection by run_scheduled_events.
1008 static void
1009 run_connection_housekeeping(int i, time_t now)
1011 cell_t cell;
1012 connection_t *conn = smartlist_get(connection_array, i);
1013 const or_options_t *options = get_options();
1014 or_connection_t *or_conn;
1015 channel_t *chan = NULL;
1016 int have_any_circuits;
1017 int past_keepalive =
1018 now >= conn->timestamp_lastwritten + options->KeepalivePeriod;
1020 if (conn->outbuf && !connection_get_outbuf_len(conn) &&
1021 conn->type == CONN_TYPE_OR)
1022 TO_OR_CONN(conn)->timestamp_lastempty = now;
1024 if (conn->marked_for_close) {
1025 /* nothing to do here */
1026 return;
1029 /* Expire any directory connections that haven't been active (sent
1030 * if a server or received if a client) for 5 min */
1031 if (conn->type == CONN_TYPE_DIR &&
1032 ((DIR_CONN_IS_SERVER(conn) &&
1033 conn->timestamp_lastwritten
1034 + options->TestingDirConnectionMaxStall < now) ||
1035 (!DIR_CONN_IS_SERVER(conn) &&
1036 conn->timestamp_lastread
1037 + options->TestingDirConnectionMaxStall < now))) {
1038 log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
1039 (int)conn->s, conn->purpose);
1040 /* This check is temporary; it's to let us know whether we should consider
1041 * parsing partial serverdesc responses. */
1042 if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
1043 connection_get_inbuf_len(conn) >= 1024) {
1044 log_info(LD_DIR,"Trying to extract information from wedged server desc "
1045 "download.");
1046 connection_dir_reached_eof(TO_DIR_CONN(conn));
1047 } else {
1048 connection_mark_for_close(conn);
1050 return;
1053 if (!connection_speaks_cells(conn))
1054 return; /* we're all done here, the rest is just for OR conns */
1056 /* If we haven't written to an OR connection for a while, then either nuke
1057 the connection or send a keepalive, depending. */
1059 or_conn = TO_OR_CONN(conn);
1060 #ifdef USE_BUFFEREVENTS
1061 tor_assert(conn->bufev);
1062 #else
1063 tor_assert(conn->outbuf);
1064 #endif
1066 chan = TLS_CHAN_TO_BASE(or_conn->chan);
1067 tor_assert(chan);
1069 if (channel_num_circuits(chan) != 0) {
1070 have_any_circuits = 1;
1071 chan->timestamp_last_had_circuits = now;
1072 } else {
1073 have_any_circuits = 0;
1076 if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan)) &&
1077 ! have_any_circuits) {
1078 /* It's bad for new circuits, and has no unmarked circuits on it:
1079 * mark it now. */
1080 log_info(LD_OR,
1081 "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1082 (int)conn->s, conn->address, conn->port);
1083 if (conn->state == OR_CONN_STATE_CONNECTING)
1084 connection_or_connect_failed(TO_OR_CONN(conn),
1085 END_OR_CONN_REASON_TIMEOUT,
1086 "Tor gave up on the connection");
1087 connection_or_close_normally(TO_OR_CONN(conn), 1);
1088 } else if (!connection_state_is_open(conn)) {
1089 if (past_keepalive) {
1090 /* We never managed to actually get this connection open and happy. */
1091 log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
1092 (int)conn->s,conn->address, conn->port);
1093 connection_or_close_normally(TO_OR_CONN(conn), 0);
1095 } else if (we_are_hibernating() &&
1096 ! have_any_circuits &&
1097 !connection_get_outbuf_len(conn)) {
1098 /* We're hibernating, there's no circuits, and nothing to flush.*/
1099 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
1100 "[Hibernating or exiting].",
1101 (int)conn->s,conn->address, conn->port);
1102 connection_or_close_normally(TO_OR_CONN(conn), 1);
1103 } else if (!have_any_circuits &&
1104 now - or_conn->idle_timeout >=
1105 chan->timestamp_last_had_circuits) {
1106 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
1107 "[no circuits for %d; timeout %d; %scanonical].",
1108 (int)conn->s, conn->address, conn->port,
1109 (int)(now - chan->timestamp_last_had_circuits),
1110 or_conn->idle_timeout,
1111 or_conn->is_canonical ? "" : "non");
1112 connection_or_close_normally(TO_OR_CONN(conn), 0);
1113 } else if (
1114 now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
1115 now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
1116 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
1117 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1118 "flush; %d seconds since last write)",
1119 (int)conn->s, conn->address, conn->port,
1120 (int)connection_get_outbuf_len(conn),
1121 (int)(now-conn->timestamp_lastwritten));
1122 connection_or_close_normally(TO_OR_CONN(conn), 0);
1123 } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
1124 /* send a padding cell */
1125 log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
1126 conn->address, conn->port);
1127 memset(&cell,0,sizeof(cell_t));
1128 cell.command = CELL_PADDING;
1129 connection_or_write_cell_to_buf(&cell, or_conn);
1133 /** Honor a NEWNYM request: make future requests unlinkable to past
1134 * requests. */
1135 static void
1136 signewnym_impl(time_t now)
1138 const or_options_t *options = get_options();
1139 if (!proxy_mode(options)) {
1140 log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
1141 "is disabled.");
1142 return;
1145 circuit_mark_all_dirty_circs_as_unusable();
1146 addressmap_clear_transient();
1147 rend_client_purge_state();
1148 time_of_last_signewnym = now;
1149 signewnym_is_pending = 0;
1151 ++newnym_epoch;
1153 control_event_signal(SIGNEWNYM);
1156 /** Return the number of times that signewnym has been called. */
1157 unsigned
1158 get_signewnym_epoch(void)
1160 return newnym_epoch;
1163 static time_t time_to_check_descriptor = 0;
1165 * Update our schedule so that we'll check whether we need to update our
1166 * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
1167 * seconds.
1169 void
1170 reschedule_descriptor_update_check(void)
1172 time_to_check_descriptor = 0;
1175 /** Perform regular maintenance tasks. This function gets run once per
1176 * second by second_elapsed_callback().
1178 static void
1179 run_scheduled_events(time_t now)
1181 static time_t last_rotated_x509_certificate = 0;
1182 static time_t time_to_check_v3_certificate = 0;
1183 static time_t time_to_check_listeners = 0;
1184 static time_t time_to_download_networkstatus = 0;
1185 static time_t time_to_shrink_memory = 0;
1186 static time_t time_to_try_getting_descriptors = 0;
1187 static time_t time_to_reset_descriptor_failures = 0;
1188 static time_t time_to_add_entropy = 0;
1189 static time_t time_to_write_bridge_status_file = 0;
1190 static time_t time_to_downrate_stability = 0;
1191 static time_t time_to_save_stability = 0;
1192 static time_t time_to_clean_caches = 0;
1193 static time_t time_to_recheck_bandwidth = 0;
1194 static time_t time_to_check_for_expired_networkstatus = 0;
1195 static time_t time_to_write_stats_files = 0;
1196 static time_t time_to_write_bridge_stats = 0;
1197 static time_t time_to_check_port_forwarding = 0;
1198 static time_t time_to_launch_reachability_tests = 0;
1199 static int should_init_bridge_stats = 1;
1200 static time_t time_to_retry_dns_init = 0;
1201 static time_t time_to_next_heartbeat = 0;
1202 const or_options_t *options = get_options();
1204 int is_server = server_mode(options);
1205 int i;
1206 int have_dir_info;
1208 /* 0. See if we've been asked to shut down and our timeout has
1209 * expired; or if our bandwidth limits are exhausted and we
1210 * should hibernate; or if it's time to wake up from hibernation.
1212 consider_hibernation(now);
1214 /* 0b. If we've deferred a signewnym, make sure it gets handled
1215 * eventually. */
1216 if (signewnym_is_pending &&
1217 time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
1218 log_info(LD_CONTROL, "Honoring delayed NEWNYM request");
1219 signewnym_impl(now);
1222 /* 0c. If we've deferred log messages for the controller, handle them now */
1223 flush_pending_log_callbacks();
1225 /* 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
1226 * shut down and restart all cpuworkers, and update the directory if
1227 * necessary.
1229 if (is_server &&
1230 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
1231 log_info(LD_GENERAL,"Rotating onion key.");
1232 rotate_onion_key();
1233 cpuworkers_rotate();
1234 if (router_rebuild_descriptor(1)<0) {
1235 log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
1237 if (advertised_server_mode() && !options->DisableNetwork)
1238 router_upload_dir_desc_to_dirservers(0);
1241 if (!should_delay_dir_fetches(options, NULL) &&
1242 time_to_try_getting_descriptors < now) {
1243 update_all_descriptor_downloads(now);
1244 update_extrainfo_downloads(now);
1245 if (router_have_minimum_dir_info())
1246 time_to_try_getting_descriptors = now + LAZY_DESCRIPTOR_RETRY_INTERVAL;
1247 else
1248 time_to_try_getting_descriptors = now + GREEDY_DESCRIPTOR_RETRY_INTERVAL;
1251 if (time_to_reset_descriptor_failures < now) {
1252 router_reset_descriptor_download_failures();
1253 time_to_reset_descriptor_failures =
1254 now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
1257 if (options->UseBridges && !options->DisableNetwork)
1258 fetch_bridge_descriptors(options, now);
1260 /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1261 * TLS context. */
1262 if (!last_rotated_x509_certificate)
1263 last_rotated_x509_certificate = now;
1264 if (last_rotated_x509_certificate+MAX_SSL_KEY_LIFETIME_INTERNAL < now) {
1265 log_info(LD_GENERAL,"Rotating tls context.");
1266 if (router_initialize_tls_context() < 0) {
1267 log_warn(LD_BUG, "Error reinitializing TLS context");
1268 /* XXX is it a bug here, that we just keep going? -RD */
1270 last_rotated_x509_certificate = now;
1271 /* We also make sure to rotate the TLS connections themselves if they've
1272 * been up for too long -- but that's done via is_bad_for_new_circs in
1273 * connection_run_housekeeping() above. */
1276 if (time_to_add_entropy < now) {
1277 if (time_to_add_entropy) {
1278 /* We already seeded once, so don't die on failure. */
1279 crypto_seed_rng(0);
1281 /** How often do we add more entropy to OpenSSL's RNG pool? */
1282 #define ENTROPY_INTERVAL (60*60)
1283 time_to_add_entropy = now + ENTROPY_INTERVAL;
1286 /* 1c. If we have to change the accounting interval or record
1287 * bandwidth used in this accounting interval, do so. */
1288 if (accounting_is_enabled(options))
1289 accounting_run_housekeeping(now);
1291 if (time_to_launch_reachability_tests < now &&
1292 (authdir_mode_tests_reachability(options)) &&
1293 !net_is_disabled()) {
1294 time_to_launch_reachability_tests = now + REACHABILITY_TEST_INTERVAL;
1295 /* try to determine reachability of the other Tor relays */
1296 dirserv_test_reachability(now);
1299 /* 1d. Periodically, we discount older stability information so that new
1300 * stability info counts more, and save the stability information to disk as
1301 * appropriate. */
1302 if (time_to_downrate_stability < now)
1303 time_to_downrate_stability = rep_hist_downrate_old_runs(now);
1304 if (authdir_mode_tests_reachability(options)) {
1305 if (time_to_save_stability < now) {
1306 if (time_to_save_stability && rep_hist_record_mtbf_data(now, 1)<0) {
1307 log_warn(LD_GENERAL, "Couldn't store mtbf data.");
1309 #define SAVE_STABILITY_INTERVAL (30*60)
1310 time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
1314 /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
1315 * close to expiring and warn the admin if it is. */
1316 if (time_to_check_v3_certificate < now) {
1317 v3_authority_check_key_expiry();
1318 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
1319 time_to_check_v3_certificate = now + CHECK_V3_CERTIFICATE_INTERVAL;
1322 /* 1f. Check whether our networkstatus has expired.
1324 if (time_to_check_for_expired_networkstatus < now) {
1325 networkstatus_t *ns = networkstatus_get_latest_consensus();
1326 /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
1327 * networkstatus_get_reasonably_live_consensus(), but that value is way
1328 * way too high. Arma: is the bridge issue there resolved yet? -NM */
1329 #define NS_EXPIRY_SLOP (24*60*60)
1330 if (ns && ns->valid_until < now+NS_EXPIRY_SLOP &&
1331 router_have_minimum_dir_info()) {
1332 router_dir_info_changed();
1334 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1335 time_to_check_for_expired_networkstatus = now + CHECK_EXPIRED_NS_INTERVAL;
1338 /* 1g. Check whether we should write statistics to disk.
1340 if (time_to_write_stats_files < now) {
1341 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1342 time_t next_time_to_write_stats_files = (time_to_write_stats_files > 0 ?
1343 time_to_write_stats_files : now) + CHECK_WRITE_STATS_INTERVAL;
1344 if (options->CellStatistics) {
1345 time_t next_write =
1346 rep_hist_buffer_stats_write(time_to_write_stats_files);
1347 if (next_write && next_write < next_time_to_write_stats_files)
1348 next_time_to_write_stats_files = next_write;
1350 if (options->DirReqStatistics) {
1351 time_t next_write = geoip_dirreq_stats_write(time_to_write_stats_files);
1352 if (next_write && next_write < next_time_to_write_stats_files)
1353 next_time_to_write_stats_files = next_write;
1355 if (options->EntryStatistics) {
1356 time_t next_write = geoip_entry_stats_write(time_to_write_stats_files);
1357 if (next_write && next_write < next_time_to_write_stats_files)
1358 next_time_to_write_stats_files = next_write;
1360 if (options->ExitPortStatistics) {
1361 time_t next_write = rep_hist_exit_stats_write(time_to_write_stats_files);
1362 if (next_write && next_write < next_time_to_write_stats_files)
1363 next_time_to_write_stats_files = next_write;
1365 if (options->ConnDirectionStatistics) {
1366 time_t next_write = rep_hist_conn_stats_write(time_to_write_stats_files);
1367 if (next_write && next_write < next_time_to_write_stats_files)
1368 next_time_to_write_stats_files = next_write;
1370 if (options->BridgeAuthoritativeDir) {
1371 time_t next_write = rep_hist_desc_stats_write(time_to_write_stats_files);
1372 if (next_write && next_write < next_time_to_write_stats_files)
1373 next_time_to_write_stats_files = next_write;
1375 time_to_write_stats_files = next_time_to_write_stats_files;
1378 /* 1h. Check whether we should write bridge statistics to disk.
1380 if (should_record_bridge_info(options)) {
1381 if (time_to_write_bridge_stats < now) {
1382 if (should_init_bridge_stats) {
1383 /* (Re-)initialize bridge statistics. */
1384 geoip_bridge_stats_init(now);
1385 time_to_write_bridge_stats = now + WRITE_STATS_INTERVAL;
1386 should_init_bridge_stats = 0;
1387 } else {
1388 /* Possibly write bridge statistics to disk and ask when to write
1389 * them next time. */
1390 time_to_write_bridge_stats = geoip_bridge_stats_write(
1391 time_to_write_bridge_stats);
1394 } else if (!should_init_bridge_stats) {
1395 /* Bridge mode was turned off. Ensure that stats are re-initialized
1396 * next time bridge mode is turned on. */
1397 should_init_bridge_stats = 1;
1400 /* Remove old information from rephist and the rend cache. */
1401 if (time_to_clean_caches < now) {
1402 rep_history_clean(now - options->RephistTrackTime);
1403 rend_cache_clean(now);
1404 rend_cache_clean_v2_descs_as_dir(now);
1405 microdesc_cache_rebuild(NULL, 0);
1406 #define CLEAN_CACHES_INTERVAL (30*60)
1407 time_to_clean_caches = now + CLEAN_CACHES_INTERVAL;
1410 #define RETRY_DNS_INTERVAL (10*60)
1411 /* If we're a server and initializing dns failed, retry periodically. */
1412 if (time_to_retry_dns_init < now) {
1413 time_to_retry_dns_init = now + RETRY_DNS_INTERVAL;
1414 if (is_server && has_dns_init_failed())
1415 dns_init();
1418 /* 2. Periodically, we consider force-uploading our descriptor
1419 * (if we've passed our internal checks). */
1421 /** How often do we check whether part of our router info has changed in a
1422 * way that would require an upload? That includes checking whether our IP
1423 * address has changed. */
1424 #define CHECK_DESCRIPTOR_INTERVAL (60)
1426 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1427 * one is inaccurate. */
1428 if (time_to_check_descriptor < now && !options->DisableNetwork) {
1429 static int dirport_reachability_count = 0;
1430 time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
1431 check_descriptor_bandwidth_changed(now);
1432 check_descriptor_ipaddress_changed(now);
1433 mark_my_descriptor_dirty_if_too_old(now);
1434 consider_publishable_server(0);
1435 /* also, check religiously for reachability, if it's within the first
1436 * 20 minutes of our uptime. */
1437 if (is_server &&
1438 (can_complete_circuit || !any_predicted_circuits(now)) &&
1439 !we_are_hibernating()) {
1440 if (stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1441 consider_testing_reachability(1, dirport_reachability_count==0);
1442 if (++dirport_reachability_count > 5)
1443 dirport_reachability_count = 0;
1444 } else if (time_to_recheck_bandwidth < now) {
1445 /* If we haven't checked for 12 hours and our bandwidth estimate is
1446 * low, do another bandwidth test. This is especially important for
1447 * bridges, since they might go long periods without much use. */
1448 const routerinfo_t *me = router_get_my_routerinfo();
1449 if (time_to_recheck_bandwidth && me &&
1450 me->bandwidthcapacity < me->bandwidthrate &&
1451 me->bandwidthcapacity < 51200) {
1452 reset_bandwidth_test();
1454 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1455 time_to_recheck_bandwidth = now + BANDWIDTH_RECHECK_INTERVAL;
1459 /* If any networkstatus documents are no longer recent, we need to
1460 * update all the descriptors' running status. */
1461 /* Remove dead routers. */
1462 routerlist_remove_old_routers();
1465 /* 2c. Every minute (or every second if TestingTorNetwork), check
1466 * whether we want to download any networkstatus documents. */
1468 /* How often do we check whether we should download network status
1469 * documents? */
1470 #define networkstatus_dl_check_interval(o) ((o)->TestingTorNetwork ? 1 : 60)
1472 if (!should_delay_dir_fetches(options, NULL) &&
1473 time_to_download_networkstatus < now) {
1474 time_to_download_networkstatus =
1475 now + networkstatus_dl_check_interval(options);
1476 update_networkstatus_downloads(now);
1479 /* 2c. Let directory voting happen. */
1480 if (authdir_mode_v3(options))
1481 dirvote_act(options, now);
1483 /* 3a. Every second, we examine pending circuits and prune the
1484 * ones which have been pending for more than a few seconds.
1485 * We do this before step 4, so it can try building more if
1486 * it's not comfortable with the number of available circuits.
1488 /* (If our circuit build timeout can ever become lower than a second (which
1489 * it can't, currently), we should do this more often.) */
1490 circuit_expire_building();
1492 /* 3b. Also look at pending streams and prune the ones that 'began'
1493 * a long time ago but haven't gotten a 'connected' yet.
1494 * Do this before step 4, so we can put them back into pending
1495 * state to be picked up by the new circuit.
1497 connection_ap_expire_beginning();
1499 /* 3c. And expire connections that we've held open for too long.
1501 connection_expire_held_open();
1503 /* 3d. And every 60 seconds, we relaunch listeners if any died. */
1504 if (!net_is_disabled() && time_to_check_listeners < now) {
1505 retry_all_listeners(NULL, NULL, 0);
1506 time_to_check_listeners = now+60;
1509 /* 4. Every second, we try a new circuit if there are no valid
1510 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1511 * that became dirty more than MaxCircuitDirtiness seconds ago,
1512 * and we make a new circ if there are no clean circuits.
1514 have_dir_info = router_have_minimum_dir_info();
1515 if (have_dir_info && !net_is_disabled()) {
1516 circuit_build_needed_circs(now);
1517 } else {
1518 circuit_expire_old_circs_as_needed(now);
1521 /* every 10 seconds, but not at the same second as other such events */
1522 if (now % 10 == 5)
1523 circuit_expire_old_circuits_serverside(now);
1525 /* 5. We do housekeeping for each connection... */
1526 connection_or_set_bad_connections(NULL, 0);
1527 for (i=0;i<smartlist_len(connection_array);i++) {
1528 run_connection_housekeeping(i, now);
1530 if (time_to_shrink_memory < now) {
1531 SMARTLIST_FOREACH(connection_array, connection_t *, conn, {
1532 if (conn->outbuf)
1533 buf_shrink(conn->outbuf);
1534 if (conn->inbuf)
1535 buf_shrink(conn->inbuf);
1537 #ifdef ENABLE_MEMPOOL
1538 clean_cell_pool();
1539 #endif /* ENABLE_MEMPOOL */
1540 buf_shrink_freelists(0);
1541 /** How often do we check buffers and pools for empty space that can be
1542 * deallocated? */
1543 #define MEM_SHRINK_INTERVAL (60)
1544 time_to_shrink_memory = now + MEM_SHRINK_INTERVAL;
1547 /* 6. And remove any marked circuits... */
1548 circuit_close_all_marked();
1550 /* 7. And upload service descriptors if necessary. */
1551 if (can_complete_circuit && !net_is_disabled()) {
1552 rend_consider_services_upload(now);
1553 rend_consider_descriptor_republication();
1556 /* 8. and blow away any connections that need to die. have to do this now,
1557 * because if we marked a conn for close and left its socket -1, then
1558 * we'll pass it to poll/select and bad things will happen.
1560 close_closeable_connections();
1562 /* 8b. And if anything in our state is ready to get flushed to disk, we
1563 * flush it. */
1564 or_state_save(now);
1566 /* 8c. Do channel cleanup just like for connections */
1567 channel_run_cleanup();
1568 channel_listener_run_cleanup();
1570 /* 9. and if we're an exit node, check whether our DNS is telling stories
1571 * to us. */
1572 if (!net_is_disabled() &&
1573 public_server_mode(options) &&
1574 time_to_check_for_correct_dns < now &&
1575 ! router_my_exit_policy_is_reject_star()) {
1576 if (!time_to_check_for_correct_dns) {
1577 time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
1578 } else {
1579 dns_launch_correctness_checks();
1580 time_to_check_for_correct_dns = now + 12*3600 +
1581 crypto_rand_int(12*3600);
1585 /* 10. write bridge networkstatus file to disk */
1586 if (options->BridgeAuthoritativeDir &&
1587 time_to_write_bridge_status_file < now) {
1588 networkstatus_dump_bridge_status_to_file(now);
1589 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
1590 time_to_write_bridge_status_file = now+BRIDGE_STATUSFILE_INTERVAL;
1593 /* 11. check the port forwarding app */
1594 if (!net_is_disabled() &&
1595 time_to_check_port_forwarding < now &&
1596 options->PortForwarding &&
1597 is_server) {
1598 #define PORT_FORWARDING_CHECK_INTERVAL 5
1599 smartlist_t *ports_to_forward = get_list_of_ports_to_forward();
1600 if (ports_to_forward) {
1601 tor_check_port_forwarding(options->PortForwardingHelper,
1602 ports_to_forward,
1603 now);
1605 SMARTLIST_FOREACH(ports_to_forward, char *, cp, tor_free(cp));
1606 smartlist_free(ports_to_forward);
1608 time_to_check_port_forwarding = now+PORT_FORWARDING_CHECK_INTERVAL;
1611 /* 11b. check pending unconfigured managed proxies */
1612 if (!net_is_disabled() && pt_proxies_configuration_pending())
1613 pt_configure_remaining_proxies();
1615 /* 12. write the heartbeat message */
1616 if (options->HeartbeatPeriod &&
1617 time_to_next_heartbeat <= now) {
1618 if (time_to_next_heartbeat) /* don't log the first heartbeat */
1619 log_heartbeat(now);
1620 time_to_next_heartbeat = now+options->HeartbeatPeriod;
1624 /** Timer: used to invoke second_elapsed_callback() once per second. */
1625 static periodic_timer_t *second_timer = NULL;
1626 /** Number of libevent errors in the last second: we die if we get too many. */
1627 static int n_libevent_errors = 0;
1629 /** Libevent callback: invoked once every second. */
1630 static void
1631 second_elapsed_callback(periodic_timer_t *timer, void *arg)
1633 /* XXXX This could be sensibly refactored into multiple callbacks, and we
1634 * could use Libevent's timers for this rather than checking the current
1635 * time against a bunch of timeouts every second. */
1636 static time_t current_second = 0;
1637 time_t now;
1638 size_t bytes_written;
1639 size_t bytes_read;
1640 int seconds_elapsed;
1641 const or_options_t *options = get_options();
1642 (void)timer;
1643 (void)arg;
1645 n_libevent_errors = 0;
1647 /* log_notice(LD_GENERAL, "Tick."); */
1648 now = time(NULL);
1649 update_approx_time(now);
1651 /* the second has rolled over. check more stuff. */
1652 seconds_elapsed = current_second ? (int)(now - current_second) : 0;
1653 #ifdef USE_BUFFEREVENTS
1655 uint64_t cur_read,cur_written;
1656 connection_get_rate_limit_totals(&cur_read, &cur_written);
1657 bytes_written = (size_t)(cur_written - stats_prev_n_written);
1658 bytes_read = (size_t)(cur_read - stats_prev_n_read);
1659 stats_n_bytes_read += bytes_read;
1660 stats_n_bytes_written += bytes_written;
1661 if (accounting_is_enabled(options) && seconds_elapsed >= 0)
1662 accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
1663 stats_prev_n_written = cur_written;
1664 stats_prev_n_read = cur_read;
1666 #else
1667 bytes_read = (size_t)(stats_n_bytes_read - stats_prev_n_read);
1668 bytes_written = (size_t)(stats_n_bytes_written - stats_prev_n_written);
1669 stats_prev_n_read = stats_n_bytes_read;
1670 stats_prev_n_written = stats_n_bytes_written;
1671 #endif
1673 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
1674 control_event_stream_bandwidth_used();
1675 control_event_conn_bandwidth_used();
1676 control_event_circ_bandwidth_used();
1677 control_event_circuit_cell_stats();
1679 if (server_mode(options) &&
1680 !net_is_disabled() &&
1681 seconds_elapsed > 0 &&
1682 can_complete_circuit &&
1683 stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
1684 (stats_n_seconds_working+seconds_elapsed) /
1685 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1686 /* every 20 minutes, check and complain if necessary */
1687 const routerinfo_t *me = router_get_my_routerinfo();
1688 if (me && !check_whether_orport_reachable()) {
1689 char *address = tor_dup_ip(me->addr);
1690 log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
1691 "its ORPort is reachable. Please check your firewalls, ports, "
1692 "address, /etc/hosts file, etc.",
1693 address, me->or_port);
1694 control_event_server_status(LOG_WARN,
1695 "REACHABILITY_FAILED ORADDRESS=%s:%d",
1696 address, me->or_port);
1697 tor_free(address);
1700 if (me && !check_whether_dirport_reachable()) {
1701 char *address = tor_dup_ip(me->addr);
1702 log_warn(LD_CONFIG,
1703 "Your server (%s:%d) has not managed to confirm that its "
1704 "DirPort is reachable. Please check your firewalls, ports, "
1705 "address, /etc/hosts file, etc.",
1706 address, me->dir_port);
1707 control_event_server_status(LOG_WARN,
1708 "REACHABILITY_FAILED DIRADDRESS=%s:%d",
1709 address, me->dir_port);
1710 tor_free(address);
1714 /** If more than this many seconds have elapsed, probably the clock
1715 * jumped: doesn't count. */
1716 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
1717 if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
1718 seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
1719 circuit_note_clock_jumped(seconds_elapsed);
1720 /* XXX if the time jumps *back* many months, do our events in
1721 * run_scheduled_events() recover? I don't think they do. -RD */
1722 } else if (seconds_elapsed > 0)
1723 stats_n_seconds_working += seconds_elapsed;
1725 run_scheduled_events(now);
1727 current_second = now; /* remember which second it is, for next time */
1730 #ifndef USE_BUFFEREVENTS
1731 /** Timer: used to invoke refill_callback(). */
1732 static periodic_timer_t *refill_timer = NULL;
1734 /** Libevent callback: invoked periodically to refill token buckets
1735 * and count r/w bytes. It is only used when bufferevents are disabled. */
1736 static void
1737 refill_callback(periodic_timer_t *timer, void *arg)
1739 static struct timeval current_millisecond;
1740 struct timeval now;
1742 size_t bytes_written;
1743 size_t bytes_read;
1744 int milliseconds_elapsed = 0;
1745 int seconds_rolled_over = 0;
1747 const or_options_t *options = get_options();
1749 (void)timer;
1750 (void)arg;
1752 tor_gettimeofday(&now);
1754 /* If this is our first time, no time has passed. */
1755 if (current_millisecond.tv_sec) {
1756 long mdiff = tv_mdiff(&current_millisecond, &now);
1757 if (mdiff > INT_MAX)
1758 mdiff = INT_MAX;
1759 milliseconds_elapsed = (int)mdiff;
1760 seconds_rolled_over = (int)(now.tv_sec - current_millisecond.tv_sec);
1763 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
1764 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
1766 stats_n_bytes_read += bytes_read;
1767 stats_n_bytes_written += bytes_written;
1768 if (accounting_is_enabled(options) && milliseconds_elapsed >= 0)
1769 accounting_add_bytes(bytes_read, bytes_written, seconds_rolled_over);
1771 if (milliseconds_elapsed > 0)
1772 connection_bucket_refill(milliseconds_elapsed, (time_t)now.tv_sec);
1774 stats_prev_global_read_bucket = global_read_bucket;
1775 stats_prev_global_write_bucket = global_write_bucket;
1777 current_millisecond = now; /* remember what time it is, for next time */
1779 #endif
1781 #ifndef _WIN32
1782 /** Called when a possibly ignorable libevent error occurs; ensures that we
1783 * don't get into an infinite loop by ignoring too many errors from
1784 * libevent. */
1785 static int
1786 got_libevent_error(void)
1788 if (++n_libevent_errors > 8) {
1789 log_err(LD_NET, "Too many libevent errors in one second; dying");
1790 return -1;
1792 return 0;
1794 #endif
1796 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
1798 /** Called when our IP address seems to have changed. <b>at_interface</b>
1799 * should be true if we detected a change in our interface, and false if we
1800 * detected a change in our published address. */
1801 void
1802 ip_address_changed(int at_interface)
1804 int server = server_mode(get_options());
1806 if (at_interface) {
1807 if (! server) {
1808 /* Okay, change our keys. */
1809 if (init_keys()<0)
1810 log_warn(LD_GENERAL, "Unable to rotate keys after IP change!");
1812 } else {
1813 if (server) {
1814 if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
1815 reset_bandwidth_test();
1816 stats_n_seconds_working = 0;
1817 router_reset_reachability();
1818 mark_my_descriptor_dirty("IP address changed");
1822 dns_servers_relaunch_checks();
1825 /** Forget what we've learned about the correctness of our DNS servers, and
1826 * start learning again. */
1827 void
1828 dns_servers_relaunch_checks(void)
1830 if (server_mode(get_options())) {
1831 dns_reset_correctness_checks();
1832 time_to_check_for_correct_dns = 0;
1836 /** Called when we get a SIGHUP: reload configuration files and keys,
1837 * retry all connections, and so on. */
1838 static int
1839 do_hup(void)
1841 const or_options_t *options = get_options();
1843 #ifdef USE_DMALLOC
1844 dmalloc_log_stats();
1845 dmalloc_log_changed(0, 1, 0, 0);
1846 #endif
1848 log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
1849 "resetting internal state.");
1850 if (accounting_is_enabled(options))
1851 accounting_record_bandwidth_usage(time(NULL), get_or_state());
1853 router_reset_warnings();
1854 routerlist_reset_warnings();
1855 /* first, reload config variables, in case they've changed */
1856 if (options->ReloadTorrcOnSIGHUP) {
1857 /* no need to provide argc/v, they've been cached in init_from_config */
1858 if (options_init_from_torrc(0, NULL) < 0) {
1859 log_err(LD_CONFIG,"Reading config failed--see warnings above. "
1860 "For usage, try -h.");
1861 return -1;
1863 options = get_options(); /* they have changed now */
1864 } else {
1865 char *msg = NULL;
1866 log_notice(LD_GENERAL, "Not reloading config file: the controller told "
1867 "us not to.");
1868 /* Make stuff get rescanned, reloaded, etc. */
1869 if (set_options((or_options_t*)options, &msg) < 0) {
1870 if (!msg)
1871 msg = tor_strdup("Unknown error");
1872 log_warn(LD_GENERAL, "Unable to re-set previous options: %s", msg);
1873 tor_free(msg);
1876 if (authdir_mode_handles_descs(options, -1)) {
1877 /* reload the approved-routers file */
1878 if (dirserv_load_fingerprint_file() < 0) {
1879 /* warnings are logged from dirserv_load_fingerprint_file() directly */
1880 log_info(LD_GENERAL, "Error reloading fingerprints. "
1881 "Continuing with old list.");
1885 /* Rotate away from the old dirty circuits. This has to be done
1886 * after we've read the new options, but before we start using
1887 * circuits for directory fetches. */
1888 circuit_mark_all_dirty_circs_as_unusable();
1890 /* retry appropriate downloads */
1891 router_reset_status_download_failures();
1892 router_reset_descriptor_download_failures();
1893 if (!options->DisableNetwork)
1894 update_networkstatus_downloads(time(NULL));
1896 /* We'll retry routerstatus downloads in about 10 seconds; no need to
1897 * force a retry there. */
1899 if (server_mode(options)) {
1900 /* Restart cpuworker and dnsworker processes, so they get up-to-date
1901 * configuration options. */
1902 cpuworkers_rotate();
1903 dns_reset();
1905 return 0;
1908 /** Tor main loop. */
1910 do_main_loop(void)
1912 int loop_result;
1913 time_t now;
1915 /* initialize dns resolve map, spawn workers if needed */
1916 if (dns_init() < 0) {
1917 if (get_options()->ServerDNSAllowBrokenConfig)
1918 log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
1919 "Network not up yet? Will try again soon.");
1920 else {
1921 log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
1922 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
1926 #ifdef USE_BUFFEREVENTS
1927 log_warn(LD_GENERAL, "Tor was compiled with the --enable-bufferevents "
1928 "option. This is still experimental, and might cause strange "
1929 "bugs. If you want a more stable Tor, be sure to build without "
1930 "--enable-bufferevents.");
1931 #endif
1933 handle_signals(1);
1935 /* load the private keys, if we're supposed to have them, and set up the
1936 * TLS context. */
1937 if (! client_identity_key_is_set()) {
1938 if (init_keys() < 0) {
1939 log_err(LD_BUG,"Error initializing keys; exiting");
1940 return -1;
1944 #ifdef ENABLE_MEMPOOLS
1945 /* Set up the packed_cell_t memory pool. */
1946 init_cell_pool();
1947 #endif /* ENABLE_MEMPOOLS */
1949 /* Set up our buckets */
1950 connection_bucket_init();
1951 #ifndef USE_BUFFEREVENTS
1952 stats_prev_global_read_bucket = global_read_bucket;
1953 stats_prev_global_write_bucket = global_write_bucket;
1954 #endif
1956 /* initialize the bootstrap status events to know we're starting up */
1957 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
1959 if (trusted_dirs_reload_certs()) {
1960 log_warn(LD_DIR,
1961 "Couldn't load all cached v3 certificates. Starting anyway.");
1963 if (router_reload_consensus_networkstatus()) {
1964 return -1;
1966 /* load the routers file, or assign the defaults. */
1967 if (router_reload_router_list()) {
1968 return -1;
1970 /* load the networkstatuses. (This launches a download for new routers as
1971 * appropriate.)
1973 now = time(NULL);
1974 directory_info_has_arrived(now, 1);
1976 if (server_mode(get_options())) {
1977 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1978 cpu_init();
1981 /* set up once-a-second callback. */
1982 if (! second_timer) {
1983 struct timeval one_second;
1984 one_second.tv_sec = 1;
1985 one_second.tv_usec = 0;
1987 second_timer = periodic_timer_new(tor_libevent_get_base(),
1988 &one_second,
1989 second_elapsed_callback,
1990 NULL);
1991 tor_assert(second_timer);
1994 #ifndef USE_BUFFEREVENTS
1995 if (!refill_timer) {
1996 struct timeval refill_interval;
1997 int msecs = get_options()->TokenBucketRefillInterval;
1999 refill_interval.tv_sec = msecs/1000;
2000 refill_interval.tv_usec = (msecs%1000)*1000;
2002 refill_timer = periodic_timer_new(tor_libevent_get_base(),
2003 &refill_interval,
2004 refill_callback,
2005 NULL);
2006 tor_assert(refill_timer);
2008 #endif
2010 for (;;) {
2011 if (nt_service_is_stopping())
2012 return 0;
2014 #ifndef _WIN32
2015 /* Make it easier to tell whether libevent failure is our fault or not. */
2016 errno = 0;
2017 #endif
2018 /* All active linked conns should get their read events activated. */
2019 SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
2020 event_active(conn->read_event, EV_READ, 1));
2021 called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
2023 update_approx_time(time(NULL));
2025 /* poll until we have an event, or the second ends, or until we have
2026 * some active linked connections to trigger events for. */
2027 loop_result = event_base_loop(tor_libevent_get_base(),
2028 called_loop_once ? EVLOOP_ONCE : 0);
2030 /* let catch() handle things like ^c, and otherwise don't worry about it */
2031 if (loop_result < 0) {
2032 int e = tor_socket_errno(-1);
2033 /* let the program survive things like ^z */
2034 if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
2035 log_err(LD_NET,"libevent call with %s failed: %s [%d]",
2036 tor_libevent_get_method(), tor_socket_strerror(e), e);
2037 return -1;
2038 #ifndef _WIN32
2039 } else if (e == EINVAL) {
2040 log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
2041 if (got_libevent_error())
2042 return -1;
2043 #endif
2044 } else {
2045 if (ERRNO_IS_EINPROGRESS(e))
2046 log_warn(LD_BUG,
2047 "libevent call returned EINPROGRESS? Please report.");
2048 log_debug(LD_NET,"libevent call interrupted.");
2049 /* You can't trust the results of this poll(). Go back to the
2050 * top of the big for loop. */
2051 continue;
2057 #ifndef _WIN32 /* Only called when we're willing to use signals */
2058 /** Libevent callback: invoked when we get a signal.
2060 static void
2061 signal_callback(int fd, short events, void *arg)
2063 uintptr_t sig = (uintptr_t)arg;
2064 (void)fd;
2065 (void)events;
2067 process_signal(sig);
2069 #endif
2071 /** Do the work of acting on a signal received in <b>sig</b> */
2072 void
2073 process_signal(uintptr_t sig)
2075 switch (sig)
2077 case SIGTERM:
2078 log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
2079 tor_cleanup();
2080 exit(0);
2081 break;
2082 case SIGINT:
2083 if (!server_mode(get_options())) { /* do it now */
2084 log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
2085 tor_cleanup();
2086 exit(0);
2088 hibernate_begin_shutdown();
2089 break;
2090 #ifdef SIGPIPE
2091 case SIGPIPE:
2092 log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
2093 break;
2094 #endif
2095 case SIGUSR1:
2096 /* prefer to log it at INFO, but make sure we always see it */
2097 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
2098 control_event_signal(sig);
2099 break;
2100 case SIGUSR2:
2101 switch_logs_debug();
2102 log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
2103 "Send HUP to change back.");
2104 control_event_signal(sig);
2105 break;
2106 case SIGHUP:
2107 if (do_hup() < 0) {
2108 log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
2109 tor_cleanup();
2110 exit(1);
2112 control_event_signal(sig);
2113 break;
2114 #ifdef SIGCHLD
2115 case SIGCHLD:
2116 notify_pending_waitpid_callbacks();
2117 break;
2118 #endif
2119 case SIGNEWNYM: {
2120 time_t now = time(NULL);
2121 if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
2122 signewnym_is_pending = 1;
2123 log_notice(LD_CONTROL,
2124 "Rate limiting NEWNYM request: delaying by %d second(s)",
2125 (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
2126 } else {
2127 signewnym_impl(now);
2129 break;
2131 case SIGCLEARDNSCACHE:
2132 addressmap_clear_transient();
2133 control_event_signal(sig);
2134 break;
2138 /** Returns Tor's uptime. */
2139 MOCK_IMPL(long,
2140 get_uptime,(void))
2142 return stats_n_seconds_working;
2145 extern uint64_t rephist_total_alloc;
2146 extern uint32_t rephist_total_num;
2149 * Write current memory usage information to the log.
2151 static void
2152 dumpmemusage(int severity)
2154 connection_dump_buffer_mem_stats(severity);
2155 tor_log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
2156 U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
2157 dump_routerlist_mem_usage(severity);
2158 dump_cell_pool_usage(severity);
2159 dump_dns_mem_usage(severity);
2160 buf_dump_freelist_sizes(severity);
2161 tor_log_mallinfo(severity);
2164 /** Write all statistics to the log, with log level <b>severity</b>. Called
2165 * in response to a SIGUSR1. */
2166 static void
2167 dumpstats(int severity)
2169 time_t now = time(NULL);
2170 time_t elapsed;
2171 size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
2173 tor_log(severity, LD_GENERAL, "Dumping stats:");
2175 SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
2176 int i = conn_sl_idx;
2177 tor_log(severity, LD_GENERAL,
2178 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
2179 i, (int)conn->s, conn->type, conn_type_to_string(conn->type),
2180 conn->state, conn_state_to_string(conn->type, conn->state),
2181 (int)(now - conn->timestamp_created));
2182 if (!connection_is_listener(conn)) {
2183 tor_log(severity,LD_GENERAL,
2184 "Conn %d is to %s:%d.", i,
2185 safe_str_client(conn->address),
2186 conn->port);
2187 tor_log(severity,LD_GENERAL,
2188 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
2190 (int)connection_get_inbuf_len(conn),
2191 (int)buf_allocation(conn->inbuf),
2192 (int)(now - conn->timestamp_lastread));
2193 tor_log(severity,LD_GENERAL,
2194 "Conn %d: %d bytes waiting on outbuf "
2195 "(len %d, last written %d secs ago)",i,
2196 (int)connection_get_outbuf_len(conn),
2197 (int)buf_allocation(conn->outbuf),
2198 (int)(now - conn->timestamp_lastwritten));
2199 if (conn->type == CONN_TYPE_OR) {
2200 or_connection_t *or_conn = TO_OR_CONN(conn);
2201 if (or_conn->tls) {
2202 tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
2203 &wbuf_cap, &wbuf_len);
2204 tor_log(severity, LD_GENERAL,
2205 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
2206 "%d/%d bytes used on write buffer.",
2207 i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
2211 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
2212 * using this conn */
2213 } SMARTLIST_FOREACH_END(conn);
2215 channel_dumpstats(severity);
2216 channel_listener_dumpstats(severity);
2218 tor_log(severity, LD_NET,
2219 "Cells processed: "U64_FORMAT" padding\n"
2220 " "U64_FORMAT" create\n"
2221 " "U64_FORMAT" created\n"
2222 " "U64_FORMAT" relay\n"
2223 " ("U64_FORMAT" relayed)\n"
2224 " ("U64_FORMAT" delivered)\n"
2225 " "U64_FORMAT" destroy",
2226 U64_PRINTF_ARG(stats_n_padding_cells_processed),
2227 U64_PRINTF_ARG(stats_n_create_cells_processed),
2228 U64_PRINTF_ARG(stats_n_created_cells_processed),
2229 U64_PRINTF_ARG(stats_n_relay_cells_processed),
2230 U64_PRINTF_ARG(stats_n_relay_cells_relayed),
2231 U64_PRINTF_ARG(stats_n_relay_cells_delivered),
2232 U64_PRINTF_ARG(stats_n_destroy_cells_processed));
2233 if (stats_n_data_cells_packaged)
2234 tor_log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
2235 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
2236 U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
2237 if (stats_n_data_cells_received)
2238 tor_log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
2239 100*(U64_TO_DBL(stats_n_data_bytes_received) /
2240 U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
2242 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_TAP, "TAP");
2243 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_NTOR,"ntor");
2245 if (now - time_of_process_start >= 0)
2246 elapsed = now - time_of_process_start;
2247 else
2248 elapsed = 0;
2250 if (elapsed) {
2251 tor_log(severity, LD_NET,
2252 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
2253 U64_PRINTF_ARG(stats_n_bytes_read),
2254 (int)elapsed,
2255 (int) (stats_n_bytes_read/elapsed));
2256 tor_log(severity, LD_NET,
2257 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
2258 U64_PRINTF_ARG(stats_n_bytes_written),
2259 (int)elapsed,
2260 (int) (stats_n_bytes_written/elapsed));
2263 tor_log(severity, LD_NET, "--------------- Dumping memory information:");
2264 dumpmemusage(severity);
2266 rep_hist_dump_stats(now,severity);
2267 rend_service_dump_stats(severity);
2268 dump_pk_ops(severity);
2269 dump_distinct_digest_count(severity);
2272 /** Called by exit() as we shut down the process.
2274 static void
2275 exit_function(void)
2277 /* NOTE: If we ever daemonize, this gets called immediately. That's
2278 * okay for now, because we only use this on Windows. */
2279 #ifdef _WIN32
2280 WSACleanup();
2281 #endif
2284 /** Set up the signal handlers for either parent or child. */
2285 void
2286 handle_signals(int is_parent)
2288 #ifndef _WIN32 /* do signal stuff only on Unix */
2289 int i;
2290 static const int signals[] = {
2291 SIGINT, /* do a controlled slow shutdown */
2292 SIGTERM, /* to terminate now */
2293 SIGPIPE, /* otherwise SIGPIPE kills us */
2294 SIGUSR1, /* dump stats */
2295 SIGUSR2, /* go to loglevel debug */
2296 SIGHUP, /* to reload config, retry conns, etc */
2297 #ifdef SIGXFSZ
2298 SIGXFSZ, /* handle file-too-big resource exhaustion */
2299 #endif
2300 SIGCHLD, /* handle dns/cpu workers that exit */
2301 -1 };
2302 static struct event *signal_events[16]; /* bigger than it has to be. */
2303 if (is_parent) {
2304 for (i = 0; signals[i] >= 0; ++i) {
2305 signal_events[i] = tor_evsignal_new(
2306 tor_libevent_get_base(), signals[i], signal_callback,
2307 (void*)(uintptr_t)signals[i]);
2308 if (event_add(signal_events[i], NULL))
2309 log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
2310 signals[i]);
2312 } else {
2313 struct sigaction action;
2314 action.sa_flags = 0;
2315 sigemptyset(&action.sa_mask);
2316 action.sa_handler = SIG_IGN;
2317 sigaction(SIGINT, &action, NULL);
2318 sigaction(SIGTERM, &action, NULL);
2319 sigaction(SIGPIPE, &action, NULL);
2320 sigaction(SIGUSR1, &action, NULL);
2321 sigaction(SIGUSR2, &action, NULL);
2322 sigaction(SIGHUP, &action, NULL);
2323 #ifdef SIGXFSZ
2324 sigaction(SIGXFSZ, &action, NULL);
2325 #endif
2327 #else /* MS windows */
2328 (void)is_parent;
2329 #endif /* signal stuff */
2332 /** Main entry point for the Tor command-line client.
2335 tor_init(int argc, char *argv[])
2337 char progname[256];
2338 int quiet = 0;
2340 time_of_process_start = time(NULL);
2341 init_connection_lists();
2342 /* Have the log set up with our application name. */
2343 tor_snprintf(progname, sizeof(progname), "Tor %s", get_version());
2344 log_set_application_name(progname);
2346 /* Set up the crypto nice and early */
2347 if (crypto_early_init() < 0) {
2348 log_err(LD_GENERAL, "Unable to initialize the crypto subsystem!");
2349 return 1;
2352 /* Initialize the history structures. */
2353 rep_hist_init();
2354 /* Initialize the service cache. */
2355 rend_cache_init();
2356 addressmap_init(); /* Init the client dns cache. Do it always, since it's
2357 * cheap. */
2360 /* We search for the "quiet" option first, since it decides whether we
2361 * will log anything at all to the command line. */
2362 config_line_t *opts = NULL, *cmdline_opts = NULL;
2363 const config_line_t *cl;
2364 (void) config_parse_commandline(argc, argv, 1, &opts, &cmdline_opts);
2365 for (cl = cmdline_opts; cl; cl = cl->next) {
2366 if (!strcmp(cl->key, "--hush"))
2367 quiet = 1;
2368 if (!strcmp(cl->key, "--quiet") ||
2369 !strcmp(cl->key, "--dump-config"))
2370 quiet = 2;
2371 /* --version, --digests, and --help imply --hush */
2372 if (!strcmp(cl->key, "--version") || !strcmp(cl->key, "--digests") ||
2373 !strcmp(cl->key, "--list-torrc-options") ||
2374 !strcmp(cl->key, "--library-versions") ||
2375 !strcmp(cl->key, "-h") || !strcmp(cl->key, "--help")) {
2376 if (quiet < 1)
2377 quiet = 1;
2380 config_free_lines(opts);
2381 config_free_lines(cmdline_opts);
2384 /* give it somewhere to log to initially */
2385 switch (quiet) {
2386 case 2:
2387 /* no initial logging */
2388 break;
2389 case 1:
2390 add_temp_log(LOG_WARN);
2391 break;
2392 default:
2393 add_temp_log(LOG_NOTICE);
2395 quiet_level = quiet;
2398 const char *version = get_version();
2399 const char *bev_str =
2400 #ifdef USE_BUFFEREVENTS
2401 "(with bufferevents) ";
2402 #else
2404 #endif
2405 log_notice(LD_GENERAL, "Tor v%s %srunning on %s with Libevent %s, "
2406 "OpenSSL %s and Zlib %s.", version, bev_str,
2407 get_uname(),
2408 tor_libevent_get_version_str(),
2409 crypto_openssl_get_version_str(),
2410 tor_zlib_get_version_str());
2412 log_notice(LD_GENERAL, "Tor can't help you if you use it wrong! "
2413 "Learn how to be safe at "
2414 "https://www.torproject.org/download/download#warning");
2416 if (strstr(version, "alpha") || strstr(version, "beta"))
2417 log_notice(LD_GENERAL, "This version is not a stable Tor release. "
2418 "Expect more bugs than usual.");
2421 #ifdef NON_ANONYMOUS_MODE_ENABLED
2422 log_warn(LD_GENERAL, "This copy of Tor was compiled to run in a "
2423 "non-anonymous mode. It will provide NO ANONYMITY.");
2424 #endif
2426 if (network_init()<0) {
2427 log_err(LD_BUG,"Error initializing network; exiting.");
2428 return -1;
2430 atexit(exit_function);
2432 if (options_init_from_torrc(argc,argv) < 0) {
2433 log_err(LD_CONFIG,"Reading config failed--see warnings above.");
2434 return -1;
2437 #ifndef _WIN32
2438 if (geteuid()==0)
2439 log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
2440 "and you probably shouldn't.");
2441 #endif
2443 if (crypto_global_init(get_options()->HardwareAccel,
2444 get_options()->AccelName,
2445 get_options()->AccelDir)) {
2446 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
2447 return -1;
2449 stream_choice_seed_weak_rng();
2450 if (tor_init_libevent_rng() < 0) {
2451 log_warn(LD_NET, "Problem initializing libevent RNG.");
2454 return 0;
2457 /** A lockfile structure, used to prevent two Tors from messing with the
2458 * data directory at once. If this variable is non-NULL, we're holding
2459 * the lockfile. */
2460 static tor_lockfile_t *lockfile = NULL;
2462 /** Try to grab the lock file described in <b>options</b>, if we do not
2463 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
2464 * holding the lock, and exit if we can't get it after waiting. Otherwise,
2465 * return -1 if we can't get the lockfile. Return 0 on success.
2468 try_locking(const or_options_t *options, int err_if_locked)
2470 if (lockfile)
2471 return 0;
2472 else {
2473 char *fname = options_get_datadir_fname2_suffix(options, "lock",NULL,NULL);
2474 int already_locked = 0;
2475 tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
2476 tor_free(fname);
2477 if (!lf) {
2478 if (err_if_locked && already_locked) {
2479 int r;
2480 log_warn(LD_GENERAL, "It looks like another Tor process is running "
2481 "with the same data directory. Waiting 5 seconds to see "
2482 "if it goes away.");
2483 #ifndef _WIN32
2484 sleep(5);
2485 #else
2486 Sleep(5000);
2487 #endif
2488 r = try_locking(options, 0);
2489 if (r<0) {
2490 log_err(LD_GENERAL, "No, it's still there. Exiting.");
2491 exit(0);
2493 return r;
2495 return -1;
2497 lockfile = lf;
2498 return 0;
2502 /** Return true iff we've successfully acquired the lock file. */
2504 have_lockfile(void)
2506 return lockfile != NULL;
2509 /** If we have successfully acquired the lock file, release it. */
2510 void
2511 release_lockfile(void)
2513 if (lockfile) {
2514 tor_lockfile_unlock(lockfile);
2515 lockfile = NULL;
2519 /** Free all memory that we might have allocated somewhere.
2520 * If <b>postfork</b>, we are a worker process and we want to free
2521 * only the parts of memory that we won't touch. If !<b>postfork</b>,
2522 * Tor is shutting down and we should free everything.
2524 * Helps us find the real leaks with dmalloc and the like. Also valgrind
2525 * should then report 0 reachable in its leak report (in an ideal world --
2526 * in practice libevent, SSL, libc etc never quite free everything). */
2527 void
2528 tor_free_all(int postfork)
2530 if (!postfork) {
2531 evdns_shutdown(1);
2533 geoip_free_all();
2534 dirvote_free_all();
2535 routerlist_free_all();
2536 networkstatus_free_all();
2537 addressmap_free_all();
2538 dirserv_free_all();
2539 rend_service_free_all();
2540 rend_cache_free_all();
2541 rend_service_authorization_free_all();
2542 rep_hist_free_all();
2543 dns_free_all();
2544 clear_pending_onions();
2545 circuit_free_all();
2546 entry_guards_free_all();
2547 pt_free_all();
2548 channel_tls_free_all();
2549 channel_free_all();
2550 connection_free_all();
2551 buf_shrink_freelists(1);
2552 memarea_clear_freelist();
2553 nodelist_free_all();
2554 microdesc_free_all();
2555 ext_orport_free_all();
2556 control_free_all();
2557 sandbox_free_getaddrinfo_cache();
2558 if (!postfork) {
2559 config_free_all();
2560 or_state_free_all();
2561 router_free_all();
2562 policies_free_all();
2564 #ifdef ENABLE_MEMPOOLS
2565 free_cell_pool();
2566 #endif /* ENABLE_MEMPOOLS */
2567 if (!postfork) {
2568 tor_tls_free_all();
2569 #ifndef _WIN32
2570 tor_getpwnam(NULL);
2571 #endif
2573 /* stuff in main.c */
2575 smartlist_free(connection_array);
2576 smartlist_free(closeable_connection_lst);
2577 smartlist_free(active_linked_connection_lst);
2578 periodic_timer_free(second_timer);
2579 #ifndef USE_BUFFEREVENTS
2580 periodic_timer_free(refill_timer);
2581 #endif
2583 if (!postfork) {
2584 release_lockfile();
2586 /* Stuff in util.c and address.c*/
2587 if (!postfork) {
2588 escaped(NULL);
2589 esc_router_info(NULL);
2590 logs_free_all(); /* free log strings. do this last so logs keep working. */
2594 /** Do whatever cleanup is necessary before shutting Tor down. */
2595 void
2596 tor_cleanup(void)
2598 const or_options_t *options = get_options();
2599 if (options->command == CMD_RUN_TOR) {
2600 time_t now = time(NULL);
2601 /* Remove our pid file. We don't care if there was an error when we
2602 * unlink, nothing we could do about it anyways. */
2603 if (options->PidFile) {
2604 if (unlink(options->PidFile) != 0) {
2605 log_warn(LD_FS, "Couldn't unlink pid file %s: %s",
2606 options->PidFile, strerror(errno));
2609 if (options->ControlPortWriteToFile) {
2610 if (unlink(options->ControlPortWriteToFile) != 0) {
2611 log_warn(LD_FS, "Couldn't unlink control port file %s: %s",
2612 options->ControlPortWriteToFile,
2613 strerror(errno));
2616 if (accounting_is_enabled(options))
2617 accounting_record_bandwidth_usage(now, get_or_state());
2618 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
2619 or_state_save(now);
2620 if (authdir_mode_tests_reachability(options))
2621 rep_hist_record_mtbf_data(now, 0);
2623 #ifdef USE_DMALLOC
2624 dmalloc_log_stats();
2625 #endif
2626 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
2627 later, if it makes shutdown unacceptably slow. But for
2628 now, leave it here: it's helped us catch bugs in the
2629 past. */
2630 crypto_global_cleanup();
2631 #ifdef USE_DMALLOC
2632 dmalloc_log_unfreed();
2633 dmalloc_shutdown();
2634 #endif
2637 /** Read/create keys as needed, and echo our fingerprint to stdout. */
2638 static int
2639 do_list_fingerprint(void)
2641 char buf[FINGERPRINT_LEN+1];
2642 crypto_pk_t *k;
2643 const char *nickname = get_options()->Nickname;
2644 if (!server_mode(get_options())) {
2645 log_err(LD_GENERAL,
2646 "Clients don't have long-term identity keys. Exiting.");
2647 return -1;
2649 tor_assert(nickname);
2650 if (init_keys() < 0) {
2651 log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
2652 return -1;
2654 if (!(k = get_server_identity_key())) {
2655 log_err(LD_GENERAL,"Error: missing identity key.");
2656 return -1;
2658 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
2659 log_err(LD_BUG, "Error computing fingerprint");
2660 return -1;
2662 printf("%s %s\n", nickname, buf);
2663 return 0;
2666 /** Entry point for password hashing: take the desired password from
2667 * the command line, and print its salted hash to stdout. **/
2668 static void
2669 do_hash_password(void)
2672 char output[256];
2673 char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
2675 crypto_rand(key, S2K_SPECIFIER_LEN-1);
2676 key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
2677 secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
2678 get_options()->command_arg, strlen(get_options()->command_arg),
2679 key);
2680 base16_encode(output, sizeof(output), key, sizeof(key));
2681 printf("16:%s\n",output);
2684 /** Entry point for configuration dumping: write the configuration to
2685 * stdout. */
2686 static int
2687 do_dump_config(void)
2689 const or_options_t *options = get_options();
2690 const char *arg = options->command_arg;
2691 int how;
2692 char *opts;
2693 if (!strcmp(arg, "short")) {
2694 how = OPTIONS_DUMP_MINIMAL;
2695 } else if (!strcmp(arg, "non-builtin")) {
2696 how = OPTIONS_DUMP_DEFAULTS;
2697 } else if (!strcmp(arg, "full")) {
2698 how = OPTIONS_DUMP_ALL;
2699 } else {
2700 printf("%s is not a recognized argument to --dump-config. "
2701 "Please select 'short', 'non-builtin', or 'full'", arg);
2702 return -1;
2705 opts = options_dump(options, how);
2706 printf("%s", opts);
2707 tor_free(opts);
2709 return 0;
2712 #if defined (WINCE)
2714 find_flashcard_path(PWCHAR path, size_t size)
2716 WIN32_FIND_DATA d = {0};
2717 HANDLE h = NULL;
2719 if (!path)
2720 return -1;
2722 h = FindFirstFlashCard(&d);
2723 if (h == INVALID_HANDLE_VALUE)
2724 return -1;
2726 if (wcslen(d.cFileName) == 0) {
2727 FindClose(h);
2728 return -1;
2731 wcsncpy(path,d.cFileName,size);
2732 FindClose(h);
2733 return 0;
2735 #endif
2737 static void
2738 init_addrinfo(void)
2740 char hname[256];
2742 // host name to sandbox
2743 gethostname(hname, sizeof(hname));
2744 sandbox_add_addrinfo(hname);
2747 static sandbox_cfg_t*
2748 sandbox_init_filter(void)
2750 const or_options_t *options = get_options();
2751 sandbox_cfg_t *cfg = sandbox_cfg_new();
2752 int i;
2754 sandbox_cfg_allow_openat_filename(&cfg,
2755 get_datadir_fname("cached-status"));
2757 sandbox_cfg_allow_open_filename_array(&cfg,
2758 get_datadir_fname("cached-certs"),
2759 get_datadir_fname("cached-certs.tmp"),
2760 get_datadir_fname("cached-consensus"),
2761 get_datadir_fname("cached-consensus.tmp"),
2762 get_datadir_fname("unverified-consensus"),
2763 get_datadir_fname("unverified-consensus.tmp"),
2764 get_datadir_fname("unverified-microdesc-consensus"),
2765 get_datadir_fname("unverified-microdesc-consensus.tmp"),
2766 get_datadir_fname("cached-microdesc-consensus"),
2767 get_datadir_fname("cached-microdesc-consensus.tmp"),
2768 get_datadir_fname("cached-microdescs"),
2769 get_datadir_fname("cached-microdescs.tmp"),
2770 get_datadir_fname("cached-microdescs.new"),
2771 get_datadir_fname("cached-microdescs.new.tmp"),
2772 get_datadir_fname("cached-descriptors"),
2773 get_datadir_fname("cached-descriptors.new"),
2774 get_datadir_fname("cached-descriptors.tmp"),
2775 get_datadir_fname("cached-descriptors.new.tmp"),
2776 get_datadir_fname("cached-descriptors.tmp.tmp"),
2777 get_datadir_fname("cached-extrainfo"),
2778 get_datadir_fname("cached-extrainfo.new"),
2779 get_datadir_fname("cached-extrainfo.tmp"),
2780 get_datadir_fname("cached-extrainfo.new.tmp"),
2781 get_datadir_fname("cached-extrainfo.tmp.tmp"),
2782 get_datadir_fname("state.tmp"),
2783 get_datadir_fname("unparseable-desc.tmp"),
2784 get_datadir_fname("unparseable-desc"),
2785 get_datadir_fname("v3-status-votes"),
2786 get_datadir_fname("v3-status-votes.tmp"),
2787 tor_strdup("/dev/srandom"),
2788 tor_strdup("/dev/urandom"),
2789 tor_strdup("/dev/random"),
2790 tor_strdup("/etc/hosts"),
2791 tor_strdup("/proc/meminfo"),
2792 NULL, 0
2794 if (options->ServerDNSResolvConfFile)
2795 sandbox_cfg_allow_open_filename(&cfg,
2796 tor_strdup(options->ServerDNSResolvConfFile));
2797 else
2798 sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
2800 for (i = 0; i < 2; ++i) {
2801 if (get_torrc_fname(i)) {
2802 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(get_torrc_fname(i)));
2806 #define RENAME_SUFFIX(name, suffix) \
2807 sandbox_cfg_allow_rename(&cfg, \
2808 get_datadir_fname(name suffix), \
2809 get_datadir_fname(name))
2811 #define RENAME_SUFFIX2(prefix, name, suffix) \
2812 sandbox_cfg_allow_rename(&cfg, \
2813 get_datadir_fname2(prefix, name suffix), \
2814 get_datadir_fname2(prefix, name))
2816 RENAME_SUFFIX("cached-certs", ".tmp");
2817 RENAME_SUFFIX("cached-consensus", ".tmp");
2818 RENAME_SUFFIX("unverified-consensus", ".tmp");
2819 RENAME_SUFFIX("unverified-microdesc-consensus", ".tmp");
2820 RENAME_SUFFIX("cached-microdesc-consensus", ".tmp");
2821 RENAME_SUFFIX("cached-microdescs", ".tmp");
2822 RENAME_SUFFIX("cached-microdescs", ".new");
2823 RENAME_SUFFIX("cached-microdescs.new", ".tmp");
2824 RENAME_SUFFIX("cached-descriptors", ".tmp");
2825 RENAME_SUFFIX("cached-descriptors", ".new");
2826 RENAME_SUFFIX("cached-descriptors.new", ".tmp");
2827 RENAME_SUFFIX("cached-extrainfo", ".tmp");
2828 RENAME_SUFFIX("cached-extrainfo", ".new");
2829 RENAME_SUFFIX("cached-extrainfo.new", ".tmp");
2830 RENAME_SUFFIX("state", ".tmp");
2831 RENAME_SUFFIX("unparseable-desc", ".tmp");
2832 RENAME_SUFFIX("v3-status-votes", ".tmp");
2834 sandbox_cfg_allow_stat_filename_array(&cfg,
2835 get_datadir_fname(NULL),
2836 get_datadir_fname("lock"),
2837 get_datadir_fname("state"),
2838 get_datadir_fname("router-stability"),
2839 get_datadir_fname("cached-extrainfo.new"),
2840 NULL, 0
2844 smartlist_t *files = smartlist_new();
2845 tor_log_get_logfile_names(files);
2846 SMARTLIST_FOREACH(files, char *, file_name, {
2847 /* steals reference */
2848 sandbox_cfg_allow_open_filename(&cfg, file_name);
2850 smartlist_free(files);
2854 smartlist_t *files = smartlist_new();
2855 smartlist_t *dirs = smartlist_new();
2856 rend_services_add_filenames_to_lists(files, dirs);
2857 SMARTLIST_FOREACH(files, char *, file_name, {
2858 char *tmp_name = NULL;
2859 tor_asprintf(&tmp_name, "%s.tmp", file_name);
2860 sandbox_cfg_allow_rename(&cfg,
2861 tor_strdup(tmp_name), tor_strdup(file_name));
2862 /* steals references */
2863 sandbox_cfg_allow_open_filename_array(&cfg, file_name, tmp_name, NULL);
2865 SMARTLIST_FOREACH(dirs, char *, dir, {
2866 /* steals reference */
2867 sandbox_cfg_allow_stat_filename(&cfg, dir);
2869 smartlist_free(files);
2870 smartlist_free(dirs);
2874 char *fname;
2875 if ((fname = get_controller_cookie_file_name())) {
2876 sandbox_cfg_allow_open_filename(&cfg, fname);
2878 if ((fname = get_ext_or_auth_cookie_file_name())) {
2879 sandbox_cfg_allow_open_filename(&cfg, fname);
2883 if (options->DirPortFrontPage) {
2884 sandbox_cfg_allow_open_filename(&cfg,
2885 tor_strdup(options->DirPortFrontPage));
2888 // orport
2889 if (server_mode(get_options())) {
2890 sandbox_cfg_allow_open_filename_array(&cfg,
2891 get_datadir_fname2("keys", "secret_id_key"),
2892 get_datadir_fname2("keys", "secret_onion_key"),
2893 get_datadir_fname2("keys", "secret_onion_key_ntor"),
2894 get_datadir_fname2("keys", "secret_onion_key_ntor.tmp"),
2895 get_datadir_fname2("keys", "secret_id_key.old"),
2896 get_datadir_fname2("keys", "secret_onion_key.old"),
2897 get_datadir_fname2("keys", "secret_onion_key_ntor.old"),
2898 get_datadir_fname2("keys", "secret_onion_key.tmp"),
2899 get_datadir_fname2("keys", "secret_id_key.tmp"),
2900 get_datadir_fname2("stats", "bridge-stats"),
2901 get_datadir_fname2("stats", "bridge-stats.tmp"),
2902 get_datadir_fname2("stats", "dirreq-stats"),
2903 get_datadir_fname2("stats", "dirreq-stats.tmp"),
2904 get_datadir_fname2("stats", "entry-stats"),
2905 get_datadir_fname2("stats", "entry-stats.tmp"),
2906 get_datadir_fname2("stats", "exit-stats"),
2907 get_datadir_fname2("stats", "exit-stats.tmp"),
2908 get_datadir_fname2("stats", "buffer-stats"),
2909 get_datadir_fname2("stats", "buffer-stats.tmp"),
2910 get_datadir_fname2("stats", "conn-stats"),
2911 get_datadir_fname2("stats", "conn-stats.tmp"),
2912 get_datadir_fname("approved-routers"),
2913 get_datadir_fname("fingerprint"),
2914 get_datadir_fname("fingerprint.tmp"),
2915 get_datadir_fname("hashed-fingerprint"),
2916 get_datadir_fname("hashed-fingerprint.tmp"),
2917 get_datadir_fname("router-stability"),
2918 get_datadir_fname("router-stability.tmp"),
2919 tor_strdup("/etc/resolv.conf"),
2920 NULL, 0
2923 RENAME_SUFFIX("fingerprint", ".tmp");
2924 RENAME_SUFFIX2("keys", "secret_onion_key_ntor", ".tmp");
2925 RENAME_SUFFIX2("keys", "secret_id_key", ".tmp");
2926 RENAME_SUFFIX2("keys", "secret_id_key.old", ".tmp");
2927 RENAME_SUFFIX2("keys", "secret_onion_key", ".tmp");
2928 RENAME_SUFFIX2("keys", "secret_onion_key.old", ".tmp");
2929 RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
2930 RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
2931 RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
2932 RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
2933 RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
2934 RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
2935 RENAME_SUFFIX("hashed-fingerprint", ".tmp");
2936 RENAME_SUFFIX("router-stability", ".tmp");
2938 sandbox_cfg_allow_rename(&cfg,
2939 get_datadir_fname2("keys", "secret_onion_key"),
2940 get_datadir_fname2("keys", "secret_onion_key.old"));
2941 sandbox_cfg_allow_rename(&cfg,
2942 get_datadir_fname2("keys", "secret_onion_key_ntor"),
2943 get_datadir_fname2("keys", "secret_onion_key_ntor.old"));
2945 sandbox_cfg_allow_stat_filename_array(&cfg,
2946 get_datadir_fname("keys"),
2947 get_datadir_fname("stats"),
2948 get_datadir_fname2("stats", "dirreq-stats"),
2949 NULL, 0
2953 init_addrinfo();
2955 return cfg;
2958 /** Main entry point for the Tor process. Called from main(). */
2959 /* This function is distinct from main() only so we can link main.c into
2960 * the unittest binary without conflicting with the unittests' main. */
2962 tor_main(int argc, char *argv[])
2964 int result = 0;
2965 #if defined (WINCE)
2966 WCHAR path [MAX_PATH] = {0};
2967 WCHAR fullpath [MAX_PATH] = {0};
2968 PWCHAR p = NULL;
2969 FILE* redir = NULL;
2970 FILE* redirdbg = NULL;
2972 // this is to facilitate debugging by opening
2973 // a file on a folder shared by the wm emulator.
2974 // if no flashcard (real or emulated) is present,
2975 // log files will be written in the root folder
2976 if (find_flashcard_path(path,MAX_PATH) == -1) {
2977 redir = _wfreopen( L"\\stdout.log", L"w", stdout );
2978 redirdbg = _wfreopen( L"\\stderr.log", L"w", stderr );
2979 } else {
2980 swprintf(fullpath,L"\\%s\\tor",path);
2981 CreateDirectory(fullpath,NULL);
2983 swprintf(fullpath,L"\\%s\\tor\\stdout.log",path);
2984 redir = _wfreopen( fullpath, L"w", stdout );
2986 swprintf(fullpath,L"\\%s\\tor\\stderr.log",path);
2987 redirdbg = _wfreopen( fullpath, L"w", stderr );
2989 #endif
2991 #ifdef _WIN32
2992 /* Call SetProcessDEPPolicy to permanently enable DEP.
2993 The function will not resolve on earlier versions of Windows,
2994 and failure is not dangerous. */
2995 HMODULE hMod = GetModuleHandleA("Kernel32.dll");
2996 if (hMod) {
2997 typedef BOOL (WINAPI *PSETDEP)(DWORD);
2998 PSETDEP setdeppolicy = (PSETDEP)GetProcAddress(hMod,
2999 "SetProcessDEPPolicy");
3000 if (setdeppolicy) setdeppolicy(1); /* PROCESS_DEP_ENABLE */
3002 #endif
3004 configure_backtrace_handler(get_version());
3006 update_approx_time(time(NULL));
3007 tor_threads_init();
3008 init_logging();
3009 #ifdef USE_DMALLOC
3011 /* Instruct OpenSSL to use our internal wrappers for malloc,
3012 realloc and free. */
3013 int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
3014 tor_assert(r);
3016 #endif
3017 #ifdef NT_SERVICE
3019 int done = 0;
3020 result = nt_service_parse_options(argc, argv, &done);
3021 if (done) return result;
3023 #endif
3024 if (tor_init(argc, argv)<0)
3025 return -1;
3027 if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
3028 sandbox_cfg_t* cfg = sandbox_init_filter();
3030 if (sandbox_init(cfg)) {
3031 log_err(LD_BUG,"Failed to create syscall sandbox filter");
3032 return -1;
3035 // registering libevent rng
3036 #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
3037 evutil_secure_rng_set_urandom_device_file(
3038 (char*) sandbox_intern_string("/dev/urandom"));
3039 #endif
3042 switch (get_options()->command) {
3043 case CMD_RUN_TOR:
3044 #ifdef NT_SERVICE
3045 nt_service_set_state(SERVICE_RUNNING);
3046 #endif
3047 result = do_main_loop();
3048 break;
3049 case CMD_LIST_FINGERPRINT:
3050 result = do_list_fingerprint();
3051 break;
3052 case CMD_HASH_PASSWORD:
3053 do_hash_password();
3054 result = 0;
3055 break;
3056 case CMD_VERIFY_CONFIG:
3057 printf("Configuration was valid\n");
3058 result = 0;
3059 break;
3060 case CMD_DUMP_CONFIG:
3061 result = do_dump_config();
3062 break;
3063 case CMD_RUN_UNITTESTS: /* only set by test.c */
3064 default:
3065 log_warn(LD_BUG,"Illegal command number %d: internal error.",
3066 get_options()->command);
3067 result = -1;
3069 tor_cleanup();
3070 return result;