Take out the TestVia config option, since it was a workaround for
[tor.git] / src / or / circuitbuild.c
blobaac8b2a7838f707abad680edd10939c5017d4e97
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 circuitbuild_c_id[] =
8 "$Id$";
10 /**
11 * \file circuitbuild.c
12 * \brief The actual details of building circuits.
13 **/
15 #include "or.h"
17 /********* START VARIABLES **********/
19 /** A global list of all circuits at this hop. */
20 extern circuit_t *global_circuitlist;
22 /** An entry_guard_t represents our information about a chosen long-term
23 * first hop, known as a "helper" node in the literature. We can't just
24 * use a routerinfo_t, since we want to remember these even when we
25 * don't have a directory. */
26 typedef struct {
27 char nickname[MAX_NICKNAME_LEN+1];
28 char identity[DIGEST_LEN];
29 time_t chosen_on_date; /**< Approximately when was this guard added?
30 * "0" if we don't know. */
31 char *chosen_by_version; /**< What tor version added this guard? NULL
32 * if we don't know. */
33 unsigned int made_contact : 1; /**< 0 if we have never connected to this
34 * router, 1 if we have. */
35 unsigned int can_retry : 1; /**< Should we retry connecting to this entry,
36 * in spite of having it marked as unreachable?*/
37 time_t bad_since; /**< 0 if this guard is currently usable, or the time at
38 * which it was observed to become (according to the
39 * directory or the user configuration) unusable. */
40 time_t unreachable_since; /**< 0 if we can connect to this guard, or the
41 * time at which we first noticed we couldn't
42 * connect to it. */
43 time_t last_attempted; /**< 0 if we can connect to this guard, or the time
44 * at which we last failed to connect to it. */
45 } entry_guard_t;
47 /** A list of our chosen entry guards. */
48 static smartlist_t *entry_guards = NULL;
49 /** A value of 1 means that the entry_guards list has changed
50 * and those changes need to be flushed to disk. */
51 static int entry_guards_dirty = 0;
53 /********* END VARIABLES ************/
55 static int circuit_deliver_create_cell(circuit_t *circ,
56 uint8_t cell_type, const char *payload);
57 static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
58 static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
59 static int onion_extend_cpath(origin_circuit_t *circ);
60 static int count_acceptable_routers(smartlist_t *routers);
61 static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
63 static void entry_guards_changed(void);
64 static time_t start_of_month(time_t when);
66 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
67 * and with the high bit specified by conn-\>circ_id_type, until we get
68 * a circ_id that is not in use by any other circuit on that conn.
70 * Return it, or 0 if can't get a unique circ_id.
72 static circid_t
73 get_unique_circ_id_by_conn(or_connection_t *conn)
75 circid_t test_circ_id;
76 circid_t attempts=0;
77 circid_t high_bit;
79 tor_assert(conn);
80 if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
81 log_warn(LD_BUG, "Trying to pick a circuit ID for a connection from "
82 "a client with no identity.");
83 return 0;
85 high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
86 do {
87 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
88 * circID such that (high_bit|test_circ_id) is not already used. */
89 test_circ_id = conn->next_circ_id++;
90 if (test_circ_id == 0 || test_circ_id >= 1<<15) {
91 test_circ_id = 1;
92 conn->next_circ_id = 2;
94 if (++attempts > 1<<15) {
95 /* Make sure we don't loop forever if all circ_id's are used. This
96 * matters because it's an external DoS opportunity.
98 log_warn(LD_CIRC,"No unused circ IDs. Failing.");
99 return 0;
101 test_circ_id |= high_bit;
102 } while (circuit_id_in_use_on_orconn(test_circ_id, conn));
103 return test_circ_id;
106 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
107 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
108 * list information about link status in a more verbose format using spaces.
109 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
110 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
111 * names.
113 static char *
114 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
116 crypt_path_t *hop;
117 smartlist_t *elements;
118 const char *states[] = {"closed", "waiting for keys", "open"};
119 char buf[128];
120 char *s;
122 elements = smartlist_create();
124 if (verbose) {
125 const char *nickname = build_state_get_exit_nickname(circ->build_state);
126 tor_snprintf(buf, sizeof(buf), "%s%s circ (length %d%s%s):",
127 circ->build_state->is_internal ? "internal" : "exit",
128 circ->build_state->need_uptime ? " (high-uptime)" : "",
129 circ->build_state->desired_path_len,
130 circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", exit ",
131 circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
132 (nickname?nickname:"*unnamed*"));
133 smartlist_add(elements, tor_strdup(buf));
136 hop = circ->cpath;
137 do {
138 routerinfo_t *ri;
139 char *elt;
140 if (!hop)
141 break;
142 if (!verbose && hop->state != CPATH_STATE_OPEN)
143 break;
144 if (!hop->extend_info)
145 break;
146 if (verbose_names) {
147 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
148 if ((ri = router_get_by_digest(hop->extend_info->identity_digest))) {
149 router_get_verbose_nickname(elt, ri);
150 } else if (hop->extend_info->nickname &&
151 is_legal_nickname(hop->extend_info->nickname)) {
152 elt[0] = '$';
153 base16_encode(elt+1, HEX_DIGEST_LEN+1,
154 hop->extend_info->identity_digest, DIGEST_LEN);
155 elt[HEX_DIGEST_LEN+1]= '~';
156 strlcpy(elt+HEX_DIGEST_LEN+2,
157 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
158 } else {
159 elt[0] = '$';
160 base16_encode(elt+1, HEX_DIGEST_LEN+1,
161 hop->extend_info->identity_digest, DIGEST_LEN);
163 } else { /* ! verbose_names */
164 if ((ri = router_get_by_digest(hop->extend_info->identity_digest)) &&
165 ri->is_named) {
166 elt = tor_strdup(hop->extend_info->nickname);
167 } else {
168 elt = tor_malloc(HEX_DIGEST_LEN+2);
169 elt[0] = '$';
170 base16_encode(elt+1, HEX_DIGEST_LEN+1,
171 hop->extend_info->identity_digest, DIGEST_LEN);
174 tor_assert(elt);
175 if (verbose) {
176 size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
177 char *v = tor_malloc(len);
178 tor_assert(hop->state <= 2);
179 tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
180 smartlist_add(elements, v);
181 tor_free(elt);
182 } else {
183 smartlist_add(elements, elt);
185 hop = hop->next;
186 } while (hop != circ->cpath);
188 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
189 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
190 smartlist_free(elements);
191 return s;
194 /** If <b>verbose</b> is false, allocate and return a comma-separated
195 * list of the currently built elements of circuit_t. If
196 * <b>verbose</b> is true, also list information about link status in
197 * a more verbose format using spaces.
199 char *
200 circuit_list_path(origin_circuit_t *circ, int verbose)
202 return circuit_list_path_impl(circ, verbose, 0);
205 /** Allocate and return a comma-separated list of the currently built elements
206 * of circuit_t, giving each as a verbose nickname.
208 char *
209 circuit_list_path_for_controller(origin_circuit_t *circ)
211 return circuit_list_path_impl(circ, 0, 1);
214 /** Log, at severity <b>severity</b>, the nicknames of each router in
215 * circ's cpath. Also log the length of the cpath, and the intended
216 * exit point.
218 void
219 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
221 char *s = circuit_list_path(circ,1);
222 log(severity,domain,"%s",s);
223 tor_free(s);
226 /** Tell the rep(utation)hist(ory) module about the status of the links
227 * in circ. Hops that have become OPEN are marked as successfully
228 * extended; the _first_ hop that isn't open (if any) is marked as
229 * unable to extend.
231 /* XXXX Someday we should learn from OR circuits too. */
232 void
233 circuit_rep_hist_note_result(origin_circuit_t *circ)
235 crypt_path_t *hop;
236 char *prev_digest = NULL;
237 routerinfo_t *router;
238 hop = circ->cpath;
239 if (!hop) /* circuit hasn't started building yet. */
240 return;
241 if (server_mode(get_options())) {
242 routerinfo_t *me = router_get_my_routerinfo();
243 if (!me)
244 return;
245 prev_digest = me->cache_info.identity_digest;
247 do {
248 router = router_get_by_digest(hop->extend_info->identity_digest);
249 if (router) {
250 if (prev_digest) {
251 if (hop->state == CPATH_STATE_OPEN)
252 rep_hist_note_extend_succeeded(prev_digest,
253 router->cache_info.identity_digest);
254 else {
255 rep_hist_note_extend_failed(prev_digest,
256 router->cache_info.identity_digest);
257 break;
260 prev_digest = router->cache_info.identity_digest;
261 } else {
262 prev_digest = NULL;
264 hop=hop->next;
265 } while (hop!=circ->cpath);
268 /** Pick all the entries in our cpath. Stop and return 0 when we're
269 * happy, or return -1 if an error occurs. */
270 static int
271 onion_populate_cpath(origin_circuit_t *circ)
273 int r;
274 again:
275 r = onion_extend_cpath(circ);
276 if (r < 0) {
277 log_info(LD_CIRC,"Generating cpath hop failed.");
278 return -1;
280 if (r == 0)
281 goto again;
282 return 0; /* if r == 1 */
285 /** Create and return a new origin circuit. Initialize its purpose and
286 * build-state based on our arguments. The <b>flags</b> argument is a
287 * bitfield of CIRCLAUNCH_* flags. */
288 origin_circuit_t *
289 origin_circuit_init(uint8_t purpose, int flags)
291 /* sets circ->p_circ_id and circ->p_conn */
292 origin_circuit_t *circ = origin_circuit_new();
293 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
294 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
295 circ->build_state->onehop_tunnel =
296 ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
297 circ->build_state->need_uptime =
298 ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
299 circ->build_state->need_capacity =
300 ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
301 circ->build_state->is_internal =
302 ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
303 circ->_base.purpose = purpose;
304 return circ;
307 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
308 * is defined, then use that as your exit router, else choose a suitable
309 * exit node.
311 * Also launch a connection to the first OR in the chosen path, if
312 * it's not open already.
314 origin_circuit_t *
315 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
317 origin_circuit_t *circ;
318 int err_reason = 0;
320 circ = origin_circuit_init(purpose, flags);
322 if (onion_pick_cpath_exit(circ, exit) < 0 ||
323 onion_populate_cpath(circ) < 0) {
324 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
325 return NULL;
328 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
330 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
331 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
332 return NULL;
334 return circ;
337 /** Start establishing the first hop of our circuit. Figure out what
338 * OR we should connect to, and if necessary start the connection to
339 * it. If we're already connected, then send the 'create' cell.
340 * Return 0 for ok, -reason if circ should be marked-for-close. */
342 circuit_handle_first_hop(origin_circuit_t *circ)
344 crypt_path_t *firsthop;
345 or_connection_t *n_conn;
346 char tmpbuf[INET_NTOA_BUF_LEN];
347 struct in_addr in;
348 int err_reason = 0;
350 firsthop = onion_next_hop_in_cpath(circ->cpath);
351 tor_assert(firsthop);
352 tor_assert(firsthop->extend_info);
354 /* now see if we're already connected to the first OR in 'route' */
355 in.s_addr = htonl(firsthop->extend_info->addr);
356 tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
357 log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",tmpbuf,
358 firsthop->extend_info->port);
360 n_conn = connection_or_get_by_identity_digest(
361 firsthop->extend_info->identity_digest);
362 /* If we don't have an open conn, or the conn we have is obsolete
363 * (i.e. old or broken) and the other side will let us make a second
364 * connection without dropping it immediately... */
365 if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
366 (n_conn->_base.or_is_obsolete)) {
367 /* not currently connected */
368 circ->_base.n_hop = extend_info_dup(firsthop->extend_info);
370 if (!n_conn || n_conn->_base.or_is_obsolete) { /* launch the connection */
371 if (circ->build_state->onehop_tunnel)
372 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
373 n_conn = connection_or_connect(firsthop->extend_info->addr,
374 firsthop->extend_info->port,
375 firsthop->extend_info->identity_digest);
376 if (!n_conn) { /* connect failed, forget the whole thing */
377 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
378 return -END_CIRC_REASON_CONNECTFAILED;
382 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
383 /* return success. The onion/circuit/etc will be taken care of
384 * automatically (may already have been) whenever n_conn reaches
385 * OR_CONN_STATE_OPEN.
387 return 0;
388 } else { /* it's already open. use it. */
389 tor_assert(!circ->_base.n_hop);
390 circ->_base.n_conn = n_conn;
391 log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
392 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
393 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
394 return err_reason;
397 return 0;
400 /** Find any circuits that are waiting on <b>or_conn</b> to become
401 * open and get them to send their create cells forward.
403 * Status is 1 if connect succeeded, or 0 if connect failed.
405 void
406 circuit_n_conn_done(or_connection_t *or_conn, int status)
408 smartlist_t *pending_circs;
409 int err_reason = 0;
411 log_debug(LD_CIRC,"or_conn to %s/%s, status=%d",
412 or_conn->nickname ? or_conn->nickname : "NULL",
413 or_conn->_base.address, status);
415 pending_circs = smartlist_create();
416 circuit_get_all_pending_on_or_conn(pending_circs, or_conn);
418 SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
420 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
421 * leaving them in in case it's possible for the status of a circuit to
422 * change as we're going down the list. */
423 if (circ->marked_for_close || circ->n_conn || !circ->n_hop ||
424 circ->state != CIRCUIT_STATE_OR_WAIT)
425 continue;
427 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
428 /* Look at addr/port. This is an unkeyed connection. */
429 if (circ->n_hop->addr != or_conn->_base.addr ||
430 circ->n_hop->port != or_conn->_base.port)
431 continue;
432 } else {
433 /* We expected a key. See if it's the right one. */
434 if (memcmp(or_conn->identity_digest,
435 circ->n_hop->identity_digest, DIGEST_LEN))
436 continue;
438 if (!status) { /* or_conn failed; close circ */
439 log_info(LD_CIRC,"or_conn failed. Closing circ.");
440 circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
441 continue;
443 log_debug(LD_CIRC, "Found circ, sending create cell.");
444 /* circuit_deliver_create_cell will set n_circ_id and add us to
445 * orconn_circuid_circuit_map, so we don't need to call
446 * set_circid_orconn here. */
447 circ->n_conn = or_conn;
448 extend_info_free(circ->n_hop);
449 circ->n_hop = NULL;
451 if (CIRCUIT_IS_ORIGIN(circ)) {
452 if ((err_reason =
453 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
454 log_info(LD_CIRC,
455 "send_next_onion_skin failed; circuit marked for closing.");
456 circuit_mark_for_close(circ, -err_reason);
457 continue;
458 /* XXX could this be bad, eg if next_onion_skin failed because conn
459 * died? */
461 } else {
462 /* pull the create cell out of circ->onionskin, and send it */
463 tor_assert(circ->n_conn_onionskin);
464 if (circuit_deliver_create_cell(circ,CELL_CREATE,
465 circ->n_conn_onionskin)<0) {
466 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
467 continue;
469 tor_free(circ->n_conn_onionskin);
470 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
473 SMARTLIST_FOREACH_END(circ);
475 smartlist_free(pending_circs);
478 /** Find a new circid that isn't currently in use on the circ->n_conn
479 * for the outgoing
480 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
481 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
482 * to this circuit.
483 * Return -1 if we failed to find a suitable circid, else return 0.
485 static int
486 circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
487 const char *payload)
489 cell_t cell;
490 circid_t id;
492 tor_assert(circ);
493 tor_assert(circ->n_conn);
494 tor_assert(payload);
495 tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
497 id = get_unique_circ_id_by_conn(circ->n_conn);
498 if (!id) {
499 log_warn(LD_CIRC,"failed to get unique circID.");
500 return -1;
502 log_debug(LD_CIRC,"Chosen circID %u.", id);
503 circuit_set_n_circid_orconn(circ, id, circ->n_conn);
505 memset(&cell, 0, sizeof(cell_t));
506 cell.command = cell_type;
507 cell.circ_id = circ->n_circ_id;
509 memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
510 append_cell_to_circuit_queue(circ, circ->n_conn, &cell, CELL_DIRECTION_OUT);
512 if (CIRCUIT_IS_ORIGIN(circ)) {
513 /* mark it so it gets better rate limiting treatment. */
514 circ->n_conn->client_used = time(NULL);
517 return 0;
520 /** We've decided to start our reachability testing. If all
521 * is set, log this to the user. Return 1 if we did, or 0 if
522 * we chose not to log anything. */
524 inform_testing_reachability(void)
526 char dirbuf[128];
527 routerinfo_t *me = router_get_my_routerinfo();
528 if (!me)
529 return 0;
530 if (me->dir_port)
531 tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
532 me->address, me->dir_port);
533 log(LOG_NOTICE, LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
534 "(this may take up to %d minutes -- look for log "
535 "messages indicating success)",
536 me->address, me->or_port,
537 me->dir_port ? dirbuf : "",
538 me->dir_port ? "are" : "is",
539 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
540 return 1;
543 /** Return true iff we should send a create_fast cell to build a circuit
544 * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
545 * information on the router, so assume true.) */
546 static INLINE int
547 should_use_create_fast_for_router(routerinfo_t *router,
548 origin_circuit_t *circ)
550 or_options_t *options = get_options();
551 (void) router; /* ignore the router's version. */
553 if (!options->FastFirstHopPK) /* create_fast is disabled */
554 return 0;
555 if (server_mode(options) && circ->cpath->extend_info->onion_key) {
556 /* We're a server, and we know an onion key. We can choose.
557 * Prefer to blend in. */
558 return 0;
561 return 1;
564 /** This is the backbone function for building circuits.
566 * If circ's first hop is closed, then we need to build a create
567 * cell and send it forward.
569 * Otherwise, we need to build a relay extend cell and send it
570 * forward.
572 * Return -reason if we want to tear down circ, else return 0.
575 circuit_send_next_onion_skin(origin_circuit_t *circ)
577 crypt_path_t *hop;
578 routerinfo_t *router;
579 char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
580 char *onionskin;
581 size_t payload_len;
583 tor_assert(circ);
585 if (circ->cpath->state == CPATH_STATE_CLOSED) {
586 int fast;
587 uint8_t cell_type;
588 log_debug(LD_CIRC,"First skin; sending create cell.");
589 if (circ->build_state->onehop_tunnel)
590 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
591 else
592 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
594 router = router_get_by_digest(circ->_base.n_conn->identity_digest);
595 fast = should_use_create_fast_for_router(router, circ);
596 if (!fast && !circ->cpath->extend_info->onion_key) {
597 log_warn(LD_CIRC,
598 "Can't send create_fast, but have no onion key. Failing.");
599 return - END_CIRC_REASON_INTERNAL;
601 if (!fast) {
602 /* We are an OR, or we are connecting to an old Tor: we should
603 * send an old slow create cell.
605 cell_type = CELL_CREATE;
606 if (onion_skin_create(circ->cpath->extend_info->onion_key,
607 &(circ->cpath->dh_handshake_state),
608 payload) < 0) {
609 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
610 return - END_CIRC_REASON_INTERNAL;
612 note_request("cell: create", 1);
613 } else {
614 /* We are not an OR, and we're building the first hop of a circuit to a
615 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
616 * and a DH operation. */
617 cell_type = CELL_CREATE_FAST;
618 memset(payload, 0, sizeof(payload));
619 crypto_rand(circ->cpath->fast_handshake_state,
620 sizeof(circ->cpath->fast_handshake_state));
621 memcpy(payload, circ->cpath->fast_handshake_state,
622 sizeof(circ->cpath->fast_handshake_state));
623 note_request("cell: create fast", 1);
626 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
627 return - END_CIRC_REASON_RESOURCELIMIT;
629 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
630 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
631 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
632 fast ? "CREATE_FAST" : "CREATE",
633 router ? router->nickname : "<unnamed>");
634 } else {
635 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
636 tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
637 log_debug(LD_CIRC,"starting to send subsequent skin.");
638 hop = onion_next_hop_in_cpath(circ->cpath);
639 if (!hop) {
640 /* done building the circuit. whew. */
641 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
642 log_info(LD_CIRC,"circuit built!");
643 circuit_reset_failure_count(0);
644 if (circ->build_state->onehop_tunnel)
645 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
646 if (!has_completed_circuit && !circ->build_state->onehop_tunnel) {
647 or_options_t *options = get_options();
648 has_completed_circuit=1;
649 /* FFFF Log a count of known routers here */
650 log(LOG_NOTICE, LD_GENERAL,
651 "Tor has successfully opened a circuit. "
652 "Looks like client functionality is working.");
653 control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
654 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
655 if (server_mode(options) && !check_whether_orport_reachable()) {
656 inform_testing_reachability();
657 consider_testing_reachability(1, 1);
660 circuit_rep_hist_note_result(circ);
661 circuit_has_opened(circ); /* do other actions as necessary */
662 return 0;
665 set_uint32(payload, htonl(hop->extend_info->addr));
666 set_uint16(payload+4, htons(hop->extend_info->port));
668 onionskin = payload+2+4;
669 memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
670 hop->extend_info->identity_digest, DIGEST_LEN);
671 payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
673 if (onion_skin_create(hop->extend_info->onion_key,
674 &(hop->dh_handshake_state), onionskin) < 0) {
675 log_warn(LD_CIRC,"onion_skin_create failed.");
676 return - END_CIRC_REASON_INTERNAL;
679 log_info(LD_CIRC,"Sending extend relay cell.");
680 note_request("cell: extend", 1);
681 /* send it to hop->prev, because it will transfer
682 * it to a create cell and then send to hop */
683 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
684 RELAY_COMMAND_EXTEND,
685 payload, payload_len, hop->prev) < 0)
686 return 0; /* circuit is closed */
688 hop->state = CPATH_STATE_AWAITING_KEYS;
690 return 0;
693 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
694 * something has also gone wrong with our network: notify the user,
695 * and abandon all not-yet-used circuits. */
696 void
697 circuit_note_clock_jumped(int seconds_elapsed)
699 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
700 log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
701 "assuming established circuits no longer work.",
702 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
703 seconds_elapsed >=0 ? "forward" : "backward");
704 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
705 seconds_elapsed);
706 has_completed_circuit=0; /* so it'll log when it works again */
707 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
708 "CLOCK_JUMPED");
709 circuit_mark_all_unused_circs();
710 circuit_expire_all_dirty_circs();
713 /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
714 * sure we're connected to the next hop, and pass it the onion skin using
715 * a create cell. Return -1 if we want to warn and tear down the circuit,
716 * else return 0.
719 circuit_extend(cell_t *cell, circuit_t *circ)
721 or_connection_t *n_conn;
722 relay_header_t rh;
723 char *onionskin;
724 char *id_digest=NULL;
725 uint32_t n_addr;
726 uint16_t n_port;
728 if (circ->n_conn) {
729 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
730 "n_conn already set. Bug/attack. Closing.");
731 return -1;
734 if (!server_mode(get_options())) {
735 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
736 "Got an extend cell, but running as a client. Closing.");
737 return -1;
740 relay_header_unpack(&rh, cell->payload);
742 if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
743 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
744 "Wrong length %d on extend cell. Closing circuit.",
745 rh.length);
746 return -1;
749 n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
750 n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
751 onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
752 id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
754 n_conn = connection_or_get_by_identity_digest(id_digest);
756 /* If we don't have an open conn, or the conn we have is obsolete
757 * (i.e. old or broken) and the other side will let us make a second
758 * connection without dropping it immediately... */
759 if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
760 n_conn->_base.or_is_obsolete) {
761 struct in_addr in;
762 char tmpbuf[INET_NTOA_BUF_LEN];
763 in.s_addr = htonl(n_addr);
764 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
765 log_debug(LD_CIRC|LD_OR,"Next router (%s:%d) not connected. Connecting.",
766 tmpbuf, (int)n_port);
768 circ->n_hop = extend_info_alloc(NULL /*nickname*/,
769 id_digest,
770 NULL /*onion_key*/,
771 n_addr, n_port);
773 circ->n_conn_onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
774 memcpy(circ->n_conn_onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
775 circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
777 if (! (n_conn && !n_conn->_base.or_is_obsolete)) {
778 /* we should try to open a connection */
779 n_conn = connection_or_connect(n_addr, n_port, id_digest);
780 if (!n_conn) {
781 log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
782 circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
783 return 0;
785 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
787 /* return success. The onion/circuit/etc will be taken care of
788 * automatically (may already have been) whenever n_conn reaches
789 * OR_CONN_STATE_OPEN.
791 return 0;
794 tor_assert(!circ->n_hop); /* Connection is already established. */
795 circ->n_conn = n_conn;
796 log_debug(LD_CIRC,"n_conn is %s:%u",
797 n_conn->_base.address,n_conn->_base.port);
799 if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
800 return -1;
801 return 0;
804 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
805 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
806 * used as follows:
807 * - 20 to initialize f_digest
808 * - 20 to initialize b_digest
809 * - 16 to key f_crypto
810 * - 16 to key b_crypto
812 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
815 circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
816 int reverse)
818 crypto_digest_env_t *tmp_digest;
819 crypto_cipher_env_t *tmp_crypto;
821 tor_assert(cpath);
822 tor_assert(key_data);
823 tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
824 cpath->f_digest || cpath->b_digest));
826 cpath->f_digest = crypto_new_digest_env();
827 crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
828 cpath->b_digest = crypto_new_digest_env();
829 crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
831 if (!(cpath->f_crypto =
832 crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
833 log_warn(LD_BUG,"Forward cipher initialization failed.");
834 return -1;
836 if (!(cpath->b_crypto =
837 crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
838 log_warn(LD_BUG,"Backward cipher initialization failed.");
839 return -1;
842 if (reverse) {
843 tmp_digest = cpath->f_digest;
844 cpath->f_digest = cpath->b_digest;
845 cpath->b_digest = tmp_digest;
846 tmp_crypto = cpath->f_crypto;
847 cpath->f_crypto = cpath->b_crypto;
848 cpath->b_crypto = tmp_crypto;
851 return 0;
854 /** A created or extended cell came back to us on the circuit, and it included
855 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
856 * contains (the second DH key, plus KH). If <b>reply_type</b> is
857 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
859 * Calculate the appropriate keys and digests, make sure KH is
860 * correct, and initialize this hop of the cpath.
862 * Return - reason if we want to mark circ for close, else return 0.
865 circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
866 const char *reply)
868 char keys[CPATH_KEY_MATERIAL_LEN];
869 crypt_path_t *hop;
871 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
872 hop = circ->cpath;
873 else {
874 hop = onion_next_hop_in_cpath(circ->cpath);
875 if (!hop) { /* got an extended when we're all done? */
876 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
877 return - END_CIRC_REASON_TORPROTOCOL;
880 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
882 if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
883 if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
884 DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
885 log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
886 return -END_CIRC_REASON_TORPROTOCOL;
888 /* Remember hash of g^xy */
889 memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
890 } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
891 if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
892 DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
893 log_warn(LD_CIRC,"fast_client_handshake failed.");
894 return -END_CIRC_REASON_TORPROTOCOL;
896 memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
897 } else {
898 log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
899 return -END_CIRC_REASON_TORPROTOCOL;
902 if (hop->dh_handshake_state) {
903 crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
904 hop->dh_handshake_state = NULL;
906 memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
908 if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
909 return -END_CIRC_REASON_TORPROTOCOL;
912 hop->state = CPATH_STATE_OPEN;
913 log_info(LD_CIRC,"Finished building %scircuit hop:",
914 (reply_type == CELL_CREATED_FAST) ? "fast " : "");
915 circuit_log_path(LOG_INFO,LD_CIRC,circ);
916 control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
918 return 0;
921 /** We received a relay truncated cell on circ.
923 * Since we don't ask for truncates currently, getting a truncated
924 * means that a connection broke or an extend failed. For now,
925 * just give up: for circ to close, and return 0.
928 circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
930 // crypt_path_t *victim;
931 // connection_t *stream;
933 tor_assert(circ);
934 tor_assert(layer);
936 /* XXX Since we don't ask for truncates currently, getting a truncated
937 * means that a connection broke or an extend failed. For now,
938 * just give up.
940 circuit_mark_for_close(TO_CIRCUIT(circ),
941 END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
942 return 0;
944 #if 0
945 while (layer->next != circ->cpath) {
946 /* we need to clear out layer->next */
947 victim = layer->next;
948 log_debug(LD_CIRC, "Killing a layer of the cpath.");
950 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
951 if (stream->cpath_layer == victim) {
952 log_info(LD_APP, "Marking stream %d for close because of truncate.",
953 stream->stream_id);
954 /* no need to send 'end' relay cells,
955 * because the other side's already dead
957 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
961 layer->next = victim->next;
962 circuit_free_cpath_node(victim);
965 log_info(LD_CIRC, "finished");
966 return 0;
967 #endif
970 /** Given a response payload and keys, initialize, then send a created
971 * cell back.
974 onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
975 const char *keys)
977 cell_t cell;
978 crypt_path_t *tmp_cpath;
980 tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
981 tmp_cpath->magic = CRYPT_PATH_MAGIC;
983 memset(&cell, 0, sizeof(cell_t));
984 cell.command = cell_type;
985 cell.circ_id = circ->p_circ_id;
987 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
989 memcpy(cell.payload, payload,
990 cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
992 log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
993 (unsigned int)*(uint32_t*)(keys),
994 (unsigned int)*(uint32_t*)(keys+20));
995 if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
996 log_warn(LD_BUG,"Circuit initialization failed");
997 tor_free(tmp_cpath);
998 return -1;
1000 circ->n_digest = tmp_cpath->f_digest;
1001 circ->n_crypto = tmp_cpath->f_crypto;
1002 circ->p_digest = tmp_cpath->b_digest;
1003 circ->p_crypto = tmp_cpath->b_crypto;
1004 tmp_cpath->magic = 0;
1005 tor_free(tmp_cpath);
1007 if (cell_type == CELL_CREATED)
1008 memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
1009 else
1010 memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
1012 circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
1014 append_cell_to_circuit_queue(TO_CIRCUIT(circ),
1015 circ->p_conn, &cell, CELL_DIRECTION_IN);
1016 log_debug(LD_CIRC,"Finished sending 'created' cell.");
1018 if (!is_local_IP(circ->p_conn->_base.addr) &&
1019 !connection_or_nonopen_was_started_here(circ->p_conn)) {
1020 /* record that we could process create cells from a non-local conn
1021 * that we didn't initiate; presumably this means that create cells
1022 * can reach us too. */
1023 router_orport_found_reachable();
1026 return 0;
1029 /** Choose a length for a circuit of purpose <b>purpose</b>.
1030 * Default length is 3 + the number of endpoints that would give something
1031 * away. If the routerlist <b>routers</b> doesn't have enough routers
1032 * to handle the desired path length, return as large a path length as
1033 * is feasible, except if it's less than 2, in which case return -1.
1035 static int
1036 new_route_len(uint8_t purpose, extend_info_t *exit,
1037 smartlist_t *routers)
1039 int num_acceptable_routers;
1040 int routelen;
1042 tor_assert(routers);
1044 routelen = 3;
1045 if (exit &&
1046 purpose != CIRCUIT_PURPOSE_TESTING &&
1047 purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
1048 routelen++;
1050 num_acceptable_routers = count_acceptable_routers(routers);
1052 log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
1053 routelen, num_acceptable_routers, smartlist_len(routers));
1055 if (num_acceptable_routers < 2) {
1056 log_info(LD_CIRC,
1057 "Not enough acceptable routers (%d). Discarding this circuit.",
1058 num_acceptable_routers);
1059 return -1;
1062 if (num_acceptable_routers < routelen) {
1063 log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
1064 routelen, num_acceptable_routers);
1065 routelen = num_acceptable_routers;
1068 return routelen;
1071 /** Fetch the list of predicted ports, dup it into a smartlist of
1072 * uint16_t's, remove the ones that are already handled by an
1073 * existing circuit, and return it.
1075 static smartlist_t *
1076 circuit_get_unhandled_ports(time_t now)
1078 smartlist_t *source = rep_hist_get_predicted_ports(now);
1079 smartlist_t *dest = smartlist_create();
1080 uint16_t *tmp;
1081 int i;
1083 for (i = 0; i < smartlist_len(source); ++i) {
1084 tmp = tor_malloc(sizeof(uint16_t));
1085 memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
1086 smartlist_add(dest, tmp);
1089 circuit_remove_handled_ports(dest);
1090 return dest;
1093 /** Return 1 if we already have circuits present or on the way for
1094 * all anticipated ports. Return 0 if we should make more.
1096 * If we're returning 0, set need_uptime and need_capacity to
1097 * indicate any requirements that the unhandled ports have.
1100 circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
1101 int *need_capacity)
1103 int i, enough;
1104 uint16_t *port;
1105 smartlist_t *sl = circuit_get_unhandled_ports(now);
1106 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1107 tor_assert(need_uptime);
1108 tor_assert(need_capacity);
1109 enough = (smartlist_len(sl) == 0);
1110 for (i = 0; i < smartlist_len(sl); ++i) {
1111 port = smartlist_get(sl, i);
1112 if (smartlist_string_num_isin(LongLivedServices, *port))
1113 *need_uptime = 1;
1114 tor_free(port);
1116 smartlist_free(sl);
1117 return enough;
1120 /** Return 1 if <b>router</b> can handle one or more of the ports in
1121 * <b>needed_ports</b>, else return 0.
1123 static int
1124 router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
1126 int i;
1127 uint16_t port;
1129 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1130 addr_policy_result_t r;
1131 port = *(uint16_t *)smartlist_get(needed_ports, i);
1132 tor_assert(port);
1133 r = compare_addr_to_addr_policy(0, port, router->exit_policy);
1134 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1135 return 1;
1137 return 0;
1140 /** Return true iff <b>conn</b> needs another general circuit to be
1141 * built. */
1142 static int
1143 ap_stream_wants_exit_attention(connection_t *conn)
1145 if (conn->type == CONN_TYPE_AP &&
1146 conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1147 !conn->marked_for_close &&
1148 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1149 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
1150 MIN_CIRCUITS_HANDLING_STREAM))
1151 return 1;
1152 return 0;
1155 /** Return a pointer to a suitable router to be the exit node for the
1156 * general-purpose circuit we're about to build.
1158 * Look through the connection array, and choose a router that maximizes
1159 * the number of pending streams that can exit from this router.
1161 * Return NULL if we can't find any suitable routers.
1163 static routerinfo_t *
1164 choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
1165 int need_capacity)
1167 int *n_supported;
1168 int i;
1169 int n_pending_connections = 0;
1170 smartlist_t *connections;
1171 int best_support = -1;
1172 int n_best_support=0;
1173 smartlist_t *sl, *preferredexits;
1174 routerinfo_t *router;
1175 or_options_t *options = get_options();
1177 connections = get_connection_array();
1179 /* Count how many connections are waiting for a circuit to be built.
1180 * We use this for log messages now, but in the future we may depend on it.
1182 SMARTLIST_FOREACH(connections, connection_t *, conn,
1184 if (ap_stream_wants_exit_attention(conn))
1185 ++n_pending_connections;
1187 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1188 // n_pending_connections);
1189 /* Now we count, for each of the routers in the directory, how many
1190 * of the pending connections could possibly exit from that
1191 * router (n_supported[i]). (We can't be sure about cases where we
1192 * don't know the IP address of the pending connection.)
1194 n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
1195 for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
1196 router = smartlist_get(dir->routers, i);
1197 if (router_is_me(router)) {
1198 n_supported[i] = -1;
1199 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1200 /* XXX there's probably a reverse predecessor attack here, but
1201 * it's slow. should we take this out? -RD
1203 continue;
1205 if (!router->is_running || router->is_bad_exit) {
1206 n_supported[i] = -1;
1207 continue; /* skip routers that are known to be down or bad exits */
1209 if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
1210 n_supported[i] = -1;
1211 continue; /* skip routers that are not suitable */
1213 if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
1214 /* if it's invalid and we don't want it */
1215 n_supported[i] = -1;
1216 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1217 // router->nickname, i);
1218 continue; /* skip invalid routers */
1220 if (router_exit_policy_rejects_all(router)) {
1221 n_supported[i] = -1;
1222 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1223 // router->nickname, i);
1224 continue; /* skip routers that reject all */
1226 n_supported[i] = 0;
1227 /* iterate over connections */
1228 SMARTLIST_FOREACH(connections, connection_t *, conn,
1230 if (!ap_stream_wants_exit_attention(conn))
1231 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1232 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router)) {
1233 ++n_supported[i];
1234 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1235 // router->nickname, i, n_supported[i]);
1236 } else {
1237 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1238 // router->nickname, i);
1240 }); /* End looping over connections. */
1241 if (n_supported[i] > best_support) {
1242 /* If this router is better than previous ones, remember its index
1243 * and goodness, and start counting how many routers are this good. */
1244 best_support = n_supported[i]; n_best_support=1;
1245 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1246 // router->nickname);
1247 } else if (n_supported[i] == best_support) {
1248 /* If this router is _as good_ as the best one, just increment the
1249 * count of equally good routers.*/
1250 ++n_best_support;
1253 log_info(LD_CIRC,
1254 "Found %d servers that might support %d/%d pending connections.",
1255 n_best_support, best_support >= 0 ? best_support : 0,
1256 n_pending_connections);
1258 preferredexits = smartlist_create();
1259 add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
1261 sl = smartlist_create();
1263 /* If any routers definitely support any pending connections, choose one
1264 * at random. */
1265 if (best_support > 0) {
1266 for (i = 0; i < smartlist_len(dir->routers); i++)
1267 if (n_supported[i] == best_support)
1268 smartlist_add(sl, smartlist_get(dir->routers, i));
1270 routerset_subtract_routers(sl,options->_ExcludeExitNodesUnion);
1271 if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
1272 smartlist_intersect(sl,preferredexits);
1273 router = routerlist_sl_choose_by_bandwidth(sl, WEIGHT_FOR_EXIT);
1274 } else {
1275 /* Either there are no pending connections, or no routers even seem to
1276 * possibly support any of them. Choose a router at random that satisfies
1277 * at least one predicted exit port. */
1279 int try;
1280 smartlist_t *needed_ports;
1282 if (best_support == -1) {
1283 if (need_uptime || need_capacity) {
1284 log_info(LD_CIRC,
1285 "We couldn't find any live%s%s routers; falling back "
1286 "to list of all routers.",
1287 need_capacity?", fast":"",
1288 need_uptime?", stable":"");
1289 smartlist_free(preferredexits);
1290 smartlist_free(sl);
1291 tor_free(n_supported);
1292 return choose_good_exit_server_general(dir, 0, 0);
1294 log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
1295 "doomed exit at random.");
1297 needed_ports = circuit_get_unhandled_ports(time(NULL));
1298 for (try = 0; try < 2; try++) {
1299 /* try once to pick only from routers that satisfy a needed port,
1300 * then if there are none, pick from any that support exiting. */
1301 for (i = 0; i < smartlist_len(dir->routers); i++) {
1302 router = smartlist_get(dir->routers, i);
1303 if (n_supported[i] != -1 &&
1304 (try || router_handles_some_port(router, needed_ports))) {
1305 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1306 // try, router->nickname);
1307 smartlist_add(sl, router);
1311 routerset_subtract_routers(sl,options->_ExcludeExitNodesUnion);
1312 if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
1313 smartlist_intersect(sl,preferredexits);
1314 /* XXX sometimes the above results in null, when the requested
1315 * exit node is down. we should pick it anyway. */
1316 router = routerlist_sl_choose_by_bandwidth(sl, WEIGHT_FOR_EXIT);
1317 if (router)
1318 break;
1320 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1321 smartlist_free(needed_ports);
1324 smartlist_free(preferredexits);
1325 smartlist_free(sl);
1326 tor_free(n_supported);
1327 if (router) {
1328 log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
1329 return router;
1331 if (options->StrictExitNodes) {
1332 log_warn(LD_CIRC,
1333 "No specified exit routers seem to be running, and "
1334 "StrictExitNodes is set: can't choose an exit.");
1336 return NULL;
1339 /** Return a pointer to a suitable router to be the exit node for the
1340 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1341 * if no router is suitable).
1343 * For general-purpose circuits, pass it off to
1344 * choose_good_exit_server_general()
1346 * For client-side rendezvous circuits, choose a random node, weighted
1347 * toward the preferences in 'options'.
1349 static routerinfo_t *
1350 choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
1351 int need_uptime, int need_capacity, int is_internal)
1353 or_options_t *options = get_options();
1354 router_crn_flags_t flags = 0;
1355 if (need_uptime)
1356 flags |= CRN_NEED_UPTIME;
1357 if (need_capacity)
1358 flags |= CRN_NEED_CAPACITY;
1360 switch (purpose) {
1361 case CIRCUIT_PURPOSE_C_GENERAL:
1362 if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
1363 flags |= CRN_ALLOW_INVALID;
1364 if (is_internal) /* pick it like a middle hop */
1365 return router_choose_random_node(NULL, NULL,
1366 options->ExcludeNodes, flags);
1367 else
1368 return choose_good_exit_server_general(dir,need_uptime,need_capacity);
1369 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1370 if (options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS)
1371 flags |= CRN_ALLOW_INVALID;
1372 return router_choose_random_node(NULL, NULL,
1373 options->ExcludeNodes, flags);
1375 log_warn(LD_BUG,"Unhandled purpose %d", purpose);
1376 tor_fragile_assert();
1377 return NULL;
1380 /** Decide a suitable length for circ's cpath, and pick an exit
1381 * router (or use <b>exit</b> if provided). Store these in the
1382 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1383 static int
1384 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
1386 cpath_build_state_t *state = circ->build_state;
1387 routerlist_t *rl = router_get_routerlist();
1389 if (state->onehop_tunnel) {
1390 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
1391 state->desired_path_len = 1;
1392 } else {
1393 int r = new_route_len(circ->_base.purpose, exit, rl->routers);
1394 if (r < 1) /* must be at least 1 */
1395 return -1;
1396 state->desired_path_len = r;
1399 if (exit) { /* the circuit-builder pre-requested one */
1400 log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
1401 exit = extend_info_dup(exit);
1402 } else { /* we have to decide one */
1403 routerinfo_t *router =
1404 choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
1405 state->need_capacity, state->is_internal);
1406 if (!router) {
1407 log_warn(LD_CIRC,"failed to choose an exit server");
1408 return -1;
1410 exit = extend_info_from_router(router);
1412 state->chosen_exit = exit;
1413 return 0;
1416 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1417 * hop to the cpath reflecting this. Don't send the next extend cell --
1418 * the caller will do this if it wants to.
1421 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1423 cpath_build_state_t *state;
1424 tor_assert(exit);
1425 tor_assert(circ);
1427 state = circ->build_state;
1428 tor_assert(state);
1429 if (state->chosen_exit)
1430 extend_info_free(state->chosen_exit);
1431 state->chosen_exit = extend_info_dup(exit);
1433 ++circ->build_state->desired_path_len;
1434 onion_append_hop(&circ->cpath, exit);
1435 return 0;
1438 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1439 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1440 * send the next extend cell to begin connecting to that hop.
1443 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1445 int err_reason = 0;
1446 circuit_append_new_exit(circ, exit);
1447 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
1448 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
1449 log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
1450 exit->nickname);
1451 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
1452 return -1;
1454 return 0;
1457 /** Return the number of routers in <b>routers</b> that are currently up
1458 * and available for building circuits through.
1460 static int
1461 count_acceptable_routers(smartlist_t *routers)
1463 int i, n;
1464 int num=0;
1465 routerinfo_t *r;
1467 n = smartlist_len(routers);
1468 for (i=0;i<n;i++) {
1469 r = smartlist_get(routers, i);
1470 // log_debug(LD_CIRC,
1471 // "Contemplating whether router %d (%s) is a new option.",
1472 // i, r->nickname);
1473 if (r->is_running == 0) {
1474 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1475 goto next_i_loop;
1477 if (r->is_valid == 0) {
1478 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1479 goto next_i_loop;
1480 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1481 * allows this node in some places, then we're getting an inaccurate
1482 * count. For now, be conservative and don't count it. But later we
1483 * should try to be smarter. */
1485 num++;
1486 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1487 next_i_loop:
1488 ; /* C requires an explicit statement after the label */
1491 return num;
1494 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1495 * This function is used to extend cpath by another hop.
1497 void
1498 onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
1500 if (*head_ptr) {
1501 new_hop->next = (*head_ptr);
1502 new_hop->prev = (*head_ptr)->prev;
1503 (*head_ptr)->prev->next = new_hop;
1504 (*head_ptr)->prev = new_hop;
1505 } else {
1506 *head_ptr = new_hop;
1507 new_hop->prev = new_hop->next = new_hop;
1511 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1512 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1513 * to length <b>cur_len</b> to decide a suitable middle hop for a
1514 * circuit. In particular, make sure we don't pick the exit node or its
1515 * family, and make sure we don't duplicate any previous nodes or their
1516 * families. */
1517 static routerinfo_t *
1518 choose_good_middle_server(uint8_t purpose,
1519 cpath_build_state_t *state,
1520 crypt_path_t *head,
1521 int cur_len)
1523 int i;
1524 routerinfo_t *r, *choice;
1525 crypt_path_t *cpath;
1526 smartlist_t *excluded;
1527 or_options_t *options = get_options();
1528 router_crn_flags_t flags = 0;
1529 tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
1530 purpose <= _CIRCUIT_PURPOSE_MAX);
1532 log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
1533 excluded = smartlist_create();
1534 if ((r = build_state_get_exit_router(state))) {
1535 smartlist_add(excluded, r);
1536 routerlist_add_family(excluded, r);
1538 for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
1539 if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
1540 smartlist_add(excluded, r);
1541 routerlist_add_family(excluded, r);
1545 if (state->need_uptime)
1546 flags |= CRN_NEED_UPTIME;
1547 if (state->need_capacity)
1548 flags |= CRN_NEED_CAPACITY;
1549 if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
1550 flags |= CRN_ALLOW_INVALID;
1551 choice = router_choose_random_node(NULL,
1552 excluded, options->ExcludeNodes, flags);
1553 smartlist_free(excluded);
1554 return choice;
1557 /** Pick a good entry server for the circuit to be built according to
1558 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1559 * router (if we're an OR), and respect firewall settings; if we're
1560 * configured to use entry guards, return one.
1562 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1563 * guard, not for any particular circuit.
1565 static routerinfo_t *
1566 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
1568 routerinfo_t *r, *choice;
1569 smartlist_t *excluded;
1570 or_options_t *options = get_options();
1571 router_crn_flags_t flags = 0;
1573 if (state && options->UseEntryGuards &&
1574 (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
1575 return choose_random_entry(state);
1578 excluded = smartlist_create();
1580 if (state && (r = build_state_get_exit_router(state))) {
1581 smartlist_add(excluded, r);
1582 routerlist_add_family(excluded, r);
1584 if (firewall_is_fascist_or()) {
1585 /*XXXX021 This can slow things down a lot; use a smarter implementation */
1586 /* exclude all ORs that listen on the wrong port */
1587 routerlist_t *rl = router_get_routerlist();
1588 int i;
1590 for (i=0; i < smartlist_len(rl->routers); i++) {
1591 r = smartlist_get(rl->routers, i);
1592 if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
1593 smartlist_add(excluded, r);
1596 /* and exclude current entry guards, if applicable */
1597 if (options->UseEntryGuards && entry_guards) {
1598 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1600 if ((r = router_get_by_digest(entry->identity)))
1601 smartlist_add(excluded, r);
1605 if (state) {
1606 flags |= CRN_NEED_GUARD;
1607 if (state->need_uptime)
1608 flags |= CRN_NEED_UPTIME;
1609 if (state->need_capacity)
1610 flags |= CRN_NEED_CAPACITY;
1612 if (options->_AllowInvalid & ALLOW_INVALID_ENTRY)
1613 flags |= CRN_ALLOW_INVALID;
1615 choice = router_choose_random_node(
1616 NULL,
1617 excluded,
1618 options->ExcludeNodes,
1619 flags);
1620 smartlist_free(excluded);
1621 return choice;
1624 /** Return the first non-open hop in cpath, or return NULL if all
1625 * hops are open. */
1626 static crypt_path_t *
1627 onion_next_hop_in_cpath(crypt_path_t *cpath)
1629 crypt_path_t *hop = cpath;
1630 do {
1631 if (hop->state != CPATH_STATE_OPEN)
1632 return hop;
1633 hop = hop->next;
1634 } while (hop != cpath);
1635 return NULL;
1638 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1639 * based on <b>state</b>. Append the hop info to head_ptr.
1641 static int
1642 onion_extend_cpath(origin_circuit_t *circ)
1644 uint8_t purpose = circ->_base.purpose;
1645 cpath_build_state_t *state = circ->build_state;
1646 int cur_len = circuit_get_cpath_len(circ);
1647 extend_info_t *info = NULL;
1649 if (cur_len >= state->desired_path_len) {
1650 log_debug(LD_CIRC, "Path is complete: %d steps long",
1651 state->desired_path_len);
1652 return 1;
1655 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
1656 state->desired_path_len);
1658 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
1659 info = extend_info_dup(state->chosen_exit);
1660 } else if (cur_len == 0) { /* picking first node */
1661 routerinfo_t *r = choose_good_entry_server(purpose, state);
1662 if (r)
1663 info = extend_info_from_router(r);
1664 } else {
1665 routerinfo_t *r =
1666 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
1667 if (r)
1668 info = extend_info_from_router(r);
1671 if (!info) {
1672 log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
1673 "this circuit.", cur_len);
1674 return -1;
1677 log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
1678 info->nickname, cur_len+1, build_state_get_exit_nickname(state));
1680 onion_append_hop(&circ->cpath, info);
1681 extend_info_free(info);
1682 return 0;
1685 /** Create a new hop, annotate it with information about its
1686 * corresponding router <b>choice</b>, and append it to the
1687 * end of the cpath <b>head_ptr</b>. */
1688 static int
1689 onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
1691 crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
1693 /* link hop into the cpath, at the end. */
1694 onion_append_to_cpath(head_ptr, hop);
1696 hop->magic = CRYPT_PATH_MAGIC;
1697 hop->state = CPATH_STATE_CLOSED;
1699 hop->extend_info = extend_info_dup(choice);
1701 hop->package_window = CIRCWINDOW_START;
1702 hop->deliver_window = CIRCWINDOW_START;
1704 return 0;
1707 /** Allocate a new extend_info object based on the various arguments. */
1708 extend_info_t *
1709 extend_info_alloc(const char *nickname, const char *digest,
1710 crypto_pk_env_t *onion_key,
1711 uint32_t addr, uint16_t port)
1713 extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
1714 memcpy(info->identity_digest, digest, DIGEST_LEN);
1715 if (nickname)
1716 strlcpy(info->nickname, nickname, sizeof(info->nickname));
1717 if (onion_key)
1718 info->onion_key = crypto_pk_dup_key(onion_key);
1719 info->addr = addr;
1720 info->port = port;
1721 return info;
1724 /** Allocate and return a new extend_info_t that can be used to build a
1725 * circuit to or through the router <b>r</b>. */
1726 extend_info_t *
1727 extend_info_from_router(routerinfo_t *r)
1729 tor_assert(r);
1730 return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
1731 r->onion_pkey, r->addr, r->or_port);
1734 /** Release storage held by an extend_info_t struct. */
1735 void
1736 extend_info_free(extend_info_t *info)
1738 tor_assert(info);
1739 if (info->onion_key)
1740 crypto_free_pk_env(info->onion_key);
1741 tor_free(info);
1744 /** Allocate and return a new extend_info_t with the same contents as
1745 * <b>info</b>. */
1746 extend_info_t *
1747 extend_info_dup(extend_info_t *info)
1749 extend_info_t *newinfo;
1750 tor_assert(info);
1751 newinfo = tor_malloc(sizeof(extend_info_t));
1752 memcpy(newinfo, info, sizeof(extend_info_t));
1753 if (info->onion_key)
1754 newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
1755 else
1756 newinfo->onion_key = NULL;
1757 return newinfo;
1760 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1761 * If there is no chosen exit, or if we don't know the routerinfo_t for
1762 * the chosen exit, return NULL.
1764 routerinfo_t *
1765 build_state_get_exit_router(cpath_build_state_t *state)
1767 if (!state || !state->chosen_exit)
1768 return NULL;
1769 return router_get_by_digest(state->chosen_exit->identity_digest);
1772 /** Return the nickname for the chosen exit router in <b>state</b>. If
1773 * there is no chosen exit, or if we don't know the routerinfo_t for the
1774 * chosen exit, return NULL.
1776 const char *
1777 build_state_get_exit_nickname(cpath_build_state_t *state)
1779 if (!state || !state->chosen_exit)
1780 return NULL;
1781 return state->chosen_exit->nickname;
1784 /** Check whether the entry guard <b>e</b> is usable, given the directory
1785 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1786 * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
1787 * accordingly. Return true iff the entry guard's status changes.
1789 * If it's not usable, set *<b>reason</b> to a static string explaining why.
1791 /*XXXX021 take a routerstatus, not a routerinfo. */
1792 static int
1793 entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
1794 time_t now, or_options_t *options, const char **reason)
1796 char buf[HEX_DIGEST_LEN+1];
1797 int changed = 0;
1799 tor_assert(options);
1801 *reason = NULL;
1803 /* Do we want to mark this guard as bad? */
1804 if (!ri)
1805 *reason = "unlisted";
1806 else if (!ri->is_running)
1807 *reason = "down";
1808 else if (options->UseBridges && ri->purpose != ROUTER_PURPOSE_BRIDGE)
1809 *reason = "not a bridge";
1810 else if (!options->UseBridges && !ri->is_possible_guard &&
1811 !router_nickname_is_in_list(ri, options->EntryNodes))
1812 *reason = "not recommended as a guard";
1813 else if (routerset_contains_router(options->ExcludeNodes, ri))
1814 *reason = "excluded";
1816 if (*reason && ! e->bad_since) {
1817 /* Router is newly bad. */
1818 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
1819 log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
1820 e->nickname, buf, *reason);
1822 e->bad_since = now;
1823 control_event_guard(e->nickname, e->identity, "BAD");
1824 changed = 1;
1825 } else if (!*reason && e->bad_since) {
1826 /* There's nothing wrong with the router any more. */
1827 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
1828 log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
1829 "marking as ok.", e->nickname, buf);
1831 e->bad_since = 0;
1832 control_event_guard(e->nickname, e->identity, "GOOD");
1833 changed = 1;
1836 return changed;
1839 /** Return true iff enough time has passed since we last tried to connect
1840 * to the unreachable guard <b>e</b> that we're willing to try again. */
1841 static int
1842 entry_is_time_to_retry(entry_guard_t *e, time_t now)
1844 long diff;
1845 if (e->last_attempted < e->unreachable_since)
1846 return 1;
1847 diff = now - e->unreachable_since;
1848 if (diff < 6*60*60)
1849 return now > (e->last_attempted + 60*60);
1850 else if (diff < 3*24*60*60)
1851 return now > (e->last_attempted + 4*60*60);
1852 else if (diff < 7*24*60*60)
1853 return now > (e->last_attempted + 18*60*60);
1854 else
1855 return now > (e->last_attempted + 36*60*60);
1858 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1859 * working well enough that we are willing to use it as an entry
1860 * right now. (Else return NULL.) In particular, it must be
1861 * - Listed as either up or never yet contacted;
1862 * - Present in the routerlist;
1863 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1864 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1865 * (This check is currently redundant with the Guard flag, but in
1866 * the future that might change. Best to leave it in for now.)
1867 * - Allowed by our current ReachableORAddresses config option; and
1868 * - Currently thought to be reachable by us (unless assume_reachable
1869 * is true).
1871 static INLINE routerinfo_t *
1872 entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
1873 int assume_reachable)
1875 routerinfo_t *r;
1876 if (e->bad_since)
1877 return NULL;
1878 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1879 if (!assume_reachable && !e->can_retry &&
1880 e->unreachable_since && !entry_is_time_to_retry(e, time(NULL)))
1881 return NULL;
1882 r = router_get_by_digest(e->identity);
1883 if (!r)
1884 return NULL;
1885 if (get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_BRIDGE)
1886 return NULL;
1887 if (!get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_GENERAL)
1888 return NULL;
1889 if (router_is_unreliable(r, need_uptime, need_capacity, 0))
1890 return NULL;
1891 if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
1892 return NULL;
1893 return r;
1896 /** Return the number of entry guards that we think are usable. */
1897 static int
1898 num_live_entry_guards(void)
1900 int n = 0;
1901 if (! entry_guards)
1902 return 0;
1903 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1905 if (entry_is_live(entry, 0, 1, 0))
1906 ++n;
1908 return n;
1911 /** If <b>digest</b> matches the identity of any node in the
1912 * entry_guards list, return that node. Else return NULL. */
1913 static INLINE entry_guard_t *
1914 is_an_entry_guard(const char *digest)
1916 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1917 if (!memcmp(digest, entry->identity, DIGEST_LEN))
1918 return entry;
1920 return NULL;
1923 /** Dump a description of our list of entry guards to the log at level
1924 * <b>severity</b>. */
1925 static void
1926 log_entry_guards(int severity)
1928 smartlist_t *elements = smartlist_create();
1929 char buf[1024];
1930 char *s;
1932 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
1934 tor_snprintf(buf, sizeof(buf), "%s (%s%s)",
1935 e->nickname,
1936 entry_is_live(e, 0, 1, 0) ? "up " : "down ",
1937 e->made_contact ? "made-contact" : "never-contacted");
1938 smartlist_add(elements, tor_strdup(buf));
1941 s = smartlist_join_strings(elements, ",", 0, NULL);
1942 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
1943 smartlist_free(elements);
1944 log_fn(severity,LD_CIRC,"%s",s);
1945 tor_free(s);
1948 /** Called when one or more guards that we would previously have used for some
1949 * purpose are no longer in use because a higher-priority guard has become
1950 * useable again. */
1951 static void
1952 control_event_guard_deferred(void)
1954 /* XXXX We don't actually have a good way to figure out _how many_ entries
1955 * are live for some purpose. We need an entry_is_even_slightly_live()
1956 * function for this to work right. NumEntryGuards isn't reliable: if we
1957 * need guards with weird properties, we can have more than that number
1958 * live.
1960 #if 0
1961 int n = 0;
1962 or_options_t *options = get_options();
1963 if (!entry_guards)
1964 return;
1965 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1967 if (entry_is_live(entry, 0, 1, 0)) {
1968 if (n++ == options->NumEntryGuards) {
1969 control_event_guard(entry->nickname, entry->identity, "DEFERRED");
1970 return;
1974 #endif
1977 /** Add a new (preferably stable and fast) router to our
1978 * entry_guards list. Return a pointer to the router if we succeed,
1979 * or NULL if we can't find any more suitable entries.
1981 * If <b>chosen</b> is defined, use that one, and if it's not
1982 * already in our entry_guards list, put it at the *beginning*.
1983 * Else, put the one we pick at the end of the list. */
1984 static routerinfo_t *
1985 add_an_entry_guard(routerinfo_t *chosen, int reset_status)
1987 routerinfo_t *router;
1988 entry_guard_t *entry;
1990 if (chosen) {
1991 router = chosen;
1992 entry = is_an_entry_guard(router->cache_info.identity_digest);
1993 if (entry) {
1994 if (reset_status) {
1995 entry->bad_since = 0;
1996 entry->can_retry = 1;
1998 return NULL;
2000 } else {
2001 router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
2002 if (!router)
2003 return NULL;
2005 entry = tor_malloc_zero(sizeof(entry_guard_t));
2006 log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
2007 strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
2008 memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
2009 entry->chosen_on_date = start_of_month(time(NULL));
2010 entry->chosen_by_version = tor_strdup(VERSION);
2011 if (chosen) /* prepend */
2012 smartlist_insert(entry_guards, 0, entry);
2013 else /* append */
2014 smartlist_add(entry_guards, entry);
2015 control_event_guard(entry->nickname, entry->identity, "NEW");
2016 control_event_guard_deferred();
2017 log_entry_guards(LOG_INFO);
2018 return router;
2021 /** If the use of entry guards is configured, choose more entry guards
2022 * until we have enough in the list. */
2023 static void
2024 pick_entry_guards(void)
2026 or_options_t *options = get_options();
2027 int changed = 0;
2029 tor_assert(entry_guards);
2031 while (num_live_entry_guards() < options->NumEntryGuards) {
2032 if (!add_an_entry_guard(NULL, 0))
2033 break;
2034 changed = 1;
2036 if (changed)
2037 entry_guards_changed();
2040 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2041 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2042 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2044 /** Release all storage held by <b>e</b>. */
2045 static void
2046 entry_guard_free(entry_guard_t *e)
2048 tor_assert(e);
2049 tor_free(e->chosen_by_version);
2050 tor_free(e);
2053 /** Remove any entry guard which was selected by an unknown version of Tor,
2054 * or which was selected by a version of Tor that's known to select
2055 * entry guards badly. */
2056 static int
2057 remove_obsolete_entry_guards(void)
2059 int changed = 0, i;
2060 for (i = 0; i < smartlist_len(entry_guards); ++i) {
2061 entry_guard_t *entry = smartlist_get(entry_guards, i);
2062 const char *ver = entry->chosen_by_version;
2063 const char *msg = NULL;
2064 tor_version_t v;
2065 int version_is_bad = 0;
2066 if (!ver) {
2067 msg = "does not say what version of Tor it was selected by";
2068 version_is_bad = 1;
2069 } else if (tor_version_parse(ver, &v)) {
2070 msg = "does not seem to be from any recognized version of Tor";
2071 version_is_bad = 1;
2072 } else if ((tor_version_as_new_as(ver, "0.1.0.10-alpha") &&
2073 !tor_version_as_new_as(ver, "0.1.2.16-dev")) ||
2074 (tor_version_as_new_as(ver, "0.2.0.0-alpha") &&
2075 !tor_version_as_new_as(ver, "0.2.0.6-alpha"))) {
2076 msg = "was selected without regard for guard bandwidth";
2077 version_is_bad = 1;
2079 if (version_is_bad) {
2080 char dbuf[HEX_DIGEST_LEN+1];
2081 tor_assert(msg);
2082 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
2083 log_notice(LD_CIRC, "Entry guard '%s' (%s) %s. (Version=%s.) "
2084 "Replacing it.",
2085 entry->nickname, dbuf, msg, ver?escaped(ver):"none");
2086 control_event_guard(entry->nickname, entry->identity, "DROPPED");
2087 entry_guard_free(entry);
2088 smartlist_del_keeporder(entry_guards, i--);
2089 log_entry_guards(LOG_INFO);
2090 changed = 1;
2094 return changed ? 1 : 0;
2097 /** Remove all entry guards that have been down or unlisted for so
2098 * long that we don't think they'll come up again. Return 1 if we
2099 * removed any, or 0 if we did nothing. */
2100 static int
2101 remove_dead_entry_guards(void)
2103 char dbuf[HEX_DIGEST_LEN+1];
2104 char tbuf[ISO_TIME_LEN+1];
2105 time_t now = time(NULL);
2106 int i;
2107 int changed = 0;
2109 for (i = 0; i < smartlist_len(entry_guards); ) {
2110 entry_guard_t *entry = smartlist_get(entry_guards, i);
2111 if (entry->bad_since &&
2112 entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
2114 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
2115 format_local_iso_time(tbuf, entry->bad_since);
2116 log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
2117 "since %s local time; removing.",
2118 entry->nickname, dbuf, tbuf);
2119 control_event_guard(entry->nickname, entry->identity, "DROPPED");
2120 entry_guard_free(entry);
2121 smartlist_del_keeporder(entry_guards, i);
2122 log_entry_guards(LOG_INFO);
2123 changed = 1;
2124 } else
2125 ++i;
2127 return changed ? 1 : 0;
2130 /** A new directory or router-status has arrived; update the down/listed
2131 * status of the entry guards.
2133 * An entry is 'down' if the directory lists it as nonrunning.
2134 * An entry is 'unlisted' if the directory doesn't include it.
2136 * Don't call this on startup; only on a fresh download. Otherwise we'll
2137 * think that things are unlisted.
2139 void
2140 entry_guards_compute_status(void)
2142 time_t now;
2143 int changed = 0;
2144 int severity = LOG_DEBUG;
2145 or_options_t *options;
2146 if (! entry_guards)
2147 return;
2149 options = get_options();
2151 now = time(NULL);
2153 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2155 routerinfo_t *r = router_get_by_digest(entry->identity);
2156 const char *reason = NULL;
2157 /*XXX021 log reason again. */
2158 if (entry_guard_set_status(entry, r, now, options, &reason))
2159 changed = 1;
2161 if (entry->bad_since)
2162 tor_assert(reason);
2165 if (remove_dead_entry_guards())
2166 changed = 1;
2168 severity = changed ? LOG_DEBUG : LOG_INFO;
2170 if (changed) {
2171 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2172 log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s, and %s.",
2173 entry->nickname,
2174 entry->unreachable_since ? "unreachable" : "reachable",
2175 entry->bad_since ? "unusable" : "usable",
2176 entry_is_live(entry, 0, 1, 0) ? "live" : "not live"));
2177 log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
2178 num_live_entry_guards(), smartlist_len(entry_guards));
2179 log_entry_guards(LOG_INFO);
2180 entry_guards_changed();
2184 /** Called when a connection to an OR with the identity digest <b>digest</b>
2185 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2186 * If the OR is an entry, change that entry's up/down status.
2187 * Return 0 normally, or -1 if we want to tear down the new connection.
2190 entry_guard_register_connect_status(const char *digest, int succeeded,
2191 time_t now)
2193 int changed = 0;
2194 int refuse_conn = 0;
2195 int first_contact = 0;
2196 entry_guard_t *entry = NULL;
2197 int idx = -1;
2198 char buf[HEX_DIGEST_LEN+1];
2200 if (! entry_guards)
2201 return 0;
2203 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2205 if (!memcmp(e->identity, digest, DIGEST_LEN)) {
2206 entry = e;
2207 idx = e_sl_idx;
2208 break;
2212 if (!entry)
2213 return 0;
2215 base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
2217 if (succeeded) {
2218 if (entry->unreachable_since) {
2219 log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
2220 entry->nickname, buf);
2221 entry->can_retry = 0;
2222 entry->unreachable_since = 0;
2223 entry->last_attempted = now;
2224 control_event_guard(entry->nickname, entry->identity, "UP");
2225 changed = 1;
2227 if (!entry->made_contact) {
2228 entry->made_contact = 1;
2229 first_contact = changed = 1;
2231 } else { /* ! succeeded */
2232 if (!entry->made_contact) {
2233 /* We've never connected to this one. */
2234 log_info(LD_CIRC,
2235 "Connection to never-contacted entry guard '%s' (%s) failed. "
2236 "Removing from the list. %d/%d entry guards usable/new.",
2237 entry->nickname, buf,
2238 num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
2239 entry_guard_free(entry);
2240 smartlist_del_keeporder(entry_guards, idx);
2241 log_entry_guards(LOG_INFO);
2242 changed = 1;
2243 } else if (!entry->unreachable_since) {
2244 log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
2245 "Marking as unreachable.", entry->nickname, buf);
2246 entry->unreachable_since = entry->last_attempted = now;
2247 control_event_guard(entry->nickname, entry->identity, "DOWN");
2248 changed = 1;
2249 entry->can_retry = 0; /* We gave it an early chance; no good. */
2250 } else {
2251 char tbuf[ISO_TIME_LEN+1];
2252 format_iso_time(tbuf, entry->unreachable_since);
2253 log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
2254 "'%s' (%s). It has been unreachable since %s.",
2255 entry->nickname, buf, tbuf);
2256 entry->last_attempted = now;
2257 entry->can_retry = 0; /* We gave it an early chance; no good. */
2261 if (first_contact) {
2262 /* We've just added a new long-term entry guard. Perhaps the network just
2263 * came back? We should give our earlier entries another try too,
2264 * and close this connection so we don't use it before we've given
2265 * the others a shot. */
2266 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
2267 if (e == entry)
2268 break;
2269 if (e->made_contact) {
2270 routerinfo_t *r = entry_is_live(e, 0, 1, 1);
2271 if (r && e->unreachable_since) {
2272 refuse_conn = 1;
2273 e->can_retry = 1;
2277 if (refuse_conn) {
2278 log_info(LD_CIRC,
2279 "Connected to new entry guard '%s' (%s). Marking earlier "
2280 "entry guards up. %d/%d entry guards usable/new.",
2281 entry->nickname, buf,
2282 num_live_entry_guards(), smartlist_len(entry_guards));
2283 log_entry_guards(LOG_INFO);
2284 changed = 1;
2288 if (changed)
2289 entry_guards_changed();
2290 return refuse_conn ? -1 : 0;
2293 /** When we try to choose an entry guard, should we parse and add
2294 * config's EntryNodes first? */
2295 static int should_add_entry_nodes = 0;
2297 /** Called when the value of EntryNodes changes in our configuration. */
2298 void
2299 entry_nodes_should_be_added(void)
2301 log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
2302 should_add_entry_nodes = 1;
2305 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2306 * of guard nodes, at the front. */
2307 static void
2308 entry_guards_prepend_from_config(void)
2310 or_options_t *options = get_options();
2311 smartlist_t *entry_routers, *entry_fps;
2312 smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
2313 tor_assert(entry_guards);
2315 should_add_entry_nodes = 0;
2317 if (!options->EntryNodes) {
2318 /* It's possible that a controller set EntryNodes, thus making
2319 * should_add_entry_nodes set, then cleared it again, all before the
2320 * call to choose_random_entry() that triggered us. If so, just return.
2322 return;
2325 log_info(LD_CIRC,"Adding configured EntryNodes '%s'.",
2326 options->EntryNodes);
2328 entry_routers = smartlist_create();
2329 entry_fps = smartlist_create();
2330 old_entry_guards_on_list = smartlist_create();
2331 old_entry_guards_not_on_list = smartlist_create();
2333 /* Split entry guards into those on the list and those not. */
2334 add_nickname_list_to_smartlist(entry_routers, options->EntryNodes, 0);
2335 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
2336 smartlist_add(entry_fps,ri->cache_info.identity_digest));
2337 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
2338 if (smartlist_digest_isin(entry_fps, e->identity))
2339 smartlist_add(old_entry_guards_on_list, e);
2340 else
2341 smartlist_add(old_entry_guards_not_on_list, e);
2344 /* Remove all currently configured entry guards from entry_routers. */
2345 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
2346 if (is_an_entry_guard(ri->cache_info.identity_digest)) {
2347 SMARTLIST_DEL_CURRENT(entry_routers, ri);
2351 /* Now build the new entry_guards list. */
2352 smartlist_clear(entry_guards);
2353 /* First, the previously configured guards that are in EntryNodes. */
2354 smartlist_add_all(entry_guards, old_entry_guards_on_list);
2355 /* Next, the rest of EntryNodes */
2356 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
2357 add_an_entry_guard(ri, 0);
2359 /* Finally, the remaining EntryNodes, unless we're strict */
2360 if (options->StrictEntryNodes) {
2361 SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
2362 entry_guard_free(e));
2363 } else {
2364 smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
2367 smartlist_free(entry_routers);
2368 smartlist_free(entry_fps);
2369 smartlist_free(old_entry_guards_on_list);
2370 smartlist_free(old_entry_guards_not_on_list);
2371 entry_guards_changed();
2374 /** Return 1 if we're fine adding arbitrary routers out of the
2375 * directory to our entry guard list. Else return 0. */
2377 entry_list_can_grow(or_options_t *options)
2379 if (options->StrictEntryNodes)
2380 return 0;
2381 if (options->UseBridges)
2382 return 0;
2383 return 1;
2386 /** Pick a live (up and listed) entry guard from entry_guards. If
2387 * <b>state</b> is non-NULL, this is for a specific circuit --
2388 * make sure not to pick this circuit's exit or any node in the
2389 * exit's family. If <b>state</b> is NULL, we're looking for a random
2390 * guard (likely a bridge). */
2391 routerinfo_t *
2392 choose_random_entry(cpath_build_state_t *state)
2394 or_options_t *options = get_options();
2395 smartlist_t *live_entry_guards = smartlist_create();
2396 smartlist_t *exit_family = smartlist_create();
2397 routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
2398 routerinfo_t *r = NULL;
2399 int need_uptime = state ? state->need_uptime : 0;
2400 int need_capacity = state ? state->need_capacity : 0;
2401 int consider_exit_family = 0;
2403 if (chosen_exit) {
2404 smartlist_add(exit_family, chosen_exit);
2405 routerlist_add_family(exit_family, chosen_exit);
2406 consider_exit_family = 1;
2409 if (!entry_guards)
2410 entry_guards = smartlist_create();
2412 if (should_add_entry_nodes)
2413 entry_guards_prepend_from_config();
2415 if (entry_list_can_grow(options) &&
2416 (! entry_guards ||
2417 smartlist_len(entry_guards) < options->NumEntryGuards))
2418 pick_entry_guards();
2420 retry:
2421 smartlist_clear(live_entry_guards);
2422 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2424 r = entry_is_live(entry, need_uptime, need_capacity, 0);
2425 if (r && (!consider_exit_family || !smartlist_isin(exit_family, r))) {
2426 smartlist_add(live_entry_guards, r);
2427 if (!entry->made_contact) {
2428 /* Always start with the first not-yet-contacted entry
2429 * guard. Otherwise we might add several new ones, pick
2430 * the second new one, and now we've expanded our entry
2431 * guard list without needing to. */
2432 goto choose_and_finish;
2434 if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
2435 break; /* we have enough */
2439 /* Try to have at least 2 choices available. This way we don't
2440 * get stuck with a single live-but-crummy entry and just keep
2441 * using him.
2442 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2443 if (smartlist_len(live_entry_guards) < 2) {
2444 if (entry_list_can_grow(options)) {
2445 /* still no? try adding a new entry then */
2446 /* XXX if guard doesn't imply fast and stable, then we need
2447 * to tell add_an_entry_guard below what we want, or it might
2448 * be a long time til we get it. -RD */
2449 r = add_an_entry_guard(NULL, 0);
2450 if (r) {
2451 smartlist_add(live_entry_guards, r);
2452 entry_guards_changed();
2455 if (!r && need_uptime) {
2456 need_uptime = 0; /* try without that requirement */
2457 goto retry;
2459 if (!r && need_capacity) {
2460 /* still no? last attempt, try without requiring capacity */
2461 need_capacity = 0;
2462 goto retry;
2464 if (!r && !entry_list_can_grow(options) && consider_exit_family) {
2465 /* still no? if we're using bridges or have strictentrynodes
2466 * set, and our chosen exit is in the same family as all our
2467 * bridges/entry guards, then be flexible about families. */
2468 consider_exit_family = 0;
2469 goto retry;
2471 /* live_entry_guards may be empty below. Oh well, we tried. */
2474 choose_and_finish:
2475 if (entry_list_can_grow(options)) {
2476 /* We choose uniformly at random here, because choose_good_entry_server()
2477 * already weights its choices by bandwidth, so we don't want to
2478 * *double*-weight our guard selection. */
2479 r = smartlist_choose(live_entry_guards);
2480 } else {
2481 /* We need to weight by bandwidth, because our bridges or entryguards
2482 * were not already selected proportional to their bandwidth. */
2483 r = routerlist_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
2485 smartlist_free(live_entry_guards);
2486 smartlist_free(exit_family);
2487 return r;
2490 /** Helper: Return the start of the month containing <b>time</b>. */
2491 static time_t
2492 start_of_month(time_t now)
2494 struct tm tm;
2495 tor_gmtime_r(&now, &tm);
2496 tm.tm_sec = 0;
2497 tm.tm_min = 0;
2498 tm.tm_hour = 0;
2499 tm.tm_mday = 1;
2500 return tor_timegm(&tm);
2503 /** Parse <b>state</b> and learn about the entry guards it describes.
2504 * If <b>set</b> is true, and there are no errors, replace the global
2505 * entry_list with what we find.
2506 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2507 * describing the error, and return -1.
2510 entry_guards_parse_state(or_state_t *state, int set, char **msg)
2512 entry_guard_t *node = NULL;
2513 smartlist_t *new_entry_guards = smartlist_create();
2514 config_line_t *line;
2515 time_t now = time(NULL);
2516 const char *state_version = state->TorVersion;
2517 digestmap_t *added_by = digestmap_new();
2519 *msg = NULL;
2520 for (line = state->EntryGuards; line; line = line->next) {
2521 if (!strcasecmp(line->key, "EntryGuard")) {
2522 smartlist_t *args = smartlist_create();
2523 node = tor_malloc_zero(sizeof(entry_guard_t));
2524 /* all entry guards on disk have been contacted */
2525 node->made_contact = 1;
2526 smartlist_add(new_entry_guards, node);
2527 smartlist_split_string(args, line->value, " ",
2528 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2529 if (smartlist_len(args)<2) {
2530 *msg = tor_strdup("Unable to parse entry nodes: "
2531 "Too few arguments to EntryGuard");
2532 } else if (!is_legal_nickname(smartlist_get(args,0))) {
2533 *msg = tor_strdup("Unable to parse entry nodes: "
2534 "Bad nickname for EntryGuard");
2535 } else {
2536 strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
2537 if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
2538 strlen(smartlist_get(args,1)))<0) {
2539 *msg = tor_strdup("Unable to parse entry nodes: "
2540 "Bad hex digest for EntryGuard");
2543 SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
2544 smartlist_free(args);
2545 if (*msg)
2546 break;
2547 } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
2548 !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
2549 time_t when;
2550 time_t last_try = 0;
2551 if (!node) {
2552 *msg = tor_strdup("Unable to parse entry nodes: "
2553 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2554 break;
2556 if (parse_iso_time(line->value, &when)<0) {
2557 *msg = tor_strdup("Unable to parse entry nodes: "
2558 "Bad time in EntryGuardDownSince/UnlistedSince");
2559 break;
2561 if (when > now) {
2562 /* It's a bad idea to believe info in the future: you can wind
2563 * up with timeouts that aren't allowed to happen for years. */
2564 continue;
2566 if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
2567 /* ignore failure */
2568 (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
2570 if (!strcasecmp(line->key, "EntryGuardDownSince")) {
2571 node->unreachable_since = when;
2572 node->last_attempted = last_try;
2573 } else {
2574 node->bad_since = when;
2576 } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
2577 char d[DIGEST_LEN];
2578 /* format is digest version date */
2579 if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
2580 log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
2581 continue;
2583 if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
2584 line->value[HEX_DIGEST_LEN] != ' ') {
2585 log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
2586 "hex digest", escaped(line->value));
2587 continue;
2589 digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
2590 } else {
2591 log_warn(LD_BUG, "Unexpected key %s", line->key);
2595 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
2597 char *sp;
2598 char *val = digestmap_get(added_by, e->identity);
2599 if (val && (sp = strchr(val, ' '))) {
2600 time_t when;
2601 *sp++ = '\0';
2602 if (parse_iso_time(sp, &when)<0) {
2603 log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
2604 } else {
2605 e->chosen_by_version = tor_strdup(val);
2606 e->chosen_on_date = when;
2608 } else {
2609 if (state_version) {
2610 e->chosen_by_version = tor_strdup(state_version);
2611 e->chosen_on_date = start_of_month(time(NULL));
2616 if (*msg || !set) {
2617 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
2618 entry_guard_free(e));
2619 smartlist_free(new_entry_guards);
2620 } else { /* !*err && set */
2621 if (entry_guards) {
2622 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2623 entry_guard_free(e));
2624 smartlist_free(entry_guards);
2626 entry_guards = new_entry_guards;
2627 entry_guards_dirty = 0;
2628 if (remove_obsolete_entry_guards())
2629 entry_guards_dirty = 1;
2631 digestmap_free(added_by, _tor_free);
2632 return *msg ? -1 : 0;
2635 /** Our list of entry guards has changed, or some element of one
2636 * of our entry guards has changed. Write the changes to disk within
2637 * the next few minutes.
2639 static void
2640 entry_guards_changed(void)
2642 time_t when;
2643 entry_guards_dirty = 1;
2645 /* or_state_save() will call entry_guards_update_state(). */
2646 when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
2647 or_state_mark_dirty(get_or_state(), when);
2650 /** If the entry guard info has not changed, do nothing and return.
2651 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2652 * a new one out of the global entry_guards list, and then mark
2653 * <b>state</b> dirty so it will get saved to disk.
2655 void
2656 entry_guards_update_state(or_state_t *state)
2658 config_line_t **next, *line;
2659 if (! entry_guards_dirty)
2660 return;
2662 config_free_lines(state->EntryGuards);
2663 next = &state->EntryGuards;
2664 *next = NULL;
2665 if (!entry_guards)
2666 entry_guards = smartlist_create();
2667 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2669 char dbuf[HEX_DIGEST_LEN+1];
2670 if (!e->made_contact)
2671 continue; /* don't write this one to disk */
2672 *next = line = tor_malloc_zero(sizeof(config_line_t));
2673 line->key = tor_strdup("EntryGuard");
2674 line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
2675 base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
2676 tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
2677 "%s %s", e->nickname, dbuf);
2678 next = &(line->next);
2679 if (e->unreachable_since) {
2680 *next = line = tor_malloc_zero(sizeof(config_line_t));
2681 line->key = tor_strdup("EntryGuardDownSince");
2682 line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
2683 format_iso_time(line->value, e->unreachable_since);
2684 if (e->last_attempted) {
2685 line->value[ISO_TIME_LEN] = ' ';
2686 format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
2688 next = &(line->next);
2690 if (e->bad_since) {
2691 *next = line = tor_malloc_zero(sizeof(config_line_t));
2692 line->key = tor_strdup("EntryGuardUnlistedSince");
2693 line->value = tor_malloc(ISO_TIME_LEN+1);
2694 format_iso_time(line->value, e->bad_since);
2695 next = &(line->next);
2697 if (e->chosen_on_date && e->chosen_by_version &&
2698 !strchr(e->chosen_by_version, ' ')) {
2699 char d[HEX_DIGEST_LEN+1];
2700 char t[ISO_TIME_LEN+1];
2701 size_t val_len;
2702 *next = line = tor_malloc_zero(sizeof(config_line_t));
2703 line->key = tor_strdup("EntryGuardAddedBy");
2704 val_len = (HEX_DIGEST_LEN+1+strlen(e->chosen_by_version)
2705 +1+ISO_TIME_LEN+1);
2706 line->value = tor_malloc(val_len);
2707 base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
2708 format_iso_time(t, e->chosen_on_date);
2709 tor_snprintf(line->value, val_len, "%s %s %s",
2710 d, e->chosen_by_version, t);
2711 next = &(line->next);
2714 if (!get_options()->AvoidDiskWrites)
2715 or_state_mark_dirty(get_or_state(), 0);
2716 entry_guards_dirty = 0;
2719 /** If <b>question</b> is the string "entry-guards", then dump
2720 * to *<b>answer</b> a newly allocated string describing all of
2721 * the nodes in the global entry_guards list. See control-spec.txt
2722 * for details.
2723 * For backward compatibility, we also handle the string "helper-nodes".
2724 * */
2726 getinfo_helper_entry_guards(control_connection_t *conn,
2727 const char *question, char **answer)
2729 int use_long_names = conn->use_long_names;
2731 if (!strcmp(question,"entry-guards") ||
2732 !strcmp(question,"helper-nodes")) {
2733 smartlist_t *sl = smartlist_create();
2734 char tbuf[ISO_TIME_LEN+1];
2735 char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
2736 if (!entry_guards)
2737 entry_guards = smartlist_create();
2738 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2740 size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
2741 char *c = tor_malloc(len);
2742 const char *status = NULL;
2743 time_t when = 0;
2744 if (!e->made_contact) {
2745 status = "never-connected";
2746 } else if (e->bad_since) {
2747 when = e->bad_since;
2748 status = "unusable";
2749 } else {
2750 status = "up";
2752 if (use_long_names) {
2753 routerinfo_t *ri = router_get_by_digest(e->identity);
2754 if (ri) {
2755 router_get_verbose_nickname(nbuf, ri);
2756 } else {
2757 nbuf[0] = '$';
2758 base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
2759 /* e->nickname field is not very reliable if we don't know about
2760 * this router any longer; don't include it. */
2762 } else {
2763 base16_encode(nbuf, sizeof(nbuf), e->identity, DIGEST_LEN);
2765 if (when) {
2766 format_iso_time(tbuf, when);
2767 tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
2768 } else {
2769 tor_snprintf(c, len, "%s %s\n", nbuf, status);
2771 smartlist_add(sl, c);
2773 *answer = smartlist_join_strings(sl, "", 0, NULL);
2774 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
2775 smartlist_free(sl);
2777 return 0;
2780 /** Information about a configured bridge. Currently this just matches the
2781 * ones in the torrc file, but one day we may be able to learn about new
2782 * bridges on our own, and remember them in the state file. */
2783 typedef struct {
2784 /** IPv4 address of the bridge. */
2785 uint32_t addr;
2786 /** TLS port for the bridge. */
2787 uint16_t port;
2788 /** Expected identity digest, or all \0's if we don't know what the
2789 * digest should be. */
2790 char identity[DIGEST_LEN];
2791 /** When should we next try to fetch a descriptor for this bridge? */
2792 download_status_t fetch_status;
2793 } bridge_info_t;
2795 /** A list of configured bridges. Whenever we actually get a descriptor
2796 * for one, we add it as an entry guard. */
2797 static smartlist_t *bridge_list = NULL;
2799 /** Initialize the bridge list to empty, creating it if needed. */
2800 void
2801 clear_bridge_list(void)
2803 if (!bridge_list)
2804 bridge_list = smartlist_create();
2805 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
2806 smartlist_clear(bridge_list);
2809 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2810 * (either by comparing keys if possible, else by comparing addr/port).
2811 * Else return NULL. */
2812 static bridge_info_t *
2813 routerinfo_get_configured_bridge(routerinfo_t *ri)
2815 if (!bridge_list)
2816 return NULL;
2817 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2819 if (tor_digest_is_zero(bridge->identity) &&
2820 bridge->addr == ri->addr && bridge->port == ri->or_port)
2821 return bridge;
2822 if (!memcmp(bridge->identity, ri->cache_info.identity_digest,
2823 DIGEST_LEN))
2824 return bridge;
2826 return NULL;
2829 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
2831 routerinfo_is_a_configured_bridge(routerinfo_t *ri)
2833 return routerinfo_get_configured_bridge(ri) ? 1 : 0;
2836 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2837 * is set, it tells us the identity key too. */
2838 void
2839 bridge_add_from_config(uint32_t addr, uint16_t port, char *digest)
2841 bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
2842 b->addr = addr;
2843 b->port = port;
2844 if (digest)
2845 memcpy(b->identity, digest, DIGEST_LEN);
2846 if (!bridge_list)
2847 bridge_list = smartlist_create();
2848 smartlist_add(bridge_list, b);
2851 /** Schedule the next fetch for <b>bridge</b>, based on
2852 * some retry schedule. */
2853 static void
2854 bridge_fetch_status_increment(bridge_info_t *bridge, time_t now)
2856 switch (bridge->fetch_status.n_download_failures) {
2857 case 0: bridge->fetch_status.next_attempt_at = now+60*15; break;
2858 case 1: bridge->fetch_status.next_attempt_at = now+60*15; break;
2859 default: bridge->fetch_status.next_attempt_at = now+60*60; break;
2861 if (bridge->fetch_status.n_download_failures < 10)
2862 bridge->fetch_status.n_download_failures++;
2865 /** We just got a new descriptor for <b>bridge</b>. Reschedule the
2866 * next fetch for a long time from <b>now</b>. */
2867 static void
2868 bridge_fetch_status_arrived(bridge_info_t *bridge, time_t now)
2870 tor_assert(bridge);
2871 bridge->fetch_status.next_attempt_at = now+60*60;
2872 bridge->fetch_status.n_download_failures = 0;
2875 /** If <b>digest</b> is one of our known bridges, return it. */
2876 static bridge_info_t *
2877 find_bridge_by_digest(char *digest)
2879 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2881 if (!memcmp(bridge->identity, digest, DIGEST_LEN))
2882 return bridge;
2884 return NULL;
2887 /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
2888 * is a helpful string describing this bridge. */
2889 static void
2890 launch_direct_bridge_descriptor_fetch(char *address, bridge_info_t *bridge)
2892 if (connection_get_by_type_addr_port_purpose(
2893 CONN_TYPE_DIR, bridge->addr, bridge->port,
2894 DIR_PURPOSE_FETCH_SERVERDESC))
2895 return; /* it's already on the way */
2896 directory_initiate_command(address, bridge->addr,
2897 bridge->port, 0,
2898 0, /* does not matter */
2899 1, bridge->identity,
2900 DIR_PURPOSE_FETCH_SERVERDESC,
2901 ROUTER_PURPOSE_BRIDGE,
2902 0, "authority.z", NULL, 0, 0);
2905 /** Fetching the bridge descriptor from the bridge authority returned a
2906 * "not found". Fall back to trying a direct fetch. */
2907 void
2908 retry_bridge_descriptor_fetch_directly(char *digest)
2910 bridge_info_t *bridge = find_bridge_by_digest(digest);
2911 char address_buf[INET_NTOA_BUF_LEN+1];
2912 struct in_addr in;
2914 if (!bridge)
2915 return; /* not found? oh well. */
2917 in.s_addr = htonl(bridge->addr);
2918 tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
2919 launch_direct_bridge_descriptor_fetch(address_buf, bridge);
2922 /** For each bridge in our list for which we don't currently have a
2923 * descriptor, fetch a new copy of its descriptor -- either directly
2924 * from the bridge or via a bridge authority. */
2925 void
2926 fetch_bridge_descriptors(time_t now)
2928 char address_buf[INET_NTOA_BUF_LEN+1];
2929 struct in_addr in;
2930 or_options_t *options = get_options();
2931 int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
2932 int ask_bridge_directly;
2933 int can_use_bridge_authority;
2935 if (!bridge_list)
2936 return;
2938 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2940 if (bridge->fetch_status.next_attempt_at > now)
2941 continue; /* don't bother, no need to retry yet */
2943 /* schedule another fetch as if this one will fail, in case it does */
2944 bridge_fetch_status_increment(bridge, now);
2946 in.s_addr = htonl(bridge->addr);
2947 tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
2949 can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
2950 num_bridge_auths;
2951 ask_bridge_directly = !can_use_bridge_authority ||
2952 !options->UpdateBridgesFromAuthority;
2953 log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
2954 ask_bridge_directly, tor_digest_is_zero(bridge->identity),
2955 !options->UpdateBridgesFromAuthority, !num_bridge_auths);
2957 if (ask_bridge_directly &&
2958 !fascist_firewall_allows_address_or(bridge->addr, bridge->port)) {
2959 log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
2960 "firewall policy. %s.", address_buf, bridge->port,
2961 can_use_bridge_authority ?
2962 "Asking bridge authority instead" : "Skipping");
2963 if (can_use_bridge_authority)
2964 ask_bridge_directly = 0;
2965 else
2966 continue;
2969 if (ask_bridge_directly) {
2970 /* we need to ask the bridge itself for its descriptor. */
2971 launch_direct_bridge_descriptor_fetch(address_buf, bridge);
2972 } else {
2973 /* We have a digest and we want to ask an authority. We could
2974 * combine all the requests into one, but that may give more
2975 * hints to the bridge authority than we want to give. */
2976 char resource[10 + HEX_DIGEST_LEN];
2977 memcpy(resource, "fp/", 3);
2978 base16_encode(resource+3, HEX_DIGEST_LEN+1,
2979 bridge->identity, DIGEST_LEN);
2980 memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
2981 log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
2982 resource);
2983 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
2984 ROUTER_PURPOSE_BRIDGE, resource, 0);
2989 /** We just learned a descriptor for a bridge. See if that
2990 * digest is in our entry guard list, and add it if not. */
2991 void
2992 learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
2994 tor_assert(ri);
2995 tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
2996 if (get_options()->UseBridges) {
2997 int first = !any_bridge_descriptors_known();
2998 bridge_info_t *bridge = routerinfo_get_configured_bridge(ri);
2999 time_t now = time(NULL);
3000 ri->is_running = 1;
3002 if (bridge) { /* if we actually want to use this one */
3003 /* it's here; schedule its re-fetch for a long time from now. */
3004 if (!from_cache)
3005 bridge_fetch_status_arrived(bridge, now);
3007 add_an_entry_guard(ri, 1);
3008 log_notice(LD_DIR, "new bridge descriptor '%s' (%s)", ri->nickname,
3009 from_cache ? "cached" : "fresh");
3010 if (first)
3011 routerlist_retry_directory_downloads(now);
3016 /** Return 1 if any of our entry guards have descriptors that
3017 * are marked with purpose 'bridge' and are running. Else return 0.
3019 * We use this function to decide if we're ready to start building
3020 * circuits through our bridges, or if we need to wait until the
3021 * directory "server/authority" requests finish. */
3023 any_bridge_descriptors_known(void)
3025 tor_assert(get_options()->UseBridges);
3026 return choose_random_entry(NULL)!=NULL ? 1 : 0;
3029 /** Return 1 if there are any directory conns fetching bridge descriptors
3030 * that aren't marked for close. We use this to guess if we should tell
3031 * the controller that we have a problem. */
3033 any_pending_bridge_descriptor_fetches(void)
3035 smartlist_t *conns = get_connection_array();
3036 SMARTLIST_FOREACH(conns, connection_t *, conn,
3038 if (conn->type == CONN_TYPE_DIR &&
3039 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
3040 TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
3041 !conn->marked_for_close &&
3042 conn->linked && !conn->linked_conn->marked_for_close) {
3043 log_debug(LD_DIR, "found one: %s", conn->address);
3044 return 1;
3047 return 0;
3050 /** Return 1 if we have at least one descriptor for a bridge and
3051 * all descriptors we know are down. Else return 0. If <b>act</b> is
3052 * 1, then mark the down bridges up; else just observe and report. */
3053 static int
3054 bridges_retry_helper(int act)
3056 routerinfo_t *ri;
3057 int any_known = 0;
3058 int any_running = 0;
3059 if (!entry_guards)
3060 entry_guards = smartlist_create();
3061 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
3063 ri = router_get_by_digest(e->identity);
3064 if (ri && ri->purpose == ROUTER_PURPOSE_BRIDGE) {
3065 any_known = 1;
3066 if (ri->is_running)
3067 any_running = 1; /* some bridge is both known and running */
3068 else if (act) { /* mark it for retry */
3069 ri->is_running = 1;
3070 e->can_retry = 1;
3071 e->bad_since = 0;
3075 return any_known && !any_running;
3078 /** Do we know any descriptors for our bridges, and are they all
3079 * down? */
3081 bridges_known_but_down(void)
3083 return bridges_retry_helper(0);
3086 /** Mark all down known bridges up. */
3087 void
3088 bridges_retry_all(void)
3090 bridges_retry_helper(1);
3093 /** Release all storage held by the list of entry guards and related
3094 * memory structs. */
3095 void
3096 entry_guards_free_all(void)
3098 if (entry_guards) {
3099 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
3100 entry_guard_free(e));
3101 smartlist_free(entry_guards);
3102 entry_guards = NULL;
3104 clear_bridge_list();
3105 smartlist_free(bridge_list);
3106 bridge_list = NULL;