1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
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
));
139 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
141 if (!hop
->extend_info
)
144 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
145 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
))) {
146 router_get_verbose_nickname(elt
, ri
);
147 } else if (hop
->extend_info
->nickname
&&
148 is_legal_nickname(hop
->extend_info
->nickname
)) {
150 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
151 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
152 elt
[HEX_DIGEST_LEN
+1]= '~';
153 strlcpy(elt
+HEX_DIGEST_LEN
+2,
154 hop
->extend_info
->nickname
, MAX_NICKNAME_LEN
+1);
157 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
158 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
160 } else { /* ! verbose_names */
161 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
)) &&
163 elt
= tor_strdup(hop
->extend_info
->nickname
);
165 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
167 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
168 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
173 size_t len
= strlen(elt
)+2+strlen(states
[hop
->state
])+1;
174 char *v
= tor_malloc(len
);
175 tor_assert(hop
->state
<= 2);
176 tor_snprintf(v
,len
,"%s(%s)",elt
,states
[hop
->state
]);
177 smartlist_add(elements
, v
);
180 smartlist_add(elements
, elt
);
183 } while (hop
!= circ
->cpath
);
185 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
186 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
187 smartlist_free(elements
);
191 /** If <b>verbose</b> is false, allocate and return a comma-separated
192 * list of the currently built elements of circuit_t. If
193 * <b>verbose</b> is true, also list information about link status in
194 * a more verbose format using spaces.
197 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
199 return circuit_list_path_impl(circ
, verbose
, 0);
202 /** Allocate and return a comma-separated list of the currently built elements
203 * of circuit_t, giving each as a verbose nickname.
206 circuit_list_path_for_controller(origin_circuit_t
*circ
)
208 return circuit_list_path_impl(circ
, 0, 1);
211 /** Log, at severity <b>severity</b>, the nicknames of each router in
212 * circ's cpath. Also log the length of the cpath, and the intended
216 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
218 char *s
= circuit_list_path(circ
,1);
219 log(severity
,domain
,"%s",s
);
223 /** Tell the rep(utation)hist(ory) module about the status of the links
224 * in circ. Hops that have become OPEN are marked as successfully
225 * extended; the _first_ hop that isn't open (if any) is marked as
228 /* XXXX Someday we should learn from OR circuits too. */
230 circuit_rep_hist_note_result(origin_circuit_t
*circ
)
233 char *prev_digest
= NULL
;
234 routerinfo_t
*router
;
236 if (!hop
) /* circuit hasn't started building yet. */
238 if (server_mode(get_options())) {
239 routerinfo_t
*me
= router_get_my_routerinfo();
242 prev_digest
= me
->cache_info
.identity_digest
;
245 router
= router_get_by_digest(hop
->extend_info
->identity_digest
);
248 if (hop
->state
== CPATH_STATE_OPEN
)
249 rep_hist_note_extend_succeeded(prev_digest
,
250 router
->cache_info
.identity_digest
);
252 rep_hist_note_extend_failed(prev_digest
,
253 router
->cache_info
.identity_digest
);
257 prev_digest
= router
->cache_info
.identity_digest
;
262 } while (hop
!=circ
->cpath
);
265 /** Pick all the entries in our cpath. Stop and return 0 when we're
266 * happy, or return -1 if an error occurs. */
268 onion_populate_cpath(origin_circuit_t
*circ
)
272 r
= onion_extend_cpath(circ
);
274 log_info(LD_CIRC
,"Generating cpath hop failed.");
279 return 0; /* if r == 1 */
282 /** Create and return a new origin circuit. Initialize its purpose and
283 * build-state based on our arguments. The <b>flags</b> argument is a
284 * bitfield of CIRCLAUNCH_* flags. */
286 origin_circuit_init(uint8_t purpose
, int flags
)
288 /* sets circ->p_circ_id and circ->p_conn */
289 origin_circuit_t
*circ
= origin_circuit_new();
290 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OR_WAIT
);
291 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
292 circ
->build_state
->onehop_tunnel
=
293 ((flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) ? 1 : 0);
294 circ
->build_state
->need_uptime
=
295 ((flags
& CIRCLAUNCH_NEED_UPTIME
) ? 1 : 0);
296 circ
->build_state
->need_capacity
=
297 ((flags
& CIRCLAUNCH_NEED_CAPACITY
) ? 1 : 0);
298 circ
->build_state
->is_internal
=
299 ((flags
& CIRCLAUNCH_IS_INTERNAL
) ? 1 : 0);
300 circ
->_base
.purpose
= purpose
;
304 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
305 * is defined, then use that as your exit router, else choose a suitable
308 * Also launch a connection to the first OR in the chosen path, if
309 * it's not open already.
312 circuit_establish_circuit(uint8_t purpose
, extend_info_t
*exit
, int flags
)
314 origin_circuit_t
*circ
;
317 circ
= origin_circuit_init(purpose
, flags
);
319 if (onion_pick_cpath_exit(circ
, exit
) < 0 ||
320 onion_populate_cpath(circ
) < 0) {
321 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
325 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
327 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
328 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
334 /** Start establishing the first hop of our circuit. Figure out what
335 * OR we should connect to, and if necessary start the connection to
336 * it. If we're already connected, then send the 'create' cell.
337 * Return 0 for ok, -reason if circ should be marked-for-close. */
339 circuit_handle_first_hop(origin_circuit_t
*circ
)
341 crypt_path_t
*firsthop
;
342 or_connection_t
*n_conn
;
344 const char *msg
= NULL
;
345 int should_launch
= 0;
347 firsthop
= onion_next_hop_in_cpath(circ
->cpath
);
348 tor_assert(firsthop
);
349 tor_assert(firsthop
->extend_info
);
351 /* now see if we're already connected to the first OR in 'route' */
352 log_debug(LD_CIRC
,"Looking for firsthop '%s:%u'",
353 fmt_addr(&firsthop
->extend_info
->addr
),
354 firsthop
->extend_info
->port
);
356 n_conn
= connection_or_get_for_extend(firsthop
->extend_info
->identity_digest
,
357 &firsthop
->extend_info
->addr
,
362 /* not currently connected in a useful way. */
363 const char *name
= firsthop
->extend_info
->nickname
?
364 firsthop
->extend_info
->nickname
: fmt_addr(&firsthop
->extend_info
->addr
);
365 log_info(LD_CIRC
, "Next router is %s: %s ", safe_str(name
), msg
?msg
:"???");
366 circ
->_base
.n_hop
= extend_info_dup(firsthop
->extend_info
);
369 if (circ
->build_state
->onehop_tunnel
)
370 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR
, 0);
371 n_conn
= connection_or_connect(&firsthop
->extend_info
->addr
,
372 firsthop
->extend_info
->port
,
373 firsthop
->extend_info
->identity_digest
);
374 if (!n_conn
) { /* connect failed, forget the whole thing */
375 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
376 return -END_CIRC_REASON_CONNECTFAILED
;
380 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
381 /* return success. The onion/circuit/etc will be taken care of
382 * automatically (may already have been) whenever n_conn reaches
383 * OR_CONN_STATE_OPEN.
386 } else { /* it's already open. use it. */
387 tor_assert(!circ
->_base
.n_hop
);
388 circ
->_base
.n_conn
= n_conn
;
389 log_debug(LD_CIRC
,"Conn open. Delivering first onion skin.");
390 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
391 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
398 /** Find any circuits that are waiting on <b>or_conn</b> to become
399 * open and get them to send their create cells forward.
401 * Status is 1 if connect succeeded, or 0 if connect failed.
404 circuit_n_conn_done(or_connection_t
*or_conn
, int status
)
406 smartlist_t
*pending_circs
;
409 log_debug(LD_CIRC
,"or_conn to %s/%s, status=%d",
410 or_conn
->nickname
? or_conn
->nickname
: "NULL",
411 or_conn
->_base
.address
, status
);
413 pending_circs
= smartlist_create();
414 circuit_get_all_pending_on_or_conn(pending_circs
, or_conn
);
416 SMARTLIST_FOREACH_BEGIN(pending_circs
, circuit_t
*, circ
)
418 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
419 * leaving them in in case it's possible for the status of a circuit to
420 * change as we're going down the list. */
421 if (circ
->marked_for_close
|| circ
->n_conn
|| !circ
->n_hop
||
422 circ
->state
!= CIRCUIT_STATE_OR_WAIT
)
425 if (tor_digest_is_zero(circ
->n_hop
->identity_digest
)) {
426 /* Look at addr/port. This is an unkeyed connection. */
427 if (!tor_addr_eq(&circ
->n_hop
->addr
, &or_conn
->_base
.addr
) ||
428 circ
->n_hop
->port
!= or_conn
->_base
.port
)
431 /* We expected a key. See if it's the right one. */
432 if (memcmp(or_conn
->identity_digest
,
433 circ
->n_hop
->identity_digest
, DIGEST_LEN
))
436 if (!status
) { /* or_conn failed; close circ */
437 log_info(LD_CIRC
,"or_conn failed. Closing circ.");
438 circuit_mark_for_close(circ
, END_CIRC_REASON_OR_CONN_CLOSED
);
441 log_debug(LD_CIRC
, "Found circ, sending create cell.");
442 /* circuit_deliver_create_cell will set n_circ_id and add us to
443 * orconn_circuid_circuit_map, so we don't need to call
444 * set_circid_orconn here. */
445 circ
->n_conn
= or_conn
;
446 extend_info_free(circ
->n_hop
);
449 if (CIRCUIT_IS_ORIGIN(circ
)) {
451 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
453 "send_next_onion_skin failed; circuit marked for closing.");
454 circuit_mark_for_close(circ
, -err_reason
);
456 /* XXX could this be bad, eg if next_onion_skin failed because conn
460 /* pull the create cell out of circ->onionskin, and send it */
461 tor_assert(circ
->n_conn_onionskin
);
462 if (circuit_deliver_create_cell(circ
,CELL_CREATE
,
463 circ
->n_conn_onionskin
)<0) {
464 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
467 tor_free(circ
->n_conn_onionskin
);
468 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
471 SMARTLIST_FOREACH_END(circ
);
473 smartlist_free(pending_circs
);
476 /** Find a new circid that isn't currently in use on the circ->n_conn
478 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
479 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
481 * Return -1 if we failed to find a suitable circid, else return 0.
484 circuit_deliver_create_cell(circuit_t
*circ
, uint8_t cell_type
,
491 tor_assert(circ
->n_conn
);
493 tor_assert(cell_type
== CELL_CREATE
|| cell_type
== CELL_CREATE_FAST
);
495 id
= get_unique_circ_id_by_conn(circ
->n_conn
);
497 log_warn(LD_CIRC
,"failed to get unique circID.");
500 log_debug(LD_CIRC
,"Chosen circID %u.", id
);
501 circuit_set_n_circid_orconn(circ
, id
, circ
->n_conn
);
503 memset(&cell
, 0, sizeof(cell_t
));
504 cell
.command
= cell_type
;
505 cell
.circ_id
= circ
->n_circ_id
;
507 memcpy(cell
.payload
, payload
, ONIONSKIN_CHALLENGE_LEN
);
508 append_cell_to_circuit_queue(circ
, circ
->n_conn
, &cell
, CELL_DIRECTION_OUT
);
510 if (CIRCUIT_IS_ORIGIN(circ
)) {
511 /* mark it so it gets better rate limiting treatment. */
512 circ
->n_conn
->client_used
= time(NULL
);
518 /** We've decided to start our reachability testing. If all
519 * is set, log this to the user. Return 1 if we did, or 0 if
520 * we chose not to log anything. */
522 inform_testing_reachability(void)
525 routerinfo_t
*me
= router_get_my_routerinfo();
529 tor_snprintf(dirbuf
, sizeof(dirbuf
), " and DirPort %s:%d",
530 me
->address
, me
->dir_port
);
531 log(LOG_NOTICE
, LD_OR
, "Now checking whether ORPort %s:%d%s %s reachable... "
532 "(this may take up to %d minutes -- look for log "
533 "messages indicating success)",
534 me
->address
, me
->or_port
,
535 me
->dir_port
? dirbuf
: "",
536 me
->dir_port
? "are" : "is",
537 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
/60);
541 /** Return true iff we should send a create_fast cell to start building a given
544 should_use_create_fast_for_circuit(origin_circuit_t
*circ
)
546 or_options_t
*options
= get_options();
547 tor_assert(circ
->cpath
);
548 tor_assert(circ
->cpath
->extend_info
);
550 if (!circ
->cpath
->extend_info
->onion_key
)
551 return 1; /* our hand is forced: only a create_fast will work. */
552 if (!options
->FastFirstHopPK
)
553 return 0; /* we prefer to avoid create_fast */
554 if (server_mode(options
)) {
555 /* We're a server, and we know an onion key. We can choose.
556 * Prefer to blend in. */
563 /** This is the backbone function for building circuits.
565 * If circ's first hop is closed, then we need to build a create
566 * cell and send it forward.
568 * Otherwise, we need to build a relay extend cell and send it
571 * Return -reason if we want to tear down circ, else return 0.
574 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
577 routerinfo_t
*router
;
578 char payload
[2+4+DIGEST_LEN
+ONIONSKIN_CHALLENGE_LEN
];
584 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
587 log_debug(LD_CIRC
,"First skin; sending create cell.");
588 if (circ
->build_state
->onehop_tunnel
)
589 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE
, 0);
591 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE
, 0);
593 router
= router_get_by_digest(circ
->_base
.n_conn
->identity_digest
);
594 fast
= should_use_create_fast_for_circuit(circ
);
596 /* We are an OR and we know the right onion key: we should
597 * send an old slow create cell.
599 cell_type
= CELL_CREATE
;
600 if (onion_skin_create(circ
->cpath
->extend_info
->onion_key
,
601 &(circ
->cpath
->dh_handshake_state
),
603 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
604 return - END_CIRC_REASON_INTERNAL
;
606 note_request("cell: create", 1);
608 /* We are not an OR, and we're building the first hop of a circuit to a
609 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
610 * and a DH operation. */
611 cell_type
= CELL_CREATE_FAST
;
612 memset(payload
, 0, sizeof(payload
));
613 crypto_rand(circ
->cpath
->fast_handshake_state
,
614 sizeof(circ
->cpath
->fast_handshake_state
));
615 memcpy(payload
, circ
->cpath
->fast_handshake_state
,
616 sizeof(circ
->cpath
->fast_handshake_state
));
617 note_request("cell: create fast", 1);
620 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), cell_type
, payload
) < 0)
621 return - END_CIRC_REASON_RESOURCELIMIT
;
623 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
624 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
625 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
626 fast
? "CREATE_FAST" : "CREATE",
627 router
? router
->nickname
: "<unnamed>");
629 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
630 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_BUILDING
);
631 log_debug(LD_CIRC
,"starting to send subsequent skin.");
632 hop
= onion_next_hop_in_cpath(circ
->cpath
);
634 /* done building the circuit. whew. */
635 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
636 log_info(LD_CIRC
,"circuit built!");
637 circuit_reset_failure_count(0);
638 if (circ
->build_state
->onehop_tunnel
)
639 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS
, 0);
640 if (!has_completed_circuit
&& !circ
->build_state
->onehop_tunnel
) {
641 or_options_t
*options
= get_options();
642 has_completed_circuit
=1;
643 /* FFFF Log a count of known routers here */
644 log(LOG_NOTICE
, LD_GENERAL
,
645 "Tor has successfully opened a circuit. "
646 "Looks like client functionality is working.");
647 control_event_bootstrap(BOOTSTRAP_STATUS_DONE
, 0);
648 control_event_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
649 if (server_mode(options
) && !check_whether_orport_reachable()) {
650 inform_testing_reachability();
651 consider_testing_reachability(1, 1);
654 circuit_rep_hist_note_result(circ
);
655 circuit_has_opened(circ
); /* do other actions as necessary */
659 if (tor_addr_family(&hop
->extend_info
->addr
) != AF_INET
) {
660 log_warn(LD_BUG
, "Trying to extend to a non-IPv4 address.");
661 return - END_CIRC_REASON_INTERNAL
;
664 set_uint32(payload
, tor_addr_to_ipv4n(&hop
->extend_info
->addr
));
665 set_uint16(payload
+4, htons(hop
->extend_info
->port
));
667 onionskin
= payload
+2+4;
668 memcpy(payload
+2+4+ONIONSKIN_CHALLENGE_LEN
,
669 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
670 payload_len
= 2+4+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
;
672 if (onion_skin_create(hop
->extend_info
->onion_key
,
673 &(hop
->dh_handshake_state
), onionskin
) < 0) {
674 log_warn(LD_CIRC
,"onion_skin_create failed.");
675 return - END_CIRC_REASON_INTERNAL
;
678 log_info(LD_CIRC
,"Sending extend relay cell.");
679 note_request("cell: extend", 1);
680 /* send it to hop->prev, because it will transfer
681 * it to a create cell and then send to hop */
682 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
683 RELAY_COMMAND_EXTEND
,
684 payload
, payload_len
, hop
->prev
) < 0)
685 return 0; /* circuit is closed */
687 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
692 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
693 * something has also gone wrong with our network: notify the user,
694 * and abandon all not-yet-used circuits. */
696 circuit_note_clock_jumped(int seconds_elapsed
)
698 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
699 log(severity
, LD_GENERAL
, "Your system clock just jumped %d seconds %s; "
700 "assuming established circuits no longer work.",
701 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
,
702 seconds_elapsed
>=0 ? "forward" : "backward");
703 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%d",
705 has_completed_circuit
=0; /* so it'll log when it works again */
706 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
708 circuit_mark_all_unused_circs();
709 circuit_expire_all_dirty_circs();
712 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
713 * skin and identity digest for the next hop. If we're already connected,
714 * pass the onion skin to the next hop using a create cell; otherwise
715 * launch a new OR connection, and <b>circ</b> will notice when the
716 * connection succeeds or fails.
718 * Return -1 if we want to warn and tear down the circuit, else return 0.
721 circuit_extend(cell_t
*cell
, circuit_t
*circ
)
723 or_connection_t
*n_conn
;
726 char *id_digest
=NULL
;
730 const char *msg
= NULL
;
731 int should_launch
= 0;
734 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
735 "n_conn already set. Bug/attack. Closing.");
739 if (!server_mode(get_options())) {
740 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
741 "Got an extend cell, but running as a client. Closing.");
745 relay_header_unpack(&rh
, cell
->payload
);
747 if (rh
.length
< 4+2+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
) {
748 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
749 "Wrong length %d on extend cell. Closing circuit.",
754 n_addr32
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
755 n_port
= ntohs(get_uint16(cell
->payload
+RELAY_HEADER_SIZE
+4));
756 onionskin
= cell
->payload
+RELAY_HEADER_SIZE
+4+2;
757 id_digest
= cell
->payload
+RELAY_HEADER_SIZE
+4+2+ONIONSKIN_CHALLENGE_LEN
;
758 tor_addr_from_ipv4h(&n_addr
, n_addr32
);
760 /* First, check if they asked us for 0000..0000. We support using
761 * an empty fingerprint for the first hop (e.g. for a bridge relay),
762 * but we don't want to let people send us extend cells for empty
763 * fingerprints -- a) because it opens the user up to a mitm attack,
764 * and b) because it lets an attacker force the relay to hold open a
765 * new TLS connection for each extend request. */
766 if (tor_digest_is_zero(id_digest
)) {
767 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
768 "Client asked me to extend without specifying an id_digest.");
772 /* Next, check if we're being asked to connect to the hop that the
773 * extend cell came from. There isn't any reason for that, and it can
774 * assist circular-path attacks. */
775 if (!memcmp(id_digest
, TO_OR_CIRCUIT(circ
)->p_conn
->identity_digest
,
777 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
778 "Client asked me to extend back to the previous hop.");
782 n_conn
= connection_or_get_for_extend(id_digest
,
788 log_debug(LD_CIRC
|LD_OR
,"Next router (%s:%d): %s",
789 fmt_addr(&n_addr
), (int)n_port
, msg
?msg
:"????");
791 circ
->n_hop
= extend_info_alloc(NULL
/*nickname*/,
796 circ
->n_conn_onionskin
= tor_malloc(ONIONSKIN_CHALLENGE_LEN
);
797 memcpy(circ
->n_conn_onionskin
, onionskin
, ONIONSKIN_CHALLENGE_LEN
);
798 circuit_set_state(circ
, CIRCUIT_STATE_OR_WAIT
);
801 /* we should try to open a connection */
802 n_conn
= connection_or_connect(&n_addr
, n_port
, id_digest
);
804 log_info(LD_CIRC
,"Launching n_conn failed. Closing circuit.");
805 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
808 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
810 /* return success. The onion/circuit/etc will be taken care of
811 * automatically (may already have been) whenever n_conn reaches
812 * OR_CONN_STATE_OPEN.
817 tor_assert(!circ
->n_hop
); /* Connection is already established. */
818 circ
->n_conn
= n_conn
;
819 log_debug(LD_CIRC
,"n_conn is %s:%u",
820 n_conn
->_base
.address
,n_conn
->_base
.port
);
822 if (circuit_deliver_create_cell(circ
, CELL_CREATE
, onionskin
) < 0)
827 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
828 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
830 * - 20 to initialize f_digest
831 * - 20 to initialize b_digest
832 * - 16 to key f_crypto
833 * - 16 to key b_crypto
835 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
838 circuit_init_cpath_crypto(crypt_path_t
*cpath
, const char *key_data
,
841 crypto_digest_env_t
*tmp_digest
;
842 crypto_cipher_env_t
*tmp_crypto
;
845 tor_assert(key_data
);
846 tor_assert(!(cpath
->f_crypto
|| cpath
->b_crypto
||
847 cpath
->f_digest
|| cpath
->b_digest
));
849 cpath
->f_digest
= crypto_new_digest_env();
850 crypto_digest_add_bytes(cpath
->f_digest
, key_data
, DIGEST_LEN
);
851 cpath
->b_digest
= crypto_new_digest_env();
852 crypto_digest_add_bytes(cpath
->b_digest
, key_data
+DIGEST_LEN
, DIGEST_LEN
);
854 if (!(cpath
->f_crypto
=
855 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
),1))) {
856 log_warn(LD_BUG
,"Forward cipher initialization failed.");
859 if (!(cpath
->b_crypto
=
860 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
)+CIPHER_KEY_LEN
,0))) {
861 log_warn(LD_BUG
,"Backward cipher initialization failed.");
866 tmp_digest
= cpath
->f_digest
;
867 cpath
->f_digest
= cpath
->b_digest
;
868 cpath
->b_digest
= tmp_digest
;
869 tmp_crypto
= cpath
->f_crypto
;
870 cpath
->f_crypto
= cpath
->b_crypto
;
871 cpath
->b_crypto
= tmp_crypto
;
877 /** A created or extended cell came back to us on the circuit, and it included
878 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
879 * contains (the second DH key, plus KH). If <b>reply_type</b> is
880 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
882 * Calculate the appropriate keys and digests, make sure KH is
883 * correct, and initialize this hop of the cpath.
885 * Return - reason if we want to mark circ for close, else return 0.
888 circuit_finish_handshake(origin_circuit_t
*circ
, uint8_t reply_type
,
891 char keys
[CPATH_KEY_MATERIAL_LEN
];
894 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
)
897 hop
= onion_next_hop_in_cpath(circ
->cpath
);
898 if (!hop
) { /* got an extended when we're all done? */
899 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
900 return - END_CIRC_REASON_TORPROTOCOL
;
903 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
905 if (reply_type
== CELL_CREATED
&& hop
->dh_handshake_state
) {
906 if (onion_skin_client_handshake(hop
->dh_handshake_state
, reply
, keys
,
907 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
908 log_warn(LD_CIRC
,"onion_skin_client_handshake failed.");
909 return -END_CIRC_REASON_TORPROTOCOL
;
911 /* Remember hash of g^xy */
912 memcpy(hop
->handshake_digest
, reply
+DH_KEY_LEN
, DIGEST_LEN
);
913 } else if (reply_type
== CELL_CREATED_FAST
&& !hop
->dh_handshake_state
) {
914 if (fast_client_handshake(hop
->fast_handshake_state
, reply
, keys
,
915 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
916 log_warn(LD_CIRC
,"fast_client_handshake failed.");
917 return -END_CIRC_REASON_TORPROTOCOL
;
919 memcpy(hop
->handshake_digest
, reply
+DIGEST_LEN
, DIGEST_LEN
);
921 log_warn(LD_PROTOCOL
,"CREATED cell type did not match CREATE cell type.");
922 return -END_CIRC_REASON_TORPROTOCOL
;
925 if (hop
->dh_handshake_state
) {
926 crypto_dh_free(hop
->dh_handshake_state
); /* don't need it anymore */
927 hop
->dh_handshake_state
= NULL
;
929 memset(hop
->fast_handshake_state
, 0, sizeof(hop
->fast_handshake_state
));
931 if (circuit_init_cpath_crypto(hop
, keys
, 0)<0) {
932 return -END_CIRC_REASON_TORPROTOCOL
;
935 hop
->state
= CPATH_STATE_OPEN
;
936 log_info(LD_CIRC
,"Finished building %scircuit hop:",
937 (reply_type
== CELL_CREATED_FAST
) ? "fast " : "");
938 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
939 control_event_circuit_status(circ
, CIRC_EVENT_EXTENDED
, 0);
944 /** We received a relay truncated cell on circ.
946 * Since we don't ask for truncates currently, getting a truncated
947 * means that a connection broke or an extend failed. For now,
948 * just give up: for circ to close, and return 0.
951 circuit_truncated(origin_circuit_t
*circ
, crypt_path_t
*layer
)
953 // crypt_path_t *victim;
954 // connection_t *stream;
959 /* XXX Since we don't ask for truncates currently, getting a truncated
960 * means that a connection broke or an extend failed. For now,
963 circuit_mark_for_close(TO_CIRCUIT(circ
),
964 END_CIRC_REASON_FLAG_REMOTE
|END_CIRC_REASON_OR_CONN_CLOSED
);
968 while (layer
->next
!= circ
->cpath
) {
969 /* we need to clear out layer->next */
970 victim
= layer
->next
;
971 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
973 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
974 if (stream
->cpath_layer
== victim
) {
975 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
977 /* no need to send 'end' relay cells,
978 * because the other side's already dead
980 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
984 layer
->next
= victim
->next
;
985 circuit_free_cpath_node(victim
);
988 log_info(LD_CIRC
, "finished");
993 /** Given a response payload and keys, initialize, then send a created
997 onionskin_answer(or_circuit_t
*circ
, uint8_t cell_type
, const char *payload
,
1001 crypt_path_t
*tmp_cpath
;
1003 tmp_cpath
= tor_malloc_zero(sizeof(crypt_path_t
));
1004 tmp_cpath
->magic
= CRYPT_PATH_MAGIC
;
1006 memset(&cell
, 0, sizeof(cell_t
));
1007 cell
.command
= cell_type
;
1008 cell
.circ_id
= circ
->p_circ_id
;
1010 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
1012 memcpy(cell
.payload
, payload
,
1013 cell_type
== CELL_CREATED
? ONIONSKIN_REPLY_LEN
: DIGEST_LEN
*2);
1015 log_debug(LD_CIRC
,"init digest forward 0x%.8x, backward 0x%.8x.",
1016 (unsigned int)*(uint32_t*)(keys
),
1017 (unsigned int)*(uint32_t*)(keys
+20));
1018 if (circuit_init_cpath_crypto(tmp_cpath
, keys
, 0)<0) {
1019 log_warn(LD_BUG
,"Circuit initialization failed");
1020 tor_free(tmp_cpath
);
1023 circ
->n_digest
= tmp_cpath
->f_digest
;
1024 circ
->n_crypto
= tmp_cpath
->f_crypto
;
1025 circ
->p_digest
= tmp_cpath
->b_digest
;
1026 circ
->p_crypto
= tmp_cpath
->b_crypto
;
1027 tmp_cpath
->magic
= 0;
1028 tor_free(tmp_cpath
);
1030 if (cell_type
== CELL_CREATED
)
1031 memcpy(circ
->handshake_digest
, cell
.payload
+DH_KEY_LEN
, DIGEST_LEN
);
1033 memcpy(circ
->handshake_digest
, cell
.payload
+DIGEST_LEN
, DIGEST_LEN
);
1035 circ
->is_first_hop
= (cell_type
== CELL_CREATED_FAST
);
1037 append_cell_to_circuit_queue(TO_CIRCUIT(circ
),
1038 circ
->p_conn
, &cell
, CELL_DIRECTION_IN
);
1039 log_debug(LD_CIRC
,"Finished sending 'created' cell.");
1041 if (!is_local_addr(&circ
->p_conn
->_base
.addr
) &&
1042 !connection_or_nonopen_was_started_here(circ
->p_conn
)) {
1043 /* record that we could process create cells from a non-local conn
1044 * that we didn't initiate; presumably this means that create cells
1045 * can reach us too. */
1046 router_orport_found_reachable();
1052 /** Choose a length for a circuit of purpose <b>purpose</b>.
1053 * Default length is 3 + the number of endpoints that would give something
1054 * away. If the routerlist <b>routers</b> doesn't have enough routers
1055 * to handle the desired path length, return as large a path length as
1056 * is feasible, except if it's less than 2, in which case return -1.
1059 new_route_len(uint8_t purpose
, extend_info_t
*exit
,
1060 smartlist_t
*routers
)
1062 int num_acceptable_routers
;
1065 tor_assert(routers
);
1069 purpose
!= CIRCUIT_PURPOSE_TESTING
&&
1070 purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
1073 num_acceptable_routers
= count_acceptable_routers(routers
);
1075 log_debug(LD_CIRC
,"Chosen route length %d (%d/%d routers suitable).",
1076 routelen
, num_acceptable_routers
, smartlist_len(routers
));
1078 if (num_acceptable_routers
< 2) {
1080 "Not enough acceptable routers (%d). Discarding this circuit.",
1081 num_acceptable_routers
);
1085 if (num_acceptable_routers
< routelen
) {
1086 log_info(LD_CIRC
,"Not enough routers: cutting routelen from %d to %d.",
1087 routelen
, num_acceptable_routers
);
1088 routelen
= num_acceptable_routers
;
1094 /** Fetch the list of predicted ports, dup it into a smartlist of
1095 * uint16_t's, remove the ones that are already handled by an
1096 * existing circuit, and return it.
1098 static smartlist_t
*
1099 circuit_get_unhandled_ports(time_t now
)
1101 smartlist_t
*source
= rep_hist_get_predicted_ports(now
);
1102 smartlist_t
*dest
= smartlist_create();
1106 for (i
= 0; i
< smartlist_len(source
); ++i
) {
1107 tmp
= tor_malloc(sizeof(uint16_t));
1108 memcpy(tmp
, smartlist_get(source
, i
), sizeof(uint16_t));
1109 smartlist_add(dest
, tmp
);
1112 circuit_remove_handled_ports(dest
);
1116 /** Return 1 if we already have circuits present or on the way for
1117 * all anticipated ports. Return 0 if we should make more.
1119 * If we're returning 0, set need_uptime and need_capacity to
1120 * indicate any requirements that the unhandled ports have.
1123 circuit_all_predicted_ports_handled(time_t now
, int *need_uptime
,
1128 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
1129 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
1130 tor_assert(need_uptime
);
1131 tor_assert(need_capacity
);
1132 enough
= (smartlist_len(sl
) == 0);
1133 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
1134 port
= smartlist_get(sl
, i
);
1135 if (smartlist_string_num_isin(LongLivedServices
, *port
))
1143 /** Return 1 if <b>router</b> can handle one or more of the ports in
1144 * <b>needed_ports</b>, else return 0.
1147 router_handles_some_port(routerinfo_t
*router
, smartlist_t
*needed_ports
)
1152 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
1153 addr_policy_result_t r
;
1154 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
1156 r
= compare_addr_to_addr_policy(0, port
, router
->exit_policy
);
1157 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
1163 /** Return true iff <b>conn</b> needs another general circuit to be
1166 ap_stream_wants_exit_attention(connection_t
*conn
)
1168 if (conn
->type
== CONN_TYPE_AP
&&
1169 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
1170 !conn
->marked_for_close
&&
1171 !(TO_EDGE_CONN(conn
)->want_onehop
) && /* ignore one-hop streams */
1172 !(TO_EDGE_CONN(conn
)->use_begindir
) && /* ignore targeted dir fetches */
1173 !(TO_EDGE_CONN(conn
)->chosen_exit_name
) && /* ignore defined streams */
1174 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
1175 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn
), 0,
1176 MIN_CIRCUITS_HANDLING_STREAM
))
1181 /** Return a pointer to a suitable router to be the exit node for the
1182 * general-purpose circuit we're about to build.
1184 * Look through the connection array, and choose a router that maximizes
1185 * the number of pending streams that can exit from this router.
1187 * Return NULL if we can't find any suitable routers.
1189 static routerinfo_t
*
1190 choose_good_exit_server_general(routerlist_t
*dir
, int need_uptime
,
1195 int n_pending_connections
= 0;
1196 smartlist_t
*connections
;
1197 int best_support
= -1;
1198 int n_best_support
=0;
1199 routerinfo_t
*router
;
1200 or_options_t
*options
= get_options();
1202 connections
= get_connection_array();
1204 /* Count how many connections are waiting for a circuit to be built.
1205 * We use this for log messages now, but in the future we may depend on it.
1207 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1209 if (ap_stream_wants_exit_attention(conn
))
1210 ++n_pending_connections
;
1212 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1213 // n_pending_connections);
1214 /* Now we count, for each of the routers in the directory, how many
1215 * of the pending connections could possibly exit from that
1216 * router (n_supported[i]). (We can't be sure about cases where we
1217 * don't know the IP address of the pending connection.)
1219 * -1 means "Don't use this router at all."
1221 n_supported
= tor_malloc(sizeof(int)*smartlist_len(dir
->routers
));
1222 for (i
= 0; i
< smartlist_len(dir
->routers
); ++i
) {/* iterate over routers */
1223 router
= smartlist_get(dir
->routers
, i
);
1224 if (router_is_me(router
)) {
1225 n_supported
[i
] = -1;
1226 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1227 /* XXX there's probably a reverse predecessor attack here, but
1228 * it's slow. should we take this out? -RD
1232 if (!router
->is_running
|| router
->is_bad_exit
) {
1233 n_supported
[i
] = -1;
1234 continue; /* skip routers that are known to be down or bad exits */
1236 if (router_is_unreliable(router
, need_uptime
, need_capacity
, 0)) {
1237 n_supported
[i
] = -1;
1238 continue; /* skip routers that are not suitable */
1240 if (!(router
->is_valid
|| options
->_AllowInvalid
& ALLOW_INVALID_EXIT
)) {
1241 /* if it's invalid and we don't want it */
1242 n_supported
[i
] = -1;
1243 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1244 // router->nickname, i);
1245 continue; /* skip invalid routers */
1247 if (options
->ExcludeSingleHopRelays
&& router
->allow_single_hop_exits
) {
1248 n_supported
[i
] = -1;
1251 if (router_exit_policy_rejects_all(router
)) {
1252 n_supported
[i
] = -1;
1253 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1254 // router->nickname, i);
1255 continue; /* skip routers that reject all */
1258 /* iterate over connections */
1259 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1261 if (!ap_stream_wants_exit_attention(conn
))
1262 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1263 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn
), router
)) {
1265 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1266 // router->nickname, i, n_supported[i]);
1268 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1269 // router->nickname, i);
1271 }); /* End looping over connections. */
1272 if (n_pending_connections
> 0 && n_supported
[i
] == 0) {
1273 /* Leave best_support at -1 if that's where it is, so we can
1274 * distinguish it later. */
1277 if (n_supported
[i
] > best_support
) {
1278 /* If this router is better than previous ones, remember its index
1279 * and goodness, and start counting how many routers are this good. */
1280 best_support
= n_supported
[i
]; n_best_support
=1;
1281 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1282 // router->nickname);
1283 } else if (n_supported
[i
] == best_support
) {
1284 /* If this router is _as good_ as the best one, just increment the
1285 * count of equally good routers.*/
1290 "Found %d servers that might support %d/%d pending connections.",
1291 n_best_support
, best_support
>= 0 ? best_support
: 0,
1292 n_pending_connections
);
1294 /* If any routers definitely support any pending connections, choose one
1296 if (best_support
> 0) {
1297 smartlist_t
*supporting
= smartlist_create(), *use
= smartlist_create();
1299 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++)
1300 if (n_supported
[i
] == best_support
)
1301 smartlist_add(supporting
, smartlist_get(dir
->routers
, i
));
1303 routersets_get_disjunction(use
, supporting
, options
->ExitNodes
,
1304 options
->_ExcludeExitNodesUnion
, 1);
1305 if (smartlist_len(use
) == 0 && !options
->StrictExitNodes
) {
1306 routersets_get_disjunction(use
, supporting
, NULL
,
1307 options
->_ExcludeExitNodesUnion
, 1);
1309 router
= routerlist_sl_choose_by_bandwidth(use
, WEIGHT_FOR_EXIT
);
1310 smartlist_free(use
);
1311 smartlist_free(supporting
);
1313 /* Either there are no pending connections, or no routers even seem to
1314 * possibly support any of them. Choose a router at random that satisfies
1315 * at least one predicted exit port. */
1318 smartlist_t
*needed_ports
, *supporting
, *use
;
1320 if (best_support
== -1) {
1321 if (need_uptime
|| need_capacity
) {
1323 "We couldn't find any live%s%s routers; falling back "
1324 "to list of all routers.",
1325 need_capacity
?", fast":"",
1326 need_uptime
?", stable":"");
1327 tor_free(n_supported
);
1328 return choose_good_exit_server_general(dir
, 0, 0);
1330 log_notice(LD_CIRC
, "All routers are down or won't exit -- choosing a "
1331 "doomed exit at random.");
1333 supporting
= smartlist_create();
1334 use
= smartlist_create();
1335 needed_ports
= circuit_get_unhandled_ports(time(NULL
));
1336 for (try = 0; try < 2; try++) {
1337 /* try once to pick only from routers that satisfy a needed port,
1338 * then if there are none, pick from any that support exiting. */
1339 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++) {
1340 router
= smartlist_get(dir
->routers
, i
);
1341 if (n_supported
[i
] != -1 &&
1342 (try || router_handles_some_port(router
, needed_ports
))) {
1343 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1344 // try, router->nickname);
1345 smartlist_add(supporting
, router
);
1349 routersets_get_disjunction(use
, supporting
, options
->ExitNodes
,
1350 options
->_ExcludeExitNodesUnion
, 1);
1351 if (smartlist_len(use
) == 0 && !options
->StrictExitNodes
) {
1352 routersets_get_disjunction(use
, supporting
, NULL
,
1353 options
->_ExcludeExitNodesUnion
, 1);
1355 /* XXX sometimes the above results in null, when the requested
1356 * exit node is down. we should pick it anyway. */
1357 router
= routerlist_sl_choose_by_bandwidth(use
, WEIGHT_FOR_EXIT
);
1360 smartlist_clear(supporting
);
1361 smartlist_clear(use
);
1363 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
1364 smartlist_free(needed_ports
);
1365 smartlist_free(use
);
1366 smartlist_free(supporting
);
1369 tor_free(n_supported
);
1371 log_info(LD_CIRC
, "Chose exit server '%s'", router
->nickname
);
1374 if (options
->StrictExitNodes
) {
1376 "No specified exit routers seem to be running, and "
1377 "StrictExitNodes is set: can't choose an exit.");
1382 /** Return a pointer to a suitable router to be the exit node for the
1383 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1384 * if no router is suitable).
1386 * For general-purpose circuits, pass it off to
1387 * choose_good_exit_server_general()
1389 * For client-side rendezvous circuits, choose a random node, weighted
1390 * toward the preferences in 'options'.
1392 static routerinfo_t
*
1393 choose_good_exit_server(uint8_t purpose
, routerlist_t
*dir
,
1394 int need_uptime
, int need_capacity
, int is_internal
)
1396 or_options_t
*options
= get_options();
1397 router_crn_flags_t flags
= 0;
1399 flags
|= CRN_NEED_UPTIME
;
1401 flags
|= CRN_NEED_CAPACITY
;
1404 case CIRCUIT_PURPOSE_C_GENERAL
:
1405 if (options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
)
1406 flags
|= CRN_ALLOW_INVALID
;
1407 if (is_internal
) /* pick it like a middle hop */
1408 return router_choose_random_node(NULL
, NULL
,
1409 options
->ExcludeNodes
, flags
);
1411 return choose_good_exit_server_general(dir
,need_uptime
,need_capacity
);
1412 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1413 if (options
->_AllowInvalid
& ALLOW_INVALID_RENDEZVOUS
)
1414 flags
|= CRN_ALLOW_INVALID
;
1415 return router_choose_random_node(NULL
, NULL
,
1416 options
->ExcludeNodes
, flags
);
1418 log_warn(LD_BUG
,"Unhandled purpose %d", purpose
);
1419 tor_fragile_assert();
1423 /** Log a warning if the user specified an exit for the circuit that
1424 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1426 warn_if_router_excluded(const extend_info_t
*exit
)
1428 or_options_t
*options
= get_options();
1429 routerinfo_t
*ri
= router_get_by_digest(exit
->identity_digest
);
1431 if (!ri
|| !options
->_ExcludeExitNodesUnion
)
1434 if (routerset_contains_router(options
->_ExcludeExitNodesUnion
, ri
))
1435 log_warn(LD_CIRC
,"Requested exit node '%s' is in ExcludeNodes, "
1436 "or ExcludeExitNodes, using anyway.",exit
->nickname
);
1441 /** Decide a suitable length for circ's cpath, and pick an exit
1442 * router (or use <b>exit</b> if provided). Store these in the
1443 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1445 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1447 cpath_build_state_t
*state
= circ
->build_state
;
1448 routerlist_t
*rl
= router_get_routerlist();
1450 if (state
->onehop_tunnel
) {
1451 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel.");
1452 state
->desired_path_len
= 1;
1454 int r
= new_route_len(circ
->_base
.purpose
, exit
, rl
->routers
);
1455 if (r
< 1) /* must be at least 1 */
1457 state
->desired_path_len
= r
;
1460 if (exit
) { /* the circuit-builder pre-requested one */
1461 warn_if_router_excluded(exit
);
1462 log_info(LD_CIRC
,"Using requested exit node '%s'", exit
->nickname
);
1463 exit
= extend_info_dup(exit
);
1464 } else { /* we have to decide one */
1465 routerinfo_t
*router
=
1466 choose_good_exit_server(circ
->_base
.purpose
, rl
, state
->need_uptime
,
1467 state
->need_capacity
, state
->is_internal
);
1469 log_warn(LD_CIRC
,"failed to choose an exit server");
1472 exit
= extend_info_from_router(router
);
1474 state
->chosen_exit
= exit
;
1478 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1479 * hop to the cpath reflecting this. Don't send the next extend cell --
1480 * the caller will do this if it wants to.
1483 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1485 cpath_build_state_t
*state
;
1489 state
= circ
->build_state
;
1491 if (state
->chosen_exit
)
1492 extend_info_free(state
->chosen_exit
);
1493 state
->chosen_exit
= extend_info_dup(exit
);
1495 ++circ
->build_state
->desired_path_len
;
1496 onion_append_hop(&circ
->cpath
, exit
);
1500 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1501 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1502 * send the next extend cell to begin connecting to that hop.
1505 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1508 circuit_append_new_exit(circ
, exit
);
1509 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
1510 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
1511 log_warn(LD_CIRC
, "Couldn't extend circuit to new point '%s'.",
1513 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
1519 /** Return the number of routers in <b>routers</b> that are currently up
1520 * and available for building circuits through.
1523 count_acceptable_routers(smartlist_t
*routers
)
1529 n
= smartlist_len(routers
);
1531 r
= smartlist_get(routers
, i
);
1532 // log_debug(LD_CIRC,
1533 // "Contemplating whether router %d (%s) is a new option.",
1535 if (r
->is_running
== 0) {
1536 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1539 if (r
->is_valid
== 0) {
1540 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1542 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1543 * allows this node in some places, then we're getting an inaccurate
1544 * count. For now, be conservative and don't count it. But later we
1545 * should try to be smarter. */
1548 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1550 ; /* C requires an explicit statement after the label */
1556 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1557 * This function is used to extend cpath by another hop.
1560 onion_append_to_cpath(crypt_path_t
**head_ptr
, crypt_path_t
*new_hop
)
1563 new_hop
->next
= (*head_ptr
);
1564 new_hop
->prev
= (*head_ptr
)->prev
;
1565 (*head_ptr
)->prev
->next
= new_hop
;
1566 (*head_ptr
)->prev
= new_hop
;
1568 *head_ptr
= new_hop
;
1569 new_hop
->prev
= new_hop
->next
= new_hop
;
1573 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1574 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1575 * to length <b>cur_len</b> to decide a suitable middle hop for a
1576 * circuit. In particular, make sure we don't pick the exit node or its
1577 * family, and make sure we don't duplicate any previous nodes or their
1579 static routerinfo_t
*
1580 choose_good_middle_server(uint8_t purpose
,
1581 cpath_build_state_t
*state
,
1586 routerinfo_t
*r
, *choice
;
1587 crypt_path_t
*cpath
;
1588 smartlist_t
*excluded
;
1589 or_options_t
*options
= get_options();
1590 router_crn_flags_t flags
= 0;
1591 tor_assert(_CIRCUIT_PURPOSE_MIN
<= purpose
&&
1592 purpose
<= _CIRCUIT_PURPOSE_MAX
);
1594 log_debug(LD_CIRC
, "Contemplating intermediate hop: random choice.");
1595 excluded
= smartlist_create();
1596 if ((r
= build_state_get_exit_router(state
))) {
1597 smartlist_add(excluded
, r
);
1598 routerlist_add_family(excluded
, r
);
1600 for (i
= 0, cpath
= head
; i
< cur_len
; ++i
, cpath
=cpath
->next
) {
1601 if ((r
= router_get_by_digest(cpath
->extend_info
->identity_digest
))) {
1602 smartlist_add(excluded
, r
);
1603 routerlist_add_family(excluded
, r
);
1607 if (state
->need_uptime
)
1608 flags
|= CRN_NEED_UPTIME
;
1609 if (state
->need_capacity
)
1610 flags
|= CRN_NEED_CAPACITY
;
1611 if (options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
)
1612 flags
|= CRN_ALLOW_INVALID
;
1613 choice
= router_choose_random_node(NULL
,
1614 excluded
, options
->ExcludeNodes
, flags
);
1615 smartlist_free(excluded
);
1619 /** Pick a good entry server for the circuit to be built according to
1620 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1621 * router (if we're an OR), and respect firewall settings; if we're
1622 * configured to use entry guards, return one.
1624 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1625 * guard, not for any particular circuit.
1627 static routerinfo_t
*
1628 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
)
1630 routerinfo_t
*r
, *choice
;
1631 smartlist_t
*excluded
;
1632 or_options_t
*options
= get_options();
1633 router_crn_flags_t flags
= 0;
1635 if (state
&& options
->UseEntryGuards
&&
1636 (purpose
!= CIRCUIT_PURPOSE_TESTING
|| options
->BridgeRelay
)) {
1637 return choose_random_entry(state
);
1640 excluded
= smartlist_create();
1642 if (state
&& (r
= build_state_get_exit_router(state
))) {
1643 smartlist_add(excluded
, r
);
1644 routerlist_add_family(excluded
, r
);
1646 if (firewall_is_fascist_or()) {
1647 /*XXXX This could slow things down a lot; use a smarter implementation */
1648 /* exclude all ORs that listen on the wrong port, if anybody notices. */
1649 routerlist_t
*rl
= router_get_routerlist();
1652 for (i
=0; i
< smartlist_len(rl
->routers
); i
++) {
1653 r
= smartlist_get(rl
->routers
, i
);
1654 if (!fascist_firewall_allows_or(r
))
1655 smartlist_add(excluded
, r
);
1658 /* and exclude current entry guards, if applicable */
1659 if (options
->UseEntryGuards
&& entry_guards
) {
1660 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1662 if ((r
= router_get_by_digest(entry
->identity
))) {
1663 smartlist_add(excluded
, r
);
1664 routerlist_add_family(excluded
, r
);
1670 flags
|= CRN_NEED_GUARD
;
1671 if (state
->need_uptime
)
1672 flags
|= CRN_NEED_UPTIME
;
1673 if (state
->need_capacity
)
1674 flags
|= CRN_NEED_CAPACITY
;
1676 if (options
->_AllowInvalid
& ALLOW_INVALID_ENTRY
)
1677 flags
|= CRN_ALLOW_INVALID
;
1679 choice
= router_choose_random_node(
1682 options
->ExcludeNodes
,
1684 smartlist_free(excluded
);
1688 /** Return the first non-open hop in cpath, or return NULL if all
1690 static crypt_path_t
*
1691 onion_next_hop_in_cpath(crypt_path_t
*cpath
)
1693 crypt_path_t
*hop
= cpath
;
1695 if (hop
->state
!= CPATH_STATE_OPEN
)
1698 } while (hop
!= cpath
);
1702 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1703 * based on <b>state</b>. Append the hop info to head_ptr.
1706 onion_extend_cpath(origin_circuit_t
*circ
)
1708 uint8_t purpose
= circ
->_base
.purpose
;
1709 cpath_build_state_t
*state
= circ
->build_state
;
1710 int cur_len
= circuit_get_cpath_len(circ
);
1711 extend_info_t
*info
= NULL
;
1713 if (cur_len
>= state
->desired_path_len
) {
1714 log_debug(LD_CIRC
, "Path is complete: %d steps long",
1715 state
->desired_path_len
);
1719 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
1720 state
->desired_path_len
);
1722 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
1723 info
= extend_info_dup(state
->chosen_exit
);
1724 } else if (cur_len
== 0) { /* picking first node */
1725 routerinfo_t
*r
= choose_good_entry_server(purpose
, state
);
1727 info
= extend_info_from_router(r
);
1730 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
1732 info
= extend_info_from_router(r
);
1736 log_warn(LD_CIRC
,"Failed to find node for hop %d of our path. Discarding "
1737 "this circuit.", cur_len
);
1741 log_debug(LD_CIRC
,"Chose router %s for hop %d (exit is %s)",
1742 info
->nickname
, cur_len
+1, build_state_get_exit_nickname(state
));
1744 onion_append_hop(&circ
->cpath
, info
);
1745 extend_info_free(info
);
1749 /** Create a new hop, annotate it with information about its
1750 * corresponding router <b>choice</b>, and append it to the
1751 * end of the cpath <b>head_ptr</b>. */
1753 onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
)
1755 crypt_path_t
*hop
= tor_malloc_zero(sizeof(crypt_path_t
));
1757 /* link hop into the cpath, at the end. */
1758 onion_append_to_cpath(head_ptr
, hop
);
1760 hop
->magic
= CRYPT_PATH_MAGIC
;
1761 hop
->state
= CPATH_STATE_CLOSED
;
1763 hop
->extend_info
= extend_info_dup(choice
);
1765 hop
->package_window
= CIRCWINDOW_START
;
1766 hop
->deliver_window
= CIRCWINDOW_START
;
1771 /** Allocate a new extend_info object based on the various arguments. */
1773 extend_info_alloc(const char *nickname
, const char *digest
,
1774 crypto_pk_env_t
*onion_key
,
1775 const tor_addr_t
*addr
, uint16_t port
)
1777 extend_info_t
*info
= tor_malloc_zero(sizeof(extend_info_t
));
1778 memcpy(info
->identity_digest
, digest
, DIGEST_LEN
);
1780 strlcpy(info
->nickname
, nickname
, sizeof(info
->nickname
));
1782 info
->onion_key
= crypto_pk_dup_key(onion_key
);
1783 tor_addr_copy(&info
->addr
, addr
);
1788 /** Allocate and return a new extend_info_t that can be used to build a
1789 * circuit to or through the router <b>r</b>. */
1791 extend_info_from_router(routerinfo_t
*r
)
1795 tor_addr_from_ipv4h(&addr
, r
->addr
);
1796 return extend_info_alloc(r
->nickname
, r
->cache_info
.identity_digest
,
1797 r
->onion_pkey
, &addr
, r
->or_port
);
1800 /** Release storage held by an extend_info_t struct. */
1802 extend_info_free(extend_info_t
*info
)
1805 if (info
->onion_key
)
1806 crypto_free_pk_env(info
->onion_key
);
1810 /** Allocate and return a new extend_info_t with the same contents as
1813 extend_info_dup(extend_info_t
*info
)
1815 extend_info_t
*newinfo
;
1817 newinfo
= tor_malloc(sizeof(extend_info_t
));
1818 memcpy(newinfo
, info
, sizeof(extend_info_t
));
1819 if (info
->onion_key
)
1820 newinfo
->onion_key
= crypto_pk_dup_key(info
->onion_key
);
1822 newinfo
->onion_key
= NULL
;
1826 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1827 * If there is no chosen exit, or if we don't know the routerinfo_t for
1828 * the chosen exit, return NULL.
1831 build_state_get_exit_router(cpath_build_state_t
*state
)
1833 if (!state
|| !state
->chosen_exit
)
1835 return router_get_by_digest(state
->chosen_exit
->identity_digest
);
1838 /** Return the nickname for the chosen exit router in <b>state</b>. If
1839 * there is no chosen exit, or if we don't know the routerinfo_t for the
1840 * chosen exit, return NULL.
1843 build_state_get_exit_nickname(cpath_build_state_t
*state
)
1845 if (!state
|| !state
->chosen_exit
)
1847 return state
->chosen_exit
->nickname
;
1850 /** Check whether the entry guard <b>e</b> is usable, given the directory
1851 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1852 * configuration (in <b>options</b>). Set <b>e</b>->bad_since
1853 * accordingly. Return true iff the entry guard's status changes.
1855 * If it's not usable, set *<b>reason</b> to a static string explaining why.
1857 /*XXXX take a routerstatus, not a routerinfo. */
1859 entry_guard_set_status(entry_guard_t
*e
, routerinfo_t
*ri
,
1860 time_t now
, or_options_t
*options
, const char **reason
)
1862 char buf
[HEX_DIGEST_LEN
+1];
1865 tor_assert(options
);
1869 /* Do we want to mark this guard as bad? */
1871 *reason
= "unlisted";
1872 else if (!ri
->is_running
)
1874 else if (options
->UseBridges
&& ri
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1875 *reason
= "not a bridge";
1876 else if (!options
->UseBridges
&& !ri
->is_possible_guard
&&
1877 !routerset_contains_router(options
->EntryNodes
,ri
))
1878 *reason
= "not recommended as a guard";
1879 else if (routerset_contains_router(options
->ExcludeNodes
, ri
))
1880 *reason
= "excluded";
1882 if (*reason
&& ! e
->bad_since
) {
1883 /* Router is newly bad. */
1884 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1885 log_info(LD_CIRC
, "Entry guard %s (%s) is %s: marking as unusable.",
1886 e
->nickname
, buf
, *reason
);
1889 control_event_guard(e
->nickname
, e
->identity
, "BAD");
1891 } else if (!*reason
&& e
->bad_since
) {
1892 /* There's nothing wrong with the router any more. */
1893 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1894 log_info(LD_CIRC
, "Entry guard %s (%s) is no longer unusable: "
1895 "marking as ok.", e
->nickname
, buf
);
1898 control_event_guard(e
->nickname
, e
->identity
, "GOOD");
1904 /** Return true iff enough time has passed since we last tried to connect
1905 * to the unreachable guard <b>e</b> that we're willing to try again. */
1907 entry_is_time_to_retry(entry_guard_t
*e
, time_t now
)
1910 if (e
->last_attempted
< e
->unreachable_since
)
1912 diff
= now
- e
->unreachable_since
;
1914 return now
> (e
->last_attempted
+ 60*60);
1915 else if (diff
< 3*24*60*60)
1916 return now
> (e
->last_attempted
+ 4*60*60);
1917 else if (diff
< 7*24*60*60)
1918 return now
> (e
->last_attempted
+ 18*60*60);
1920 return now
> (e
->last_attempted
+ 36*60*60);
1923 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1924 * working well enough that we are willing to use it as an entry
1925 * right now. (Else return NULL.) In particular, it must be
1926 * - Listed as either up or never yet contacted;
1927 * - Present in the routerlist;
1928 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1929 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1930 * (This check is currently redundant with the Guard flag, but in
1931 * the future that might change. Best to leave it in for now.)
1932 * - Allowed by our current ReachableORAddresses config option; and
1933 * - Currently thought to be reachable by us (unless assume_reachable
1936 static INLINE routerinfo_t
*
1937 entry_is_live(entry_guard_t
*e
, int need_uptime
, int need_capacity
,
1938 int assume_reachable
)
1943 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1944 if (!assume_reachable
&& !e
->can_retry
&&
1945 e
->unreachable_since
&& !entry_is_time_to_retry(e
, time(NULL
)))
1947 r
= router_get_by_digest(e
->identity
);
1950 if (get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1952 if (!get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_GENERAL
)
1954 if (router_is_unreliable(r
, need_uptime
, need_capacity
, 0))
1956 if (!fascist_firewall_allows_or(r
))
1961 /** Return the number of entry guards that we think are usable. */
1963 num_live_entry_guards(void)
1968 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1970 if (entry_is_live(entry
, 0, 1, 0))
1976 /** If <b>digest</b> matches the identity of any node in the
1977 * entry_guards list, return that node. Else return NULL. */
1978 static INLINE entry_guard_t
*
1979 is_an_entry_guard(const char *digest
)
1981 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1982 if (!memcmp(digest
, entry
->identity
, DIGEST_LEN
))
1988 /** Dump a description of our list of entry guards to the log at level
1989 * <b>severity</b>. */
1991 log_entry_guards(int severity
)
1993 smartlist_t
*elements
= smartlist_create();
1997 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
1999 tor_snprintf(buf
, sizeof(buf
), "%s (%s%s)",
2001 entry_is_live(e
, 0, 1, 0) ? "up " : "down ",
2002 e
->made_contact
? "made-contact" : "never-contacted");
2003 smartlist_add(elements
, tor_strdup(buf
));
2006 s
= smartlist_join_strings(elements
, ",", 0, NULL
);
2007 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
2008 smartlist_free(elements
);
2009 log_fn(severity
,LD_CIRC
,"%s",s
);
2013 /** Called when one or more guards that we would previously have used for some
2014 * purpose are no longer in use because a higher-priority guard has become
2017 control_event_guard_deferred(void)
2019 /* XXXX We don't actually have a good way to figure out _how many_ entries
2020 * are live for some purpose. We need an entry_is_even_slightly_live()
2021 * function for this to work right. NumEntryGuards isn't reliable: if we
2022 * need guards with weird properties, we can have more than that number
2027 or_options_t
*options
= get_options();
2030 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2032 if (entry_is_live(entry
, 0, 1, 0)) {
2033 if (n
++ == options
->NumEntryGuards
) {
2034 control_event_guard(entry
->nickname
, entry
->identity
, "DEFERRED");
2042 /** Add a new (preferably stable and fast) router to our
2043 * entry_guards list. Return a pointer to the router if we succeed,
2044 * or NULL if we can't find any more suitable entries.
2046 * If <b>chosen</b> is defined, use that one, and if it's not
2047 * already in our entry_guards list, put it at the *beginning*.
2048 * Else, put the one we pick at the end of the list. */
2049 static routerinfo_t
*
2050 add_an_entry_guard(routerinfo_t
*chosen
, int reset_status
)
2052 routerinfo_t
*router
;
2053 entry_guard_t
*entry
;
2057 entry
= is_an_entry_guard(router
->cache_info
.identity_digest
);
2060 entry
->bad_since
= 0;
2061 entry
->can_retry
= 1;
2066 router
= choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL
, NULL
);
2070 entry
= tor_malloc_zero(sizeof(entry_guard_t
));
2071 log_info(LD_CIRC
, "Chose '%s' as new entry guard.", router
->nickname
);
2072 strlcpy(entry
->nickname
, router
->nickname
, sizeof(entry
->nickname
));
2073 memcpy(entry
->identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
2074 entry
->chosen_on_date
= start_of_month(time(NULL
));
2075 entry
->chosen_by_version
= tor_strdup(VERSION
);
2076 if (chosen
) /* prepend */
2077 smartlist_insert(entry_guards
, 0, entry
);
2079 smartlist_add(entry_guards
, entry
);
2080 control_event_guard(entry
->nickname
, entry
->identity
, "NEW");
2081 control_event_guard_deferred();
2082 log_entry_guards(LOG_INFO
);
2086 /** If the use of entry guards is configured, choose more entry guards
2087 * until we have enough in the list. */
2089 pick_entry_guards(void)
2091 or_options_t
*options
= get_options();
2094 tor_assert(entry_guards
);
2096 while (num_live_entry_guards() < options
->NumEntryGuards
) {
2097 if (!add_an_entry_guard(NULL
, 0))
2102 entry_guards_changed();
2105 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2106 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2107 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2109 /** Release all storage held by <b>e</b>. */
2111 entry_guard_free(entry_guard_t
*e
)
2114 tor_free(e
->chosen_by_version
);
2118 /** Remove any entry guard which was selected by an unknown version of Tor,
2119 * or which was selected by a version of Tor that's known to select
2120 * entry guards badly. */
2122 remove_obsolete_entry_guards(void)
2125 for (i
= 0; i
< smartlist_len(entry_guards
); ++i
) {
2126 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2127 const char *ver
= entry
->chosen_by_version
;
2128 const char *msg
= NULL
;
2130 int version_is_bad
= 0;
2132 msg
= "does not say what version of Tor it was selected by";
2134 } else if (tor_version_parse(ver
, &v
)) {
2135 msg
= "does not seem to be from any recognized version of Tor";
2137 } else if ((tor_version_as_new_as(ver
, "0.1.0.10-alpha") &&
2138 !tor_version_as_new_as(ver
, "0.1.2.16-dev")) ||
2139 (tor_version_as_new_as(ver
, "0.2.0.0-alpha") &&
2140 !tor_version_as_new_as(ver
, "0.2.0.6-alpha"))) {
2141 msg
= "was selected without regard for guard bandwidth";
2144 if (version_is_bad
) {
2145 char dbuf
[HEX_DIGEST_LEN
+1];
2147 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2148 log_notice(LD_CIRC
, "Entry guard '%s' (%s) %s. (Version=%s.) "
2150 entry
->nickname
, dbuf
, msg
, ver
?escaped(ver
):"none");
2151 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2152 entry_guard_free(entry
);
2153 smartlist_del_keeporder(entry_guards
, i
--);
2154 log_entry_guards(LOG_INFO
);
2159 return changed
? 1 : 0;
2162 /** Remove all entry guards that have been down or unlisted for so
2163 * long that we don't think they'll come up again. Return 1 if we
2164 * removed any, or 0 if we did nothing. */
2166 remove_dead_entry_guards(void)
2168 char dbuf
[HEX_DIGEST_LEN
+1];
2169 char tbuf
[ISO_TIME_LEN
+1];
2170 time_t now
= time(NULL
);
2174 for (i
= 0; i
< smartlist_len(entry_guards
); ) {
2175 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2176 if (entry
->bad_since
&&
2177 entry
->bad_since
+ ENTRY_GUARD_REMOVE_AFTER
< now
) {
2179 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2180 format_local_iso_time(tbuf
, entry
->bad_since
);
2181 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been down or unlisted "
2182 "since %s local time; removing.",
2183 entry
->nickname
, dbuf
, tbuf
);
2184 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2185 entry_guard_free(entry
);
2186 smartlist_del_keeporder(entry_guards
, i
);
2187 log_entry_guards(LOG_INFO
);
2192 return changed
? 1 : 0;
2195 /** A new directory or router-status has arrived; update the down/listed
2196 * status of the entry guards.
2198 * An entry is 'down' if the directory lists it as nonrunning.
2199 * An entry is 'unlisted' if the directory doesn't include it.
2201 * Don't call this on startup; only on a fresh download. Otherwise we'll
2202 * think that things are unlisted.
2205 entry_guards_compute_status(void)
2209 int severity
= LOG_DEBUG
;
2210 or_options_t
*options
;
2211 digestmap_t
*reasons
;
2215 options
= get_options();
2219 reasons
= digestmap_new();
2220 SMARTLIST_FOREACH_BEGIN(entry_guards
, entry_guard_t
*, entry
)
2222 routerinfo_t
*r
= router_get_by_digest(entry
->identity
);
2223 const char *reason
= NULL
;
2224 if (entry_guard_set_status(entry
, r
, now
, options
, &reason
))
2227 if (entry
->bad_since
)
2230 digestmap_set(reasons
, entry
->identity
, (char*)reason
);
2232 SMARTLIST_FOREACH_END(entry
);
2234 if (remove_dead_entry_guards())
2237 severity
= changed
? LOG_DEBUG
: LOG_INFO
;
2240 SMARTLIST_FOREACH_BEGIN(entry_guards
, entry_guard_t
*, entry
) {
2241 const char *reason
= digestmap_get(reasons
, entry
->identity
);
2242 log_info(LD_CIRC
, "Summary: Entry '%s' is %s, %s%s%s, and %s.",
2244 entry
->unreachable_since
? "unreachable" : "reachable",
2245 entry
->bad_since
? "unusable" : "usable",
2247 reason
? reason
: "",
2248 entry_is_live(entry
, 0, 1, 0) ? "live" : "not live");
2249 } SMARTLIST_FOREACH_END(entry
);
2250 log_info(LD_CIRC
, " (%d/%d entry guards are usable/new)",
2251 num_live_entry_guards(), smartlist_len(entry_guards
));
2252 log_entry_guards(LOG_INFO
);
2253 entry_guards_changed();
2256 digestmap_free(reasons
, NULL
);
2259 /** Called when a connection to an OR with the identity digest <b>digest</b>
2260 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2261 * If the OR is an entry, change that entry's up/down status.
2262 * Return 0 normally, or -1 if we want to tear down the new connection.
2264 * If <b>mark_relay_status</b>, also call router_set_status() on this
2267 * XXX022 change succeeded and mark_relay_status into 'int flags'.
2270 entry_guard_register_connect_status(const char *digest
, int succeeded
,
2271 int mark_relay_status
, time_t now
)
2274 int refuse_conn
= 0;
2275 int first_contact
= 0;
2276 entry_guard_t
*entry
= NULL
;
2278 char buf
[HEX_DIGEST_LEN
+1];
2283 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2285 if (!memcmp(e
->identity
, digest
, DIGEST_LEN
)) {
2295 base16_encode(buf
, sizeof(buf
), entry
->identity
, DIGEST_LEN
);
2298 if (entry
->unreachable_since
) {
2299 log_info(LD_CIRC
, "Entry guard '%s' (%s) is now reachable again. Good.",
2300 entry
->nickname
, buf
);
2301 entry
->can_retry
= 0;
2302 entry
->unreachable_since
= 0;
2303 entry
->last_attempted
= now
;
2304 control_event_guard(entry
->nickname
, entry
->identity
, "UP");
2307 if (!entry
->made_contact
) {
2308 entry
->made_contact
= 1;
2309 first_contact
= changed
= 1;
2311 } else { /* ! succeeded */
2312 if (!entry
->made_contact
) {
2313 /* We've never connected to this one. */
2315 "Connection to never-contacted entry guard '%s' (%s) failed. "
2316 "Removing from the list. %d/%d entry guards usable/new.",
2317 entry
->nickname
, buf
,
2318 num_live_entry_guards()-1, smartlist_len(entry_guards
)-1);
2319 entry_guard_free(entry
);
2320 smartlist_del_keeporder(entry_guards
, idx
);
2321 log_entry_guards(LOG_INFO
);
2323 } else if (!entry
->unreachable_since
) {
2324 log_info(LD_CIRC
, "Unable to connect to entry guard '%s' (%s). "
2325 "Marking as unreachable.", entry
->nickname
, buf
);
2326 entry
->unreachable_since
= entry
->last_attempted
= now
;
2327 control_event_guard(entry
->nickname
, entry
->identity
, "DOWN");
2329 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2331 char tbuf
[ISO_TIME_LEN
+1];
2332 format_iso_time(tbuf
, entry
->unreachable_since
);
2333 log_debug(LD_CIRC
, "Failed to connect to unreachable entry guard "
2334 "'%s' (%s). It has been unreachable since %s.",
2335 entry
->nickname
, buf
, tbuf
);
2336 entry
->last_attempted
= now
;
2337 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2341 /* if the caller asked us to, also update the is_running flags for this
2343 if (mark_relay_status
)
2344 router_set_status(digest
, succeeded
);
2346 if (first_contact
) {
2347 /* We've just added a new long-term entry guard. Perhaps the network just
2348 * came back? We should give our earlier entries another try too,
2349 * and close this connection so we don't use it before we've given
2350 * the others a shot. */
2351 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2354 if (e
->made_contact
) {
2355 routerinfo_t
*r
= entry_is_live(e
, 0, 1, 1);
2356 if (r
&& e
->unreachable_since
) {
2364 "Connected to new entry guard '%s' (%s). Marking earlier "
2365 "entry guards up. %d/%d entry guards usable/new.",
2366 entry
->nickname
, buf
,
2367 num_live_entry_guards(), smartlist_len(entry_guards
));
2368 log_entry_guards(LOG_INFO
);
2374 entry_guards_changed();
2375 return refuse_conn
? -1 : 0;
2378 /** When we try to choose an entry guard, should we parse and add
2379 * config's EntryNodes first? */
2380 static int should_add_entry_nodes
= 0;
2382 /** Called when the value of EntryNodes changes in our configuration. */
2384 entry_nodes_should_be_added(void)
2386 log_info(LD_CIRC
, "New EntryNodes config option detected. Will use.");
2387 should_add_entry_nodes
= 1;
2390 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2391 * of guard nodes, at the front. */
2393 entry_guards_prepend_from_config(void)
2395 or_options_t
*options
= get_options();
2396 smartlist_t
*entry_routers
, *entry_fps
;
2397 smartlist_t
*old_entry_guards_on_list
, *old_entry_guards_not_on_list
;
2398 tor_assert(entry_guards
);
2400 should_add_entry_nodes
= 0;
2402 if (!options
->EntryNodes
) {
2403 /* It's possible that a controller set EntryNodes, thus making
2404 * should_add_entry_nodes set, then cleared it again, all before the
2405 * call to choose_random_entry() that triggered us. If so, just return.
2410 if (options
->EntryNodes
) {
2411 char *string
= routerset_to_string(options
->EntryNodes
);
2412 log_info(LD_CIRC
,"Adding configured EntryNodes '%s'.", string
);
2416 entry_routers
= smartlist_create();
2417 entry_fps
= smartlist_create();
2418 old_entry_guards_on_list
= smartlist_create();
2419 old_entry_guards_not_on_list
= smartlist_create();
2421 /* Split entry guards into those on the list and those not. */
2423 /* XXXX022 Now that we allow countries and IP ranges in EntryNodes, this is
2424 * potentially an enormous list. For now, we disable such values for
2425 * EntryNodes in options_validate(); really, this wants a better solution.
2426 * Perhaps we should do this calculation once whenever the list of routers
2427 * changes or the entrynodes setting changes.
2429 routerset_get_all_routers(entry_routers
, options
->EntryNodes
, 0);
2430 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
,
2431 smartlist_add(entry_fps
,ri
->cache_info
.identity_digest
));
2432 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2433 if (smartlist_digest_isin(entry_fps
, e
->identity
))
2434 smartlist_add(old_entry_guards_on_list
, e
);
2436 smartlist_add(old_entry_guards_not_on_list
, e
);
2439 /* Remove all currently configured entry guards from entry_routers. */
2440 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2441 if (is_an_entry_guard(ri
->cache_info
.identity_digest
)) {
2442 SMARTLIST_DEL_CURRENT(entry_routers
, ri
);
2446 /* Now build the new entry_guards list. */
2447 smartlist_clear(entry_guards
);
2448 /* First, the previously configured guards that are in EntryNodes. */
2449 smartlist_add_all(entry_guards
, old_entry_guards_on_list
);
2450 /* Next, the rest of EntryNodes */
2451 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2452 add_an_entry_guard(ri
, 0);
2454 /* Finally, the remaining EntryNodes, unless we're strict */
2455 if (options
->StrictEntryNodes
) {
2456 SMARTLIST_FOREACH(old_entry_guards_not_on_list
, entry_guard_t
*, e
,
2457 entry_guard_free(e
));
2459 smartlist_add_all(entry_guards
, old_entry_guards_not_on_list
);
2462 smartlist_free(entry_routers
);
2463 smartlist_free(entry_fps
);
2464 smartlist_free(old_entry_guards_on_list
);
2465 smartlist_free(old_entry_guards_not_on_list
);
2466 entry_guards_changed();
2469 /** Return 1 if we're fine adding arbitrary routers out of the
2470 * directory to our entry guard list. Else return 0. */
2472 entry_list_can_grow(or_options_t
*options
)
2474 if (options
->StrictEntryNodes
)
2476 if (options
->UseBridges
)
2481 /** Pick a live (up and listed) entry guard from entry_guards. If
2482 * <b>state</b> is non-NULL, this is for a specific circuit --
2483 * make sure not to pick this circuit's exit or any node in the
2484 * exit's family. If <b>state</b> is NULL, we're looking for a random
2485 * guard (likely a bridge). */
2487 choose_random_entry(cpath_build_state_t
*state
)
2489 or_options_t
*options
= get_options();
2490 smartlist_t
*live_entry_guards
= smartlist_create();
2491 smartlist_t
*exit_family
= smartlist_create();
2492 routerinfo_t
*chosen_exit
= state
?build_state_get_exit_router(state
) : NULL
;
2493 routerinfo_t
*r
= NULL
;
2494 int need_uptime
= state
? state
->need_uptime
: 0;
2495 int need_capacity
= state
? state
->need_capacity
: 0;
2496 int consider_exit_family
= 0;
2499 smartlist_add(exit_family
, chosen_exit
);
2500 routerlist_add_family(exit_family
, chosen_exit
);
2501 consider_exit_family
= 1;
2505 entry_guards
= smartlist_create();
2507 if (should_add_entry_nodes
)
2508 entry_guards_prepend_from_config();
2510 if (entry_list_can_grow(options
) &&
2512 smartlist_len(entry_guards
) < options
->NumEntryGuards
))
2513 pick_entry_guards();
2516 smartlist_clear(live_entry_guards
);
2517 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2519 r
= entry_is_live(entry
, need_uptime
, need_capacity
, 0);
2520 if (r
&& (!consider_exit_family
|| !smartlist_isin(exit_family
, r
))) {
2521 smartlist_add(live_entry_guards
, r
);
2522 if (!entry
->made_contact
) {
2523 /* Always start with the first not-yet-contacted entry
2524 * guard. Otherwise we might add several new ones, pick
2525 * the second new one, and now we've expanded our entry
2526 * guard list without needing to. */
2527 goto choose_and_finish
;
2529 if (smartlist_len(live_entry_guards
) >= options
->NumEntryGuards
)
2530 break; /* we have enough */
2534 /* Try to have at least 2 choices available. This way we don't
2535 * get stuck with a single live-but-crummy entry and just keep
2537 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2538 if (smartlist_len(live_entry_guards
) < 2) {
2539 if (entry_list_can_grow(options
)) {
2540 /* still no? try adding a new entry then */
2541 /* XXX if guard doesn't imply fast and stable, then we need
2542 * to tell add_an_entry_guard below what we want, or it might
2543 * be a long time til we get it. -RD */
2544 r
= add_an_entry_guard(NULL
, 0);
2546 entry_guards_changed();
2547 /* XXX we start over here in case the new node we added shares
2548 * a family with our exit node. There's a chance that we'll just
2549 * load up on entry guards here, if the network we're using is
2550 * one big family. Perhaps we should teach add_an_entry_guard()
2551 * to understand nodes-to-avoid-if-possible? -RD */
2555 if (!r
&& need_uptime
) {
2556 need_uptime
= 0; /* try without that requirement */
2559 if (!r
&& need_capacity
) {
2560 /* still no? last attempt, try without requiring capacity */
2564 if (!r
&& !entry_list_can_grow(options
) && consider_exit_family
) {
2565 /* still no? if we're using bridges or have strictentrynodes
2566 * set, and our chosen exit is in the same family as all our
2567 * bridges/entry guards, then be flexible about families. */
2568 consider_exit_family
= 0;
2571 /* live_entry_guards may be empty below. Oh well, we tried. */
2575 if (entry_list_can_grow(options
)) {
2576 /* We choose uniformly at random here, because choose_good_entry_server()
2577 * already weights its choices by bandwidth, so we don't want to
2578 * *double*-weight our guard selection. */
2579 r
= smartlist_choose(live_entry_guards
);
2581 /* We need to weight by bandwidth, because our bridges or entryguards
2582 * were not already selected proportional to their bandwidth. */
2583 r
= routerlist_sl_choose_by_bandwidth(live_entry_guards
, WEIGHT_FOR_GUARD
);
2585 smartlist_free(live_entry_guards
);
2586 smartlist_free(exit_family
);
2590 /** Helper: Return the start of the month containing <b>time</b>. */
2592 start_of_month(time_t now
)
2595 tor_gmtime_r(&now
, &tm
);
2600 return tor_timegm(&tm
);
2603 /** Parse <b>state</b> and learn about the entry guards it describes.
2604 * If <b>set</b> is true, and there are no errors, replace the global
2605 * entry_list with what we find.
2606 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2607 * describing the error, and return -1.
2610 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
2612 entry_guard_t
*node
= NULL
;
2613 smartlist_t
*new_entry_guards
= smartlist_create();
2614 config_line_t
*line
;
2615 time_t now
= time(NULL
);
2616 const char *state_version
= state
->TorVersion
;
2617 digestmap_t
*added_by
= digestmap_new();
2620 for (line
= state
->EntryGuards
; line
; line
= line
->next
) {
2621 if (!strcasecmp(line
->key
, "EntryGuard")) {
2622 smartlist_t
*args
= smartlist_create();
2623 node
= tor_malloc_zero(sizeof(entry_guard_t
));
2624 /* all entry guards on disk have been contacted */
2625 node
->made_contact
= 1;
2626 smartlist_add(new_entry_guards
, node
);
2627 smartlist_split_string(args
, line
->value
, " ",
2628 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2629 if (smartlist_len(args
)<2) {
2630 *msg
= tor_strdup("Unable to parse entry nodes: "
2631 "Too few arguments to EntryGuard");
2632 } else if (!is_legal_nickname(smartlist_get(args
,0))) {
2633 *msg
= tor_strdup("Unable to parse entry nodes: "
2634 "Bad nickname for EntryGuard");
2636 strlcpy(node
->nickname
, smartlist_get(args
,0), MAX_NICKNAME_LEN
+1);
2637 if (base16_decode(node
->identity
, DIGEST_LEN
, smartlist_get(args
,1),
2638 strlen(smartlist_get(args
,1)))<0) {
2639 *msg
= tor_strdup("Unable to parse entry nodes: "
2640 "Bad hex digest for EntryGuard");
2643 SMARTLIST_FOREACH(args
, char*, cp
, tor_free(cp
));
2644 smartlist_free(args
);
2647 } else if (!strcasecmp(line
->key
, "EntryGuardDownSince") ||
2648 !strcasecmp(line
->key
, "EntryGuardUnlistedSince")) {
2650 time_t last_try
= 0;
2652 *msg
= tor_strdup("Unable to parse entry nodes: "
2653 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2656 if (parse_iso_time(line
->value
, &when
)<0) {
2657 *msg
= tor_strdup("Unable to parse entry nodes: "
2658 "Bad time in EntryGuardDownSince/UnlistedSince");
2662 /* It's a bad idea to believe info in the future: you can wind
2663 * up with timeouts that aren't allowed to happen for years. */
2666 if (strlen(line
->value
) >= ISO_TIME_LEN
+ISO_TIME_LEN
+1) {
2667 /* ignore failure */
2668 (void) parse_iso_time(line
->value
+ISO_TIME_LEN
+1, &last_try
);
2670 if (!strcasecmp(line
->key
, "EntryGuardDownSince")) {
2671 node
->unreachable_since
= when
;
2672 node
->last_attempted
= last_try
;
2674 node
->bad_since
= when
;
2676 } else if (!strcasecmp(line
->key
, "EntryGuardAddedBy")) {
2678 /* format is digest version date */
2679 if (strlen(line
->value
) < HEX_DIGEST_LEN
+1+1+1+ISO_TIME_LEN
) {
2680 log_warn(LD_BUG
, "EntryGuardAddedBy line is not long enough.");
2683 if (base16_decode(d
, sizeof(d
), line
->value
, HEX_DIGEST_LEN
)<0 ||
2684 line
->value
[HEX_DIGEST_LEN
] != ' ') {
2685 log_warn(LD_BUG
, "EntryGuardAddedBy line %s does not begin with "
2686 "hex digest", escaped(line
->value
));
2689 digestmap_set(added_by
, d
, tor_strdup(line
->value
+HEX_DIGEST_LEN
+1));
2691 log_warn(LD_BUG
, "Unexpected key %s", line
->key
);
2695 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2698 char *val
= digestmap_get(added_by
, e
->identity
);
2699 if (val
&& (sp
= strchr(val
, ' '))) {
2702 if (parse_iso_time(sp
, &when
)<0) {
2703 log_warn(LD_BUG
, "Can't read time %s in EntryGuardAddedBy", sp
);
2705 e
->chosen_by_version
= tor_strdup(val
);
2706 e
->chosen_on_date
= when
;
2709 if (state_version
) {
2710 e
->chosen_by_version
= tor_strdup(state_version
);
2711 e
->chosen_on_date
= start_of_month(time(NULL
));
2717 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2718 entry_guard_free(e
));
2719 smartlist_free(new_entry_guards
);
2720 } else { /* !*err && set */
2722 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2723 entry_guard_free(e
));
2724 smartlist_free(entry_guards
);
2726 entry_guards
= new_entry_guards
;
2727 entry_guards_dirty
= 0;
2728 if (remove_obsolete_entry_guards())
2729 entry_guards_dirty
= 1;
2731 digestmap_free(added_by
, _tor_free
);
2732 return *msg
? -1 : 0;
2735 /** Our list of entry guards has changed, or some element of one
2736 * of our entry guards has changed. Write the changes to disk within
2737 * the next few minutes.
2740 entry_guards_changed(void)
2743 entry_guards_dirty
= 1;
2745 /* or_state_save() will call entry_guards_update_state(). */
2746 when
= get_options()->AvoidDiskWrites
? time(NULL
) + 3600 : time(NULL
)+600;
2747 or_state_mark_dirty(get_or_state(), when
);
2750 /** If the entry guard info has not changed, do nothing and return.
2751 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2752 * a new one out of the global entry_guards list, and then mark
2753 * <b>state</b> dirty so it will get saved to disk.
2756 entry_guards_update_state(or_state_t
*state
)
2758 config_line_t
**next
, *line
;
2759 if (! entry_guards_dirty
)
2762 config_free_lines(state
->EntryGuards
);
2763 next
= &state
->EntryGuards
;
2766 entry_guards
= smartlist_create();
2767 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2769 char dbuf
[HEX_DIGEST_LEN
+1];
2770 if (!e
->made_contact
)
2771 continue; /* don't write this one to disk */
2772 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2773 line
->key
= tor_strdup("EntryGuard");
2774 line
->value
= tor_malloc(HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2);
2775 base16_encode(dbuf
, sizeof(dbuf
), e
->identity
, DIGEST_LEN
);
2776 tor_snprintf(line
->value
,HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2,
2777 "%s %s", e
->nickname
, dbuf
);
2778 next
= &(line
->next
);
2779 if (e
->unreachable_since
) {
2780 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2781 line
->key
= tor_strdup("EntryGuardDownSince");
2782 line
->value
= tor_malloc(ISO_TIME_LEN
+1+ISO_TIME_LEN
+1);
2783 format_iso_time(line
->value
, e
->unreachable_since
);
2784 if (e
->last_attempted
) {
2785 line
->value
[ISO_TIME_LEN
] = ' ';
2786 format_iso_time(line
->value
+ISO_TIME_LEN
+1, e
->last_attempted
);
2788 next
= &(line
->next
);
2791 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2792 line
->key
= tor_strdup("EntryGuardUnlistedSince");
2793 line
->value
= tor_malloc(ISO_TIME_LEN
+1);
2794 format_iso_time(line
->value
, e
->bad_since
);
2795 next
= &(line
->next
);
2797 if (e
->chosen_on_date
&& e
->chosen_by_version
&&
2798 !strchr(e
->chosen_by_version
, ' ')) {
2799 char d
[HEX_DIGEST_LEN
+1];
2800 char t
[ISO_TIME_LEN
+1];
2802 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2803 line
->key
= tor_strdup("EntryGuardAddedBy");
2804 val_len
= (HEX_DIGEST_LEN
+1+strlen(e
->chosen_by_version
)
2806 line
->value
= tor_malloc(val_len
);
2807 base16_encode(d
, sizeof(d
), e
->identity
, DIGEST_LEN
);
2808 format_iso_time(t
, e
->chosen_on_date
);
2809 tor_snprintf(line
->value
, val_len
, "%s %s %s",
2810 d
, e
->chosen_by_version
, t
);
2811 next
= &(line
->next
);
2814 if (!get_options()->AvoidDiskWrites
)
2815 or_state_mark_dirty(get_or_state(), 0);
2816 entry_guards_dirty
= 0;
2819 /** If <b>question</b> is the string "entry-guards", then dump
2820 * to *<b>answer</b> a newly allocated string describing all of
2821 * the nodes in the global entry_guards list. See control-spec.txt
2823 * For backward compatibility, we also handle the string "helper-nodes".
2826 getinfo_helper_entry_guards(control_connection_t
*conn
,
2827 const char *question
, char **answer
)
2829 int use_long_names
= conn
->use_long_names
;
2831 if (!strcmp(question
,"entry-guards") ||
2832 !strcmp(question
,"helper-nodes")) {
2833 smartlist_t
*sl
= smartlist_create();
2834 char tbuf
[ISO_TIME_LEN
+1];
2835 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
2837 entry_guards
= smartlist_create();
2838 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2840 size_t len
= MAX_VERBOSE_NICKNAME_LEN
+ISO_TIME_LEN
+32;
2841 char *c
= tor_malloc(len
);
2842 const char *status
= NULL
;
2844 if (!e
->made_contact
) {
2845 status
= "never-connected";
2846 } else if (e
->bad_since
) {
2847 when
= e
->bad_since
;
2848 status
= "unusable";
2852 if (use_long_names
) {
2853 routerinfo_t
*ri
= router_get_by_digest(e
->identity
);
2855 router_get_verbose_nickname(nbuf
, ri
);
2858 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
2859 /* e->nickname field is not very reliable if we don't know about
2860 * this router any longer; don't include it. */
2863 base16_encode(nbuf
, sizeof(nbuf
), e
->identity
, DIGEST_LEN
);
2866 format_iso_time(tbuf
, when
);
2867 tor_snprintf(c
, len
, "%s %s %s\n", nbuf
, status
, tbuf
);
2869 tor_snprintf(c
, len
, "%s %s\n", nbuf
, status
);
2871 smartlist_add(sl
, c
);
2873 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2874 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2880 /** Information about a configured bridge. Currently this just matches the
2881 * ones in the torrc file, but one day we may be able to learn about new
2882 * bridges on our own, and remember them in the state file. */
2884 /** Address of the bridge. */
2886 /** TLS port for the bridge. */
2888 /** Expected identity digest, or all zero bytes if we don't know what the
2889 * digest should be. */
2890 char identity
[DIGEST_LEN
];
2891 /** When should we next try to fetch a descriptor for this bridge? */
2892 download_status_t fetch_status
;
2895 /** A list of configured bridges. Whenever we actually get a descriptor
2896 * for one, we add it as an entry guard. */
2897 static smartlist_t
*bridge_list
= NULL
;
2899 /** Initialize the bridge list to empty, creating it if needed. */
2901 clear_bridge_list(void)
2904 bridge_list
= smartlist_create();
2905 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, b
, tor_free(b
));
2906 smartlist_clear(bridge_list
);
2909 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2910 * (either by comparing keys if possible, else by comparing addr/port).
2911 * Else return NULL. */
2912 static bridge_info_t
*
2913 routerinfo_get_configured_bridge(routerinfo_t
*ri
)
2917 SMARTLIST_FOREACH_BEGIN(bridge_list
, bridge_info_t
*, bridge
)
2919 if (tor_digest_is_zero(bridge
->identity
) &&
2920 tor_addr_eq_ipv4h(&bridge
->addr
, ri
->addr
) &&
2921 bridge
->port
== ri
->or_port
)
2923 if (!memcmp(bridge
->identity
, ri
->cache_info
.identity_digest
,
2927 SMARTLIST_FOREACH_END(bridge
);
2931 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
2933 routerinfo_is_a_configured_bridge(routerinfo_t
*ri
)
2935 return routerinfo_get_configured_bridge(ri
) ? 1 : 0;
2938 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2939 * is set, it tells us the identity key too. */
2941 bridge_add_from_config(const tor_addr_t
*addr
, uint16_t port
, char *digest
)
2943 bridge_info_t
*b
= tor_malloc_zero(sizeof(bridge_info_t
));
2944 tor_addr_copy(&b
->addr
, addr
);
2947 memcpy(b
->identity
, digest
, DIGEST_LEN
);
2948 b
->fetch_status
.schedule
= DL_SCHED_BRIDGE
;
2950 bridge_list
= smartlist_create();
2951 smartlist_add(bridge_list
, b
);
2954 /** If <b>digest</b> is one of our known bridges, return it. */
2955 static bridge_info_t
*
2956 find_bridge_by_digest(const char *digest
)
2958 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2960 if (!memcmp(bridge
->identity
, digest
, DIGEST_LEN
))
2966 /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
2967 * is a helpful string describing this bridge. */
2969 launch_direct_bridge_descriptor_fetch(bridge_info_t
*bridge
)
2973 if (connection_get_by_type_addr_port_purpose(
2974 CONN_TYPE_DIR
, &bridge
->addr
, bridge
->port
,
2975 DIR_PURPOSE_FETCH_SERVERDESC
))
2976 return; /* it's already on the way */
2978 address
= tor_dup_addr(&bridge
->addr
);
2979 directory_initiate_command(address
, &bridge
->addr
,
2981 0, /* does not matter */
2982 1, bridge
->identity
,
2983 DIR_PURPOSE_FETCH_SERVERDESC
,
2984 ROUTER_PURPOSE_BRIDGE
,
2985 0, "authority.z", NULL
, 0, 0);
2989 /** Fetching the bridge descriptor from the bridge authority returned a
2990 * "not found". Fall back to trying a direct fetch. */
2992 retry_bridge_descriptor_fetch_directly(const char *digest
)
2994 bridge_info_t
*bridge
= find_bridge_by_digest(digest
);
2996 return; /* not found? oh well. */
2998 launch_direct_bridge_descriptor_fetch(bridge
);
3001 /** For each bridge in our list for which we don't currently have a
3002 * descriptor, fetch a new copy of its descriptor -- either directly
3003 * from the bridge or via a bridge authority. */
3005 fetch_bridge_descriptors(time_t now
)
3007 or_options_t
*options
= get_options();
3008 int num_bridge_auths
= get_n_authorities(BRIDGE_AUTHORITY
);
3009 int ask_bridge_directly
;
3010 int can_use_bridge_authority
;
3015 SMARTLIST_FOREACH_BEGIN(bridge_list
, bridge_info_t
*, bridge
)
3017 if (!download_status_is_ready(&bridge
->fetch_status
, now
,
3018 IMPOSSIBLE_TO_DOWNLOAD
))
3019 continue; /* don't bother, no need to retry yet */
3021 /* schedule another fetch as if this one will fail, in case it does */
3022 download_status_failed(&bridge
->fetch_status
, 0);
3024 can_use_bridge_authority
= !tor_digest_is_zero(bridge
->identity
) &&
3026 ask_bridge_directly
= !can_use_bridge_authority
||
3027 !options
->UpdateBridgesFromAuthority
;
3028 log_debug(LD_DIR
, "ask_bridge_directly=%d (%d, %d, %d)",
3029 ask_bridge_directly
, tor_digest_is_zero(bridge
->identity
),
3030 !options
->UpdateBridgesFromAuthority
, !num_bridge_auths
);
3032 if (ask_bridge_directly
&&
3033 !fascist_firewall_allows_address_or(&bridge
->addr
, bridge
->port
)) {
3034 log_notice(LD_DIR
, "Bridge at '%s:%d' isn't reachable by our "
3035 "firewall policy. %s.", fmt_addr(&bridge
->addr
),
3037 can_use_bridge_authority
?
3038 "Asking bridge authority instead" : "Skipping");
3039 if (can_use_bridge_authority
)
3040 ask_bridge_directly
= 0;
3045 if (ask_bridge_directly
) {
3046 /* we need to ask the bridge itself for its descriptor. */
3047 launch_direct_bridge_descriptor_fetch(bridge
);
3049 /* We have a digest and we want to ask an authority. We could
3050 * combine all the requests into one, but that may give more
3051 * hints to the bridge authority than we want to give. */
3052 char resource
[10 + HEX_DIGEST_LEN
];
3053 memcpy(resource
, "fp/", 3);
3054 base16_encode(resource
+3, HEX_DIGEST_LEN
+1,
3055 bridge
->identity
, DIGEST_LEN
);
3056 memcpy(resource
+3+HEX_DIGEST_LEN
, ".z", 3);
3057 log_info(LD_DIR
, "Fetching bridge info '%s' from bridge authority.",
3059 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
3060 ROUTER_PURPOSE_BRIDGE
, resource
, 0);
3063 SMARTLIST_FOREACH_END(bridge
);
3066 /** We just learned a descriptor for a bridge. See if that
3067 * digest is in our entry guard list, and add it if not. */
3069 learned_bridge_descriptor(routerinfo_t
*ri
, int from_cache
)
3072 tor_assert(ri
->purpose
== ROUTER_PURPOSE_BRIDGE
);
3073 if (get_options()->UseBridges
) {
3074 int first
= !any_bridge_descriptors_known();
3075 bridge_info_t
*bridge
= routerinfo_get_configured_bridge(ri
);
3076 time_t now
= time(NULL
);
3079 if (bridge
) { /* if we actually want to use this one */
3080 /* it's here; schedule its re-fetch for a long time from now. */
3082 download_status_reset(&bridge
->fetch_status
);
3084 add_an_entry_guard(ri
, 1);
3085 log_notice(LD_DIR
, "new bridge descriptor '%s' (%s)", ri
->nickname
,
3086 from_cache
? "cached" : "fresh");
3088 routerlist_retry_directory_downloads(now
);
3093 /** Return 1 if any of our entry guards have descriptors that
3094 * are marked with purpose 'bridge' and are running. Else return 0.
3096 * We use this function to decide if we're ready to start building
3097 * circuits through our bridges, or if we need to wait until the
3098 * directory "server/authority" requests finish. */
3100 any_bridge_descriptors_known(void)
3102 tor_assert(get_options()->UseBridges
);
3103 return choose_random_entry(NULL
)!=NULL
? 1 : 0;
3106 /** Return 1 if there are any directory conns fetching bridge descriptors
3107 * that aren't marked for close. We use this to guess if we should tell
3108 * the controller that we have a problem. */
3110 any_pending_bridge_descriptor_fetches(void)
3112 smartlist_t
*conns
= get_connection_array();
3113 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3115 if (conn
->type
== CONN_TYPE_DIR
&&
3116 conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
3117 TO_DIR_CONN(conn
)->router_purpose
== ROUTER_PURPOSE_BRIDGE
&&
3118 !conn
->marked_for_close
&&
3119 conn
->linked
&& !conn
->linked_conn
->marked_for_close
) {
3120 log_debug(LD_DIR
, "found one: %s", conn
->address
);
3127 /** Return 1 if we have at least one descriptor for a bridge and
3128 * all descriptors we know are down. Else return 0. If <b>act</b> is
3129 * 1, then mark the down bridges up; else just observe and report. */
3131 bridges_retry_helper(int act
)
3135 int any_running
= 0;
3137 entry_guards
= smartlist_create();
3138 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3140 ri
= router_get_by_digest(e
->identity
);
3141 if (ri
&& ri
->purpose
== ROUTER_PURPOSE_BRIDGE
) {
3144 any_running
= 1; /* some bridge is both known and running */
3145 else if (act
) { /* mark it for retry */
3152 log_debug(LD_DIR
, "any_known %d, any_running %d", any_known
, any_running
);
3153 return any_known
&& !any_running
;
3156 /** Do we know any descriptors for our bridges, and are they all
3159 bridges_known_but_down(void)
3161 return bridges_retry_helper(0);
3164 /** Mark all down known bridges up. */
3166 bridges_retry_all(void)
3168 bridges_retry_helper(1);
3171 /** Release all storage held by the list of entry guards and related
3172 * memory structs. */
3174 entry_guards_free_all(void)
3177 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3178 entry_guard_free(e
));
3179 smartlist_free(entry_guards
);
3180 entry_guards
= NULL
;
3182 clear_bridge_list();
3183 smartlist_free(bridge_list
);