using fascistfirewall and having your bridge on an unreachable
[tor.git] / src / or / circuitbuild.c
blobe56b92dd2ca46106da73db700c9a77e09966c471
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char circuitbuild_c_id[] =
7 "$Id$";
9 /**
10 * \file circuitbuild.c
11 * \brief The actual details of building circuits.
12 **/
14 #include "or.h"
16 /********* START VARIABLES **********/
18 /** A global list of all circuits at this hop. */
19 extern circuit_t *global_circuitlist;
21 /** An entry_guard_t represents our information about a chosen long-term
22 * first hop, known as a "helper" node in the literature. We can't just
23 * use a routerinfo_t, since we want to remember these even when we
24 * don't have a directory. */
25 typedef struct {
26 char nickname[MAX_NICKNAME_LEN+1];
27 char identity[DIGEST_LEN];
28 unsigned int made_contact : 1; /**< 0 if we have never connected to this
29 * router, 1 if we have. */
30 unsigned int can_retry : 1; /**< Should we retry connecting to this entry,
31 * in spite of having it marked as unreachable?*/
32 time_t bad_since; /**< 0 if this guard is currently usable, or the time at
33 * which it was observed to become (according to the
34 * directory or the user configuration) unusable. */
35 time_t unreachable_since; /**< 0 if we can connect to this guard, or the
36 * time at which we first noticed we couldn't
37 * connect to it. */
38 time_t last_attempted; /**< 0 if we can connect to this guard, or the time
39 * at which we last failed to connect to it. */
40 } entry_guard_t;
42 /** A list of our chosen entry guards. */
43 static smartlist_t *entry_guards = NULL;
44 /** A value of 1 means that the entry_guards list has changed
45 * and those changes need to be flushed to disk. */
46 static int entry_guards_dirty = 0;
48 /********* END VARIABLES ************/
50 static int circuit_deliver_create_cell(circuit_t *circ,
51 uint8_t cell_type, const char *payload);
52 static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
53 static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
54 static int onion_extend_cpath(origin_circuit_t *circ);
55 static int count_acceptable_routers(smartlist_t *routers);
56 static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
58 static void entry_guards_changed(void);
60 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
61 * and with the high bit specified by conn-\>circ_id_type, until we get
62 * a circ_id that is not in use by any other circuit on that conn.
64 * Return it, or 0 if can't get a unique circ_id.
66 static uint16_t
67 get_unique_circ_id_by_conn(or_connection_t *conn)
69 uint16_t test_circ_id;
70 uint16_t attempts=0;
71 uint16_t high_bit;
73 tor_assert(conn);
74 if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
75 log_warn(LD_BUG, "Trying to pick a circuit ID for a connection from "
76 "a client with no identity.");
77 return 0;
79 high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
80 do {
81 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
82 * circID such that (high_bit|test_circ_id) is not already used. */
83 test_circ_id = conn->next_circ_id++;
84 if (test_circ_id == 0 || test_circ_id >= 1<<15) {
85 test_circ_id = 1;
86 conn->next_circ_id = 2;
88 if (++attempts > 1<<15) {
89 /* Make sure we don't loop forever if all circ_id's are used. This
90 * matters because it's an external DoS opportunity.
92 log_warn(LD_CIRC,"No unused circ IDs. Failing.");
93 return 0;
95 test_circ_id |= high_bit;
96 } while (circuit_get_by_circid_orconn(test_circ_id, conn));
97 return test_circ_id;
100 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
101 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
102 * list information about link status in a more verbose format using spaces.
103 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
104 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
105 * names.
107 static char *
108 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
110 crypt_path_t *hop;
111 smartlist_t *elements;
112 const char *states[] = {"closed", "waiting for keys", "open"};
113 char buf[128];
114 char *s;
116 elements = smartlist_create();
118 if (verbose) {
119 const char *nickname = build_state_get_exit_nickname(circ->build_state);
120 tor_snprintf(buf, sizeof(buf), "%s%s circ (length %d%s%s):",
121 circ->build_state->is_internal ? "internal" : "exit",
122 circ->build_state->need_uptime ? " (high-uptime)" : "",
123 circ->build_state->desired_path_len,
124 circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", exit ",
125 circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
126 (nickname?nickname:"*unnamed*"));
127 smartlist_add(elements, tor_strdup(buf));
130 hop = circ->cpath;
131 do {
132 routerinfo_t *ri;
133 char *elt;
134 if (!hop)
135 break;
136 if (!verbose && hop->state != CPATH_STATE_OPEN)
137 break;
138 if (!hop->extend_info)
139 break;
140 if (verbose_names) {
141 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
142 if ((ri = router_get_by_digest(hop->extend_info->identity_digest))) {
143 router_get_verbose_nickname(elt, ri);
144 } else if (hop->extend_info->nickname &&
145 is_legal_nickname(hop->extend_info->nickname)) {
146 elt[0] = '$';
147 base16_encode(elt+1, HEX_DIGEST_LEN+1,
148 hop->extend_info->identity_digest, DIGEST_LEN);
149 elt[HEX_DIGEST_LEN+1]= '~';
150 strlcpy(elt+HEX_DIGEST_LEN+2,
151 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
152 } else {
153 elt[0] = '$';
154 base16_encode(elt+1, HEX_DIGEST_LEN+1,
155 hop->extend_info->identity_digest, DIGEST_LEN);
157 } else { /* ! verbose_names */
158 if ((ri = router_get_by_digest(hop->extend_info->identity_digest)) &&
159 ri->is_named) {
160 elt = tor_strdup(hop->extend_info->nickname);
161 } else {
162 elt = tor_malloc(HEX_DIGEST_LEN+2);
163 elt[0] = '$';
164 base16_encode(elt+1, HEX_DIGEST_LEN+1,
165 hop->extend_info->identity_digest, DIGEST_LEN);
168 tor_assert(elt);
169 if (verbose) {
170 size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
171 char *v = tor_malloc(len);
172 tor_assert(hop->state <= 2);
173 tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
174 smartlist_add(elements, v);
175 tor_free(elt);
176 } else {
177 smartlist_add(elements, elt);
179 hop = hop->next;
180 } while (hop != circ->cpath);
182 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
183 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
184 smartlist_free(elements);
185 return s;
188 /** If <b>verbose</b> is false, allocate and return a comma-separated
189 * list of the currently built elements of circuit_t. If
190 * <b>verbose</b> is true, also list information about link status in
191 * a more verbose format using spaces.
193 char *
194 circuit_list_path(origin_circuit_t *circ, int verbose)
196 return circuit_list_path_impl(circ, verbose, 0);
199 /** Allocate and return a comma-separated list of the currently built elements
200 * of circuit_t, giving each as a verbose nickname.
202 char *
203 circuit_list_path_for_controller(origin_circuit_t *circ)
205 return circuit_list_path_impl(circ, 0, 1);
208 /** Log, at severity <b>severity</b>, the nicknames of each router in
209 * circ's cpath. Also log the length of the cpath, and the intended
210 * exit point.
212 void
213 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
215 char *s = circuit_list_path(circ,1);
216 log(severity,domain,"%s",s);
217 tor_free(s);
220 /** Tell the rep(utation)hist(ory) module about the status of the links
221 * in circ. Hops that have become OPEN are marked as successfully
222 * extended; the _first_ hop that isn't open (if any) is marked as
223 * unable to extend.
225 /* XXXX Someday we should learn from OR circuits too. */
226 void
227 circuit_rep_hist_note_result(origin_circuit_t *circ)
229 crypt_path_t *hop;
230 char *prev_digest = NULL;
231 routerinfo_t *router;
232 hop = circ->cpath;
233 if (!hop) /* circuit hasn't started building yet. */
234 return;
235 if (server_mode(get_options())) {
236 routerinfo_t *me = router_get_my_routerinfo();
237 if (!me)
238 return;
239 prev_digest = me->cache_info.identity_digest;
241 do {
242 router = router_get_by_digest(hop->extend_info->identity_digest);
243 if (router) {
244 if (prev_digest) {
245 if (hop->state == CPATH_STATE_OPEN)
246 rep_hist_note_extend_succeeded(prev_digest,
247 router->cache_info.identity_digest);
248 else {
249 rep_hist_note_extend_failed(prev_digest,
250 router->cache_info.identity_digest);
251 break;
254 prev_digest = router->cache_info.identity_digest;
255 } else {
256 prev_digest = NULL;
258 hop=hop->next;
259 } while (hop!=circ->cpath);
262 /** Pick all the entries in our cpath. Stop and return 0 when we're
263 * happy, or return -1 if an error occurs. */
264 static int
265 onion_populate_cpath(origin_circuit_t *circ)
267 int r;
268 again:
269 r = onion_extend_cpath(circ);
270 if (r < 0) {
271 log_info(LD_CIRC,"Generating cpath hop failed.");
272 return -1;
274 if (r == 0)
275 goto again;
276 return 0; /* if r == 1 */
279 /** Create and return a new origin circuit. Initialize its purpose and
280 * build-state based on our arguments. */
281 origin_circuit_t *
282 origin_circuit_init(uint8_t purpose, int onehop_tunnel,
283 int need_uptime, int need_capacity, int internal)
285 /* sets circ->p_circ_id and circ->p_conn */
286 origin_circuit_t *circ = origin_circuit_new();
287 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
288 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
289 circ->build_state->onehop_tunnel = onehop_tunnel;
290 circ->build_state->need_uptime = need_uptime;
291 circ->build_state->need_capacity = need_capacity;
292 circ->build_state->is_internal = internal;
293 circ->_base.purpose = purpose;
294 return circ;
297 /** Build a new circuit for <b>purpose</b>. If <b>info</b>
298 * is defined, then use that as your exit router, else choose a suitable
299 * exit node.
301 * Also launch a connection to the first OR in the chosen path, if
302 * it's not open already.
304 origin_circuit_t *
305 circuit_establish_circuit(uint8_t purpose, int onehop_tunnel,
306 extend_info_t *exit,
307 int need_uptime, int need_capacity, int internal)
309 origin_circuit_t *circ;
310 int err_reason = 0;
312 circ = origin_circuit_init(purpose, onehop_tunnel,
313 need_uptime, need_capacity, internal);
315 if (onion_pick_cpath_exit(circ, exit) < 0 ||
316 onion_populate_cpath(circ) < 0) {
317 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
318 return NULL;
321 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
323 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
324 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
325 return NULL;
327 return circ;
330 /** Start establishing the first hop of our circuit. Figure out what
331 * OR we should connect to, and if necessary start the connection to
332 * it. If we're already connected, then send the 'create' cell.
333 * Return 0 for ok, -reason if circ should be marked-for-close. */
335 circuit_handle_first_hop(origin_circuit_t *circ)
337 crypt_path_t *firsthop;
338 or_connection_t *n_conn;
339 char tmpbuf[INET_NTOA_BUF_LEN];
340 struct in_addr in;
341 int err_reason = 0;
343 firsthop = onion_next_hop_in_cpath(circ->cpath);
344 tor_assert(firsthop);
345 tor_assert(firsthop->extend_info);
347 /* now see if we're already connected to the first OR in 'route' */
348 in.s_addr = htonl(firsthop->extend_info->addr);
349 tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
350 log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",tmpbuf,
351 firsthop->extend_info->port);
352 /* imprint the circuit with its future n_conn->id */
353 memcpy(circ->_base.n_conn_id_digest, firsthop->extend_info->identity_digest,
354 DIGEST_LEN);
355 n_conn = connection_or_get_by_identity_digest(
356 firsthop->extend_info->identity_digest);
357 /* If we don't have an open conn, or the conn we have is obsolete
358 * (i.e. old or broken) and the other side will let us make a second
359 * connection without dropping it immediately... */
360 if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
361 (n_conn->_base.or_is_obsolete &&
362 router_digest_version_as_new_as(firsthop->extend_info->identity_digest,
363 "0.1.1.9-alpha-cvs"))) {
364 /* not currently connected */
365 circ->_base.n_addr = firsthop->extend_info->addr;
366 circ->_base.n_port = firsthop->extend_info->port;
368 if (!n_conn || n_conn->_base.or_is_obsolete) { /* launch the connection */
369 n_conn = connection_or_connect(firsthop->extend_info->addr,
370 firsthop->extend_info->port,
371 firsthop->extend_info->identity_digest);
372 if (!n_conn) { /* connect failed, forget the whole thing */
373 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
374 return -END_CIRC_REASON_CONNECTFAILED;
378 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
379 /* return success. The onion/circuit/etc will be taken care of
380 * automatically (may already have been) whenever n_conn reaches
381 * OR_CONN_STATE_OPEN.
383 return 0;
384 } else { /* it's already open. use it. */
385 circ->_base.n_addr = n_conn->_base.addr;
386 circ->_base.n_port = n_conn->_base.port;
387 circ->_base.n_conn = n_conn;
388 log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
389 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
390 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
391 return err_reason;
394 return 0;
397 /** Find any circuits that are waiting on <b>or_conn</b> to become
398 * open and get them to send their create cells forward.
400 * Status is 1 if connect succeeded, or 0 if connect failed.
402 void
403 circuit_n_conn_done(or_connection_t *or_conn, int status)
405 smartlist_t *pending_circs;
406 int err_reason = 0;
408 log_debug(LD_CIRC,"or_conn to %s, status=%d",
409 or_conn->nickname ? or_conn->nickname : "NULL", status);
411 pending_circs = smartlist_create();
412 circuit_get_all_pending_on_or_conn(pending_circs, or_conn);
414 SMARTLIST_FOREACH(pending_circs, circuit_t *, circ,
416 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
417 * leaving them in in case it's possible for the status of a circuit to
418 * change as we're going down the list. */
419 if (circ->marked_for_close || circ->n_conn ||
420 circ->state != CIRCUIT_STATE_OR_WAIT)
421 continue;
422 if (tor_digest_is_zero(circ->n_conn_id_digest)) {
423 /* Look at addr/port. This is an unkeyed connection. */
424 if (circ->n_addr != or_conn->_base.addr ||
425 circ->n_port != or_conn->_base.port)
426 continue;
427 /* now teach circ the right identity_digest */
428 memcpy(circ->n_conn_id_digest, or_conn->identity_digest, DIGEST_LEN);
429 } else {
430 /* We expected a key. See if it's the right one. */
431 if (memcmp(or_conn->identity_digest,
432 circ->n_conn_id_digest, DIGEST_LEN))
433 continue;
435 if (!status) { /* or_conn failed; close circ */
436 log_info(LD_CIRC,"or_conn failed. Closing circ.");
437 circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
438 continue;
440 log_debug(LD_CIRC, "Found circ, sending create cell.");
441 /* circuit_deliver_create_cell will set n_circ_id and add us to
442 * orconn_circuid_circuit_map, so we don't need to call
443 * set_circid_orconn here. */
444 circ->n_conn = or_conn;
445 if (CIRCUIT_IS_ORIGIN(circ)) {
446 if ((err_reason =
447 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
448 log_info(LD_CIRC,
449 "send_next_onion_skin failed; circuit marked for closing.");
450 circuit_mark_for_close(circ, -err_reason);
451 continue;
452 /* XXX could this be bad, eg if next_onion_skin failed because conn
453 * died? */
455 } else {
456 /* pull the create cell out of circ->onionskin, and send it */
457 tor_assert(circ->onionskin);
458 if (circuit_deliver_create_cell(circ,CELL_CREATE,circ->onionskin)<0) {
459 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
460 continue;
462 tor_free(circ->onionskin);
463 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
467 smartlist_free(pending_circs);
470 /** Find a new circid that isn't currently in use on the circ->n_conn
471 * for the outgoing
472 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
473 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
474 * to this circuit.
475 * Return -1 if we failed to find a suitable circid, else return 0.
477 static int
478 circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
479 const char *payload)
481 cell_t cell;
482 uint16_t id;
484 tor_assert(circ);
485 tor_assert(circ->n_conn);
486 tor_assert(payload);
487 tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
489 id = get_unique_circ_id_by_conn(circ->n_conn);
490 if (!id) {
491 log_warn(LD_CIRC,"failed to get unique circID.");
492 return -1;
494 log_debug(LD_CIRC,"Chosen circID %u.", id);
495 circuit_set_n_circid_orconn(circ, id, circ->n_conn);
497 memset(&cell, 0, sizeof(cell_t));
498 cell.command = cell_type;
499 cell.circ_id = circ->n_circ_id;
501 memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
502 append_cell_to_circuit_queue(circ, circ->n_conn, &cell, CELL_DIRECTION_OUT);
504 /* mark it so it gets better rate limiting treatment. */
505 circ->n_conn->client_used = 1;
507 return 0;
510 /** We've decided to start our reachability testing. If all
511 * is set, log this to the user. Return 1 if we did, or 0 if
512 * we chose not to log anything. */
514 inform_testing_reachability(void)
516 char dirbuf[128];
517 routerinfo_t *me = router_get_my_routerinfo();
518 if (!me)
519 return 0;
520 if (me->dir_port)
521 tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
522 me->address, me->dir_port);
523 log(LOG_NOTICE, LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
524 "(this may take up to %d minutes -- look for log "
525 "messages indicating success)",
526 me->address, me->or_port,
527 me->dir_port ? dirbuf : "",
528 me->dir_port ? "are" : "is",
529 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
530 return 1;
533 /** Return true iff we should send a create_fast cell to build a circuit
534 * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
535 * information on the router, so assume true.) */
536 static INLINE int
537 should_use_create_fast_for_router(routerinfo_t *router,
538 origin_circuit_t *circ)
540 or_options_t *options = get_options();
542 if (!options->FastFirstHopPK) /* create_fast is disabled */
543 return 0;
544 if (router && router->platform &&
545 !tor_version_as_new_as(router->platform, "0.1.0.6-rc")) {
546 /* known not to work */
547 return 0;
549 if (server_mode(options) && circ->cpath->extend_info->onion_key) {
550 /* We're a server, and we know an onion key. We can choose.
551 * Prefer to blend in. */
552 return 0;
555 return 1;
558 /** This is the backbone function for building circuits.
560 * If circ's first hop is closed, then we need to build a create
561 * cell and send it forward.
563 * Otherwise, we need to build a relay extend cell and send it
564 * forward.
566 * Return -reason if we want to tear down circ, else return 0.
569 circuit_send_next_onion_skin(origin_circuit_t *circ)
571 crypt_path_t *hop;
572 routerinfo_t *router;
573 char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
574 char *onionskin;
575 size_t payload_len;
577 tor_assert(circ);
579 if (circ->cpath->state == CPATH_STATE_CLOSED) {
580 int fast;
581 uint8_t cell_type;
582 log_debug(LD_CIRC,"First skin; sending create cell.");
584 router = router_get_by_digest(circ->_base.n_conn->identity_digest);
585 fast = should_use_create_fast_for_router(router, circ);
586 if (!fast && !circ->cpath->extend_info->onion_key) {
587 log_warn(LD_CIRC,
588 "Can't send create_fast, but have no onion key. Failing.");
589 return - END_CIRC_REASON_INTERNAL;
591 if (!fast) {
592 /* We are an OR, or we are connecting to an old Tor: we should
593 * send an old slow create cell.
595 cell_type = CELL_CREATE;
596 if (onion_skin_create(circ->cpath->extend_info->onion_key,
597 &(circ->cpath->dh_handshake_state),
598 payload) < 0) {
599 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
600 return - END_CIRC_REASON_INTERNAL;
602 } else {
603 /* We are not an OR, and we're building the first hop of a circuit to a
604 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
605 * and a DH operation. */
606 cell_type = CELL_CREATE_FAST;
607 memset(payload, 0, sizeof(payload));
608 crypto_rand(circ->cpath->fast_handshake_state,
609 sizeof(circ->cpath->fast_handshake_state));
610 memcpy(payload, circ->cpath->fast_handshake_state,
611 sizeof(circ->cpath->fast_handshake_state));
614 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
615 return - END_CIRC_REASON_RESOURCELIMIT;
617 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
618 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
619 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
620 fast ? "CREATE_FAST" : "CREATE",
621 router ? router->nickname : "<unnamed>");
622 } else {
623 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
624 tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
625 log_debug(LD_CIRC,"starting to send subsequent skin.");
626 hop = onion_next_hop_in_cpath(circ->cpath);
627 if (!hop) {
628 /* done building the circuit. whew. */
629 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
630 log_info(LD_CIRC,"circuit built!");
631 circuit_reset_failure_count(0);
632 if (!has_completed_circuit && !circ->build_state->onehop_tunnel) {
633 or_options_t *options = get_options();
634 has_completed_circuit=1;
635 /* FFFF Log a count of known routers here */
636 log(LOG_NOTICE, LD_GENERAL,
637 "Tor has successfully opened a circuit. "
638 "Looks like client functionality is working.");
639 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
640 if (server_mode(options) && !check_whether_orport_reachable()) {
641 inform_testing_reachability();
642 consider_testing_reachability(1, 1);
645 circuit_rep_hist_note_result(circ);
646 circuit_has_opened(circ); /* do other actions as necessary */
647 return 0;
650 set_uint32(payload, htonl(hop->extend_info->addr));
651 set_uint16(payload+4, htons(hop->extend_info->port));
653 onionskin = payload+2+4;
654 memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
655 hop->extend_info->identity_digest, DIGEST_LEN);
656 payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
658 if (onion_skin_create(hop->extend_info->onion_key,
659 &(hop->dh_handshake_state), onionskin) < 0) {
660 log_warn(LD_CIRC,"onion_skin_create failed.");
661 return - END_CIRC_REASON_INTERNAL;
664 log_info(LD_CIRC,"Sending extend relay cell.");
665 /* send it to hop->prev, because it will transfer
666 * it to a create cell and then send to hop */
667 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
668 RELAY_COMMAND_EXTEND,
669 payload, payload_len, hop->prev) < 0)
670 return 0; /* circuit is closed */
672 hop->state = CPATH_STATE_AWAITING_KEYS;
674 return 0;
677 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
678 * something has also gone wrong with our network: notify the user,
679 * and abandon all not-yet-used circuits. */
680 void
681 circuit_note_clock_jumped(int seconds_elapsed)
683 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
684 log(severity, LD_GENERAL, "Your clock just jumped %d seconds %s; "
685 "assuming established circuits no longer work.",
686 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
687 seconds_elapsed >=0 ? "forward" : "backward");
688 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
689 seconds_elapsed);
690 has_completed_circuit=0; /* so it'll log when it works again */
691 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
692 "CLOCK_JUMPED");
693 circuit_mark_all_unused_circs();
694 circuit_expire_all_dirty_circs();
697 /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
698 * sure we're connected to the next hop, and pass it the onion skin using
699 * a create cell. Return -1 if we want to warn and tear down the circuit,
700 * else return 0.
703 circuit_extend(cell_t *cell, circuit_t *circ)
705 or_connection_t *n_conn;
706 relay_header_t rh;
707 char *onionskin;
708 char *id_digest=NULL;
710 if (circ->n_conn) {
711 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
712 "n_conn already set. Bug/attack. Closing.");
713 return -1;
716 if (!server_mode(get_options())) {
717 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
718 "Got an extend cell, but running as a client. Closing.");
719 return -1;
722 relay_header_unpack(&rh, cell->payload);
724 if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
725 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
726 "Wrong length %d on extend cell. Closing circuit.",
727 rh.length);
728 return -1;
731 circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
732 circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
734 onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
735 id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
736 n_conn = connection_or_get_by_identity_digest(id_digest);
738 /* If we don't have an open conn, or the conn we have is obsolete
739 * (i.e. old or broken) and the other side will let us make a second
740 * connection without dropping it immediately... */
741 if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
742 (n_conn->_base.or_is_obsolete &&
743 router_digest_version_as_new_as(id_digest,"0.1.1.9-alpha-cvs"))) {
744 struct in_addr in;
745 char tmpbuf[INET_NTOA_BUF_LEN];
746 in.s_addr = htonl(circ->n_addr);
747 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
748 log_info(LD_CIRC|LD_OR,"Next router (%s:%d) not connected. Connecting.",
749 tmpbuf, circ->n_port);
751 circ->onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
752 memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
753 circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
755 /* imprint the circuit with its future n_conn->id */
756 memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
758 if (n_conn && !n_conn->_base.or_is_obsolete) {
759 circ->n_addr = n_conn->_base.addr;
760 circ->n_port = n_conn->_base.port;
761 } else {
762 /* we should try to open a connection */
763 n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
764 if (!n_conn) {
765 log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
766 circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
767 return 0;
769 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
771 /* return success. The onion/circuit/etc will be taken care of
772 * automatically (may already have been) whenever n_conn reaches
773 * OR_CONN_STATE_OPEN.
775 return 0;
778 /* these may be different if the router connected to us from elsewhere */
779 circ->n_addr = n_conn->_base.addr;
780 circ->n_port = n_conn->_base.port;
782 circ->n_conn = n_conn;
783 memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
784 log_debug(LD_CIRC,"n_conn is %s:%u",
785 n_conn->_base.address,n_conn->_base.port);
787 if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
788 return -1;
789 return 0;
792 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
793 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
794 * used as follows:
795 * - 20 to initialize f_digest
796 * - 20 to initialize b_digest
797 * - 16 to key f_crypto
798 * - 16 to key b_crypto
800 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
803 circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
804 int reverse)
806 crypto_digest_env_t *tmp_digest;
807 crypto_cipher_env_t *tmp_crypto;
809 tor_assert(cpath);
810 tor_assert(key_data);
811 tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
812 cpath->f_digest || cpath->b_digest));
814 cpath->f_digest = crypto_new_digest_env();
815 crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
816 cpath->b_digest = crypto_new_digest_env();
817 crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
819 if (!(cpath->f_crypto =
820 crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
821 log_warn(LD_BUG,"Forward cipher initialization failed.");
822 return -1;
824 if (!(cpath->b_crypto =
825 crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
826 log_warn(LD_BUG,"Backward cipher initialization failed.");
827 return -1;
830 if (reverse) {
831 tmp_digest = cpath->f_digest;
832 cpath->f_digest = cpath->b_digest;
833 cpath->b_digest = tmp_digest;
834 tmp_crypto = cpath->f_crypto;
835 cpath->f_crypto = cpath->b_crypto;
836 cpath->b_crypto = tmp_crypto;
839 return 0;
842 /** A created or extended cell came back to us on the circuit, and it included
843 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
844 * contains (the second DH key, plus KH). If <b>reply_type</b> is
845 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
847 * Calculate the appropriate keys and digests, make sure KH is
848 * correct, and initialize this hop of the cpath.
850 * Return - reason if we want to mark circ for close, else return 0.
853 circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
854 const char *reply)
856 char keys[CPATH_KEY_MATERIAL_LEN];
857 crypt_path_t *hop;
859 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
860 hop = circ->cpath;
861 else {
862 hop = onion_next_hop_in_cpath(circ->cpath);
863 if (!hop) { /* got an extended when we're all done? */
864 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
865 return - END_CIRC_REASON_TORPROTOCOL;
868 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
870 if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
871 if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
872 DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
873 log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
874 return -END_CIRC_REASON_TORPROTOCOL;
876 /* Remember hash of g^xy */
877 memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
878 } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
879 if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
880 DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
881 log_warn(LD_CIRC,"fast_client_handshake failed.");
882 return -END_CIRC_REASON_TORPROTOCOL;
884 memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
885 } else {
886 log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
887 return -END_CIRC_REASON_TORPROTOCOL;
890 if (hop->dh_handshake_state) {
891 crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
892 hop->dh_handshake_state = NULL;
894 memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
896 if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
897 return -END_CIRC_REASON_TORPROTOCOL;
900 hop->state = CPATH_STATE_OPEN;
901 log_info(LD_CIRC,"Finished building %scircuit hop:",
902 (reply_type == CELL_CREATED_FAST) ? "fast " : "");
903 circuit_log_path(LOG_INFO,LD_CIRC,circ);
904 control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
906 return 0;
909 /** We received a relay truncated cell on circ.
911 * Since we don't ask for truncates currently, getting a truncated
912 * means that a connection broke or an extend failed. For now,
913 * just give up: for circ to close, and return 0.
916 circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
918 // crypt_path_t *victim;
919 // connection_t *stream;
921 tor_assert(circ);
922 tor_assert(layer);
924 /* XXX Since we don't ask for truncates currently, getting a truncated
925 * means that a connection broke or an extend failed. For now,
926 * just give up.
928 circuit_mark_for_close(TO_CIRCUIT(circ),
929 END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
930 return 0;
932 #if 0
933 while (layer->next != circ->cpath) {
934 /* we need to clear out layer->next */
935 victim = layer->next;
936 log_debug(LD_CIRC, "Killing a layer of the cpath.");
938 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
939 if (stream->cpath_layer == victim) {
940 log_info(LD_APP, "Marking stream %d for close because of truncate.",
941 stream->stream_id);
942 /* no need to send 'end' relay cells,
943 * because the other side's already dead
945 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
949 layer->next = victim->next;
950 circuit_free_cpath_node(victim);
953 log_info(LD_CIRC, "finished");
954 return 0;
955 #endif
958 /** Given a response payload and keys, initialize, then send a created
959 * cell back.
962 onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
963 const char *keys)
965 cell_t cell;
966 crypt_path_t *tmp_cpath;
968 tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
969 tmp_cpath->magic = CRYPT_PATH_MAGIC;
971 memset(&cell, 0, sizeof(cell_t));
972 cell.command = cell_type;
973 cell.circ_id = circ->p_circ_id;
975 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
977 memcpy(cell.payload, payload,
978 cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
980 log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
981 (unsigned int)*(uint32_t*)(keys),
982 (unsigned int)*(uint32_t*)(keys+20));
983 if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
984 log_warn(LD_BUG,"Circuit initialization failed");
985 tor_free(tmp_cpath);
986 return -1;
988 circ->n_digest = tmp_cpath->f_digest;
989 circ->n_crypto = tmp_cpath->f_crypto;
990 circ->p_digest = tmp_cpath->b_digest;
991 circ->p_crypto = tmp_cpath->b_crypto;
992 tmp_cpath->magic = 0;
993 tor_free(tmp_cpath);
995 if (cell_type == CELL_CREATED)
996 memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
997 else
998 memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
1000 circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
1002 append_cell_to_circuit_queue(TO_CIRCUIT(circ),
1003 circ->p_conn, &cell, CELL_DIRECTION_IN);
1004 log_debug(LD_CIRC,"Finished sending 'created' cell.");
1006 if (!is_local_IP(circ->p_conn->_base.addr) &&
1007 !connection_or_nonopen_was_started_here(circ->p_conn)) {
1008 /* record that we could process create cells from a non-local conn
1009 * that we didn't initiate; presumably this means that create cells
1010 * can reach us too. */
1011 router_orport_found_reachable();
1014 return 0;
1017 /** Choose a length for a circuit of purpose <b>purpose</b>.
1018 * Default length is 3 + the number of endpoints that would give something
1019 * away. If the routerlist <b>routers</b> doesn't have enough routers
1020 * to handle the desired path length, return as large a path length as
1021 * is feasible, except if it's less than 2, in which case return -1.
1023 static int
1024 new_route_len(uint8_t purpose, extend_info_t *exit,
1025 smartlist_t *routers)
1027 int num_acceptable_routers;
1028 int routelen;
1030 tor_assert(routers);
1032 #ifdef TOR_PERF
1033 routelen = 2;
1034 #else
1035 routelen = 3;
1036 if (exit &&
1037 purpose != CIRCUIT_PURPOSE_TESTING &&
1038 purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
1039 routelen++;
1040 #endif
1041 log_debug(LD_CIRC,"Chosen route length %d (%d routers available).",
1042 routelen, smartlist_len(routers));
1044 num_acceptable_routers = count_acceptable_routers(routers);
1046 if (num_acceptable_routers < 2) {
1047 log_info(LD_CIRC,
1048 "Not enough acceptable routers (%d). Discarding this circuit.",
1049 num_acceptable_routers);
1050 return -1;
1053 if (num_acceptable_routers < routelen) {
1054 log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
1055 routelen, num_acceptable_routers);
1056 routelen = num_acceptable_routers;
1059 return routelen;
1062 /** Fetch the list of predicted ports, dup it into a smartlist of
1063 * uint16_t's, remove the ones that are already handled by an
1064 * existing circuit, and return it.
1066 static smartlist_t *
1067 circuit_get_unhandled_ports(time_t now)
1069 smartlist_t *source = rep_hist_get_predicted_ports(now);
1070 smartlist_t *dest = smartlist_create();
1071 uint16_t *tmp;
1072 int i;
1074 for (i = 0; i < smartlist_len(source); ++i) {
1075 tmp = tor_malloc(sizeof(uint16_t));
1076 memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
1077 smartlist_add(dest, tmp);
1080 circuit_remove_handled_ports(dest);
1081 return dest;
1084 /** Return 1 if we already have circuits present or on the way for
1085 * all anticipated ports. Return 0 if we should make more.
1087 * If we're returning 0, set need_uptime and need_capacity to
1088 * indicate any requirements that the unhandled ports have.
1091 circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
1092 int *need_capacity)
1094 int i, enough;
1095 uint16_t *port;
1096 smartlist_t *sl = circuit_get_unhandled_ports(now);
1097 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1098 tor_assert(need_uptime);
1099 tor_assert(need_capacity);
1100 enough = (smartlist_len(sl) == 0);
1101 for (i = 0; i < smartlist_len(sl); ++i) {
1102 port = smartlist_get(sl, i);
1103 if (smartlist_string_num_isin(LongLivedServices, *port))
1104 *need_uptime = 1;
1105 tor_free(port);
1107 smartlist_free(sl);
1108 return enough;
1111 /** Return 1 if <b>router</b> can handle one or more of the ports in
1112 * <b>needed_ports</b>, else return 0.
1114 static int
1115 router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
1117 int i;
1118 uint16_t port;
1120 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1121 addr_policy_result_t r;
1122 port = *(uint16_t *)smartlist_get(needed_ports, i);
1123 tor_assert(port);
1124 r = compare_addr_to_addr_policy(0, port, router->exit_policy);
1125 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1126 return 1;
1128 return 0;
1131 /** Return true iff <b>conn</b> needs another general circuit to be
1132 * built. */
1133 static int
1134 ap_stream_wants_exit_attention(connection_t *conn)
1136 if (conn->type == CONN_TYPE_AP &&
1137 conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1138 !conn->marked_for_close &&
1139 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1140 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
1141 MIN_CIRCUITS_HANDLING_STREAM))
1142 return 1;
1143 return 0;
1146 /** Return a pointer to a suitable router to be the exit node for the
1147 * general-purpose circuit we're about to build.
1149 * Look through the connection array, and choose a router that maximizes
1150 * the number of pending streams that can exit from this router.
1152 * Return NULL if we can't find any suitable routers.
1154 static routerinfo_t *
1155 choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
1156 int need_capacity)
1158 int *n_supported;
1159 int i;
1160 int n_pending_connections = 0;
1161 smartlist_t *connections;
1162 int best_support = -1;
1163 int n_best_support=0;
1164 smartlist_t *sl, *preferredexits, *excludedexits;
1165 routerinfo_t *router;
1166 or_options_t *options = get_options();
1168 connections = get_connection_array();
1170 /* Count how many connections are waiting for a circuit to be built.
1171 * We use this for log messages now, but in the future we may depend on it.
1173 SMARTLIST_FOREACH(connections, connection_t *, conn,
1175 if (ap_stream_wants_exit_attention(conn))
1176 ++n_pending_connections;
1178 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1179 // n_pending_connections);
1180 /* Now we count, for each of the routers in the directory, how many
1181 * of the pending connections could possibly exit from that
1182 * router (n_supported[i]). (We can't be sure about cases where we
1183 * don't know the IP address of the pending connection.)
1185 n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
1186 for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
1187 router = smartlist_get(dir->routers, i);
1188 if (router_is_me(router)) {
1189 n_supported[i] = -1;
1190 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1191 /* XXX there's probably a reverse predecessor attack here, but
1192 * it's slow. should we take this out? -RD
1194 continue;
1196 if (!router->is_running || router->is_bad_exit) {
1197 n_supported[i] = -1;
1198 continue; /* skip routers that are known to be down or bad exits */
1200 if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
1201 n_supported[i] = -1;
1202 continue; /* skip routers that are not suitable */
1204 if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
1205 /* if it's invalid and we don't want it */
1206 n_supported[i] = -1;
1207 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1208 // router->nickname, i);
1209 continue; /* skip invalid routers */
1211 if (router_exit_policy_rejects_all(router)) {
1212 n_supported[i] = -1;
1213 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1214 // router->nickname, i);
1215 continue; /* skip routers that reject all */
1217 n_supported[i] = 0;
1218 /* iterate over connections */
1219 SMARTLIST_FOREACH(connections, connection_t *, conn,
1221 if (!ap_stream_wants_exit_attention(conn))
1222 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1223 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router)) {
1224 ++n_supported[i];
1225 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1226 // router->nickname, i, n_supported[i]);
1227 } else {
1228 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1229 // router->nickname, i);
1231 }); /* End looping over connections. */
1232 if (n_supported[i] > best_support) {
1233 /* If this router is better than previous ones, remember its index
1234 * and goodness, and start counting how many routers are this good. */
1235 best_support = n_supported[i]; n_best_support=1;
1236 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1237 // router->nickname);
1238 } else if (n_supported[i] == best_support) {
1239 /* If this router is _as good_ as the best one, just increment the
1240 * count of equally good routers.*/
1241 ++n_best_support;
1244 log_info(LD_CIRC,
1245 "Found %d servers that might support %d/%d pending connections.",
1246 n_best_support, best_support >= 0 ? best_support : 0,
1247 n_pending_connections);
1249 preferredexits = smartlist_create();
1250 add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
1252 excludedexits = smartlist_create();
1253 add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0);
1255 sl = smartlist_create();
1257 /* If any routers definitely support any pending connections, choose one
1258 * at random. */
1259 if (best_support > 0) {
1260 for (i = 0; i < smartlist_len(dir->routers); i++)
1261 if (n_supported[i] == best_support)
1262 smartlist_add(sl, smartlist_get(dir->routers, i));
1264 smartlist_subtract(sl,excludedexits);
1265 if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
1266 smartlist_intersect(sl,preferredexits);
1267 router = routerlist_sl_choose_by_bandwidth(sl, 1);
1268 } else {
1269 /* Either there are no pending connections, or no routers even seem to
1270 * possibly support any of them. Choose a router at random that satisfies
1271 * at least one predicted exit port. */
1273 int try;
1274 smartlist_t *needed_ports = circuit_get_unhandled_ports(time(NULL));
1276 if (best_support == -1) {
1277 if (need_uptime || need_capacity) {
1278 log_info(LD_CIRC,
1279 "We couldn't find any live%s%s routers; falling back "
1280 "to list of all routers.",
1281 need_capacity?", fast":"",
1282 need_uptime?", stable":"");
1283 smartlist_free(preferredexits);
1284 smartlist_free(excludedexits);
1285 smartlist_free(sl);
1286 tor_free(n_supported);
1287 return choose_good_exit_server_general(dir, 0, 0);
1289 log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
1290 "doomed exit at random.");
1292 for (try = 0; try < 2; try++) {
1293 /* try once to pick only from routers that satisfy a needed port,
1294 * then if there are none, pick from any that support exiting. */
1295 for (i = 0; i < smartlist_len(dir->routers); i++) {
1296 router = smartlist_get(dir->routers, i);
1297 if (n_supported[i] != -1 &&
1298 (try || router_handles_some_port(router, needed_ports))) {
1299 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1300 // try, router->nickname);
1301 smartlist_add(sl, router);
1305 smartlist_subtract(sl,excludedexits);
1306 if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
1307 smartlist_intersect(sl,preferredexits);
1308 /* XXX sometimes the above results in null, when the requested
1309 * exit node is down. we should pick it anyway. */
1310 router = routerlist_sl_choose_by_bandwidth(sl, 1);
1311 if (router)
1312 break;
1314 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1315 smartlist_free(needed_ports);
1318 smartlist_free(preferredexits);
1319 smartlist_free(excludedexits);
1320 smartlist_free(sl);
1321 tor_free(n_supported);
1322 if (router) {
1323 log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
1324 return router;
1326 if (options->StrictExitNodes) {
1327 log_warn(LD_CIRC,
1328 "No specified exit routers seem to be running, and "
1329 "StrictExitNodes is set: can't choose an exit.");
1331 return NULL;
1334 /** Return a pointer to a suitable router to be the exit node for the
1335 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1336 * if no router is suitable).
1338 * For general-purpose circuits, pass it off to
1339 * choose_good_exit_server_general()
1341 * For client-side rendezvous circuits, choose a random node, weighted
1342 * toward the preferences in 'options'.
1344 static routerinfo_t *
1345 choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
1346 int need_uptime, int need_capacity, int is_internal)
1348 or_options_t *options = get_options();
1349 switch (purpose) {
1350 case CIRCUIT_PURPOSE_C_GENERAL:
1351 if (is_internal) /* pick it like a middle hop */
1352 return router_choose_random_node(NULL, get_options()->ExcludeNodes,
1353 NULL, need_uptime, need_capacity, 0,
1354 get_options()->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
1355 else
1356 return choose_good_exit_server_general(dir,need_uptime,need_capacity);
1357 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1358 return router_choose_random_node(
1359 options->RendNodes, options->RendExcludeNodes,
1360 NULL, need_uptime, need_capacity, 0,
1361 options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS, 0, 0);
1363 log_warn(LD_BUG,"Unhandled purpose %d", purpose);
1364 tor_fragile_assert();
1365 return NULL;
1368 /** Decide a suitable length for circ's cpath, and pick an exit
1369 * router (or use <b>exit</b> if provided). Store these in the
1370 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1371 static int
1372 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
1374 cpath_build_state_t *state = circ->build_state;
1375 routerlist_t *rl = router_get_routerlist();
1377 if (state->onehop_tunnel) {
1378 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
1379 state->desired_path_len = 1;
1380 } else {
1381 int r = new_route_len(circ->_base.purpose, exit, rl->routers);
1382 if (r < 1) /* must be at least 1 */
1383 return -1;
1384 state->desired_path_len = r;
1387 if (exit) { /* the circuit-builder pre-requested one */
1388 log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
1389 exit = extend_info_dup(exit);
1390 } else { /* we have to decide one */
1391 routerinfo_t *router =
1392 choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
1393 state->need_capacity, state->is_internal);
1394 if (!router) {
1395 log_warn(LD_CIRC,"failed to choose an exit server");
1396 return -1;
1398 exit = extend_info_from_router(router);
1400 state->chosen_exit = exit;
1401 return 0;
1404 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1405 * hop to the cpath reflecting this. Don't send the next extend cell --
1406 * the caller will do this if it wants to.
1409 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1411 cpath_build_state_t *state;
1412 tor_assert(exit);
1413 tor_assert(circ);
1415 state = circ->build_state;
1416 tor_assert(state);
1417 if (state->chosen_exit)
1418 extend_info_free(state->chosen_exit);
1419 state->chosen_exit = extend_info_dup(exit);
1421 ++circ->build_state->desired_path_len;
1422 onion_append_hop(&circ->cpath, exit);
1423 return 0;
1426 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1427 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1428 * send the next extend cell to begin connecting to that hop.
1431 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1433 int err_reason = 0;
1434 circuit_append_new_exit(circ, exit);
1435 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
1436 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
1437 log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
1438 exit->nickname);
1439 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
1440 return -1;
1442 return 0;
1445 /** Return the number of routers in <b>routers</b> that are currently up
1446 * and available for building circuits through.
1448 static int
1449 count_acceptable_routers(smartlist_t *routers)
1451 int i, n;
1452 int num=0;
1453 routerinfo_t *r;
1455 n = smartlist_len(routers);
1456 for (i=0;i<n;i++) {
1457 r = smartlist_get(routers, i);
1458 // log_debug(LD_CIRC,
1459 // "Contemplating whether router %d (%s) is a new option.",
1460 // i, r->nickname);
1461 if (r->is_running == 0) {
1462 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1463 goto next_i_loop;
1465 if (r->is_valid == 0) {
1466 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1467 goto next_i_loop;
1468 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1469 * allows this node in some places, then we're getting an inaccurate
1470 * count. For now, be conservative and don't count it. But later we
1471 * should try to be smarter. */
1473 num++;
1474 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1475 next_i_loop:
1476 ; /* C requires an explicit statement after the label */
1479 return num;
1482 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1483 * This function is used to extend cpath by another hop.
1485 void
1486 onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
1488 if (*head_ptr) {
1489 new_hop->next = (*head_ptr);
1490 new_hop->prev = (*head_ptr)->prev;
1491 (*head_ptr)->prev->next = new_hop;
1492 (*head_ptr)->prev = new_hop;
1493 } else {
1494 *head_ptr = new_hop;
1495 new_hop->prev = new_hop->next = new_hop;
1499 /** Pick a random server digest that's running a Tor version that
1500 * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
1501 * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
1502 * probably already connected to them.
1504 * We only return one, so this doesn't become stupid when the
1505 * whole network has upgraded. */
1506 static char *
1507 compute_preferred_testing_list(const char *answer)
1509 smartlist_t *choices;
1510 routerlist_t *rl = router_get_routerlist();
1511 routerinfo_t *router;
1512 char *s;
1514 if (answer) /* they have one in mind -- easy */
1515 return tor_strdup(answer);
1517 choices = smartlist_create();
1518 /* now count up our choices */
1519 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1520 if (r->is_running && r->is_valid &&
1521 ((tor_version_as_new_as(r->platform,"0.1.1.21-cvs") &&
1522 !tor_version_as_new_as(r->platform,"0.1.2.0-alpha-cvs")) ||
1523 tor_version_as_new_as(r->platform,"0.1.2.1-alpha")) &&
1524 !is_local_IP(r->addr) &&
1525 !router_get_trusteddirserver_by_digest(r->cache_info.identity_digest))
1526 smartlist_add(choices, r));
1527 router = smartlist_choose(choices);
1528 smartlist_free(choices);
1529 if (!router) {
1530 log_info(LD_CIRC, "Looking for middle server that doesn't have the "
1531 "reachability bug, but didn't find one. Oh well.");
1532 return NULL;
1534 log_info(LD_CIRC, "Looking for middle server that doesn't have the "
1535 "reachability bug, and chose '%s'. Great.", router->nickname);
1536 s = tor_malloc(HEX_DIGEST_LEN+2);
1537 s[0] = '$';
1538 base16_encode(s+1, HEX_DIGEST_LEN+1,
1539 router->cache_info.identity_digest, DIGEST_LEN);
1540 return s;
1543 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1544 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1545 * to length <b>cur_len</b> to decide a suitable middle hop for a
1546 * circuit. In particular, make sure we don't pick the exit node or its
1547 * family, and make sure we don't duplicate any previous nodes or their
1548 * families. */
1549 static routerinfo_t *
1550 choose_good_middle_server(uint8_t purpose,
1551 cpath_build_state_t *state,
1552 crypt_path_t *head,
1553 int cur_len)
1555 int i;
1556 routerinfo_t *r, *choice;
1557 crypt_path_t *cpath;
1558 smartlist_t *excluded;
1559 or_options_t *options = get_options();
1560 char *preferred = NULL;
1561 tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
1562 purpose <= _CIRCUIT_PURPOSE_MAX);
1564 log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
1565 excluded = smartlist_create();
1566 if ((r = build_state_get_exit_router(state))) {
1567 smartlist_add(excluded, r);
1568 routerlist_add_family(excluded, r);
1570 if ((r = routerlist_find_my_routerinfo())) {
1571 smartlist_add(excluded, r);
1572 routerlist_add_family(excluded, r);
1574 for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
1575 if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
1576 smartlist_add(excluded, r);
1577 routerlist_add_family(excluded, r);
1580 if (purpose == CIRCUIT_PURPOSE_TESTING)
1581 preferred = compute_preferred_testing_list(options->TestVia);
1582 choice = router_choose_random_node(preferred,
1583 options->ExcludeNodes, excluded,
1584 state->need_uptime, state->need_capacity, 0,
1585 options->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
1586 if (preferred)
1587 tor_free(preferred);
1588 smartlist_free(excluded);
1589 return choice;
1592 /** Pick a good entry server for the circuit to be built according to
1593 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1594 * router (if we're an OR), and respect firewall settings; if we're
1595 * configured to use entry guards, return one.
1597 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1598 * guard, not for any particular circuit.
1600 static routerinfo_t *
1601 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
1603 routerinfo_t *r, *choice;
1604 smartlist_t *excluded;
1605 or_options_t *options = get_options();
1606 (void)purpose; /* not used yet. */
1608 if (state && options->UseEntryGuards) {
1609 return choose_random_entry(state);
1612 excluded = smartlist_create();
1614 if (state && (r = build_state_get_exit_router(state))) {
1615 smartlist_add(excluded, r);
1616 routerlist_add_family(excluded, r);
1618 if ((r = routerlist_find_my_routerinfo())) {
1619 smartlist_add(excluded, r);
1620 routerlist_add_family(excluded, r);
1622 if (firewall_is_fascist_or()) {
1623 /* exclude all ORs that listen on the wrong port */
1624 routerlist_t *rl = router_get_routerlist();
1625 int i;
1627 for (i=0; i < smartlist_len(rl->routers); i++) {
1628 r = smartlist_get(rl->routers, i);
1629 if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
1630 smartlist_add(excluded, r);
1633 /* and exclude current entry guards, if applicable */
1634 if (options->UseEntryGuards && entry_guards) {
1635 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1637 if ((r = router_get_by_digest(entry->identity)))
1638 smartlist_add(excluded, r);
1642 choice = router_choose_random_node(
1643 NULL, options->ExcludeNodes,
1644 excluded, state ? state->need_uptime : 0,
1645 state ? state->need_capacity : 0,
1646 state ? 0 : 1,
1647 options->_AllowInvalid & ALLOW_INVALID_ENTRY, 0, 0);
1648 smartlist_free(excluded);
1649 return choice;
1652 /** Return the first non-open hop in cpath, or return NULL if all
1653 * hops are open. */
1654 static crypt_path_t *
1655 onion_next_hop_in_cpath(crypt_path_t *cpath)
1657 crypt_path_t *hop = cpath;
1658 do {
1659 if (hop->state != CPATH_STATE_OPEN)
1660 return hop;
1661 hop = hop->next;
1662 } while (hop != cpath);
1663 return NULL;
1666 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1667 * based on <b>state</b>. Append the hop info to head_ptr.
1669 static int
1670 onion_extend_cpath(origin_circuit_t *circ)
1672 uint8_t purpose = circ->_base.purpose;
1673 cpath_build_state_t *state = circ->build_state;
1674 int cur_len = circuit_get_cpath_len(circ);
1675 extend_info_t *info = NULL;
1677 if (cur_len >= state->desired_path_len) {
1678 log_debug(LD_CIRC, "Path is complete: %d steps long",
1679 state->desired_path_len);
1680 return 1;
1683 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
1684 state->desired_path_len);
1686 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
1687 info = extend_info_dup(state->chosen_exit);
1688 } else if (cur_len == 0) { /* picking first node */
1689 routerinfo_t *r = choose_good_entry_server(purpose, state);
1690 if (r)
1691 info = extend_info_from_router(r);
1692 } else {
1693 routerinfo_t *r =
1694 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
1695 if (r)
1696 info = extend_info_from_router(r);
1699 if (!info) {
1700 log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
1701 "this circuit.", cur_len);
1702 return -1;
1705 log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
1706 info->nickname, cur_len+1, build_state_get_exit_nickname(state));
1708 onion_append_hop(&circ->cpath, info);
1709 extend_info_free(info);
1710 return 0;
1713 /** Create a new hop, annotate it with information about its
1714 * corresponding router <b>choice</b>, and append it to the
1715 * end of the cpath <b>head_ptr</b>. */
1716 static int
1717 onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
1719 crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
1721 /* link hop into the cpath, at the end. */
1722 onion_append_to_cpath(head_ptr, hop);
1724 hop->magic = CRYPT_PATH_MAGIC;
1725 hop->state = CPATH_STATE_CLOSED;
1727 hop->extend_info = extend_info_dup(choice);
1729 hop->package_window = CIRCWINDOW_START;
1730 hop->deliver_window = CIRCWINDOW_START;
1732 return 0;
1735 /** Allocate a new extend_info object based on the various arguments. */
1736 extend_info_t *
1737 extend_info_alloc(const char *nickname, const char *digest,
1738 crypto_pk_env_t *onion_key,
1739 uint32_t addr, uint16_t port)
1741 extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
1742 memcpy(info->identity_digest, digest, DIGEST_LEN);
1743 strlcpy(info->nickname, nickname, sizeof(info->nickname));
1744 if (onion_key)
1745 info->onion_key = crypto_pk_dup_key(onion_key);
1746 info->addr = addr;
1747 info->port = port;
1748 return info;
1751 /** Allocate and return a new extend_info_t that can be used to build a
1752 * circuit to or through the router <b>r</b>. */
1753 extend_info_t *
1754 extend_info_from_router(routerinfo_t *r)
1756 tor_assert(r);
1757 return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
1758 r->onion_pkey, r->addr, r->or_port);
1761 #if 0
1762 /** What router purpose is <b>digest</b>?
1763 * It's a general purpose router unless it's on our bridges list.
1765 static uint8_t
1766 get_router_purpose_from_digest(char *digest)
1768 if (digest_is_a_bridge(digest))
1769 return ROUTER_PURPOSE_BRIDGE;
1770 return ROUTER_PURPOSE_GENERAL;
1772 #endif
1774 #if 0
1775 /** Allocate and return a new extend_info_t that can be used to build a
1776 * circuit to or through the router <b>r</b>. */
1777 extend_info_t *
1778 extend_info_from_routerstatus(routerstatus_t *s)
1780 tor_assert(s);
1781 /* routerstatus doesn't know onion_key; leave it NULL */
1782 return extend_info_alloc(s->nickname, s->identity_digest,
1783 NULL, s->addr, s->or_port);
1784 // get_router_purpose_from_digest(s->identity_digest));
1786 #endif
1788 /** Release storage held by an extend_info_t struct. */
1789 void
1790 extend_info_free(extend_info_t *info)
1792 tor_assert(info);
1793 if (info->onion_key)
1794 crypto_free_pk_env(info->onion_key);
1795 tor_free(info);
1798 /** Allocate and return a new extend_info_t with the same contents as
1799 * <b>info</b>. */
1800 extend_info_t *
1801 extend_info_dup(extend_info_t *info)
1803 extend_info_t *newinfo;
1804 tor_assert(info);
1805 newinfo = tor_malloc(sizeof(extend_info_t));
1806 memcpy(newinfo, info, sizeof(extend_info_t));
1807 if (info->onion_key)
1808 newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
1809 else
1810 newinfo->onion_key = NULL;
1811 return newinfo;
1814 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1815 * If there is no chosen exit, or if we don't know the routerinfo_t for
1816 * the chosen exit, return NULL.
1818 routerinfo_t *
1819 build_state_get_exit_router(cpath_build_state_t *state)
1821 if (!state || !state->chosen_exit)
1822 return NULL;
1823 return router_get_by_digest(state->chosen_exit->identity_digest);
1826 /** Return the nickname for the chosen exit router in <b>state</b>. If
1827 * there is no chosen exit, or if we don't know the routerinfo_t for the
1828 * chosen exit, return NULL.
1830 const char *
1831 build_state_get_exit_nickname(cpath_build_state_t *state)
1833 if (!state || !state->chosen_exit)
1834 return NULL;
1835 return state->chosen_exit->nickname;
1838 /** Check whether the entry guard <b>e</b> is usable, given the directory
1839 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1840 * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
1841 * accordingly. Return true iff the entry guard's status changes. */
1842 static int
1843 entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
1844 time_t now, or_options_t *options)
1846 const char *reason = NULL;
1847 char buf[HEX_DIGEST_LEN+1];
1848 int changed = 0;
1850 tor_assert(options);
1852 /* Do we want to mark this guard as bad? */
1853 if (!ri)
1854 reason = "unlisted";
1855 else if (!ri->is_running)
1856 reason = "down";
1857 else if (options->UseBridges && ri->purpose != ROUTER_PURPOSE_BRIDGE)
1858 reason = "not a bridge";
1859 else if (!options->UseBridges && !ri->is_possible_guard &&
1860 !router_nickname_is_in_list(ri, options->EntryNodes))
1861 reason = "not recommended as a guard";
1862 else if (router_nickname_is_in_list(ri, options->ExcludeNodes))
1863 reason = "excluded";
1865 if (reason && ! e->bad_since) {
1866 /* Router is newly bad. */
1867 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
1868 log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
1869 e->nickname, buf, reason);
1871 e->bad_since = now;
1872 control_event_guard(e->nickname, e->identity, "BAD");
1873 changed = 1;
1874 } else if (!reason && e->bad_since) {
1875 /* There's nothing wrong with the router any more. */
1876 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
1877 log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
1878 "marking as ok.", e->nickname, buf);
1880 e->bad_since = 0;
1881 control_event_guard(e->nickname, e->identity, "GOOD");
1882 changed = 1;
1885 return changed;
1888 /** Return true iff enough time has passed since we last tried connect to the
1889 * unreachable guard <b>e</b> that we're willing to try again. */
1890 static int
1891 entry_is_time_to_retry(entry_guard_t *e, time_t now)
1893 long diff;
1894 if (e->last_attempted < e->unreachable_since)
1895 return 1;
1896 diff = now - e->unreachable_since;
1897 if (diff < 6*60*60)
1898 return now > (e->last_attempted + 60*60);
1899 else if (diff < 3*24*60*60)
1900 return now > (e->last_attempted + 4*60*60);
1901 else if (diff < 7*24*60*60)
1902 return now > (e->last_attempted + 18*60*60);
1903 else
1904 return now > (e->last_attempted + 36*60*60);
1907 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1908 * working well enough that we are willing to use it as an entry
1909 * right now. (Else return NULL.) In particular, it must be
1910 * - Listed as either up or never yet contacted;
1911 * - Present in the routerlist;
1912 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1913 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1914 * (This check is currently redundant with the Guard flag, but in
1915 * the future that might change. Best to leave it in for now.)
1916 * - Allowed by our current ReachableAddresses config option; and
1917 * - Currently thought to be reachable by us (unless assume_reachable
1918 * is true).
1920 static INLINE routerinfo_t *
1921 entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
1922 int assume_reachable)
1924 routerinfo_t *r;
1925 if (e->bad_since)
1926 return NULL;
1927 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1928 if ((!assume_reachable && !e->can_retry) &&
1929 e->unreachable_since && !entry_is_time_to_retry(e, time(NULL)))
1930 return NULL;
1931 r = router_get_by_digest(e->identity);
1932 if (!r)
1933 return NULL;
1934 if (get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_BRIDGE)
1935 return NULL;
1936 if (!get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_GENERAL)
1937 return NULL;
1938 if (router_is_unreliable(r, need_uptime, need_capacity, 0))
1939 return NULL;
1940 if (firewall_is_fascist_or() &&
1941 !fascist_firewall_allows_address_or(r->addr,r->or_port))
1942 return NULL;
1943 return r;
1946 /** Return the number of entry guards that we think are usable. */
1947 static int
1948 num_live_entry_guards(void)
1950 int n = 0;
1951 if (! entry_guards)
1952 return 0;
1953 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1955 if (entry_is_live(entry, 0, 1, 0))
1956 ++n;
1958 return n;
1961 /** If <b>digest</b> matches the identity of any node in the
1962 * entry_guards list, return that node. Else return NULL. */
1963 static INLINE entry_guard_t *
1964 is_an_entry_guard(const char *digest)
1966 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
1967 if (!memcmp(digest, entry->identity, DIGEST_LEN))
1968 return entry;
1970 return NULL;
1973 /** Dump a description of our list of entry guards to the log at level
1974 * <b>severity</b>. */
1975 static void
1976 log_entry_guards(int severity)
1978 smartlist_t *elements = smartlist_create();
1979 char buf[1024];
1980 char *s;
1982 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
1984 tor_snprintf(buf, sizeof(buf), "%s (%s%s)",
1985 e->nickname,
1986 e->bad_since ? "down " : "up ",
1987 e->made_contact ? "made-contact" : "never-contacted");
1988 smartlist_add(elements, tor_strdup(buf));
1991 s = smartlist_join_strings(elements, ",", 0, NULL);
1992 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
1993 smartlist_free(elements);
1994 log_fn(severity,LD_CIRC,"%s",s);
1995 tor_free(s);
1998 /** Called when one or more guards that we would previously have used for some
1999 * purpose are no longer in use because a higher-priority guard has become
2000 * useable again. */
2001 static void
2002 control_event_guard_deferred(void)
2004 /* XXXX We don't actually have a good way to figure out _how many_ entries
2005 * are live for some purpose. We need an entry_is_even_slightly_live()
2006 * function for this to work right. NumEntryGuards isn't reliable: if we
2007 * need guards with weird properties, we can have more than that number
2008 * live.
2010 #if 0
2011 int n = 0;
2012 or_options_t *options = get_options();
2013 if (!entry_guards)
2014 return;
2015 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2017 if (entry_is_live(entry, 0, 1, 0)) {
2018 if (n++ == options->NumEntryGuards) {
2019 control_event_guard(entry->nickname, entry->identity, "DEFERRED");
2020 return;
2024 #endif
2027 /** Add a new (preferably stable and fast) router to our
2028 * entry_guards list. Return a pointer to the router if we succeed,
2029 * or NULL if we can't find any more suitable entries.
2031 * If <b>chosen</b> is defined, use that one, and if it's not
2032 * already in our entry_guards list, put it at the *beginning*.
2033 * Else, put the one we pick at the end of the list. */
2034 static routerinfo_t *
2035 add_an_entry_guard(routerinfo_t *chosen, int reset_status)
2037 routerinfo_t *router;
2038 entry_guard_t *entry;
2040 if (chosen) {
2041 router = chosen;
2042 entry = is_an_entry_guard(router->cache_info.identity_digest);
2043 if (entry) {
2044 if (reset_status)
2045 entry->bad_since = 0;
2046 return NULL;
2048 } else {
2049 router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
2050 if (!router)
2051 return NULL;
2053 entry = tor_malloc_zero(sizeof(entry_guard_t));
2054 log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
2055 strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
2056 memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
2057 if (chosen) /* prepend */
2058 smartlist_insert(entry_guards, 0, entry);
2059 else /* append */
2060 smartlist_add(entry_guards, entry);
2061 control_event_guard(entry->nickname, entry->identity, "NEW");
2062 control_event_guard_deferred();
2063 log_entry_guards(LOG_INFO);
2064 return router;
2067 /** If the use of entry guards is configured, choose more entry guards
2068 * until we have enough in the list. */
2069 static void
2070 pick_entry_guards(void)
2072 or_options_t *options = get_options();
2073 int changed = 0;
2075 tor_assert(entry_guards);
2077 while (num_live_entry_guards() < options->NumEntryGuards) {
2078 if (!add_an_entry_guard(NULL, 0))
2079 break;
2080 changed = 1;
2082 if (changed)
2083 entry_guards_changed();
2086 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2087 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2088 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2090 /** Remove all entry guards that have been down or unlisted for so
2091 * long that we don't think they'll come up again. Return 1 if we
2092 * removed any, or 0 if we did nothing. */
2093 static int
2094 remove_dead_entries(void)
2096 char dbuf[HEX_DIGEST_LEN+1];
2097 char tbuf[ISO_TIME_LEN+1];
2098 time_t now = time(NULL);
2099 int i;
2100 int changed = 0;
2102 for (i = 0; i < smartlist_len(entry_guards); ) {
2103 entry_guard_t *entry = smartlist_get(entry_guards, i);
2104 if (entry->bad_since &&
2105 entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
2107 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
2108 format_local_iso_time(tbuf, entry->bad_since);
2109 log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
2110 "since %s local time; removing.",
2111 entry->nickname, dbuf, tbuf);
2112 control_event_guard(entry->nickname, entry->identity, "DROPPED");
2113 tor_free(entry);
2114 smartlist_del_keeporder(entry_guards, i);
2115 log_entry_guards(LOG_INFO);
2116 changed = 1;
2117 } else
2118 ++i;
2120 return changed ? 1 : 0;
2123 /** A new directory or router-status has arrived; update the down/listed
2124 * status of the entry guards.
2126 * An entry is 'down' if the directory lists it as nonrunning.
2127 * An entry is 'unlisted' if the directory doesn't include it.
2129 void
2130 entry_guards_compute_status(void)
2132 /* Don't call this on startup; only on a fresh download. Otherwise we'll
2133 * think that things are unlisted. */
2134 time_t now;
2135 int changed = 0;
2136 int severity = LOG_INFO;
2137 or_options_t *options;
2138 if (! entry_guards)
2139 return;
2141 options = get_options();
2143 now = time(NULL);
2145 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2147 routerinfo_t *r = router_get_by_digest(entry->identity);
2148 if (entry_guard_set_status(entry, r, now, options))
2149 changed = 1;
2151 log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s and %s.",
2152 entry->nickname,
2153 entry->unreachable_since ? "unreachable" : "reachable",
2154 entry->bad_since ? "unusable" : "usable",
2155 entry_is_live(entry, 0, 1, 0) ? "live" : "not live");
2158 if (remove_dead_entries())
2159 changed = 1;
2161 if (changed) {
2162 log_fn(severity, LD_CIRC, " (%d/%d entry guards are usable/new)",
2163 num_live_entry_guards(), smartlist_len(entry_guards));
2164 log_entry_guards(LOG_INFO);
2165 entry_guards_changed();
2169 /** Called when a connection to an OR with the identity digest <b>digest</b>
2170 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2171 * If the OR is an entry, change that entry's up/down status.
2172 * Return 0 normally, or -1 if we want to tear down the new connection.
2175 entry_guard_register_connect_status(const char *digest, int succeeded,
2176 time_t now)
2178 int changed = 0;
2179 int refuse_conn = 0;
2180 int first_contact = 0;
2181 entry_guard_t *entry = NULL;
2182 int idx = -1;
2183 char buf[HEX_DIGEST_LEN+1];
2185 if (! entry_guards)
2186 return 0;
2188 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2190 if (!memcmp(e->identity, digest, DIGEST_LEN)) {
2191 entry = e;
2192 idx = e_sl_idx;
2193 break;
2197 if (!entry)
2198 return 0;
2200 base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
2202 if (succeeded) {
2203 if (entry->unreachable_since) {
2204 log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
2205 entry->nickname, buf);
2206 entry->can_retry = 0;
2207 entry->unreachable_since = 0;
2208 entry->last_attempted = now;
2209 control_event_guard(entry->nickname, entry->identity, "UP");
2210 changed = 1;
2212 if (!entry->made_contact) {
2213 entry->made_contact = 1;
2214 first_contact = changed = 1;
2216 } else { /* ! succeeded */
2217 if (!entry->made_contact) {
2218 /* We've never connected to this one. */
2219 log_info(LD_CIRC,
2220 "Connection to never-contacted entry guard '%s' (%s) failed. "
2221 "Removing from the list. %d/%d entry guards usable/new.",
2222 entry->nickname, buf,
2223 num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
2224 tor_free(entry);
2225 smartlist_del_keeporder(entry_guards, idx);
2226 log_entry_guards(LOG_INFO);
2227 changed = 1;
2228 } else if (!entry->unreachable_since) {
2229 log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
2230 "Marking as unreachable.", entry->nickname, buf);
2231 entry->unreachable_since = entry->last_attempted = now;
2232 control_event_guard(entry->nickname, entry->identity, "DOWN");
2233 changed = 1;
2234 } else {
2235 char tbuf[ISO_TIME_LEN+1];
2236 format_iso_time(tbuf, entry->unreachable_since);
2237 log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
2238 "'%s' (%s). It has been unreachable since %s.",
2239 entry->nickname, buf, tbuf);
2240 entry->last_attempted = now;
2242 if (entry)
2243 entry->can_retry = 0; /* We gave it an early chance; no good. */
2246 if (first_contact) {
2247 /* We've just added a new long-term entry guard. Perhaps the network just
2248 * came back? We should give our earlier entries another try too,
2249 * and close this connection so we don't use it before we've given
2250 * the others a shot. */
2251 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
2252 if (e == entry)
2253 break;
2254 if (e->made_contact) {
2255 routerinfo_t *r = entry_is_live(e, 0, 1, 1);
2256 if (r && e->unreachable_since) {
2257 refuse_conn = 1;
2258 e->can_retry = 1;
2262 if (refuse_conn) {
2263 log_info(LD_CIRC,
2264 "Connected to new entry guard '%s' (%s). Marking earlier "
2265 "entry guards up. %d/%d entry guards usable/new.",
2266 entry->nickname, buf,
2267 num_live_entry_guards(), smartlist_len(entry_guards));
2268 log_entry_guards(LOG_INFO);
2269 changed = 1;
2273 if (changed)
2274 entry_guards_changed();
2275 return refuse_conn ? -1 : 0;
2278 /** When we try to choose an entry guard, should we parse and add
2279 * config's EntryNodes first? */
2280 static int should_add_entry_nodes = 0;
2282 /** Called when the value of EntryNodes changes in our configuration. */
2283 void
2284 entry_nodes_should_be_added(void)
2286 log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
2287 should_add_entry_nodes = 1;
2290 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2291 * of guard nodes, at the front. */
2292 static void
2293 entry_guards_prepend_from_config(void)
2295 or_options_t *options = get_options();
2296 smartlist_t *entry_routers, *entry_fps;
2297 smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
2298 tor_assert(entry_guards);
2300 should_add_entry_nodes = 0;
2302 if (!options->EntryNodes) {
2303 /* It's possible that a controller set EntryNodes, thus making
2304 * should_add_entry_nodes set, then cleared it again, all before the
2305 * call to choose_random_entry() that triggered us. If so, just return.
2307 return;
2310 log_info(LD_CIRC,"Adding configured EntryNodes '%s'.",
2311 options->EntryNodes);
2313 entry_routers = smartlist_create();
2314 entry_fps = smartlist_create();
2315 old_entry_guards_on_list = smartlist_create();
2316 old_entry_guards_not_on_list = smartlist_create();
2318 /* Split entry guards into those on the list and those not. */
2319 add_nickname_list_to_smartlist(entry_routers, options->EntryNodes, 0);
2320 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
2321 smartlist_add(entry_fps,ri->cache_info.identity_digest));
2322 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
2323 if (smartlist_digest_isin(entry_fps, e->identity))
2324 smartlist_add(old_entry_guards_on_list, e);
2325 else
2326 smartlist_add(old_entry_guards_not_on_list, e);
2329 /* Remove all currently configured entry guards from entry_routers. */
2330 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
2331 if (is_an_entry_guard(ri->cache_info.identity_digest)) {
2332 SMARTLIST_DEL_CURRENT(entry_routers, ri);
2336 /* Now build the new entry_guards list. */
2337 smartlist_clear(entry_guards);
2338 /* First, the previously configured guards that are in EntryNodes. */
2339 smartlist_add_all(entry_guards, old_entry_guards_on_list);
2340 /* Next, the rest of EntryNodes */
2341 SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
2342 add_an_entry_guard(ri, 0);
2344 /* Finally, the remaining EntryNodes, unless we're strict */
2345 if (options->StrictEntryNodes) {
2346 SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
2347 tor_free(e));
2348 } else {
2349 smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
2352 smartlist_free(entry_routers);
2353 smartlist_free(entry_fps);
2354 smartlist_free(old_entry_guards_on_list);
2355 smartlist_free(old_entry_guards_not_on_list);
2356 entry_guards_changed();
2359 /** Return 1 if we're fine adding arbitrary routers out of the
2360 * directory to our entry guard list. Else return 0. */
2361 static int
2362 can_grow_entry_list(or_options_t *options)
2364 if (options->StrictEntryNodes)
2365 return 0;
2366 if (options->UseBridges)
2367 return 0;
2368 return 1;
2371 /** Pick a live (up and listed) entry guard from entry_guards. If
2372 * <b>state</b> is non-NULL, this is for a specific circuit --
2373 * make sure not to pick this circuit's exit or any node in the
2374 * exit's family. If <b>state</b> is NULL, we're looking for a random
2375 * guard (likely a bridge). */
2376 routerinfo_t *
2377 choose_random_entry(cpath_build_state_t *state)
2379 or_options_t *options = get_options();
2380 smartlist_t *live_entry_guards = smartlist_create();
2381 smartlist_t *exit_family = smartlist_create();
2382 routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
2383 routerinfo_t *r = NULL;
2384 int need_uptime = state ? state->need_uptime : 0;
2385 int need_capacity = state ? state->need_capacity : 0;
2387 if (chosen_exit) {
2388 smartlist_add(exit_family, chosen_exit);
2389 routerlist_add_family(exit_family, chosen_exit);
2392 if (!entry_guards)
2393 entry_guards = smartlist_create();
2395 if (should_add_entry_nodes)
2396 entry_guards_prepend_from_config();
2398 if (can_grow_entry_list(options) &&
2399 (! entry_guards ||
2400 smartlist_len(entry_guards) < options->NumEntryGuards))
2401 pick_entry_guards();
2403 retry:
2404 smartlist_clear(live_entry_guards);
2405 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
2407 r = entry_is_live(entry, need_uptime, need_capacity, 0);
2408 if (r && !smartlist_isin(exit_family, r)) {
2409 smartlist_add(live_entry_guards, r);
2410 if (!entry->made_contact) {
2411 /* Always start with the first not-yet-contacted entry
2412 * guard. Otherwise we might add several new ones, pick
2413 * the second new one, and now we've expanded our entry
2414 * guard list without needing to. */
2415 goto choose_and_finish;
2417 if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
2418 break; /* we have enough */
2422 /* Try to have at least 2 choices available. This way we don't
2423 * get stuck with a single live-but-crummy entry and just keep
2424 * using him.
2425 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2426 if (smartlist_len(live_entry_guards) < 2) {
2427 if (can_grow_entry_list(options)) {
2428 /* still no? try adding a new entry then */
2429 /* XXX if guard doesn't imply fast and stable, then we need
2430 * to tell add_an_entry_guard below what we want, or it might
2431 * be a long time til we get it. -RD */
2432 r = add_an_entry_guard(NULL, 0);
2433 if (r) {
2434 smartlist_add(live_entry_guards, r);
2435 entry_guards_changed();
2438 if (!r && need_uptime) {
2439 need_uptime = 0; /* try without that requirement */
2440 goto retry;
2442 if (!r && need_capacity) {
2443 /* still no? last attempt, try without requiring capacity */
2444 need_capacity = 0;
2445 goto retry;
2447 /* live_entry_guards may be empty below. Oh well, we tried. */
2450 choose_and_finish:
2451 r = smartlist_choose(live_entry_guards);
2452 smartlist_free(live_entry_guards);
2453 smartlist_free(exit_family);
2454 return r;
2457 /** Parse <b>state</b> and learn about the entry guards it describes.
2458 * If <b>set</b> is true, and there are no errors, replace the global
2459 * entry_list with what we find.
2460 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2461 * describing the error, and return -1.
2464 entry_guards_parse_state(or_state_t *state, int set, char **msg)
2466 entry_guard_t *node = NULL;
2467 smartlist_t *new_entry_guards = smartlist_create();
2468 config_line_t *line;
2470 *msg = NULL;
2471 for (line = state->EntryGuards; line; line = line->next) {
2472 if (!strcasecmp(line->key, "EntryGuard")) {
2473 smartlist_t *args = smartlist_create();
2474 node = tor_malloc_zero(sizeof(entry_guard_t));
2475 /* all entry guards on disk have been contacted */
2476 node->made_contact = 1;
2477 smartlist_add(new_entry_guards, node);
2478 smartlist_split_string(args, line->value, " ",
2479 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2480 if (smartlist_len(args)<2) {
2481 *msg = tor_strdup("Unable to parse entry nodes: "
2482 "Too few arguments to EntryGuard");
2483 } else if (!is_legal_nickname(smartlist_get(args,0))) {
2484 *msg = tor_strdup("Unable to parse entry nodes: "
2485 "Bad nickname for EntryGuard");
2486 } else {
2487 strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
2488 if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
2489 strlen(smartlist_get(args,1)))<0) {
2490 *msg = tor_strdup("Unable to parse entry nodes: "
2491 "Bad hex digest for EntryGuard");
2494 SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
2495 smartlist_free(args);
2496 if (*msg)
2497 break;
2498 } else {
2499 time_t when;
2500 time_t last_try = 0;
2501 if (!node) {
2502 *msg = tor_strdup("Unable to parse entry nodes: "
2503 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2504 break;
2506 if (parse_iso_time(line->value, &when)<0) {
2507 *msg = tor_strdup("Unable to parse entry nodes: "
2508 "Bad time in EntryGuardDownSince/UnlistedSince");
2509 break;
2511 if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
2512 /* ignore failure */
2513 parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
2515 if (!strcasecmp(line->key, "EntryGuardDownSince")) {
2516 node->unreachable_since = when;
2517 node->last_attempted = last_try;
2518 } else {
2519 node->bad_since = when;
2524 if (*msg || !set) {
2525 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e, tor_free(e));
2526 smartlist_free(new_entry_guards);
2527 } else { /* !*err && set */
2528 if (entry_guards) {
2529 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
2530 smartlist_free(entry_guards);
2532 entry_guards = new_entry_guards;
2533 entry_guards_dirty = 0;
2535 return *msg ? -1 : 0;
2538 /** Our list of entry guards has changed, or some element of one
2539 * of our entry guards has changed. Write the changes to disk within
2540 * the next few minutes.
2542 static void
2543 entry_guards_changed(void)
2545 time_t when;
2546 entry_guards_dirty = 1;
2548 /* or_state_save() will call entry_guards_update_state(). */
2549 when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
2550 or_state_mark_dirty(get_or_state(), when);
2553 /** If the entry guard info has not changed, do nothing and return.
2554 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2555 * a new one out of the global entry_guards list, and then mark
2556 * <b>state</b> dirty so it will get saved to disk.
2558 void
2559 entry_guards_update_state(or_state_t *state)
2561 config_line_t **next, *line;
2562 if (! entry_guards_dirty)
2563 return;
2565 config_free_lines(state->EntryGuards);
2566 next = &state->EntryGuards;
2567 *next = NULL;
2568 if (!entry_guards)
2569 entry_guards = smartlist_create();
2570 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2572 char dbuf[HEX_DIGEST_LEN+1];
2573 if (!e->made_contact)
2574 continue; /* don't write this one to disk */
2575 *next = line = tor_malloc_zero(sizeof(config_line_t));
2576 line->key = tor_strdup("EntryGuard");
2577 line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
2578 base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
2579 tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
2580 "%s %s", e->nickname, dbuf);
2581 next = &(line->next);
2582 if (e->unreachable_since) {
2583 *next = line = tor_malloc_zero(sizeof(config_line_t));
2584 line->key = tor_strdup("EntryGuardDownSince");
2585 line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
2586 format_iso_time(line->value, e->unreachable_since);
2587 if (e->last_attempted) {
2588 line->value[ISO_TIME_LEN] = ' ';
2589 format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
2591 next = &(line->next);
2593 if (e->bad_since) {
2594 *next = line = tor_malloc_zero(sizeof(config_line_t));
2595 line->key = tor_strdup("EntryGuardUnlistedSince");
2596 line->value = tor_malloc(ISO_TIME_LEN+1);
2597 format_iso_time(line->value, e->bad_since);
2598 next = &(line->next);
2601 if (!get_options()->AvoidDiskWrites)
2602 or_state_mark_dirty(get_or_state(), 0);
2603 entry_guards_dirty = 0;
2606 /** If <b>question</b> is the string "entry-guards", then dump
2607 * to *<b>answer</b> a newly allocated string describing all of
2608 * the nodes in the global entry_guards list. See control-spec.txt
2609 * for details.
2610 * For backward compatibility, we also handle the string "helper-nodes".
2611 * */
2613 getinfo_helper_entry_guards(control_connection_t *conn,
2614 const char *question, char **answer)
2616 int use_long_names = conn->use_long_names;
2618 if (!strcmp(question,"entry-guards") ||
2619 !strcmp(question,"helper-nodes")) {
2620 smartlist_t *sl = smartlist_create();
2621 char tbuf[ISO_TIME_LEN+1];
2622 char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
2623 if (!entry_guards)
2624 entry_guards = smartlist_create();
2625 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2627 size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
2628 char *c = tor_malloc(len);
2629 const char *status = NULL;
2630 time_t when = 0;
2631 if (!e->made_contact) {
2632 status = "never-connected";
2633 } else if (e->bad_since) {
2634 when = e->bad_since;
2635 status = "unusable";
2636 } else {
2637 status = "up";
2639 if (use_long_names) {
2640 routerinfo_t *ri = router_get_by_digest(e->identity);
2641 if (ri) {
2642 router_get_verbose_nickname(nbuf, ri);
2643 } else {
2644 nbuf[0] = '$';
2645 base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
2646 /* e->nickname field is not very reliable if we don't know about
2647 * this router any longer; don't include it. */
2649 } else {
2650 base16_encode(nbuf, sizeof(nbuf), e->identity, DIGEST_LEN);
2652 if (when) {
2653 format_iso_time(tbuf, when);
2654 tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
2655 } else {
2656 tor_snprintf(c, len, "%s %s\n", nbuf, status);
2658 smartlist_add(sl, c);
2660 *answer = smartlist_join_strings(sl, "", 0, NULL);
2661 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
2662 smartlist_free(sl);
2664 return 0;
2667 typedef struct {
2668 uint32_t addr;
2669 uint16_t port;
2670 char identity[DIGEST_LEN];
2671 } bridge_info_t;
2673 /** A list of known bridges. */
2674 static smartlist_t *bridge_list = NULL;
2676 /** Initialize the bridge list to empty, creating it if needed. */
2677 void
2678 clear_bridge_list(void)
2680 if (!bridge_list)
2681 bridge_list = smartlist_create();
2682 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
2683 smartlist_clear(bridge_list);
2686 #if 0
2687 /** Return 1 if <b>digest</b> is one of our known bridges. */
2689 identity_digest_is_a_bridge(const char *digest)
2691 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2693 if (!memcmp(bridge->identity, digest, DIGEST_LEN))
2694 return 1;
2696 return 0;
2698 #endif
2700 /** Return 1 if <b>ri</b> is one of our known bridges (either by
2701 * comparing keys if possible, else by comparing addr/port). */
2703 routerinfo_is_a_bridge(routerinfo_t *ri)
2705 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2707 if (tor_digest_is_zero(bridge->identity) &&
2708 bridge->addr == ri->addr && bridge->port == ri->or_port)
2709 return 1;
2710 if (!memcmp(bridge->identity, ri->cache_info.identity_digest,
2711 DIGEST_LEN))
2712 return 1;
2714 return 0;
2717 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2718 * is set, it tells us the identity key too. */
2719 void
2720 bridge_add_from_config(uint32_t addr, uint16_t port, char *digest)
2722 bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
2723 b->addr = addr;
2724 b->port = port;
2725 if (digest)
2726 memcpy(b->identity, digest, DIGEST_LEN);
2727 if (!bridge_list)
2728 bridge_list = smartlist_create();
2729 smartlist_add(bridge_list, b);
2732 /** For each bridge in our list for which we don't currently have a
2733 * descriptor, fetch a new copy of its descriptor -- either directly
2734 * from the bridge or via a bridge authority. */
2735 void
2736 fetch_bridge_descriptors(void)
2738 char address_buf[INET_NTOA_BUF_LEN+1];
2739 struct in_addr in;
2740 or_options_t *options = get_options();
2741 int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
2742 int ask_bridge_directly;
2744 if (!bridge_list)
2745 return;
2747 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
2749 if (router_get_by_digest(bridge->identity))
2750 continue; /* we've already got one. great. */
2751 in.s_addr = htonl(bridge->addr);
2752 tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
2754 ask_bridge_directly = tor_digest_is_zero(bridge->identity) ||
2755 !options->UpdateBridgesFromAuthority ||
2756 !num_bridge_auths;
2758 if (ask_bridge_directly &&
2759 !fascist_firewall_allows_address_or(bridge->addr, bridge->port)) {
2760 log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
2761 "firewall policy. %s.", address_buf, bridge->port,
2762 num_bridge_auths ? "Asking bridge authority instead" :
2763 "Skipping");
2764 ask_bridge_directly = 0;
2767 if (ask_bridge_directly) {
2768 if (!connection_get_by_type_addr_port_purpose(
2769 CONN_TYPE_DIR, bridge->addr, bridge->port,
2770 DIR_PURPOSE_FETCH_SERVERDESC)) {
2771 /* we need to ask the bridge itself for its descriptor. */
2772 directory_initiate_command(address_buf, bridge->addr,
2773 bridge->port, 0,
2774 1, bridge->identity,
2775 DIR_PURPOSE_FETCH_SERVERDESC,
2776 ROUTER_PURPOSE_BRIDGE,
2777 0, "authority", NULL, 0);
2779 } else {
2780 /* we have a digest and we want to ask an authority. */
2781 // XXX
2786 /** We just learned a descriptor for a bridge. See if that
2787 * digest is in our entry guard list, and add it if not. */
2788 void
2789 learned_bridge_descriptor(routerinfo_t *ri)
2791 tor_assert(ri);
2792 tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
2793 if (get_options()->UseBridges) {
2794 int first = !any_bridge_descriptors_known();
2795 ri->is_running = 1;
2796 add_an_entry_guard(ri, 1);
2797 log_notice(LD_DIR, "new bridge descriptor '%s'", ri->nickname);
2798 if (first)
2799 routerlist_retry_directory_downloads(time(NULL));
2803 /** Return 1 if any of our entry guards have descriptors that
2804 * are marked with purpose 'bridge'. Else return 0.
2806 * We use this function to decide if we're ready to start building
2807 * circuits through our bridges, or if we need to wait until the
2808 * directory "server/authority" requests finish. */
2810 any_bridge_descriptors_known(void)
2812 return choose_random_entry(NULL)!=NULL ? 1 : 0;
2813 #if 0
2814 routerinfo_t *ri;
2815 if (!entry_guards)
2816 entry_guards = smartlist_create();
2817 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2819 ri = router_get_by_digest(e->identity);
2820 if (ri && ri->purpose == ROUTER_PURPOSE_BRIDGE)
2821 return 1;
2823 return 0;
2824 #endif
2827 /** Release all storage held by the list of entry guards and related
2828 * memory structs. */
2829 void
2830 entry_guards_free_all(void)
2832 if (entry_guards) {
2833 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, tor_free(e));
2834 smartlist_free(entry_guards);
2835 entry_guards = NULL;
2837 clear_bridge_list();
2838 smartlist_free(bridge_list);
2839 bridge_list = NULL;