Merge remote-tracking branch 'andrea/bug11476'
[tor.git] / src / or / main.c
blob1168f43c9d9848437f3a9e4ad176a86ac3b07c2f
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 "ext_orport.h"
58 #ifdef USE_DMALLOC
59 #include <dmalloc.h>
60 #include <openssl/crypto.h>
61 #endif
62 #include "memarea.h"
63 #include "../common/sandbox.h"
65 #ifdef HAVE_EVENT2_EVENT_H
66 #include <event2/event.h>
67 #else
68 #include <event.h>
69 #endif
71 #ifdef USE_BUFFEREVENTS
72 #include <event2/bufferevent.h>
73 #endif
75 void evdns_shutdown(int);
77 /********* PROTOTYPES **********/
79 static void dumpmemusage(int severity);
80 static void dumpstats(int severity); /* log stats */
81 static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
82 static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
83 static void second_elapsed_callback(periodic_timer_t *timer, void *args);
84 static int conn_close_if_marked(int i);
85 static void connection_start_reading_from_linked_conn(connection_t *conn);
86 static int connection_should_read_from_linked_conn(connection_t *conn);
88 /********* START VARIABLES **********/
90 #ifndef USE_BUFFEREVENTS
91 int global_read_bucket; /**< Max number of bytes I can read this second. */
92 int global_write_bucket; /**< Max number of bytes I can write this second. */
94 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
95 int global_relayed_read_bucket;
96 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
97 int global_relayed_write_bucket;
98 /** What was the read bucket before the last second_elapsed_callback() call?
99 * (used to determine how many bytes we've read). */
100 static int stats_prev_global_read_bucket;
101 /** What was the write bucket before the last second_elapsed_callback() call?
102 * (used to determine how many bytes we've written). */
103 static int stats_prev_global_write_bucket;
104 #endif
106 /* DOCDOC stats_prev_n_read */
107 static uint64_t stats_prev_n_read = 0;
108 /* DOCDOC stats_prev_n_written */
109 static uint64_t stats_prev_n_written = 0;
111 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
112 /** How many bytes have we read since we started the process? */
113 static uint64_t stats_n_bytes_read = 0;
114 /** How many bytes have we written since we started the process? */
115 static uint64_t stats_n_bytes_written = 0;
116 /** What time did this process start up? */
117 time_t time_of_process_start = 0;
118 /** How many seconds have we been running? */
119 long stats_n_seconds_working = 0;
120 /** When do we next launch DNS wildcarding checks? */
121 static time_t time_to_check_for_correct_dns = 0;
123 /** How often will we honor SIGNEWNYM requests? */
124 #define MAX_SIGNEWNYM_RATE 10
125 /** When did we last process a SIGNEWNYM request? */
126 static time_t time_of_last_signewnym = 0;
127 /** Is there a signewnym request we're currently waiting to handle? */
128 static int signewnym_is_pending = 0;
129 /** How many times have we called newnym? */
130 static unsigned newnym_epoch = 0;
132 /** Smartlist of all open connections. */
133 static smartlist_t *connection_array = NULL;
134 /** List of connections that have been marked for close and need to be freed
135 * and removed from connection_array. */
136 static smartlist_t *closeable_connection_lst = NULL;
137 /** List of linked connections that are currently reading data into their
138 * inbuf from their partner's outbuf. */
139 static smartlist_t *active_linked_connection_lst = NULL;
140 /** Flag: Set to true iff we entered the current libevent main loop via
141 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
142 * to handle linked connections. */
143 static int called_loop_once = 0;
145 /** We set this to 1 when we've opened a circuit, so we can print a log
146 * entry to inform the user that Tor is working. We set it to 0 when
147 * we think the fact that we once opened a circuit doesn't mean we can do so
148 * any longer (a big time jump happened, when we notice our directory is
149 * heinously out-of-date, etc.
151 int can_complete_circuit=0;
153 /** How often do we check for router descriptors that we should download
154 * when we have too little directory info? */
155 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
156 /** How often do we check for router descriptors that we should download
157 * when we have enough directory info? */
158 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
159 /** How often do we 'forgive' undownloadable router descriptors and attempt
160 * to download them again? */
161 #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
163 /** Decides our behavior when no logs are configured/before any
164 * logs have been configured. For 0, we log notice to stdout as normal.
165 * For 1, we log warnings only. For 2, we log nothing.
167 int quiet_level = 0;
169 /********* END VARIABLES ************/
171 /****************************************************************************
173 * This section contains accessors and other methods on the connection_array
174 * variables (which are global within this file and unavailable outside it).
176 ****************************************************************************/
178 #if 0 && defined(USE_BUFFEREVENTS)
179 static void
180 free_old_inbuf(connection_t *conn)
182 if (! conn->inbuf)
183 return;
185 tor_assert(conn->outbuf);
186 tor_assert(buf_datalen(conn->inbuf) == 0);
187 tor_assert(buf_datalen(conn->outbuf) == 0);
188 buf_free(conn->inbuf);
189 buf_free(conn->outbuf);
190 conn->inbuf = conn->outbuf = NULL;
192 if (conn->read_event) {
193 event_del(conn->read_event);
194 tor_event_free(conn->read_event);
196 if (conn->write_event) {
197 event_del(conn->read_event);
198 tor_event_free(conn->write_event);
200 conn->read_event = conn->write_event = NULL;
202 #endif
204 #if defined(_WIN32) && defined(USE_BUFFEREVENTS)
205 /** Remove the kernel-space send and receive buffers for <b>s</b>. For use
206 * with IOCP only. */
207 static int
208 set_buffer_lengths_to_zero(tor_socket_t s)
210 int zero = 0;
211 int r = 0;
212 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&zero, sizeof(zero))) {
213 log_warn(LD_NET, "Unable to clear SO_SNDBUF");
214 r = -1;
216 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&zero, sizeof(zero))) {
217 log_warn(LD_NET, "Unable to clear SO_RCVBUF");
218 r = -1;
220 return r;
222 #endif
224 /** Add <b>conn</b> to the array of connections that we can poll on. The
225 * connection's socket must be set; the connection starts out
226 * non-reading and non-writing.
229 connection_add_impl(connection_t *conn, int is_connecting)
231 tor_assert(conn);
232 tor_assert(SOCKET_OK(conn->s) ||
233 conn->linked ||
234 (conn->type == CONN_TYPE_AP &&
235 TO_EDGE_CONN(conn)->is_dns_request));
237 tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
238 conn->conn_array_index = smartlist_len(connection_array);
239 smartlist_add(connection_array, conn);
241 #ifdef USE_BUFFEREVENTS
242 if (connection_type_uses_bufferevent(conn)) {
243 if (SOCKET_OK(conn->s) && !conn->linked) {
245 #ifdef _WIN32
246 if (tor_libevent_using_iocp_bufferevents() &&
247 get_options()->UserspaceIOCPBuffers) {
248 set_buffer_lengths_to_zero(conn->s);
250 #endif
252 conn->bufev = bufferevent_socket_new(
253 tor_libevent_get_base(),
254 conn->s,
255 BEV_OPT_DEFER_CALLBACKS);
256 if (!conn->bufev) {
257 log_warn(LD_BUG, "Unable to create socket bufferevent");
258 smartlist_del(connection_array, conn->conn_array_index);
259 conn->conn_array_index = -1;
260 return -1;
262 if (is_connecting) {
263 /* Put the bufferevent into a "connecting" state so that we'll get
264 * a "connected" event callback on successful write. */
265 bufferevent_socket_connect(conn->bufev, NULL, 0);
267 connection_configure_bufferevent_callbacks(conn);
268 } else if (conn->linked && conn->linked_conn &&
269 connection_type_uses_bufferevent(conn->linked_conn)) {
270 tor_assert(!(SOCKET_OK(conn->s)));
271 if (!conn->bufev) {
272 struct bufferevent *pair[2] = { NULL, NULL };
273 if (bufferevent_pair_new(tor_libevent_get_base(),
274 BEV_OPT_DEFER_CALLBACKS,
275 pair) < 0) {
276 log_warn(LD_BUG, "Unable to create bufferevent pair");
277 smartlist_del(connection_array, conn->conn_array_index);
278 conn->conn_array_index = -1;
279 return -1;
281 tor_assert(pair[0]);
282 conn->bufev = pair[0];
283 conn->linked_conn->bufev = pair[1];
284 } /* else the other side already was added, and got a bufferevent_pair */
285 connection_configure_bufferevent_callbacks(conn);
286 } else {
287 tor_assert(!conn->linked);
290 if (conn->bufev)
291 tor_assert(conn->inbuf == NULL);
293 if (conn->linked_conn && conn->linked_conn->bufev)
294 tor_assert(conn->linked_conn->inbuf == NULL);
296 #else
297 (void) is_connecting;
298 #endif
300 if (!HAS_BUFFEREVENT(conn) && (SOCKET_OK(conn->s) || conn->linked)) {
301 conn->read_event = tor_event_new(tor_libevent_get_base(),
302 conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
303 conn->write_event = tor_event_new(tor_libevent_get_base(),
304 conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
305 /* XXXX CHECK FOR NULL RETURN! */
308 log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
309 conn_type_to_string(conn->type), (int)conn->s, conn->address,
310 smartlist_len(connection_array));
312 return 0;
315 /** Tell libevent that we don't care about <b>conn</b> any more. */
316 void
317 connection_unregister_events(connection_t *conn)
319 if (conn->read_event) {
320 if (event_del(conn->read_event))
321 log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
322 tor_free(conn->read_event);
324 if (conn->write_event) {
325 if (event_del(conn->write_event))
326 log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
327 tor_free(conn->write_event);
329 #ifdef USE_BUFFEREVENTS
330 if (conn->bufev) {
331 bufferevent_free(conn->bufev);
332 conn->bufev = NULL;
334 #endif
335 if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
336 dnsserv_close_listener(conn);
340 /** Remove the connection from the global list, and remove the
341 * corresponding poll entry. Calling this function will shift the last
342 * connection (if any) into the position occupied by conn.
345 connection_remove(connection_t *conn)
347 int current_index;
348 connection_t *tmp;
350 tor_assert(conn);
352 log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
353 (int)conn->s, conn_type_to_string(conn->type),
354 smartlist_len(connection_array));
356 control_event_conn_bandwidth(conn);
358 tor_assert(conn->conn_array_index >= 0);
359 current_index = conn->conn_array_index;
360 connection_unregister_events(conn); /* This is redundant, but cheap. */
361 if (current_index == smartlist_len(connection_array)-1) { /* at the end */
362 smartlist_del(connection_array, current_index);
363 return 0;
366 /* replace this one with the one at the end */
367 smartlist_del(connection_array, current_index);
368 tmp = smartlist_get(connection_array, current_index);
369 tmp->conn_array_index = current_index;
371 return 0;
374 /** If <b>conn</b> is an edge conn, remove it from the list
375 * of conn's on this circuit. If it's not on an edge,
376 * flush and send destroys for all circuits on this conn.
378 * Remove it from connection_array (if applicable) and
379 * from closeable_connection_list.
381 * Then free it.
383 static void
384 connection_unlink(connection_t *conn)
386 connection_about_to_close_connection(conn);
387 if (conn->conn_array_index >= 0) {
388 connection_remove(conn);
390 if (conn->linked_conn) {
391 conn->linked_conn->linked_conn = NULL;
392 if (! conn->linked_conn->marked_for_close &&
393 conn->linked_conn->reading_from_linked_conn)
394 connection_start_reading(conn->linked_conn);
395 conn->linked_conn = NULL;
397 smartlist_remove(closeable_connection_lst, conn);
398 smartlist_remove(active_linked_connection_lst, conn);
399 if (conn->type == CONN_TYPE_EXIT) {
400 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
402 if (conn->type == CONN_TYPE_OR) {
403 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
404 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
405 /* connection_unlink() can only get called if the connection
406 * was already on the closeable list, and it got there by
407 * connection_mark_for_close(), which was called from
408 * connection_or_close_normally() or
409 * connection_or_close_for_error(), so the channel should
410 * already be in CHANNEL_STATE_CLOSING, and then the
411 * connection_about_to_close_connection() goes to
412 * connection_or_about_to_close(), which calls channel_closed()
413 * to notify the channel_t layer, and closed the channel, so
414 * nothing more to do here to deal with the channel associated
415 * with an orconn.
418 connection_free(conn);
421 /** Initialize the global connection list, closeable connection list,
422 * and active connection list. */
423 STATIC void
424 init_connection_lists(void)
426 if (!connection_array)
427 connection_array = smartlist_new();
428 if (!closeable_connection_lst)
429 closeable_connection_lst = smartlist_new();
430 if (!active_linked_connection_lst)
431 active_linked_connection_lst = smartlist_new();
434 /** Schedule <b>conn</b> to be closed. **/
435 void
436 add_connection_to_closeable_list(connection_t *conn)
438 tor_assert(!smartlist_contains(closeable_connection_lst, conn));
439 tor_assert(conn->marked_for_close);
440 assert_connection_ok(conn, time(NULL));
441 smartlist_add(closeable_connection_lst, conn);
444 /** Return 1 if conn is on the closeable list, else return 0. */
446 connection_is_on_closeable_list(connection_t *conn)
448 return smartlist_contains(closeable_connection_lst, conn);
451 /** Return true iff conn is in the current poll array. */
453 connection_in_array(connection_t *conn)
455 return smartlist_contains(connection_array, conn);
458 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
459 * to the length of the array. <b>*array</b> and <b>*n</b> must not
460 * be modified.
462 smartlist_t *
463 get_connection_array(void)
465 if (!connection_array)
466 connection_array = smartlist_new();
467 return connection_array;
470 /** Provides the traffic read and written over the life of the process. */
472 MOCK_IMPL(uint64_t,
473 get_bytes_read,(void))
475 return stats_n_bytes_read;
478 /* DOCDOC get_bytes_written */
479 MOCK_IMPL(uint64_t,
480 get_bytes_written,(void))
482 return stats_n_bytes_written;
485 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
486 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
488 void
489 connection_watch_events(connection_t *conn, watchable_events_t events)
491 IF_HAS_BUFFEREVENT(conn, {
492 short ev = ((short)events) & (EV_READ|EV_WRITE);
493 short old_ev = bufferevent_get_enabled(conn->bufev);
494 if ((ev & ~old_ev) != 0) {
495 bufferevent_enable(conn->bufev, ev);
497 if ((old_ev & ~ev) != 0) {
498 bufferevent_disable(conn->bufev, old_ev & ~ev);
500 return;
502 if (events & READ_EVENT)
503 connection_start_reading(conn);
504 else
505 connection_stop_reading(conn);
507 if (events & WRITE_EVENT)
508 connection_start_writing(conn);
509 else
510 connection_stop_writing(conn);
513 /** Return true iff <b>conn</b> is listening for read events. */
515 connection_is_reading(connection_t *conn)
517 tor_assert(conn);
519 IF_HAS_BUFFEREVENT(conn,
520 return (bufferevent_get_enabled(conn->bufev) & EV_READ) != 0;
522 return conn->reading_from_linked_conn ||
523 (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
526 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
527 MOCK_IMPL(void,
528 connection_stop_reading,(connection_t *conn))
530 tor_assert(conn);
532 IF_HAS_BUFFEREVENT(conn, {
533 bufferevent_disable(conn->bufev, EV_READ);
534 return;
537 tor_assert(conn->read_event);
539 if (conn->linked) {
540 conn->reading_from_linked_conn = 0;
541 connection_stop_reading_from_linked_conn(conn);
542 } else {
543 if (event_del(conn->read_event))
544 log_warn(LD_NET, "Error from libevent setting read event state for %d "
545 "to unwatched: %s",
546 (int)conn->s,
547 tor_socket_strerror(tor_socket_errno(conn->s)));
551 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
552 MOCK_IMPL(void,
553 connection_start_reading,(connection_t *conn))
555 tor_assert(conn);
557 IF_HAS_BUFFEREVENT(conn, {
558 bufferevent_enable(conn->bufev, EV_READ);
559 return;
562 tor_assert(conn->read_event);
564 if (conn->linked) {
565 conn->reading_from_linked_conn = 1;
566 if (connection_should_read_from_linked_conn(conn))
567 connection_start_reading_from_linked_conn(conn);
568 } else {
569 if (event_add(conn->read_event, NULL))
570 log_warn(LD_NET, "Error from libevent setting read event state for %d "
571 "to watched: %s",
572 (int)conn->s,
573 tor_socket_strerror(tor_socket_errno(conn->s)));
577 /** Return true iff <b>conn</b> is listening for write events. */
579 connection_is_writing(connection_t *conn)
581 tor_assert(conn);
583 IF_HAS_BUFFEREVENT(conn,
584 return (bufferevent_get_enabled(conn->bufev) & EV_WRITE) != 0;
587 return conn->writing_to_linked_conn ||
588 (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
591 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
592 MOCK_IMPL(void,
593 connection_stop_writing,(connection_t *conn))
595 tor_assert(conn);
597 IF_HAS_BUFFEREVENT(conn, {
598 bufferevent_disable(conn->bufev, EV_WRITE);
599 return;
602 tor_assert(conn->write_event);
604 if (conn->linked) {
605 conn->writing_to_linked_conn = 0;
606 if (conn->linked_conn)
607 connection_stop_reading_from_linked_conn(conn->linked_conn);
608 } else {
609 if (event_del(conn->write_event))
610 log_warn(LD_NET, "Error from libevent setting write event state for %d "
611 "to unwatched: %s",
612 (int)conn->s,
613 tor_socket_strerror(tor_socket_errno(conn->s)));
617 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
618 MOCK_IMPL(void,
619 connection_start_writing,(connection_t *conn))
621 tor_assert(conn);
623 IF_HAS_BUFFEREVENT(conn, {
624 bufferevent_enable(conn->bufev, EV_WRITE);
625 return;
628 tor_assert(conn->write_event);
630 if (conn->linked) {
631 conn->writing_to_linked_conn = 1;
632 if (conn->linked_conn &&
633 connection_should_read_from_linked_conn(conn->linked_conn))
634 connection_start_reading_from_linked_conn(conn->linked_conn);
635 } else {
636 if (event_add(conn->write_event, NULL))
637 log_warn(LD_NET, "Error from libevent setting write event state for %d "
638 "to watched: %s",
639 (int)conn->s,
640 tor_socket_strerror(tor_socket_errno(conn->s)));
644 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
645 * linked to it would be good and feasible. (Reading is "feasible" if the
646 * other conn exists and has data in its outbuf, and is "good" if we have our
647 * reading_from_linked_conn flag set and the other conn has its
648 * writing_to_linked_conn flag set.)*/
649 static int
650 connection_should_read_from_linked_conn(connection_t *conn)
652 if (conn->linked && conn->reading_from_linked_conn) {
653 if (! conn->linked_conn ||
654 (conn->linked_conn->writing_to_linked_conn &&
655 buf_datalen(conn->linked_conn->outbuf)))
656 return 1;
658 return 0;
661 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
662 * its linked connection, if it is not doing so already. Called by
663 * connection_start_reading and connection_start_writing as appropriate. */
664 static void
665 connection_start_reading_from_linked_conn(connection_t *conn)
667 tor_assert(conn);
668 tor_assert(conn->linked == 1);
670 if (!conn->active_on_link) {
671 conn->active_on_link = 1;
672 smartlist_add(active_linked_connection_lst, conn);
673 if (!called_loop_once) {
674 /* This is the first event on the list; we won't be in LOOP_ONCE mode,
675 * so we need to make sure that the event_base_loop() actually exits at
676 * the end of its run through the current connections and lets us
677 * activate read events for linked connections. */
678 struct timeval tv = { 0, 0 };
679 tor_event_base_loopexit(tor_libevent_get_base(), &tv);
681 } else {
682 tor_assert(smartlist_contains(active_linked_connection_lst, conn));
686 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
687 * connection, if is currently doing so. Called by connection_stop_reading,
688 * connection_stop_writing, and connection_read. */
689 void
690 connection_stop_reading_from_linked_conn(connection_t *conn)
692 tor_assert(conn);
693 tor_assert(conn->linked == 1);
695 if (conn->active_on_link) {
696 conn->active_on_link = 0;
697 /* FFFF We could keep an index here so we can smartlist_del
698 * cleanly. On the other hand, this doesn't show up on profiles,
699 * so let's leave it alone for now. */
700 smartlist_remove(active_linked_connection_lst, conn);
701 } else {
702 tor_assert(!smartlist_contains(active_linked_connection_lst, conn));
706 /** Close all connections that have been scheduled to get closed. */
707 STATIC void
708 close_closeable_connections(void)
710 int i;
711 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
712 connection_t *conn = smartlist_get(closeable_connection_lst, i);
713 if (conn->conn_array_index < 0) {
714 connection_unlink(conn); /* blow it away right now */
715 } else {
716 if (!conn_close_if_marked(conn->conn_array_index))
717 ++i;
722 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
723 * some data to read. */
724 static void
725 conn_read_callback(evutil_socket_t fd, short event, void *_conn)
727 connection_t *conn = _conn;
728 (void)fd;
729 (void)event;
731 log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
733 /* assert_connection_ok(conn, time(NULL)); */
735 if (connection_handle_read(conn) < 0) {
736 if (!conn->marked_for_close) {
737 #ifndef _WIN32
738 log_warn(LD_BUG,"Unhandled error on read for %s connection "
739 "(fd %d); removing",
740 conn_type_to_string(conn->type), (int)conn->s);
741 tor_fragile_assert();
742 #endif
743 if (CONN_IS_EDGE(conn))
744 connection_edge_end_errno(TO_EDGE_CONN(conn));
745 connection_mark_for_close(conn);
748 assert_connection_ok(conn, time(NULL));
750 if (smartlist_len(closeable_connection_lst))
751 close_closeable_connections();
754 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
755 * some data to write. */
756 static void
757 conn_write_callback(evutil_socket_t fd, short events, void *_conn)
759 connection_t *conn = _conn;
760 (void)fd;
761 (void)events;
763 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
764 (int)conn->s));
766 /* assert_connection_ok(conn, time(NULL)); */
768 if (connection_handle_write(conn, 0) < 0) {
769 if (!conn->marked_for_close) {
770 /* this connection is broken. remove it. */
771 log_fn(LOG_WARN,LD_BUG,
772 "unhandled error on write for %s connection (fd %d); removing",
773 conn_type_to_string(conn->type), (int)conn->s);
774 tor_fragile_assert();
775 if (CONN_IS_EDGE(conn)) {
776 /* otherwise we cry wolf about duplicate close */
777 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
778 if (!edge_conn->end_reason)
779 edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
780 edge_conn->edge_has_sent_end = 1;
782 connection_close_immediate(conn); /* So we don't try to flush. */
783 connection_mark_for_close(conn);
786 assert_connection_ok(conn, time(NULL));
788 if (smartlist_len(closeable_connection_lst))
789 close_closeable_connections();
792 /** If the connection at connection_array[i] is marked for close, then:
793 * - If it has data that it wants to flush, try to flush it.
794 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
795 * true, then leave the connection open and return.
796 * - Otherwise, remove the connection from connection_array and from
797 * all other lists, close it, and free it.
798 * Returns 1 if the connection was closed, 0 otherwise.
800 static int
801 conn_close_if_marked(int i)
803 connection_t *conn;
804 int retval;
805 time_t now;
807 conn = smartlist_get(connection_array, i);
808 if (!conn->marked_for_close)
809 return 0; /* nothing to see here, move along */
810 now = time(NULL);
811 assert_connection_ok(conn, now);
812 /* assert_all_pending_dns_resolves_ok(); */
814 #ifdef USE_BUFFEREVENTS
815 if (conn->bufev) {
816 if (conn->hold_open_until_flushed &&
817 evbuffer_get_length(bufferevent_get_output(conn->bufev))) {
818 /* don't close yet. */
819 return 0;
821 if (conn->linked_conn && ! conn->linked_conn->marked_for_close) {
822 /* We need to do this explicitly so that the linked connection
823 * notices that there was an EOF. */
824 bufferevent_flush(conn->bufev, EV_WRITE, BEV_FINISHED);
827 #endif
829 log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
830 conn->s);
832 /* If the connection we are about to close was trying to connect to
833 a proxy server and failed, the client won't be able to use that
834 proxy. We should warn the user about this. */
835 if (conn->proxy_state == PROXY_INFANT)
836 log_failed_proxy_connection(conn);
838 IF_HAS_BUFFEREVENT(conn, goto unlink);
839 if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
840 connection_wants_to_flush(conn)) {
841 /* s == -1 means it's an incomplete edge connection, or that the socket
842 * has already been closed as unflushable. */
843 ssize_t sz = connection_bucket_write_limit(conn, now);
844 if (!conn->hold_open_until_flushed)
845 log_info(LD_NET,
846 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
847 "to flush %d bytes. (Marked at %s:%d)",
848 escaped_safe_str_client(conn->address),
849 (int)conn->s, conn_type_to_string(conn->type), conn->state,
850 (int)conn->outbuf_flushlen,
851 conn->marked_for_close_file, conn->marked_for_close);
852 if (conn->linked_conn) {
853 retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
854 &conn->outbuf_flushlen);
855 if (retval >= 0) {
856 /* The linked conn will notice that it has data when it notices that
857 * we're gone. */
858 connection_start_reading_from_linked_conn(conn->linked_conn);
860 log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
861 "%d left; flushlen %d; wants-to-flush==%d", retval,
862 (int)connection_get_outbuf_len(conn),
863 (int)conn->outbuf_flushlen,
864 connection_wants_to_flush(conn));
865 } else if (connection_speaks_cells(conn)) {
866 if (conn->state == OR_CONN_STATE_OPEN) {
867 retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
868 &conn->outbuf_flushlen);
869 } else
870 retval = -1; /* never flush non-open broken tls connections */
871 } else {
872 retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
874 if (retval >= 0 && /* Technically, we could survive things like
875 TLS_WANT_WRITE here. But don't bother for now. */
876 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
877 if (retval > 0) {
878 LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
879 "Holding conn (fd %d) open for more flushing.",
880 (int)conn->s));
881 conn->timestamp_lastwritten = now; /* reset so we can flush more */
882 } else if (sz == 0) {
883 /* Also, retval==0. If we get here, we didn't want to write anything
884 * (because of rate-limiting) and we didn't. */
886 /* Connection must flush before closing, but it's being rate-limited.
887 * Let's remove from Libevent, and mark it as blocked on bandwidth
888 * so it will be re-added on next token bucket refill. Prevents
889 * busy Libevent loops where we keep ending up here and returning
890 * 0 until we are no longer blocked on bandwidth.
892 if (connection_is_writing(conn)) {
893 conn->write_blocked_on_bw = 1;
894 connection_stop_writing(conn);
896 if (connection_is_reading(conn)) {
897 /* XXXX024 We should make this code unreachable; if a connection is
898 * marked for close and flushing, there is no point in reading to it
899 * at all. Further, checking at this point is a bit of a hack: it
900 * would make much more sense to react in
901 * connection_handle_read_impl, or to just stop reading in
902 * mark_and_flush */
903 #if 0
904 #define MARKED_READING_RATE 180
905 static ratelim_t marked_read_lim = RATELIM_INIT(MARKED_READING_RATE);
906 char *m;
907 if ((m = rate_limit_log(&marked_read_lim, now))) {
908 log_warn(LD_BUG, "Marked connection (fd %d, type %s, state %s) "
909 "is still reading; that shouldn't happen.%s",
910 (int)conn->s, conn_type_to_string(conn->type),
911 conn_state_to_string(conn->type, conn->state), m);
912 tor_free(m);
914 #endif
915 conn->read_blocked_on_bw = 1;
916 connection_stop_reading(conn);
919 return 0;
921 if (connection_wants_to_flush(conn)) {
922 log_fn(LOG_INFO, LD_NET, "We stalled too much while trying to write %d "
923 "bytes to address %s. If this happens a lot, either "
924 "something is wrong with your network connection, or "
925 "something is wrong with theirs. "
926 "(fd %d, type %s, state %d, marked at %s:%d).",
927 (int)connection_get_outbuf_len(conn),
928 escaped_safe_str_client(conn->address),
929 (int)conn->s, conn_type_to_string(conn->type), conn->state,
930 conn->marked_for_close_file,
931 conn->marked_for_close);
935 #ifdef USE_BUFFEREVENTS
936 unlink:
937 #endif
938 connection_unlink(conn); /* unlink, remove, free */
939 return 1;
942 /** We've just tried every dirserver we know about, and none of
943 * them were reachable. Assume the network is down. Change state
944 * so next time an application connection arrives we'll delay it
945 * and try another directory fetch. Kill off all the circuit_wait
946 * streams that are waiting now, since they will all timeout anyway.
948 void
949 directory_all_unreachable(time_t now)
951 connection_t *conn;
952 (void)now;
954 stats_n_seconds_working=0; /* reset it */
956 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
957 AP_CONN_STATE_CIRCUIT_WAIT))) {
958 entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
959 log_notice(LD_NET,
960 "Is your network connection down? "
961 "Failing connection to '%s:%d'.",
962 safe_str_client(entry_conn->socks_request->address),
963 entry_conn->socks_request->port);
964 connection_mark_unattached_ap(entry_conn,
965 END_STREAM_REASON_NET_UNREACHABLE);
967 control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
970 /** This function is called whenever we successfully pull down some new
971 * network statuses or server descriptors. */
972 void
973 directory_info_has_arrived(time_t now, int from_cache)
975 const or_options_t *options = get_options();
977 if (!router_have_minimum_dir_info()) {
978 int quiet = from_cache ||
979 directory_too_idle_to_fetch_descriptors(options, now);
980 tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
981 "I learned some more directory information, but not enough to "
982 "build a circuit: %s", get_dir_info_status_string());
983 update_all_descriptor_downloads(now);
984 return;
985 } else {
986 if (directory_fetches_from_authorities(options)) {
987 update_all_descriptor_downloads(now);
990 /* if we have enough dir info, then update our guard status with
991 * whatever we just learned. */
992 entry_guards_compute_status(options, now);
993 /* Don't even bother trying to get extrainfo until the rest of our
994 * directory info is up-to-date */
995 if (options->DownloadExtraInfo)
996 update_extrainfo_downloads(now);
999 if (server_mode(options) && !net_is_disabled() && !from_cache &&
1000 (can_complete_circuit || !any_predicted_circuits(now)))
1001 consider_testing_reachability(1, 1);
1004 /** How long do we wait before killing OR connections with no circuits?
1005 * In Tor versions up to 0.2.1.25 and 0.2.2.12-alpha, we waited 15 minutes
1006 * before cancelling these connections, which caused fast relays to accrue
1007 * many many idle connections. Hopefully 3 minutes is low enough that
1008 * it kills most idle connections, without being so low that we cause
1009 * clients to bounce on and off.
1011 #define IDLE_OR_CONN_TIMEOUT 180
1013 /** Perform regular maintenance tasks for a single connection. This
1014 * function gets run once per second per connection by run_scheduled_events.
1016 static void
1017 run_connection_housekeeping(int i, time_t now)
1019 cell_t cell;
1020 connection_t *conn = smartlist_get(connection_array, i);
1021 const or_options_t *options = get_options();
1022 or_connection_t *or_conn;
1023 int past_keepalive =
1024 now >= conn->timestamp_lastwritten + options->KeepalivePeriod;
1026 if (conn->outbuf && !connection_get_outbuf_len(conn) &&
1027 conn->type == CONN_TYPE_OR)
1028 TO_OR_CONN(conn)->timestamp_lastempty = now;
1030 if (conn->marked_for_close) {
1031 /* nothing to do here */
1032 return;
1035 /* Expire any directory connections that haven't been active (sent
1036 * if a server or received if a client) for 5 min */
1037 if (conn->type == CONN_TYPE_DIR &&
1038 ((DIR_CONN_IS_SERVER(conn) &&
1039 conn->timestamp_lastwritten
1040 + options->TestingDirConnectionMaxStall < now) ||
1041 (!DIR_CONN_IS_SERVER(conn) &&
1042 conn->timestamp_lastread
1043 + options->TestingDirConnectionMaxStall < now))) {
1044 log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
1045 (int)conn->s, conn->purpose);
1046 /* This check is temporary; it's to let us know whether we should consider
1047 * parsing partial serverdesc responses. */
1048 if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
1049 connection_get_inbuf_len(conn) >= 1024) {
1050 log_info(LD_DIR,"Trying to extract information from wedged server desc "
1051 "download.");
1052 connection_dir_reached_eof(TO_DIR_CONN(conn));
1053 } else {
1054 connection_mark_for_close(conn);
1056 return;
1059 if (!connection_speaks_cells(conn))
1060 return; /* we're all done here, the rest is just for OR conns */
1062 /* If we haven't written to an OR connection for a while, then either nuke
1063 the connection or send a keepalive, depending. */
1065 or_conn = TO_OR_CONN(conn);
1066 #ifdef USE_BUFFEREVENTS
1067 tor_assert(conn->bufev);
1068 #else
1069 tor_assert(conn->outbuf);
1070 #endif
1072 if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan)) &&
1073 !connection_or_get_num_circuits(or_conn)) {
1074 /* It's bad for new circuits, and has no unmarked circuits on it:
1075 * mark it now. */
1076 log_info(LD_OR,
1077 "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
1078 (int)conn->s, conn->address, conn->port);
1079 if (conn->state == OR_CONN_STATE_CONNECTING)
1080 connection_or_connect_failed(TO_OR_CONN(conn),
1081 END_OR_CONN_REASON_TIMEOUT,
1082 "Tor gave up on the connection");
1083 connection_or_close_normally(TO_OR_CONN(conn), 1);
1084 } else if (!connection_state_is_open(conn)) {
1085 if (past_keepalive) {
1086 /* We never managed to actually get this connection open and happy. */
1087 log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
1088 (int)conn->s,conn->address, conn->port);
1089 connection_or_close_normally(TO_OR_CONN(conn), 0);
1091 } else if (we_are_hibernating() &&
1092 !connection_or_get_num_circuits(or_conn) &&
1093 !connection_get_outbuf_len(conn)) {
1094 /* We're hibernating, there's no circuits, and nothing to flush.*/
1095 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
1096 "[Hibernating or exiting].",
1097 (int)conn->s,conn->address, conn->port);
1098 connection_or_close_normally(TO_OR_CONN(conn), 1);
1099 } else if (!connection_or_get_num_circuits(or_conn) &&
1100 now >= or_conn->timestamp_last_added_nonpadding +
1101 IDLE_OR_CONN_TIMEOUT) {
1102 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
1103 "[idle %d].", (int)conn->s,conn->address, conn->port,
1104 (int)(now - or_conn->timestamp_last_added_nonpadding));
1105 connection_or_close_normally(TO_OR_CONN(conn), 0);
1106 } else if (
1107 now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
1108 now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
1109 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
1110 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
1111 "flush; %d seconds since last write)",
1112 (int)conn->s, conn->address, conn->port,
1113 (int)connection_get_outbuf_len(conn),
1114 (int)(now-conn->timestamp_lastwritten));
1115 connection_or_close_normally(TO_OR_CONN(conn), 0);
1116 } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
1117 /* send a padding cell */
1118 log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
1119 conn->address, conn->port);
1120 memset(&cell,0,sizeof(cell_t));
1121 cell.command = CELL_PADDING;
1122 connection_or_write_cell_to_buf(&cell, or_conn);
1126 /** Honor a NEWNYM request: make future requests unlinkable to past
1127 * requests. */
1128 static void
1129 signewnym_impl(time_t now)
1131 const or_options_t *options = get_options();
1132 if (!proxy_mode(options)) {
1133 log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
1134 "is disabled.");
1135 return;
1138 circuit_mark_all_dirty_circs_as_unusable();
1139 addressmap_clear_transient();
1140 rend_client_purge_state();
1141 time_of_last_signewnym = now;
1142 signewnym_is_pending = 0;
1144 ++newnym_epoch;
1146 control_event_signal(SIGNEWNYM);
1149 /** Return the number of times that signewnym has been called. */
1150 unsigned
1151 get_signewnym_epoch(void)
1153 return newnym_epoch;
1156 static time_t time_to_check_descriptor = 0;
1158 * Update our schedule so that we'll check whether we need to update our
1159 * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
1160 * seconds.
1162 void
1163 reschedule_descriptor_update_check(void)
1165 time_to_check_descriptor = 0;
1168 /** Perform regular maintenance tasks. This function gets run once per
1169 * second by second_elapsed_callback().
1171 static void
1172 run_scheduled_events(time_t now)
1174 static time_t last_rotated_x509_certificate = 0;
1175 static time_t time_to_check_v3_certificate = 0;
1176 static time_t time_to_check_listeners = 0;
1177 static time_t time_to_download_networkstatus = 0;
1178 static time_t time_to_shrink_memory = 0;
1179 static time_t time_to_try_getting_descriptors = 0;
1180 static time_t time_to_reset_descriptor_failures = 0;
1181 static time_t time_to_add_entropy = 0;
1182 static time_t time_to_write_bridge_status_file = 0;
1183 static time_t time_to_downrate_stability = 0;
1184 static time_t time_to_save_stability = 0;
1185 static time_t time_to_clean_caches = 0;
1186 static time_t time_to_recheck_bandwidth = 0;
1187 static time_t time_to_check_for_expired_networkstatus = 0;
1188 static time_t time_to_write_stats_files = 0;
1189 static time_t time_to_write_bridge_stats = 0;
1190 static time_t time_to_check_port_forwarding = 0;
1191 static time_t time_to_launch_reachability_tests = 0;
1192 static int should_init_bridge_stats = 1;
1193 static time_t time_to_retry_dns_init = 0;
1194 static time_t time_to_next_heartbeat = 0;
1195 const or_options_t *options = get_options();
1197 int is_server = server_mode(options);
1198 int i;
1199 int have_dir_info;
1201 /* 0. See if we've been asked to shut down and our timeout has
1202 * expired; or if our bandwidth limits are exhausted and we
1203 * should hibernate; or if it's time to wake up from hibernation.
1205 consider_hibernation(now);
1207 /* 0b. If we've deferred a signewnym, make sure it gets handled
1208 * eventually. */
1209 if (signewnym_is_pending &&
1210 time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
1211 log_info(LD_CONTROL, "Honoring delayed NEWNYM request");
1212 signewnym_impl(now);
1215 /* 0c. If we've deferred log messages for the controller, handle them now */
1216 flush_pending_log_callbacks();
1218 /* 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
1219 * shut down and restart all cpuworkers, and update the directory if
1220 * necessary.
1222 if (is_server &&
1223 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
1224 log_info(LD_GENERAL,"Rotating onion key.");
1225 rotate_onion_key();
1226 cpuworkers_rotate();
1227 if (router_rebuild_descriptor(1)<0) {
1228 log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
1230 if (advertised_server_mode() && !options->DisableNetwork)
1231 router_upload_dir_desc_to_dirservers(0);
1234 if (!options->DisableNetwork && time_to_try_getting_descriptors < now) {
1235 update_all_descriptor_downloads(now);
1236 update_extrainfo_downloads(now);
1237 if (router_have_minimum_dir_info())
1238 time_to_try_getting_descriptors = now + LAZY_DESCRIPTOR_RETRY_INTERVAL;
1239 else
1240 time_to_try_getting_descriptors = now + GREEDY_DESCRIPTOR_RETRY_INTERVAL;
1243 if (time_to_reset_descriptor_failures < now) {
1244 router_reset_descriptor_download_failures();
1245 time_to_reset_descriptor_failures =
1246 now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
1249 if (options->UseBridges)
1250 fetch_bridge_descriptors(options, now);
1252 /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
1253 * TLS context. */
1254 if (!last_rotated_x509_certificate)
1255 last_rotated_x509_certificate = now;
1256 if (last_rotated_x509_certificate+MAX_SSL_KEY_LIFETIME_INTERNAL < now) {
1257 log_info(LD_GENERAL,"Rotating tls context.");
1258 if (router_initialize_tls_context() < 0) {
1259 log_warn(LD_BUG, "Error reinitializing TLS context");
1260 /* XXX is it a bug here, that we just keep going? -RD */
1262 last_rotated_x509_certificate = now;
1263 /* We also make sure to rotate the TLS connections themselves if they've
1264 * been up for too long -- but that's done via is_bad_for_new_circs in
1265 * connection_run_housekeeping() above. */
1268 if (time_to_add_entropy < now) {
1269 if (time_to_add_entropy) {
1270 /* We already seeded once, so don't die on failure. */
1271 crypto_seed_rng(0);
1273 /** How often do we add more entropy to OpenSSL's RNG pool? */
1274 #define ENTROPY_INTERVAL (60*60)
1275 time_to_add_entropy = now + ENTROPY_INTERVAL;
1278 /* 1c. If we have to change the accounting interval or record
1279 * bandwidth used in this accounting interval, do so. */
1280 if (accounting_is_enabled(options))
1281 accounting_run_housekeeping(now);
1283 if (time_to_launch_reachability_tests < now &&
1284 (authdir_mode_tests_reachability(options)) &&
1285 !net_is_disabled()) {
1286 time_to_launch_reachability_tests = now + REACHABILITY_TEST_INTERVAL;
1287 /* try to determine reachability of the other Tor relays */
1288 dirserv_test_reachability(now);
1291 /* 1d. Periodically, we discount older stability information so that new
1292 * stability info counts more, and save the stability information to disk as
1293 * appropriate. */
1294 if (time_to_downrate_stability < now)
1295 time_to_downrate_stability = rep_hist_downrate_old_runs(now);
1296 if (authdir_mode_tests_reachability(options)) {
1297 if (time_to_save_stability < now) {
1298 if (time_to_save_stability && rep_hist_record_mtbf_data(now, 1)<0) {
1299 log_warn(LD_GENERAL, "Couldn't store mtbf data.");
1301 #define SAVE_STABILITY_INTERVAL (30*60)
1302 time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
1306 /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
1307 * close to expiring and warn the admin if it is. */
1308 if (time_to_check_v3_certificate < now) {
1309 v3_authority_check_key_expiry();
1310 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
1311 time_to_check_v3_certificate = now + CHECK_V3_CERTIFICATE_INTERVAL;
1314 /* 1f. Check whether our networkstatus has expired.
1316 if (time_to_check_for_expired_networkstatus < now) {
1317 networkstatus_t *ns = networkstatus_get_latest_consensus();
1318 /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
1319 * networkstatus_get_reasonably_live_consensus(), but that value is way
1320 * way too high. Arma: is the bridge issue there resolved yet? -NM */
1321 #define NS_EXPIRY_SLOP (24*60*60)
1322 if (ns && ns->valid_until < now+NS_EXPIRY_SLOP &&
1323 router_have_minimum_dir_info()) {
1324 router_dir_info_changed();
1326 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1327 time_to_check_for_expired_networkstatus = now + CHECK_EXPIRED_NS_INTERVAL;
1330 /* 1g. Check whether we should write statistics to disk.
1332 if (time_to_write_stats_files < now) {
1333 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1334 time_t next_time_to_write_stats_files = (time_to_write_stats_files > 0 ?
1335 time_to_write_stats_files : now) + CHECK_WRITE_STATS_INTERVAL;
1336 if (options->CellStatistics) {
1337 time_t next_write =
1338 rep_hist_buffer_stats_write(time_to_write_stats_files);
1339 if (next_write && next_write < next_time_to_write_stats_files)
1340 next_time_to_write_stats_files = next_write;
1342 if (options->DirReqStatistics) {
1343 time_t next_write = geoip_dirreq_stats_write(time_to_write_stats_files);
1344 if (next_write && next_write < next_time_to_write_stats_files)
1345 next_time_to_write_stats_files = next_write;
1347 if (options->EntryStatistics) {
1348 time_t next_write = geoip_entry_stats_write(time_to_write_stats_files);
1349 if (next_write && next_write < next_time_to_write_stats_files)
1350 next_time_to_write_stats_files = next_write;
1352 if (options->ExitPortStatistics) {
1353 time_t next_write = rep_hist_exit_stats_write(time_to_write_stats_files);
1354 if (next_write && next_write < next_time_to_write_stats_files)
1355 next_time_to_write_stats_files = next_write;
1357 if (options->ConnDirectionStatistics) {
1358 time_t next_write = rep_hist_conn_stats_write(time_to_write_stats_files);
1359 if (next_write && next_write < next_time_to_write_stats_files)
1360 next_time_to_write_stats_files = next_write;
1362 if (options->BridgeAuthoritativeDir) {
1363 time_t next_write = rep_hist_desc_stats_write(time_to_write_stats_files);
1364 if (next_write && next_write < next_time_to_write_stats_files)
1365 next_time_to_write_stats_files = next_write;
1367 time_to_write_stats_files = next_time_to_write_stats_files;
1370 /* 1h. Check whether we should write bridge statistics to disk.
1372 if (should_record_bridge_info(options)) {
1373 if (time_to_write_bridge_stats < now) {
1374 if (should_init_bridge_stats) {
1375 /* (Re-)initialize bridge statistics. */
1376 geoip_bridge_stats_init(now);
1377 time_to_write_bridge_stats = now + WRITE_STATS_INTERVAL;
1378 should_init_bridge_stats = 0;
1379 } else {
1380 /* Possibly write bridge statistics to disk and ask when to write
1381 * them next time. */
1382 time_to_write_bridge_stats = geoip_bridge_stats_write(
1383 time_to_write_bridge_stats);
1386 } else if (!should_init_bridge_stats) {
1387 /* Bridge mode was turned off. Ensure that stats are re-initialized
1388 * next time bridge mode is turned on. */
1389 should_init_bridge_stats = 1;
1392 /* Remove old information from rephist and the rend cache. */
1393 if (time_to_clean_caches < now) {
1394 rep_history_clean(now - options->RephistTrackTime);
1395 rend_cache_clean(now);
1396 rend_cache_clean_v2_descs_as_dir(now);
1397 microdesc_cache_rebuild(NULL, 0);
1398 #define CLEAN_CACHES_INTERVAL (30*60)
1399 time_to_clean_caches = now + CLEAN_CACHES_INTERVAL;
1402 #define RETRY_DNS_INTERVAL (10*60)
1403 /* If we're a server and initializing dns failed, retry periodically. */
1404 if (time_to_retry_dns_init < now) {
1405 time_to_retry_dns_init = now + RETRY_DNS_INTERVAL;
1406 if (is_server && has_dns_init_failed())
1407 dns_init();
1410 /* 2. Periodically, we consider force-uploading our descriptor
1411 * (if we've passed our internal checks). */
1413 /** How often do we check whether part of our router info has changed in a
1414 * way that would require an upload? That includes checking whether our IP
1415 * address has changed. */
1416 #define CHECK_DESCRIPTOR_INTERVAL (60)
1418 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1419 * one is inaccurate. */
1420 if (time_to_check_descriptor < now && !options->DisableNetwork) {
1421 static int dirport_reachability_count = 0;
1422 time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
1423 check_descriptor_bandwidth_changed(now);
1424 check_descriptor_ipaddress_changed(now);
1425 mark_my_descriptor_dirty_if_too_old(now);
1426 consider_publishable_server(0);
1427 /* also, check religiously for reachability, if it's within the first
1428 * 20 minutes of our uptime. */
1429 if (is_server &&
1430 (can_complete_circuit || !any_predicted_circuits(now)) &&
1431 !we_are_hibernating()) {
1432 if (stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1433 consider_testing_reachability(1, dirport_reachability_count==0);
1434 if (++dirport_reachability_count > 5)
1435 dirport_reachability_count = 0;
1436 } else if (time_to_recheck_bandwidth < now) {
1437 /* If we haven't checked for 12 hours and our bandwidth estimate is
1438 * low, do another bandwidth test. This is especially important for
1439 * bridges, since they might go long periods without much use. */
1440 const routerinfo_t *me = router_get_my_routerinfo();
1441 if (time_to_recheck_bandwidth && me &&
1442 me->bandwidthcapacity < me->bandwidthrate &&
1443 me->bandwidthcapacity < 51200) {
1444 reset_bandwidth_test();
1446 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1447 time_to_recheck_bandwidth = now + BANDWIDTH_RECHECK_INTERVAL;
1451 /* If any networkstatus documents are no longer recent, we need to
1452 * update all the descriptors' running status. */
1453 /* Remove dead routers. */
1454 routerlist_remove_old_routers();
1457 /* 2c. Every minute (or every second if TestingTorNetwork), check
1458 * whether we want to download any networkstatus documents. */
1460 /* How often do we check whether we should download network status
1461 * documents? */
1462 #define networkstatus_dl_check_interval(o) ((o)->TestingTorNetwork ? 1 : 60)
1464 if (time_to_download_networkstatus < now && !options->DisableNetwork) {
1465 time_to_download_networkstatus =
1466 now + networkstatus_dl_check_interval(options);
1467 update_networkstatus_downloads(now);
1470 /* 2c. Let directory voting happen. */
1471 if (authdir_mode_v3(options))
1472 dirvote_act(options, now);
1474 /* 3a. Every second, we examine pending circuits and prune the
1475 * ones which have been pending for more than a few seconds.
1476 * We do this before step 4, so it can try building more if
1477 * it's not comfortable with the number of available circuits.
1479 /* (If our circuit build timeout can ever become lower than a second (which
1480 * it can't, currently), we should do this more often.) */
1481 circuit_expire_building();
1483 /* 3b. Also look at pending streams and prune the ones that 'began'
1484 * a long time ago but haven't gotten a 'connected' yet.
1485 * Do this before step 4, so we can put them back into pending
1486 * state to be picked up by the new circuit.
1488 connection_ap_expire_beginning();
1490 /* 3c. And expire connections that we've held open for too long.
1492 connection_expire_held_open();
1494 /* 3d. And every 60 seconds, we relaunch listeners if any died. */
1495 if (!net_is_disabled() && time_to_check_listeners < now) {
1496 retry_all_listeners(NULL, NULL, 0);
1497 time_to_check_listeners = now+60;
1500 /* 4. Every second, we try a new circuit if there are no valid
1501 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1502 * that became dirty more than MaxCircuitDirtiness seconds ago,
1503 * and we make a new circ if there are no clean circuits.
1505 have_dir_info = router_have_minimum_dir_info();
1506 if (have_dir_info && !net_is_disabled())
1507 circuit_build_needed_circs(now);
1509 /* every 10 seconds, but not at the same second as other such events */
1510 if (now % 10 == 5)
1511 circuit_expire_old_circuits_serverside(now);
1513 /* 5. We do housekeeping for each connection... */
1514 connection_or_set_bad_connections(NULL, 0);
1515 for (i=0;i<smartlist_len(connection_array);i++) {
1516 run_connection_housekeeping(i, now);
1518 if (time_to_shrink_memory < now) {
1519 SMARTLIST_FOREACH(connection_array, connection_t *, conn, {
1520 if (conn->outbuf)
1521 buf_shrink(conn->outbuf);
1522 if (conn->inbuf)
1523 buf_shrink(conn->inbuf);
1525 #ifdef ENABLE_MEMPOOL
1526 clean_cell_pool();
1527 #endif /* ENABLE_MEMPOOL */
1528 buf_shrink_freelists(0);
1529 /** How often do we check buffers and pools for empty space that can be
1530 * deallocated? */
1531 #define MEM_SHRINK_INTERVAL (60)
1532 time_to_shrink_memory = now + MEM_SHRINK_INTERVAL;
1535 /* 6. And remove any marked circuits... */
1536 circuit_close_all_marked();
1538 /* 7. And upload service descriptors if necessary. */
1539 if (can_complete_circuit && !net_is_disabled()) {
1540 rend_consider_services_upload(now);
1541 rend_consider_descriptor_republication();
1544 /* 8. and blow away any connections that need to die. have to do this now,
1545 * because if we marked a conn for close and left its socket -1, then
1546 * we'll pass it to poll/select and bad things will happen.
1548 close_closeable_connections();
1550 /* 8b. And if anything in our state is ready to get flushed to disk, we
1551 * flush it. */
1552 or_state_save(now);
1554 /* 8c. Do channel cleanup just like for connections */
1555 channel_run_cleanup();
1556 channel_listener_run_cleanup();
1558 /* 9. and if we're an exit node, check whether our DNS is telling stories
1559 * to us. */
1560 if (!net_is_disabled() &&
1561 public_server_mode(options) &&
1562 time_to_check_for_correct_dns < now &&
1563 ! router_my_exit_policy_is_reject_star()) {
1564 if (!time_to_check_for_correct_dns) {
1565 time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
1566 } else {
1567 dns_launch_correctness_checks();
1568 time_to_check_for_correct_dns = now + 12*3600 +
1569 crypto_rand_int(12*3600);
1573 /* 10. write bridge networkstatus file to disk */
1574 if (options->BridgeAuthoritativeDir &&
1575 time_to_write_bridge_status_file < now) {
1576 networkstatus_dump_bridge_status_to_file(now);
1577 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
1578 time_to_write_bridge_status_file = now+BRIDGE_STATUSFILE_INTERVAL;
1581 /* 11. check the port forwarding app */
1582 if (!net_is_disabled() &&
1583 time_to_check_port_forwarding < now &&
1584 options->PortForwarding &&
1585 is_server) {
1586 #define PORT_FORWARDING_CHECK_INTERVAL 5
1587 smartlist_t *ports_to_forward = get_list_of_ports_to_forward();
1588 if (ports_to_forward) {
1589 tor_check_port_forwarding(options->PortForwardingHelper,
1590 ports_to_forward,
1591 now);
1593 SMARTLIST_FOREACH(ports_to_forward, char *, cp, tor_free(cp));
1594 smartlist_free(ports_to_forward);
1596 time_to_check_port_forwarding = now+PORT_FORWARDING_CHECK_INTERVAL;
1599 /* 11b. check pending unconfigured managed proxies */
1600 if (!net_is_disabled() && pt_proxies_configuration_pending())
1601 pt_configure_remaining_proxies();
1603 /* 12. write the heartbeat message */
1604 if (options->HeartbeatPeriod &&
1605 time_to_next_heartbeat <= now) {
1606 if (time_to_next_heartbeat) /* don't log the first heartbeat */
1607 log_heartbeat(now);
1608 time_to_next_heartbeat = now+options->HeartbeatPeriod;
1612 /** Timer: used to invoke second_elapsed_callback() once per second. */
1613 static periodic_timer_t *second_timer = NULL;
1614 /** Number of libevent errors in the last second: we die if we get too many. */
1615 static int n_libevent_errors = 0;
1617 /** Libevent callback: invoked once every second. */
1618 static void
1619 second_elapsed_callback(periodic_timer_t *timer, void *arg)
1621 /* XXXX This could be sensibly refactored into multiple callbacks, and we
1622 * could use Libevent's timers for this rather than checking the current
1623 * time against a bunch of timeouts every second. */
1624 static time_t current_second = 0;
1625 time_t now;
1626 size_t bytes_written;
1627 size_t bytes_read;
1628 int seconds_elapsed;
1629 const or_options_t *options = get_options();
1630 (void)timer;
1631 (void)arg;
1633 n_libevent_errors = 0;
1635 /* log_notice(LD_GENERAL, "Tick."); */
1636 now = time(NULL);
1637 update_approx_time(now);
1639 /* the second has rolled over. check more stuff. */
1640 seconds_elapsed = current_second ? (int)(now - current_second) : 0;
1641 #ifdef USE_BUFFEREVENTS
1643 uint64_t cur_read,cur_written;
1644 connection_get_rate_limit_totals(&cur_read, &cur_written);
1645 bytes_written = (size_t)(cur_written - stats_prev_n_written);
1646 bytes_read = (size_t)(cur_read - stats_prev_n_read);
1647 stats_n_bytes_read += bytes_read;
1648 stats_n_bytes_written += bytes_written;
1649 if (accounting_is_enabled(options) && seconds_elapsed >= 0)
1650 accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
1651 stats_prev_n_written = cur_written;
1652 stats_prev_n_read = cur_read;
1654 #else
1655 bytes_read = (size_t)(stats_n_bytes_read - stats_prev_n_read);
1656 bytes_written = (size_t)(stats_n_bytes_written - stats_prev_n_written);
1657 stats_prev_n_read = stats_n_bytes_read;
1658 stats_prev_n_written = stats_n_bytes_written;
1659 #endif
1661 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
1662 control_event_stream_bandwidth_used();
1663 control_event_conn_bandwidth_used();
1664 control_event_circ_bandwidth_used();
1665 control_event_circuit_cell_stats();
1667 if (server_mode(options) &&
1668 !net_is_disabled() &&
1669 seconds_elapsed > 0 &&
1670 can_complete_circuit &&
1671 stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
1672 (stats_n_seconds_working+seconds_elapsed) /
1673 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1674 /* every 20 minutes, check and complain if necessary */
1675 const routerinfo_t *me = router_get_my_routerinfo();
1676 if (me && !check_whether_orport_reachable()) {
1677 char *address = tor_dup_ip(me->addr);
1678 log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
1679 "its ORPort is reachable. Please check your firewalls, ports, "
1680 "address, /etc/hosts file, etc.",
1681 address, me->or_port);
1682 control_event_server_status(LOG_WARN,
1683 "REACHABILITY_FAILED ORADDRESS=%s:%d",
1684 address, me->or_port);
1685 tor_free(address);
1688 if (me && !check_whether_dirport_reachable()) {
1689 char *address = tor_dup_ip(me->addr);
1690 log_warn(LD_CONFIG,
1691 "Your server (%s:%d) has not managed to confirm that its "
1692 "DirPort is reachable. Please check your firewalls, ports, "
1693 "address, /etc/hosts file, etc.",
1694 address, me->dir_port);
1695 control_event_server_status(LOG_WARN,
1696 "REACHABILITY_FAILED DIRADDRESS=%s:%d",
1697 address, me->dir_port);
1698 tor_free(address);
1702 /** If more than this many seconds have elapsed, probably the clock
1703 * jumped: doesn't count. */
1704 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
1705 if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
1706 seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
1707 circuit_note_clock_jumped(seconds_elapsed);
1708 /* XXX if the time jumps *back* many months, do our events in
1709 * run_scheduled_events() recover? I don't think they do. -RD */
1710 } else if (seconds_elapsed > 0)
1711 stats_n_seconds_working += seconds_elapsed;
1713 run_scheduled_events(now);
1715 current_second = now; /* remember which second it is, for next time */
1718 #ifndef USE_BUFFEREVENTS
1719 /** Timer: used to invoke refill_callback(). */
1720 static periodic_timer_t *refill_timer = NULL;
1722 /** Libevent callback: invoked periodically to refill token buckets
1723 * and count r/w bytes. It is only used when bufferevents are disabled. */
1724 static void
1725 refill_callback(periodic_timer_t *timer, void *arg)
1727 static struct timeval current_millisecond;
1728 struct timeval now;
1730 size_t bytes_written;
1731 size_t bytes_read;
1732 int milliseconds_elapsed = 0;
1733 int seconds_rolled_over = 0;
1735 const or_options_t *options = get_options();
1737 (void)timer;
1738 (void)arg;
1740 tor_gettimeofday(&now);
1742 /* If this is our first time, no time has passed. */
1743 if (current_millisecond.tv_sec) {
1744 long mdiff = tv_mdiff(&current_millisecond, &now);
1745 if (mdiff > INT_MAX)
1746 mdiff = INT_MAX;
1747 milliseconds_elapsed = (int)mdiff;
1748 seconds_rolled_over = (int)(now.tv_sec - current_millisecond.tv_sec);
1751 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
1752 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
1754 stats_n_bytes_read += bytes_read;
1755 stats_n_bytes_written += bytes_written;
1756 if (accounting_is_enabled(options) && milliseconds_elapsed >= 0)
1757 accounting_add_bytes(bytes_read, bytes_written, seconds_rolled_over);
1759 if (milliseconds_elapsed > 0)
1760 connection_bucket_refill(milliseconds_elapsed, (time_t)now.tv_sec);
1762 stats_prev_global_read_bucket = global_read_bucket;
1763 stats_prev_global_write_bucket = global_write_bucket;
1765 current_millisecond = now; /* remember what time it is, for next time */
1767 #endif
1769 #ifndef _WIN32
1770 /** Called when a possibly ignorable libevent error occurs; ensures that we
1771 * don't get into an infinite loop by ignoring too many errors from
1772 * libevent. */
1773 static int
1774 got_libevent_error(void)
1776 if (++n_libevent_errors > 8) {
1777 log_err(LD_NET, "Too many libevent errors in one second; dying");
1778 return -1;
1780 return 0;
1782 #endif
1784 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
1786 /** Called when our IP address seems to have changed. <b>at_interface</b>
1787 * should be true if we detected a change in our interface, and false if we
1788 * detected a change in our published address. */
1789 void
1790 ip_address_changed(int at_interface)
1792 int server = server_mode(get_options());
1794 if (at_interface) {
1795 if (! server) {
1796 /* Okay, change our keys. */
1797 if (init_keys()<0)
1798 log_warn(LD_GENERAL, "Unable to rotate keys after IP change!");
1800 } else {
1801 if (server) {
1802 if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
1803 reset_bandwidth_test();
1804 stats_n_seconds_working = 0;
1805 router_reset_reachability();
1806 mark_my_descriptor_dirty("IP address changed");
1810 dns_servers_relaunch_checks();
1813 /** Forget what we've learned about the correctness of our DNS servers, and
1814 * start learning again. */
1815 void
1816 dns_servers_relaunch_checks(void)
1818 if (server_mode(get_options())) {
1819 dns_reset_correctness_checks();
1820 time_to_check_for_correct_dns = 0;
1824 /** Called when we get a SIGHUP: reload configuration files and keys,
1825 * retry all connections, and so on. */
1826 static int
1827 do_hup(void)
1829 const or_options_t *options = get_options();
1831 #ifdef USE_DMALLOC
1832 dmalloc_log_stats();
1833 dmalloc_log_changed(0, 1, 0, 0);
1834 #endif
1836 log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
1837 "resetting internal state.");
1838 if (accounting_is_enabled(options))
1839 accounting_record_bandwidth_usage(time(NULL), get_or_state());
1841 router_reset_warnings();
1842 routerlist_reset_warnings();
1843 /* first, reload config variables, in case they've changed */
1844 if (options->ReloadTorrcOnSIGHUP) {
1845 /* no need to provide argc/v, they've been cached in init_from_config */
1846 if (options_init_from_torrc(0, NULL) < 0) {
1847 log_err(LD_CONFIG,"Reading config failed--see warnings above. "
1848 "For usage, try -h.");
1849 return -1;
1851 options = get_options(); /* they have changed now */
1852 } else {
1853 char *msg = NULL;
1854 log_notice(LD_GENERAL, "Not reloading config file: the controller told "
1855 "us not to.");
1856 /* Make stuff get rescanned, reloaded, etc. */
1857 if (set_options((or_options_t*)options, &msg) < 0) {
1858 if (!msg)
1859 msg = tor_strdup("Unknown error");
1860 log_warn(LD_GENERAL, "Unable to re-set previous options: %s", msg);
1861 tor_free(msg);
1864 if (authdir_mode_handles_descs(options, -1)) {
1865 /* reload the approved-routers file */
1866 if (dirserv_load_fingerprint_file() < 0) {
1867 /* warnings are logged from dirserv_load_fingerprint_file() directly */
1868 log_info(LD_GENERAL, "Error reloading fingerprints. "
1869 "Continuing with old list.");
1873 /* Rotate away from the old dirty circuits. This has to be done
1874 * after we've read the new options, but before we start using
1875 * circuits for directory fetches. */
1876 circuit_mark_all_dirty_circs_as_unusable();
1878 /* retry appropriate downloads */
1879 router_reset_status_download_failures();
1880 router_reset_descriptor_download_failures();
1881 if (!options->DisableNetwork)
1882 update_networkstatus_downloads(time(NULL));
1884 /* We'll retry routerstatus downloads in about 10 seconds; no need to
1885 * force a retry there. */
1887 if (server_mode(options)) {
1888 /* Restart cpuworker and dnsworker processes, so they get up-to-date
1889 * configuration options. */
1890 cpuworkers_rotate();
1891 dns_reset();
1893 return 0;
1896 /** Tor main loop. */
1898 do_main_loop(void)
1900 int loop_result;
1901 time_t now;
1903 /* initialize dns resolve map, spawn workers if needed */
1904 if (dns_init() < 0) {
1905 if (get_options()->ServerDNSAllowBrokenConfig)
1906 log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
1907 "Network not up yet? Will try again soon.");
1908 else {
1909 log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
1910 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
1914 #ifdef USE_BUFFEREVENTS
1915 log_warn(LD_GENERAL, "Tor was compiled with the --enable-bufferevents "
1916 "option. This is still experimental, and might cause strange "
1917 "bugs. If you want a more stable Tor, be sure to build without "
1918 "--enable-bufferevents.");
1919 #endif
1921 handle_signals(1);
1923 /* load the private keys, if we're supposed to have them, and set up the
1924 * TLS context. */
1925 if (! client_identity_key_is_set()) {
1926 if (init_keys() < 0) {
1927 log_err(LD_BUG,"Error initializing keys; exiting");
1928 return -1;
1932 #ifdef ENABLE_MEMPOOLS
1933 /* Set up the packed_cell_t memory pool. */
1934 init_cell_pool();
1935 #endif /* ENABLE_MEMPOOLS */
1937 /* Set up our buckets */
1938 connection_bucket_init();
1939 #ifndef USE_BUFFEREVENTS
1940 stats_prev_global_read_bucket = global_read_bucket;
1941 stats_prev_global_write_bucket = global_write_bucket;
1942 #endif
1944 /* initialize the bootstrap status events to know we're starting up */
1945 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
1947 if (trusted_dirs_reload_certs()) {
1948 log_warn(LD_DIR,
1949 "Couldn't load all cached v3 certificates. Starting anyway.");
1951 if (router_reload_consensus_networkstatus()) {
1952 return -1;
1954 /* load the routers file, or assign the defaults. */
1955 if (router_reload_router_list()) {
1956 return -1;
1958 /* load the networkstatuses. (This launches a download for new routers as
1959 * appropriate.)
1961 now = time(NULL);
1962 directory_info_has_arrived(now, 1);
1964 if (server_mode(get_options())) {
1965 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1966 cpu_init();
1969 /* set up once-a-second callback. */
1970 if (! second_timer) {
1971 struct timeval one_second;
1972 one_second.tv_sec = 1;
1973 one_second.tv_usec = 0;
1975 second_timer = periodic_timer_new(tor_libevent_get_base(),
1976 &one_second,
1977 second_elapsed_callback,
1978 NULL);
1979 tor_assert(second_timer);
1982 #ifndef USE_BUFFEREVENTS
1983 if (!refill_timer) {
1984 struct timeval refill_interval;
1985 int msecs = get_options()->TokenBucketRefillInterval;
1987 refill_interval.tv_sec = msecs/1000;
1988 refill_interval.tv_usec = (msecs%1000)*1000;
1990 refill_timer = periodic_timer_new(tor_libevent_get_base(),
1991 &refill_interval,
1992 refill_callback,
1993 NULL);
1994 tor_assert(refill_timer);
1996 #endif
1998 for (;;) {
1999 if (nt_service_is_stopping())
2000 return 0;
2002 #ifndef _WIN32
2003 /* Make it easier to tell whether libevent failure is our fault or not. */
2004 errno = 0;
2005 #endif
2006 /* All active linked conns should get their read events activated. */
2007 SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
2008 event_active(conn->read_event, EV_READ, 1));
2009 called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
2011 update_approx_time(time(NULL));
2013 /* poll until we have an event, or the second ends, or until we have
2014 * some active linked connections to trigger events for. */
2015 loop_result = event_base_loop(tor_libevent_get_base(),
2016 called_loop_once ? EVLOOP_ONCE : 0);
2018 /* let catch() handle things like ^c, and otherwise don't worry about it */
2019 if (loop_result < 0) {
2020 int e = tor_socket_errno(-1);
2021 /* let the program survive things like ^z */
2022 if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
2023 log_err(LD_NET,"libevent call with %s failed: %s [%d]",
2024 tor_libevent_get_method(), tor_socket_strerror(e), e);
2025 return -1;
2026 #ifndef _WIN32
2027 } else if (e == EINVAL) {
2028 log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
2029 if (got_libevent_error())
2030 return -1;
2031 #endif
2032 } else {
2033 if (ERRNO_IS_EINPROGRESS(e))
2034 log_warn(LD_BUG,
2035 "libevent call returned EINPROGRESS? Please report.");
2036 log_debug(LD_NET,"libevent call interrupted.");
2037 /* You can't trust the results of this poll(). Go back to the
2038 * top of the big for loop. */
2039 continue;
2045 #ifndef _WIN32 /* Only called when we're willing to use signals */
2046 /** Libevent callback: invoked when we get a signal.
2048 static void
2049 signal_callback(int fd, short events, void *arg)
2051 uintptr_t sig = (uintptr_t)arg;
2052 (void)fd;
2053 (void)events;
2055 process_signal(sig);
2057 #endif
2059 /** Do the work of acting on a signal received in <b>sig</b> */
2060 void
2061 process_signal(uintptr_t sig)
2063 switch (sig)
2065 case SIGTERM:
2066 log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
2067 tor_cleanup();
2068 exit(0);
2069 break;
2070 case SIGINT:
2071 if (!server_mode(get_options())) { /* do it now */
2072 log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
2073 tor_cleanup();
2074 exit(0);
2076 hibernate_begin_shutdown();
2077 break;
2078 #ifdef SIGPIPE
2079 case SIGPIPE:
2080 log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
2081 break;
2082 #endif
2083 case SIGUSR1:
2084 /* prefer to log it at INFO, but make sure we always see it */
2085 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
2086 control_event_signal(sig);
2087 break;
2088 case SIGUSR2:
2089 switch_logs_debug();
2090 log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
2091 "Send HUP to change back.");
2092 control_event_signal(sig);
2093 break;
2094 case SIGHUP:
2095 if (do_hup() < 0) {
2096 log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
2097 tor_cleanup();
2098 exit(1);
2100 control_event_signal(sig);
2101 break;
2102 #ifdef SIGCHLD
2103 case SIGCHLD:
2104 while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more
2105 zombies */
2106 break;
2107 #endif
2108 case SIGNEWNYM: {
2109 time_t now = time(NULL);
2110 if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
2111 signewnym_is_pending = 1;
2112 log_notice(LD_CONTROL,
2113 "Rate limiting NEWNYM request: delaying by %d second(s)",
2114 (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
2115 } else {
2116 signewnym_impl(now);
2118 break;
2120 case SIGCLEARDNSCACHE:
2121 addressmap_clear_transient();
2122 control_event_signal(sig);
2123 break;
2127 /** Returns Tor's uptime. */
2128 MOCK_IMPL(long,
2129 get_uptime,(void))
2131 return stats_n_seconds_working;
2134 extern uint64_t rephist_total_alloc;
2135 extern uint32_t rephist_total_num;
2138 * Write current memory usage information to the log.
2140 static void
2141 dumpmemusage(int severity)
2143 connection_dump_buffer_mem_stats(severity);
2144 tor_log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
2145 U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
2146 dump_routerlist_mem_usage(severity);
2147 dump_cell_pool_usage(severity);
2148 dump_dns_mem_usage(severity);
2149 buf_dump_freelist_sizes(severity);
2150 tor_log_mallinfo(severity);
2153 /** Write all statistics to the log, with log level <b>severity</b>. Called
2154 * in response to a SIGUSR1. */
2155 static void
2156 dumpstats(int severity)
2158 time_t now = time(NULL);
2159 time_t elapsed;
2160 size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
2162 tor_log(severity, LD_GENERAL, "Dumping stats:");
2164 SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
2165 int i = conn_sl_idx;
2166 tor_log(severity, LD_GENERAL,
2167 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
2168 i, (int)conn->s, conn->type, conn_type_to_string(conn->type),
2169 conn->state, conn_state_to_string(conn->type, conn->state),
2170 (int)(now - conn->timestamp_created));
2171 if (!connection_is_listener(conn)) {
2172 tor_log(severity,LD_GENERAL,
2173 "Conn %d is to %s:%d.", i,
2174 safe_str_client(conn->address),
2175 conn->port);
2176 tor_log(severity,LD_GENERAL,
2177 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
2179 (int)connection_get_inbuf_len(conn),
2180 (int)buf_allocation(conn->inbuf),
2181 (int)(now - conn->timestamp_lastread));
2182 tor_log(severity,LD_GENERAL,
2183 "Conn %d: %d bytes waiting on outbuf "
2184 "(len %d, last written %d secs ago)",i,
2185 (int)connection_get_outbuf_len(conn),
2186 (int)buf_allocation(conn->outbuf),
2187 (int)(now - conn->timestamp_lastwritten));
2188 if (conn->type == CONN_TYPE_OR) {
2189 or_connection_t *or_conn = TO_OR_CONN(conn);
2190 if (or_conn->tls) {
2191 tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
2192 &wbuf_cap, &wbuf_len);
2193 tor_log(severity, LD_GENERAL,
2194 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
2195 "%d/%d bytes used on write buffer.",
2196 i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
2200 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
2201 * using this conn */
2202 } SMARTLIST_FOREACH_END(conn);
2204 channel_dumpstats(severity);
2205 channel_listener_dumpstats(severity);
2207 tor_log(severity, LD_NET,
2208 "Cells processed: "U64_FORMAT" padding\n"
2209 " "U64_FORMAT" create\n"
2210 " "U64_FORMAT" created\n"
2211 " "U64_FORMAT" relay\n"
2212 " ("U64_FORMAT" relayed)\n"
2213 " ("U64_FORMAT" delivered)\n"
2214 " "U64_FORMAT" destroy",
2215 U64_PRINTF_ARG(stats_n_padding_cells_processed),
2216 U64_PRINTF_ARG(stats_n_create_cells_processed),
2217 U64_PRINTF_ARG(stats_n_created_cells_processed),
2218 U64_PRINTF_ARG(stats_n_relay_cells_processed),
2219 U64_PRINTF_ARG(stats_n_relay_cells_relayed),
2220 U64_PRINTF_ARG(stats_n_relay_cells_delivered),
2221 U64_PRINTF_ARG(stats_n_destroy_cells_processed));
2222 if (stats_n_data_cells_packaged)
2223 tor_log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
2224 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
2225 U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
2226 if (stats_n_data_cells_received)
2227 tor_log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
2228 100*(U64_TO_DBL(stats_n_data_bytes_received) /
2229 U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
2231 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_TAP, "TAP");
2232 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_NTOR,"ntor");
2234 if (now - time_of_process_start >= 0)
2235 elapsed = now - time_of_process_start;
2236 else
2237 elapsed = 0;
2239 if (elapsed) {
2240 tor_log(severity, LD_NET,
2241 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
2242 U64_PRINTF_ARG(stats_n_bytes_read),
2243 (int)elapsed,
2244 (int) (stats_n_bytes_read/elapsed));
2245 tor_log(severity, LD_NET,
2246 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
2247 U64_PRINTF_ARG(stats_n_bytes_written),
2248 (int)elapsed,
2249 (int) (stats_n_bytes_written/elapsed));
2252 tor_log(severity, LD_NET, "--------------- Dumping memory information:");
2253 dumpmemusage(severity);
2255 rep_hist_dump_stats(now,severity);
2256 rend_service_dump_stats(severity);
2257 dump_pk_ops(severity);
2258 dump_distinct_digest_count(severity);
2261 /** Called by exit() as we shut down the process.
2263 static void
2264 exit_function(void)
2266 /* NOTE: If we ever daemonize, this gets called immediately. That's
2267 * okay for now, because we only use this on Windows. */
2268 #ifdef _WIN32
2269 WSACleanup();
2270 #endif
2273 /** Set up the signal handlers for either parent or child. */
2274 void
2275 handle_signals(int is_parent)
2277 #ifndef _WIN32 /* do signal stuff only on Unix */
2278 int i;
2279 static const int signals[] = {
2280 SIGINT, /* do a controlled slow shutdown */
2281 SIGTERM, /* to terminate now */
2282 SIGPIPE, /* otherwise SIGPIPE kills us */
2283 SIGUSR1, /* dump stats */
2284 SIGUSR2, /* go to loglevel debug */
2285 SIGHUP, /* to reload config, retry conns, etc */
2286 #ifdef SIGXFSZ
2287 SIGXFSZ, /* handle file-too-big resource exhaustion */
2288 #endif
2289 SIGCHLD, /* handle dns/cpu workers that exit */
2290 -1 };
2291 static struct event *signal_events[16]; /* bigger than it has to be. */
2292 if (is_parent) {
2293 for (i = 0; signals[i] >= 0; ++i) {
2294 signal_events[i] = tor_evsignal_new(
2295 tor_libevent_get_base(), signals[i], signal_callback,
2296 (void*)(uintptr_t)signals[i]);
2297 if (event_add(signal_events[i], NULL))
2298 log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
2299 signals[i]);
2301 } else {
2302 struct sigaction action;
2303 action.sa_flags = 0;
2304 sigemptyset(&action.sa_mask);
2305 action.sa_handler = SIG_IGN;
2306 sigaction(SIGINT, &action, NULL);
2307 sigaction(SIGTERM, &action, NULL);
2308 sigaction(SIGPIPE, &action, NULL);
2309 sigaction(SIGUSR1, &action, NULL);
2310 sigaction(SIGUSR2, &action, NULL);
2311 sigaction(SIGHUP, &action, NULL);
2312 #ifdef SIGXFSZ
2313 sigaction(SIGXFSZ, &action, NULL);
2314 #endif
2316 #else /* MS windows */
2317 (void)is_parent;
2318 #endif /* signal stuff */
2321 /** Main entry point for the Tor command-line client.
2324 tor_init(int argc, char *argv[])
2326 char progname[256];
2327 int quiet = 0;
2329 time_of_process_start = time(NULL);
2330 init_connection_lists();
2331 /* Have the log set up with our application name. */
2332 tor_snprintf(progname, sizeof(progname), "Tor %s", get_version());
2333 log_set_application_name(progname);
2335 /* Set up the crypto nice and early */
2336 if (crypto_early_init() < 0) {
2337 log_err(LD_GENERAL, "Unable to initialize the crypto subsystem!");
2338 return 1;
2341 /* Initialize the history structures. */
2342 rep_hist_init();
2343 /* Initialize the service cache. */
2344 rend_cache_init();
2345 addressmap_init(); /* Init the client dns cache. Do it always, since it's
2346 * cheap. */
2349 /* We search for the "quiet" option first, since it decides whether we
2350 * will log anything at all to the command line. */
2351 config_line_t *opts = NULL, *cmdline_opts = NULL;
2352 const config_line_t *cl;
2353 (void) config_parse_commandline(argc, argv, 1, &opts, &cmdline_opts);
2354 for (cl = cmdline_opts; cl; cl = cl->next) {
2355 if (!strcmp(cl->key, "--hush"))
2356 quiet = 1;
2357 if (!strcmp(cl->key, "--quiet") ||
2358 !strcmp(cl->key, "--dump-config"))
2359 quiet = 2;
2360 /* --version, --digests, and --help imply --hush */
2361 if (!strcmp(cl->key, "--version") || !strcmp(cl->key, "--digests") ||
2362 !strcmp(cl->key, "--list-torrc-options") ||
2363 !strcmp(cl->key, "--library-versions") ||
2364 !strcmp(cl->key, "-h") || !strcmp(cl->key, "--help")) {
2365 if (quiet < 1)
2366 quiet = 1;
2369 config_free_lines(opts);
2370 config_free_lines(cmdline_opts);
2373 /* give it somewhere to log to initially */
2374 switch (quiet) {
2375 case 2:
2376 /* no initial logging */
2377 break;
2378 case 1:
2379 add_temp_log(LOG_WARN);
2380 break;
2381 default:
2382 add_temp_log(LOG_NOTICE);
2384 quiet_level = quiet;
2387 const char *version = get_version();
2388 const char *bev_str =
2389 #ifdef USE_BUFFEREVENTS
2390 "(with bufferevents) ";
2391 #else
2393 #endif
2394 log_notice(LD_GENERAL, "Tor v%s %srunning on %s with Libevent %s, "
2395 "OpenSSL %s and Zlib %s.", version, bev_str,
2396 get_uname(),
2397 tor_libevent_get_version_str(),
2398 crypto_openssl_get_version_str(),
2399 tor_zlib_get_version_str());
2401 log_notice(LD_GENERAL, "Tor can't help you if you use it wrong! "
2402 "Learn how to be safe at "
2403 "https://www.torproject.org/download/download#warning");
2405 if (strstr(version, "alpha") || strstr(version, "beta"))
2406 log_notice(LD_GENERAL, "This version is not a stable Tor release. "
2407 "Expect more bugs than usual.");
2410 #ifdef NON_ANONYMOUS_MODE_ENABLED
2411 log_warn(LD_GENERAL, "This copy of Tor was compiled to run in a "
2412 "non-anonymous mode. It will provide NO ANONYMITY.");
2413 #endif
2415 if (network_init()<0) {
2416 log_err(LD_BUG,"Error initializing network; exiting.");
2417 return -1;
2419 atexit(exit_function);
2421 if (options_init_from_torrc(argc,argv) < 0) {
2422 log_err(LD_CONFIG,"Reading config failed--see warnings above.");
2423 return -1;
2426 #ifndef _WIN32
2427 if (geteuid()==0)
2428 log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
2429 "and you probably shouldn't.");
2430 #endif
2432 if (crypto_global_init(get_options()->HardwareAccel,
2433 get_options()->AccelName,
2434 get_options()->AccelDir)) {
2435 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
2436 return -1;
2438 stream_choice_seed_weak_rng();
2439 if (tor_init_libevent_rng() < 0) {
2440 log_warn(LD_NET, "Problem initializing libevent RNG.");
2443 return 0;
2446 /** A lockfile structure, used to prevent two Tors from messing with the
2447 * data directory at once. If this variable is non-NULL, we're holding
2448 * the lockfile. */
2449 static tor_lockfile_t *lockfile = NULL;
2451 /** Try to grab the lock file described in <b>options</b>, if we do not
2452 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
2453 * holding the lock, and exit if we can't get it after waiting. Otherwise,
2454 * return -1 if we can't get the lockfile. Return 0 on success.
2457 try_locking(const or_options_t *options, int err_if_locked)
2459 if (lockfile)
2460 return 0;
2461 else {
2462 char *fname = options_get_datadir_fname2_suffix(options, "lock",NULL,NULL);
2463 int already_locked = 0;
2464 tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
2465 tor_free(fname);
2466 if (!lf) {
2467 if (err_if_locked && already_locked) {
2468 int r;
2469 log_warn(LD_GENERAL, "It looks like another Tor process is running "
2470 "with the same data directory. Waiting 5 seconds to see "
2471 "if it goes away.");
2472 #ifndef _WIN32
2473 sleep(5);
2474 #else
2475 Sleep(5000);
2476 #endif
2477 r = try_locking(options, 0);
2478 if (r<0) {
2479 log_err(LD_GENERAL, "No, it's still there. Exiting.");
2480 exit(0);
2482 return r;
2484 return -1;
2486 lockfile = lf;
2487 return 0;
2491 /** Return true iff we've successfully acquired the lock file. */
2493 have_lockfile(void)
2495 return lockfile != NULL;
2498 /** If we have successfully acquired the lock file, release it. */
2499 void
2500 release_lockfile(void)
2502 if (lockfile) {
2503 tor_lockfile_unlock(lockfile);
2504 lockfile = NULL;
2508 /** Free all memory that we might have allocated somewhere.
2509 * If <b>postfork</b>, we are a worker process and we want to free
2510 * only the parts of memory that we won't touch. If !<b>postfork</b>,
2511 * Tor is shutting down and we should free everything.
2513 * Helps us find the real leaks with dmalloc and the like. Also valgrind
2514 * should then report 0 reachable in its leak report (in an ideal world --
2515 * in practice libevent, SSL, libc etc never quite free everything). */
2516 void
2517 tor_free_all(int postfork)
2519 if (!postfork) {
2520 evdns_shutdown(1);
2522 geoip_free_all();
2523 dirvote_free_all();
2524 routerlist_free_all();
2525 networkstatus_free_all();
2526 addressmap_free_all();
2527 dirserv_free_all();
2528 rend_service_free_all();
2529 rend_cache_free_all();
2530 rend_service_authorization_free_all();
2531 rep_hist_free_all();
2532 dns_free_all();
2533 clear_pending_onions();
2534 circuit_free_all();
2535 entry_guards_free_all();
2536 pt_free_all();
2537 channel_tls_free_all();
2538 channel_free_all();
2539 connection_free_all();
2540 buf_shrink_freelists(1);
2541 memarea_clear_freelist();
2542 nodelist_free_all();
2543 microdesc_free_all();
2544 ext_orport_free_all();
2545 control_free_all();
2546 if (!postfork) {
2547 config_free_all();
2548 or_state_free_all();
2549 router_free_all();
2550 policies_free_all();
2552 #ifdef ENABLE_MEMPOOLS
2553 free_cell_pool();
2554 #endif /* ENABLE_MEMPOOLS */
2555 if (!postfork) {
2556 tor_tls_free_all();
2557 #ifndef _WIN32
2558 tor_getpwnam(NULL);
2559 #endif
2561 /* stuff in main.c */
2563 smartlist_free(connection_array);
2564 smartlist_free(closeable_connection_lst);
2565 smartlist_free(active_linked_connection_lst);
2566 periodic_timer_free(second_timer);
2567 #ifndef USE_BUFFEREVENTS
2568 periodic_timer_free(refill_timer);
2569 #endif
2571 if (!postfork) {
2572 release_lockfile();
2574 /* Stuff in util.c and address.c*/
2575 if (!postfork) {
2576 escaped(NULL);
2577 esc_router_info(NULL);
2578 logs_free_all(); /* free log strings. do this last so logs keep working. */
2582 /** Do whatever cleanup is necessary before shutting Tor down. */
2583 void
2584 tor_cleanup(void)
2586 const or_options_t *options = get_options();
2587 if (options->command == CMD_RUN_TOR) {
2588 time_t now = time(NULL);
2589 /* Remove our pid file. We don't care if there was an error when we
2590 * unlink, nothing we could do about it anyways. */
2591 if (options->PidFile) {
2592 if (unlink(options->PidFile) != 0) {
2593 log_warn(LD_FS, "Couldn't unlink pid file %s: %s",
2594 options->PidFile, strerror(errno));
2597 if (options->ControlPortWriteToFile) {
2598 if (unlink(options->ControlPortWriteToFile) != 0) {
2599 log_warn(LD_FS, "Couldn't unlink control port file %s: %s",
2600 options->ControlPortWriteToFile,
2601 strerror(errno));
2604 if (accounting_is_enabled(options))
2605 accounting_record_bandwidth_usage(now, get_or_state());
2606 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
2607 or_state_save(now);
2608 if (authdir_mode_tests_reachability(options))
2609 rep_hist_record_mtbf_data(now, 0);
2611 #ifdef USE_DMALLOC
2612 dmalloc_log_stats();
2613 #endif
2614 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
2615 later, if it makes shutdown unacceptably slow. But for
2616 now, leave it here: it's helped us catch bugs in the
2617 past. */
2618 crypto_global_cleanup();
2619 #ifdef USE_DMALLOC
2620 dmalloc_log_unfreed();
2621 dmalloc_shutdown();
2622 #endif
2625 /** Read/create keys as needed, and echo our fingerprint to stdout. */
2626 static int
2627 do_list_fingerprint(void)
2629 char buf[FINGERPRINT_LEN+1];
2630 crypto_pk_t *k;
2631 const char *nickname = get_options()->Nickname;
2632 if (!server_mode(get_options())) {
2633 log_err(LD_GENERAL,
2634 "Clients don't have long-term identity keys. Exiting.");
2635 return -1;
2637 tor_assert(nickname);
2638 if (init_keys() < 0) {
2639 log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
2640 return -1;
2642 if (!(k = get_server_identity_key())) {
2643 log_err(LD_GENERAL,"Error: missing identity key.");
2644 return -1;
2646 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
2647 log_err(LD_BUG, "Error computing fingerprint");
2648 return -1;
2650 printf("%s %s\n", nickname, buf);
2651 return 0;
2654 /** Entry point for password hashing: take the desired password from
2655 * the command line, and print its salted hash to stdout. **/
2656 static void
2657 do_hash_password(void)
2660 char output[256];
2661 char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
2663 crypto_rand(key, S2K_SPECIFIER_LEN-1);
2664 key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
2665 secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
2666 get_options()->command_arg, strlen(get_options()->command_arg),
2667 key);
2668 base16_encode(output, sizeof(output), key, sizeof(key));
2669 printf("16:%s\n",output);
2672 /** Entry point for configuration dumping: write the configuration to
2673 * stdout. */
2674 static int
2675 do_dump_config(void)
2677 const or_options_t *options = get_options();
2678 const char *arg = options->command_arg;
2679 int how;
2680 char *opts;
2681 if (!strcmp(arg, "short")) {
2682 how = OPTIONS_DUMP_MINIMAL;
2683 } else if (!strcmp(arg, "non-builtin")) {
2684 how = OPTIONS_DUMP_DEFAULTS;
2685 } else if (!strcmp(arg, "full")) {
2686 how = OPTIONS_DUMP_ALL;
2687 } else {
2688 printf("%s is not a recognized argument to --dump-config. "
2689 "Please select 'short', 'non-builtin', or 'full'", arg);
2690 return -1;
2693 opts = options_dump(options, how);
2694 printf("%s", opts);
2695 tor_free(opts);
2697 return 0;
2700 #if defined (WINCE)
2702 find_flashcard_path(PWCHAR path, size_t size)
2704 WIN32_FIND_DATA d = {0};
2705 HANDLE h = NULL;
2707 if (!path)
2708 return -1;
2710 h = FindFirstFlashCard(&d);
2711 if (h == INVALID_HANDLE_VALUE)
2712 return -1;
2714 if (wcslen(d.cFileName) == 0) {
2715 FindClose(h);
2716 return -1;
2719 wcsncpy(path,d.cFileName,size);
2720 FindClose(h);
2721 return 0;
2723 #endif
2725 static void
2726 init_addrinfo(void)
2728 char hname[256];
2730 // host name to sandbox
2731 gethostname(hname, sizeof(hname));
2732 sandbox_add_addrinfo(hname);
2735 static sandbox_cfg_t*
2736 sandbox_init_filter(void)
2738 const or_options_t *options = get_options();
2739 sandbox_cfg_t *cfg = sandbox_cfg_new();
2740 int i;
2742 sandbox_cfg_allow_openat_filename(&cfg,
2743 get_datadir_fname("cached-status"));
2745 sandbox_cfg_allow_open_filename_array(&cfg,
2746 get_datadir_fname("cached-certs"),
2747 get_datadir_fname("cached-certs.tmp"),
2748 get_datadir_fname("cached-consensus"),
2749 get_datadir_fname("cached-consensus.tmp"),
2750 get_datadir_fname("unverified-consensus"),
2751 get_datadir_fname("unverified-consensus.tmp"),
2752 get_datadir_fname("unverified-microdesc-consensus"),
2753 get_datadir_fname("unverified-microdesc-consensus.tmp"),
2754 get_datadir_fname("cached-microdesc-consensus"),
2755 get_datadir_fname("cached-microdesc-consensus.tmp"),
2756 get_datadir_fname("cached-microdescs"),
2757 get_datadir_fname("cached-microdescs.tmp"),
2758 get_datadir_fname("cached-microdescs.new"),
2759 get_datadir_fname("cached-microdescs.new.tmp"),
2760 get_datadir_fname("cached-descriptors"),
2761 get_datadir_fname("cached-descriptors.new"),
2762 get_datadir_fname("cached-descriptors.tmp"),
2763 get_datadir_fname("cached-descriptors.new.tmp"),
2764 get_datadir_fname("cached-descriptors.tmp.tmp"),
2765 get_datadir_fname("cached-extrainfo"),
2766 get_datadir_fname("cached-extrainfo.new"),
2767 get_datadir_fname("cached-extrainfo.tmp"),
2768 get_datadir_fname("cached-extrainfo.new.tmp"),
2769 get_datadir_fname("cached-extrainfo.tmp.tmp"),
2770 get_datadir_fname("state.tmp"),
2771 get_datadir_fname("unparseable-desc.tmp"),
2772 get_datadir_fname("unparseable-desc"),
2773 get_datadir_fname("v3-status-votes"),
2774 get_datadir_fname("v3-status-votes.tmp"),
2775 tor_strdup("/dev/srandom"),
2776 tor_strdup("/dev/urandom"),
2777 tor_strdup("/dev/random"),
2778 tor_strdup("/etc/hosts"),
2779 tor_strdup("/proc/meminfo"),
2780 NULL, 0
2782 if (options->ServerDNSResolvConfFile)
2783 sandbox_cfg_allow_open_filename(&cfg,
2784 tor_strdup(options->ServerDNSResolvConfFile));
2785 else
2786 sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
2788 for (i = 0; i < 2; ++i) {
2789 if (get_torrc_fname(i)) {
2790 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(get_torrc_fname(i)));
2794 #define RENAME_SUFFIX(name, suffix) \
2795 sandbox_cfg_allow_rename(&cfg, \
2796 get_datadir_fname(name suffix), \
2797 get_datadir_fname(name))
2799 #define RENAME_SUFFIX2(prefix, name, suffix) \
2800 sandbox_cfg_allow_rename(&cfg, \
2801 get_datadir_fname2(prefix, name suffix), \
2802 get_datadir_fname2(prefix, name))
2804 RENAME_SUFFIX("cached-certs", ".tmp");
2805 RENAME_SUFFIX("cached-consensus", ".tmp");
2806 RENAME_SUFFIX("unverified-consensus", ".tmp");
2807 RENAME_SUFFIX("unverified-microdesc-consensus", ".tmp");
2808 RENAME_SUFFIX("cached-microdesc-consensus", ".tmp");
2809 RENAME_SUFFIX("cached-microdescs", ".tmp");
2810 RENAME_SUFFIX("cached-microdescs", ".new");
2811 RENAME_SUFFIX("cached-microdescs.new", ".tmp");
2812 RENAME_SUFFIX("cached-descriptors", ".tmp");
2813 RENAME_SUFFIX("cached-descriptors", ".new");
2814 RENAME_SUFFIX("cached-descriptors.new", ".tmp");
2815 RENAME_SUFFIX("cached-extrainfo", ".tmp");
2816 RENAME_SUFFIX("cached-extrainfo", ".new");
2817 RENAME_SUFFIX("cached-extrainfo.new", ".tmp");
2818 RENAME_SUFFIX("state", ".tmp");
2819 RENAME_SUFFIX("unparseable-desc", ".tmp");
2820 RENAME_SUFFIX("v3-status-votes", ".tmp");
2822 sandbox_cfg_allow_stat_filename_array(&cfg,
2823 get_datadir_fname(NULL),
2824 get_datadir_fname("lock"),
2825 get_datadir_fname("state"),
2826 get_datadir_fname("router-stability"),
2827 get_datadir_fname("cached-extrainfo.new"),
2828 NULL, 0
2832 smartlist_t *logfiles = smartlist_new();
2833 tor_log_get_logfile_names(logfiles);
2834 SMARTLIST_FOREACH(logfiles, char *, logfile_name, {
2835 /* steals reference */
2836 sandbox_cfg_allow_open_filename(&cfg, logfile_name);
2838 smartlist_free(logfiles);
2841 // orport
2842 if (server_mode(get_options())) {
2843 sandbox_cfg_allow_open_filename_array(&cfg,
2844 get_datadir_fname2("keys", "secret_id_key"),
2845 get_datadir_fname2("keys", "secret_onion_key"),
2846 get_datadir_fname2("keys", "secret_onion_key_ntor"),
2847 get_datadir_fname2("keys", "secret_onion_key_ntor.tmp"),
2848 get_datadir_fname2("keys", "secret_id_key.old"),
2849 get_datadir_fname2("keys", "secret_onion_key.old"),
2850 get_datadir_fname2("keys", "secret_onion_key_ntor.old"),
2851 get_datadir_fname2("keys", "secret_onion_key.tmp"),
2852 get_datadir_fname2("keys", "secret_id_key.tmp"),
2853 get_datadir_fname2("stats", "bridge-stats"),
2854 get_datadir_fname2("stats", "bridge-stats.tmp"),
2855 get_datadir_fname2("stats", "dirreq-stats"),
2856 get_datadir_fname2("stats", "dirreq-stats.tmp"),
2857 get_datadir_fname("fingerprint"),
2858 get_datadir_fname("fingerprint.tmp"),
2859 get_datadir_fname("hashed-fingerprint"),
2860 get_datadir_fname("hashed-fingerprint.tmp"),
2861 get_datadir_fname("router-stability"),
2862 get_datadir_fname("router-stability.tmp"),
2863 tor_strdup("/etc/resolv.conf"),
2864 NULL, 0
2867 if (options->DirPortFrontPage) {
2868 sandbox_cfg_allow_open_filename(&cfg,
2869 tor_strdup(options->DirPortFrontPage));
2872 RENAME_SUFFIX("fingerprint", ".tmp");
2873 RENAME_SUFFIX2("keys", "secret_onion_key_ntor", ".tmp");
2874 RENAME_SUFFIX2("keys", "secret_id_key", ".tmp");
2875 RENAME_SUFFIX2("keys", "secret_id_key.old", ".tmp");
2876 RENAME_SUFFIX2("keys", "secret_onion_key", ".tmp");
2877 RENAME_SUFFIX2("keys", "secret_onion_key.old", ".tmp");
2878 RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
2879 RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
2880 RENAME_SUFFIX("hashed-fingerprint", ".tmp");
2881 RENAME_SUFFIX("router-stability", ".tmp");
2883 sandbox_cfg_allow_rename(&cfg,
2884 get_datadir_fname2("keys", "secret_onion_key"),
2885 get_datadir_fname2("keys", "secret_onion_key.old"));
2886 sandbox_cfg_allow_rename(&cfg,
2887 get_datadir_fname2("keys", "secret_onion_key_ntor"),
2888 get_datadir_fname2("keys", "secret_onion_key_ntor.old"));
2890 sandbox_cfg_allow_stat_filename_array(&cfg,
2891 get_datadir_fname("keys"),
2892 get_datadir_fname2("stats", "dirreq-stats"),
2893 NULL, 0
2897 init_addrinfo();
2899 return cfg;
2902 /** Main entry point for the Tor process. Called from main(). */
2903 /* This function is distinct from main() only so we can link main.c into
2904 * the unittest binary without conflicting with the unittests' main. */
2906 tor_main(int argc, char *argv[])
2908 int result = 0;
2909 #if defined (WINCE)
2910 WCHAR path [MAX_PATH] = {0};
2911 WCHAR fullpath [MAX_PATH] = {0};
2912 PWCHAR p = NULL;
2913 FILE* redir = NULL;
2914 FILE* redirdbg = NULL;
2916 // this is to facilitate debugging by opening
2917 // a file on a folder shared by the wm emulator.
2918 // if no flashcard (real or emulated) is present,
2919 // log files will be written in the root folder
2920 if (find_flashcard_path(path,MAX_PATH) == -1) {
2921 redir = _wfreopen( L"\\stdout.log", L"w", stdout );
2922 redirdbg = _wfreopen( L"\\stderr.log", L"w", stderr );
2923 } else {
2924 swprintf(fullpath,L"\\%s\\tor",path);
2925 CreateDirectory(fullpath,NULL);
2927 swprintf(fullpath,L"\\%s\\tor\\stdout.log",path);
2928 redir = _wfreopen( fullpath, L"w", stdout );
2930 swprintf(fullpath,L"\\%s\\tor\\stderr.log",path);
2931 redirdbg = _wfreopen( fullpath, L"w", stderr );
2933 #endif
2935 #ifdef _WIN32
2936 /* Call SetProcessDEPPolicy to permanently enable DEP.
2937 The function will not resolve on earlier versions of Windows,
2938 and failure is not dangerous. */
2939 HMODULE hMod = GetModuleHandleA("Kernel32.dll");
2940 if (hMod) {
2941 typedef BOOL (WINAPI *PSETDEP)(DWORD);
2942 PSETDEP setdeppolicy = (PSETDEP)GetProcAddress(hMod,
2943 "SetProcessDEPPolicy");
2944 if (setdeppolicy) setdeppolicy(1); /* PROCESS_DEP_ENABLE */
2946 #endif
2948 configure_backtrace_handler(get_version());
2950 update_approx_time(time(NULL));
2951 tor_threads_init();
2952 init_logging();
2953 #ifdef USE_DMALLOC
2955 /* Instruct OpenSSL to use our internal wrappers for malloc,
2956 realloc and free. */
2957 int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
2958 tor_assert(r);
2960 #endif
2961 #ifdef NT_SERVICE
2963 int done = 0;
2964 result = nt_service_parse_options(argc, argv, &done);
2965 if (done) return result;
2967 #endif
2968 if (tor_init(argc, argv)<0)
2969 return -1;
2971 if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
2972 sandbox_cfg_t* cfg = sandbox_init_filter();
2974 if (sandbox_init(cfg)) {
2975 log_err(LD_BUG,"Failed to create syscall sandbox filter");
2976 return -1;
2979 // registering libevent rng
2980 #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
2981 evutil_secure_rng_set_urandom_device_file(
2982 (char*) sandbox_intern_string("/dev/urandom"));
2983 #endif
2986 switch (get_options()->command) {
2987 case CMD_RUN_TOR:
2988 #ifdef NT_SERVICE
2989 nt_service_set_state(SERVICE_RUNNING);
2990 #endif
2991 result = do_main_loop();
2992 break;
2993 case CMD_LIST_FINGERPRINT:
2994 result = do_list_fingerprint();
2995 break;
2996 case CMD_HASH_PASSWORD:
2997 do_hash_password();
2998 result = 0;
2999 break;
3000 case CMD_VERIFY_CONFIG:
3001 printf("Configuration was valid\n");
3002 result = 0;
3003 break;
3004 case CMD_DUMP_CONFIG:
3005 result = do_dump_config();
3006 break;
3007 case CMD_RUN_UNITTESTS: /* only set by test.c */
3008 default:
3009 log_warn(LD_BUG,"Illegal command number %d: internal error.",
3010 get_options()->command);
3011 result = -1;
3013 tor_cleanup();
3014 return result;