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-2009, 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);
61 static time_t start_of_month(time_t when
);
63 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
64 * and with the high bit specified by conn-\>circ_id_type, until we get
65 * a circ_id that is not in use by any other circuit on that conn.
67 * Return it, or 0 if can't get a unique circ_id.
70 get_unique_circ_id_by_conn(or_connection_t
*conn
)
72 circid_t test_circ_id
;
77 if (conn
->circ_id_type
== CIRC_ID_TYPE_NEITHER
) {
78 log_warn(LD_BUG
, "Trying to pick a circuit ID for a connection from "
79 "a client with no identity.");
82 high_bit
= (conn
->circ_id_type
== CIRC_ID_TYPE_HIGHER
) ? 1<<15 : 0;
84 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
85 * circID such that (high_bit|test_circ_id) is not already used. */
86 test_circ_id
= conn
->next_circ_id
++;
87 if (test_circ_id
== 0 || test_circ_id
>= 1<<15) {
89 conn
->next_circ_id
= 2;
91 if (++attempts
> 1<<15) {
92 /* Make sure we don't loop forever if all circ_id's are used. This
93 * matters because it's an external DoS opportunity.
95 log_warn(LD_CIRC
,"No unused circ IDs. Failing.");
98 test_circ_id
|= high_bit
;
99 } while (circuit_id_in_use_on_orconn(test_circ_id
, conn
));
103 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
104 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
105 * list information about link status in a more verbose format using spaces.
106 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
107 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
111 circuit_list_path_impl(origin_circuit_t
*circ
, int verbose
, int verbose_names
)
114 smartlist_t
*elements
;
115 const char *states
[] = {"closed", "waiting for keys", "open"};
119 elements
= smartlist_create();
122 const char *nickname
= build_state_get_exit_nickname(circ
->build_state
);
123 tor_snprintf(buf
, sizeof(buf
), "%s%s circ (length %d%s%s):",
124 circ
->build_state
->is_internal
? "internal" : "exit",
125 circ
->build_state
->need_uptime
? " (high-uptime)" : "",
126 circ
->build_state
->desired_path_len
,
127 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" : ", exit ",
128 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" :
129 (nickname
?nickname
:"*unnamed*"));
130 smartlist_add(elements
, tor_strdup(buf
));
141 id
= hop
->extend_info
->identity_digest
;
142 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
144 if (!hop
->extend_info
)
147 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
148 if ((ri
= router_get_by_digest(id
))) {
149 router_get_verbose_nickname(elt
, ri
);
150 } else if ((rs
= router_get_consensus_status_by_id(id
))) {
151 routerstatus_get_verbose_nickname(elt
, rs
);
152 } else if (hop
->extend_info
->nickname
&&
153 is_legal_nickname(hop
->extend_info
->nickname
)) {
155 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
156 elt
[HEX_DIGEST_LEN
+1]= '~';
157 strlcpy(elt
+HEX_DIGEST_LEN
+2,
158 hop
->extend_info
->nickname
, MAX_NICKNAME_LEN
+1);
161 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
163 } else { /* ! verbose_names */
164 if ((ri
= router_get_by_digest(id
)) &&
166 elt
= tor_strdup(hop
->extend_info
->nickname
);
168 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
170 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
175 size_t len
= strlen(elt
)+2+strlen(states
[hop
->state
])+1;
176 char *v
= tor_malloc(len
);
177 tor_assert(hop
->state
<= 2);
178 tor_snprintf(v
,len
,"%s(%s)",elt
,states
[hop
->state
]);
179 smartlist_add(elements
, v
);
182 smartlist_add(elements
, elt
);
185 } while (hop
!= circ
->cpath
);
187 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
188 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
189 smartlist_free(elements
);
193 /** If <b>verbose</b> is false, allocate and return a comma-separated
194 * list of the currently built elements of circuit_t. If
195 * <b>verbose</b> is true, also list information about link status in
196 * a more verbose format using spaces.
199 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
201 return circuit_list_path_impl(circ
, verbose
, 0);
204 /** Allocate and return a comma-separated list of the currently built elements
205 * of circuit_t, giving each as a verbose nickname.
208 circuit_list_path_for_controller(origin_circuit_t
*circ
)
210 return circuit_list_path_impl(circ
, 0, 1);
213 /** Log, at severity <b>severity</b>, the nicknames of each router in
214 * circ's cpath. Also log the length of the cpath, and the intended
218 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
220 char *s
= circuit_list_path(circ
,1);
221 log(severity
,domain
,"%s",s
);
225 /** Tell the rep(utation)hist(ory) module about the status of the links
226 * in circ. Hops that have become OPEN are marked as successfully
227 * extended; the _first_ hop that isn't open (if any) is marked as
230 /* XXXX Someday we should learn from OR circuits too. */
232 circuit_rep_hist_note_result(origin_circuit_t
*circ
)
235 char *prev_digest
= NULL
;
236 routerinfo_t
*router
;
238 if (!hop
) /* circuit hasn't started building yet. */
240 if (server_mode(get_options())) {
241 routerinfo_t
*me
= router_get_my_routerinfo();
244 prev_digest
= me
->cache_info
.identity_digest
;
247 router
= router_get_by_digest(hop
->extend_info
->identity_digest
);
250 if (hop
->state
== CPATH_STATE_OPEN
)
251 rep_hist_note_extend_succeeded(prev_digest
,
252 router
->cache_info
.identity_digest
);
254 rep_hist_note_extend_failed(prev_digest
,
255 router
->cache_info
.identity_digest
);
259 prev_digest
= router
->cache_info
.identity_digest
;
264 } while (hop
!=circ
->cpath
);
267 /** Pick all the entries in our cpath. Stop and return 0 when we're
268 * happy, or return -1 if an error occurs. */
270 onion_populate_cpath(origin_circuit_t
*circ
)
274 r
= onion_extend_cpath(circ
);
276 log_info(LD_CIRC
,"Generating cpath hop failed.");
281 return 0; /* if r == 1 */
284 /** Create and return a new origin circuit. Initialize its purpose and
285 * build-state based on our arguments. The <b>flags</b> argument is a
286 * bitfield of CIRCLAUNCH_* flags. */
288 origin_circuit_init(uint8_t purpose
, int flags
)
290 /* sets circ->p_circ_id and circ->p_conn */
291 origin_circuit_t
*circ
= origin_circuit_new();
292 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OR_WAIT
);
293 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
294 circ
->build_state
->onehop_tunnel
=
295 ((flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) ? 1 : 0);
296 circ
->build_state
->need_uptime
=
297 ((flags
& CIRCLAUNCH_NEED_UPTIME
) ? 1 : 0);
298 circ
->build_state
->need_capacity
=
299 ((flags
& CIRCLAUNCH_NEED_CAPACITY
) ? 1 : 0);
300 circ
->build_state
->is_internal
=
301 ((flags
& CIRCLAUNCH_IS_INTERNAL
) ? 1 : 0);
302 circ
->_base
.purpose
= purpose
;
306 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
307 * is defined, then use that as your exit router, else choose a suitable
310 * Also launch a connection to the first OR in the chosen path, if
311 * it's not open already.
314 circuit_establish_circuit(uint8_t purpose
, extend_info_t
*exit
, int flags
)
316 origin_circuit_t
*circ
;
319 circ
= origin_circuit_init(purpose
, flags
);
321 if (onion_pick_cpath_exit(circ
, exit
) < 0 ||
322 onion_populate_cpath(circ
) < 0) {
323 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
327 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
329 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
330 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
336 /** Start establishing the first hop of our circuit. Figure out what
337 * OR we should connect to, and if necessary start the connection to
338 * it. If we're already connected, then send the 'create' cell.
339 * Return 0 for ok, -reason if circ should be marked-for-close. */
341 circuit_handle_first_hop(origin_circuit_t
*circ
)
343 crypt_path_t
*firsthop
;
344 or_connection_t
*n_conn
;
346 const char *msg
= NULL
;
347 int should_launch
= 0;
349 firsthop
= onion_next_hop_in_cpath(circ
->cpath
);
350 tor_assert(firsthop
);
351 tor_assert(firsthop
->extend_info
);
353 /* now see if we're already connected to the first OR in 'route' */
354 log_debug(LD_CIRC
,"Looking for firsthop '%s:%u'",
355 fmt_addr(&firsthop
->extend_info
->addr
),
356 firsthop
->extend_info
->port
);
358 n_conn
= connection_or_get_for_extend(firsthop
->extend_info
->identity_digest
,
359 &firsthop
->extend_info
->addr
,
364 /* not currently connected in a useful way. */
365 const char *name
= firsthop
->extend_info
->nickname
?
366 firsthop
->extend_info
->nickname
: fmt_addr(&firsthop
->extend_info
->addr
);
367 log_info(LD_CIRC
, "Next router is %s: %s ", safe_str(name
), msg
?msg
:"???");
368 circ
->_base
.n_hop
= extend_info_dup(firsthop
->extend_info
);
371 if (circ
->build_state
->onehop_tunnel
)
372 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR
, 0);
373 n_conn
= connection_or_connect(&firsthop
->extend_info
->addr
,
374 firsthop
->extend_info
->port
,
375 firsthop
->extend_info
->identity_digest
);
376 if (!n_conn
) { /* connect failed, forget the whole thing */
377 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
378 return -END_CIRC_REASON_CONNECTFAILED
;
382 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
383 /* return success. The onion/circuit/etc will be taken care of
384 * automatically (may already have been) whenever n_conn reaches
385 * OR_CONN_STATE_OPEN.
388 } else { /* it's already open. use it. */
389 tor_assert(!circ
->_base
.n_hop
);
390 circ
->_base
.n_conn
= n_conn
;
391 log_debug(LD_CIRC
,"Conn open. Delivering first onion skin.");
392 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
393 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
400 /** Find any circuits that are waiting on <b>or_conn</b> to become
401 * open and get them to send their create cells forward.
403 * Status is 1 if connect succeeded, or 0 if connect failed.
406 circuit_n_conn_done(or_connection_t
*or_conn
, int status
)
408 smartlist_t
*pending_circs
;
411 log_debug(LD_CIRC
,"or_conn to %s/%s, status=%d",
412 or_conn
->nickname
? or_conn
->nickname
: "NULL",
413 or_conn
->_base
.address
, status
);
415 pending_circs
= smartlist_create();
416 circuit_get_all_pending_on_or_conn(pending_circs
, or_conn
);
418 SMARTLIST_FOREACH_BEGIN(pending_circs
, circuit_t
*, circ
)
420 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
421 * leaving them in in case it's possible for the status of a circuit to
422 * change as we're going down the list. */
423 if (circ
->marked_for_close
|| circ
->n_conn
|| !circ
->n_hop
||
424 circ
->state
!= CIRCUIT_STATE_OR_WAIT
)
427 if (tor_digest_is_zero(circ
->n_hop
->identity_digest
)) {
428 /* Look at addr/port. This is an unkeyed connection. */
429 if (!tor_addr_eq(&circ
->n_hop
->addr
, &or_conn
->_base
.addr
) ||
430 circ
->n_hop
->port
!= or_conn
->_base
.port
)
433 /* We expected a key. See if it's the right one. */
434 if (memcmp(or_conn
->identity_digest
,
435 circ
->n_hop
->identity_digest
, DIGEST_LEN
))
438 if (!status
) { /* or_conn failed; close circ */
439 log_info(LD_CIRC
,"or_conn failed. Closing circ.");
440 circuit_mark_for_close(circ
, END_CIRC_REASON_OR_CONN_CLOSED
);
443 log_debug(LD_CIRC
, "Found circ, sending create cell.");
444 /* circuit_deliver_create_cell will set n_circ_id and add us to
445 * orconn_circuid_circuit_map, so we don't need to call
446 * set_circid_orconn here. */
447 circ
->n_conn
= or_conn
;
448 extend_info_free(circ
->n_hop
);
451 if (CIRCUIT_IS_ORIGIN(circ
)) {
453 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
455 "send_next_onion_skin failed; circuit marked for closing.");
456 circuit_mark_for_close(circ
, -err_reason
);
458 /* XXX could this be bad, eg if next_onion_skin failed because conn
462 /* pull the create cell out of circ->onionskin, and send it */
463 tor_assert(circ
->n_conn_onionskin
);
464 if (circuit_deliver_create_cell(circ
,CELL_CREATE
,
465 circ
->n_conn_onionskin
)<0) {
466 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
469 tor_free(circ
->n_conn_onionskin
);
470 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
473 SMARTLIST_FOREACH_END(circ
);
475 smartlist_free(pending_circs
);
478 /** Find a new circid that isn't currently in use on the circ->n_conn
480 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
481 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
483 * Return -1 if we failed to find a suitable circid, else return 0.
486 circuit_deliver_create_cell(circuit_t
*circ
, uint8_t cell_type
,
493 tor_assert(circ
->n_conn
);
495 tor_assert(cell_type
== CELL_CREATE
|| cell_type
== CELL_CREATE_FAST
);
497 id
= get_unique_circ_id_by_conn(circ
->n_conn
);
499 log_warn(LD_CIRC
,"failed to get unique circID.");
502 log_debug(LD_CIRC
,"Chosen circID %u.", id
);
503 circuit_set_n_circid_orconn(circ
, id
, circ
->n_conn
);
505 memset(&cell
, 0, sizeof(cell_t
));
506 cell
.command
= cell_type
;
507 cell
.circ_id
= circ
->n_circ_id
;
509 memcpy(cell
.payload
, payload
, ONIONSKIN_CHALLENGE_LEN
);
510 append_cell_to_circuit_queue(circ
, circ
->n_conn
, &cell
, CELL_DIRECTION_OUT
);
512 if (CIRCUIT_IS_ORIGIN(circ
)) {
513 /* mark it so it gets better rate limiting treatment. */
514 circ
->n_conn
->client_used
= time(NULL
);
520 /** We've decided to start our reachability testing. If all
521 * is set, log this to the user. Return 1 if we did, or 0 if
522 * we chose not to log anything. */
524 inform_testing_reachability(void)
527 routerinfo_t
*me
= router_get_my_routerinfo();
531 tor_snprintf(dirbuf
, sizeof(dirbuf
), " and DirPort %s:%d",
532 me
->address
, me
->dir_port
);
533 log(LOG_NOTICE
, LD_OR
, "Now checking whether ORPort %s:%d%s %s reachable... "
534 "(this may take up to %d minutes -- look for log "
535 "messages indicating success)",
536 me
->address
, me
->or_port
,
537 me
->dir_port
? dirbuf
: "",
538 me
->dir_port
? "are" : "is",
539 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
/60);
543 /** Return true iff we should send a create_fast cell to start building a given
546 should_use_create_fast_for_circuit(origin_circuit_t
*circ
)
548 or_options_t
*options
= get_options();
549 tor_assert(circ
->cpath
);
550 tor_assert(circ
->cpath
->extend_info
);
552 if (!circ
->cpath
->extend_info
->onion_key
)
553 return 1; /* our hand is forced: only a create_fast will work. */
554 if (!options
->FastFirstHopPK
)
555 return 0; /* we prefer to avoid create_fast */
556 if (server_mode(options
)) {
557 /* We're a server, and we know an onion key. We can choose.
558 * Prefer to blend in. */
565 /** This is the backbone function for building circuits.
567 * If circ's first hop is closed, then we need to build a create
568 * cell and send it forward.
570 * Otherwise, we need to build a relay extend cell and send it
573 * Return -reason if we want to tear down circ, else return 0.
576 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
579 routerinfo_t
*router
;
580 char payload
[2+4+DIGEST_LEN
+ONIONSKIN_CHALLENGE_LEN
];
586 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
589 log_debug(LD_CIRC
,"First skin; sending create cell.");
590 if (circ
->build_state
->onehop_tunnel
)
591 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE
, 0);
593 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE
, 0);
595 router
= router_get_by_digest(circ
->_base
.n_conn
->identity_digest
);
596 fast
= should_use_create_fast_for_circuit(circ
);
598 /* We are an OR and we know the right onion key: we should
599 * send an old slow create cell.
601 cell_type
= CELL_CREATE
;
602 if (onion_skin_create(circ
->cpath
->extend_info
->onion_key
,
603 &(circ
->cpath
->dh_handshake_state
),
605 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
606 return - END_CIRC_REASON_INTERNAL
;
608 note_request("cell: create", 1);
610 /* We are not an OR, and we're building the first hop of a circuit to a
611 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
612 * and a DH operation. */
613 cell_type
= CELL_CREATE_FAST
;
614 memset(payload
, 0, sizeof(payload
));
615 crypto_rand(circ
->cpath
->fast_handshake_state
,
616 sizeof(circ
->cpath
->fast_handshake_state
));
617 memcpy(payload
, circ
->cpath
->fast_handshake_state
,
618 sizeof(circ
->cpath
->fast_handshake_state
));
619 note_request("cell: create fast", 1);
622 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), cell_type
, payload
) < 0)
623 return - END_CIRC_REASON_RESOURCELIMIT
;
625 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
626 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
627 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
628 fast
? "CREATE_FAST" : "CREATE",
629 router
? router
->nickname
: "<unnamed>");
631 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
632 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_BUILDING
);
633 log_debug(LD_CIRC
,"starting to send subsequent skin.");
634 hop
= onion_next_hop_in_cpath(circ
->cpath
);
636 /* done building the circuit. whew. */
637 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
638 log_info(LD_CIRC
,"circuit built!");
639 circuit_reset_failure_count(0);
640 if (circ
->build_state
->onehop_tunnel
)
641 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS
, 0);
642 if (!has_completed_circuit
&& !circ
->build_state
->onehop_tunnel
) {
643 or_options_t
*options
= get_options();
644 has_completed_circuit
=1;
645 /* FFFF Log a count of known routers here */
646 log(LOG_NOTICE
, LD_GENERAL
,
647 "Tor has successfully opened a circuit. "
648 "Looks like client functionality is working.");
649 control_event_bootstrap(BOOTSTRAP_STATUS_DONE
, 0);
650 control_event_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
651 if (server_mode(options
) && !check_whether_orport_reachable()) {
652 inform_testing_reachability();
653 consider_testing_reachability(1, 1);
656 circuit_rep_hist_note_result(circ
);
657 circuit_has_opened(circ
); /* do other actions as necessary */
661 if (tor_addr_family(&hop
->extend_info
->addr
) != AF_INET
) {
662 log_warn(LD_BUG
, "Trying to extend to a non-IPv4 address.");
663 return - END_CIRC_REASON_INTERNAL
;
666 set_uint32(payload
, tor_addr_to_ipv4n(&hop
->extend_info
->addr
));
667 set_uint16(payload
+4, htons(hop
->extend_info
->port
));
669 onionskin
= payload
+2+4;
670 memcpy(payload
+2+4+ONIONSKIN_CHALLENGE_LEN
,
671 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
672 payload_len
= 2+4+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
;
674 if (onion_skin_create(hop
->extend_info
->onion_key
,
675 &(hop
->dh_handshake_state
), onionskin
) < 0) {
676 log_warn(LD_CIRC
,"onion_skin_create failed.");
677 return - END_CIRC_REASON_INTERNAL
;
680 log_info(LD_CIRC
,"Sending extend relay cell.");
681 note_request("cell: extend", 1);
682 /* send it to hop->prev, because it will transfer
683 * it to a create cell and then send to hop */
684 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
685 RELAY_COMMAND_EXTEND
,
686 payload
, payload_len
, hop
->prev
) < 0)
687 return 0; /* circuit is closed */
689 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
694 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
695 * something has also gone wrong with our network: notify the user,
696 * and abandon all not-yet-used circuits. */
698 circuit_note_clock_jumped(int seconds_elapsed
)
700 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
701 log(severity
, LD_GENERAL
, "Your system clock just jumped %d seconds %s; "
702 "assuming established circuits no longer work.",
703 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
,
704 seconds_elapsed
>=0 ? "forward" : "backward");
705 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%d",
707 has_completed_circuit
=0; /* so it'll log when it works again */
708 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
710 circuit_mark_all_unused_circs();
711 circuit_expire_all_dirty_circs();
714 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
715 * skin and identity digest for the next hop. If we're already connected,
716 * pass the onion skin to the next hop using a create cell; otherwise
717 * launch a new OR connection, and <b>circ</b> will notice when the
718 * connection succeeds or fails.
720 * Return -1 if we want to warn and tear down the circuit, else return 0.
723 circuit_extend(cell_t
*cell
, circuit_t
*circ
)
725 or_connection_t
*n_conn
;
728 char *id_digest
=NULL
;
732 const char *msg
= NULL
;
733 int should_launch
= 0;
736 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
737 "n_conn already set. Bug/attack. Closing.");
741 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
742 "conn to next hop already launched. Bug/attack. Closing.");
746 if (!server_mode(get_options())) {
747 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
748 "Got an extend cell, but running as a client. Closing.");
752 relay_header_unpack(&rh
, cell
->payload
);
754 if (rh
.length
< 4+2+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
) {
755 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
756 "Wrong length %d on extend cell. Closing circuit.",
761 n_addr32
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
762 n_port
= ntohs(get_uint16(cell
->payload
+RELAY_HEADER_SIZE
+4));
763 onionskin
= cell
->payload
+RELAY_HEADER_SIZE
+4+2;
764 id_digest
= cell
->payload
+RELAY_HEADER_SIZE
+4+2+ONIONSKIN_CHALLENGE_LEN
;
765 tor_addr_from_ipv4h(&n_addr
, n_addr32
);
767 if (!n_port
|| !n_addr32
) {
768 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
769 "Client asked me to extend to zero destination port or addr.");
773 /* Check if they asked us for 0000..0000. We support using
774 * an empty fingerprint for the first hop (e.g. for a bridge relay),
775 * but we don't want to let people send us extend cells for empty
776 * fingerprints -- a) because it opens the user up to a mitm attack,
777 * and b) because it lets an attacker force the relay to hold open a
778 * new TLS connection for each extend request. */
779 if (tor_digest_is_zero(id_digest
)) {
780 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
781 "Client asked me to extend without specifying an id_digest.");
785 /* Next, check if we're being asked to connect to the hop that the
786 * extend cell came from. There isn't any reason for that, and it can
787 * assist circular-path attacks. */
788 if (!memcmp(id_digest
, TO_OR_CIRCUIT(circ
)->p_conn
->identity_digest
,
790 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
791 "Client asked me to extend back to the previous hop.");
795 n_conn
= connection_or_get_for_extend(id_digest
,
801 log_debug(LD_CIRC
|LD_OR
,"Next router (%s:%d): %s",
802 fmt_addr(&n_addr
), (int)n_port
, msg
?msg
:"????");
804 circ
->n_hop
= extend_info_alloc(NULL
/*nickname*/,
809 circ
->n_conn_onionskin
= tor_malloc(ONIONSKIN_CHALLENGE_LEN
);
810 memcpy(circ
->n_conn_onionskin
, onionskin
, ONIONSKIN_CHALLENGE_LEN
);
811 circuit_set_state(circ
, CIRCUIT_STATE_OR_WAIT
);
814 /* we should try to open a connection */
815 n_conn
= connection_or_connect(&n_addr
, n_port
, id_digest
);
817 log_info(LD_CIRC
,"Launching n_conn failed. Closing circuit.");
818 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
821 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
823 /* return success. The onion/circuit/etc will be taken care of
824 * automatically (may already have been) whenever n_conn reaches
825 * OR_CONN_STATE_OPEN.
830 tor_assert(!circ
->n_hop
); /* Connection is already established. */
831 circ
->n_conn
= n_conn
;
832 log_debug(LD_CIRC
,"n_conn is %s:%u",
833 n_conn
->_base
.address
,n_conn
->_base
.port
);
835 if (circuit_deliver_create_cell(circ
, CELL_CREATE
, onionskin
) < 0)
840 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
841 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
843 * - 20 to initialize f_digest
844 * - 20 to initialize b_digest
845 * - 16 to key f_crypto
846 * - 16 to key b_crypto
848 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
851 circuit_init_cpath_crypto(crypt_path_t
*cpath
, const char *key_data
,
854 crypto_digest_env_t
*tmp_digest
;
855 crypto_cipher_env_t
*tmp_crypto
;
858 tor_assert(key_data
);
859 tor_assert(!(cpath
->f_crypto
|| cpath
->b_crypto
||
860 cpath
->f_digest
|| cpath
->b_digest
));
862 cpath
->f_digest
= crypto_new_digest_env();
863 crypto_digest_add_bytes(cpath
->f_digest
, key_data
, DIGEST_LEN
);
864 cpath
->b_digest
= crypto_new_digest_env();
865 crypto_digest_add_bytes(cpath
->b_digest
, key_data
+DIGEST_LEN
, DIGEST_LEN
);
867 if (!(cpath
->f_crypto
=
868 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
),1))) {
869 log_warn(LD_BUG
,"Forward cipher initialization failed.");
872 if (!(cpath
->b_crypto
=
873 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
)+CIPHER_KEY_LEN
,0))) {
874 log_warn(LD_BUG
,"Backward cipher initialization failed.");
879 tmp_digest
= cpath
->f_digest
;
880 cpath
->f_digest
= cpath
->b_digest
;
881 cpath
->b_digest
= tmp_digest
;
882 tmp_crypto
= cpath
->f_crypto
;
883 cpath
->f_crypto
= cpath
->b_crypto
;
884 cpath
->b_crypto
= tmp_crypto
;
890 /** A created or extended cell came back to us on the circuit, and it included
891 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
892 * contains (the second DH key, plus KH). If <b>reply_type</b> is
893 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
895 * Calculate the appropriate keys and digests, make sure KH is
896 * correct, and initialize this hop of the cpath.
898 * Return - reason if we want to mark circ for close, else return 0.
901 circuit_finish_handshake(origin_circuit_t
*circ
, uint8_t reply_type
,
904 char keys
[CPATH_KEY_MATERIAL_LEN
];
907 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
)
910 hop
= onion_next_hop_in_cpath(circ
->cpath
);
911 if (!hop
) { /* got an extended when we're all done? */
912 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
913 return - END_CIRC_REASON_TORPROTOCOL
;
916 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
918 if (reply_type
== CELL_CREATED
&& hop
->dh_handshake_state
) {
919 if (onion_skin_client_handshake(hop
->dh_handshake_state
, reply
, keys
,
920 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
921 log_warn(LD_CIRC
,"onion_skin_client_handshake failed.");
922 return -END_CIRC_REASON_TORPROTOCOL
;
924 /* Remember hash of g^xy */
925 memcpy(hop
->handshake_digest
, reply
+DH_KEY_LEN
, DIGEST_LEN
);
926 } else if (reply_type
== CELL_CREATED_FAST
&& !hop
->dh_handshake_state
) {
927 if (fast_client_handshake(hop
->fast_handshake_state
, reply
, keys
,
928 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
929 log_warn(LD_CIRC
,"fast_client_handshake failed.");
930 return -END_CIRC_REASON_TORPROTOCOL
;
932 memcpy(hop
->handshake_digest
, reply
+DIGEST_LEN
, DIGEST_LEN
);
934 log_warn(LD_PROTOCOL
,"CREATED cell type did not match CREATE cell type.");
935 return -END_CIRC_REASON_TORPROTOCOL
;
938 if (hop
->dh_handshake_state
) {
939 crypto_dh_free(hop
->dh_handshake_state
); /* don't need it anymore */
940 hop
->dh_handshake_state
= NULL
;
942 memset(hop
->fast_handshake_state
, 0, sizeof(hop
->fast_handshake_state
));
944 if (circuit_init_cpath_crypto(hop
, keys
, 0)<0) {
945 return -END_CIRC_REASON_TORPROTOCOL
;
948 hop
->state
= CPATH_STATE_OPEN
;
949 log_info(LD_CIRC
,"Finished building %scircuit hop:",
950 (reply_type
== CELL_CREATED_FAST
) ? "fast " : "");
951 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
952 control_event_circuit_status(circ
, CIRC_EVENT_EXTENDED
, 0);
957 /** We received a relay truncated cell on circ.
959 * Since we don't ask for truncates currently, getting a truncated
960 * means that a connection broke or an extend failed. For now,
961 * just give up: for circ to close, and return 0.
964 circuit_truncated(origin_circuit_t
*circ
, crypt_path_t
*layer
)
966 // crypt_path_t *victim;
967 // connection_t *stream;
972 /* XXX Since we don't ask for truncates currently, getting a truncated
973 * means that a connection broke or an extend failed. For now,
976 circuit_mark_for_close(TO_CIRCUIT(circ
),
977 END_CIRC_REASON_FLAG_REMOTE
|END_CIRC_REASON_OR_CONN_CLOSED
);
981 while (layer
->next
!= circ
->cpath
) {
982 /* we need to clear out layer->next */
983 victim
= layer
->next
;
984 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
986 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
987 if (stream
->cpath_layer
== victim
) {
988 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
990 /* no need to send 'end' relay cells,
991 * because the other side's already dead
993 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
997 layer
->next
= victim
->next
;
998 circuit_free_cpath_node(victim
);
1001 log_info(LD_CIRC
, "finished");
1006 /** Given a response payload and keys, initialize, then send a created
1010 onionskin_answer(or_circuit_t
*circ
, uint8_t cell_type
, const char *payload
,
1014 crypt_path_t
*tmp_cpath
;
1016 tmp_cpath
= tor_malloc_zero(sizeof(crypt_path_t
));
1017 tmp_cpath
->magic
= CRYPT_PATH_MAGIC
;
1019 memset(&cell
, 0, sizeof(cell_t
));
1020 cell
.command
= cell_type
;
1021 cell
.circ_id
= circ
->p_circ_id
;
1023 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
1025 memcpy(cell
.payload
, payload
,
1026 cell_type
== CELL_CREATED
? ONIONSKIN_REPLY_LEN
: DIGEST_LEN
*2);
1028 log_debug(LD_CIRC
,"init digest forward 0x%.8x, backward 0x%.8x.",
1029 (unsigned int)*(uint32_t*)(keys
),
1030 (unsigned int)*(uint32_t*)(keys
+20));
1031 if (circuit_init_cpath_crypto(tmp_cpath
, keys
, 0)<0) {
1032 log_warn(LD_BUG
,"Circuit initialization failed");
1033 tor_free(tmp_cpath
);
1036 circ
->n_digest
= tmp_cpath
->f_digest
;
1037 circ
->n_crypto
= tmp_cpath
->f_crypto
;
1038 circ
->p_digest
= tmp_cpath
->b_digest
;
1039 circ
->p_crypto
= tmp_cpath
->b_crypto
;
1040 tmp_cpath
->magic
= 0;
1041 tor_free(tmp_cpath
);
1043 if (cell_type
== CELL_CREATED
)
1044 memcpy(circ
->handshake_digest
, cell
.payload
+DH_KEY_LEN
, DIGEST_LEN
);
1046 memcpy(circ
->handshake_digest
, cell
.payload
+DIGEST_LEN
, DIGEST_LEN
);
1048 circ
->is_first_hop
= (cell_type
== CELL_CREATED_FAST
);
1050 append_cell_to_circuit_queue(TO_CIRCUIT(circ
),
1051 circ
->p_conn
, &cell
, CELL_DIRECTION_IN
);
1052 log_debug(LD_CIRC
,"Finished sending 'created' cell.");
1054 if (!is_local_addr(&circ
->p_conn
->_base
.addr
) &&
1055 !connection_or_nonopen_was_started_here(circ
->p_conn
)) {
1056 /* record that we could process create cells from a non-local conn
1057 * that we didn't initiate; presumably this means that create cells
1058 * can reach us too. */
1059 router_orport_found_reachable();
1065 /** Choose a length for a circuit of purpose <b>purpose</b>.
1066 * Default length is 3 + the number of endpoints that would give something
1067 * away. If the routerlist <b>routers</b> doesn't have enough routers
1068 * to handle the desired path length, return as large a path length as
1069 * is feasible, except if it's less than 2, in which case return -1.
1072 new_route_len(uint8_t purpose
, extend_info_t
*exit
,
1073 smartlist_t
*routers
)
1075 int num_acceptable_routers
;
1078 tor_assert(routers
);
1082 purpose
!= CIRCUIT_PURPOSE_TESTING
&&
1083 purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
1086 num_acceptable_routers
= count_acceptable_routers(routers
);
1088 log_debug(LD_CIRC
,"Chosen route length %d (%d/%d routers suitable).",
1089 routelen
, num_acceptable_routers
, smartlist_len(routers
));
1091 if (num_acceptable_routers
< 2) {
1093 "Not enough acceptable routers (%d). Discarding this circuit.",
1094 num_acceptable_routers
);
1098 if (num_acceptable_routers
< routelen
) {
1099 log_info(LD_CIRC
,"Not enough routers: cutting routelen from %d to %d.",
1100 routelen
, num_acceptable_routers
);
1101 routelen
= num_acceptable_routers
;
1107 /** Fetch the list of predicted ports, dup it into a smartlist of
1108 * uint16_t's, remove the ones that are already handled by an
1109 * existing circuit, and return it.
1111 static smartlist_t
*
1112 circuit_get_unhandled_ports(time_t now
)
1114 smartlist_t
*source
= rep_hist_get_predicted_ports(now
);
1115 smartlist_t
*dest
= smartlist_create();
1119 for (i
= 0; i
< smartlist_len(source
); ++i
) {
1120 tmp
= tor_malloc(sizeof(uint16_t));
1121 memcpy(tmp
, smartlist_get(source
, i
), sizeof(uint16_t));
1122 smartlist_add(dest
, tmp
);
1125 circuit_remove_handled_ports(dest
);
1129 /** Return 1 if we already have circuits present or on the way for
1130 * all anticipated ports. Return 0 if we should make more.
1132 * If we're returning 0, set need_uptime and need_capacity to
1133 * indicate any requirements that the unhandled ports have.
1136 circuit_all_predicted_ports_handled(time_t now
, int *need_uptime
,
1141 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
1142 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
1143 tor_assert(need_uptime
);
1144 tor_assert(need_capacity
);
1145 enough
= (smartlist_len(sl
) == 0);
1146 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
1147 port
= smartlist_get(sl
, i
);
1148 if (smartlist_string_num_isin(LongLivedServices
, *port
))
1156 /** Return 1 if <b>router</b> can handle one or more of the ports in
1157 * <b>needed_ports</b>, else return 0.
1160 router_handles_some_port(routerinfo_t
*router
, smartlist_t
*needed_ports
)
1165 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
1166 addr_policy_result_t r
;
1167 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
1169 r
= compare_addr_to_addr_policy(0, port
, router
->exit_policy
);
1170 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
1176 /** Return true iff <b>conn</b> needs another general circuit to be
1179 ap_stream_wants_exit_attention(connection_t
*conn
)
1181 if (conn
->type
== CONN_TYPE_AP
&&
1182 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
1183 !conn
->marked_for_close
&&
1184 !(TO_EDGE_CONN(conn
)->want_onehop
) && /* ignore one-hop streams */
1185 !(TO_EDGE_CONN(conn
)->use_begindir
) && /* ignore targeted dir fetches */
1186 !(TO_EDGE_CONN(conn
)->chosen_exit_name
) && /* ignore defined streams */
1187 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
1188 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn
), 0,
1189 MIN_CIRCUITS_HANDLING_STREAM
))
1194 /** Return a pointer to a suitable router to be the exit node for the
1195 * general-purpose circuit we're about to build.
1197 * Look through the connection array, and choose a router that maximizes
1198 * the number of pending streams that can exit from this router.
1200 * Return NULL if we can't find any suitable routers.
1202 static routerinfo_t
*
1203 choose_good_exit_server_general(routerlist_t
*dir
, int need_uptime
,
1208 int n_pending_connections
= 0;
1209 smartlist_t
*connections
;
1210 int best_support
= -1;
1211 int n_best_support
=0;
1212 routerinfo_t
*router
;
1213 or_options_t
*options
= get_options();
1215 connections
= get_connection_array();
1217 /* Count how many connections are waiting for a circuit to be built.
1218 * We use this for log messages now, but in the future we may depend on it.
1220 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1222 if (ap_stream_wants_exit_attention(conn
))
1223 ++n_pending_connections
;
1225 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1226 // n_pending_connections);
1227 /* Now we count, for each of the routers in the directory, how many
1228 * of the pending connections could possibly exit from that
1229 * router (n_supported[i]). (We can't be sure about cases where we
1230 * don't know the IP address of the pending connection.)
1232 * -1 means "Don't use this router at all."
1234 n_supported
= tor_malloc(sizeof(int)*smartlist_len(dir
->routers
));
1235 for (i
= 0; i
< smartlist_len(dir
->routers
); ++i
) {/* iterate over routers */
1236 router
= smartlist_get(dir
->routers
, i
);
1237 if (router_is_me(router
)) {
1238 n_supported
[i
] = -1;
1239 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1240 /* XXX there's probably a reverse predecessor attack here, but
1241 * it's slow. should we take this out? -RD
1245 if (!router
->is_running
|| router
->is_bad_exit
) {
1246 n_supported
[i
] = -1;
1247 continue; /* skip routers that are known to be down or bad exits */
1249 if (router_is_unreliable(router
, need_uptime
, need_capacity
, 0)) {
1250 n_supported
[i
] = -1;
1251 continue; /* skip routers that are not suitable */
1253 if (!(router
->is_valid
|| options
->_AllowInvalid
& ALLOW_INVALID_EXIT
)) {
1254 /* if it's invalid and we don't want it */
1255 n_supported
[i
] = -1;
1256 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1257 // router->nickname, i);
1258 continue; /* skip invalid routers */
1260 if (options
->ExcludeSingleHopRelays
&& router
->allow_single_hop_exits
) {
1261 n_supported
[i
] = -1;
1264 if (router_exit_policy_rejects_all(router
)) {
1265 n_supported
[i
] = -1;
1266 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1267 // router->nickname, i);
1268 continue; /* skip routers that reject all */
1271 /* iterate over connections */
1272 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1274 if (!ap_stream_wants_exit_attention(conn
))
1275 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1276 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn
), router
)) {
1278 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1279 // router->nickname, i, n_supported[i]);
1281 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1282 // router->nickname, i);
1284 }); /* End looping over connections. */
1285 if (n_pending_connections
> 0 && n_supported
[i
] == 0) {
1286 /* Leave best_support at -1 if that's where it is, so we can
1287 * distinguish it later. */
1290 if (n_supported
[i
] > best_support
) {
1291 /* If this router is better than previous ones, remember its index
1292 * and goodness, and start counting how many routers are this good. */
1293 best_support
= n_supported
[i
]; n_best_support
=1;
1294 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1295 // router->nickname);
1296 } else if (n_supported
[i
] == best_support
) {
1297 /* If this router is _as good_ as the best one, just increment the
1298 * count of equally good routers.*/
1303 "Found %d servers that might support %d/%d pending connections.",
1304 n_best_support
, best_support
>= 0 ? best_support
: 0,
1305 n_pending_connections
);
1307 /* If any routers definitely support any pending connections, choose one
1309 if (best_support
> 0) {
1310 smartlist_t
*supporting
= smartlist_create(), *use
= smartlist_create();
1312 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++)
1313 if (n_supported
[i
] == best_support
)
1314 smartlist_add(supporting
, smartlist_get(dir
->routers
, i
));
1316 routersets_get_disjunction(use
, supporting
, options
->ExitNodes
,
1317 options
->_ExcludeExitNodesUnion
, 1);
1318 if (smartlist_len(use
) == 0 && !options
->StrictExitNodes
) {
1319 routersets_get_disjunction(use
, supporting
, NULL
,
1320 options
->_ExcludeExitNodesUnion
, 1);
1322 router
= routerlist_sl_choose_by_bandwidth(use
, WEIGHT_FOR_EXIT
);
1323 smartlist_free(use
);
1324 smartlist_free(supporting
);
1326 /* Either there are no pending connections, or no routers even seem to
1327 * possibly support any of them. Choose a router at random that satisfies
1328 * at least one predicted exit port. */
1331 smartlist_t
*needed_ports
, *supporting
, *use
;
1333 if (best_support
== -1) {
1334 if (need_uptime
|| need_capacity
) {
1336 "We couldn't find any live%s%s routers; falling back "
1337 "to list of all routers.",
1338 need_capacity
?", fast":"",
1339 need_uptime
?", stable":"");
1340 tor_free(n_supported
);
1341 return choose_good_exit_server_general(dir
, 0, 0);
1343 log_notice(LD_CIRC
, "All routers are down or won't exit -- choosing a "
1344 "doomed exit at random.");
1346 supporting
= smartlist_create();
1347 use
= smartlist_create();
1348 needed_ports
= circuit_get_unhandled_ports(time(NULL
));
1349 for (try = 0; try < 2; try++) {
1350 /* try once to pick only from routers that satisfy a needed port,
1351 * then if there are none, pick from any that support exiting. */
1352 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++) {
1353 router
= smartlist_get(dir
->routers
, i
);
1354 if (n_supported
[i
] != -1 &&
1355 (try || router_handles_some_port(router
, needed_ports
))) {
1356 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1357 // try, router->nickname);
1358 smartlist_add(supporting
, router
);
1362 routersets_get_disjunction(use
, supporting
, options
->ExitNodes
,
1363 options
->_ExcludeExitNodesUnion
, 1);
1364 if (smartlist_len(use
) == 0 && !options
->StrictExitNodes
) {
1365 routersets_get_disjunction(use
, supporting
, NULL
,
1366 options
->_ExcludeExitNodesUnion
, 1);
1368 /* XXX sometimes the above results in null, when the requested
1369 * exit node is down. we should pick it anyway. */
1370 router
= routerlist_sl_choose_by_bandwidth(use
, WEIGHT_FOR_EXIT
);
1373 smartlist_clear(supporting
);
1374 smartlist_clear(use
);
1376 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
1377 smartlist_free(needed_ports
);
1378 smartlist_free(use
);
1379 smartlist_free(supporting
);
1382 tor_free(n_supported
);
1384 log_info(LD_CIRC
, "Chose exit server '%s'", router
->nickname
);
1387 if (options
->StrictExitNodes
) {
1389 "No specified exit routers seem to be running, and "
1390 "StrictExitNodes is set: can't choose an exit.");
1395 /** Return a pointer to a suitable router to be the exit node for the
1396 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1397 * if no router is suitable).
1399 * For general-purpose circuits, pass it off to
1400 * choose_good_exit_server_general()
1402 * For client-side rendezvous circuits, choose a random node, weighted
1403 * toward the preferences in 'options'.
1405 static routerinfo_t
*
1406 choose_good_exit_server(uint8_t purpose
, routerlist_t
*dir
,
1407 int need_uptime
, int need_capacity
, int is_internal
)
1409 or_options_t
*options
= get_options();
1410 router_crn_flags_t flags
= 0;
1412 flags
|= CRN_NEED_UPTIME
;
1414 flags
|= CRN_NEED_CAPACITY
;
1417 case CIRCUIT_PURPOSE_C_GENERAL
:
1418 if (options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
)
1419 flags
|= CRN_ALLOW_INVALID
;
1420 if (is_internal
) /* pick it like a middle hop */
1421 return router_choose_random_node(NULL
, NULL
,
1422 options
->ExcludeNodes
, flags
);
1424 return choose_good_exit_server_general(dir
,need_uptime
,need_capacity
);
1425 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1426 if (options
->_AllowInvalid
& ALLOW_INVALID_RENDEZVOUS
)
1427 flags
|= CRN_ALLOW_INVALID
;
1428 return router_choose_random_node(NULL
, NULL
,
1429 options
->ExcludeNodes
, flags
);
1431 log_warn(LD_BUG
,"Unhandled purpose %d", purpose
);
1432 tor_fragile_assert();
1436 /** Log a warning if the user specified an exit for the circuit that
1437 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1439 warn_if_router_excluded(const extend_info_t
*exit
)
1441 or_options_t
*options
= get_options();
1442 routerinfo_t
*ri
= router_get_by_digest(exit
->identity_digest
);
1444 if (!ri
|| !options
->_ExcludeExitNodesUnion
)
1447 if (routerset_contains_router(options
->_ExcludeExitNodesUnion
, ri
))
1448 log_warn(LD_CIRC
,"Requested exit node '%s' is in ExcludeNodes, "
1449 "or ExcludeExitNodes, using anyway.",exit
->nickname
);
1454 /** Decide a suitable length for circ's cpath, and pick an exit
1455 * router (or use <b>exit</b> if provided). Store these in the
1456 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1458 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1460 cpath_build_state_t
*state
= circ
->build_state
;
1461 routerlist_t
*rl
= router_get_routerlist();
1463 if (state
->onehop_tunnel
) {
1464 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel.");
1465 state
->desired_path_len
= 1;
1467 int r
= new_route_len(circ
->_base
.purpose
, exit
, rl
->routers
);
1468 if (r
< 1) /* must be at least 1 */
1470 state
->desired_path_len
= r
;
1473 if (exit
) { /* the circuit-builder pre-requested one */
1474 warn_if_router_excluded(exit
);
1475 log_info(LD_CIRC
,"Using requested exit node '%s'", exit
->nickname
);
1476 exit
= extend_info_dup(exit
);
1477 } else { /* we have to decide one */
1478 routerinfo_t
*router
=
1479 choose_good_exit_server(circ
->_base
.purpose
, rl
, state
->need_uptime
,
1480 state
->need_capacity
, state
->is_internal
);
1482 log_warn(LD_CIRC
,"failed to choose an exit server");
1485 exit
= extend_info_from_router(router
);
1487 state
->chosen_exit
= exit
;
1491 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1492 * hop to the cpath reflecting this. Don't send the next extend cell --
1493 * the caller will do this if it wants to.
1496 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1498 cpath_build_state_t
*state
;
1502 state
= circ
->build_state
;
1504 if (state
->chosen_exit
)
1505 extend_info_free(state
->chosen_exit
);
1506 state
->chosen_exit
= extend_info_dup(exit
);
1508 ++circ
->build_state
->desired_path_len
;
1509 onion_append_hop(&circ
->cpath
, exit
);
1513 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1514 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1515 * send the next extend cell to begin connecting to that hop.
1518 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1521 circuit_append_new_exit(circ
, exit
);
1522 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
1523 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
1524 log_warn(LD_CIRC
, "Couldn't extend circuit to new point '%s'.",
1526 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
1532 /** Return the number of routers in <b>routers</b> that are currently up
1533 * and available for building circuits through.
1536 count_acceptable_routers(smartlist_t
*routers
)
1542 n
= smartlist_len(routers
);
1544 r
= smartlist_get(routers
, i
);
1545 // log_debug(LD_CIRC,
1546 // "Contemplating whether router %d (%s) is a new option.",
1548 if (r
->is_running
== 0) {
1549 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1552 if (r
->is_valid
== 0) {
1553 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1555 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1556 * allows this node in some places, then we're getting an inaccurate
1557 * count. For now, be conservative and don't count it. But later we
1558 * should try to be smarter. */
1561 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1563 ; /* C requires an explicit statement after the label */
1569 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1570 * This function is used to extend cpath by another hop.
1573 onion_append_to_cpath(crypt_path_t
**head_ptr
, crypt_path_t
*new_hop
)
1576 new_hop
->next
= (*head_ptr
);
1577 new_hop
->prev
= (*head_ptr
)->prev
;
1578 (*head_ptr
)->prev
->next
= new_hop
;
1579 (*head_ptr
)->prev
= new_hop
;
1581 *head_ptr
= new_hop
;
1582 new_hop
->prev
= new_hop
->next
= new_hop
;
1586 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1587 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1588 * to length <b>cur_len</b> to decide a suitable middle hop for a
1589 * circuit. In particular, make sure we don't pick the exit node or its
1590 * family, and make sure we don't duplicate any previous nodes or their
1592 static routerinfo_t
*
1593 choose_good_middle_server(uint8_t purpose
,
1594 cpath_build_state_t
*state
,
1599 routerinfo_t
*r
, *choice
;
1600 crypt_path_t
*cpath
;
1601 smartlist_t
*excluded
;
1602 or_options_t
*options
= get_options();
1603 router_crn_flags_t flags
= 0;
1604 tor_assert(_CIRCUIT_PURPOSE_MIN
<= purpose
&&
1605 purpose
<= _CIRCUIT_PURPOSE_MAX
);
1607 log_debug(LD_CIRC
, "Contemplating intermediate hop: random choice.");
1608 excluded
= smartlist_create();
1609 if ((r
= build_state_get_exit_router(state
))) {
1610 smartlist_add(excluded
, r
);
1611 routerlist_add_family(excluded
, r
);
1613 for (i
= 0, cpath
= head
; i
< cur_len
; ++i
, cpath
=cpath
->next
) {
1614 if ((r
= router_get_by_digest(cpath
->extend_info
->identity_digest
))) {
1615 smartlist_add(excluded
, r
);
1616 routerlist_add_family(excluded
, r
);
1620 if (state
->need_uptime
)
1621 flags
|= CRN_NEED_UPTIME
;
1622 if (state
->need_capacity
)
1623 flags
|= CRN_NEED_CAPACITY
;
1624 if (options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
)
1625 flags
|= CRN_ALLOW_INVALID
;
1626 choice
= router_choose_random_node(NULL
,
1627 excluded
, options
->ExcludeNodes
, flags
);
1628 smartlist_free(excluded
);
1632 /** Pick a good entry server for the circuit to be built according to
1633 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1634 * router (if we're an OR), and respect firewall settings; if we're
1635 * configured to use entry guards, return one.
1637 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1638 * guard, not for any particular circuit.
1640 static routerinfo_t
*
1641 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
)
1643 routerinfo_t
*r
, *choice
;
1644 smartlist_t
*excluded
;
1645 or_options_t
*options
= get_options();
1646 router_crn_flags_t flags
= 0;
1648 if (state
&& options
->UseEntryGuards
&&
1649 (purpose
!= CIRCUIT_PURPOSE_TESTING
|| options
->BridgeRelay
)) {
1650 return choose_random_entry(state
);
1653 excluded
= smartlist_create();
1655 if (state
&& (r
= build_state_get_exit_router(state
))) {
1656 smartlist_add(excluded
, r
);
1657 routerlist_add_family(excluded
, r
);
1659 if (firewall_is_fascist_or()) {
1660 /*XXXX This could slow things down a lot; use a smarter implementation */
1661 /* exclude all ORs that listen on the wrong port, if anybody notices. */
1662 routerlist_t
*rl
= router_get_routerlist();
1665 for (i
=0; i
< smartlist_len(rl
->routers
); i
++) {
1666 r
= smartlist_get(rl
->routers
, i
);
1667 if (!fascist_firewall_allows_or(r
))
1668 smartlist_add(excluded
, r
);
1671 /* and exclude current entry guards, if applicable */
1672 if (options
->UseEntryGuards
&& entry_guards
) {
1673 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1675 if ((r
= router_get_by_digest(entry
->identity
))) {
1676 smartlist_add(excluded
, r
);
1677 routerlist_add_family(excluded
, r
);
1683 flags
|= CRN_NEED_GUARD
;
1684 if (state
->need_uptime
)
1685 flags
|= CRN_NEED_UPTIME
;
1686 if (state
->need_capacity
)
1687 flags
|= CRN_NEED_CAPACITY
;
1689 if (options
->_AllowInvalid
& ALLOW_INVALID_ENTRY
)
1690 flags
|= CRN_ALLOW_INVALID
;
1692 choice
= router_choose_random_node(
1695 options
->ExcludeNodes
,
1697 smartlist_free(excluded
);
1701 /** Return the first non-open hop in cpath, or return NULL if all
1703 static crypt_path_t
*
1704 onion_next_hop_in_cpath(crypt_path_t
*cpath
)
1706 crypt_path_t
*hop
= cpath
;
1708 if (hop
->state
!= CPATH_STATE_OPEN
)
1711 } while (hop
!= cpath
);
1715 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1716 * based on <b>state</b>. Append the hop info to head_ptr.
1719 onion_extend_cpath(origin_circuit_t
*circ
)
1721 uint8_t purpose
= circ
->_base
.purpose
;
1722 cpath_build_state_t
*state
= circ
->build_state
;
1723 int cur_len
= circuit_get_cpath_len(circ
);
1724 extend_info_t
*info
= NULL
;
1726 if (cur_len
>= state
->desired_path_len
) {
1727 log_debug(LD_CIRC
, "Path is complete: %d steps long",
1728 state
->desired_path_len
);
1732 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
1733 state
->desired_path_len
);
1735 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
1736 info
= extend_info_dup(state
->chosen_exit
);
1737 } else if (cur_len
== 0) { /* picking first node */
1738 routerinfo_t
*r
= choose_good_entry_server(purpose
, state
);
1740 info
= extend_info_from_router(r
);
1743 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
1745 info
= extend_info_from_router(r
);
1749 log_warn(LD_CIRC
,"Failed to find node for hop %d of our path. Discarding "
1750 "this circuit.", cur_len
);
1754 log_debug(LD_CIRC
,"Chose router %s for hop %d (exit is %s)",
1755 info
->nickname
, cur_len
+1, build_state_get_exit_nickname(state
));
1757 onion_append_hop(&circ
->cpath
, info
);
1758 extend_info_free(info
);
1762 /** Create a new hop, annotate it with information about its
1763 * corresponding router <b>choice</b>, and append it to the
1764 * end of the cpath <b>head_ptr</b>. */
1766 onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
)
1768 crypt_path_t
*hop
= tor_malloc_zero(sizeof(crypt_path_t
));
1770 /* link hop into the cpath, at the end. */
1771 onion_append_to_cpath(head_ptr
, hop
);
1773 hop
->magic
= CRYPT_PATH_MAGIC
;
1774 hop
->state
= CPATH_STATE_CLOSED
;
1776 hop
->extend_info
= extend_info_dup(choice
);
1778 hop
->package_window
= CIRCWINDOW_START
;
1779 hop
->deliver_window
= CIRCWINDOW_START
;
1784 /** Allocate a new extend_info object based on the various arguments. */
1786 extend_info_alloc(const char *nickname
, const char *digest
,
1787 crypto_pk_env_t
*onion_key
,
1788 const tor_addr_t
*addr
, uint16_t port
)
1790 extend_info_t
*info
= tor_malloc_zero(sizeof(extend_info_t
));
1791 memcpy(info
->identity_digest
, digest
, DIGEST_LEN
);
1793 strlcpy(info
->nickname
, nickname
, sizeof(info
->nickname
));
1795 info
->onion_key
= crypto_pk_dup_key(onion_key
);
1796 tor_addr_copy(&info
->addr
, addr
);
1801 /** Allocate and return a new extend_info_t that can be used to build a
1802 * circuit to or through the router <b>r</b>. */
1804 extend_info_from_router(routerinfo_t
*r
)
1808 tor_addr_from_ipv4h(&addr
, r
->addr
);
1809 return extend_info_alloc(r
->nickname
, r
->cache_info
.identity_digest
,
1810 r
->onion_pkey
, &addr
, r
->or_port
);
1813 /** Release storage held by an extend_info_t struct. */
1815 extend_info_free(extend_info_t
*info
)
1818 if (info
->onion_key
)
1819 crypto_free_pk_env(info
->onion_key
);
1823 /** Allocate and return a new extend_info_t with the same contents as
1826 extend_info_dup(extend_info_t
*info
)
1828 extend_info_t
*newinfo
;
1830 newinfo
= tor_malloc(sizeof(extend_info_t
));
1831 memcpy(newinfo
, info
, sizeof(extend_info_t
));
1832 if (info
->onion_key
)
1833 newinfo
->onion_key
= crypto_pk_dup_key(info
->onion_key
);
1835 newinfo
->onion_key
= NULL
;
1839 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1840 * If there is no chosen exit, or if we don't know the routerinfo_t for
1841 * the chosen exit, return NULL.
1844 build_state_get_exit_router(cpath_build_state_t
*state
)
1846 if (!state
|| !state
->chosen_exit
)
1848 return router_get_by_digest(state
->chosen_exit
->identity_digest
);
1851 /** Return the nickname for the chosen exit router in <b>state</b>. If
1852 * there is no chosen exit, or if we don't know the routerinfo_t for the
1853 * chosen exit, return NULL.
1856 build_state_get_exit_nickname(cpath_build_state_t
*state
)
1858 if (!state
|| !state
->chosen_exit
)
1860 return state
->chosen_exit
->nickname
;
1863 /** Check whether the entry guard <b>e</b> is usable, given the directory
1864 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1865 * configuration (in <b>options</b>). Set <b>e</b>->bad_since
1866 * accordingly. Return true iff the entry guard's status changes.
1868 * If it's not usable, set *<b>reason</b> to a static string explaining why.
1870 /*XXXX take a routerstatus, not a routerinfo. */
1872 entry_guard_set_status(entry_guard_t
*e
, routerinfo_t
*ri
,
1873 time_t now
, or_options_t
*options
, const char **reason
)
1875 char buf
[HEX_DIGEST_LEN
+1];
1878 tor_assert(options
);
1882 /* Do we want to mark this guard as bad? */
1884 *reason
= "unlisted";
1885 else if (!ri
->is_running
)
1887 else if (options
->UseBridges
&& ri
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1888 *reason
= "not a bridge";
1889 else if (!options
->UseBridges
&& !ri
->is_possible_guard
&&
1890 !routerset_contains_router(options
->EntryNodes
,ri
))
1891 *reason
= "not recommended as a guard";
1892 else if (routerset_contains_router(options
->ExcludeNodes
, ri
))
1893 *reason
= "excluded";
1895 if (*reason
&& ! e
->bad_since
) {
1896 /* Router is newly bad. */
1897 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1898 log_info(LD_CIRC
, "Entry guard %s (%s) is %s: marking as unusable.",
1899 e
->nickname
, buf
, *reason
);
1902 control_event_guard(e
->nickname
, e
->identity
, "BAD");
1904 } else if (!*reason
&& e
->bad_since
) {
1905 /* There's nothing wrong with the router any more. */
1906 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1907 log_info(LD_CIRC
, "Entry guard %s (%s) is no longer unusable: "
1908 "marking as ok.", e
->nickname
, buf
);
1911 control_event_guard(e
->nickname
, e
->identity
, "GOOD");
1917 /** Return true iff enough time has passed since we last tried to connect
1918 * to the unreachable guard <b>e</b> that we're willing to try again. */
1920 entry_is_time_to_retry(entry_guard_t
*e
, time_t now
)
1923 if (e
->last_attempted
< e
->unreachable_since
)
1925 diff
= now
- e
->unreachable_since
;
1927 return now
> (e
->last_attempted
+ 60*60);
1928 else if (diff
< 3*24*60*60)
1929 return now
> (e
->last_attempted
+ 4*60*60);
1930 else if (diff
< 7*24*60*60)
1931 return now
> (e
->last_attempted
+ 18*60*60);
1933 return now
> (e
->last_attempted
+ 36*60*60);
1936 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1937 * working well enough that we are willing to use it as an entry
1938 * right now. (Else return NULL.) In particular, it must be
1939 * - Listed as either up or never yet contacted;
1940 * - Present in the routerlist;
1941 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1942 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1943 * (This check is currently redundant with the Guard flag, but in
1944 * the future that might change. Best to leave it in for now.)
1945 * - Allowed by our current ReachableORAddresses config option; and
1946 * - Currently thought to be reachable by us (unless assume_reachable
1949 static INLINE routerinfo_t
*
1950 entry_is_live(entry_guard_t
*e
, int need_uptime
, int need_capacity
,
1951 int assume_reachable
)
1956 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1957 if (!assume_reachable
&& !e
->can_retry
&&
1958 e
->unreachable_since
&& !entry_is_time_to_retry(e
, time(NULL
)))
1960 r
= router_get_by_digest(e
->identity
);
1963 if (get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1965 if (!get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_GENERAL
)
1967 if (router_is_unreliable(r
, need_uptime
, need_capacity
, 0))
1969 if (!fascist_firewall_allows_or(r
))
1974 /** Return the number of entry guards that we think are usable. */
1976 num_live_entry_guards(void)
1981 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1983 if (entry_is_live(entry
, 0, 1, 0))
1989 /** If <b>digest</b> matches the identity of any node in the
1990 * entry_guards list, return that node. Else return NULL. */
1991 static INLINE entry_guard_t
*
1992 is_an_entry_guard(const char *digest
)
1994 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1995 if (!memcmp(digest
, entry
->identity
, DIGEST_LEN
))
2001 /** Dump a description of our list of entry guards to the log at level
2002 * <b>severity</b>. */
2004 log_entry_guards(int severity
)
2006 smartlist_t
*elements
= smartlist_create();
2010 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2012 tor_snprintf(buf
, sizeof(buf
), "%s (%s%s)",
2014 entry_is_live(e
, 0, 1, 0) ? "up " : "down ",
2015 e
->made_contact
? "made-contact" : "never-contacted");
2016 smartlist_add(elements
, tor_strdup(buf
));
2019 s
= smartlist_join_strings(elements
, ",", 0, NULL
);
2020 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
2021 smartlist_free(elements
);
2022 log_fn(severity
,LD_CIRC
,"%s",s
);
2026 /** Called when one or more guards that we would previously have used for some
2027 * purpose are no longer in use because a higher-priority guard has become
2030 control_event_guard_deferred(void)
2032 /* XXXX We don't actually have a good way to figure out _how many_ entries
2033 * are live for some purpose. We need an entry_is_even_slightly_live()
2034 * function for this to work right. NumEntryGuards isn't reliable: if we
2035 * need guards with weird properties, we can have more than that number
2040 or_options_t
*options
= get_options();
2043 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2045 if (entry_is_live(entry
, 0, 1, 0)) {
2046 if (n
++ == options
->NumEntryGuards
) {
2047 control_event_guard(entry
->nickname
, entry
->identity
, "DEFERRED");
2055 /** Add a new (preferably stable and fast) router to our
2056 * entry_guards list. Return a pointer to the router if we succeed,
2057 * or NULL if we can't find any more suitable entries.
2059 * If <b>chosen</b> is defined, use that one, and if it's not
2060 * already in our entry_guards list, put it at the *beginning*.
2061 * Else, put the one we pick at the end of the list. */
2062 static routerinfo_t
*
2063 add_an_entry_guard(routerinfo_t
*chosen
, int reset_status
)
2065 routerinfo_t
*router
;
2066 entry_guard_t
*entry
;
2070 entry
= is_an_entry_guard(router
->cache_info
.identity_digest
);
2073 entry
->bad_since
= 0;
2074 entry
->can_retry
= 1;
2079 router
= choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL
, NULL
);
2083 entry
= tor_malloc_zero(sizeof(entry_guard_t
));
2084 log_info(LD_CIRC
, "Chose '%s' as new entry guard.", router
->nickname
);
2085 strlcpy(entry
->nickname
, router
->nickname
, sizeof(entry
->nickname
));
2086 memcpy(entry
->identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
2087 entry
->chosen_on_date
= start_of_month(time(NULL
));
2088 entry
->chosen_by_version
= tor_strdup(VERSION
);
2089 if (chosen
) /* prepend */
2090 smartlist_insert(entry_guards
, 0, entry
);
2092 smartlist_add(entry_guards
, entry
);
2093 control_event_guard(entry
->nickname
, entry
->identity
, "NEW");
2094 control_event_guard_deferred();
2095 log_entry_guards(LOG_INFO
);
2099 /** If the use of entry guards is configured, choose more entry guards
2100 * until we have enough in the list. */
2102 pick_entry_guards(void)
2104 or_options_t
*options
= get_options();
2107 tor_assert(entry_guards
);
2109 while (num_live_entry_guards() < options
->NumEntryGuards
) {
2110 if (!add_an_entry_guard(NULL
, 0))
2115 entry_guards_changed();
2118 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2119 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2120 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2122 /** Release all storage held by <b>e</b>. */
2124 entry_guard_free(entry_guard_t
*e
)
2127 tor_free(e
->chosen_by_version
);
2131 /** Remove any entry guard which was selected by an unknown version of Tor,
2132 * or which was selected by a version of Tor that's known to select
2133 * entry guards badly. */
2135 remove_obsolete_entry_guards(void)
2138 time_t this_month
= start_of_month(time(NULL
));
2140 for (i
= 0; i
< smartlist_len(entry_guards
); ++i
) {
2141 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2142 const char *ver
= entry
->chosen_by_version
;
2143 const char *msg
= NULL
;
2145 int version_is_bad
= 0, date_is_bad
= 0;
2147 msg
= "does not say what version of Tor it was selected by";
2149 } else if (tor_version_parse(ver
, &v
)) {
2150 msg
= "does not seem to be from any recognized version of Tor";
2152 } else if ((tor_version_as_new_as(ver
, "0.1.0.10-alpha") &&
2153 !tor_version_as_new_as(ver
, "0.1.2.16-dev")) ||
2154 (tor_version_as_new_as(ver
, "0.2.0.0-alpha") &&
2155 !tor_version_as_new_as(ver
, "0.2.0.6-alpha"))) {
2156 msg
= "was selected without regard for guard bandwidth";
2158 } else if (entry
->chosen_on_date
+ 3600*24*35 < this_month
) {
2159 /* It's been more than a month, and probably more like two since
2160 * chosen_on_date is clipped to the beginning of its month. */
2161 msg
= "was selected several months ago";
2165 if (version_is_bad
|| date_is_bad
) { /* we need to drop it */
2166 char dbuf
[HEX_DIGEST_LEN
+1];
2168 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2169 log_fn(version_is_bad
? LOG_NOTICE
: LOG_INFO
, LD_CIRC
,
2170 "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
2171 entry
->nickname
, dbuf
, msg
, ver
?escaped(ver
):"none");
2172 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2173 entry_guard_free(entry
);
2174 smartlist_del_keeporder(entry_guards
, i
--);
2175 log_entry_guards(LOG_INFO
);
2180 return changed
? 1 : 0;
2183 /** Remove all entry guards that have been down or unlisted for so
2184 * long that we don't think they'll come up again. Return 1 if we
2185 * removed any, or 0 if we did nothing. */
2187 remove_dead_entry_guards(void)
2189 char dbuf
[HEX_DIGEST_LEN
+1];
2190 char tbuf
[ISO_TIME_LEN
+1];
2191 time_t now
= time(NULL
);
2195 for (i
= 0; i
< smartlist_len(entry_guards
); ) {
2196 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2197 if (entry
->bad_since
&&
2198 entry
->bad_since
+ ENTRY_GUARD_REMOVE_AFTER
< now
) {
2200 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2201 format_local_iso_time(tbuf
, entry
->bad_since
);
2202 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been down or unlisted "
2203 "since %s local time; removing.",
2204 entry
->nickname
, dbuf
, tbuf
);
2205 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2206 entry_guard_free(entry
);
2207 smartlist_del_keeporder(entry_guards
, i
);
2208 log_entry_guards(LOG_INFO
);
2213 return changed
? 1 : 0;
2216 /** A new directory or router-status has arrived; update the down/listed
2217 * status of the entry guards.
2219 * An entry is 'down' if the directory lists it as nonrunning.
2220 * An entry is 'unlisted' if the directory doesn't include it.
2222 * Don't call this on startup; only on a fresh download. Otherwise we'll
2223 * think that things are unlisted.
2226 entry_guards_compute_status(void)
2230 int severity
= LOG_DEBUG
;
2231 or_options_t
*options
;
2232 digestmap_t
*reasons
;
2236 options
= get_options();
2240 reasons
= digestmap_new();
2241 SMARTLIST_FOREACH_BEGIN(entry_guards
, entry_guard_t
*, entry
)
2243 routerinfo_t
*r
= router_get_by_digest(entry
->identity
);
2244 const char *reason
= NULL
;
2245 if (entry_guard_set_status(entry
, r
, now
, options
, &reason
))
2248 if (entry
->bad_since
)
2251 digestmap_set(reasons
, entry
->identity
, (char*)reason
);
2253 SMARTLIST_FOREACH_END(entry
);
2255 if (remove_dead_entry_guards())
2258 severity
= changed
? LOG_DEBUG
: LOG_INFO
;
2261 SMARTLIST_FOREACH_BEGIN(entry_guards
, entry_guard_t
*, entry
) {
2262 const char *reason
= digestmap_get(reasons
, entry
->identity
);
2263 log_info(LD_CIRC
, "Summary: Entry '%s' is %s, %s%s%s, and %s.",
2265 entry
->unreachable_since
? "unreachable" : "reachable",
2266 entry
->bad_since
? "unusable" : "usable",
2268 reason
? reason
: "",
2269 entry_is_live(entry
, 0, 1, 0) ? "live" : "not live");
2270 } SMARTLIST_FOREACH_END(entry
);
2271 log_info(LD_CIRC
, " (%d/%d entry guards are usable/new)",
2272 num_live_entry_guards(), smartlist_len(entry_guards
));
2273 log_entry_guards(LOG_INFO
);
2274 entry_guards_changed();
2277 digestmap_free(reasons
, NULL
);
2280 /** Called when a connection to an OR with the identity digest <b>digest</b>
2281 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2282 * If the OR is an entry, change that entry's up/down status.
2283 * Return 0 normally, or -1 if we want to tear down the new connection.
2285 * If <b>mark_relay_status</b>, also call router_set_status() on this
2288 * XXX022 change succeeded and mark_relay_status into 'int flags'.
2291 entry_guard_register_connect_status(const char *digest
, int succeeded
,
2292 int mark_relay_status
, time_t now
)
2295 int refuse_conn
= 0;
2296 int first_contact
= 0;
2297 entry_guard_t
*entry
= NULL
;
2299 char buf
[HEX_DIGEST_LEN
+1];
2304 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2306 if (!memcmp(e
->identity
, digest
, DIGEST_LEN
)) {
2316 base16_encode(buf
, sizeof(buf
), entry
->identity
, DIGEST_LEN
);
2319 if (entry
->unreachable_since
) {
2320 log_info(LD_CIRC
, "Entry guard '%s' (%s) is now reachable again. Good.",
2321 entry
->nickname
, buf
);
2322 entry
->can_retry
= 0;
2323 entry
->unreachable_since
= 0;
2324 entry
->last_attempted
= now
;
2325 control_event_guard(entry
->nickname
, entry
->identity
, "UP");
2328 if (!entry
->made_contact
) {
2329 entry
->made_contact
= 1;
2330 first_contact
= changed
= 1;
2332 } else { /* ! succeeded */
2333 if (!entry
->made_contact
) {
2334 /* We've never connected to this one. */
2336 "Connection to never-contacted entry guard '%s' (%s) failed. "
2337 "Removing from the list. %d/%d entry guards usable/new.",
2338 entry
->nickname
, buf
,
2339 num_live_entry_guards()-1, smartlist_len(entry_guards
)-1);
2340 entry_guard_free(entry
);
2341 smartlist_del_keeporder(entry_guards
, idx
);
2342 log_entry_guards(LOG_INFO
);
2344 } else if (!entry
->unreachable_since
) {
2345 log_info(LD_CIRC
, "Unable to connect to entry guard '%s' (%s). "
2346 "Marking as unreachable.", entry
->nickname
, buf
);
2347 entry
->unreachable_since
= entry
->last_attempted
= now
;
2348 control_event_guard(entry
->nickname
, entry
->identity
, "DOWN");
2350 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2352 char tbuf
[ISO_TIME_LEN
+1];
2353 format_iso_time(tbuf
, entry
->unreachable_since
);
2354 log_debug(LD_CIRC
, "Failed to connect to unreachable entry guard "
2355 "'%s' (%s). It has been unreachable since %s.",
2356 entry
->nickname
, buf
, tbuf
);
2357 entry
->last_attempted
= now
;
2358 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2362 /* if the caller asked us to, also update the is_running flags for this
2364 if (mark_relay_status
)
2365 router_set_status(digest
, succeeded
);
2367 if (first_contact
) {
2368 /* We've just added a new long-term entry guard. Perhaps the network just
2369 * came back? We should give our earlier entries another try too,
2370 * and close this connection so we don't use it before we've given
2371 * the others a shot. */
2372 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2375 if (e
->made_contact
) {
2376 routerinfo_t
*r
= entry_is_live(e
, 0, 1, 1);
2377 if (r
&& e
->unreachable_since
) {
2385 "Connected to new entry guard '%s' (%s). Marking earlier "
2386 "entry guards up. %d/%d entry guards usable/new.",
2387 entry
->nickname
, buf
,
2388 num_live_entry_guards(), smartlist_len(entry_guards
));
2389 log_entry_guards(LOG_INFO
);
2395 entry_guards_changed();
2396 return refuse_conn
? -1 : 0;
2399 /** When we try to choose an entry guard, should we parse and add
2400 * config's EntryNodes first? */
2401 static int should_add_entry_nodes
= 0;
2403 /** Called when the value of EntryNodes changes in our configuration. */
2405 entry_nodes_should_be_added(void)
2407 log_info(LD_CIRC
, "New EntryNodes config option detected. Will use.");
2408 should_add_entry_nodes
= 1;
2411 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2412 * of guard nodes, at the front. */
2414 entry_guards_prepend_from_config(void)
2416 or_options_t
*options
= get_options();
2417 smartlist_t
*entry_routers
, *entry_fps
;
2418 smartlist_t
*old_entry_guards_on_list
, *old_entry_guards_not_on_list
;
2419 tor_assert(entry_guards
);
2421 should_add_entry_nodes
= 0;
2423 if (!options
->EntryNodes
) {
2424 /* It's possible that a controller set EntryNodes, thus making
2425 * should_add_entry_nodes set, then cleared it again, all before the
2426 * call to choose_random_entry() that triggered us. If so, just return.
2431 if (options
->EntryNodes
) {
2432 char *string
= routerset_to_string(options
->EntryNodes
);
2433 log_info(LD_CIRC
,"Adding configured EntryNodes '%s'.", string
);
2437 entry_routers
= smartlist_create();
2438 entry_fps
= smartlist_create();
2439 old_entry_guards_on_list
= smartlist_create();
2440 old_entry_guards_not_on_list
= smartlist_create();
2442 /* Split entry guards into those on the list and those not. */
2444 /* XXXX022 Now that we allow countries and IP ranges in EntryNodes, this is
2445 * potentially an enormous list. For now, we disable such values for
2446 * EntryNodes in options_validate(); really, this wants a better solution.
2447 * Perhaps we should do this calculation once whenever the list of routers
2448 * changes or the entrynodes setting changes.
2450 routerset_get_all_routers(entry_routers
, options
->EntryNodes
, 0);
2451 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
,
2452 smartlist_add(entry_fps
,ri
->cache_info
.identity_digest
));
2453 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2454 if (smartlist_digest_isin(entry_fps
, e
->identity
))
2455 smartlist_add(old_entry_guards_on_list
, e
);
2457 smartlist_add(old_entry_guards_not_on_list
, e
);
2460 /* Remove all currently configured entry guards from entry_routers. */
2461 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2462 if (is_an_entry_guard(ri
->cache_info
.identity_digest
)) {
2463 SMARTLIST_DEL_CURRENT(entry_routers
, ri
);
2467 /* Now build the new entry_guards list. */
2468 smartlist_clear(entry_guards
);
2469 /* First, the previously configured guards that are in EntryNodes. */
2470 smartlist_add_all(entry_guards
, old_entry_guards_on_list
);
2471 /* Next, the rest of EntryNodes */
2472 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2473 add_an_entry_guard(ri
, 0);
2475 /* Finally, the remaining EntryNodes, unless we're strict */
2476 if (options
->StrictEntryNodes
) {
2477 SMARTLIST_FOREACH(old_entry_guards_not_on_list
, entry_guard_t
*, e
,
2478 entry_guard_free(e
));
2480 smartlist_add_all(entry_guards
, old_entry_guards_not_on_list
);
2483 smartlist_free(entry_routers
);
2484 smartlist_free(entry_fps
);
2485 smartlist_free(old_entry_guards_on_list
);
2486 smartlist_free(old_entry_guards_not_on_list
);
2487 entry_guards_changed();
2490 /** Return 1 if we're fine adding arbitrary routers out of the
2491 * directory to our entry guard list. Else return 0. */
2493 entry_list_can_grow(or_options_t
*options
)
2495 if (options
->StrictEntryNodes
)
2497 if (options
->UseBridges
)
2502 /** Pick a live (up and listed) entry guard from entry_guards. If
2503 * <b>state</b> is non-NULL, this is for a specific circuit --
2504 * make sure not to pick this circuit's exit or any node in the
2505 * exit's family. If <b>state</b> is NULL, we're looking for a random
2506 * guard (likely a bridge). */
2508 choose_random_entry(cpath_build_state_t
*state
)
2510 or_options_t
*options
= get_options();
2511 smartlist_t
*live_entry_guards
= smartlist_create();
2512 smartlist_t
*exit_family
= smartlist_create();
2513 routerinfo_t
*chosen_exit
= state
?build_state_get_exit_router(state
) : NULL
;
2514 routerinfo_t
*r
= NULL
;
2515 int need_uptime
= state
? state
->need_uptime
: 0;
2516 int need_capacity
= state
? state
->need_capacity
: 0;
2517 int consider_exit_family
= 0;
2520 smartlist_add(exit_family
, chosen_exit
);
2521 routerlist_add_family(exit_family
, chosen_exit
);
2522 consider_exit_family
= 1;
2526 entry_guards
= smartlist_create();
2528 if (should_add_entry_nodes
)
2529 entry_guards_prepend_from_config();
2531 if (entry_list_can_grow(options
) &&
2533 smartlist_len(entry_guards
) < options
->NumEntryGuards
))
2534 pick_entry_guards();
2537 smartlist_clear(live_entry_guards
);
2538 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2540 r
= entry_is_live(entry
, need_uptime
, need_capacity
, 0);
2541 if (r
&& (!consider_exit_family
|| !smartlist_isin(exit_family
, r
))) {
2542 smartlist_add(live_entry_guards
, r
);
2543 if (!entry
->made_contact
) {
2544 /* Always start with the first not-yet-contacted entry
2545 * guard. Otherwise we might add several new ones, pick
2546 * the second new one, and now we've expanded our entry
2547 * guard list without needing to. */
2548 goto choose_and_finish
;
2550 if (smartlist_len(live_entry_guards
) >= options
->NumEntryGuards
)
2551 break; /* we have enough */
2555 /* Try to have at least 2 choices available. This way we don't
2556 * get stuck with a single live-but-crummy entry and just keep
2558 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2559 if (smartlist_len(live_entry_guards
) < 2) {
2560 if (entry_list_can_grow(options
)) {
2561 /* still no? try adding a new entry then */
2562 /* XXX if guard doesn't imply fast and stable, then we need
2563 * to tell add_an_entry_guard below what we want, or it might
2564 * be a long time til we get it. -RD */
2565 r
= add_an_entry_guard(NULL
, 0);
2567 entry_guards_changed();
2568 /* XXX we start over here in case the new node we added shares
2569 * a family with our exit node. There's a chance that we'll just
2570 * load up on entry guards here, if the network we're using is
2571 * one big family. Perhaps we should teach add_an_entry_guard()
2572 * to understand nodes-to-avoid-if-possible? -RD */
2576 if (!r
&& need_uptime
) {
2577 need_uptime
= 0; /* try without that requirement */
2580 if (!r
&& need_capacity
) {
2581 /* still no? last attempt, try without requiring capacity */
2585 if (!r
&& !entry_list_can_grow(options
) && consider_exit_family
) {
2586 /* still no? if we're using bridges or have strictentrynodes
2587 * set, and our chosen exit is in the same family as all our
2588 * bridges/entry guards, then be flexible about families. */
2589 consider_exit_family
= 0;
2592 /* live_entry_guards may be empty below. Oh well, we tried. */
2596 if (entry_list_can_grow(options
)) {
2597 /* We choose uniformly at random here, because choose_good_entry_server()
2598 * already weights its choices by bandwidth, so we don't want to
2599 * *double*-weight our guard selection. */
2600 r
= smartlist_choose(live_entry_guards
);
2602 /* We need to weight by bandwidth, because our bridges or entryguards
2603 * were not already selected proportional to their bandwidth. */
2604 r
= routerlist_sl_choose_by_bandwidth(live_entry_guards
, WEIGHT_FOR_GUARD
);
2606 smartlist_free(live_entry_guards
);
2607 smartlist_free(exit_family
);
2611 /** Helper: Return the start of the month containing <b>time</b>. */
2613 start_of_month(time_t now
)
2616 tor_gmtime_r(&now
, &tm
);
2621 return tor_timegm(&tm
);
2624 /** Parse <b>state</b> and learn about the entry guards it describes.
2625 * If <b>set</b> is true, and there are no errors, replace the global
2626 * entry_list with what we find.
2627 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2628 * describing the error, and return -1.
2631 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
2633 entry_guard_t
*node
= NULL
;
2634 smartlist_t
*new_entry_guards
= smartlist_create();
2635 config_line_t
*line
;
2636 time_t now
= time(NULL
);
2637 const char *state_version
= state
->TorVersion
;
2638 digestmap_t
*added_by
= digestmap_new();
2641 for (line
= state
->EntryGuards
; line
; line
= line
->next
) {
2642 if (!strcasecmp(line
->key
, "EntryGuard")) {
2643 smartlist_t
*args
= smartlist_create();
2644 node
= tor_malloc_zero(sizeof(entry_guard_t
));
2645 /* all entry guards on disk have been contacted */
2646 node
->made_contact
= 1;
2647 smartlist_add(new_entry_guards
, node
);
2648 smartlist_split_string(args
, line
->value
, " ",
2649 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2650 if (smartlist_len(args
)<2) {
2651 *msg
= tor_strdup("Unable to parse entry nodes: "
2652 "Too few arguments to EntryGuard");
2653 } else if (!is_legal_nickname(smartlist_get(args
,0))) {
2654 *msg
= tor_strdup("Unable to parse entry nodes: "
2655 "Bad nickname for EntryGuard");
2657 strlcpy(node
->nickname
, smartlist_get(args
,0), MAX_NICKNAME_LEN
+1);
2658 if (base16_decode(node
->identity
, DIGEST_LEN
, smartlist_get(args
,1),
2659 strlen(smartlist_get(args
,1)))<0) {
2660 *msg
= tor_strdup("Unable to parse entry nodes: "
2661 "Bad hex digest for EntryGuard");
2664 SMARTLIST_FOREACH(args
, char*, cp
, tor_free(cp
));
2665 smartlist_free(args
);
2668 } else if (!strcasecmp(line
->key
, "EntryGuardDownSince") ||
2669 !strcasecmp(line
->key
, "EntryGuardUnlistedSince")) {
2671 time_t last_try
= 0;
2673 *msg
= tor_strdup("Unable to parse entry nodes: "
2674 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2677 if (parse_iso_time(line
->value
, &when
)<0) {
2678 *msg
= tor_strdup("Unable to parse entry nodes: "
2679 "Bad time in EntryGuardDownSince/UnlistedSince");
2683 /* It's a bad idea to believe info in the future: you can wind
2684 * up with timeouts that aren't allowed to happen for years. */
2687 if (strlen(line
->value
) >= ISO_TIME_LEN
+ISO_TIME_LEN
+1) {
2688 /* ignore failure */
2689 (void) parse_iso_time(line
->value
+ISO_TIME_LEN
+1, &last_try
);
2691 if (!strcasecmp(line
->key
, "EntryGuardDownSince")) {
2692 node
->unreachable_since
= when
;
2693 node
->last_attempted
= last_try
;
2695 node
->bad_since
= when
;
2697 } else if (!strcasecmp(line
->key
, "EntryGuardAddedBy")) {
2699 /* format is digest version date */
2700 if (strlen(line
->value
) < HEX_DIGEST_LEN
+1+1+1+ISO_TIME_LEN
) {
2701 log_warn(LD_BUG
, "EntryGuardAddedBy line is not long enough.");
2704 if (base16_decode(d
, sizeof(d
), line
->value
, HEX_DIGEST_LEN
)<0 ||
2705 line
->value
[HEX_DIGEST_LEN
] != ' ') {
2706 log_warn(LD_BUG
, "EntryGuardAddedBy line %s does not begin with "
2707 "hex digest", escaped(line
->value
));
2710 digestmap_set(added_by
, d
, tor_strdup(line
->value
+HEX_DIGEST_LEN
+1));
2712 log_warn(LD_BUG
, "Unexpected key %s", line
->key
);
2716 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2719 char *val
= digestmap_get(added_by
, e
->identity
);
2720 if (val
&& (sp
= strchr(val
, ' '))) {
2723 if (parse_iso_time(sp
, &when
)<0) {
2724 log_warn(LD_BUG
, "Can't read time %s in EntryGuardAddedBy", sp
);
2726 e
->chosen_by_version
= tor_strdup(val
);
2727 e
->chosen_on_date
= when
;
2730 if (state_version
) {
2731 e
->chosen_by_version
= tor_strdup(state_version
);
2732 e
->chosen_on_date
= start_of_month(time(NULL
));
2738 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2739 entry_guard_free(e
));
2740 smartlist_free(new_entry_guards
);
2741 } else { /* !err && set */
2743 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2744 entry_guard_free(e
));
2745 smartlist_free(entry_guards
);
2747 entry_guards
= new_entry_guards
;
2748 entry_guards_dirty
= 0;
2749 /* XXX022 hand new_entry_guards to this func, and move it up a
2750 * few lines, so we don't have to re-dirty it */
2751 if (remove_obsolete_entry_guards())
2752 entry_guards_dirty
= 1;
2754 digestmap_free(added_by
, _tor_free
);
2755 return *msg
? -1 : 0;
2758 /** Our list of entry guards has changed, or some element of one
2759 * of our entry guards has changed. Write the changes to disk within
2760 * the next few minutes.
2763 entry_guards_changed(void)
2766 entry_guards_dirty
= 1;
2768 /* or_state_save() will call entry_guards_update_state(). */
2769 when
= get_options()->AvoidDiskWrites
? time(NULL
) + 3600 : time(NULL
)+600;
2770 or_state_mark_dirty(get_or_state(), when
);
2773 /** If the entry guard info has not changed, do nothing and return.
2774 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2775 * a new one out of the global entry_guards list, and then mark
2776 * <b>state</b> dirty so it will get saved to disk.
2779 entry_guards_update_state(or_state_t
*state
)
2781 config_line_t
**next
, *line
;
2782 if (! entry_guards_dirty
)
2785 config_free_lines(state
->EntryGuards
);
2786 next
= &state
->EntryGuards
;
2789 entry_guards
= smartlist_create();
2790 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2792 char dbuf
[HEX_DIGEST_LEN
+1];
2793 if (!e
->made_contact
)
2794 continue; /* don't write this one to disk */
2795 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2796 line
->key
= tor_strdup("EntryGuard");
2797 line
->value
= tor_malloc(HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2);
2798 base16_encode(dbuf
, sizeof(dbuf
), e
->identity
, DIGEST_LEN
);
2799 tor_snprintf(line
->value
,HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2,
2800 "%s %s", e
->nickname
, dbuf
);
2801 next
= &(line
->next
);
2802 if (e
->unreachable_since
) {
2803 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2804 line
->key
= tor_strdup("EntryGuardDownSince");
2805 line
->value
= tor_malloc(ISO_TIME_LEN
+1+ISO_TIME_LEN
+1);
2806 format_iso_time(line
->value
, e
->unreachable_since
);
2807 if (e
->last_attempted
) {
2808 line
->value
[ISO_TIME_LEN
] = ' ';
2809 format_iso_time(line
->value
+ISO_TIME_LEN
+1, e
->last_attempted
);
2811 next
= &(line
->next
);
2814 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2815 line
->key
= tor_strdup("EntryGuardUnlistedSince");
2816 line
->value
= tor_malloc(ISO_TIME_LEN
+1);
2817 format_iso_time(line
->value
, e
->bad_since
);
2818 next
= &(line
->next
);
2820 if (e
->chosen_on_date
&& e
->chosen_by_version
&&
2821 !strchr(e
->chosen_by_version
, ' ')) {
2822 char d
[HEX_DIGEST_LEN
+1];
2823 char t
[ISO_TIME_LEN
+1];
2825 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2826 line
->key
= tor_strdup("EntryGuardAddedBy");
2827 val_len
= (HEX_DIGEST_LEN
+1+strlen(e
->chosen_by_version
)
2829 line
->value
= tor_malloc(val_len
);
2830 base16_encode(d
, sizeof(d
), e
->identity
, DIGEST_LEN
);
2831 format_iso_time(t
, e
->chosen_on_date
);
2832 tor_snprintf(line
->value
, val_len
, "%s %s %s",
2833 d
, e
->chosen_by_version
, t
);
2834 next
= &(line
->next
);
2837 if (!get_options()->AvoidDiskWrites
)
2838 or_state_mark_dirty(get_or_state(), 0);
2839 entry_guards_dirty
= 0;
2842 /** If <b>question</b> is the string "entry-guards", then dump
2843 * to *<b>answer</b> a newly allocated string describing all of
2844 * the nodes in the global entry_guards list. See control-spec.txt
2846 * For backward compatibility, we also handle the string "helper-nodes".
2849 getinfo_helper_entry_guards(control_connection_t
*conn
,
2850 const char *question
, char **answer
)
2852 int use_long_names
= conn
->use_long_names
;
2854 if (!strcmp(question
,"entry-guards") ||
2855 !strcmp(question
,"helper-nodes")) {
2856 smartlist_t
*sl
= smartlist_create();
2857 char tbuf
[ISO_TIME_LEN
+1];
2858 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
2860 entry_guards
= smartlist_create();
2861 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2863 size_t len
= MAX_VERBOSE_NICKNAME_LEN
+ISO_TIME_LEN
+32;
2864 char *c
= tor_malloc(len
);
2865 const char *status
= NULL
;
2867 if (!e
->made_contact
) {
2868 status
= "never-connected";
2869 } else if (e
->bad_since
) {
2870 when
= e
->bad_since
;
2871 status
= "unusable";
2875 if (use_long_names
) {
2876 routerinfo_t
*ri
= router_get_by_digest(e
->identity
);
2878 router_get_verbose_nickname(nbuf
, ri
);
2881 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
2882 /* e->nickname field is not very reliable if we don't know about
2883 * this router any longer; don't include it. */
2886 base16_encode(nbuf
, sizeof(nbuf
), e
->identity
, DIGEST_LEN
);
2889 format_iso_time(tbuf
, when
);
2890 tor_snprintf(c
, len
, "%s %s %s\n", nbuf
, status
, tbuf
);
2892 tor_snprintf(c
, len
, "%s %s\n", nbuf
, status
);
2894 smartlist_add(sl
, c
);
2896 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2897 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2903 /** Information about a configured bridge. Currently this just matches the
2904 * ones in the torrc file, but one day we may be able to learn about new
2905 * bridges on our own, and remember them in the state file. */
2907 /** Address of the bridge. */
2909 /** TLS port for the bridge. */
2911 /** Expected identity digest, or all zero bytes if we don't know what the
2912 * digest should be. */
2913 char identity
[DIGEST_LEN
];
2914 /** When should we next try to fetch a descriptor for this bridge? */
2915 download_status_t fetch_status
;
2918 /** A list of configured bridges. Whenever we actually get a descriptor
2919 * for one, we add it as an entry guard. */
2920 static smartlist_t
*bridge_list
= NULL
;
2922 /** Initialize the bridge list to empty, creating it if needed. */
2924 clear_bridge_list(void)
2927 bridge_list
= smartlist_create();
2928 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, b
, tor_free(b
));
2929 smartlist_clear(bridge_list
);
2932 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2933 * (either by comparing keys if possible, else by comparing addr/port).
2934 * Else return NULL. */
2935 static bridge_info_t
*
2936 routerinfo_get_configured_bridge(routerinfo_t
*ri
)
2940 SMARTLIST_FOREACH_BEGIN(bridge_list
, bridge_info_t
*, bridge
)
2942 if (tor_digest_is_zero(bridge
->identity
) &&
2943 tor_addr_eq_ipv4h(&bridge
->addr
, ri
->addr
) &&
2944 bridge
->port
== ri
->or_port
)
2946 if (!memcmp(bridge
->identity
, ri
->cache_info
.identity_digest
,
2950 SMARTLIST_FOREACH_END(bridge
);
2954 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
2956 routerinfo_is_a_configured_bridge(routerinfo_t
*ri
)
2958 return routerinfo_get_configured_bridge(ri
) ? 1 : 0;
2961 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2962 * is set, it tells us the identity key too. */
2964 bridge_add_from_config(const tor_addr_t
*addr
, uint16_t port
, char *digest
)
2966 bridge_info_t
*b
= tor_malloc_zero(sizeof(bridge_info_t
));
2967 tor_addr_copy(&b
->addr
, addr
);
2970 memcpy(b
->identity
, digest
, DIGEST_LEN
);
2971 b
->fetch_status
.schedule
= DL_SCHED_BRIDGE
;
2973 bridge_list
= smartlist_create();
2974 smartlist_add(bridge_list
, b
);
2977 /** If <b>digest</b> is one of our known bridges, return it. */
2978 static bridge_info_t
*
2979 find_bridge_by_digest(const char *digest
)
2981 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2983 if (!memcmp(bridge
->identity
, digest
, DIGEST_LEN
))
2989 /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
2990 * is a helpful string describing this bridge. */
2992 launch_direct_bridge_descriptor_fetch(bridge_info_t
*bridge
)
2996 if (connection_get_by_type_addr_port_purpose(
2997 CONN_TYPE_DIR
, &bridge
->addr
, bridge
->port
,
2998 DIR_PURPOSE_FETCH_SERVERDESC
))
2999 return; /* it's already on the way */
3001 address
= tor_dup_addr(&bridge
->addr
);
3002 directory_initiate_command(address
, &bridge
->addr
,
3004 0, /* does not matter */
3005 1, bridge
->identity
,
3006 DIR_PURPOSE_FETCH_SERVERDESC
,
3007 ROUTER_PURPOSE_BRIDGE
,
3008 0, "authority.z", NULL
, 0, 0);
3012 /** Fetching the bridge descriptor from the bridge authority returned a
3013 * "not found". Fall back to trying a direct fetch. */
3015 retry_bridge_descriptor_fetch_directly(const char *digest
)
3017 bridge_info_t
*bridge
= find_bridge_by_digest(digest
);
3019 return; /* not found? oh well. */
3021 launch_direct_bridge_descriptor_fetch(bridge
);
3024 /** For each bridge in our list for which we don't currently have a
3025 * descriptor, fetch a new copy of its descriptor -- either directly
3026 * from the bridge or via a bridge authority. */
3028 fetch_bridge_descriptors(time_t now
)
3030 or_options_t
*options
= get_options();
3031 int num_bridge_auths
= get_n_authorities(BRIDGE_AUTHORITY
);
3032 int ask_bridge_directly
;
3033 int can_use_bridge_authority
;
3038 SMARTLIST_FOREACH_BEGIN(bridge_list
, bridge_info_t
*, bridge
)
3040 if (!download_status_is_ready(&bridge
->fetch_status
, now
,
3041 IMPOSSIBLE_TO_DOWNLOAD
))
3042 continue; /* don't bother, no need to retry yet */
3044 /* schedule another fetch as if this one will fail, in case it does */
3045 download_status_failed(&bridge
->fetch_status
, 0);
3047 can_use_bridge_authority
= !tor_digest_is_zero(bridge
->identity
) &&
3049 ask_bridge_directly
= !can_use_bridge_authority
||
3050 !options
->UpdateBridgesFromAuthority
;
3051 log_debug(LD_DIR
, "ask_bridge_directly=%d (%d, %d, %d)",
3052 ask_bridge_directly
, tor_digest_is_zero(bridge
->identity
),
3053 !options
->UpdateBridgesFromAuthority
, !num_bridge_auths
);
3055 if (ask_bridge_directly
&&
3056 !fascist_firewall_allows_address_or(&bridge
->addr
, bridge
->port
)) {
3057 log_notice(LD_DIR
, "Bridge at '%s:%d' isn't reachable by our "
3058 "firewall policy. %s.", fmt_addr(&bridge
->addr
),
3060 can_use_bridge_authority
?
3061 "Asking bridge authority instead" : "Skipping");
3062 if (can_use_bridge_authority
)
3063 ask_bridge_directly
= 0;
3068 if (ask_bridge_directly
) {
3069 /* we need to ask the bridge itself for its descriptor. */
3070 launch_direct_bridge_descriptor_fetch(bridge
);
3072 /* We have a digest and we want to ask an authority. We could
3073 * combine all the requests into one, but that may give more
3074 * hints to the bridge authority than we want to give. */
3075 char resource
[10 + HEX_DIGEST_LEN
];
3076 memcpy(resource
, "fp/", 3);
3077 base16_encode(resource
+3, HEX_DIGEST_LEN
+1,
3078 bridge
->identity
, DIGEST_LEN
);
3079 memcpy(resource
+3+HEX_DIGEST_LEN
, ".z", 3);
3080 log_info(LD_DIR
, "Fetching bridge info '%s' from bridge authority.",
3082 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
3083 ROUTER_PURPOSE_BRIDGE
, resource
, 0);
3086 SMARTLIST_FOREACH_END(bridge
);
3089 /** We just learned a descriptor for a bridge. See if that
3090 * digest is in our entry guard list, and add it if not. */
3092 learned_bridge_descriptor(routerinfo_t
*ri
, int from_cache
)
3095 tor_assert(ri
->purpose
== ROUTER_PURPOSE_BRIDGE
);
3096 if (get_options()->UseBridges
) {
3097 int first
= !any_bridge_descriptors_known();
3098 bridge_info_t
*bridge
= routerinfo_get_configured_bridge(ri
);
3099 time_t now
= time(NULL
);
3102 if (bridge
) { /* if we actually want to use this one */
3103 /* it's here; schedule its re-fetch for a long time from now. */
3105 download_status_reset(&bridge
->fetch_status
);
3107 add_an_entry_guard(ri
, 1);
3108 log_notice(LD_DIR
, "new bridge descriptor '%s' (%s)", ri
->nickname
,
3109 from_cache
? "cached" : "fresh");
3111 routerlist_retry_directory_downloads(now
);
3116 /** Return 1 if any of our entry guards have descriptors that
3117 * are marked with purpose 'bridge' and are running. Else return 0.
3119 * We use this function to decide if we're ready to start building
3120 * circuits through our bridges, or if we need to wait until the
3121 * directory "server/authority" requests finish. */
3123 any_bridge_descriptors_known(void)
3125 tor_assert(get_options()->UseBridges
);
3126 return choose_random_entry(NULL
)!=NULL
? 1 : 0;
3129 /** Return 1 if there are any directory conns fetching bridge descriptors
3130 * that aren't marked for close. We use this to guess if we should tell
3131 * the controller that we have a problem. */
3133 any_pending_bridge_descriptor_fetches(void)
3135 smartlist_t
*conns
= get_connection_array();
3136 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3138 if (conn
->type
== CONN_TYPE_DIR
&&
3139 conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
3140 TO_DIR_CONN(conn
)->router_purpose
== ROUTER_PURPOSE_BRIDGE
&&
3141 !conn
->marked_for_close
&&
3142 conn
->linked
&& !conn
->linked_conn
->marked_for_close
) {
3143 log_debug(LD_DIR
, "found one: %s", conn
->address
);
3150 /** Return 1 if we have at least one descriptor for a bridge and
3151 * all descriptors we know are down. Else return 0. If <b>act</b> is
3152 * 1, then mark the down bridges up; else just observe and report. */
3154 bridges_retry_helper(int act
)
3158 int any_running
= 0;
3160 entry_guards
= smartlist_create();
3161 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3163 ri
= router_get_by_digest(e
->identity
);
3164 if (ri
&& ri
->purpose
== ROUTER_PURPOSE_BRIDGE
) {
3167 any_running
= 1; /* some bridge is both known and running */
3168 else if (act
) { /* mark it for retry */
3175 log_debug(LD_DIR
, "any_known %d, any_running %d", any_known
, any_running
);
3176 return any_known
&& !any_running
;
3179 /** Do we know any descriptors for our bridges, and are they all
3182 bridges_known_but_down(void)
3184 return bridges_retry_helper(0);
3187 /** Mark all down known bridges up. */
3189 bridges_retry_all(void)
3191 bridges_retry_helper(1);
3194 /** Release all storage held by the list of entry guards and related
3195 * memory structs. */
3197 entry_guards_free_all(void)
3200 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3201 entry_guard_free(e
));
3202 smartlist_free(entry_guards
);
3203 entry_guards
= NULL
;
3205 clear_bridge_list();
3206 smartlist_free(bridge_list
);