1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char circuitbuild_c_id
[] =
10 * \file circuitbuild.c
11 * \brief The actual details of building circuits.
16 /********* START VARIABLES **********/
18 /** A global list of all circuits at this hop. */
19 extern circuit_t
*global_circuitlist
;
21 /** An entry_guard_t represents our information about a chosen long-term
22 * first hop, known as a "helper" node in the literature. We can't just
23 * use a routerinfo_t, since we want to remember these even when we
24 * don't have a directory. */
26 char nickname
[MAX_NICKNAME_LEN
+1];
27 char identity
[DIGEST_LEN
];
28 unsigned int made_contact
: 1; /**< 0 if we have never connected to this
29 * router, 1 if we have. */
30 unsigned int can_retry
: 1; /**< Should we retry connecting to this entry,
31 * in spite of having it marked as unreachable?*/
32 time_t bad_since
; /**< 0 if this guard is currently usable, or the time at
33 * which it was observed to become (according to the
34 * directory or the user configuration) unusable. */
35 time_t unreachable_since
; /**< 0 if we can connect to this guard, or the
36 * time at which we first noticed we couldn't
38 time_t last_attempted
; /**< 0 if we can connect to this guard, or the time
39 * at which we last failed to connect to it. */
42 /** A list of our chosen entry guards. */
43 static smartlist_t
*entry_guards
= NULL
;
44 /** A value of 1 means that the entry_guards list has changed
45 * and those changes need to be flushed to disk. */
46 static int entry_guards_dirty
= 0;
48 /********* END VARIABLES ************/
50 static int circuit_deliver_create_cell(circuit_t
*circ
,
51 uint8_t cell_type
, const char *payload
);
52 static int onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
);
53 static crypt_path_t
*onion_next_hop_in_cpath(crypt_path_t
*cpath
);
54 static int onion_extend_cpath(origin_circuit_t
*circ
);
55 static int count_acceptable_routers(smartlist_t
*routers
);
56 static int onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
);
58 static void entry_guards_changed(void);
60 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
61 * and with the high bit specified by conn-\>circ_id_type, until we get
62 * a circ_id that is not in use by any other circuit on that conn.
64 * Return it, or 0 if can't get a unique circ_id.
67 get_unique_circ_id_by_conn(or_connection_t
*conn
)
69 uint16_t test_circ_id
;
74 if (conn
->circ_id_type
== CIRC_ID_TYPE_NEITHER
) {
75 log_warn(LD_BUG
, "Trying to pick a circuit ID for a connection from "
76 "a client with no identity.");
79 high_bit
= (conn
->circ_id_type
== CIRC_ID_TYPE_HIGHER
) ? 1<<15 : 0;
81 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
82 * circID such that (high_bit|test_circ_id) is not already used. */
83 test_circ_id
= conn
->next_circ_id
++;
84 if (test_circ_id
== 0 || test_circ_id
>= 1<<15) {
86 conn
->next_circ_id
= 2;
88 if (++attempts
> 1<<15) {
89 /* Make sure we don't loop forever if all circ_id's are used. This
90 * matters because it's an external DoS opportunity.
92 log_warn(LD_CIRC
,"No unused circ IDs. Failing.");
95 test_circ_id
|= high_bit
;
96 } while (circuit_get_by_circid_orconn(test_circ_id
, conn
));
100 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
101 * the currently built elements of circuit_t. If <b>verbose</b> is true, also
102 * list information about link status in a more verbose format using spaces.
103 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
104 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
108 circuit_list_path_impl(origin_circuit_t
*circ
, int verbose
, int verbose_names
)
111 smartlist_t
*elements
;
112 const char *states
[] = {"closed", "waiting for keys", "open"};
116 elements
= smartlist_create();
119 const char *nickname
= build_state_get_exit_nickname(circ
->build_state
);
120 tor_snprintf(buf
, sizeof(buf
), "%s%s circ (length %d%s%s):",
121 circ
->build_state
->is_internal
? "internal" : "exit",
122 circ
->build_state
->need_uptime
? " (high-uptime)" : "",
123 circ
->build_state
->desired_path_len
,
124 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" : ", exit ",
125 circ
->_base
.state
== CIRCUIT_STATE_OPEN
? "" :
126 (nickname
?nickname
:"*unnamed*"));
127 smartlist_add(elements
, tor_strdup(buf
));
136 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
138 if (!hop
->extend_info
)
141 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
142 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
))) {
143 router_get_verbose_nickname(elt
, ri
);
144 } else if (hop
->extend_info
->nickname
&&
145 is_legal_nickname(hop
->extend_info
->nickname
)) {
147 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
148 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
149 elt
[HEX_DIGEST_LEN
+1]= '~';
150 strlcpy(elt
+HEX_DIGEST_LEN
+2,
151 hop
->extend_info
->nickname
, MAX_NICKNAME_LEN
+1);
154 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
155 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
157 } else { /* ! verbose_names */
158 if ((ri
= router_get_by_digest(hop
->extend_info
->identity_digest
)) &&
160 elt
= tor_strdup(hop
->extend_info
->nickname
);
162 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
164 base16_encode(elt
+1, HEX_DIGEST_LEN
+1,
165 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
170 size_t len
= strlen(elt
)+2+strlen(states
[hop
->state
])+1;
171 char *v
= tor_malloc(len
);
172 tor_assert(hop
->state
<= 2);
173 tor_snprintf(v
,len
,"%s(%s)",elt
,states
[hop
->state
]);
174 smartlist_add(elements
, v
);
177 smartlist_add(elements
, elt
);
180 } while (hop
!= circ
->cpath
);
182 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
183 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
184 smartlist_free(elements
);
188 /** If <b>verbose</b> is false, allocate and return a comma-separated
189 * list of the currently built elements of circuit_t. If
190 * <b>verbose</b> is true, also list information about link status in
191 * a more verbose format using spaces.
194 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
196 return circuit_list_path_impl(circ
, verbose
, 0);
199 /** Allocate and return a comma-separated list of the currently built elements
200 * of circuit_t, giving each as a verbose nickname.
203 circuit_list_path_for_controller(origin_circuit_t
*circ
)
205 return circuit_list_path_impl(circ
, 0, 1);
208 /** Log, at severity <b>severity</b>, the nicknames of each router in
209 * circ's cpath. Also log the length of the cpath, and the intended
213 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
215 char *s
= circuit_list_path(circ
,1);
216 log(severity
,domain
,"%s",s
);
220 /** Tell the rep(utation)hist(ory) module about the status of the links
221 * in circ. Hops that have become OPEN are marked as successfully
222 * extended; the _first_ hop that isn't open (if any) is marked as
225 /* XXXX Someday we should learn from OR circuits too. */
227 circuit_rep_hist_note_result(origin_circuit_t
*circ
)
230 char *prev_digest
= NULL
;
231 routerinfo_t
*router
;
233 if (!hop
) /* circuit hasn't started building yet. */
235 if (server_mode(get_options())) {
236 routerinfo_t
*me
= router_get_my_routerinfo();
239 prev_digest
= me
->cache_info
.identity_digest
;
242 router
= router_get_by_digest(hop
->extend_info
->identity_digest
);
245 if (hop
->state
== CPATH_STATE_OPEN
)
246 rep_hist_note_extend_succeeded(prev_digest
,
247 router
->cache_info
.identity_digest
);
249 rep_hist_note_extend_failed(prev_digest
,
250 router
->cache_info
.identity_digest
);
254 prev_digest
= router
->cache_info
.identity_digest
;
259 } while (hop
!=circ
->cpath
);
262 /** Pick all the entries in our cpath. Stop and return 0 when we're
263 * happy, or return -1 if an error occurs. */
265 onion_populate_cpath(origin_circuit_t
*circ
)
269 r
= onion_extend_cpath(circ
);
271 log_info(LD_CIRC
,"Generating cpath hop failed.");
276 return 0; /* if r == 1 */
279 /** Create and return a new origin circuit. Initialize its purpose and
280 * build-state based on our arguments. */
282 origin_circuit_init(uint8_t purpose
, int onehop_tunnel
,
283 int need_uptime
, int need_capacity
, int internal
)
285 /* sets circ->p_circ_id and circ->p_conn */
286 origin_circuit_t
*circ
= origin_circuit_new();
287 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OR_WAIT
);
288 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
289 circ
->build_state
->onehop_tunnel
= onehop_tunnel
;
290 circ
->build_state
->need_uptime
= need_uptime
;
291 circ
->build_state
->need_capacity
= need_capacity
;
292 circ
->build_state
->is_internal
= internal
;
293 circ
->_base
.purpose
= purpose
;
297 /** Build a new circuit for <b>purpose</b>. If <b>info</b>
298 * is defined, then use that as your exit router, else choose a suitable
301 * Also launch a connection to the first OR in the chosen path, if
302 * it's not open already.
305 circuit_establish_circuit(uint8_t purpose
, int onehop_tunnel
,
307 int need_uptime
, int need_capacity
, int internal
)
309 origin_circuit_t
*circ
;
312 circ
= origin_circuit_init(purpose
, onehop_tunnel
,
313 need_uptime
, need_capacity
, internal
);
315 if (onion_pick_cpath_exit(circ
, exit
) < 0 ||
316 onion_populate_cpath(circ
) < 0) {
317 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
321 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
323 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
324 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
330 /** Start establishing the first hop of our circuit. Figure out what
331 * OR we should connect to, and if necessary start the connection to
332 * it. If we're already connected, then send the 'create' cell.
333 * Return 0 for ok, -reason if circ should be marked-for-close. */
335 circuit_handle_first_hop(origin_circuit_t
*circ
)
337 crypt_path_t
*firsthop
;
338 or_connection_t
*n_conn
;
339 char tmpbuf
[INET_NTOA_BUF_LEN
];
343 firsthop
= onion_next_hop_in_cpath(circ
->cpath
);
344 tor_assert(firsthop
);
345 tor_assert(firsthop
->extend_info
);
347 /* now see if we're already connected to the first OR in 'route' */
348 in
.s_addr
= htonl(firsthop
->extend_info
->addr
);
349 tor_inet_ntoa(&in
, tmpbuf
, sizeof(tmpbuf
));
350 log_debug(LD_CIRC
,"Looking for firsthop '%s:%u'",tmpbuf
,
351 firsthop
->extend_info
->port
);
352 /* imprint the circuit with its future n_conn->id */
353 memcpy(circ
->_base
.n_conn_id_digest
, firsthop
->extend_info
->identity_digest
,
355 n_conn
= connection_or_get_by_identity_digest(
356 firsthop
->extend_info
->identity_digest
);
357 /* If we don't have an open conn, or the conn we have is obsolete
358 * (i.e. old or broken) and the other side will let us make a second
359 * connection without dropping it immediately... */
360 if (!n_conn
|| n_conn
->_base
.state
!= OR_CONN_STATE_OPEN
||
361 (n_conn
->_base
.or_is_obsolete
&&
362 router_digest_version_as_new_as(firsthop
->extend_info
->identity_digest
,
363 "0.1.1.9-alpha-cvs"))) {
364 /* not currently connected */
365 circ
->_base
.n_addr
= firsthop
->extend_info
->addr
;
366 circ
->_base
.n_port
= firsthop
->extend_info
->port
;
368 if (!n_conn
|| n_conn
->_base
.or_is_obsolete
) { /* launch the connection */
369 n_conn
= connection_or_connect(firsthop
->extend_info
->addr
,
370 firsthop
->extend_info
->port
,
371 firsthop
->extend_info
->identity_digest
);
372 if (!n_conn
) { /* connect failed, forget the whole thing */
373 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
374 return -END_CIRC_REASON_CONNECTFAILED
;
378 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
379 /* return success. The onion/circuit/etc will be taken care of
380 * automatically (may already have been) whenever n_conn reaches
381 * OR_CONN_STATE_OPEN.
384 } else { /* it's already open. use it. */
385 circ
->_base
.n_addr
= n_conn
->_base
.addr
;
386 circ
->_base
.n_port
= n_conn
->_base
.port
;
387 circ
->_base
.n_conn
= n_conn
;
388 log_debug(LD_CIRC
,"Conn open. Delivering first onion skin.");
389 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
390 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
397 /** Find any circuits that are waiting on <b>or_conn</b> to become
398 * open and get them to send their create cells forward.
400 * Status is 1 if connect succeeded, or 0 if connect failed.
403 circuit_n_conn_done(or_connection_t
*or_conn
, int status
)
405 smartlist_t
*pending_circs
;
408 log_debug(LD_CIRC
,"or_conn to %s, status=%d",
409 or_conn
->nickname
? or_conn
->nickname
: "NULL", status
);
411 pending_circs
= smartlist_create();
412 circuit_get_all_pending_on_or_conn(pending_circs
, or_conn
);
414 SMARTLIST_FOREACH(pending_circs
, circuit_t
*, circ
,
416 /* This check is redundant wrt get_all_pending_on_or_conn, but I'm
417 * leaving them in in case it's possible for the status of a circuit to
418 * change as we're going down the list. */
419 if (circ
->marked_for_close
|| circ
->n_conn
||
420 circ
->state
!= CIRCUIT_STATE_OR_WAIT
||
421 memcmp(or_conn
->identity_digest
, circ
->n_conn_id_digest
, DIGEST_LEN
))
423 if (!status
) { /* or_conn failed; close circ */
424 log_info(LD_CIRC
,"or_conn failed. Closing circ.");
425 circuit_mark_for_close(circ
, END_CIRC_REASON_OR_CONN_CLOSED
);
428 log_debug(LD_CIRC
, "Found circ, sending create cell.");
429 /* circuit_deliver_create_cell will set n_circ_id and add us to
430 * orconn_circuid_circuit_map, so we don't need to call
431 * set_circid_orconn here. */
432 circ
->n_conn
= or_conn
;
433 if (CIRCUIT_IS_ORIGIN(circ
)) {
435 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
437 "send_next_onion_skin failed; circuit marked for closing.");
438 circuit_mark_for_close(circ
, -err_reason
);
440 /* XXX could this be bad, eg if next_onion_skin failed because conn
444 /* pull the create cell out of circ->onionskin, and send it */
445 tor_assert(circ
->onionskin
);
446 if (circuit_deliver_create_cell(circ
,CELL_CREATE
,circ
->onionskin
)<0) {
447 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
450 tor_free(circ
->onionskin
);
451 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
455 smartlist_free(pending_circs
);
458 /** Find a new circid that isn't currently in use on the circ->n_conn
460 * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
461 * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
463 * Return -1 if we failed to find a suitable circid, else return 0.
466 circuit_deliver_create_cell(circuit_t
*circ
, uint8_t cell_type
,
473 tor_assert(circ
->n_conn
);
475 tor_assert(cell_type
== CELL_CREATE
|| cell_type
== CELL_CREATE_FAST
);
477 id
= get_unique_circ_id_by_conn(circ
->n_conn
);
479 log_warn(LD_CIRC
,"failed to get unique circID.");
482 log_debug(LD_CIRC
,"Chosen circID %u.", id
);
483 circuit_set_n_circid_orconn(circ
, id
, circ
->n_conn
);
485 memset(&cell
, 0, sizeof(cell_t
));
486 cell
.command
= cell_type
;
487 cell
.circ_id
= circ
->n_circ_id
;
489 memcpy(cell
.payload
, payload
, ONIONSKIN_CHALLENGE_LEN
);
490 append_cell_to_circuit_queue(circ
, circ
->n_conn
, &cell
, CELL_DIRECTION_OUT
);
492 /* mark it so it gets better rate limiting treatment. */
493 circ
->n_conn
->client_used
= 1;
498 /** We've decided to start our reachability testing. If all
499 * is set, log this to the user. Return 1 if we did, or 0 if
500 * we chose not to log anything. */
502 inform_testing_reachability(void)
505 routerinfo_t
*me
= router_get_my_routerinfo();
509 tor_snprintf(dirbuf
, sizeof(dirbuf
), " and DirPort %s:%d",
510 me
->address
, me
->dir_port
);
511 log(LOG_NOTICE
, LD_OR
, "Now checking whether ORPort %s:%d%s %s reachable... "
512 "(this may take up to %d minutes -- look for log "
513 "messages indicating success)",
514 me
->address
, me
->or_port
,
515 me
->dir_port
? dirbuf
: "",
516 me
->dir_port
? "are" : "is",
517 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
/60);
521 /** Return true iff we should send a create_fast cell to build a circuit
522 * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
523 * information on the router, so assume true.) */
525 should_use_create_fast_for_router(routerinfo_t
*router
,
526 origin_circuit_t
*circ
)
528 or_options_t
*options
= get_options();
530 if (!options
->FastFirstHopPK
) /* create_fast is disabled */
532 if (router
&& router
->platform
&&
533 !tor_version_as_new_as(router
->platform
, "0.1.0.6-rc")) {
534 /* known not to work */
537 if (server_mode(options
) && circ
->cpath
->extend_info
->onion_key
) {
538 /* We're a server, and we know an onion key. We can choose.
539 * Prefer to blend in. */
546 /** This is the backbone function for building circuits.
548 * If circ's first hop is closed, then we need to build a create
549 * cell and send it forward.
551 * Otherwise, we need to build a relay extend cell and send it
554 * Return -reason if we want to tear down circ, else return 0.
557 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
560 routerinfo_t
*router
;
561 char payload
[2+4+DIGEST_LEN
+ONIONSKIN_CHALLENGE_LEN
];
567 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
570 log_debug(LD_CIRC
,"First skin; sending create cell.");
572 router
= router_get_by_digest(circ
->_base
.n_conn
->identity_digest
);
573 fast
= should_use_create_fast_for_router(router
, circ
);
574 if (!fast
&& !circ
->cpath
->extend_info
->onion_key
) {
576 "Can't send create_fast, but have no onion key. Failing.");
577 return - END_CIRC_REASON_INTERNAL
;
580 /* We are an OR, or we are connecting to an old Tor: we should
581 * send an old slow create cell.
583 cell_type
= CELL_CREATE
;
584 if (onion_skin_create(circ
->cpath
->extend_info
->onion_key
,
585 &(circ
->cpath
->dh_handshake_state
),
587 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
588 return - END_CIRC_REASON_INTERNAL
;
591 /* We are not an OR, and we're building the first hop of a circuit to a
592 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
593 * and a DH operation. */
594 cell_type
= CELL_CREATE_FAST
;
595 memset(payload
, 0, sizeof(payload
));
596 crypto_rand(circ
->cpath
->fast_handshake_state
,
597 sizeof(circ
->cpath
->fast_handshake_state
));
598 memcpy(payload
, circ
->cpath
->fast_handshake_state
,
599 sizeof(circ
->cpath
->fast_handshake_state
));
602 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), cell_type
, payload
) < 0)
603 return - END_CIRC_REASON_RESOURCELIMIT
;
605 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
606 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
607 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
608 fast
? "CREATE_FAST" : "CREATE",
609 router
? router
->nickname
: "<unnamed>");
611 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
612 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_BUILDING
);
613 log_debug(LD_CIRC
,"starting to send subsequent skin.");
614 hop
= onion_next_hop_in_cpath(circ
->cpath
);
616 /* done building the circuit. whew. */
617 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
618 log_info(LD_CIRC
,"circuit built!");
619 circuit_reset_failure_count(0);
620 if (!has_completed_circuit
&& !circ
->build_state
->onehop_tunnel
) {
621 or_options_t
*options
= get_options();
622 has_completed_circuit
=1;
623 /* FFFF Log a count of known routers here */
624 log(LOG_NOTICE
, LD_GENERAL
,
625 "Tor has successfully opened a circuit. "
626 "Looks like client functionality is working.");
627 control_event_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
628 if (server_mode(options
) && !check_whether_orport_reachable()) {
629 inform_testing_reachability();
630 consider_testing_reachability(1, 1);
633 circuit_rep_hist_note_result(circ
);
634 circuit_has_opened(circ
); /* do other actions as necessary */
638 set_uint32(payload
, htonl(hop
->extend_info
->addr
));
639 set_uint16(payload
+4, htons(hop
->extend_info
->port
));
641 onionskin
= payload
+2+4;
642 memcpy(payload
+2+4+ONIONSKIN_CHALLENGE_LEN
,
643 hop
->extend_info
->identity_digest
, DIGEST_LEN
);
644 payload_len
= 2+4+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
;
646 if (onion_skin_create(hop
->extend_info
->onion_key
,
647 &(hop
->dh_handshake_state
), onionskin
) < 0) {
648 log_warn(LD_CIRC
,"onion_skin_create failed.");
649 return - END_CIRC_REASON_INTERNAL
;
652 log_info(LD_CIRC
,"Sending extend relay cell.");
653 /* send it to hop->prev, because it will transfer
654 * it to a create cell and then send to hop */
655 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
656 RELAY_COMMAND_EXTEND
,
657 payload
, payload_len
, hop
->prev
) < 0)
658 return 0; /* circuit is closed */
660 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
665 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
666 * something has also gone wrong with our network: notify the user,
667 * and abandon all not-yet-used circuits. */
669 circuit_note_clock_jumped(int seconds_elapsed
)
671 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
672 log(severity
, LD_GENERAL
, "Your clock just jumped %d seconds %s; "
673 "assuming established circuits no longer work.",
674 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
,
675 seconds_elapsed
>=0 ? "forward" : "backward");
676 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%d",
678 has_completed_circuit
=0; /* so it'll log when it works again */
679 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
681 circuit_mark_all_unused_circs();
682 circuit_expire_all_dirty_circs();
685 /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
686 * sure we're connected to the next hop, and pass it the onion skin using
687 * a create cell. Return -1 if we want to warn and tear down the circuit,
691 circuit_extend(cell_t
*cell
, circuit_t
*circ
)
693 or_connection_t
*n_conn
;
696 char *id_digest
=NULL
;
699 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
700 "n_conn already set. Bug/attack. Closing.");
704 if (!server_mode(get_options())) {
705 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
706 "Got an extend cell, but running as a client. Closing.");
710 relay_header_unpack(&rh
, cell
->payload
);
712 if (rh
.length
< 4+2+ONIONSKIN_CHALLENGE_LEN
+DIGEST_LEN
) {
713 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
714 "Wrong length %d on extend cell. Closing circuit.",
719 circ
->n_addr
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
));
720 circ
->n_port
= ntohs(get_uint16(cell
->payload
+RELAY_HEADER_SIZE
+4));
722 onionskin
= cell
->payload
+RELAY_HEADER_SIZE
+4+2;
723 id_digest
= cell
->payload
+RELAY_HEADER_SIZE
+4+2+ONIONSKIN_CHALLENGE_LEN
;
724 n_conn
= connection_or_get_by_identity_digest(id_digest
);
726 /* If we don't have an open conn, or the conn we have is obsolete
727 * (i.e. old or broken) and the other side will let us make a second
728 * connection without dropping it immediately... */
729 if (!n_conn
|| n_conn
->_base
.state
!= OR_CONN_STATE_OPEN
||
730 (n_conn
->_base
.or_is_obsolete
&&
731 router_digest_version_as_new_as(id_digest
,"0.1.1.9-alpha-cvs"))) {
733 char tmpbuf
[INET_NTOA_BUF_LEN
];
734 in
.s_addr
= htonl(circ
->n_addr
);
735 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
736 log_info(LD_CIRC
|LD_OR
,"Next router (%s:%d) not connected. Connecting.",
737 tmpbuf
, circ
->n_port
);
739 circ
->onionskin
= tor_malloc(ONIONSKIN_CHALLENGE_LEN
);
740 memcpy(circ
->onionskin
, onionskin
, ONIONSKIN_CHALLENGE_LEN
);
741 circuit_set_state(circ
, CIRCUIT_STATE_OR_WAIT
);
743 /* imprint the circuit with its future n_conn->id */
744 memcpy(circ
->n_conn_id_digest
, id_digest
, DIGEST_LEN
);
746 if (n_conn
&& !n_conn
->_base
.or_is_obsolete
) {
747 circ
->n_addr
= n_conn
->_base
.addr
;
748 circ
->n_port
= n_conn
->_base
.port
;
750 /* we should try to open a connection */
751 n_conn
= connection_or_connect(circ
->n_addr
, circ
->n_port
, id_digest
);
753 log_info(LD_CIRC
,"Launching n_conn failed. Closing circuit.");
754 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
757 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
759 /* return success. The onion/circuit/etc will be taken care of
760 * automatically (may already have been) whenever n_conn reaches
761 * OR_CONN_STATE_OPEN.
766 /* these may be different if the router connected to us from elsewhere */
767 circ
->n_addr
= n_conn
->_base
.addr
;
768 circ
->n_port
= n_conn
->_base
.port
;
770 circ
->n_conn
= n_conn
;
771 memcpy(circ
->n_conn_id_digest
, n_conn
->identity_digest
, DIGEST_LEN
);
772 log_debug(LD_CIRC
,"n_conn is %s:%u",
773 n_conn
->_base
.address
,n_conn
->_base
.port
);
775 if (circuit_deliver_create_cell(circ
, CELL_CREATE
, onionskin
) < 0)
780 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
781 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
783 * - 20 to initialize f_digest
784 * - 20 to initialize b_digest
785 * - 16 to key f_crypto
786 * - 16 to key b_crypto
788 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
791 circuit_init_cpath_crypto(crypt_path_t
*cpath
, const char *key_data
,
794 crypto_digest_env_t
*tmp_digest
;
795 crypto_cipher_env_t
*tmp_crypto
;
798 tor_assert(key_data
);
799 tor_assert(!(cpath
->f_crypto
|| cpath
->b_crypto
||
800 cpath
->f_digest
|| cpath
->b_digest
));
802 cpath
->f_digest
= crypto_new_digest_env();
803 crypto_digest_add_bytes(cpath
->f_digest
, key_data
, DIGEST_LEN
);
804 cpath
->b_digest
= crypto_new_digest_env();
805 crypto_digest_add_bytes(cpath
->b_digest
, key_data
+DIGEST_LEN
, DIGEST_LEN
);
807 if (!(cpath
->f_crypto
=
808 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
),1))) {
809 log_warn(LD_BUG
,"Forward cipher initialization failed.");
812 if (!(cpath
->b_crypto
=
813 crypto_create_init_cipher(key_data
+(2*DIGEST_LEN
)+CIPHER_KEY_LEN
,0))) {
814 log_warn(LD_BUG
,"Backward cipher initialization failed.");
819 tmp_digest
= cpath
->f_digest
;
820 cpath
->f_digest
= cpath
->b_digest
;
821 cpath
->b_digest
= tmp_digest
;
822 tmp_crypto
= cpath
->f_crypto
;
823 cpath
->f_crypto
= cpath
->b_crypto
;
824 cpath
->b_crypto
= tmp_crypto
;
830 /** A created or extended cell came back to us on the circuit, and it included
831 * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
832 * contains (the second DH key, plus KH). If <b>reply_type</b> is
833 * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
835 * Calculate the appropriate keys and digests, make sure KH is
836 * correct, and initialize this hop of the cpath.
838 * Return - reason if we want to mark circ for close, else return 0.
841 circuit_finish_handshake(origin_circuit_t
*circ
, uint8_t reply_type
,
844 char keys
[CPATH_KEY_MATERIAL_LEN
];
847 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
)
850 hop
= onion_next_hop_in_cpath(circ
->cpath
);
851 if (!hop
) { /* got an extended when we're all done? */
852 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
853 return - END_CIRC_REASON_TORPROTOCOL
;
856 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
858 if (reply_type
== CELL_CREATED
&& hop
->dh_handshake_state
) {
859 if (onion_skin_client_handshake(hop
->dh_handshake_state
, reply
, keys
,
860 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
861 log_warn(LD_CIRC
,"onion_skin_client_handshake failed.");
862 return -END_CIRC_REASON_TORPROTOCOL
;
864 /* Remember hash of g^xy */
865 memcpy(hop
->handshake_digest
, reply
+DH_KEY_LEN
, DIGEST_LEN
);
866 } else if (reply_type
== CELL_CREATED_FAST
&& !hop
->dh_handshake_state
) {
867 if (fast_client_handshake(hop
->fast_handshake_state
, reply
, keys
,
868 DIGEST_LEN
*2+CIPHER_KEY_LEN
*2) < 0) {
869 log_warn(LD_CIRC
,"fast_client_handshake failed.");
870 return -END_CIRC_REASON_TORPROTOCOL
;
872 memcpy(hop
->handshake_digest
, reply
+DIGEST_LEN
, DIGEST_LEN
);
874 log_warn(LD_PROTOCOL
,"CREATED cell type did not match CREATE cell type.");
875 return -END_CIRC_REASON_TORPROTOCOL
;
878 if (hop
->dh_handshake_state
) {
879 crypto_dh_free(hop
->dh_handshake_state
); /* don't need it anymore */
880 hop
->dh_handshake_state
= NULL
;
882 memset(hop
->fast_handshake_state
, 0, sizeof(hop
->fast_handshake_state
));
884 if (circuit_init_cpath_crypto(hop
, keys
, 0)<0) {
885 return -END_CIRC_REASON_TORPROTOCOL
;
888 hop
->state
= CPATH_STATE_OPEN
;
889 log_info(LD_CIRC
,"Finished building %scircuit hop:",
890 (reply_type
== CELL_CREATED_FAST
) ? "fast " : "");
891 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
892 control_event_circuit_status(circ
, CIRC_EVENT_EXTENDED
, 0);
897 /** We received a relay truncated cell on circ.
899 * Since we don't ask for truncates currently, getting a truncated
900 * means that a connection broke or an extend failed. For now,
901 * just give up: for circ to close, and return 0.
904 circuit_truncated(origin_circuit_t
*circ
, crypt_path_t
*layer
)
906 // crypt_path_t *victim;
907 // connection_t *stream;
912 /* XXX Since we don't ask for truncates currently, getting a truncated
913 * means that a connection broke or an extend failed. For now,
916 circuit_mark_for_close(TO_CIRCUIT(circ
),
917 END_CIRC_REASON_FLAG_REMOTE
|END_CIRC_REASON_OR_CONN_CLOSED
);
921 while (layer
->next
!= circ
->cpath
) {
922 /* we need to clear out layer->next */
923 victim
= layer
->next
;
924 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
926 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
927 if (stream
->cpath_layer
== victim
) {
928 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
930 /* no need to send 'end' relay cells,
931 * because the other side's already dead
933 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
937 layer
->next
= victim
->next
;
938 circuit_free_cpath_node(victim
);
941 log_info(LD_CIRC
, "finished");
946 /** Given a response payload and keys, initialize, then send a created
950 onionskin_answer(or_circuit_t
*circ
, uint8_t cell_type
, const char *payload
,
954 crypt_path_t
*tmp_cpath
;
956 tmp_cpath
= tor_malloc_zero(sizeof(crypt_path_t
));
957 tmp_cpath
->magic
= CRYPT_PATH_MAGIC
;
959 memset(&cell
, 0, sizeof(cell_t
));
960 cell
.command
= cell_type
;
961 cell
.circ_id
= circ
->p_circ_id
;
963 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
965 memcpy(cell
.payload
, payload
,
966 cell_type
== CELL_CREATED
? ONIONSKIN_REPLY_LEN
: DIGEST_LEN
*2);
968 log_debug(LD_CIRC
,"init digest forward 0x%.8x, backward 0x%.8x.",
969 (unsigned int)*(uint32_t*)(keys
),
970 (unsigned int)*(uint32_t*)(keys
+20));
971 if (circuit_init_cpath_crypto(tmp_cpath
, keys
, 0)<0) {
972 log_warn(LD_BUG
,"Circuit initialization failed");
976 circ
->n_digest
= tmp_cpath
->f_digest
;
977 circ
->n_crypto
= tmp_cpath
->f_crypto
;
978 circ
->p_digest
= tmp_cpath
->b_digest
;
979 circ
->p_crypto
= tmp_cpath
->b_crypto
;
980 tmp_cpath
->magic
= 0;
983 if (cell_type
== CELL_CREATED
)
984 memcpy(circ
->handshake_digest
, cell
.payload
+DH_KEY_LEN
, DIGEST_LEN
);
986 memcpy(circ
->handshake_digest
, cell
.payload
+DIGEST_LEN
, DIGEST_LEN
);
988 circ
->is_first_hop
= (cell_type
== CELL_CREATED_FAST
);
990 append_cell_to_circuit_queue(TO_CIRCUIT(circ
),
991 circ
->p_conn
, &cell
, CELL_DIRECTION_IN
);
992 log_debug(LD_CIRC
,"Finished sending 'created' cell.");
994 if (!is_local_IP(circ
->p_conn
->_base
.addr
) &&
995 !connection_or_nonopen_was_started_here(circ
->p_conn
)) {
996 /* record that we could process create cells from a non-local conn
997 * that we didn't initiate; presumably this means that create cells
998 * can reach us too. */
999 router_orport_found_reachable();
1005 /** Choose a length for a circuit of purpose <b>purpose</b>.
1006 * Default length is 3 + the number of endpoints that would give something
1007 * away. If the routerlist <b>routers</b> doesn't have enough routers
1008 * to handle the desired path length, return as large a path length as
1009 * is feasible, except if it's less than 2, in which case return -1.
1012 new_route_len(uint8_t purpose
, extend_info_t
*exit
,
1013 smartlist_t
*routers
)
1015 int num_acceptable_routers
;
1018 tor_assert(routers
);
1025 purpose
!= CIRCUIT_PURPOSE_TESTING
&&
1026 purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
1029 log_debug(LD_CIRC
,"Chosen route length %d (%d routers available).",
1030 routelen
, smartlist_len(routers
));
1032 num_acceptable_routers
= count_acceptable_routers(routers
);
1034 if (num_acceptable_routers
< 2) {
1036 "Not enough acceptable routers (%d). Discarding this circuit.",
1037 num_acceptable_routers
);
1041 if (num_acceptable_routers
< routelen
) {
1042 log_info(LD_CIRC
,"Not enough routers: cutting routelen from %d to %d.",
1043 routelen
, num_acceptable_routers
);
1044 routelen
= num_acceptable_routers
;
1050 /** Fetch the list of predicted ports, dup it into a smartlist of
1051 * uint16_t's, remove the ones that are already handled by an
1052 * existing circuit, and return it.
1054 static smartlist_t
*
1055 circuit_get_unhandled_ports(time_t now
)
1057 smartlist_t
*source
= rep_hist_get_predicted_ports(now
);
1058 smartlist_t
*dest
= smartlist_create();
1062 for (i
= 0; i
< smartlist_len(source
); ++i
) {
1063 tmp
= tor_malloc(sizeof(uint16_t));
1064 memcpy(tmp
, smartlist_get(source
, i
), sizeof(uint16_t));
1065 smartlist_add(dest
, tmp
);
1068 circuit_remove_handled_ports(dest
);
1072 /** Return 1 if we already have circuits present or on the way for
1073 * all anticipated ports. Return 0 if we should make more.
1075 * If we're returning 0, set need_uptime and need_capacity to
1076 * indicate any requirements that the unhandled ports have.
1079 circuit_all_predicted_ports_handled(time_t now
, int *need_uptime
,
1084 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
1085 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
1086 tor_assert(need_uptime
);
1087 tor_assert(need_capacity
);
1088 enough
= (smartlist_len(sl
) == 0);
1089 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
1090 port
= smartlist_get(sl
, i
);
1091 if (smartlist_string_num_isin(LongLivedServices
, *port
))
1099 /** Return 1 if <b>router</b> can handle one or more of the ports in
1100 * <b>needed_ports</b>, else return 0.
1103 router_handles_some_port(routerinfo_t
*router
, smartlist_t
*needed_ports
)
1108 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
1109 addr_policy_result_t r
;
1110 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
1112 r
= compare_addr_to_addr_policy(0, port
, router
->exit_policy
);
1113 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
1119 /** Return true iff <b>conn</b> needs another general circuit to be
1122 ap_stream_wants_exit_attention(connection_t
*conn
)
1124 if (conn
->type
== CONN_TYPE_AP
&&
1125 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
1126 !conn
->marked_for_close
&&
1127 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
1128 !circuit_stream_is_being_handled(TO_EDGE_CONN(conn
), 0,
1129 MIN_CIRCUITS_HANDLING_STREAM
))
1134 /** Return a pointer to a suitable router to be the exit node for the
1135 * general-purpose circuit we're about to build.
1137 * Look through the connection array, and choose a router that maximizes
1138 * the number of pending streams that can exit from this router.
1140 * Return NULL if we can't find any suitable routers.
1142 static routerinfo_t
*
1143 choose_good_exit_server_general(routerlist_t
*dir
, int need_uptime
,
1148 int n_pending_connections
= 0;
1149 smartlist_t
*connections
;
1150 int best_support
= -1;
1151 int n_best_support
=0;
1152 smartlist_t
*sl
, *preferredexits
, *excludedexits
;
1153 routerinfo_t
*router
;
1154 or_options_t
*options
= get_options();
1156 connections
= get_connection_array();
1158 /* Count how many connections are waiting for a circuit to be built.
1159 * We use this for log messages now, but in the future we may depend on it.
1161 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1163 if (ap_stream_wants_exit_attention(conn
))
1164 ++n_pending_connections
;
1166 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1167 // n_pending_connections);
1168 /* Now we count, for each of the routers in the directory, how many
1169 * of the pending connections could possibly exit from that
1170 * router (n_supported[i]). (We can't be sure about cases where we
1171 * don't know the IP address of the pending connection.)
1173 n_supported
= tor_malloc(sizeof(int)*smartlist_len(dir
->routers
));
1174 for (i
= 0; i
< smartlist_len(dir
->routers
); ++i
) {/* iterate over routers */
1175 router
= smartlist_get(dir
->routers
, i
);
1176 if (router_is_me(router
)) {
1177 n_supported
[i
] = -1;
1178 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1179 /* XXX there's probably a reverse predecessor attack here, but
1180 * it's slow. should we take this out? -RD
1184 if (!router
->is_running
|| router
->is_bad_exit
) {
1185 n_supported
[i
] = -1;
1186 continue; /* skip routers that are known to be down or bad exits */
1188 if (router_is_unreliable(router
, need_uptime
, need_capacity
, 0)) {
1189 n_supported
[i
] = -1;
1190 continue; /* skip routers that are not suitable */
1192 if (!(router
->is_valid
|| options
->_AllowInvalid
& ALLOW_INVALID_EXIT
)) {
1193 /* if it's invalid and we don't want it */
1194 n_supported
[i
] = -1;
1195 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1196 // router->nickname, i);
1197 continue; /* skip invalid routers */
1199 if (router_exit_policy_rejects_all(router
)) {
1200 n_supported
[i
] = -1;
1201 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1202 // router->nickname, i);
1203 continue; /* skip routers that reject all */
1206 /* iterate over connections */
1207 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1209 if (!ap_stream_wants_exit_attention(conn
))
1210 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1211 if (connection_ap_can_use_exit(TO_EDGE_CONN(conn
), router
)) {
1213 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1214 // router->nickname, i, n_supported[i]);
1216 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1217 // router->nickname, i);
1219 }); /* End looping over connections. */
1220 if (n_supported
[i
] > best_support
) {
1221 /* If this router is better than previous ones, remember its index
1222 * and goodness, and start counting how many routers are this good. */
1223 best_support
= n_supported
[i
]; n_best_support
=1;
1224 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1225 // router->nickname);
1226 } else if (n_supported
[i
] == best_support
) {
1227 /* If this router is _as good_ as the best one, just increment the
1228 * count of equally good routers.*/
1233 "Found %d servers that might support %d/%d pending connections.",
1234 n_best_support
, best_support
>= 0 ? best_support
: 0,
1235 n_pending_connections
);
1237 preferredexits
= smartlist_create();
1238 add_nickname_list_to_smartlist(preferredexits
,options
->ExitNodes
,1);
1240 excludedexits
= smartlist_create();
1241 add_nickname_list_to_smartlist(excludedexits
,options
->ExcludeNodes
,0);
1243 sl
= smartlist_create();
1245 /* If any routers definitely support any pending connections, choose one
1247 if (best_support
> 0) {
1248 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++)
1249 if (n_supported
[i
] == best_support
)
1250 smartlist_add(sl
, smartlist_get(dir
->routers
, i
));
1252 smartlist_subtract(sl
,excludedexits
);
1253 if (options
->StrictExitNodes
|| smartlist_overlap(sl
,preferredexits
))
1254 smartlist_intersect(sl
,preferredexits
);
1255 router
= routerlist_sl_choose_by_bandwidth(sl
, 1);
1257 /* Either there are no pending connections, or no routers even seem to
1258 * possibly support any of them. Choose a router at random that satisfies
1259 * at least one predicted exit port. */
1262 smartlist_t
*needed_ports
= circuit_get_unhandled_ports(time(NULL
));
1264 if (best_support
== -1) {
1265 if (need_uptime
|| need_capacity
) {
1267 "We couldn't find any live%s%s routers; falling back "
1268 "to list of all routers.",
1269 need_capacity
?", fast":"",
1270 need_uptime
?", stable":"");
1271 smartlist_free(preferredexits
);
1272 smartlist_free(excludedexits
);
1274 tor_free(n_supported
);
1275 return choose_good_exit_server_general(dir
, 0, 0);
1277 log_notice(LD_CIRC
, "All routers are down or won't exit -- choosing a "
1278 "doomed exit at random.");
1280 for (try = 0; try < 2; try++) {
1281 /* try once to pick only from routers that satisfy a needed port,
1282 * then if there are none, pick from any that support exiting. */
1283 for (i
= 0; i
< smartlist_len(dir
->routers
); i
++) {
1284 router
= smartlist_get(dir
->routers
, i
);
1285 if (n_supported
[i
] != -1 &&
1286 (try || router_handles_some_port(router
, needed_ports
))) {
1287 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1288 // try, router->nickname);
1289 smartlist_add(sl
, router
);
1293 smartlist_subtract(sl
,excludedexits
);
1294 if (options
->StrictExitNodes
|| smartlist_overlap(sl
,preferredexits
))
1295 smartlist_intersect(sl
,preferredexits
);
1296 /* XXX sometimes the above results in null, when the requested
1297 * exit node is down. we should pick it anyway. */
1298 router
= routerlist_sl_choose_by_bandwidth(sl
, 1);
1302 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
1303 smartlist_free(needed_ports
);
1306 smartlist_free(preferredexits
);
1307 smartlist_free(excludedexits
);
1309 tor_free(n_supported
);
1311 log_info(LD_CIRC
, "Chose exit server '%s'", router
->nickname
);
1314 if (options
->StrictExitNodes
) {
1316 "No specified exit routers seem to be running, and "
1317 "StrictExitNodes is set: can't choose an exit.");
1322 /** Return a pointer to a suitable router to be the exit node for the
1323 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1324 * if no router is suitable).
1326 * For general-purpose circuits, pass it off to
1327 * choose_good_exit_server_general()
1329 * For client-side rendezvous circuits, choose a random node, weighted
1330 * toward the preferences in 'options'.
1332 static routerinfo_t
*
1333 choose_good_exit_server(uint8_t purpose
, routerlist_t
*dir
,
1334 int need_uptime
, int need_capacity
, int is_internal
)
1336 or_options_t
*options
= get_options();
1338 case CIRCUIT_PURPOSE_C_GENERAL
:
1339 if (is_internal
) /* pick it like a middle hop */
1340 return router_choose_random_node(NULL
, get_options()->ExcludeNodes
,
1341 NULL
, need_uptime
, need_capacity
, 0,
1342 get_options()->_AllowInvalid
& ALLOW_INVALID_MIDDLE
, 0, 0);
1344 return choose_good_exit_server_general(dir
,need_uptime
,need_capacity
);
1345 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1346 return router_choose_random_node(
1347 options
->RendNodes
, options
->RendExcludeNodes
,
1348 NULL
, need_uptime
, need_capacity
, 0,
1349 options
->_AllowInvalid
& ALLOW_INVALID_RENDEZVOUS
, 0, 0);
1351 log_warn(LD_BUG
,"Unhandled purpose %d", purpose
);
1352 tor_fragile_assert();
1356 /** Decide a suitable length for circ's cpath, and pick an exit
1357 * router (or use <b>exit</b> if provided). Store these in the
1358 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1360 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1362 cpath_build_state_t
*state
= circ
->build_state
;
1363 routerlist_t
*rl
= router_get_routerlist();
1365 if (state
->onehop_tunnel
) {
1366 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel.");
1367 state
->desired_path_len
= 1;
1369 int r
= new_route_len(circ
->_base
.purpose
, exit
, rl
->routers
);
1370 if (r
< 1) /* must be at least 1 */
1372 state
->desired_path_len
= r
;
1375 if (exit
) { /* the circuit-builder pre-requested one */
1376 log_info(LD_CIRC
,"Using requested exit node '%s'", exit
->nickname
);
1377 exit
= extend_info_dup(exit
);
1378 } else { /* we have to decide one */
1379 routerinfo_t
*router
=
1380 choose_good_exit_server(circ
->_base
.purpose
, rl
, state
->need_uptime
,
1381 state
->need_capacity
, state
->is_internal
);
1383 log_warn(LD_CIRC
,"failed to choose an exit server");
1386 exit
= extend_info_from_router(router
);
1388 state
->chosen_exit
= exit
;
1392 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1393 * hop to the cpath reflecting this. Don't send the next extend cell --
1394 * the caller will do this if it wants to.
1397 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1399 cpath_build_state_t
*state
;
1403 state
= circ
->build_state
;
1405 if (state
->chosen_exit
)
1406 extend_info_free(state
->chosen_exit
);
1407 state
->chosen_exit
= extend_info_dup(exit
);
1409 ++circ
->build_state
->desired_path_len
;
1410 onion_append_hop(&circ
->cpath
, exit
);
1414 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1415 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1416 * send the next extend cell to begin connecting to that hop.
1419 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
1422 circuit_append_new_exit(circ
, exit
);
1423 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
1424 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
1425 log_warn(LD_CIRC
, "Couldn't extend circuit to new point '%s'.",
1427 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
1433 /** Return the number of routers in <b>routers</b> that are currently up
1434 * and available for building circuits through.
1437 count_acceptable_routers(smartlist_t
*routers
)
1443 n
= smartlist_len(routers
);
1445 r
= smartlist_get(routers
, i
);
1446 // log_debug(LD_CIRC,
1447 // "Contemplating whether router %d (%s) is a new option.",
1449 if (r
->is_running
== 0) {
1450 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1453 if (r
->is_valid
== 0) {
1454 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1456 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1457 * allows this node in some places, then we're getting an inaccurate
1458 * count. For now, be conservative and don't count it. But later we
1459 * should try to be smarter. */
1462 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1464 ; /* C requires an explicit statement after the label */
1470 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1471 * This function is used to extend cpath by another hop.
1474 onion_append_to_cpath(crypt_path_t
**head_ptr
, crypt_path_t
*new_hop
)
1477 new_hop
->next
= (*head_ptr
);
1478 new_hop
->prev
= (*head_ptr
)->prev
;
1479 (*head_ptr
)->prev
->next
= new_hop
;
1480 (*head_ptr
)->prev
= new_hop
;
1482 *head_ptr
= new_hop
;
1483 new_hop
->prev
= new_hop
->next
= new_hop
;
1487 /** Pick a random server digest that's running a Tor version that
1488 * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
1489 * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
1490 * probably already connected to them.
1492 * We only return one, so this doesn't become stupid when the
1493 * whole network has upgraded. */
1495 compute_preferred_testing_list(const char *answer
)
1497 smartlist_t
*choices
;
1498 routerlist_t
*rl
= router_get_routerlist();
1499 routerinfo_t
*router
;
1502 if (answer
) /* they have one in mind -- easy */
1503 return tor_strdup(answer
);
1505 choices
= smartlist_create();
1506 /* now count up our choices */
1507 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
1508 if (r
->is_running
&& r
->is_valid
&&
1509 ((tor_version_as_new_as(r
->platform
,"0.1.1.21-cvs") &&
1510 !tor_version_as_new_as(r
->platform
,"0.1.2.0-alpha-cvs")) ||
1511 tor_version_as_new_as(r
->platform
,"0.1.2.1-alpha")) &&
1512 !is_local_IP(r
->addr
) &&
1513 !router_get_trusteddirserver_by_digest(r
->cache_info
.identity_digest
))
1514 smartlist_add(choices
, r
));
1515 router
= smartlist_choose(choices
);
1516 smartlist_free(choices
);
1518 log_info(LD_CIRC
, "Looking for middle server that doesn't have the "
1519 "reachability bug, but didn't find one. Oh well.");
1522 log_info(LD_CIRC
, "Looking for middle server that doesn't have the "
1523 "reachability bug, and chose '%s'. Great.", router
->nickname
);
1524 s
= tor_malloc(HEX_DIGEST_LEN
+2);
1526 base16_encode(s
+1, HEX_DIGEST_LEN
+1,
1527 router
->cache_info
.identity_digest
, DIGEST_LEN
);
1531 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1532 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1533 * to length <b>cur_len</b> to decide a suitable middle hop for a
1534 * circuit. In particular, make sure we don't pick the exit node or its
1535 * family, and make sure we don't duplicate any previous nodes or their
1537 static routerinfo_t
*
1538 choose_good_middle_server(uint8_t purpose
,
1539 cpath_build_state_t
*state
,
1544 routerinfo_t
*r
, *choice
;
1545 crypt_path_t
*cpath
;
1546 smartlist_t
*excluded
;
1547 or_options_t
*options
= get_options();
1548 char *preferred
= NULL
;
1549 tor_assert(_CIRCUIT_PURPOSE_MIN
<= purpose
&&
1550 purpose
<= _CIRCUIT_PURPOSE_MAX
);
1552 log_debug(LD_CIRC
, "Contemplating intermediate hop: random choice.");
1553 excluded
= smartlist_create();
1554 if ((r
= build_state_get_exit_router(state
))) {
1555 smartlist_add(excluded
, r
);
1556 routerlist_add_family(excluded
, r
);
1558 if ((r
= routerlist_find_my_routerinfo())) {
1559 smartlist_add(excluded
, r
);
1560 routerlist_add_family(excluded
, r
);
1562 for (i
= 0, cpath
= head
; i
< cur_len
; ++i
, cpath
=cpath
->next
) {
1563 if ((r
= router_get_by_digest(cpath
->extend_info
->identity_digest
))) {
1564 smartlist_add(excluded
, r
);
1565 routerlist_add_family(excluded
, r
);
1568 if (purpose
== CIRCUIT_PURPOSE_TESTING
)
1569 preferred
= compute_preferred_testing_list(options
->TestVia
);
1570 choice
= router_choose_random_node(preferred
,
1571 options
->ExcludeNodes
, excluded
,
1572 state
->need_uptime
, state
->need_capacity
, 0,
1573 options
->_AllowInvalid
& ALLOW_INVALID_MIDDLE
, 0, 0);
1575 tor_free(preferred
);
1576 smartlist_free(excluded
);
1580 /** Pick a good entry server for the circuit to be built according to
1581 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
1582 * router (if we're an OR), and respect firewall settings; if we're
1583 * configured to use entry guards, return one.
1585 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
1586 * guard, not for any particular circuit.
1588 static routerinfo_t
*
1589 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
)
1591 routerinfo_t
*r
, *choice
;
1592 smartlist_t
*excluded
;
1593 or_options_t
*options
= get_options();
1594 (void)purpose
; /* not used yet. */
1596 if (state
&& options
->UseEntryGuards
) {
1597 return choose_random_entry(state
);
1600 excluded
= smartlist_create();
1602 if (state
&& (r
= build_state_get_exit_router(state
))) {
1603 smartlist_add(excluded
, r
);
1604 routerlist_add_family(excluded
, r
);
1606 if ((r
= routerlist_find_my_routerinfo())) {
1607 smartlist_add(excluded
, r
);
1608 routerlist_add_family(excluded
, r
);
1610 if (firewall_is_fascist_or()) {
1611 /* exclude all ORs that listen on the wrong port */
1612 routerlist_t
*rl
= router_get_routerlist();
1615 for (i
=0; i
< smartlist_len(rl
->routers
); i
++) {
1616 r
= smartlist_get(rl
->routers
, i
);
1617 if (!fascist_firewall_allows_address_or(r
->addr
,r
->or_port
))
1618 smartlist_add(excluded
, r
);
1621 /* and exclude current entry guards, if applicable */
1622 if (options
->UseEntryGuards
&& entry_guards
) {
1623 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1625 if ((r
= router_get_by_digest(entry
->identity
)))
1626 smartlist_add(excluded
, r
);
1630 choice
= router_choose_random_node(
1631 NULL
, options
->ExcludeNodes
,
1632 excluded
, state
? state
->need_uptime
: 0,
1633 state
? state
->need_capacity
: 0,
1635 options
->_AllowInvalid
& ALLOW_INVALID_ENTRY
, 0, 0);
1636 smartlist_free(excluded
);
1640 /** Return the first non-open hop in cpath, or return NULL if all
1642 static crypt_path_t
*
1643 onion_next_hop_in_cpath(crypt_path_t
*cpath
)
1645 crypt_path_t
*hop
= cpath
;
1647 if (hop
->state
!= CPATH_STATE_OPEN
)
1650 } while (hop
!= cpath
);
1654 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
1655 * based on <b>state</b>. Append the hop info to head_ptr.
1658 onion_extend_cpath(origin_circuit_t
*circ
)
1660 uint8_t purpose
= circ
->_base
.purpose
;
1661 cpath_build_state_t
*state
= circ
->build_state
;
1662 int cur_len
= circuit_get_cpath_len(circ
);
1663 extend_info_t
*info
= NULL
;
1665 if (cur_len
>= state
->desired_path_len
) {
1666 log_debug(LD_CIRC
, "Path is complete: %d steps long",
1667 state
->desired_path_len
);
1671 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
1672 state
->desired_path_len
);
1674 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
1675 info
= extend_info_dup(state
->chosen_exit
);
1676 } else if (cur_len
== 0) { /* picking first node */
1677 routerinfo_t
*r
= choose_good_entry_server(purpose
, state
);
1679 info
= extend_info_from_router(r
);
1682 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
1684 info
= extend_info_from_router(r
);
1688 log_warn(LD_CIRC
,"Failed to find node for hop %d of our path. Discarding "
1689 "this circuit.", cur_len
);
1693 log_debug(LD_CIRC
,"Chose router %s for hop %d (exit is %s)",
1694 info
->nickname
, cur_len
+1, build_state_get_exit_nickname(state
));
1696 onion_append_hop(&circ
->cpath
, info
);
1697 extend_info_free(info
);
1701 /** Create a new hop, annotate it with information about its
1702 * corresponding router <b>choice</b>, and append it to the
1703 * end of the cpath <b>head_ptr</b>. */
1705 onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
)
1707 crypt_path_t
*hop
= tor_malloc_zero(sizeof(crypt_path_t
));
1709 /* link hop into the cpath, at the end. */
1710 onion_append_to_cpath(head_ptr
, hop
);
1712 hop
->magic
= CRYPT_PATH_MAGIC
;
1713 hop
->state
= CPATH_STATE_CLOSED
;
1715 hop
->extend_info
= extend_info_dup(choice
);
1717 hop
->package_window
= CIRCWINDOW_START
;
1718 hop
->deliver_window
= CIRCWINDOW_START
;
1723 /** Allocate a new extend_info object based on the various arguments. */
1725 extend_info_alloc(const char *nickname
, const char *digest
,
1726 crypto_pk_env_t
*onion_key
,
1727 uint32_t addr
, uint16_t port
)
1729 extend_info_t
*info
= tor_malloc_zero(sizeof(extend_info_t
));
1730 memcpy(info
->identity_digest
, digest
, DIGEST_LEN
);
1731 strlcpy(info
->nickname
, nickname
, sizeof(info
->nickname
));
1733 info
->onion_key
= crypto_pk_dup_key(onion_key
);
1739 /** Allocate and return a new extend_info_t that can be used to build a
1740 * circuit to or through the router <b>r</b>. */
1742 extend_info_from_router(routerinfo_t
*r
)
1745 return extend_info_alloc(r
->nickname
, r
->cache_info
.identity_digest
,
1746 r
->onion_pkey
, r
->addr
, r
->or_port
);
1750 /** What router purpose is <b>digest</b>?
1751 * It's a general purpose router unless it's on our bridges list.
1754 get_router_purpose_from_digest(char *digest
)
1756 if (digest_is_a_bridge(digest
))
1757 return ROUTER_PURPOSE_BRIDGE
;
1758 return ROUTER_PURPOSE_GENERAL
;
1763 /** Allocate and return a new extend_info_t that can be used to build a
1764 * circuit to or through the router <b>r</b>. */
1766 extend_info_from_routerstatus(routerstatus_t
*s
)
1769 /* routerstatus doesn't know onion_key; leave it NULL */
1770 return extend_info_alloc(s
->nickname
, s
->identity_digest
,
1771 NULL
, s
->addr
, s
->or_port
);
1772 // get_router_purpose_from_digest(s->identity_digest));
1776 /** Release storage held by an extend_info_t struct. */
1778 extend_info_free(extend_info_t
*info
)
1781 if (info
->onion_key
)
1782 crypto_free_pk_env(info
->onion_key
);
1786 /** Allocate and return a new extend_info_t with the same contents as
1789 extend_info_dup(extend_info_t
*info
)
1791 extend_info_t
*newinfo
;
1793 newinfo
= tor_malloc(sizeof(extend_info_t
));
1794 memcpy(newinfo
, info
, sizeof(extend_info_t
));
1795 if (info
->onion_key
)
1796 newinfo
->onion_key
= crypto_pk_dup_key(info
->onion_key
);
1798 newinfo
->onion_key
= NULL
;
1802 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
1803 * If there is no chosen exit, or if we don't know the routerinfo_t for
1804 * the chosen exit, return NULL.
1807 build_state_get_exit_router(cpath_build_state_t
*state
)
1809 if (!state
|| !state
->chosen_exit
)
1811 return router_get_by_digest(state
->chosen_exit
->identity_digest
);
1814 /** Return the nickname for the chosen exit router in <b>state</b>. If
1815 * there is no chosen exit, or if we don't know the routerinfo_t for the
1816 * chosen exit, return NULL.
1819 build_state_get_exit_nickname(cpath_build_state_t
*state
)
1821 if (!state
|| !state
->chosen_exit
)
1823 return state
->chosen_exit
->nickname
;
1826 /** Check whether the entry guard <b>e</b> is usable, given the directory
1827 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
1828 * configuration (in <b>options</b>). Set <b>e</b>->bad_since
1829 * accordingly. Return true iff the entry guard's status changes. */
1831 entry_guard_set_status(entry_guard_t
*e
, routerinfo_t
*ri
,
1832 time_t now
, or_options_t
*options
)
1834 const char *reason
= NULL
;
1835 char buf
[HEX_DIGEST_LEN
+1];
1838 tor_assert(options
);
1840 /* Do we want to mark this guard as bad? */
1842 reason
= "unlisted";
1843 else if (!ri
->is_running
)
1845 else if (options
->UseBridges
&& ri
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1846 reason
= "not a bridge";
1847 else if (!options
->UseBridges
&& !ri
->is_possible_guard
&&
1848 !router_nickname_is_in_list(ri
, options
->EntryNodes
))
1849 reason
= "not recommended as a guard";
1850 else if (router_nickname_is_in_list(ri
, options
->ExcludeNodes
))
1851 reason
= "excluded";
1853 if (reason
&& ! e
->bad_since
) {
1854 /* Router is newly bad. */
1855 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1856 log_info(LD_CIRC
, "Entry guard %s (%s) is %s: marking as unusable.",
1857 e
->nickname
, buf
, reason
);
1860 control_event_guard(e
->nickname
, e
->identity
, "BAD");
1862 } else if (!reason
&& e
->bad_since
) {
1863 /* There's nothing wrong with the router any more. */
1864 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
1865 log_info(LD_CIRC
, "Entry guard %s (%s) is no longer unusable: "
1866 "marking as ok.", e
->nickname
, buf
);
1869 control_event_guard(e
->nickname
, e
->identity
, "GOOD");
1876 /** Return true iff enough time has passed since we last tried connect to the
1877 * unreachable guard <b>e</b> that we're willing to try again. */
1879 entry_is_time_to_retry(entry_guard_t
*e
, time_t now
)
1882 if (e
->last_attempted
< e
->unreachable_since
)
1884 diff
= now
- e
->unreachable_since
;
1886 return now
> (e
->last_attempted
+ 60*60);
1887 else if (diff
< 3*24*60*60)
1888 return now
> (e
->last_attempted
+ 4*60*60);
1889 else if (diff
< 7*24*60*60)
1890 return now
> (e
->last_attempted
+ 18*60*60);
1892 return now
> (e
->last_attempted
+ 36*60*60);
1895 /** Return the router corresponding to <b>e</b>, if <b>e</b> is
1896 * working well enough that we are willing to use it as an entry
1897 * right now. (Else return NULL.) In particular, it must be
1898 * - Listed as either up or never yet contacted;
1899 * - Present in the routerlist;
1900 * - Listed as 'stable' or 'fast' by the current dirserver concensus,
1901 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
1902 * (This check is currently redundant with the Guard flag, but in
1903 * the future that might change. Best to leave it in for now.)
1904 * - Allowed by our current ReachableAddresses config option; and
1905 * - Currently thought to be reachable by us (unless assume_reachable
1908 static INLINE routerinfo_t
*
1909 entry_is_live(entry_guard_t
*e
, int need_uptime
, int need_capacity
,
1910 int assume_reachable
)
1915 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
1916 if ((!assume_reachable
&& !e
->can_retry
) &&
1917 e
->unreachable_since
&& !entry_is_time_to_retry(e
, time(NULL
)))
1919 r
= router_get_by_digest(e
->identity
);
1922 if (get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
1924 if (!get_options()->UseBridges
&& r
->purpose
!= ROUTER_PURPOSE_GENERAL
)
1926 if (router_is_unreliable(r
, need_uptime
, need_capacity
, 0))
1928 if (firewall_is_fascist_or() &&
1929 !fascist_firewall_allows_address_or(r
->addr
,r
->or_port
))
1934 /** Return the number of entry guards that we think are usable. */
1936 num_live_entry_guards(void)
1941 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1943 if (entry_is_live(entry
, 0, 1, 0))
1949 /** Return 1 if <b>digest</b> matches the identity of any node
1950 * in the entry_guards list. Else return 0. */
1952 is_an_entry_guard(const char *digest
)
1954 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
1955 if (!memcmp(digest
, entry
->identity
, DIGEST_LEN
))
1961 /** Dump a description of our list of entry guards to the log at level
1962 * <b>severity</b>. */
1964 log_entry_guards(int severity
)
1966 smartlist_t
*elements
= smartlist_create();
1970 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
1972 tor_snprintf(buf
, sizeof(buf
), "%s (%s%s)",
1974 e
->bad_since
? "down " : "up ",
1975 e
->made_contact
? "made-contact" : "never-contacted");
1976 smartlist_add(elements
, tor_strdup(buf
));
1979 s
= smartlist_join_strings(elements
, ",", 0, NULL
);
1980 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
1981 smartlist_free(elements
);
1982 log_fn(severity
,LD_CIRC
,"%s",s
);
1986 /** Called when one or more guards that we would previously have used for some
1987 * purpose are no longer in use because a higher-priority guard has become
1990 control_event_guard_deferred(void)
1992 /* XXXX We don't actually have a good way to figure out _how many_ entries
1993 * are live for some purpose. We need an entry_is_even_slightly_live()
1994 * function for this to work right. NumEntryGuards isn't reliable: if we
1995 * need guards with weird properties, we can have more than that number
2000 or_options_t
*options
= get_options();
2003 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2005 if (entry_is_live(entry
, 0, 1, 0)) {
2006 if (n
++ == options
->NumEntryGuards
) {
2007 control_event_guard(entry
->nickname
, entry
->identity
, "DEFERRED");
2015 /** Add a new (preferably stable and fast) router to our
2016 * entry_guards list. Return a pointer to the router if we succeed,
2017 * or NULL if we can't find any more suitable entries.
2019 * If <b>chosen</b> is defined, use that one, and if it's not
2020 * already in our entry_guards list, put it at the *beginning*.
2021 * Else, put the one we pick at the end of the list. */
2022 static routerinfo_t
*
2023 add_an_entry_guard(routerinfo_t
*chosen
)
2025 routerinfo_t
*router
;
2026 entry_guard_t
*entry
;
2030 if (is_an_entry_guard(router
->cache_info
.identity_digest
))
2033 router
= choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL
, NULL
);
2037 entry
= tor_malloc_zero(sizeof(entry_guard_t
));
2038 log_info(LD_CIRC
, "Chose '%s' as new entry guard.", router
->nickname
);
2039 strlcpy(entry
->nickname
, router
->nickname
, sizeof(entry
->nickname
));
2040 memcpy(entry
->identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
2041 if (chosen
) /* prepend */
2042 smartlist_insert(entry_guards
, 0, entry
);
2044 smartlist_add(entry_guards
, entry
);
2045 control_event_guard(entry
->nickname
, entry
->identity
, "NEW");
2046 control_event_guard_deferred();
2047 log_entry_guards(LOG_INFO
);
2051 /** If the use of entry guards is configured, choose more entry guards
2052 * until we have enough in the list. */
2054 pick_entry_guards(void)
2056 or_options_t
*options
= get_options();
2059 tor_assert(entry_guards
);
2061 while (num_live_entry_guards() < options
->NumEntryGuards
) {
2062 if (!add_an_entry_guard(NULL
))
2067 entry_guards_changed();
2070 /** Release all storage held by the list of entry guards. */
2072 entry_guards_free_all(void)
2075 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, tor_free(e
));
2076 smartlist_free(entry_guards
);
2077 entry_guards
= NULL
;
2081 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2082 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2083 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2085 /** Remove all entry guards that have been down or unlisted for so
2086 * long that we don't think they'll come up again. Return 1 if we
2087 * removed any, or 0 if we did nothing. */
2089 remove_dead_entries(void)
2091 char dbuf
[HEX_DIGEST_LEN
+1];
2092 char tbuf
[ISO_TIME_LEN
+1];
2093 time_t now
= time(NULL
);
2097 for (i
= 0; i
< smartlist_len(entry_guards
); ) {
2098 entry_guard_t
*entry
= smartlist_get(entry_guards
, i
);
2099 if (entry
->bad_since
&&
2100 entry
->bad_since
+ ENTRY_GUARD_REMOVE_AFTER
< now
) {
2102 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
2103 format_local_iso_time(tbuf
, entry
->bad_since
);
2104 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been down or unlisted "
2105 "since %s local time; removing.",
2106 entry
->nickname
, dbuf
, tbuf
);
2107 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
2109 smartlist_del_keeporder(entry_guards
, i
);
2110 log_entry_guards(LOG_INFO
);
2115 return changed
? 1 : 0;
2118 /** A new directory or router-status has arrived; update the down/listed
2119 * status of the entry guards.
2121 * An entry is 'down' if the directory lists it as nonrunning.
2122 * An entry is 'unlisted' if the directory doesn't include it.
2125 entry_guards_compute_status(void)
2127 /* Don't call this on startup; only on a fresh download. Otherwise we'll
2128 * think that things are unlisted. */
2131 int severity
= LOG_INFO
;
2132 or_options_t
*options
;
2136 options
= get_options();
2140 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2142 routerinfo_t
*r
= router_get_by_digest(entry
->identity
);
2143 if (entry_guard_set_status(entry
, r
, now
, options
))
2146 log_info(LD_CIRC
, "Summary: Entry '%s' is %s, %s and %s.",
2148 entry
->unreachable_since
? "unreachable" : "reachable",
2149 entry
->bad_since
? "unusable" : "usable",
2150 entry_is_live(entry
, 0, 1, 0) ? "live" : "not live");
2153 if (remove_dead_entries())
2157 log_fn(severity
, LD_CIRC
, " (%d/%d entry guards are usable/new)",
2158 num_live_entry_guards(), smartlist_len(entry_guards
));
2159 log_entry_guards(LOG_INFO
);
2160 entry_guards_changed();
2164 /** Called when a connection to an OR with the identity digest <b>digest</b>
2165 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
2166 * If the OR is an entry, change that entry's up/down status.
2167 * Return 0 normally, or -1 if we want to tear down the new connection.
2170 entry_guard_register_connect_status(const char *digest
, int succeeded
,
2174 int refuse_conn
= 0;
2175 int first_contact
= 0;
2176 entry_guard_t
*entry
= NULL
;
2178 char buf
[HEX_DIGEST_LEN
+1];
2183 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2185 if (!memcmp(e
->identity
, digest
, DIGEST_LEN
)) {
2195 base16_encode(buf
, sizeof(buf
), entry
->identity
, DIGEST_LEN
);
2198 if (entry
->unreachable_since
) {
2199 log_info(LD_CIRC
, "Entry guard '%s' (%s) is now reachable again. Good.",
2200 entry
->nickname
, buf
);
2201 entry
->can_retry
= 0;
2202 entry
->unreachable_since
= 0;
2203 entry
->last_attempted
= now
;
2204 control_event_guard(entry
->nickname
, entry
->identity
, "UP");
2207 if (!entry
->made_contact
) {
2208 entry
->made_contact
= 1;
2209 first_contact
= changed
= 1;
2211 } else { /* ! succeeded */
2212 if (!entry
->made_contact
) {
2213 /* We've never connected to this one. */
2215 "Connection to never-contacted entry guard '%s' (%s) failed. "
2216 "Removing from the list. %d/%d entry guards usable/new.",
2217 entry
->nickname
, buf
,
2218 num_live_entry_guards()-1, smartlist_len(entry_guards
)-1);
2220 smartlist_del_keeporder(entry_guards
, idx
);
2221 log_entry_guards(LOG_INFO
);
2223 } else if (!entry
->unreachable_since
) {
2224 log_info(LD_CIRC
, "Unable to connect to entry guard '%s' (%s). "
2225 "Marking as unreachable.", entry
->nickname
, buf
);
2226 entry
->unreachable_since
= entry
->last_attempted
= now
;
2227 control_event_guard(entry
->nickname
, entry
->identity
, "DOWN");
2230 char tbuf
[ISO_TIME_LEN
+1];
2231 format_iso_time(tbuf
, entry
->unreachable_since
);
2232 log_debug(LD_CIRC
, "Failed to connect to unreachable entry guard "
2233 "'%s' (%s). It has been unreachable since %s.",
2234 entry
->nickname
, buf
, tbuf
);
2235 entry
->last_attempted
= now
;
2238 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
2241 if (first_contact
) {
2242 /* We've just added a new long-term entry guard. Perhaps the network just
2243 * came back? We should give our earlier entries another try too,
2244 * and close this connection so we don't use it before we've given
2245 * the others a shot. */
2246 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2249 if (e
->made_contact
) {
2250 routerinfo_t
*r
= entry_is_live(e
, 0, 1, 1);
2251 if (r
&& e
->unreachable_since
) {
2259 "Connected to new entry guard '%s' (%s). Marking earlier "
2260 "entry guards up. %d/%d entry guards usable/new.",
2261 entry
->nickname
, buf
,
2262 num_live_entry_guards(), smartlist_len(entry_guards
));
2263 log_entry_guards(LOG_INFO
);
2269 entry_guards_changed();
2270 return refuse_conn
? -1 : 0;
2273 /** When we try to choose an entry guard, should we parse and add
2274 * config's EntryNodes first? */
2275 static int should_add_entry_nodes
= 0;
2277 /** Called when the value of EntryNodes changes in our configuration. */
2279 entry_nodes_should_be_added(void)
2281 log_info(LD_CIRC
, "New EntryNodes config option detected. Will use.");
2282 should_add_entry_nodes
= 1;
2285 /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
2286 * of guard nodes, at the front. */
2288 entry_guards_prepend_from_config(void)
2290 or_options_t
*options
= get_options();
2291 smartlist_t
*entry_routers
, *entry_fps
;
2292 smartlist_t
*old_entry_guards_on_list
, *old_entry_guards_not_on_list
;
2293 tor_assert(entry_guards
);
2295 should_add_entry_nodes
= 0;
2297 if (!options
->EntryNodes
) {
2298 /* It's possible that a controller set EntryNodes, thus making
2299 * should_add_entry_nodes set, then cleared it again, all before the
2300 * call to choose_random_entry() that triggered us. If so, just return.
2305 log_info(LD_CIRC
,"Adding configured EntryNodes '%s'.",
2306 options
->EntryNodes
);
2308 entry_routers
= smartlist_create();
2309 entry_fps
= smartlist_create();
2310 old_entry_guards_on_list
= smartlist_create();
2311 old_entry_guards_not_on_list
= smartlist_create();
2313 /* Split entry guards into those on the list and those not. */
2314 add_nickname_list_to_smartlist(entry_routers
, options
->EntryNodes
, 0);
2315 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
,
2316 smartlist_add(entry_fps
,ri
->cache_info
.identity_digest
));
2317 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, {
2318 if (smartlist_digest_isin(entry_fps
, e
->identity
))
2319 smartlist_add(old_entry_guards_on_list
, e
);
2321 smartlist_add(old_entry_guards_not_on_list
, e
);
2324 /* Remove all currently configured entry guards from entry_routers. */
2325 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2326 if (is_an_entry_guard(ri
->cache_info
.identity_digest
)) {
2327 SMARTLIST_DEL_CURRENT(entry_routers
, ri
);
2331 /* Now build the new entry_guards list. */
2332 smartlist_clear(entry_guards
);
2333 /* First, the previously configured guards that are in EntryNodes. */
2334 smartlist_add_all(entry_guards
, old_entry_guards_on_list
);
2335 /* Next, the rest of EntryNodes */
2336 SMARTLIST_FOREACH(entry_routers
, routerinfo_t
*, ri
, {
2337 add_an_entry_guard(ri
);
2339 /* Finally, the remaining EntryNodes, unless we're strict */
2340 if (options
->StrictEntryNodes
) {
2341 SMARTLIST_FOREACH(old_entry_guards_not_on_list
, entry_guard_t
*, e
,
2344 smartlist_add_all(entry_guards
, old_entry_guards_not_on_list
);
2347 smartlist_free(entry_routers
);
2348 smartlist_free(entry_fps
);
2349 smartlist_free(old_entry_guards_on_list
);
2350 smartlist_free(old_entry_guards_not_on_list
);
2351 entry_guards_changed();
2354 /** Return 1 if we're fine adding arbitrary routers out of the
2355 * directory to our entry guard list. Else return 0. */
2357 can_grow_entry_list(or_options_t
*options
)
2359 if (options
->StrictEntryNodes
)
2361 if (options
->UseBridges
)
2366 /** Pick a live (up and listed) entry guard from entry_guards. If
2367 * <b>state</b> is non-NULL, this is for a specific circuit --
2368 * make sure not to pick this circuit's exit or any node in the
2369 * exit's family. If <b>state</b> is NULL, we're looking for a random
2370 * guard (likely a bridge). */
2372 choose_random_entry(cpath_build_state_t
*state
)
2374 or_options_t
*options
= get_options();
2375 smartlist_t
*live_entry_guards
= smartlist_create();
2376 smartlist_t
*exit_family
= smartlist_create();
2377 routerinfo_t
*chosen_exit
= state
?build_state_get_exit_router(state
) : NULL
;
2378 routerinfo_t
*r
= NULL
;
2379 int need_uptime
= state
? state
->need_uptime
: 0;
2380 int need_capacity
= state
? state
->need_capacity
: 0;
2383 smartlist_add(exit_family
, chosen_exit
);
2384 routerlist_add_family(exit_family
, chosen_exit
);
2388 entry_guards
= smartlist_create();
2390 if (should_add_entry_nodes
)
2391 entry_guards_prepend_from_config();
2393 if (can_grow_entry_list(options
) &&
2395 smartlist_len(entry_guards
) < options
->NumEntryGuards
))
2396 pick_entry_guards();
2399 smartlist_clear(live_entry_guards
);
2400 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
2402 r
= entry_is_live(entry
, need_uptime
, need_capacity
, 0);
2403 if (r
&& !smartlist_isin(exit_family
, r
)) {
2404 smartlist_add(live_entry_guards
, r
);
2405 if (smartlist_len(live_entry_guards
) >= options
->NumEntryGuards
)
2406 break; /* we have enough */
2410 /* Try to have at least 2 choices available. This way we don't
2411 * get stuck with a single live-but-crummy entry and just keep
2413 * (We might get 2 live-but-crummy entry guards, but so be it.) */
2414 if (smartlist_len(live_entry_guards
) < 2) {
2415 if (can_grow_entry_list(options
)) {
2416 /* still no? try adding a new entry then */
2417 /* XXX if guard doesn't imply fast and stable, then we need
2418 * to tell add_an_entry_guard below what we want, or it might
2419 * be a long time til we get it. -RD */
2420 r
= add_an_entry_guard(NULL
);
2422 smartlist_add(live_entry_guards
, r
);
2423 entry_guards_changed();
2426 if (!r
&& need_uptime
) {
2427 need_uptime
= 0; /* try without that requirement */
2430 if (!r
&& need_capacity
) {
2431 /* still no? last attempt, try without requiring capacity */
2435 /* live_entry_guards may be empty below. Oh well, we tried. */
2438 r
= smartlist_choose(live_entry_guards
);
2439 smartlist_free(live_entry_guards
);
2440 smartlist_free(exit_family
);
2444 /** Parse <b>state</b> and learn about the entry guards it describes.
2445 * If <b>set</b> is true, and there are no errors, replace the global
2446 * entry_list with what we find.
2447 * On success, return 0. On failure, alloc into *<b>msg</b> a string
2448 * describing the error, and return -1.
2451 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
2453 entry_guard_t
*node
= NULL
;
2454 smartlist_t
*new_entry_guards
= smartlist_create();
2455 config_line_t
*line
;
2458 for (line
= state
->EntryGuards
; line
; line
= line
->next
) {
2459 if (!strcasecmp(line
->key
, "EntryGuard")) {
2460 smartlist_t
*args
= smartlist_create();
2461 node
= tor_malloc_zero(sizeof(entry_guard_t
));
2462 /* all entry guards on disk have been contacted */
2463 node
->made_contact
= 1;
2464 smartlist_add(new_entry_guards
, node
);
2465 smartlist_split_string(args
, line
->value
, " ",
2466 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2467 if (smartlist_len(args
)<2) {
2468 *msg
= tor_strdup("Unable to parse entry nodes: "
2469 "Too few arguments to EntryGuard");
2470 } else if (!is_legal_nickname(smartlist_get(args
,0))) {
2471 *msg
= tor_strdup("Unable to parse entry nodes: "
2472 "Bad nickname for EntryGuard");
2474 strlcpy(node
->nickname
, smartlist_get(args
,0), MAX_NICKNAME_LEN
+1);
2475 if (base16_decode(node
->identity
, DIGEST_LEN
, smartlist_get(args
,1),
2476 strlen(smartlist_get(args
,1)))<0) {
2477 *msg
= tor_strdup("Unable to parse entry nodes: "
2478 "Bad hex digest for EntryGuard");
2481 SMARTLIST_FOREACH(args
, char*, cp
, tor_free(cp
));
2482 smartlist_free(args
);
2487 time_t last_try
= 0;
2489 *msg
= tor_strdup("Unable to parse entry nodes: "
2490 "EntryGuardDownSince/UnlistedSince without EntryGuard");
2493 if (parse_iso_time(line
->value
, &when
)<0) {
2494 *msg
= tor_strdup("Unable to parse entry nodes: "
2495 "Bad time in EntryGuardDownSince/UnlistedSince");
2498 if (strlen(line
->value
) >= ISO_TIME_LEN
+ISO_TIME_LEN
+1) {
2499 /* ignore failure */
2500 parse_iso_time(line
->value
+ISO_TIME_LEN
+1, &last_try
);
2502 if (!strcasecmp(line
->key
, "EntryGuardDownSince")) {
2503 node
->unreachable_since
= when
;
2504 node
->last_attempted
= last_try
;
2506 node
->bad_since
= when
;
2512 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
, tor_free(e
));
2513 smartlist_free(new_entry_guards
);
2514 } else { /* !*err && set */
2516 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
, tor_free(e
));
2517 smartlist_free(entry_guards
);
2519 entry_guards
= new_entry_guards
;
2520 entry_guards_dirty
= 0;
2522 return *msg
? -1 : 0;
2525 /** Our list of entry guards has changed, or some element of one
2526 * of our entry guards has changed. Write the changes to disk within
2527 * the next few minutes.
2530 entry_guards_changed(void)
2533 entry_guards_dirty
= 1;
2535 /* or_state_save() will call entry_guards_update_state(). */
2536 when
= get_options()->AvoidDiskWrites
? time(NULL
) + 3600 : time(NULL
)+600;
2537 or_state_mark_dirty(get_or_state(), when
);
2540 /** If the entry guard info has not changed, do nothing and return.
2541 * Otherwise, free the EntryGuards piece of <b>state</b> and create
2542 * a new one out of the global entry_guards list, and then mark
2543 * <b>state</b> dirty so it will get saved to disk.
2546 entry_guards_update_state(or_state_t
*state
)
2548 config_line_t
**next
, *line
;
2549 if (! entry_guards_dirty
)
2552 config_free_lines(state
->EntryGuards
);
2553 next
= &state
->EntryGuards
;
2556 entry_guards
= smartlist_create();
2557 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2559 char dbuf
[HEX_DIGEST_LEN
+1];
2560 if (!e
->made_contact
)
2561 continue; /* don't write this one to disk */
2562 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2563 line
->key
= tor_strdup("EntryGuard");
2564 line
->value
= tor_malloc(HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2);
2565 base16_encode(dbuf
, sizeof(dbuf
), e
->identity
, DIGEST_LEN
);
2566 tor_snprintf(line
->value
,HEX_DIGEST_LEN
+MAX_NICKNAME_LEN
+2,
2567 "%s %s", e
->nickname
, dbuf
);
2568 next
= &(line
->next
);
2569 if (e
->unreachable_since
) {
2570 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2571 line
->key
= tor_strdup("EntryGuardDownSince");
2572 line
->value
= tor_malloc(ISO_TIME_LEN
+1+ISO_TIME_LEN
+1);
2573 format_iso_time(line
->value
, e
->unreachable_since
);
2574 if (e
->last_attempted
) {
2575 line
->value
[ISO_TIME_LEN
] = ' ';
2576 format_iso_time(line
->value
+ISO_TIME_LEN
+1, e
->last_attempted
);
2578 next
= &(line
->next
);
2581 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
2582 line
->key
= tor_strdup("EntryGuardUnlistedSince");
2583 line
->value
= tor_malloc(ISO_TIME_LEN
+1);
2584 format_iso_time(line
->value
, e
->bad_since
);
2585 next
= &(line
->next
);
2588 if (!get_options()->AvoidDiskWrites
)
2589 or_state_mark_dirty(get_or_state(), 0);
2590 entry_guards_dirty
= 0;
2593 /** If <b>question</b> is the string "entry-guards", then dump
2594 * to *<b>answer</b> a newly allocated string describing all of
2595 * the nodes in the global entry_guards list. See control-spec.txt
2597 * For backward compatibility, we also handle the string "helper-nodes".
2600 getinfo_helper_entry_guards(control_connection_t
*conn
,
2601 const char *question
, char **answer
)
2603 int use_long_names
= conn
->use_long_names
;
2605 if (!strcmp(question
,"entry-guards") ||
2606 !strcmp(question
,"helper-nodes")) {
2607 smartlist_t
*sl
= smartlist_create();
2608 char tbuf
[ISO_TIME_LEN
+1];
2609 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
2611 entry_guards
= smartlist_create();
2612 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2614 size_t len
= MAX_VERBOSE_NICKNAME_LEN
+ISO_TIME_LEN
+32;
2615 char *c
= tor_malloc(len
);
2616 const char *status
= NULL
;
2618 if (!e
->made_contact
) {
2619 status
= "never-connected";
2620 } else if (e
->bad_since
) {
2621 when
= e
->bad_since
;
2622 status
= "unusable";
2626 if (use_long_names
) {
2627 routerinfo_t
*ri
= router_get_by_digest(e
->identity
);
2629 router_get_verbose_nickname(nbuf
, ri
);
2632 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
2633 /* e->nickname field is not very reliable if we don't know about
2634 * this router any longer; don't include it. */
2637 base16_encode(nbuf
, sizeof(nbuf
), e
->identity
, DIGEST_LEN
);
2640 format_iso_time(tbuf
, when
);
2641 tor_snprintf(c
, len
, "%s %s %s\n", nbuf
, status
, tbuf
);
2643 tor_snprintf(c
, len
, "%s %s\n", nbuf
, status
);
2645 smartlist_add(sl
, c
);
2647 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
2648 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
2657 char identity
[DIGEST_LEN
];
2660 /** A list of known bridges. */
2661 static smartlist_t
*bridge_list
= NULL
;
2663 /** Initialize the bridge list to empty, creating it if needed. */
2665 clear_bridge_list(void)
2668 bridge_list
= smartlist_create();
2669 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, b
, tor_free(b
));
2670 smartlist_clear(bridge_list
);
2673 /** Return 1 if <b>digest</b> is one of our known bridges. */
2675 identity_digest_is_a_bridge(const char *digest
)
2677 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2679 if (!memcmp(bridge
->identity
, digest
, DIGEST_LEN
))
2685 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
2686 * is set, it tells us the identity key too. */
2688 bridge_add_from_config(uint32_t addr
, uint16_t port
, char *digest
)
2690 bridge_info_t
*b
= tor_malloc_zero(sizeof(bridge_info_t
));
2694 memcpy(b
->identity
, digest
, DIGEST_LEN
);
2696 bridge_list
= smartlist_create();
2697 smartlist_add(bridge_list
, b
);
2700 /** For each bridge in our list for which we don't currently have a
2701 * descriptor, fetch a new copy of its descriptor -- either directly
2702 * from the bridge or via a bridge authority. */
2704 fetch_bridge_descriptors(void)
2706 char address_buf
[INET_NTOA_BUF_LEN
+1];
2708 or_options_t
*options
= get_options();
2709 int num_bridge_auths
= get_n_authorities(BRIDGE_AUTHORITY
);
2714 SMARTLIST_FOREACH(bridge_list
, bridge_info_t
*, bridge
,
2716 if (router_get_by_digest(bridge
->identity
))
2717 continue; /* we've already got one. great. */
2718 in
.s_addr
= htonl(bridge
->addr
);
2719 tor_inet_ntoa(&in
, address_buf
, sizeof(address_buf
));
2721 if (tor_digest_is_zero(bridge
->identity
) ||
2722 !options
->UpdateBridgesFromAuthority
||
2723 !num_bridge_auths
) {
2724 if (!connection_get_by_type_addr_port_purpose(
2725 CONN_TYPE_DIR
, bridge
->addr
, bridge
->port
,
2726 DIR_PURPOSE_FETCH_SERVERDESC
)) {
2727 /* we need to ask the bridge itself for its descriptor. */
2728 directory_initiate_command(address_buf
, bridge
->addr
,
2730 1, bridge
->identity
,
2731 DIR_PURPOSE_FETCH_SERVERDESC
,
2732 ROUTER_PURPOSE_BRIDGE
,
2733 0, "authority", NULL
, 0);
2736 /* we have a digest and we want to ask an authority. */
2742 /** We just learned a descriptor for a bridge. See if that
2743 * digest is in our entry guard list, and add it if not. */
2745 learned_bridge_descriptor(routerinfo_t
*ri
)
2748 tor_assert(ri
->purpose
== ROUTER_PURPOSE_BRIDGE
);
2749 if (get_options()->UseBridges
) {
2750 int first
= !any_bridge_descriptors_known();
2752 add_an_entry_guard(ri
);
2753 log_notice(LD_DIR
, "new bridge descriptor '%s'", ri
->nickname
);
2755 routerlist_retry_directory_downloads(time(NULL
));
2759 /** Return 1 if any of our entry guards have descriptors that
2760 * are marked with purpose 'bridge'. Else return 0.
2762 * We use this function to decide if we're ready to start building
2763 * circuits through our bridges, or if we need to wait until the
2764 * directory "server/authority" requests finish. */
2766 any_bridge_descriptors_known(void)
2768 return choose_random_entry(NULL
)!=NULL
? 1 : 0;
2772 entry_guards
= smartlist_create();
2773 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, e
,
2775 ri
= router_get_by_digest(e
->identity
);
2776 if (ri
&& ri
->purpose
== ROUTER_PURPOSE_BRIDGE
)