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-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief The actual details of building circuits.
14 /********* START VARIABLES **********/
16 /** A global list of all circuits at this hop. */
17 extern circuit_t
*global_circuitlist
;
19 /** An entry_guard_t represents our information about a chosen long-term
20 * first hop, known as a "helper" node in the literature. We can't just
21 * use a routerinfo_t, since we want to remember these even when we
22 * don't have a directory. */
24 char nickname
[MAX_NICKNAME_LEN
+1];
25 char identity
[DIGEST_LEN
];
26 time_t chosen_on_date
; /**< Approximately when was this guard added?
27 * "0" if we don't know. */
28 char *chosen_by_version
; /**< What tor version added this guard? NULL
29 * if we don't know. */
30 unsigned int made_contact
: 1; /**< 0 if we have never connected to this
31 * router, 1 if we have. */
32 unsigned int can_retry
: 1; /**< Should we retry connecting to this entry,
33 * in spite of having it marked as unreachable?*/
34 time_t bad_since
; /**< 0 if this guard is currently usable, or the time at
35 * which it was observed to become (according to the
36 * directory or the user configuration) unusable. */
37 time_t unreachable_since
; /**< 0 if we can connect to this guard, or the
38 * time at which we first noticed we couldn't
40 time_t last_attempted
; /**< 0 if we can connect to this guard, or the time
41 * at which we last failed to connect to it. */
44 /** A list of our chosen entry guards. */
45 static smartlist_t
*entry_guards
= NULL
;
46 /** A value of 1 means that the entry_guards list has changed
47 * and those changes need to be flushed to disk. */
48 static int entry_guards_dirty
= 0;
50 /********* END VARIABLES ************/
52 static int circuit_deliver_create_cell(circuit_t
*circ
,
53 uint8_t cell_type
, const char *payload
);
54 static int onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
);
55 static crypt_path_t
*onion_next_hop_in_cpath(crypt_path_t
*cpath
);
56 static int onion_extend_cpath(origin_circuit_t
*circ
);
57 static int count_acceptable_routers(smartlist_t
*routers
);
58 static int onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
);
60 static void entry_guards_changed(void);
62 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
63 * and with the high bit specified by conn-\>circ_id_type, until we get
64 * a circ_id that is not in use by any other circuit on that conn.
66 * Return it, or 0 if can't get a unique circ_id.
69 get_unique_circ_id_by_conn(or_connection_t
*conn
)
71 circid_t test_circ_id
;
76 if (conn
->circ_id_type
== CIRC_ID_TYPE_NEITHER
) {
77 log_warn(LD_BUG
, "Trying to pick a circuit ID for a connection from "
78 "a client with no identity.");
81 high_bit
= (conn
->circ_id_type
== CIRC_ID_TYPE_HIGHER
) ? 1<<15 : 0;
83 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
84 * circID such that (high_bit|test_circ_id) is not already used. */
85 test_circ_id
= conn
->next_circ_id
++;
86 if (test_circ_id
== 0 || test_circ_id
>= 1<<15) {
88 conn
->next_circ_id
= 2;
90 if (++attempts
> 1<<15) {
91 /* Make sure we don't loop forever if all circ_id's are used. This
92 * matters because it's an external DoS opportunity.
94 log_warn(LD_CIRC
,"No unused circ IDs. Failing.");
97 test_circ_id
|= high_bit
;
98 } while (circuit_id_in_use_on_orconn(test_circ_id
, conn
));
102 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
103 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
104 * list information about link status in a more verbose format using spaces.
105 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
106 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
110 circuit_list_path_impl(origin_circuit_t
*circ
, int verbose
, int verbose_names
)
113 smartlist_t
*elements
;
114 const char *states
[] = {"closed", "waiting for keys", "open"};
118 elements
= smartlist_create();
121 const char *nickname
= build_state_get_exit_nickname(circ
->build_state
);
122 tor_snprintf(buf
, sizeof(buf
), "%s%s circ (length %d%s%s):",
123 circ
->build_state
->is_internal
? "internal" : "exit",
124 circ
->build_state
->need_uptime
? " (high-uptime)" : "",
125 circ
->build_state
->desired_path_len
,
126 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" : ", exit ",
127 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" :
128 (nickname
?nickname
:"*unnamed*"));
129 smartlist_add(elements
, tor_strdup(buf
));
140 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
142 if (!hop
->extend_info
)
144 id
= hop
->extend_info
->identity_digest
;
146 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
147 if ((ri
= router_get_by_digest(id
))) {
148 router_get_verbose_nickname(elt
, ri
);
149 } else if ((rs
= router_get_consensus_status_by_id(id
))) {
150 routerstatus_get_verbose_nickname(elt
, rs
);
151 } else if (hop
->extend_info
->nickname
&&
152 is_legal_nickname(hop
->extend_info
->nickname
)) {
154 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, 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, id
, DIGEST_LEN
);
162 } else { /* ! verbose_names */
163 if ((ri
= router_get_by_digest(id
)) &&
165 elt
= tor_strdup(hop
->extend_info
->nickname
);
167 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
169 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
174 size_t len
= strlen(elt
)+2+strlen(states
[hop
->state
])+1;
175 char *v
= tor_malloc(len
);
176 tor_assert(hop
->state
<= 2);
177 tor_snprintf(v
,len
,"%s(%s)",elt
,states
[hop
->state
]);
178 smartlist_add(elements
, v
);
181 smartlist_add(elements
, elt
);
184 } while (hop
!= circ
->cpath
);
186 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
187 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
188 smartlist_free(elements
);
192 /** If <b>verbose</b> is false, allocate and return a comma-separated
193 * list of the currently built elements of circuit_t. If
194 * <b>verbose</b> is true, also list information about link status in
195 * a more verbose format using spaces.
198 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
200 return circuit_list_path_impl(circ
, verbose
, 0);
203 /** Allocate and return a comma-separated list of the currently built elements
204 * of circuit_t, giving each as a verbose nickname.
207 circuit_list_path_for_controller(origin_circuit_t
*circ
)
209 return circuit_list_path_impl(circ
, 0, 1);
212 /** Log, at severity <b>severity</b>, the nicknames of each router in
213 * circ's cpath. Also log the length of the cpath, and the intended
217 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
219 char *s
= circuit_list_path(circ
,1);
220 log(severity
,domain
,"%s",s
);
224 /** Tell the rep(utation)hist(ory) module about the status of the links
225 * in circ. Hops that have become OPEN are marked as successfully
226 * extended; the _first_ hop that isn't open (if any) is marked as
229 /* XXXX Someday we should learn from OR circuits too. */
231 circuit_rep_hist_note_result(origin_circuit_t
*circ
)
234 char *prev_digest
= NULL
;
235 routerinfo_t
*router
;
237 if (!hop
) /* circuit hasn't started building yet. */
239 if (server_mode(get_options())) {
240 routerinfo_t
*me
= router_get_my_routerinfo();
243 prev_digest
= me
->cache_info
.identity_digest
;
246 router
= router_get_by_digest(hop
->extend_info
->identity_digest
);
249 if (hop
->state
== CPATH_STATE_OPEN
)
250 rep_hist_note_extend_succeeded(prev_digest
,
251 router
->cache_info
.identity_digest
);
253 rep_hist_note_extend_failed(prev_digest
,
254 router
->cache_info
.identity_digest
);
258 prev_digest
= router
->cache_info
.identity_digest
;
263 } while (hop
!=circ
->cpath
);
266 /** Pick all the entries in our cpath. Stop and return 0 when we're
267 * happy, or return -1 if an error occurs. */
269 onion_populate_cpath(origin_circuit_t
*circ
)
273 r
= onion_extend_cpath(circ
);
275 log_info(LD_CIRC
,"Generating cpath hop failed.");
280 return 0; /* if r == 1 */
283 /** Create and return a new origin circuit. Initialize its purpose and
284 * build-state based on our arguments. The <b>flags</b> argument is a
285 * bitfield of CIRCLAUNCH_* flags. */
287 origin_circuit_init(uint8_t purpose
, int flags
)
289 /* sets circ->p_circ_id and circ->p_conn */
290 origin_circuit_t
*circ
= origin_circuit_new();
291 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OR_WAIT
);
292 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
293 circ
->build_state
->onehop_tunnel
=
294 ((flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) ? 1 : 0);
295 circ
->build_state
->need_uptime
=
296 ((flags
& CIRCLAUNCH_NEED_UPTIME
) ? 1 : 0);
297 circ
->build_state
->need_capacity
=
298 ((flags
& CIRCLAUNCH_NEED_CAPACITY
) ? 1 : 0);
299 circ
->build_state
->is_internal
=
300 ((flags
& CIRCLAUNCH_IS_INTERNAL
) ? 1 : 0);
301 circ
->_base
.purpose
= purpose
;
305 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
306 * is defined, then use that as your exit router, else choose a suitable
309 * Also launch a connection to the first OR in the chosen path, if
310 * it's not open already.
313 circuit_establish_circuit(uint8_t purpose
, extend_info_t
*exit
, int flags
)
315 origin_circuit_t
*circ
;
318 circ
= origin_circuit_init(purpose
, flags
);
320 if (onion_pick_cpath_exit(circ
, exit
) < 0 ||
321 onion_populate_cpath(circ
) < 0) {
322 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
326 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
328 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
329 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
335 /** Start establishing the first hop of our circuit. Figure out what
336 * OR we should connect to, and if necessary start the connection to
337 * it. If we're already connected, then send the 'create' cell.
338 * Return 0 for ok, -reason if circ should be marked-for-close. */
340 circuit_handle_first_hop(origin_circuit_t
*circ
)
342 crypt_path_t
*firsthop
;
343 or_connection_t
*n_conn
;
345 const char *msg
= NULL
;
346 int should_launch
= 0;
348 firsthop
= onion_next_hop_in_cpath(circ
->cpath
);
349 tor_assert(firsthop
);
350 tor_assert(firsthop
->extend_info
);
352 /* now see if we're already connected to the first OR in 'route' */
353 log_debug(LD_CIRC
,"Looking for firsthop '%s:%u'",
354 fmt_addr(&firsthop
->extend_info
->addr
),
355 firsthop
->extend_info
->port
);
357 n_conn
= connection_or_get_for_extend(firsthop
->extend_info
->identity_digest
,
358 &firsthop
->extend_info
->addr
,
363 /* not currently connected in a useful way. */
364 const char *name
= firsthop
->extend_info
->nickname
?
365 firsthop
->extend_info
->nickname
: fmt_addr(&firsthop
->extend_info
->addr
);
366 log_info(LD_CIRC
, "Next router is %s: %s ", safe_str(name
), msg
?msg
:"???");
367 circ
->_base
.n_hop
= extend_info_dup(firsthop
->extend_info
);
370 if (circ
->build_state
->onehop_tunnel
)
371 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR
, 0);
372 n_conn
= connection_or_connect(&firsthop
->extend_info
->addr
,
373 firsthop
->extend_info
->port
,
374 firsthop
->extend_info
->identity_digest
);
375 if (!n_conn
) { /* connect failed, forget the whole thing */
376 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
377 return -END_CIRC_REASON_CONNECTFAILED
;
381 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
382 /* return success. The onion/circuit/etc will be taken care of
383 * automatically (may already have been) whenever n_conn reaches
384 * OR_CONN_STATE_OPEN.
387 } else { /* it's already open. use it. */
388 tor_assert(!circ
->_base
.n_hop
);
389 circ
->_base
.n_conn
= n_conn
;
390 log_debug(LD_CIRC
,"Conn open. Delivering first onion skin.");
391 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
392 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
399 /** Find any circuits that are waiting on <b>or_conn</b> to become
400 * open and get them to send their create cells forward.
402 * Status is 1 if connect succeeded, or 0 if connect failed.
405 circuit_n_conn_done(or_connection_t
*or_conn
, int status
)
407 smartlist_t
*pending_circs
;
410 log_debug(LD_CIRC
,"or_conn to %s/%s, status=%d",
411 or_conn
->nickname
? or_conn
->nickname
: "NULL",
412 or_conn
->_base
.address
, status
);
414 pending_circs
= smartlist_create();
415 circuit_get_all_pending_on_or_conn(pending_circs
, or_conn
);
417 SMARTLIST_FOREACH_BEGIN(pending_circs
, circuit_t
*, circ
)
419 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
420 * leaving them in in case it's possible for the status of a circuit to
421 * change as we're going down the list. */
422 if (circ
->marked_for_close
|| circ
->n_conn
|| !circ
->n_hop
||
423 circ
->state
!= CIRCUIT_STATE_OR_WAIT
)
426 if (tor_digest_is_zero(circ
->n_hop
->identity_digest
)) {
427 /* Look at addr/port. This is an unkeyed connection. */
428 if (!tor_addr_eq(&circ
->n_hop
->addr
, &or_conn
->_base
.addr
) ||
429 circ
->n_hop
->port
!= or_conn
->_base
.port
)
432 /* We expected a key. See if it's the right one. */
433 if (memcmp(or_conn
->identity_digest
,
434 circ
->n_hop
->identity_digest
, DIGEST_LEN
))
437 if (!status
) { /* or_conn failed; close circ */
438 log_info(LD_CIRC
,"or_conn failed. Closing circ.");
439 circuit_mark_for_close(circ
, END_CIRC_REASON_OR_CONN_CLOSED
);
442 log_debug(LD_CIRC
, "Found circ, sending create cell.");
443 /* circuit_deliver_create_cell will set n_circ_id and add us to
444 * orconn_circuid_circuit_map, so we don't need to call
445 * set_circid_orconn here. */
446 circ
->n_conn
= or_conn
;
447 extend_info_free(circ
->n_hop
);
450 if (CIRCUIT_IS_ORIGIN(circ
)) {
452 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
454 "send_next_onion_skin failed; circuit marked for closing.");
455 circuit_mark_for_close(circ
, -err_reason
);
457 /* XXX could this be bad, eg if next_onion_skin failed because conn
461 /* pull the create cell out of circ->onionskin, and send it */
462 tor_assert(circ
->n_conn_onionskin
);
463 if (circuit_deliver_create_cell(circ
,CELL_CREATE
,
464 circ
->n_conn_onionskin
)<0) {
465 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
468 tor_free(circ
->n_conn_onionskin
);
469 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
472 SMARTLIST_FOREACH_END(circ
);
474 smartlist_free(pending_circs
);
477 /** Find a new circid that isn't currently in use on the circ->n_conn
479 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
480 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
482 * Return -1 if we failed to find a suitable circid, else return 0.
485 circuit_deliver_create_cell(circuit_t
*circ
, uint8_t cell_type
,
492 tor_assert(circ
->n_conn
);
494 tor_assert(cell_type
== CELL_CREATE
|| cell_type
== CELL_CREATE_FAST
);
496 id
= get_unique_circ_id_by_conn(circ
->n_conn
);
498 log_warn(LD_CIRC
,"failed to get unique circID.");
501 log_debug(LD_CIRC
,"Chosen circID %u.", id
);
502 circuit_set_n_circid_orconn(circ
, id
, circ
->n_conn
);
504 memset(&cell
, 0, sizeof(cell_t
));
505 cell
.command
= cell_type
;
506 cell
.circ_id
= circ
->n_circ_id
;
508 memcpy(cell
.payload
, payload
, ONIONSKIN_CHALLENGE_LEN
);
509 append_cell_to_circuit_queue(circ
, circ
->n_conn
, &cell
, CELL_DIRECTION_OUT
);
511 if (CIRCUIT_IS_ORIGIN(circ
)) {
512 /* mark it so it gets better rate limiting treatment. */
513 circ
->n_conn
->client_used
= time(NULL
);
519 /** We've decided to start our reachability testing. If all
520 * is set, log this to the user. Return 1 if we did, or 0 if
521 * we chose not to log anything. */
523 inform_testing_reachability(void)
526 routerinfo_t
*me
= router_get_my_routerinfo();
529 control_event_server_status(LOG_NOTICE
,
530 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
531 me
->address
, me
->or_port
);
533 tor_snprintf(dirbuf
, sizeof(dirbuf
), " and DirPort %s:%d",
534 me
->address
, me
->dir_port
);
535 control_event_server_status(LOG_NOTICE
,
536 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
537 me
->address
, me
->dir_port
);
539 log(LOG_NOTICE
, LD_OR
, "Now checking whether ORPort %s:%d%s %s reachable... "
540 "(this may take up to %d minutes -- look for log "
541 "messages indicating success)",
542 me
->address
, me
->or_port
,
543 me
->dir_port
? dirbuf
: "",
544 me
->dir_port
? "are" : "is",
545 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
/60);
550 /** Return true iff we should send a create_fast cell to start building a given
553 should_use_create_fast_for_circuit(origin_circuit_t
*circ
)
555 or_options_t
*options
= get_options();
556 tor_assert(circ
->cpath
);
557 tor_assert(circ
->cpath
->extend_info
);
559 if (!circ
->cpath
->extend_info
->onion_key
)
560 return 1; /* our hand is forced: only a create_fast will work. */
561 if (!options
->FastFirstHopPK
)
562 return 0; /* we prefer to avoid create_fast */
563 if (server_mode(options
)) {
564 /* We're a server, and we know an onion key. We can choose.
565 * Prefer to blend in. */
572 /** This is the backbone function for building circuits.
574 * If circ's first hop is closed, then we need to build a create
575 * cell and send it forward.
577 * Otherwise, we need to build a relay extend cell and send it
580 * Return -reason if we want to tear down circ, else return 0.
583 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
586 routerinfo_t
*router
;
587 char payload
[2+4+DIGEST_LEN
+ONIONSKIN_CHALLENGE_LEN
];
593 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
596 log_debug(LD_CIRC
,"First skin; sending create cell.");
597 if (circ
->build_state
->onehop_tunnel
)
598 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE
, 0);
600 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE
, 0);
602 router
= router_get_by_digest(circ
->_base
.n_conn
->identity_digest
);
603 fast
= should_use_create_fast_for_circuit(circ
);
605 /* We are an OR and we know the right onion key: we should
606 * send an old slow create cell.
608 cell_type
= CELL_CREATE
;
609 if (onion_skin_create(circ
->cpath
->extend_info
->onion_key
,
610 &(circ
->cpath
->dh_handshake_state
),
612 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
613 return - END_CIRC_REASON_INTERNAL
;
615 note_request("cell: create", 1);
617 /* We are not an OR, and we're building the first hop of a circuit to a
618 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
619 * and a DH operation. */
620 cell_type
= CELL_CREATE_FAST
;
621 memset(payload
, 0, sizeof(payload
));
622 crypto_rand(circ
->cpath
->fast_handshake_state
,
623 sizeof(circ
->cpath
->fast_handshake_state
));
624 memcpy(payload
, circ
->cpath
->fast_handshake_state
,
625 sizeof(circ
->cpath
->fast_handshake_state
));
626 note_request("cell: create fast", 1);
629 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), cell_type
, payload
) < 0)
630 return - END_CIRC_REASON_RESOURCELIMIT
;
632 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
633 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
634 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
635 fast
? "CREATE_FAST" : "CREATE",
636 router
? router
->nickname
: "<unnamed>");
638 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
639 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_BUILDING
);
640 log_debug(LD_CIRC
,"starting to send subsequent skin.");
641 hop
= onion_next_hop_in_cpath(circ
->cpath
);
643 /* done building the circuit. whew. */
644 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
645 log_info(LD_CIRC
,"circuit built!");
646 circuit_reset_failure_count(0);
647 if (circ
->build_state
->onehop_tunnel
)
648 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS
, 0);
649 if (!has_completed_circuit
&& !circ
->build_state
->onehop_tunnel
) {
650 or_options_t
*options
= get_options();
651 has_completed_circuit
=1;
652 /* FFFF Log a count of known routers here */
653 log(LOG_NOTICE
, LD_GENERAL
,
654 "Tor has successfully opened a circuit. "
655 "Looks like client functionality is working.");
656 control_event_bootstrap(BOOTSTRAP_STATUS_DONE
, 0);
657 control_event_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
658 if (server_mode(options
) && !check_whether_orport_reachable()) {
659 inform_testing_reachability();
660 consider_testing_reachability(1, 1);
663 circuit_rep_hist_note_result(circ
);
664 circuit_has_opened(circ
); /* do other actions as necessary */
668 if (tor_addr_family(&hop
->extend_info
->addr
) != AF_INET
) {
669 log_warn(LD_BUG
, "Trying to extend to a non-IPv4 address.");
670 return - END_CIRC_REASON_INTERNAL
;
673 set_uint32(payload
, tor_addr_to_ipv4n(&hop
->extend_info
->addr
));
674 set_uint16(payload
+4, htons(hop
->extend_info
->port
));
676 onionskin
= payload
+2+4;
677 memcpy(payload
+2+4+ONIONSKIN_CHALLENGE_LEN
,
678 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
679 payload_len
= 2+4+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
;
681 if (onion_skin_create(hop
->extend_info
->onion_key
,
682 &(hop
->dh_handshake_state
), onionskin
) < 0) {
683 log_warn(LD_CIRC
,"onion_skin_create failed.");
684 return - END_CIRC_REASON_INTERNAL
;
687 log_info(LD_CIRC
,"Sending extend relay cell.");
688 note_request("cell: extend", 1);
689 /* send it to hop->prev, because it will transfer
690 * it to a create cell and then send to hop */
691 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
692 RELAY_COMMAND_EXTEND
,
693 payload
, payload_len
, hop
->prev
) < 0)
694 return 0; /* circuit is closed */
696 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
701 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
702 * something has also gone wrong with our network: notify the user,
703 * and abandon all not-yet-used circuits. */
705 circuit_note_clock_jumped(int seconds_elapsed
)
707 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
708 log(severity
, LD_GENERAL
, "Your system clock just jumped %d seconds %s; "
709 "assuming established circuits no longer work.",
710 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
,
711 seconds_elapsed
>=0 ? "forward" : "backward");
712 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%d",
714 has_completed_circuit
=0; /* so it'll log when it works again */
715 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
717 circuit_mark_all_unused_circs();
718 circuit_expire_all_dirty_circs();
721 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
722 * skin and identity digest for the next hop. If we're already connected,
723 * pass the onion skin to the next hop using a create cell; otherwise
724 * launch a new OR connection, and <b>circ</b> will notice when the
725 * connection succeeds or fails.
727 * Return -1 if we want to warn and tear down the circuit, else return 0.
730 circuit_extend(cell_t
*cell
, circuit_t
*circ
)
732 or_connection_t
*n_conn
;
735 char *id_digest
=NULL
;
739 const char *msg
= NULL
;
740 int should_launch
= 0;
743 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
744 "n_conn already set. Bug/attack. Closing.");
748 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
749 "conn to next hop already launched. Bug/attack. Closing.");
753 if (!server_mode(get_options())) {
754 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
755 "Got an extend cell, but running as a client. Closing.");
759 relay_header_unpack(&rh
, cell
->payload
);
761 if (rh
.length
< 4+2+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
) {
762 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
763 "Wrong length %d on extend cell. Closing circuit.",
768 n_addr32
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
769 n_port
= ntohs(get_uint16(cell
->payload
+RELAY_HEADER_SIZE
+4));
770 onionskin
= cell
->payload
+RELAY_HEADER_SIZE
+4+2;
771 id_digest
= cell
->payload
+RELAY_HEADER_SIZE
+4+2+ONIONSKIN_CHALLENGE_LEN
;
772 tor_addr_from_ipv4h(&n_addr
, n_addr32
);
774 if (!n_port
|| !n_addr32
) {
775 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
776 "Client asked me to extend to zero destination port or addr.");
780 /* Check if they asked us for 0000..0000. We support using
781 * an empty fingerprint for the first hop (e.g. for a bridge relay),
782 * but we don't want to let people send us extend cells for empty
783 * fingerprints -- a) because it opens the user up to a mitm attack,
784 * and b) because it lets an attacker force the relay to hold open a
785 * new TLS connection for each extend request. */
786 if (tor_digest_is_zero(id_digest
)) {
787 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
788 "Client asked me to extend without specifying an id_digest.");
792 /* Next, check if we're being asked to connect to the hop that the
793 * extend cell came from. There isn't any reason for that, and it can
794 * assist circular-path attacks. */
795 if (!memcmp(id_digest
, TO_OR_CIRCUIT(circ
)->p_conn
->identity_digest
,
797 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
798 "Client asked me to extend back to the previous hop.");
802 n_conn
= connection_or_get_for_extend(id_digest
,
808 log_debug(LD_CIRC
|LD_OR
,"Next router (%s:%d): %s",
809 fmt_addr(&n_addr
), (int)n_port
, msg
?msg
:"????");
811 circ
->n_hop
= extend_info_alloc(NULL
/*nickname*/,
816 circ
->n_conn_onionskin
= tor_malloc(ONIONSKIN_CHALLENGE_LEN
);
817 memcpy(circ
->n_conn_onionskin
, onionskin
, ONIONSKIN_CHALLENGE_LEN
);
818 circuit_set_state(circ
, CIRCUIT_STATE_OR_WAIT
);
821 /* we should try to open a connection */
822 n_conn
= connection_or_connect(&n_addr
, n_port
, id_digest
);
824 log_info(LD_CIRC
,"Launching n_conn failed. Closing circuit.");
825 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
828 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
830 /* return success. The onion/circuit/etc will be taken care of
831 * automatically (may already have been) whenever n_conn reaches
832 * OR_CONN_STATE_OPEN.
837 tor_assert(!circ
->n_hop
); /* Connection is already established. */
838 circ
->n_conn
= n_conn
;
839 log_debug(LD_CIRC
,"n_conn is %s:%u",
840 n_conn
->_base
.address
,n_conn
->_base
.port
);
842 if (circuit_deliver_create_cell(circ
, CELL_CREATE
, onionskin
) < 0)
847 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
848 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
850 * - 20 to initialize f_digest
851 * - 20 to initialize b_digest
852 * - 16 to key f_crypto
853 * - 16 to key b_crypto
855 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
858 circuit_init_cpath_crypto(crypt_path_t
*cpath
, const char *key_data
,
861 crypto_digest_env_t
*tmp_digest
;
862 crypto_cipher_env_t
*tmp_crypto
;
865 tor_assert(key_data
);
866 tor_assert(!(cpath
->f_crypto
|| cpath
->b_crypto
||
867 cpath
->f_digest
|| cpath
->b_digest
));
869 cpath
->f_digest
= crypto_new_digest_env();
870 crypto_digest_add_bytes(cpath
->f_digest
, key_data
, DIGEST_LEN
);
871 cpath
->b_digest
= crypto_new_digest_env();
872 crypto_digest_add_bytes(cpath
->b_digest
, key_data
+DIGEST_LEN
, DIGEST_LEN
);
874 if (!(cpath
->f_crypto
=
875 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
),1))) {
876 log_warn(LD_BUG
,"Forward cipher initialization failed.");
879 if (!(cpath
->b_crypto
=
880 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
)+CIPHER_KEY_LEN
,0))) {
881 log_warn(LD_BUG
,"Backward cipher initialization failed.");
886 tmp_digest
= cpath
->f_digest
;
887 cpath
->f_digest
= cpath
->b_digest
;
888 cpath
->b_digest
= tmp_digest
;
889 tmp_crypto
= cpath
->f_crypto
;
890 cpath
->f_crypto
= cpath
->b_crypto
;
891 cpath
->b_crypto
= tmp_crypto
;
897 /** A created or extended cell came back to us on the circuit, and it included
898 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
899 * contains (the second DH key, plus KH). If <b>reply_type</b> is
900 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
902 * Calculate the appropriate keys and digests, make sure KH is
903 * correct, and initialize this hop of the cpath.
905 * Return - reason if we want to mark circ for close, else return 0.
908 circuit_finish_handshake(origin_circuit_t
*circ
, uint8_t reply_type
,
911 char keys
[CPATH_KEY_MATERIAL_LEN
];
914 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
)
917 hop
= onion_next_hop_in_cpath(circ
->cpath
);
918 if (!hop
) { /* got an extended when we're all done? */
919 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
920 return - END_CIRC_REASON_TORPROTOCOL
;
923 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
925 if (reply_type
== CELL_CREATED
&& hop
->dh_handshake_state
) {
926 if (onion_skin_client_handshake(hop
->dh_handshake_state
, reply
, keys
,
927 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
928 log_warn(LD_CIRC
,"onion_skin_client_handshake failed.");
929 return -END_CIRC_REASON_TORPROTOCOL
;
931 /* Remember hash of g^xy */
932 memcpy(hop
->handshake_digest
, reply
+DH_KEY_LEN
, DIGEST_LEN
);
933 } else if (reply_type
== CELL_CREATED_FAST
&& !hop
->dh_handshake_state
) {
934 if (fast_client_handshake(hop
->fast_handshake_state
, reply
, keys
,
935 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
936 log_warn(LD_CIRC
,"fast_client_handshake failed.");
937 return -END_CIRC_REASON_TORPROTOCOL
;
939 memcpy(hop
->handshake_digest
, reply
+DIGEST_LEN
, DIGEST_LEN
);
941 log_warn(LD_PROTOCOL
,"CREATED cell type did not match CREATE cell type.");
942 return -END_CIRC_REASON_TORPROTOCOL
;
945 if (hop
->dh_handshake_state
) {
946 crypto_dh_free(hop
->dh_handshake_state
); /* don't need it anymore */
947 hop
->dh_handshake_state
= NULL
;
949 memset(hop
->fast_handshake_state
, 0, sizeof(hop
->fast_handshake_state
));
951 if (circuit_init_cpath_crypto(hop
, keys
, 0)<0) {
952 return -END_CIRC_REASON_TORPROTOCOL
;
955 hop
->state
= CPATH_STATE_OPEN
;
956 log_info(LD_CIRC
,"Finished building %scircuit hop:",
957 (reply_type
== CELL_CREATED_FAST
) ? "fast " : "");
958 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
959 control_event_circuit_status(circ
, CIRC_EVENT_EXTENDED
, 0);
964 /** We received a relay truncated cell on circ.
966 * Since we don't ask for truncates currently, getting a truncated
967 * means that a connection broke or an extend failed. For now,
968 * just give up: for circ to close, and return 0.
971 circuit_truncated(origin_circuit_t
*circ
, crypt_path_t
*layer
)
973 // crypt_path_t *victim;
974 // connection_t *stream;
979 /* XXX Since we don't ask for truncates currently, getting a truncated
980 * means that a connection broke or an extend failed. For now,
983 circuit_mark_for_close(TO_CIRCUIT(circ
),
984 END_CIRC_REASON_FLAG_REMOTE
|END_CIRC_REASON_OR_CONN_CLOSED
);
988 while (layer
->next
!= circ
->cpath
) {
989 /* we need to clear out layer->next */
990 victim
= layer
->next
;
991 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
993 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
994 if (stream
->cpath_layer
== victim
) {
995 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
997 /* no need to send 'end' relay cells,
998 * because the other side's already dead
1000 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
1004 layer
->next
= victim
->next
;
1005 circuit_free_cpath_node(victim
);
1008 log_info(LD_CIRC
, "finished");
1013 /** Given a response payload and keys, initialize, then send a created
1017 onionskin_answer(or_circuit_t
*circ
, uint8_t cell_type
, const char *payload
,
1021 crypt_path_t
*tmp_cpath
;
1023 tmp_cpath
= tor_malloc_zero(sizeof(crypt_path_t
));
1024 tmp_cpath
->magic
= CRYPT_PATH_MAGIC
;
1026 memset(&cell
, 0, sizeof(cell_t
));
1027 cell
.command
= cell_type
;
1028 cell
.circ_id
= circ
->p_circ_id
;
1030 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
1032 memcpy(cell
.payload
, payload
,
1033 cell_type
== CELL_CREATED
? ONIONSKIN_REPLY_LEN
: DIGEST_LEN
*2);
1035 log_debug(LD_CIRC
,"init digest forward 0x%.8x, backward 0x%.8x.",
1036 (unsigned int)*(uint32_t*)(keys
),
1037 (unsigned int)*(uint32_t*)(keys
+20));
1038 if (circuit_init_cpath_crypto(tmp_cpath
, keys
, 0)<0) {
1039 log_warn(LD_BUG
,"Circuit initialization failed");
1040 tor_free(tmp_cpath
);
1043 circ
->n_digest
= tmp_cpath
->f_digest
;
1044 circ
->n_crypto
= tmp_cpath
->f_crypto
;
1045 circ
->p_digest
= tmp_cpath
->b_digest
;
1046 circ
->p_crypto
= tmp_cpath
->b_crypto
;
1047 tmp_cpath
->magic
= 0;
1048 tor_free(tmp_cpath
);
1050 if (cell_type
== CELL_CREATED
)
1051 memcpy(circ
->handshake_digest
, cell
.payload
+DH_KEY_LEN
, DIGEST_LEN
);
1053 memcpy(circ
->handshake_digest
, cell
.payload
+DIGEST_LEN
, DIGEST_LEN
);
1055 circ
->is_first_hop
= (cell_type
== CELL_CREATED_FAST
);
1057 append_cell_to_circuit_queue(TO_CIRCUIT(circ
),
1058 circ
->p_conn
, &cell
, CELL_DIRECTION_IN
);
1059 log_debug(LD_CIRC
,"Finished sending 'created' cell.");
1061 if (!is_local_addr(&circ
->p_conn
->_base
.addr
) &&
1062 !connection_or_nonopen_was_started_here(circ
->p_conn
)) {
1063 /* record that we could process create cells from a non-local conn
1064 * that we didn't initiate; presumably this means that create cells
1065 * can reach us too. */
1066 router_orport_found_reachable();
1072 /** Choose a length for a circuit of purpose <b>purpose</b>.
1073 * Default length is 3 + the number of endpoints that would give something
1074 * away. If the routerlist <b>routers</b> doesn't have enough routers
1075 * to handle the desired path length, return as large a path length as
1076 * is feasible, except if it's less than 2, in which case return -1.
1079 new_route_len(uint8_t purpose
, extend_info_t
*exit
,
1080 smartlist_t
*routers
)
1082 int num_acceptable_routers
;
1085 tor_assert(routers
);
1089 purpose
!= CIRCUIT_PURPOSE_TESTING
&&
1090 purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
1093 num_acceptable_routers
= count_acceptable_routers(routers
);
1095 log_debug(LD_CIRC
,"Chosen route length %d (%d/%d routers suitable).",
1096 routelen
, num_acceptable_routers
, smartlist_len(routers
));
1098 if (num_acceptable_routers
< 2) {
1100 "Not enough acceptable routers (%d). Discarding this circuit.",
1101 num_acceptable_routers
);
1105 if (num_acceptable_routers
< routelen
) {
1106 log_info(LD_CIRC
,"Not enough routers: cutting routelen from %d to %d.",
1107 routelen
, num_acceptable_routers
);
1108 routelen
= num_acceptable_routers
;
1114 /** Fetch the list of predicted ports, dup it into a smartlist of
1115 * uint16_t's, remove the ones that are already handled by an
1116 * existing circuit, and return it.
1118 static smartlist_t
*
1119 circuit_get_unhandled_ports(time_t now
)
1121 smartlist_t
*source
= rep_hist_get_predicted_ports(now
);
1122 smartlist_t
*dest
= smartlist_create();
1126 for (i
= 0; i
< smartlist_len(source
); ++i
) {
1127 tmp
= tor_malloc(sizeof(uint16_t));
1128 memcpy(tmp
, smartlist_get(source
, i
), sizeof(uint16_t));
1129 smartlist_add(dest
, tmp
);
1132 circuit_remove_handled_ports(dest
);
1136 /** Return 1 if we already have circuits present or on the way for
1137 * all anticipated ports. Return 0 if we should make more.
1139 * If we're returning 0, set need_uptime and need_capacity to
1140 * indicate any requirements that the unhandled ports have.
1143 circuit_all_predicted_ports_handled(time_t now
, int *need_uptime
,
1148 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
1149 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
1150 tor_assert(need_uptime
);
1151 tor_assert(need_capacity
);
1152 enough
= (smartlist_len(sl
) == 0);
1153 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
1154 port
= smartlist_get(sl
, i
);
1155 if (smartlist_string_num_isin(LongLivedServices
, *port
))
1163 /** Return 1 if <b>router</b> can handle one or more of the ports in
1164 * <b>needed_ports</b>, else return 0.
1167 router_handles_some_port(routerinfo_t
*router
, smartlist_t
*needed_ports
)
1172 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
1173 addr_policy_result_t r
;
1174 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
1176 r
= compare_addr_to_addr_policy(0, port
, router
->exit_policy
);
1177 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
1183 /** Return true iff <b>conn</b> needs another general circuit to be
1186 ap_stream_wants_exit_attention(connection_t
*conn
)
1188 if (conn
->type
== CONN_TYPE_AP
&&
1189 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
1190 !conn
->marked_for_close
&&
1191 !(TO_EDGE_CONN(conn
)->want_onehop
) && /* ignore one-hop streams */
1192 !(TO_EDGE_CONN(conn
)->use_begindir
) && /* ignore targeted dir fetches */
1193 !(TO_EDGE_CONN(conn
)->chosen_exit_name
) && /* ignore defined streams */
1194 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
1195 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn
), 0,
1196 MIN_CIRCUITS_HANDLING_STREAM
))
1201 /** Return a pointer to a suitable router to be the exit node for the
1202 * general-purpose circuit we're about to build.
1204 * Look through the connection array, and choose a router that maximizes
1205 * the number of pending streams that can exit from this router.
1207 * Return NULL if we can't find any suitable routers.
1209 static routerinfo_t
*
1210 choose_good_exit_server_general(routerlist_t
*dir
, int need_uptime
,
1215 int n_pending_connections
= 0;
1216 smartlist_t
*connections
;
1217 int best_support
= -1;
1218 int n_best_support
=0;
1219 routerinfo_t
*router
;
1220 or_options_t
*options
= get_options();
1222 connections
= get_connection_array();
1224 /* Count how many connections are waiting for a circuit to be built.
1225 * We use this for log messages now, but in the future we may depend on it.
1227 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1229 if (ap_stream_wants_exit_attention(conn
))
1230 ++n_pending_connections
;
1232 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1233 // n_pending_connections);
1234 /* Now we count, for each of the routers in the directory, how many
1235 * of the pending connections could possibly exit from that
1236 * router (n_supported[i]). (We can't be sure about cases where we
1237 * don't know the IP address of the pending connection.)
1239 * -1 means "Don't use this router at all."
1241 n_supported
= tor_malloc(sizeof(int)*smartlist_len(dir
->routers
));
1242 for (i
= 0; i
< smartlist_len(dir
->routers
); ++i
) {/* iterate over routers */
1243 router
= smartlist_get(dir
->routers
, i
);
1244 if (router_is_me(router
)) {
1245 n_supported
[i
] = -1;
1246 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1247 /* XXX there's probably a reverse predecessor attack here, but
1248 * it's slow. should we take this out? -RD
1252 if (!router
->is_running
|| router
->is_bad_exit
) {
1253 n_supported
[i
] = -1;
1254 continue; /* skip routers that are known to be down or bad exits */
1256 if (router_is_unreliable(router
, need_uptime
, need_capacity
, 0)) {
1257 n_supported
[i
] = -1;
1258 continue; /* skip routers that are not suitable */
1260 if (!(router
->is_valid
|| options
->_AllowInvalid
& ALLOW_INVALID_EXIT
)) {
1261 /* if it's invalid and we don't want it */
1262 n_supported
[i
] = -1;
1263 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1264 // router->nickname, i);
1265 continue; /* skip invalid routers */
1267 if (options
->ExcludeSingleHopRelays
&& router
->allow_single_hop_exits
) {
1268 n_supported
[i
] = -1;
1271 if (router_exit_policy_rejects_all(router
)) {
1272 n_supported
[i
] = -1;
1273 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1274 // router->nickname, i);
1275 continue; /* skip routers that reject all */
1278 /* iterate over connections */
1279 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1281 if (!ap_stream_wants_exit_attention(conn
))
1282 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1283 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn
), router
)) {
1285 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1286 // router->nickname, i, n_supported[i]);
1288 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1289 // router->nickname, i);
1291 }); /* End looping over connections. */
1292 if (n_pending_connections
> 0 && n_supported
[i
] == 0) {
1293 /* Leave best_support at -1 if that's where it is, so we can
1294 * distinguish it later. */
1297 if (n_supported
[i
] > best_support
) {
1298 /* If this router is better than previous ones, remember its index
1299 * and goodness, and start counting how many routers are this good. */
1300 best_support
= n_supported
[i
]; n_best_support
=1;
1301 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1302 // router->nickname);
1303 } else if (n_supported
[i
] == best_support
) {
1304 /* If this router is _as good_ as the best one, just increment the
1305 * count of equally good routers.*/
1310 "Found %d servers that might support %d/%d pending connections.",
1311 n_best_support
, best_support
>= 0 ? best_support
: 0,
1312 n_pending_connections
);
1314 /* If any routers definitely support any pending connections, choose one
1316 if (best_support
> 0) {
1317 smartlist_t
*supporting
= smartlist_create(), *use
= smartlist_create();
1319 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++)
1320 if (n_supported
[i
] == best_support
)
1321 smartlist_add(supporting
, smartlist_get(dir
->routers
, i
));
1323 routersets_get_disjunction(use
, supporting
, options
->ExitNodes
,
1324 options
->_ExcludeExitNodesUnion
, 1);
1325 if (smartlist_len(use
) == 0 && !options
->StrictExitNodes
) {
1326 routersets_get_disjunction(use
, supporting
, NULL
,
1327 options
->_ExcludeExitNodesUnion
, 1);
1329 router
= routerlist_sl_choose_by_bandwidth(use
, WEIGHT_FOR_EXIT
);
1330 smartlist_free(use
);
1331 smartlist_free(supporting
);
1333 /* Either there are no pending connections, or no routers even seem to
1334 * possibly support any of them. Choose a router at random that satisfies
1335 * at least one predicted exit port. */
1338 smartlist_t
*needed_ports
, *supporting
, *use
;
1340 if (best_support
== -1) {
1341 if (need_uptime
|| need_capacity
) {
1343 "We couldn't find any live%s%s routers; falling back "
1344 "to list of all routers.",
1345 need_capacity
?", fast":"",
1346 need_uptime
?", stable":"");
1347 tor_free(n_supported
);
1348 return choose_good_exit_server_general(dir
, 0, 0);
1350 log_notice(LD_CIRC
, "All routers are down or won't exit -- choosing a "
1351 "doomed exit at random.");
1353 supporting
= smartlist_create();
1354 use
= smartlist_create();
1355 needed_ports
= circuit_get_unhandled_ports(time(NULL
));
1356 for (try = 0; try < 2; try++) {
1357 /* try once to pick only from routers that satisfy a needed port,
1358 * then if there are none, pick from any that support exiting. */
1359 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++) {
1360 router
= smartlist_get(dir
->routers
, i
);
1361 if (n_supported
[i
] != -1 &&
1362 (try || router_handles_some_port(router
, needed_ports
))) {
1363 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1364 // try, router->nickname);
1365 smartlist_add(supporting
, router
);
1369 routersets_get_disjunction(use
, supporting
, options
->ExitNodes
,
1370 options
->_ExcludeExitNodesUnion
, 1);
1371 if (smartlist_len(use
) == 0 && !options
->StrictExitNodes
) {
1372 routersets_get_disjunction(use
, supporting
, NULL
,
1373 options
->_ExcludeExitNodesUnion
, 1);
1375 /* XXX sometimes the above results in null, when the requested
1376 * exit node is down. we should pick it anyway. */
1377 router
= routerlist_sl_choose_by_bandwidth(use
, WEIGHT_FOR_EXIT
);
1380 smartlist_clear(supporting
);
1381 smartlist_clear(use
);
1383 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
1384 smartlist_free(needed_ports
);
1385 smartlist_free(use
);
1386 smartlist_free(supporting
);
1389 tor_free(n_supported
);
1391 log_info(LD_CIRC
, "Chose exit server '%s'", router
->nickname
);
1394 if (options
->StrictExitNodes
) {
1396 "No specified exit routers seem to be running, and "
1397 "StrictExitNodes is set: can't choose an exit.");
1402 /** Return a pointer to a suitable router to be the exit node for the
1403 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1404 * if no router is suitable).
1406 * For general-purpose circuits, pass it off to
1407 * choose_good_exit_server_general()
1409 * For client-side rendezvous circuits, choose a random node, weighted
1410 * toward the preferences in 'options'.
1412 static routerinfo_t
*
1413 choose_good_exit_server(uint8_t purpose
, routerlist_t
*dir
,
1414 int need_uptime
, int need_capacity
, int is_internal
)
1416 or_options_t
*options
= get_options();
1417 router_crn_flags_t flags
= 0;
1419 flags
|= CRN_NEED_UPTIME
;
1421 flags
|= CRN_NEED_CAPACITY
;
1424 case CIRCUIT_PURPOSE_C_GENERAL
:
1425 if (options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
)
1426 flags
|= CRN_ALLOW_INVALID
;
1427 if (is_internal
) /* pick it like a middle hop */
1428 return router_choose_random_node(NULL
, NULL
,
1429 options
->ExcludeNodes
, flags
);
1431 return choose_good_exit_server_general(dir
,need_uptime
,need_capacity
);
1432 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1433 if (options
->_AllowInvalid
& ALLOW_INVALID_RENDEZVOUS
)
1434 flags
|= CRN_ALLOW_INVALID
;
1435 return router_choose_random_node(NULL
, NULL
,
1436 options
->ExcludeNodes
, flags
);
1438 log_warn(LD_BUG
,"Unhandled purpose %d", purpose
);
1439 tor_fragile_assert();
1443 /** Log a warning if the user specified an exit for the circuit that
1444 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1446 warn_if_last_router_excluded(origin_circuit_t
*circ
, const extend_info_t
*exit
)
1448 or_options_t
*options
= get_options();
1449 routerset_t
*rs
= options
->ExcludeNodes
;
1450 const char *description
;
1451 int domain
= LD_CIRC
;
1452 uint8_t purpose
= circ
->_base
.purpose
;
1454 if (circ
->build_state
->onehop_tunnel
)
1460 case CIRCUIT_PURPOSE_OR
:
1461 case CIRCUIT_PURPOSE_INTRO_POINT
:
1462 case CIRCUIT_PURPOSE_REND_POINT_WAITING
:
1463 case CIRCUIT_PURPOSE_REND_ESTABLISHED
:
1464 log_warn(LD_BUG
, "Called on non-origin circuit (purpose %d)",
1467 case CIRCUIT_PURPOSE_C_GENERAL
:
1468 if (circ
->build_state
->is_internal
)
1470 description
= "Requested exit node";
1471 rs
= options
->_ExcludeExitNodesUnion
;
1473 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1474 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
1475 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
:
1476 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1477 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1478 case CIRCUIT_PURPOSE_S_REND_JOINED
:
1479 case CIRCUIT_PURPOSE_TESTING
:
1481 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1482 case CIRCUIT_PURPOSE_C_REND_READY
:
1483 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
1484 case CIRCUIT_PURPOSE_C_REND_JOINED
:
1485 description
= "Chosen rendezvous point";
1488 case CIRCUIT_PURPOSE_CONTROLLER
:
1489 rs
= options
->_ExcludeExitNodesUnion
;
1490 description
= "Controller-selected circuit target";
1494 if (routerset_contains_extendinfo(rs
, exit
)) {
1495 log_fn(LOG_WARN
, domain
, "%s '%s' is in ExcludeNodes%s. Using anyway "
1496 "(circuit purpose %d).",
1497 description
,exit
->nickname
,
1498 rs
==options
->ExcludeNodes
?"":" or ExcludeExitNodes",
1500 circuit_log_path(LOG_WARN
, domain
, circ
);
1506 /** Decide a suitable length for circ's cpath, and pick an exit
1507 * router (or use <b>exit</b> if provided). Store these in the
1508 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1510 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1512 cpath_build_state_t
*state
= circ
->build_state
;
1513 routerlist_t
*rl
= router_get_routerlist();
1515 if (state
->onehop_tunnel
) {
1516 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel.");
1517 state
->desired_path_len
= 1;
1519 int r
= new_route_len(circ
->_base
.purpose
, exit
, rl
->routers
);
1520 if (r
< 1) /* must be at least 1 */
1522 state
->desired_path_len
= r
;
1525 if (exit
) { /* the circuit-builder pre-requested one */
1526 warn_if_last_router_excluded(circ
, exit
);
1527 log_info(LD_CIRC
,"Using requested exit node '%s'", exit
->nickname
);
1528 exit
= extend_info_dup(exit
);
1529 } else { /* we have to decide one */
1530 routerinfo_t
*router
=
1531 choose_good_exit_server(circ
->_base
.purpose
, rl
, state
->need_uptime
,
1532 state
->need_capacity
, state
->is_internal
);
1534 log_warn(LD_CIRC
,"failed to choose an exit server");
1537 exit
= extend_info_from_router(router
);
1539 state
->chosen_exit
= exit
;
1543 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1544 * hop to the cpath reflecting this. Don't send the next extend cell --
1545 * the caller will do this if it wants to.
1548 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1550 cpath_build_state_t
*state
;
1554 state
= circ
->build_state
;
1556 if (state
->chosen_exit
)
1557 extend_info_free(state
->chosen_exit
);
1558 state
->chosen_exit
= extend_info_dup(exit
);
1560 ++circ
->build_state
->desired_path_len
;
1561 onion_append_hop(&circ
->cpath
, exit
);
1565 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1566 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1567 * send the next extend cell to begin connecting to that hop.
1570 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1573 warn_if_last_router_excluded(circ
, exit
);
1574 circuit_append_new_exit(circ
, exit
);
1575 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
1576 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
1577 log_warn(LD_CIRC
, "Couldn't extend circuit to new point '%s'.",
1579 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
1585 /** Return the number of routers in <b>routers</b> that are currently up
1586 * and available for building circuits through.
1589 count_acceptable_routers(smartlist_t
*routers
)
1595 n
= smartlist_len(routers
);
1597 r
= smartlist_get(routers
, i
);
1598 // log_debug(LD_CIRC,
1599 // "Contemplating whether router %d (%s) is a new option.",
1601 if (r
->is_running
== 0) {
1602 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1605 if (r
->is_valid
== 0) {
1606 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1608 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1609 * allows this node in some places, then we're getting an inaccurate
1610 * count. For now, be conservative and don't count it. But later we
1611 * should try to be smarter. */
1614 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1616 ; /* C requires an explicit statement after the label */
1622 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1623 * This function is used to extend cpath by another hop.
1626 onion_append_to_cpath(crypt_path_t
**head_ptr
, crypt_path_t
*new_hop
)
1629 new_hop
->next
= (*head_ptr
);
1630 new_hop
->prev
= (*head_ptr
)->prev
;
1631 (*head_ptr
)->prev
->next
= new_hop
;
1632 (*head_ptr
)->prev
= new_hop
;
1634 *head_ptr
= new_hop
;
1635 new_hop
->prev
= new_hop
->next
= new_hop
;
1639 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1640 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1641 * to length <b>cur_len</b> to decide a suitable middle hop for a
1642 * circuit. In particular, make sure we don't pick the exit node or its
1643 * family, and make sure we don't duplicate any previous nodes or their
1645 static routerinfo_t
*
1646 choose_good_middle_server(uint8_t purpose
,
1647 cpath_build_state_t
*state
,
1652 routerinfo_t
*r
, *choice
;
1653 crypt_path_t
*cpath
;
1654 smartlist_t
*excluded
;
1655 or_options_t
*options
= get_options();
1656 router_crn_flags_t flags
= 0;
1657 tor_assert(_CIRCUIT_PURPOSE_MIN
<= purpose
&&
1658 purpose
<= _CIRCUIT_PURPOSE_MAX
);
1660 log_debug(LD_CIRC
, "Contemplating intermediate hop: random choice.");
1661 excluded
= smartlist_create();
1662 if ((r
= build_state_get_exit_router(state
))) {
1663 smartlist_add(excluded
, r
);
1664 routerlist_add_family(excluded
, r
);
1666 for (i
= 0, cpath
= head
; i
< cur_len
; ++i
, cpath
=cpath
->next
) {
1667 if ((r
= router_get_by_digest(cpath
->extend_info
->identity_digest
))) {
1668 smartlist_add(excluded
, r
);
1669 routerlist_add_family(excluded
, r
);
1673 if (state
->need_uptime
)
1674 flags
|= CRN_NEED_UPTIME
;
1675 if (state
->need_capacity
)
1676 flags
|= CRN_NEED_CAPACITY
;
1677 if (options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
)
1678 flags
|= CRN_ALLOW_INVALID
;
1679 choice
= router_choose_random_node(NULL
,
1680 excluded
, options
->ExcludeNodes
, flags
);
1681 smartlist_free(excluded
);
1685 /** Pick a good entry server for the circuit to be built according to
1686 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1687 * router (if we're an OR), and respect firewall settings; if we're
1688 * configured to use entry guards, return one.
1690 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1691 * guard, not for any particular circuit.
1693 static routerinfo_t
*
1694 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
)
1696 routerinfo_t
*r
, *choice
;
1697 smartlist_t
*excluded
;
1698 or_options_t
*options
= get_options();
1699 router_crn_flags_t flags
= CRN_NEED_GUARD
;
1701 if (state
&& options
->UseEntryGuards
&&
1702 (purpose
!= CIRCUIT_PURPOSE_TESTING
|| options
->BridgeRelay
)) {
1703 return choose_random_entry(state
);
1706 excluded
= smartlist_create();
1708 if (state
&& (r
= build_state_get_exit_router(state
))) {
1709 smartlist_add(excluded
, r
);
1710 routerlist_add_family(excluded
, r
);
1712 if (firewall_is_fascist_or()) {
1713 /*XXXX This could slow things down a lot; use a smarter implementation */
1714 /* exclude all ORs that listen on the wrong port, if anybody notices. */
1715 routerlist_t
*rl
= router_get_routerlist();
1718 for (i
=0; i
< smartlist_len(rl
->routers
); i
++) {
1719 r
= smartlist_get(rl
->routers
, i
);
1720 if (!fascist_firewall_allows_or(r
))
1721 smartlist_add(excluded
, r
);
1724 /* and exclude current entry guards, if applicable */
1725 if (options
->UseEntryGuards
&& entry_guards
) {
1726 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1728 if ((r
= router_get_by_digest(entry
->identity
))) {
1729 smartlist_add(excluded
, r
);
1730 routerlist_add_family(excluded
, r
);
1736 if (state
->need_uptime
)
1737 flags
|= CRN_NEED_UPTIME
;
1738 if (state
->need_capacity
)
1739 flags
|= CRN_NEED_CAPACITY
;
1741 if (options
->_AllowInvalid
& ALLOW_INVALID_ENTRY
)
1742 flags
|= CRN_ALLOW_INVALID
;
1744 choice
= router_choose_random_node(
1747 options
->ExcludeNodes
,
1749 smartlist_free(excluded
);
1753 /** Return the first non-open hop in cpath, or return NULL if all
1755 static crypt_path_t
*
1756 onion_next_hop_in_cpath(crypt_path_t
*cpath
)
1758 crypt_path_t
*hop
= cpath
;
1760 if (hop
->state
!= CPATH_STATE_OPEN
)
1763 } while (hop
!= cpath
);
1767 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1768 * based on <b>state</b>. Append the hop info to head_ptr.
1771 onion_extend_cpath(origin_circuit_t
*circ
)
1773 uint8_t purpose
= circ
->_base
.purpose
;
1774 cpath_build_state_t
*state
= circ
->build_state
;
1775 int cur_len
= circuit_get_cpath_len(circ
);
1776 extend_info_t
*info
= NULL
;
1778 if (cur_len
>= state
->desired_path_len
) {
1779 log_debug(LD_CIRC
, "Path is complete: %d steps long",
1780 state
->desired_path_len
);
1784 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
1785 state
->desired_path_len
);
1787 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
1788 info
= extend_info_dup(state
->chosen_exit
);
1789 } else if (cur_len
== 0) { /* picking first node */
1790 routerinfo_t
*r
= choose_good_entry_server(purpose
, state
);
1792 info
= extend_info_from_router(r
);
1795 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
1797 info
= extend_info_from_router(r
);
1801 log_warn(LD_CIRC
,"Failed to find node for hop %d of our path. Discarding "
1802 "this circuit.", cur_len
);
1806 log_debug(LD_CIRC
,"Chose router %s for hop %d (exit is %s)",
1807 info
->nickname
, cur_len
+1, build_state_get_exit_nickname(state
));
1809 onion_append_hop(&circ
->cpath
, info
);
1810 extend_info_free(info
);
1814 /** Create a new hop, annotate it with information about its
1815 * corresponding router <b>choice</b>, and append it to the
1816 * end of the cpath <b>head_ptr</b>. */
1818 onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
)
1820 crypt_path_t
*hop
= tor_malloc_zero(sizeof(crypt_path_t
));
1822 /* link hop into the cpath, at the end. */
1823 onion_append_to_cpath(head_ptr
, hop
);
1825 hop
->magic
= CRYPT_PATH_MAGIC
;
1826 hop
->state
= CPATH_STATE_CLOSED
;
1828 hop
->extend_info
= extend_info_dup(choice
);
1830 hop
->package_window
= circuit_initial_package_window();
1831 hop
->deliver_window
= CIRCWINDOW_START
;
1836 /** Allocate a new extend_info object based on the various arguments. */
1838 extend_info_alloc(const char *nickname
, const char *digest
,
1839 crypto_pk_env_t
*onion_key
,
1840 const tor_addr_t
*addr
, uint16_t port
)
1842 extend_info_t
*info
= tor_malloc_zero(sizeof(extend_info_t
));
1843 memcpy(info
->identity_digest
, digest
, DIGEST_LEN
);
1845 strlcpy(info
->nickname
, nickname
, sizeof(info
->nickname
));
1847 info
->onion_key
= crypto_pk_dup_key(onion_key
);
1848 tor_addr_copy(&info
->addr
, addr
);
1853 /** Allocate and return a new extend_info_t that can be used to build a
1854 * circuit to or through the router <b>r</b>. */
1856 extend_info_from_router(routerinfo_t
*r
)
1860 tor_addr_from_ipv4h(&addr
, r
->addr
);
1861 return extend_info_alloc(r
->nickname
, r
->cache_info
.identity_digest
,
1862 r
->onion_pkey
, &addr
, r
->or_port
);
1865 /** Release storage held by an extend_info_t struct. */
1867 extend_info_free(extend_info_t
*info
)
1870 if (info
->onion_key
)
1871 crypto_free_pk_env(info
->onion_key
);
1875 /** Allocate and return a new extend_info_t with the same contents as
1878 extend_info_dup(extend_info_t
*info
)
1880 extend_info_t
*newinfo
;
1882 newinfo
= tor_malloc(sizeof(extend_info_t
));
1883 memcpy(newinfo
, info
, sizeof(extend_info_t
));
1884 if (info
->onion_key
)
1885 newinfo
->onion_key
= crypto_pk_dup_key(info
->onion_key
);
1887 newinfo
->onion_key
= NULL
;
1891 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1892 * If there is no chosen exit, or if we don't know the routerinfo_t for
1893 * the chosen exit, return NULL.
1896 build_state_get_exit_router(cpath_build_state_t
*state
)
1898 if (!state
|| !state
->chosen_exit
)
1900 return router_get_by_digest(state
->chosen_exit
->identity_digest
);
1903 /** Return the nickname for the chosen exit router in <b>state</b>. If
1904 * there is no chosen exit, or if we don't know the routerinfo_t for the
1905 * chosen exit, return NULL.
1908 build_state_get_exit_nickname(cpath_build_state_t
*state
)
1910 if (!state
|| !state
->chosen_exit
)
1912 return state
->chosen_exit
->nickname
;
1915 /** Check whether the entry guard <b>e</b> is usable, given the directory
1916 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1917 * configuration (in <b>options</b>). Set <b>e</b>->bad_since
1918 * accordingly. Return true iff the entry guard's status changes.
1920 * If it's not usable, set *<b>reason</b> to a static string explaining why.
1922 /*XXXX take a routerstatus, not a routerinfo. */
1924 entry_guard_set_status(entry_guard_t
*e
, routerinfo_t
*ri
,
1925 time_t now
, or_options_t
*options
, const char **reason
)
1927 char buf
[HEX_DIGEST_LEN
+1];
1930 tor_assert(options
);
1934 /* Do we want to mark this guard as bad? */
1936 *reason
= "unlisted";
1937 else if (!ri
->is_running
)
1939 else if (options
->UseBridges
&& ri
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1940 *reason
= "not a bridge";
1941 else if (!options
->UseBridges
&& !ri
->is_possible_guard
&&
1942 !routerset_contains_router(options
->EntryNodes
,ri
))
1943 *reason
= "not recommended as a guard";
1944 else if (routerset_contains_router(options
->ExcludeNodes
, ri
))
1945 *reason
= "excluded";
1947 if (*reason
&& ! e
->bad_since
) {
1948 /* Router is newly bad. */
1949 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1950 log_info(LD_CIRC
, "Entry guard %s (%s) is %s: marking as unusable.",
1951 e
->nickname
, buf
, *reason
);
1954 control_event_guard(e
->nickname
, e
->identity
, "BAD");
1956 } else if (!*reason
&& e
->bad_since
) {
1957 /* There's nothing wrong with the router any more. */
1958 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1959 log_info(LD_CIRC
, "Entry guard %s (%s) is no longer unusable: "
1960 "marking as ok.", e
->nickname
, buf
);
1963 control_event_guard(e
->nickname
, e
->identity
, "GOOD");
1969 /** Return true iff enough time has passed since we last tried to connect
1970 * to the unreachable guard <b>e</b> that we're willing to try again. */
1972 entry_is_time_to_retry(entry_guard_t
*e
, time_t now
)
1975 if (e
->last_attempted
< e
->unreachable_since
)
1977 diff
= now
- e
->unreachable_since
;
1979 return now
> (e
->last_attempted
+ 60*60);
1980 else if (diff
< 3*24*60*60)
1981 return now
> (e
->last_attempted
+ 4*60*60);
1982 else if (diff
< 7*24*60*60)
1983 return now
> (e
->last_attempted
+ 18*60*60);
1985 return now
> (e
->last_attempted
+ 36*60*60);
1988 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1989 * working well enough that we are willing to use it as an entry
1990 * right now. (Else return NULL.) In particular, it must be
1991 * - Listed as either up or never yet contacted;
1992 * - Present in the routerlist;
1993 * - Listed as 'stable' or 'fast' by the current dirserver consensus,
1994 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1995 * (This check is currently redundant with the Guard flag, but in
1996 * the future that might change. Best to leave it in for now.)
1997 * - Allowed by our current ReachableORAddresses config option; and
1998 * - Currently thought to be reachable by us (unless assume_reachable
2001 static INLINE routerinfo_t
*
2002 entry_is_live(entry_guard_t
*e
, int need_uptime
, int need_capacity
,
2003 int assume_reachable
)
2008 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
2009 if (!assume_reachable
&& !e
->can_retry
&&
2010 e
->unreachable_since
&& !entry_is_time_to_retry(e
, time(NULL
)))
2012 r
= router_get_by_digest(e
->identity
);
2015 if (get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
2017 if (!get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_GENERAL
)
2019 if (router_is_unreliable(r
, need_uptime
, need_capacity
, 0))
2021 if (!fascist_firewall_allows_or(r
))
2026 /** Return the number of entry guards that we think are usable. */
2028 num_live_entry_guards(void)
2033 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2035 if (entry_is_live(entry
, 0, 1, 0))
2041 /** If <b>digest</b> matches the identity of any node in the
2042 * entry_guards list, return that node. Else return NULL. */
2043 static INLINE entry_guard_t
*
2044 is_an_entry_guard(const char *digest
)
2046 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2047 if (!memcmp(digest
, entry
->identity
, DIGEST_LEN
))
2053 /** Dump a description of our list of entry guards to the log at level
2054 * <b>severity</b>. */
2056 log_entry_guards(int severity
)
2058 smartlist_t
*elements
= smartlist_create();
2062 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2064 tor_snprintf(buf
, sizeof(buf
), "%s (%s%s)",
2066 entry_is_live(e
, 0, 1, 0) ? "up " : "down ",
2067 e
->made_contact
? "made-contact" : "never-contacted");
2068 smartlist_add(elements
, tor_strdup(buf
));
2071 s
= smartlist_join_strings(elements
, ",", 0, NULL
);
2072 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
2073 smartlist_free(elements
);
2074 log_fn(severity
,LD_CIRC
,"%s",s
);
2078 /** Called when one or more guards that we would previously have used for some
2079 * purpose are no longer in use because a higher-priority guard has become
2082 control_event_guard_deferred(void)
2084 /* XXXX We don't actually have a good way to figure out _how many_ entries
2085 * are live for some purpose. We need an entry_is_even_slightly_live()
2086 * function for this to work right. NumEntryGuards isn't reliable: if we
2087 * need guards with weird properties, we can have more than that number
2092 or_options_t
*options
= get_options();
2095 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2097 if (entry_is_live(entry
, 0, 1, 0)) {
2098 if (n
++ == options
->NumEntryGuards
) {
2099 control_event_guard(entry
->nickname
, entry
->identity
, "DEFERRED");
2107 /** Add a new (preferably stable and fast) router to our
2108 * entry_guards list. Return a pointer to the router if we succeed,
2109 * or NULL if we can't find any more suitable entries.
2111 * If <b>chosen</b> is defined, use that one, and if it's not
2112 * already in our entry_guards list, put it at the *beginning*.
2113 * Else, put the one we pick at the end of the list. */
2114 static routerinfo_t
*
2115 add_an_entry_guard(routerinfo_t
*chosen
, int reset_status
)
2117 routerinfo_t
*router
;
2118 entry_guard_t
*entry
;
2122 entry
= is_an_entry_guard(router
->cache_info
.identity_digest
);
2125 entry
->bad_since
= 0;
2126 entry
->can_retry
= 1;
2131 router
= choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL
, NULL
);
2135 entry
= tor_malloc_zero(sizeof(entry_guard_t
));
2136 log_info(LD_CIRC
, "Chose '%s' as new entry guard.", router
->nickname
);
2137 strlcpy(entry
->nickname
, router
->nickname
, sizeof(entry
->nickname
));
2138 memcpy(entry
->identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
2139 /* Choose expiry time smudged over the past month. The goal here
2140 * is to a) spread out when Tor clients rotate their guards, so they
2141 * don't all select them on the same day, and b) avoid leaving a
2142 * precise timestamp in the state file about when we first picked
2143 * this guard. For details, see the Jan 2010 or-dev thread. */
2144 entry
->chosen_on_date
= time(NULL
) - crypto_rand_int(3600*24*30);
2145 entry
->chosen_by_version
= tor_strdup(VERSION
);
2146 if (chosen
) /* prepend */
2147 smartlist_insert(entry_guards
, 0, entry
);
2149 smartlist_add(entry_guards
, entry
);
2150 control_event_guard(entry
->nickname
, entry
->identity
, "NEW");
2151 control_event_guard_deferred();
2152 log_entry_guards(LOG_INFO
);
2156 /** If the use of entry guards is configured, choose more entry guards
2157 * until we have enough in the list. */
2159 pick_entry_guards(void)
2161 or_options_t
*options
= get_options();
2164 tor_assert(entry_guards
);
2166 while (num_live_entry_guards() < options
->NumEntryGuards
) {
2167 if (!add_an_entry_guard(NULL
, 0))
2172 entry_guards_changed();
2175 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2176 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2177 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2179 /** Release all storage held by <b>e</b>. */
2181 entry_guard_free(entry_guard_t
*e
)
2184 tor_free(e
->chosen_by_version
);
2188 /** Remove any entry guard which was selected by an unknown version of Tor,
2189 * or which was selected by a version of Tor that's known to select
2190 * entry guards badly. */
2192 remove_obsolete_entry_guards(void)
2195 time_t now
= time(NULL
);
2197 for (i
= 0; i
< smartlist_len(entry_guards
); ++i
) {
2198 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2199 const char *ver
= entry
->chosen_by_version
;
2200 const char *msg
= NULL
;
2202 int version_is_bad
= 0, date_is_bad
= 0;
2204 msg
= "does not say what version of Tor it was selected by";
2206 } else if (tor_version_parse(ver
, &v
)) {
2207 msg
= "does not seem to be from any recognized version of Tor";
2210 size_t len
= strlen(ver
)+5;
2211 char *tor_ver
= tor_malloc(len
);
2212 tor_snprintf(tor_ver
, len
, "Tor %s", ver
);
2213 if ((tor_version_as_new_as(tor_ver
, "0.1.0.10-alpha") &&
2214 !tor_version_as_new_as(tor_ver
, "0.1.2.16-dev")) ||
2215 (tor_version_as_new_as(tor_ver
, "0.2.0.0-alpha") &&
2216 !tor_version_as_new_as(tor_ver
, "0.2.0.6-alpha")) ||
2217 /* above are bug 440; below are bug 1217 */
2218 (tor_version_as_new_as(tor_ver
, "0.2.1.3-alpha") &&
2219 !tor_version_as_new_as(tor_ver
, "0.2.1.23")) ||
2220 (tor_version_as_new_as(tor_ver
, "0.2.2.0-alpha") &&
2221 !tor_version_as_new_as(tor_ver
, "0.2.2.7-alpha"))) {
2222 msg
= "was selected without regard for guard bandwidth";
2227 if (!version_is_bad
&& entry
->chosen_on_date
+ 3600*24*60 < now
) {
2228 /* It's been 2 months since the date listed in our state file. */
2229 msg
= "was selected several months ago";
2233 if (version_is_bad
|| date_is_bad
) { /* we need to drop it */
2234 char dbuf
[HEX_DIGEST_LEN
+1];
2236 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2237 log_fn(version_is_bad
? LOG_NOTICE
: LOG_INFO
, LD_CIRC
,
2238 "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
2239 entry
->nickname
, dbuf
, msg
, ver
?escaped(ver
):"none");
2240 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2241 entry_guard_free(entry
);
2242 smartlist_del_keeporder(entry_guards
, i
--);
2243 log_entry_guards(LOG_INFO
);
2248 return changed
? 1 : 0;
2251 /** Remove all entry guards that have been down or unlisted for so
2252 * long that we don't think they'll come up again. Return 1 if we
2253 * removed any, or 0 if we did nothing. */
2255 remove_dead_entry_guards(void)
2257 char dbuf
[HEX_DIGEST_LEN
+1];
2258 char tbuf
[ISO_TIME_LEN
+1];
2259 time_t now
= time(NULL
);
2263 for (i
= 0; i
< smartlist_len(entry_guards
); ) {
2264 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2265 if (entry
->bad_since
&&
2266 entry
->bad_since
+ ENTRY_GUARD_REMOVE_AFTER
< now
) {
2268 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2269 format_local_iso_time(tbuf
, entry
->bad_since
);
2270 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been down or unlisted "
2271 "since %s local time; removing.",
2272 entry
->nickname
, dbuf
, tbuf
);
2273 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2274 entry_guard_free(entry
);
2275 smartlist_del_keeporder(entry_guards
, i
);
2276 log_entry_guards(LOG_INFO
);
2281 return changed
? 1 : 0;
2284 /** A new directory or router-status has arrived; update the down/listed
2285 * status of the entry guards.
2287 * An entry is 'down' if the directory lists it as nonrunning.
2288 * An entry is 'unlisted' if the directory doesn't include it.
2290 * Don't call this on startup; only on a fresh download. Otherwise we'll
2291 * think that things are unlisted.
2294 entry_guards_compute_status(void)
2298 int severity
= LOG_DEBUG
;
2299 or_options_t
*options
;
2300 digestmap_t
*reasons
;
2304 options
= get_options();
2308 reasons
= digestmap_new();
2309 SMARTLIST_FOREACH_BEGIN(entry_guards
, entry_guard_t
*, entry
)
2311 routerinfo_t
*r
= router_get_by_digest(entry
->identity
);
2312 const char *reason
= NULL
;
2313 if (entry_guard_set_status(entry
, r
, now
, options
, &reason
))
2316 if (entry
->bad_since
)
2319 digestmap_set(reasons
, entry
->identity
, (char*)reason
);
2321 SMARTLIST_FOREACH_END(entry
);
2323 if (remove_dead_entry_guards())
2326 severity
= changed
? LOG_DEBUG
: LOG_INFO
;
2329 SMARTLIST_FOREACH_BEGIN(entry_guards
, entry_guard_t
*, entry
) {
2330 const char *reason
= digestmap_get(reasons
, entry
->identity
);
2331 log_info(LD_CIRC
, "Summary: Entry '%s' is %s, %s%s%s, and %s.",
2333 entry
->unreachable_since
? "unreachable" : "reachable",
2334 entry
->bad_since
? "unusable" : "usable",
2336 reason
? reason
: "",
2337 entry_is_live(entry
, 0, 1, 0) ? "live" : "not live");
2338 } SMARTLIST_FOREACH_END(entry
);
2339 log_info(LD_CIRC
, " (%d/%d entry guards are usable/new)",
2340 num_live_entry_guards(), smartlist_len(entry_guards
));
2341 log_entry_guards(LOG_INFO
);
2342 entry_guards_changed();
2345 digestmap_free(reasons
, NULL
);
2348 /** Called when a connection to an OR with the identity digest <b>digest</b>
2349 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2350 * If the OR is an entry, change that entry's up/down status.
2351 * Return 0 normally, or -1 if we want to tear down the new connection.
2353 * If <b>mark_relay_status</b>, also call router_set_status() on this
2356 * XXX022 change succeeded and mark_relay_status into 'int flags'.
2359 entry_guard_register_connect_status(const char *digest
, int succeeded
,
2360 int mark_relay_status
, time_t now
)
2363 int refuse_conn
= 0;
2364 int first_contact
= 0;
2365 entry_guard_t
*entry
= NULL
;
2367 char buf
[HEX_DIGEST_LEN
+1];
2372 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2374 if (!memcmp(e
->identity
, digest
, DIGEST_LEN
)) {
2384 base16_encode(buf
, sizeof(buf
), entry
->identity
, DIGEST_LEN
);
2387 if (entry
->unreachable_since
) {
2388 log_info(LD_CIRC
, "Entry guard '%s' (%s) is now reachable again. Good.",
2389 entry
->nickname
, buf
);
2390 entry
->can_retry
= 0;
2391 entry
->unreachable_since
= 0;
2392 entry
->last_attempted
= now
;
2393 control_event_guard(entry
->nickname
, entry
->identity
, "UP");
2396 if (!entry
->made_contact
) {
2397 entry
->made_contact
= 1;
2398 first_contact
= changed
= 1;
2400 } else { /* ! succeeded */
2401 if (!entry
->made_contact
) {
2402 /* We've never connected to this one. */
2404 "Connection to never-contacted entry guard '%s' (%s) failed. "
2405 "Removing from the list. %d/%d entry guards usable/new.",
2406 entry
->nickname
, buf
,
2407 num_live_entry_guards()-1, smartlist_len(entry_guards
)-1);
2408 entry_guard_free(entry
);
2409 smartlist_del_keeporder(entry_guards
, idx
);
2410 log_entry_guards(LOG_INFO
);
2412 } else if (!entry
->unreachable_since
) {
2413 log_info(LD_CIRC
, "Unable to connect to entry guard '%s' (%s). "
2414 "Marking as unreachable.", entry
->nickname
, buf
);
2415 entry
->unreachable_since
= entry
->last_attempted
= now
;
2416 control_event_guard(entry
->nickname
, entry
->identity
, "DOWN");
2418 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2420 char tbuf
[ISO_TIME_LEN
+1];
2421 format_iso_time(tbuf
, entry
->unreachable_since
);
2422 log_debug(LD_CIRC
, "Failed to connect to unreachable entry guard "
2423 "'%s' (%s). It has been unreachable since %s.",
2424 entry
->nickname
, buf
, tbuf
);
2425 entry
->last_attempted
= now
;
2426 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2430 /* if the caller asked us to, also update the is_running flags for this
2432 if (mark_relay_status
)
2433 router_set_status(digest
, succeeded
);
2435 if (first_contact
) {
2436 /* We've just added a new long-term entry guard. Perhaps the network just
2437 * came back? We should give our earlier entries another try too,
2438 * and close this connection so we don't use it before we've given
2439 * the others a shot. */
2440 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2443 if (e
->made_contact
) {
2444 routerinfo_t
*r
= entry_is_live(e
, 0, 1, 1);
2445 if (r
&& e
->unreachable_since
) {
2453 "Connected to new entry guard '%s' (%s). Marking earlier "
2454 "entry guards up. %d/%d entry guards usable/new.",
2455 entry
->nickname
, buf
,
2456 num_live_entry_guards(), smartlist_len(entry_guards
));
2457 log_entry_guards(LOG_INFO
);
2463 entry_guards_changed();
2464 return refuse_conn
? -1 : 0;
2467 /** When we try to choose an entry guard, should we parse and add
2468 * config's EntryNodes first? */
2469 static int should_add_entry_nodes
= 0;
2471 /** Called when the value of EntryNodes changes in our configuration. */
2473 entry_nodes_should_be_added(void)
2475 log_info(LD_CIRC
, "New EntryNodes config option detected. Will use.");
2476 should_add_entry_nodes
= 1;
2479 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2480 * of guard nodes, at the front. */
2482 entry_guards_prepend_from_config(void)
2484 or_options_t
*options
= get_options();
2485 smartlist_t
*entry_routers
, *entry_fps
;
2486 smartlist_t
*old_entry_guards_on_list
, *old_entry_guards_not_on_list
;
2487 tor_assert(entry_guards
);
2489 should_add_entry_nodes
= 0;
2491 if (!options
->EntryNodes
) {
2492 /* It's possible that a controller set EntryNodes, thus making
2493 * should_add_entry_nodes set, then cleared it again, all before the
2494 * call to choose_random_entry() that triggered us. If so, just return.
2499 if (options
->EntryNodes
) {
2500 char *string
= routerset_to_string(options
->EntryNodes
);
2501 log_info(LD_CIRC
,"Adding configured EntryNodes '%s'.", string
);
2505 entry_routers
= smartlist_create();
2506 entry_fps
= smartlist_create();
2507 old_entry_guards_on_list
= smartlist_create();
2508 old_entry_guards_not_on_list
= smartlist_create();
2510 /* Split entry guards into those on the list and those not. */
2512 /* XXXX022 Now that we allow countries and IP ranges in EntryNodes, this is
2513 * potentially an enormous list. For now, we disable such values for
2514 * EntryNodes in options_validate(); really, this wants a better solution.
2515 * Perhaps we should do this calculation once whenever the list of routers
2516 * changes or the entrynodes setting changes.
2518 routerset_get_all_routers(entry_routers
, options
->EntryNodes
, 0);
2519 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
,
2520 smartlist_add(entry_fps
,ri
->cache_info
.identity_digest
));
2521 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2522 if (smartlist_digest_isin(entry_fps
, e
->identity
))
2523 smartlist_add(old_entry_guards_on_list
, e
);
2525 smartlist_add(old_entry_guards_not_on_list
, e
);
2528 /* Remove all currently configured entry guards from entry_routers. */
2529 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2530 if (is_an_entry_guard(ri
->cache_info
.identity_digest
)) {
2531 SMARTLIST_DEL_CURRENT(entry_routers
, ri
);
2535 /* Now build the new entry_guards list. */
2536 smartlist_clear(entry_guards
);
2537 /* First, the previously configured guards that are in EntryNodes. */
2538 smartlist_add_all(entry_guards
, old_entry_guards_on_list
);
2539 /* Next, the rest of EntryNodes */
2540 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2541 add_an_entry_guard(ri
, 0);
2543 /* Finally, the remaining EntryNodes, unless we're strict */
2544 if (options
->StrictEntryNodes
) {
2545 SMARTLIST_FOREACH(old_entry_guards_not_on_list
, entry_guard_t
*, e
,
2546 entry_guard_free(e
));
2548 smartlist_add_all(entry_guards
, old_entry_guards_not_on_list
);
2551 smartlist_free(entry_routers
);
2552 smartlist_free(entry_fps
);
2553 smartlist_free(old_entry_guards_on_list
);
2554 smartlist_free(old_entry_guards_not_on_list
);
2555 entry_guards_changed();
2558 /** Return 1 if we're fine adding arbitrary routers out of the
2559 * directory to our entry guard list. Else return 0. */
2561 entry_list_can_grow(or_options_t
*options
)
2563 if (options
->StrictEntryNodes
)
2565 if (options
->UseBridges
)
2570 /** Pick a live (up and listed) entry guard from entry_guards. If
2571 * <b>state</b> is non-NULL, this is for a specific circuit --
2572 * make sure not to pick this circuit's exit or any node in the
2573 * exit's family. If <b>state</b> is NULL, we're looking for a random
2574 * guard (likely a bridge). */
2576 choose_random_entry(cpath_build_state_t
*state
)
2578 or_options_t
*options
= get_options();
2579 smartlist_t
*live_entry_guards
= smartlist_create();
2580 smartlist_t
*exit_family
= smartlist_create();
2581 routerinfo_t
*chosen_exit
= state
?build_state_get_exit_router(state
) : NULL
;
2582 routerinfo_t
*r
= NULL
;
2583 int need_uptime
= state
? state
->need_uptime
: 0;
2584 int need_capacity
= state
? state
->need_capacity
: 0;
2585 int consider_exit_family
= 0;
2588 smartlist_add(exit_family
, chosen_exit
);
2589 routerlist_add_family(exit_family
, chosen_exit
);
2590 consider_exit_family
= 1;
2594 entry_guards
= smartlist_create();
2596 if (should_add_entry_nodes
)
2597 entry_guards_prepend_from_config();
2599 if (entry_list_can_grow(options
) &&
2601 smartlist_len(entry_guards
) < options
->NumEntryGuards
))
2602 pick_entry_guards();
2605 smartlist_clear(live_entry_guards
);
2606 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2608 r
= entry_is_live(entry
, need_uptime
, need_capacity
, 0);
2609 if (r
&& (!consider_exit_family
|| !smartlist_isin(exit_family
, r
))) {
2610 smartlist_add(live_entry_guards
, r
);
2611 if (!entry
->made_contact
) {
2612 /* Always start with the first not-yet-contacted entry
2613 * guard. Otherwise we might add several new ones, pick
2614 * the second new one, and now we've expanded our entry
2615 * guard list without needing to. */
2616 goto choose_and_finish
;
2618 if (smartlist_len(live_entry_guards
) >= options
->NumEntryGuards
)
2619 break; /* we have enough */
2623 /* Try to have at least 2 choices available. This way we don't
2624 * get stuck with a single live-but-crummy entry and just keep
2626 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2627 if (smartlist_len(live_entry_guards
) < 2) {
2628 if (entry_list_can_grow(options
)) {
2629 /* still no? try adding a new entry then */
2630 /* XXX if guard doesn't imply fast and stable, then we need
2631 * to tell add_an_entry_guard below what we want, or it might
2632 * be a long time til we get it. -RD */
2633 r
= add_an_entry_guard(NULL
, 0);
2635 entry_guards_changed();
2636 /* XXX we start over here in case the new node we added shares
2637 * a family with our exit node. There's a chance that we'll just
2638 * load up on entry guards here, if the network we're using is
2639 * one big family. Perhaps we should teach add_an_entry_guard()
2640 * to understand nodes-to-avoid-if-possible? -RD */
2644 if (!r
&& need_uptime
) {
2645 need_uptime
= 0; /* try without that requirement */
2648 if (!r
&& need_capacity
) {
2649 /* still no? last attempt, try without requiring capacity */
2653 if (!r
&& !entry_list_can_grow(options
) && consider_exit_family
) {
2654 /* still no? if we're using bridges or have strictentrynodes
2655 * set, and our chosen exit is in the same family as all our
2656 * bridges/entry guards, then be flexible about families. */
2657 consider_exit_family
= 0;
2660 /* live_entry_guards may be empty below. Oh well, we tried. */
2664 if (entry_list_can_grow(options
)) {
2665 /* We choose uniformly at random here, because choose_good_entry_server()
2666 * already weights its choices by bandwidth, so we don't want to
2667 * *double*-weight our guard selection. */
2668 r
= smartlist_choose(live_entry_guards
);
2670 /* We need to weight by bandwidth, because our bridges or entryguards
2671 * were not already selected proportional to their bandwidth. */
2672 r
= routerlist_sl_choose_by_bandwidth(live_entry_guards
, WEIGHT_FOR_GUARD
);
2674 smartlist_free(live_entry_guards
);
2675 smartlist_free(exit_family
);
2679 /** Parse <b>state</b> and learn about the entry guards it describes.
2680 * If <b>set</b> is true, and there are no errors, replace the global
2681 * entry_list with what we find.
2682 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2683 * describing the error, and return -1.
2686 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
2688 entry_guard_t
*node
= NULL
;
2689 smartlist_t
*new_entry_guards
= smartlist_create();
2690 config_line_t
*line
;
2691 time_t now
= time(NULL
);
2692 const char *state_version
= state
->TorVersion
;
2693 digestmap_t
*added_by
= digestmap_new();
2696 for (line
= state
->EntryGuards
; line
; line
= line
->next
) {
2697 if (!strcasecmp(line
->key
, "EntryGuard")) {
2698 smartlist_t
*args
= smartlist_create();
2699 node
= tor_malloc_zero(sizeof(entry_guard_t
));
2700 /* all entry guards on disk have been contacted */
2701 node
->made_contact
= 1;
2702 smartlist_add(new_entry_guards
, node
);
2703 smartlist_split_string(args
, line
->value
, " ",
2704 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2705 if (smartlist_len(args
)<2) {
2706 *msg
= tor_strdup("Unable to parse entry nodes: "
2707 "Too few arguments to EntryGuard");
2708 } else if (!is_legal_nickname(smartlist_get(args
,0))) {
2709 *msg
= tor_strdup("Unable to parse entry nodes: "
2710 "Bad nickname for EntryGuard");
2712 strlcpy(node
->nickname
, smartlist_get(args
,0), MAX_NICKNAME_LEN
+1);
2713 if (base16_decode(node
->identity
, DIGEST_LEN
, smartlist_get(args
,1),
2714 strlen(smartlist_get(args
,1)))<0) {
2715 *msg
= tor_strdup("Unable to parse entry nodes: "
2716 "Bad hex digest for EntryGuard");
2719 SMARTLIST_FOREACH(args
, char*, cp
, tor_free(cp
));
2720 smartlist_free(args
);
2723 } else if (!strcasecmp(line
->key
, "EntryGuardDownSince") ||
2724 !strcasecmp(line
->key
, "EntryGuardUnlistedSince")) {
2726 time_t last_try
= 0;
2728 *msg
= tor_strdup("Unable to parse entry nodes: "
2729 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2732 if (parse_iso_time(line
->value
, &when
)<0) {
2733 *msg
= tor_strdup("Unable to parse entry nodes: "
2734 "Bad time in EntryGuardDownSince/UnlistedSince");
2738 /* It's a bad idea to believe info in the future: you can wind
2739 * up with timeouts that aren't allowed to happen for years. */
2742 if (strlen(line
->value
) >= ISO_TIME_LEN
+ISO_TIME_LEN
+1) {
2743 /* ignore failure */
2744 (void) parse_iso_time(line
->value
+ISO_TIME_LEN
+1, &last_try
);
2746 if (!strcasecmp(line
->key
, "EntryGuardDownSince")) {
2747 node
->unreachable_since
= when
;
2748 node
->last_attempted
= last_try
;
2750 node
->bad_since
= when
;
2752 } else if (!strcasecmp(line
->key
, "EntryGuardAddedBy")) {
2754 /* format is digest version date */
2755 if (strlen(line
->value
) < HEX_DIGEST_LEN
+1+1+1+ISO_TIME_LEN
) {
2756 log_warn(LD_BUG
, "EntryGuardAddedBy line is not long enough.");
2759 if (base16_decode(d
, sizeof(d
), line
->value
, HEX_DIGEST_LEN
)<0 ||
2760 line
->value
[HEX_DIGEST_LEN
] != ' ') {
2761 log_warn(LD_BUG
, "EntryGuardAddedBy line %s does not begin with "
2762 "hex digest", escaped(line
->value
));
2765 digestmap_set(added_by
, d
, tor_strdup(line
->value
+HEX_DIGEST_LEN
+1));
2767 log_warn(LD_BUG
, "Unexpected key %s", line
->key
);
2771 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2774 char *val
= digestmap_get(added_by
, e
->identity
);
2775 if (val
&& (sp
= strchr(val
, ' '))) {
2778 if (parse_iso_time(sp
, &when
)<0) {
2779 log_warn(LD_BUG
, "Can't read time %s in EntryGuardAddedBy", sp
);
2781 e
->chosen_by_version
= tor_strdup(val
);
2782 e
->chosen_on_date
= when
;
2785 if (state_version
) {
2786 e
->chosen_by_version
= tor_strdup(state_version
);
2787 e
->chosen_on_date
= time(NULL
) - crypto_rand_int(3600*24*30);
2793 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2794 entry_guard_free(e
));
2795 smartlist_free(new_entry_guards
);
2796 } else { /* !err && set */
2798 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2799 entry_guard_free(e
));
2800 smartlist_free(entry_guards
);
2802 entry_guards
= new_entry_guards
;
2803 entry_guards_dirty
= 0;
2804 /* XXX022 hand new_entry_guards to this func, and move it up a
2805 * few lines, so we don't have to re-dirty it */
2806 if (remove_obsolete_entry_guards())
2807 entry_guards_dirty
= 1;
2809 digestmap_free(added_by
, _tor_free
);
2810 return *msg
? -1 : 0;
2813 /** Our list of entry guards has changed, or some element of one
2814 * of our entry guards has changed. Write the changes to disk within
2815 * the next few minutes.
2818 entry_guards_changed(void)
2821 entry_guards_dirty
= 1;
2823 /* or_state_save() will call entry_guards_update_state(). */
2824 when
= get_options()->AvoidDiskWrites
? time(NULL
) + 3600 : time(NULL
)+600;
2825 or_state_mark_dirty(get_or_state(), when
);
2828 /** If the entry guard info has not changed, do nothing and return.
2829 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2830 * a new one out of the global entry_guards list, and then mark
2831 * <b>state</b> dirty so it will get saved to disk.
2834 entry_guards_update_state(or_state_t
*state
)
2836 config_line_t
**next
, *line
;
2837 if (! entry_guards_dirty
)
2840 config_free_lines(state
->EntryGuards
);
2841 next
= &state
->EntryGuards
;
2844 entry_guards
= smartlist_create();
2845 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2847 char dbuf
[HEX_DIGEST_LEN
+1];
2848 if (!e
->made_contact
)
2849 continue; /* don't write this one to disk */
2850 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2851 line
->key
= tor_strdup("EntryGuard");
2852 line
->value
= tor_malloc(HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2);
2853 base16_encode(dbuf
, sizeof(dbuf
), e
->identity
, DIGEST_LEN
);
2854 tor_snprintf(line
->value
,HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2,
2855 "%s %s", e
->nickname
, dbuf
);
2856 next
= &(line
->next
);
2857 if (e
->unreachable_since
) {
2858 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2859 line
->key
= tor_strdup("EntryGuardDownSince");
2860 line
->value
= tor_malloc(ISO_TIME_LEN
+1+ISO_TIME_LEN
+1);
2861 format_iso_time(line
->value
, e
->unreachable_since
);
2862 if (e
->last_attempted
) {
2863 line
->value
[ISO_TIME_LEN
] = ' ';
2864 format_iso_time(line
->value
+ISO_TIME_LEN
+1, e
->last_attempted
);
2866 next
= &(line
->next
);
2869 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2870 line
->key
= tor_strdup("EntryGuardUnlistedSince");
2871 line
->value
= tor_malloc(ISO_TIME_LEN
+1);
2872 format_iso_time(line
->value
, e
->bad_since
);
2873 next
= &(line
->next
);
2875 if (e
->chosen_on_date
&& e
->chosen_by_version
&&
2876 !strchr(e
->chosen_by_version
, ' ')) {
2877 char d
[HEX_DIGEST_LEN
+1];
2878 char t
[ISO_TIME_LEN
+1];
2880 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2881 line
->key
= tor_strdup("EntryGuardAddedBy");
2882 val_len
= (HEX_DIGEST_LEN
+1+strlen(e
->chosen_by_version
)
2884 line
->value
= tor_malloc(val_len
);
2885 base16_encode(d
, sizeof(d
), e
->identity
, DIGEST_LEN
);
2886 format_iso_time(t
, e
->chosen_on_date
);
2887 tor_snprintf(line
->value
, val_len
, "%s %s %s",
2888 d
, e
->chosen_by_version
, t
);
2889 next
= &(line
->next
);
2892 if (!get_options()->AvoidDiskWrites
)
2893 or_state_mark_dirty(get_or_state(), 0);
2894 entry_guards_dirty
= 0;
2897 /** If <b>question</b> is the string "entry-guards", then dump
2898 * to *<b>answer</b> a newly allocated string describing all of
2899 * the nodes in the global entry_guards list. See control-spec.txt
2901 * For backward compatibility, we also handle the string "helper-nodes".
2904 getinfo_helper_entry_guards(control_connection_t
*conn
,
2905 const char *question
, char **answer
)
2907 int use_long_names
= conn
->use_long_names
;
2909 if (!strcmp(question
,"entry-guards") ||
2910 !strcmp(question
,"helper-nodes")) {
2911 smartlist_t
*sl
= smartlist_create();
2912 char tbuf
[ISO_TIME_LEN
+1];
2913 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
2915 entry_guards
= smartlist_create();
2916 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2918 size_t len
= MAX_VERBOSE_NICKNAME_LEN
+ISO_TIME_LEN
+32;
2919 char *c
= tor_malloc(len
);
2920 const char *status
= NULL
;
2922 if (!e
->made_contact
) {
2923 status
= "never-connected";
2924 } else if (e
->bad_since
) {
2925 when
= e
->bad_since
;
2926 status
= "unusable";
2930 if (use_long_names
) {
2931 routerinfo_t
*ri
= router_get_by_digest(e
->identity
);
2933 router_get_verbose_nickname(nbuf
, ri
);
2936 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
2937 /* e->nickname field is not very reliable if we don't know about
2938 * this router any longer; don't include it. */
2941 base16_encode(nbuf
, sizeof(nbuf
), e
->identity
, DIGEST_LEN
);
2944 format_iso_time(tbuf
, when
);
2945 tor_snprintf(c
, len
, "%s %s %s\n", nbuf
, status
, tbuf
);
2947 tor_snprintf(c
, len
, "%s %s\n", nbuf
, status
);
2949 smartlist_add(sl
, c
);
2951 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2952 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2958 /** Information about a configured bridge. Currently this just matches the
2959 * ones in the torrc file, but one day we may be able to learn about new
2960 * bridges on our own, and remember them in the state file. */
2962 /** Address of the bridge. */
2964 /** TLS port for the bridge. */
2966 /** Expected identity digest, or all zero bytes if we don't know what the
2967 * digest should be. */
2968 char identity
[DIGEST_LEN
];
2969 /** When should we next try to fetch a descriptor for this bridge? */
2970 download_status_t fetch_status
;
2973 /** A list of configured bridges. Whenever we actually get a descriptor
2974 * for one, we add it as an entry guard. */
2975 static smartlist_t
*bridge_list
= NULL
;
2977 /** Initialize the bridge list to empty, creating it if needed. */
2979 clear_bridge_list(void)
2982 bridge_list
= smartlist_create();
2983 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, b
, tor_free(b
));
2984 smartlist_clear(bridge_list
);
2987 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2988 * (either by comparing keys if possible, else by comparing addr/port).
2989 * Else return NULL. */
2990 static bridge_info_t
*
2991 routerinfo_get_configured_bridge(routerinfo_t
*ri
)
2995 SMARTLIST_FOREACH_BEGIN(bridge_list
, bridge_info_t
*, bridge
)
2997 if (tor_digest_is_zero(bridge
->identity
) &&
2998 tor_addr_eq_ipv4h(&bridge
->addr
, ri
->addr
) &&
2999 bridge
->port
== ri
->or_port
)
3001 if (!memcmp(bridge
->identity
, ri
->cache_info
.identity_digest
,
3005 SMARTLIST_FOREACH_END(bridge
);
3009 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
3011 routerinfo_is_a_configured_bridge(routerinfo_t
*ri
)
3013 return routerinfo_get_configured_bridge(ri
) ? 1 : 0;
3016 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
3017 * is set, it tells us the identity key too. */
3019 bridge_add_from_config(const tor_addr_t
*addr
, uint16_t port
, char *digest
)
3021 bridge_info_t
*b
= tor_malloc_zero(sizeof(bridge_info_t
));
3022 tor_addr_copy(&b
->addr
, addr
);
3025 memcpy(b
->identity
, digest
, DIGEST_LEN
);
3026 b
->fetch_status
.schedule
= DL_SCHED_BRIDGE
;
3028 bridge_list
= smartlist_create();
3029 smartlist_add(bridge_list
, b
);
3032 /** If <b>digest</b> is one of our known bridges, return it. */
3033 static bridge_info_t
*
3034 find_bridge_by_digest(const char *digest
)
3036 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
3038 if (!memcmp(bridge
->identity
, digest
, DIGEST_LEN
))
3044 /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
3045 * is a helpful string describing this bridge. */
3047 launch_direct_bridge_descriptor_fetch(bridge_info_t
*bridge
)
3051 if (connection_get_by_type_addr_port_purpose(
3052 CONN_TYPE_DIR
, &bridge
->addr
, bridge
->port
,
3053 DIR_PURPOSE_FETCH_SERVERDESC
))
3054 return; /* it's already on the way */
3056 address
= tor_dup_addr(&bridge
->addr
);
3057 directory_initiate_command(address
, &bridge
->addr
,
3059 0, /* does not matter */
3060 1, bridge
->identity
,
3061 DIR_PURPOSE_FETCH_SERVERDESC
,
3062 ROUTER_PURPOSE_BRIDGE
,
3063 0, "authority.z", NULL
, 0, 0);
3067 /** Fetching the bridge descriptor from the bridge authority returned a
3068 * "not found". Fall back to trying a direct fetch. */
3070 retry_bridge_descriptor_fetch_directly(const char *digest
)
3072 bridge_info_t
*bridge
= find_bridge_by_digest(digest
);
3074 return; /* not found? oh well. */
3076 launch_direct_bridge_descriptor_fetch(bridge
);
3079 /** For each bridge in our list for which we don't currently have a
3080 * descriptor, fetch a new copy of its descriptor -- either directly
3081 * from the bridge or via a bridge authority. */
3083 fetch_bridge_descriptors(time_t now
)
3085 or_options_t
*options
= get_options();
3086 int num_bridge_auths
= get_n_authorities(BRIDGE_AUTHORITY
);
3087 int ask_bridge_directly
;
3088 int can_use_bridge_authority
;
3093 SMARTLIST_FOREACH_BEGIN(bridge_list
, bridge_info_t
*, bridge
)
3095 if (!download_status_is_ready(&bridge
->fetch_status
, now
,
3096 IMPOSSIBLE_TO_DOWNLOAD
))
3097 continue; /* don't bother, no need to retry yet */
3099 /* schedule another fetch as if this one will fail, in case it does */
3100 download_status_failed(&bridge
->fetch_status
, 0);
3102 can_use_bridge_authority
= !tor_digest_is_zero(bridge
->identity
) &&
3104 ask_bridge_directly
= !can_use_bridge_authority
||
3105 !options
->UpdateBridgesFromAuthority
;
3106 log_debug(LD_DIR
, "ask_bridge_directly=%d (%d, %d, %d)",
3107 ask_bridge_directly
, tor_digest_is_zero(bridge
->identity
),
3108 !options
->UpdateBridgesFromAuthority
, !num_bridge_auths
);
3110 if (ask_bridge_directly
&&
3111 !fascist_firewall_allows_address_or(&bridge
->addr
, bridge
->port
)) {
3112 log_notice(LD_DIR
, "Bridge at '%s:%d' isn't reachable by our "
3113 "firewall policy. %s.", fmt_addr(&bridge
->addr
),
3115 can_use_bridge_authority
?
3116 "Asking bridge authority instead" : "Skipping");
3117 if (can_use_bridge_authority
)
3118 ask_bridge_directly
= 0;
3123 if (ask_bridge_directly
) {
3124 /* we need to ask the bridge itself for its descriptor. */
3125 launch_direct_bridge_descriptor_fetch(bridge
);
3127 /* We have a digest and we want to ask an authority. We could
3128 * combine all the requests into one, but that may give more
3129 * hints to the bridge authority than we want to give. */
3130 char resource
[10 + HEX_DIGEST_LEN
];
3131 memcpy(resource
, "fp/", 3);
3132 base16_encode(resource
+3, HEX_DIGEST_LEN
+1,
3133 bridge
->identity
, DIGEST_LEN
);
3134 memcpy(resource
+3+HEX_DIGEST_LEN
, ".z", 3);
3135 log_info(LD_DIR
, "Fetching bridge info '%s' from bridge authority.",
3137 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
3138 ROUTER_PURPOSE_BRIDGE
, resource
, 0);
3141 SMARTLIST_FOREACH_END(bridge
);
3144 /** We just learned a descriptor for a bridge. See if that
3145 * digest is in our entry guard list, and add it if not. */
3147 learned_bridge_descriptor(routerinfo_t
*ri
, int from_cache
)
3150 tor_assert(ri
->purpose
== ROUTER_PURPOSE_BRIDGE
);
3151 if (get_options()->UseBridges
) {
3152 int first
= !any_bridge_descriptors_known();
3153 bridge_info_t
*bridge
= routerinfo_get_configured_bridge(ri
);
3154 time_t now
= time(NULL
);
3157 if (bridge
) { /* if we actually want to use this one */
3158 /* it's here; schedule its re-fetch for a long time from now. */
3160 download_status_reset(&bridge
->fetch_status
);
3162 add_an_entry_guard(ri
, 1);
3163 log_notice(LD_DIR
, "new bridge descriptor '%s' (%s)", ri
->nickname
,
3164 from_cache
? "cached" : "fresh");
3166 routerlist_retry_directory_downloads(now
);
3171 /** Return 1 if any of our entry guards have descriptors that
3172 * are marked with purpose 'bridge' and are running. Else return 0.
3174 * We use this function to decide if we're ready to start building
3175 * circuits through our bridges, or if we need to wait until the
3176 * directory "server/authority" requests finish. */
3178 any_bridge_descriptors_known(void)
3180 tor_assert(get_options()->UseBridges
);
3181 return choose_random_entry(NULL
)!=NULL
? 1 : 0;
3184 /** Return 1 if there are any directory conns fetching bridge descriptors
3185 * that aren't marked for close. We use this to guess if we should tell
3186 * the controller that we have a problem. */
3188 any_pending_bridge_descriptor_fetches(void)
3190 smartlist_t
*conns
= get_connection_array();
3191 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3193 if (conn
->type
== CONN_TYPE_DIR
&&
3194 conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
3195 TO_DIR_CONN(conn
)->router_purpose
== ROUTER_PURPOSE_BRIDGE
&&
3196 !conn
->marked_for_close
&&
3197 conn
->linked
&& !conn
->linked_conn
->marked_for_close
) {
3198 log_debug(LD_DIR
, "found one: %s", conn
->address
);
3205 /** Return 1 if we have at least one descriptor for a bridge and
3206 * all descriptors we know are down. Else return 0. If <b>act</b> is
3207 * 1, then mark the down bridges up; else just observe and report. */
3209 bridges_retry_helper(int act
)
3213 int any_running
= 0;
3215 entry_guards
= smartlist_create();
3216 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3218 ri
= router_get_by_digest(e
->identity
);
3219 if (ri
&& ri
->purpose
== ROUTER_PURPOSE_BRIDGE
) {
3222 any_running
= 1; /* some bridge is both known and running */
3223 else if (act
) { /* mark it for retry */
3230 log_debug(LD_DIR
, "any_known %d, any_running %d", any_known
, any_running
);
3231 return any_known
&& !any_running
;
3234 /** Do we know any descriptors for our bridges, and are they all
3237 bridges_known_but_down(void)
3239 return bridges_retry_helper(0);
3242 /** Mark all down known bridges up. */
3244 bridges_retry_all(void)
3246 bridges_retry_helper(1);
3249 /** Release all storage held by the list of entry guards and related
3250 * memory structs. */
3252 entry_guards_free_all(void)
3255 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3256 entry_guard_free(e
));
3257 smartlist_free(entry_guards
);
3258 entry_guards
= NULL
;
3260 clear_bridge_list();
3261 smartlist_free(bridge_list
);