Fix a crash when we load a bridge descriptor from disk but we don't
[tor.git] / src / or / circuitbuild.c
blob6ca23b9d51cde4c621587606d31fd894c8902f8f
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, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char circuitbuild_c_id[] =
8 "$Id$";
10 /**
11 * \file circuitbuild.c
12 * \brief The actual details of building circuits.
13 **/
15 #include "or.h"
17 /********* START VARIABLES **********/
19 /** A global list of all circuits at this hop. */
20 extern circuit_t *global_circuitlist;
22 /** An entry_guard_t represents our information about a chosen long-term
23 * first hop, known as a "helper" node in the literature. We can't just
24 * use a routerinfo_t, since we want to remember these even when we
25 * don't have a directory. */
26 typedef struct {
27 char nickname[MAX_NICKNAME_LEN+1];
28 char identity[DIGEST_LEN];
29 time_t chosen_on_date; /**< Approximately when was this guard added?
30 * "0" if we don't know. */
31 char *chosen_by_version; /**< What tor version added this guard? NULL
32 * if we don't know. */
33 unsigned int made_contact : 1; /**< 0 if we have never connected to this
34 * router, 1 if we have. */
35 unsigned int can_retry : 1; /**< Should we retry connecting to this entry,
36 * in spite of having it marked as unreachable?*/
37 time_t bad_since; /**< 0 if this guard is currently usable, or the time at
38 * which it was observed to become (according to the
39 * directory or the user configuration) unusable. */
40 time_t unreachable_since; /**< 0 if we can connect to this guard, or the
41 * time at which we first noticed we couldn't
42 * connect to it. */
43 time_t last_attempted; /**< 0 if we can connect to this guard, or the time
44 * at which we last failed to connect to it. */
45 } entry_guard_t;
47 /** A list of our chosen entry guards. */
48 static smartlist_t *entry_guards = NULL;
49 /** A value of 1 means that the entry_guards list has changed
50 * and those changes need to be flushed to disk. */
51 static int entry_guards_dirty = 0;
53 /********* END VARIABLES ************/
55 static int circuit_deliver_create_cell(circuit_t *circ,
56 uint8_t cell_type, const char *payload);
57 static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
58 static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
59 static int onion_extend_cpath(origin_circuit_t *circ);
60 static int count_acceptable_routers(smartlist_t *routers);
61 static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
63 static void entry_guards_changed(void);
64 static time_t start_of_month(time_t when);
66 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
67 * and with the high bit specified by conn-\>circ_id_type, until we get
68 * a circ_id that is not in use by any other circuit on that conn.
70 * Return it, or 0 if can't get a unique circ_id.
72 static uint16_t
73 get_unique_circ_id_by_conn(or_connection_t *conn)
75 uint16_t test_circ_id;
76 uint16_t attempts=0;
77 uint16_t high_bit;
79 tor_assert(conn);
80 if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
81 log_warn(LD_BUG, "Trying to pick a circuit ID for a connection from "
82 "a client with no identity.");
83 return 0;
85 high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
86 do {
87 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
88 * circID such that (high_bit|test_circ_id) is not already used. */
89 test_circ_id = conn->next_circ_id++;
90 if (test_circ_id == 0 || test_circ_id >= 1<<15) {
91 test_circ_id = 1;
92 conn->next_circ_id = 2;
94 if (++attempts > 1<<15) {
95 /* Make sure we don't loop forever if all circ_id's are used. This
96 * matters because it's an external DoS opportunity.
98 log_warn(LD_CIRC,"No unused circ IDs. Failing.");
99 return 0;
101 test_circ_id |= high_bit;
102 } while (circuit_get_by_circid_orconn(test_circ_id, conn));
103 return test_circ_id;
106 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
107 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
108 * list information about link status in a more verbose format using spaces.
109 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
110 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
111 * names.
113 static char *
114 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
116 crypt_path_t *hop;
117 smartlist_t *elements;
118 const char *states[] = {"closed", "waiting for keys", "open"};
119 char buf[128];
120 char *s;
122 elements = smartlist_create();
124 if (verbose) {
125 const char *nickname = build_state_get_exit_nickname(circ->build_state);
126 tor_snprintf(buf, sizeof(buf), "%s%s circ (length %d%s%s):",
127 circ->build_state->is_internal ? "internal" : "exit",
128 circ->build_state->need_uptime ? " (high-uptime)" : "",
129 circ->build_state->desired_path_len,
130 circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", exit ",
131 circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
132 (nickname?nickname:"*unnamed*"));
133 smartlist_add(elements, tor_strdup(buf));
136 hop = circ->cpath;
137 do {
138 routerinfo_t *ri;
139 char *elt;
140 if (!hop)
141 break;
142 if (!verbose && hop->state != CPATH_STATE_OPEN)
143 break;
144 if (!hop->extend_info)
145 break;
146 if (verbose_names) {
147 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
148 if ((ri = router_get_by_digest(hop->extend_info->identity_digest))) {
149 router_get_verbose_nickname(elt, ri);
150 } else if (hop->extend_info->nickname &&
151 is_legal_nickname(hop->extend_info->nickname)) {
152 elt[0] = '$';
153 base16_encode(elt+1, HEX_DIGEST_LEN+1,
154 hop->extend_info->identity_digest, DIGEST_LEN);
155 elt[HEX_DIGEST_LEN+1]= '~';
156 strlcpy(elt+HEX_DIGEST_LEN+2,
157 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
158 } else {
159 elt[0] = '$';
160 base16_encode(elt+1, HEX_DIGEST_LEN+1,
161 hop->extend_info->identity_digest, DIGEST_LEN);
163 } else { /* ! verbose_names */
164 if ((ri = router_get_by_digest(hop->extend_info->identity_digest)) &&
165 ri->is_named) {
166 elt = tor_strdup(hop->extend_info->nickname);
167 } else {
168 elt = tor_malloc(HEX_DIGEST_LEN+2);
169 elt[0] = '$';
170 base16_encode(elt+1, HEX_DIGEST_LEN+1,
171 hop->extend_info->identity_digest, DIGEST_LEN);
174 tor_assert(elt);
175 if (verbose) {
176 size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
177 char *v = tor_malloc(len);
178 tor_assert(hop->state <= 2);
179 tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
180 smartlist_add(elements, v);
181 tor_free(elt);
182 } else {
183 smartlist_add(elements, elt);
185 hop = hop->next;
186 } while (hop != circ->cpath);
188 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
189 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
190 smartlist_free(elements);
191 return s;
194 /** If <b>verbose</b> is false, allocate and return a comma-separated
195 * list of the currently built elements of circuit_t. If
196 * <b>verbose</b> is true, also list information about link status in
197 * a more verbose format using spaces.
199 char *
200 circuit_list_path(origin_circuit_t *circ, int verbose)
202 return circuit_list_path_impl(circ, verbose, 0);
205 /** Allocate and return a comma-separated list of the currently built elements
206 * of circuit_t, giving each as a verbose nickname.
208 char *
209 circuit_list_path_for_controller(origin_circuit_t *circ)
211 return circuit_list_path_impl(circ, 0, 1);
214 /** Log, at severity <b>severity</b>, the nicknames of each router in
215 * circ's cpath. Also log the length of the cpath, and the intended
216 * exit point.
218 void
219 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
221 char *s = circuit_list_path(circ,1);
222 log(severity,domain,"%s",s);
223 tor_free(s);
226 /** Tell the rep(utation)hist(ory) module about the status of the links
227 * in circ. Hops that have become OPEN are marked as successfully
228 * extended; the _first_ hop that isn't open (if any) is marked as
229 * unable to extend.
231 /* XXXX Someday we should learn from OR circuits too. */
232 void
233 circuit_rep_hist_note_result(origin_circuit_t *circ)
235 crypt_path_t *hop;
236 char *prev_digest = NULL;
237 routerinfo_t *router;
238 hop = circ->cpath;
239 if (!hop) /* circuit hasn't started building yet. */
240 return;
241 if (server_mode(get_options())) {
242 routerinfo_t *me = router_get_my_routerinfo();
243 if (!me)
244 return;
245 prev_digest = me->cache_info.identity_digest;
247 do {
248 router = router_get_by_digest(hop->extend_info->identity_digest);
249 if (router) {
250 if (prev_digest) {
251 if (hop->state == CPATH_STATE_OPEN)
252 rep_hist_note_extend_succeeded(prev_digest,
253 router->cache_info.identity_digest);
254 else {
255 rep_hist_note_extend_failed(prev_digest,
256 router->cache_info.identity_digest);
257 break;
260 prev_digest = router->cache_info.identity_digest;
261 } else {
262 prev_digest = NULL;
264 hop=hop->next;
265 } while (hop!=circ->cpath);
268 /** Pick all the entries in our cpath. Stop and return 0 when we're
269 * happy, or return -1 if an error occurs. */
270 static int
271 onion_populate_cpath(origin_circuit_t *circ)
273 int r;
274 again:
275 r = onion_extend_cpath(circ);
276 if (r < 0) {
277 log_info(LD_CIRC,"Generating cpath hop failed.");
278 return -1;
280 if (r == 0)
281 goto again;
282 return 0; /* if r == 1 */
285 /** Create and return a new origin circuit. Initialize its purpose and
286 * build-state based on our arguments. */
287 origin_circuit_t *
288 origin_circuit_init(uint8_t purpose, int onehop_tunnel,
289 int need_uptime, int need_capacity, int internal)
291 /* sets circ->p_circ_id and circ->p_conn */
292 origin_circuit_t *circ = origin_circuit_new();
293 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
294 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
295 circ->build_state->onehop_tunnel = onehop_tunnel;
296 circ->build_state->need_uptime = need_uptime;
297 circ->build_state->need_capacity = need_capacity;
298 circ->build_state->is_internal = internal;
299 circ->_base.purpose = purpose;
300 return circ;
303 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
304 * is defined, then use that as your exit router, else choose a suitable
305 * exit node.
307 * Also launch a connection to the first OR in the chosen path, if
308 * it's not open already.
310 origin_circuit_t *
311 circuit_establish_circuit(uint8_t purpose, int onehop_tunnel,
312 extend_info_t *exit,
313 int need_uptime, int need_capacity, int internal)
315 origin_circuit_t *circ;
316 int err_reason = 0;
318 circ = origin_circuit_init(purpose, onehop_tunnel,
319 need_uptime, need_capacity, internal);
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 char tmpbuf[INET_NTOA_BUF_LEN];
346 struct in_addr in;
347 int err_reason = 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 in.s_addr = htonl(firsthop->extend_info->addr);
355 tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
356 log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",tmpbuf,
357 firsthop->extend_info->port);
358 /* imprint the circuit with its future n_conn->id */
359 memcpy(circ->_base.n_conn_id_digest, firsthop->extend_info->identity_digest,
360 DIGEST_LEN);
361 n_conn = connection_or_get_by_identity_digest(
362 firsthop->extend_info->identity_digest);
363 /* If we don't have an open conn, or the conn we have is obsolete
364 * (i.e. old or broken) and the other side will let us make a second
365 * connection without dropping it immediately... */
366 if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
367 (n_conn->_base.or_is_obsolete &&
368 router_digest_version_as_new_as(firsthop->extend_info->identity_digest,
369 "0.1.1.9-alpha-cvs"))) {
370 /* not currently connected */
371 circ->_base.n_addr = firsthop->extend_info->addr;
372 circ->_base.n_port = firsthop->extend_info->port;
374 if (!n_conn || n_conn->_base.or_is_obsolete) { /* launch the connection */
375 n_conn = connection_or_connect(firsthop->extend_info->addr,
376 firsthop->extend_info->port,
377 firsthop->extend_info->identity_digest);
378 if (!n_conn) { /* connect failed, forget the whole thing */
379 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
380 return -END_CIRC_REASON_CONNECTFAILED;
384 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
385 /* return success. The onion/circuit/etc will be taken care of
386 * automatically (may already have been) whenever n_conn reaches
387 * OR_CONN_STATE_OPEN.
389 return 0;
390 } else { /* it's already open. use it. */
391 circ->_base.n_addr = n_conn->_base.addr;
392 circ->_base.n_port = n_conn->_base.port;
393 circ->_base.n_conn = n_conn;
394 log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
395 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
396 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
397 return err_reason;
400 return 0;
403 /** Find any circuits that are waiting on <b>or_conn</b> to become
404 * open and get them to send their create cells forward.
406 * Status is 1 if connect succeeded, or 0 if connect failed.
408 void
409 circuit_n_conn_done(or_connection_t *or_conn, int status)
411 smartlist_t *pending_circs;
412 int err_reason = 0;
414 log_debug(LD_CIRC,"or_conn to %s, status=%d",
415 or_conn->nickname ? or_conn->nickname : "NULL", status);
417 pending_circs = smartlist_create();
418 circuit_get_all_pending_on_or_conn(pending_circs, or_conn);
420 SMARTLIST_FOREACH(pending_circs, circuit_t *, circ,
422 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
423 * leaving them in in case it's possible for the status of a circuit to
424 * change as we're going down the list. */
425 if (circ->marked_for_close || circ->n_conn ||
426 circ->state != CIRCUIT_STATE_OR_WAIT)
427 continue;
428 if (tor_digest_is_zero(circ->n_conn_id_digest)) {
429 /* Look at addr/port. This is an unkeyed connection. */
430 if (circ->n_addr != or_conn->_base.addr ||
431 circ->n_port != or_conn->_base.port)
432 continue;
433 /* now teach circ the right identity_digest */
434 memcpy(circ->n_conn_id_digest, or_conn->identity_digest, DIGEST_LEN);
435 } else {
436 /* We expected a key. See if it's the right one. */
437 if (memcmp(or_conn->identity_digest,
438 circ->n_conn_id_digest, DIGEST_LEN))
439 continue;
441 if (!status) { /* or_conn failed; close circ */
442 log_info(LD_CIRC,"or_conn failed. Closing circ.");
443 circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
444 continue;
446 log_debug(LD_CIRC, "Found circ, sending create cell.");
447 /* circuit_deliver_create_cell will set n_circ_id and add us to
448 * orconn_circuid_circuit_map, so we don't need to call
449 * set_circid_orconn here. */
450 circ->n_conn = or_conn;
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->onionskin);
464 if (circuit_deliver_create_cell(circ,CELL_CREATE,circ->onionskin)<0) {
465 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
466 continue;
468 tor_free(circ->onionskin);
469 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
473 smartlist_free(pending_circs);
476 /** Find a new circid that isn't currently in use on the circ->n_conn
477 * for the outgoing
478 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
479 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
480 * to this circuit.
481 * Return -1 if we failed to find a suitable circid, else return 0.
483 static int
484 circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
485 const char *payload)
487 cell_t cell;
488 uint16_t id;
490 tor_assert(circ);
491 tor_assert(circ->n_conn);
492 tor_assert(payload);
493 tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
495 id = get_unique_circ_id_by_conn(circ->n_conn);
496 if (!id) {
497 log_warn(LD_CIRC,"failed to get unique circID.");
498 return -1;
500 log_debug(LD_CIRC,"Chosen circID %u.", id);
501 circuit_set_n_circid_orconn(circ, id, circ->n_conn);
503 memset(&cell, 0, sizeof(cell_t));
504 cell.command = cell_type;
505 cell.circ_id = circ->n_circ_id;
507 memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
508 append_cell_to_circuit_queue(circ, circ->n_conn, &cell, CELL_DIRECTION_OUT);
510 if (CIRCUIT_IS_ORIGIN(circ)) {
511 /* mark it so it gets better rate limiting treatment. */
512 circ->n_conn->client_used = time(NULL);
515 return 0;
518 /** We've decided to start our reachability testing. If all
519 * is set, log this to the user. Return 1 if we did, or 0 if
520 * we chose not to log anything. */
522 inform_testing_reachability(void)
524 char dirbuf[128];
525 routerinfo_t *me = router_get_my_routerinfo();
526 if (!me)
527 return 0;
528 if (me->dir_port)
529 tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
530 me->address, me->dir_port);
531 log(LOG_NOTICE, LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
532 "(this may take up to %d minutes -- look for log "
533 "messages indicating success)",
534 me->address, me->or_port,
535 me->dir_port ? dirbuf : "",
536 me->dir_port ? "are" : "is",
537 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
538 return 1;
541 /** Return true iff we should send a create_fast cell to build a circuit
542 * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
543 * information on the router, so assume true.) */
544 static INLINE int
545 should_use_create_fast_for_router(routerinfo_t *router,
546 origin_circuit_t *circ)
548 or_options_t *options = get_options();
550 if (!options->FastFirstHopPK) /* create_fast is disabled */
551 return 0;
552 if (router && router->platform &&
553 !tor_version_as_new_as(router->platform, "0.1.0.6-rc")) {
554 /* known not to work */
555 return 0;
557 if (server_mode(options) && circ->cpath->extend_info->onion_key) {
558 /* We're a server, and we know an onion key. We can choose.
559 * Prefer to blend in. */
560 return 0;
563 return 1;
566 /** This is the backbone function for building circuits.
568 * If circ's first hop is closed, then we need to build a create
569 * cell and send it forward.
571 * Otherwise, we need to build a relay extend cell and send it
572 * forward.
574 * Return -reason if we want to tear down circ, else return 0.
577 circuit_send_next_onion_skin(origin_circuit_t *circ)
579 crypt_path_t *hop;
580 routerinfo_t *router;
581 char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
582 char *onionskin;
583 size_t payload_len;
585 tor_assert(circ);
587 if (circ->cpath->state == CPATH_STATE_CLOSED) {
588 int fast;
589 uint8_t cell_type;
590 log_debug(LD_CIRC,"First skin; sending create cell.");
592 router = router_get_by_digest(circ->_base.n_conn->identity_digest);
593 fast = should_use_create_fast_for_router(router, circ);
594 if (!fast && !circ->cpath->extend_info->onion_key) {
595 log_warn(LD_CIRC,
596 "Can't send create_fast, but have no onion key. Failing.");
597 return - END_CIRC_REASON_INTERNAL;
599 if (!fast) {
600 /* We are an OR, or we are connecting to an old Tor: we should
601 * send an old slow create cell.
603 cell_type = CELL_CREATE;
604 if (onion_skin_create(circ->cpath->extend_info->onion_key,
605 &(circ->cpath->dh_handshake_state),
606 payload) < 0) {
607 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
608 return - END_CIRC_REASON_INTERNAL;
610 } else {
611 /* We are not an OR, and we're building the first hop of a circuit to a
612 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
613 * and a DH operation. */
614 cell_type = CELL_CREATE_FAST;
615 memset(payload, 0, sizeof(payload));
616 crypto_rand(circ->cpath->fast_handshake_state,
617 sizeof(circ->cpath->fast_handshake_state));
618 memcpy(payload, circ->cpath->fast_handshake_state,
619 sizeof(circ->cpath->fast_handshake_state));
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 (!has_completed_circuit && !circ->build_state->onehop_tunnel) {
641 or_options_t *options = get_options();
642 has_completed_circuit=1;
643 /* FFFF Log a count of known routers here */
644 log(LOG_NOTICE, LD_GENERAL,
645 "Tor has successfully opened a circuit. "
646 "Looks like client functionality is working.");
647 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
648 if (server_mode(options) && !check_whether_orport_reachable()) {
649 inform_testing_reachability();
650 consider_testing_reachability(1, 1);
653 circuit_rep_hist_note_result(circ);
654 circuit_has_opened(circ); /* do other actions as necessary */
655 return 0;
658 set_uint32(payload, htonl(hop->extend_info->addr));
659 set_uint16(payload+4, htons(hop->extend_info->port));
661 onionskin = payload+2+4;
662 memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
663 hop->extend_info->identity_digest, DIGEST_LEN);
664 payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
666 if (onion_skin_create(hop->extend_info->onion_key,
667 &(hop->dh_handshake_state), onionskin) < 0) {
668 log_warn(LD_CIRC,"onion_skin_create failed.");
669 return - END_CIRC_REASON_INTERNAL;
672 log_info(LD_CIRC,"Sending extend relay cell.");
673 /* send it to hop->prev, because it will transfer
674 * it to a create cell and then send to hop */
675 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
676 RELAY_COMMAND_EXTEND,
677 payload, payload_len, hop->prev) < 0)
678 return 0; /* circuit is closed */
680 hop->state = CPATH_STATE_AWAITING_KEYS;
682 return 0;
685 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
686 * something has also gone wrong with our network: notify the user,
687 * and abandon all not-yet-used circuits. */
688 void
689 circuit_note_clock_jumped(int seconds_elapsed)
691 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
692 log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
693 "assuming established circuits no longer work.",
694 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
695 seconds_elapsed >=0 ? "forward" : "backward");
696 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
697 seconds_elapsed);
698 has_completed_circuit=0; /* so it'll log when it works again */
699 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
700 "CLOCK_JUMPED");
701 circuit_mark_all_unused_circs();
702 circuit_expire_all_dirty_circs();
705 /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
706 * sure we're connected to the next hop, and pass it the onion skin using
707 * a create cell. Return -1 if we want to warn and tear down the circuit,
708 * else return 0.
711 circuit_extend(cell_t *cell, circuit_t *circ)
713 or_connection_t *n_conn;
714 relay_header_t rh;
715 char *onionskin;
716 char *id_digest=NULL;
718 if (circ->n_conn) {
719 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
720 "n_conn already set. Bug/attack. Closing.");
721 return -1;
724 if (!server_mode(get_options())) {
725 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
726 "Got an extend cell, but running as a client. Closing.");
727 return -1;
730 relay_header_unpack(&rh, cell->payload);
732 if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
733 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
734 "Wrong length %d on extend cell. Closing circuit.",
735 rh.length);
736 return -1;
739 circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
740 circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
742 onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
743 id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
744 n_conn = connection_or_get_by_identity_digest(id_digest);
746 /* If we don't have an open conn, or the conn we have is obsolete
747 * (i.e. old or broken) and the other side will let us make a second
748 * connection without dropping it immediately... */
749 if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
750 (n_conn->_base.or_is_obsolete &&
751 router_digest_version_as_new_as(id_digest,"0.1.1.9-alpha-cvs"))) {
752 struct in_addr in;
753 char tmpbuf[INET_NTOA_BUF_LEN];
754 in.s_addr = htonl(circ->n_addr);
755 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
756 log_info(LD_CIRC|LD_OR,"Next router (%s:%d) not connected. Connecting.",
757 tmpbuf, circ->n_port);
759 circ->onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
760 memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
761 circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
763 /* imprint the circuit with its future n_conn->id */
764 memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
766 if (n_conn && !n_conn->_base.or_is_obsolete) {
767 circ->n_addr = n_conn->_base.addr;
768 circ->n_port = n_conn->_base.port;
769 } else {
770 /* we should try to open a connection */
771 n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
772 if (!n_conn) {
773 log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
774 circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
775 return 0;
777 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
779 /* return success. The onion/circuit/etc will be taken care of
780 * automatically (may already have been) whenever n_conn reaches
781 * OR_CONN_STATE_OPEN.
783 return 0;
786 /* these may be different if the router connected to us from elsewhere */
787 circ->n_addr = n_conn->_base.addr;
788 circ->n_port = n_conn->_base.port;
790 circ->n_conn = n_conn;
791 memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
792 log_debug(LD_CIRC,"n_conn is %s:%u",
793 n_conn->_base.address,n_conn->_base.port);
795 if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
796 return -1;
797 return 0;
800 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
801 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
802 * used as follows:
803 * - 20 to initialize f_digest
804 * - 20 to initialize b_digest
805 * - 16 to key f_crypto
806 * - 16 to key b_crypto
808 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
811 circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
812 int reverse)
814 crypto_digest_env_t *tmp_digest;
815 crypto_cipher_env_t *tmp_crypto;
817 tor_assert(cpath);
818 tor_assert(key_data);
819 tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
820 cpath->f_digest || cpath->b_digest));
822 cpath->f_digest = crypto_new_digest_env();
823 crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
824 cpath->b_digest = crypto_new_digest_env();
825 crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
827 if (!(cpath->f_crypto =
828 crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
829 log_warn(LD_BUG,"Forward cipher initialization failed.");
830 return -1;
832 if (!(cpath->b_crypto =
833 crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
834 log_warn(LD_BUG,"Backward cipher initialization failed.");
835 return -1;
838 if (reverse) {
839 tmp_digest = cpath->f_digest;
840 cpath->f_digest = cpath->b_digest;
841 cpath->b_digest = tmp_digest;
842 tmp_crypto = cpath->f_crypto;
843 cpath->f_crypto = cpath->b_crypto;
844 cpath->b_crypto = tmp_crypto;
847 return 0;
850 /** A created or extended cell came back to us on the circuit, and it included
851 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
852 * contains (the second DH key, plus KH). If <b>reply_type</b> is
853 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
855 * Calculate the appropriate keys and digests, make sure KH is
856 * correct, and initialize this hop of the cpath.
858 * Return - reason if we want to mark circ for close, else return 0.
861 circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
862 const char *reply)
864 char keys[CPATH_KEY_MATERIAL_LEN];
865 crypt_path_t *hop;
867 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
868 hop = circ->cpath;
869 else {
870 hop = onion_next_hop_in_cpath(circ->cpath);
871 if (!hop) { /* got an extended when we're all done? */
872 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
873 return - END_CIRC_REASON_TORPROTOCOL;
876 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
878 if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
879 if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
880 DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
881 log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
882 return -END_CIRC_REASON_TORPROTOCOL;
884 /* Remember hash of g^xy */
885 memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
886 } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
887 if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
888 DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
889 log_warn(LD_CIRC,"fast_client_handshake failed.");
890 return -END_CIRC_REASON_TORPROTOCOL;
892 memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
893 } else {
894 log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
895 return -END_CIRC_REASON_TORPROTOCOL;
898 if (hop->dh_handshake_state) {
899 crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
900 hop->dh_handshake_state = NULL;
902 memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
904 if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
905 return -END_CIRC_REASON_TORPROTOCOL;
908 hop->state = CPATH_STATE_OPEN;
909 log_info(LD_CIRC,"Finished building %scircuit hop:",
910 (reply_type == CELL_CREATED_FAST) ? "fast " : "");
911 circuit_log_path(LOG_INFO,LD_CIRC,circ);
912 control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
914 return 0;
917 /** We received a relay truncated cell on circ.
919 * Since we don't ask for truncates currently, getting a truncated
920 * means that a connection broke or an extend failed. For now,
921 * just give up: for circ to close, and return 0.
924 circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
926 // crypt_path_t *victim;
927 // connection_t *stream;
929 tor_assert(circ);
930 tor_assert(layer);
932 /* XXX Since we don't ask for truncates currently, getting a truncated
933 * means that a connection broke or an extend failed. For now,
934 * just give up.
936 circuit_mark_for_close(TO_CIRCUIT(circ),
937 END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
938 return 0;
940 #if 0
941 while (layer->next != circ->cpath) {
942 /* we need to clear out layer->next */
943 victim = layer->next;
944 log_debug(LD_CIRC, "Killing a layer of the cpath.");
946 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
947 if (stream->cpath_layer == victim) {
948 log_info(LD_APP, "Marking stream %d for close because of truncate.",
949 stream->stream_id);
950 /* no need to send 'end' relay cells,
951 * because the other side's already dead
953 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
957 layer->next = victim->next;
958 circuit_free_cpath_node(victim);
961 log_info(LD_CIRC, "finished");
962 return 0;
963 #endif
966 /** Given a response payload and keys, initialize, then send a created
967 * cell back.
970 onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
971 const char *keys)
973 cell_t cell;
974 crypt_path_t *tmp_cpath;
976 tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
977 tmp_cpath->magic = CRYPT_PATH_MAGIC;
979 memset(&cell, 0, sizeof(cell_t));
980 cell.command = cell_type;
981 cell.circ_id = circ->p_circ_id;
983 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
985 memcpy(cell.payload, payload,
986 cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
988 log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
989 (unsigned int)*(uint32_t*)(keys),
990 (unsigned int)*(uint32_t*)(keys+20));
991 if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
992 log_warn(LD_BUG,"Circuit initialization failed");
993 tor_free(tmp_cpath);
994 return -1;
996 circ->n_digest = tmp_cpath->f_digest;
997 circ->n_crypto = tmp_cpath->f_crypto;
998 circ->p_digest = tmp_cpath->b_digest;
999 circ->p_crypto = tmp_cpath->b_crypto;
1000 tmp_cpath->magic = 0;
1001 tor_free(tmp_cpath);
1003 if (cell_type == CELL_CREATED)
1004 memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
1005 else
1006 memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
1008 circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
1010 append_cell_to_circuit_queue(TO_CIRCUIT(circ),
1011 circ->p_conn, &cell, CELL_DIRECTION_IN);
1012 log_debug(LD_CIRC,"Finished sending 'created' cell.");
1014 if (!is_local_IP(circ->p_conn->_base.addr) &&
1015 !connection_or_nonopen_was_started_here(circ->p_conn)) {
1016 /* record that we could process create cells from a non-local conn
1017 * that we didn't initiate; presumably this means that create cells
1018 * can reach us too. */
1019 router_orport_found_reachable();
1022 return 0;
1025 /** Choose a length for a circuit of purpose <b>purpose</b>.
1026 * Default length is 3 + the number of endpoints that would give something
1027 * away. If the routerlist <b>routers</b> doesn't have enough routers
1028 * to handle the desired path length, return as large a path length as
1029 * is feasible, except if it's less than 2, in which case return -1.
1031 static int
1032 new_route_len(uint8_t purpose, extend_info_t *exit,
1033 smartlist_t *routers)
1035 int num_acceptable_routers;
1036 int routelen;
1038 tor_assert(routers);
1040 #ifdef TOR_PERF
1041 routelen = 2;
1042 #else
1043 routelen = 3;
1044 if (exit &&
1045 purpose != CIRCUIT_PURPOSE_TESTING &&
1046 purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
1047 routelen++;
1048 #endif
1049 log_debug(LD_CIRC,"Chosen route length %d (%d routers available).",
1050 routelen, smartlist_len(routers));
1052 num_acceptable_routers = count_acceptable_routers(routers);
1054 if (num_acceptable_routers < 2) {
1055 log_info(LD_CIRC,
1056 "Not enough acceptable routers (%d). Discarding this circuit.",
1057 num_acceptable_routers);
1058 return -1;
1061 if (num_acceptable_routers < routelen) {
1062 log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
1063 routelen, num_acceptable_routers);
1064 routelen = num_acceptable_routers;
1067 return routelen;
1070 /** Fetch the list of predicted ports, dup it into a smartlist of
1071 * uint16_t's, remove the ones that are already handled by an
1072 * existing circuit, and return it.
1074 static smartlist_t *
1075 circuit_get_unhandled_ports(time_t now)
1077 smartlist_t *source = rep_hist_get_predicted_ports(now);
1078 smartlist_t *dest = smartlist_create();
1079 uint16_t *tmp;
1080 int i;
1082 for (i = 0; i < smartlist_len(source); ++i) {
1083 tmp = tor_malloc(sizeof(uint16_t));
1084 memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
1085 smartlist_add(dest, tmp);
1088 circuit_remove_handled_ports(dest);
1089 return dest;
1092 /** Return 1 if we already have circuits present or on the way for
1093 * all anticipated ports. Return 0 if we should make more.
1095 * If we're returning 0, set need_uptime and need_capacity to
1096 * indicate any requirements that the unhandled ports have.
1099 circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
1100 int *need_capacity)
1102 int i, enough;
1103 uint16_t *port;
1104 smartlist_t *sl = circuit_get_unhandled_ports(now);
1105 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1106 tor_assert(need_uptime);
1107 tor_assert(need_capacity);
1108 enough = (smartlist_len(sl) == 0);
1109 for (i = 0; i < smartlist_len(sl); ++i) {
1110 port = smartlist_get(sl, i);
1111 if (smartlist_string_num_isin(LongLivedServices, *port))
1112 *need_uptime = 1;
1113 tor_free(port);
1115 smartlist_free(sl);
1116 return enough;
1119 /** Return 1 if <b>router</b> can handle one or more of the ports in
1120 * <b>needed_ports</b>, else return 0.
1122 static int
1123 router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
1125 int i;
1126 uint16_t port;
1128 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1129 addr_policy_result_t r;
1130 port = *(uint16_t *)smartlist_get(needed_ports, i);
1131 tor_assert(port);
1132 r = compare_addr_to_addr_policy(0, port, router->exit_policy);
1133 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1134 return 1;
1136 return 0;
1139 /** Return true iff <b>conn</b> needs another general circuit to be
1140 * built. */
1141 static int
1142 ap_stream_wants_exit_attention(connection_t *conn)
1144 if (conn->type == CONN_TYPE_AP &&
1145 conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1146 !conn->marked_for_close &&
1147 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1148 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
1149 MIN_CIRCUITS_HANDLING_STREAM))
1150 return 1;
1151 return 0;
1154 /** Return a pointer to a suitable router to be the exit node for the
1155 * general-purpose circuit we're about to build.
1157 * Look through the connection array, and choose a router that maximizes
1158 * the number of pending streams that can exit from this router.
1160 * Return NULL if we can't find any suitable routers.
1162 static routerinfo_t *
1163 choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
1164 int need_capacity)
1166 int *n_supported;
1167 int i;
1168 int n_pending_connections = 0;
1169 smartlist_t *connections;
1170 int best_support = -1;
1171 int n_best_support=0;
1172 smartlist_t *sl, *preferredexits, *excludedexits;
1173 routerinfo_t *router;
1174 or_options_t *options = get_options();
1176 connections = get_connection_array();
1178 /* Count how many connections are waiting for a circuit to be built.
1179 * We use this for log messages now, but in the future we may depend on it.
1181 SMARTLIST_FOREACH(connections, connection_t *, conn,
1183 if (ap_stream_wants_exit_attention(conn))
1184 ++n_pending_connections;
1186 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1187 // n_pending_connections);
1188 /* Now we count, for each of the routers in the directory, how many
1189 * of the pending connections could possibly exit from that
1190 * router (n_supported[i]). (We can't be sure about cases where we
1191 * don't know the IP address of the pending connection.)
1193 n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
1194 for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
1195 router = smartlist_get(dir->routers, i);
1196 if (router_is_me(router)) {
1197 n_supported[i] = -1;
1198 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1199 /* XXX there's probably a reverse predecessor attack here, but
1200 * it's slow. should we take this out? -RD
1202 continue;
1204 if (!router->is_running || router->is_bad_exit) {
1205 n_supported[i] = -1;
1206 continue; /* skip routers that are known to be down or bad exits */
1208 if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
1209 n_supported[i] = -1;
1210 continue; /* skip routers that are not suitable */
1212 if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
1213 /* if it's invalid and we don't want it */
1214 n_supported[i] = -1;
1215 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1216 // router->nickname, i);
1217 continue; /* skip invalid routers */
1219 if (router_exit_policy_rejects_all(router)) {
1220 n_supported[i] = -1;
1221 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1222 // router->nickname, i);
1223 continue; /* skip routers that reject all */
1225 n_supported[i] = 0;
1226 /* iterate over connections */
1227 SMARTLIST_FOREACH(connections, connection_t *, conn,
1229 if (!ap_stream_wants_exit_attention(conn))
1230 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1231 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router)) {
1232 ++n_supported[i];
1233 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1234 // router->nickname, i, n_supported[i]);
1235 } else {
1236 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1237 // router->nickname, i);
1239 }); /* End looping over connections. */
1240 if (n_supported[i] > best_support) {
1241 /* If this router is better than previous ones, remember its index
1242 * and goodness, and start counting how many routers are this good. */
1243 best_support = n_supported[i]; n_best_support=1;
1244 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1245 // router->nickname);
1246 } else if (n_supported[i] == best_support) {
1247 /* If this router is _as good_ as the best one, just increment the
1248 * count of equally good routers.*/
1249 ++n_best_support;
1252 log_info(LD_CIRC,
1253 "Found %d servers that might support %d/%d pending connections.",
1254 n_best_support, best_support >= 0 ? best_support : 0,
1255 n_pending_connections);
1257 preferredexits = smartlist_create();
1258 add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
1260 excludedexits = smartlist_create();
1261 add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0);
1263 sl = smartlist_create();
1265 /* If any routers definitely support any pending connections, choose one
1266 * at random. */
1267 if (best_support > 0) {
1268 for (i = 0; i < smartlist_len(dir->routers); i++)
1269 if (n_supported[i] == best_support)
1270 smartlist_add(sl, smartlist_get(dir->routers, i));
1272 smartlist_subtract(sl,excludedexits);
1273 if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
1274 smartlist_intersect(sl,preferredexits);
1275 router = routerlist_sl_choose_by_bandwidth(sl, WEIGHT_FOR_EXIT);
1276 } else {
1277 /* Either there are no pending connections, or no routers even seem to
1278 * possibly support any of them. Choose a router at random that satisfies
1279 * at least one predicted exit port. */
1281 int try;
1282 smartlist_t *needed_ports;
1284 if (best_support == -1) {
1285 if (need_uptime || need_capacity) {
1286 log_info(LD_CIRC,
1287 "We couldn't find any live%s%s routers; falling back "
1288 "to list of all routers.",
1289 need_capacity?", fast":"",
1290 need_uptime?", stable":"");
1291 smartlist_free(preferredexits);
1292 smartlist_free(excludedexits);
1293 smartlist_free(sl);
1294 tor_free(n_supported);
1295 return choose_good_exit_server_general(dir, 0, 0);
1297 log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
1298 "doomed exit at random.");
1300 needed_ports = circuit_get_unhandled_ports(time(NULL));
1301 for (try = 0; try < 2; try++) {
1302 /* try once to pick only from routers that satisfy a needed port,
1303 * then if there are none, pick from any that support exiting. */
1304 for (i = 0; i < smartlist_len(dir->routers); i++) {
1305 router = smartlist_get(dir->routers, i);
1306 if (n_supported[i] != -1 &&
1307 (try || router_handles_some_port(router, needed_ports))) {
1308 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1309 // try, router->nickname);
1310 smartlist_add(sl, router);
1314 smartlist_subtract(sl,excludedexits);
1315 if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
1316 smartlist_intersect(sl,preferredexits);
1317 /* XXX sometimes the above results in null, when the requested
1318 * exit node is down. we should pick it anyway. */
1319 router = routerlist_sl_choose_by_bandwidth(sl, WEIGHT_FOR_EXIT);
1320 if (router)
1321 break;
1323 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1324 smartlist_free(needed_ports);
1327 smartlist_free(preferredexits);
1328 smartlist_free(excludedexits);
1329 smartlist_free(sl);
1330 tor_free(n_supported);
1331 if (router) {
1332 log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
1333 return router;
1335 if (options->StrictExitNodes) {
1336 log_warn(LD_CIRC,
1337 "No specified exit routers seem to be running, and "
1338 "StrictExitNodes is set: can't choose an exit.");
1340 return NULL;
1343 /** Return a pointer to a suitable router to be the exit node for the
1344 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1345 * if no router is suitable).
1347 * For general-purpose circuits, pass it off to
1348 * choose_good_exit_server_general()
1350 * For client-side rendezvous circuits, choose a random node, weighted
1351 * toward the preferences in 'options'.
1353 static routerinfo_t *
1354 choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
1355 int need_uptime, int need_capacity, int is_internal)
1357 or_options_t *options = get_options();
1358 switch (purpose) {
1359 case CIRCUIT_PURPOSE_C_GENERAL:
1360 if (is_internal) /* pick it like a middle hop */
1361 return router_choose_random_node(NULL, get_options()->ExcludeNodes,
1362 NULL, need_uptime, need_capacity, 0,
1363 get_options()->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
1364 else
1365 return choose_good_exit_server_general(dir,need_uptime,need_capacity);
1366 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1367 return router_choose_random_node(
1368 options->RendNodes, options->RendExcludeNodes,
1369 NULL, need_uptime, need_capacity, 0,
1370 options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS, 0, 0);
1372 log_warn(LD_BUG,"Unhandled purpose %d", purpose);
1373 tor_fragile_assert();
1374 return NULL;
1377 /** Decide a suitable length for circ's cpath, and pick an exit
1378 * router (or use <b>exit</b> if provided). Store these in the
1379 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1380 static int
1381 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
1383 cpath_build_state_t *state = circ->build_state;
1384 routerlist_t *rl = router_get_routerlist();
1386 if (state->onehop_tunnel) {
1387 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
1388 state->desired_path_len = 1;
1389 } else {
1390 int r = new_route_len(circ->_base.purpose, exit, rl->routers);
1391 if (r < 1) /* must be at least 1 */
1392 return -1;
1393 state->desired_path_len = r;
1396 if (exit) { /* the circuit-builder pre-requested one */
1397 log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
1398 exit = extend_info_dup(exit);
1399 } else { /* we have to decide one */
1400 routerinfo_t *router =
1401 choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
1402 state->need_capacity, state->is_internal);
1403 if (!router) {
1404 log_warn(LD_CIRC,"failed to choose an exit server");
1405 return -1;
1407 exit = extend_info_from_router(router);
1409 state->chosen_exit = exit;
1410 return 0;
1413 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1414 * hop to the cpath reflecting this. Don't send the next extend cell --
1415 * the caller will do this if it wants to.
1418 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1420 cpath_build_state_t *state;
1421 tor_assert(exit);
1422 tor_assert(circ);
1424 state = circ->build_state;
1425 tor_assert(state);
1426 if (state->chosen_exit)
1427 extend_info_free(state->chosen_exit);
1428 state->chosen_exit = extend_info_dup(exit);
1430 ++circ->build_state->desired_path_len;
1431 onion_append_hop(&circ->cpath, exit);
1432 return 0;
1435 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1436 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1437 * send the next extend cell to begin connecting to that hop.
1440 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1442 int err_reason = 0;
1443 circuit_append_new_exit(circ, exit);
1444 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
1445 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
1446 log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
1447 exit->nickname);
1448 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
1449 return -1;
1451 return 0;
1454 /** Return the number of routers in <b>routers</b> that are currently up
1455 * and available for building circuits through.
1457 static int
1458 count_acceptable_routers(smartlist_t *routers)
1460 int i, n;
1461 int num=0;
1462 routerinfo_t *r;
1464 n = smartlist_len(routers);
1465 for (i=0;i<n;i++) {
1466 r = smartlist_get(routers, i);
1467 // log_debug(LD_CIRC,
1468 // "Contemplating whether router %d (%s) is a new option.",
1469 // i, r->nickname);
1470 if (r->is_running == 0) {
1471 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1472 goto next_i_loop;
1474 if (r->is_valid == 0) {
1475 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1476 goto next_i_loop;
1477 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1478 * allows this node in some places, then we're getting an inaccurate
1479 * count. For now, be conservative and don't count it. But later we
1480 * should try to be smarter. */
1482 num++;
1483 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1484 next_i_loop:
1485 ; /* C requires an explicit statement after the label */
1488 return num;
1491 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1492 * This function is used to extend cpath by another hop.
1494 void
1495 onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
1497 if (*head_ptr) {
1498 new_hop->next = (*head_ptr);
1499 new_hop->prev = (*head_ptr)->prev;
1500 (*head_ptr)->prev->next = new_hop;
1501 (*head_ptr)->prev = new_hop;
1502 } else {
1503 *head_ptr = new_hop;
1504 new_hop->prev = new_hop->next = new_hop;
1508 /** Pick a random server digest that's running a Tor version that
1509 * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
1510 * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
1511 * probably already connected to them.
1513 * We only return one, so this doesn't become stupid when the
1514 * whole network has upgraded. */
1515 static char *
1516 compute_preferred_testing_list(const char *answer)
1518 smartlist_t *choices;
1519 routerlist_t *rl = router_get_routerlist();
1520 routerinfo_t *router;
1521 char *s;
1523 if (answer) /* they have one in mind -- easy */
1524 return tor_strdup(answer);
1526 choices = smartlist_create();
1527 /* now count up our choices */
1528 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1529 if (r->is_running && r->is_valid &&
1530 ((tor_version_as_new_as(r->platform,"0.1.1.21-cvs") &&
1531 !tor_version_as_new_as(r->platform,"0.1.2.0-alpha-cvs")) ||
1532 tor_version_as_new_as(r->platform,"0.1.2.1-alpha")) &&
1533 !is_local_IP(r->addr) &&
1534 !router_get_trusteddirserver_by_digest(r->cache_info.identity_digest))
1535 smartlist_add(choices, r));
1536 router = smartlist_choose(choices);
1537 smartlist_free(choices);
1538 if (!router) {
1539 log_info(LD_CIRC, "Looking for middle server that doesn't have the "
1540 "reachability bug, but didn't find one. Oh well.");
1541 return NULL;
1543 log_info(LD_CIRC, "Looking for middle server that doesn't have the "
1544 "reachability bug, and chose '%s'. Great.", router->nickname);
1545 s = tor_malloc(HEX_DIGEST_LEN+2);
1546 s[0] = '$';
1547 base16_encode(s+1, HEX_DIGEST_LEN+1,
1548 router->cache_info.identity_digest, DIGEST_LEN);
1549 return s;
1552 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1553 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1554 * to length <b>cur_len</b> to decide a suitable middle hop for a
1555 * circuit. In particular, make sure we don't pick the exit node or its
1556 * family, and make sure we don't duplicate any previous nodes or their
1557 * families. */
1558 static routerinfo_t *
1559 choose_good_middle_server(uint8_t purpose,
1560 cpath_build_state_t *state,
1561 crypt_path_t *head,
1562 int cur_len)
1564 int i;
1565 routerinfo_t *r, *choice;
1566 crypt_path_t *cpath;
1567 smartlist_t *excluded;
1568 or_options_t *options = get_options();
1569 char *preferred = NULL;
1570 tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
1571 purpose <= _CIRCUIT_PURPOSE_MAX);
1573 log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
1574 excluded = smartlist_create();
1575 if ((r = build_state_get_exit_router(state))) {
1576 smartlist_add(excluded, r);
1577 routerlist_add_family(excluded, r);
1579 if ((r = routerlist_find_my_routerinfo())) {
1580 smartlist_add(excluded, r);
1581 routerlist_add_family(excluded, r);
1583 for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
1584 if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
1585 smartlist_add(excluded, r);
1586 routerlist_add_family(excluded, r);
1589 if (purpose == CIRCUIT_PURPOSE_TESTING)
1590 preferred = compute_preferred_testing_list(options->TestVia);
1591 choice = router_choose_random_node(preferred,
1592 options->ExcludeNodes, excluded,
1593 state->need_uptime, state->need_capacity, 0,
1594 options->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
1595 tor_free(preferred);
1596 smartlist_free(excluded);
1597 return choice;
1600 /** Pick a good entry server for the circuit to be built according to
1601 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1602 * router (if we're an OR), and respect firewall settings; if we're
1603 * configured to use entry guards, return one.
1605 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1606 * guard, not for any particular circuit.
1608 static routerinfo_t *
1609 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
1611 routerinfo_t *r, *choice;
1612 smartlist_t *excluded;
1613 or_options_t *options = get_options();
1614 (void)purpose; /* not used yet. */
1616 if (state && options->UseEntryGuards) {
1617 return choose_random_entry(state);
1620 excluded = smartlist_create();
1622 if (state && (r = build_state_get_exit_router(state))) {
1623 smartlist_add(excluded, r);
1624 routerlist_add_family(excluded, r);
1626 if ((r = routerlist_find_my_routerinfo())) {
1627 smartlist_add(excluded, r);
1628 routerlist_add_family(excluded, r);
1630 if (firewall_is_fascist_or()) {
1631 /* exclude all ORs that listen on the wrong port */
1632 routerlist_t *rl = router_get_routerlist();
1633 int i;
1635 for (i=0; i < smartlist_len(rl->routers); i++) {
1636 r = smartlist_get(rl->routers, i);
1637 if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
1638 smartlist_add(excluded, r);
1641 /* and exclude current entry guards, if applicable */
1642 if (options->UseEntryGuards && entry_guards) {
1643 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1645 if ((r = router_get_by_digest(entry->identity)))
1646 smartlist_add(excluded, r);
1650 choice = router_choose_random_node(
1651 NULL, options->ExcludeNodes,
1652 excluded, state ? state->need_uptime : 0,
1653 state ? state->need_capacity : 0,
1654 state ? 0 : 1,
1655 options->_AllowInvalid & ALLOW_INVALID_ENTRY, 0, 0);
1656 smartlist_free(excluded);
1657 return choice;
1660 /** Return the first non-open hop in cpath, or return NULL if all
1661 * hops are open. */
1662 static crypt_path_t *
1663 onion_next_hop_in_cpath(crypt_path_t *cpath)
1665 crypt_path_t *hop = cpath;
1666 do {
1667 if (hop->state != CPATH_STATE_OPEN)
1668 return hop;
1669 hop = hop->next;
1670 } while (hop != cpath);
1671 return NULL;
1674 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1675 * based on <b>state</b>. Append the hop info to head_ptr.
1677 static int
1678 onion_extend_cpath(origin_circuit_t *circ)
1680 uint8_t purpose = circ->_base.purpose;
1681 cpath_build_state_t *state = circ->build_state;
1682 int cur_len = circuit_get_cpath_len(circ);
1683 extend_info_t *info = NULL;
1685 if (cur_len >= state->desired_path_len) {
1686 log_debug(LD_CIRC, "Path is complete: %d steps long",
1687 state->desired_path_len);
1688 return 1;
1691 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
1692 state->desired_path_len);
1694 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
1695 info = extend_info_dup(state->chosen_exit);
1696 } else if (cur_len == 0) { /* picking first node */
1697 routerinfo_t *r = choose_good_entry_server(purpose, state);
1698 if (r)
1699 info = extend_info_from_router(r);
1700 } else {
1701 routerinfo_t *r =
1702 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
1703 if (r)
1704 info = extend_info_from_router(r);
1707 if (!info) {
1708 log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
1709 "this circuit.", cur_len);
1710 return -1;
1713 log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
1714 info->nickname, cur_len+1, build_state_get_exit_nickname(state));
1716 onion_append_hop(&circ->cpath, info);
1717 extend_info_free(info);
1718 return 0;
1721 /** Create a new hop, annotate it with information about its
1722 * corresponding router <b>choice</b>, and append it to the
1723 * end of the cpath <b>head_ptr</b>. */
1724 static int
1725 onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
1727 crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
1729 /* link hop into the cpath, at the end. */
1730 onion_append_to_cpath(head_ptr, hop);
1732 hop->magic = CRYPT_PATH_MAGIC;
1733 hop->state = CPATH_STATE_CLOSED;
1735 hop->extend_info = extend_info_dup(choice);
1737 hop->package_window = CIRCWINDOW_START;
1738 hop->deliver_window = CIRCWINDOW_START;
1740 return 0;
1743 /** Allocate a new extend_info object based on the various arguments. */
1744 extend_info_t *
1745 extend_info_alloc(const char *nickname, const char *digest,
1746 crypto_pk_env_t *onion_key,
1747 uint32_t addr, uint16_t port)
1749 extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
1750 memcpy(info->identity_digest, digest, DIGEST_LEN);
1751 if (nickname)
1752 strlcpy(info->nickname, nickname, sizeof(info->nickname));
1753 if (onion_key)
1754 info->onion_key = crypto_pk_dup_key(onion_key);
1755 info->addr = addr;
1756 info->port = port;
1757 return info;
1760 /** Allocate and return a new extend_info_t that can be used to build a
1761 * circuit to or through the router <b>r</b>. */
1762 extend_info_t *
1763 extend_info_from_router(routerinfo_t *r)
1765 tor_assert(r);
1766 return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
1767 r->onion_pkey, r->addr, r->or_port);
1770 #if 0
1771 /** What router purpose is <b>digest</b>?
1772 * It's a general purpose router unless it's on our bridges list.
1774 static uint8_t
1775 get_router_purpose_from_digest(char *digest)
1777 if (digest_is_a_bridge(digest))
1778 return ROUTER_PURPOSE_BRIDGE;
1779 return ROUTER_PURPOSE_GENERAL;
1781 #endif
1783 #if 0
1784 /** Allocate and return a new extend_info_t that can be used to build a
1785 * circuit to or through the router <b>r</b>. */
1786 extend_info_t *
1787 extend_info_from_routerstatus(routerstatus_t *s)
1789 tor_assert(s);
1790 /* routerstatus doesn't know onion_key; leave it NULL */
1791 return extend_info_alloc(s->nickname, s->identity_digest,
1792 NULL, s->addr, s->or_port);
1793 // get_router_purpose_from_digest(s->identity_digest));
1795 #endif
1797 /** Release storage held by an extend_info_t struct. */
1798 void
1799 extend_info_free(extend_info_t *info)
1801 tor_assert(info);
1802 if (info->onion_key)
1803 crypto_free_pk_env(info->onion_key);
1804 tor_free(info);
1807 /** Allocate and return a new extend_info_t with the same contents as
1808 * <b>info</b>. */
1809 extend_info_t *
1810 extend_info_dup(extend_info_t *info)
1812 extend_info_t *newinfo;
1813 tor_assert(info);
1814 newinfo = tor_malloc(sizeof(extend_info_t));
1815 memcpy(newinfo, info, sizeof(extend_info_t));
1816 if (info->onion_key)
1817 newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
1818 else
1819 newinfo->onion_key = NULL;
1820 return newinfo;
1823 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1824 * If there is no chosen exit, or if we don't know the routerinfo_t for
1825 * the chosen exit, return NULL.
1827 routerinfo_t *
1828 build_state_get_exit_router(cpath_build_state_t *state)
1830 if (!state || !state->chosen_exit)
1831 return NULL;
1832 return router_get_by_digest(state->chosen_exit->identity_digest);
1835 /** Return the nickname for the chosen exit router in <b>state</b>. If
1836 * there is no chosen exit, or if we don't know the routerinfo_t for the
1837 * chosen exit, return NULL.
1839 const char *
1840 build_state_get_exit_nickname(cpath_build_state_t *state)
1842 if (!state || !state->chosen_exit)
1843 return NULL;
1844 return state->chosen_exit->nickname;
1847 /** Check whether the entry guard <b>e</b> is usable, given the directory
1848 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1849 * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
1850 * accordingly. Return true iff the entry guard's status changes.
1852 * If it's not usable, set *<b>reason</b> to a static string explaining why.
1854 static int
1855 entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
1856 time_t now, or_options_t *options, const char **reason)
1858 char buf[HEX_DIGEST_LEN+1];
1859 int changed = 0;
1861 tor_assert(options);
1863 *reason = NULL;
1865 /* Do we want to mark this guard as bad? */
1866 if (!ri)
1867 *reason = "unlisted";
1868 else if (!ri->is_running)
1869 *reason = "down";
1870 else if (options->UseBridges && ri->purpose != ROUTER_PURPOSE_BRIDGE)
1871 *reason = "not a bridge";
1872 else if (!options->UseBridges && !ri->is_possible_guard &&
1873 !router_nickname_is_in_list(ri, options->EntryNodes))
1874 *reason = "not recommended as a guard";
1875 else if (router_nickname_is_in_list(ri, options->ExcludeNodes))
1876 *reason = "excluded";
1878 if (*reason && ! e->bad_since) {
1879 /* Router is newly bad. */
1880 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
1881 log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
1882 e->nickname, buf, *reason);
1884 e->bad_since = now;
1885 control_event_guard(e->nickname, e->identity, "BAD");
1886 changed = 1;
1887 } else if (!*reason && e->bad_since) {
1888 /* There's nothing wrong with the router any more. */
1889 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
1890 log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
1891 "marking as ok.", e->nickname, buf);
1893 e->bad_since = 0;
1894 control_event_guard(e->nickname, e->identity, "GOOD");
1895 changed = 1;
1898 return changed;
1901 /** Return true iff enough time has passed since we last tried to connect
1902 * to the unreachable guard <b>e</b> that we're willing to try again. */
1903 static int
1904 entry_is_time_to_retry(entry_guard_t *e, time_t now)
1906 long diff;
1907 if (e->last_attempted < e->unreachable_since)
1908 return 1;
1909 diff = now - e->unreachable_since;
1910 if (diff < 6*60*60)
1911 return now > (e->last_attempted + 60*60);
1912 else if (diff < 3*24*60*60)
1913 return now > (e->last_attempted + 4*60*60);
1914 else if (diff < 7*24*60*60)
1915 return now > (e->last_attempted + 18*60*60);
1916 else
1917 return now > (e->last_attempted + 36*60*60);
1920 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1921 * working well enough that we are willing to use it as an entry
1922 * right now. (Else return NULL.) In particular, it must be
1923 * - Listed as either up or never yet contacted;
1924 * - Present in the routerlist;
1925 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1926 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1927 * (This check is currently redundant with the Guard flag, but in
1928 * the future that might change. Best to leave it in for now.)
1929 * - Allowed by our current ReachableORAddresses config option; and
1930 * - Currently thought to be reachable by us (unless assume_reachable
1931 * is true).
1933 static INLINE routerinfo_t *
1934 entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
1935 int assume_reachable)
1937 routerinfo_t *r;
1938 if (e->bad_since)
1939 return NULL;
1940 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1941 if ((!assume_reachable && !e->can_retry) &&
1942 e->unreachable_since && !entry_is_time_to_retry(e, time(NULL)))
1943 return NULL;
1944 r = router_get_by_digest(e->identity);
1945 if (!r)
1946 return NULL;
1947 if (get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_BRIDGE)
1948 return NULL;
1949 if (!get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_GENERAL)
1950 return NULL;
1951 if (router_is_unreliable(r, need_uptime, need_capacity, 0))
1952 return NULL;
1953 if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
1954 return NULL;
1955 return r;
1958 /** Return the number of entry guards that we think are usable. */
1959 static int
1960 num_live_entry_guards(void)
1962 int n = 0;
1963 if (! entry_guards)
1964 return 0;
1965 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1967 if (entry_is_live(entry, 0, 1, 0))
1968 ++n;
1970 return n;
1973 /** If <b>digest</b> matches the identity of any node in the
1974 * entry_guards list, return that node. Else return NULL. */
1975 static INLINE entry_guard_t *
1976 is_an_entry_guard(const char *digest)
1978 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1979 if (!memcmp(digest, entry->identity, DIGEST_LEN))
1980 return entry;
1982 return NULL;
1985 /** Dump a description of our list of entry guards to the log at level
1986 * <b>severity</b>. */
1987 static void
1988 log_entry_guards(int severity)
1990 smartlist_t *elements = smartlist_create();
1991 char buf[1024];
1992 char *s;
1994 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
1996 tor_snprintf(buf, sizeof(buf), "%s (%s%s)",
1997 e->nickname,
1998 e->bad_since ? "down " : "up ",
1999 e->made_contact ? "made-contact" : "never-contacted");
2000 smartlist_add(elements, tor_strdup(buf));
2003 s = smartlist_join_strings(elements, ",", 0, NULL);
2004 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
2005 smartlist_free(elements);
2006 log_fn(severity,LD_CIRC,"%s",s);
2007 tor_free(s);
2010 /** Called when one or more guards that we would previously have used for some
2011 * purpose are no longer in use because a higher-priority guard has become
2012 * useable again. */
2013 static void
2014 control_event_guard_deferred(void)
2016 /* XXXX We don't actually have a good way to figure out _how many_ entries
2017 * are live for some purpose. We need an entry_is_even_slightly_live()
2018 * function for this to work right. NumEntryGuards isn't reliable: if we
2019 * need guards with weird properties, we can have more than that number
2020 * live.
2022 #if 0
2023 int n = 0;
2024 or_options_t *options = get_options();
2025 if (!entry_guards)
2026 return;
2027 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2029 if (entry_is_live(entry, 0, 1, 0)) {
2030 if (n++ == options->NumEntryGuards) {
2031 control_event_guard(entry->nickname, entry->identity, "DEFERRED");
2032 return;
2036 #endif
2039 /** Add a new (preferably stable and fast) router to our
2040 * entry_guards list. Return a pointer to the router if we succeed,
2041 * or NULL if we can't find any more suitable entries.
2043 * If <b>chosen</b> is defined, use that one, and if it's not
2044 * already in our entry_guards list, put it at the *beginning*.
2045 * Else, put the one we pick at the end of the list. */
2046 static routerinfo_t *
2047 add_an_entry_guard(routerinfo_t *chosen, int reset_status)
2049 routerinfo_t *router;
2050 entry_guard_t *entry;
2052 if (chosen) {
2053 router = chosen;
2054 entry = is_an_entry_guard(router->cache_info.identity_digest);
2055 if (entry) {
2056 if (reset_status)
2057 entry->bad_since = 0;
2058 return NULL;
2060 } else {
2061 router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
2062 if (!router)
2063 return NULL;
2065 entry = tor_malloc_zero(sizeof(entry_guard_t));
2066 log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
2067 strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
2068 memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
2069 entry->chosen_on_date = start_of_month(time(NULL));
2070 entry->chosen_by_version = tor_strdup(VERSION);
2071 if (chosen) /* prepend */
2072 smartlist_insert(entry_guards, 0, entry);
2073 else /* append */
2074 smartlist_add(entry_guards, entry);
2075 control_event_guard(entry->nickname, entry->identity, "NEW");
2076 control_event_guard_deferred();
2077 log_entry_guards(LOG_INFO);
2078 return router;
2081 /** If the use of entry guards is configured, choose more entry guards
2082 * until we have enough in the list. */
2083 static void
2084 pick_entry_guards(void)
2086 or_options_t *options = get_options();
2087 int changed = 0;
2089 tor_assert(entry_guards);
2091 while (num_live_entry_guards() < options->NumEntryGuards) {
2092 if (!add_an_entry_guard(NULL, 0))
2093 break;
2094 changed = 1;
2096 if (changed)
2097 entry_guards_changed();
2100 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2101 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2102 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2104 /** Release all storage held by <b>e</b>. */
2105 static void
2106 entry_guard_free(entry_guard_t *e)
2108 tor_assert(e);
2109 tor_free(e->chosen_by_version);
2110 tor_free(e);
2113 /** Remove any entry guard which was selected by an unknown version of Tor,
2114 * or which was selected by a version of Tor that's known to select
2115 * entry guards badly. */
2116 static int
2117 remove_obsolete_entry_guards(void)
2119 int changed = 0, i;
2120 for (i = 0; i < smartlist_len(entry_guards); ++i) {
2121 entry_guard_t *entry = smartlist_get(entry_guards, i);
2122 const char *ver = entry->chosen_by_version;
2123 const char *msg = NULL;
2124 tor_version_t v;
2125 int version_is_bad = 0;
2126 if (!ver) {
2127 msg = "does not say what version of Tor it was selected by";
2128 version_is_bad = 1;
2129 } else if (tor_version_parse(ver, &v)) {
2130 msg = "does not seem to be from any recognized version of Tor";
2131 version_is_bad = 1;
2132 } else if ((tor_version_as_new_as(ver, "0.1.0.10-alpha") &&
2133 !tor_version_as_new_as(ver, "0.1.2.16-dev")) ||
2134 (tor_version_as_new_as(ver, "0.2.0.0-alpha") &&
2135 !tor_version_as_new_as(ver, "0.2.0.6-alpha"))) {
2136 msg = "was selected without regard for guard bandwidth";
2137 version_is_bad = 1;
2139 if (version_is_bad) {
2140 char dbuf[HEX_DIGEST_LEN+1];
2141 tor_assert(msg);
2142 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
2143 log_notice(LD_CIRC, "Entry guard '%s' (%s) %s. (Version=%s.) "
2144 "Replacing it.",
2145 entry->nickname, dbuf, msg, ver?escaped(ver):"none");
2146 control_event_guard(entry->nickname, entry->identity, "DROPPED");
2147 entry_guard_free(entry);
2148 smartlist_del_keeporder(entry_guards, i--);
2149 log_entry_guards(LOG_INFO);
2150 changed = 1;
2154 return changed ? 1 : 0;
2157 /** Remove all entry guards that have been down or unlisted for so
2158 * long that we don't think they'll come up again. Return 1 if we
2159 * removed any, or 0 if we did nothing. */
2160 static int
2161 remove_dead_entry_guards(void)
2163 char dbuf[HEX_DIGEST_LEN+1];
2164 char tbuf[ISO_TIME_LEN+1];
2165 time_t now = time(NULL);
2166 int i;
2167 int changed = 0;
2169 for (i = 0; i < smartlist_len(entry_guards); ) {
2170 entry_guard_t *entry = smartlist_get(entry_guards, i);
2171 if (entry->bad_since &&
2172 entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
2174 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
2175 format_local_iso_time(tbuf, entry->bad_since);
2176 log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
2177 "since %s local time; removing.",
2178 entry->nickname, dbuf, tbuf);
2179 control_event_guard(entry->nickname, entry->identity, "DROPPED");
2180 entry_guard_free(entry);
2181 smartlist_del_keeporder(entry_guards, i);
2182 log_entry_guards(LOG_INFO);
2183 changed = 1;
2184 } else
2185 ++i;
2187 return changed ? 1 : 0;
2190 /** A new directory or router-status has arrived; update the down/listed
2191 * status of the entry guards.
2193 * An entry is 'down' if the directory lists it as nonrunning.
2194 * An entry is 'unlisted' if the directory doesn't include it.
2196 * Don't call this on startup; only on a fresh download. Otherwise we'll
2197 * think that things are unlisted.
2199 void
2200 entry_guards_compute_status(void)
2202 time_t now;
2203 int changed = 0;
2204 int severity = LOG_INFO;
2205 or_options_t *options;
2206 if (! entry_guards)
2207 return;
2209 options = get_options();
2211 now = time(NULL);
2213 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2215 routerinfo_t *r = router_get_by_digest(entry->identity);
2216 const char *reason = NULL;
2217 if (entry_guard_set_status(entry, r, now, options, &reason))
2218 changed = 1;
2220 if (entry->bad_since)
2221 tor_assert(reason);
2223 log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s%s, and %s.",
2224 entry->nickname,
2225 entry->unreachable_since ? "unreachable" : "reachable",
2226 entry->bad_since ? "unusable: " : "usable",
2227 entry->bad_since ? reason : "",
2228 entry_is_live(entry, 0, 1, 0) ? "live" : "not live");
2231 if (remove_dead_entry_guards())
2232 changed = 1;
2234 if (changed) {
2235 log_fn(severity, LD_CIRC, " (%d/%d entry guards are usable/new)",
2236 num_live_entry_guards(), smartlist_len(entry_guards));
2237 log_entry_guards(LOG_INFO);
2238 entry_guards_changed();
2242 /** Called when a connection to an OR with the identity digest <b>digest</b>
2243 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2244 * If the OR is an entry, change that entry's up/down status.
2245 * Return 0 normally, or -1 if we want to tear down the new connection.
2248 entry_guard_register_connect_status(const char *digest, int succeeded,
2249 time_t now)
2251 int changed = 0;
2252 int refuse_conn = 0;
2253 int first_contact = 0;
2254 entry_guard_t *entry = NULL;
2255 int idx = -1;
2256 char buf[HEX_DIGEST_LEN+1];
2258 if (! entry_guards)
2259 return 0;
2261 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2263 if (!memcmp(e->identity, digest, DIGEST_LEN)) {
2264 entry = e;
2265 idx = e_sl_idx;
2266 break;
2270 if (!entry)
2271 return 0;
2273 base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
2275 if (succeeded) {
2276 if (entry->unreachable_since) {
2277 log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
2278 entry->nickname, buf);
2279 entry->can_retry = 0;
2280 entry->unreachable_since = 0;
2281 entry->last_attempted = now;
2282 control_event_guard(entry->nickname, entry->identity, "UP");
2283 changed = 1;
2285 if (!entry->made_contact) {
2286 entry->made_contact = 1;
2287 first_contact = changed = 1;
2289 } else { /* ! succeeded */
2290 if (!entry->made_contact) {
2291 /* We've never connected to this one. */
2292 log_info(LD_CIRC,
2293 "Connection to never-contacted entry guard '%s' (%s) failed. "
2294 "Removing from the list. %d/%d entry guards usable/new.",
2295 entry->nickname, buf,
2296 num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
2297 entry_guard_free(entry);
2298 smartlist_del_keeporder(entry_guards, idx);
2299 log_entry_guards(LOG_INFO);
2300 changed = 1;
2301 } else if (!entry->unreachable_since) {
2302 log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
2303 "Marking as unreachable.", entry->nickname, buf);
2304 entry->unreachable_since = entry->last_attempted = now;
2305 control_event_guard(entry->nickname, entry->identity, "DOWN");
2306 changed = 1;
2307 entry->can_retry = 0; /* We gave it an early chance; no good. */
2308 } else {
2309 char tbuf[ISO_TIME_LEN+1];
2310 format_iso_time(tbuf, entry->unreachable_since);
2311 log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
2312 "'%s' (%s). It has been unreachable since %s.",
2313 entry->nickname, buf, tbuf);
2314 entry->last_attempted = now;
2315 entry->can_retry = 0; /* We gave it an early chance; no good. */
2319 if (first_contact) {
2320 /* We've just added a new long-term entry guard. Perhaps the network just
2321 * came back? We should give our earlier entries another try too,
2322 * and close this connection so we don't use it before we've given
2323 * the others a shot. */
2324 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
2325 if (e == entry)
2326 break;
2327 if (e->made_contact) {
2328 routerinfo_t *r = entry_is_live(e, 0, 1, 1);
2329 if (r && e->unreachable_since) {
2330 refuse_conn = 1;
2331 e->can_retry = 1;
2335 if (refuse_conn) {
2336 log_info(LD_CIRC,
2337 "Connected to new entry guard '%s' (%s). Marking earlier "
2338 "entry guards up. %d/%d entry guards usable/new.",
2339 entry->nickname, buf,
2340 num_live_entry_guards(), smartlist_len(entry_guards));
2341 log_entry_guards(LOG_INFO);
2342 changed = 1;
2346 if (changed)
2347 entry_guards_changed();
2348 return refuse_conn ? -1 : 0;
2351 /** When we try to choose an entry guard, should we parse and add
2352 * config's EntryNodes first? */
2353 static int should_add_entry_nodes = 0;
2355 /** Called when the value of EntryNodes changes in our configuration. */
2356 void
2357 entry_nodes_should_be_added(void)
2359 log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
2360 should_add_entry_nodes = 1;
2363 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2364 * of guard nodes, at the front. */
2365 static void
2366 entry_guards_prepend_from_config(void)
2368 or_options_t *options = get_options();
2369 smartlist_t *entry_routers, *entry_fps;
2370 smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
2371 tor_assert(entry_guards);
2373 should_add_entry_nodes = 0;
2375 if (!options->EntryNodes) {
2376 /* It's possible that a controller set EntryNodes, thus making
2377 * should_add_entry_nodes set, then cleared it again, all before the
2378 * call to choose_random_entry() that triggered us. If so, just return.
2380 return;
2383 log_info(LD_CIRC,"Adding configured EntryNodes '%s'.",
2384 options->EntryNodes);
2386 entry_routers = smartlist_create();
2387 entry_fps = smartlist_create();
2388 old_entry_guards_on_list = smartlist_create();
2389 old_entry_guards_not_on_list = smartlist_create();
2391 /* Split entry guards into those on the list and those not. */
2392 add_nickname_list_to_smartlist(entry_routers, options->EntryNodes, 0);
2393 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
2394 smartlist_add(entry_fps,ri->cache_info.identity_digest));
2395 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
2396 if (smartlist_digest_isin(entry_fps, e->identity))
2397 smartlist_add(old_entry_guards_on_list, e);
2398 else
2399 smartlist_add(old_entry_guards_not_on_list, e);
2402 /* Remove all currently configured entry guards from entry_routers. */
2403 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
2404 if (is_an_entry_guard(ri->cache_info.identity_digest)) {
2405 SMARTLIST_DEL_CURRENT(entry_routers, ri);
2409 /* Now build the new entry_guards list. */
2410 smartlist_clear(entry_guards);
2411 /* First, the previously configured guards that are in EntryNodes. */
2412 smartlist_add_all(entry_guards, old_entry_guards_on_list);
2413 /* Next, the rest of EntryNodes */
2414 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
2415 add_an_entry_guard(ri, 0);
2417 /* Finally, the remaining EntryNodes, unless we're strict */
2418 if (options->StrictEntryNodes) {
2419 SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
2420 entry_guard_free(e));
2421 } else {
2422 smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
2425 smartlist_free(entry_routers);
2426 smartlist_free(entry_fps);
2427 smartlist_free(old_entry_guards_on_list);
2428 smartlist_free(old_entry_guards_not_on_list);
2429 entry_guards_changed();
2432 /** Return 1 if we're fine adding arbitrary routers out of the
2433 * directory to our entry guard list. Else return 0. */
2435 entry_list_can_grow(or_options_t *options)
2437 if (options->StrictEntryNodes)
2438 return 0;
2439 if (options->UseBridges)
2440 return 0;
2441 return 1;
2444 /** Pick a live (up and listed) entry guard from entry_guards. If
2445 * <b>state</b> is non-NULL, this is for a specific circuit --
2446 * make sure not to pick this circuit's exit or any node in the
2447 * exit's family. If <b>state</b> is NULL, we're looking for a random
2448 * guard (likely a bridge). */
2449 routerinfo_t *
2450 choose_random_entry(cpath_build_state_t *state)
2452 or_options_t *options = get_options();
2453 smartlist_t *live_entry_guards = smartlist_create();
2454 smartlist_t *exit_family = smartlist_create();
2455 routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
2456 routerinfo_t *r = NULL;
2457 int need_uptime = state ? state->need_uptime : 0;
2458 int need_capacity = state ? state->need_capacity : 0;
2459 int consider_exit_family = 0;
2461 if (chosen_exit) {
2462 smartlist_add(exit_family, chosen_exit);
2463 routerlist_add_family(exit_family, chosen_exit);
2464 consider_exit_family = 1;
2467 if (!entry_guards)
2468 entry_guards = smartlist_create();
2470 if (should_add_entry_nodes)
2471 entry_guards_prepend_from_config();
2473 if (entry_list_can_grow(options) &&
2474 (! entry_guards ||
2475 smartlist_len(entry_guards) < options->NumEntryGuards))
2476 pick_entry_guards();
2478 retry:
2479 smartlist_clear(live_entry_guards);
2480 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2482 r = entry_is_live(entry, need_uptime, need_capacity, 0);
2483 if (r && (!consider_exit_family || !smartlist_isin(exit_family, r))) {
2484 smartlist_add(live_entry_guards, r);
2485 if (!entry->made_contact) {
2486 /* Always start with the first not-yet-contacted entry
2487 * guard. Otherwise we might add several new ones, pick
2488 * the second new one, and now we've expanded our entry
2489 * guard list without needing to. */
2490 goto choose_and_finish;
2492 if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
2493 break; /* we have enough */
2497 /* Try to have at least 2 choices available. This way we don't
2498 * get stuck with a single live-but-crummy entry and just keep
2499 * using him.
2500 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2501 if (smartlist_len(live_entry_guards) < 2) {
2502 if (entry_list_can_grow(options)) {
2503 /* still no? try adding a new entry then */
2504 /* XXX if guard doesn't imply fast and stable, then we need
2505 * to tell add_an_entry_guard below what we want, or it might
2506 * be a long time til we get it. -RD */
2507 r = add_an_entry_guard(NULL, 0);
2508 if (r) {
2509 smartlist_add(live_entry_guards, r);
2510 entry_guards_changed();
2513 if (!r && need_uptime) {
2514 need_uptime = 0; /* try without that requirement */
2515 goto retry;
2517 if (!r && need_capacity) {
2518 /* still no? last attempt, try without requiring capacity */
2519 need_capacity = 0;
2520 goto retry;
2522 if (!r && !entry_list_can_grow(options) && consider_exit_family) {
2523 /* still no? if we're using bridges or have strictentrynodes
2524 * set, and our chosen exit is in the same family as all our
2525 * bridges/entry guards, then be flexible about families. */
2526 consider_exit_family = 0;
2527 goto retry;
2529 /* live_entry_guards may be empty below. Oh well, we tried. */
2532 choose_and_finish:
2533 r = smartlist_choose(live_entry_guards);
2534 smartlist_free(live_entry_guards);
2535 smartlist_free(exit_family);
2536 return r;
2539 /** Helper: Return the start of the month containing <b>time</b>. */
2540 static time_t
2541 start_of_month(time_t now)
2543 struct tm tm;
2544 tor_gmtime_r(&now, &tm);
2545 tm.tm_sec = 0;
2546 tm.tm_min = 0;
2547 tm.tm_hour = 0;
2548 tm.tm_mday = 1;
2549 return tor_timegm(&tm);
2552 /** Parse <b>state</b> and learn about the entry guards it describes.
2553 * If <b>set</b> is true, and there are no errors, replace the global
2554 * entry_list with what we find.
2555 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2556 * describing the error, and return -1.
2559 entry_guards_parse_state(or_state_t *state, int set, char **msg)
2561 entry_guard_t *node = NULL;
2562 smartlist_t *new_entry_guards = smartlist_create();
2563 config_line_t *line;
2564 time_t now = time(NULL);
2565 const char *state_version = state->TorVersion;
2566 digestmap_t *added_by = digestmap_new();
2568 *msg = NULL;
2569 for (line = state->EntryGuards; line; line = line->next) {
2570 if (!strcasecmp(line->key, "EntryGuard")) {
2571 smartlist_t *args = smartlist_create();
2572 node = tor_malloc_zero(sizeof(entry_guard_t));
2573 /* all entry guards on disk have been contacted */
2574 node->made_contact = 1;
2575 smartlist_add(new_entry_guards, node);
2576 smartlist_split_string(args, line->value, " ",
2577 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2578 if (smartlist_len(args)<2) {
2579 *msg = tor_strdup("Unable to parse entry nodes: "
2580 "Too few arguments to EntryGuard");
2581 } else if (!is_legal_nickname(smartlist_get(args,0))) {
2582 *msg = tor_strdup("Unable to parse entry nodes: "
2583 "Bad nickname for EntryGuard");
2584 } else {
2585 strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
2586 if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
2587 strlen(smartlist_get(args,1)))<0) {
2588 *msg = tor_strdup("Unable to parse entry nodes: "
2589 "Bad hex digest for EntryGuard");
2592 SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
2593 smartlist_free(args);
2594 if (*msg)
2595 break;
2596 } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
2597 !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
2598 time_t when;
2599 time_t last_try = 0;
2600 if (!node) {
2601 *msg = tor_strdup("Unable to parse entry nodes: "
2602 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2603 break;
2605 if (parse_iso_time(line->value, &when)<0) {
2606 *msg = tor_strdup("Unable to parse entry nodes: "
2607 "Bad time in EntryGuardDownSince/UnlistedSince");
2608 break;
2610 if (when > now) {
2611 /* It's a bad idea to believe info in the future: you can wind
2612 * up with timeouts that aren't allowed to happen for years. */
2613 continue;
2615 if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
2616 /* ignore failure */
2617 parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
2619 if (!strcasecmp(line->key, "EntryGuardDownSince")) {
2620 node->unreachable_since = when;
2621 node->last_attempted = last_try;
2622 } else {
2623 node->bad_since = when;
2625 } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
2626 char d[DIGEST_LEN];
2627 /* format is digest version date */
2628 if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
2629 log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
2630 continue;
2632 if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
2633 line->value[HEX_DIGEST_LEN] != ' ') {
2634 log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
2635 "hex digest", escaped(line->value));
2636 continue;
2638 digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
2639 } else {
2640 log_warn(LD_BUG, "Unexpected key %s", line->key);
2644 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
2646 char *sp;
2647 char *val = digestmap_get(added_by, e->identity);
2648 if (val && (sp = strchr(val, ' '))) {
2649 time_t when;
2650 *sp++ = '\0';
2651 if (parse_iso_time(sp, &when)<0) {
2652 log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
2653 } else {
2654 e->chosen_by_version = tor_strdup(val);
2655 e->chosen_on_date = when;
2657 } else {
2658 if (state_version) {
2659 e->chosen_by_version = tor_strdup(state_version);
2660 e->chosen_on_date = start_of_month(time(NULL));
2665 if (*msg || !set) {
2666 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
2667 entry_guard_free(e));
2668 smartlist_free(new_entry_guards);
2669 } else { /* !*err && set */
2670 if (entry_guards) {
2671 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2672 entry_guard_free(e));
2673 smartlist_free(entry_guards);
2675 entry_guards = new_entry_guards;
2676 entry_guards_dirty = 0;
2677 if (remove_obsolete_entry_guards())
2678 entry_guards_dirty = 1;
2680 digestmap_free(added_by, _tor_free);
2681 return *msg ? -1 : 0;
2684 /** Our list of entry guards has changed, or some element of one
2685 * of our entry guards has changed. Write the changes to disk within
2686 * the next few minutes.
2688 static void
2689 entry_guards_changed(void)
2691 time_t when;
2692 entry_guards_dirty = 1;
2694 /* or_state_save() will call entry_guards_update_state(). */
2695 when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
2696 or_state_mark_dirty(get_or_state(), when);
2699 /** If the entry guard info has not changed, do nothing and return.
2700 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2701 * a new one out of the global entry_guards list, and then mark
2702 * <b>state</b> dirty so it will get saved to disk.
2704 void
2705 entry_guards_update_state(or_state_t *state)
2707 config_line_t **next, *line;
2708 if (! entry_guards_dirty)
2709 return;
2711 config_free_lines(state->EntryGuards);
2712 next = &state->EntryGuards;
2713 *next = NULL;
2714 if (!entry_guards)
2715 entry_guards = smartlist_create();
2716 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2718 char dbuf[HEX_DIGEST_LEN+1];
2719 if (!e->made_contact)
2720 continue; /* don't write this one to disk */
2721 *next = line = tor_malloc_zero(sizeof(config_line_t));
2722 line->key = tor_strdup("EntryGuard");
2723 line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
2724 base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
2725 tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
2726 "%s %s", e->nickname, dbuf);
2727 next = &(line->next);
2728 if (e->unreachable_since) {
2729 *next = line = tor_malloc_zero(sizeof(config_line_t));
2730 line->key = tor_strdup("EntryGuardDownSince");
2731 line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
2732 format_iso_time(line->value, e->unreachable_since);
2733 if (e->last_attempted) {
2734 line->value[ISO_TIME_LEN] = ' ';
2735 format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
2737 next = &(line->next);
2739 if (e->bad_since) {
2740 *next = line = tor_malloc_zero(sizeof(config_line_t));
2741 line->key = tor_strdup("EntryGuardUnlistedSince");
2742 line->value = tor_malloc(ISO_TIME_LEN+1);
2743 format_iso_time(line->value, e->bad_since);
2744 next = &(line->next);
2746 if (e->chosen_on_date && e->chosen_by_version &&
2747 !strchr(e->chosen_by_version, ' ')) {
2748 char d[HEX_DIGEST_LEN+1];
2749 char t[ISO_TIME_LEN+1];
2750 size_t val_len;
2751 *next = line = tor_malloc_zero(sizeof(config_line_t));
2752 line->key = tor_strdup("EntryGuardAddedBy");
2753 val_len = (HEX_DIGEST_LEN+1+strlen(e->chosen_by_version)
2754 +1+ISO_TIME_LEN+1);
2755 line->value = tor_malloc(val_len);
2756 base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
2757 format_iso_time(t, e->chosen_on_date);
2758 tor_snprintf(line->value, val_len, "%s %s %s",
2759 d, e->chosen_by_version, t);
2760 next = &(line->next);
2763 if (!get_options()->AvoidDiskWrites)
2764 or_state_mark_dirty(get_or_state(), 0);
2765 entry_guards_dirty = 0;
2768 /** If <b>question</b> is the string "entry-guards", then dump
2769 * to *<b>answer</b> a newly allocated string describing all of
2770 * the nodes in the global entry_guards list. See control-spec.txt
2771 * for details.
2772 * For backward compatibility, we also handle the string "helper-nodes".
2773 * */
2775 getinfo_helper_entry_guards(control_connection_t *conn,
2776 const char *question, char **answer)
2778 int use_long_names = conn->use_long_names;
2780 if (!strcmp(question,"entry-guards") ||
2781 !strcmp(question,"helper-nodes")) {
2782 smartlist_t *sl = smartlist_create();
2783 char tbuf[ISO_TIME_LEN+1];
2784 char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
2785 if (!entry_guards)
2786 entry_guards = smartlist_create();
2787 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2789 size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
2790 char *c = tor_malloc(len);
2791 const char *status = NULL;
2792 time_t when = 0;
2793 if (!e->made_contact) {
2794 status = "never-connected";
2795 } else if (e->bad_since) {
2796 when = e->bad_since;
2797 status = "unusable";
2798 } else {
2799 status = "up";
2801 if (use_long_names) {
2802 routerinfo_t *ri = router_get_by_digest(e->identity);
2803 if (ri) {
2804 router_get_verbose_nickname(nbuf, ri);
2805 } else {
2806 nbuf[0] = '$';
2807 base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
2808 /* e->nickname field is not very reliable if we don't know about
2809 * this router any longer; don't include it. */
2811 } else {
2812 base16_encode(nbuf, sizeof(nbuf), e->identity, DIGEST_LEN);
2814 if (when) {
2815 format_iso_time(tbuf, when);
2816 tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
2817 } else {
2818 tor_snprintf(c, len, "%s %s\n", nbuf, status);
2820 smartlist_add(sl, c);
2822 *answer = smartlist_join_strings(sl, "", 0, NULL);
2823 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
2824 smartlist_free(sl);
2826 return 0;
2829 /** DOCDOC */
2830 typedef struct {
2831 uint32_t addr;
2832 uint16_t port;
2833 char identity[DIGEST_LEN];
2834 download_status_t fetch_status;
2835 } bridge_info_t;
2837 /** A list of known bridges. */
2838 static smartlist_t *bridge_list = NULL;
2840 /** Initialize the bridge list to empty, creating it if needed. */
2841 void
2842 clear_bridge_list(void)
2844 if (!bridge_list)
2845 bridge_list = smartlist_create();
2846 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
2847 smartlist_clear(bridge_list);
2850 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2851 * (either by comparing keys if possible, else by comparing addr/port).
2852 * Else return NULL. */
2853 static bridge_info_t *
2854 routerinfo_get_configured_bridge(routerinfo_t *ri)
2856 if (!bridge_list)
2857 return NULL;
2858 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2860 if (tor_digest_is_zero(bridge->identity) &&
2861 bridge->addr == ri->addr && bridge->port == ri->or_port)
2862 return bridge;
2863 if (!memcmp(bridge->identity, ri->cache_info.identity_digest,
2864 DIGEST_LEN))
2865 return bridge;
2867 return NULL;
2870 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
2872 routerinfo_is_a_configured_bridge(routerinfo_t *ri)
2874 return routerinfo_get_configured_bridge(ri) ? 1 : 0;
2877 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2878 * is set, it tells us the identity key too. */
2879 void
2880 bridge_add_from_config(uint32_t addr, uint16_t port, char *digest)
2882 bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
2883 b->addr = addr;
2884 b->port = port;
2885 if (digest)
2886 memcpy(b->identity, digest, DIGEST_LEN);
2887 if (!bridge_list)
2888 bridge_list = smartlist_create();
2889 smartlist_add(bridge_list, b);
2892 /** Schedule the next fetch for <b>bridge</b>, based on
2893 * some retry schedule. */
2894 static void
2895 bridge_fetch_status_increment(bridge_info_t *bridge, time_t now)
2897 switch (bridge->fetch_status.n_download_failures) {
2898 case 0: bridge->fetch_status.next_attempt_at = now+60*15; break;
2899 case 1: bridge->fetch_status.next_attempt_at = now+60*15; break;
2900 default: bridge->fetch_status.next_attempt_at = now+60*60; break;
2902 if (bridge->fetch_status.n_download_failures < 10)
2903 bridge->fetch_status.n_download_failures++;
2906 /** We just got a new descriptor for <b>bridge</b>. Reschedule the
2907 * next fetch for a long time from <b>now</b>. */
2908 static void
2909 bridge_fetch_status_arrived(bridge_info_t *bridge, time_t now)
2911 tor_assert(bridge);
2912 bridge->fetch_status.next_attempt_at = now+60*60;
2913 bridge->fetch_status.n_download_failures = 0;
2916 /** If <b>digest</b> is one of our known bridges, return it. */
2917 static bridge_info_t *
2918 find_bridge_by_digest(char *digest)
2920 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2922 if (!memcmp(bridge->identity, digest, DIGEST_LEN))
2923 return bridge;
2925 return NULL;
2928 /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
2929 * is a helpful string describing this bridge. */
2930 static void
2931 launch_direct_bridge_descriptor_fetch(char *address, bridge_info_t *bridge)
2933 if (connection_get_by_type_addr_port_purpose(
2934 CONN_TYPE_DIR, bridge->addr, bridge->port,
2935 DIR_PURPOSE_FETCH_SERVERDESC))
2936 return; /* it's already on the way */
2937 directory_initiate_command(address, bridge->addr,
2938 bridge->port, 0,
2939 1, bridge->identity,
2940 DIR_PURPOSE_FETCH_SERVERDESC,
2941 ROUTER_PURPOSE_BRIDGE,
2942 0, "authority.z", NULL, 0, 0);
2945 /** Fetching the bridge descriptor from the bridge authority returned a
2946 * "not found". Fall back to trying a direct fetch. */
2947 void
2948 retry_bridge_descriptor_fetch_directly(char *digest)
2950 bridge_info_t *bridge = find_bridge_by_digest(digest);
2951 char address_buf[INET_NTOA_BUF_LEN+1];
2952 struct in_addr in;
2954 if (!bridge)
2955 return; /* not found? oh well. */
2957 in.s_addr = htonl(bridge->addr);
2958 tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
2959 launch_direct_bridge_descriptor_fetch(address_buf, bridge);
2962 /** For each bridge in our list for which we don't currently have a
2963 * descriptor, fetch a new copy of its descriptor -- either directly
2964 * from the bridge or via a bridge authority. */
2965 void
2966 fetch_bridge_descriptors(time_t now)
2968 char address_buf[INET_NTOA_BUF_LEN+1];
2969 struct in_addr in;
2970 or_options_t *options = get_options();
2971 int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
2972 int ask_bridge_directly;
2973 int can_use_bridge_authority;
2975 if (!bridge_list)
2976 return;
2978 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2980 if (bridge->fetch_status.next_attempt_at > now)
2981 continue; /* don't bother, no need to retry yet */
2983 /* schedule another fetch as if this one will fail, in case it does */
2984 bridge_fetch_status_increment(bridge, now);
2986 in.s_addr = htonl(bridge->addr);
2987 tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
2989 can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
2990 num_bridge_auths;
2991 ask_bridge_directly = !can_use_bridge_authority ||
2992 !options->UpdateBridgesFromAuthority;
2993 log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
2994 ask_bridge_directly, tor_digest_is_zero(bridge->identity),
2995 !options->UpdateBridgesFromAuthority, !num_bridge_auths);
2997 if (ask_bridge_directly &&
2998 !fascist_firewall_allows_address_or(bridge->addr, bridge->port)) {
2999 log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
3000 "firewall policy. %s.", address_buf, bridge->port,
3001 can_use_bridge_authority ?
3002 "Asking bridge authority instead" : "Skipping");
3003 if (can_use_bridge_authority)
3004 ask_bridge_directly = 0;
3005 else
3006 continue;
3009 if (ask_bridge_directly) {
3010 /* we need to ask the bridge itself for its descriptor. */
3011 launch_direct_bridge_descriptor_fetch(address_buf, bridge);
3012 } else {
3013 /* We have a digest and we want to ask an authority. We could
3014 * combine all the requests into one, but that may give more
3015 * hints to the bridge authority than we want to give. */
3016 char resource[10 + HEX_DIGEST_LEN];
3017 memcpy(resource, "fp/", 3);
3018 base16_encode(resource+3, HEX_DIGEST_LEN+1,
3019 bridge->identity, DIGEST_LEN);
3020 memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
3021 log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
3022 resource);
3023 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
3024 ROUTER_PURPOSE_BRIDGE, resource, 0);
3029 /** We just learned a descriptor for a bridge. See if that
3030 * digest is in our entry guard list, and add it if not. */
3031 void
3032 learned_bridge_descriptor(routerinfo_t *ri)
3034 tor_assert(ri);
3035 tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
3036 if (get_options()->UseBridges) {
3037 int first = !any_bridge_descriptors_known();
3038 bridge_info_t *bridge = routerinfo_get_configured_bridge(ri);
3039 time_t now = time(NULL);
3040 ri->is_running = 1;
3042 if (bridge) { /* if we actually want to use this one */
3043 /* it's here; schedule its re-fetch for a long time from now. */
3044 bridge_fetch_status_arrived(bridge, now);
3046 add_an_entry_guard(ri, 1);
3047 log_notice(LD_DIR, "new bridge descriptor '%s'", ri->nickname);
3048 if (first)
3049 routerlist_retry_directory_downloads(now);
3054 /** Return 1 if any of our entry guards have descriptors that
3055 * are marked with purpose 'bridge' and are running. Else return 0.
3057 * We use this function to decide if we're ready to start building
3058 * circuits through our bridges, or if we need to wait until the
3059 * directory "server/authority" requests finish. */
3061 any_bridge_descriptors_known(void)
3063 tor_assert(get_options()->UseBridges);
3064 return choose_random_entry(NULL)!=NULL ? 1 : 0;
3067 /** Return 1 if we have at least one descriptor for a bridge and
3068 * all descriptors we know are down. Else return 0. If <b>act</b> is
3069 * 1, then mark the down bridges up; else just observe and report. */
3070 static int
3071 bridges_retry_helper(int act)
3073 routerinfo_t *ri;
3074 int any_known = 0;
3075 int any_running = 0;
3076 if (!entry_guards)
3077 entry_guards = smartlist_create();
3078 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
3080 ri = router_get_by_digest(e->identity);
3081 if (ri && ri->purpose == ROUTER_PURPOSE_BRIDGE) {
3082 any_known = 1;
3083 if (ri->is_running)
3084 any_running = 1; /* some bridge is both known and running */
3085 else if (act) { /* mark it for retry */
3086 ri->is_running = 1;
3087 e->can_retry = 1;
3088 e->bad_since = 0;
3092 return any_known && !any_running;
3095 /** Do we know any descriptors for our bridges, and are they all
3096 * down? */
3098 bridges_known_but_down(void)
3100 return bridges_retry_helper(0);
3103 /** Mark all down known bridges up. */
3104 void
3105 bridges_retry_all(void)
3107 bridges_retry_helper(1);
3110 /** Release all storage held by the list of entry guards and related
3111 * memory structs. */
3112 void
3113 entry_guards_free_all(void)
3115 if (entry_guards) {
3116 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
3117 entry_guard_free(e));
3118 smartlist_free(entry_guards);
3119 entry_guards = NULL;
3121 clear_bridge_list();
3122 smartlist_free(bridge_list);
3123 bridge_list = NULL;