1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char circuitbuild_c_id
[] =
10 * \file circuitbuild.c
11 * \brief The actual details of building circuits.
16 /********* START VARIABLES **********/
18 /** A global list of all circuits at this hop. */
19 extern circuit_t
*global_circuitlist
;
21 /** An entry_guard_t represents our information about a chosen long-term
22 * first hop, known as a "helper" node in the literature. We can't just
23 * use a routerinfo_t, since we want to remember these even when we
24 * don't have a directory. */
26 char nickname
[MAX_NICKNAME_LEN
+1];
27 char identity
[DIGEST_LEN
];
28 unsigned int made_contact
: 1; /**< 0 if we have never connected to this
29 * router, 1 if we have. */
30 unsigned int can_retry
: 1; /**< Should we retry connecting to this entry,
31 * in spite of having it marked as unreachable?*/
32 time_t bad_since
; /**< 0 if this guard is currently usable, or the time at
33 * which it was observed to become (according to the
34 * directory or the user configuration) unusable. */
35 time_t unreachable_since
; /**< 0 if we can connect to this guard, or the
36 * time at which we first noticed we couldn't
38 time_t last_attempted
; /**< 0 if we can connect to this guard, or the time
39 * at which we last failed to connect to it. */
42 /** A list of our chosen entry guards. */
43 static smartlist_t
*entry_guards
= NULL
;
44 /** A value of 1 means that the entry_guards list has changed
45 * and those changes need to be flushed to disk. */
46 static int entry_guards_dirty
= 0;
48 /********* END VARIABLES ************/
50 static int circuit_deliver_create_cell(circuit_t
*circ
,
51 uint8_t cell_type
, const char *payload
);
52 static int onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
);
53 static crypt_path_t
*onion_next_hop_in_cpath(crypt_path_t
*cpath
);
54 static int onion_extend_cpath(origin_circuit_t
*circ
);
55 static int count_acceptable_routers(smartlist_t
*routers
);
56 static int onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
);
58 static void entry_guards_changed(void);
60 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
61 * and with the high bit specified by conn-\>circ_id_type, until we get
62 * a circ_id that is not in use by any other circuit on that conn.
64 * Return it, or 0 if can't get a unique circ_id.
67 get_unique_circ_id_by_conn(or_connection_t
*conn
)
69 uint16_t test_circ_id
;
74 if (conn
->circ_id_type
== CIRC_ID_TYPE_NEITHER
) {
75 log_warn(LD_BUG
, "Trying to pick a circuit ID for a connection from "
76 "a client with no identity.");
79 high_bit
= (conn
->circ_id_type
== CIRC_ID_TYPE_HIGHER
) ? 1<<15 : 0;
81 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
82 * circID such that (high_bit|test_circ_id) is not already used. */
83 test_circ_id
= conn
->next_circ_id
++;
84 if (test_circ_id
== 0 || test_circ_id
>= 1<<15) {
86 conn
->next_circ_id
= 2;
88 if (++attempts
> 1<<15) {
89 /* Make sure we don't loop forever if all circ_id's are used. This
90 * matters because it's an external DoS opportunity.
92 log_warn(LD_CIRC
,"No unused circ IDs. Failing.");
95 test_circ_id
|= high_bit
;
96 } while (circuit_get_by_circid_orconn(test_circ_id
, conn
));
100 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
101 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
102 * list information about link status in a more verbose format using spaces.
103 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
104 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
108 circuit_list_path_impl(origin_circuit_t
*circ
, int verbose
, int verbose_names
)
111 smartlist_t
*elements
;
112 const char *states
[] = {"closed", "waiting for keys", "open"};
116 elements
= smartlist_create();
119 const char *nickname
= build_state_get_exit_nickname(circ
->build_state
);
120 tor_snprintf(buf
, sizeof(buf
), "%s%s circ (length %d%s%s):",
121 circ
->build_state
->is_internal
? "internal" : "exit",
122 circ
->build_state
->need_uptime
? " (high-uptime)" : "",
123 circ
->build_state
->desired_path_len
,
124 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" : ", exit ",
125 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" :
126 (nickname
?nickname
:"*unnamed*"));
127 smartlist_add(elements
, tor_strdup(buf
));
136 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
138 if (!hop
->extend_info
)
141 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
142 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
))) {
143 router_get_verbose_nickname(elt
, ri
);
144 } else if (hop
->extend_info
->nickname
&&
145 is_legal_nickname(hop
->extend_info
->nickname
)) {
147 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
148 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
149 elt
[HEX_DIGEST_LEN
+1]= '~';
150 strlcpy(elt
+HEX_DIGEST_LEN
+2,
151 hop
->extend_info
->nickname
, MAX_NICKNAME_LEN
+1);
154 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
155 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
157 } else { /* ! verbose_names */
158 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
)) &&
160 elt
= tor_strdup(hop
->extend_info
->nickname
);
162 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
164 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
165 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
170 size_t len
= strlen(elt
)+2+strlen(states
[hop
->state
])+1;
171 char *v
= tor_malloc(len
);
172 tor_assert(hop
->state
<= 2);
173 tor_snprintf(v
,len
,"%s(%s)",elt
,states
[hop
->state
]);
174 smartlist_add(elements
, v
);
177 smartlist_add(elements
, elt
);
180 } while (hop
!= circ
->cpath
);
182 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
183 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
184 smartlist_free(elements
);
188 /** If <b>verbose</b> is false, allocate and return a comma-separated
189 * list of the currently built elements of circuit_t. If
190 * <b>verbose</b> is true, also list information about link status in
191 * a more verbose format using spaces.
194 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
196 return circuit_list_path_impl(circ
, verbose
, 0);
199 /** Allocate and return a comma-separated list of the currently built elements
200 * of circuit_t, giving each as a verbose nickname.
203 circuit_list_path_for_controller(origin_circuit_t
*circ
)
205 return circuit_list_path_impl(circ
, 0, 1);
208 /** Log, at severity <b>severity</b>, the nicknames of each router in
209 * circ's cpath. Also log the length of the cpath, and the intended
213 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
215 char *s
= circuit_list_path(circ
,1);
216 log(severity
,domain
,"%s",s
);
220 /** Tell the rep(utation)hist(ory) module about the status of the links
221 * in circ. Hops that have become OPEN are marked as successfully
222 * extended; the _first_ hop that isn't open (if any) is marked as
225 /* XXXX Someday we should learn from OR circuits too. */
227 circuit_rep_hist_note_result(origin_circuit_t
*circ
)
230 char *prev_digest
= NULL
;
231 routerinfo_t
*router
;
233 if (!hop
) /* circuit hasn't started building yet. */
235 if (server_mode(get_options())) {
236 routerinfo_t
*me
= router_get_my_routerinfo();
239 prev_digest
= me
->cache_info
.identity_digest
;
242 router
= router_get_by_digest(hop
->extend_info
->identity_digest
);
245 if (hop
->state
== CPATH_STATE_OPEN
)
246 rep_hist_note_extend_succeeded(prev_digest
,
247 router
->cache_info
.identity_digest
);
249 rep_hist_note_extend_failed(prev_digest
,
250 router
->cache_info
.identity_digest
);
254 prev_digest
= router
->cache_info
.identity_digest
;
259 } while (hop
!=circ
->cpath
);
262 /** Pick all the entries in our cpath. Stop and return 0 when we're
263 * happy, or return -1 if an error occurs. */
265 onion_populate_cpath(origin_circuit_t
*circ
)
269 r
= onion_extend_cpath(circ
);
271 log_info(LD_CIRC
,"Generating cpath hop failed.");
276 return 0; /* if r == 1 */
279 /** Create and return a new origin circuit. Initialize its purpose and
280 * build-state based on our arguments. */
282 origin_circuit_init(uint8_t purpose
, int onehop_tunnel
,
283 int need_uptime
, int need_capacity
, int internal
)
285 /* sets circ->p_circ_id and circ->p_conn */
286 origin_circuit_t
*circ
= origin_circuit_new();
287 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OR_WAIT
);
288 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
289 circ
->build_state
->onehop_tunnel
= onehop_tunnel
;
290 circ
->build_state
->need_uptime
= need_uptime
;
291 circ
->build_state
->need_capacity
= need_capacity
;
292 circ
->build_state
->is_internal
= internal
;
293 circ
->_base
.purpose
= purpose
;
297 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
298 * is defined, then use that as your exit router, else choose a suitable
301 * Also launch a connection to the first OR in the chosen path, if
302 * it's not open already.
305 circuit_establish_circuit(uint8_t purpose
, int onehop_tunnel
,
307 int need_uptime
, int need_capacity
, int internal
)
309 origin_circuit_t
*circ
;
312 circ
= origin_circuit_init(purpose
, onehop_tunnel
,
313 need_uptime
, need_capacity
, internal
);
315 if (onion_pick_cpath_exit(circ
, exit
) < 0 ||
316 onion_populate_cpath(circ
) < 0) {
317 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
321 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
323 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
324 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
330 /** Start establishing the first hop of our circuit. Figure out what
331 * OR we should connect to, and if necessary start the connection to
332 * it. If we're already connected, then send the 'create' cell.
333 * Return 0 for ok, -reason if circ should be marked-for-close. */
335 circuit_handle_first_hop(origin_circuit_t
*circ
)
337 crypt_path_t
*firsthop
;
338 or_connection_t
*n_conn
;
339 char tmpbuf
[INET_NTOA_BUF_LEN
];
343 firsthop
= onion_next_hop_in_cpath(circ
->cpath
);
344 tor_assert(firsthop
);
345 tor_assert(firsthop
->extend_info
);
347 /* now see if we're already connected to the first OR in 'route' */
348 in
.s_addr
= htonl(firsthop
->extend_info
->addr
);
349 tor_inet_ntoa(&in
, tmpbuf
, sizeof(tmpbuf
));
350 log_debug(LD_CIRC
,"Looking for firsthop '%s:%u'",tmpbuf
,
351 firsthop
->extend_info
->port
);
352 /* imprint the circuit with its future n_conn->id */
353 memcpy(circ
->_base
.n_conn_id_digest
, firsthop
->extend_info
->identity_digest
,
355 n_conn
= connection_or_get_by_identity_digest(
356 firsthop
->extend_info
->identity_digest
);
357 /* If we don't have an open conn, or the conn we have is obsolete
358 * (i.e. old or broken) and the other side will let us make a second
359 * connection without dropping it immediately... */
360 if (!n_conn
|| n_conn
->_base
.state
!= OR_CONN_STATE_OPEN
||
361 (n_conn
->_base
.or_is_obsolete
&&
362 router_digest_version_as_new_as(firsthop
->extend_info
->identity_digest
,
363 "0.1.1.9-alpha-cvs"))) {
364 /* not currently connected */
365 circ
->_base
.n_addr
= firsthop
->extend_info
->addr
;
366 circ
->_base
.n_port
= firsthop
->extend_info
->port
;
368 if (!n_conn
|| n_conn
->_base
.or_is_obsolete
) { /* launch the connection */
369 n_conn
= connection_or_connect(firsthop
->extend_info
->addr
,
370 firsthop
->extend_info
->port
,
371 firsthop
->extend_info
->identity_digest
);
372 if (!n_conn
) { /* connect failed, forget the whole thing */
373 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
374 return -END_CIRC_REASON_CONNECTFAILED
;
378 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
379 /* return success. The onion/circuit/etc will be taken care of
380 * automatically (may already have been) whenever n_conn reaches
381 * OR_CONN_STATE_OPEN.
384 } else { /* it's already open. use it. */
385 circ
->_base
.n_addr
= n_conn
->_base
.addr
;
386 circ
->_base
.n_port
= n_conn
->_base
.port
;
387 circ
->_base
.n_conn
= n_conn
;
388 log_debug(LD_CIRC
,"Conn open. Delivering first onion skin.");
389 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
390 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
397 /** Find any circuits that are waiting on <b>or_conn</b> to become
398 * open and get them to send their create cells forward.
400 * Status is 1 if connect succeeded, or 0 if connect failed.
403 circuit_n_conn_done(or_connection_t
*or_conn
, int status
)
405 smartlist_t
*pending_circs
;
408 log_debug(LD_CIRC
,"or_conn to %s, status=%d",
409 or_conn
->nickname
? or_conn
->nickname
: "NULL", status
);
411 pending_circs
= smartlist_create();
412 circuit_get_all_pending_on_or_conn(pending_circs
, or_conn
);
414 SMARTLIST_FOREACH(pending_circs
, circuit_t
*, circ
,
416 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
417 * leaving them in in case it's possible for the status of a circuit to
418 * change as we're going down the list. */
419 if (circ
->marked_for_close
|| circ
->n_conn
||
420 circ
->state
!= CIRCUIT_STATE_OR_WAIT
)
422 if (tor_digest_is_zero(circ
->n_conn_id_digest
)) {
423 /* Look at addr/port. This is an unkeyed connection. */
424 if (circ
->n_addr
!= or_conn
->_base
.addr
||
425 circ
->n_port
!= or_conn
->_base
.port
)
427 /* now teach circ the right identity_digest */
428 memcpy(circ
->n_conn_id_digest
, or_conn
->identity_digest
, DIGEST_LEN
);
430 /* We expected a key. See if it's the right one. */
431 if (memcmp(or_conn
->identity_digest
,
432 circ
->n_conn_id_digest
, DIGEST_LEN
))
435 if (!status
) { /* or_conn failed; close circ */
436 log_info(LD_CIRC
,"or_conn failed. Closing circ.");
437 circuit_mark_for_close(circ
, END_CIRC_REASON_OR_CONN_CLOSED
);
440 log_debug(LD_CIRC
, "Found circ, sending create cell.");
441 /* circuit_deliver_create_cell will set n_circ_id and add us to
442 * orconn_circuid_circuit_map, so we don't need to call
443 * set_circid_orconn here. */
444 circ
->n_conn
= or_conn
;
445 if (CIRCUIT_IS_ORIGIN(circ
)) {
447 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
449 "send_next_onion_skin failed; circuit marked for closing.");
450 circuit_mark_for_close(circ
, -err_reason
);
452 /* XXX could this be bad, eg if next_onion_skin failed because conn
456 /* pull the create cell out of circ->onionskin, and send it */
457 tor_assert(circ
->onionskin
);
458 if (circuit_deliver_create_cell(circ
,CELL_CREATE
,circ
->onionskin
)<0) {
459 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
462 tor_free(circ
->onionskin
);
463 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
467 smartlist_free(pending_circs
);
470 /** Find a new circid that isn't currently in use on the circ->n_conn
472 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
473 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
475 * Return -1 if we failed to find a suitable circid, else return 0.
478 circuit_deliver_create_cell(circuit_t
*circ
, uint8_t cell_type
,
485 tor_assert(circ
->n_conn
);
487 tor_assert(cell_type
== CELL_CREATE
|| cell_type
== CELL_CREATE_FAST
);
489 id
= get_unique_circ_id_by_conn(circ
->n_conn
);
491 log_warn(LD_CIRC
,"failed to get unique circID.");
494 log_debug(LD_CIRC
,"Chosen circID %u.", id
);
495 circuit_set_n_circid_orconn(circ
, id
, circ
->n_conn
);
497 memset(&cell
, 0, sizeof(cell_t
));
498 cell
.command
= cell_type
;
499 cell
.circ_id
= circ
->n_circ_id
;
501 memcpy(cell
.payload
, payload
, ONIONSKIN_CHALLENGE_LEN
);
502 append_cell_to_circuit_queue(circ
, circ
->n_conn
, &cell
, CELL_DIRECTION_OUT
);
504 /* mark it so it gets better rate limiting treatment. */
505 circ
->n_conn
->client_used
= time(NULL
);
510 /** We've decided to start our reachability testing. If all
511 * is set, log this to the user. Return 1 if we did, or 0 if
512 * we chose not to log anything. */
514 inform_testing_reachability(void)
517 routerinfo_t
*me
= router_get_my_routerinfo();
521 tor_snprintf(dirbuf
, sizeof(dirbuf
), " and DirPort %s:%d",
522 me
->address
, me
->dir_port
);
523 log(LOG_NOTICE
, LD_OR
, "Now checking whether ORPort %s:%d%s %s reachable... "
524 "(this may take up to %d minutes -- look for log "
525 "messages indicating success)",
526 me
->address
, me
->or_port
,
527 me
->dir_port
? dirbuf
: "",
528 me
->dir_port
? "are" : "is",
529 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
/60);
533 /** Return true iff we should send a create_fast cell to build a circuit
534 * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
535 * information on the router, so assume true.) */
537 should_use_create_fast_for_router(routerinfo_t
*router
,
538 origin_circuit_t
*circ
)
540 or_options_t
*options
= get_options();
542 if (!options
->FastFirstHopPK
) /* create_fast is disabled */
544 if (router
&& router
->platform
&&
545 !tor_version_as_new_as(router
->platform
, "0.1.0.6-rc")) {
546 /* known not to work */
549 if (server_mode(options
) && circ
->cpath
->extend_info
->onion_key
) {
550 /* We're a server, and we know an onion key. We can choose.
551 * Prefer to blend in. */
558 /** This is the backbone function for building circuits.
560 * If circ's first hop is closed, then we need to build a create
561 * cell and send it forward.
563 * Otherwise, we need to build a relay extend cell and send it
566 * Return -reason if we want to tear down circ, else return 0.
569 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
572 routerinfo_t
*router
;
573 char payload
[2+4+DIGEST_LEN
+ONIONSKIN_CHALLENGE_LEN
];
579 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
582 log_debug(LD_CIRC
,"First skin; sending create cell.");
584 router
= router_get_by_digest(circ
->_base
.n_conn
->identity_digest
);
585 fast
= should_use_create_fast_for_router(router
, circ
);
586 if (!fast
&& !circ
->cpath
->extend_info
->onion_key
) {
588 "Can't send create_fast, but have no onion key. Failing.");
589 return - END_CIRC_REASON_INTERNAL
;
592 /* We are an OR, or we are connecting to an old Tor: we should
593 * send an old slow create cell.
595 cell_type
= CELL_CREATE
;
596 if (onion_skin_create(circ
->cpath
->extend_info
->onion_key
,
597 &(circ
->cpath
->dh_handshake_state
),
599 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
600 return - END_CIRC_REASON_INTERNAL
;
603 /* We are not an OR, and we're building the first hop of a circuit to a
604 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
605 * and a DH operation. */
606 cell_type
= CELL_CREATE_FAST
;
607 memset(payload
, 0, sizeof(payload
));
608 crypto_rand(circ
->cpath
->fast_handshake_state
,
609 sizeof(circ
->cpath
->fast_handshake_state
));
610 memcpy(payload
, circ
->cpath
->fast_handshake_state
,
611 sizeof(circ
->cpath
->fast_handshake_state
));
614 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), cell_type
, payload
) < 0)
615 return - END_CIRC_REASON_RESOURCELIMIT
;
617 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
618 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
619 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
620 fast
? "CREATE_FAST" : "CREATE",
621 router
? router
->nickname
: "<unnamed>");
623 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
624 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_BUILDING
);
625 log_debug(LD_CIRC
,"starting to send subsequent skin.");
626 hop
= onion_next_hop_in_cpath(circ
->cpath
);
628 /* done building the circuit. whew. */
629 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
630 log_info(LD_CIRC
,"circuit built!");
631 circuit_reset_failure_count(0);
632 if (!has_completed_circuit
&& !circ
->build_state
->onehop_tunnel
) {
633 or_options_t
*options
= get_options();
634 has_completed_circuit
=1;
635 /* FFFF Log a count of known routers here */
636 log(LOG_NOTICE
, LD_GENERAL
,
637 "Tor has successfully opened a circuit. "
638 "Looks like client functionality is working.");
639 control_event_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
640 if (server_mode(options
) && !check_whether_orport_reachable()) {
641 inform_testing_reachability();
642 consider_testing_reachability(1, 1);
645 circuit_rep_hist_note_result(circ
);
646 circuit_has_opened(circ
); /* do other actions as necessary */
650 set_uint32(payload
, htonl(hop
->extend_info
->addr
));
651 set_uint16(payload
+4, htons(hop
->extend_info
->port
));
653 onionskin
= payload
+2+4;
654 memcpy(payload
+2+4+ONIONSKIN_CHALLENGE_LEN
,
655 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
656 payload_len
= 2+4+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
;
658 if (onion_skin_create(hop
->extend_info
->onion_key
,
659 &(hop
->dh_handshake_state
), onionskin
) < 0) {
660 log_warn(LD_CIRC
,"onion_skin_create failed.");
661 return - END_CIRC_REASON_INTERNAL
;
664 log_info(LD_CIRC
,"Sending extend relay cell.");
665 /* send it to hop->prev, because it will transfer
666 * it to a create cell and then send to hop */
667 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
668 RELAY_COMMAND_EXTEND
,
669 payload
, payload_len
, hop
->prev
) < 0)
670 return 0; /* circuit is closed */
672 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
677 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
678 * something has also gone wrong with our network: notify the user,
679 * and abandon all not-yet-used circuits. */
681 circuit_note_clock_jumped(int seconds_elapsed
)
683 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
684 log(severity
, LD_GENERAL
, "Your clock just jumped %d seconds %s; "
685 "assuming established circuits no longer work.",
686 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
,
687 seconds_elapsed
>=0 ? "forward" : "backward");
688 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%d",
690 has_completed_circuit
=0; /* so it'll log when it works again */
691 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
693 circuit_mark_all_unused_circs();
694 circuit_expire_all_dirty_circs();
697 /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
698 * sure we're connected to the next hop, and pass it the onion skin using
699 * a create cell. Return -1 if we want to warn and tear down the circuit,
703 circuit_extend(cell_t
*cell
, circuit_t
*circ
)
705 or_connection_t
*n_conn
;
708 char *id_digest
=NULL
;
711 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
712 "n_conn already set. Bug/attack. Closing.");
716 if (!server_mode(get_options())) {
717 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
718 "Got an extend cell, but running as a client. Closing.");
722 relay_header_unpack(&rh
, cell
->payload
);
724 if (rh
.length
< 4+2+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
) {
725 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
726 "Wrong length %d on extend cell. Closing circuit.",
731 circ
->n_addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
732 circ
->n_port
= ntohs(get_uint16(cell
->payload
+RELAY_HEADER_SIZE
+4));
734 onionskin
= cell
->payload
+RELAY_HEADER_SIZE
+4+2;
735 id_digest
= cell
->payload
+RELAY_HEADER_SIZE
+4+2+ONIONSKIN_CHALLENGE_LEN
;
736 n_conn
= connection_or_get_by_identity_digest(id_digest
);
738 /* If we don't have an open conn, or the conn we have is obsolete
739 * (i.e. old or broken) and the other side will let us make a second
740 * connection without dropping it immediately... */
741 if (!n_conn
|| n_conn
->_base
.state
!= OR_CONN_STATE_OPEN
||
742 (n_conn
->_base
.or_is_obsolete
&&
743 router_digest_version_as_new_as(id_digest
,"0.1.1.9-alpha-cvs"))) {
745 char tmpbuf
[INET_NTOA_BUF_LEN
];
746 in
.s_addr
= htonl(circ
->n_addr
);
747 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
748 log_info(LD_CIRC
|LD_OR
,"Next router (%s:%d) not connected. Connecting.",
749 tmpbuf
, circ
->n_port
);
751 circ
->onionskin
= tor_malloc(ONIONSKIN_CHALLENGE_LEN
);
752 memcpy(circ
->onionskin
, onionskin
, ONIONSKIN_CHALLENGE_LEN
);
753 circuit_set_state(circ
, CIRCUIT_STATE_OR_WAIT
);
755 /* imprint the circuit with its future n_conn->id */
756 memcpy(circ
->n_conn_id_digest
, id_digest
, DIGEST_LEN
);
758 if (n_conn
&& !n_conn
->_base
.or_is_obsolete
) {
759 circ
->n_addr
= n_conn
->_base
.addr
;
760 circ
->n_port
= n_conn
->_base
.port
;
762 /* we should try to open a connection */
763 n_conn
= connection_or_connect(circ
->n_addr
, circ
->n_port
, id_digest
);
765 log_info(LD_CIRC
,"Launching n_conn failed. Closing circuit.");
766 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
769 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
771 /* return success. The onion/circuit/etc will be taken care of
772 * automatically (may already have been) whenever n_conn reaches
773 * OR_CONN_STATE_OPEN.
778 /* these may be different if the router connected to us from elsewhere */
779 circ
->n_addr
= n_conn
->_base
.addr
;
780 circ
->n_port
= n_conn
->_base
.port
;
782 circ
->n_conn
= n_conn
;
783 memcpy(circ
->n_conn_id_digest
, n_conn
->identity_digest
, DIGEST_LEN
);
784 log_debug(LD_CIRC
,"n_conn is %s:%u",
785 n_conn
->_base
.address
,n_conn
->_base
.port
);
787 if (circuit_deliver_create_cell(circ
, CELL_CREATE
, onionskin
) < 0)
792 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
793 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
795 * - 20 to initialize f_digest
796 * - 20 to initialize b_digest
797 * - 16 to key f_crypto
798 * - 16 to key b_crypto
800 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
803 circuit_init_cpath_crypto(crypt_path_t
*cpath
, const char *key_data
,
806 crypto_digest_env_t
*tmp_digest
;
807 crypto_cipher_env_t
*tmp_crypto
;
810 tor_assert(key_data
);
811 tor_assert(!(cpath
->f_crypto
|| cpath
->b_crypto
||
812 cpath
->f_digest
|| cpath
->b_digest
));
814 cpath
->f_digest
= crypto_new_digest_env();
815 crypto_digest_add_bytes(cpath
->f_digest
, key_data
, DIGEST_LEN
);
816 cpath
->b_digest
= crypto_new_digest_env();
817 crypto_digest_add_bytes(cpath
->b_digest
, key_data
+DIGEST_LEN
, DIGEST_LEN
);
819 if (!(cpath
->f_crypto
=
820 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
),1))) {
821 log_warn(LD_BUG
,"Forward cipher initialization failed.");
824 if (!(cpath
->b_crypto
=
825 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
)+CIPHER_KEY_LEN
,0))) {
826 log_warn(LD_BUG
,"Backward cipher initialization failed.");
831 tmp_digest
= cpath
->f_digest
;
832 cpath
->f_digest
= cpath
->b_digest
;
833 cpath
->b_digest
= tmp_digest
;
834 tmp_crypto
= cpath
->f_crypto
;
835 cpath
->f_crypto
= cpath
->b_crypto
;
836 cpath
->b_crypto
= tmp_crypto
;
842 /** A created or extended cell came back to us on the circuit, and it included
843 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
844 * contains (the second DH key, plus KH). If <b>reply_type</b> is
845 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
847 * Calculate the appropriate keys and digests, make sure KH is
848 * correct, and initialize this hop of the cpath.
850 * Return - reason if we want to mark circ for close, else return 0.
853 circuit_finish_handshake(origin_circuit_t
*circ
, uint8_t reply_type
,
856 char keys
[CPATH_KEY_MATERIAL_LEN
];
859 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
)
862 hop
= onion_next_hop_in_cpath(circ
->cpath
);
863 if (!hop
) { /* got an extended when we're all done? */
864 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
865 return - END_CIRC_REASON_TORPROTOCOL
;
868 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
870 if (reply_type
== CELL_CREATED
&& hop
->dh_handshake_state
) {
871 if (onion_skin_client_handshake(hop
->dh_handshake_state
, reply
, keys
,
872 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
873 log_warn(LD_CIRC
,"onion_skin_client_handshake failed.");
874 return -END_CIRC_REASON_TORPROTOCOL
;
876 /* Remember hash of g^xy */
877 memcpy(hop
->handshake_digest
, reply
+DH_KEY_LEN
, DIGEST_LEN
);
878 } else if (reply_type
== CELL_CREATED_FAST
&& !hop
->dh_handshake_state
) {
879 if (fast_client_handshake(hop
->fast_handshake_state
, reply
, keys
,
880 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
881 log_warn(LD_CIRC
,"fast_client_handshake failed.");
882 return -END_CIRC_REASON_TORPROTOCOL
;
884 memcpy(hop
->handshake_digest
, reply
+DIGEST_LEN
, DIGEST_LEN
);
886 log_warn(LD_PROTOCOL
,"CREATED cell type did not match CREATE cell type.");
887 return -END_CIRC_REASON_TORPROTOCOL
;
890 if (hop
->dh_handshake_state
) {
891 crypto_dh_free(hop
->dh_handshake_state
); /* don't need it anymore */
892 hop
->dh_handshake_state
= NULL
;
894 memset(hop
->fast_handshake_state
, 0, sizeof(hop
->fast_handshake_state
));
896 if (circuit_init_cpath_crypto(hop
, keys
, 0)<0) {
897 return -END_CIRC_REASON_TORPROTOCOL
;
900 hop
->state
= CPATH_STATE_OPEN
;
901 log_info(LD_CIRC
,"Finished building %scircuit hop:",
902 (reply_type
== CELL_CREATED_FAST
) ? "fast " : "");
903 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
904 control_event_circuit_status(circ
, CIRC_EVENT_EXTENDED
, 0);
909 /** We received a relay truncated cell on circ.
911 * Since we don't ask for truncates currently, getting a truncated
912 * means that a connection broke or an extend failed. For now,
913 * just give up: for circ to close, and return 0.
916 circuit_truncated(origin_circuit_t
*circ
, crypt_path_t
*layer
)
918 // crypt_path_t *victim;
919 // connection_t *stream;
924 /* XXX Since we don't ask for truncates currently, getting a truncated
925 * means that a connection broke or an extend failed. For now,
928 circuit_mark_for_close(TO_CIRCUIT(circ
),
929 END_CIRC_REASON_FLAG_REMOTE
|END_CIRC_REASON_OR_CONN_CLOSED
);
933 while (layer
->next
!= circ
->cpath
) {
934 /* we need to clear out layer->next */
935 victim
= layer
->next
;
936 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
938 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
939 if (stream
->cpath_layer
== victim
) {
940 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
942 /* no need to send 'end' relay cells,
943 * because the other side's already dead
945 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
949 layer
->next
= victim
->next
;
950 circuit_free_cpath_node(victim
);
953 log_info(LD_CIRC
, "finished");
958 /** Given a response payload and keys, initialize, then send a created
962 onionskin_answer(or_circuit_t
*circ
, uint8_t cell_type
, const char *payload
,
966 crypt_path_t
*tmp_cpath
;
968 tmp_cpath
= tor_malloc_zero(sizeof(crypt_path_t
));
969 tmp_cpath
->magic
= CRYPT_PATH_MAGIC
;
971 memset(&cell
, 0, sizeof(cell_t
));
972 cell
.command
= cell_type
;
973 cell
.circ_id
= circ
->p_circ_id
;
975 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
977 memcpy(cell
.payload
, payload
,
978 cell_type
== CELL_CREATED
? ONIONSKIN_REPLY_LEN
: DIGEST_LEN
*2);
980 log_debug(LD_CIRC
,"init digest forward 0x%.8x, backward 0x%.8x.",
981 (unsigned int)*(uint32_t*)(keys
),
982 (unsigned int)*(uint32_t*)(keys
+20));
983 if (circuit_init_cpath_crypto(tmp_cpath
, keys
, 0)<0) {
984 log_warn(LD_BUG
,"Circuit initialization failed");
988 circ
->n_digest
= tmp_cpath
->f_digest
;
989 circ
->n_crypto
= tmp_cpath
->f_crypto
;
990 circ
->p_digest
= tmp_cpath
->b_digest
;
991 circ
->p_crypto
= tmp_cpath
->b_crypto
;
992 tmp_cpath
->magic
= 0;
995 if (cell_type
== CELL_CREATED
)
996 memcpy(circ
->handshake_digest
, cell
.payload
+DH_KEY_LEN
, DIGEST_LEN
);
998 memcpy(circ
->handshake_digest
, cell
.payload
+DIGEST_LEN
, DIGEST_LEN
);
1000 circ
->is_first_hop
= (cell_type
== CELL_CREATED_FAST
);
1002 append_cell_to_circuit_queue(TO_CIRCUIT(circ
),
1003 circ
->p_conn
, &cell
, CELL_DIRECTION_IN
);
1004 log_debug(LD_CIRC
,"Finished sending 'created' cell.");
1006 if (!is_local_IP(circ
->p_conn
->_base
.addr
) &&
1007 !connection_or_nonopen_was_started_here(circ
->p_conn
)) {
1008 /* record that we could process create cells from a non-local conn
1009 * that we didn't initiate; presumably this means that create cells
1010 * can reach us too. */
1011 router_orport_found_reachable();
1017 /** Choose a length for a circuit of purpose <b>purpose</b>.
1018 * Default length is 3 + the number of endpoints that would give something
1019 * away. If the routerlist <b>routers</b> doesn't have enough routers
1020 * to handle the desired path length, return as large a path length as
1021 * is feasible, except if it's less than 2, in which case return -1.
1024 new_route_len(uint8_t purpose
, extend_info_t
*exit
,
1025 smartlist_t
*routers
)
1027 int num_acceptable_routers
;
1030 tor_assert(routers
);
1037 purpose
!= CIRCUIT_PURPOSE_TESTING
&&
1038 purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
1041 log_debug(LD_CIRC
,"Chosen route length %d (%d routers available).",
1042 routelen
, smartlist_len(routers
));
1044 num_acceptable_routers
= count_acceptable_routers(routers
);
1046 if (num_acceptable_routers
< 2) {
1048 "Not enough acceptable routers (%d). Discarding this circuit.",
1049 num_acceptable_routers
);
1053 if (num_acceptable_routers
< routelen
) {
1054 log_info(LD_CIRC
,"Not enough routers: cutting routelen from %d to %d.",
1055 routelen
, num_acceptable_routers
);
1056 routelen
= num_acceptable_routers
;
1062 /** Fetch the list of predicted ports, dup it into a smartlist of
1063 * uint16_t's, remove the ones that are already handled by an
1064 * existing circuit, and return it.
1066 static smartlist_t
*
1067 circuit_get_unhandled_ports(time_t now
)
1069 smartlist_t
*source
= rep_hist_get_predicted_ports(now
);
1070 smartlist_t
*dest
= smartlist_create();
1074 for (i
= 0; i
< smartlist_len(source
); ++i
) {
1075 tmp
= tor_malloc(sizeof(uint16_t));
1076 memcpy(tmp
, smartlist_get(source
, i
), sizeof(uint16_t));
1077 smartlist_add(dest
, tmp
);
1080 circuit_remove_handled_ports(dest
);
1084 /** Return 1 if we already have circuits present or on the way for
1085 * all anticipated ports. Return 0 if we should make more.
1087 * If we're returning 0, set need_uptime and need_capacity to
1088 * indicate any requirements that the unhandled ports have.
1091 circuit_all_predicted_ports_handled(time_t now
, int *need_uptime
,
1096 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
1097 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
1098 tor_assert(need_uptime
);
1099 tor_assert(need_capacity
);
1100 enough
= (smartlist_len(sl
) == 0);
1101 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
1102 port
= smartlist_get(sl
, i
);
1103 if (smartlist_string_num_isin(LongLivedServices
, *port
))
1111 /** Return 1 if <b>router</b> can handle one or more of the ports in
1112 * <b>needed_ports</b>, else return 0.
1115 router_handles_some_port(routerinfo_t
*router
, smartlist_t
*needed_ports
)
1120 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
1121 addr_policy_result_t r
;
1122 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
1124 r
= compare_addr_to_addr_policy(0, port
, router
->exit_policy
);
1125 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
1131 /** Return true iff <b>conn</b> needs another general circuit to be
1134 ap_stream_wants_exit_attention(connection_t
*conn
)
1136 if (conn
->type
== CONN_TYPE_AP
&&
1137 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
1138 !conn
->marked_for_close
&&
1139 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
1140 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn
), 0,
1141 MIN_CIRCUITS_HANDLING_STREAM
))
1146 /** Return a pointer to a suitable router to be the exit node for the
1147 * general-purpose circuit we're about to build.
1149 * Look through the connection array, and choose a router that maximizes
1150 * the number of pending streams that can exit from this router.
1152 * Return NULL if we can't find any suitable routers.
1154 static routerinfo_t
*
1155 choose_good_exit_server_general(routerlist_t
*dir
, int need_uptime
,
1160 int n_pending_connections
= 0;
1161 smartlist_t
*connections
;
1162 int best_support
= -1;
1163 int n_best_support
=0;
1164 smartlist_t
*sl
, *preferredexits
, *excludedexits
;
1165 routerinfo_t
*router
;
1166 or_options_t
*options
= get_options();
1168 connections
= get_connection_array();
1170 /* Count how many connections are waiting for a circuit to be built.
1171 * We use this for log messages now, but in the future we may depend on it.
1173 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1175 if (ap_stream_wants_exit_attention(conn
))
1176 ++n_pending_connections
;
1178 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1179 // n_pending_connections);
1180 /* Now we count, for each of the routers in the directory, how many
1181 * of the pending connections could possibly exit from that
1182 * router (n_supported[i]). (We can't be sure about cases where we
1183 * don't know the IP address of the pending connection.)
1185 n_supported
= tor_malloc(sizeof(int)*smartlist_len(dir
->routers
));
1186 for (i
= 0; i
< smartlist_len(dir
->routers
); ++i
) {/* iterate over routers */
1187 router
= smartlist_get(dir
->routers
, i
);
1188 if (router_is_me(router
)) {
1189 n_supported
[i
] = -1;
1190 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1191 /* XXX there's probably a reverse predecessor attack here, but
1192 * it's slow. should we take this out? -RD
1196 if (!router
->is_running
|| router
->is_bad_exit
) {
1197 n_supported
[i
] = -1;
1198 continue; /* skip routers that are known to be down or bad exits */
1200 if (router_is_unreliable(router
, need_uptime
, need_capacity
, 0)) {
1201 n_supported
[i
] = -1;
1202 continue; /* skip routers that are not suitable */
1204 if (!(router
->is_valid
|| options
->_AllowInvalid
& ALLOW_INVALID_EXIT
)) {
1205 /* if it's invalid and we don't want it */
1206 n_supported
[i
] = -1;
1207 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1208 // router->nickname, i);
1209 continue; /* skip invalid routers */
1211 if (router_exit_policy_rejects_all(router
)) {
1212 n_supported
[i
] = -1;
1213 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1214 // router->nickname, i);
1215 continue; /* skip routers that reject all */
1218 /* iterate over connections */
1219 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1221 if (!ap_stream_wants_exit_attention(conn
))
1222 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1223 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn
), router
)) {
1225 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1226 // router->nickname, i, n_supported[i]);
1228 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1229 // router->nickname, i);
1231 }); /* End looping over connections. */
1232 if (n_supported
[i
] > best_support
) {
1233 /* If this router is better than previous ones, remember its index
1234 * and goodness, and start counting how many routers are this good. */
1235 best_support
= n_supported
[i
]; n_best_support
=1;
1236 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1237 // router->nickname);
1238 } else if (n_supported
[i
] == best_support
) {
1239 /* If this router is _as good_ as the best one, just increment the
1240 * count of equally good routers.*/
1245 "Found %d servers that might support %d/%d pending connections.",
1246 n_best_support
, best_support
>= 0 ? best_support
: 0,
1247 n_pending_connections
);
1249 preferredexits
= smartlist_create();
1250 add_nickname_list_to_smartlist(preferredexits
,options
->ExitNodes
,1);
1252 excludedexits
= smartlist_create();
1253 add_nickname_list_to_smartlist(excludedexits
,options
->ExcludeNodes
,0);
1255 sl
= smartlist_create();
1257 /* If any routers definitely support any pending connections, choose one
1259 if (best_support
> 0) {
1260 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++)
1261 if (n_supported
[i
] == best_support
)
1262 smartlist_add(sl
, smartlist_get(dir
->routers
, i
));
1264 smartlist_subtract(sl
,excludedexits
);
1265 if (options
->StrictExitNodes
|| smartlist_overlap(sl
,preferredexits
))
1266 smartlist_intersect(sl
,preferredexits
);
1267 router
= routerlist_sl_choose_by_bandwidth(sl
, WEIGHT_FOR_EXIT
);
1269 /* Either there are no pending connections, or no routers even seem to
1270 * possibly support any of them. Choose a router at random that satisfies
1271 * at least one predicted exit port. */
1274 smartlist_t
*needed_ports
;
1276 if (best_support
== -1) {
1277 if (need_uptime
|| need_capacity
) {
1279 "We couldn't find any live%s%s routers; falling back "
1280 "to list of all routers.",
1281 need_capacity
?", fast":"",
1282 need_uptime
?", stable":"");
1283 smartlist_free(preferredexits
);
1284 smartlist_free(excludedexits
);
1286 tor_free(n_supported
);
1287 return choose_good_exit_server_general(dir
, 0, 0);
1289 log_notice(LD_CIRC
, "All routers are down or won't exit -- choosing a "
1290 "doomed exit at random.");
1292 needed_ports
= circuit_get_unhandled_ports(time(NULL
));
1293 for (try = 0; try < 2; try++) {
1294 /* try once to pick only from routers that satisfy a needed port,
1295 * then if there are none, pick from any that support exiting. */
1296 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++) {
1297 router
= smartlist_get(dir
->routers
, i
);
1298 if (n_supported
[i
] != -1 &&
1299 (try || router_handles_some_port(router
, needed_ports
))) {
1300 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1301 // try, router->nickname);
1302 smartlist_add(sl
, router
);
1306 smartlist_subtract(sl
,excludedexits
);
1307 if (options
->StrictExitNodes
|| smartlist_overlap(sl
,preferredexits
))
1308 smartlist_intersect(sl
,preferredexits
);
1309 /* XXX sometimes the above results in null, when the requested
1310 * exit node is down. we should pick it anyway. */
1311 router
= routerlist_sl_choose_by_bandwidth(sl
, WEIGHT_FOR_EXIT
);
1315 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
1316 smartlist_free(needed_ports
);
1319 smartlist_free(preferredexits
);
1320 smartlist_free(excludedexits
);
1322 tor_free(n_supported
);
1324 log_info(LD_CIRC
, "Chose exit server '%s'", router
->nickname
);
1327 if (options
->StrictExitNodes
) {
1329 "No specified exit routers seem to be running, and "
1330 "StrictExitNodes is set: can't choose an exit.");
1335 /** Return a pointer to a suitable router to be the exit node for the
1336 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1337 * if no router is suitable).
1339 * For general-purpose circuits, pass it off to
1340 * choose_good_exit_server_general()
1342 * For client-side rendezvous circuits, choose a random node, weighted
1343 * toward the preferences in 'options'.
1345 static routerinfo_t
*
1346 choose_good_exit_server(uint8_t purpose
, routerlist_t
*dir
,
1347 int need_uptime
, int need_capacity
, int is_internal
)
1349 or_options_t
*options
= get_options();
1351 case CIRCUIT_PURPOSE_C_GENERAL
:
1352 if (is_internal
) /* pick it like a middle hop */
1353 return router_choose_random_node(NULL
, get_options()->ExcludeNodes
,
1354 NULL
, need_uptime
, need_capacity
, 0,
1355 get_options()->_AllowInvalid
& ALLOW_INVALID_MIDDLE
, 0, 0);
1357 return choose_good_exit_server_general(dir
,need_uptime
,need_capacity
);
1358 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1359 return router_choose_random_node(
1360 options
->RendNodes
, options
->RendExcludeNodes
,
1361 NULL
, need_uptime
, need_capacity
, 0,
1362 options
->_AllowInvalid
& ALLOW_INVALID_RENDEZVOUS
, 0, 0);
1364 log_warn(LD_BUG
,"Unhandled purpose %d", purpose
);
1365 tor_fragile_assert();
1369 /** Decide a suitable length for circ's cpath, and pick an exit
1370 * router (or use <b>exit</b> if provided). Store these in the
1371 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1373 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1375 cpath_build_state_t
*state
= circ
->build_state
;
1376 routerlist_t
*rl
= router_get_routerlist();
1378 if (state
->onehop_tunnel
) {
1379 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel.");
1380 state
->desired_path_len
= 1;
1382 int r
= new_route_len(circ
->_base
.purpose
, exit
, rl
->routers
);
1383 if (r
< 1) /* must be at least 1 */
1385 state
->desired_path_len
= r
;
1388 if (exit
) { /* the circuit-builder pre-requested one */
1389 log_info(LD_CIRC
,"Using requested exit node '%s'", exit
->nickname
);
1390 exit
= extend_info_dup(exit
);
1391 } else { /* we have to decide one */
1392 routerinfo_t
*router
=
1393 choose_good_exit_server(circ
->_base
.purpose
, rl
, state
->need_uptime
,
1394 state
->need_capacity
, state
->is_internal
);
1396 log_warn(LD_CIRC
,"failed to choose an exit server");
1399 exit
= extend_info_from_router(router
);
1401 state
->chosen_exit
= exit
;
1405 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1406 * hop to the cpath reflecting this. Don't send the next extend cell --
1407 * the caller will do this if it wants to.
1410 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1412 cpath_build_state_t
*state
;
1416 state
= circ
->build_state
;
1418 if (state
->chosen_exit
)
1419 extend_info_free(state
->chosen_exit
);
1420 state
->chosen_exit
= extend_info_dup(exit
);
1422 ++circ
->build_state
->desired_path_len
;
1423 onion_append_hop(&circ
->cpath
, exit
);
1427 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1428 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1429 * send the next extend cell to begin connecting to that hop.
1432 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1435 circuit_append_new_exit(circ
, exit
);
1436 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
1437 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
1438 log_warn(LD_CIRC
, "Couldn't extend circuit to new point '%s'.",
1440 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
1446 /** Return the number of routers in <b>routers</b> that are currently up
1447 * and available for building circuits through.
1450 count_acceptable_routers(smartlist_t
*routers
)
1456 n
= smartlist_len(routers
);
1458 r
= smartlist_get(routers
, i
);
1459 // log_debug(LD_CIRC,
1460 // "Contemplating whether router %d (%s) is a new option.",
1462 if (r
->is_running
== 0) {
1463 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1466 if (r
->is_valid
== 0) {
1467 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1469 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1470 * allows this node in some places, then we're getting an inaccurate
1471 * count. For now, be conservative and don't count it. But later we
1472 * should try to be smarter. */
1475 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1477 ; /* C requires an explicit statement after the label */
1483 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1484 * This function is used to extend cpath by another hop.
1487 onion_append_to_cpath(crypt_path_t
**head_ptr
, crypt_path_t
*new_hop
)
1490 new_hop
->next
= (*head_ptr
);
1491 new_hop
->prev
= (*head_ptr
)->prev
;
1492 (*head_ptr
)->prev
->next
= new_hop
;
1493 (*head_ptr
)->prev
= new_hop
;
1495 *head_ptr
= new_hop
;
1496 new_hop
->prev
= new_hop
->next
= new_hop
;
1500 /** Pick a random server digest that's running a Tor version that
1501 * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
1502 * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
1503 * probably already connected to them.
1505 * We only return one, so this doesn't become stupid when the
1506 * whole network has upgraded. */
1508 compute_preferred_testing_list(const char *answer
)
1510 smartlist_t
*choices
;
1511 routerlist_t
*rl
= router_get_routerlist();
1512 routerinfo_t
*router
;
1515 if (answer
) /* they have one in mind -- easy */
1516 return tor_strdup(answer
);
1518 choices
= smartlist_create();
1519 /* now count up our choices */
1520 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
1521 if (r
->is_running
&& r
->is_valid
&&
1522 ((tor_version_as_new_as(r
->platform
,"0.1.1.21-cvs") &&
1523 !tor_version_as_new_as(r
->platform
,"0.1.2.0-alpha-cvs")) ||
1524 tor_version_as_new_as(r
->platform
,"0.1.2.1-alpha")) &&
1525 !is_local_IP(r
->addr
) &&
1526 !router_get_trusteddirserver_by_digest(r
->cache_info
.identity_digest
))
1527 smartlist_add(choices
, r
));
1528 router
= smartlist_choose(choices
);
1529 smartlist_free(choices
);
1531 log_info(LD_CIRC
, "Looking for middle server that doesn't have the "
1532 "reachability bug, but didn't find one. Oh well.");
1535 log_info(LD_CIRC
, "Looking for middle server that doesn't have the "
1536 "reachability bug, and chose '%s'. Great.", router
->nickname
);
1537 s
= tor_malloc(HEX_DIGEST_LEN
+2);
1539 base16_encode(s
+1, HEX_DIGEST_LEN
+1,
1540 router
->cache_info
.identity_digest
, DIGEST_LEN
);
1544 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1545 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1546 * to length <b>cur_len</b> to decide a suitable middle hop for a
1547 * circuit. In particular, make sure we don't pick the exit node or its
1548 * family, and make sure we don't duplicate any previous nodes or their
1550 static routerinfo_t
*
1551 choose_good_middle_server(uint8_t purpose
,
1552 cpath_build_state_t
*state
,
1557 routerinfo_t
*r
, *choice
;
1558 crypt_path_t
*cpath
;
1559 smartlist_t
*excluded
;
1560 or_options_t
*options
= get_options();
1561 char *preferred
= NULL
;
1562 tor_assert(_CIRCUIT_PURPOSE_MIN
<= purpose
&&
1563 purpose
<= _CIRCUIT_PURPOSE_MAX
);
1565 log_debug(LD_CIRC
, "Contemplating intermediate hop: random choice.");
1566 excluded
= smartlist_create();
1567 if ((r
= build_state_get_exit_router(state
))) {
1568 smartlist_add(excluded
, r
);
1569 routerlist_add_family(excluded
, r
);
1571 if ((r
= routerlist_find_my_routerinfo())) {
1572 smartlist_add(excluded
, r
);
1573 routerlist_add_family(excluded
, r
);
1575 for (i
= 0, cpath
= head
; i
< cur_len
; ++i
, cpath
=cpath
->next
) {
1576 if ((r
= router_get_by_digest(cpath
->extend_info
->identity_digest
))) {
1577 smartlist_add(excluded
, r
);
1578 routerlist_add_family(excluded
, r
);
1581 if (purpose
== CIRCUIT_PURPOSE_TESTING
)
1582 preferred
= compute_preferred_testing_list(options
->TestVia
);
1583 choice
= router_choose_random_node(preferred
,
1584 options
->ExcludeNodes
, excluded
,
1585 state
->need_uptime
, state
->need_capacity
, 0,
1586 options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
, 0, 0);
1587 tor_free(preferred
);
1588 smartlist_free(excluded
);
1592 /** Pick a good entry server for the circuit to be built according to
1593 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1594 * router (if we're an OR), and respect firewall settings; if we're
1595 * configured to use entry guards, return one.
1597 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1598 * guard, not for any particular circuit.
1600 static routerinfo_t
*
1601 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
)
1603 routerinfo_t
*r
, *choice
;
1604 smartlist_t
*excluded
;
1605 or_options_t
*options
= get_options();
1606 (void)purpose
; /* not used yet. */
1608 if (state
&& options
->UseEntryGuards
) {
1609 return choose_random_entry(state
);
1612 excluded
= smartlist_create();
1614 if (state
&& (r
= build_state_get_exit_router(state
))) {
1615 smartlist_add(excluded
, r
);
1616 routerlist_add_family(excluded
, r
);
1618 if ((r
= routerlist_find_my_routerinfo())) {
1619 smartlist_add(excluded
, r
);
1620 routerlist_add_family(excluded
, r
);
1622 if (firewall_is_fascist_or()) {
1623 /* exclude all ORs that listen on the wrong port */
1624 routerlist_t
*rl
= router_get_routerlist();
1627 for (i
=0; i
< smartlist_len(rl
->routers
); i
++) {
1628 r
= smartlist_get(rl
->routers
, i
);
1629 if (!fascist_firewall_allows_address_or(r
->addr
,r
->or_port
))
1630 smartlist_add(excluded
, r
);
1633 /* and exclude current entry guards, if applicable */
1634 if (options
->UseEntryGuards
&& entry_guards
) {
1635 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1637 if ((r
= router_get_by_digest(entry
->identity
)))
1638 smartlist_add(excluded
, r
);
1642 choice
= router_choose_random_node(
1643 NULL
, options
->ExcludeNodes
,
1644 excluded
, state
? state
->need_uptime
: 0,
1645 state
? state
->need_capacity
: 0,
1647 options
->_AllowInvalid
& ALLOW_INVALID_ENTRY
, 0, 0);
1648 smartlist_free(excluded
);
1652 /** Return the first non-open hop in cpath, or return NULL if all
1654 static crypt_path_t
*
1655 onion_next_hop_in_cpath(crypt_path_t
*cpath
)
1657 crypt_path_t
*hop
= cpath
;
1659 if (hop
->state
!= CPATH_STATE_OPEN
)
1662 } while (hop
!= cpath
);
1666 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1667 * based on <b>state</b>. Append the hop info to head_ptr.
1670 onion_extend_cpath(origin_circuit_t
*circ
)
1672 uint8_t purpose
= circ
->_base
.purpose
;
1673 cpath_build_state_t
*state
= circ
->build_state
;
1674 int cur_len
= circuit_get_cpath_len(circ
);
1675 extend_info_t
*info
= NULL
;
1677 if (cur_len
>= state
->desired_path_len
) {
1678 log_debug(LD_CIRC
, "Path is complete: %d steps long",
1679 state
->desired_path_len
);
1683 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
1684 state
->desired_path_len
);
1686 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
1687 info
= extend_info_dup(state
->chosen_exit
);
1688 } else if (cur_len
== 0) { /* picking first node */
1689 routerinfo_t
*r
= choose_good_entry_server(purpose
, state
);
1691 info
= extend_info_from_router(r
);
1694 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
1696 info
= extend_info_from_router(r
);
1700 log_warn(LD_CIRC
,"Failed to find node for hop %d of our path. Discarding "
1701 "this circuit.", cur_len
);
1705 log_debug(LD_CIRC
,"Chose router %s for hop %d (exit is %s)",
1706 info
->nickname
, cur_len
+1, build_state_get_exit_nickname(state
));
1708 onion_append_hop(&circ
->cpath
, info
);
1709 extend_info_free(info
);
1713 /** Create a new hop, annotate it with information about its
1714 * corresponding router <b>choice</b>, and append it to the
1715 * end of the cpath <b>head_ptr</b>. */
1717 onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
)
1719 crypt_path_t
*hop
= tor_malloc_zero(sizeof(crypt_path_t
));
1721 /* link hop into the cpath, at the end. */
1722 onion_append_to_cpath(head_ptr
, hop
);
1724 hop
->magic
= CRYPT_PATH_MAGIC
;
1725 hop
->state
= CPATH_STATE_CLOSED
;
1727 hop
->extend_info
= extend_info_dup(choice
);
1729 hop
->package_window
= CIRCWINDOW_START
;
1730 hop
->deliver_window
= CIRCWINDOW_START
;
1735 /** Allocate a new extend_info object based on the various arguments. */
1737 extend_info_alloc(const char *nickname
, const char *digest
,
1738 crypto_pk_env_t
*onion_key
,
1739 uint32_t addr
, uint16_t port
)
1741 extend_info_t
*info
= tor_malloc_zero(sizeof(extend_info_t
));
1742 memcpy(info
->identity_digest
, digest
, DIGEST_LEN
);
1744 strlcpy(info
->nickname
, nickname
, sizeof(info
->nickname
));
1746 info
->onion_key
= crypto_pk_dup_key(onion_key
);
1752 /** Allocate and return a new extend_info_t that can be used to build a
1753 * circuit to or through the router <b>r</b>. */
1755 extend_info_from_router(routerinfo_t
*r
)
1758 return extend_info_alloc(r
->nickname
, r
->cache_info
.identity_digest
,
1759 r
->onion_pkey
, r
->addr
, r
->or_port
);
1763 /** What router purpose is <b>digest</b>?
1764 * It's a general purpose router unless it's on our bridges list.
1767 get_router_purpose_from_digest(char *digest
)
1769 if (digest_is_a_bridge(digest
))
1770 return ROUTER_PURPOSE_BRIDGE
;
1771 return ROUTER_PURPOSE_GENERAL
;
1776 /** Allocate and return a new extend_info_t that can be used to build a
1777 * circuit to or through the router <b>r</b>. */
1779 extend_info_from_routerstatus(routerstatus_t
*s
)
1782 /* routerstatus doesn't know onion_key; leave it NULL */
1783 return extend_info_alloc(s
->nickname
, s
->identity_digest
,
1784 NULL
, s
->addr
, s
->or_port
);
1785 // get_router_purpose_from_digest(s->identity_digest));
1789 /** Release storage held by an extend_info_t struct. */
1791 extend_info_free(extend_info_t
*info
)
1794 if (info
->onion_key
)
1795 crypto_free_pk_env(info
->onion_key
);
1799 /** Allocate and return a new extend_info_t with the same contents as
1802 extend_info_dup(extend_info_t
*info
)
1804 extend_info_t
*newinfo
;
1806 newinfo
= tor_malloc(sizeof(extend_info_t
));
1807 memcpy(newinfo
, info
, sizeof(extend_info_t
));
1808 if (info
->onion_key
)
1809 newinfo
->onion_key
= crypto_pk_dup_key(info
->onion_key
);
1811 newinfo
->onion_key
= NULL
;
1815 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1816 * If there is no chosen exit, or if we don't know the routerinfo_t for
1817 * the chosen exit, return NULL.
1820 build_state_get_exit_router(cpath_build_state_t
*state
)
1822 if (!state
|| !state
->chosen_exit
)
1824 return router_get_by_digest(state
->chosen_exit
->identity_digest
);
1827 /** Return the nickname for the chosen exit router in <b>state</b>. If
1828 * there is no chosen exit, or if we don't know the routerinfo_t for the
1829 * chosen exit, return NULL.
1832 build_state_get_exit_nickname(cpath_build_state_t
*state
)
1834 if (!state
|| !state
->chosen_exit
)
1836 return state
->chosen_exit
->nickname
;
1839 /** Check whether the entry guard <b>e</b> is usable, given the directory
1840 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1841 * configuration (in <b>options</b>). Set <b>e</b>->bad_since
1842 * accordingly. Return true iff the entry guard's status changes. */
1844 entry_guard_set_status(entry_guard_t
*e
, routerinfo_t
*ri
,
1845 time_t now
, or_options_t
*options
)
1847 const char *reason
= NULL
;
1848 char buf
[HEX_DIGEST_LEN
+1];
1851 tor_assert(options
);
1853 /* Do we want to mark this guard as bad? */
1855 reason
= "unlisted";
1856 else if (!ri
->is_running
)
1858 else if (options
->UseBridges
&& ri
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1859 reason
= "not a bridge";
1860 else if (!options
->UseBridges
&& !ri
->is_possible_guard
&&
1861 !router_nickname_is_in_list(ri
, options
->EntryNodes
))
1862 reason
= "not recommended as a guard";
1863 else if (router_nickname_is_in_list(ri
, options
->ExcludeNodes
))
1864 reason
= "excluded";
1866 if (reason
&& ! e
->bad_since
) {
1867 /* Router is newly bad. */
1868 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1869 log_info(LD_CIRC
, "Entry guard %s (%s) is %s: marking as unusable.",
1870 e
->nickname
, buf
, reason
);
1873 control_event_guard(e
->nickname
, e
->identity
, "BAD");
1875 } else if (!reason
&& e
->bad_since
) {
1876 /* There's nothing wrong with the router any more. */
1877 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1878 log_info(LD_CIRC
, "Entry guard %s (%s) is no longer unusable: "
1879 "marking as ok.", e
->nickname
, buf
);
1882 control_event_guard(e
->nickname
, e
->identity
, "GOOD");
1889 /** Return true iff enough time has passed since we last tried to connect
1890 * to the unreachable guard <b>e</b> that we're willing to try again. */
1892 entry_is_time_to_retry(entry_guard_t
*e
, time_t now
)
1895 if (e
->last_attempted
< e
->unreachable_since
)
1897 diff
= now
- e
->unreachable_since
;
1899 return now
> (e
->last_attempted
+ 60*60);
1900 else if (diff
< 3*24*60*60)
1901 return now
> (e
->last_attempted
+ 4*60*60);
1902 else if (diff
< 7*24*60*60)
1903 return now
> (e
->last_attempted
+ 18*60*60);
1905 return now
> (e
->last_attempted
+ 36*60*60);
1908 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1909 * working well enough that we are willing to use it as an entry
1910 * right now. (Else return NULL.) In particular, it must be
1911 * - Listed as either up or never yet contacted;
1912 * - Present in the routerlist;
1913 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1914 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1915 * (This check is currently redundant with the Guard flag, but in
1916 * the future that might change. Best to leave it in for now.)
1917 * - Allowed by our current ReachableORAddresses config option; and
1918 * - Currently thought to be reachable by us (unless assume_reachable
1921 static INLINE routerinfo_t
*
1922 entry_is_live(entry_guard_t
*e
, int need_uptime
, int need_capacity
,
1923 int assume_reachable
)
1928 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1929 if ((!assume_reachable
&& !e
->can_retry
) &&
1930 e
->unreachable_since
&& !entry_is_time_to_retry(e
, time(NULL
)))
1932 r
= router_get_by_digest(e
->identity
);
1935 if (get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1937 if (!get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_GENERAL
)
1939 if (router_is_unreliable(r
, need_uptime
, need_capacity
, 0))
1941 if (!fascist_firewall_allows_address_or(r
->addr
,r
->or_port
))
1946 /** Return the number of entry guards that we think are usable. */
1948 num_live_entry_guards(void)
1953 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1955 if (entry_is_live(entry
, 0, 1, 0))
1961 /** If <b>digest</b> matches the identity of any node in the
1962 * entry_guards list, return that node. Else return NULL. */
1963 static INLINE entry_guard_t
*
1964 is_an_entry_guard(const char *digest
)
1966 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1967 if (!memcmp(digest
, entry
->identity
, DIGEST_LEN
))
1973 /** Dump a description of our list of entry guards to the log at level
1974 * <b>severity</b>. */
1976 log_entry_guards(int severity
)
1978 smartlist_t
*elements
= smartlist_create();
1982 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
1984 tor_snprintf(buf
, sizeof(buf
), "%s (%s%s)",
1986 e
->bad_since
? "down " : "up ",
1987 e
->made_contact
? "made-contact" : "never-contacted");
1988 smartlist_add(elements
, tor_strdup(buf
));
1991 s
= smartlist_join_strings(elements
, ",", 0, NULL
);
1992 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
1993 smartlist_free(elements
);
1994 log_fn(severity
,LD_CIRC
,"%s",s
);
1998 /** Called when one or more guards that we would previously have used for some
1999 * purpose are no longer in use because a higher-priority guard has become
2002 control_event_guard_deferred(void)
2004 /* XXXX We don't actually have a good way to figure out _how many_ entries
2005 * are live for some purpose. We need an entry_is_even_slightly_live()
2006 * function for this to work right. NumEntryGuards isn't reliable: if we
2007 * need guards with weird properties, we can have more than that number
2012 or_options_t
*options
= get_options();
2015 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2017 if (entry_is_live(entry
, 0, 1, 0)) {
2018 if (n
++ == options
->NumEntryGuards
) {
2019 control_event_guard(entry
->nickname
, entry
->identity
, "DEFERRED");
2027 /** Add a new (preferably stable and fast) router to our
2028 * entry_guards list. Return a pointer to the router if we succeed,
2029 * or NULL if we can't find any more suitable entries.
2031 * If <b>chosen</b> is defined, use that one, and if it's not
2032 * already in our entry_guards list, put it at the *beginning*.
2033 * Else, put the one we pick at the end of the list. */
2034 static routerinfo_t
*
2035 add_an_entry_guard(routerinfo_t
*chosen
, int reset_status
)
2037 routerinfo_t
*router
;
2038 entry_guard_t
*entry
;
2042 entry
= is_an_entry_guard(router
->cache_info
.identity_digest
);
2045 entry
->bad_since
= 0;
2049 router
= choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL
, NULL
);
2053 entry
= tor_malloc_zero(sizeof(entry_guard_t
));
2054 log_info(LD_CIRC
, "Chose '%s' as new entry guard.", router
->nickname
);
2055 strlcpy(entry
->nickname
, router
->nickname
, sizeof(entry
->nickname
));
2056 memcpy(entry
->identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
2057 if (chosen
) /* prepend */
2058 smartlist_insert(entry_guards
, 0, entry
);
2060 smartlist_add(entry_guards
, entry
);
2061 control_event_guard(entry
->nickname
, entry
->identity
, "NEW");
2062 control_event_guard_deferred();
2063 log_entry_guards(LOG_INFO
);
2067 /** If the use of entry guards is configured, choose more entry guards
2068 * until we have enough in the list. */
2070 pick_entry_guards(void)
2072 or_options_t
*options
= get_options();
2075 tor_assert(entry_guards
);
2077 while (num_live_entry_guards() < options
->NumEntryGuards
) {
2078 if (!add_an_entry_guard(NULL
, 0))
2083 entry_guards_changed();
2086 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2087 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2088 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2090 /** Remove all entry guards that have been down or unlisted for so
2091 * long that we don't think they'll come up again. Return 1 if we
2092 * removed any, or 0 if we did nothing. */
2094 remove_dead_entries(void)
2096 char dbuf
[HEX_DIGEST_LEN
+1];
2097 char tbuf
[ISO_TIME_LEN
+1];
2098 time_t now
= time(NULL
);
2102 for (i
= 0; i
< smartlist_len(entry_guards
); ) {
2103 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2104 if (entry
->bad_since
&&
2105 entry
->bad_since
+ ENTRY_GUARD_REMOVE_AFTER
< now
) {
2107 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2108 format_local_iso_time(tbuf
, entry
->bad_since
);
2109 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been down or unlisted "
2110 "since %s local time; removing.",
2111 entry
->nickname
, dbuf
, tbuf
);
2112 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2114 smartlist_del_keeporder(entry_guards
, i
);
2115 log_entry_guards(LOG_INFO
);
2120 return changed
? 1 : 0;
2123 /** A new directory or router-status has arrived; update the down/listed
2124 * status of the entry guards.
2126 * An entry is 'down' if the directory lists it as nonrunning.
2127 * An entry is 'unlisted' if the directory doesn't include it.
2130 entry_guards_compute_status(void)
2132 /* Don't call this on startup; only on a fresh download. Otherwise we'll
2133 * think that things are unlisted. */
2136 int severity
= LOG_INFO
;
2137 or_options_t
*options
;
2141 options
= get_options();
2145 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2147 routerinfo_t
*r
= router_get_by_digest(entry
->identity
);
2148 if (entry_guard_set_status(entry
, r
, now
, options
))
2151 log_info(LD_CIRC
, "Summary: Entry '%s' is %s, %s and %s.",
2153 entry
->unreachable_since
? "unreachable" : "reachable",
2154 entry
->bad_since
? "unusable" : "usable",
2155 entry_is_live(entry
, 0, 1, 0) ? "live" : "not live");
2158 if (remove_dead_entries())
2162 log_fn(severity
, LD_CIRC
, " (%d/%d entry guards are usable/new)",
2163 num_live_entry_guards(), smartlist_len(entry_guards
));
2164 log_entry_guards(LOG_INFO
);
2165 entry_guards_changed();
2169 /** Called when a connection to an OR with the identity digest <b>digest</b>
2170 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2171 * If the OR is an entry, change that entry's up/down status.
2172 * Return 0 normally, or -1 if we want to tear down the new connection.
2175 entry_guard_register_connect_status(const char *digest
, int succeeded
,
2179 int refuse_conn
= 0;
2180 int first_contact
= 0;
2181 entry_guard_t
*entry
= NULL
;
2183 char buf
[HEX_DIGEST_LEN
+1];
2188 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2190 if (!memcmp(e
->identity
, digest
, DIGEST_LEN
)) {
2200 base16_encode(buf
, sizeof(buf
), entry
->identity
, DIGEST_LEN
);
2203 if (entry
->unreachable_since
) {
2204 log_info(LD_CIRC
, "Entry guard '%s' (%s) is now reachable again. Good.",
2205 entry
->nickname
, buf
);
2206 entry
->can_retry
= 0;
2207 entry
->unreachable_since
= 0;
2208 entry
->last_attempted
= now
;
2209 control_event_guard(entry
->nickname
, entry
->identity
, "UP");
2212 if (!entry
->made_contact
) {
2213 entry
->made_contact
= 1;
2214 first_contact
= changed
= 1;
2216 } else { /* ! succeeded */
2217 if (!entry
->made_contact
) {
2218 /* We've never connected to this one. */
2220 "Connection to never-contacted entry guard '%s' (%s) failed. "
2221 "Removing from the list. %d/%d entry guards usable/new.",
2222 entry
->nickname
, buf
,
2223 num_live_entry_guards()-1, smartlist_len(entry_guards
)-1);
2225 smartlist_del_keeporder(entry_guards
, idx
);
2226 log_entry_guards(LOG_INFO
);
2228 } else if (!entry
->unreachable_since
) {
2229 log_info(LD_CIRC
, "Unable to connect to entry guard '%s' (%s). "
2230 "Marking as unreachable.", entry
->nickname
, buf
);
2231 entry
->unreachable_since
= entry
->last_attempted
= now
;
2232 control_event_guard(entry
->nickname
, entry
->identity
, "DOWN");
2235 char tbuf
[ISO_TIME_LEN
+1];
2236 format_iso_time(tbuf
, entry
->unreachable_since
);
2237 log_debug(LD_CIRC
, "Failed to connect to unreachable entry guard "
2238 "'%s' (%s). It has been unreachable since %s.",
2239 entry
->nickname
, buf
, tbuf
);
2240 entry
->last_attempted
= now
;
2243 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2246 if (first_contact
) {
2247 /* We've just added a new long-term entry guard. Perhaps the network just
2248 * came back? We should give our earlier entries another try too,
2249 * and close this connection so we don't use it before we've given
2250 * the others a shot. */
2251 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2254 if (e
->made_contact
) {
2255 routerinfo_t
*r
= entry_is_live(e
, 0, 1, 1);
2256 if (r
&& e
->unreachable_since
) {
2264 "Connected to new entry guard '%s' (%s). Marking earlier "
2265 "entry guards up. %d/%d entry guards usable/new.",
2266 entry
->nickname
, buf
,
2267 num_live_entry_guards(), smartlist_len(entry_guards
));
2268 log_entry_guards(LOG_INFO
);
2274 entry_guards_changed();
2275 return refuse_conn
? -1 : 0;
2278 /** When we try to choose an entry guard, should we parse and add
2279 * config's EntryNodes first? */
2280 static int should_add_entry_nodes
= 0;
2282 /** Called when the value of EntryNodes changes in our configuration. */
2284 entry_nodes_should_be_added(void)
2286 log_info(LD_CIRC
, "New EntryNodes config option detected. Will use.");
2287 should_add_entry_nodes
= 1;
2290 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2291 * of guard nodes, at the front. */
2293 entry_guards_prepend_from_config(void)
2295 or_options_t
*options
= get_options();
2296 smartlist_t
*entry_routers
, *entry_fps
;
2297 smartlist_t
*old_entry_guards_on_list
, *old_entry_guards_not_on_list
;
2298 tor_assert(entry_guards
);
2300 should_add_entry_nodes
= 0;
2302 if (!options
->EntryNodes
) {
2303 /* It's possible that a controller set EntryNodes, thus making
2304 * should_add_entry_nodes set, then cleared it again, all before the
2305 * call to choose_random_entry() that triggered us. If so, just return.
2310 log_info(LD_CIRC
,"Adding configured EntryNodes '%s'.",
2311 options
->EntryNodes
);
2313 entry_routers
= smartlist_create();
2314 entry_fps
= smartlist_create();
2315 old_entry_guards_on_list
= smartlist_create();
2316 old_entry_guards_not_on_list
= smartlist_create();
2318 /* Split entry guards into those on the list and those not. */
2319 add_nickname_list_to_smartlist(entry_routers
, options
->EntryNodes
, 0);
2320 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
,
2321 smartlist_add(entry_fps
,ri
->cache_info
.identity_digest
));
2322 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2323 if (smartlist_digest_isin(entry_fps
, e
->identity
))
2324 smartlist_add(old_entry_guards_on_list
, e
);
2326 smartlist_add(old_entry_guards_not_on_list
, e
);
2329 /* Remove all currently configured entry guards from entry_routers. */
2330 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2331 if (is_an_entry_guard(ri
->cache_info
.identity_digest
)) {
2332 SMARTLIST_DEL_CURRENT(entry_routers
, ri
);
2336 /* Now build the new entry_guards list. */
2337 smartlist_clear(entry_guards
);
2338 /* First, the previously configured guards that are in EntryNodes. */
2339 smartlist_add_all(entry_guards
, old_entry_guards_on_list
);
2340 /* Next, the rest of EntryNodes */
2341 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2342 add_an_entry_guard(ri
, 0);
2344 /* Finally, the remaining EntryNodes, unless we're strict */
2345 if (options
->StrictEntryNodes
) {
2346 SMARTLIST_FOREACH(old_entry_guards_not_on_list
, entry_guard_t
*, e
,
2349 smartlist_add_all(entry_guards
, old_entry_guards_not_on_list
);
2352 smartlist_free(entry_routers
);
2353 smartlist_free(entry_fps
);
2354 smartlist_free(old_entry_guards_on_list
);
2355 smartlist_free(old_entry_guards_not_on_list
);
2356 entry_guards_changed();
2359 /** Return 1 if we're fine adding arbitrary routers out of the
2360 * directory to our entry guard list. Else return 0. */
2362 can_grow_entry_list(or_options_t
*options
)
2364 if (options
->StrictEntryNodes
)
2366 if (options
->UseBridges
)
2371 /** Pick a live (up and listed) entry guard from entry_guards. If
2372 * <b>state</b> is non-NULL, this is for a specific circuit --
2373 * make sure not to pick this circuit's exit or any node in the
2374 * exit's family. If <b>state</b> is NULL, we're looking for a random
2375 * guard (likely a bridge). */
2377 choose_random_entry(cpath_build_state_t
*state
)
2379 or_options_t
*options
= get_options();
2380 smartlist_t
*live_entry_guards
= smartlist_create();
2381 smartlist_t
*exit_family
= smartlist_create();
2382 routerinfo_t
*chosen_exit
= state
?build_state_get_exit_router(state
) : NULL
;
2383 routerinfo_t
*r
= NULL
;
2384 int need_uptime
= state
? state
->need_uptime
: 0;
2385 int need_capacity
= state
? state
->need_capacity
: 0;
2388 smartlist_add(exit_family
, chosen_exit
);
2389 routerlist_add_family(exit_family
, chosen_exit
);
2393 entry_guards
= smartlist_create();
2395 if (should_add_entry_nodes
)
2396 entry_guards_prepend_from_config();
2398 if (can_grow_entry_list(options
) &&
2400 smartlist_len(entry_guards
) < options
->NumEntryGuards
))
2401 pick_entry_guards();
2404 smartlist_clear(live_entry_guards
);
2405 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2407 r
= entry_is_live(entry
, need_uptime
, need_capacity
, 0);
2408 if (r
&& !smartlist_isin(exit_family
, r
)) {
2409 smartlist_add(live_entry_guards
, r
);
2410 if (!entry
->made_contact
) {
2411 /* Always start with the first not-yet-contacted entry
2412 * guard. Otherwise we might add several new ones, pick
2413 * the second new one, and now we've expanded our entry
2414 * guard list without needing to. */
2415 goto choose_and_finish
;
2417 if (smartlist_len(live_entry_guards
) >= options
->NumEntryGuards
)
2418 break; /* we have enough */
2422 /* Try to have at least 2 choices available. This way we don't
2423 * get stuck with a single live-but-crummy entry and just keep
2425 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2426 if (smartlist_len(live_entry_guards
) < 2) {
2427 if (can_grow_entry_list(options
)) {
2428 /* still no? try adding a new entry then */
2429 /* XXX if guard doesn't imply fast and stable, then we need
2430 * to tell add_an_entry_guard below what we want, or it might
2431 * be a long time til we get it. -RD */
2432 r
= add_an_entry_guard(NULL
, 0);
2434 smartlist_add(live_entry_guards
, r
);
2435 entry_guards_changed();
2438 if (!r
&& need_uptime
) {
2439 need_uptime
= 0; /* try without that requirement */
2442 if (!r
&& need_capacity
) {
2443 /* still no? last attempt, try without requiring capacity */
2447 /* live_entry_guards may be empty below. Oh well, we tried. */
2451 r
= smartlist_choose(live_entry_guards
);
2452 smartlist_free(live_entry_guards
);
2453 smartlist_free(exit_family
);
2457 /** Parse <b>state</b> and learn about the entry guards it describes.
2458 * If <b>set</b> is true, and there are no errors, replace the global
2459 * entry_list with what we find.
2460 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2461 * describing the error, and return -1.
2464 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
2466 entry_guard_t
*node
= NULL
;
2467 smartlist_t
*new_entry_guards
= smartlist_create();
2468 config_line_t
*line
;
2469 time_t now
= time(NULL
);
2472 for (line
= state
->EntryGuards
; line
; line
= line
->next
) {
2473 if (!strcasecmp(line
->key
, "EntryGuard")) {
2474 smartlist_t
*args
= smartlist_create();
2475 node
= tor_malloc_zero(sizeof(entry_guard_t
));
2476 /* all entry guards on disk have been contacted */
2477 node
->made_contact
= 1;
2478 smartlist_add(new_entry_guards
, node
);
2479 smartlist_split_string(args
, line
->value
, " ",
2480 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2481 if (smartlist_len(args
)<2) {
2482 *msg
= tor_strdup("Unable to parse entry nodes: "
2483 "Too few arguments to EntryGuard");
2484 } else if (!is_legal_nickname(smartlist_get(args
,0))) {
2485 *msg
= tor_strdup("Unable to parse entry nodes: "
2486 "Bad nickname for EntryGuard");
2488 strlcpy(node
->nickname
, smartlist_get(args
,0), MAX_NICKNAME_LEN
+1);
2489 if (base16_decode(node
->identity
, DIGEST_LEN
, smartlist_get(args
,1),
2490 strlen(smartlist_get(args
,1)))<0) {
2491 *msg
= tor_strdup("Unable to parse entry nodes: "
2492 "Bad hex digest for EntryGuard");
2495 SMARTLIST_FOREACH(args
, char*, cp
, tor_free(cp
));
2496 smartlist_free(args
);
2501 time_t last_try
= 0;
2503 *msg
= tor_strdup("Unable to parse entry nodes: "
2504 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2507 if (parse_iso_time(line
->value
, &when
)<0) {
2508 *msg
= tor_strdup("Unable to parse entry nodes: "
2509 "Bad time in EntryGuardDownSince/UnlistedSince");
2513 /* It's a bad idea to believe info in the future: you can wind
2514 * up with timeouts that aren't allowed to happen for years. */
2517 if (strlen(line
->value
) >= ISO_TIME_LEN
+ISO_TIME_LEN
+1) {
2518 /* ignore failure */
2519 parse_iso_time(line
->value
+ISO_TIME_LEN
+1, &last_try
);
2521 if (!strcasecmp(line
->key
, "EntryGuardDownSince")) {
2522 node
->unreachable_since
= when
;
2523 node
->last_attempted
= last_try
;
2525 node
->bad_since
= when
;
2531 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
, tor_free(e
));
2532 smartlist_free(new_entry_guards
);
2533 } else { /* !*err && set */
2535 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, tor_free(e
));
2536 smartlist_free(entry_guards
);
2538 entry_guards
= new_entry_guards
;
2539 entry_guards_dirty
= 0;
2541 return *msg
? -1 : 0;
2544 /** Our list of entry guards has changed, or some element of one
2545 * of our entry guards has changed. Write the changes to disk within
2546 * the next few minutes.
2549 entry_guards_changed(void)
2552 entry_guards_dirty
= 1;
2554 /* or_state_save() will call entry_guards_update_state(). */
2555 when
= get_options()->AvoidDiskWrites
? time(NULL
) + 3600 : time(NULL
)+600;
2556 or_state_mark_dirty(get_or_state(), when
);
2559 /** If the entry guard info has not changed, do nothing and return.
2560 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2561 * a new one out of the global entry_guards list, and then mark
2562 * <b>state</b> dirty so it will get saved to disk.
2565 entry_guards_update_state(or_state_t
*state
)
2567 config_line_t
**next
, *line
;
2568 if (! entry_guards_dirty
)
2571 config_free_lines(state
->EntryGuards
);
2572 next
= &state
->EntryGuards
;
2575 entry_guards
= smartlist_create();
2576 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2578 char dbuf
[HEX_DIGEST_LEN
+1];
2579 if (!e
->made_contact
)
2580 continue; /* don't write this one to disk */
2581 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2582 line
->key
= tor_strdup("EntryGuard");
2583 line
->value
= tor_malloc(HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2);
2584 base16_encode(dbuf
, sizeof(dbuf
), e
->identity
, DIGEST_LEN
);
2585 tor_snprintf(line
->value
,HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2,
2586 "%s %s", e
->nickname
, dbuf
);
2587 next
= &(line
->next
);
2588 if (e
->unreachable_since
) {
2589 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2590 line
->key
= tor_strdup("EntryGuardDownSince");
2591 line
->value
= tor_malloc(ISO_TIME_LEN
+1+ISO_TIME_LEN
+1);
2592 format_iso_time(line
->value
, e
->unreachable_since
);
2593 if (e
->last_attempted
) {
2594 line
->value
[ISO_TIME_LEN
] = ' ';
2595 format_iso_time(line
->value
+ISO_TIME_LEN
+1, e
->last_attempted
);
2597 next
= &(line
->next
);
2600 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2601 line
->key
= tor_strdup("EntryGuardUnlistedSince");
2602 line
->value
= tor_malloc(ISO_TIME_LEN
+1);
2603 format_iso_time(line
->value
, e
->bad_since
);
2604 next
= &(line
->next
);
2607 if (!get_options()->AvoidDiskWrites
)
2608 or_state_mark_dirty(get_or_state(), 0);
2609 entry_guards_dirty
= 0;
2612 /** If <b>question</b> is the string "entry-guards", then dump
2613 * to *<b>answer</b> a newly allocated string describing all of
2614 * the nodes in the global entry_guards list. See control-spec.txt
2616 * For backward compatibility, we also handle the string "helper-nodes".
2619 getinfo_helper_entry_guards(control_connection_t
*conn
,
2620 const char *question
, char **answer
)
2622 int use_long_names
= conn
->use_long_names
;
2624 if (!strcmp(question
,"entry-guards") ||
2625 !strcmp(question
,"helper-nodes")) {
2626 smartlist_t
*sl
= smartlist_create();
2627 char tbuf
[ISO_TIME_LEN
+1];
2628 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
2630 entry_guards
= smartlist_create();
2631 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2633 size_t len
= MAX_VERBOSE_NICKNAME_LEN
+ISO_TIME_LEN
+32;
2634 char *c
= tor_malloc(len
);
2635 const char *status
= NULL
;
2637 if (!e
->made_contact
) {
2638 status
= "never-connected";
2639 } else if (e
->bad_since
) {
2640 when
= e
->bad_since
;
2641 status
= "unusable";
2645 if (use_long_names
) {
2646 routerinfo_t
*ri
= router_get_by_digest(e
->identity
);
2648 router_get_verbose_nickname(nbuf
, ri
);
2651 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
2652 /* e->nickname field is not very reliable if we don't know about
2653 * this router any longer; don't include it. */
2656 base16_encode(nbuf
, sizeof(nbuf
), e
->identity
, DIGEST_LEN
);
2659 format_iso_time(tbuf
, when
);
2660 tor_snprintf(c
, len
, "%s %s %s\n", nbuf
, status
, tbuf
);
2662 tor_snprintf(c
, len
, "%s %s\n", nbuf
, status
);
2664 smartlist_add(sl
, c
);
2666 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2667 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2676 char identity
[DIGEST_LEN
];
2677 download_status_t fetch_status
;
2680 /** A list of known bridges. */
2681 static smartlist_t
*bridge_list
= NULL
;
2683 /** Initialize the bridge list to empty, creating it if needed. */
2685 clear_bridge_list(void)
2688 bridge_list
= smartlist_create();
2689 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, b
, tor_free(b
));
2690 smartlist_clear(bridge_list
);
2694 /** Return 1 if <b>digest</b> is one of our known bridges. */
2696 identity_digest_is_a_bridge(const char *digest
)
2698 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2700 if (!memcmp(bridge
->identity
, digest
, DIGEST_LEN
))
2707 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2708 * (either by comparing keys if possible, else by comparing addr/port).
2709 * Else return NULL. */
2710 static bridge_info_t
*
2711 routerinfo_get_configured_bridge(routerinfo_t
*ri
)
2713 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2715 if (tor_digest_is_zero(bridge
->identity
) &&
2716 bridge
->addr
== ri
->addr
&& bridge
->port
== ri
->or_port
)
2718 if (!memcmp(bridge
->identity
, ri
->cache_info
.identity_digest
,
2725 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
2727 routerinfo_is_a_configured_bridge(routerinfo_t
*ri
)
2729 return routerinfo_get_configured_bridge(ri
) ? 1 : 0;
2732 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2733 * is set, it tells us the identity key too. */
2735 bridge_add_from_config(uint32_t addr
, uint16_t port
, char *digest
)
2737 bridge_info_t
*b
= tor_malloc_zero(sizeof(bridge_info_t
));
2741 memcpy(b
->identity
, digest
, DIGEST_LEN
);
2743 bridge_list
= smartlist_create();
2744 smartlist_add(bridge_list
, b
);
2747 /** Schedule the next fetch for <b>bridge</b>, based on
2748 * some retry schedule. */
2750 bridge_fetch_status_increment(bridge_info_t
*bridge
, time_t now
)
2752 switch (bridge
->fetch_status
.n_download_failures
) {
2753 case 0: bridge
->fetch_status
.next_attempt_at
= now
+60*15; break;
2754 case 1: bridge
->fetch_status
.next_attempt_at
= now
+60*15; break;
2755 default: bridge
->fetch_status
.next_attempt_at
= now
+60*60; break;
2757 if (bridge
->fetch_status
.n_download_failures
< 10)
2758 bridge
->fetch_status
.n_download_failures
++;
2761 /** We just got a new descriptor for <b>bridge</b>. Reschedule the
2762 * next fetch for a long time from <b>now</b>. */
2764 bridge_fetch_status_arrived(bridge_info_t
*bridge
, time_t now
)
2766 bridge
->fetch_status
.next_attempt_at
= now
+60*60;
2767 bridge
->fetch_status
.n_download_failures
= 0;
2770 /** For each bridge in our list for which we don't currently have a
2771 * descriptor, fetch a new copy of its descriptor -- either directly
2772 * from the bridge or via a bridge authority. */
2774 fetch_bridge_descriptors(time_t now
)
2776 char address_buf
[INET_NTOA_BUF_LEN
+1];
2778 or_options_t
*options
= get_options();
2779 int num_bridge_auths
= get_n_authorities(BRIDGE_AUTHORITY
);
2780 int ask_bridge_directly
;
2785 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2787 if (bridge
->fetch_status
.next_attempt_at
> now
)
2788 continue; /* don't bother, no need to retry yet */
2790 /* schedule another fetch as if this one will fail, in case it does */
2791 bridge_fetch_status_increment(bridge
, now
);
2793 in
.s_addr
= htonl(bridge
->addr
);
2794 tor_inet_ntoa(&in
, address_buf
, sizeof(address_buf
));
2796 ask_bridge_directly
= tor_digest_is_zero(bridge
->identity
) ||
2797 !options
->UpdateBridgesFromAuthority
||
2800 if (ask_bridge_directly
&&
2801 !fascist_firewall_allows_address_or(bridge
->addr
, bridge
->port
)) {
2802 log_notice(LD_DIR
, "Bridge at '%s:%d' isn't reachable by our "
2803 "firewall policy. %s.", address_buf
, bridge
->port
,
2804 num_bridge_auths
? "Asking bridge authority instead" :
2806 ask_bridge_directly
= 0;
2809 if (ask_bridge_directly
) {
2810 if (!connection_get_by_type_addr_port_purpose(
2811 CONN_TYPE_DIR
, bridge
->addr
, bridge
->port
,
2812 DIR_PURPOSE_FETCH_SERVERDESC
)) {
2813 /* we need to ask the bridge itself for its descriptor. */
2814 directory_initiate_command(address_buf
, bridge
->addr
,
2816 1, bridge
->identity
,
2817 DIR_PURPOSE_FETCH_SERVERDESC
,
2818 ROUTER_PURPOSE_BRIDGE
,
2819 0, "authority.z", NULL
, 0);
2822 /* We have a digest and we want to ask an authority. We could
2823 * combine all the requests into one, but that may give more
2824 * hints to the bridge authority than we want to give. */
2825 char resource
[10 + HEX_DIGEST_LEN
];
2826 memcpy(resource
, "fp/", 3);
2827 base16_encode(resource
+3, HEX_DIGEST_LEN
+1,
2828 bridge
->identity
, DIGEST_LEN
);
2829 memcpy(resource
+3+HEX_DIGEST_LEN
, ".z", 3);
2830 log_info(LD_DIR
, "Fetching bridge info '%s' from bridge authority.",
2832 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
2833 ROUTER_PURPOSE_BRIDGE
, resource
, 1);
2838 /** We just learned a descriptor for a bridge. See if that
2839 * digest is in our entry guard list, and add it if not. */
2841 learned_bridge_descriptor(routerinfo_t
*ri
)
2844 tor_assert(ri
->purpose
== ROUTER_PURPOSE_BRIDGE
);
2845 if (get_options()->UseBridges
) {
2846 int first
= !any_bridge_descriptors_known();
2847 bridge_info_t
*bridge
= routerinfo_get_configured_bridge(ri
);
2848 time_t now
= time(NULL
);
2851 /* it's here; schedule its re-fetch for a long time from now. */
2852 bridge_fetch_status_arrived(bridge
, now
);
2854 add_an_entry_guard(ri
, 1);
2855 log_notice(LD_DIR
, "new bridge descriptor '%s'", ri
->nickname
);
2857 routerlist_retry_directory_downloads(now
);
2861 /** Return 1 if any of our entry guards have descriptors that
2862 * are marked with purpose 'bridge' and are running. Else return 0.
2864 * We use this function to decide if we're ready to start building
2865 * circuits through our bridges, or if we need to wait until the
2866 * directory "server/authority" requests finish. */
2868 any_bridge_descriptors_known(void)
2870 tor_assert(get_options()->UseBridges
);
2871 return choose_random_entry(NULL
)!=NULL
? 1 : 0;
2874 /** Return 1 if we have at least one descriptor for a bridge and
2875 * all descriptors we know are down. Else return 0. If <b>act</b> is
2876 * 1, then mark the down bridges up; else just observe and report. */
2878 bridges_retry_helper(int act
)
2882 int any_running
= 0;
2884 entry_guards
= smartlist_create();
2885 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2887 ri
= router_get_by_digest(e
->identity
);
2888 if (ri
&& ri
->purpose
== ROUTER_PURPOSE_BRIDGE
) {
2891 any_running
= 1; /* some bridge is both known and running */
2892 else if (act
) { /* mark it for retry */
2899 return any_known
&& !any_running
;
2902 /** Do we know any descriptors for our bridges, and are they all
2905 bridges_should_be_retried(void)
2907 return bridges_retry_helper(0);
2910 /** Mark all down known bridges up. */
2912 bridges_retry_all(void)
2914 bridges_retry_helper(1);
2917 /** Release all storage held by the list of entry guards and related
2918 * memory structs. */
2920 entry_guards_free_all(void)
2923 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, tor_free(e
));
2924 smartlist_free(entry_guards
);
2925 entry_guards
= NULL
;
2927 clear_bridge_list();
2928 smartlist_free(bridge_list
);