Merge branch 'maint-0.2.2'
[tor.git] / src / or / main.c
blob93fe2fd6c6a3a812ed7b9ef3c6f444cc71e3bb24
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-2011, 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 "buffers.h"
16 #include "circuitbuild.h"
17 #include "circuitlist.h"
18 #include "circuituse.h"
19 #include "command.h"
20 #include "config.h"
21 #include "connection.h"
22 #include "connection_edge.h"
23 #include "connection_or.h"
24 #include "control.h"
25 #include "cpuworker.h"
26 #include "directory.h"
27 #include "dirserv.h"
28 #include "dirvote.h"
29 #include "dns.h"
30 #include "dnsserv.h"
31 #include "geoip.h"
32 #include "hibernate.h"
33 #include "main.h"
34 #include "microdesc.h"
35 #include "networkstatus.h"
36 #include "nodelist.h"
37 #include "ntmain.h"
38 #include "onion.h"
39 #include "policies.h"
40 #include "relay.h"
41 #include "rendclient.h"
42 #include "rendcommon.h"
43 #include "rendservice.h"
44 #include "rephist.h"
45 #include "router.h"
46 #include "routerlist.h"
47 #include "routerparse.h"
48 #include "status.h"
49 #ifdef USE_DMALLOC
50 #include <dmalloc.h>
51 #include <openssl/crypto.h>
52 #endif
53 #include "memarea.h"
55 #ifdef HAVE_EVENT2_EVENT_H
56 #include <event2/event.h>
57 #else
58 #include <event.h>
59 #endif
61 #ifdef USE_BUFFEREVENTS
62 #include <event2/bufferevent.h>
63 #endif
65 void evdns_shutdown(int);
67 /********* PROTOTYPES **********/
69 static void dumpmemusage(int severity);
70 static void dumpstats(int severity); /* log stats */
71 static void conn_read_callback(int fd, short event, void *_conn);
72 static void conn_write_callback(int fd, short event, void *_conn);
73 static void second_elapsed_callback(periodic_timer_t *timer, void *args);
74 static int conn_close_if_marked(int i);
75 static void connection_start_reading_from_linked_conn(connection_t *conn);
76 static int connection_should_read_from_linked_conn(connection_t *conn);
78 /********* START VARIABLES **********/
80 #ifndef USE_BUFFEREVENTS
81 int global_read_bucket; /**< Max number of bytes I can read this second. */
82 int global_write_bucket; /**< Max number of bytes I can write this second. */
84 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
85 int global_relayed_read_bucket;
86 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
87 int global_relayed_write_bucket;
88 /** What was the read bucket before the last second_elapsed_callback() call?
89 * (used to determine how many bytes we've read). */
90 static int stats_prev_global_read_bucket;
91 /** What was the write bucket before the last second_elapsed_callback() call?
92 * (used to determine how many bytes we've written). */
93 static int stats_prev_global_write_bucket;
94 #else
95 static uint64_t stats_prev_n_read = 0;
96 static uint64_t stats_prev_n_written = 0;
97 #endif
99 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
100 /** How many bytes have we read since we started the process? */
101 static uint64_t stats_n_bytes_read = 0;
102 /** How many bytes have we written since we started the process? */
103 static uint64_t stats_n_bytes_written = 0;
104 /** What time did this process start up? */
105 time_t time_of_process_start = 0;
106 /** How many seconds have we been running? */
107 long stats_n_seconds_working = 0;
108 /** When do we next launch DNS wildcarding checks? */
109 static time_t time_to_check_for_correct_dns = 0;
111 /** How often will we honor SIGNEWNYM requests? */
112 #define MAX_SIGNEWNYM_RATE 10
113 /** When did we last process a SIGNEWNYM request? */
114 static time_t time_of_last_signewnym = 0;
115 /** Is there a signewnym request we're currently waiting to handle? */
116 static int signewnym_is_pending = 0;
118 /** Smartlist of all open connections. */
119 static smartlist_t *connection_array = NULL;
120 /** List of connections that have been marked for close and need to be freed
121 * and removed from connection_array. */
122 static smartlist_t *closeable_connection_lst = NULL;
123 /** List of linked connections that are currently reading data into their
124 * inbuf from their partner's outbuf. */
125 static smartlist_t *active_linked_connection_lst = NULL;
126 /** Flag: Set to true iff we entered the current libevent main loop via
127 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
128 * to handle linked connections. */
129 static int called_loop_once = 0;
131 /** We set this to 1 when we've opened a circuit, so we can print a log
132 * entry to inform the user that Tor is working. We set it to 0 when
133 * we think the fact that we once opened a circuit doesn't mean we can do so
134 * any longer (a big time jump happened, when we notice our directory is
135 * heinously out-of-date, etc.
137 int can_complete_circuit=0;
139 /** How often do we check for router descriptors that we should download
140 * when we have too little directory info? */
141 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
142 /** How often do we check for router descriptors that we should download
143 * when we have enough directory info? */
144 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
145 /** How often do we 'forgive' undownloadable router descriptors and attempt
146 * to download them again? */
147 #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
148 /** How long do we let a directory connection stall before expiring it? */
149 #define DIR_CONN_MAX_STALL (5*60)
151 /** How long do we let OR connections handshake before we decide that
152 * they are obsolete? */
153 #define TLS_HANDSHAKE_TIMEOUT (60)
155 /********* END VARIABLES ************/
157 /****************************************************************************
159 * This section contains accessors and other methods on the connection_array
160 * variables (which are global within this file and unavailable outside it).
162 ****************************************************************************/
164 #if 0 && defined(USE_BUFFEREVENTS)
165 static void
166 free_old_inbuf(connection_t *conn)
168 if (! conn->inbuf)
169 return;
171 tor_assert(conn->outbuf);
172 tor_assert(buf_datalen(conn->inbuf) == 0);
173 tor_assert(buf_datalen(conn->outbuf) == 0);
174 buf_free(conn->inbuf);
175 buf_free(conn->outbuf);
176 conn->inbuf = conn->outbuf = NULL;
178 if (conn->read_event) {
179 event_del(conn->read_event);
180 tor_event_free(conn->read_event);
182 if (conn->write_event) {
183 event_del(conn->read_event);
184 tor_event_free(conn->write_event);
186 conn->read_event = conn->write_event = NULL;
188 #endif
190 /** Add <b>conn</b> to the array of connections that we can poll on. The
191 * connection's socket must be set; the connection starts out
192 * non-reading and non-writing.
195 connection_add_impl(connection_t *conn, int is_connecting)
197 tor_assert(conn);
198 tor_assert(conn->s >= 0 ||
199 conn->linked ||
200 (conn->type == CONN_TYPE_AP &&
201 TO_EDGE_CONN(conn)->is_dns_request));
203 tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
204 conn->conn_array_index = smartlist_len(connection_array);
205 smartlist_add(connection_array, conn);
207 #ifdef USE_BUFFEREVENTS
208 if (connection_type_uses_bufferevent(conn)) {
209 if (conn->s >= 0 && !conn->linked) {
210 conn->bufev = bufferevent_socket_new(
211 tor_libevent_get_base(),
212 conn->s,
213 BEV_OPT_DEFER_CALLBACKS);
214 if (!conn->bufev) {
215 log_warn(LD_BUG, "Unable to create socket bufferevent");
216 smartlist_del(connection_array, conn->conn_array_index);
217 conn->conn_array_index = -1;
218 return -1;
220 if (is_connecting) {
221 /* Put the bufferevent into a "connecting" state so that we'll get
222 * a "connected" event callback on successful write. */
223 bufferevent_socket_connect(conn->bufev, NULL, 0);
225 connection_configure_bufferevent_callbacks(conn);
226 } else if (conn->linked && conn->linked_conn &&
227 connection_type_uses_bufferevent(conn->linked_conn)) {
228 tor_assert(conn->s < 0);
229 if (!conn->bufev) {
230 struct bufferevent *pair[2] = { NULL, NULL };
231 if (bufferevent_pair_new(tor_libevent_get_base(),
232 BEV_OPT_DEFER_CALLBACKS,
233 pair) < 0) {
234 log_warn(LD_BUG, "Unable to create bufferevent pair");
235 smartlist_del(connection_array, conn->conn_array_index);
236 conn->conn_array_index = -1;
237 return -1;
239 tor_assert(pair[0]);
240 conn->bufev = pair[0];
241 conn->linked_conn->bufev = pair[1];
242 } /* else the other side already was added, and got a bufferevent_pair */
243 connection_configure_bufferevent_callbacks(conn);
244 } else {
245 tor_assert(!conn->linked);
248 if (conn->bufev)
249 tor_assert(conn->inbuf == NULL);
251 if (conn->linked_conn && conn->linked_conn->bufev)
252 tor_assert(conn->linked_conn->inbuf == NULL);
254 #else
255 (void) is_connecting;
256 #endif
258 if (!HAS_BUFFEREVENT(conn) && (conn->s >= 0 || conn->linked)) {
259 conn->read_event = tor_event_new(tor_libevent_get_base(),
260 conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
261 conn->write_event = tor_event_new(tor_libevent_get_base(),
262 conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
263 /* XXXX CHECK FOR NULL RETURN! */
266 log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
267 conn_type_to_string(conn->type), conn->s, conn->address,
268 smartlist_len(connection_array));
270 return 0;
273 /** Tell libevent that we don't care about <b>conn</b> any more. */
274 void
275 connection_unregister_events(connection_t *conn)
277 if (conn->read_event) {
278 if (event_del(conn->read_event))
279 log_warn(LD_BUG, "Error removing read event for %d", conn->s);
280 tor_free(conn->read_event);
282 if (conn->write_event) {
283 if (event_del(conn->write_event))
284 log_warn(LD_BUG, "Error removing write event for %d", conn->s);
285 tor_free(conn->write_event);
287 #ifdef USE_BUFFEREVENTS
288 if (conn->bufev) {
289 bufferevent_free(conn->bufev);
290 conn->bufev = NULL;
292 #endif
293 if (conn->dns_server_port) {
294 dnsserv_close_listener(conn);
298 /** Remove the connection from the global list, and remove the
299 * corresponding poll entry. Calling this function will shift the last
300 * connection (if any) into the position occupied by conn.
303 connection_remove(connection_t *conn)
305 int current_index;
306 connection_t *tmp;
308 tor_assert(conn);
310 log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
311 conn->s, conn_type_to_string(conn->type),
312 smartlist_len(connection_array));
314 tor_assert(conn->conn_array_index >= 0);
315 current_index = conn->conn_array_index;
316 connection_unregister_events(conn); /* This is redundant, but cheap. */
317 if (current_index == smartlist_len(connection_array)-1) { /* at the end */
318 smartlist_del(connection_array, current_index);
319 return 0;
322 /* replace this one with the one at the end */
323 smartlist_del(connection_array, current_index);
324 tmp = smartlist_get(connection_array, current_index);
325 tmp->conn_array_index = current_index;
327 return 0;
330 /** If <b>conn</b> is an edge conn, remove it from the list
331 * of conn's on this circuit. If it's not on an edge,
332 * flush and send destroys for all circuits on this conn.
334 * Remove it from connection_array (if applicable) and
335 * from closeable_connection_list.
337 * Then free it.
339 static void
340 connection_unlink(connection_t *conn)
342 connection_about_to_close_connection(conn);
343 if (conn->conn_array_index >= 0) {
344 connection_remove(conn);
346 if (conn->linked_conn) {
347 conn->linked_conn->linked_conn = NULL;
348 if (! conn->linked_conn->marked_for_close &&
349 conn->linked_conn->reading_from_linked_conn)
350 connection_start_reading(conn->linked_conn);
351 conn->linked_conn = NULL;
353 smartlist_remove(closeable_connection_lst, conn);
354 smartlist_remove(active_linked_connection_lst, conn);
355 if (conn->type == CONN_TYPE_EXIT) {
356 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
358 if (conn->type == CONN_TYPE_OR) {
359 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
360 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
362 connection_free(conn);
365 /** Schedule <b>conn</b> to be closed. **/
366 void
367 add_connection_to_closeable_list(connection_t *conn)
369 tor_assert(!smartlist_isin(closeable_connection_lst, conn));
370 tor_assert(conn->marked_for_close);
371 assert_connection_ok(conn, time(NULL));
372 smartlist_add(closeable_connection_lst, conn);
375 /** Return 1 if conn is on the closeable list, else return 0. */
377 connection_is_on_closeable_list(connection_t *conn)
379 return smartlist_isin(closeable_connection_lst, conn);
382 /** Return true iff conn is in the current poll array. */
384 connection_in_array(connection_t *conn)
386 return smartlist_isin(connection_array, conn);
389 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
390 * to the length of the array. <b>*array</b> and <b>*n</b> must not
391 * be modified.
393 smartlist_t *
394 get_connection_array(void)
396 if (!connection_array)
397 connection_array = smartlist_create();
398 return connection_array;
401 /** Provides the traffic read and written over the life of the process. */
403 uint64_t
404 get_bytes_read(void)
406 return stats_n_bytes_read;
409 uint64_t
410 get_bytes_written(void)
412 return stats_n_bytes_written;
415 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
416 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
418 void
419 connection_watch_events(connection_t *conn, watchable_events_t events)
421 IF_HAS_BUFFEREVENT(conn, {
422 short ev = ((short)events) & (EV_READ|EV_WRITE);
423 short old_ev = bufferevent_get_enabled(conn->bufev);
424 if ((ev & ~old_ev) != 0) {
425 bufferevent_enable(conn->bufev, ev);
427 if ((old_ev & ~ev) != 0) {
428 bufferevent_disable(conn->bufev, old_ev & ~ev);
430 return;
432 if (events & READ_EVENT)
433 connection_start_reading(conn);
434 else
435 connection_stop_reading(conn);
437 if (events & WRITE_EVENT)
438 connection_start_writing(conn);
439 else
440 connection_stop_writing(conn);
443 /** Return true iff <b>conn</b> is listening for read events. */
445 connection_is_reading(connection_t *conn)
447 tor_assert(conn);
449 IF_HAS_BUFFEREVENT(conn,
450 return (bufferevent_get_enabled(conn->bufev) & EV_READ) != 0;
452 return conn->reading_from_linked_conn ||
453 (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
456 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
457 void
458 connection_stop_reading(connection_t *conn)
460 tor_assert(conn);
462 IF_HAS_BUFFEREVENT(conn, {
463 bufferevent_disable(conn->bufev, EV_READ);
464 return;
467 tor_assert(conn->read_event);
469 if (conn->linked) {
470 conn->reading_from_linked_conn = 0;
471 connection_stop_reading_from_linked_conn(conn);
472 } else {
473 if (event_del(conn->read_event))
474 log_warn(LD_NET, "Error from libevent setting read event state for %d "
475 "to unwatched: %s",
476 conn->s,
477 tor_socket_strerror(tor_socket_errno(conn->s)));
481 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
482 void
483 connection_start_reading(connection_t *conn)
485 tor_assert(conn);
487 IF_HAS_BUFFEREVENT(conn, {
488 bufferevent_enable(conn->bufev, EV_READ);
489 return;
492 tor_assert(conn->read_event);
494 if (conn->linked) {
495 conn->reading_from_linked_conn = 1;
496 if (connection_should_read_from_linked_conn(conn))
497 connection_start_reading_from_linked_conn(conn);
498 } else {
499 if (event_add(conn->read_event, NULL))
500 log_warn(LD_NET, "Error from libevent setting read event state for %d "
501 "to watched: %s",
502 conn->s,
503 tor_socket_strerror(tor_socket_errno(conn->s)));
507 /** Return true iff <b>conn</b> is listening for write events. */
509 connection_is_writing(connection_t *conn)
511 tor_assert(conn);
513 IF_HAS_BUFFEREVENT(conn,
514 return (bufferevent_get_enabled(conn->bufev) & EV_WRITE) != 0;
517 return conn->writing_to_linked_conn ||
518 (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
521 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
522 void
523 connection_stop_writing(connection_t *conn)
525 tor_assert(conn);
527 IF_HAS_BUFFEREVENT(conn, {
528 bufferevent_disable(conn->bufev, EV_WRITE);
529 return;
532 tor_assert(conn->write_event);
534 if (conn->linked) {
535 conn->writing_to_linked_conn = 0;
536 if (conn->linked_conn)
537 connection_stop_reading_from_linked_conn(conn->linked_conn);
538 } else {
539 if (event_del(conn->write_event))
540 log_warn(LD_NET, "Error from libevent setting write event state for %d "
541 "to unwatched: %s",
542 conn->s,
543 tor_socket_strerror(tor_socket_errno(conn->s)));
547 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
548 void
549 connection_start_writing(connection_t *conn)
551 tor_assert(conn);
553 IF_HAS_BUFFEREVENT(conn, {
554 bufferevent_enable(conn->bufev, EV_WRITE);
555 return;
558 tor_assert(conn->write_event);
560 if (conn->linked) {
561 conn->writing_to_linked_conn = 1;
562 if (conn->linked_conn &&
563 connection_should_read_from_linked_conn(conn->linked_conn))
564 connection_start_reading_from_linked_conn(conn->linked_conn);
565 } else {
566 if (event_add(conn->write_event, NULL))
567 log_warn(LD_NET, "Error from libevent setting write event state for %d "
568 "to watched: %s",
569 conn->s,
570 tor_socket_strerror(tor_socket_errno(conn->s)));
574 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
575 * linked to it would be good and feasible. (Reading is "feasible" if the
576 * other conn exists and has data in its outbuf, and is "good" if we have our
577 * reading_from_linked_conn flag set and the other conn has its
578 * writing_to_linked_conn flag set.)*/
579 static int
580 connection_should_read_from_linked_conn(connection_t *conn)
582 if (conn->linked && conn->reading_from_linked_conn) {
583 if (! conn->linked_conn ||
584 (conn->linked_conn->writing_to_linked_conn &&
585 buf_datalen(conn->linked_conn->outbuf)))
586 return 1;
588 return 0;
591 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
592 * its linked connection, if it is not doing so already. Called by
593 * connection_start_reading and connection_start_writing as appropriate. */
594 static void
595 connection_start_reading_from_linked_conn(connection_t *conn)
597 tor_assert(conn);
598 tor_assert(conn->linked == 1);
600 if (!conn->active_on_link) {
601 conn->active_on_link = 1;
602 smartlist_add(active_linked_connection_lst, conn);
603 if (!called_loop_once) {
604 /* This is the first event on the list; we won't be in LOOP_ONCE mode,
605 * so we need to make sure that the event_base_loop() actually exits at
606 * the end of its run through the current connections and lets us
607 * activate read events for linked connections. */
608 struct timeval tv = { 0, 0 };
609 tor_event_base_loopexit(tor_libevent_get_base(), &tv);
611 } else {
612 tor_assert(smartlist_isin(active_linked_connection_lst, conn));
616 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
617 * connection, if is currently doing so. Called by connection_stop_reading,
618 * connection_stop_writing, and connection_read. */
619 void
620 connection_stop_reading_from_linked_conn(connection_t *conn)
622 tor_assert(conn);
623 tor_assert(conn->linked == 1);
625 if (conn->active_on_link) {
626 conn->active_on_link = 0;
627 /* FFFF We could keep an index here so we can smartlist_del
628 * cleanly. On the other hand, this doesn't show up on profiles,
629 * so let's leave it alone for now. */
630 smartlist_remove(active_linked_connection_lst, conn);
631 } else {
632 tor_assert(!smartlist_isin(active_linked_connection_lst, conn));
636 /** Close all connections that have been scheduled to get closed. */
637 static void
638 close_closeable_connections(void)
640 int i;
641 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
642 connection_t *conn = smartlist_get(closeable_connection_lst, i);
643 if (conn->conn_array_index < 0) {
644 connection_unlink(conn); /* blow it away right now */
645 } else {
646 if (!conn_close_if_marked(conn->conn_array_index))
647 ++i;
652 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
653 * some data to read. */
654 static void
655 conn_read_callback(int fd, short event, void *_conn)
657 connection_t *conn = _conn;
658 (void)fd;
659 (void)event;
661 log_debug(LD_NET,"socket %d wants to read.",conn->s);
663 /* assert_connection_ok(conn, time(NULL)); */
665 if (connection_handle_read(conn) < 0) {
666 if (!conn->marked_for_close) {
667 #ifndef MS_WINDOWS
668 log_warn(LD_BUG,"Unhandled error on read for %s connection "
669 "(fd %d); removing",
670 conn_type_to_string(conn->type), conn->s);
671 tor_fragile_assert();
672 #endif
673 if (CONN_IS_EDGE(conn))
674 connection_edge_end_errno(TO_EDGE_CONN(conn));
675 connection_mark_for_close(conn);
678 assert_connection_ok(conn, time(NULL));
680 if (smartlist_len(closeable_connection_lst))
681 close_closeable_connections();
684 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
685 * some data to write. */
686 static void
687 conn_write_callback(int fd, short events, void *_conn)
689 connection_t *conn = _conn;
690 (void)fd;
691 (void)events;
693 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
695 /* assert_connection_ok(conn, time(NULL)); */
697 if (connection_handle_write(conn, 0) < 0) {
698 if (!conn->marked_for_close) {
699 /* this connection is broken. remove it. */
700 log_fn(LOG_WARN,LD_BUG,
701 "unhandled error on write for %s connection (fd %d); removing",
702 conn_type_to_string(conn->type), conn->s);
703 tor_fragile_assert();
704 if (CONN_IS_EDGE(conn)) {
705 /* otherwise we cry wolf about duplicate close */
706 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
707 if (!edge_conn->end_reason)
708 edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
709 edge_conn->edge_has_sent_end = 1;
711 connection_close_immediate(conn); /* So we don't try to flush. */
712 connection_mark_for_close(conn);
715 assert_connection_ok(conn, time(NULL));
717 if (smartlist_len(closeable_connection_lst))
718 close_closeable_connections();
721 /** If the connection at connection_array[i] is marked for close, then:
722 * - If it has data that it wants to flush, try to flush it.
723 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
724 * true, then leave the connection open and return.
725 * - Otherwise, remove the connection from connection_array and from
726 * all other lists, close it, and free it.
727 * Returns 1 if the connection was closed, 0 otherwise.
729 static int
730 conn_close_if_marked(int i)
732 connection_t *conn;
733 int retval;
734 time_t now;
736 conn = smartlist_get(connection_array, i);
737 if (!conn->marked_for_close)
738 return 0; /* nothing to see here, move along */
739 now = time(NULL);
740 assert_connection_ok(conn, now);
741 /* assert_all_pending_dns_resolves_ok(); */
743 #ifdef USE_BUFFEREVENTS
744 if (conn->bufev) {
745 if (conn->hold_open_until_flushed &&
746 evbuffer_get_length(bufferevent_get_output(conn->bufev))) {
747 /* don't close yet. */
748 return 0;
750 if (conn->linked_conn && ! conn->linked_conn->marked_for_close) {
751 /* We need to do this explicitly so that the linked connection
752 * notices that there was an EOF. */
753 bufferevent_flush(conn->bufev, EV_WRITE, BEV_FINISHED);
756 #endif
758 log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
759 IF_HAS_BUFFEREVENT(conn, goto unlink);
760 if ((conn->s >= 0 || conn->linked_conn) && connection_wants_to_flush(conn)) {
761 /* s == -1 means it's an incomplete edge connection, or that the socket
762 * has already been closed as unflushable. */
763 ssize_t sz = connection_bucket_write_limit(conn, now);
764 if (!conn->hold_open_until_flushed)
765 log_info(LD_NET,
766 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
767 "to flush %d bytes. (Marked at %s:%d)",
768 escaped_safe_str_client(conn->address),
769 conn->s, conn_type_to_string(conn->type), conn->state,
770 (int)conn->outbuf_flushlen,
771 conn->marked_for_close_file, conn->marked_for_close);
772 if (conn->linked_conn) {
773 retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
774 &conn->outbuf_flushlen);
775 if (retval >= 0) {
776 /* The linked conn will notice that it has data when it notices that
777 * we're gone. */
778 connection_start_reading_from_linked_conn(conn->linked_conn);
780 log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
781 "%d left; flushlen %d; wants-to-flush==%d", retval,
782 (int)connection_get_outbuf_len(conn),
783 (int)conn->outbuf_flushlen,
784 connection_wants_to_flush(conn));
785 } else if (connection_speaks_cells(conn)) {
786 if (conn->state == OR_CONN_STATE_OPEN) {
787 retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
788 &conn->outbuf_flushlen);
789 } else
790 retval = -1; /* never flush non-open broken tls connections */
791 } else {
792 retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
794 if (retval >= 0 && /* Technically, we could survive things like
795 TLS_WANT_WRITE here. But don't bother for now. */
796 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
797 if (retval > 0) {
798 LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
799 "Holding conn (fd %d) open for more flushing.",
800 conn->s));
801 conn->timestamp_lastwritten = now; /* reset so we can flush more */
803 return 0;
805 if (connection_wants_to_flush(conn)) {
806 int severity;
807 if (conn->type == CONN_TYPE_EXIT ||
808 (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
809 (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
810 severity = LOG_INFO;
811 else
812 severity = LOG_NOTICE;
813 /* XXXX Maybe allow this to happen a certain amount per hour; it usually
814 * is meaningless. */
815 log_fn(severity, LD_NET, "We stalled too much while trying to write %d "
816 "bytes to address %s. If this happens a lot, either "
817 "something is wrong with your network connection, or "
818 "something is wrong with theirs. "
819 "(fd %d, type %s, state %d, marked at %s:%d).",
820 (int)connection_get_outbuf_len(conn),
821 escaped_safe_str_client(conn->address),
822 conn->s, conn_type_to_string(conn->type), conn->state,
823 conn->marked_for_close_file,
824 conn->marked_for_close);
828 #ifdef USE_BUFFEREVENTS
829 unlink:
830 #endif
831 connection_unlink(conn); /* unlink, remove, free */
832 return 1;
835 /** We've just tried every dirserver we know about, and none of
836 * them were reachable. Assume the network is down. Change state
837 * so next time an application connection arrives we'll delay it
838 * and try another directory fetch. Kill off all the circuit_wait
839 * streams that are waiting now, since they will all timeout anyway.
841 void
842 directory_all_unreachable(time_t now)
844 connection_t *conn;
845 (void)now;
847 stats_n_seconds_working=0; /* reset it */
849 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
850 AP_CONN_STATE_CIRCUIT_WAIT))) {
851 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
852 log_notice(LD_NET,
853 "Is your network connection down? "
854 "Failing connection to '%s:%d'.",
855 safe_str_client(edge_conn->socks_request->address),
856 edge_conn->socks_request->port);
857 connection_mark_unattached_ap(edge_conn,
858 END_STREAM_REASON_NET_UNREACHABLE);
860 control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
863 /** This function is called whenever we successfully pull down some new
864 * network statuses or server descriptors. */
865 void
866 directory_info_has_arrived(time_t now, int from_cache)
868 or_options_t *options = get_options();
870 if (!router_have_minimum_dir_info()) {
871 int quiet = directory_too_idle_to_fetch_descriptors(options, now);
872 log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
873 "I learned some more directory information, but not enough to "
874 "build a circuit: %s", get_dir_info_status_string());
875 update_all_descriptor_downloads(now);
876 return;
877 } else {
878 if (directory_fetches_from_authorities(options)) {
879 update_all_descriptor_downloads(now);
882 /* if we have enough dir info, then update our guard status with
883 * whatever we just learned. */
884 entry_guards_compute_status(options, now);
885 /* Don't even bother trying to get extrainfo until the rest of our
886 * directory info is up-to-date */
887 if (options->DownloadExtraInfo)
888 update_extrainfo_downloads(now);
891 if (server_mode(options) && !we_are_hibernating() && !from_cache &&
892 (can_complete_circuit || !any_predicted_circuits(now)))
893 consider_testing_reachability(1, 1);
896 /** How long do we wait before killing OR connections with no circuits?
897 * In Tor versions up to 0.2.1.25 and 0.2.2.12-alpha, we waited 15 minutes
898 * before cancelling these connections, which caused fast relays to accrue
899 * many many idle connections. Hopefully 3 minutes is low enough that
900 * it kills most idle connections, without being so low that we cause
901 * clients to bounce on and off.
903 #define IDLE_OR_CONN_TIMEOUT 180
905 /** Perform regular maintenance tasks for a single connection. This
906 * function gets run once per second per connection by run_scheduled_events.
908 static void
909 run_connection_housekeeping(int i, time_t now)
911 cell_t cell;
912 connection_t *conn = smartlist_get(connection_array, i);
913 or_options_t *options = get_options();
914 or_connection_t *or_conn;
915 int past_keepalive =
916 now >= conn->timestamp_lastwritten + options->KeepalivePeriod;
918 if (conn->outbuf && !connection_get_outbuf_len(conn) &&
919 conn->type == CONN_TYPE_OR)
920 TO_OR_CONN(conn)->timestamp_lastempty = now;
922 if (conn->marked_for_close) {
923 /* nothing to do here */
924 return;
927 /* Expire any directory connections that haven't been active (sent
928 * if a server or received if a client) for 5 min */
929 if (conn->type == CONN_TYPE_DIR &&
930 ((DIR_CONN_IS_SERVER(conn) &&
931 conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
932 (!DIR_CONN_IS_SERVER(conn) &&
933 conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
934 log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
935 conn->s, conn->purpose);
936 /* This check is temporary; it's to let us know whether we should consider
937 * parsing partial serverdesc responses. */
938 if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
939 connection_get_inbuf_len(conn) >= 1024) {
940 log_info(LD_DIR,"Trying to extract information from wedged server desc "
941 "download.");
942 connection_dir_reached_eof(TO_DIR_CONN(conn));
943 } else {
944 connection_mark_for_close(conn);
946 return;
949 if (!connection_speaks_cells(conn))
950 return; /* we're all done here, the rest is just for OR conns */
952 /* If we haven't written to an OR connection for a while, then either nuke
953 the connection or send a keepalive, depending. */
955 or_conn = TO_OR_CONN(conn);
956 #ifdef USE_BUFFEREVENTS
957 tor_assert(conn->bufev);
958 #else
959 tor_assert(conn->outbuf);
960 #endif
962 if (or_conn->is_bad_for_new_circs && !or_conn->n_circuits) {
963 /* It's bad for new circuits, and has no unmarked circuits on it:
964 * mark it now. */
965 log_info(LD_OR,
966 "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
967 conn->s, conn->address, conn->port);
968 if (conn->state == OR_CONN_STATE_CONNECTING)
969 connection_or_connect_failed(TO_OR_CONN(conn),
970 END_OR_CONN_REASON_TIMEOUT,
971 "Tor gave up on the connection");
972 connection_mark_and_flush(conn);
973 } else if (!connection_state_is_open(conn)) {
974 if (past_keepalive) {
975 /* We never managed to actually get this connection open and happy. */
976 log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
977 conn->s,conn->address, conn->port);
978 connection_mark_for_close(conn);
980 } else if (we_are_hibernating() && !or_conn->n_circuits &&
981 !connection_get_outbuf_len(conn)) {
982 /* We're hibernating, there's no circuits, and nothing to flush.*/
983 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
984 "[Hibernating or exiting].",
985 conn->s,conn->address, conn->port);
986 connection_mark_and_flush(conn);
987 } else if (!or_conn->n_circuits &&
988 now >= or_conn->timestamp_last_added_nonpadding +
989 IDLE_OR_CONN_TIMEOUT) {
990 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
991 "[idle %d].", conn->s,conn->address, conn->port,
992 (int)(now - or_conn->timestamp_last_added_nonpadding));
993 connection_mark_for_close(conn);
994 } else if (
995 now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
996 now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
997 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
998 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
999 "flush; %d seconds since last write)",
1000 conn->s, conn->address, conn->port,
1001 (int)connection_get_outbuf_len(conn),
1002 (int)(now-conn->timestamp_lastwritten));
1003 connection_mark_for_close(conn);
1004 } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
1005 /* send a padding cell */
1006 log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
1007 conn->address, conn->port);
1008 memset(&cell,0,sizeof(cell_t));
1009 cell.command = CELL_PADDING;
1010 connection_or_write_cell_to_buf(&cell, or_conn);
1014 /** Honor a NEWNYM request: make future requests unlinkable to past
1015 * requests. */
1016 static void
1017 signewnym_impl(time_t now)
1019 or_options_t *options = get_options();
1020 if (!proxy_mode(options)) {
1021 log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
1022 "is disabled.");
1023 return;
1026 circuit_expire_all_dirty_circs();
1027 addressmap_clear_transient();
1028 rend_cache_purge();
1029 rend_client_cancel_descriptor_fetches();
1030 time_of_last_signewnym = now;
1031 signewnym_is_pending = 0;
1034 /** Perform regular maintenance tasks. This function gets run once per
1035 * second by second_elapsed_callback().
1037 static void
1038 run_scheduled_events(time_t now)
1040 static time_t last_rotated_x509_certificate = 0;
1041 static time_t time_to_check_v3_certificate = 0;
1042 static time_t time_to_check_listeners = 0;
1043 static time_t time_to_check_descriptor = 0;
1044 static time_t time_to_check_ipaddress = 0;
1045 static time_t time_to_shrink_memory = 0;
1046 static time_t time_to_try_getting_descriptors = 0;
1047 static time_t time_to_reset_descriptor_failures = 0;
1048 static time_t time_to_add_entropy = 0;
1049 static time_t time_to_write_bridge_status_file = 0;
1050 static time_t time_to_downrate_stability = 0;
1051 static time_t time_to_save_stability = 0;
1052 static time_t time_to_clean_caches = 0;
1053 static time_t time_to_recheck_bandwidth = 0;
1054 static time_t time_to_check_for_expired_networkstatus = 0;
1055 static time_t time_to_write_stats_files = 0;
1056 static time_t time_to_write_bridge_stats = 0;
1057 static time_t time_to_check_port_forwarding = 0;
1058 static time_t time_to_launch_reachability_tests = 0;
1059 static int should_init_bridge_stats = 1;
1060 static time_t time_to_retry_dns_init = 0;
1061 static time_t time_to_next_heartbeat = 0;
1062 or_options_t *options = get_options();
1063 int is_server = server_mode(options);
1064 int i;
1065 int have_dir_info;
1067 /** 0. See if we've been asked to shut down and our timeout has
1068 * expired; or if our bandwidth limits are exhausted and we
1069 * should hibernate; or if it's time to wake up from hibernation.
1071 consider_hibernation(now);
1073 #if 0
1075 static time_t nl_check_time = 0;
1076 if (nl_check_time <= now) {
1077 nodelist_assert_ok();
1078 nl_check_time = now + 30;
1081 #endif
1083 /* 0b. If we've deferred a signewnym, make sure it gets handled
1084 * eventually. */
1085 if (signewnym_is_pending &&
1086 time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
1087 log(LOG_INFO, LD_CONTROL, "Honoring delayed NEWNYM request");
1088 signewnym_impl(now);
1091 /* 0c. If we've deferred log messages for the controller, handle them now */
1092 flush_pending_log_callbacks();
1094 /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
1095 * shut down and restart all cpuworkers, and update the directory if
1096 * necessary.
1098 if (is_server &&
1099 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
1100 log_info(LD_GENERAL,"Rotating onion key.");
1101 rotate_onion_key();
1102 cpuworkers_rotate();
1103 if (router_rebuild_descriptor(1)<0) {
1104 log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
1106 if (advertised_server_mode())
1107 router_upload_dir_desc_to_dirservers(0);
1110 if (time_to_try_getting_descriptors < now) {
1111 update_all_descriptor_downloads(now);
1112 update_extrainfo_downloads(now);
1113 if (router_have_minimum_dir_info())
1114 time_to_try_getting_descriptors = now + LAZY_DESCRIPTOR_RETRY_INTERVAL;
1115 else
1116 time_to_try_getting_descriptors = now + GREEDY_DESCRIPTOR_RETRY_INTERVAL;
1119 if (time_to_reset_descriptor_failures < now) {
1120 router_reset_descriptor_download_failures();
1121 time_to_reset_descriptor_failures =
1122 now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
1125 if (options->UseBridges)
1126 fetch_bridge_descriptors(options, now);
1128 /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
1129 if (!last_rotated_x509_certificate)
1130 last_rotated_x509_certificate = now;
1131 if (last_rotated_x509_certificate+MAX_SSL_KEY_LIFETIME < now) {
1132 log_info(LD_GENERAL,"Rotating tls context.");
1133 if (tor_tls_context_init(public_server_mode(options),
1134 get_tlsclient_identity_key(),
1135 is_server ? get_server_identity_key() : NULL,
1136 MAX_SSL_KEY_LIFETIME) < 0) {
1137 log_warn(LD_BUG, "Error reinitializing TLS context");
1138 /* XXX is it a bug here, that we just keep going? -RD */
1140 last_rotated_x509_certificate = now;
1141 /* We also make sure to rotate the TLS connections themselves if they've
1142 * been up for too long -- but that's done via is_bad_for_new_circs in
1143 * connection_run_housekeeping() above. */
1146 if (time_to_add_entropy < now) {
1147 if (time_to_add_entropy) {
1148 /* We already seeded once, so don't die on failure. */
1149 crypto_seed_rng(0);
1151 /** How often do we add more entropy to OpenSSL's RNG pool? */
1152 #define ENTROPY_INTERVAL (60*60)
1153 time_to_add_entropy = now + ENTROPY_INTERVAL;
1156 /** 1c. If we have to change the accounting interval or record
1157 * bandwidth used in this accounting interval, do so. */
1158 if (accounting_is_enabled(options))
1159 accounting_run_housekeeping(now);
1161 if (time_to_launch_reachability_tests < now &&
1162 (authdir_mode_tests_reachability(options)) &&
1163 !we_are_hibernating()) {
1164 time_to_launch_reachability_tests = now + REACHABILITY_TEST_INTERVAL;
1165 /* try to determine reachability of the other Tor relays */
1166 dirserv_test_reachability(now);
1169 /** 1d. Periodically, we discount older stability information so that new
1170 * stability info counts more, and save the stability information to disk as
1171 * appropriate. */
1172 if (time_to_downrate_stability < now)
1173 time_to_downrate_stability = rep_hist_downrate_old_runs(now);
1174 if (authdir_mode_tests_reachability(options)) {
1175 if (time_to_save_stability < now) {
1176 if (time_to_save_stability && rep_hist_record_mtbf_data(now, 1)<0) {
1177 log_warn(LD_GENERAL, "Couldn't store mtbf data.");
1179 #define SAVE_STABILITY_INTERVAL (30*60)
1180 time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
1184 /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
1185 * close to expiring and warn the admin if it is. */
1186 if (time_to_check_v3_certificate < now) {
1187 v3_authority_check_key_expiry();
1188 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
1189 time_to_check_v3_certificate = now + CHECK_V3_CERTIFICATE_INTERVAL;
1192 /* 1f. Check whether our networkstatus has expired.
1194 if (time_to_check_for_expired_networkstatus < now) {
1195 networkstatus_t *ns = networkstatus_get_latest_consensus();
1196 /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
1197 * networkstatus_get_reasonably_live_consensus(), but that value is way
1198 * way too high. Arma: is the bridge issue there resolved yet? -NM */
1199 #define NS_EXPIRY_SLOP (24*60*60)
1200 if (ns && ns->valid_until < now+NS_EXPIRY_SLOP &&
1201 router_have_minimum_dir_info()) {
1202 router_dir_info_changed();
1204 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
1205 time_to_check_for_expired_networkstatus = now + CHECK_EXPIRED_NS_INTERVAL;
1208 /* 1g. Check whether we should write statistics to disk.
1210 if (time_to_write_stats_files < now) {
1211 #define CHECK_WRITE_STATS_INTERVAL (60*60)
1212 time_t next_time_to_write_stats_files = (time_to_write_stats_files > 0 ?
1213 time_to_write_stats_files : now) + CHECK_WRITE_STATS_INTERVAL;
1214 if (options->CellStatistics) {
1215 time_t next_write =
1216 rep_hist_buffer_stats_write(time_to_write_stats_files);
1217 if (next_write && next_write < next_time_to_write_stats_files)
1218 next_time_to_write_stats_files = next_write;
1220 if (options->DirReqStatistics) {
1221 time_t next_write = geoip_dirreq_stats_write(time_to_write_stats_files);
1222 if (next_write && next_write < next_time_to_write_stats_files)
1223 next_time_to_write_stats_files = next_write;
1225 if (options->EntryStatistics) {
1226 time_t next_write = geoip_entry_stats_write(time_to_write_stats_files);
1227 if (next_write && next_write < next_time_to_write_stats_files)
1228 next_time_to_write_stats_files = next_write;
1230 if (options->ExitPortStatistics) {
1231 time_t next_write = rep_hist_exit_stats_write(time_to_write_stats_files);
1232 if (next_write && next_write < next_time_to_write_stats_files)
1233 next_time_to_write_stats_files = next_write;
1235 if (options->ConnDirectionStatistics) {
1236 time_t next_write = rep_hist_conn_stats_write(time_to_write_stats_files);
1237 if (next_write && next_write < next_time_to_write_stats_files)
1238 next_time_to_write_stats_files = next_write;
1240 time_to_write_stats_files = next_time_to_write_stats_files;
1243 /* 1h. Check whether we should write bridge statistics to disk.
1245 if (should_record_bridge_info(options)) {
1246 if (time_to_write_bridge_stats < now) {
1247 if (should_init_bridge_stats) {
1248 /* (Re-)initialize bridge statistics. */
1249 geoip_bridge_stats_init(now);
1250 time_to_write_bridge_stats = now + WRITE_STATS_INTERVAL;
1251 should_init_bridge_stats = 0;
1252 } else {
1253 /* Possibly write bridge statistics to disk and ask when to write
1254 * them next time. */
1255 time_to_write_bridge_stats = geoip_bridge_stats_write(
1256 time_to_write_bridge_stats);
1259 } else if (!should_init_bridge_stats) {
1260 /* Bridge mode was turned off. Ensure that stats are re-initialized
1261 * next time bridge mode is turned on. */
1262 should_init_bridge_stats = 1;
1265 /* Remove old information from rephist and the rend cache. */
1266 if (time_to_clean_caches < now) {
1267 rep_history_clean(now - options->RephistTrackTime);
1268 rend_cache_clean(now);
1269 rend_cache_clean_v2_descs_as_dir(now);
1270 microdesc_cache_rebuild(NULL, 0);
1271 #define CLEAN_CACHES_INTERVAL (30*60)
1272 time_to_clean_caches = now + CLEAN_CACHES_INTERVAL;
1275 #define RETRY_DNS_INTERVAL (10*60)
1276 /* If we're a server and initializing dns failed, retry periodically. */
1277 if (time_to_retry_dns_init < now) {
1278 time_to_retry_dns_init = now + RETRY_DNS_INTERVAL;
1279 if (is_server && has_dns_init_failed())
1280 dns_init();
1283 /** 2. Periodically, we consider force-uploading our descriptor
1284 * (if we've passed our internal checks). */
1286 /** How often do we check whether part of our router info has changed in a way
1287 * that would require an upload? */
1288 #define CHECK_DESCRIPTOR_INTERVAL (60)
1289 /** How often do we (as a router) check whether our IP address has changed? */
1290 #define CHECK_IPADDRESS_INTERVAL (15*60)
1292 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1293 * one is inaccurate. */
1294 if (time_to_check_descriptor < now) {
1295 static int dirport_reachability_count = 0;
1296 time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
1297 check_descriptor_bandwidth_changed(now);
1298 if (time_to_check_ipaddress < now) {
1299 time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
1300 check_descriptor_ipaddress_changed(now);
1302 /** If our router descriptor ever goes this long without being regenerated
1303 * because something changed, we force an immediate regenerate-and-upload. */
1304 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
1305 mark_my_descriptor_dirty_if_older_than(
1306 now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
1307 consider_publishable_server(0);
1308 /* also, check religiously for reachability, if it's within the first
1309 * 20 minutes of our uptime. */
1310 if (is_server &&
1311 (can_complete_circuit || !any_predicted_circuits(now)) &&
1312 !we_are_hibernating()) {
1313 if (stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1314 consider_testing_reachability(1, dirport_reachability_count==0);
1315 if (++dirport_reachability_count > 5)
1316 dirport_reachability_count = 0;
1317 } else if (time_to_recheck_bandwidth < now) {
1318 /* If we haven't checked for 12 hours and our bandwidth estimate is
1319 * low, do another bandwidth test. This is especially important for
1320 * bridges, since they might go long periods without much use. */
1321 const routerinfo_t *me = router_get_my_routerinfo();
1322 if (time_to_recheck_bandwidth && me &&
1323 me->bandwidthcapacity < me->bandwidthrate &&
1324 me->bandwidthcapacity < 51200) {
1325 reset_bandwidth_test();
1327 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1328 time_to_recheck_bandwidth = now + BANDWIDTH_RECHECK_INTERVAL;
1332 /* If any networkstatus documents are no longer recent, we need to
1333 * update all the descriptors' running status. */
1334 /* purge obsolete entries */
1335 networkstatus_v2_list_clean(now);
1336 /* Remove dead routers. */
1337 routerlist_remove_old_routers();
1339 /* Also, once per minute, check whether we want to download any
1340 * networkstatus documents.
1342 update_networkstatus_downloads(now);
1345 /** 2c. Let directory voting happen. */
1346 if (authdir_mode_v3(options))
1347 dirvote_act(options, now);
1349 /** 3a. Every second, we examine pending circuits and prune the
1350 * ones which have been pending for more than a few seconds.
1351 * We do this before step 4, so it can try building more if
1352 * it's not comfortable with the number of available circuits.
1354 /* XXXX022 If our circuit build timeout is much lower than a second, maybe
1355 we should do this more often? */
1356 circuit_expire_building();
1358 /** 3b. Also look at pending streams and prune the ones that 'began'
1359 * a long time ago but haven't gotten a 'connected' yet.
1360 * Do this before step 4, so we can put them back into pending
1361 * state to be picked up by the new circuit.
1363 connection_ap_expire_beginning();
1365 /** 3c. And expire connections that we've held open for too long.
1367 connection_expire_held_open();
1369 /** 3d. And every 60 seconds, we relaunch listeners if any died. */
1370 if (!we_are_hibernating() && time_to_check_listeners < now) {
1371 retry_all_listeners(NULL, NULL);
1372 time_to_check_listeners = now+60;
1375 /** 4. Every second, we try a new circuit if there are no valid
1376 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1377 * that became dirty more than MaxCircuitDirtiness seconds ago,
1378 * and we make a new circ if there are no clean circuits.
1380 have_dir_info = router_have_minimum_dir_info();
1381 if (have_dir_info && !we_are_hibernating())
1382 circuit_build_needed_circs(now);
1384 /* every 10 seconds, but not at the same second as other such events */
1385 if (now % 10 == 5)
1386 circuit_expire_old_circuits_serverside(now);
1388 /** 5. We do housekeeping for each connection... */
1389 connection_or_set_bad_connections(NULL, 0);
1390 for (i=0;i<smartlist_len(connection_array);i++) {
1391 run_connection_housekeeping(i, now);
1393 if (time_to_shrink_memory < now) {
1394 SMARTLIST_FOREACH(connection_array, connection_t *, conn, {
1395 if (conn->outbuf)
1396 buf_shrink(conn->outbuf);
1397 if (conn->inbuf)
1398 buf_shrink(conn->inbuf);
1400 clean_cell_pool();
1401 buf_shrink_freelists(0);
1402 /** How often do we check buffers and pools for empty space that can be
1403 * deallocated? */
1404 #define MEM_SHRINK_INTERVAL (60)
1405 time_to_shrink_memory = now + MEM_SHRINK_INTERVAL;
1408 /** 6. And remove any marked circuits... */
1409 circuit_close_all_marked();
1411 /** 7. And upload service descriptors if necessary. */
1412 if (can_complete_circuit && !we_are_hibernating()) {
1413 rend_consider_services_upload(now);
1414 rend_consider_descriptor_republication();
1417 /** 8. and blow away any connections that need to die. have to do this now,
1418 * because if we marked a conn for close and left its socket -1, then
1419 * we'll pass it to poll/select and bad things will happen.
1421 close_closeable_connections();
1423 /** 8b. And if anything in our state is ready to get flushed to disk, we
1424 * flush it. */
1425 or_state_save(now);
1427 /** 9. and if we're a server, check whether our DNS is telling stories to
1428 * us. */
1429 if (is_server && time_to_check_for_correct_dns < now) {
1430 if (!time_to_check_for_correct_dns) {
1431 time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
1432 } else {
1433 dns_launch_correctness_checks();
1434 time_to_check_for_correct_dns = now + 12*3600 +
1435 crypto_rand_int(12*3600);
1439 /** 10b. write bridge networkstatus file to disk */
1440 if (options->BridgeAuthoritativeDir &&
1441 time_to_write_bridge_status_file < now) {
1442 networkstatus_dump_bridge_status_to_file(now);
1443 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
1444 time_to_write_bridge_status_file = now+BRIDGE_STATUSFILE_INTERVAL;
1447 if (time_to_check_port_forwarding < now &&
1448 options->PortForwarding &&
1449 is_server) {
1450 #define PORT_FORWARDING_CHECK_INTERVAL 5
1451 tor_check_port_forwarding(options->PortForwardingHelper,
1452 options->DirPort,
1453 options->ORPort,
1454 now);
1455 time_to_check_port_forwarding = now+PORT_FORWARDING_CHECK_INTERVAL;
1458 /** 11. write the heartbeat message */
1459 if (options->HeartbeatPeriod &&
1460 time_to_next_heartbeat < now) {
1461 log_heartbeat(now);
1462 time_to_next_heartbeat = now+options->HeartbeatPeriod;
1466 /** Timer: used to invoke second_elapsed_callback() once per second. */
1467 static periodic_timer_t *second_timer = NULL;
1468 /** Number of libevent errors in the last second: we die if we get too many. */
1469 static int n_libevent_errors = 0;
1471 /** Libevent callback: invoked once every second. */
1472 static void
1473 second_elapsed_callback(periodic_timer_t *timer, void *arg)
1475 /* XXXX This could be sensibly refactored into multiple callbacks, and we
1476 * could use Libevent's timers for this rather than checking the current
1477 * time against a bunch of timeouts every second. */
1478 static time_t current_second = 0;
1479 time_t now;
1480 size_t bytes_written;
1481 size_t bytes_read;
1482 int seconds_elapsed;
1483 #ifdef USE_BUFFEREVENTS
1484 uint64_t cur_read,cur_written;
1485 #endif
1486 or_options_t *options = get_options();
1487 (void)timer;
1488 (void)arg;
1490 n_libevent_errors = 0;
1492 /* log_notice(LD_GENERAL, "Tick."); */
1493 now = time(NULL);
1494 update_approx_time(now);
1496 /* the second has rolled over. check more stuff. */
1497 seconds_elapsed = current_second ? (int)(now - current_second) : 0;
1498 #ifdef USE_BUFFEREVENTS
1499 connection_get_rate_limit_totals(&cur_read, &cur_written);
1500 bytes_written = (size_t)(cur_written - stats_prev_n_written);
1501 bytes_read = (size_t)(cur_read - stats_prev_n_read);
1502 #else
1503 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
1504 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
1505 #endif
1506 stats_n_bytes_read += bytes_read;
1507 stats_n_bytes_written += bytes_written;
1508 if (accounting_is_enabled(options) && seconds_elapsed >= 0)
1509 accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
1510 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
1511 control_event_stream_bandwidth_used();
1513 if (seconds_elapsed > 0)
1514 connection_bucket_refill(seconds_elapsed, now);
1515 #ifdef USE_BUFFEREVENTS
1516 stats_prev_n_written = cur_written;
1517 stats_prev_n_read = cur_read;
1518 #else
1519 stats_prev_global_read_bucket = global_read_bucket;
1520 stats_prev_global_write_bucket = global_write_bucket;
1521 #endif
1523 if (server_mode(options) &&
1524 !we_are_hibernating() &&
1525 seconds_elapsed > 0 &&
1526 can_complete_circuit &&
1527 stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
1528 (stats_n_seconds_working+seconds_elapsed) /
1529 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1530 /* every 20 minutes, check and complain if necessary */
1531 const routerinfo_t *me = router_get_my_routerinfo();
1532 if (me && !check_whether_orport_reachable()) {
1533 log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
1534 "its ORPort is reachable. Please check your firewalls, ports, "
1535 "address, /etc/hosts file, etc.",
1536 me->address, me->or_port);
1537 control_event_server_status(LOG_WARN,
1538 "REACHABILITY_FAILED ORADDRESS=%s:%d",
1539 me->address, me->or_port);
1542 if (me && !check_whether_dirport_reachable()) {
1543 log_warn(LD_CONFIG,
1544 "Your server (%s:%d) has not managed to confirm that its "
1545 "DirPort is reachable. Please check your firewalls, ports, "
1546 "address, /etc/hosts file, etc.",
1547 me->address, me->dir_port);
1548 control_event_server_status(LOG_WARN,
1549 "REACHABILITY_FAILED DIRADDRESS=%s:%d",
1550 me->address, me->dir_port);
1554 /** If more than this many seconds have elapsed, probably the clock
1555 * jumped: doesn't count. */
1556 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
1557 if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
1558 seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
1559 circuit_note_clock_jumped(seconds_elapsed);
1560 /* XXX if the time jumps *back* many months, do our events in
1561 * run_scheduled_events() recover? I don't think they do. -RD */
1562 } else if (seconds_elapsed > 0)
1563 stats_n_seconds_working += seconds_elapsed;
1565 run_scheduled_events(now);
1567 current_second = now; /* remember which second it is, for next time */
1570 #ifndef MS_WINDOWS
1571 /** Called when a possibly ignorable libevent error occurs; ensures that we
1572 * don't get into an infinite loop by ignoring too many errors from
1573 * libevent. */
1574 static int
1575 got_libevent_error(void)
1577 if (++n_libevent_errors > 8) {
1578 log_err(LD_NET, "Too many libevent errors in one second; dying");
1579 return -1;
1581 return 0;
1583 #endif
1585 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
1587 /** Called when our IP address seems to have changed. <b>at_interface</b>
1588 * should be true if we detected a change in our interface, and false if we
1589 * detected a change in our published address. */
1590 void
1591 ip_address_changed(int at_interface)
1593 int server = server_mode(get_options());
1595 if (at_interface) {
1596 if (! server) {
1597 /* Okay, change our keys. */
1598 init_keys();
1600 } else {
1601 if (server) {
1602 if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
1603 reset_bandwidth_test();
1604 stats_n_seconds_working = 0;
1605 router_reset_reachability();
1606 mark_my_descriptor_dirty("IP address changed");
1610 dns_servers_relaunch_checks();
1613 /** Forget what we've learned about the correctness of our DNS servers, and
1614 * start learning again. */
1615 void
1616 dns_servers_relaunch_checks(void)
1618 if (server_mode(get_options())) {
1619 dns_reset_correctness_checks();
1620 time_to_check_for_correct_dns = 0;
1624 /** Called when we get a SIGHUP: reload configuration files and keys,
1625 * retry all connections, and so on. */
1626 static int
1627 do_hup(void)
1629 or_options_t *options = get_options();
1631 #ifdef USE_DMALLOC
1632 dmalloc_log_stats();
1633 dmalloc_log_changed(0, 1, 0, 0);
1634 #endif
1636 log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
1637 "resetting internal state.");
1638 if (accounting_is_enabled(options))
1639 accounting_record_bandwidth_usage(time(NULL), get_or_state());
1641 router_reset_warnings();
1642 routerlist_reset_warnings();
1643 /* first, reload config variables, in case they've changed */
1644 if (options->ReloadTorrcOnSIGHUP) {
1645 /* no need to provide argc/v, they've been cached in init_from_config */
1646 if (options_init_from_torrc(0, NULL) < 0) {
1647 log_err(LD_CONFIG,"Reading config failed--see warnings above. "
1648 "For usage, try -h.");
1649 return -1;
1651 options = get_options(); /* they have changed now */
1652 } else {
1653 log_notice(LD_GENERAL, "Not reloading config file: the controller told "
1654 "us not to.");
1656 if (authdir_mode_handles_descs(options, -1)) {
1657 /* reload the approved-routers file */
1658 if (dirserv_load_fingerprint_file() < 0) {
1659 /* warnings are logged from dirserv_load_fingerprint_file() directly */
1660 log_info(LD_GENERAL, "Error reloading fingerprints. "
1661 "Continuing with old list.");
1665 /* Rotate away from the old dirty circuits. This has to be done
1666 * after we've read the new options, but before we start using
1667 * circuits for directory fetches. */
1668 circuit_expire_all_dirty_circs();
1670 /* retry appropriate downloads */
1671 router_reset_status_download_failures();
1672 router_reset_descriptor_download_failures();
1673 update_networkstatus_downloads(time(NULL));
1675 /* We'll retry routerstatus downloads in about 10 seconds; no need to
1676 * force a retry there. */
1678 if (server_mode(options)) {
1679 /* Restart cpuworker and dnsworker processes, so they get up-to-date
1680 * configuration options. */
1681 cpuworkers_rotate();
1682 dns_reset();
1684 return 0;
1687 /** Tor main loop. */
1688 /* static */ int
1689 do_main_loop(void)
1691 int loop_result;
1692 time_t now;
1694 /* initialize dns resolve map, spawn workers if needed */
1695 if (dns_init() < 0) {
1696 if (get_options()->ServerDNSAllowBrokenConfig)
1697 log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
1698 "Network not up yet? Will try again soon.");
1699 else {
1700 log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
1701 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
1705 handle_signals(1);
1707 /* load the private keys, if we're supposed to have them, and set up the
1708 * TLS context. */
1709 if (! client_identity_key_is_set()) {
1710 if (init_keys() < 0) {
1711 log_err(LD_BUG,"Error initializing keys; exiting");
1712 return -1;
1716 /* Set up the packed_cell_t memory pool. */
1717 init_cell_pool();
1719 /* Set up our buckets */
1720 connection_bucket_init();
1721 #ifndef USE_BUFFEREVENTS
1722 stats_prev_global_read_bucket = global_read_bucket;
1723 stats_prev_global_write_bucket = global_write_bucket;
1724 #endif
1726 /* initialize the bootstrap status events to know we're starting up */
1727 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
1729 if (trusted_dirs_reload_certs()) {
1730 log_warn(LD_DIR,
1731 "Couldn't load all cached v3 certificates. Starting anyway.");
1733 if (router_reload_v2_networkstatus()) {
1734 return -1;
1736 if (router_reload_consensus_networkstatus()) {
1737 return -1;
1739 /* load the routers file, or assign the defaults. */
1740 if (router_reload_router_list()) {
1741 return -1;
1743 /* load the networkstatuses. (This launches a download for new routers as
1744 * appropriate.)
1746 now = time(NULL);
1747 directory_info_has_arrived(now, 1);
1749 if (server_mode(get_options())) {
1750 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1751 cpu_init();
1754 /* set up once-a-second callback. */
1755 if (! second_timer) {
1756 struct timeval one_second;
1757 one_second.tv_sec = 1;
1758 one_second.tv_usec = 0;
1760 second_timer = periodic_timer_new(tor_libevent_get_base(),
1761 &one_second,
1762 second_elapsed_callback,
1763 NULL);
1764 tor_assert(second_timer);
1767 for (;;) {
1768 if (nt_service_is_stopping())
1769 return 0;
1771 #ifndef MS_WINDOWS
1772 /* Make it easier to tell whether libevent failure is our fault or not. */
1773 errno = 0;
1774 #endif
1775 /* All active linked conns should get their read events activated. */
1776 SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
1777 event_active(conn->read_event, EV_READ, 1));
1778 called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
1780 update_approx_time(time(NULL));
1782 /* poll until we have an event, or the second ends, or until we have
1783 * some active linked connections to trigger events for. */
1784 loop_result = event_base_loop(tor_libevent_get_base(),
1785 called_loop_once ? EVLOOP_ONCE : 0);
1787 /* let catch() handle things like ^c, and otherwise don't worry about it */
1788 if (loop_result < 0) {
1789 int e = tor_socket_errno(-1);
1790 /* let the program survive things like ^z */
1791 if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
1792 log_err(LD_NET,"libevent call with %s failed: %s [%d]",
1793 tor_libevent_get_method(), tor_socket_strerror(e), e);
1794 return -1;
1795 #ifndef MS_WINDOWS
1796 } else if (e == EINVAL) {
1797 log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
1798 if (got_libevent_error())
1799 return -1;
1800 #endif
1801 } else {
1802 if (ERRNO_IS_EINPROGRESS(e))
1803 log_warn(LD_BUG,
1804 "libevent call returned EINPROGRESS? Please report.");
1805 log_debug(LD_NET,"libevent call interrupted.");
1806 /* You can't trust the results of this poll(). Go back to the
1807 * top of the big for loop. */
1808 continue;
1814 #ifndef MS_WINDOWS /* Only called when we're willing to use signals */
1815 /** Libevent callback: invoked when we get a signal.
1817 static void
1818 signal_callback(int fd, short events, void *arg)
1820 uintptr_t sig = (uintptr_t)arg;
1821 (void)fd;
1822 (void)events;
1824 process_signal(sig);
1826 #endif
1828 /** Do the work of acting on a signal received in <b>sig</b> */
1829 void
1830 process_signal(uintptr_t sig)
1832 switch (sig)
1834 case SIGTERM:
1835 log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
1836 tor_cleanup();
1837 exit(0);
1838 break;
1839 case SIGINT:
1840 if (!server_mode(get_options())) { /* do it now */
1841 log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
1842 tor_cleanup();
1843 exit(0);
1845 hibernate_begin_shutdown();
1846 break;
1847 #ifdef SIGPIPE
1848 case SIGPIPE:
1849 log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
1850 break;
1851 #endif
1852 case SIGUSR1:
1853 /* prefer to log it at INFO, but make sure we always see it */
1854 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
1855 control_event_signal(sig);
1856 break;
1857 case SIGUSR2:
1858 switch_logs_debug();
1859 log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
1860 "Send HUP to change back.");
1861 control_event_signal(sig);
1862 break;
1863 case SIGHUP:
1864 if (do_hup() < 0) {
1865 log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
1866 tor_cleanup();
1867 exit(1);
1869 control_event_signal(sig);
1870 break;
1871 #ifdef SIGCHLD
1872 case SIGCHLD:
1873 while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more
1874 zombies */
1875 break;
1876 #endif
1877 case SIGNEWNYM: {
1878 time_t now = time(NULL);
1879 if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
1880 signewnym_is_pending = 1;
1881 log(LOG_NOTICE, LD_CONTROL,
1882 "Rate limiting NEWNYM request: delaying by %d second(s)",
1883 (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
1884 } else {
1885 signewnym_impl(now);
1886 control_event_signal(sig);
1888 break;
1890 case SIGCLEARDNSCACHE:
1891 addressmap_clear_transient();
1892 control_event_signal(sig);
1893 break;
1897 /** Returns Tor's uptime. */
1898 long
1899 get_uptime(void)
1901 return stats_n_seconds_working;
1904 extern uint64_t rephist_total_alloc;
1905 extern uint32_t rephist_total_num;
1908 * Write current memory usage information to the log.
1910 static void
1911 dumpmemusage(int severity)
1913 connection_dump_buffer_mem_stats(severity);
1914 log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
1915 U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
1916 dump_routerlist_mem_usage(severity);
1917 dump_cell_pool_usage(severity);
1918 dump_dns_mem_usage(severity);
1919 buf_dump_freelist_sizes(severity);
1920 tor_log_mallinfo(severity);
1923 /** Write all statistics to the log, with log level <b>severity</b>. Called
1924 * in response to a SIGUSR1. */
1925 static void
1926 dumpstats(int severity)
1928 time_t now = time(NULL);
1929 time_t elapsed;
1930 size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
1932 log(severity, LD_GENERAL, "Dumping stats:");
1934 SMARTLIST_FOREACH(connection_array, connection_t *, conn,
1936 int i = conn_sl_idx;
1937 log(severity, LD_GENERAL,
1938 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
1939 i, conn->s, conn->type, conn_type_to_string(conn->type),
1940 conn->state, conn_state_to_string(conn->type, conn->state),
1941 (int)(now - conn->timestamp_created));
1942 if (!connection_is_listener(conn)) {
1943 log(severity,LD_GENERAL,
1944 "Conn %d is to %s:%d.", i,
1945 safe_str_client(conn->address),
1946 conn->port);
1947 log(severity,LD_GENERAL,
1948 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
1950 (int)connection_get_inbuf_len(conn),
1951 (int)buf_allocation(conn->inbuf),
1952 (int)(now - conn->timestamp_lastread));
1953 log(severity,LD_GENERAL,
1954 "Conn %d: %d bytes waiting on outbuf "
1955 "(len %d, last written %d secs ago)",i,
1956 (int)connection_get_outbuf_len(conn),
1957 (int)buf_allocation(conn->outbuf),
1958 (int)(now - conn->timestamp_lastwritten));
1959 if (conn->type == CONN_TYPE_OR) {
1960 or_connection_t *or_conn = TO_OR_CONN(conn);
1961 if (or_conn->tls) {
1962 tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
1963 &wbuf_cap, &wbuf_len);
1964 log(severity, LD_GENERAL,
1965 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
1966 "%d/%d bytes used on write buffer.",
1967 i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
1971 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
1972 * using this conn */
1974 log(severity, LD_NET,
1975 "Cells processed: "U64_FORMAT" padding\n"
1976 " "U64_FORMAT" create\n"
1977 " "U64_FORMAT" created\n"
1978 " "U64_FORMAT" relay\n"
1979 " ("U64_FORMAT" relayed)\n"
1980 " ("U64_FORMAT" delivered)\n"
1981 " "U64_FORMAT" destroy",
1982 U64_PRINTF_ARG(stats_n_padding_cells_processed),
1983 U64_PRINTF_ARG(stats_n_create_cells_processed),
1984 U64_PRINTF_ARG(stats_n_created_cells_processed),
1985 U64_PRINTF_ARG(stats_n_relay_cells_processed),
1986 U64_PRINTF_ARG(stats_n_relay_cells_relayed),
1987 U64_PRINTF_ARG(stats_n_relay_cells_delivered),
1988 U64_PRINTF_ARG(stats_n_destroy_cells_processed));
1989 if (stats_n_data_cells_packaged)
1990 log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
1991 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
1992 U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
1993 if (stats_n_data_cells_received)
1994 log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
1995 100*(U64_TO_DBL(stats_n_data_bytes_received) /
1996 U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
1998 if (now - time_of_process_start >= 0)
1999 elapsed = now - time_of_process_start;
2000 else
2001 elapsed = 0;
2003 if (elapsed) {
2004 log(severity, LD_NET,
2005 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
2006 U64_PRINTF_ARG(stats_n_bytes_read),
2007 (int)elapsed,
2008 (int) (stats_n_bytes_read/elapsed));
2009 log(severity, LD_NET,
2010 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
2011 U64_PRINTF_ARG(stats_n_bytes_written),
2012 (int)elapsed,
2013 (int) (stats_n_bytes_written/elapsed));
2016 log(severity, LD_NET, "--------------- Dumping memory information:");
2017 dumpmemusage(severity);
2019 rep_hist_dump_stats(now,severity);
2020 rend_service_dump_stats(severity);
2021 dump_pk_ops(severity);
2022 dump_distinct_digest_count(severity);
2025 /** Called by exit() as we shut down the process.
2027 static void
2028 exit_function(void)
2030 /* NOTE: If we ever daemonize, this gets called immediately. That's
2031 * okay for now, because we only use this on Windows. */
2032 #ifdef MS_WINDOWS
2033 WSACleanup();
2034 #endif
2037 /** Set up the signal handlers for either parent or child. */
2038 void
2039 handle_signals(int is_parent)
2041 #ifndef MS_WINDOWS /* do signal stuff only on Unix */
2042 int i;
2043 static const int signals[] = {
2044 SIGINT, /* do a controlled slow shutdown */
2045 SIGTERM, /* to terminate now */
2046 SIGPIPE, /* otherwise SIGPIPE kills us */
2047 SIGUSR1, /* dump stats */
2048 SIGUSR2, /* go to loglevel debug */
2049 SIGHUP, /* to reload config, retry conns, etc */
2050 #ifdef SIGXFSZ
2051 SIGXFSZ, /* handle file-too-big resource exhaustion */
2052 #endif
2053 SIGCHLD, /* handle dns/cpu workers that exit */
2054 -1 };
2055 static struct event *signal_events[16]; /* bigger than it has to be. */
2056 if (is_parent) {
2057 for (i = 0; signals[i] >= 0; ++i) {
2058 signal_events[i] = tor_evsignal_new(
2059 tor_libevent_get_base(), signals[i], signal_callback,
2060 (void*)(uintptr_t)signals[i]);
2061 if (event_add(signal_events[i], NULL))
2062 log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
2063 signals[i]);
2065 } else {
2066 struct sigaction action;
2067 action.sa_flags = 0;
2068 sigemptyset(&action.sa_mask);
2069 action.sa_handler = SIG_IGN;
2070 sigaction(SIGINT, &action, NULL);
2071 sigaction(SIGTERM, &action, NULL);
2072 sigaction(SIGPIPE, &action, NULL);
2073 sigaction(SIGUSR1, &action, NULL);
2074 sigaction(SIGUSR2, &action, NULL);
2075 sigaction(SIGHUP, &action, NULL);
2076 #ifdef SIGXFSZ
2077 sigaction(SIGXFSZ, &action, NULL);
2078 #endif
2080 #else /* MS windows */
2081 (void)is_parent;
2082 #endif /* signal stuff */
2085 /** Main entry point for the Tor command-line client.
2087 /* static */ int
2088 tor_init(int argc, char *argv[])
2090 char buf[256];
2091 int i, quiet = 0;
2092 time_of_process_start = time(NULL);
2093 if (!connection_array)
2094 connection_array = smartlist_create();
2095 if (!closeable_connection_lst)
2096 closeable_connection_lst = smartlist_create();
2097 if (!active_linked_connection_lst)
2098 active_linked_connection_lst = smartlist_create();
2099 /* Have the log set up with our application name. */
2100 tor_snprintf(buf, sizeof(buf), "Tor %s", get_version());
2101 log_set_application_name(buf);
2102 /* Initialize the history structures. */
2103 rep_hist_init();
2104 /* Initialize the service cache. */
2105 rend_cache_init();
2106 addressmap_init(); /* Init the client dns cache. Do it always, since it's
2107 * cheap. */
2109 /* We search for the "quiet" option first, since it decides whether we
2110 * will log anything at all to the command line. */
2111 for (i=1;i<argc;++i) {
2112 if (!strcmp(argv[i], "--hush"))
2113 quiet = 1;
2114 if (!strcmp(argv[i], "--quiet"))
2115 quiet = 2;
2117 /* give it somewhere to log to initially */
2118 switch (quiet) {
2119 case 2:
2120 /* no initial logging */
2121 break;
2122 case 1:
2123 add_temp_log(LOG_WARN);
2124 break;
2125 default:
2126 add_temp_log(LOG_NOTICE);
2129 log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. "
2130 "Do not rely on it for strong anonymity. (Running on %s)",get_version(),
2131 get_uname());
2133 if (network_init()<0) {
2134 log_err(LD_BUG,"Error initializing network; exiting.");
2135 return -1;
2137 atexit(exit_function);
2139 if (options_init_from_torrc(argc,argv) < 0) {
2140 log_err(LD_CONFIG,"Reading config failed--see warnings above.");
2141 return -1;
2144 #ifndef MS_WINDOWS
2145 if (geteuid()==0)
2146 log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
2147 "and you probably shouldn't.");
2148 #endif
2150 if (crypto_global_init(get_options()->HardwareAccel,
2151 get_options()->AccelName,
2152 get_options()->AccelDir)) {
2153 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
2154 return -1;
2157 return 0;
2160 /** A lockfile structure, used to prevent two Tors from messing with the
2161 * data directory at once. If this variable is non-NULL, we're holding
2162 * the lockfile. */
2163 static tor_lockfile_t *lockfile = NULL;
2165 /** Try to grab the lock file described in <b>options</b>, if we do not
2166 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
2167 * holding the lock, and exit if we can't get it after waiting. Otherwise,
2168 * return -1 if we can't get the lockfile. Return 0 on success.
2171 try_locking(or_options_t *options, int err_if_locked)
2173 if (lockfile)
2174 return 0;
2175 else {
2176 char *fname = options_get_datadir_fname2_suffix(options, "lock",NULL,NULL);
2177 int already_locked = 0;
2178 tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
2179 tor_free(fname);
2180 if (!lf) {
2181 if (err_if_locked && already_locked) {
2182 int r;
2183 log_warn(LD_GENERAL, "It looks like another Tor process is running "
2184 "with the same data directory. Waiting 5 seconds to see "
2185 "if it goes away.");
2186 #ifndef WIN32
2187 sleep(5);
2188 #else
2189 Sleep(5000);
2190 #endif
2191 r = try_locking(options, 0);
2192 if (r<0) {
2193 log_err(LD_GENERAL, "No, it's still there. Exiting.");
2194 exit(0);
2196 return r;
2198 return -1;
2200 lockfile = lf;
2201 return 0;
2205 /** Return true iff we've successfully acquired the lock file. */
2207 have_lockfile(void)
2209 return lockfile != NULL;
2212 /** If we have successfully acquired the lock file, release it. */
2213 void
2214 release_lockfile(void)
2216 if (lockfile) {
2217 tor_lockfile_unlock(lockfile);
2218 lockfile = NULL;
2222 /** Free all memory that we might have allocated somewhere.
2223 * If <b>postfork</b>, we are a worker process and we want to free
2224 * only the parts of memory that we won't touch. If !<b>postfork</b>,
2225 * Tor is shutting down and we should free everything.
2227 * Helps us find the real leaks with dmalloc and the like. Also valgrind
2228 * should then report 0 reachable in its leak report (in an ideal world --
2229 * in practice libevent, SSL, libc etc never quite free everything). */
2230 void
2231 tor_free_all(int postfork)
2233 if (!postfork) {
2234 evdns_shutdown(1);
2236 geoip_free_all();
2237 dirvote_free_all();
2238 routerlist_free_all();
2239 networkstatus_free_all();
2240 addressmap_free_all();
2241 dirserv_free_all();
2242 rend_service_free_all();
2243 rend_cache_free_all();
2244 rend_service_authorization_free_all();
2245 rep_hist_free_all();
2246 dns_free_all();
2247 clear_pending_onions();
2248 circuit_free_all();
2249 entry_guards_free_all();
2250 connection_free_all();
2251 buf_shrink_freelists(1);
2252 memarea_clear_freelist();
2253 nodelist_free_all();
2254 microdesc_free_all();
2255 if (!postfork) {
2256 config_free_all();
2257 router_free_all();
2258 policies_free_all();
2260 free_cell_pool();
2261 if (!postfork) {
2262 tor_tls_free_all();
2264 /* stuff in main.c */
2266 smartlist_free(connection_array);
2267 smartlist_free(closeable_connection_lst);
2268 smartlist_free(active_linked_connection_lst);
2269 periodic_timer_free(second_timer);
2270 if (!postfork) {
2271 release_lockfile();
2273 /* Stuff in util.c and address.c*/
2274 if (!postfork) {
2275 escaped(NULL);
2276 esc_router_info(NULL);
2277 logs_free_all(); /* free log strings. do this last so logs keep working. */
2281 /** Do whatever cleanup is necessary before shutting Tor down. */
2282 void
2283 tor_cleanup(void)
2285 or_options_t *options = get_options();
2286 if (options->command == CMD_RUN_TOR) {
2287 time_t now = time(NULL);
2288 /* Remove our pid file. We don't care if there was an error when we
2289 * unlink, nothing we could do about it anyways. */
2290 if (options->PidFile)
2291 unlink(options->PidFile);
2292 if (options->ControlPortWriteToFile)
2293 unlink(options->ControlPortWriteToFile);
2294 if (accounting_is_enabled(options))
2295 accounting_record_bandwidth_usage(now, get_or_state());
2296 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
2297 or_state_save(now);
2298 if (authdir_mode_tests_reachability(options))
2299 rep_hist_record_mtbf_data(now, 0);
2301 #ifdef USE_DMALLOC
2302 dmalloc_log_stats();
2303 #endif
2304 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
2305 later, if it makes shutdown unacceptably slow. But for
2306 now, leave it here: it's helped us catch bugs in the
2307 past. */
2308 crypto_global_cleanup();
2309 #ifdef USE_DMALLOC
2310 dmalloc_log_unfreed();
2311 dmalloc_shutdown();
2312 #endif
2315 /** Read/create keys as needed, and echo our fingerprint to stdout. */
2316 /* static */ int
2317 do_list_fingerprint(void)
2319 char buf[FINGERPRINT_LEN+1];
2320 crypto_pk_env_t *k;
2321 const char *nickname = get_options()->Nickname;
2322 if (!server_mode(get_options())) {
2323 log_err(LD_GENERAL,
2324 "Clients don't have long-term identity keys. Exiting.\n");
2325 return -1;
2327 tor_assert(nickname);
2328 if (init_keys() < 0) {
2329 log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
2330 return -1;
2332 if (!(k = get_server_identity_key())) {
2333 log_err(LD_GENERAL,"Error: missing identity key.");
2334 return -1;
2336 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
2337 log_err(LD_BUG, "Error computing fingerprint");
2338 return -1;
2340 printf("%s %s\n", nickname, buf);
2341 return 0;
2344 /** Entry point for password hashing: take the desired password from
2345 * the command line, and print its salted hash to stdout. **/
2346 /* static */ void
2347 do_hash_password(void)
2350 char output[256];
2351 char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
2353 crypto_rand(key, S2K_SPECIFIER_LEN-1);
2354 key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
2355 secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
2356 get_options()->command_arg, strlen(get_options()->command_arg),
2357 key);
2358 base16_encode(output, sizeof(output), key, sizeof(key));
2359 printf("16:%s\n",output);
2362 #if defined (WINCE)
2364 find_flashcard_path(PWCHAR path, size_t size)
2366 WIN32_FIND_DATA d = {0};
2367 HANDLE h = NULL;
2369 if (!path)
2370 return -1;
2372 h = FindFirstFlashCard(&d);
2373 if (h == INVALID_HANDLE_VALUE)
2374 return -1;
2376 if (wcslen(d.cFileName) == 0) {
2377 FindClose(h);
2378 return -1;
2381 wcsncpy(path,d.cFileName,size);
2382 FindClose(h);
2383 return 0;
2385 #endif
2387 /** Main entry point for the Tor process. Called from main(). */
2388 /* This function is distinct from main() only so we can link main.c into
2389 * the unittest binary without conflicting with the unittests' main. */
2391 tor_main(int argc, char *argv[])
2393 int result = 0;
2394 #if defined (WINCE)
2395 WCHAR path [MAX_PATH] = {0};
2396 WCHAR fullpath [MAX_PATH] = {0};
2397 PWCHAR p = NULL;
2398 FILE* redir = NULL;
2399 FILE* redirdbg = NULL;
2401 // this is to facilitate debugging by opening
2402 // a file on a folder shared by the wm emulator.
2403 // if no flashcard (real or emulated) is present,
2404 // log files will be written in the root folder
2405 if (find_flashcard_path(path,MAX_PATH) == -1)
2407 redir = _wfreopen( L"\\stdout.log", L"w", stdout );
2408 redirdbg = _wfreopen( L"\\stderr.log", L"w", stderr );
2409 } else {
2410 swprintf(fullpath,L"\\%s\\tor",path);
2411 CreateDirectory(fullpath,NULL);
2413 swprintf(fullpath,L"\\%s\\tor\\stdout.log",path);
2414 redir = _wfreopen( fullpath, L"w", stdout );
2416 swprintf(fullpath,L"\\%s\\tor\\stderr.log",path);
2417 redirdbg = _wfreopen( fullpath, L"w", stderr );
2419 #endif
2421 #ifdef MS_WINDOWS
2422 /* Call SetProcessDEPPolicy to permanently enable DEP.
2423 The function will not resolve on earlier versions of Windows,
2424 and failure is not dangerous. */
2425 HMODULE hMod = GetModuleHandleA("Kernel32.dll");
2426 if (hMod) {
2427 typedef BOOL (WINAPI *PSETDEP)(DWORD);
2428 PSETDEP setdeppolicy = (PSETDEP)GetProcAddress(hMod,
2429 "SetProcessDEPPolicy");
2430 if (setdeppolicy) setdeppolicy(1); /* PROCESS_DEP_ENABLE */
2432 #endif
2434 update_approx_time(time(NULL));
2435 tor_threads_init();
2436 init_logging();
2437 #ifdef USE_DMALLOC
2439 /* Instruct OpenSSL to use our internal wrappers for malloc,
2440 realloc and free. */
2441 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
2442 tor_assert(r);
2444 #endif
2445 #ifdef NT_SERVICE
2447 int done = 0;
2448 result = nt_service_parse_options(argc, argv, &done);
2449 if (done) return result;
2451 #endif
2452 if (tor_init(argc, argv)<0)
2453 return -1;
2454 switch (get_options()->command) {
2455 case CMD_RUN_TOR:
2456 #ifdef NT_SERVICE
2457 nt_service_set_state(SERVICE_RUNNING);
2458 #endif
2459 result = do_main_loop();
2460 break;
2461 case CMD_LIST_FINGERPRINT:
2462 result = do_list_fingerprint();
2463 break;
2464 case CMD_HASH_PASSWORD:
2465 do_hash_password();
2466 result = 0;
2467 break;
2468 case CMD_VERIFY_CONFIG:
2469 printf("Configuration was valid\n");
2470 result = 0;
2471 break;
2472 case CMD_RUN_UNITTESTS: /* only set by test.c */
2473 default:
2474 log_warn(LD_BUG,"Illegal command number %d: internal error.",
2475 get_options()->command);
2476 result = -1;
2478 tor_cleanup();
2479 return result;