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, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 const char circuitbuild_c_id
[] =
11 * \file circuitbuild.c
12 * \brief The actual details of building circuits.
17 /********* START VARIABLES **********/
19 /** A global list of all circuits at this hop. */
20 extern circuit_t
*global_circuitlist
;
22 /** An entry_guard_t represents our information about a chosen long-term
23 * first hop, known as a "helper" node in the literature. We can't just
24 * use a routerinfo_t, since we want to remember these even when we
25 * don't have a directory. */
27 char nickname
[MAX_NICKNAME_LEN
+1];
28 char identity
[DIGEST_LEN
];
29 time_t chosen_on_date
; /**< Approximately when was this guard added?
30 * "0" if we don't know. */
31 char *chosen_by_version
; /**< What tor version added this guard? NULL
32 * if we don't know. */
33 unsigned int made_contact
: 1; /**< 0 if we have never connected to this
34 * router, 1 if we have. */
35 unsigned int can_retry
: 1; /**< Should we retry connecting to this entry,
36 * in spite of having it marked as unreachable?*/
37 time_t bad_since
; /**< 0 if this guard is currently usable, or the time at
38 * which it was observed to become (according to the
39 * directory or the user configuration) unusable. */
40 time_t unreachable_since
; /**< 0 if we can connect to this guard, or the
41 * time at which we first noticed we couldn't
43 time_t last_attempted
; /**< 0 if we can connect to this guard, or the time
44 * at which we last failed to connect to it. */
47 /** A list of our chosen entry guards. */
48 static smartlist_t
*entry_guards
= NULL
;
49 /** A value of 1 means that the entry_guards list has changed
50 * and those changes need to be flushed to disk. */
51 static int entry_guards_dirty
= 0;
53 /********* END VARIABLES ************/
55 static int circuit_deliver_create_cell(circuit_t
*circ
,
56 uint8_t cell_type
, const char *payload
);
57 static int onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
);
58 static crypt_path_t
*onion_next_hop_in_cpath(crypt_path_t
*cpath
);
59 static int onion_extend_cpath(origin_circuit_t
*circ
);
60 static int count_acceptable_routers(smartlist_t
*routers
);
61 static int onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
);
63 static void entry_guards_changed(void);
64 static time_t start_of_month(time_t when
);
66 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
67 * and with the high bit specified by conn-\>circ_id_type, until we get
68 * a circ_id that is not in use by any other circuit on that conn.
70 * Return it, or 0 if can't get a unique circ_id.
73 get_unique_circ_id_by_conn(or_connection_t
*conn
)
75 uint16_t test_circ_id
;
80 if (conn
->circ_id_type
== CIRC_ID_TYPE_NEITHER
) {
81 log_warn(LD_BUG
, "Trying to pick a circuit ID for a connection from "
82 "a client with no identity.");
85 high_bit
= (conn
->circ_id_type
== CIRC_ID_TYPE_HIGHER
) ? 1<<15 : 0;
87 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
88 * circID such that (high_bit|test_circ_id) is not already used. */
89 test_circ_id
= conn
->next_circ_id
++;
90 if (test_circ_id
== 0 || test_circ_id
>= 1<<15) {
92 conn
->next_circ_id
= 2;
94 if (++attempts
> 1<<15) {
95 /* Make sure we don't loop forever if all circ_id's are used. This
96 * matters because it's an external DoS opportunity.
98 log_warn(LD_CIRC
,"No unused circ IDs. Failing.");
101 test_circ_id
|= high_bit
;
102 } while (circuit_get_by_circid_orconn(test_circ_id
, conn
));
106 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
107 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
108 * list information about link status in a more verbose format using spaces.
109 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
110 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
114 circuit_list_path_impl(origin_circuit_t
*circ
, int verbose
, int verbose_names
)
117 smartlist_t
*elements
;
118 const char *states
[] = {"closed", "waiting for keys", "open"};
122 elements
= smartlist_create();
125 const char *nickname
= build_state_get_exit_nickname(circ
->build_state
);
126 tor_snprintf(buf
, sizeof(buf
), "%s%s circ (length %d%s%s):",
127 circ
->build_state
->is_internal
? "internal" : "exit",
128 circ
->build_state
->need_uptime
? " (high-uptime)" : "",
129 circ
->build_state
->desired_path_len
,
130 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" : ", exit ",
131 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" :
132 (nickname
?nickname
:"*unnamed*"));
133 smartlist_add(elements
, tor_strdup(buf
));
142 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
144 if (!hop
->extend_info
)
147 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
148 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
))) {
149 router_get_verbose_nickname(elt
, ri
);
150 } else if (hop
->extend_info
->nickname
&&
151 is_legal_nickname(hop
->extend_info
->nickname
)) {
153 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
154 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
155 elt
[HEX_DIGEST_LEN
+1]= '~';
156 strlcpy(elt
+HEX_DIGEST_LEN
+2,
157 hop
->extend_info
->nickname
, MAX_NICKNAME_LEN
+1);
160 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
161 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
163 } else { /* ! verbose_names */
164 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
)) &&
166 elt
= tor_strdup(hop
->extend_info
->nickname
);
168 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
170 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
171 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
176 size_t len
= strlen(elt
)+2+strlen(states
[hop
->state
])+1;
177 char *v
= tor_malloc(len
);
178 tor_assert(hop
->state
<= 2);
179 tor_snprintf(v
,len
,"%s(%s)",elt
,states
[hop
->state
]);
180 smartlist_add(elements
, v
);
183 smartlist_add(elements
, elt
);
186 } while (hop
!= circ
->cpath
);
188 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
189 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
190 smartlist_free(elements
);
194 /** If <b>verbose</b> is false, allocate and return a comma-separated
195 * list of the currently built elements of circuit_t. If
196 * <b>verbose</b> is true, also list information about link status in
197 * a more verbose format using spaces.
200 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
202 return circuit_list_path_impl(circ
, verbose
, 0);
205 /** Allocate and return a comma-separated list of the currently built elements
206 * of circuit_t, giving each as a verbose nickname.
209 circuit_list_path_for_controller(origin_circuit_t
*circ
)
211 return circuit_list_path_impl(circ
, 0, 1);
214 /** Log, at severity <b>severity</b>, the nicknames of each router in
215 * circ's cpath. Also log the length of the cpath, and the intended
219 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
221 char *s
= circuit_list_path(circ
,1);
222 log(severity
,domain
,"%s",s
);
226 /** Tell the rep(utation)hist(ory) module about the status of the links
227 * in circ. Hops that have become OPEN are marked as successfully
228 * extended; the _first_ hop that isn't open (if any) is marked as
231 /* XXXX Someday we should learn from OR circuits too. */
233 circuit_rep_hist_note_result(origin_circuit_t
*circ
)
236 char *prev_digest
= NULL
;
237 routerinfo_t
*router
;
239 if (!hop
) /* circuit hasn't started building yet. */
241 if (server_mode(get_options())) {
242 routerinfo_t
*me
= router_get_my_routerinfo();
245 prev_digest
= me
->cache_info
.identity_digest
;
248 router
= router_get_by_digest(hop
->extend_info
->identity_digest
);
251 if (hop
->state
== CPATH_STATE_OPEN
)
252 rep_hist_note_extend_succeeded(prev_digest
,
253 router
->cache_info
.identity_digest
);
255 rep_hist_note_extend_failed(prev_digest
,
256 router
->cache_info
.identity_digest
);
260 prev_digest
= router
->cache_info
.identity_digest
;
265 } while (hop
!=circ
->cpath
);
268 /** Pick all the entries in our cpath. Stop and return 0 when we're
269 * happy, or return -1 if an error occurs. */
271 onion_populate_cpath(origin_circuit_t
*circ
)
275 r
= onion_extend_cpath(circ
);
277 log_info(LD_CIRC
,"Generating cpath hop failed.");
282 return 0; /* if r == 1 */
285 /** Create and return a new origin circuit. Initialize its purpose and
286 * build-state based on our arguments. */
288 origin_circuit_init(uint8_t purpose
, int onehop_tunnel
,
289 int need_uptime
, int need_capacity
, int internal
)
291 /* sets circ->p_circ_id and circ->p_conn */
292 origin_circuit_t
*circ
= origin_circuit_new();
293 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OR_WAIT
);
294 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
295 circ
->build_state
->onehop_tunnel
= onehop_tunnel
;
296 circ
->build_state
->need_uptime
= need_uptime
;
297 circ
->build_state
->need_capacity
= need_capacity
;
298 circ
->build_state
->is_internal
= internal
;
299 circ
->_base
.purpose
= purpose
;
303 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
304 * is defined, then use that as your exit router, else choose a suitable
307 * Also launch a connection to the first OR in the chosen path, if
308 * it's not open already.
311 circuit_establish_circuit(uint8_t purpose
, int onehop_tunnel
,
313 int need_uptime
, int need_capacity
, int internal
)
315 origin_circuit_t
*circ
;
318 circ
= origin_circuit_init(purpose
, onehop_tunnel
,
319 need_uptime
, need_capacity
, internal
);
321 if (onion_pick_cpath_exit(circ
, exit
) < 0 ||
322 onion_populate_cpath(circ
) < 0) {
323 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
327 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
329 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
330 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
336 /** Start establishing the first hop of our circuit. Figure out what
337 * OR we should connect to, and if necessary start the connection to
338 * it. If we're already connected, then send the 'create' cell.
339 * Return 0 for ok, -reason if circ should be marked-for-close. */
341 circuit_handle_first_hop(origin_circuit_t
*circ
)
343 crypt_path_t
*firsthop
;
344 or_connection_t
*n_conn
;
345 char tmpbuf
[INET_NTOA_BUF_LEN
];
349 firsthop
= onion_next_hop_in_cpath(circ
->cpath
);
350 tor_assert(firsthop
);
351 tor_assert(firsthop
->extend_info
);
353 /* now see if we're already connected to the first OR in 'route' */
354 in
.s_addr
= htonl(firsthop
->extend_info
->addr
);
355 tor_inet_ntoa(&in
, tmpbuf
, sizeof(tmpbuf
));
356 log_debug(LD_CIRC
,"Looking for firsthop '%s:%u'",tmpbuf
,
357 firsthop
->extend_info
->port
);
358 /* imprint the circuit with its future n_conn->id */
359 memcpy(circ
->_base
.n_conn_id_digest
, firsthop
->extend_info
->identity_digest
,
361 n_conn
= connection_or_get_by_identity_digest(
362 firsthop
->extend_info
->identity_digest
);
363 /* If we don't have an open conn, or the conn we have is obsolete
364 * (i.e. old or broken) and the other side will let us make a second
365 * connection without dropping it immediately... */
366 if (!n_conn
|| n_conn
->_base
.state
!= OR_CONN_STATE_OPEN
||
367 (n_conn
->_base
.or_is_obsolete
&&
368 router_digest_version_as_new_as(firsthop
->extend_info
->identity_digest
,
369 "0.1.1.9-alpha-cvs"))) {
370 /* not currently connected */
371 circ
->_base
.n_addr
= firsthop
->extend_info
->addr
;
372 circ
->_base
.n_port
= firsthop
->extend_info
->port
;
374 if (!n_conn
|| n_conn
->_base
.or_is_obsolete
) { /* launch the connection */
375 n_conn
= connection_or_connect(firsthop
->extend_info
->addr
,
376 firsthop
->extend_info
->port
,
377 firsthop
->extend_info
->identity_digest
);
378 if (!n_conn
) { /* connect failed, forget the whole thing */
379 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
380 return -END_CIRC_REASON_CONNECTFAILED
;
384 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
385 /* return success. The onion/circuit/etc will be taken care of
386 * automatically (may already have been) whenever n_conn reaches
387 * OR_CONN_STATE_OPEN.
390 } else { /* it's already open. use it. */
391 circ
->_base
.n_addr
= n_conn
->_base
.addr
;
392 circ
->_base
.n_port
= n_conn
->_base
.port
;
393 circ
->_base
.n_conn
= n_conn
;
394 log_debug(LD_CIRC
,"Conn open. Delivering first onion skin.");
395 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
396 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
403 /** Find any circuits that are waiting on <b>or_conn</b> to become
404 * open and get them to send their create cells forward.
406 * Status is 1 if connect succeeded, or 0 if connect failed.
409 circuit_n_conn_done(or_connection_t
*or_conn
, int status
)
411 smartlist_t
*pending_circs
;
414 log_debug(LD_CIRC
,"or_conn to %s, status=%d",
415 or_conn
->nickname
? or_conn
->nickname
: "NULL", status
);
417 pending_circs
= smartlist_create();
418 circuit_get_all_pending_on_or_conn(pending_circs
, or_conn
);
420 SMARTLIST_FOREACH(pending_circs
, circuit_t
*, circ
,
422 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
423 * leaving them in in case it's possible for the status of a circuit to
424 * change as we're going down the list. */
425 if (circ
->marked_for_close
|| circ
->n_conn
||
426 circ
->state
!= CIRCUIT_STATE_OR_WAIT
)
428 if (tor_digest_is_zero(circ
->n_conn_id_digest
)) {
429 /* Look at addr/port. This is an unkeyed connection. */
430 if (circ
->n_addr
!= or_conn
->_base
.addr
||
431 circ
->n_port
!= or_conn
->_base
.port
)
433 /* now teach circ the right identity_digest */
434 memcpy(circ
->n_conn_id_digest
, or_conn
->identity_digest
, DIGEST_LEN
);
436 /* We expected a key. See if it's the right one. */
437 if (memcmp(or_conn
->identity_digest
,
438 circ
->n_conn_id_digest
, DIGEST_LEN
))
441 if (!status
) { /* or_conn failed; close circ */
442 log_info(LD_CIRC
,"or_conn failed. Closing circ.");
443 circuit_mark_for_close(circ
, END_CIRC_REASON_OR_CONN_CLOSED
);
446 log_debug(LD_CIRC
, "Found circ, sending create cell.");
447 /* circuit_deliver_create_cell will set n_circ_id and add us to
448 * orconn_circuid_circuit_map, so we don't need to call
449 * set_circid_orconn here. */
450 circ
->n_conn
= or_conn
;
451 if (CIRCUIT_IS_ORIGIN(circ
)) {
453 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
455 "send_next_onion_skin failed; circuit marked for closing.");
456 circuit_mark_for_close(circ
, -err_reason
);
458 /* XXX could this be bad, eg if next_onion_skin failed because conn
462 /* pull the create cell out of circ->onionskin, and send it */
463 tor_assert(circ
->onionskin
);
464 if (circuit_deliver_create_cell(circ
,CELL_CREATE
,circ
->onionskin
)<0) {
465 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
468 tor_free(circ
->onionskin
);
469 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
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 build a circuit
542 * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
543 * information on the router, so assume true.) */
545 should_use_create_fast_for_router(routerinfo_t
*router
,
546 origin_circuit_t
*circ
)
548 or_options_t
*options
= get_options();
550 if (!options
->FastFirstHopPK
) /* create_fast is disabled */
552 if (router
&& router
->platform
&&
553 !tor_version_as_new_as(router
->platform
, "0.1.0.6-rc")) {
554 /* known not to work */
557 if (server_mode(options
) && circ
->cpath
->extend_info
->onion_key
) {
558 /* We're a server, and we know an onion key. We can choose.
559 * Prefer to blend in. */
566 /** This is the backbone function for building circuits.
568 * If circ's first hop is closed, then we need to build a create
569 * cell and send it forward.
571 * Otherwise, we need to build a relay extend cell and send it
574 * Return -reason if we want to tear down circ, else return 0.
577 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
580 routerinfo_t
*router
;
581 char payload
[2+4+DIGEST_LEN
+ONIONSKIN_CHALLENGE_LEN
];
587 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
590 log_debug(LD_CIRC
,"First skin; sending create cell.");
592 router
= router_get_by_digest(circ
->_base
.n_conn
->identity_digest
);
593 fast
= should_use_create_fast_for_router(router
, circ
);
594 if (!fast
&& !circ
->cpath
->extend_info
->onion_key
) {
596 "Can't send create_fast, but have no onion key. Failing.");
597 return - END_CIRC_REASON_INTERNAL
;
600 /* We are an OR, or we are connecting to an old Tor: we should
601 * send an old slow create cell.
603 cell_type
= CELL_CREATE
;
604 if (onion_skin_create(circ
->cpath
->extend_info
->onion_key
,
605 &(circ
->cpath
->dh_handshake_state
),
607 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
608 return - END_CIRC_REASON_INTERNAL
;
611 /* We are not an OR, and we're building the first hop of a circuit to a
612 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
613 * and a DH operation. */
614 cell_type
= CELL_CREATE_FAST
;
615 memset(payload
, 0, sizeof(payload
));
616 crypto_rand(circ
->cpath
->fast_handshake_state
,
617 sizeof(circ
->cpath
->fast_handshake_state
));
618 memcpy(payload
, circ
->cpath
->fast_handshake_state
,
619 sizeof(circ
->cpath
->fast_handshake_state
));
622 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), cell_type
, payload
) < 0)
623 return - END_CIRC_REASON_RESOURCELIMIT
;
625 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
626 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
627 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
628 fast
? "CREATE_FAST" : "CREATE",
629 router
? router
->nickname
: "<unnamed>");
631 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
632 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_BUILDING
);
633 log_debug(LD_CIRC
,"starting to send subsequent skin.");
634 hop
= onion_next_hop_in_cpath(circ
->cpath
);
636 /* done building the circuit. whew. */
637 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
638 log_info(LD_CIRC
,"circuit built!");
639 circuit_reset_failure_count(0);
640 if (!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_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
648 if (server_mode(options
) && !check_whether_orport_reachable()) {
649 inform_testing_reachability();
650 consider_testing_reachability(1, 1);
653 circuit_rep_hist_note_result(circ
);
654 circuit_has_opened(circ
); /* do other actions as necessary */
658 set_uint32(payload
, htonl(hop
->extend_info
->addr
));
659 set_uint16(payload
+4, htons(hop
->extend_info
->port
));
661 onionskin
= payload
+2+4;
662 memcpy(payload
+2+4+ONIONSKIN_CHALLENGE_LEN
,
663 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
664 payload_len
= 2+4+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
;
666 if (onion_skin_create(hop
->extend_info
->onion_key
,
667 &(hop
->dh_handshake_state
), onionskin
) < 0) {
668 log_warn(LD_CIRC
,"onion_skin_create failed.");
669 return - END_CIRC_REASON_INTERNAL
;
672 log_info(LD_CIRC
,"Sending extend relay cell.");
673 /* send it to hop->prev, because it will transfer
674 * it to a create cell and then send to hop */
675 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
676 RELAY_COMMAND_EXTEND
,
677 payload
, payload_len
, hop
->prev
) < 0)
678 return 0; /* circuit is closed */
680 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
685 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
686 * something has also gone wrong with our network: notify the user,
687 * and abandon all not-yet-used circuits. */
689 circuit_note_clock_jumped(int seconds_elapsed
)
691 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
692 log(severity
, LD_GENERAL
, "Your system clock just jumped %d seconds %s; "
693 "assuming established circuits no longer work.",
694 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
,
695 seconds_elapsed
>=0 ? "forward" : "backward");
696 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%d",
698 has_completed_circuit
=0; /* so it'll log when it works again */
699 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
701 circuit_mark_all_unused_circs();
702 circuit_expire_all_dirty_circs();
705 /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
706 * sure we're connected to the next hop, and pass it the onion skin using
707 * a create cell. Return -1 if we want to warn and tear down the circuit,
711 circuit_extend(cell_t
*cell
, circuit_t
*circ
)
713 or_connection_t
*n_conn
;
716 char *id_digest
=NULL
;
719 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
720 "n_conn already set. Bug/attack. Closing.");
724 if (!server_mode(get_options())) {
725 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
726 "Got an extend cell, but running as a client. Closing.");
730 relay_header_unpack(&rh
, cell
->payload
);
732 if (rh
.length
< 4+2+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
) {
733 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
734 "Wrong length %d on extend cell. Closing circuit.",
739 circ
->n_addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
740 circ
->n_port
= ntohs(get_uint16(cell
->payload
+RELAY_HEADER_SIZE
+4));
742 onionskin
= cell
->payload
+RELAY_HEADER_SIZE
+4+2;
743 id_digest
= cell
->payload
+RELAY_HEADER_SIZE
+4+2+ONIONSKIN_CHALLENGE_LEN
;
744 n_conn
= connection_or_get_by_identity_digest(id_digest
);
746 /* If we don't have an open conn, or the conn we have is obsolete
747 * (i.e. old or broken) and the other side will let us make a second
748 * connection without dropping it immediately... */
749 if (!n_conn
|| n_conn
->_base
.state
!= OR_CONN_STATE_OPEN
||
750 (n_conn
->_base
.or_is_obsolete
&&
751 router_digest_version_as_new_as(id_digest
,"0.1.1.9-alpha-cvs"))) {
753 char tmpbuf
[INET_NTOA_BUF_LEN
];
754 in
.s_addr
= htonl(circ
->n_addr
);
755 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
756 log_info(LD_CIRC
|LD_OR
,"Next router (%s:%d) not connected. Connecting.",
757 tmpbuf
, circ
->n_port
);
759 circ
->onionskin
= tor_malloc(ONIONSKIN_CHALLENGE_LEN
);
760 memcpy(circ
->onionskin
, onionskin
, ONIONSKIN_CHALLENGE_LEN
);
761 circuit_set_state(circ
, CIRCUIT_STATE_OR_WAIT
);
763 /* imprint the circuit with its future n_conn->id */
764 memcpy(circ
->n_conn_id_digest
, id_digest
, DIGEST_LEN
);
766 if (n_conn
&& !n_conn
->_base
.or_is_obsolete
) {
767 circ
->n_addr
= n_conn
->_base
.addr
;
768 circ
->n_port
= n_conn
->_base
.port
;
770 /* we should try to open a connection */
771 n_conn
= connection_or_connect(circ
->n_addr
, circ
->n_port
, id_digest
);
773 log_info(LD_CIRC
,"Launching n_conn failed. Closing circuit.");
774 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
777 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
779 /* return success. The onion/circuit/etc will be taken care of
780 * automatically (may already have been) whenever n_conn reaches
781 * OR_CONN_STATE_OPEN.
786 /* these may be different if the router connected to us from elsewhere */
787 circ
->n_addr
= n_conn
->_base
.addr
;
788 circ
->n_port
= n_conn
->_base
.port
;
790 circ
->n_conn
= n_conn
;
791 memcpy(circ
->n_conn_id_digest
, n_conn
->identity_digest
, DIGEST_LEN
);
792 log_debug(LD_CIRC
,"n_conn is %s:%u",
793 n_conn
->_base
.address
,n_conn
->_base
.port
);
795 if (circuit_deliver_create_cell(circ
, CELL_CREATE
, onionskin
) < 0)
800 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
801 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
803 * - 20 to initialize f_digest
804 * - 20 to initialize b_digest
805 * - 16 to key f_crypto
806 * - 16 to key b_crypto
808 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
811 circuit_init_cpath_crypto(crypt_path_t
*cpath
, const char *key_data
,
814 crypto_digest_env_t
*tmp_digest
;
815 crypto_cipher_env_t
*tmp_crypto
;
818 tor_assert(key_data
);
819 tor_assert(!(cpath
->f_crypto
|| cpath
->b_crypto
||
820 cpath
->f_digest
|| cpath
->b_digest
));
822 cpath
->f_digest
= crypto_new_digest_env();
823 crypto_digest_add_bytes(cpath
->f_digest
, key_data
, DIGEST_LEN
);
824 cpath
->b_digest
= crypto_new_digest_env();
825 crypto_digest_add_bytes(cpath
->b_digest
, key_data
+DIGEST_LEN
, DIGEST_LEN
);
827 if (!(cpath
->f_crypto
=
828 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
),1))) {
829 log_warn(LD_BUG
,"Forward cipher initialization failed.");
832 if (!(cpath
->b_crypto
=
833 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
)+CIPHER_KEY_LEN
,0))) {
834 log_warn(LD_BUG
,"Backward cipher initialization failed.");
839 tmp_digest
= cpath
->f_digest
;
840 cpath
->f_digest
= cpath
->b_digest
;
841 cpath
->b_digest
= tmp_digest
;
842 tmp_crypto
= cpath
->f_crypto
;
843 cpath
->f_crypto
= cpath
->b_crypto
;
844 cpath
->b_crypto
= tmp_crypto
;
850 /** A created or extended cell came back to us on the circuit, and it included
851 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
852 * contains (the second DH key, plus KH). If <b>reply_type</b> is
853 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
855 * Calculate the appropriate keys and digests, make sure KH is
856 * correct, and initialize this hop of the cpath.
858 * Return - reason if we want to mark circ for close, else return 0.
861 circuit_finish_handshake(origin_circuit_t
*circ
, uint8_t reply_type
,
864 char keys
[CPATH_KEY_MATERIAL_LEN
];
867 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
)
870 hop
= onion_next_hop_in_cpath(circ
->cpath
);
871 if (!hop
) { /* got an extended when we're all done? */
872 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
873 return - END_CIRC_REASON_TORPROTOCOL
;
876 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
878 if (reply_type
== CELL_CREATED
&& hop
->dh_handshake_state
) {
879 if (onion_skin_client_handshake(hop
->dh_handshake_state
, reply
, keys
,
880 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
881 log_warn(LD_CIRC
,"onion_skin_client_handshake failed.");
882 return -END_CIRC_REASON_TORPROTOCOL
;
884 /* Remember hash of g^xy */
885 memcpy(hop
->handshake_digest
, reply
+DH_KEY_LEN
, DIGEST_LEN
);
886 } else if (reply_type
== CELL_CREATED_FAST
&& !hop
->dh_handshake_state
) {
887 if (fast_client_handshake(hop
->fast_handshake_state
, reply
, keys
,
888 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
889 log_warn(LD_CIRC
,"fast_client_handshake failed.");
890 return -END_CIRC_REASON_TORPROTOCOL
;
892 memcpy(hop
->handshake_digest
, reply
+DIGEST_LEN
, DIGEST_LEN
);
894 log_warn(LD_PROTOCOL
,"CREATED cell type did not match CREATE cell type.");
895 return -END_CIRC_REASON_TORPROTOCOL
;
898 if (hop
->dh_handshake_state
) {
899 crypto_dh_free(hop
->dh_handshake_state
); /* don't need it anymore */
900 hop
->dh_handshake_state
= NULL
;
902 memset(hop
->fast_handshake_state
, 0, sizeof(hop
->fast_handshake_state
));
904 if (circuit_init_cpath_crypto(hop
, keys
, 0)<0) {
905 return -END_CIRC_REASON_TORPROTOCOL
;
908 hop
->state
= CPATH_STATE_OPEN
;
909 log_info(LD_CIRC
,"Finished building %scircuit hop:",
910 (reply_type
== CELL_CREATED_FAST
) ? "fast " : "");
911 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
912 control_event_circuit_status(circ
, CIRC_EVENT_EXTENDED
, 0);
917 /** We received a relay truncated cell on circ.
919 * Since we don't ask for truncates currently, getting a truncated
920 * means that a connection broke or an extend failed. For now,
921 * just give up: for circ to close, and return 0.
924 circuit_truncated(origin_circuit_t
*circ
, crypt_path_t
*layer
)
926 // crypt_path_t *victim;
927 // connection_t *stream;
932 /* XXX Since we don't ask for truncates currently, getting a truncated
933 * means that a connection broke or an extend failed. For now,
936 circuit_mark_for_close(TO_CIRCUIT(circ
),
937 END_CIRC_REASON_FLAG_REMOTE
|END_CIRC_REASON_OR_CONN_CLOSED
);
941 while (layer
->next
!= circ
->cpath
) {
942 /* we need to clear out layer->next */
943 victim
= layer
->next
;
944 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
946 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
947 if (stream
->cpath_layer
== victim
) {
948 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
950 /* no need to send 'end' relay cells,
951 * because the other side's already dead
953 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
957 layer
->next
= victim
->next
;
958 circuit_free_cpath_node(victim
);
961 log_info(LD_CIRC
, "finished");
966 /** Given a response payload and keys, initialize, then send a created
970 onionskin_answer(or_circuit_t
*circ
, uint8_t cell_type
, const char *payload
,
974 crypt_path_t
*tmp_cpath
;
976 tmp_cpath
= tor_malloc_zero(sizeof(crypt_path_t
));
977 tmp_cpath
->magic
= CRYPT_PATH_MAGIC
;
979 memset(&cell
, 0, sizeof(cell_t
));
980 cell
.command
= cell_type
;
981 cell
.circ_id
= circ
->p_circ_id
;
983 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
985 memcpy(cell
.payload
, payload
,
986 cell_type
== CELL_CREATED
? ONIONSKIN_REPLY_LEN
: DIGEST_LEN
*2);
988 log_debug(LD_CIRC
,"init digest forward 0x%.8x, backward 0x%.8x.",
989 (unsigned int)*(uint32_t*)(keys
),
990 (unsigned int)*(uint32_t*)(keys
+20));
991 if (circuit_init_cpath_crypto(tmp_cpath
, keys
, 0)<0) {
992 log_warn(LD_BUG
,"Circuit initialization failed");
996 circ
->n_digest
= tmp_cpath
->f_digest
;
997 circ
->n_crypto
= tmp_cpath
->f_crypto
;
998 circ
->p_digest
= tmp_cpath
->b_digest
;
999 circ
->p_crypto
= tmp_cpath
->b_crypto
;
1000 tmp_cpath
->magic
= 0;
1001 tor_free(tmp_cpath
);
1003 if (cell_type
== CELL_CREATED
)
1004 memcpy(circ
->handshake_digest
, cell
.payload
+DH_KEY_LEN
, DIGEST_LEN
);
1006 memcpy(circ
->handshake_digest
, cell
.payload
+DIGEST_LEN
, DIGEST_LEN
);
1008 circ
->is_first_hop
= (cell_type
== CELL_CREATED_FAST
);
1010 append_cell_to_circuit_queue(TO_CIRCUIT(circ
),
1011 circ
->p_conn
, &cell
, CELL_DIRECTION_IN
);
1012 log_debug(LD_CIRC
,"Finished sending 'created' cell.");
1014 if (!is_local_IP(circ
->p_conn
->_base
.addr
) &&
1015 !connection_or_nonopen_was_started_here(circ
->p_conn
)) {
1016 /* record that we could process create cells from a non-local conn
1017 * that we didn't initiate; presumably this means that create cells
1018 * can reach us too. */
1019 router_orport_found_reachable();
1025 /** Choose a length for a circuit of purpose <b>purpose</b>.
1026 * Default length is 3 + the number of endpoints that would give something
1027 * away. If the routerlist <b>routers</b> doesn't have enough routers
1028 * to handle the desired path length, return as large a path length as
1029 * is feasible, except if it's less than 2, in which case return -1.
1032 new_route_len(uint8_t purpose
, extend_info_t
*exit
,
1033 smartlist_t
*routers
)
1035 int num_acceptable_routers
;
1038 tor_assert(routers
);
1045 purpose
!= CIRCUIT_PURPOSE_TESTING
&&
1046 purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
1049 log_debug(LD_CIRC
,"Chosen route length %d (%d routers available).",
1050 routelen
, smartlist_len(routers
));
1052 num_acceptable_routers
= count_acceptable_routers(routers
);
1054 if (num_acceptable_routers
< 2) {
1056 "Not enough acceptable routers (%d). Discarding this circuit.",
1057 num_acceptable_routers
);
1061 if (num_acceptable_routers
< routelen
) {
1062 log_info(LD_CIRC
,"Not enough routers: cutting routelen from %d to %d.",
1063 routelen
, num_acceptable_routers
);
1064 routelen
= num_acceptable_routers
;
1070 /** Fetch the list of predicted ports, dup it into a smartlist of
1071 * uint16_t's, remove the ones that are already handled by an
1072 * existing circuit, and return it.
1074 static smartlist_t
*
1075 circuit_get_unhandled_ports(time_t now
)
1077 smartlist_t
*source
= rep_hist_get_predicted_ports(now
);
1078 smartlist_t
*dest
= smartlist_create();
1082 for (i
= 0; i
< smartlist_len(source
); ++i
) {
1083 tmp
= tor_malloc(sizeof(uint16_t));
1084 memcpy(tmp
, smartlist_get(source
, i
), sizeof(uint16_t));
1085 smartlist_add(dest
, tmp
);
1088 circuit_remove_handled_ports(dest
);
1092 /** Return 1 if we already have circuits present or on the way for
1093 * all anticipated ports. Return 0 if we should make more.
1095 * If we're returning 0, set need_uptime and need_capacity to
1096 * indicate any requirements that the unhandled ports have.
1099 circuit_all_predicted_ports_handled(time_t now
, int *need_uptime
,
1104 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
1105 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
1106 tor_assert(need_uptime
);
1107 tor_assert(need_capacity
);
1108 enough
= (smartlist_len(sl
) == 0);
1109 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
1110 port
= smartlist_get(sl
, i
);
1111 if (smartlist_string_num_isin(LongLivedServices
, *port
))
1119 /** Return 1 if <b>router</b> can handle one or more of the ports in
1120 * <b>needed_ports</b>, else return 0.
1123 router_handles_some_port(routerinfo_t
*router
, smartlist_t
*needed_ports
)
1128 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
1129 addr_policy_result_t r
;
1130 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
1132 r
= compare_addr_to_addr_policy(0, port
, router
->exit_policy
);
1133 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
1139 /** Return true iff <b>conn</b> needs another general circuit to be
1142 ap_stream_wants_exit_attention(connection_t
*conn
)
1144 if (conn
->type
== CONN_TYPE_AP
&&
1145 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
1146 !conn
->marked_for_close
&&
1147 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
1148 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn
), 0,
1149 MIN_CIRCUITS_HANDLING_STREAM
))
1154 /** Return a pointer to a suitable router to be the exit node for the
1155 * general-purpose circuit we're about to build.
1157 * Look through the connection array, and choose a router that maximizes
1158 * the number of pending streams that can exit from this router.
1160 * Return NULL if we can't find any suitable routers.
1162 static routerinfo_t
*
1163 choose_good_exit_server_general(routerlist_t
*dir
, int need_uptime
,
1168 int n_pending_connections
= 0;
1169 smartlist_t
*connections
;
1170 int best_support
= -1;
1171 int n_best_support
=0;
1172 smartlist_t
*sl
, *preferredexits
, *excludedexits
;
1173 routerinfo_t
*router
;
1174 or_options_t
*options
= get_options();
1176 connections
= get_connection_array();
1178 /* Count how many connections are waiting for a circuit to be built.
1179 * We use this for log messages now, but in the future we may depend on it.
1181 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1183 if (ap_stream_wants_exit_attention(conn
))
1184 ++n_pending_connections
;
1186 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1187 // n_pending_connections);
1188 /* Now we count, for each of the routers in the directory, how many
1189 * of the pending connections could possibly exit from that
1190 * router (n_supported[i]). (We can't be sure about cases where we
1191 * don't know the IP address of the pending connection.)
1193 n_supported
= tor_malloc(sizeof(int)*smartlist_len(dir
->routers
));
1194 for (i
= 0; i
< smartlist_len(dir
->routers
); ++i
) {/* iterate over routers */
1195 router
= smartlist_get(dir
->routers
, i
);
1196 if (router_is_me(router
)) {
1197 n_supported
[i
] = -1;
1198 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1199 /* XXX there's probably a reverse predecessor attack here, but
1200 * it's slow. should we take this out? -RD
1204 if (!router
->is_running
|| router
->is_bad_exit
) {
1205 n_supported
[i
] = -1;
1206 continue; /* skip routers that are known to be down or bad exits */
1208 if (router_is_unreliable(router
, need_uptime
, need_capacity
, 0)) {
1209 n_supported
[i
] = -1;
1210 continue; /* skip routers that are not suitable */
1212 if (!(router
->is_valid
|| options
->_AllowInvalid
& ALLOW_INVALID_EXIT
)) {
1213 /* if it's invalid and we don't want it */
1214 n_supported
[i
] = -1;
1215 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1216 // router->nickname, i);
1217 continue; /* skip invalid routers */
1219 if (router_exit_policy_rejects_all(router
)) {
1220 n_supported
[i
] = -1;
1221 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1222 // router->nickname, i);
1223 continue; /* skip routers that reject all */
1226 /* iterate over connections */
1227 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1229 if (!ap_stream_wants_exit_attention(conn
))
1230 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1231 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn
), router
)) {
1233 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1234 // router->nickname, i, n_supported[i]);
1236 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1237 // router->nickname, i);
1239 }); /* End looping over connections. */
1240 if (n_supported
[i
] > best_support
) {
1241 /* If this router is better than previous ones, remember its index
1242 * and goodness, and start counting how many routers are this good. */
1243 best_support
= n_supported
[i
]; n_best_support
=1;
1244 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1245 // router->nickname);
1246 } else if (n_supported
[i
] == best_support
) {
1247 /* If this router is _as good_ as the best one, just increment the
1248 * count of equally good routers.*/
1253 "Found %d servers that might support %d/%d pending connections.",
1254 n_best_support
, best_support
>= 0 ? best_support
: 0,
1255 n_pending_connections
);
1257 preferredexits
= smartlist_create();
1258 add_nickname_list_to_smartlist(preferredexits
,options
->ExitNodes
,1);
1260 excludedexits
= smartlist_create();
1261 add_nickname_list_to_smartlist(excludedexits
,options
->ExcludeNodes
,0);
1263 sl
= smartlist_create();
1265 /* If any routers definitely support any pending connections, choose one
1267 if (best_support
> 0) {
1268 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++)
1269 if (n_supported
[i
] == best_support
)
1270 smartlist_add(sl
, smartlist_get(dir
->routers
, i
));
1272 smartlist_subtract(sl
,excludedexits
);
1273 if (options
->StrictExitNodes
|| smartlist_overlap(sl
,preferredexits
))
1274 smartlist_intersect(sl
,preferredexits
);
1275 router
= routerlist_sl_choose_by_bandwidth(sl
, WEIGHT_FOR_EXIT
);
1277 /* Either there are no pending connections, or no routers even seem to
1278 * possibly support any of them. Choose a router at random that satisfies
1279 * at least one predicted exit port. */
1282 smartlist_t
*needed_ports
;
1284 if (best_support
== -1) {
1285 if (need_uptime
|| need_capacity
) {
1287 "We couldn't find any live%s%s routers; falling back "
1288 "to list of all routers.",
1289 need_capacity
?", fast":"",
1290 need_uptime
?", stable":"");
1291 smartlist_free(preferredexits
);
1292 smartlist_free(excludedexits
);
1294 tor_free(n_supported
);
1295 return choose_good_exit_server_general(dir
, 0, 0);
1297 log_notice(LD_CIRC
, "All routers are down or won't exit -- choosing a "
1298 "doomed exit at random.");
1300 needed_ports
= circuit_get_unhandled_ports(time(NULL
));
1301 for (try = 0; try < 2; try++) {
1302 /* try once to pick only from routers that satisfy a needed port,
1303 * then if there are none, pick from any that support exiting. */
1304 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++) {
1305 router
= smartlist_get(dir
->routers
, i
);
1306 if (n_supported
[i
] != -1 &&
1307 (try || router_handles_some_port(router
, needed_ports
))) {
1308 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1309 // try, router->nickname);
1310 smartlist_add(sl
, router
);
1314 smartlist_subtract(sl
,excludedexits
);
1315 if (options
->StrictExitNodes
|| smartlist_overlap(sl
,preferredexits
))
1316 smartlist_intersect(sl
,preferredexits
);
1317 /* XXX sometimes the above results in null, when the requested
1318 * exit node is down. we should pick it anyway. */
1319 router
= routerlist_sl_choose_by_bandwidth(sl
, WEIGHT_FOR_EXIT
);
1323 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
1324 smartlist_free(needed_ports
);
1327 smartlist_free(preferredexits
);
1328 smartlist_free(excludedexits
);
1330 tor_free(n_supported
);
1332 log_info(LD_CIRC
, "Chose exit server '%s'", router
->nickname
);
1335 if (options
->StrictExitNodes
) {
1337 "No specified exit routers seem to be running, and "
1338 "StrictExitNodes is set: can't choose an exit.");
1343 /** Return a pointer to a suitable router to be the exit node for the
1344 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1345 * if no router is suitable).
1347 * For general-purpose circuits, pass it off to
1348 * choose_good_exit_server_general()
1350 * For client-side rendezvous circuits, choose a random node, weighted
1351 * toward the preferences in 'options'.
1353 static routerinfo_t
*
1354 choose_good_exit_server(uint8_t purpose
, routerlist_t
*dir
,
1355 int need_uptime
, int need_capacity
, int is_internal
)
1357 or_options_t
*options
= get_options();
1359 case CIRCUIT_PURPOSE_C_GENERAL
:
1360 if (is_internal
) /* pick it like a middle hop */
1361 return router_choose_random_node(NULL
, get_options()->ExcludeNodes
,
1362 NULL
, need_uptime
, need_capacity
, 0,
1363 get_options()->_AllowInvalid
& ALLOW_INVALID_MIDDLE
, 0, 0);
1365 return choose_good_exit_server_general(dir
,need_uptime
,need_capacity
);
1366 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1367 return router_choose_random_node(
1368 options
->RendNodes
, options
->RendExcludeNodes
,
1369 NULL
, need_uptime
, need_capacity
, 0,
1370 options
->_AllowInvalid
& ALLOW_INVALID_RENDEZVOUS
, 0, 0);
1372 log_warn(LD_BUG
,"Unhandled purpose %d", purpose
);
1373 tor_fragile_assert();
1377 /** Decide a suitable length for circ's cpath, and pick an exit
1378 * router (or use <b>exit</b> if provided). Store these in the
1379 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1381 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1383 cpath_build_state_t
*state
= circ
->build_state
;
1384 routerlist_t
*rl
= router_get_routerlist();
1386 if (state
->onehop_tunnel
) {
1387 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel.");
1388 state
->desired_path_len
= 1;
1390 int r
= new_route_len(circ
->_base
.purpose
, exit
, rl
->routers
);
1391 if (r
< 1) /* must be at least 1 */
1393 state
->desired_path_len
= r
;
1396 if (exit
) { /* the circuit-builder pre-requested one */
1397 log_info(LD_CIRC
,"Using requested exit node '%s'", exit
->nickname
);
1398 exit
= extend_info_dup(exit
);
1399 } else { /* we have to decide one */
1400 routerinfo_t
*router
=
1401 choose_good_exit_server(circ
->_base
.purpose
, rl
, state
->need_uptime
,
1402 state
->need_capacity
, state
->is_internal
);
1404 log_warn(LD_CIRC
,"failed to choose an exit server");
1407 exit
= extend_info_from_router(router
);
1409 state
->chosen_exit
= exit
;
1413 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1414 * hop to the cpath reflecting this. Don't send the next extend cell --
1415 * the caller will do this if it wants to.
1418 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1420 cpath_build_state_t
*state
;
1424 state
= circ
->build_state
;
1426 if (state
->chosen_exit
)
1427 extend_info_free(state
->chosen_exit
);
1428 state
->chosen_exit
= extend_info_dup(exit
);
1430 ++circ
->build_state
->desired_path_len
;
1431 onion_append_hop(&circ
->cpath
, exit
);
1435 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1436 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1437 * send the next extend cell to begin connecting to that hop.
1440 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1443 circuit_append_new_exit(circ
, exit
);
1444 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
1445 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
1446 log_warn(LD_CIRC
, "Couldn't extend circuit to new point '%s'.",
1448 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
1454 /** Return the number of routers in <b>routers</b> that are currently up
1455 * and available for building circuits through.
1458 count_acceptable_routers(smartlist_t
*routers
)
1464 n
= smartlist_len(routers
);
1466 r
= smartlist_get(routers
, i
);
1467 // log_debug(LD_CIRC,
1468 // "Contemplating whether router %d (%s) is a new option.",
1470 if (r
->is_running
== 0) {
1471 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1474 if (r
->is_valid
== 0) {
1475 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1477 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1478 * allows this node in some places, then we're getting an inaccurate
1479 * count. For now, be conservative and don't count it. But later we
1480 * should try to be smarter. */
1483 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1485 ; /* C requires an explicit statement after the label */
1491 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1492 * This function is used to extend cpath by another hop.
1495 onion_append_to_cpath(crypt_path_t
**head_ptr
, crypt_path_t
*new_hop
)
1498 new_hop
->next
= (*head_ptr
);
1499 new_hop
->prev
= (*head_ptr
)->prev
;
1500 (*head_ptr
)->prev
->next
= new_hop
;
1501 (*head_ptr
)->prev
= new_hop
;
1503 *head_ptr
= new_hop
;
1504 new_hop
->prev
= new_hop
->next
= new_hop
;
1508 /** Pick a random server digest that's running a Tor version that
1509 * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
1510 * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
1511 * probably already connected to them.
1513 * We only return one, so this doesn't become stupid when the
1514 * whole network has upgraded. */
1516 compute_preferred_testing_list(const char *answer
)
1518 smartlist_t
*choices
;
1519 routerlist_t
*rl
= router_get_routerlist();
1520 routerinfo_t
*router
;
1523 if (answer
) /* they have one in mind -- easy */
1524 return tor_strdup(answer
);
1526 choices
= smartlist_create();
1527 /* now count up our choices */
1528 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
1529 if (r
->is_running
&& r
->is_valid
&&
1530 ((tor_version_as_new_as(r
->platform
,"0.1.1.21-cvs") &&
1531 !tor_version_as_new_as(r
->platform
,"0.1.2.0-alpha-cvs")) ||
1532 tor_version_as_new_as(r
->platform
,"0.1.2.1-alpha")) &&
1533 !is_local_IP(r
->addr
) &&
1534 !router_get_trusteddirserver_by_digest(r
->cache_info
.identity_digest
))
1535 smartlist_add(choices
, r
));
1536 router
= smartlist_choose(choices
);
1537 smartlist_free(choices
);
1539 log_info(LD_CIRC
, "Looking for middle server that doesn't have the "
1540 "reachability bug, but didn't find one. Oh well.");
1543 log_info(LD_CIRC
, "Looking for middle server that doesn't have the "
1544 "reachability bug, and chose '%s'. Great.", router
->nickname
);
1545 s
= tor_malloc(HEX_DIGEST_LEN
+2);
1547 base16_encode(s
+1, HEX_DIGEST_LEN
+1,
1548 router
->cache_info
.identity_digest
, DIGEST_LEN
);
1552 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1553 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1554 * to length <b>cur_len</b> to decide a suitable middle hop for a
1555 * circuit. In particular, make sure we don't pick the exit node or its
1556 * family, and make sure we don't duplicate any previous nodes or their
1558 static routerinfo_t
*
1559 choose_good_middle_server(uint8_t purpose
,
1560 cpath_build_state_t
*state
,
1565 routerinfo_t
*r
, *choice
;
1566 crypt_path_t
*cpath
;
1567 smartlist_t
*excluded
;
1568 or_options_t
*options
= get_options();
1569 char *preferred
= NULL
;
1570 tor_assert(_CIRCUIT_PURPOSE_MIN
<= purpose
&&
1571 purpose
<= _CIRCUIT_PURPOSE_MAX
);
1573 log_debug(LD_CIRC
, "Contemplating intermediate hop: random choice.");
1574 excluded
= smartlist_create();
1575 if ((r
= build_state_get_exit_router(state
))) {
1576 smartlist_add(excluded
, r
);
1577 routerlist_add_family(excluded
, r
);
1579 if ((r
= routerlist_find_my_routerinfo())) {
1580 smartlist_add(excluded
, r
);
1581 routerlist_add_family(excluded
, r
);
1583 for (i
= 0, cpath
= head
; i
< cur_len
; ++i
, cpath
=cpath
->next
) {
1584 if ((r
= router_get_by_digest(cpath
->extend_info
->identity_digest
))) {
1585 smartlist_add(excluded
, r
);
1586 routerlist_add_family(excluded
, r
);
1589 if (purpose
== CIRCUIT_PURPOSE_TESTING
)
1590 preferred
= compute_preferred_testing_list(options
->TestVia
);
1591 choice
= router_choose_random_node(preferred
,
1592 options
->ExcludeNodes
, excluded
,
1593 state
->need_uptime
, state
->need_capacity
, 0,
1594 options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
, 0, 0);
1595 tor_free(preferred
);
1596 smartlist_free(excluded
);
1600 /** Pick a good entry server for the circuit to be built according to
1601 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1602 * router (if we're an OR), and respect firewall settings; if we're
1603 * configured to use entry guards, return one.
1605 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1606 * guard, not for any particular circuit.
1608 static routerinfo_t
*
1609 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
)
1611 routerinfo_t
*r
, *choice
;
1612 smartlist_t
*excluded
;
1613 or_options_t
*options
= get_options();
1614 (void)purpose
; /* not used yet. */
1616 if (state
&& options
->UseEntryGuards
) {
1617 return choose_random_entry(state
);
1620 excluded
= smartlist_create();
1622 if (state
&& (r
= build_state_get_exit_router(state
))) {
1623 smartlist_add(excluded
, r
);
1624 routerlist_add_family(excluded
, r
);
1626 if ((r
= routerlist_find_my_routerinfo())) {
1627 smartlist_add(excluded
, r
);
1628 routerlist_add_family(excluded
, r
);
1630 if (firewall_is_fascist_or()) {
1631 /* exclude all ORs that listen on the wrong port */
1632 routerlist_t
*rl
= router_get_routerlist();
1635 for (i
=0; i
< smartlist_len(rl
->routers
); i
++) {
1636 r
= smartlist_get(rl
->routers
, i
);
1637 if (!fascist_firewall_allows_address_or(r
->addr
,r
->or_port
))
1638 smartlist_add(excluded
, r
);
1641 /* and exclude current entry guards, if applicable */
1642 if (options
->UseEntryGuards
&& entry_guards
) {
1643 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1645 if ((r
= router_get_by_digest(entry
->identity
)))
1646 smartlist_add(excluded
, r
);
1650 choice
= router_choose_random_node(
1651 NULL
, options
->ExcludeNodes
,
1652 excluded
, state
? state
->need_uptime
: 0,
1653 state
? state
->need_capacity
: 0,
1655 options
->_AllowInvalid
& ALLOW_INVALID_ENTRY
, 0, 0);
1656 smartlist_free(excluded
);
1660 /** Return the first non-open hop in cpath, or return NULL if all
1662 static crypt_path_t
*
1663 onion_next_hop_in_cpath(crypt_path_t
*cpath
)
1665 crypt_path_t
*hop
= cpath
;
1667 if (hop
->state
!= CPATH_STATE_OPEN
)
1670 } while (hop
!= cpath
);
1674 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1675 * based on <b>state</b>. Append the hop info to head_ptr.
1678 onion_extend_cpath(origin_circuit_t
*circ
)
1680 uint8_t purpose
= circ
->_base
.purpose
;
1681 cpath_build_state_t
*state
= circ
->build_state
;
1682 int cur_len
= circuit_get_cpath_len(circ
);
1683 extend_info_t
*info
= NULL
;
1685 if (cur_len
>= state
->desired_path_len
) {
1686 log_debug(LD_CIRC
, "Path is complete: %d steps long",
1687 state
->desired_path_len
);
1691 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
1692 state
->desired_path_len
);
1694 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
1695 info
= extend_info_dup(state
->chosen_exit
);
1696 } else if (cur_len
== 0) { /* picking first node */
1697 routerinfo_t
*r
= choose_good_entry_server(purpose
, state
);
1699 info
= extend_info_from_router(r
);
1702 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
1704 info
= extend_info_from_router(r
);
1708 log_warn(LD_CIRC
,"Failed to find node for hop %d of our path. Discarding "
1709 "this circuit.", cur_len
);
1713 log_debug(LD_CIRC
,"Chose router %s for hop %d (exit is %s)",
1714 info
->nickname
, cur_len
+1, build_state_get_exit_nickname(state
));
1716 onion_append_hop(&circ
->cpath
, info
);
1717 extend_info_free(info
);
1721 /** Create a new hop, annotate it with information about its
1722 * corresponding router <b>choice</b>, and append it to the
1723 * end of the cpath <b>head_ptr</b>. */
1725 onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
)
1727 crypt_path_t
*hop
= tor_malloc_zero(sizeof(crypt_path_t
));
1729 /* link hop into the cpath, at the end. */
1730 onion_append_to_cpath(head_ptr
, hop
);
1732 hop
->magic
= CRYPT_PATH_MAGIC
;
1733 hop
->state
= CPATH_STATE_CLOSED
;
1735 hop
->extend_info
= extend_info_dup(choice
);
1737 hop
->package_window
= CIRCWINDOW_START
;
1738 hop
->deliver_window
= CIRCWINDOW_START
;
1743 /** Allocate a new extend_info object based on the various arguments. */
1745 extend_info_alloc(const char *nickname
, const char *digest
,
1746 crypto_pk_env_t
*onion_key
,
1747 uint32_t addr
, uint16_t port
)
1749 extend_info_t
*info
= tor_malloc_zero(sizeof(extend_info_t
));
1750 memcpy(info
->identity_digest
, digest
, DIGEST_LEN
);
1752 strlcpy(info
->nickname
, nickname
, sizeof(info
->nickname
));
1754 info
->onion_key
= crypto_pk_dup_key(onion_key
);
1760 /** Allocate and return a new extend_info_t that can be used to build a
1761 * circuit to or through the router <b>r</b>. */
1763 extend_info_from_router(routerinfo_t
*r
)
1766 return extend_info_alloc(r
->nickname
, r
->cache_info
.identity_digest
,
1767 r
->onion_pkey
, r
->addr
, r
->or_port
);
1771 /** What router purpose is <b>digest</b>?
1772 * It's a general purpose router unless it's on our bridges list.
1775 get_router_purpose_from_digest(char *digest
)
1777 if (digest_is_a_bridge(digest
))
1778 return ROUTER_PURPOSE_BRIDGE
;
1779 return ROUTER_PURPOSE_GENERAL
;
1784 /** Allocate and return a new extend_info_t that can be used to build a
1785 * circuit to or through the router <b>r</b>. */
1787 extend_info_from_routerstatus(routerstatus_t
*s
)
1790 /* routerstatus doesn't know onion_key; leave it NULL */
1791 return extend_info_alloc(s
->nickname
, s
->identity_digest
,
1792 NULL
, s
->addr
, s
->or_port
);
1793 // get_router_purpose_from_digest(s->identity_digest));
1797 /** Release storage held by an extend_info_t struct. */
1799 extend_info_free(extend_info_t
*info
)
1802 if (info
->onion_key
)
1803 crypto_free_pk_env(info
->onion_key
);
1807 /** Allocate and return a new extend_info_t with the same contents as
1810 extend_info_dup(extend_info_t
*info
)
1812 extend_info_t
*newinfo
;
1814 newinfo
= tor_malloc(sizeof(extend_info_t
));
1815 memcpy(newinfo
, info
, sizeof(extend_info_t
));
1816 if (info
->onion_key
)
1817 newinfo
->onion_key
= crypto_pk_dup_key(info
->onion_key
);
1819 newinfo
->onion_key
= NULL
;
1823 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1824 * If there is no chosen exit, or if we don't know the routerinfo_t for
1825 * the chosen exit, return NULL.
1828 build_state_get_exit_router(cpath_build_state_t
*state
)
1830 if (!state
|| !state
->chosen_exit
)
1832 return router_get_by_digest(state
->chosen_exit
->identity_digest
);
1835 /** Return the nickname for the chosen exit router in <b>state</b>. If
1836 * there is no chosen exit, or if we don't know the routerinfo_t for the
1837 * chosen exit, return NULL.
1840 build_state_get_exit_nickname(cpath_build_state_t
*state
)
1842 if (!state
|| !state
->chosen_exit
)
1844 return state
->chosen_exit
->nickname
;
1847 /** Check whether the entry guard <b>e</b> is usable, given the directory
1848 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1849 * configuration (in <b>options</b>). Set <b>e</b>->bad_since
1850 * accordingly. Return true iff the entry guard's status changes.
1852 * If it's not usable, set *<b>reason</b> to a static string explaining why.
1855 entry_guard_set_status(entry_guard_t
*e
, routerinfo_t
*ri
,
1856 time_t now
, or_options_t
*options
, const char **reason
)
1858 char buf
[HEX_DIGEST_LEN
+1];
1861 tor_assert(options
);
1865 /* Do we want to mark this guard as bad? */
1867 *reason
= "unlisted";
1868 else if (!ri
->is_running
)
1870 else if (options
->UseBridges
&& ri
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1871 *reason
= "not a bridge";
1872 else if (!options
->UseBridges
&& !ri
->is_possible_guard
&&
1873 !router_nickname_is_in_list(ri
, options
->EntryNodes
))
1874 *reason
= "not recommended as a guard";
1875 else if (router_nickname_is_in_list(ri
, options
->ExcludeNodes
))
1876 *reason
= "excluded";
1878 if (*reason
&& ! e
->bad_since
) {
1879 /* Router is newly bad. */
1880 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1881 log_info(LD_CIRC
, "Entry guard %s (%s) is %s: marking as unusable.",
1882 e
->nickname
, buf
, *reason
);
1885 control_event_guard(e
->nickname
, e
->identity
, "BAD");
1887 } else if (!*reason
&& e
->bad_since
) {
1888 /* There's nothing wrong with the router any more. */
1889 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1890 log_info(LD_CIRC
, "Entry guard %s (%s) is no longer unusable: "
1891 "marking as ok.", e
->nickname
, buf
);
1894 control_event_guard(e
->nickname
, e
->identity
, "GOOD");
1901 /** Return true iff enough time has passed since we last tried to connect
1902 * to the unreachable guard <b>e</b> that we're willing to try again. */
1904 entry_is_time_to_retry(entry_guard_t
*e
, time_t now
)
1907 if (e
->last_attempted
< e
->unreachable_since
)
1909 diff
= now
- e
->unreachable_since
;
1911 return now
> (e
->last_attempted
+ 60*60);
1912 else if (diff
< 3*24*60*60)
1913 return now
> (e
->last_attempted
+ 4*60*60);
1914 else if (diff
< 7*24*60*60)
1915 return now
> (e
->last_attempted
+ 18*60*60);
1917 return now
> (e
->last_attempted
+ 36*60*60);
1920 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1921 * working well enough that we are willing to use it as an entry
1922 * right now. (Else return NULL.) In particular, it must be
1923 * - Listed as either up or never yet contacted;
1924 * - Present in the routerlist;
1925 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1926 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1927 * (This check is currently redundant with the Guard flag, but in
1928 * the future that might change. Best to leave it in for now.)
1929 * - Allowed by our current ReachableORAddresses config option; and
1930 * - Currently thought to be reachable by us (unless assume_reachable
1933 static INLINE routerinfo_t
*
1934 entry_is_live(entry_guard_t
*e
, int need_uptime
, int need_capacity
,
1935 int assume_reachable
)
1940 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1941 if ((!assume_reachable
&& !e
->can_retry
) &&
1942 e
->unreachable_since
&& !entry_is_time_to_retry(e
, time(NULL
)))
1944 r
= router_get_by_digest(e
->identity
);
1947 if (get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1949 if (!get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_GENERAL
)
1951 if (router_is_unreliable(r
, need_uptime
, need_capacity
, 0))
1953 if (!fascist_firewall_allows_address_or(r
->addr
,r
->or_port
))
1958 /** Return the number of entry guards that we think are usable. */
1960 num_live_entry_guards(void)
1965 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1967 if (entry_is_live(entry
, 0, 1, 0))
1973 /** If <b>digest</b> matches the identity of any node in the
1974 * entry_guards list, return that node. Else return NULL. */
1975 static INLINE entry_guard_t
*
1976 is_an_entry_guard(const char *digest
)
1978 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1979 if (!memcmp(digest
, entry
->identity
, DIGEST_LEN
))
1985 /** Dump a description of our list of entry guards to the log at level
1986 * <b>severity</b>. */
1988 log_entry_guards(int severity
)
1990 smartlist_t
*elements
= smartlist_create();
1994 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
1996 tor_snprintf(buf
, sizeof(buf
), "%s (%s%s)",
1998 e
->bad_since
? "down " : "up ",
1999 e
->made_contact
? "made-contact" : "never-contacted");
2000 smartlist_add(elements
, tor_strdup(buf
));
2003 s
= smartlist_join_strings(elements
, ",", 0, NULL
);
2004 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
2005 smartlist_free(elements
);
2006 log_fn(severity
,LD_CIRC
,"%s",s
);
2010 /** Called when one or more guards that we would previously have used for some
2011 * purpose are no longer in use because a higher-priority guard has become
2014 control_event_guard_deferred(void)
2016 /* XXXX We don't actually have a good way to figure out _how many_ entries
2017 * are live for some purpose. We need an entry_is_even_slightly_live()
2018 * function for this to work right. NumEntryGuards isn't reliable: if we
2019 * need guards with weird properties, we can have more than that number
2024 or_options_t
*options
= get_options();
2027 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2029 if (entry_is_live(entry
, 0, 1, 0)) {
2030 if (n
++ == options
->NumEntryGuards
) {
2031 control_event_guard(entry
->nickname
, entry
->identity
, "DEFERRED");
2039 /** Add a new (preferably stable and fast) router to our
2040 * entry_guards list. Return a pointer to the router if we succeed,
2041 * or NULL if we can't find any more suitable entries.
2043 * If <b>chosen</b> is defined, use that one, and if it's not
2044 * already in our entry_guards list, put it at the *beginning*.
2045 * Else, put the one we pick at the end of the list. */
2046 static routerinfo_t
*
2047 add_an_entry_guard(routerinfo_t
*chosen
, int reset_status
)
2049 routerinfo_t
*router
;
2050 entry_guard_t
*entry
;
2054 entry
= is_an_entry_guard(router
->cache_info
.identity_digest
);
2057 entry
->bad_since
= 0;
2061 router
= choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL
, NULL
);
2065 entry
= tor_malloc_zero(sizeof(entry_guard_t
));
2066 log_info(LD_CIRC
, "Chose '%s' as new entry guard.", router
->nickname
);
2067 strlcpy(entry
->nickname
, router
->nickname
, sizeof(entry
->nickname
));
2068 memcpy(entry
->identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
2069 entry
->chosen_on_date
= start_of_month(time(NULL
));
2070 entry
->chosen_by_version
= tor_strdup(VERSION
);
2071 if (chosen
) /* prepend */
2072 smartlist_insert(entry_guards
, 0, entry
);
2074 smartlist_add(entry_guards
, entry
);
2075 control_event_guard(entry
->nickname
, entry
->identity
, "NEW");
2076 control_event_guard_deferred();
2077 log_entry_guards(LOG_INFO
);
2081 /** If the use of entry guards is configured, choose more entry guards
2082 * until we have enough in the list. */
2084 pick_entry_guards(void)
2086 or_options_t
*options
= get_options();
2089 tor_assert(entry_guards
);
2091 while (num_live_entry_guards() < options
->NumEntryGuards
) {
2092 if (!add_an_entry_guard(NULL
, 0))
2097 entry_guards_changed();
2100 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2101 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2102 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2104 /** Release all storage held by <b>e</b>. */
2106 entry_guard_free(entry_guard_t
*e
)
2109 tor_free(e
->chosen_by_version
);
2113 /** Remove any entry guard which was selected by an unknown version of Tor,
2114 * or which was selected by a version of Tor that's known to select
2115 * entry guards badly. */
2117 remove_obsolete_entry_guards(void)
2120 for (i
= 0; i
< smartlist_len(entry_guards
); ++i
) {
2121 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2122 const char *ver
= entry
->chosen_by_version
;
2123 const char *msg
= NULL
;
2125 int version_is_bad
= 0;
2127 msg
= "does not say what version of Tor it was selected by";
2129 } else if (tor_version_parse(ver
, &v
)) {
2130 msg
= "does not seem to be from any recognized version of Tor";
2132 } else if ((tor_version_as_new_as(ver
, "0.1.0.10-alpha") &&
2133 !tor_version_as_new_as(ver
, "0.1.2.16-dev")) ||
2134 (tor_version_as_new_as(ver
, "0.2.0.0-alpha") &&
2135 !tor_version_as_new_as(ver
, "0.2.0.6-alpha"))) {
2136 msg
= "was selected without regard for guard bandwidth";
2139 if (version_is_bad
) {
2140 char dbuf
[HEX_DIGEST_LEN
+1];
2142 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2143 log_notice(LD_CIRC
, "Entry guard '%s' (%s) %s. (Version=%s.) "
2145 entry
->nickname
, dbuf
, msg
, ver
?escaped(ver
):"none");
2146 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2147 entry_guard_free(entry
);
2148 smartlist_del_keeporder(entry_guards
, i
--);
2149 log_entry_guards(LOG_INFO
);
2154 return changed
? 1 : 0;
2157 /** Remove all entry guards that have been down or unlisted for so
2158 * long that we don't think they'll come up again. Return 1 if we
2159 * removed any, or 0 if we did nothing. */
2161 remove_dead_entry_guards(void)
2163 char dbuf
[HEX_DIGEST_LEN
+1];
2164 char tbuf
[ISO_TIME_LEN
+1];
2165 time_t now
= time(NULL
);
2169 for (i
= 0; i
< smartlist_len(entry_guards
); ) {
2170 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2171 if (entry
->bad_since
&&
2172 entry
->bad_since
+ ENTRY_GUARD_REMOVE_AFTER
< now
) {
2174 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2175 format_local_iso_time(tbuf
, entry
->bad_since
);
2176 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been down or unlisted "
2177 "since %s local time; removing.",
2178 entry
->nickname
, dbuf
, tbuf
);
2179 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2180 entry_guard_free(entry
);
2181 smartlist_del_keeporder(entry_guards
, i
);
2182 log_entry_guards(LOG_INFO
);
2187 return changed
? 1 : 0;
2190 /** A new directory or router-status has arrived; update the down/listed
2191 * status of the entry guards.
2193 * An entry is 'down' if the directory lists it as nonrunning.
2194 * An entry is 'unlisted' if the directory doesn't include it.
2196 * Don't call this on startup; only on a fresh download. Otherwise we'll
2197 * think that things are unlisted.
2200 entry_guards_compute_status(void)
2204 int severity
= LOG_INFO
;
2205 or_options_t
*options
;
2209 options
= get_options();
2213 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2215 routerinfo_t
*r
= router_get_by_digest(entry
->identity
);
2216 const char *reason
= NULL
;
2217 if (entry_guard_set_status(entry
, r
, now
, options
, &reason
))
2220 if (entry
->bad_since
)
2223 log_info(LD_CIRC
, "Summary: Entry '%s' is %s, %s%s, and %s.",
2225 entry
->unreachable_since
? "unreachable" : "reachable",
2226 entry
->bad_since
? "unusable: " : "usable",
2227 entry
->bad_since
? reason
: "",
2228 entry_is_live(entry
, 0, 1, 0) ? "live" : "not live");
2231 if (remove_dead_entry_guards())
2235 log_fn(severity
, LD_CIRC
, " (%d/%d entry guards are usable/new)",
2236 num_live_entry_guards(), smartlist_len(entry_guards
));
2237 log_entry_guards(LOG_INFO
);
2238 entry_guards_changed();
2242 /** Called when a connection to an OR with the identity digest <b>digest</b>
2243 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2244 * If the OR is an entry, change that entry's up/down status.
2245 * Return 0 normally, or -1 if we want to tear down the new connection.
2248 entry_guard_register_connect_status(const char *digest
, int succeeded
,
2252 int refuse_conn
= 0;
2253 int first_contact
= 0;
2254 entry_guard_t
*entry
= NULL
;
2256 char buf
[HEX_DIGEST_LEN
+1];
2261 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2263 if (!memcmp(e
->identity
, digest
, DIGEST_LEN
)) {
2273 base16_encode(buf
, sizeof(buf
), entry
->identity
, DIGEST_LEN
);
2276 if (entry
->unreachable_since
) {
2277 log_info(LD_CIRC
, "Entry guard '%s' (%s) is now reachable again. Good.",
2278 entry
->nickname
, buf
);
2279 entry
->can_retry
= 0;
2280 entry
->unreachable_since
= 0;
2281 entry
->last_attempted
= now
;
2282 control_event_guard(entry
->nickname
, entry
->identity
, "UP");
2285 if (!entry
->made_contact
) {
2286 entry
->made_contact
= 1;
2287 first_contact
= changed
= 1;
2289 } else { /* ! succeeded */
2290 if (!entry
->made_contact
) {
2291 /* We've never connected to this one. */
2293 "Connection to never-contacted entry guard '%s' (%s) failed. "
2294 "Removing from the list. %d/%d entry guards usable/new.",
2295 entry
->nickname
, buf
,
2296 num_live_entry_guards()-1, smartlist_len(entry_guards
)-1);
2297 entry_guard_free(entry
);
2298 smartlist_del_keeporder(entry_guards
, idx
);
2299 log_entry_guards(LOG_INFO
);
2301 } else if (!entry
->unreachable_since
) {
2302 log_info(LD_CIRC
, "Unable to connect to entry guard '%s' (%s). "
2303 "Marking as unreachable.", entry
->nickname
, buf
);
2304 entry
->unreachable_since
= entry
->last_attempted
= now
;
2305 control_event_guard(entry
->nickname
, entry
->identity
, "DOWN");
2307 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2309 char tbuf
[ISO_TIME_LEN
+1];
2310 format_iso_time(tbuf
, entry
->unreachable_since
);
2311 log_debug(LD_CIRC
, "Failed to connect to unreachable entry guard "
2312 "'%s' (%s). It has been unreachable since %s.",
2313 entry
->nickname
, buf
, tbuf
);
2314 entry
->last_attempted
= now
;
2315 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2319 if (first_contact
) {
2320 /* We've just added a new long-term entry guard. Perhaps the network just
2321 * came back? We should give our earlier entries another try too,
2322 * and close this connection so we don't use it before we've given
2323 * the others a shot. */
2324 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2327 if (e
->made_contact
) {
2328 routerinfo_t
*r
= entry_is_live(e
, 0, 1, 1);
2329 if (r
&& e
->unreachable_since
) {
2337 "Connected to new entry guard '%s' (%s). Marking earlier "
2338 "entry guards up. %d/%d entry guards usable/new.",
2339 entry
->nickname
, buf
,
2340 num_live_entry_guards(), smartlist_len(entry_guards
));
2341 log_entry_guards(LOG_INFO
);
2347 entry_guards_changed();
2348 return refuse_conn
? -1 : 0;
2351 /** When we try to choose an entry guard, should we parse and add
2352 * config's EntryNodes first? */
2353 static int should_add_entry_nodes
= 0;
2355 /** Called when the value of EntryNodes changes in our configuration. */
2357 entry_nodes_should_be_added(void)
2359 log_info(LD_CIRC
, "New EntryNodes config option detected. Will use.");
2360 should_add_entry_nodes
= 1;
2363 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2364 * of guard nodes, at the front. */
2366 entry_guards_prepend_from_config(void)
2368 or_options_t
*options
= get_options();
2369 smartlist_t
*entry_routers
, *entry_fps
;
2370 smartlist_t
*old_entry_guards_on_list
, *old_entry_guards_not_on_list
;
2371 tor_assert(entry_guards
);
2373 should_add_entry_nodes
= 0;
2375 if (!options
->EntryNodes
) {
2376 /* It's possible that a controller set EntryNodes, thus making
2377 * should_add_entry_nodes set, then cleared it again, all before the
2378 * call to choose_random_entry() that triggered us. If so, just return.
2383 log_info(LD_CIRC
,"Adding configured EntryNodes '%s'.",
2384 options
->EntryNodes
);
2386 entry_routers
= smartlist_create();
2387 entry_fps
= smartlist_create();
2388 old_entry_guards_on_list
= smartlist_create();
2389 old_entry_guards_not_on_list
= smartlist_create();
2391 /* Split entry guards into those on the list and those not. */
2392 add_nickname_list_to_smartlist(entry_routers
, options
->EntryNodes
, 0);
2393 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
,
2394 smartlist_add(entry_fps
,ri
->cache_info
.identity_digest
));
2395 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2396 if (smartlist_digest_isin(entry_fps
, e
->identity
))
2397 smartlist_add(old_entry_guards_on_list
, e
);
2399 smartlist_add(old_entry_guards_not_on_list
, e
);
2402 /* Remove all currently configured entry guards from entry_routers. */
2403 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2404 if (is_an_entry_guard(ri
->cache_info
.identity_digest
)) {
2405 SMARTLIST_DEL_CURRENT(entry_routers
, ri
);
2409 /* Now build the new entry_guards list. */
2410 smartlist_clear(entry_guards
);
2411 /* First, the previously configured guards that are in EntryNodes. */
2412 smartlist_add_all(entry_guards
, old_entry_guards_on_list
);
2413 /* Next, the rest of EntryNodes */
2414 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2415 add_an_entry_guard(ri
, 0);
2417 /* Finally, the remaining EntryNodes, unless we're strict */
2418 if (options
->StrictEntryNodes
) {
2419 SMARTLIST_FOREACH(old_entry_guards_not_on_list
, entry_guard_t
*, e
,
2420 entry_guard_free(e
));
2422 smartlist_add_all(entry_guards
, old_entry_guards_not_on_list
);
2425 smartlist_free(entry_routers
);
2426 smartlist_free(entry_fps
);
2427 smartlist_free(old_entry_guards_on_list
);
2428 smartlist_free(old_entry_guards_not_on_list
);
2429 entry_guards_changed();
2432 /** Return 1 if we're fine adding arbitrary routers out of the
2433 * directory to our entry guard list. Else return 0. */
2435 entry_list_can_grow(or_options_t
*options
)
2437 if (options
->StrictEntryNodes
)
2439 if (options
->UseBridges
)
2444 /** Pick a live (up and listed) entry guard from entry_guards. If
2445 * <b>state</b> is non-NULL, this is for a specific circuit --
2446 * make sure not to pick this circuit's exit or any node in the
2447 * exit's family. If <b>state</b> is NULL, we're looking for a random
2448 * guard (likely a bridge). */
2450 choose_random_entry(cpath_build_state_t
*state
)
2452 or_options_t
*options
= get_options();
2453 smartlist_t
*live_entry_guards
= smartlist_create();
2454 smartlist_t
*exit_family
= smartlist_create();
2455 routerinfo_t
*chosen_exit
= state
?build_state_get_exit_router(state
) : NULL
;
2456 routerinfo_t
*r
= NULL
;
2457 int need_uptime
= state
? state
->need_uptime
: 0;
2458 int need_capacity
= state
? state
->need_capacity
: 0;
2459 int consider_exit_family
= 0;
2462 smartlist_add(exit_family
, chosen_exit
);
2463 routerlist_add_family(exit_family
, chosen_exit
);
2464 consider_exit_family
= 1;
2468 entry_guards
= smartlist_create();
2470 if (should_add_entry_nodes
)
2471 entry_guards_prepend_from_config();
2473 if (entry_list_can_grow(options
) &&
2475 smartlist_len(entry_guards
) < options
->NumEntryGuards
))
2476 pick_entry_guards();
2479 smartlist_clear(live_entry_guards
);
2480 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2482 r
= entry_is_live(entry
, need_uptime
, need_capacity
, 0);
2483 if (r
&& (!consider_exit_family
|| !smartlist_isin(exit_family
, r
))) {
2484 smartlist_add(live_entry_guards
, r
);
2485 if (!entry
->made_contact
) {
2486 /* Always start with the first not-yet-contacted entry
2487 * guard. Otherwise we might add several new ones, pick
2488 * the second new one, and now we've expanded our entry
2489 * guard list without needing to. */
2490 goto choose_and_finish
;
2492 if (smartlist_len(live_entry_guards
) >= options
->NumEntryGuards
)
2493 break; /* we have enough */
2497 /* Try to have at least 2 choices available. This way we don't
2498 * get stuck with a single live-but-crummy entry and just keep
2500 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2501 if (smartlist_len(live_entry_guards
) < 2) {
2502 if (entry_list_can_grow(options
)) {
2503 /* still no? try adding a new entry then */
2504 /* XXX if guard doesn't imply fast and stable, then we need
2505 * to tell add_an_entry_guard below what we want, or it might
2506 * be a long time til we get it. -RD */
2507 r
= add_an_entry_guard(NULL
, 0);
2509 smartlist_add(live_entry_guards
, r
);
2510 entry_guards_changed();
2513 if (!r
&& need_uptime
) {
2514 need_uptime
= 0; /* try without that requirement */
2517 if (!r
&& need_capacity
) {
2518 /* still no? last attempt, try without requiring capacity */
2522 if (!r
&& !entry_list_can_grow(options
) && consider_exit_family
) {
2523 /* still no? if we're using bridges or have strictentrynodes
2524 * set, and our chosen exit is in the same family as all our
2525 * bridges/entry guards, then be flexible about families. */
2526 consider_exit_family
= 0;
2529 /* live_entry_guards may be empty below. Oh well, we tried. */
2533 r
= smartlist_choose(live_entry_guards
);
2534 smartlist_free(live_entry_guards
);
2535 smartlist_free(exit_family
);
2539 /** Helper: Return the start of the month containing <b>time</b>. */
2541 start_of_month(time_t now
)
2544 tor_gmtime_r(&now
, &tm
);
2549 return tor_timegm(&tm
);
2552 /** Parse <b>state</b> and learn about the entry guards it describes.
2553 * If <b>set</b> is true, and there are no errors, replace the global
2554 * entry_list with what we find.
2555 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2556 * describing the error, and return -1.
2559 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
2561 entry_guard_t
*node
= NULL
;
2562 smartlist_t
*new_entry_guards
= smartlist_create();
2563 config_line_t
*line
;
2564 time_t now
= time(NULL
);
2565 const char *state_version
= state
->TorVersion
;
2566 digestmap_t
*added_by
= digestmap_new();
2569 for (line
= state
->EntryGuards
; line
; line
= line
->next
) {
2570 if (!strcasecmp(line
->key
, "EntryGuard")) {
2571 smartlist_t
*args
= smartlist_create();
2572 node
= tor_malloc_zero(sizeof(entry_guard_t
));
2573 /* all entry guards on disk have been contacted */
2574 node
->made_contact
= 1;
2575 smartlist_add(new_entry_guards
, node
);
2576 smartlist_split_string(args
, line
->value
, " ",
2577 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2578 if (smartlist_len(args
)<2) {
2579 *msg
= tor_strdup("Unable to parse entry nodes: "
2580 "Too few arguments to EntryGuard");
2581 } else if (!is_legal_nickname(smartlist_get(args
,0))) {
2582 *msg
= tor_strdup("Unable to parse entry nodes: "
2583 "Bad nickname for EntryGuard");
2585 strlcpy(node
->nickname
, smartlist_get(args
,0), MAX_NICKNAME_LEN
+1);
2586 if (base16_decode(node
->identity
, DIGEST_LEN
, smartlist_get(args
,1),
2587 strlen(smartlist_get(args
,1)))<0) {
2588 *msg
= tor_strdup("Unable to parse entry nodes: "
2589 "Bad hex digest for EntryGuard");
2592 SMARTLIST_FOREACH(args
, char*, cp
, tor_free(cp
));
2593 smartlist_free(args
);
2596 } else if (!strcasecmp(line
->key
, "EntryGuardDownSince") ||
2597 !strcasecmp(line
->key
, "EntryGuardUnlistedSince")) {
2599 time_t last_try
= 0;
2601 *msg
= tor_strdup("Unable to parse entry nodes: "
2602 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2605 if (parse_iso_time(line
->value
, &when
)<0) {
2606 *msg
= tor_strdup("Unable to parse entry nodes: "
2607 "Bad time in EntryGuardDownSince/UnlistedSince");
2611 /* It's a bad idea to believe info in the future: you can wind
2612 * up with timeouts that aren't allowed to happen for years. */
2615 if (strlen(line
->value
) >= ISO_TIME_LEN
+ISO_TIME_LEN
+1) {
2616 /* ignore failure */
2617 parse_iso_time(line
->value
+ISO_TIME_LEN
+1, &last_try
);
2619 if (!strcasecmp(line
->key
, "EntryGuardDownSince")) {
2620 node
->unreachable_since
= when
;
2621 node
->last_attempted
= last_try
;
2623 node
->bad_since
= when
;
2625 } else if (!strcasecmp(line
->key
, "EntryGuardAddedBy")) {
2627 /* format is digest version date */
2628 if (strlen(line
->value
) < HEX_DIGEST_LEN
+1+1+1+ISO_TIME_LEN
) {
2629 log_warn(LD_BUG
, "EntryGuardAddedBy line is not long enough.");
2632 if (base16_decode(d
, sizeof(d
), line
->value
, HEX_DIGEST_LEN
)<0 ||
2633 line
->value
[HEX_DIGEST_LEN
] != ' ') {
2634 log_warn(LD_BUG
, "EntryGuardAddedBy line %s does not begin with "
2635 "hex digest", escaped(line
->value
));
2638 digestmap_set(added_by
, d
, tor_strdup(line
->value
+HEX_DIGEST_LEN
+1));
2640 log_warn(LD_BUG
, "Unexpected key %s", line
->key
);
2644 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2647 char *val
= digestmap_get(added_by
, e
->identity
);
2648 if (val
&& (sp
= strchr(val
, ' '))) {
2651 if (parse_iso_time(sp
, &when
)<0) {
2652 log_warn(LD_BUG
, "Can't read time %s in EntryGuardAddedBy", sp
);
2654 e
->chosen_by_version
= tor_strdup(val
);
2655 e
->chosen_on_date
= when
;
2658 if (state_version
) {
2659 e
->chosen_by_version
= tor_strdup(state_version
);
2660 e
->chosen_on_date
= start_of_month(time(NULL
));
2666 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
2667 entry_guard_free(e
));
2668 smartlist_free(new_entry_guards
);
2669 } else { /* !*err && set */
2671 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2672 entry_guard_free(e
));
2673 smartlist_free(entry_guards
);
2675 entry_guards
= new_entry_guards
;
2676 entry_guards_dirty
= 0;
2677 if (remove_obsolete_entry_guards())
2678 entry_guards_dirty
= 1;
2680 digestmap_free(added_by
, _tor_free
);
2681 return *msg
? -1 : 0;
2684 /** Our list of entry guards has changed, or some element of one
2685 * of our entry guards has changed. Write the changes to disk within
2686 * the next few minutes.
2689 entry_guards_changed(void)
2692 entry_guards_dirty
= 1;
2694 /* or_state_save() will call entry_guards_update_state(). */
2695 when
= get_options()->AvoidDiskWrites
? time(NULL
) + 3600 : time(NULL
)+600;
2696 or_state_mark_dirty(get_or_state(), when
);
2699 /** If the entry guard info has not changed, do nothing and return.
2700 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2701 * a new one out of the global entry_guards list, and then mark
2702 * <b>state</b> dirty so it will get saved to disk.
2705 entry_guards_update_state(or_state_t
*state
)
2707 config_line_t
**next
, *line
;
2708 if (! entry_guards_dirty
)
2711 config_free_lines(state
->EntryGuards
);
2712 next
= &state
->EntryGuards
;
2715 entry_guards
= smartlist_create();
2716 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2718 char dbuf
[HEX_DIGEST_LEN
+1];
2719 if (!e
->made_contact
)
2720 continue; /* don't write this one to disk */
2721 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2722 line
->key
= tor_strdup("EntryGuard");
2723 line
->value
= tor_malloc(HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2);
2724 base16_encode(dbuf
, sizeof(dbuf
), e
->identity
, DIGEST_LEN
);
2725 tor_snprintf(line
->value
,HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2,
2726 "%s %s", e
->nickname
, dbuf
);
2727 next
= &(line
->next
);
2728 if (e
->unreachable_since
) {
2729 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2730 line
->key
= tor_strdup("EntryGuardDownSince");
2731 line
->value
= tor_malloc(ISO_TIME_LEN
+1+ISO_TIME_LEN
+1);
2732 format_iso_time(line
->value
, e
->unreachable_since
);
2733 if (e
->last_attempted
) {
2734 line
->value
[ISO_TIME_LEN
] = ' ';
2735 format_iso_time(line
->value
+ISO_TIME_LEN
+1, e
->last_attempted
);
2737 next
= &(line
->next
);
2740 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2741 line
->key
= tor_strdup("EntryGuardUnlistedSince");
2742 line
->value
= tor_malloc(ISO_TIME_LEN
+1);
2743 format_iso_time(line
->value
, e
->bad_since
);
2744 next
= &(line
->next
);
2746 if (e
->chosen_on_date
&& e
->chosen_by_version
&&
2747 !strchr(e
->chosen_by_version
, ' ')) {
2748 char d
[HEX_DIGEST_LEN
+1];
2749 char t
[ISO_TIME_LEN
+1];
2751 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2752 line
->key
= tor_strdup("EntryGuardAddedBy");
2753 val_len
= (HEX_DIGEST_LEN
+1+strlen(e
->chosen_by_version
)
2755 line
->value
= tor_malloc(val_len
);
2756 base16_encode(d
, sizeof(d
), e
->identity
, DIGEST_LEN
);
2757 format_iso_time(t
, e
->chosen_on_date
);
2758 tor_snprintf(line
->value
, val_len
, "%s %s %s",
2759 d
, e
->chosen_by_version
, t
);
2760 next
= &(line
->next
);
2763 if (!get_options()->AvoidDiskWrites
)
2764 or_state_mark_dirty(get_or_state(), 0);
2765 entry_guards_dirty
= 0;
2768 /** If <b>question</b> is the string "entry-guards", then dump
2769 * to *<b>answer</b> a newly allocated string describing all of
2770 * the nodes in the global entry_guards list. See control-spec.txt
2772 * For backward compatibility, we also handle the string "helper-nodes".
2775 getinfo_helper_entry_guards(control_connection_t
*conn
,
2776 const char *question
, char **answer
)
2778 int use_long_names
= conn
->use_long_names
;
2780 if (!strcmp(question
,"entry-guards") ||
2781 !strcmp(question
,"helper-nodes")) {
2782 smartlist_t
*sl
= smartlist_create();
2783 char tbuf
[ISO_TIME_LEN
+1];
2784 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
2786 entry_guards
= smartlist_create();
2787 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2789 size_t len
= MAX_VERBOSE_NICKNAME_LEN
+ISO_TIME_LEN
+32;
2790 char *c
= tor_malloc(len
);
2791 const char *status
= NULL
;
2793 if (!e
->made_contact
) {
2794 status
= "never-connected";
2795 } else if (e
->bad_since
) {
2796 when
= e
->bad_since
;
2797 status
= "unusable";
2801 if (use_long_names
) {
2802 routerinfo_t
*ri
= router_get_by_digest(e
->identity
);
2804 router_get_verbose_nickname(nbuf
, ri
);
2807 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
2808 /* e->nickname field is not very reliable if we don't know about
2809 * this router any longer; don't include it. */
2812 base16_encode(nbuf
, sizeof(nbuf
), e
->identity
, DIGEST_LEN
);
2815 format_iso_time(tbuf
, when
);
2816 tor_snprintf(c
, len
, "%s %s %s\n", nbuf
, status
, tbuf
);
2818 tor_snprintf(c
, len
, "%s %s\n", nbuf
, status
);
2820 smartlist_add(sl
, c
);
2822 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2823 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2833 char identity
[DIGEST_LEN
];
2834 download_status_t fetch_status
;
2837 /** A list of known bridges. */
2838 static smartlist_t
*bridge_list
= NULL
;
2840 /** Initialize the bridge list to empty, creating it if needed. */
2842 clear_bridge_list(void)
2845 bridge_list
= smartlist_create();
2846 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, b
, tor_free(b
));
2847 smartlist_clear(bridge_list
);
2850 /** Return a bridge pointer if <b>ri</b> is one of our known bridges
2851 * (either by comparing keys if possible, else by comparing addr/port).
2852 * Else return NULL. */
2853 static bridge_info_t
*
2854 routerinfo_get_configured_bridge(routerinfo_t
*ri
)
2858 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2860 if (tor_digest_is_zero(bridge
->identity
) &&
2861 bridge
->addr
== ri
->addr
&& bridge
->port
== ri
->or_port
)
2863 if (!memcmp(bridge
->identity
, ri
->cache_info
.identity_digest
,
2870 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
2872 routerinfo_is_a_configured_bridge(routerinfo_t
*ri
)
2874 return routerinfo_get_configured_bridge(ri
) ? 1 : 0;
2877 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2878 * is set, it tells us the identity key too. */
2880 bridge_add_from_config(uint32_t addr
, uint16_t port
, char *digest
)
2882 bridge_info_t
*b
= tor_malloc_zero(sizeof(bridge_info_t
));
2886 memcpy(b
->identity
, digest
, DIGEST_LEN
);
2888 bridge_list
= smartlist_create();
2889 smartlist_add(bridge_list
, b
);
2892 /** Schedule the next fetch for <b>bridge</b>, based on
2893 * some retry schedule. */
2895 bridge_fetch_status_increment(bridge_info_t
*bridge
, time_t now
)
2897 switch (bridge
->fetch_status
.n_download_failures
) {
2898 case 0: bridge
->fetch_status
.next_attempt_at
= now
+60*15; break;
2899 case 1: bridge
->fetch_status
.next_attempt_at
= now
+60*15; break;
2900 default: bridge
->fetch_status
.next_attempt_at
= now
+60*60; break;
2902 if (bridge
->fetch_status
.n_download_failures
< 10)
2903 bridge
->fetch_status
.n_download_failures
++;
2906 /** We just got a new descriptor for <b>bridge</b>. Reschedule the
2907 * next fetch for a long time from <b>now</b>. */
2909 bridge_fetch_status_arrived(bridge_info_t
*bridge
, time_t now
)
2912 bridge
->fetch_status
.next_attempt_at
= now
+60*60;
2913 bridge
->fetch_status
.n_download_failures
= 0;
2916 /** If <b>digest</b> is one of our known bridges, return it. */
2917 static bridge_info_t
*
2918 find_bridge_by_digest(char *digest
)
2920 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2922 if (!memcmp(bridge
->identity
, digest
, DIGEST_LEN
))
2928 /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
2929 * is a helpful string describing this bridge. */
2931 launch_direct_bridge_descriptor_fetch(char *address
, bridge_info_t
*bridge
)
2933 if (connection_get_by_type_addr_port_purpose(
2934 CONN_TYPE_DIR
, bridge
->addr
, bridge
->port
,
2935 DIR_PURPOSE_FETCH_SERVERDESC
))
2936 return; /* it's already on the way */
2937 directory_initiate_command(address
, bridge
->addr
,
2939 1, bridge
->identity
,
2940 DIR_PURPOSE_FETCH_SERVERDESC
,
2941 ROUTER_PURPOSE_BRIDGE
,
2942 0, "authority.z", NULL
, 0, 0);
2945 /** Fetching the bridge descriptor from the bridge authority returned a
2946 * "not found". Fall back to trying a direct fetch. */
2948 retry_bridge_descriptor_fetch_directly(char *digest
)
2950 bridge_info_t
*bridge
= find_bridge_by_digest(digest
);
2951 char address_buf
[INET_NTOA_BUF_LEN
+1];
2955 return; /* not found? oh well. */
2957 in
.s_addr
= htonl(bridge
->addr
);
2958 tor_inet_ntoa(&in
, address_buf
, sizeof(address_buf
));
2959 launch_direct_bridge_descriptor_fetch(address_buf
, bridge
);
2962 /** For each bridge in our list for which we don't currently have a
2963 * descriptor, fetch a new copy of its descriptor -- either directly
2964 * from the bridge or via a bridge authority. */
2966 fetch_bridge_descriptors(time_t now
)
2968 char address_buf
[INET_NTOA_BUF_LEN
+1];
2970 or_options_t
*options
= get_options();
2971 int num_bridge_auths
= get_n_authorities(BRIDGE_AUTHORITY
);
2972 int ask_bridge_directly
;
2973 int can_use_bridge_authority
;
2978 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2980 if (bridge
->fetch_status
.next_attempt_at
> now
)
2981 continue; /* don't bother, no need to retry yet */
2983 /* schedule another fetch as if this one will fail, in case it does */
2984 bridge_fetch_status_increment(bridge
, now
);
2986 in
.s_addr
= htonl(bridge
->addr
);
2987 tor_inet_ntoa(&in
, address_buf
, sizeof(address_buf
));
2989 can_use_bridge_authority
= !tor_digest_is_zero(bridge
->identity
) &&
2991 ask_bridge_directly
= !can_use_bridge_authority
||
2992 !options
->UpdateBridgesFromAuthority
;
2993 log_debug(LD_DIR
, "ask_bridge_directly=%d (%d, %d, %d)",
2994 ask_bridge_directly
, tor_digest_is_zero(bridge
->identity
),
2995 !options
->UpdateBridgesFromAuthority
, !num_bridge_auths
);
2997 if (ask_bridge_directly
&&
2998 !fascist_firewall_allows_address_or(bridge
->addr
, bridge
->port
)) {
2999 log_notice(LD_DIR
, "Bridge at '%s:%d' isn't reachable by our "
3000 "firewall policy. %s.", address_buf
, bridge
->port
,
3001 can_use_bridge_authority
?
3002 "Asking bridge authority instead" : "Skipping");
3003 if (can_use_bridge_authority
)
3004 ask_bridge_directly
= 0;
3009 if (ask_bridge_directly
) {
3010 /* we need to ask the bridge itself for its descriptor. */
3011 launch_direct_bridge_descriptor_fetch(address_buf
, bridge
);
3013 /* We have a digest and we want to ask an authority. We could
3014 * combine all the requests into one, but that may give more
3015 * hints to the bridge authority than we want to give. */
3016 char resource
[10 + HEX_DIGEST_LEN
];
3017 memcpy(resource
, "fp/", 3);
3018 base16_encode(resource
+3, HEX_DIGEST_LEN
+1,
3019 bridge
->identity
, DIGEST_LEN
);
3020 memcpy(resource
+3+HEX_DIGEST_LEN
, ".z", 3);
3021 log_info(LD_DIR
, "Fetching bridge info '%s' from bridge authority.",
3023 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
3024 ROUTER_PURPOSE_BRIDGE
, resource
, 0);
3029 /** We just learned a descriptor for a bridge. See if that
3030 * digest is in our entry guard list, and add it if not. */
3032 learned_bridge_descriptor(routerinfo_t
*ri
)
3035 tor_assert(ri
->purpose
== ROUTER_PURPOSE_BRIDGE
);
3036 if (get_options()->UseBridges
) {
3037 int first
= !any_bridge_descriptors_known();
3038 bridge_info_t
*bridge
= routerinfo_get_configured_bridge(ri
);
3039 time_t now
= time(NULL
);
3042 if (bridge
) { /* if we actually want to use this one */
3043 /* it's here; schedule its re-fetch for a long time from now. */
3044 bridge_fetch_status_arrived(bridge
, now
);
3046 add_an_entry_guard(ri
, 1);
3047 log_notice(LD_DIR
, "new bridge descriptor '%s'", ri
->nickname
);
3049 routerlist_retry_directory_downloads(now
);
3054 /** Return 1 if any of our entry guards have descriptors that
3055 * are marked with purpose 'bridge' and are running. Else return 0.
3057 * We use this function to decide if we're ready to start building
3058 * circuits through our bridges, or if we need to wait until the
3059 * directory "server/authority" requests finish. */
3061 any_bridge_descriptors_known(void)
3063 tor_assert(get_options()->UseBridges
);
3064 return choose_random_entry(NULL
)!=NULL
? 1 : 0;
3067 /** Return 1 if we have at least one descriptor for a bridge and
3068 * all descriptors we know are down. Else return 0. If <b>act</b> is
3069 * 1, then mark the down bridges up; else just observe and report. */
3071 bridges_retry_helper(int act
)
3075 int any_running
= 0;
3077 entry_guards
= smartlist_create();
3078 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3080 ri
= router_get_by_digest(e
->identity
);
3081 if (ri
&& ri
->purpose
== ROUTER_PURPOSE_BRIDGE
) {
3084 any_running
= 1; /* some bridge is both known and running */
3085 else if (act
) { /* mark it for retry */
3092 return any_known
&& !any_running
;
3095 /** Do we know any descriptors for our bridges, and are they all
3098 bridges_known_but_down(void)
3100 return bridges_retry_helper(0);
3103 /** Mark all down known bridges up. */
3105 bridges_retry_all(void)
3107 bridges_retry_helper(1);
3110 /** Release all storage held by the list of entry guards and related
3111 * memory structs. */
3113 entry_guards_free_all(void)
3116 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
3117 entry_guard_free(e
));
3118 smartlist_free(entry_guards
);
3119 entry_guards
= NULL
;
3121 clear_bridge_list();
3122 smartlist_free(bridge_list
);