1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 const char circuitbuild_c_id
[] =
11 * \file circuitbuild.c
12 * \brief The actual details of building circuits.
17 /********* START VARIABLES **********/
19 /** A global list of all circuits at this hop. */
20 extern circuit_t
*global_circuitlist
;
22 /** An entry_guard_t represents our information about a chosen long-term
23 * first hop, known as a "helper" node in the literature. We can't just
24 * use a routerinfo_t, since we want to remember these even when we
25 * don't have a directory. */
27 char nickname
[MAX_NICKNAME_LEN
+1];
28 char identity
[DIGEST_LEN
];
29 time_t chosen_on_date
; /**< Approximately when was this guard added?
30 * "0" if we don't know. */
31 char *chosen_by_version
; /**< What tor version added this guard? NULL
32 * if we don't know. */
33 unsigned int made_contact
: 1; /**< 0 if we have never connected to this
34 * router, 1 if we have. */
35 unsigned int can_retry
: 1; /**< Should we retry connecting to this entry,
36 * in spite of having it marked as unreachable?*/
37 time_t bad_since
; /**< 0 if this guard is currently usable, or the time at
38 * which it was observed to become (according to the
39 * directory or the user configuration) unusable. */
40 time_t unreachable_since
; /**< 0 if we can connect to this guard, or the
41 * time at which we first noticed we couldn't
43 time_t last_attempted
; /**< 0 if we can connect to this guard, or the time
44 * at which we last failed to connect to it. */
47 /** A list of our chosen entry guards. */
48 static smartlist_t
*entry_guards
= NULL
;
49 /** A value of 1 means that the entry_guards list has changed
50 * and those changes need to be flushed to disk. */
51 static int entry_guards_dirty
= 0;
53 /********* END VARIABLES ************/
55 static int circuit_deliver_create_cell(circuit_t
*circ
,
56 uint8_t cell_type
, const char *payload
);
57 static int onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
);
58 static crypt_path_t
*onion_next_hop_in_cpath(crypt_path_t
*cpath
);
59 static int onion_extend_cpath(origin_circuit_t
*circ
);
60 static int count_acceptable_routers(smartlist_t
*routers
);
61 static int onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
);
63 static void entry_guards_changed(void);
64 static time_t start_of_month(time_t when
);
66 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
67 * and with the high bit specified by conn-\>circ_id_type, until we get
68 * a circ_id that is not in use by any other circuit on that conn.
70 * Return it, or 0 if can't get a unique circ_id.
73 get_unique_circ_id_by_conn(or_connection_t
*conn
)
75 circid_t test_circ_id
;
80 if (conn
->circ_id_type
== CIRC_ID_TYPE_NEITHER
) {
81 log_warn(LD_BUG
, "Trying to pick a circuit ID for a connection from "
82 "a client with no identity.");
85 high_bit
= (conn
->circ_id_type
== CIRC_ID_TYPE_HIGHER
) ? 1<<15 : 0;
87 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
88 * circID such that (high_bit|test_circ_id) is not already used. */
89 test_circ_id
= conn
->next_circ_id
++;
90 if (test_circ_id
== 0 || test_circ_id
>= 1<<15) {
92 conn
->next_circ_id
= 2;
94 if (++attempts
> 1<<15) {
95 /* Make sure we don't loop forever if all circ_id's are used. This
96 * matters because it's an external DoS opportunity.
98 log_warn(LD_CIRC
,"No unused circ IDs. Failing.");
101 test_circ_id
|= high_bit
;
102 } while (circuit_id_in_use_on_orconn(test_circ_id
, conn
));
106 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
107 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
108 * list information about link status in a more verbose format using spaces.
109 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
110 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
114 circuit_list_path_impl(origin_circuit_t
*circ
, int verbose
, int verbose_names
)
117 smartlist_t
*elements
;
118 const char *states
[] = {"closed", "waiting for keys", "open"};
122 elements
= smartlist_create();
125 const char *nickname
= build_state_get_exit_nickname(circ
->build_state
);
126 tor_snprintf(buf
, sizeof(buf
), "%s%s circ (length %d%s%s):",
127 circ
->build_state
->is_internal
? "internal" : "exit",
128 circ
->build_state
->need_uptime
? " (high-uptime)" : "",
129 circ
->build_state
->desired_path_len
,
130 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" : ", exit ",
131 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" :
132 (nickname
?nickname
:"*unnamed*"));
133 smartlist_add(elements
, tor_strdup(buf
));
142 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
144 if (!hop
->extend_info
)
147 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
148 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
))) {
149 router_get_verbose_nickname(elt
, ri
);
150 } else if (hop
->extend_info
->nickname
&&
151 is_legal_nickname(hop
->extend_info
->nickname
)) {
153 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
154 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
155 elt
[HEX_DIGEST_LEN
+1]= '~';
156 strlcpy(elt
+HEX_DIGEST_LEN
+2,
157 hop
->extend_info
->nickname
, MAX_NICKNAME_LEN
+1);
160 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
161 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
163 } else { /* ! verbose_names */
164 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
)) &&
166 elt
= tor_strdup(hop
->extend_info
->nickname
);
168 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
170 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
171 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
176 size_t len
= strlen(elt
)+2+strlen(states
[hop
->state
])+1;
177 char *v
= tor_malloc(len
);
178 tor_assert(hop
->state
<= 2);
179 tor_snprintf(v
,len
,"%s(%s)",elt
,states
[hop
->state
]);
180 smartlist_add(elements
, v
);
183 smartlist_add(elements
, elt
);
186 } while (hop
!= circ
->cpath
);
188 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
189 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
190 smartlist_free(elements
);
194 /** If <b>verbose</b> is false, allocate and return a comma-separated
195 * list of the currently built elements of circuit_t. If
196 * <b>verbose</b> is true, also list information about link status in
197 * a more verbose format using spaces.
200 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
202 return circuit_list_path_impl(circ
, verbose
, 0);
205 /** Allocate and return a comma-separated list of the currently built elements
206 * of circuit_t, giving each as a verbose nickname.
209 circuit_list_path_for_controller(origin_circuit_t
*circ
)
211 return circuit_list_path_impl(circ
, 0, 1);
214 /** Log, at severity <b>severity</b>, the nicknames of each router in
215 * circ's cpath. Also log the length of the cpath, and the intended
219 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
221 char *s
= circuit_list_path(circ
,1);
222 log(severity
,domain
,"%s",s
);
226 /** Tell the rep(utation)hist(ory) module about the status of the links
227 * in circ. Hops that have become OPEN are marked as successfully
228 * extended; the _first_ hop that isn't open (if any) is marked as
231 /* XXXX Someday we should learn from OR circuits too. */
233 circuit_rep_hist_note_result(origin_circuit_t
*circ
)
236 char *prev_digest
= NULL
;
237 routerinfo_t
*router
;
239 if (!hop
) /* circuit hasn't started building yet. */
241 if (server_mode(get_options())) {
242 routerinfo_t
*me
= router_get_my_routerinfo();
245 prev_digest
= me
->cache_info
.identity_digest
;
248 router
= router_get_by_digest(hop
->extend_info
->identity_digest
);
251 if (hop
->state
== CPATH_STATE_OPEN
)
252 rep_hist_note_extend_succeeded(prev_digest
,
253 router
->cache_info
.identity_digest
);
255 rep_hist_note_extend_failed(prev_digest
,
256 router
->cache_info
.identity_digest
);
260 prev_digest
= router
->cache_info
.identity_digest
;
265 } while (hop
!=circ
->cpath
);
268 /** Pick all the entries in our cpath. Stop and return 0 when we're
269 * happy, or return -1 if an error occurs. */
271 onion_populate_cpath(origin_circuit_t
*circ
)
275 r
= onion_extend_cpath(circ
);
277 log_info(LD_CIRC
,"Generating cpath hop failed.");
282 return 0; /* if r == 1 */
285 /** Create and return a new origin circuit. Initialize its purpose and
286 * build-state based on our arguments. The <b>flags</b> argument is a
287 * bitfield of CIRCLAUNCH_* flags. */
289 origin_circuit_init(uint8_t purpose
, int flags
)
291 /* sets circ->p_circ_id and circ->p_conn */
292 origin_circuit_t
*circ
= origin_circuit_new();
293 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OR_WAIT
);
294 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
295 circ
->build_state
->onehop_tunnel
=
296 ((flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) ? 1 : 0);
297 circ
->build_state
->need_uptime
=
298 ((flags
& CIRCLAUNCH_NEED_UPTIME
) ? 1 : 0);
299 circ
->build_state
->need_capacity
=
300 ((flags
& CIRCLAUNCH_NEED_CAPACITY
) ? 1 : 0);
301 circ
->build_state
->is_internal
=
302 ((flags
& CIRCLAUNCH_IS_INTERNAL
) ? 1 : 0);
303 circ
->_base
.purpose
= purpose
;
307 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
308 * is defined, then use that as your exit router, else choose a suitable
311 * Also launch a connection to the first OR in the chosen path, if
312 * it's not open already.
315 circuit_establish_circuit(uint8_t purpose
, extend_info_t
*exit
, int flags
)
317 origin_circuit_t
*circ
;
320 circ
= origin_circuit_init(purpose
, flags
);
322 if (onion_pick_cpath_exit(circ
, exit
) < 0 ||
323 onion_populate_cpath(circ
) < 0) {
324 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
328 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
330 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
331 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
337 /** Return true iff <b>n_conn</b> (a connection with a desired identity), is
338 * an acceptable choice for extending or launching a circuit to the address
339 * <b>target_addr</b>. If it is not, set <b>state_out</b> to a message
340 * describing the connection's state and our next action, and set
341 * <b>launch_out</b> to a boolean for whether we should launch a new
342 * connection or not. */
344 connection_good_enough_for_extend(const or_connection_t
*n_conn
,
345 const tor_addr_t
*target_addr
,
346 const char **state_out
,
349 tor_assert(state_out
);
350 tor_assert(launch_out
);
351 tor_assert(target_addr
);
354 *state_out
= "not connected. Connecting.";
357 } else if (n_conn
->_base
.state
!= OR_CONN_STATE_OPEN
) {
358 *state_out
= "in progress. Waiting.";
359 *launch_out
= 0; /* We'll just wait till the connection finishes. */
361 } else if (n_conn
->is_bad_for_new_circs
) {
362 *state_out
= "too old. Launching a new one.";
365 } else if (tor_addr_compare(&n_conn
->_base
.addr
, target_addr
, CMP_EXACT
) &&
366 ! n_conn
->is_canonical
) {
367 *state_out
= "is not from a canonical address. Launching a new one.";
371 *state_out
= "is fine; using it.";
377 /** Start establishing the first hop of our circuit. Figure out what
378 * OR we should connect to, and if necessary start the connection to
379 * it. If we're already connected, then send the 'create' cell.
380 * Return 0 for ok, -reason if circ should be marked-for-close. */
382 circuit_handle_first_hop(origin_circuit_t
*circ
)
384 crypt_path_t
*firsthop
;
385 or_connection_t
*n_conn
;
387 const char *msg
= NULL
;
388 int should_launch
= 0;
390 firsthop
= onion_next_hop_in_cpath(circ
->cpath
);
391 tor_assert(firsthop
);
392 tor_assert(firsthop
->extend_info
);
394 /* now see if we're already connected to the first OR in 'route' */
395 log_debug(LD_CIRC
,"Looking for firsthop '%s:%u'",
396 fmt_addr(&firsthop
->extend_info
->addr
),
397 firsthop
->extend_info
->port
);
399 n_conn
= connection_or_get_by_identity_digest(
400 firsthop
->extend_info
->identity_digest
);
402 /* If we don't have an open conn, or the conn we have is obsolete
403 * (i.e. old or broken) and the other side will let us make a second
404 * connection without dropping it immediately... */
405 if (!connection_good_enough_for_extend(n_conn
, &firsthop
->extend_info
->addr
,
406 &msg
, &should_launch
)) {
407 /* XXXX021 log msg, maybe. */
408 /* not currently connected */
409 circ
->_base
.n_hop
= extend_info_dup(firsthop
->extend_info
);
412 if (circ
->build_state
->onehop_tunnel
)
413 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR
, 0);
414 n_conn
= connection_or_connect(&firsthop
->extend_info
->addr
,
415 firsthop
->extend_info
->port
,
416 firsthop
->extend_info
->identity_digest
);
417 if (!n_conn
) { /* connect failed, forget the whole thing */
418 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
419 return -END_CIRC_REASON_CONNECTFAILED
;
423 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
424 /* return success. The onion/circuit/etc will be taken care of
425 * automatically (may already have been) whenever n_conn reaches
426 * OR_CONN_STATE_OPEN.
429 } else { /* it's already open. use it. */
430 tor_assert(!circ
->_base
.n_hop
);
431 circ
->_base
.n_conn
= n_conn
;
432 log_debug(LD_CIRC
,"Conn open. Delivering first onion skin.");
433 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
434 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
441 /** Find any circuits that are waiting on <b>or_conn</b> to become
442 * open and get them to send their create cells forward.
444 * Status is 1 if connect succeeded, or 0 if connect failed.
447 circuit_n_conn_done(or_connection_t
*or_conn
, int status
)
449 smartlist_t
*pending_circs
;
452 log_debug(LD_CIRC
,"or_conn to %s/%s, status=%d",
453 or_conn
->nickname
? or_conn
->nickname
: "NULL",
454 or_conn
->_base
.address
, status
);
456 pending_circs
= smartlist_create();
457 circuit_get_all_pending_on_or_conn(pending_circs
, or_conn
);
459 SMARTLIST_FOREACH_BEGIN(pending_circs
, circuit_t
*, circ
)
461 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
462 * leaving them in in case it's possible for the status of a circuit to
463 * change as we're going down the list. */
464 if (circ
->marked_for_close
|| circ
->n_conn
|| !circ
->n_hop
||
465 circ
->state
!= CIRCUIT_STATE_OR_WAIT
)
468 if (tor_digest_is_zero(circ
->n_hop
->identity_digest
)) {
469 /* Look at addr/port. This is an unkeyed connection. */
470 if (!tor_addr_eq(&circ
->n_hop
->addr
, &or_conn
->_base
.addr
) ||
471 circ
->n_hop
->port
!= or_conn
->_base
.port
)
474 /* We expected a key. See if it's the right one. */
475 if (memcmp(or_conn
->identity_digest
,
476 circ
->n_hop
->identity_digest
, DIGEST_LEN
))
479 if (!status
) { /* or_conn failed; close circ */
480 log_info(LD_CIRC
,"or_conn failed. Closing circ.");
481 circuit_mark_for_close(circ
, END_CIRC_REASON_OR_CONN_CLOSED
);
484 log_debug(LD_CIRC
, "Found circ, sending create cell.");
485 /* circuit_deliver_create_cell will set n_circ_id and add us to
486 * orconn_circuid_circuit_map, so we don't need to call
487 * set_circid_orconn here. */
488 circ
->n_conn
= or_conn
;
489 extend_info_free(circ
->n_hop
);
492 if (CIRCUIT_IS_ORIGIN(circ
)) {
494 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
496 "send_next_onion_skin failed; circuit marked for closing.");
497 circuit_mark_for_close(circ
, -err_reason
);
499 /* XXX could this be bad, eg if next_onion_skin failed because conn
503 /* pull the create cell out of circ->onionskin, and send it */
504 tor_assert(circ
->n_conn_onionskin
);
505 if (circuit_deliver_create_cell(circ
,CELL_CREATE
,
506 circ
->n_conn_onionskin
)<0) {
507 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
510 tor_free(circ
->n_conn_onionskin
);
511 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
514 SMARTLIST_FOREACH_END(circ
);
516 smartlist_free(pending_circs
);
519 /** Find a new circid that isn't currently in use on the circ->n_conn
521 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
522 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
524 * Return -1 if we failed to find a suitable circid, else return 0.
527 circuit_deliver_create_cell(circuit_t
*circ
, uint8_t cell_type
,
534 tor_assert(circ
->n_conn
);
536 tor_assert(cell_type
== CELL_CREATE
|| cell_type
== CELL_CREATE_FAST
);
538 id
= get_unique_circ_id_by_conn(circ
->n_conn
);
540 log_warn(LD_CIRC
,"failed to get unique circID.");
543 log_debug(LD_CIRC
,"Chosen circID %u.", id
);
544 circuit_set_n_circid_orconn(circ
, id
, circ
->n_conn
);
546 memset(&cell
, 0, sizeof(cell_t
));
547 cell
.command
= cell_type
;
548 cell
.circ_id
= circ
->n_circ_id
;
550 memcpy(cell
.payload
, payload
, ONIONSKIN_CHALLENGE_LEN
);
551 append_cell_to_circuit_queue(circ
, circ
->n_conn
, &cell
, CELL_DIRECTION_OUT
);
553 if (CIRCUIT_IS_ORIGIN(circ
)) {
554 /* mark it so it gets better rate limiting treatment. */
555 circ
->n_conn
->client_used
= time(NULL
);
561 /** We've decided to start our reachability testing. If all
562 * is set, log this to the user. Return 1 if we did, or 0 if
563 * we chose not to log anything. */
565 inform_testing_reachability(void)
568 routerinfo_t
*me
= router_get_my_routerinfo();
572 tor_snprintf(dirbuf
, sizeof(dirbuf
), " and DirPort %s:%d",
573 me
->address
, me
->dir_port
);
574 log(LOG_NOTICE
, LD_OR
, "Now checking whether ORPort %s:%d%s %s reachable... "
575 "(this may take up to %d minutes -- look for log "
576 "messages indicating success)",
577 me
->address
, me
->or_port
,
578 me
->dir_port
? dirbuf
: "",
579 me
->dir_port
? "are" : "is",
580 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
/60);
584 /** Return true iff we should send a create_fast cell to start building a given
587 should_use_create_fast_for_circuit(origin_circuit_t
*circ
)
589 or_options_t
*options
= get_options();
590 tor_assert(circ
->cpath
);
591 tor_assert(circ
->cpath
->extend_info
);
593 if (!circ
->cpath
->extend_info
->onion_key
)
594 return 1; /* our hand is forced: only a create_fast will work. */
595 if (!options
->FastFirstHopPK
)
596 return 0; /* we prefer to avoid create_fast */
597 if (server_mode(options
)) {
598 /* We're a server, and we know an onion key. We can choose.
599 * Prefer to blend in. */
606 /** This is the backbone function for building circuits.
608 * If circ's first hop is closed, then we need to build a create
609 * cell and send it forward.
611 * Otherwise, we need to build a relay extend cell and send it
614 * Return -reason if we want to tear down circ, else return 0.
617 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
620 routerinfo_t
*router
;
621 char payload
[2+4+DIGEST_LEN
+ONIONSKIN_CHALLENGE_LEN
];
627 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
630 log_debug(LD_CIRC
,"First skin; sending create cell.");
631 if (circ
->build_state
->onehop_tunnel
)
632 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE
, 0);
634 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE
, 0);
636 router
= router_get_by_digest(circ
->_base
.n_conn
->identity_digest
);
637 fast
= should_use_create_fast_for_circuit(circ
);
639 /* We are an OR and we know the right onion key: we should
640 * send an old slow create cell.
642 cell_type
= CELL_CREATE
;
643 if (onion_skin_create(circ
->cpath
->extend_info
->onion_key
,
644 &(circ
->cpath
->dh_handshake_state
),
646 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
647 return - END_CIRC_REASON_INTERNAL
;
649 note_request("cell: create", 1);
651 /* We are not an OR, and we're building the first hop of a circuit to a
652 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
653 * and a DH operation. */
654 cell_type
= CELL_CREATE_FAST
;
655 memset(payload
, 0, sizeof(payload
));
656 crypto_rand(circ
->cpath
->fast_handshake_state
,
657 sizeof(circ
->cpath
->fast_handshake_state
));
658 memcpy(payload
, circ
->cpath
->fast_handshake_state
,
659 sizeof(circ
->cpath
->fast_handshake_state
));
660 note_request("cell: create fast", 1);
663 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), cell_type
, payload
) < 0)
664 return - END_CIRC_REASON_RESOURCELIMIT
;
666 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
667 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
668 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
669 fast
? "CREATE_FAST" : "CREATE",
670 router
? router
->nickname
: "<unnamed>");
672 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
673 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_BUILDING
);
674 log_debug(LD_CIRC
,"starting to send subsequent skin.");
675 hop
= onion_next_hop_in_cpath(circ
->cpath
);
677 /* done building the circuit. whew. */
678 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
679 log_info(LD_CIRC
,"circuit built!");
680 circuit_reset_failure_count(0);
681 if (circ
->build_state
->onehop_tunnel
)
682 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS
, 0);
683 if (!has_completed_circuit
&& !circ
->build_state
->onehop_tunnel
) {
684 or_options_t
*options
= get_options();
685 has_completed_circuit
=1;
686 /* FFFF Log a count of known routers here */
687 log(LOG_NOTICE
, LD_GENERAL
,
688 "Tor has successfully opened a circuit. "
689 "Looks like client functionality is working.");
690 control_event_bootstrap(BOOTSTRAP_STATUS_DONE
, 0);
691 control_event_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
692 if (server_mode(options
) && !check_whether_orport_reachable()) {
693 inform_testing_reachability();
694 consider_testing_reachability(1, 1);
697 circuit_rep_hist_note_result(circ
);
698 circuit_has_opened(circ
); /* do other actions as necessary */
702 if (tor_addr_family(&hop
->extend_info
->addr
) != AF_INET
) {
703 log_warn(LD_BUG
, "Trying to extend to a non-IPv4 address.");
704 return - END_CIRC_REASON_INTERNAL
;
707 set_uint32(payload
, tor_addr_to_ipv4n(&hop
->extend_info
->addr
));
708 set_uint16(payload
+4, htons(hop
->extend_info
->port
));
710 onionskin
= payload
+2+4;
711 memcpy(payload
+2+4+ONIONSKIN_CHALLENGE_LEN
,
712 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
713 payload_len
= 2+4+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
;
715 if (onion_skin_create(hop
->extend_info
->onion_key
,
716 &(hop
->dh_handshake_state
), onionskin
) < 0) {
717 log_warn(LD_CIRC
,"onion_skin_create failed.");
718 return - END_CIRC_REASON_INTERNAL
;
721 log_info(LD_CIRC
,"Sending extend relay cell.");
722 note_request("cell: extend", 1);
723 /* send it to hop->prev, because it will transfer
724 * it to a create cell and then send to hop */
725 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
726 RELAY_COMMAND_EXTEND
,
727 payload
, payload_len
, hop
->prev
) < 0)
728 return 0; /* circuit is closed */
730 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
735 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
736 * something has also gone wrong with our network: notify the user,
737 * and abandon all not-yet-used circuits. */
739 circuit_note_clock_jumped(int seconds_elapsed
)
741 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
742 log(severity
, LD_GENERAL
, "Your system clock just jumped %d seconds %s; "
743 "assuming established circuits no longer work.",
744 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
,
745 seconds_elapsed
>=0 ? "forward" : "backward");
746 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%d",
748 has_completed_circuit
=0; /* so it'll log when it works again */
749 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
751 circuit_mark_all_unused_circs();
752 circuit_expire_all_dirty_circs();
755 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
756 * skin and identity digest for the next hop. If we're already connected,
757 * pass the onion skin to the next hop using a create cell; otherwise
758 * launch a new OR connection, and <b>circ</b> will notice when the
759 * connection succeeds or fails.
761 * Return -1 if we want to warn and tear down the circuit, else return 0.
764 circuit_extend(cell_t
*cell
, circuit_t
*circ
)
766 or_connection_t
*n_conn
;
769 char *id_digest
=NULL
;
773 const char *msg
= NULL
;
774 int should_launch
= 0;
777 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
778 "n_conn already set. Bug/attack. Closing.");
782 if (!server_mode(get_options())) {
783 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
784 "Got an extend cell, but running as a client. Closing.");
788 relay_header_unpack(&rh
, cell
->payload
);
790 if (rh
.length
< 4+2+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
) {
791 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
792 "Wrong length %d on extend cell. Closing circuit.",
797 n_addr32
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
798 n_port
= ntohs(get_uint16(cell
->payload
+RELAY_HEADER_SIZE
+4));
799 onionskin
= cell
->payload
+RELAY_HEADER_SIZE
+4+2;
800 id_digest
= cell
->payload
+RELAY_HEADER_SIZE
+4+2+ONIONSKIN_CHALLENGE_LEN
;
801 tor_addr_from_ipv4h(&n_addr
, n_addr32
);
803 /* First, check if they asked us for 0000..0000. We support using
804 * an empty fingerprint for the first hop (e.g. for a bridge relay),
805 * but we don't want to let people send us extend cells for empty
806 * fingerprints -- a) because it opens the user up to a mitm attack,
807 * and b) because it lets an attacker force the relay to hold open a
808 * new TLS connection for each extend request. */
809 if (tor_digest_is_zero(id_digest
)) {
810 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
811 "Client asked me to extend without specifying an id_digest.");
815 /* Next, check if we're being asked to connect to the hop that the
816 * extend cell came from. There isn't any reason for that, and it can
817 * assist circular-path attacks. */
818 if (!memcmp(id_digest
, TO_OR_CIRCUIT(circ
)->p_conn
->identity_digest
,
820 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
821 "Client asked me to extend back to the previous hop.");
825 n_conn
= connection_or_get_by_identity_digest(id_digest
);
827 /* If we don't have an open conn, or the conn we have is obsolete
828 * (i.e. old or broken) and the other side will let us make a second
829 * connection without dropping it immediately... */
830 if (!connection_good_enough_for_extend(n_conn
, &n_addr
, &msg
,
832 log_debug(LD_CIRC
|LD_OR
,"Next router (%s:%d) %s",
833 fmt_addr(&n_addr
), (int)n_port
, msg
?msg
:"????");
835 circ
->n_hop
= extend_info_alloc(NULL
/*nickname*/,
840 circ
->n_conn_onionskin
= tor_malloc(ONIONSKIN_CHALLENGE_LEN
);
841 memcpy(circ
->n_conn_onionskin
, onionskin
, ONIONSKIN_CHALLENGE_LEN
);
842 circuit_set_state(circ
, CIRCUIT_STATE_OR_WAIT
);
845 /* we should try to open a connection */
846 n_conn
= connection_or_connect(&n_addr
, n_port
, id_digest
);
848 log_info(LD_CIRC
,"Launching n_conn failed. Closing circuit.");
849 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
852 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
854 /* return success. The onion/circuit/etc will be taken care of
855 * automatically (may already have been) whenever n_conn reaches
856 * OR_CONN_STATE_OPEN.
861 tor_assert(!circ
->n_hop
); /* Connection is already established. */
862 circ
->n_conn
= n_conn
;
863 log_debug(LD_CIRC
,"n_conn is %s:%u",
864 n_conn
->_base
.address
,n_conn
->_base
.port
);
866 if (circuit_deliver_create_cell(circ
, CELL_CREATE
, onionskin
) < 0)
871 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
872 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
874 * - 20 to initialize f_digest
875 * - 20 to initialize b_digest
876 * - 16 to key f_crypto
877 * - 16 to key b_crypto
879 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
882 circuit_init_cpath_crypto(crypt_path_t
*cpath
, const char *key_data
,
885 crypto_digest_env_t
*tmp_digest
;
886 crypto_cipher_env_t
*tmp_crypto
;
889 tor_assert(key_data
);
890 tor_assert(!(cpath
->f_crypto
|| cpath
->b_crypto
||
891 cpath
->f_digest
|| cpath
->b_digest
));
893 cpath
->f_digest
= crypto_new_digest_env();
894 crypto_digest_add_bytes(cpath
->f_digest
, key_data
, DIGEST_LEN
);
895 cpath
->b_digest
= crypto_new_digest_env();
896 crypto_digest_add_bytes(cpath
->b_digest
, key_data
+DIGEST_LEN
, DIGEST_LEN
);
898 if (!(cpath
->f_crypto
=
899 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
),1))) {
900 log_warn(LD_BUG
,"Forward cipher initialization failed.");
903 if (!(cpath
->b_crypto
=
904 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
)+CIPHER_KEY_LEN
,0))) {
905 log_warn(LD_BUG
,"Backward cipher initialization failed.");
910 tmp_digest
= cpath
->f_digest
;
911 cpath
->f_digest
= cpath
->b_digest
;
912 cpath
->b_digest
= tmp_digest
;
913 tmp_crypto
= cpath
->f_crypto
;
914 cpath
->f_crypto
= cpath
->b_crypto
;
915 cpath
->b_crypto
= tmp_crypto
;
921 /** A created or extended cell came back to us on the circuit, and it included
922 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
923 * contains (the second DH key, plus KH). If <b>reply_type</b> is
924 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
926 * Calculate the appropriate keys and digests, make sure KH is
927 * correct, and initialize this hop of the cpath.
929 * Return - reason if we want to mark circ for close, else return 0.
932 circuit_finish_handshake(origin_circuit_t
*circ
, uint8_t reply_type
,
935 char keys
[CPATH_KEY_MATERIAL_LEN
];
938 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
)
941 hop
= onion_next_hop_in_cpath(circ
->cpath
);
942 if (!hop
) { /* got an extended when we're all done? */
943 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
944 return - END_CIRC_REASON_TORPROTOCOL
;
947 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
949 if (reply_type
== CELL_CREATED
&& hop
->dh_handshake_state
) {
950 if (onion_skin_client_handshake(hop
->dh_handshake_state
, reply
, keys
,
951 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
952 log_warn(LD_CIRC
,"onion_skin_client_handshake failed.");
953 return -END_CIRC_REASON_TORPROTOCOL
;
955 /* Remember hash of g^xy */
956 memcpy(hop
->handshake_digest
, reply
+DH_KEY_LEN
, DIGEST_LEN
);
957 } else if (reply_type
== CELL_CREATED_FAST
&& !hop
->dh_handshake_state
) {
958 if (fast_client_handshake(hop
->fast_handshake_state
, reply
, keys
,
959 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
960 log_warn(LD_CIRC
,"fast_client_handshake failed.");
961 return -END_CIRC_REASON_TORPROTOCOL
;
963 memcpy(hop
->handshake_digest
, reply
+DIGEST_LEN
, DIGEST_LEN
);
965 log_warn(LD_PROTOCOL
,"CREATED cell type did not match CREATE cell type.");
966 return -END_CIRC_REASON_TORPROTOCOL
;
969 if (hop
->dh_handshake_state
) {
970 crypto_dh_free(hop
->dh_handshake_state
); /* don't need it anymore */
971 hop
->dh_handshake_state
= NULL
;
973 memset(hop
->fast_handshake_state
, 0, sizeof(hop
->fast_handshake_state
));
975 if (circuit_init_cpath_crypto(hop
, keys
, 0)<0) {
976 return -END_CIRC_REASON_TORPROTOCOL
;
979 hop
->state
= CPATH_STATE_OPEN
;
980 log_info(LD_CIRC
,"Finished building %scircuit hop:",
981 (reply_type
== CELL_CREATED_FAST
) ? "fast " : "");
982 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
983 control_event_circuit_status(circ
, CIRC_EVENT_EXTENDED
, 0);
988 /** We received a relay truncated cell on circ.
990 * Since we don't ask for truncates currently, getting a truncated
991 * means that a connection broke or an extend failed. For now,
992 * just give up: for circ to close, and return 0.
995 circuit_truncated(origin_circuit_t
*circ
, crypt_path_t
*layer
)
997 // crypt_path_t *victim;
998 // connection_t *stream;
1003 /* XXX Since we don't ask for truncates currently, getting a truncated
1004 * means that a connection broke or an extend failed. For now,
1007 circuit_mark_for_close(TO_CIRCUIT(circ
),
1008 END_CIRC_REASON_FLAG_REMOTE
|END_CIRC_REASON_OR_CONN_CLOSED
);
1012 while (layer
->next
!= circ
->cpath
) {
1013 /* we need to clear out layer->next */
1014 victim
= layer
->next
;
1015 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
1017 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
1018 if (stream
->cpath_layer
== victim
) {
1019 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
1021 /* no need to send 'end' relay cells,
1022 * because the other side's already dead
1024 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
1028 layer
->next
= victim
->next
;
1029 circuit_free_cpath_node(victim
);
1032 log_info(LD_CIRC
, "finished");
1037 /** Given a response payload and keys, initialize, then send a created
1041 onionskin_answer(or_circuit_t
*circ
, uint8_t cell_type
, const char *payload
,
1045 crypt_path_t
*tmp_cpath
;
1047 tmp_cpath
= tor_malloc_zero(sizeof(crypt_path_t
));
1048 tmp_cpath
->magic
= CRYPT_PATH_MAGIC
;
1050 memset(&cell
, 0, sizeof(cell_t
));
1051 cell
.command
= cell_type
;
1052 cell
.circ_id
= circ
->p_circ_id
;
1054 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
1056 memcpy(cell
.payload
, payload
,
1057 cell_type
== CELL_CREATED
? ONIONSKIN_REPLY_LEN
: DIGEST_LEN
*2);
1059 log_debug(LD_CIRC
,"init digest forward 0x%.8x, backward 0x%.8x.",
1060 (unsigned int)*(uint32_t*)(keys
),
1061 (unsigned int)*(uint32_t*)(keys
+20));
1062 if (circuit_init_cpath_crypto(tmp_cpath
, keys
, 0)<0) {
1063 log_warn(LD_BUG
,"Circuit initialization failed");
1064 tor_free(tmp_cpath
);
1067 circ
->n_digest
= tmp_cpath
->f_digest
;
1068 circ
->n_crypto
= tmp_cpath
->f_crypto
;
1069 circ
->p_digest
= tmp_cpath
->b_digest
;
1070 circ
->p_crypto
= tmp_cpath
->b_crypto
;
1071 tmp_cpath
->magic
= 0;
1072 tor_free(tmp_cpath
);
1074 if (cell_type
== CELL_CREATED
)
1075 memcpy(circ
->handshake_digest
, cell
.payload
+DH_KEY_LEN
, DIGEST_LEN
);
1077 memcpy(circ
->handshake_digest
, cell
.payload
+DIGEST_LEN
, DIGEST_LEN
);
1079 circ
->is_first_hop
= (cell_type
== CELL_CREATED_FAST
);
1081 append_cell_to_circuit_queue(TO_CIRCUIT(circ
),
1082 circ
->p_conn
, &cell
, CELL_DIRECTION_IN
);
1083 log_debug(LD_CIRC
,"Finished sending 'created' cell.");
1085 if (!is_local_addr(&circ
->p_conn
->_base
.addr
) &&
1086 !connection_or_nonopen_was_started_here(circ
->p_conn
)) {
1087 /* record that we could process create cells from a non-local conn
1088 * that we didn't initiate; presumably this means that create cells
1089 * can reach us too. */
1090 router_orport_found_reachable();
1096 /** Choose a length for a circuit of purpose <b>purpose</b>.
1097 * Default length is 3 + the number of endpoints that would give something
1098 * away. If the routerlist <b>routers</b> doesn't have enough routers
1099 * to handle the desired path length, return as large a path length as
1100 * is feasible, except if it's less than 2, in which case return -1.
1103 new_route_len(uint8_t purpose
, extend_info_t
*exit
,
1104 smartlist_t
*routers
)
1106 int num_acceptable_routers
;
1109 tor_assert(routers
);
1113 purpose
!= CIRCUIT_PURPOSE_TESTING
&&
1114 purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
1117 num_acceptable_routers
= count_acceptable_routers(routers
);
1119 log_debug(LD_CIRC
,"Chosen route length %d (%d/%d routers suitable).",
1120 routelen
, num_acceptable_routers
, smartlist_len(routers
));
1122 if (num_acceptable_routers
< 2) {
1124 "Not enough acceptable routers (%d). Discarding this circuit.",
1125 num_acceptable_routers
);
1129 if (num_acceptable_routers
< routelen
) {
1130 log_info(LD_CIRC
,"Not enough routers: cutting routelen from %d to %d.",
1131 routelen
, num_acceptable_routers
);
1132 routelen
= num_acceptable_routers
;
1138 /** Fetch the list of predicted ports, dup it into a smartlist of
1139 * uint16_t's, remove the ones that are already handled by an
1140 * existing circuit, and return it.
1142 static smartlist_t
*
1143 circuit_get_unhandled_ports(time_t now
)
1145 smartlist_t
*source
= rep_hist_get_predicted_ports(now
);
1146 smartlist_t
*dest
= smartlist_create();
1150 for (i
= 0; i
< smartlist_len(source
); ++i
) {
1151 tmp
= tor_malloc(sizeof(uint16_t));
1152 memcpy(tmp
, smartlist_get(source
, i
), sizeof(uint16_t));
1153 smartlist_add(dest
, tmp
);
1156 circuit_remove_handled_ports(dest
);
1160 /** Return 1 if we already have circuits present or on the way for
1161 * all anticipated ports. Return 0 if we should make more.
1163 * If we're returning 0, set need_uptime and need_capacity to
1164 * indicate any requirements that the unhandled ports have.
1167 circuit_all_predicted_ports_handled(time_t now
, int *need_uptime
,
1172 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
1173 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
1174 tor_assert(need_uptime
);
1175 tor_assert(need_capacity
);
1176 enough
= (smartlist_len(sl
) == 0);
1177 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
1178 port
= smartlist_get(sl
, i
);
1179 if (smartlist_string_num_isin(LongLivedServices
, *port
))
1187 /** Return 1 if <b>router</b> can handle one or more of the ports in
1188 * <b>needed_ports</b>, else return 0.
1191 router_handles_some_port(routerinfo_t
*router
, smartlist_t
*needed_ports
)
1196 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
1197 addr_policy_result_t r
;
1198 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
1200 r
= compare_addr_to_addr_policy(0, port
, router
->exit_policy
);
1201 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
1207 /** Return true iff <b>conn</b> needs another general circuit to be
1210 ap_stream_wants_exit_attention(connection_t
*conn
)
1212 if (conn
->type
== CONN_TYPE_AP
&&
1213 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
1214 !conn
->marked_for_close
&&
1215 !(TO_EDGE_CONN(conn
)->want_onehop
) && /* ignore one-hop streams */
1216 !(TO_EDGE_CONN(conn
)->use_begindir
) && /* ignore targeted dir fetches */
1217 !(TO_EDGE_CONN(conn
)->chosen_exit_name
) && /* ignore defined streams */
1218 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
1219 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn
), 0,
1220 MIN_CIRCUITS_HANDLING_STREAM
))
1225 /** Return a pointer to a suitable router to be the exit node for the
1226 * general-purpose circuit we're about to build.
1228 * Look through the connection array, and choose a router that maximizes
1229 * the number of pending streams that can exit from this router.
1231 * Return NULL if we can't find any suitable routers.
1233 static routerinfo_t
*
1234 choose_good_exit_server_general(routerlist_t
*dir
, int need_uptime
,
1239 int n_pending_connections
= 0;
1240 smartlist_t
*connections
;
1241 int best_support
= -1;
1242 int n_best_support
=0;
1243 routerinfo_t
*router
;
1244 or_options_t
*options
= get_options();
1246 connections
= get_connection_array();
1248 /* Count how many connections are waiting for a circuit to be built.
1249 * We use this for log messages now, but in the future we may depend on it.
1251 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1253 if (ap_stream_wants_exit_attention(conn
))
1254 ++n_pending_connections
;
1256 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1257 // n_pending_connections);
1258 /* Now we count, for each of the routers in the directory, how many
1259 * of the pending connections could possibly exit from that
1260 * router (n_supported[i]). (We can't be sure about cases where we
1261 * don't know the IP address of the pending connection.)
1263 * -1 means "Don't use this router at all."
1265 n_supported
= tor_malloc(sizeof(int)*smartlist_len(dir
->routers
));
1266 for (i
= 0; i
< smartlist_len(dir
->routers
); ++i
) {/* iterate over routers */
1267 router
= smartlist_get(dir
->routers
, i
);
1268 if (router_is_me(router
)) {
1269 n_supported
[i
] = -1;
1270 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1271 /* XXX there's probably a reverse predecessor attack here, but
1272 * it's slow. should we take this out? -RD
1276 if (!router
->is_running
|| router
->is_bad_exit
) {
1277 n_supported
[i
] = -1;
1278 continue; /* skip routers that are known to be down or bad exits */
1280 if (router_is_unreliable(router
, need_uptime
, need_capacity
, 0)) {
1281 n_supported
[i
] = -1;
1282 continue; /* skip routers that are not suitable */
1284 if (!(router
->is_valid
|| options
->_AllowInvalid
& ALLOW_INVALID_EXIT
)) {
1285 /* if it's invalid and we don't want it */
1286 n_supported
[i
] = -1;
1287 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1288 // router->nickname, i);
1289 continue; /* skip invalid routers */
1291 if (options
->ExcludeSingleHopRelays
&& router
->allow_single_hop_exits
) {
1292 n_supported
[i
] = -1;
1295 if (router_exit_policy_rejects_all(router
)) {
1296 n_supported
[i
] = -1;
1297 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1298 // router->nickname, i);
1299 continue; /* skip routers that reject all */
1302 /* iterate over connections */
1303 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1305 if (!ap_stream_wants_exit_attention(conn
))
1306 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1307 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn
), router
)) {
1309 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1310 // router->nickname, i, n_supported[i]);
1312 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1313 // router->nickname, i);
1315 }); /* End looping over connections. */
1316 if (n_pending_connections
> 0 && n_supported
[i
] == 0) {
1317 /* Leave best_support at -1 if that's where it is, so we can
1318 * distinguish it later. */
1321 if (n_supported
[i
] > best_support
) {
1322 /* If this router is better than previous ones, remember its index
1323 * and goodness, and start counting how many routers are this good. */
1324 best_support
= n_supported
[i
]; n_best_support
=1;
1325 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1326 // router->nickname);
1327 } else if (n_supported
[i
] == best_support
) {
1328 /* If this router is _as good_ as the best one, just increment the
1329 * count of equally good routers.*/
1334 "Found %d servers that might support %d/%d pending connections.",
1335 n_best_support
, best_support
>= 0 ? best_support
: 0,
1336 n_pending_connections
);
1338 /* If any routers definitely support any pending connections, choose one
1340 if (best_support
> 0) {
1341 smartlist_t
*supporting
= smartlist_create(), *use
= smartlist_create();
1343 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++)
1344 if (n_supported
[i
] == best_support
)
1345 smartlist_add(supporting
, smartlist_get(dir
->routers
, i
));
1347 routersets_get_disjunction(use
, supporting
, options
->ExitNodes
,
1348 options
->_ExcludeExitNodesUnion
, 1);
1349 if (smartlist_len(use
) == 0 && !options
->StrictExitNodes
) {
1350 routersets_get_disjunction(use
, supporting
, NULL
,
1351 options
->_ExcludeExitNodesUnion
, 1);
1353 router
= routerlist_sl_choose_by_bandwidth(use
, WEIGHT_FOR_EXIT
);
1354 smartlist_free(use
);
1355 smartlist_free(supporting
);
1357 /* Either there are no pending connections, or no routers even seem to
1358 * possibly support any of them. Choose a router at random that satisfies
1359 * at least one predicted exit port. */
1362 smartlist_t
*needed_ports
, *supporting
, *use
;
1364 if (best_support
== -1) {
1365 if (need_uptime
|| need_capacity
) {
1367 "We couldn't find any live%s%s routers; falling back "
1368 "to list of all routers.",
1369 need_capacity
?", fast":"",
1370 need_uptime
?", stable":"");
1371 tor_free(n_supported
);
1372 return choose_good_exit_server_general(dir
, 0, 0);
1374 log_notice(LD_CIRC
, "All routers are down or won't exit -- choosing a "
1375 "doomed exit at random.");
1377 supporting
= smartlist_create();
1378 use
= smartlist_create();
1379 needed_ports
= circuit_get_unhandled_ports(time(NULL
));
1380 for (try = 0; try < 2; try++) {
1381 /* try once to pick only from routers that satisfy a needed port,
1382 * then if there are none, pick from any that support exiting. */
1383 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++) {
1384 router
= smartlist_get(dir
->routers
, i
);
1385 if (n_supported
[i
] != -1 &&
1386 (try || router_handles_some_port(router
, needed_ports
))) {
1387 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1388 // try, router->nickname);
1389 smartlist_add(supporting
, router
);
1393 routersets_get_disjunction(use
, supporting
, options
->ExitNodes
,
1394 options
->_ExcludeExitNodesUnion
, 1);
1395 if (smartlist_len(use
) == 0 && !options
->StrictExitNodes
) {
1396 routersets_get_disjunction(use
, supporting
, NULL
,
1397 options
->_ExcludeExitNodesUnion
, 1);
1399 /* XXX sometimes the above results in null, when the requested
1400 * exit node is down. we should pick it anyway. */
1401 router
= routerlist_sl_choose_by_bandwidth(use
, WEIGHT_FOR_EXIT
);
1404 smartlist_clear(supporting
);
1405 smartlist_clear(use
);
1407 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
1408 smartlist_free(needed_ports
);
1409 smartlist_free(use
);
1410 smartlist_free(supporting
);
1413 tor_free(n_supported
);
1415 log_info(LD_CIRC
, "Chose exit server '%s'", router
->nickname
);
1418 if (options
->StrictExitNodes
) {
1420 "No specified exit routers seem to be running, and "
1421 "StrictExitNodes is set: can't choose an exit.");
1426 /** Return a pointer to a suitable router to be the exit node for the
1427 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1428 * if no router is suitable).
1430 * For general-purpose circuits, pass it off to
1431 * choose_good_exit_server_general()
1433 * For client-side rendezvous circuits, choose a random node, weighted
1434 * toward the preferences in 'options'.
1436 static routerinfo_t
*
1437 choose_good_exit_server(uint8_t purpose
, routerlist_t
*dir
,
1438 int need_uptime
, int need_capacity
, int is_internal
)
1440 or_options_t
*options
= get_options();
1441 router_crn_flags_t flags
= 0;
1443 flags
|= CRN_NEED_UPTIME
;
1445 flags
|= CRN_NEED_CAPACITY
;
1448 case CIRCUIT_PURPOSE_C_GENERAL
:
1449 if (options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
)
1450 flags
|= CRN_ALLOW_INVALID
;
1451 if (is_internal
) /* pick it like a middle hop */
1452 return router_choose_random_node(NULL
, NULL
,
1453 options
->ExcludeNodes
, flags
);
1455 return choose_good_exit_server_general(dir
,need_uptime
,need_capacity
);
1456 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1457 if (options
->_AllowInvalid
& ALLOW_INVALID_RENDEZVOUS
)
1458 flags
|= CRN_ALLOW_INVALID
;
1459 return router_choose_random_node(NULL
, NULL
,
1460 options
->ExcludeNodes
, flags
);
1462 log_warn(LD_BUG
,"Unhandled purpose %d", purpose
);
1463 tor_fragile_assert();
1467 /** Log a warning if the user specified an exit for the circuit that
1468 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1470 warn_if_router_excluded(const extend_info_t
*exit
)
1472 or_options_t
*options
= get_options();
1473 routerinfo_t
*ri
= router_get_by_digest(exit
->identity_digest
);
1475 if (!ri
|| !options
->_ExcludeExitNodesUnion
)
1478 if (routerset_contains_router(options
->_ExcludeExitNodesUnion
, ri
))
1479 log_warn(LD_CIRC
,"Requested exit node '%s' is in ExcludeNodes, "
1480 "or ExcludeExitNodes, using anyway.",exit
->nickname
);
1485 /** Decide a suitable length for circ's cpath, and pick an exit
1486 * router (or use <b>exit</b> if provided). Store these in the
1487 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1489 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1491 cpath_build_state_t
*state
= circ
->build_state
;
1492 routerlist_t
*rl
= router_get_routerlist();
1494 if (state
->onehop_tunnel
) {
1495 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel.");
1496 state
->desired_path_len
= 1;
1498 int r
= new_route_len(circ
->_base
.purpose
, exit
, rl
->routers
);
1499 if (r
< 1) /* must be at least 1 */
1501 state
->desired_path_len
= r
;
1504 if (exit
) { /* the circuit-builder pre-requested one */
1505 warn_if_router_excluded(exit
);
1506 log_info(LD_CIRC
,"Using requested exit node '%s'", exit
->nickname
);
1507 exit
= extend_info_dup(exit
);
1508 } else { /* we have to decide one */
1509 routerinfo_t
*router
=
1510 choose_good_exit_server(circ
->_base
.purpose
, rl
, state
->need_uptime
,
1511 state
->need_capacity
, state
->is_internal
);
1513 log_warn(LD_CIRC
,"failed to choose an exit server");
1516 exit
= extend_info_from_router(router
);
1518 state
->chosen_exit
= exit
;
1522 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1523 * hop to the cpath reflecting this. Don't send the next extend cell --
1524 * the caller will do this if it wants to.
1527 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1529 cpath_build_state_t
*state
;
1533 state
= circ
->build_state
;
1535 if (state
->chosen_exit
)
1536 extend_info_free(state
->chosen_exit
);
1537 state
->chosen_exit
= extend_info_dup(exit
);
1539 ++circ
->build_state
->desired_path_len
;
1540 onion_append_hop(&circ
->cpath
, exit
);
1544 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1545 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1546 * send the next extend cell to begin connecting to that hop.
1549 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1552 circuit_append_new_exit(circ
, exit
);
1553 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
1554 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
1555 log_warn(LD_CIRC
, "Couldn't extend circuit to new point '%s'.",
1557 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
1563 /** Return the number of routers in <b>routers</b> that are currently up
1564 * and available for building circuits through.
1567 count_acceptable_routers(smartlist_t
*routers
)
1573 n
= smartlist_len(routers
);
1575 r
= smartlist_get(routers
, i
);
1576 // log_debug(LD_CIRC,
1577 // "Contemplating whether router %d (%s) is a new option.",
1579 if (r
->is_running
== 0) {
1580 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1583 if (r
->is_valid
== 0) {
1584 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1586 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1587 * allows this node in some places, then we're getting an inaccurate
1588 * count. For now, be conservative and don't count it. But later we
1589 * should try to be smarter. */
1592 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1594 ; /* C requires an explicit statement after the label */
1600 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1601 * This function is used to extend cpath by another hop.
1604 onion_append_to_cpath(crypt_path_t
**head_ptr
, crypt_path_t
*new_hop
)
1607 new_hop
->next
= (*head_ptr
);
1608 new_hop
->prev
= (*head_ptr
)->prev
;
1609 (*head_ptr
)->prev
->next
= new_hop
;
1610 (*head_ptr
)->prev
= new_hop
;
1612 *head_ptr
= new_hop
;
1613 new_hop
->prev
= new_hop
->next
= new_hop
;
1617 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1618 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1619 * to length <b>cur_len</b> to decide a suitable middle hop for a
1620 * circuit. In particular, make sure we don't pick the exit node or its
1621 * family, and make sure we don't duplicate any previous nodes or their
1623 static routerinfo_t
*
1624 choose_good_middle_server(uint8_t purpose
,
1625 cpath_build_state_t
*state
,
1630 routerinfo_t
*r
, *choice
;
1631 crypt_path_t
*cpath
;
1632 smartlist_t
*excluded
;
1633 or_options_t
*options
= get_options();
1634 router_crn_flags_t flags
= 0;
1635 tor_assert(_CIRCUIT_PURPOSE_MIN
<= purpose
&&
1636 purpose
<= _CIRCUIT_PURPOSE_MAX
);
1638 log_debug(LD_CIRC
, "Contemplating intermediate hop: random choice.");
1639 excluded
= smartlist_create();
1640 if ((r
= build_state_get_exit_router(state
))) {
1641 smartlist_add(excluded
, r
);
1642 routerlist_add_family(excluded
, r
);
1644 for (i
= 0, cpath
= head
; i
< cur_len
; ++i
, cpath
=cpath
->next
) {
1645 if ((r
= router_get_by_digest(cpath
->extend_info
->identity_digest
))) {
1646 smartlist_add(excluded
, r
);
1647 routerlist_add_family(excluded
, r
);
1651 if (state
->need_uptime
)
1652 flags
|= CRN_NEED_UPTIME
;
1653 if (state
->need_capacity
)
1654 flags
|= CRN_NEED_CAPACITY
;
1655 if (options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
)
1656 flags
|= CRN_ALLOW_INVALID
;
1657 choice
= router_choose_random_node(NULL
,
1658 excluded
, options
->ExcludeNodes
, flags
);
1659 smartlist_free(excluded
);
1663 /** Pick a good entry server for the circuit to be built according to
1664 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1665 * router (if we're an OR), and respect firewall settings; if we're
1666 * configured to use entry guards, return one.
1668 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1669 * guard, not for any particular circuit.
1671 static routerinfo_t
*
1672 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
)
1674 routerinfo_t
*r
, *choice
;
1675 smartlist_t
*excluded
;
1676 or_options_t
*options
= get_options();
1677 router_crn_flags_t flags
= 0;
1679 if (state
&& options
->UseEntryGuards
&&
1680 (purpose
!= CIRCUIT_PURPOSE_TESTING
|| options
->BridgeRelay
)) {
1681 return choose_random_entry(state
);
1684 excluded
= smartlist_create();
1686 if (state
&& (r
= build_state_get_exit_router(state
))) {
1687 smartlist_add(excluded
, r
);
1688 routerlist_add_family(excluded
, r
);
1690 if (firewall_is_fascist_or()) {
1691 /*XXXX This could slow things down a lot; use a smarter implementation */
1692 /* exclude all ORs that listen on the wrong port, if anybody notices. */
1693 routerlist_t
*rl
= router_get_routerlist();
1696 for (i
=0; i
< smartlist_len(rl
->routers
); i
++) {
1697 r
= smartlist_get(rl
->routers
, i
);
1698 if (!fascist_firewall_allows_or(r
))
1699 smartlist_add(excluded
, r
);
1702 /* and exclude current entry guards, if applicable */
1703 if (options
->UseEntryGuards
&& entry_guards
) {
1704 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1706 if ((r
= router_get_by_digest(entry
->identity
))) {
1707 smartlist_add(excluded
, r
);
1708 routerlist_add_family(excluded
, r
);
1714 flags
|= CRN_NEED_GUARD
;
1715 if (state
->need_uptime
)
1716 flags
|= CRN_NEED_UPTIME
;
1717 if (state
->need_capacity
)
1718 flags
|= CRN_NEED_CAPACITY
;
1720 if (options
->_AllowInvalid
& ALLOW_INVALID_ENTRY
)
1721 flags
|= CRN_ALLOW_INVALID
;
1723 choice
= router_choose_random_node(
1726 options
->ExcludeNodes
,
1728 smartlist_free(excluded
);
1732 /** Return the first non-open hop in cpath, or return NULL if all
1734 static crypt_path_t
*
1735 onion_next_hop_in_cpath(crypt_path_t
*cpath
)
1737 crypt_path_t
*hop
= cpath
;
1739 if (hop
->state
!= CPATH_STATE_OPEN
)
1742 } while (hop
!= cpath
);
1746 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1747 * based on <b>state</b>. Append the hop info to head_ptr.
1750 onion_extend_cpath(origin_circuit_t
*circ
)
1752 uint8_t purpose
= circ
->_base
.purpose
;
1753 cpath_build_state_t
*state
= circ
->build_state
;
1754 int cur_len
= circuit_get_cpath_len(circ
);
1755 extend_info_t
*info
= NULL
;
1757 if (cur_len
>= state
->desired_path_len
) {
1758 log_debug(LD_CIRC
, "Path is complete: %d steps long",
1759 state
->desired_path_len
);
1763 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
1764 state
->desired_path_len
);
1766 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
1767 info
= extend_info_dup(state
->chosen_exit
);
1768 } else if (cur_len
== 0) { /* picking first node */
1769 routerinfo_t
*r
= choose_good_entry_server(purpose
, state
);
1771 info
= extend_info_from_router(r
);
1774 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
1776 info
= extend_info_from_router(r
);
1780 log_warn(LD_CIRC
,"Failed to find node for hop %d of our path. Discarding "
1781 "this circuit.", cur_len
);
1785 log_debug(LD_CIRC
,"Chose router %s for hop %d (exit is %s)",
1786 info
->nickname
, cur_len
+1, build_state_get_exit_nickname(state
));
1788 onion_append_hop(&circ
->cpath
, info
);
1789 extend_info_free(info
);
1793 /** Create a new hop, annotate it with information about its
1794 * corresponding router <b>choice</b>, and append it to the
1795 * end of the cpath <b>head_ptr</b>. */
1797 onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
)
1799 crypt_path_t
*hop
= tor_malloc_zero(sizeof(crypt_path_t
));
1801 /* link hop into the cpath, at the end. */
1802 onion_append_to_cpath(head_ptr
, hop
);
1804 hop
->magic
= CRYPT_PATH_MAGIC
;
1805 hop
->state
= CPATH_STATE_CLOSED
;
1807 hop
->extend_info
= extend_info_dup(choice
);
1809 hop
->package_window
= CIRCWINDOW_START
;
1810 hop
->deliver_window
= CIRCWINDOW_START
;
1815 /** Allocate a new extend_info object based on the various arguments. */
1817 extend_info_alloc(const char *nickname
, const char *digest
,
1818 crypto_pk_env_t
*onion_key
,
1819 const tor_addr_t
*addr
, uint16_t port
)
1821 extend_info_t
*info
= tor_malloc_zero(sizeof(extend_info_t
));
1822 memcpy(info
->identity_digest
, digest
, DIGEST_LEN
);
1824 strlcpy(info
->nickname
, nickname
, sizeof(info
->nickname
));
1826 info
->onion_key
= crypto_pk_dup_key(onion_key
);
1827 tor_addr_copy(&info
->addr
, addr
);
1832 /** Allocate and return a new extend_info_t that can be used to build a
1833 * circuit to or through the router <b>r</b>. */
1835 extend_info_from_router(routerinfo_t
*r
)
1839 tor_addr_from_ipv4h(&addr
, r
->addr
);
1840 return extend_info_alloc(r
->nickname
, r
->cache_info
.identity_digest
,
1841 r
->onion_pkey
, &addr
, r
->or_port
);
1844 /** Release storage held by an extend_info_t struct. */
1846 extend_info_free(extend_info_t
*info
)
1849 if (info
->onion_key
)
1850 crypto_free_pk_env(info
->onion_key
);
1854 /** Allocate and return a new extend_info_t with the same contents as
1857 extend_info_dup(extend_info_t
*info
)
1859 extend_info_t
*newinfo
;
1861 newinfo
= tor_malloc(sizeof(extend_info_t
));
1862 memcpy(newinfo
, info
, sizeof(extend_info_t
));
1863 if (info
->onion_key
)
1864 newinfo
->onion_key
= crypto_pk_dup_key(info
->onion_key
);
1866 newinfo
->onion_key
= NULL
;
1870 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1871 * If there is no chosen exit, or if we don't know the routerinfo_t for
1872 * the chosen exit, return NULL.
1875 build_state_get_exit_router(cpath_build_state_t
*state
)
1877 if (!state
|| !state
->chosen_exit
)
1879 return router_get_by_digest(state
->chosen_exit
->identity_digest
);
1882 /** Return the nickname for the chosen exit router in <b>state</b>. If
1883 * there is no chosen exit, or if we don't know the routerinfo_t for the
1884 * chosen exit, return NULL.
1887 build_state_get_exit_nickname(cpath_build_state_t
*state
)
1889 if (!state
|| !state
->chosen_exit
)
1891 return state
->chosen_exit
->nickname
;
1894 /** Check whether the entry guard <b>e</b> is usable, given the directory
1895 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1896 * configuration (in <b>options</b>). Set <b>e</b>->bad_since
1897 * accordingly. Return true iff the entry guard's status changes.
1899 * If it's not usable, set *<b>reason</b> to a static string explaining why.
1901 /*XXXX take a routerstatus, not a routerinfo. */
1903 entry_guard_set_status(entry_guard_t
*e
, routerinfo_t
*ri
,
1904 time_t now
, or_options_t
*options
, const char **reason
)
1906 char buf
[HEX_DIGEST_LEN
+1];
1909 tor_assert(options
);
1913 /* Do we want to mark this guard as bad? */
1915 *reason
= "unlisted";
1916 else if (!ri
->is_running
)
1918 else if (options
->UseBridges
&& ri
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1919 *reason
= "not a bridge";
1920 else if (!options
->UseBridges
&& !ri
->is_possible_guard
&&
1921 !routerset_contains_router(options
->EntryNodes
,ri
))
1922 *reason
= "not recommended as a guard";
1923 else if (routerset_contains_router(options
->ExcludeNodes
, ri
))
1924 *reason
= "excluded";
1926 if (*reason
&& ! e
->bad_since
) {
1927 /* Router is newly bad. */
1928 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1929 log_info(LD_CIRC
, "Entry guard %s (%s) is %s: marking as unusable.",
1930 e
->nickname
, buf
, *reason
);
1933 control_event_guard(e
->nickname
, e
->identity
, "BAD");
1935 } else if (!*reason
&& e
->bad_since
) {
1936 /* There's nothing wrong with the router any more. */
1937 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1938 log_info(LD_CIRC
, "Entry guard %s (%s) is no longer unusable: "
1939 "marking as ok.", e
->nickname
, buf
);
1942 control_event_guard(e
->nickname
, e
->identity
, "GOOD");
1948 /** Return true iff enough time has passed since we last tried to connect
1949 * to the unreachable guard <b>e</b> that we're willing to try again. */
1951 entry_is_time_to_retry(entry_guard_t
*e
, time_t now
)
1954 if (e
->last_attempted
< e
->unreachable_since
)
1956 diff
= now
- e
->unreachable_since
;
1958 return now
> (e
->last_attempted
+ 60*60);
1959 else if (diff
< 3*24*60*60)
1960 return now
> (e
->last_attempted
+ 4*60*60);
1961 else if (diff
< 7*24*60*60)
1962 return now
> (e
->last_attempted
+ 18*60*60);
1964 return now
> (e
->last_attempted
+ 36*60*60);
1967 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1968 * working well enough that we are willing to use it as an entry
1969 * right now. (Else return NULL.) In particular, it must be
1970 * - Listed as either up or never yet contacted;
1971 * - Present in the routerlist;
1972 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1973 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1974 * (This check is currently redundant with the Guard flag, but in
1975 * the future that might change. Best to leave it in for now.)
1976 * - Allowed by our current ReachableORAddresses config option; and
1977 * - Currently thought to be reachable by us (unless assume_reachable
1980 static INLINE routerinfo_t
*
1981 entry_is_live(entry_guard_t
*e
, int need_uptime
, int need_capacity
,
1982 int assume_reachable
)
1987 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1988 if (!assume_reachable
&& !e
->can_retry
&&
1989 e
->unreachable_since
&& !entry_is_time_to_retry(e
, time(NULL
)))
1991 r
= router_get_by_digest(e
->identity
);
1994 if (get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1996 if (!get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_GENERAL
)
1998 if (router_is_unreliable(r
, need_uptime
, need_capacity
, 0))
2000 if (!fascist_firewall_allows_or(r
))
2005 /** Return the number of entry guards that we think are usable. */
2007 num_live_entry_guards(void)
2012 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2014 if (entry_is_live(entry
, 0, 1, 0))
2020 /** If <b>digest</b> matches the identity of any node in the
2021 * entry_guards list, return that node. Else return NULL. */
2022 static INLINE entry_guard_t
*
2023 is_an_entry_guard(const char *digest
)
2025 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2026 if (!memcmp(digest
, entry
->identity
, DIGEST_LEN
))
2032 /** Dump a description of our list of entry guards to the log at level
2033 * <b>severity</b>. */
2035 log_entry_guards(int severity
)
2037 smartlist_t
*elements
= smartlist_create();
2041 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2043 tor_snprintf(buf
, sizeof(buf
), "%s (%s%s)",
2045 entry_is_live(e
, 0, 1, 0) ? "up " : "down ",
2046 e
->made_contact
? "made-contact" : "never-contacted");
2047 smartlist_add(elements
, tor_strdup(buf
));
2050 s
= smartlist_join_strings(elements
, ",", 0, NULL
);
2051 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
2052 smartlist_free(elements
);
2053 log_fn(severity
,LD_CIRC
,"%s",s
);
2057 /** Called when one or more guards that we would previously have used for some
2058 * purpose are no longer in use because a higher-priority guard has become
2061 control_event_guard_deferred(void)
2063 /* XXXX We don't actually have a good way to figure out _how many_ entries
2064 * are live for some purpose. We need an entry_is_even_slightly_live()
2065 * function for this to work right. NumEntryGuards isn't reliable: if we
2066 * need guards with weird properties, we can have more than that number
2071 or_options_t
*options
= get_options();
2074 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2076 if (entry_is_live(entry
, 0, 1, 0)) {
2077 if (n
++ == options
->NumEntryGuards
) {
2078 control_event_guard(entry
->nickname
, entry
->identity
, "DEFERRED");
2086 /** Add a new (preferably stable and fast) router to our
2087 * entry_guards list. Return a pointer to the router if we succeed,
2088 * or NULL if we can't find any more suitable entries.
2090 * If <b>chosen</b> is defined, use that one, and if it's not
2091 * already in our entry_guards list, put it at the *beginning*.
2092 * Else, put the one we pick at the end of the list. */
2093 static routerinfo_t
*
2094 add_an_entry_guard(routerinfo_t
*chosen
, int reset_status
)
2096 routerinfo_t
*router
;
2097 entry_guard_t
*entry
;
2101 entry
= is_an_entry_guard(router
->cache_info
.identity_digest
);
2104 entry
->bad_since
= 0;
2105 entry
->can_retry
= 1;
2110 router
= choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL
, NULL
);
2114 entry
= tor_malloc_zero(sizeof(entry_guard_t
));
2115 log_info(LD_CIRC
, "Chose '%s' as new entry guard.", router
->nickname
);
2116 strlcpy(entry
->nickname
, router
->nickname
, sizeof(entry
->nickname
));
2117 memcpy(entry
->identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
2118 entry
->chosen_on_date
= start_of_month(time(NULL
));
2119 entry
->chosen_by_version
= tor_strdup(VERSION
);
2120 if (chosen
) /* prepend */
2121 smartlist_insert(entry_guards
, 0, entry
);
2123 smartlist_add(entry_guards
, entry
);
2124 control_event_guard(entry
->nickname
, entry
->identity
, "NEW");
2125 control_event_guard_deferred();
2126 log_entry_guards(LOG_INFO
);
2130 /** If the use of entry guards is configured, choose more entry guards
2131 * until we have enough in the list. */
2133 pick_entry_guards(void)
2135 or_options_t
*options
= get_options();
2138 tor_assert(entry_guards
);
2140 while (num_live_entry_guards() < options
->NumEntryGuards
) {
2141 if (!add_an_entry_guard(NULL
, 0))
2146 entry_guards_changed();
2149 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2150 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2151 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2153 /** Release all storage held by <b>e</b>. */
2155 entry_guard_free(entry_guard_t
*e
)
2158 tor_free(e
->chosen_by_version
);
2162 /** Remove any entry guard which was selected by an unknown version of Tor,
2163 * or which was selected by a version of Tor that's known to select
2164 * entry guards badly. */
2166 remove_obsolete_entry_guards(void)
2169 for (i
= 0; i
< smartlist_len(entry_guards
); ++i
) {
2170 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2171 const char *ver
= entry
->chosen_by_version
;
2172 const char *msg
= NULL
;
2174 int version_is_bad
= 0;
2176 msg
= "does not say what version of Tor it was selected by";
2178 } else if (tor_version_parse(ver
, &v
)) {
2179 msg
= "does not seem to be from any recognized version of Tor";
2181 } else if ((tor_version_as_new_as(ver
, "0.1.0.10-alpha") &&
2182 !tor_version_as_new_as(ver
, "0.1.2.16-dev")) ||
2183 (tor_version_as_new_as(ver
, "0.2.0.0-alpha") &&
2184 !tor_version_as_new_as(ver
, "0.2.0.6-alpha"))) {
2185 msg
= "was selected without regard for guard bandwidth";
2188 if (version_is_bad
) {
2189 char dbuf
[HEX_DIGEST_LEN
+1];
2191 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2192 log_notice(LD_CIRC
, "Entry guard '%s' (%s) %s. (Version=%s.) "
2194 entry
->nickname
, dbuf
, msg
, ver
?escaped(ver
):"none");
2195 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2196 entry_guard_free(entry
);
2197 smartlist_del_keeporder(entry_guards
, i
--);
2198 log_entry_guards(LOG_INFO
);
2203 return changed
? 1 : 0;
2206 /** Remove all entry guards that have been down or unlisted for so
2207 * long that we don't think they'll come up again. Return 1 if we
2208 * removed any, or 0 if we did nothing. */
2210 remove_dead_entry_guards(void)
2212 char dbuf
[HEX_DIGEST_LEN
+1];
2213 char tbuf
[ISO_TIME_LEN
+1];
2214 time_t now
= time(NULL
);
2218 for (i
= 0; i
< smartlist_len(entry_guards
); ) {
2219 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2220 if (entry
->bad_since
&&
2221 entry
->bad_since
+ ENTRY_GUARD_REMOVE_AFTER
< now
) {
2223 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2224 format_local_iso_time(tbuf
, entry
->bad_since
);
2225 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been down or unlisted "
2226 "since %s local time; removing.",
2227 entry
->nickname
, dbuf
, tbuf
);
2228 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2229 entry_guard_free(entry
);
2230 smartlist_del_keeporder(entry_guards
, i
);
2231 log_entry_guards(LOG_INFO
);
2236 return changed
? 1 : 0;
2239 /** A new directory or router-status has arrived; update the down/listed
2240 * status of the entry guards.
2242 * An entry is 'down' if the directory lists it as nonrunning.
2243 * An entry is 'unlisted' if the directory doesn't include it.
2245 * Don't call this on startup; only on a fresh download. Otherwise we'll
2246 * think that things are unlisted.
2249 entry_guards_compute_status(void)
2253 int severity
= LOG_DEBUG
;
2254 or_options_t
*options
;
2258 options
= get_options();
2262 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2264 routerinfo_t
*r
= router_get_by_digest(entry
->identity
);
2265 const char *reason
= NULL
;
2266 /*XXX021 log reason again. */
2267 if (entry_guard_set_status(entry
, r
, now
, options
, &reason
))
2270 if (entry
->bad_since
)
2274 if (remove_dead_entry_guards())
2277 severity
= changed
? LOG_DEBUG
: LOG_INFO
;
2280 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2281 log_info(LD_CIRC
, "Summary: Entry '%s' is %s, %s, and %s.",
2283 entry
->unreachable_since
? "unreachable" : "reachable",
2284 entry
->bad_since
? "unusable" : "usable",
2285 entry_is_live(entry
, 0, 1, 0) ? "live" : "not live"));
2286 log_info(LD_CIRC
, " (%d/%d entry guards are usable/new)",
2287 num_live_entry_guards(), smartlist_len(entry_guards
));
2288 log_entry_guards(LOG_INFO
);
2289 entry_guards_changed();
2293 /** Called when a connection to an OR with the identity digest <b>digest</b>
2294 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2295 * If the OR is an entry, change that entry's up/down status.
2296 * Return 0 normally, or -1 if we want to tear down the new connection.
2299 entry_guard_register_connect_status(const char *digest
, int succeeded
,
2303 int refuse_conn
= 0;
2304 int first_contact
= 0;
2305 entry_guard_t
*entry
= NULL
;
2307 char buf
[HEX_DIGEST_LEN
+1];
2312 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2314 if (!memcmp(e
->identity
, digest
, DIGEST_LEN
)) {
2324 base16_encode(buf
, sizeof(buf
), entry
->identity
, DIGEST_LEN
);
2327 if (entry
->unreachable_since
) {
2328 log_info(LD_CIRC
, "Entry guard '%s' (%s) is now reachable again. Good.",
2329 entry
->nickname
, buf
);
2330 entry
->can_retry
= 0;
2331 entry
->unreachable_since
= 0;
2332 entry
->last_attempted
= now
;
2333 control_event_guard(entry
->nickname
, entry
->identity
, "UP");
2336 if (!entry
->made_contact
) {
2337 entry
->made_contact
= 1;
2338 first_contact
= changed
= 1;
2340 } else { /* ! succeeded */
2341 if (!entry
->made_contact
) {
2342 /* We've never connected to this one. */
2344 "Connection to never-contacted entry guard '%s' (%s) failed. "
2345 "Removing from the list. %d/%d entry guards usable/new.",
2346 entry
->nickname
, buf
,
2347 num_live_entry_guards()-1, smartlist_len(entry_guards
)-1);
2348 entry_guard_free(entry
);
2349 smartlist_del_keeporder(entry_guards
, idx
);
2350 log_entry_guards(LOG_INFO
);
2352 } else if (!entry
->unreachable_since
) {
2353 log_info(LD_CIRC
, "Unable to connect to entry guard '%s' (%s). "
2354 "Marking as unreachable.", entry
->nickname
, buf
);
2355 entry
->unreachable_since
= entry
->last_attempted
= now
;
2356 control_event_guard(entry
->nickname
, entry
->identity
, "DOWN");
2358 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2360 char tbuf
[ISO_TIME_LEN
+1];
2361 format_iso_time(tbuf
, entry
->unreachable_since
);
2362 log_debug(LD_CIRC
, "Failed to connect to unreachable entry guard "
2363 "'%s' (%s). It has been unreachable since %s.",
2364 entry
->nickname
, buf
, tbuf
);
2365 entry
->last_attempted
= now
;
2366 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2370 if (first_contact
) {
2371 /* We've just added a new long-term entry guard. Perhaps the network just
2372 * came back? We should give our earlier entries another try too,
2373 * and close this connection so we don't use it before we've given
2374 * the others a shot. */
2375 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2378 if (e
->made_contact
) {
2379 routerinfo_t
*r
= entry_is_live(e
, 0, 1, 1);
2380 if (r
&& e
->unreachable_since
) {
2388 "Connected to new entry guard '%s' (%s). Marking earlier "
2389 "entry guards up. %d/%d entry guards usable/new.",
2390 entry
->nickname
, buf
,
2391 num_live_entry_guards(), smartlist_len(entry_guards
));
2392 log_entry_guards(LOG_INFO
);
2398 entry_guards_changed();
2399 return refuse_conn
? -1 : 0;
2402 /** When we try to choose an entry guard, should we parse and add
2403 * config's EntryNodes first? */
2404 static int should_add_entry_nodes
= 0;
2406 /** Called when the value of EntryNodes changes in our configuration. */
2408 entry_nodes_should_be_added(void)
2410 log_info(LD_CIRC
, "New EntryNodes config option detected. Will use.");
2411 should_add_entry_nodes
= 1;
2414 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2415 * of guard nodes, at the front. */
2417 entry_guards_prepend_from_config(void)
2419 or_options_t
*options
= get_options();
2420 smartlist_t
*entry_routers
, *entry_fps
;
2421 smartlist_t
*old_entry_guards_on_list
, *old_entry_guards_not_on_list
;
2422 tor_assert(entry_guards
);
2424 should_add_entry_nodes
= 0;
2426 if (!options
->EntryNodes
) {
2427 /* It's possible that a controller set EntryNodes, thus making
2428 * should_add_entry_nodes set, then cleared it again, all before the
2429 * call to choose_random_entry() that triggered us. If so, just return.
2434 if (options
->EntryNodes
) {
2435 char *string
= routerset_to_string(options
->EntryNodes
);
2436 log_info(LD_CIRC
,"Adding configured EntryNodes '%s'.", string
);
2440 entry_routers
= smartlist_create();
2441 entry_fps
= smartlist_create();
2442 old_entry_guards_on_list
= smartlist_create();
2443 old_entry_guards_not_on_list
= smartlist_create();
2445 /* Split entry guards into those on the list and those not. */
2446 /* XXXX021 Now that we allow countries and IP ranges in EntryNodes, this is
2447 * potentially an enormous list. For now, we disable such values for
2448 * EntryNodes in options_validate(); really, this wants a better solution.
2450 routerset_get_all_routers(entry_routers
, options
->EntryNodes
, 0);
2451 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
,
2452 smartlist_add(entry_fps
,ri
->cache_info
.identity_digest
));
2453 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2454 if (smartlist_digest_isin(entry_fps
, e
->identity
))
2455 smartlist_add(old_entry_guards_on_list
, e
);
2457 smartlist_add(old_entry_guards_not_on_list
, e
);
2460 /* Remove all currently configured entry guards from entry_routers. */
2461 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2462 if (is_an_entry_guard(ri
->cache_info
.identity_digest
)) {
2463 SMARTLIST_DEL_CURRENT(entry_routers
, ri
);
2467 /* Now build the new entry_guards list. */
2468 smartlist_clear(entry_guards
);
2469 /* First, the previously configured guards that are in EntryNodes. */
2470 smartlist_add_all(entry_guards
, old_entry_guards_on_list
);
2471 /* Next, the rest of EntryNodes */
2472 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2473 add_an_entry_guard(ri
, 0);
2475 /* Finally, the remaining EntryNodes, unless we're strict */
2476 if (options
->StrictEntryNodes
) {
2477 SMARTLIST_FOREACH(old_entry_guards_not_on_list
, entry_guard_t
*, e
,
2478 entry_guard_free(e
));
2480 smartlist_add_all(entry_guards
, old_entry_guards_not_on_list
);
2483 smartlist_free(entry_routers
);
2484 smartlist_free(entry_fps
);
2485 smartlist_free(old_entry_guards_on_list
);
2486 smartlist_free(old_entry_guards_not_on_list
);
2487 entry_guards_changed();
2490 /** Return 1 if we're fine adding arbitrary routers out of the
2491 * directory to our entry guard list. Else return 0. */
2493 entry_list_can_grow(or_options_t
*options
)
2495 if (options
->StrictEntryNodes
)
2497 if (options
->UseBridges
)
2502 /** Pick a live (up and listed) entry guard from entry_guards. If
2503 * <b>state</b> is non-NULL, this is for a specific circuit --
2504 * make sure not to pick this circuit's exit or any node in the
2505 * exit's family. If <b>state</b> is NULL, we're looking for a random
2506 * guard (likely a bridge). */
2508 choose_random_entry(cpath_build_state_t
*state
)
2510 or_options_t
*options
= get_options();
2511 smartlist_t
*live_entry_guards
= smartlist_create();
2512 smartlist_t
*exit_family
= smartlist_create();
2513 routerinfo_t
*chosen_exit
= state
?build_state_get_exit_router(state
) : NULL
;
2514 routerinfo_t
*r
= NULL
;
2515 int need_uptime
= state
? state
->need_uptime
: 0;
2516 int need_capacity
= state
? state
->need_capacity
: 0;
2517 int consider_exit_family
= 0;
2520 smartlist_add(exit_family
, chosen_exit
);
2521 routerlist_add_family(exit_family
, chosen_exit
);
2522 consider_exit_family
= 1;
2526 entry_guards
= smartlist_create();
2528 if (should_add_entry_nodes
)
2529 entry_guards_prepend_from_config();
2531 if (entry_list_can_grow(options
) &&
2533 smartlist_len(entry_guards
) < options
->NumEntryGuards
))
2534 pick_entry_guards();
2537 smartlist_clear(live_entry_guards
);
2538 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2540 r
= entry_is_live(entry
, need_uptime
, need_capacity
, 0);
2541 if (r
&& (!consider_exit_family
|| !smartlist_isin(exit_family
, r
))) {
2542 smartlist_add(live_entry_guards
, r
);
2543 if (!entry
->made_contact
) {
2544 /* Always start with the first not-yet-contacted entry
2545 * guard. Otherwise we might add several new ones, pick
2546 * the second new one, and now we've expanded our entry
2547 * guard list without needing to. */
2548 goto choose_and_finish
;
2550 if (smartlist_len(live_entry_guards
) >= options
->NumEntryGuards
)
2551 break; /* we have enough */
2555 /* Try to have at least 2 choices available. This way we don't
2556 * get stuck with a single live-but-crummy entry and just keep
2558 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2559 if (smartlist_len(live_entry_guards
) < 2) {
2560 if (entry_list_can_grow(options
)) {
2561 /* still no? try adding a new entry then */
2562 /* XXX if guard doesn't imply fast and stable, then we need
2563 * to tell add_an_entry_guard below what we want, or it might
2564 * be a long time til we get it. -RD */
2565 r
= add_an_entry_guard(NULL
, 0);
2567 entry_guards_changed();
2568 /* XXX we start over here in case the new node we added shares
2569 * a family with our exit node. There's a chance that we'll just
2570 * load up on entry guards here, if the network we're using is
2571 * one big family. Perhaps we should teach add_an_entry_guard()
2572 * to understand nodes-to-avoid-if-possible? -RD */
2576 if (!r
&& need_uptime
) {
2577 need_uptime
= 0; /* try without that requirement */
2580 if (!r
&& need_capacity
) {
2581 /* still no? last attempt, try without requiring capacity */
2585 if (!r
&& !entry_list_can_grow(options
) && consider_exit_family
) {
2586 /* still no? if we're using bridges or have strictentrynodes
2587 * set, and our chosen exit is in the same family as all our
2588 * bridges/entry guards, then be flexible about families. */
2589 consider_exit_family
= 0;
2592 /* live_entry_guards may be empty below. Oh well, we tried. */
2596 if (entry_list_can_grow(options
)) {
2597 /* We choose uniformly at random here, because choose_good_entry_server()
2598 * already weights its choices by bandwidth, so we don't want to
2599 * *double*-weight our guard selection. */
2600 r
= smartlist_choose(live_entry_guards
);
2602 /* We need to weight by bandwidth, because our bridges or entryguards
2603 * were not already selected proportional to their bandwidth. */
2604 r
= routerlist_sl_choose_by_bandwidth(live_entry_guards
, WEIGHT_FOR_GUARD
);
2606 smartlist_free(live_entry_guards
);
2607 smartlist_free(exit_family
);
2611 /** Helper: Return the start of the month containing <b>time</b>. */
2613 start_of_month(time_t now
)
2616 tor_gmtime_r(&now
, &tm
);
2621 return tor_timegm(&tm
);
2624 /** Parse <b>state</b> and learn about the entry guards it describes.
2625 * If <b>set</b> is true, and there are no errors, replace the global
2626 * entry_list with what we find.
2627 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2628 * describing the error, and return -1.
2631 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
2633 entry_guard_t
*node
= NULL
;
2634 smartlist_t
*new_entry_guards
= smartlist_create();
2635 config_line_t
*line
;
2636 time_t now
= time(NULL
);
2637 const char *state_version
= state
->TorVersion
;
2638 digestmap_t
*added_by
= digestmap_new();
2641 for (line
= state
->EntryGuards
; line
; line
= line
->next
) {
2642 if (!strcasecmp(line
->key
, "EntryGuard")) {
2643 smartlist_t
*args
= smartlist_create();
2644 node
= tor_malloc_zero(sizeof(entry_guard_t
));
2645 /* all entry guards on disk have been contacted */
2646 node
->made_contact
= 1;
2647 smartlist_add(new_entry_guards
, node
);
2648 smartlist_split_string(args
, line
->value
, " ",
2649 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2650 if (smartlist_len(args
)<2) {
2651 *msg
= tor_strdup("Unable to parse entry nodes: "
2652 "Too few arguments to EntryGuard");
2653 } else if (!is_legal_nickname(smartlist_get(args
,0))) {
2654 *msg
= tor_strdup("Unable to parse entry nodes: "
2655 "Bad nickname for EntryGuard");
2657 strlcpy(node
->nickname
, smartlist_get(args
,0), MAX_NICKNAME_LEN
+1);
2658 if (base16_decode(node
->identity
, DIGEST_LEN
, smartlist_get(args
,1),
2659 strlen(smartlist_get(args
,1)))<0) {
2660 *msg
= tor_strdup("Unable to parse entry nodes: "
2661 "Bad hex digest for EntryGuard");
2664 SMARTLIST_FOREACH(args
, char*, cp
, tor_free(cp
));
2665 smartlist_free(args
);
2668 } else if (!strcasecmp(line
->key
, "EntryGuardDownSince") ||
2669 !strcasecmp(line
->key
, "EntryGuardUnlistedSince")) {
2671 time_t last_try
= 0;
2673 *msg
= tor_strdup("Unable to parse entry nodes: "
2674 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2677 if (parse_iso_time(line
->value
, &when
)<0) {
2678 *msg
= tor_strdup("Unable to parse entry nodes: "
2679 "Bad time in EntryGuardDownSince/UnlistedSince");
2683 /* It's a bad idea to believe info in the future: you can wind
2684 * up with timeouts that aren't allowed to happen for years. */
2687 if (strlen(line
->value
) >= ISO_TIME_LEN
+ISO_TIME_LEN
+1) {
2688 /* ignore failure */
2689 (void) parse_iso_time(line
->value
+ISO_TIME_LEN
+1, &last_try
);
2691 if (!strcasecmp(line
->key
, "EntryGuardDownSince")) {
2692 node
->unreachable_since
= when
;
2693 node
->last_attempted
= last_try
;
2695 node
->bad_since
= when
;
2697 } else if (!strcasecmp(line
->key
, "EntryGuardAddedBy")) {
2699 /* format is digest version date */
2700 if (strlen(line
->value
) < HEX_DIGEST_LEN
+1+1+1+ISO_TIME_LEN
) {
2701 log_warn(LD_BUG
, "EntryGuardAddedBy line is not long enough.");
2704 if (base16_decode(d
, sizeof(d
), line
->value
, HEX_DIGEST_LEN
)<0 ||
2705 line
->value
[HEX_DIGEST_LEN
] != ' ') {
2706 log_warn(LD_BUG
, "EntryGuardAddedBy line %s does not begin with "
2707 "hex digest", escaped(line
->value
));
2710 digestmap_set(added_by
, d
, tor_strdup(line
->value
+HEX_DIGEST_LEN
+1));
2712 log_warn(LD_BUG
, "Unexpected key %s", line
->key
);
2716 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2719 char *val
= digestmap_get(added_by
, e
->identity
);
2720 if (val
&& (sp
= strchr(val
, ' '))) {
2723 if (parse_iso_time(sp
, &when
)<0) {
2724 log_warn(LD_BUG
, "Can't read time %s in EntryGuardAddedBy", sp
);
2726 e
->chosen_by_version
= tor_strdup(val
);
2727 e
->chosen_on_date
= when
;
2730 if (state_version
) {
2731 e
->chosen_by_version
= tor_strdup(state_version
);
2732 e
->chosen_on_date
= start_of_month(time(NULL
));
2738 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2739 entry_guard_free(e
));
2740 smartlist_free(new_entry_guards
);
2741 } else { /* !*err && set */
2743 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2744 entry_guard_free(e
));
2745 smartlist_free(entry_guards
);
2747 entry_guards
= new_entry_guards
;
2748 entry_guards_dirty
= 0;
2749 if (remove_obsolete_entry_guards())
2750 entry_guards_dirty
= 1;
2752 digestmap_free(added_by
, _tor_free
);
2753 return *msg
? -1 : 0;
2756 /** Our list of entry guards has changed, or some element of one
2757 * of our entry guards has changed. Write the changes to disk within
2758 * the next few minutes.
2761 entry_guards_changed(void)
2764 entry_guards_dirty
= 1;
2766 /* or_state_save() will call entry_guards_update_state(). */
2767 when
= get_options()->AvoidDiskWrites
? time(NULL
) + 3600 : time(NULL
)+600;
2768 or_state_mark_dirty(get_or_state(), when
);
2771 /** If the entry guard info has not changed, do nothing and return.
2772 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2773 * a new one out of the global entry_guards list, and then mark
2774 * <b>state</b> dirty so it will get saved to disk.
2777 entry_guards_update_state(or_state_t
*state
)
2779 config_line_t
**next
, *line
;
2780 if (! entry_guards_dirty
)
2783 config_free_lines(state
->EntryGuards
);
2784 next
= &state
->EntryGuards
;
2787 entry_guards
= smartlist_create();
2788 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2790 char dbuf
[HEX_DIGEST_LEN
+1];
2791 if (!e
->made_contact
)
2792 continue; /* don't write this one to disk */
2793 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2794 line
->key
= tor_strdup("EntryGuard");
2795 line
->value
= tor_malloc(HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2);
2796 base16_encode(dbuf
, sizeof(dbuf
), e
->identity
, DIGEST_LEN
);
2797 tor_snprintf(line
->value
,HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2,
2798 "%s %s", e
->nickname
, dbuf
);
2799 next
= &(line
->next
);
2800 if (e
->unreachable_since
) {
2801 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2802 line
->key
= tor_strdup("EntryGuardDownSince");
2803 line
->value
= tor_malloc(ISO_TIME_LEN
+1+ISO_TIME_LEN
+1);
2804 format_iso_time(line
->value
, e
->unreachable_since
);
2805 if (e
->last_attempted
) {
2806 line
->value
[ISO_TIME_LEN
] = ' ';
2807 format_iso_time(line
->value
+ISO_TIME_LEN
+1, e
->last_attempted
);
2809 next
= &(line
->next
);
2812 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2813 line
->key
= tor_strdup("EntryGuardUnlistedSince");
2814 line
->value
= tor_malloc(ISO_TIME_LEN
+1);
2815 format_iso_time(line
->value
, e
->bad_since
);
2816 next
= &(line
->next
);
2818 if (e
->chosen_on_date
&& e
->chosen_by_version
&&
2819 !strchr(e
->chosen_by_version
, ' ')) {
2820 char d
[HEX_DIGEST_LEN
+1];
2821 char t
[ISO_TIME_LEN
+1];
2823 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2824 line
->key
= tor_strdup("EntryGuardAddedBy");
2825 val_len
= (HEX_DIGEST_LEN
+1+strlen(e
->chosen_by_version
)
2827 line
->value
= tor_malloc(val_len
);
2828 base16_encode(d
, sizeof(d
), e
->identity
, DIGEST_LEN
);
2829 format_iso_time(t
, e
->chosen_on_date
);
2830 tor_snprintf(line
->value
, val_len
, "%s %s %s",
2831 d
, e
->chosen_by_version
, t
);
2832 next
= &(line
->next
);
2835 if (!get_options()->AvoidDiskWrites
)
2836 or_state_mark_dirty(get_or_state(), 0);
2837 entry_guards_dirty
= 0;
2840 /** If <b>question</b> is the string "entry-guards", then dump
2841 * to *<b>answer</b> a newly allocated string describing all of
2842 * the nodes in the global entry_guards list. See control-spec.txt
2844 * For backward compatibility, we also handle the string "helper-nodes".
2847 getinfo_helper_entry_guards(control_connection_t
*conn
,
2848 const char *question
, char **answer
)
2850 int use_long_names
= conn
->use_long_names
;
2852 if (!strcmp(question
,"entry-guards") ||
2853 !strcmp(question
,"helper-nodes")) {
2854 smartlist_t
*sl
= smartlist_create();
2855 char tbuf
[ISO_TIME_LEN
+1];
2856 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
2858 entry_guards
= smartlist_create();
2859 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2861 size_t len
= MAX_VERBOSE_NICKNAME_LEN
+ISO_TIME_LEN
+32;
2862 char *c
= tor_malloc(len
);
2863 const char *status
= NULL
;
2865 if (!e
->made_contact
) {
2866 status
= "never-connected";
2867 } else if (e
->bad_since
) {
2868 when
= e
->bad_since
;
2869 status
= "unusable";
2873 if (use_long_names
) {
2874 routerinfo_t
*ri
= router_get_by_digest(e
->identity
);
2876 router_get_verbose_nickname(nbuf
, ri
);
2879 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
2880 /* e->nickname field is not very reliable if we don't know about
2881 * this router any longer; don't include it. */
2884 base16_encode(nbuf
, sizeof(nbuf
), e
->identity
, DIGEST_LEN
);
2887 format_iso_time(tbuf
, when
);
2888 tor_snprintf(c
, len
, "%s %s %s\n", nbuf
, status
, tbuf
);
2890 tor_snprintf(c
, len
, "%s %s\n", nbuf
, status
);
2892 smartlist_add(sl
, c
);
2894 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2895 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2901 /** Information about a configured bridge. Currently this just matches the
2902 * ones in the torrc file, but one day we may be able to learn about new
2903 * bridges on our own, and remember them in the state file. */
2905 /** Address of the bridge. */
2907 /** TLS port for the bridge. */
2909 /** Expected identity digest, or all \0's if we don't know what the
2910 * digest should be. */
2911 char identity
[DIGEST_LEN
];
2912 /** When should we next try to fetch a descriptor for this bridge? */
2913 download_status_t fetch_status
;
2916 /** A list of configured bridges. Whenever we actually get a descriptor
2917 * for one, we add it as an entry guard. */
2918 static smartlist_t
*bridge_list
= NULL
;
2920 /** Initialize the bridge list to empty, creating it if needed. */
2922 clear_bridge_list(void)
2925 bridge_list
= smartlist_create();
2926 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, b
, tor_free(b
));
2927 smartlist_clear(bridge_list
);
2930 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2931 * (either by comparing keys if possible, else by comparing addr/port).
2932 * Else return NULL. */
2933 static bridge_info_t
*
2934 routerinfo_get_configured_bridge(routerinfo_t
*ri
)
2938 SMARTLIST_FOREACH_BEGIN(bridge_list
, bridge_info_t
*, bridge
)
2940 if (tor_digest_is_zero(bridge
->identity
) &&
2941 tor_addr_eq_ipv4h(&bridge
->addr
, ri
->addr
) &&
2942 bridge
->port
== ri
->or_port
)
2944 if (!memcmp(bridge
->identity
, ri
->cache_info
.identity_digest
,
2948 SMARTLIST_FOREACH_END(bridge
);
2952 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
2954 routerinfo_is_a_configured_bridge(routerinfo_t
*ri
)
2956 return routerinfo_get_configured_bridge(ri
) ? 1 : 0;
2959 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2960 * is set, it tells us the identity key too. */
2962 bridge_add_from_config(const tor_addr_t
*addr
, uint16_t port
, char *digest
)
2964 bridge_info_t
*b
= tor_malloc_zero(sizeof(bridge_info_t
));
2965 tor_addr_copy(&b
->addr
, addr
);
2968 memcpy(b
->identity
, digest
, DIGEST_LEN
);
2970 bridge_list
= smartlist_create();
2971 smartlist_add(bridge_list
, b
);
2974 /** Schedule the next fetch for <b>bridge</b>, based on
2975 * some retry schedule. */
2977 bridge_fetch_status_increment(bridge_info_t
*bridge
, time_t now
)
2979 switch (bridge
->fetch_status
.n_download_failures
) {
2980 case 0: bridge
->fetch_status
.next_attempt_at
= now
+60*15; break;
2981 case 1: bridge
->fetch_status
.next_attempt_at
= now
+60*15; break;
2982 default: bridge
->fetch_status
.next_attempt_at
= now
+60*60; break;
2984 if (bridge
->fetch_status
.n_download_failures
< 10)
2985 bridge
->fetch_status
.n_download_failures
++;
2988 /** We just got a new descriptor for <b>bridge</b>. Reschedule the
2989 * next fetch for a long time from <b>now</b>. */
2991 bridge_fetch_status_arrived(bridge_info_t
*bridge
, time_t now
)
2994 bridge
->fetch_status
.next_attempt_at
= now
+60*60;
2995 bridge
->fetch_status
.n_download_failures
= 0;
2998 /** If <b>digest</b> is one of our known bridges, return it. */
2999 static bridge_info_t
*
3000 find_bridge_by_digest(const char *digest
)
3002 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
3004 if (!memcmp(bridge
->identity
, digest
, DIGEST_LEN
))
3010 /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
3011 * is a helpful string describing this bridge. */
3013 launch_direct_bridge_descriptor_fetch(bridge_info_t
*bridge
)
3017 if (connection_get_by_type_addr_port_purpose(
3018 CONN_TYPE_DIR
, &bridge
->addr
, bridge
->port
,
3019 DIR_PURPOSE_FETCH_SERVERDESC
))
3020 return; /* it's already on the way */
3022 address
= tor_dup_addr(&bridge
->addr
);
3023 directory_initiate_command(address
, &bridge
->addr
,
3025 0, /* does not matter */
3026 1, bridge
->identity
,
3027 DIR_PURPOSE_FETCH_SERVERDESC
,
3028 ROUTER_PURPOSE_BRIDGE
,
3029 0, "authority.z", NULL
, 0, 0);
3033 /** Fetching the bridge descriptor from the bridge authority returned a
3034 * "not found". Fall back to trying a direct fetch. */
3036 retry_bridge_descriptor_fetch_directly(const char *digest
)
3038 bridge_info_t
*bridge
= find_bridge_by_digest(digest
);
3040 return; /* not found? oh well. */
3042 launch_direct_bridge_descriptor_fetch(bridge
);
3045 /** For each bridge in our list for which we don't currently have a
3046 * descriptor, fetch a new copy of its descriptor -- either directly
3047 * from the bridge or via a bridge authority. */
3049 fetch_bridge_descriptors(time_t now
)
3051 or_options_t
*options
= get_options();
3052 int num_bridge_auths
= get_n_authorities(BRIDGE_AUTHORITY
);
3053 int ask_bridge_directly
;
3054 int can_use_bridge_authority
;
3059 SMARTLIST_FOREACH_BEGIN(bridge_list
, bridge_info_t
*, bridge
)
3061 if (bridge
->fetch_status
.next_attempt_at
> now
)
3062 continue; /* don't bother, no need to retry yet */
3064 /* schedule another fetch as if this one will fail, in case it does */
3065 bridge_fetch_status_increment(bridge
, now
);
3067 can_use_bridge_authority
= !tor_digest_is_zero(bridge
->identity
) &&
3069 ask_bridge_directly
= !can_use_bridge_authority
||
3070 !options
->UpdateBridgesFromAuthority
;
3071 log_debug(LD_DIR
, "ask_bridge_directly=%d (%d, %d, %d)",
3072 ask_bridge_directly
, tor_digest_is_zero(bridge
->identity
),
3073 !options
->UpdateBridgesFromAuthority
, !num_bridge_auths
);
3075 if (ask_bridge_directly
&&
3076 !fascist_firewall_allows_address_or(&bridge
->addr
, bridge
->port
)) {
3077 log_notice(LD_DIR
, "Bridge at '%s:%d' isn't reachable by our "
3078 "firewall policy. %s.", fmt_addr(&bridge
->addr
),
3080 can_use_bridge_authority
?
3081 "Asking bridge authority instead" : "Skipping");
3082 if (can_use_bridge_authority
)
3083 ask_bridge_directly
= 0;
3088 if (ask_bridge_directly
) {
3089 /* we need to ask the bridge itself for its descriptor. */
3090 launch_direct_bridge_descriptor_fetch(bridge
);
3092 /* We have a digest and we want to ask an authority. We could
3093 * combine all the requests into one, but that may give more
3094 * hints to the bridge authority than we want to give. */
3095 char resource
[10 + HEX_DIGEST_LEN
];
3096 memcpy(resource
, "fp/", 3);
3097 base16_encode(resource
+3, HEX_DIGEST_LEN
+1,
3098 bridge
->identity
, DIGEST_LEN
);
3099 memcpy(resource
+3+HEX_DIGEST_LEN
, ".z", 3);
3100 log_info(LD_DIR
, "Fetching bridge info '%s' from bridge authority.",
3102 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
3103 ROUTER_PURPOSE_BRIDGE
, resource
, 0);
3106 SMARTLIST_FOREACH_END(bridge
);
3109 /** We just learned a descriptor for a bridge. See if that
3110 * digest is in our entry guard list, and add it if not. */
3112 learned_bridge_descriptor(routerinfo_t
*ri
, int from_cache
)
3115 tor_assert(ri
->purpose
== ROUTER_PURPOSE_BRIDGE
);
3116 if (get_options()->UseBridges
) {
3117 int first
= !any_bridge_descriptors_known();
3118 bridge_info_t
*bridge
= routerinfo_get_configured_bridge(ri
);
3119 time_t now
= time(NULL
);
3122 if (bridge
) { /* if we actually want to use this one */
3123 /* it's here; schedule its re-fetch for a long time from now. */
3125 bridge_fetch_status_arrived(bridge
, now
);
3127 add_an_entry_guard(ri
, 1);
3128 log_notice(LD_DIR
, "new bridge descriptor '%s' (%s)", ri
->nickname
,
3129 from_cache
? "cached" : "fresh");
3131 routerlist_retry_directory_downloads(now
);
3136 /** Return 1 if any of our entry guards have descriptors that
3137 * are marked with purpose 'bridge' and are running. Else return 0.
3139 * We use this function to decide if we're ready to start building
3140 * circuits through our bridges, or if we need to wait until the
3141 * directory "server/authority" requests finish. */
3143 any_bridge_descriptors_known(void)
3145 tor_assert(get_options()->UseBridges
);
3146 return choose_random_entry(NULL
)!=NULL
? 1 : 0;
3149 /** Return 1 if there are any directory conns fetching bridge descriptors
3150 * that aren't marked for close. We use this to guess if we should tell
3151 * the controller that we have a problem. */
3153 any_pending_bridge_descriptor_fetches(void)
3155 smartlist_t
*conns
= get_connection_array();
3156 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3158 if (conn
->type
== CONN_TYPE_DIR
&&
3159 conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
3160 TO_DIR_CONN(conn
)->router_purpose
== ROUTER_PURPOSE_BRIDGE
&&
3161 !conn
->marked_for_close
&&
3162 conn
->linked
&& !conn
->linked_conn
->marked_for_close
) {
3163 log_debug(LD_DIR
, "found one: %s", conn
->address
);
3170 /** Return 1 if we have at least one descriptor for a bridge and
3171 * all descriptors we know are down. Else return 0. If <b>act</b> is
3172 * 1, then mark the down bridges up; else just observe and report. */
3174 bridges_retry_helper(int act
)
3178 int any_running
= 0;
3180 entry_guards
= smartlist_create();
3181 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3183 ri
= router_get_by_digest(e
->identity
);
3184 if (ri
&& ri
->purpose
== ROUTER_PURPOSE_BRIDGE
) {
3187 any_running
= 1; /* some bridge is both known and running */
3188 else if (act
) { /* mark it for retry */
3195 return any_known
&& !any_running
;
3198 /** Do we know any descriptors for our bridges, and are they all
3201 bridges_known_but_down(void)
3203 return bridges_retry_helper(0);
3206 /** Mark all down known bridges up. */
3208 bridges_retry_all(void)
3210 bridges_retry_helper(1);
3213 /** Release all storage held by the list of entry guards and related
3214 * memory structs. */
3216 entry_guards_free_all(void)
3219 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3220 entry_guard_free(e
));
3221 smartlist_free(entry_guards
);
3222 entry_guards
= NULL
;
3224 clear_bridge_list();
3225 smartlist_free(bridge_list
);