Whitespace fixes.
[tor.git] / src / or / main.c
blob47af2d01edb1d28b21ab2e990ce28206bc2f68f1
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-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char main_c_id[] =
8 "$Id$";
10 /**
11 * \file main.c
12 * \brief Toplevel module. Handles signals, multiplexes between
13 * connections, implements main loop, and drives scheduled events.
14 **/
16 #define MAIN_PRIVATE
17 #include "or.h"
18 #ifdef USE_DMALLOC
19 #include <dmalloc.h>
20 #include <openssl/crypto.h>
21 #endif
22 #include "memarea.h"
24 void evdns_shutdown(int);
26 /********* PROTOTYPES **********/
28 static void dumpmemusage(int severity);
29 static void dumpstats(int severity); /* log stats */
30 static void conn_read_callback(int fd, short event, void *_conn);
31 static void conn_write_callback(int fd, short event, void *_conn);
32 static void signal_callback(int fd, short events, void *arg);
33 static void second_elapsed_callback(int fd, short event, void *args);
34 static int conn_close_if_marked(int i);
35 static void connection_start_reading_from_linked_conn(connection_t *conn);
36 static int connection_should_read_from_linked_conn(connection_t *conn);
38 /********* START VARIABLES **********/
40 int global_read_bucket; /**< Max number of bytes I can read this second. */
41 int global_write_bucket; /**< Max number of bytes I can write this second. */
43 /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
44 int global_relayed_read_bucket;
45 /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
46 int global_relayed_write_bucket;
48 /** What was the read bucket before the last call to prepare_for_pool?
49 * (used to determine how many bytes we've read). */
50 static int stats_prev_global_read_bucket;
51 /** What was the write bucket before the last call to prepare_for_pool?
52 * (used to determine how many bytes we've written). */
53 static int stats_prev_global_write_bucket;
54 /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
55 /** How many bytes have we read/written since we started the process? */
56 static uint64_t stats_n_bytes_read = 0;
57 static uint64_t stats_n_bytes_written = 0;
58 /** What time did this process start up? */
59 time_t time_of_process_start = 0;
60 /** How many seconds have we been running? */
61 long stats_n_seconds_working = 0;
62 /** When do we next launch DNS wildcarding checks? */
63 static time_t time_to_check_for_correct_dns = 0;
65 /** How often will we honor SIGNEWNYM requests? */
66 #define MAX_SIGNEWNYM_RATE 10
67 /** When did we last process a SIGNEWNYM request? */
68 static time_t time_of_last_signewnym = 0;
69 /** Is there a signewnym request we're currently waiting to handle? */
70 static int signewnym_is_pending = 0;
72 /** Smartlist of all open connections. */
73 static smartlist_t *connection_array = NULL;
74 /** List of connections that have been marked for close and need to be freed
75 * and removed from connection_array. */
76 static smartlist_t *closeable_connection_lst = NULL;
77 /** List of linked connections that are currently reading data into their
78 * inbuf from their partner's outbuf. */
79 static smartlist_t *active_linked_connection_lst = NULL;
80 /** Flag: Set to true iff we entered the current libevent main loop via
81 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
82 * to handle linked connections. */
83 static int called_loop_once = 0;
85 /** We set this to 1 when we've opened a circuit, so we can print a log
86 * entry to inform the user that Tor is working. */
87 int has_completed_circuit=0;
89 /** How often do we check for router descriptors that we should download
90 * when we have too little directory info? */
91 #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
92 /** How often do we check for router descriptors that we should download
93 * when we have enough directory info? */
94 #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
95 /** How often do we 'forgive' undownloadable router descriptors and attempt
96 * to download them again? */
97 #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
98 /** How long do we let a directory connection stall before expiring it? */
99 #define DIR_CONN_MAX_STALL (5*60)
101 /** How old do we let a connection to an OR get before deciding it's
102 * obsolete? */
103 #define TIME_BEFORE_OR_CONN_IS_OBSOLETE (60*60*24*7)
104 /** How long do we let OR connections handshake before we decide that
105 * they are obsolete? */
106 #define TLS_HANDSHAKE_TIMEOUT (60)
108 /********* END VARIABLES ************/
110 /****************************************************************************
112 * This section contains accessors and other methods on the connection_array
113 * variables (which are global within this file and unavailable outside it).
115 ****************************************************************************/
117 /** Add <b>conn</b> to the array of connections that we can poll on. The
118 * connection's socket must be set; the connection starts out
119 * non-reading and non-writing.
122 connection_add(connection_t *conn)
124 tor_assert(conn);
125 tor_assert(conn->s >= 0 ||
126 conn->linked ||
127 (conn->type == CONN_TYPE_AP &&
128 TO_EDGE_CONN(conn)->is_dns_request));
130 tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
131 conn->conn_array_index = smartlist_len(connection_array);
132 smartlist_add(connection_array, conn);
134 if (conn->s >= 0 || conn->linked) {
135 conn->read_event = tor_malloc_zero(sizeof(struct event));
136 conn->write_event = tor_malloc_zero(sizeof(struct event));
137 event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
138 conn_read_callback, conn);
139 event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
140 conn_write_callback, conn);
143 log_debug(LD_NET,"new conn type %s, socket %d, n_conns %d.",
144 conn_type_to_string(conn->type), conn->s,
145 smartlist_len(connection_array));
147 return 0;
150 /** Remove the connection from the global list, and remove the
151 * corresponding poll entry. Calling this function will shift the last
152 * connection (if any) into the position occupied by conn.
155 connection_remove(connection_t *conn)
157 int current_index;
158 connection_t *tmp;
160 tor_assert(conn);
162 log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
163 conn->s, conn_type_to_string(conn->type),
164 smartlist_len(connection_array));
166 tor_assert(conn->conn_array_index >= 0);
167 current_index = conn->conn_array_index;
168 connection_unregister_events(conn); /* This is redundant, but cheap. */
169 if (current_index == smartlist_len(connection_array)-1) { /* at the end */
170 smartlist_del(connection_array, current_index);
171 return 0;
174 /* replace this one with the one at the end */
175 smartlist_del(connection_array, current_index);
176 tmp = smartlist_get(connection_array, current_index);
177 tmp->conn_array_index = current_index;
179 return 0;
182 /** If <b>conn</b> is an edge conn, remove it from the list
183 * of conn's on this circuit. If it's not on an edge,
184 * flush and send destroys for all circuits on this conn.
186 * Remove it from connection_array (if applicable) and
187 * from closeable_connection_list.
189 * Then free it.
191 static void
192 connection_unlink(connection_t *conn)
194 connection_about_to_close_connection(conn);
195 if (conn->conn_array_index >= 0) {
196 connection_remove(conn);
198 if (conn->linked_conn) {
199 conn->linked_conn->linked_conn = NULL;
200 if (! conn->linked_conn->marked_for_close &&
201 conn->linked_conn->reading_from_linked_conn)
202 connection_start_reading(conn->linked_conn);
203 conn->linked_conn = NULL;
205 smartlist_remove(closeable_connection_lst, conn);
206 smartlist_remove(active_linked_connection_lst, conn);
207 if (conn->type == CONN_TYPE_EXIT) {
208 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
210 if (conn->type == CONN_TYPE_OR) {
211 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
212 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
214 connection_free(conn);
217 /** Schedule <b>conn</b> to be closed. **/
218 void
219 add_connection_to_closeable_list(connection_t *conn)
221 tor_assert(!smartlist_isin(closeable_connection_lst, conn));
222 tor_assert(conn->marked_for_close);
223 assert_connection_ok(conn, time(NULL));
224 smartlist_add(closeable_connection_lst, conn);
227 /** Return 1 if conn is on the closeable list, else return 0. */
229 connection_is_on_closeable_list(connection_t *conn)
231 return smartlist_isin(closeable_connection_lst, conn);
234 /** Return true iff conn is in the current poll array. */
236 connection_in_array(connection_t *conn)
238 return smartlist_isin(connection_array, conn);
241 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
242 * to the length of the array. <b>*array</b> and <b>*n</b> must not
243 * be modified.
245 smartlist_t *
246 get_connection_array(void)
248 if (!connection_array)
249 connection_array = smartlist_create();
250 return connection_array;
253 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
254 * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
256 void
257 connection_watch_events(connection_t *conn, short events)
259 if (events & EV_READ)
260 connection_start_reading(conn);
261 else
262 connection_stop_reading(conn);
264 if (events & EV_WRITE)
265 connection_start_writing(conn);
266 else
267 connection_stop_writing(conn);
270 /** Return true iff <b>conn</b> is listening for read events. */
272 connection_is_reading(connection_t *conn)
274 tor_assert(conn);
276 return conn->reading_from_linked_conn ||
277 (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
280 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
281 void
282 connection_stop_reading(connection_t *conn)
284 tor_assert(conn);
285 tor_assert(conn->read_event);
287 if (conn->linked) {
288 conn->reading_from_linked_conn = 0;
289 connection_stop_reading_from_linked_conn(conn);
290 } else {
291 if (event_del(conn->read_event))
292 log_warn(LD_NET, "Error from libevent setting read event state for %d "
293 "to unwatched: %s",
294 conn->s,
295 tor_socket_strerror(tor_socket_errno(conn->s)));
299 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
300 void
301 connection_start_reading(connection_t *conn)
303 tor_assert(conn);
304 tor_assert(conn->read_event);
306 if (conn->linked) {
307 conn->reading_from_linked_conn = 1;
308 if (connection_should_read_from_linked_conn(conn))
309 connection_start_reading_from_linked_conn(conn);
310 } else {
311 if (event_add(conn->read_event, NULL))
312 log_warn(LD_NET, "Error from libevent setting read event state for %d "
313 "to watched: %s",
314 conn->s,
315 tor_socket_strerror(tor_socket_errno(conn->s)));
319 /** Return true iff <b>conn</b> is listening for write events. */
321 connection_is_writing(connection_t *conn)
323 tor_assert(conn);
325 return conn->writing_to_linked_conn ||
326 (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
329 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
330 void
331 connection_stop_writing(connection_t *conn)
333 tor_assert(conn);
334 tor_assert(conn->write_event);
336 if (conn->linked) {
337 conn->writing_to_linked_conn = 0;
338 if (conn->linked_conn)
339 connection_stop_reading_from_linked_conn(conn->linked_conn);
340 } else {
341 if (event_del(conn->write_event))
342 log_warn(LD_NET, "Error from libevent setting write event state for %d "
343 "to unwatched: %s",
344 conn->s,
345 tor_socket_strerror(tor_socket_errno(conn->s)));
349 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
350 void
351 connection_start_writing(connection_t *conn)
353 tor_assert(conn);
354 tor_assert(conn->write_event);
356 if (conn->linked) {
357 conn->writing_to_linked_conn = 1;
358 if (conn->linked_conn &&
359 connection_should_read_from_linked_conn(conn->linked_conn))
360 connection_start_reading_from_linked_conn(conn->linked_conn);
361 } else {
362 if (event_add(conn->write_event, NULL))
363 log_warn(LD_NET, "Error from libevent setting write event state for %d "
364 "to watched: %s",
365 conn->s,
366 tor_socket_strerror(tor_socket_errno(conn->s)));
370 /** Return true iff <b>conn</b> is linked conn, and reading from the conn
371 * linked to it would be good and feasible. (Reading is "feasible" if the
372 * other conn exists and has data in its outbuf, and is "good" if we have our
373 * reading_from_linked_conn flag set and the other conn has its
374 * writing_to_linked_conn flag set.)*/
375 static int
376 connection_should_read_from_linked_conn(connection_t *conn)
378 if (conn->linked && conn->reading_from_linked_conn) {
379 if (! conn->linked_conn ||
380 (conn->linked_conn->writing_to_linked_conn &&
381 buf_datalen(conn->linked_conn->outbuf)))
382 return 1;
384 return 0;
387 /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
388 * its linked connection, if it is not doing so already. Called by
389 * connection_start_reading and connection_start_writing as appropriate. */
390 static void
391 connection_start_reading_from_linked_conn(connection_t *conn)
393 tor_assert(conn);
394 tor_assert(conn->linked == 1);
396 if (!conn->active_on_link) {
397 conn->active_on_link = 1;
398 smartlist_add(active_linked_connection_lst, conn);
399 if (!called_loop_once) {
400 /* This is the first event on the list; we won't be in LOOP_ONCE mode,
401 * so we need to make sure that the event_loop() actually exits at the
402 * end of its run through the current connections and
403 * lets us activate read events for linked connections. */
404 struct timeval tv = { 0, 0 };
405 event_loopexit(&tv);
407 } else {
408 tor_assert(smartlist_isin(active_linked_connection_lst, conn));
412 /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
413 * connection, if is currently doing so. Called by connection_stop_reading,
414 * connection_stop_writing, and connection_read. */
415 void
416 connection_stop_reading_from_linked_conn(connection_t *conn)
418 tor_assert(conn);
419 tor_assert(conn->linked == 1);
421 if (conn->active_on_link) {
422 conn->active_on_link = 0;
423 /* FFFF We could keep an index here so we can smartlist_del
424 * cleanly. On the other hand, this doesn't show up on profiles,
425 * so let's leave it alone for now. */
426 smartlist_remove(active_linked_connection_lst, conn);
427 } else {
428 tor_assert(!smartlist_isin(active_linked_connection_lst, conn));
432 /** Close all connections that have been scheduled to get closed. */
433 static void
434 close_closeable_connections(void)
436 int i;
437 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
438 connection_t *conn = smartlist_get(closeable_connection_lst, i);
439 if (conn->conn_array_index < 0) {
440 connection_unlink(conn); /* blow it away right now */
441 } else {
442 if (!conn_close_if_marked(conn->conn_array_index))
443 ++i;
448 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
449 * some data to read. */
450 static void
451 conn_read_callback(int fd, short event, void *_conn)
453 connection_t *conn = _conn;
454 (void)fd;
455 (void)event;
457 log_debug(LD_NET,"socket %d wants to read.",conn->s);
459 assert_connection_ok(conn, time(NULL));
461 if (connection_handle_read(conn) < 0) {
462 if (!conn->marked_for_close) {
463 #ifndef MS_WINDOWS
464 log_warn(LD_BUG,"Unhandled error on read for %s connection "
465 "(fd %d); removing",
466 conn_type_to_string(conn->type), conn->s);
467 tor_fragile_assert();
468 #endif
469 if (CONN_IS_EDGE(conn))
470 connection_edge_end_errno(TO_EDGE_CONN(conn));
471 connection_mark_for_close(conn);
474 assert_connection_ok(conn, time(NULL));
476 if (smartlist_len(closeable_connection_lst))
477 close_closeable_connections();
480 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
481 * some data to write. */
482 static void
483 conn_write_callback(int fd, short events, void *_conn)
485 connection_t *conn = _conn;
486 (void)fd;
487 (void)events;
489 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
491 assert_connection_ok(conn, time(NULL));
493 if (connection_handle_write(conn, 0) < 0) {
494 if (!conn->marked_for_close) {
495 /* this connection is broken. remove it. */
496 log_fn(LOG_WARN,LD_BUG,
497 "unhandled error on write for %s connection (fd %d); removing",
498 conn_type_to_string(conn->type), conn->s);
499 tor_fragile_assert();
500 if (CONN_IS_EDGE(conn)) {
501 /* otherwise we cry wolf about duplicate close */
502 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
503 if (!edge_conn->end_reason)
504 edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
505 conn->edge_has_sent_end = 1;
507 connection_close_immediate(conn); /* So we don't try to flush. */
508 connection_mark_for_close(conn);
511 assert_connection_ok(conn, time(NULL));
513 if (smartlist_len(closeable_connection_lst))
514 close_closeable_connections();
517 /** If the connection at connection_array[i] is marked for close, then:
518 * - If it has data that it wants to flush, try to flush it.
519 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
520 * true, then leave the connection open and return.
521 * - Otherwise, remove the connection from connection_array and from
522 * all other lists, close it, and free it.
523 * Returns 1 if the connection was closed, 0 otherwise.
525 static int
526 conn_close_if_marked(int i)
528 connection_t *conn;
529 int retval;
530 time_t now;
532 conn = smartlist_get(connection_array, i);
533 if (!conn->marked_for_close)
534 return 0; /* nothing to see here, move along */
535 now = time(NULL);
536 assert_connection_ok(conn, now);
537 assert_all_pending_dns_resolves_ok();
539 log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
540 if ((conn->s >= 0 || conn->linked_conn) && connection_wants_to_flush(conn)) {
541 /* s == -1 means it's an incomplete edge connection, or that the socket
542 * has already been closed as unflushable. */
543 ssize_t sz = connection_bucket_write_limit(conn, now);
544 if (!conn->hold_open_until_flushed)
545 log_info(LD_NET,
546 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
547 "to flush %d bytes. (Marked at %s:%d)",
548 escaped_safe_str(conn->address),
549 conn->s, conn_type_to_string(conn->type), conn->state,
550 (int)conn->outbuf_flushlen,
551 conn->marked_for_close_file, conn->marked_for_close);
552 if (conn->linked_conn) {
553 retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
554 &conn->outbuf_flushlen);
555 if (retval >= 0) {
556 /* The linked conn will notice that it has data when it notices that
557 * we're gone. */
558 connection_start_reading_from_linked_conn(conn->linked_conn);
560 log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
561 "%d left; flushlen %d; wants-to-flush==%d", retval,
562 (int)buf_datalen(conn->outbuf),
563 (int)conn->outbuf_flushlen,
564 connection_wants_to_flush(conn));
565 } else if (connection_speaks_cells(conn)) {
566 if (conn->state == OR_CONN_STATE_OPEN) {
567 retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
568 &conn->outbuf_flushlen);
569 } else
570 retval = -1; /* never flush non-open broken tls connections */
571 } else {
572 retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
574 if (retval >= 0 && /* Technically, we could survive things like
575 TLS_WANT_WRITE here. But don't bother for now. */
576 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
577 if (retval > 0) {
578 LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
579 "Holding conn (fd %d) open for more flushing.",
580 conn->s));
581 conn->timestamp_lastwritten = now; /* reset so we can flush more */
583 return 0;
585 if (connection_wants_to_flush(conn)) {
586 int severity;
587 if (conn->type == CONN_TYPE_EXIT ||
588 (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
589 (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
590 severity = LOG_INFO;
591 else
592 severity = LOG_NOTICE;
593 /* XXXX Maybe allow this to happen a certain amount per hour; it usually
594 * is meaningless. */
595 log_fn(severity, LD_NET, "We stalled too much while trying to write %d "
596 "bytes to address %s. If this happens a lot, either "
597 "something is wrong with your network connection, or "
598 "something is wrong with theirs. "
599 "(fd %d, type %s, state %d, marked at %s:%d).",
600 (int)buf_datalen(conn->outbuf),
601 escaped_safe_str(conn->address), conn->s,
602 conn_type_to_string(conn->type), conn->state,
603 conn->marked_for_close_file,
604 conn->marked_for_close);
607 connection_unlink(conn); /* unlink, remove, free */
608 return 1;
611 /** We've just tried every dirserver we know about, and none of
612 * them were reachable. Assume the network is down. Change state
613 * so next time an application connection arrives we'll delay it
614 * and try another directory fetch. Kill off all the circuit_wait
615 * streams that are waiting now, since they will all timeout anyway.
617 void
618 directory_all_unreachable(time_t now)
620 connection_t *conn;
621 (void)now;
623 stats_n_seconds_working=0; /* reset it */
625 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
626 AP_CONN_STATE_CIRCUIT_WAIT))) {
627 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
628 log_notice(LD_NET,
629 "Is your network connection down? "
630 "Failing connection to '%s:%d'.",
631 safe_str(edge_conn->socks_request->address),
632 edge_conn->socks_request->port);
633 connection_mark_unattached_ap(edge_conn,
634 END_STREAM_REASON_NET_UNREACHABLE);
636 control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
639 /** This function is called whenever we successfully pull down some new
640 * network statuses or server descriptors. */
641 void
642 directory_info_has_arrived(time_t now, int from_cache)
644 or_options_t *options = get_options();
646 if (!router_have_minimum_dir_info()) {
647 int quiet = directory_too_idle_to_fetch_descriptors(options, now);
648 log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
649 "I learned some more directory information, but not enough to "
650 "build a circuit: %s", get_dir_info_status_string());
651 update_router_descriptor_downloads(now);
652 return;
653 } else {
654 /* if we have enough dir info, then update our guard status with
655 * whatever we just learned. */
656 entry_guards_compute_status();
657 /* Don't even bother trying to get extrainfo until the rest of our
658 * directory info is up-to-date */
659 if (options->DownloadExtraInfo)
660 update_extrainfo_downloads(now);
663 if (server_mode(options) && !we_are_hibernating() && !from_cache &&
664 (has_completed_circuit || !any_predicted_circuits(now)))
665 consider_testing_reachability(1, 1);
668 /** Perform regular maintenance tasks for a single connection. This
669 * function gets run once per second per connection by run_scheduled_events.
671 static void
672 run_connection_housekeeping(int i, time_t now)
674 cell_t cell;
675 connection_t *conn = smartlist_get(connection_array, i);
676 or_options_t *options = get_options();
677 or_connection_t *or_conn;
679 if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
680 TO_OR_CONN(conn)->timestamp_lastempty = now;
682 if (conn->marked_for_close) {
683 /* nothing to do here */
684 return;
687 /* Expire any directory connections that haven't been active (sent
688 * if a server or received if a client) for 5 min */
689 if (conn->type == CONN_TYPE_DIR &&
690 ((DIR_CONN_IS_SERVER(conn) &&
691 conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
692 (!DIR_CONN_IS_SERVER(conn) &&
693 conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
694 log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
695 conn->s, conn->purpose);
696 /* This check is temporary; it's to let us know whether we should consider
697 * parsing partial serverdesc responses. */
698 if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
699 buf_datalen(conn->inbuf)>=1024) {
700 log_info(LD_DIR,"Trying to extract information from wedged server desc "
701 "download.");
702 connection_dir_reached_eof(TO_DIR_CONN(conn));
703 } else {
704 connection_mark_for_close(conn);
706 return;
709 if (!connection_speaks_cells(conn))
710 return; /* we're all done here, the rest is just for OR conns */
712 or_conn = TO_OR_CONN(conn);
714 if (!conn->or_is_obsolete) {
715 if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_OBSOLETE < now) {
716 log_info(LD_OR,
717 "Marking OR conn to %s:%d obsolete (fd %d, %d secs old).",
718 conn->address, conn->port, conn->s,
719 (int)(now - conn->timestamp_created));
720 conn->or_is_obsolete = 1;
721 } else {
722 or_connection_t *best =
723 connection_or_get_by_identity_digest(or_conn->identity_digest);
724 if (best && best != or_conn &&
725 (conn->state == OR_CONN_STATE_OPEN ||
726 now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
727 /* We only mark as obsolete connections that already are in
728 * OR_CONN_STATE_OPEN, i.e. that have finished their TLS handshaking.
729 * This is necessary because authorities judge whether a router is
730 * reachable based on whether they were able to TLS handshake with it
731 * recently. Without this check we would expire connections too
732 * early for router->last_reachable to be updated.
734 log_info(LD_OR,
735 "Marking duplicate conn to %s:%d obsolete "
736 "(fd %d, %d secs old).",
737 conn->address, conn->port, conn->s,
738 (int)(now - conn->timestamp_created));
739 conn->or_is_obsolete = 1;
744 if (conn->or_is_obsolete && !or_conn->n_circuits) {
745 /* no unmarked circs -- mark it now */
746 log_info(LD_OR,
747 "Expiring non-used OR connection to fd %d (%s:%d) [Obsolete].",
748 conn->s, conn->address, conn->port);
749 if (conn->state == OR_CONN_STATE_CONNECTING)
750 connection_or_connect_failed(TO_OR_CONN(conn),
751 END_OR_CONN_REASON_TIMEOUT,
752 "Tor gave up on the connection");
753 connection_mark_for_close(conn);
754 conn->hold_open_until_flushed = 1;
755 return;
758 /* If we haven't written to an OR connection for a while, then either nuke
759 the connection or send a keepalive, depending. */
760 if (now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
761 routerinfo_t *router = router_get_by_digest(or_conn->identity_digest);
762 int maxCircuitlessPeriod = options->MaxCircuitDirtiness*3/2;
763 if (!connection_state_is_open(conn)) {
764 /* We never managed to actually get this connection open and happy. */
765 log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
766 conn->s,conn->address, conn->port);
767 connection_mark_for_close(conn);
768 conn->hold_open_until_flushed = 1;
769 } else if (we_are_hibernating() && !or_conn->n_circuits &&
770 !buf_datalen(conn->outbuf)) {
771 /* We're hibernating, there's no circuits, and nothing to flush.*/
772 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
773 "[Hibernating or exiting].",
774 conn->s,conn->address, conn->port);
775 connection_mark_for_close(conn);
776 conn->hold_open_until_flushed = 1;
777 } else if (!clique_mode(options) && !or_conn->n_circuits &&
778 now >= or_conn->timestamp_last_added_nonpadding +
779 maxCircuitlessPeriod &&
780 (!router || !server_mode(options) ||
781 !router_is_clique_mode(router))) {
782 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
783 "[Not in clique mode].",
784 conn->s,conn->address, conn->port);
785 connection_mark_for_close(conn);
786 conn->hold_open_until_flushed = 1;
787 } else if (
788 now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
789 now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
790 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
791 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
792 "flush; %d seconds since last write)",
793 conn->s, conn->address, conn->port,
794 (int)buf_datalen(conn->outbuf),
795 (int)(now-conn->timestamp_lastwritten));
796 connection_mark_for_close(conn);
797 } else if (!buf_datalen(conn->outbuf)) {
798 /* either in clique mode, or we've got a circuit. send a padding cell. */
799 log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
800 conn->address, conn->port);
801 memset(&cell,0,sizeof(cell_t));
802 cell.command = CELL_PADDING;
803 connection_or_write_cell_to_buf(&cell, or_conn);
808 /** Honor a NEWNYM request: make future requests unlinkability to past
809 * requests. */
810 static void
811 signewnym_impl(time_t now)
813 circuit_expire_all_dirty_circs();
814 addressmap_clear_transient();
815 time_of_last_signewnym = now;
816 signewnym_is_pending = 0;
819 /** Perform regular maintenance tasks. This function gets run once per
820 * second by prepare_for_poll.
822 static void
823 run_scheduled_events(time_t now)
825 static time_t time_to_fetch_directory = 0;
826 static time_t time_to_fetch_running_routers = 0;
827 static time_t last_rotated_x509_certificate = 0;
828 static time_t time_to_check_v3_certificate = 0;
829 static time_t time_to_check_listeners = 0;
830 static time_t time_to_check_descriptor = 0;
831 static time_t time_to_check_ipaddress = 0;
832 static time_t time_to_shrink_memory = 0;
833 static time_t time_to_try_getting_descriptors = 0;
834 static time_t time_to_reset_descriptor_failures = 0;
835 static time_t time_to_add_entropy = 0;
836 static time_t time_to_write_hs_statistics = 0;
837 static time_t time_to_write_bridge_status_file = 0;
838 static time_t time_to_downrate_stability = 0;
839 static time_t time_to_save_stability = 0;
840 static time_t time_to_clean_caches = 0;
841 static time_t time_to_recheck_bandwidth = 0;
842 static time_t time_to_check_for_expired_networkstatus = 0;
843 static time_t time_to_dump_geoip_stats = 0;
844 or_options_t *options = get_options();
845 int i;
846 int have_dir_info;
848 /** 0. See if we've been asked to shut down and our timeout has
849 * expired; or if our bandwidth limits are exhausted and we
850 * should hibernate; or if it's time to wake up from hibernation.
852 consider_hibernation(now);
854 /* 0b. If we've deferred a signewnym, make sure it gets handled
855 * eventually. */
856 if (signewnym_is_pending &&
857 time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
858 log(LOG_INFO, LD_CONTROL, "Honoring delayed NEWNYM request");
859 signewnym_impl(now);
862 /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
863 * shut down and restart all cpuworkers, and update the directory if
864 * necessary.
866 if (server_mode(options) &&
867 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
868 log_info(LD_GENERAL,"Rotating onion key.");
869 rotate_onion_key();
870 cpuworkers_rotate();
871 if (router_rebuild_descriptor(1)<0) {
872 log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
874 if (advertised_server_mode())
875 router_upload_dir_desc_to_dirservers(0);
878 if (time_to_try_getting_descriptors < now) {
879 update_router_descriptor_downloads(now);
880 update_extrainfo_downloads(now);
881 if (options->UseBridges)
882 fetch_bridge_descriptors(now);
883 if (router_have_minimum_dir_info())
884 time_to_try_getting_descriptors = now + LAZY_DESCRIPTOR_RETRY_INTERVAL;
885 else
886 time_to_try_getting_descriptors = now + GREEDY_DESCRIPTOR_RETRY_INTERVAL;
889 if (time_to_reset_descriptor_failures < now) {
890 router_reset_descriptor_download_failures();
891 time_to_reset_descriptor_failures =
892 now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
895 /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
896 if (!last_rotated_x509_certificate)
897 last_rotated_x509_certificate = now;
898 if (last_rotated_x509_certificate+MAX_SSL_KEY_LIFETIME < now) {
899 log_info(LD_GENERAL,"Rotating tls context.");
900 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
901 log_warn(LD_BUG, "Error reinitializing TLS context");
902 /* XXX is it a bug here, that we just keep going? -RD */
904 last_rotated_x509_certificate = now;
905 /* We also make sure to rotate the TLS connections themselves if they've
906 * been up for too long -- but that's done via or_is_obsolete in
907 * connection_run_housekeeping() above. */
910 if (time_to_add_entropy < now) {
911 if (time_to_add_entropy) {
912 /* We already seeded once, so don't die on failure. */
913 crypto_seed_rng(0);
915 /** How often do we add more entropy to OpenSSL's RNG pool? */
916 #define ENTROPY_INTERVAL (60*60)
917 time_to_add_entropy = now + ENTROPY_INTERVAL;
920 /** 1c. If we have to change the accounting interval or record
921 * bandwidth used in this accounting interval, do so. */
922 if (accounting_is_enabled(options))
923 accounting_run_housekeeping(now);
925 if (now % 10 == 0 && (authdir_mode_tests_reachability(options)) &&
926 !we_are_hibernating()) {
927 /* try to determine reachability of the other Tor relays */
928 dirserv_test_reachability(now, 0);
931 /** 1d. Periodically, we discount older stability information so that new
932 * stability info counts more, and save the stability information to disk as
933 * appropriate. */
934 if (time_to_downrate_stability < now)
935 time_to_downrate_stability = rep_hist_downrate_old_runs(now);
936 if (authdir_mode_tests_reachability(options)) {
937 if (time_to_save_stability < now) {
938 if (time_to_save_stability && rep_hist_record_mtbf_data()<0) {
939 log_warn(LD_GENERAL, "Couldn't store mtbf data.");
941 #define SAVE_STABILITY_INTERVAL (30*60)
942 time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
946 /* 1e. Periodicaly, if we're a v3 authority, we check whether our cert is
947 * close to expiring and warn the admin if it is. */
948 if (time_to_check_v3_certificate < now) {
949 v3_authority_check_key_expiry();
950 #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
951 time_to_check_v3_certificate = now + CHECK_V3_CERTIFICATE_INTERVAL;
954 /* 1f. Check whether our networkstatus has expired.
956 if (time_to_check_for_expired_networkstatus < now) {
957 networkstatus_t *ns = networkstatus_get_latest_consensus();
958 /*XXXX020 this value needs to be the same as REASONABLY_LIVE_TIME in
959 * networkstatus_get_reasonably_live_consensus(), but that value is way
960 * way too high. Arma: is the bridge issue there resolved yet? -NM */
961 #define NS_EXPIRY_SLOP (24*60*60)
962 if (ns && ns->valid_until < now+NS_EXPIRY_SLOP &&
963 router_have_minimum_dir_info()) {
964 router_dir_info_changed();
966 #define CHECK_EXPIRED_NS_INTERVAL (2*60)
967 time_to_check_for_expired_networkstatus = now + CHECK_EXPIRED_NS_INTERVAL;
970 if (time_to_dump_geoip_stats < now) {
971 #define DUMP_GEOIP_STATS_INTERVAL (60*60);
972 if (time_to_dump_geoip_stats)
973 dump_geoip_stats();
974 time_to_dump_geoip_stats = now + DUMP_GEOIP_STATS_INTERVAL;
977 /** 2. Periodically, we consider getting a new directory, getting a
978 * new running-routers list, and/or force-uploading our descriptor
979 * (if we've passed our internal checks). */
980 if (time_to_fetch_directory < now) {
981 /* Only caches actually need to fetch v1 directories now. */
982 if (directory_fetches_dir_info_early(options) &&
983 !authdir_mode_v1(options) && any_trusted_dir_is_v1_authority() &&
984 !should_delay_dir_fetches(options))
985 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR,
986 ROUTER_PURPOSE_GENERAL, NULL, 1);
987 /** How often do we (as a cache) fetch a new V1 directory? */
988 #define V1_DIR_FETCH_PERIOD (12*60*60)
989 time_to_fetch_directory = now + V1_DIR_FETCH_PERIOD;
992 /* Caches need to fetch running_routers; directory clients don't. */
993 if (time_to_fetch_running_routers < now) {
994 if (directory_fetches_dir_info_early(options) &&
995 !authdir_mode_v1(options) && any_trusted_dir_is_v1_authority() &&
996 !should_delay_dir_fetches(options))
997 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST,
998 ROUTER_PURPOSE_GENERAL, NULL, 1);
999 /** How often do we (as a cache) fetch a new V1 runningrouters document? */
1000 #define V1_RUNNINGROUTERS_FETCH_PERIOD (12*60*60)
1001 time_to_fetch_running_routers = now + V1_RUNNINGROUTERS_FETCH_PERIOD;
1004 /* Remove old information from rephist and the rend cache. */
1005 if (time_to_clean_caches < now) {
1006 rep_history_clean(now - options->RephistTrackTime);
1007 rend_cache_clean();
1008 rend_cache_clean_v2_descs_as_dir();
1009 #define CLEAN_CACHES_INTERVAL (30*60)
1010 time_to_clean_caches = now + CLEAN_CACHES_INTERVAL;
1013 /** How often do we check whether part of our router info has changed in a way
1014 * that would require an upload? */
1015 #define CHECK_DESCRIPTOR_INTERVAL (60)
1016 /** How often do we (as a router) check whether our IP address has changed? */
1017 #define CHECK_IPADDRESS_INTERVAL (15*60)
1019 /* 2b. Once per minute, regenerate and upload the descriptor if the old
1020 * one is inaccurate. */
1021 if (time_to_check_descriptor < now) {
1022 static int dirport_reachability_count = 0;
1023 time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
1024 check_descriptor_bandwidth_changed(now);
1025 if (time_to_check_ipaddress < now) {
1026 time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
1027 check_descriptor_ipaddress_changed(now);
1029 /** If our router descriptor ever goes this long without being regenerated
1030 * because something changed, we force an immediate regenerate-and-upload. */
1031 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
1032 mark_my_descriptor_dirty_if_older_than(
1033 now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
1034 consider_publishable_server(0);
1035 /* also, check religiously for reachability, if it's within the first
1036 * 20 minutes of our uptime. */
1037 if (server_mode(options) &&
1038 (has_completed_circuit || !any_predicted_circuits(now)) &&
1039 !we_are_hibernating()) {
1040 if (stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1041 consider_testing_reachability(1, dirport_reachability_count==0);
1042 if (++dirport_reachability_count > 5)
1043 dirport_reachability_count = 0;
1044 } else if (time_to_recheck_bandwidth < now) {
1045 /* If we haven't checked for 12 hours and our bandwidth estimate is
1046 * low, do another bandwidth test. This is especially important for
1047 * bridges, since they might go long periods without much use. */
1048 routerinfo_t *me = router_get_my_routerinfo();
1049 if (time_to_recheck_bandwidth && me &&
1050 me->bandwidthcapacity < me->bandwidthrate &&
1051 me->bandwidthcapacity < 51200) {
1052 reset_bandwidth_test();
1054 #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
1055 time_to_recheck_bandwidth = now + BANDWIDTH_RECHECK_INTERVAL;
1059 /* If any networkstatus documents are no longer recent, we need to
1060 * update all the descriptors' running status. */
1061 /* purge obsolete entries */
1062 networkstatus_v2_list_clean(now);
1063 /* Remove dead routers. */
1064 routerlist_remove_old_routers();
1066 /* Also, once per minute, check whether we want to download any
1067 * networkstatus documents.
1069 update_networkstatus_downloads(now);
1072 /** 2c. Let directory voting happen. */
1073 if (authdir_mode_v3(options))
1074 dirvote_act(options, now);
1076 /** 3a. Every second, we examine pending circuits and prune the
1077 * ones which have been pending for more than a few seconds.
1078 * We do this before step 4, so it can try building more if
1079 * it's not comfortable with the number of available circuits.
1081 circuit_expire_building(now);
1083 /** 3b. Also look at pending streams and prune the ones that 'began'
1084 * a long time ago but haven't gotten a 'connected' yet.
1085 * Do this before step 4, so we can put them back into pending
1086 * state to be picked up by the new circuit.
1088 connection_ap_expire_beginning();
1090 /** 3c. And expire connections that we've held open for too long.
1092 connection_expire_held_open();
1094 /** 3d. And every 60 seconds, we relaunch listeners if any died. */
1095 if (!we_are_hibernating() && time_to_check_listeners < now) {
1096 retry_all_listeners(NULL, NULL);
1097 time_to_check_listeners = now+60;
1100 /** 4. Every second, we try a new circuit if there are no valid
1101 * circuits. Every NewCircuitPeriod seconds, we expire circuits
1102 * that became dirty more than MaxCircuitDirtiness seconds ago,
1103 * and we make a new circ if there are no clean circuits.
1105 have_dir_info = router_have_minimum_dir_info();
1106 if (have_dir_info && !we_are_hibernating())
1107 circuit_build_needed_circs(now);
1109 /** 5. We do housekeeping for each connection... */
1110 for (i=0;i<smartlist_len(connection_array);i++) {
1111 run_connection_housekeeping(i, now);
1113 if (time_to_shrink_memory < now) {
1114 SMARTLIST_FOREACH(connection_array, connection_t *, conn, {
1115 if (conn->outbuf)
1116 buf_shrink(conn->outbuf);
1117 if (conn->inbuf)
1118 buf_shrink(conn->inbuf);
1120 clean_cell_pool();
1121 buf_shrink_freelists(0);
1122 /** How often do we check buffers and pools for empty space that can be
1123 * deallocated? */
1124 #define MEM_SHRINK_INTERVAL (60)
1125 time_to_shrink_memory = now + MEM_SHRINK_INTERVAL;
1128 /** 6. And remove any marked circuits... */
1129 circuit_close_all_marked();
1131 /** 7. And upload service descriptors if necessary. */
1132 if (has_completed_circuit && !we_are_hibernating()) {
1133 rend_consider_services_upload(now);
1134 rend_consider_descriptor_republication();
1137 /** 8. and blow away any connections that need to die. have to do this now,
1138 * because if we marked a conn for close and left its socket -1, then
1139 * we'll pass it to poll/select and bad things will happen.
1141 close_closeable_connections();
1143 /** 8b. And if anything in our state is ready to get flushed to disk, we
1144 * flush it. */
1145 or_state_save(now);
1147 /** 9. and if we're a server, check whether our DNS is telling stories to
1148 * us. */
1149 if (server_mode(options) && time_to_check_for_correct_dns < now) {
1150 if (!time_to_check_for_correct_dns) {
1151 time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
1152 } else {
1153 dns_launch_correctness_checks();
1154 time_to_check_for_correct_dns = now + 12*3600 +
1155 crypto_rand_int(12*3600);
1159 /** 10. write hidden service usage statistic to disk */
1160 if (options->HSAuthorityRecordStats && time_to_write_hs_statistics < now) {
1161 hs_usage_write_statistics_to_file(now);
1162 #define WRITE_HSUSAGE_INTERVAL (30*60)
1163 time_to_write_hs_statistics = now+WRITE_HSUSAGE_INTERVAL;
1165 /** 10b. write bridge networkstatus file to disk */
1166 if (options->BridgeAuthoritativeDir &&
1167 time_to_write_bridge_status_file < now) {
1168 networkstatus_dump_bridge_status_to_file(now);
1169 #define BRIDGE_STATUSFILE_INTERVAL (30*60)
1170 time_to_write_bridge_status_file = now+BRIDGE_STATUSFILE_INTERVAL;
1174 /** Libevent timer: used to invoke second_elapsed_callback() once per
1175 * second. */
1176 static struct event *timeout_event = NULL;
1177 /** Number of libevent errors in the last second: we die if we get too many. */
1178 static int n_libevent_errors = 0;
1180 /** Libevent callback: invoked once every second. */
1181 static void
1182 second_elapsed_callback(int fd, short event, void *args)
1184 /* XXXX This could be sensibly refactored into multiple callbacks, and we
1185 * could use libevent's timers for this rather than checking the current
1186 * time against a bunch of timeouts every second. */
1187 static struct timeval one_second;
1188 static long current_second = 0;
1189 struct timeval now;
1190 size_t bytes_written;
1191 size_t bytes_read;
1192 int seconds_elapsed;
1193 or_options_t *options = get_options();
1194 (void)fd;
1195 (void)event;
1196 (void)args;
1197 if (!timeout_event) {
1198 timeout_event = tor_malloc_zero(sizeof(struct event));
1199 evtimer_set(timeout_event, second_elapsed_callback, NULL);
1200 one_second.tv_sec = 1;
1201 one_second.tv_usec = 0;
1204 n_libevent_errors = 0;
1206 /* log_fn(LOG_NOTICE, "Tick."); */
1207 tor_gettimeofday(&now);
1209 /* the second has rolled over. check more stuff. */
1210 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
1211 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
1212 seconds_elapsed = current_second ? (int)(now.tv_sec - current_second) : 0;
1213 stats_n_bytes_read += bytes_read;
1214 stats_n_bytes_written += bytes_written;
1215 if (accounting_is_enabled(options) && seconds_elapsed >= 0)
1216 accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
1217 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
1218 control_event_stream_bandwidth_used();
1220 if (seconds_elapsed > 0)
1221 connection_bucket_refill(seconds_elapsed, now.tv_sec);
1222 stats_prev_global_read_bucket = global_read_bucket;
1223 stats_prev_global_write_bucket = global_write_bucket;
1225 if (server_mode(options) &&
1226 !we_are_hibernating() &&
1227 seconds_elapsed > 0 &&
1228 has_completed_circuit &&
1229 stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
1230 (stats_n_seconds_working+seconds_elapsed) /
1231 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1232 /* every 20 minutes, check and complain if necessary */
1233 routerinfo_t *me = router_get_my_routerinfo();
1234 if (me && !check_whether_orport_reachable())
1235 log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
1236 "its ORPort is reachable. Please check your firewalls, ports, "
1237 "address, /etc/hosts file, etc.",
1238 me->address, me->or_port);
1239 if (me && !check_whether_dirport_reachable())
1240 log_warn(LD_CONFIG,
1241 "Your server (%s:%d) has not managed to confirm that its "
1242 "DirPort is reachable. Please check your firewalls, ports, "
1243 "address, /etc/hosts file, etc.",
1244 me->address, me->dir_port);
1247 /** If more than this many seconds have elapsed, probably the clock
1248 * jumped: doesn't count. */
1249 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
1250 if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
1251 seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
1252 circuit_note_clock_jumped(seconds_elapsed);
1253 /* XXX if the time jumps *back* many months, do our events in
1254 * run_scheduled_events() recover? I don't think they do. -RD */
1255 } else if (seconds_elapsed > 0)
1256 stats_n_seconds_working += seconds_elapsed;
1258 run_scheduled_events(now.tv_sec);
1260 current_second = now.tv_sec; /* remember which second it is, for next time */
1262 #if 0
1263 if (current_second % 300 == 0) {
1264 rep_history_clean(current_second - options->RephistTrackTime);
1265 dumpmemusage(get_min_log_level()<LOG_INFO ?
1266 get_min_log_level() : LOG_INFO);
1268 #endif
1270 if (evtimer_add(timeout_event, &one_second))
1271 log_err(LD_NET,
1272 "Error from libevent when setting one-second timeout event");
1275 #ifndef MS_WINDOWS
1276 /** Called when a possibly ignorable libevent error occurs; ensures that we
1277 * don't get into an infinite loop by ignoring too many errors from
1278 * libevent. */
1279 static int
1280 got_libevent_error(void)
1282 if (++n_libevent_errors > 8) {
1283 log_err(LD_NET, "Too many libevent errors in one second; dying");
1284 return -1;
1286 return 0;
1288 #endif
1290 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
1292 /** Called when our IP address seems to have changed. <b>at_interface</b>
1293 * should be true if we detected a change in our interface, and false if we
1294 * detected a change in our published address. */
1295 void
1296 ip_address_changed(int at_interface)
1298 int server = server_mode(get_options());
1300 if (at_interface) {
1301 if (! server) {
1302 /* Okay, change our keys. */
1303 init_keys();
1305 } else {
1306 if (server) {
1307 if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
1308 reset_bandwidth_test();
1309 stats_n_seconds_working = 0;
1310 router_reset_reachability();
1311 mark_my_descriptor_dirty();
1315 dns_servers_relaunch_checks();
1318 /** Forget what we've learned about the correctness of our DNS servers, and
1319 * start learning again. */
1320 void
1321 dns_servers_relaunch_checks(void)
1323 if (server_mode(get_options())) {
1324 dns_reset_correctness_checks();
1325 time_to_check_for_correct_dns = 0;
1329 /** Called when we get a SIGHUP: reload configuration files and keys,
1330 * retry all connections, and so on. */
1331 static int
1332 do_hup(void)
1334 or_options_t *options = get_options();
1336 #ifdef USE_DMALLOC
1337 dmalloc_log_stats();
1338 dmalloc_log_changed(0, 1, 0, 0);
1339 #endif
1341 log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config.");
1342 if (accounting_is_enabled(options))
1343 accounting_record_bandwidth_usage(time(NULL), get_or_state());
1345 router_reset_warnings();
1346 routerlist_reset_warnings();
1347 addressmap_clear_transient();
1348 /* first, reload config variables, in case they've changed */
1349 /* no need to provide argc/v, they've been cached inside init_from_config */
1350 if (options_init_from_torrc(0, NULL) < 0) {
1351 log_err(LD_CONFIG,"Reading config failed--see warnings above. "
1352 "For usage, try -h.");
1353 return -1;
1355 options = get_options(); /* they have changed now */
1356 if (authdir_mode_handles_descs(options, -1)) {
1357 /* reload the approved-routers file */
1358 if (dirserv_load_fingerprint_file() < 0) {
1359 /* warnings are logged from dirserv_load_fingerprint_file() directly */
1360 log_info(LD_GENERAL, "Error reloading fingerprints. "
1361 "Continuing with old list.");
1365 /* Rotate away from the old dirty circuits. This has to be done
1366 * after we've read the new options, but before we start using
1367 * circuits for directory fetches. */
1368 circuit_expire_all_dirty_circs();
1370 /* retry appropriate downloads */
1371 router_reset_status_download_failures();
1372 router_reset_descriptor_download_failures();
1373 update_networkstatus_downloads(time(NULL));
1375 /* We'll retry routerstatus downloads in about 10 seconds; no need to
1376 * force a retry there. */
1378 if (server_mode(options)) {
1379 /* Restart cpuworker and dnsworker processes, so they get up-to-date
1380 * configuration options. */
1381 cpuworkers_rotate();
1382 dns_reset();
1384 return 0;
1387 /** Tor main loop. */
1388 /* static */ int
1389 do_main_loop(void)
1391 int loop_result;
1392 time_t now;
1394 /* initialize dns resolve map, spawn workers if needed */
1395 if (dns_init() < 0) {
1396 log_err(LD_GENERAL,"Error initializing dns subsystem; exiting");
1397 return -1;
1400 handle_signals(1);
1402 /* load the private keys, if we're supposed to have them, and set up the
1403 * TLS context. */
1404 if (! identity_key_is_set()) {
1405 if (init_keys() < 0) {
1406 log_err(LD_BUG,"Error initializing keys; exiting");
1407 return -1;
1411 /* Set up the packed_cell_t memory pool. */
1412 init_cell_pool();
1414 /* Set up our buckets */
1415 connection_bucket_init();
1416 stats_prev_global_read_bucket = global_read_bucket;
1417 stats_prev_global_write_bucket = global_write_bucket;
1419 /* initialize the bootstrap status events to know we're starting up */
1420 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
1422 if (trusted_dirs_reload_certs())
1423 return -1;
1424 if (router_reload_v2_networkstatus()) {
1425 return -1;
1427 if (router_reload_consensus_networkstatus()) {
1428 return -1;
1430 /* load the routers file, or assign the defaults. */
1431 if (router_reload_router_list()) {
1432 return -1;
1434 /* load the networkstatuses. (This launches a download for new routers as
1435 * appropriate.)
1437 now = time(NULL);
1438 directory_info_has_arrived(now, 1);
1440 if (authdir_mode_tests_reachability(get_options())) {
1441 /* the directory is already here, run startup things */
1442 dirserv_test_reachability(now, 1);
1445 if (server_mode(get_options())) {
1446 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1447 cpu_init();
1450 /* set up once-a-second callback. */
1451 second_elapsed_callback(0,0,NULL);
1453 for (;;) {
1454 if (nt_service_is_stopping())
1455 return 0;
1457 #ifndef MS_WINDOWS
1458 /* Make it easier to tell whether libevent failure is our fault or not. */
1459 errno = 0;
1460 #endif
1461 /* All active linked conns should get their read events activated. */
1462 SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
1463 event_active(conn->read_event, EV_READ, 1));
1464 called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
1466 /* poll until we have an event, or the second ends, or until we have
1467 * some active linked connections to trigger events for. */
1468 loop_result = event_loop(called_loop_once ? EVLOOP_ONCE : 0);
1470 /* let catch() handle things like ^c, and otherwise don't worry about it */
1471 if (loop_result < 0) {
1472 int e = tor_socket_errno(-1);
1473 /* let the program survive things like ^z */
1474 if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
1475 #ifdef HAVE_EVENT_GET_METHOD
1476 log_err(LD_NET,"libevent call with %s failed: %s [%d]",
1477 event_get_method(), tor_socket_strerror(e), e);
1478 #else
1479 log_err(LD_NET,"libevent call failed: %s [%d]",
1480 tor_socket_strerror(e), e);
1481 #endif
1482 return -1;
1483 #ifndef MS_WINDOWS
1484 } else if (e == EINVAL) {
1485 log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
1486 if (got_libevent_error())
1487 return -1;
1488 #endif
1489 } else {
1490 if (ERRNO_IS_EINPROGRESS(e))
1491 log_warn(LD_BUG,
1492 "libevent call returned EINPROGRESS? Please report.");
1493 log_debug(LD_NET,"libevent call interrupted.");
1494 /* You can't trust the results of this poll(). Go back to the
1495 * top of the big for loop. */
1496 continue;
1502 /** Used to implement the SIGNAL control command: if we accept
1503 * <b>the_signal</b> as a remote pseudo-signal, act on it. */
1504 /* We don't re-use catch() here because:
1505 * 1. We handle a different set of signals than those allowed in catch.
1506 * 2. Platforms without signal() are unlikely to define SIGfoo.
1507 * 3. The control spec is defined to use fixed numeric signal values
1508 * which just happen to match the unix values.
1510 void
1511 control_signal_act(int the_signal)
1513 switch (the_signal)
1515 case 1:
1516 signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
1517 break;
1518 case 2:
1519 signal_callback(0,0,(void*)(uintptr_t)SIGINT);
1520 break;
1521 case 10:
1522 signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
1523 break;
1524 case 12:
1525 signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
1526 break;
1527 case 15:
1528 signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
1529 break;
1530 case SIGNEWNYM:
1531 signal_callback(0,0,(void*)(uintptr_t)SIGNEWNYM);
1532 break;
1533 case SIGCLEARDNSCACHE:
1534 signal_callback(0,0,(void*)(uintptr_t)SIGCLEARDNSCACHE);
1535 break;
1536 default:
1537 log_warn(LD_BUG, "Unrecognized signal number %d.", the_signal);
1538 break;
1542 /** Libevent callback: invoked when we get a signal.
1544 static void
1545 signal_callback(int fd, short events, void *arg)
1547 uintptr_t sig = (uintptr_t)arg;
1548 (void)fd;
1549 (void)events;
1550 switch (sig)
1552 case SIGTERM:
1553 log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
1554 tor_cleanup();
1555 exit(0);
1556 break;
1557 case SIGINT:
1558 if (!server_mode(get_options())) { /* do it now */
1559 log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
1560 tor_cleanup();
1561 exit(0);
1563 hibernate_begin_shutdown();
1564 break;
1565 #ifdef SIGPIPE
1566 case SIGPIPE:
1567 log_debug(LD_GENERAL,"Caught sigpipe. Ignoring.");
1568 break;
1569 #endif
1570 case SIGUSR1:
1571 /* prefer to log it at INFO, but make sure we always see it */
1572 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
1573 break;
1574 case SIGUSR2:
1575 switch_logs_debug();
1576 log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
1577 "Send HUP to change back.");
1578 break;
1579 case SIGHUP:
1580 if (do_hup() < 0) {
1581 log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
1582 tor_cleanup();
1583 exit(1);
1585 break;
1586 #ifdef SIGCHLD
1587 case SIGCHLD:
1588 while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more
1589 zombies */
1590 break;
1591 #endif
1592 case SIGNEWNYM: {
1593 time_t now = time(NULL);
1594 if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
1595 signewnym_is_pending = 1;
1596 log(LOG_NOTICE, LD_CONTROL,
1597 "Rate limiting NEWNYM request: delaying by %d second(s)",
1598 (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
1599 } else {
1600 signewnym_impl(now);
1602 break;
1604 case SIGCLEARDNSCACHE:
1605 addressmap_clear_transient();
1606 break;
1610 extern uint64_t rephist_total_alloc;
1611 extern uint32_t rephist_total_num;
1614 * Write current memory usage information to the log.
1616 static void
1617 dumpmemusage(int severity)
1619 connection_dump_buffer_mem_stats(severity);
1620 log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
1621 U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
1622 dump_routerlist_mem_usage(severity);
1623 dump_cell_pool_usage(severity);
1624 buf_dump_freelist_sizes(severity);
1625 tor_log_mallinfo(severity);
1628 /** Write all statistics to the log, with log level 'severity'. Called
1629 * in response to a SIGUSR1. */
1630 static void
1631 dumpstats(int severity)
1633 time_t now = time(NULL);
1634 time_t elapsed;
1635 int rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
1637 log(severity, LD_GENERAL, "Dumping stats:");
1639 SMARTLIST_FOREACH(connection_array, connection_t *, conn,
1641 int i = conn_sl_idx;
1642 log(severity, LD_GENERAL,
1643 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
1644 i, conn->s, conn->type, conn_type_to_string(conn->type),
1645 conn->state, conn_state_to_string(conn->type, conn->state),
1646 (int)(now - conn->timestamp_created));
1647 if (!connection_is_listener(conn)) {
1648 log(severity,LD_GENERAL,
1649 "Conn %d is to %s:%d.", i,
1650 safe_str(conn->address), conn->port);
1651 log(severity,LD_GENERAL,
1652 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
1654 (int)buf_datalen(conn->inbuf),
1655 (int)buf_allocation(conn->inbuf),
1656 (int)(now - conn->timestamp_lastread));
1657 log(severity,LD_GENERAL,
1658 "Conn %d: %d bytes waiting on outbuf "
1659 "(len %d, last written %d secs ago)",i,
1660 (int)buf_datalen(conn->outbuf),
1661 (int)buf_allocation(conn->outbuf),
1662 (int)(now - conn->timestamp_lastwritten));
1663 if (conn->type == CONN_TYPE_OR) {
1664 or_connection_t *or_conn = TO_OR_CONN(conn);
1665 if (or_conn->tls) {
1666 tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
1667 &wbuf_cap, &wbuf_len);
1668 log(severity, LD_GENERAL,
1669 "Conn %d: %d/%d bytes used on openssl read buffer; "
1670 "%d/%d bytes used on write buffer.",
1671 i, rbuf_len, rbuf_cap, wbuf_len, wbuf_cap);
1675 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
1676 * using this conn */
1678 log(severity, LD_NET,
1679 "Cells processed: "U64_FORMAT" padding\n"
1680 " "U64_FORMAT" create\n"
1681 " "U64_FORMAT" created\n"
1682 " "U64_FORMAT" relay\n"
1683 " ("U64_FORMAT" relayed)\n"
1684 " ("U64_FORMAT" delivered)\n"
1685 " "U64_FORMAT" destroy",
1686 U64_PRINTF_ARG(stats_n_padding_cells_processed),
1687 U64_PRINTF_ARG(stats_n_create_cells_processed),
1688 U64_PRINTF_ARG(stats_n_created_cells_processed),
1689 U64_PRINTF_ARG(stats_n_relay_cells_processed),
1690 U64_PRINTF_ARG(stats_n_relay_cells_relayed),
1691 U64_PRINTF_ARG(stats_n_relay_cells_delivered),
1692 U64_PRINTF_ARG(stats_n_destroy_cells_processed));
1693 if (stats_n_data_cells_packaged)
1694 log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
1695 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
1696 U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
1697 if (stats_n_data_cells_received)
1698 log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
1699 100*(U64_TO_DBL(stats_n_data_bytes_received) /
1700 U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
1702 if (now - time_of_process_start >= 0)
1703 elapsed = now - time_of_process_start;
1704 else
1705 elapsed = 0;
1707 if (elapsed) {
1708 log(severity, LD_NET,
1709 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
1710 U64_PRINTF_ARG(stats_n_bytes_read),
1711 (int)elapsed,
1712 (int) (stats_n_bytes_read/elapsed));
1713 log(severity, LD_NET,
1714 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
1715 U64_PRINTF_ARG(stats_n_bytes_written),
1716 (int)elapsed,
1717 (int) (stats_n_bytes_written/elapsed));
1720 log(severity, LD_NET, "--------------- Dumping memory information:");
1721 dumpmemusage(severity);
1723 rep_hist_dump_stats(now,severity);
1724 rend_service_dump_stats(severity);
1725 dump_pk_ops(severity);
1726 dump_distinct_digest_count(severity);
1729 /** Called by exit() as we shut down the process.
1731 static void
1732 exit_function(void)
1734 /* NOTE: If we ever daemonize, this gets called immediately. That's
1735 * okay for now, because we only use this on Windows. */
1736 #ifdef MS_WINDOWS
1737 WSACleanup();
1738 #endif
1741 /** Set up the signal handlers for either parent or child. */
1742 void
1743 handle_signals(int is_parent)
1745 #ifndef MS_WINDOWS /* do signal stuff only on unix */
1746 int i;
1747 static int signals[] = {
1748 SIGINT, /* do a controlled slow shutdown */
1749 SIGTERM, /* to terminate now */
1750 SIGPIPE, /* otherwise sigpipe kills us */
1751 SIGUSR1, /* dump stats */
1752 SIGUSR2, /* go to loglevel debug */
1753 SIGHUP, /* to reload config, retry conns, etc */
1754 #ifdef SIGXFSZ
1755 SIGXFSZ, /* handle file-too-big resource exhaustion */
1756 #endif
1757 SIGCHLD, /* handle dns/cpu workers that exit */
1758 -1 };
1759 static struct event signal_events[16]; /* bigger than it has to be. */
1760 if (is_parent) {
1761 for (i = 0; signals[i] >= 0; ++i) {
1762 signal_set(&signal_events[i], signals[i], signal_callback,
1763 (void*)(uintptr_t)signals[i]);
1764 if (signal_add(&signal_events[i], NULL))
1765 log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
1766 signals[i]);
1768 } else {
1769 struct sigaction action;
1770 action.sa_flags = 0;
1771 sigemptyset(&action.sa_mask);
1772 action.sa_handler = SIG_IGN;
1773 sigaction(SIGINT, &action, NULL);
1774 sigaction(SIGTERM, &action, NULL);
1775 sigaction(SIGPIPE, &action, NULL);
1776 sigaction(SIGUSR1, &action, NULL);
1777 sigaction(SIGUSR2, &action, NULL);
1778 sigaction(SIGHUP, &action, NULL);
1779 #ifdef SIGXFSZ
1780 sigaction(SIGXFSZ, &action, NULL);
1781 #endif
1783 #else /* MS windows */
1784 (void)is_parent;
1785 #endif /* signal stuff */
1788 /** Main entry point for the Tor command-line client.
1790 /* static */ int
1791 tor_init(int argc, char *argv[])
1793 char buf[256];
1794 int i, quiet = 0;
1795 time_of_process_start = time(NULL);
1796 if (!connection_array)
1797 connection_array = smartlist_create();
1798 if (!closeable_connection_lst)
1799 closeable_connection_lst = smartlist_create();
1800 if (!active_linked_connection_lst)
1801 active_linked_connection_lst = smartlist_create();
1802 /* Have the log set up with our application name. */
1803 tor_snprintf(buf, sizeof(buf), "Tor %s", get_version());
1804 log_set_application_name(buf);
1805 /* Initialize the history structures. */
1806 rep_hist_init();
1807 /* Initialize the service cache. */
1808 rend_cache_init();
1809 addressmap_init(); /* Init the client dns cache. Do it always, since it's
1810 * cheap. */
1812 /* We search for the "quiet" option first, since it decides whether we
1813 * will log anything at all to the command line. */
1814 for (i=1;i<argc;++i) {
1815 if (!strcmp(argv[i], "--hush"))
1816 quiet = 1;
1817 if (!strcmp(argv[i], "--quiet"))
1818 quiet = 2;
1820 /* give it somewhere to log to initially */
1821 switch (quiet) {
1822 case 2:
1823 /* no initial logging */
1824 break;
1825 case 1:
1826 add_temp_log(LOG_WARN);
1827 break;
1828 default:
1829 add_temp_log(LOG_NOTICE);
1832 log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. "
1833 "Do not rely on it for strong anonymity. (Running on %s)",get_version(),
1834 get_uname());
1836 if (network_init()<0) {
1837 log_err(LD_BUG,"Error initializing network; exiting.");
1838 return -1;
1840 atexit(exit_function);
1842 if (options_init_from_torrc(argc,argv) < 0) {
1843 log_err(LD_CONFIG,"Reading config failed--see warnings above.");
1844 return -1;
1847 #ifndef MS_WINDOWS
1848 if (geteuid()==0)
1849 log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
1850 "and you probably shouldn't.");
1851 #endif
1853 crypto_global_init(get_options()->HardwareAccel);
1854 if (crypto_seed_rng(1)) {
1855 log_err(LD_BUG, "Unable to seed random number generator. Exiting.");
1856 return -1;
1859 return 0;
1862 static tor_lockfile_t *lockfile = NULL;
1865 try_locking(or_options_t *options, int err_if_locked)
1867 if (lockfile)
1868 return 0;
1869 else {
1870 char *fname = options_get_datadir_fname2_suffix(options, "lock",NULL,NULL);
1871 int already_locked = 0;
1872 tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
1873 tor_free(fname);
1874 if (!lf) {
1875 if (err_if_locked && already_locked) {
1876 int r;
1877 log_warn(LD_GENERAL, "It looks like another Tor process is running "
1878 "with the same data directory. Waiting 5 seconds to see "
1879 "if it goes away.");
1880 #ifndef WIN32
1881 sleep(5);
1882 #else
1883 Sleep(5000);
1884 #endif
1885 r = try_locking(options, 0);
1886 if (r<0) {
1887 log_err(LD_GENERAL, "No, it's still there. Exiting.");
1888 exit(0);
1890 return r;
1892 return -1;
1894 lockfile = lf;
1895 return 0;
1900 have_lockfile(void)
1902 return lockfile != NULL;
1905 void
1906 release_lockfile(void)
1908 if (lockfile) {
1909 tor_lockfile_unlock(lockfile);
1910 lockfile = NULL;
1914 /** Free all memory that we might have allocated somewhere.
1915 * If <b>postfork</b>, we are a worker process and we want to free
1916 * only the parts of memory that we won't touch. If !<b>postfork</b>,
1917 * Tor is shutting down and we should free everything.
1919 * Helps us find the real leaks with dmalloc and the like. Also valgrind
1920 * should then report 0 reachable in its leak report (in an ideal world --
1921 * in practice libevent, ssl, libc etc never quite free everything). */
1922 void
1923 tor_free_all(int postfork)
1925 if (!postfork) {
1926 evdns_shutdown(1);
1928 geoip_free_all();
1929 dirvote_free_all();
1930 routerlist_free_all();
1931 networkstatus_free_all();
1932 addressmap_free_all();
1933 set_exit_redirects(NULL); /* free the registered exit redirects */
1934 dirserv_free_all();
1935 rend_service_free_all();
1936 rend_cache_free_all();
1937 rend_service_authorization_free_all();
1938 rep_hist_free_all();
1939 hs_usage_free_all();
1940 dns_free_all();
1941 clear_pending_onions();
1942 circuit_free_all();
1943 entry_guards_free_all();
1944 connection_free_all();
1945 buf_shrink_freelists(1);
1946 memarea_clear_freelist();
1947 if (!postfork) {
1948 config_free_all();
1949 router_free_all();
1950 policies_free_all();
1952 free_cell_pool();
1953 if (!postfork) {
1954 tor_tls_free_all();
1956 /* stuff in main.c */
1957 if (connection_array)
1958 smartlist_free(connection_array);
1959 if (closeable_connection_lst)
1960 smartlist_free(closeable_connection_lst);
1961 if (active_linked_connection_lst)
1962 smartlist_free(active_linked_connection_lst);
1963 tor_free(timeout_event);
1964 /* Stuff in util.c and address.c*/
1965 if (!postfork) {
1966 escaped(NULL);
1967 esc_router_info(NULL);
1968 logs_free_all(); /* free log strings. do this last so logs keep working. */
1972 /** Do whatever cleanup is necessary before shutting Tor down. */
1973 void
1974 tor_cleanup(void)
1976 or_options_t *options = get_options();
1977 /* Remove our pid file. We don't care if there was an error when we
1978 * unlink, nothing we could do about it anyways. */
1979 if (options->command == CMD_RUN_TOR) {
1980 if (options->PidFile)
1981 unlink(options->PidFile);
1982 if (accounting_is_enabled(options))
1983 accounting_record_bandwidth_usage(time(NULL), get_or_state());
1984 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
1985 or_state_save(time(NULL));
1986 if (authdir_mode_tests_reachability(options))
1987 rep_hist_record_mtbf_data();
1989 #ifdef USE_DMALLOC
1990 dmalloc_log_stats();
1991 #endif
1992 tor_free_all(0); /* We could move tor_free_all back into the ifdef below
1993 later, if it makes shutdown unacceptably slow. But for
1994 now, leave it here: it's helped us catch bugs in the
1995 past. */
1996 crypto_global_cleanup();
1997 #ifdef USE_DMALLOC
1998 dmalloc_log_unfreed();
1999 dmalloc_shutdown();
2000 #endif
2003 /** Read/create keys as needed, and echo our fingerprint to stdout. */
2004 /* static */ int
2005 do_list_fingerprint(void)
2007 char buf[FINGERPRINT_LEN+1];
2008 crypto_pk_env_t *k;
2009 const char *nickname = get_options()->Nickname;
2010 if (!server_mode(get_options())) {
2011 log_err(LD_GENERAL,
2012 "Clients don't have long-term identity keys. Exiting.\n");
2013 return -1;
2015 tor_assert(nickname);
2016 if (init_keys() < 0) {
2017 log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
2018 return -1;
2020 if (!(k = get_identity_key())) {
2021 log_err(LD_GENERAL,"Error: missing identity key.");
2022 return -1;
2024 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
2025 log_err(LD_BUG, "Error computing fingerprint");
2026 return -1;
2028 printf("%s %s\n", nickname, buf);
2029 return 0;
2032 /** Entry point for password hashing: take the desired password from
2033 * the command line, and print its salted hash to stdout. **/
2034 /* static */ void
2035 do_hash_password(void)
2038 char output[256];
2039 char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
2041 crypto_rand(key, S2K_SPECIFIER_LEN-1);
2042 key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
2043 secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
2044 get_options()->command_arg, strlen(get_options()->command_arg),
2045 key);
2046 base16_encode(output, sizeof(output), key, sizeof(key));
2047 printf("16:%s\n",output);
2050 /** Main entry point for the Tor process. Called from main(). */
2051 /* This function is distinct from main() only so we can link main.c into
2052 * the unittest binary without conflicting with the unittests' main. */
2054 tor_main(int argc, char *argv[])
2056 int result = 0;
2057 tor_threads_init();
2058 init_logging();
2059 #ifdef USE_DMALLOC
2061 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
2062 tor_assert(r);
2064 #endif
2065 #ifdef NT_SERVICE
2067 int done = 0;
2068 result = nt_service_parse_options(argc, argv, &done);
2069 if (done) return result;
2071 #endif
2072 if (tor_init(argc, argv)<0)
2073 return -1;
2074 switch (get_options()->command) {
2075 case CMD_RUN_TOR:
2076 #ifdef NT_SERVICE
2077 nt_service_set_state(SERVICE_RUNNING);
2078 #endif
2079 result = do_main_loop();
2080 break;
2081 case CMD_LIST_FINGERPRINT:
2082 result = do_list_fingerprint();
2083 break;
2084 case CMD_HASH_PASSWORD:
2085 do_hash_password();
2086 result = 0;
2087 break;
2088 case CMD_VERIFY_CONFIG:
2089 printf("Configuration was valid\n");
2090 result = 0;
2091 break;
2092 case CMD_RUN_UNITTESTS: /* only set by test.c */
2093 default:
2094 log_warn(LD_BUG,"Illegal command number %d: internal error.",
2095 get_options()->command);
2096 result = -1;
2098 tor_cleanup();
2099 return result;