Clients replace entry guards that were chosen more than a few months
[tor/rransom.git] / src / or / circuitbuild.c
blob64196b07a9a88d816065e03c2e3295bb9d626480
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 */
7 /**
8 * \file circuitbuild.c
9 * \brief The actual details of building circuits.
10 **/
12 #include "or.h"
14 /********* START VARIABLES **********/
16 /** A global list of all circuits at this hop. */
17 extern circuit_t *global_circuitlist;
19 /** An entry_guard_t represents our information about a chosen long-term
20 * first hop, known as a "helper" node in the literature. We can't just
21 * use a routerinfo_t, since we want to remember these even when we
22 * don't have a directory. */
23 typedef struct {
24 char nickname[MAX_NICKNAME_LEN+1];
25 char identity[DIGEST_LEN];
26 time_t chosen_on_date; /**< Approximately when was this guard added?
27 * "0" if we don't know. */
28 char *chosen_by_version; /**< What tor version added this guard? NULL
29 * if we don't know. */
30 unsigned int made_contact : 1; /**< 0 if we have never connected to this
31 * router, 1 if we have. */
32 unsigned int can_retry : 1; /**< Should we retry connecting to this entry,
33 * in spite of having it marked as unreachable?*/
34 time_t bad_since; /**< 0 if this guard is currently usable, or the time at
35 * which it was observed to become (according to the
36 * directory or the user configuration) unusable. */
37 time_t unreachable_since; /**< 0 if we can connect to this guard, or the
38 * time at which we first noticed we couldn't
39 * connect to it. */
40 time_t last_attempted; /**< 0 if we can connect to this guard, or the time
41 * at which we last failed to connect to it. */
42 } entry_guard_t;
44 /** A list of our chosen entry guards. */
45 static smartlist_t *entry_guards = NULL;
46 /** A value of 1 means that the entry_guards list has changed
47 * and those changes need to be flushed to disk. */
48 static int entry_guards_dirty = 0;
50 /********* END VARIABLES ************/
52 static int circuit_deliver_create_cell(circuit_t *circ,
53 uint8_t cell_type, const char *payload);
54 static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
55 static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
56 static int onion_extend_cpath(origin_circuit_t *circ);
57 static int count_acceptable_routers(smartlist_t *routers);
58 static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
60 static void entry_guards_changed(void);
61 static time_t start_of_month(time_t when);
63 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
64 * and with the high bit specified by conn-\>circ_id_type, until we get
65 * a circ_id that is not in use by any other circuit on that conn.
67 * Return it, or 0 if can't get a unique circ_id.
69 static circid_t
70 get_unique_circ_id_by_conn(or_connection_t *conn)
72 circid_t test_circ_id;
73 circid_t attempts=0;
74 circid_t high_bit;
76 tor_assert(conn);
77 if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
78 log_warn(LD_BUG, "Trying to pick a circuit ID for a connection from "
79 "a client with no identity.");
80 return 0;
82 high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
83 do {
84 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
85 * circID such that (high_bit|test_circ_id) is not already used. */
86 test_circ_id = conn->next_circ_id++;
87 if (test_circ_id == 0 || test_circ_id >= 1<<15) {
88 test_circ_id = 1;
89 conn->next_circ_id = 2;
91 if (++attempts > 1<<15) {
92 /* Make sure we don't loop forever if all circ_id's are used. This
93 * matters because it's an external DoS opportunity.
95 log_warn(LD_CIRC,"No unused circ IDs. Failing.");
96 return 0;
98 test_circ_id |= high_bit;
99 } while (circuit_id_in_use_on_orconn(test_circ_id, conn));
100 return test_circ_id;
103 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
104 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
105 * list information about link status in a more verbose format using spaces.
106 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
107 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
108 * names.
110 static char *
111 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
113 crypt_path_t *hop;
114 smartlist_t *elements;
115 const char *states[] = {"closed", "waiting for keys", "open"};
116 char buf[128];
117 char *s;
119 elements = smartlist_create();
121 if (verbose) {
122 const char *nickname = build_state_get_exit_nickname(circ->build_state);
123 tor_snprintf(buf, sizeof(buf), "%s%s circ (length %d%s%s):",
124 circ->build_state->is_internal ? "internal" : "exit",
125 circ->build_state->need_uptime ? " (high-uptime)" : "",
126 circ->build_state->desired_path_len,
127 circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", exit ",
128 circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
129 (nickname?nickname:"*unnamed*"));
130 smartlist_add(elements, tor_strdup(buf));
133 hop = circ->cpath;
134 do {
135 routerinfo_t *ri;
136 routerstatus_t *rs;
137 char *elt;
138 const char *id;
139 if (!hop)
140 break;
141 id = hop->extend_info->identity_digest;
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(id))) {
149 router_get_verbose_nickname(elt, ri);
150 } else if ((rs = router_get_consensus_status_by_id(id))) {
151 routerstatus_get_verbose_nickname(elt, rs);
152 } else if (hop->extend_info->nickname &&
153 is_legal_nickname(hop->extend_info->nickname)) {
154 elt[0] = '$';
155 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
156 elt[HEX_DIGEST_LEN+1]= '~';
157 strlcpy(elt+HEX_DIGEST_LEN+2,
158 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
159 } else {
160 elt[0] = '$';
161 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
163 } else { /* ! verbose_names */
164 if ((ri = router_get_by_digest(id)) &&
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, id, DIGEST_LEN);
173 tor_assert(elt);
174 if (verbose) {
175 size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
176 char *v = tor_malloc(len);
177 tor_assert(hop->state <= 2);
178 tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
179 smartlist_add(elements, v);
180 tor_free(elt);
181 } else {
182 smartlist_add(elements, elt);
184 hop = hop->next;
185 } while (hop != circ->cpath);
187 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
188 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
189 smartlist_free(elements);
190 return s;
193 /** If <b>verbose</b> is false, allocate and return a comma-separated
194 * list of the currently built elements of circuit_t. If
195 * <b>verbose</b> is true, also list information about link status in
196 * a more verbose format using spaces.
198 char *
199 circuit_list_path(origin_circuit_t *circ, int verbose)
201 return circuit_list_path_impl(circ, verbose, 0);
204 /** Allocate and return a comma-separated list of the currently built elements
205 * of circuit_t, giving each as a verbose nickname.
207 char *
208 circuit_list_path_for_controller(origin_circuit_t *circ)
210 return circuit_list_path_impl(circ, 0, 1);
213 /** Log, at severity <b>severity</b>, the nicknames of each router in
214 * circ's cpath. Also log the length of the cpath, and the intended
215 * exit point.
217 void
218 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
220 char *s = circuit_list_path(circ,1);
221 log(severity,domain,"%s",s);
222 tor_free(s);
225 /** Tell the rep(utation)hist(ory) module about the status of the links
226 * in circ. Hops that have become OPEN are marked as successfully
227 * extended; the _first_ hop that isn't open (if any) is marked as
228 * unable to extend.
230 /* XXXX Someday we should learn from OR circuits too. */
231 void
232 circuit_rep_hist_note_result(origin_circuit_t *circ)
234 crypt_path_t *hop;
235 char *prev_digest = NULL;
236 routerinfo_t *router;
237 hop = circ->cpath;
238 if (!hop) /* circuit hasn't started building yet. */
239 return;
240 if (server_mode(get_options())) {
241 routerinfo_t *me = router_get_my_routerinfo();
242 if (!me)
243 return;
244 prev_digest = me->cache_info.identity_digest;
246 do {
247 router = router_get_by_digest(hop->extend_info->identity_digest);
248 if (router) {
249 if (prev_digest) {
250 if (hop->state == CPATH_STATE_OPEN)
251 rep_hist_note_extend_succeeded(prev_digest,
252 router->cache_info.identity_digest);
253 else {
254 rep_hist_note_extend_failed(prev_digest,
255 router->cache_info.identity_digest);
256 break;
259 prev_digest = router->cache_info.identity_digest;
260 } else {
261 prev_digest = NULL;
263 hop=hop->next;
264 } while (hop!=circ->cpath);
267 /** Pick all the entries in our cpath. Stop and return 0 when we're
268 * happy, or return -1 if an error occurs. */
269 static int
270 onion_populate_cpath(origin_circuit_t *circ)
272 int r;
273 again:
274 r = onion_extend_cpath(circ);
275 if (r < 0) {
276 log_info(LD_CIRC,"Generating cpath hop failed.");
277 return -1;
279 if (r == 0)
280 goto again;
281 return 0; /* if r == 1 */
284 /** Create and return a new origin circuit. Initialize its purpose and
285 * build-state based on our arguments. The <b>flags</b> argument is a
286 * bitfield of CIRCLAUNCH_* flags. */
287 origin_circuit_t *
288 origin_circuit_init(uint8_t purpose, int flags)
290 /* sets circ->p_circ_id and circ->p_conn */
291 origin_circuit_t *circ = origin_circuit_new();
292 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
293 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
294 circ->build_state->onehop_tunnel =
295 ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
296 circ->build_state->need_uptime =
297 ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
298 circ->build_state->need_capacity =
299 ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
300 circ->build_state->is_internal =
301 ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
302 circ->_base.purpose = purpose;
303 return circ;
306 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
307 * is defined, then use that as your exit router, else choose a suitable
308 * exit node.
310 * Also launch a connection to the first OR in the chosen path, if
311 * it's not open already.
313 origin_circuit_t *
314 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
316 origin_circuit_t *circ;
317 int err_reason = 0;
319 circ = origin_circuit_init(purpose, flags);
321 if (onion_pick_cpath_exit(circ, exit) < 0 ||
322 onion_populate_cpath(circ) < 0) {
323 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
324 return NULL;
327 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
329 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
330 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
331 return NULL;
333 return circ;
336 /** Start establishing the first hop of our circuit. Figure out what
337 * OR we should connect to, and if necessary start the connection to
338 * it. If we're already connected, then send the 'create' cell.
339 * Return 0 for ok, -reason if circ should be marked-for-close. */
341 circuit_handle_first_hop(origin_circuit_t *circ)
343 crypt_path_t *firsthop;
344 or_connection_t *n_conn;
345 int err_reason = 0;
346 const char *msg = NULL;
347 int should_launch = 0;
349 firsthop = onion_next_hop_in_cpath(circ->cpath);
350 tor_assert(firsthop);
351 tor_assert(firsthop->extend_info);
353 /* now see if we're already connected to the first OR in 'route' */
354 log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",
355 fmt_addr(&firsthop->extend_info->addr),
356 firsthop->extend_info->port);
358 n_conn = connection_or_get_for_extend(firsthop->extend_info->identity_digest,
359 &firsthop->extend_info->addr,
360 &msg,
361 &should_launch);
363 if (!n_conn) {
364 /* not currently connected in a useful way. */
365 const char *name = firsthop->extend_info->nickname ?
366 firsthop->extend_info->nickname : fmt_addr(&firsthop->extend_info->addr);
367 log_info(LD_CIRC, "Next router is %s: %s ", safe_str(name), msg?msg:"???");
368 circ->_base.n_hop = extend_info_dup(firsthop->extend_info);
370 if (should_launch) {
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 (!tor_addr_eq(&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 start building a given
544 * circuit */
545 static INLINE int
546 should_use_create_fast_for_circuit(origin_circuit_t *circ)
548 or_options_t *options = get_options();
549 tor_assert(circ->cpath);
550 tor_assert(circ->cpath->extend_info);
552 if (!circ->cpath->extend_info->onion_key)
553 return 1; /* our hand is forced: only a create_fast will work. */
554 if (!options->FastFirstHopPK)
555 return 0; /* we prefer to avoid create_fast */
556 if (server_mode(options)) {
557 /* We're a server, and we know an onion key. We can choose.
558 * Prefer to blend in. */
559 return 0;
562 return 1;
565 /** This is the backbone function for building circuits.
567 * If circ's first hop is closed, then we need to build a create
568 * cell and send it forward.
570 * Otherwise, we need to build a relay extend cell and send it
571 * forward.
573 * Return -reason if we want to tear down circ, else return 0.
576 circuit_send_next_onion_skin(origin_circuit_t *circ)
578 crypt_path_t *hop;
579 routerinfo_t *router;
580 char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
581 char *onionskin;
582 size_t payload_len;
584 tor_assert(circ);
586 if (circ->cpath->state == CPATH_STATE_CLOSED) {
587 int fast;
588 uint8_t cell_type;
589 log_debug(LD_CIRC,"First skin; sending create cell.");
590 if (circ->build_state->onehop_tunnel)
591 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
592 else
593 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
595 router = router_get_by_digest(circ->_base.n_conn->identity_digest);
596 fast = should_use_create_fast_for_circuit(circ);
597 if (!fast) {
598 /* We are an OR and we know the right onion key: we should
599 * send an old slow create cell.
601 cell_type = CELL_CREATE;
602 if (onion_skin_create(circ->cpath->extend_info->onion_key,
603 &(circ->cpath->dh_handshake_state),
604 payload) < 0) {
605 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
606 return - END_CIRC_REASON_INTERNAL;
608 note_request("cell: create", 1);
609 } else {
610 /* We are not an OR, and we're building the first hop of a circuit to a
611 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
612 * and a DH operation. */
613 cell_type = CELL_CREATE_FAST;
614 memset(payload, 0, sizeof(payload));
615 crypto_rand(circ->cpath->fast_handshake_state,
616 sizeof(circ->cpath->fast_handshake_state));
617 memcpy(payload, circ->cpath->fast_handshake_state,
618 sizeof(circ->cpath->fast_handshake_state));
619 note_request("cell: create fast", 1);
622 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
623 return - END_CIRC_REASON_RESOURCELIMIT;
625 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
626 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
627 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
628 fast ? "CREATE_FAST" : "CREATE",
629 router ? router->nickname : "<unnamed>");
630 } else {
631 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
632 tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
633 log_debug(LD_CIRC,"starting to send subsequent skin.");
634 hop = onion_next_hop_in_cpath(circ->cpath);
635 if (!hop) {
636 /* done building the circuit. whew. */
637 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
638 log_info(LD_CIRC,"circuit built!");
639 circuit_reset_failure_count(0);
640 if (circ->build_state->onehop_tunnel)
641 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
642 if (!has_completed_circuit && !circ->build_state->onehop_tunnel) {
643 or_options_t *options = get_options();
644 has_completed_circuit=1;
645 /* FFFF Log a count of known routers here */
646 log(LOG_NOTICE, LD_GENERAL,
647 "Tor has successfully opened a circuit. "
648 "Looks like client functionality is working.");
649 control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
650 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
651 if (server_mode(options) && !check_whether_orport_reachable()) {
652 inform_testing_reachability();
653 consider_testing_reachability(1, 1);
656 circuit_rep_hist_note_result(circ);
657 circuit_has_opened(circ); /* do other actions as necessary */
658 return 0;
661 if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
662 log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
663 return - END_CIRC_REASON_INTERNAL;
666 set_uint32(payload, tor_addr_to_ipv4n(&hop->extend_info->addr));
667 set_uint16(payload+4, htons(hop->extend_info->port));
669 onionskin = payload+2+4;
670 memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
671 hop->extend_info->identity_digest, DIGEST_LEN);
672 payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
674 if (onion_skin_create(hop->extend_info->onion_key,
675 &(hop->dh_handshake_state), onionskin) < 0) {
676 log_warn(LD_CIRC,"onion_skin_create failed.");
677 return - END_CIRC_REASON_INTERNAL;
680 log_info(LD_CIRC,"Sending extend relay cell.");
681 note_request("cell: extend", 1);
682 /* send it to hop->prev, because it will transfer
683 * it to a create cell and then send to hop */
684 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
685 RELAY_COMMAND_EXTEND,
686 payload, payload_len, hop->prev) < 0)
687 return 0; /* circuit is closed */
689 hop->state = CPATH_STATE_AWAITING_KEYS;
691 return 0;
694 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
695 * something has also gone wrong with our network: notify the user,
696 * and abandon all not-yet-used circuits. */
697 void
698 circuit_note_clock_jumped(int seconds_elapsed)
700 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
701 log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
702 "assuming established circuits no longer work.",
703 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
704 seconds_elapsed >=0 ? "forward" : "backward");
705 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
706 seconds_elapsed);
707 has_completed_circuit=0; /* so it'll log when it works again */
708 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
709 "CLOCK_JUMPED");
710 circuit_mark_all_unused_circs();
711 circuit_expire_all_dirty_circs();
714 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
715 * skin and identity digest for the next hop. If we're already connected,
716 * pass the onion skin to the next hop using a create cell; otherwise
717 * launch a new OR connection, and <b>circ</b> will notice when the
718 * connection succeeds or fails.
720 * Return -1 if we want to warn and tear down the circuit, else return 0.
723 circuit_extend(cell_t *cell, circuit_t *circ)
725 or_connection_t *n_conn;
726 relay_header_t rh;
727 char *onionskin;
728 char *id_digest=NULL;
729 uint32_t n_addr32;
730 uint16_t n_port;
731 tor_addr_t n_addr;
732 const char *msg = NULL;
733 int should_launch = 0;
735 if (circ->n_conn) {
736 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
737 "n_conn already set. Bug/attack. Closing.");
738 return -1;
740 if (circ->n_hop) {
741 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
742 "conn to next hop already launched. Bug/attack. Closing.");
743 return -1;
746 if (!server_mode(get_options())) {
747 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
748 "Got an extend cell, but running as a client. Closing.");
749 return -1;
752 relay_header_unpack(&rh, cell->payload);
754 if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
755 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
756 "Wrong length %d on extend cell. Closing circuit.",
757 rh.length);
758 return -1;
761 n_addr32 = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
762 n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
763 onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
764 id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
765 tor_addr_from_ipv4h(&n_addr, n_addr32);
767 if (!n_port || !n_addr32) {
768 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
769 "Client asked me to extend to zero destination port or addr.");
770 return -1;
773 /* Check if they asked us for 0000..0000. We support using
774 * an empty fingerprint for the first hop (e.g. for a bridge relay),
775 * but we don't want to let people send us extend cells for empty
776 * fingerprints -- a) because it opens the user up to a mitm attack,
777 * and b) because it lets an attacker force the relay to hold open a
778 * new TLS connection for each extend request. */
779 if (tor_digest_is_zero(id_digest)) {
780 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
781 "Client asked me to extend without specifying an id_digest.");
782 return -1;
785 /* Next, check if we're being asked to connect to the hop that the
786 * extend cell came from. There isn't any reason for that, and it can
787 * assist circular-path attacks. */
788 if (!memcmp(id_digest, TO_OR_CIRCUIT(circ)->p_conn->identity_digest,
789 DIGEST_LEN)) {
790 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
791 "Client asked me to extend back to the previous hop.");
792 return -1;
795 n_conn = connection_or_get_for_extend(id_digest,
796 &n_addr,
797 &msg,
798 &should_launch);
800 if (!n_conn) {
801 log_debug(LD_CIRC|LD_OR,"Next router (%s:%d): %s",
802 fmt_addr(&n_addr), (int)n_port, msg?msg:"????");
804 circ->n_hop = extend_info_alloc(NULL /*nickname*/,
805 id_digest,
806 NULL /*onion_key*/,
807 &n_addr, n_port);
809 circ->n_conn_onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
810 memcpy(circ->n_conn_onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
811 circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
813 if (should_launch) {
814 /* we should try to open a connection */
815 n_conn = connection_or_connect(&n_addr, n_port, id_digest);
816 if (!n_conn) {
817 log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
818 circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
819 return 0;
821 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
823 /* return success. The onion/circuit/etc will be taken care of
824 * automatically (may already have been) whenever n_conn reaches
825 * OR_CONN_STATE_OPEN.
827 return 0;
830 tor_assert(!circ->n_hop); /* Connection is already established. */
831 circ->n_conn = n_conn;
832 log_debug(LD_CIRC,"n_conn is %s:%u",
833 n_conn->_base.address,n_conn->_base.port);
835 if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
836 return -1;
837 return 0;
840 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
841 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
842 * used as follows:
843 * - 20 to initialize f_digest
844 * - 20 to initialize b_digest
845 * - 16 to key f_crypto
846 * - 16 to key b_crypto
848 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
851 circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
852 int reverse)
854 crypto_digest_env_t *tmp_digest;
855 crypto_cipher_env_t *tmp_crypto;
857 tor_assert(cpath);
858 tor_assert(key_data);
859 tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
860 cpath->f_digest || cpath->b_digest));
862 cpath->f_digest = crypto_new_digest_env();
863 crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
864 cpath->b_digest = crypto_new_digest_env();
865 crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
867 if (!(cpath->f_crypto =
868 crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
869 log_warn(LD_BUG,"Forward cipher initialization failed.");
870 return -1;
872 if (!(cpath->b_crypto =
873 crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
874 log_warn(LD_BUG,"Backward cipher initialization failed.");
875 return -1;
878 if (reverse) {
879 tmp_digest = cpath->f_digest;
880 cpath->f_digest = cpath->b_digest;
881 cpath->b_digest = tmp_digest;
882 tmp_crypto = cpath->f_crypto;
883 cpath->f_crypto = cpath->b_crypto;
884 cpath->b_crypto = tmp_crypto;
887 return 0;
890 /** A created or extended cell came back to us on the circuit, and it included
891 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
892 * contains (the second DH key, plus KH). If <b>reply_type</b> is
893 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
895 * Calculate the appropriate keys and digests, make sure KH is
896 * correct, and initialize this hop of the cpath.
898 * Return - reason if we want to mark circ for close, else return 0.
901 circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
902 const char *reply)
904 char keys[CPATH_KEY_MATERIAL_LEN];
905 crypt_path_t *hop;
907 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
908 hop = circ->cpath;
909 else {
910 hop = onion_next_hop_in_cpath(circ->cpath);
911 if (!hop) { /* got an extended when we're all done? */
912 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
913 return - END_CIRC_REASON_TORPROTOCOL;
916 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
918 if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
919 if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
920 DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
921 log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
922 return -END_CIRC_REASON_TORPROTOCOL;
924 /* Remember hash of g^xy */
925 memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
926 } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
927 if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
928 DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
929 log_warn(LD_CIRC,"fast_client_handshake failed.");
930 return -END_CIRC_REASON_TORPROTOCOL;
932 memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
933 } else {
934 log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
935 return -END_CIRC_REASON_TORPROTOCOL;
938 if (hop->dh_handshake_state) {
939 crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
940 hop->dh_handshake_state = NULL;
942 memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
944 if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
945 return -END_CIRC_REASON_TORPROTOCOL;
948 hop->state = CPATH_STATE_OPEN;
949 log_info(LD_CIRC,"Finished building %scircuit hop:",
950 (reply_type == CELL_CREATED_FAST) ? "fast " : "");
951 circuit_log_path(LOG_INFO,LD_CIRC,circ);
952 control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
954 return 0;
957 /** We received a relay truncated cell on circ.
959 * Since we don't ask for truncates currently, getting a truncated
960 * means that a connection broke or an extend failed. For now,
961 * just give up: for circ to close, and return 0.
964 circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
966 // crypt_path_t *victim;
967 // connection_t *stream;
969 tor_assert(circ);
970 tor_assert(layer);
972 /* XXX Since we don't ask for truncates currently, getting a truncated
973 * means that a connection broke or an extend failed. For now,
974 * just give up.
976 circuit_mark_for_close(TO_CIRCUIT(circ),
977 END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
978 return 0;
980 #if 0
981 while (layer->next != circ->cpath) {
982 /* we need to clear out layer->next */
983 victim = layer->next;
984 log_debug(LD_CIRC, "Killing a layer of the cpath.");
986 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
987 if (stream->cpath_layer == victim) {
988 log_info(LD_APP, "Marking stream %d for close because of truncate.",
989 stream->stream_id);
990 /* no need to send 'end' relay cells,
991 * because the other side's already dead
993 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
997 layer->next = victim->next;
998 circuit_free_cpath_node(victim);
1001 log_info(LD_CIRC, "finished");
1002 return 0;
1003 #endif
1006 /** Given a response payload and keys, initialize, then send a created
1007 * cell back.
1010 onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
1011 const char *keys)
1013 cell_t cell;
1014 crypt_path_t *tmp_cpath;
1016 tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
1017 tmp_cpath->magic = CRYPT_PATH_MAGIC;
1019 memset(&cell, 0, sizeof(cell_t));
1020 cell.command = cell_type;
1021 cell.circ_id = circ->p_circ_id;
1023 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
1025 memcpy(cell.payload, payload,
1026 cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
1028 log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
1029 (unsigned int)*(uint32_t*)(keys),
1030 (unsigned int)*(uint32_t*)(keys+20));
1031 if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
1032 log_warn(LD_BUG,"Circuit initialization failed");
1033 tor_free(tmp_cpath);
1034 return -1;
1036 circ->n_digest = tmp_cpath->f_digest;
1037 circ->n_crypto = tmp_cpath->f_crypto;
1038 circ->p_digest = tmp_cpath->b_digest;
1039 circ->p_crypto = tmp_cpath->b_crypto;
1040 tmp_cpath->magic = 0;
1041 tor_free(tmp_cpath);
1043 if (cell_type == CELL_CREATED)
1044 memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
1045 else
1046 memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
1048 circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
1050 append_cell_to_circuit_queue(TO_CIRCUIT(circ),
1051 circ->p_conn, &cell, CELL_DIRECTION_IN);
1052 log_debug(LD_CIRC,"Finished sending 'created' cell.");
1054 if (!is_local_addr(&circ->p_conn->_base.addr) &&
1055 !connection_or_nonopen_was_started_here(circ->p_conn)) {
1056 /* record that we could process create cells from a non-local conn
1057 * that we didn't initiate; presumably this means that create cells
1058 * can reach us too. */
1059 router_orport_found_reachable();
1062 return 0;
1065 /** Choose a length for a circuit of purpose <b>purpose</b>.
1066 * Default length is 3 + the number of endpoints that would give something
1067 * away. If the routerlist <b>routers</b> doesn't have enough routers
1068 * to handle the desired path length, return as large a path length as
1069 * is feasible, except if it's less than 2, in which case return -1.
1071 static int
1072 new_route_len(uint8_t purpose, extend_info_t *exit,
1073 smartlist_t *routers)
1075 int num_acceptable_routers;
1076 int routelen;
1078 tor_assert(routers);
1080 routelen = 3;
1081 if (exit &&
1082 purpose != CIRCUIT_PURPOSE_TESTING &&
1083 purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
1084 routelen++;
1086 num_acceptable_routers = count_acceptable_routers(routers);
1088 log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
1089 routelen, num_acceptable_routers, smartlist_len(routers));
1091 if (num_acceptable_routers < 2) {
1092 log_info(LD_CIRC,
1093 "Not enough acceptable routers (%d). Discarding this circuit.",
1094 num_acceptable_routers);
1095 return -1;
1098 if (num_acceptable_routers < routelen) {
1099 log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
1100 routelen, num_acceptable_routers);
1101 routelen = num_acceptable_routers;
1104 return routelen;
1107 /** Fetch the list of predicted ports, dup it into a smartlist of
1108 * uint16_t's, remove the ones that are already handled by an
1109 * existing circuit, and return it.
1111 static smartlist_t *
1112 circuit_get_unhandled_ports(time_t now)
1114 smartlist_t *source = rep_hist_get_predicted_ports(now);
1115 smartlist_t *dest = smartlist_create();
1116 uint16_t *tmp;
1117 int i;
1119 for (i = 0; i < smartlist_len(source); ++i) {
1120 tmp = tor_malloc(sizeof(uint16_t));
1121 memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
1122 smartlist_add(dest, tmp);
1125 circuit_remove_handled_ports(dest);
1126 return dest;
1129 /** Return 1 if we already have circuits present or on the way for
1130 * all anticipated ports. Return 0 if we should make more.
1132 * If we're returning 0, set need_uptime and need_capacity to
1133 * indicate any requirements that the unhandled ports have.
1136 circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
1137 int *need_capacity)
1139 int i, enough;
1140 uint16_t *port;
1141 smartlist_t *sl = circuit_get_unhandled_ports(now);
1142 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1143 tor_assert(need_uptime);
1144 tor_assert(need_capacity);
1145 enough = (smartlist_len(sl) == 0);
1146 for (i = 0; i < smartlist_len(sl); ++i) {
1147 port = smartlist_get(sl, i);
1148 if (smartlist_string_num_isin(LongLivedServices, *port))
1149 *need_uptime = 1;
1150 tor_free(port);
1152 smartlist_free(sl);
1153 return enough;
1156 /** Return 1 if <b>router</b> can handle one or more of the ports in
1157 * <b>needed_ports</b>, else return 0.
1159 static int
1160 router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
1162 int i;
1163 uint16_t port;
1165 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1166 addr_policy_result_t r;
1167 port = *(uint16_t *)smartlist_get(needed_ports, i);
1168 tor_assert(port);
1169 r = compare_addr_to_addr_policy(0, port, router->exit_policy);
1170 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1171 return 1;
1173 return 0;
1176 /** Return true iff <b>conn</b> needs another general circuit to be
1177 * built. */
1178 static int
1179 ap_stream_wants_exit_attention(connection_t *conn)
1181 if (conn->type == CONN_TYPE_AP &&
1182 conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1183 !conn->marked_for_close &&
1184 !(TO_EDGE_CONN(conn)->want_onehop) && /* ignore one-hop streams */
1185 !(TO_EDGE_CONN(conn)->use_begindir) && /* ignore targeted dir fetches */
1186 !(TO_EDGE_CONN(conn)->chosen_exit_name) && /* ignore defined streams */
1187 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1188 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
1189 MIN_CIRCUITS_HANDLING_STREAM))
1190 return 1;
1191 return 0;
1194 /** Return a pointer to a suitable router to be the exit node for the
1195 * general-purpose circuit we're about to build.
1197 * Look through the connection array, and choose a router that maximizes
1198 * the number of pending streams that can exit from this router.
1200 * Return NULL if we can't find any suitable routers.
1202 static routerinfo_t *
1203 choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
1204 int need_capacity)
1206 int *n_supported;
1207 int i;
1208 int n_pending_connections = 0;
1209 smartlist_t *connections;
1210 int best_support = -1;
1211 int n_best_support=0;
1212 routerinfo_t *router;
1213 or_options_t *options = get_options();
1215 connections = get_connection_array();
1217 /* Count how many connections are waiting for a circuit to be built.
1218 * We use this for log messages now, but in the future we may depend on it.
1220 SMARTLIST_FOREACH(connections, connection_t *, conn,
1222 if (ap_stream_wants_exit_attention(conn))
1223 ++n_pending_connections;
1225 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1226 // n_pending_connections);
1227 /* Now we count, for each of the routers in the directory, how many
1228 * of the pending connections could possibly exit from that
1229 * router (n_supported[i]). (We can't be sure about cases where we
1230 * don't know the IP address of the pending connection.)
1232 * -1 means "Don't use this router at all."
1234 n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
1235 for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
1236 router = smartlist_get(dir->routers, i);
1237 if (router_is_me(router)) {
1238 n_supported[i] = -1;
1239 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1240 /* XXX there's probably a reverse predecessor attack here, but
1241 * it's slow. should we take this out? -RD
1243 continue;
1245 if (!router->is_running || router->is_bad_exit) {
1246 n_supported[i] = -1;
1247 continue; /* skip routers that are known to be down or bad exits */
1249 if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
1250 n_supported[i] = -1;
1251 continue; /* skip routers that are not suitable */
1253 if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
1254 /* if it's invalid and we don't want it */
1255 n_supported[i] = -1;
1256 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1257 // router->nickname, i);
1258 continue; /* skip invalid routers */
1260 if (options->ExcludeSingleHopRelays && router->allow_single_hop_exits) {
1261 n_supported[i] = -1;
1262 continue;
1264 if (router_exit_policy_rejects_all(router)) {
1265 n_supported[i] = -1;
1266 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1267 // router->nickname, i);
1268 continue; /* skip routers that reject all */
1270 n_supported[i] = 0;
1271 /* iterate over connections */
1272 SMARTLIST_FOREACH(connections, connection_t *, conn,
1274 if (!ap_stream_wants_exit_attention(conn))
1275 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1276 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router)) {
1277 ++n_supported[i];
1278 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1279 // router->nickname, i, n_supported[i]);
1280 } else {
1281 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1282 // router->nickname, i);
1284 }); /* End looping over connections. */
1285 if (n_pending_connections > 0 && n_supported[i] == 0) {
1286 /* Leave best_support at -1 if that's where it is, so we can
1287 * distinguish it later. */
1288 continue;
1290 if (n_supported[i] > best_support) {
1291 /* If this router is better than previous ones, remember its index
1292 * and goodness, and start counting how many routers are this good. */
1293 best_support = n_supported[i]; n_best_support=1;
1294 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1295 // router->nickname);
1296 } else if (n_supported[i] == best_support) {
1297 /* If this router is _as good_ as the best one, just increment the
1298 * count of equally good routers.*/
1299 ++n_best_support;
1302 log_info(LD_CIRC,
1303 "Found %d servers that might support %d/%d pending connections.",
1304 n_best_support, best_support >= 0 ? best_support : 0,
1305 n_pending_connections);
1307 /* If any routers definitely support any pending connections, choose one
1308 * at random. */
1309 if (best_support > 0) {
1310 smartlist_t *supporting = smartlist_create(), *use = smartlist_create();
1312 for (i = 0; i < smartlist_len(dir->routers); i++)
1313 if (n_supported[i] == best_support)
1314 smartlist_add(supporting, smartlist_get(dir->routers, i));
1316 routersets_get_disjunction(use, supporting, options->ExitNodes,
1317 options->_ExcludeExitNodesUnion, 1);
1318 if (smartlist_len(use) == 0 && !options->StrictExitNodes) {
1319 routersets_get_disjunction(use, supporting, NULL,
1320 options->_ExcludeExitNodesUnion, 1);
1322 router = routerlist_sl_choose_by_bandwidth(use, WEIGHT_FOR_EXIT);
1323 smartlist_free(use);
1324 smartlist_free(supporting);
1325 } else {
1326 /* Either there are no pending connections, or no routers even seem to
1327 * possibly support any of them. Choose a router at random that satisfies
1328 * at least one predicted exit port. */
1330 int try;
1331 smartlist_t *needed_ports, *supporting, *use;
1333 if (best_support == -1) {
1334 if (need_uptime || need_capacity) {
1335 log_info(LD_CIRC,
1336 "We couldn't find any live%s%s routers; falling back "
1337 "to list of all routers.",
1338 need_capacity?", fast":"",
1339 need_uptime?", stable":"");
1340 tor_free(n_supported);
1341 return choose_good_exit_server_general(dir, 0, 0);
1343 log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
1344 "doomed exit at random.");
1346 supporting = smartlist_create();
1347 use = smartlist_create();
1348 needed_ports = circuit_get_unhandled_ports(time(NULL));
1349 for (try = 0; try < 2; try++) {
1350 /* try once to pick only from routers that satisfy a needed port,
1351 * then if there are none, pick from any that support exiting. */
1352 for (i = 0; i < smartlist_len(dir->routers); i++) {
1353 router = smartlist_get(dir->routers, i);
1354 if (n_supported[i] != -1 &&
1355 (try || router_handles_some_port(router, needed_ports))) {
1356 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1357 // try, router->nickname);
1358 smartlist_add(supporting, router);
1362 routersets_get_disjunction(use, supporting, options->ExitNodes,
1363 options->_ExcludeExitNodesUnion, 1);
1364 if (smartlist_len(use) == 0 && !options->StrictExitNodes) {
1365 routersets_get_disjunction(use, supporting, NULL,
1366 options->_ExcludeExitNodesUnion, 1);
1368 /* XXX sometimes the above results in null, when the requested
1369 * exit node is down. we should pick it anyway. */
1370 router = routerlist_sl_choose_by_bandwidth(use, WEIGHT_FOR_EXIT);
1371 if (router)
1372 break;
1373 smartlist_clear(supporting);
1374 smartlist_clear(use);
1376 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1377 smartlist_free(needed_ports);
1378 smartlist_free(use);
1379 smartlist_free(supporting);
1382 tor_free(n_supported);
1383 if (router) {
1384 log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
1385 return router;
1387 if (options->StrictExitNodes) {
1388 log_warn(LD_CIRC,
1389 "No specified exit routers seem to be running, and "
1390 "StrictExitNodes is set: can't choose an exit.");
1392 return NULL;
1395 /** Return a pointer to a suitable router to be the exit node for the
1396 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1397 * if no router is suitable).
1399 * For general-purpose circuits, pass it off to
1400 * choose_good_exit_server_general()
1402 * For client-side rendezvous circuits, choose a random node, weighted
1403 * toward the preferences in 'options'.
1405 static routerinfo_t *
1406 choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
1407 int need_uptime, int need_capacity, int is_internal)
1409 or_options_t *options = get_options();
1410 router_crn_flags_t flags = 0;
1411 if (need_uptime)
1412 flags |= CRN_NEED_UPTIME;
1413 if (need_capacity)
1414 flags |= CRN_NEED_CAPACITY;
1416 switch (purpose) {
1417 case CIRCUIT_PURPOSE_C_GENERAL:
1418 if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
1419 flags |= CRN_ALLOW_INVALID;
1420 if (is_internal) /* pick it like a middle hop */
1421 return router_choose_random_node(NULL, NULL,
1422 options->ExcludeNodes, flags);
1423 else
1424 return choose_good_exit_server_general(dir,need_uptime,need_capacity);
1425 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1426 if (options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS)
1427 flags |= CRN_ALLOW_INVALID;
1428 return router_choose_random_node(NULL, NULL,
1429 options->ExcludeNodes, flags);
1431 log_warn(LD_BUG,"Unhandled purpose %d", purpose);
1432 tor_fragile_assert();
1433 return NULL;
1436 /** Log a warning if the user specified an exit for the circuit that
1437 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1438 static void
1439 warn_if_router_excluded(const extend_info_t *exit)
1441 or_options_t *options = get_options();
1442 routerinfo_t *ri = router_get_by_digest(exit->identity_digest);
1444 if (!ri || !options->_ExcludeExitNodesUnion)
1445 return;
1447 if (routerset_contains_router(options->_ExcludeExitNodesUnion, ri))
1448 log_warn(LD_CIRC,"Requested exit node '%s' is in ExcludeNodes, "
1449 "or ExcludeExitNodes, using anyway.",exit->nickname);
1451 return;
1454 /** Decide a suitable length for circ's cpath, and pick an exit
1455 * router (or use <b>exit</b> if provided). Store these in the
1456 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1457 static int
1458 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
1460 cpath_build_state_t *state = circ->build_state;
1461 routerlist_t *rl = router_get_routerlist();
1463 if (state->onehop_tunnel) {
1464 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
1465 state->desired_path_len = 1;
1466 } else {
1467 int r = new_route_len(circ->_base.purpose, exit, rl->routers);
1468 if (r < 1) /* must be at least 1 */
1469 return -1;
1470 state->desired_path_len = r;
1473 if (exit) { /* the circuit-builder pre-requested one */
1474 warn_if_router_excluded(exit);
1475 log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
1476 exit = extend_info_dup(exit);
1477 } else { /* we have to decide one */
1478 routerinfo_t *router =
1479 choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
1480 state->need_capacity, state->is_internal);
1481 if (!router) {
1482 log_warn(LD_CIRC,"failed to choose an exit server");
1483 return -1;
1485 exit = extend_info_from_router(router);
1487 state->chosen_exit = exit;
1488 return 0;
1491 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1492 * hop to the cpath reflecting this. Don't send the next extend cell --
1493 * the caller will do this if it wants to.
1496 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1498 cpath_build_state_t *state;
1499 tor_assert(exit);
1500 tor_assert(circ);
1502 state = circ->build_state;
1503 tor_assert(state);
1504 if (state->chosen_exit)
1505 extend_info_free(state->chosen_exit);
1506 state->chosen_exit = extend_info_dup(exit);
1508 ++circ->build_state->desired_path_len;
1509 onion_append_hop(&circ->cpath, exit);
1510 return 0;
1513 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1514 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1515 * send the next extend cell to begin connecting to that hop.
1518 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1520 int err_reason = 0;
1521 circuit_append_new_exit(circ, exit);
1522 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
1523 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
1524 log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
1525 exit->nickname);
1526 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
1527 return -1;
1529 return 0;
1532 /** Return the number of routers in <b>routers</b> that are currently up
1533 * and available for building circuits through.
1535 static int
1536 count_acceptable_routers(smartlist_t *routers)
1538 int i, n;
1539 int num=0;
1540 routerinfo_t *r;
1542 n = smartlist_len(routers);
1543 for (i=0;i<n;i++) {
1544 r = smartlist_get(routers, i);
1545 // log_debug(LD_CIRC,
1546 // "Contemplating whether router %d (%s) is a new option.",
1547 // i, r->nickname);
1548 if (r->is_running == 0) {
1549 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1550 goto next_i_loop;
1552 if (r->is_valid == 0) {
1553 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1554 goto next_i_loop;
1555 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1556 * allows this node in some places, then we're getting an inaccurate
1557 * count. For now, be conservative and don't count it. But later we
1558 * should try to be smarter. */
1560 num++;
1561 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1562 next_i_loop:
1563 ; /* C requires an explicit statement after the label */
1566 return num;
1569 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1570 * This function is used to extend cpath by another hop.
1572 void
1573 onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
1575 if (*head_ptr) {
1576 new_hop->next = (*head_ptr);
1577 new_hop->prev = (*head_ptr)->prev;
1578 (*head_ptr)->prev->next = new_hop;
1579 (*head_ptr)->prev = new_hop;
1580 } else {
1581 *head_ptr = new_hop;
1582 new_hop->prev = new_hop->next = new_hop;
1586 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1587 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1588 * to length <b>cur_len</b> to decide a suitable middle hop for a
1589 * circuit. In particular, make sure we don't pick the exit node or its
1590 * family, and make sure we don't duplicate any previous nodes or their
1591 * families. */
1592 static routerinfo_t *
1593 choose_good_middle_server(uint8_t purpose,
1594 cpath_build_state_t *state,
1595 crypt_path_t *head,
1596 int cur_len)
1598 int i;
1599 routerinfo_t *r, *choice;
1600 crypt_path_t *cpath;
1601 smartlist_t *excluded;
1602 or_options_t *options = get_options();
1603 router_crn_flags_t flags = 0;
1604 tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
1605 purpose <= _CIRCUIT_PURPOSE_MAX);
1607 log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
1608 excluded = smartlist_create();
1609 if ((r = build_state_get_exit_router(state))) {
1610 smartlist_add(excluded, r);
1611 routerlist_add_family(excluded, r);
1613 for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
1614 if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
1615 smartlist_add(excluded, r);
1616 routerlist_add_family(excluded, r);
1620 if (state->need_uptime)
1621 flags |= CRN_NEED_UPTIME;
1622 if (state->need_capacity)
1623 flags |= CRN_NEED_CAPACITY;
1624 if (options->_AllowInvalid & ALLOW_INVALID_MIDDLE)
1625 flags |= CRN_ALLOW_INVALID;
1626 choice = router_choose_random_node(NULL,
1627 excluded, options->ExcludeNodes, flags);
1628 smartlist_free(excluded);
1629 return choice;
1632 /** Pick a good entry server for the circuit to be built according to
1633 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1634 * router (if we're an OR), and respect firewall settings; if we're
1635 * configured to use entry guards, return one.
1637 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1638 * guard, not for any particular circuit.
1640 static routerinfo_t *
1641 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
1643 routerinfo_t *r, *choice;
1644 smartlist_t *excluded;
1645 or_options_t *options = get_options();
1646 router_crn_flags_t flags = 0;
1648 if (state && options->UseEntryGuards &&
1649 (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
1650 return choose_random_entry(state);
1653 excluded = smartlist_create();
1655 if (state && (r = build_state_get_exit_router(state))) {
1656 smartlist_add(excluded, r);
1657 routerlist_add_family(excluded, r);
1659 if (firewall_is_fascist_or()) {
1660 /*XXXX This could slow things down a lot; use a smarter implementation */
1661 /* exclude all ORs that listen on the wrong port, if anybody notices. */
1662 routerlist_t *rl = router_get_routerlist();
1663 int i;
1665 for (i=0; i < smartlist_len(rl->routers); i++) {
1666 r = smartlist_get(rl->routers, i);
1667 if (!fascist_firewall_allows_or(r))
1668 smartlist_add(excluded, r);
1671 /* and exclude current entry guards, if applicable */
1672 if (options->UseEntryGuards && entry_guards) {
1673 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1675 if ((r = router_get_by_digest(entry->identity))) {
1676 smartlist_add(excluded, r);
1677 routerlist_add_family(excluded, r);
1682 if (state) {
1683 flags |= CRN_NEED_GUARD;
1684 if (state->need_uptime)
1685 flags |= CRN_NEED_UPTIME;
1686 if (state->need_capacity)
1687 flags |= CRN_NEED_CAPACITY;
1689 if (options->_AllowInvalid & ALLOW_INVALID_ENTRY)
1690 flags |= CRN_ALLOW_INVALID;
1692 choice = router_choose_random_node(
1693 NULL,
1694 excluded,
1695 options->ExcludeNodes,
1696 flags);
1697 smartlist_free(excluded);
1698 return choice;
1701 /** Return the first non-open hop in cpath, or return NULL if all
1702 * hops are open. */
1703 static crypt_path_t *
1704 onion_next_hop_in_cpath(crypt_path_t *cpath)
1706 crypt_path_t *hop = cpath;
1707 do {
1708 if (hop->state != CPATH_STATE_OPEN)
1709 return hop;
1710 hop = hop->next;
1711 } while (hop != cpath);
1712 return NULL;
1715 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1716 * based on <b>state</b>. Append the hop info to head_ptr.
1718 static int
1719 onion_extend_cpath(origin_circuit_t *circ)
1721 uint8_t purpose = circ->_base.purpose;
1722 cpath_build_state_t *state = circ->build_state;
1723 int cur_len = circuit_get_cpath_len(circ);
1724 extend_info_t *info = NULL;
1726 if (cur_len >= state->desired_path_len) {
1727 log_debug(LD_CIRC, "Path is complete: %d steps long",
1728 state->desired_path_len);
1729 return 1;
1732 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
1733 state->desired_path_len);
1735 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
1736 info = extend_info_dup(state->chosen_exit);
1737 } else if (cur_len == 0) { /* picking first node */
1738 routerinfo_t *r = choose_good_entry_server(purpose, state);
1739 if (r)
1740 info = extend_info_from_router(r);
1741 } else {
1742 routerinfo_t *r =
1743 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
1744 if (r)
1745 info = extend_info_from_router(r);
1748 if (!info) {
1749 log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
1750 "this circuit.", cur_len);
1751 return -1;
1754 log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
1755 info->nickname, cur_len+1, build_state_get_exit_nickname(state));
1757 onion_append_hop(&circ->cpath, info);
1758 extend_info_free(info);
1759 return 0;
1762 /** Create a new hop, annotate it with information about its
1763 * corresponding router <b>choice</b>, and append it to the
1764 * end of the cpath <b>head_ptr</b>. */
1765 static int
1766 onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
1768 crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
1770 /* link hop into the cpath, at the end. */
1771 onion_append_to_cpath(head_ptr, hop);
1773 hop->magic = CRYPT_PATH_MAGIC;
1774 hop->state = CPATH_STATE_CLOSED;
1776 hop->extend_info = extend_info_dup(choice);
1778 hop->package_window = CIRCWINDOW_START;
1779 hop->deliver_window = CIRCWINDOW_START;
1781 return 0;
1784 /** Allocate a new extend_info object based on the various arguments. */
1785 extend_info_t *
1786 extend_info_alloc(const char *nickname, const char *digest,
1787 crypto_pk_env_t *onion_key,
1788 const tor_addr_t *addr, uint16_t port)
1790 extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
1791 memcpy(info->identity_digest, digest, DIGEST_LEN);
1792 if (nickname)
1793 strlcpy(info->nickname, nickname, sizeof(info->nickname));
1794 if (onion_key)
1795 info->onion_key = crypto_pk_dup_key(onion_key);
1796 tor_addr_copy(&info->addr, addr);
1797 info->port = port;
1798 return info;
1801 /** Allocate and return a new extend_info_t that can be used to build a
1802 * circuit to or through the router <b>r</b>. */
1803 extend_info_t *
1804 extend_info_from_router(routerinfo_t *r)
1806 tor_addr_t addr;
1807 tor_assert(r);
1808 tor_addr_from_ipv4h(&addr, r->addr);
1809 return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
1810 r->onion_pkey, &addr, r->or_port);
1813 /** Release storage held by an extend_info_t struct. */
1814 void
1815 extend_info_free(extend_info_t *info)
1817 tor_assert(info);
1818 if (info->onion_key)
1819 crypto_free_pk_env(info->onion_key);
1820 tor_free(info);
1823 /** Allocate and return a new extend_info_t with the same contents as
1824 * <b>info</b>. */
1825 extend_info_t *
1826 extend_info_dup(extend_info_t *info)
1828 extend_info_t *newinfo;
1829 tor_assert(info);
1830 newinfo = tor_malloc(sizeof(extend_info_t));
1831 memcpy(newinfo, info, sizeof(extend_info_t));
1832 if (info->onion_key)
1833 newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
1834 else
1835 newinfo->onion_key = NULL;
1836 return newinfo;
1839 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1840 * If there is no chosen exit, or if we don't know the routerinfo_t for
1841 * the chosen exit, return NULL.
1843 routerinfo_t *
1844 build_state_get_exit_router(cpath_build_state_t *state)
1846 if (!state || !state->chosen_exit)
1847 return NULL;
1848 return router_get_by_digest(state->chosen_exit->identity_digest);
1851 /** Return the nickname for the chosen exit router in <b>state</b>. If
1852 * there is no chosen exit, or if we don't know the routerinfo_t for the
1853 * chosen exit, return NULL.
1855 const char *
1856 build_state_get_exit_nickname(cpath_build_state_t *state)
1858 if (!state || !state->chosen_exit)
1859 return NULL;
1860 return state->chosen_exit->nickname;
1863 /** Check whether the entry guard <b>e</b> is usable, given the directory
1864 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1865 * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
1866 * accordingly. Return true iff the entry guard's status changes.
1868 * If it's not usable, set *<b>reason</b> to a static string explaining why.
1870 /*XXXX take a routerstatus, not a routerinfo. */
1871 static int
1872 entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
1873 time_t now, or_options_t *options, const char **reason)
1875 char buf[HEX_DIGEST_LEN+1];
1876 int changed = 0;
1878 tor_assert(options);
1880 *reason = NULL;
1882 /* Do we want to mark this guard as bad? */
1883 if (!ri)
1884 *reason = "unlisted";
1885 else if (!ri->is_running)
1886 *reason = "down";
1887 else if (options->UseBridges && ri->purpose != ROUTER_PURPOSE_BRIDGE)
1888 *reason = "not a bridge";
1889 else if (!options->UseBridges && !ri->is_possible_guard &&
1890 !routerset_contains_router(options->EntryNodes,ri))
1891 *reason = "not recommended as a guard";
1892 else if (routerset_contains_router(options->ExcludeNodes, ri))
1893 *reason = "excluded";
1895 if (*reason && ! e->bad_since) {
1896 /* Router is newly bad. */
1897 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
1898 log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
1899 e->nickname, buf, *reason);
1901 e->bad_since = now;
1902 control_event_guard(e->nickname, e->identity, "BAD");
1903 changed = 1;
1904 } else if (!*reason && e->bad_since) {
1905 /* There's nothing wrong with the router any more. */
1906 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
1907 log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
1908 "marking as ok.", e->nickname, buf);
1910 e->bad_since = 0;
1911 control_event_guard(e->nickname, e->identity, "GOOD");
1912 changed = 1;
1914 return changed;
1917 /** Return true iff enough time has passed since we last tried to connect
1918 * to the unreachable guard <b>e</b> that we're willing to try again. */
1919 static int
1920 entry_is_time_to_retry(entry_guard_t *e, time_t now)
1922 long diff;
1923 if (e->last_attempted < e->unreachable_since)
1924 return 1;
1925 diff = now - e->unreachable_since;
1926 if (diff < 6*60*60)
1927 return now > (e->last_attempted + 60*60);
1928 else if (diff < 3*24*60*60)
1929 return now > (e->last_attempted + 4*60*60);
1930 else if (diff < 7*24*60*60)
1931 return now > (e->last_attempted + 18*60*60);
1932 else
1933 return now > (e->last_attempted + 36*60*60);
1936 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1937 * working well enough that we are willing to use it as an entry
1938 * right now. (Else return NULL.) In particular, it must be
1939 * - Listed as either up or never yet contacted;
1940 * - Present in the routerlist;
1941 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1942 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1943 * (This check is currently redundant with the Guard flag, but in
1944 * the future that might change. Best to leave it in for now.)
1945 * - Allowed by our current ReachableORAddresses config option; and
1946 * - Currently thought to be reachable by us (unless assume_reachable
1947 * is true).
1949 static INLINE routerinfo_t *
1950 entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
1951 int assume_reachable)
1953 routerinfo_t *r;
1954 if (e->bad_since)
1955 return NULL;
1956 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1957 if (!assume_reachable && !e->can_retry &&
1958 e->unreachable_since && !entry_is_time_to_retry(e, time(NULL)))
1959 return NULL;
1960 r = router_get_by_digest(e->identity);
1961 if (!r)
1962 return NULL;
1963 if (get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_BRIDGE)
1964 return NULL;
1965 if (!get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_GENERAL)
1966 return NULL;
1967 if (router_is_unreliable(r, need_uptime, need_capacity, 0))
1968 return NULL;
1969 if (!fascist_firewall_allows_or(r))
1970 return NULL;
1971 return r;
1974 /** Return the number of entry guards that we think are usable. */
1975 static int
1976 num_live_entry_guards(void)
1978 int n = 0;
1979 if (! entry_guards)
1980 return 0;
1981 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1983 if (entry_is_live(entry, 0, 1, 0))
1984 ++n;
1986 return n;
1989 /** If <b>digest</b> matches the identity of any node in the
1990 * entry_guards list, return that node. Else return NULL. */
1991 static INLINE entry_guard_t *
1992 is_an_entry_guard(const char *digest)
1994 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1995 if (!memcmp(digest, entry->identity, DIGEST_LEN))
1996 return entry;
1998 return NULL;
2001 /** Dump a description of our list of entry guards to the log at level
2002 * <b>severity</b>. */
2003 static void
2004 log_entry_guards(int severity)
2006 smartlist_t *elements = smartlist_create();
2007 char buf[1024];
2008 char *s;
2010 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2012 tor_snprintf(buf, sizeof(buf), "%s (%s%s)",
2013 e->nickname,
2014 entry_is_live(e, 0, 1, 0) ? "up " : "down ",
2015 e->made_contact ? "made-contact" : "never-contacted");
2016 smartlist_add(elements, tor_strdup(buf));
2019 s = smartlist_join_strings(elements, ",", 0, NULL);
2020 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
2021 smartlist_free(elements);
2022 log_fn(severity,LD_CIRC,"%s",s);
2023 tor_free(s);
2026 /** Called when one or more guards that we would previously have used for some
2027 * purpose are no longer in use because a higher-priority guard has become
2028 * useable again. */
2029 static void
2030 control_event_guard_deferred(void)
2032 /* XXXX We don't actually have a good way to figure out _how many_ entries
2033 * are live for some purpose. We need an entry_is_even_slightly_live()
2034 * function for this to work right. NumEntryGuards isn't reliable: if we
2035 * need guards with weird properties, we can have more than that number
2036 * live.
2038 #if 0
2039 int n = 0;
2040 or_options_t *options = get_options();
2041 if (!entry_guards)
2042 return;
2043 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2045 if (entry_is_live(entry, 0, 1, 0)) {
2046 if (n++ == options->NumEntryGuards) {
2047 control_event_guard(entry->nickname, entry->identity, "DEFERRED");
2048 return;
2052 #endif
2055 /** Add a new (preferably stable and fast) router to our
2056 * entry_guards list. Return a pointer to the router if we succeed,
2057 * or NULL if we can't find any more suitable entries.
2059 * If <b>chosen</b> is defined, use that one, and if it's not
2060 * already in our entry_guards list, put it at the *beginning*.
2061 * Else, put the one we pick at the end of the list. */
2062 static routerinfo_t *
2063 add_an_entry_guard(routerinfo_t *chosen, int reset_status)
2065 routerinfo_t *router;
2066 entry_guard_t *entry;
2068 if (chosen) {
2069 router = chosen;
2070 entry = is_an_entry_guard(router->cache_info.identity_digest);
2071 if (entry) {
2072 if (reset_status) {
2073 entry->bad_since = 0;
2074 entry->can_retry = 1;
2076 return NULL;
2078 } else {
2079 router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
2080 if (!router)
2081 return NULL;
2083 entry = tor_malloc_zero(sizeof(entry_guard_t));
2084 log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
2085 strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
2086 memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
2087 entry->chosen_on_date = start_of_month(time(NULL));
2088 entry->chosen_by_version = tor_strdup(VERSION);
2089 if (chosen) /* prepend */
2090 smartlist_insert(entry_guards, 0, entry);
2091 else /* append */
2092 smartlist_add(entry_guards, entry);
2093 control_event_guard(entry->nickname, entry->identity, "NEW");
2094 control_event_guard_deferred();
2095 log_entry_guards(LOG_INFO);
2096 return router;
2099 /** If the use of entry guards is configured, choose more entry guards
2100 * until we have enough in the list. */
2101 static void
2102 pick_entry_guards(void)
2104 or_options_t *options = get_options();
2105 int changed = 0;
2107 tor_assert(entry_guards);
2109 while (num_live_entry_guards() < options->NumEntryGuards) {
2110 if (!add_an_entry_guard(NULL, 0))
2111 break;
2112 changed = 1;
2114 if (changed)
2115 entry_guards_changed();
2118 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2119 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2120 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2122 /** Release all storage held by <b>e</b>. */
2123 static void
2124 entry_guard_free(entry_guard_t *e)
2126 tor_assert(e);
2127 tor_free(e->chosen_by_version);
2128 tor_free(e);
2131 /** Remove any entry guard which was selected by an unknown version of Tor,
2132 * or which was selected by a version of Tor that's known to select
2133 * entry guards badly. */
2134 static int
2135 remove_obsolete_entry_guards(void)
2137 int changed = 0, i;
2138 time_t this_month = start_of_month(time(NULL));
2140 for (i = 0; i < smartlist_len(entry_guards); ++i) {
2141 entry_guard_t *entry = smartlist_get(entry_guards, i);
2142 const char *ver = entry->chosen_by_version;
2143 const char *msg = NULL;
2144 tor_version_t v;
2145 if (!ver) {
2146 msg = "does not say what version of Tor it was selected by";
2147 } else if (tor_version_parse(ver, &v)) {
2148 msg = "does not seem to be from any recognized version of Tor";
2149 } else if ((tor_version_as_new_as(ver, "0.1.0.10-alpha") &&
2150 !tor_version_as_new_as(ver, "0.1.2.16-dev")) ||
2151 (tor_version_as_new_as(ver, "0.2.0.0-alpha") &&
2152 !tor_version_as_new_as(ver, "0.2.0.6-alpha"))) {
2153 msg = "was selected without regard for guard bandwidth";
2154 } else if (entry->chosen_on_date + 3600*24*35 < this_month) {
2155 /* It's been more than a month, and probably more like two since
2156 * chosen_on_date is clipped to the beginning of its month. */
2157 msg = "was selected several months ago";
2160 if (msg) { /* we need to drop it */
2161 char dbuf[HEX_DIGEST_LEN+1];
2162 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
2163 log_notice(LD_CIRC, "Entry guard '%s' (%s) %s. (Version=%s.) "
2164 "Replacing it.",
2165 entry->nickname, dbuf, msg, ver?escaped(ver):"none");
2166 control_event_guard(entry->nickname, entry->identity, "DROPPED");
2167 entry_guard_free(entry);
2168 smartlist_del_keeporder(entry_guards, i--);
2169 log_entry_guards(LOG_INFO);
2170 changed = 1;
2174 return changed ? 1 : 0;
2177 /** Remove all entry guards that have been down or unlisted for so
2178 * long that we don't think they'll come up again. Return 1 if we
2179 * removed any, or 0 if we did nothing. */
2180 static int
2181 remove_dead_entry_guards(void)
2183 char dbuf[HEX_DIGEST_LEN+1];
2184 char tbuf[ISO_TIME_LEN+1];
2185 time_t now = time(NULL);
2186 int i;
2187 int changed = 0;
2189 for (i = 0; i < smartlist_len(entry_guards); ) {
2190 entry_guard_t *entry = smartlist_get(entry_guards, i);
2191 if (entry->bad_since &&
2192 entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
2194 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
2195 format_local_iso_time(tbuf, entry->bad_since);
2196 log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
2197 "since %s local time; removing.",
2198 entry->nickname, dbuf, tbuf);
2199 control_event_guard(entry->nickname, entry->identity, "DROPPED");
2200 entry_guard_free(entry);
2201 smartlist_del_keeporder(entry_guards, i);
2202 log_entry_guards(LOG_INFO);
2203 changed = 1;
2204 } else
2205 ++i;
2207 return changed ? 1 : 0;
2210 /** A new directory or router-status has arrived; update the down/listed
2211 * status of the entry guards.
2213 * An entry is 'down' if the directory lists it as nonrunning.
2214 * An entry is 'unlisted' if the directory doesn't include it.
2216 * Don't call this on startup; only on a fresh download. Otherwise we'll
2217 * think that things are unlisted.
2219 void
2220 entry_guards_compute_status(void)
2222 time_t now;
2223 int changed = 0;
2224 int severity = LOG_DEBUG;
2225 or_options_t *options;
2226 digestmap_t *reasons;
2227 if (! entry_guards)
2228 return;
2230 options = get_options();
2232 now = time(NULL);
2234 reasons = digestmap_new();
2235 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
2237 routerinfo_t *r = router_get_by_digest(entry->identity);
2238 const char *reason = NULL;
2239 if (entry_guard_set_status(entry, r, now, options, &reason))
2240 changed = 1;
2242 if (entry->bad_since)
2243 tor_assert(reason);
2244 if (reason)
2245 digestmap_set(reasons, entry->identity, (char*)reason);
2247 SMARTLIST_FOREACH_END(entry);
2249 if (remove_dead_entry_guards())
2250 changed = 1;
2252 severity = changed ? LOG_DEBUG : LOG_INFO;
2254 if (changed) {
2255 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
2256 const char *reason = digestmap_get(reasons, entry->identity);
2257 log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s%s%s, and %s.",
2258 entry->nickname,
2259 entry->unreachable_since ? "unreachable" : "reachable",
2260 entry->bad_since ? "unusable" : "usable",
2261 reason ? ", ": "",
2262 reason ? reason : "",
2263 entry_is_live(entry, 0, 1, 0) ? "live" : "not live");
2264 } SMARTLIST_FOREACH_END(entry);
2265 log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
2266 num_live_entry_guards(), smartlist_len(entry_guards));
2267 log_entry_guards(LOG_INFO);
2268 entry_guards_changed();
2271 digestmap_free(reasons, NULL);
2274 /** Called when a connection to an OR with the identity digest <b>digest</b>
2275 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2276 * If the OR is an entry, change that entry's up/down status.
2277 * Return 0 normally, or -1 if we want to tear down the new connection.
2279 * If <b>mark_relay_status</b>, also call router_set_status() on this
2280 * relay.
2282 * XXX022 change succeeded and mark_relay_status into 'int flags'.
2285 entry_guard_register_connect_status(const char *digest, int succeeded,
2286 int mark_relay_status, time_t now)
2288 int changed = 0;
2289 int refuse_conn = 0;
2290 int first_contact = 0;
2291 entry_guard_t *entry = NULL;
2292 int idx = -1;
2293 char buf[HEX_DIGEST_LEN+1];
2295 if (! entry_guards)
2296 return 0;
2298 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2300 if (!memcmp(e->identity, digest, DIGEST_LEN)) {
2301 entry = e;
2302 idx = e_sl_idx;
2303 break;
2307 if (!entry)
2308 return 0;
2310 base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
2312 if (succeeded) {
2313 if (entry->unreachable_since) {
2314 log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
2315 entry->nickname, buf);
2316 entry->can_retry = 0;
2317 entry->unreachable_since = 0;
2318 entry->last_attempted = now;
2319 control_event_guard(entry->nickname, entry->identity, "UP");
2320 changed = 1;
2322 if (!entry->made_contact) {
2323 entry->made_contact = 1;
2324 first_contact = changed = 1;
2326 } else { /* ! succeeded */
2327 if (!entry->made_contact) {
2328 /* We've never connected to this one. */
2329 log_info(LD_CIRC,
2330 "Connection to never-contacted entry guard '%s' (%s) failed. "
2331 "Removing from the list. %d/%d entry guards usable/new.",
2332 entry->nickname, buf,
2333 num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
2334 entry_guard_free(entry);
2335 smartlist_del_keeporder(entry_guards, idx);
2336 log_entry_guards(LOG_INFO);
2337 changed = 1;
2338 } else if (!entry->unreachable_since) {
2339 log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
2340 "Marking as unreachable.", entry->nickname, buf);
2341 entry->unreachable_since = entry->last_attempted = now;
2342 control_event_guard(entry->nickname, entry->identity, "DOWN");
2343 changed = 1;
2344 entry->can_retry = 0; /* We gave it an early chance; no good. */
2345 } else {
2346 char tbuf[ISO_TIME_LEN+1];
2347 format_iso_time(tbuf, entry->unreachable_since);
2348 log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
2349 "'%s' (%s). It has been unreachable since %s.",
2350 entry->nickname, buf, tbuf);
2351 entry->last_attempted = now;
2352 entry->can_retry = 0; /* We gave it an early chance; no good. */
2356 /* if the caller asked us to, also update the is_running flags for this
2357 * relay */
2358 if (mark_relay_status)
2359 router_set_status(digest, succeeded);
2361 if (first_contact) {
2362 /* We've just added a new long-term entry guard. Perhaps the network just
2363 * came back? We should give our earlier entries another try too,
2364 * and close this connection so we don't use it before we've given
2365 * the others a shot. */
2366 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
2367 if (e == entry)
2368 break;
2369 if (e->made_contact) {
2370 routerinfo_t *r = entry_is_live(e, 0, 1, 1);
2371 if (r && e->unreachable_since) {
2372 refuse_conn = 1;
2373 e->can_retry = 1;
2377 if (refuse_conn) {
2378 log_info(LD_CIRC,
2379 "Connected to new entry guard '%s' (%s). Marking earlier "
2380 "entry guards up. %d/%d entry guards usable/new.",
2381 entry->nickname, buf,
2382 num_live_entry_guards(), smartlist_len(entry_guards));
2383 log_entry_guards(LOG_INFO);
2384 changed = 1;
2388 if (changed)
2389 entry_guards_changed();
2390 return refuse_conn ? -1 : 0;
2393 /** When we try to choose an entry guard, should we parse and add
2394 * config's EntryNodes first? */
2395 static int should_add_entry_nodes = 0;
2397 /** Called when the value of EntryNodes changes in our configuration. */
2398 void
2399 entry_nodes_should_be_added(void)
2401 log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
2402 should_add_entry_nodes = 1;
2405 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2406 * of guard nodes, at the front. */
2407 static void
2408 entry_guards_prepend_from_config(void)
2410 or_options_t *options = get_options();
2411 smartlist_t *entry_routers, *entry_fps;
2412 smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
2413 tor_assert(entry_guards);
2415 should_add_entry_nodes = 0;
2417 if (!options->EntryNodes) {
2418 /* It's possible that a controller set EntryNodes, thus making
2419 * should_add_entry_nodes set, then cleared it again, all before the
2420 * call to choose_random_entry() that triggered us. If so, just return.
2422 return;
2425 if (options->EntryNodes) {
2426 char *string = routerset_to_string(options->EntryNodes);
2427 log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
2428 tor_free(string);
2431 entry_routers = smartlist_create();
2432 entry_fps = smartlist_create();
2433 old_entry_guards_on_list = smartlist_create();
2434 old_entry_guards_not_on_list = smartlist_create();
2436 /* Split entry guards into those on the list and those not. */
2438 /* XXXX022 Now that we allow countries and IP ranges in EntryNodes, this is
2439 * potentially an enormous list. For now, we disable such values for
2440 * EntryNodes in options_validate(); really, this wants a better solution.
2441 * Perhaps we should do this calculation once whenever the list of routers
2442 * changes or the entrynodes setting changes.
2444 routerset_get_all_routers(entry_routers, options->EntryNodes, 0);
2445 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
2446 smartlist_add(entry_fps,ri->cache_info.identity_digest));
2447 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
2448 if (smartlist_digest_isin(entry_fps, e->identity))
2449 smartlist_add(old_entry_guards_on_list, e);
2450 else
2451 smartlist_add(old_entry_guards_not_on_list, e);
2454 /* Remove all currently configured entry guards from entry_routers. */
2455 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
2456 if (is_an_entry_guard(ri->cache_info.identity_digest)) {
2457 SMARTLIST_DEL_CURRENT(entry_routers, ri);
2461 /* Now build the new entry_guards list. */
2462 smartlist_clear(entry_guards);
2463 /* First, the previously configured guards that are in EntryNodes. */
2464 smartlist_add_all(entry_guards, old_entry_guards_on_list);
2465 /* Next, the rest of EntryNodes */
2466 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
2467 add_an_entry_guard(ri, 0);
2469 /* Finally, the remaining EntryNodes, unless we're strict */
2470 if (options->StrictEntryNodes) {
2471 SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
2472 entry_guard_free(e));
2473 } else {
2474 smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
2477 smartlist_free(entry_routers);
2478 smartlist_free(entry_fps);
2479 smartlist_free(old_entry_guards_on_list);
2480 smartlist_free(old_entry_guards_not_on_list);
2481 entry_guards_changed();
2484 /** Return 1 if we're fine adding arbitrary routers out of the
2485 * directory to our entry guard list. Else return 0. */
2487 entry_list_can_grow(or_options_t *options)
2489 if (options->StrictEntryNodes)
2490 return 0;
2491 if (options->UseBridges)
2492 return 0;
2493 return 1;
2496 /** Pick a live (up and listed) entry guard from entry_guards. If
2497 * <b>state</b> is non-NULL, this is for a specific circuit --
2498 * make sure not to pick this circuit's exit or any node in the
2499 * exit's family. If <b>state</b> is NULL, we're looking for a random
2500 * guard (likely a bridge). */
2501 routerinfo_t *
2502 choose_random_entry(cpath_build_state_t *state)
2504 or_options_t *options = get_options();
2505 smartlist_t *live_entry_guards = smartlist_create();
2506 smartlist_t *exit_family = smartlist_create();
2507 routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
2508 routerinfo_t *r = NULL;
2509 int need_uptime = state ? state->need_uptime : 0;
2510 int need_capacity = state ? state->need_capacity : 0;
2511 int consider_exit_family = 0;
2513 if (chosen_exit) {
2514 smartlist_add(exit_family, chosen_exit);
2515 routerlist_add_family(exit_family, chosen_exit);
2516 consider_exit_family = 1;
2519 if (!entry_guards)
2520 entry_guards = smartlist_create();
2522 if (should_add_entry_nodes)
2523 entry_guards_prepend_from_config();
2525 if (entry_list_can_grow(options) &&
2526 (! entry_guards ||
2527 smartlist_len(entry_guards) < options->NumEntryGuards))
2528 pick_entry_guards();
2530 retry:
2531 smartlist_clear(live_entry_guards);
2532 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2534 r = entry_is_live(entry, need_uptime, need_capacity, 0);
2535 if (r && (!consider_exit_family || !smartlist_isin(exit_family, r))) {
2536 smartlist_add(live_entry_guards, r);
2537 if (!entry->made_contact) {
2538 /* Always start with the first not-yet-contacted entry
2539 * guard. Otherwise we might add several new ones, pick
2540 * the second new one, and now we've expanded our entry
2541 * guard list without needing to. */
2542 goto choose_and_finish;
2544 if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
2545 break; /* we have enough */
2549 /* Try to have at least 2 choices available. This way we don't
2550 * get stuck with a single live-but-crummy entry and just keep
2551 * using him.
2552 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2553 if (smartlist_len(live_entry_guards) < 2) {
2554 if (entry_list_can_grow(options)) {
2555 /* still no? try adding a new entry then */
2556 /* XXX if guard doesn't imply fast and stable, then we need
2557 * to tell add_an_entry_guard below what we want, or it might
2558 * be a long time til we get it. -RD */
2559 r = add_an_entry_guard(NULL, 0);
2560 if (r) {
2561 entry_guards_changed();
2562 /* XXX we start over here in case the new node we added shares
2563 * a family with our exit node. There's a chance that we'll just
2564 * load up on entry guards here, if the network we're using is
2565 * one big family. Perhaps we should teach add_an_entry_guard()
2566 * to understand nodes-to-avoid-if-possible? -RD */
2567 goto retry;
2570 if (!r && need_uptime) {
2571 need_uptime = 0; /* try without that requirement */
2572 goto retry;
2574 if (!r && need_capacity) {
2575 /* still no? last attempt, try without requiring capacity */
2576 need_capacity = 0;
2577 goto retry;
2579 if (!r && !entry_list_can_grow(options) && consider_exit_family) {
2580 /* still no? if we're using bridges or have strictentrynodes
2581 * set, and our chosen exit is in the same family as all our
2582 * bridges/entry guards, then be flexible about families. */
2583 consider_exit_family = 0;
2584 goto retry;
2586 /* live_entry_guards may be empty below. Oh well, we tried. */
2589 choose_and_finish:
2590 if (entry_list_can_grow(options)) {
2591 /* We choose uniformly at random here, because choose_good_entry_server()
2592 * already weights its choices by bandwidth, so we don't want to
2593 * *double*-weight our guard selection. */
2594 r = smartlist_choose(live_entry_guards);
2595 } else {
2596 /* We need to weight by bandwidth, because our bridges or entryguards
2597 * were not already selected proportional to their bandwidth. */
2598 r = routerlist_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
2600 smartlist_free(live_entry_guards);
2601 smartlist_free(exit_family);
2602 return r;
2605 /** Helper: Return the start of the month containing <b>time</b>. */
2606 static time_t
2607 start_of_month(time_t now)
2609 struct tm tm;
2610 tor_gmtime_r(&now, &tm);
2611 tm.tm_sec = 0;
2612 tm.tm_min = 0;
2613 tm.tm_hour = 0;
2614 tm.tm_mday = 1;
2615 return tor_timegm(&tm);
2618 /** Parse <b>state</b> and learn about the entry guards it describes.
2619 * If <b>set</b> is true, and there are no errors, replace the global
2620 * entry_list with what we find.
2621 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2622 * describing the error, and return -1.
2625 entry_guards_parse_state(or_state_t *state, int set, char **msg)
2627 entry_guard_t *node = NULL;
2628 smartlist_t *new_entry_guards = smartlist_create();
2629 config_line_t *line;
2630 time_t now = time(NULL);
2631 const char *state_version = state->TorVersion;
2632 digestmap_t *added_by = digestmap_new();
2634 *msg = NULL;
2635 for (line = state->EntryGuards; line; line = line->next) {
2636 if (!strcasecmp(line->key, "EntryGuard")) {
2637 smartlist_t *args = smartlist_create();
2638 node = tor_malloc_zero(sizeof(entry_guard_t));
2639 /* all entry guards on disk have been contacted */
2640 node->made_contact = 1;
2641 smartlist_add(new_entry_guards, node);
2642 smartlist_split_string(args, line->value, " ",
2643 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2644 if (smartlist_len(args)<2) {
2645 *msg = tor_strdup("Unable to parse entry nodes: "
2646 "Too few arguments to EntryGuard");
2647 } else if (!is_legal_nickname(smartlist_get(args,0))) {
2648 *msg = tor_strdup("Unable to parse entry nodes: "
2649 "Bad nickname for EntryGuard");
2650 } else {
2651 strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
2652 if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
2653 strlen(smartlist_get(args,1)))<0) {
2654 *msg = tor_strdup("Unable to parse entry nodes: "
2655 "Bad hex digest for EntryGuard");
2658 SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
2659 smartlist_free(args);
2660 if (*msg)
2661 break;
2662 } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
2663 !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
2664 time_t when;
2665 time_t last_try = 0;
2666 if (!node) {
2667 *msg = tor_strdup("Unable to parse entry nodes: "
2668 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2669 break;
2671 if (parse_iso_time(line->value, &when)<0) {
2672 *msg = tor_strdup("Unable to parse entry nodes: "
2673 "Bad time in EntryGuardDownSince/UnlistedSince");
2674 break;
2676 if (when > now) {
2677 /* It's a bad idea to believe info in the future: you can wind
2678 * up with timeouts that aren't allowed to happen for years. */
2679 continue;
2681 if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
2682 /* ignore failure */
2683 (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
2685 if (!strcasecmp(line->key, "EntryGuardDownSince")) {
2686 node->unreachable_since = when;
2687 node->last_attempted = last_try;
2688 } else {
2689 node->bad_since = when;
2691 } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
2692 char d[DIGEST_LEN];
2693 /* format is digest version date */
2694 if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
2695 log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
2696 continue;
2698 if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
2699 line->value[HEX_DIGEST_LEN] != ' ') {
2700 log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
2701 "hex digest", escaped(line->value));
2702 continue;
2704 digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
2705 } else {
2706 log_warn(LD_BUG, "Unexpected key %s", line->key);
2710 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
2712 char *sp;
2713 char *val = digestmap_get(added_by, e->identity);
2714 if (val && (sp = strchr(val, ' '))) {
2715 time_t when;
2716 *sp++ = '\0';
2717 if (parse_iso_time(sp, &when)<0) {
2718 log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
2719 } else {
2720 e->chosen_by_version = tor_strdup(val);
2721 e->chosen_on_date = when;
2723 } else {
2724 if (state_version) {
2725 e->chosen_by_version = tor_strdup(state_version);
2726 e->chosen_on_date = start_of_month(time(NULL));
2731 if (*msg || !set) {
2732 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
2733 entry_guard_free(e));
2734 smartlist_free(new_entry_guards);
2735 } else { /* !err && set */
2736 if (entry_guards) {
2737 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2738 entry_guard_free(e));
2739 smartlist_free(entry_guards);
2741 entry_guards = new_entry_guards;
2742 entry_guards_dirty = 0;
2743 /* XXX022 hand new_entry_guards to this func, and move it up a
2744 * few lines, so we don't have to re-dirty it */
2745 if (remove_obsolete_entry_guards())
2746 entry_guards_dirty = 1;
2748 digestmap_free(added_by, _tor_free);
2749 return *msg ? -1 : 0;
2752 /** Our list of entry guards has changed, or some element of one
2753 * of our entry guards has changed. Write the changes to disk within
2754 * the next few minutes.
2756 static void
2757 entry_guards_changed(void)
2759 time_t when;
2760 entry_guards_dirty = 1;
2762 /* or_state_save() will call entry_guards_update_state(). */
2763 when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
2764 or_state_mark_dirty(get_or_state(), when);
2767 /** If the entry guard info has not changed, do nothing and return.
2768 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2769 * a new one out of the global entry_guards list, and then mark
2770 * <b>state</b> dirty so it will get saved to disk.
2772 void
2773 entry_guards_update_state(or_state_t *state)
2775 config_line_t **next, *line;
2776 if (! entry_guards_dirty)
2777 return;
2779 config_free_lines(state->EntryGuards);
2780 next = &state->EntryGuards;
2781 *next = NULL;
2782 if (!entry_guards)
2783 entry_guards = smartlist_create();
2784 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2786 char dbuf[HEX_DIGEST_LEN+1];
2787 if (!e->made_contact)
2788 continue; /* don't write this one to disk */
2789 *next = line = tor_malloc_zero(sizeof(config_line_t));
2790 line->key = tor_strdup("EntryGuard");
2791 line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
2792 base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
2793 tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
2794 "%s %s", e->nickname, dbuf);
2795 next = &(line->next);
2796 if (e->unreachable_since) {
2797 *next = line = tor_malloc_zero(sizeof(config_line_t));
2798 line->key = tor_strdup("EntryGuardDownSince");
2799 line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
2800 format_iso_time(line->value, e->unreachable_since);
2801 if (e->last_attempted) {
2802 line->value[ISO_TIME_LEN] = ' ';
2803 format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
2805 next = &(line->next);
2807 if (e->bad_since) {
2808 *next = line = tor_malloc_zero(sizeof(config_line_t));
2809 line->key = tor_strdup("EntryGuardUnlistedSince");
2810 line->value = tor_malloc(ISO_TIME_LEN+1);
2811 format_iso_time(line->value, e->bad_since);
2812 next = &(line->next);
2814 if (e->chosen_on_date && e->chosen_by_version &&
2815 !strchr(e->chosen_by_version, ' ')) {
2816 char d[HEX_DIGEST_LEN+1];
2817 char t[ISO_TIME_LEN+1];
2818 size_t val_len;
2819 *next = line = tor_malloc_zero(sizeof(config_line_t));
2820 line->key = tor_strdup("EntryGuardAddedBy");
2821 val_len = (HEX_DIGEST_LEN+1+strlen(e->chosen_by_version)
2822 +1+ISO_TIME_LEN+1);
2823 line->value = tor_malloc(val_len);
2824 base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
2825 format_iso_time(t, e->chosen_on_date);
2826 tor_snprintf(line->value, val_len, "%s %s %s",
2827 d, e->chosen_by_version, t);
2828 next = &(line->next);
2831 if (!get_options()->AvoidDiskWrites)
2832 or_state_mark_dirty(get_or_state(), 0);
2833 entry_guards_dirty = 0;
2836 /** If <b>question</b> is the string "entry-guards", then dump
2837 * to *<b>answer</b> a newly allocated string describing all of
2838 * the nodes in the global entry_guards list. See control-spec.txt
2839 * for details.
2840 * For backward compatibility, we also handle the string "helper-nodes".
2841 * */
2843 getinfo_helper_entry_guards(control_connection_t *conn,
2844 const char *question, char **answer)
2846 int use_long_names = conn->use_long_names;
2848 if (!strcmp(question,"entry-guards") ||
2849 !strcmp(question,"helper-nodes")) {
2850 smartlist_t *sl = smartlist_create();
2851 char tbuf[ISO_TIME_LEN+1];
2852 char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
2853 if (!entry_guards)
2854 entry_guards = smartlist_create();
2855 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2857 size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
2858 char *c = tor_malloc(len);
2859 const char *status = NULL;
2860 time_t when = 0;
2861 if (!e->made_contact) {
2862 status = "never-connected";
2863 } else if (e->bad_since) {
2864 when = e->bad_since;
2865 status = "unusable";
2866 } else {
2867 status = "up";
2869 if (use_long_names) {
2870 routerinfo_t *ri = router_get_by_digest(e->identity);
2871 if (ri) {
2872 router_get_verbose_nickname(nbuf, ri);
2873 } else {
2874 nbuf[0] = '$';
2875 base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
2876 /* e->nickname field is not very reliable if we don't know about
2877 * this router any longer; don't include it. */
2879 } else {
2880 base16_encode(nbuf, sizeof(nbuf), e->identity, DIGEST_LEN);
2882 if (when) {
2883 format_iso_time(tbuf, when);
2884 tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
2885 } else {
2886 tor_snprintf(c, len, "%s %s\n", nbuf, status);
2888 smartlist_add(sl, c);
2890 *answer = smartlist_join_strings(sl, "", 0, NULL);
2891 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
2892 smartlist_free(sl);
2894 return 0;
2897 /** Information about a configured bridge. Currently this just matches the
2898 * ones in the torrc file, but one day we may be able to learn about new
2899 * bridges on our own, and remember them in the state file. */
2900 typedef struct {
2901 /** Address of the bridge. */
2902 tor_addr_t addr;
2903 /** TLS port for the bridge. */
2904 uint16_t port;
2905 /** Expected identity digest, or all zero bytes if we don't know what the
2906 * digest should be. */
2907 char identity[DIGEST_LEN];
2908 /** When should we next try to fetch a descriptor for this bridge? */
2909 download_status_t fetch_status;
2910 } bridge_info_t;
2912 /** A list of configured bridges. Whenever we actually get a descriptor
2913 * for one, we add it as an entry guard. */
2914 static smartlist_t *bridge_list = NULL;
2916 /** Initialize the bridge list to empty, creating it if needed. */
2917 void
2918 clear_bridge_list(void)
2920 if (!bridge_list)
2921 bridge_list = smartlist_create();
2922 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
2923 smartlist_clear(bridge_list);
2926 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2927 * (either by comparing keys if possible, else by comparing addr/port).
2928 * Else return NULL. */
2929 static bridge_info_t *
2930 routerinfo_get_configured_bridge(routerinfo_t *ri)
2932 if (!bridge_list)
2933 return NULL;
2934 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
2936 if (tor_digest_is_zero(bridge->identity) &&
2937 tor_addr_eq_ipv4h(&bridge->addr, ri->addr) &&
2938 bridge->port == ri->or_port)
2939 return bridge;
2940 if (!memcmp(bridge->identity, ri->cache_info.identity_digest,
2941 DIGEST_LEN))
2942 return bridge;
2944 SMARTLIST_FOREACH_END(bridge);
2945 return NULL;
2948 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
2950 routerinfo_is_a_configured_bridge(routerinfo_t *ri)
2952 return routerinfo_get_configured_bridge(ri) ? 1 : 0;
2955 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2956 * is set, it tells us the identity key too. */
2957 void
2958 bridge_add_from_config(const tor_addr_t *addr, uint16_t port, char *digest)
2960 bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
2961 tor_addr_copy(&b->addr, addr);
2962 b->port = port;
2963 if (digest)
2964 memcpy(b->identity, digest, DIGEST_LEN);
2965 b->fetch_status.schedule = DL_SCHED_BRIDGE;
2966 if (!bridge_list)
2967 bridge_list = smartlist_create();
2968 smartlist_add(bridge_list, b);
2971 /** If <b>digest</b> is one of our known bridges, return it. */
2972 static bridge_info_t *
2973 find_bridge_by_digest(const char *digest)
2975 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2977 if (!memcmp(bridge->identity, digest, DIGEST_LEN))
2978 return bridge;
2980 return NULL;
2983 /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
2984 * is a helpful string describing this bridge. */
2985 static void
2986 launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
2988 char *address;
2990 if (connection_get_by_type_addr_port_purpose(
2991 CONN_TYPE_DIR, &bridge->addr, bridge->port,
2992 DIR_PURPOSE_FETCH_SERVERDESC))
2993 return; /* it's already on the way */
2995 address = tor_dup_addr(&bridge->addr);
2996 directory_initiate_command(address, &bridge->addr,
2997 bridge->port, 0,
2998 0, /* does not matter */
2999 1, bridge->identity,
3000 DIR_PURPOSE_FETCH_SERVERDESC,
3001 ROUTER_PURPOSE_BRIDGE,
3002 0, "authority.z", NULL, 0, 0);
3003 tor_free(address);
3006 /** Fetching the bridge descriptor from the bridge authority returned a
3007 * "not found". Fall back to trying a direct fetch. */
3008 void
3009 retry_bridge_descriptor_fetch_directly(const char *digest)
3011 bridge_info_t *bridge = find_bridge_by_digest(digest);
3012 if (!bridge)
3013 return; /* not found? oh well. */
3015 launch_direct_bridge_descriptor_fetch(bridge);
3018 /** For each bridge in our list for which we don't currently have a
3019 * descriptor, fetch a new copy of its descriptor -- either directly
3020 * from the bridge or via a bridge authority. */
3021 void
3022 fetch_bridge_descriptors(time_t now)
3024 or_options_t *options = get_options();
3025 int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
3026 int ask_bridge_directly;
3027 int can_use_bridge_authority;
3029 if (!bridge_list)
3030 return;
3032 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
3034 if (!download_status_is_ready(&bridge->fetch_status, now,
3035 IMPOSSIBLE_TO_DOWNLOAD))
3036 continue; /* don't bother, no need to retry yet */
3038 /* schedule another fetch as if this one will fail, in case it does */
3039 download_status_failed(&bridge->fetch_status, 0);
3041 can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
3042 num_bridge_auths;
3043 ask_bridge_directly = !can_use_bridge_authority ||
3044 !options->UpdateBridgesFromAuthority;
3045 log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
3046 ask_bridge_directly, tor_digest_is_zero(bridge->identity),
3047 !options->UpdateBridgesFromAuthority, !num_bridge_auths);
3049 if (ask_bridge_directly &&
3050 !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
3051 log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
3052 "firewall policy. %s.", fmt_addr(&bridge->addr),
3053 bridge->port,
3054 can_use_bridge_authority ?
3055 "Asking bridge authority instead" : "Skipping");
3056 if (can_use_bridge_authority)
3057 ask_bridge_directly = 0;
3058 else
3059 continue;
3062 if (ask_bridge_directly) {
3063 /* we need to ask the bridge itself for its descriptor. */
3064 launch_direct_bridge_descriptor_fetch(bridge);
3065 } else {
3066 /* We have a digest and we want to ask an authority. We could
3067 * combine all the requests into one, but that may give more
3068 * hints to the bridge authority than we want to give. */
3069 char resource[10 + HEX_DIGEST_LEN];
3070 memcpy(resource, "fp/", 3);
3071 base16_encode(resource+3, HEX_DIGEST_LEN+1,
3072 bridge->identity, DIGEST_LEN);
3073 memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
3074 log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
3075 resource);
3076 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
3077 ROUTER_PURPOSE_BRIDGE, resource, 0);
3080 SMARTLIST_FOREACH_END(bridge);
3083 /** We just learned a descriptor for a bridge. See if that
3084 * digest is in our entry guard list, and add it if not. */
3085 void
3086 learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
3088 tor_assert(ri);
3089 tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
3090 if (get_options()->UseBridges) {
3091 int first = !any_bridge_descriptors_known();
3092 bridge_info_t *bridge = routerinfo_get_configured_bridge(ri);
3093 time_t now = time(NULL);
3094 ri->is_running = 1;
3096 if (bridge) { /* if we actually want to use this one */
3097 /* it's here; schedule its re-fetch for a long time from now. */
3098 if (!from_cache)
3099 download_status_reset(&bridge->fetch_status);
3101 add_an_entry_guard(ri, 1);
3102 log_notice(LD_DIR, "new bridge descriptor '%s' (%s)", ri->nickname,
3103 from_cache ? "cached" : "fresh");
3104 if (first)
3105 routerlist_retry_directory_downloads(now);
3110 /** Return 1 if any of our entry guards have descriptors that
3111 * are marked with purpose 'bridge' and are running. Else return 0.
3113 * We use this function to decide if we're ready to start building
3114 * circuits through our bridges, or if we need to wait until the
3115 * directory "server/authority" requests finish. */
3117 any_bridge_descriptors_known(void)
3119 tor_assert(get_options()->UseBridges);
3120 return choose_random_entry(NULL)!=NULL ? 1 : 0;
3123 /** Return 1 if there are any directory conns fetching bridge descriptors
3124 * that aren't marked for close. We use this to guess if we should tell
3125 * the controller that we have a problem. */
3127 any_pending_bridge_descriptor_fetches(void)
3129 smartlist_t *conns = get_connection_array();
3130 SMARTLIST_FOREACH(conns, connection_t *, conn,
3132 if (conn->type == CONN_TYPE_DIR &&
3133 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
3134 TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
3135 !conn->marked_for_close &&
3136 conn->linked && !conn->linked_conn->marked_for_close) {
3137 log_debug(LD_DIR, "found one: %s", conn->address);
3138 return 1;
3141 return 0;
3144 /** Return 1 if we have at least one descriptor for a bridge and
3145 * all descriptors we know are down. Else return 0. If <b>act</b> is
3146 * 1, then mark the down bridges up; else just observe and report. */
3147 static int
3148 bridges_retry_helper(int act)
3150 routerinfo_t *ri;
3151 int any_known = 0;
3152 int any_running = 0;
3153 if (!entry_guards)
3154 entry_guards = smartlist_create();
3155 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
3157 ri = router_get_by_digest(e->identity);
3158 if (ri && ri->purpose == ROUTER_PURPOSE_BRIDGE) {
3159 any_known = 1;
3160 if (ri->is_running)
3161 any_running = 1; /* some bridge is both known and running */
3162 else if (act) { /* mark it for retry */
3163 ri->is_running = 1;
3164 e->can_retry = 1;
3165 e->bad_since = 0;
3169 log_debug(LD_DIR, "any_known %d, any_running %d", any_known, any_running);
3170 return any_known && !any_running;
3173 /** Do we know any descriptors for our bridges, and are they all
3174 * down? */
3176 bridges_known_but_down(void)
3178 return bridges_retry_helper(0);
3181 /** Mark all down known bridges up. */
3182 void
3183 bridges_retry_all(void)
3185 bridges_retry_helper(1);
3188 /** Release all storage held by the list of entry guards and related
3189 * memory structs. */
3190 void
3191 entry_guards_free_all(void)
3193 if (entry_guards) {
3194 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
3195 entry_guard_free(e));
3196 smartlist_free(entry_guards);
3197 entry_guards = NULL;
3199 clear_bridge_list();
3200 smartlist_free(bridge_list);
3201 bridge_list = NULL;