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-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Launch the right sort of circuits and attach streams to them.
13 #include "addressmap.h"
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuitstats.h"
18 #include "circuituse.h"
20 #include "connection.h"
21 #include "connection_edge.h"
23 #include "entrynodes.h"
25 #include "networkstatus.h"
27 #include "rendclient.h"
28 #include "rendcommon.h"
29 #include "rendservice.h"
32 #include "routerlist.h"
34 /********* START VARIABLES **********/
36 extern circuit_t
*global_circuitlist
; /* from circuitlist.c */
38 /********* END VARIABLES ************/
40 static void circuit_expire_old_circuits_clientside(void);
41 static void circuit_increment_failure_count(void);
43 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
47 circuit_is_acceptable(const origin_circuit_t
*origin_circ
,
48 const entry_connection_t
*conn
,
49 int must_be_open
, uint8_t purpose
,
50 int need_uptime
, int need_internal
,
53 const circuit_t
*circ
= TO_CIRCUIT(origin_circ
);
54 const node_t
*exitnode
;
55 cpath_build_state_t
*build_state
;
58 tor_assert(conn
->socks_request
);
60 if (must_be_open
&& (circ
->state
!= CIRCUIT_STATE_OPEN
|| !circ
->n_chan
))
61 return 0; /* ignore non-open circs */
62 if (circ
->marked_for_close
)
65 /* if this circ isn't our purpose, skip. */
66 if (purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
&& !must_be_open
) {
67 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_ESTABLISH_REND
&&
68 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_READY
&&
69 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
&&
70 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_JOINED
)
72 } else if (purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
&&
74 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCING
&&
75 circ
->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
78 if (purpose
!= circ
->purpose
)
82 /* If this is a timed-out hidden service circuit, skip it. */
83 if (origin_circ
->hs_circ_has_timed_out
) {
87 if (purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
88 purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
89 if (circ
->timestamp_dirty
&&
90 circ
->timestamp_dirty
+get_options()->MaxCircuitDirtiness
<= now
)
94 if (origin_circ
->unusable_for_new_conns
)
97 /* decide if this circ is suitable for this conn */
99 /* for rend circs, circ->cpath->prev is not the last router in the
100 * circuit, it's the magical extra bob hop. so just check the nickname
101 * of the one we meant to finish at.
103 build_state
= origin_circ
->build_state
;
104 exitnode
= build_state_get_exit_node(build_state
);
106 if (need_uptime
&& !build_state
->need_uptime
)
108 if (need_internal
!= build_state
->is_internal
)
111 if (purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
113 const int family
= tor_addr_parse(&addr
, conn
->socks_request
->address
);
114 if (!exitnode
&& !build_state
->onehop_tunnel
) {
115 log_debug(LD_CIRC
,"Not considering circuit with unknown router.");
116 return 0; /* this circuit is screwed and doesn't know it yet,
117 * or is a rendezvous circuit. */
119 if (build_state
->onehop_tunnel
) {
120 if (!conn
->want_onehop
) {
121 log_debug(LD_CIRC
,"Skipping one-hop circuit.");
124 tor_assert(conn
->chosen_exit_name
);
125 if (build_state
->chosen_exit
) {
126 char digest
[DIGEST_LEN
];
127 if (hexdigest_to_digest(conn
->chosen_exit_name
, digest
) < 0)
128 return 0; /* broken digest, we don't want it */
129 if (tor_memneq(digest
, build_state
->chosen_exit
->identity_digest
,
131 return 0; /* this is a circuit to somewhere else */
132 if (tor_digest_is_zero(digest
)) {
133 /* we don't know the digest; have to compare addr:port */
135 !tor_addr_eq(&build_state
->chosen_exit
->addr
, &addr
) ||
136 build_state
->chosen_exit
->port
!= conn
->socks_request
->port
)
141 if (conn
->want_onehop
) {
142 /* don't use three-hop circuits -- that could hurt our anonymity. */
146 if (origin_circ
->prepend_policy
&& family
!= -1) {
147 int r
= compare_tor_addr_to_addr_policy(&addr
,
148 conn
->socks_request
->port
,
149 origin_circ
->prepend_policy
);
150 if (r
== ADDR_POLICY_REJECTED
)
153 if (exitnode
&& !connection_ap_can_use_exit(conn
, exitnode
)) {
154 /* can't exit from this router */
157 } else { /* not general */
158 const edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
159 if ((edge_conn
->rend_data
&& !origin_circ
->rend_data
) ||
160 (!edge_conn
->rend_data
&& origin_circ
->rend_data
) ||
161 (edge_conn
->rend_data
&& origin_circ
->rend_data
&&
162 rend_cmp_service_ids(edge_conn
->rend_data
->onion_address
,
163 origin_circ
->rend_data
->onion_address
))) {
164 /* this circ is not for this conn */
169 if (!connection_edge_compatible_with_circuit(conn
, origin_circ
)) {
170 /* conn needs to be isolated from other conns that have already used
178 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
179 * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
182 circuit_is_better(const origin_circuit_t
*oa
, const origin_circuit_t
*ob
,
183 const entry_connection_t
*conn
)
185 const circuit_t
*a
= TO_CIRCUIT(oa
);
186 const circuit_t
*b
= TO_CIRCUIT(ob
);
187 const uint8_t purpose
= ENTRY_TO_CONN(conn
)->purpose
;
190 /* If one of the circuits was allowed to live due to relaxing its timeout,
191 * it is definitely worse (it's probably a much slower path). */
192 if (oa
->relaxed_timeout
&& !ob
->relaxed_timeout
)
193 return 0; /* ob is better. It's not relaxed. */
194 if (!oa
->relaxed_timeout
&& ob
->relaxed_timeout
)
195 return 1; /* oa is better. It's not relaxed. */
198 case CIRCUIT_PURPOSE_C_GENERAL
:
199 /* if it's used but less dirty it's best;
200 * else if it's more recently created it's best
202 if (b
->timestamp_dirty
) {
203 if (a
->timestamp_dirty
&&
204 a
->timestamp_dirty
> b
->timestamp_dirty
)
207 if (a
->timestamp_dirty
||
208 timercmp(&a
->timestamp_began
, &b
->timestamp_began
, >))
210 if (ob
->build_state
->is_internal
)
211 /* XXX023 what the heck is this internal thing doing here. I
212 * think we can get rid of it. circuit_is_acceptable() already
213 * makes sure that is_internal is exactly what we need it to
218 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
219 /* the closer it is to ack_wait the better it is */
220 if (a
->purpose
> b
->purpose
)
223 case CIRCUIT_PURPOSE_C_REND_JOINED
:
224 /* the closer it is to rend_joined the better it is */
225 if (a
->purpose
> b
->purpose
)
230 /* XXXX023 Maybe this check should get a higher priority to avoid
231 * using up circuits too rapidly. */
233 a_bits
= connection_edge_update_circuit_isolation(conn
,
234 (origin_circuit_t
*)oa
, 1);
235 b_bits
= connection_edge_update_circuit_isolation(conn
,
236 (origin_circuit_t
*)ob
, 1);
237 /* if x_bits < 0, then we have not used x for anything; better not to dirty
238 * a connection if we can help it. */
241 } else if (b_bits
< 0) {
244 a_bits
&= ~ oa
->isolation_flags_mixed
;
245 a_bits
&= ~ ob
->isolation_flags_mixed
;
246 if (n_bits_set_u8(a_bits
) < n_bits_set_u8(b_bits
)) {
247 /* The fewer new restrictions we need to make on a circuit for stream
248 * isolation, the better. */
255 /** Find the best circ that conn can use, preferably one which is
256 * dirty. Circ must not be too old.
258 * Conn must be defined.
260 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
262 * circ_purpose specifies what sort of circuit we must have.
263 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
265 * If it's REND_JOINED and must_be_open==0, then return the closest
266 * rendezvous-purposed circuit that you can find.
268 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
269 * closest introduce-purposed circuit that you can find.
271 static origin_circuit_t
*
272 circuit_get_best(const entry_connection_t
*conn
,
273 int must_be_open
, uint8_t purpose
,
274 int need_uptime
, int need_internal
)
277 origin_circuit_t
*best
=NULL
;
279 int intro_going_on_but_too_old
= 0;
283 tor_assert(purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
284 purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
||
285 purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
);
287 tor_gettimeofday(&now
);
289 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
290 origin_circuit_t
*origin_circ
;
291 if (!CIRCUIT_IS_ORIGIN(circ
))
293 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
295 /* Log an info message if we're going to launch a new intro circ in
297 if (purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
&&
298 !must_be_open
&& origin_circ
->hs_circ_has_timed_out
) {
299 intro_going_on_but_too_old
= 1;
303 if (!circuit_is_acceptable(origin_circ
,conn
,must_be_open
,purpose
,
304 need_uptime
,need_internal
,now
.tv_sec
))
307 /* now this is an acceptable circ to hand back. but that doesn't
308 * mean it's the *best* circ to hand back. try to decide.
310 if (!best
|| circuit_is_better(origin_circ
,best
,conn
))
314 if (!best
&& intro_going_on_but_too_old
)
315 log_info(LD_REND
|LD_CIRC
, "There is an intro circuit being created "
316 "right now, but it has already taken quite a while. Starting "
322 /** Return the number of not-yet-open general-purpose origin circuits. */
324 count_pending_general_client_circuits(void)
326 const circuit_t
*circ
;
330 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
331 if (circ
->marked_for_close
||
332 circ
->state
== CIRCUIT_STATE_OPEN
||
333 circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
||
334 !CIRCUIT_IS_ORIGIN(circ
))
344 /** Check whether, according to the policies in <b>options</b>, the
345 * circuit <b>circ</b> makes sense. */
346 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
347 * Also, it doesn't have the right definition of an exit circuit. Also,
348 * it's never called. */
350 circuit_conforms_to_options(const origin_circuit_t
*circ
,
351 const or_options_t
*options
)
353 const crypt_path_t
*cpath
, *cpath_next
= NULL
;
355 /* first check if it includes any excluded nodes */
356 for (cpath
= circ
->cpath
; cpath_next
!= circ
->cpath
; cpath
= cpath_next
) {
357 cpath_next
= cpath
->next
;
358 if (routerset_contains_extendinfo(options
->ExcludeNodes
,
363 /* then consider the final hop */
364 if (routerset_contains_extendinfo(options
->ExcludeExitNodes
,
365 circ
->cpath
->prev
->extend_info
))
372 /** Close all circuits that start at us, aren't open, and were born
373 * at least CircuitBuildTimeout seconds ago.
376 circuit_expire_building(void)
378 circuit_t
*victim
, *next_circ
= global_circuitlist
;
379 /* circ_times.timeout_ms and circ_times.close_ms are from
380 * circuit_build_times_get_initial_timeout() if we haven't computed
381 * custom timeouts yet */
382 struct timeval general_cutoff
, begindir_cutoff
, fourhop_cutoff
,
383 close_cutoff
, extremely_old_cutoff
, hs_extremely_old_cutoff
,
384 cannibalized_cutoff
, c_intro_cutoff
, s_intro_cutoff
, stream_cutoff
;
385 const or_options_t
*options
= get_options();
387 cpath_build_state_t
*build_state
;
388 int any_opened_circs
= 0;
390 tor_gettimeofday(&now
);
392 /* Check to see if we have any opened circuits. If we don't,
393 * we want to be more lenient with timeouts, in case the
394 * user has relocated and/or changed network connections.
397 if (!CIRCUIT_IS_ORIGIN(next_circ
) || /* didn't originate here */
398 next_circ
->marked_for_close
) { /* don't mess with marked circs */
399 next_circ
= next_circ
->next
;
403 if (TO_ORIGIN_CIRCUIT(next_circ
)->has_opened
&&
404 next_circ
->state
== CIRCUIT_STATE_OPEN
&&
405 TO_ORIGIN_CIRCUIT(next_circ
)->build_state
&&
406 TO_ORIGIN_CIRCUIT(next_circ
)->build_state
->desired_path_len
407 == DEFAULT_ROUTE_LEN
) {
408 any_opened_circs
= 1;
411 next_circ
= next_circ
->next
;
413 next_circ
= global_circuitlist
;
415 #define SET_CUTOFF(target, msec) do { \
416 long ms = tor_lround(msec); \
417 struct timeval diff; \
418 diff.tv_sec = ms / 1000; \
419 diff.tv_usec = (int)((ms % 1000) * 1000); \
420 timersub(&now, &diff, &target); \
424 * Because circuit build timeout is calculated only based on 3 hop
425 * general purpose circuit construction, we need to scale the timeout
426 * to make it properly apply to longer circuits, and circuits of
427 * certain usage types. The following diagram illustrates how we
428 * derive the scaling below. In short, we calculate the number
429 * of times our telescoping-based circuit construction causes cells
430 * to traverse each link for the circuit purpose types in question,
431 * and then assume each link is equivalent.
433 * OP --a--> A --b--> B --c--> C
434 * OP --a--> A --b--> B --c--> C --d--> D
436 * Let h = a = b = c = d
438 * Three hops (general_cutoff)
445 * RTTs = 4a + 3b + 2c + d
447 * Client INTRODUCE1+ACK: // XXX: correct?
448 * RTTs = 5a + 4b + 3c + 2d
451 * RTTs = 4a + 3b + 2c
454 SET_CUTOFF(general_cutoff
, circ_times
.timeout_ms
);
455 SET_CUTOFF(begindir_cutoff
, circ_times
.timeout_ms
);
457 /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
459 SET_CUTOFF(fourhop_cutoff
, circ_times
.timeout_ms
* (10/6.0) + 1000);
461 /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
462 * Use the stream cutoff (more or less). */
463 SET_CUTOFF(stream_cutoff
, MAX(options
->CircuitStreamTimeout
,15)*1000 + 1000);
465 /* Be lenient with cannibalized circs. They already survived the official
466 * CBT, and they're usually not performance-critical. */
467 SET_CUTOFF(cannibalized_cutoff
,
468 MAX(circ_times
.close_ms
*(4/6.0),
469 options
->CircuitStreamTimeout
* 1000) + 1000);
471 /* Intro circs have an extra round trip (and are also 4 hops long) */
472 SET_CUTOFF(c_intro_cutoff
, circ_times
.timeout_ms
* (14/6.0) + 1000);
474 /* Server intro circs have an extra round trip */
475 SET_CUTOFF(s_intro_cutoff
, circ_times
.timeout_ms
* (9/6.0) + 1000);
477 SET_CUTOFF(close_cutoff
, circ_times
.close_ms
);
478 SET_CUTOFF(extremely_old_cutoff
, circ_times
.close_ms
*2 + 1000);
480 SET_CUTOFF(hs_extremely_old_cutoff
,
481 MAX(circ_times
.close_ms
*2 + 1000,
482 options
->SocksTimeout
* 1000));
485 struct timeval cutoff
;
487 next_circ
= next_circ
->next
;
488 if (!CIRCUIT_IS_ORIGIN(victim
) || /* didn't originate here */
489 victim
->marked_for_close
) /* don't mess with marked circs */
492 /* If we haven't yet started the first hop, it means we don't have
493 * any orconns available, and thus have not started counting time yet
494 * for this circuit. See circuit_deliver_create_cell() and uses of
497 * Continue to wait in this case. The ORConn should timeout
498 * independently and kill us then.
500 if (TO_ORIGIN_CIRCUIT(victim
)->cpath
->state
== CPATH_STATE_CLOSED
) {
504 build_state
= TO_ORIGIN_CIRCUIT(victim
)->build_state
;
505 if (build_state
&& build_state
->onehop_tunnel
)
506 cutoff
= begindir_cutoff
;
507 else if (victim
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
)
508 cutoff
= close_cutoff
;
509 else if (victim
->purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
||
510 victim
->purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
511 cutoff
= c_intro_cutoff
;
512 else if (victim
->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
513 cutoff
= s_intro_cutoff
;
514 else if (victim
->purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
)
515 cutoff
= stream_cutoff
;
516 else if (victim
->purpose
== CIRCUIT_PURPOSE_PATH_BIAS_TESTING
)
517 cutoff
= close_cutoff
;
518 else if (TO_ORIGIN_CIRCUIT(victim
)->has_opened
&&
519 victim
->state
!= CIRCUIT_STATE_OPEN
)
520 cutoff
= cannibalized_cutoff
;
521 else if (build_state
&& build_state
->desired_path_len
>= 4)
522 cutoff
= fourhop_cutoff
;
524 cutoff
= general_cutoff
;
526 if (TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
)
527 cutoff
= hs_extremely_old_cutoff
;
529 if (timercmp(&victim
->timestamp_began
, &cutoff
, >))
530 continue; /* it's still young, leave it alone */
532 /* We need to double-check the opened state here because
533 * we don't want to consider opened 1-hop dircon circuits for
534 * deciding when to relax the timeout, but we *do* want to relax
535 * those circuits too if nothing else is opened *and* they still
537 if (!any_opened_circs
&& victim
->state
!= CIRCUIT_STATE_OPEN
) {
538 /* It's still young enough that we wouldn't close it, right? */
539 if (timercmp(&victim
->timestamp_began
, &close_cutoff
, >)) {
540 if (!TO_ORIGIN_CIRCUIT(victim
)->relaxed_timeout
) {
541 int first_hop_succeeded
= TO_ORIGIN_CIRCUIT(victim
)->cpath
->state
544 "No circuits are opened. Relaxing timeout for circuit %d "
545 "(a %s %d-hop circuit in state %s with channel state %s). "
546 "%d guards are live.",
547 TO_ORIGIN_CIRCUIT(victim
)->global_identifier
,
548 circuit_purpose_to_string(victim
->purpose
),
549 TO_ORIGIN_CIRCUIT(victim
)->build_state
->desired_path_len
,
550 circuit_state_to_string(victim
->state
),
551 channel_state_to_string(victim
->n_chan
->state
),
552 num_live_entry_guards(0));
554 /* We count the timeout here for CBT, because technically this
555 * was a timeout, and the timeout value needs to reset if we
556 * see enough of them. Note this means we also need to avoid
557 * double-counting below, too. */
558 circuit_build_times_count_timeout(&circ_times
, first_hop_succeeded
);
559 TO_ORIGIN_CIRCUIT(victim
)->relaxed_timeout
= 1;
563 static ratelim_t relax_timeout_limit
= RATELIM_INIT(3600);
564 log_fn_ratelim(&relax_timeout_limit
, LOG_NOTICE
, LD_CIRC
,
565 "No circuits are opened. Relaxed timeout for circuit %d "
566 "(a %s %d-hop circuit in state %s with channel state %s) to "
567 "%ldms. However, it appears the circuit has timed out "
568 "anyway. %d guards are live.",
569 TO_ORIGIN_CIRCUIT(victim
)->global_identifier
,
570 circuit_purpose_to_string(victim
->purpose
),
571 TO_ORIGIN_CIRCUIT(victim
)->build_state
->desired_path_len
,
572 circuit_state_to_string(victim
->state
),
573 channel_state_to_string(victim
->n_chan
->state
),
574 (long)circ_times
.close_ms
, num_live_entry_guards(0));
579 /* some debug logs, to help track bugs */
580 if (victim
->purpose
>= CIRCUIT_PURPOSE_C_INTRODUCING
&&
581 victim
->purpose
<= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
) {
582 if (!victim
->timestamp_dirty
)
583 log_fn(LOG_DEBUG
,"Considering %sopen purpose %d to %s (circid %d)."
585 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
586 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
589 log_fn(LOG_DEBUG
,"Considering %sopen purpose %d to %s (circid %d). "
590 "%d secs since dirty.",
591 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
592 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
594 (int)(now
- victim
->timestamp_dirty
));
598 /* if circ is !open, or if it's open but purpose is a non-finished
599 * intro or rend, then mark it for close */
600 if (victim
->state
== CIRCUIT_STATE_OPEN
) {
601 switch (victim
->purpose
) {
602 default: /* most open circuits can be left alone. */
603 continue; /* yes, continue inside a switch refers to the nearest
604 * enclosing loop. C is smart. */
605 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
606 break; /* too old, need to die */
607 case CIRCUIT_PURPOSE_C_REND_READY
:
608 /* it's a rend_ready circ -- has it already picked a query? */
609 /* c_rend_ready circs measure age since timestamp_dirty,
610 * because that's set when they switch purposes
612 if (TO_ORIGIN_CIRCUIT(victim
)->rend_data
||
613 victim
->timestamp_dirty
> cutoff
.tv_sec
)
616 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING
:
617 /* Open path bias testing circuits are given a long
618 * time to complete the test, but not forever */
619 TO_ORIGIN_CIRCUIT(victim
)->path_state
= PATH_STATE_USE_FAILED
;
621 case CIRCUIT_PURPOSE_C_INTRODUCING
:
622 /* We keep old introducing circuits around for
623 * a while in parallel, and they can end up "opened".
624 * We decide below if we're going to mark them timed
625 * out and eventually close them.
628 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
629 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
630 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
631 /* rend and intro circs become dirty each time they
632 * make an introduction attempt. so timestamp_dirty
633 * will reflect the time since the last attempt.
635 if (victim
->timestamp_dirty
> cutoff
.tv_sec
)
639 } else { /* circuit not open, consider recording failure as timeout */
640 int first_hop_succeeded
= TO_ORIGIN_CIRCUIT(victim
)->cpath
&&
641 TO_ORIGIN_CIRCUIT(victim
)->cpath
->state
== CPATH_STATE_OPEN
;
643 if (TO_ORIGIN_CIRCUIT(victim
)->p_streams
!= NULL
) {
644 log_warn(LD_BUG
, "Circuit %d (purpose %d, %s) has timed out, "
645 "yet has attached streams!",
646 TO_ORIGIN_CIRCUIT(victim
)->global_identifier
,
648 circuit_purpose_to_string(victim
->purpose
));
649 tor_fragile_assert();
653 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim
)) &&
654 circuit_build_times_enough_to_compute(&circ_times
)) {
655 /* Circuits are allowed to last longer for measurement.
656 * Switch their purpose and wait. */
657 if (victim
->purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
658 control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim
),
660 END_CIRC_REASON_TIMEOUT
);
661 circuit_change_purpose(victim
, CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
);
662 /* Record this failure to check for too many timeouts
663 * in a row. This function does not record a time value yet
664 * (we do that later); it only counts the fact that we did
665 * have a timeout. We also want to avoid double-counting
666 * already "relaxed" circuits, which are counted above. */
667 if (!TO_ORIGIN_CIRCUIT(victim
)->relaxed_timeout
) {
668 circuit_build_times_count_timeout(&circ_times
,
669 first_hop_succeeded
);
675 * If the circuit build time is much greater than we would have cut
676 * it off at, we probably had a suspend event along this codepath,
677 * and we should discard the value.
679 if (timercmp(&victim
->timestamp_began
, &extremely_old_cutoff
, <)) {
681 "Extremely large value for circuit build timeout: %lds. "
682 "Assuming clock jump. Purpose %d (%s)",
683 (long)(now
.tv_sec
- victim
->timestamp_began
.tv_sec
),
685 circuit_purpose_to_string(victim
->purpose
));
686 } else if (circuit_build_times_count_close(&circ_times
,
688 victim
->timestamp_created
.tv_sec
)) {
689 circuit_build_times_set_timeout(&circ_times
);
694 /* If this is a hidden service client circuit which is far enough
695 * along in connecting to its destination, and we haven't already
696 * flagged it as 'timed out', and the user has not told us to
697 * close such circs immediately on timeout, flag it as 'timed out'
698 * so we'll launch another intro or rend circ, but don't mark it
701 * (Circs flagged as 'timed out' are given a much longer timeout
702 * period above, so we won't close them in the next call to
703 * circuit_expire_building.) */
704 if (!(options
->CloseHSClientCircuitsImmediatelyOnTimeout
) &&
705 !(TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
)) {
706 switch (victim
->purpose
) {
707 case CIRCUIT_PURPOSE_C_REND_READY
:
708 /* We only want to spare a rend circ if it has been specified in
709 * an INTRODUCE1 cell sent to a hidden service. A circ's
710 * pending_final_cpath field is non-NULL iff it is a rend circ
711 * and we have tried to send an INTRODUCE1 cell specifying it.
712 * Thus, if the pending_final_cpath field *is* NULL, then we
713 * want to not spare it. */
714 if (TO_ORIGIN_CIRCUIT(victim
)->build_state
->pending_final_cpath
==
718 case CIRCUIT_PURPOSE_C_INTRODUCING
:
719 /* connection_ap_handshake_attach_circuit() will relaunch for us */
720 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
721 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
722 /* If we have reached this line, we want to spare the circ for now. */
723 log_info(LD_CIRC
,"Marking circ %u (state %d:%s, purpose %d) "
724 "as timed-out HS circ",
725 (unsigned)victim
->n_circ_id
,
726 victim
->state
, circuit_state_to_string(victim
->state
),
728 TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
= 1;
735 /* If this is a service-side rendezvous circuit which is far
736 * enough along in connecting to its destination, consider sparing
738 if (!(options
->CloseHSServiceRendCircuitsImmediatelyOnTimeout
) &&
739 !(TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
) &&
740 victim
->purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
) {
741 log_info(LD_CIRC
,"Marking circ %u (state %d:%s, purpose %d) "
742 "as timed-out HS circ; relaunching rendezvous attempt.",
743 (unsigned)victim
->n_circ_id
,
744 victim
->state
, circuit_state_to_string(victim
->state
),
746 TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
= 1;
747 rend_service_relaunch_rendezvous(TO_ORIGIN_CIRCUIT(victim
));
753 "Abandoning circ %u %s:%d (state %d,%d:%s, purpose %d, "
754 "len %d)", TO_ORIGIN_CIRCUIT(victim
)->global_identifier
,
755 channel_get_canonical_remote_descr(victim
->n_chan
),
756 (unsigned)victim
->n_circ_id
,
757 TO_ORIGIN_CIRCUIT(victim
)->has_opened
,
758 victim
->state
, circuit_state_to_string(victim
->state
),
760 TO_ORIGIN_CIRCUIT(victim
)->build_state
->desired_path_len
);
763 "Abandoning circ %u %d (state %d,%d:%s, purpose %d, len %d)",
764 TO_ORIGIN_CIRCUIT(victim
)->global_identifier
,
765 (unsigned)victim
->n_circ_id
,
766 TO_ORIGIN_CIRCUIT(victim
)->has_opened
,
768 circuit_state_to_string(victim
->state
), victim
->purpose
,
769 TO_ORIGIN_CIRCUIT(victim
)->build_state
->desired_path_len
);
771 circuit_log_path(LOG_INFO
,LD_CIRC
,TO_ORIGIN_CIRCUIT(victim
));
772 if (victim
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
)
773 circuit_mark_for_close(victim
, END_CIRC_REASON_MEASUREMENT_EXPIRED
);
775 circuit_mark_for_close(victim
, END_CIRC_REASON_TIMEOUT
);
777 pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim
));
781 /** Remove any elements in <b>needed_ports</b> that are handled by an
782 * open or in-progress circuit.
785 circuit_remove_handled_ports(smartlist_t
*needed_ports
)
790 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
791 port
= smartlist_get(needed_ports
, i
);
793 if (circuit_stream_is_being_handled(NULL
, *port
,
794 MIN_CIRCUITS_HANDLING_STREAM
)) {
795 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
796 smartlist_del(needed_ports
, i
--);
799 log_debug(LD_CIRC
,"Port %d is not handled.", *port
);
804 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
805 * will have an acceptable exit node for exit stream <b>conn</b> if it
806 * is defined, else for "*:port".
810 circuit_stream_is_being_handled(entry_connection_t
*conn
,
811 uint16_t port
, int min
)
814 const node_t
*exitnode
;
816 time_t now
= time(NULL
);
817 int need_uptime
= smartlist_contains_int_as_string(
818 get_options()->LongLivedPorts
,
819 conn
? conn
->socks_request
->port
: port
);
821 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
822 if (CIRCUIT_IS_ORIGIN(circ
) &&
823 !circ
->marked_for_close
&&
824 circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
&&
825 (!circ
->timestamp_dirty
||
826 circ
->timestamp_dirty
+ get_options()->MaxCircuitDirtiness
> now
)) {
827 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
828 cpath_build_state_t
*build_state
= origin_circ
->build_state
;
829 if (build_state
->is_internal
|| build_state
->onehop_tunnel
)
831 if (origin_circ
->unusable_for_new_conns
)
834 exitnode
= build_state_get_exit_node(build_state
);
835 if (exitnode
&& (!need_uptime
|| build_state
->need_uptime
)) {
838 ok
= connection_ap_can_use_exit(conn
, exitnode
);
840 addr_policy_result_t r
;
841 r
= compare_tor_addr_to_node_policy(NULL
, port
, exitnode
);
842 ok
= r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
;
854 /** Don't keep more than this many unused open circuits around. */
855 #define MAX_UNUSED_OPEN_CIRCUITS 14
857 /** Figure out how many circuits we have open that are clean. Make
858 * sure it's enough for all the upcoming behaviors we predict we'll have.
859 * But put an upper bound on the total number of circuits.
862 circuit_predict_and_launch_new(void)
865 int num
=0, num_internal
=0, num_uptime_internal
=0;
866 int hidserv_needs_uptime
=0, hidserv_needs_capacity
=1;
867 int port_needs_uptime
=0, port_needs_capacity
=1;
868 time_t now
= time(NULL
);
871 /* First, count how many of each type of circuit we have already. */
872 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
873 cpath_build_state_t
*build_state
;
874 origin_circuit_t
*origin_circ
;
875 if (!CIRCUIT_IS_ORIGIN(circ
))
877 if (circ
->marked_for_close
)
878 continue; /* don't mess with marked circs */
879 if (circ
->timestamp_dirty
)
880 continue; /* only count clean circs */
881 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
882 continue; /* only pay attention to general-purpose circs */
883 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
884 if (origin_circ
->unusable_for_new_conns
)
886 build_state
= origin_circ
->build_state
;
887 if (build_state
->onehop_tunnel
)
890 if (build_state
->is_internal
)
892 if (build_state
->need_uptime
&& build_state
->is_internal
)
893 num_uptime_internal
++;
896 /* If that's enough, then stop now. */
897 if (num
>= MAX_UNUSED_OPEN_CIRCUITS
)
898 return; /* we already have many, making more probably will hurt */
900 /* Second, see if we need any more exit circuits. */
901 /* check if we know of a port that's been requested recently
902 * and no circuit is currently available that can handle it. */
903 if (!circuit_all_predicted_ports_handled(now
, &port_needs_uptime
,
904 &port_needs_capacity
)) {
905 if (port_needs_uptime
)
906 flags
|= CIRCLAUNCH_NEED_UPTIME
;
907 if (port_needs_capacity
)
908 flags
|= CIRCLAUNCH_NEED_CAPACITY
;
910 "Have %d clean circs (%d internal), need another exit circ.",
912 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, flags
);
916 /* Third, see if we need any more hidden service (server) circuits. */
917 if (num_rend_services() && num_uptime_internal
< 3) {
918 flags
= (CIRCLAUNCH_NEED_CAPACITY
| CIRCLAUNCH_NEED_UPTIME
|
919 CIRCLAUNCH_IS_INTERNAL
);
921 "Have %d clean circs (%d internal), need another internal "
922 "circ for my hidden service.",
924 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, flags
);
928 /* Fourth, see if we need any more hidden service (client) circuits. */
929 if (rep_hist_get_predicted_internal(now
, &hidserv_needs_uptime
,
930 &hidserv_needs_capacity
) &&
931 ((num_uptime_internal
<2 && hidserv_needs_uptime
) ||
933 if (hidserv_needs_uptime
)
934 flags
|= CIRCLAUNCH_NEED_UPTIME
;
935 if (hidserv_needs_capacity
)
936 flags
|= CIRCLAUNCH_NEED_CAPACITY
;
937 flags
|= CIRCLAUNCH_IS_INTERNAL
;
939 "Have %d clean circs (%d uptime-internal, %d internal), need"
940 " another hidden service circ.",
941 num
, num_uptime_internal
, num_internal
);
942 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, flags
);
946 /* Finally, check to see if we still need more circuits to learn
947 * a good build timeout. But if we're close to our max number we
948 * want, don't do another -- we want to leave a few slots open so
949 * we can still build circuits preemptively as needed. */
950 if (num
< MAX_UNUSED_OPEN_CIRCUITS
-2 &&
951 ! circuit_build_times_disabled() &&
952 circuit_build_times_needs_circuits_now(&circ_times
)) {
953 flags
= CIRCLAUNCH_NEED_CAPACITY
;
955 "Have %d clean circs need another buildtime test circ.", num
);
956 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, flags
);
961 /** Build a new test circuit every 5 minutes */
962 #define TESTING_CIRCUIT_INTERVAL 300
964 /** This function is called once a second, if router_have_min_dir_info() is
965 * true. Its job is to make sure all services we offer have enough circuits
966 * available. Some services just want enough circuits for current tasks,
967 * whereas others want a minimum set of idle circuits hanging around.
970 circuit_build_needed_circs(time_t now
)
972 static time_t time_to_new_circuit
= 0;
973 const or_options_t
*options
= get_options();
975 /* launch a new circ for any pending streams that need one */
976 connection_ap_attach_pending();
978 /* make sure any hidden services have enough intro points */
979 rend_services_introduce();
981 if (time_to_new_circuit
< now
) {
982 circuit_reset_failure_count(1);
983 time_to_new_circuit
= now
+ options
->NewCircuitPeriod
;
984 if (proxy_mode(get_options()))
985 addressmap_clean(now
);
986 circuit_expire_old_circuits_clientside();
988 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
989 circ
= circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL
);
990 if (get_options()->RunTesting
&&
992 circ
->timestamp_began
.tv_sec
+ TESTING_CIRCUIT_INTERVAL
< now
) {
993 log_fn(LOG_INFO
,"Creating a new testing circuit.");
994 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, 0);
998 if (!options
->DisablePredictedCircuits
)
999 circuit_predict_and_launch_new();
1002 /** If the stream <b>conn</b> is a member of any of the linked
1003 * lists of <b>circ</b>, then remove it from the list.
1006 circuit_detach_stream(circuit_t
*circ
, edge_connection_t
*conn
)
1008 edge_connection_t
*prevconn
;
1013 if (conn
->base_
.type
== CONN_TYPE_AP
) {
1014 entry_connection_t
*entry_conn
= EDGE_TO_ENTRY_CONN(conn
);
1015 entry_conn
->may_use_optimistic_data
= 0;
1017 conn
->cpath_layer
= NULL
; /* don't keep a stale pointer */
1018 conn
->on_circuit
= NULL
;
1020 if (CIRCUIT_IS_ORIGIN(circ
)) {
1021 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
1022 if (conn
== origin_circ
->p_streams
) {
1023 origin_circ
->p_streams
= conn
->next_stream
;
1027 for (prevconn
= origin_circ
->p_streams
;
1028 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
1029 prevconn
= prevconn
->next_stream
)
1031 if (prevconn
&& prevconn
->next_stream
) {
1032 prevconn
->next_stream
= conn
->next_stream
;
1036 or_circuit_t
*or_circ
= TO_OR_CIRCUIT(circ
);
1037 if (conn
== or_circ
->n_streams
) {
1038 or_circ
->n_streams
= conn
->next_stream
;
1041 if (conn
== or_circ
->resolving_streams
) {
1042 or_circ
->resolving_streams
= conn
->next_stream
;
1046 for (prevconn
= or_circ
->n_streams
;
1047 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
1048 prevconn
= prevconn
->next_stream
)
1050 if (prevconn
&& prevconn
->next_stream
) {
1051 prevconn
->next_stream
= conn
->next_stream
;
1055 for (prevconn
= or_circ
->resolving_streams
;
1056 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
1057 prevconn
= prevconn
->next_stream
)
1059 if (prevconn
&& prevconn
->next_stream
) {
1060 prevconn
->next_stream
= conn
->next_stream
;
1065 log_warn(LD_BUG
,"Edge connection not in circuit's list.");
1066 /* Don't give an error here; it's harmless. */
1067 tor_fragile_assert();
1070 /** If we haven't yet decided on a good timeout value for circuit
1071 * building, we close idles circuits aggressively so we can get more
1073 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
1075 /** Find each circuit that has been unused for too long, or dirty
1076 * for too long and has no streams on it: mark it for close.
1079 circuit_expire_old_circuits_clientside(void)
1082 struct timeval cutoff
, now
;
1084 tor_gettimeofday(&now
);
1087 if (! circuit_build_times_disabled() &&
1088 circuit_build_times_needs_circuits(&circ_times
)) {
1089 /* Circuits should be shorter lived if we need more of them
1090 * for learning a good build timeout */
1091 cutoff
.tv_sec
-= IDLE_TIMEOUT_WHILE_LEARNING
;
1093 cutoff
.tv_sec
-= get_options()->CircuitIdleTimeout
;
1096 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
1097 if (circ
->marked_for_close
|| !CIRCUIT_IS_ORIGIN(circ
))
1099 /* If the circuit has been dirty for too long, and there are no streams
1100 * on it, mark it for close.
1102 if (circ
->timestamp_dirty
&&
1103 circ
->timestamp_dirty
+ get_options()->MaxCircuitDirtiness
<
1105 !TO_ORIGIN_CIRCUIT(circ
)->p_streams
/* nothing attached */ ) {
1106 log_debug(LD_CIRC
, "Closing n_circ_id %u (dirty %ld sec ago, "
1108 (unsigned)circ
->n_circ_id
,
1109 (long)(now
.tv_sec
- circ
->timestamp_dirty
),
1111 /* Don't do this magic for testing circuits. Their death is governed
1112 * by circuit_expire_building */
1113 if (circ
->purpose
!= CIRCUIT_PURPOSE_PATH_BIAS_TESTING
)
1114 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
1115 } else if (!circ
->timestamp_dirty
&& circ
->state
== CIRCUIT_STATE_OPEN
) {
1116 if (timercmp(&circ
->timestamp_began
, &cutoff
, <)) {
1117 if (circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
1118 circ
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
||
1119 circ
->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
1120 circ
->purpose
== CIRCUIT_PURPOSE_TESTING
||
1121 (circ
->purpose
>= CIRCUIT_PURPOSE_C_INTRODUCING
&&
1122 circ
->purpose
<= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
) ||
1123 circ
->purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
) {
1125 "Closing circuit that has been unused for %ld msec.",
1126 tv_mdiff(&circ
->timestamp_began
, &now
));
1127 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
1128 } else if (!TO_ORIGIN_CIRCUIT(circ
)->is_ancient
) {
1129 /* Server-side rend joined circuits can end up really old, because
1130 * they are reused by clients for longer than normal. The client
1131 * controls their lifespan. (They never become dirty, because
1132 * connection_exit_begin_conn() never marks anything as dirty.)
1133 * Similarly, server-side intro circuits last a long time. */
1134 if (circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
&&
1135 circ
->purpose
!= CIRCUIT_PURPOSE_S_INTRO
) {
1137 "Ancient non-dirty circuit %d is still around after "
1138 "%ld milliseconds. Purpose: %d (%s)",
1139 TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
1140 tv_mdiff(&circ
->timestamp_began
, &now
),
1142 circuit_purpose_to_string(circ
->purpose
));
1143 TO_ORIGIN_CIRCUIT(circ
)->is_ancient
= 1;
1151 /** How long do we wait before killing circuits with the properties
1154 * Probably we could choose a number here as low as 5 to 10 seconds,
1155 * since these circs are used for begindir, and a) generally you either
1156 * ask another begindir question right after or you don't for a long time,
1157 * b) clients at least through 0.2.1.x choose from the whole set of
1158 * directory mirrors at each choice, and c) re-establishing a one-hop
1159 * circuit via create-fast is a light operation assuming the TLS conn is
1162 * I expect "b" to go away one day when we move to using directory
1163 * guards, but I think "a" and "c" are good enough reasons that a low
1164 * number is safe even then.
1166 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
1168 /** Find each non-origin circuit that has been unused for too long,
1169 * has no streams on it, used a create_fast, and ends here: mark it
1173 circuit_expire_old_circuits_serverside(time_t now
)
1176 or_circuit_t
*or_circ
;
1177 time_t cutoff
= now
- IDLE_ONE_HOP_CIRC_TIMEOUT
;
1179 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
1180 if (circ
->marked_for_close
|| CIRCUIT_IS_ORIGIN(circ
))
1182 or_circ
= TO_OR_CIRCUIT(circ
);
1183 /* If the circuit has been idle for too long, and there are no streams
1184 * on it, and it ends here, and it used a create_fast, mark it for close.
1186 if (or_circ
->is_first_hop
&& !circ
->n_chan
&&
1187 !or_circ
->n_streams
&& !or_circ
->resolving_streams
&&
1189 channel_when_last_xmit(or_circ
->p_chan
) <= cutoff
) {
1190 log_info(LD_CIRC
, "Closing circ_id %u (empty %d secs ago)",
1191 (unsigned)or_circ
->p_circ_id
,
1192 (int)(now
- channel_when_last_xmit(or_circ
->p_chan
)));
1193 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
1198 /** Number of testing circuits we want open before testing our bandwidth. */
1199 #define NUM_PARALLEL_TESTING_CIRCS 4
1201 /** True iff we've ever had enough testing circuits open to test our
1203 static int have_performed_bandwidth_test
= 0;
1205 /** Reset have_performed_bandwidth_test, so we'll start building
1206 * testing circuits again so we can exercise our bandwidth. */
1208 reset_bandwidth_test(void)
1210 have_performed_bandwidth_test
= 0;
1213 /** Return 1 if we've already exercised our bandwidth, or if we
1214 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
1215 * established or on the way. Else return 0.
1218 circuit_enough_testing_circs(void)
1223 if (have_performed_bandwidth_test
)
1226 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
1227 if (!circ
->marked_for_close
&& CIRCUIT_IS_ORIGIN(circ
) &&
1228 circ
->purpose
== CIRCUIT_PURPOSE_TESTING
&&
1229 circ
->state
== CIRCUIT_STATE_OPEN
)
1232 return num
>= NUM_PARALLEL_TESTING_CIRCS
;
1235 /** A testing circuit has completed. Take whatever stats we want.
1236 * Noticing reachability is taken care of in onionskin_answer(),
1237 * so there's no need to record anything here. But if we still want
1238 * to do the bandwidth test, and we now have enough testing circuits
1242 circuit_testing_opened(origin_circuit_t
*circ
)
1244 if (have_performed_bandwidth_test
||
1245 !check_whether_orport_reachable()) {
1246 /* either we've already done everything we want with testing circuits,
1247 * or this testing circuit became open due to a fluke, e.g. we picked
1248 * a last hop where we already had the connection open due to an
1249 * outgoing local circuit. */
1250 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_AT_ORIGIN
);
1251 } else if (circuit_enough_testing_circs()) {
1252 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS
, time(NULL
));
1253 have_performed_bandwidth_test
= 1;
1255 consider_testing_reachability(1, 0);
1258 /** A testing circuit has failed to build. Take whatever stats we want. */
1260 circuit_testing_failed(origin_circuit_t
*circ
, int at_last_hop
)
1262 if (server_mode(get_options()) && check_whether_orport_reachable())
1265 log_info(LD_GENERAL
,
1266 "Our testing circuit (to see if your ORPort is reachable) "
1267 "has failed. I'll try again later.");
1269 /* These aren't used yet. */
1274 /** The circuit <b>circ</b> has just become open. Take the next
1275 * step: for rendezvous circuits, we pass circ to the appropriate
1276 * function in rendclient or rendservice. For general circuits, we
1277 * call connection_ap_attach_pending, which looks for pending streams
1278 * that could use circ.
1281 circuit_has_opened(origin_circuit_t
*circ
)
1283 control_event_circuit_status(circ
, CIRC_EVENT_BUILT
, 0);
1285 /* Remember that this circuit has finished building. Now if we start
1286 * it building again later (e.g. by extending it), we will know not
1287 * to consider its build time. */
1288 circ
->has_opened
= 1;
1290 switch (TO_CIRCUIT(circ
)->purpose
) {
1291 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1292 rend_client_rendcirc_has_opened(circ
);
1293 /* Start building an intro circ if we don't have one yet. */
1294 connection_ap_attach_pending();
1295 /* This isn't a call to circuit_try_attaching_streams because a
1296 * circuit in _C_ESTABLISH_REND state isn't connected to its
1297 * hidden service yet, thus we can't attach streams to it yet,
1298 * thus circuit_try_attaching_streams would always clear the
1299 * circuit's isolation state. circuit_try_attaching_streams is
1300 * called later, when the rend circ enters _C_REND_JOINED
1303 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1304 rend_client_introcirc_has_opened(circ
);
1306 case CIRCUIT_PURPOSE_C_GENERAL
:
1307 /* Tell any AP connections that have been waiting for a new
1308 * circuit that one is ready. */
1309 circuit_try_attaching_streams(circ
);
1311 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1312 /* at Bob, waiting for introductions */
1313 rend_service_intro_has_opened(circ
);
1315 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1316 /* at Bob, connecting to rend point */
1317 rend_service_rendezvous_has_opened(circ
);
1319 case CIRCUIT_PURPOSE_TESTING
:
1320 circuit_testing_opened(circ
);
1323 * This won't happen in normal operation, but might happen if the
1324 * controller did it. Just let it slide. */
1328 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
1329 * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
1331 circuit_try_clearing_isolation_state(origin_circuit_t
*circ
)
1333 if (/* The circuit may have become non-open if it was cannibalized.*/
1334 circ
->base_
.state
== CIRCUIT_STATE_OPEN
&&
1335 /* If !isolation_values_set, there is nothing to clear. */
1336 circ
->isolation_values_set
&&
1337 /* It's not legal to clear a circuit's isolation info if it's ever had
1338 * streams attached */
1339 !circ
->isolation_any_streams_attached
) {
1340 /* If we have any isolation information set on this circuit, and
1341 * we didn't manage to attach any streams to it, then we can
1342 * and should clear it and try again. */
1343 circuit_clear_isolation(circ
);
1350 /** Called when a circuit becomes ready for streams to be attached to
1353 circuit_try_attaching_streams(origin_circuit_t
*circ
)
1355 /* Attach streams to this circuit if we can. */
1356 connection_ap_attach_pending();
1358 /* The call to circuit_try_clearing_isolation_state here will do
1359 * nothing and return 0 if we didn't attach any streams to circ
1361 if (circuit_try_clearing_isolation_state(circ
)) {
1362 /* Maybe *now* we can attach some streams to this circuit. */
1363 connection_ap_attach_pending();
1367 /** Called whenever a circuit could not be successfully built.
1370 circuit_build_failed(origin_circuit_t
*circ
)
1372 channel_t
*n_chan
= NULL
;
1373 /* we should examine circ and see if it failed because of
1374 * the last hop or an earlier hop. then use this info below.
1376 int failed_at_last_hop
= 0;
1377 /* If the last hop isn't open, and the second-to-last is, we failed
1378 * at the last hop. */
1380 circ
->cpath
->prev
->state
!= CPATH_STATE_OPEN
&&
1381 circ
->cpath
->prev
->prev
->state
== CPATH_STATE_OPEN
) {
1382 failed_at_last_hop
= 1;
1385 circ
->cpath
->state
!= CPATH_STATE_OPEN
&&
1386 ! circ
->base_
.received_destroy
) {
1387 /* We failed at the first hop for some reason other than a DESTROY cell.
1388 * If there's an OR connection to blame, blame it. Also, avoid this relay
1389 * for a while, and fail any one-hop directory fetches destined for it. */
1390 const char *n_chan_id
= circ
->cpath
->extend_info
->identity_digest
;
1391 int already_marked
= 0;
1392 if (circ
->base_
.n_chan
) {
1393 n_chan
= circ
->base_
.n_chan
;
1395 if (n_chan
->is_bad_for_new_circs
) {
1396 /* We only want to blame this router when a fresh healthy
1397 * connection fails. So don't mark this router as newly failed,
1398 * since maybe this was just an old circuit attempt that's
1399 * finally timing out now. Also, there's no need to blow away
1400 * circuits/streams/etc, since the failure of an unhealthy conn
1401 * doesn't tell us much about whether a healthy conn would
1406 "Our circuit failed to get a response from the first hop "
1407 "(%s). I'm going to try to rotate to a better connection.",
1408 channel_get_canonical_remote_descr(n_chan
));
1409 n_chan
->is_bad_for_new_circs
= 1;
1412 "Our circuit died before the first hop with no connection");
1414 if (n_chan_id
&& !already_marked
) {
1415 entry_guard_register_connect_status(n_chan_id
, 0, 1, time(NULL
));
1416 /* if there are any one-hop streams waiting on this circuit, fail
1417 * them now so they can retry elsewhere. */
1418 connection_ap_fail_onehop(n_chan_id
, circ
->build_state
);
1422 switch (circ
->base_
.purpose
) {
1423 case CIRCUIT_PURPOSE_C_GENERAL
:
1424 /* If we never built the circuit, note it as a failure. */
1425 circuit_increment_failure_count();
1426 if (failed_at_last_hop
) {
1427 /* Make sure any streams that demand our last hop as their exit
1428 * know that it's unlikely to happen. */
1429 circuit_discard_optional_exit_enclaves(circ
->cpath
->prev
->extend_info
);
1432 case CIRCUIT_PURPOSE_TESTING
:
1433 circuit_testing_failed(circ
, failed_at_last_hop
);
1435 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1436 /* at Bob, waiting for introductions */
1437 if (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
) {
1438 circuit_increment_failure_count();
1440 /* no need to care here, because bob will rebuild intro
1441 * points periodically. */
1443 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1444 /* at Alice, connecting to intro point */
1445 /* Don't increment failure count, since Bob may have picked
1446 * the introduction point maliciously */
1447 /* Alice will pick a new intro point when this one dies, if
1448 * the stream in question still cares. No need to act here. */
1450 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1451 /* at Alice, waiting for Bob */
1452 circuit_increment_failure_count();
1453 /* Alice will pick a new rend point when this one dies, if
1454 * the stream in question still cares. No need to act here. */
1456 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1457 /* at Bob, connecting to rend point */
1458 /* Don't increment failure count, since Alice may have picked
1459 * the rendezvous point maliciously */
1461 "Couldn't connect to Alice's chosen rend point %s "
1463 escaped(build_state_get_exit_nickname(circ
->build_state
)),
1464 failed_at_last_hop
?"last":"non-last");
1465 rend_service_relaunch_rendezvous(circ
);
1468 * This won't happen in normal operation, but might happen if the
1469 * controller did it. Just let it slide. */
1473 /** Number of consecutive failures so far; should only be touched by
1474 * circuit_launch_new and circuit_*_failure_count.
1476 static int n_circuit_failures
= 0;
1477 /** Before the last time we called circuit_reset_failure_count(), were
1478 * there a lot of failures? */
1479 static int did_circs_fail_last_period
= 0;
1481 /** Don't retry launching a new circuit if we try this many times with no
1483 #define MAX_CIRCUIT_FAILURES 5
1485 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1486 * details on arguments. */
1488 circuit_launch(uint8_t purpose
, int flags
)
1490 return circuit_launch_by_extend_info(purpose
, NULL
, flags
);
1493 /** Launch a new circuit with purpose <b>purpose</b> and exit node
1494 * <b>extend_info</b> (or NULL to select a random exit node). If flags
1495 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
1496 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
1497 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
1498 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
1499 * Return the newly allocated circuit on success, or NULL on failure. */
1501 circuit_launch_by_extend_info(uint8_t purpose
,
1502 extend_info_t
*extend_info
,
1505 origin_circuit_t
*circ
;
1506 int onehop_tunnel
= (flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) != 0;
1508 if (!onehop_tunnel
&& !router_have_minimum_dir_info()) {
1509 log_debug(LD_CIRC
,"Haven't fetched enough directory info yet; canceling "
1514 if ((extend_info
|| purpose
!= CIRCUIT_PURPOSE_C_GENERAL
) &&
1515 purpose
!= CIRCUIT_PURPOSE_TESTING
&& !onehop_tunnel
) {
1516 /* see if there are appropriate circs available to cannibalize. */
1517 /* XXX if we're planning to add a hop, perhaps we want to look for
1518 * internal circs rather than exit circs? -RD */
1519 circ
= circuit_find_to_cannibalize(purpose
, extend_info
, flags
);
1521 uint8_t old_purpose
= circ
->base_
.purpose
;
1522 struct timeval old_timestamp_began
= circ
->base_
.timestamp_began
;
1524 log_info(LD_CIRC
,"Cannibalizing circ '%s' for purpose %d (%s)",
1525 build_state_get_exit_nickname(circ
->build_state
), purpose
,
1526 circuit_purpose_to_string(purpose
));
1528 if ((purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
||
1529 purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
) &&
1530 circ
->path_state
== PATH_STATE_BUILD_SUCCEEDED
) {
1531 /* Path bias: Cannibalized rends pre-emptively count as a
1532 * successfully built but unused closed circuit. We don't
1533 * wait until the extend (or the close) because the rend
1534 * point could be malicious.
1536 * Same deal goes for client side introductions. Clients
1537 * can be manipulated to connect repeatedly to them
1538 * (especially web clients).
1540 * If we decide to probe the initial portion of these circs,
1541 * (up to the adversary's final hop), we need to remove this,
1542 * or somehow mark the circuit with a special path state.
1545 /* This must be called before the purpose change */
1546 pathbias_check_close(circ
, END_CIRC_REASON_FINISHED
);
1549 circuit_change_purpose(TO_CIRCUIT(circ
), purpose
);
1550 /* Reset the start date of this circ, else expire_building
1551 * will see it and think it's been trying to build since it
1554 * Technically, the code should reset this when the
1555 * create cell is finally sent, but we're close enough
1557 tor_gettimeofday(&circ
->base_
.timestamp_began
);
1559 control_event_circuit_cannibalized(circ
, old_purpose
,
1560 &old_timestamp_began
);
1563 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1564 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1565 /* it's ready right now */
1567 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1568 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1569 case CIRCUIT_PURPOSE_C_GENERAL
:
1570 /* need to add a new hop */
1571 tor_assert(extend_info
);
1572 if (circuit_extend_to_new_exit(circ
, extend_info
) < 0)
1577 "unexpected purpose %d when cannibalizing a circ.",
1579 tor_fragile_assert();
1586 if (did_circs_fail_last_period
&&
1587 n_circuit_failures
> MAX_CIRCUIT_FAILURES
) {
1588 /* too many failed circs in a row. don't try. */
1589 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1593 /* try a circ. if it fails, circuit_mark_for_close will increment
1594 * n_circuit_failures */
1595 return circuit_establish_circuit(purpose
, extend_info
, flags
);
1598 /** Record another failure at opening a general circuit. When we have
1599 * too many, we'll stop trying for the remainder of this minute.
1602 circuit_increment_failure_count(void)
1604 ++n_circuit_failures
;
1605 log_debug(LD_CIRC
,"n_circuit_failures now %d.",n_circuit_failures
);
1608 /** Reset the failure count for opening general circuits. This means
1609 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1613 circuit_reset_failure_count(int timeout
)
1615 if (timeout
&& n_circuit_failures
> MAX_CIRCUIT_FAILURES
)
1616 did_circs_fail_last_period
= 1;
1618 did_circs_fail_last_period
= 0;
1619 n_circuit_failures
= 0;
1622 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1623 * there isn't one, and there isn't one on the way, launch one and return
1624 * 0. If it will never work, return -1.
1626 * Write the found or in-progress or launched circ into *circp.
1629 circuit_get_open_circ_or_launch(entry_connection_t
*conn
,
1630 uint8_t desired_circuit_purpose
,
1631 origin_circuit_t
**circp
)
1633 origin_circuit_t
*circ
;
1634 int check_exit_policy
;
1635 int need_uptime
, need_internal
;
1637 const or_options_t
*options
= get_options();
1641 tor_assert(ENTRY_TO_CONN(conn
)->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1643 conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
&&
1644 !conn
->use_begindir
&&
1645 !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn
));
1646 want_onehop
= conn
->want_onehop
;
1648 need_uptime
= !conn
->want_onehop
&& !conn
->use_begindir
&&
1649 smartlist_contains_int_as_string(options
->LongLivedPorts
,
1650 conn
->socks_request
->port
);
1652 if (desired_circuit_purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
1654 else if (conn
->use_begindir
|| conn
->want_onehop
)
1659 circ
= circuit_get_best(conn
, 1, desired_circuit_purpose
,
1660 need_uptime
, need_internal
);
1664 return 1; /* we're happy */
1667 if (!want_onehop
&& !router_have_minimum_dir_info()) {
1668 if (!connection_get_by_type(CONN_TYPE_DIR
)) {
1669 int severity
= LOG_NOTICE
;
1670 /* FFFF if this is a tunneled directory fetch, don't yell
1671 * as loudly. the user doesn't even know it's happening. */
1672 if (entry_list_is_constrained(options
) &&
1673 entries_known_but_down(options
)) {
1674 log_fn(severity
, LD_APP
|LD_DIR
,
1675 "Application request when we haven't used client functionality "
1676 "lately. Optimistically trying known %s again.",
1677 options
->UseBridges
? "bridges" : "entrynodes");
1678 entries_retry_all(options
);
1679 } else if (!options
->UseBridges
|| any_bridge_descriptors_known()) {
1680 log_fn(severity
, LD_APP
|LD_DIR
,
1681 "Application request when we haven't used client functionality "
1682 "lately. Optimistically trying directory fetches again.");
1683 routerlist_retry_directory_downloads(time(NULL
));
1686 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1687 * 1, or when all directory attempts fail and directory_all_unreachable()
1693 /* Do we need to check exit policy? */
1694 if (check_exit_policy
) {
1695 if (!conn
->chosen_exit_name
) {
1697 tor_addr_t addr
, *addrp
=NULL
;
1698 if (tor_inet_aton(conn
->socks_request
->address
, &in
)) {
1699 tor_addr_from_in(&addr
, &in
);
1702 if (router_exit_policy_all_nodes_reject(addrp
,
1703 conn
->socks_request
->port
,
1706 "No Tor server allows exit to %s:%d. Rejecting.",
1707 safe_str_client(conn
->socks_request
->address
),
1708 conn
->socks_request
->port
);
1712 /* XXXX024 Duplicates checks in connection_ap_handshake_attach_circuit:
1713 * refactor into a single function? */
1714 const node_t
*node
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1715 int opt
= conn
->chosen_exit_optional
;
1716 if (node
&& !connection_ap_can_use_exit(conn
, node
)) {
1717 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1718 "Requested exit point '%s' is excluded or "
1719 "would refuse request. %s.",
1720 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1722 conn
->chosen_exit_optional
= 0;
1723 tor_free(conn
->chosen_exit_name
);
1725 return circuit_get_open_circ_or_launch(conn
,
1726 desired_circuit_purpose
,
1734 /* is one already on the way? */
1735 circ
= circuit_get_best(conn
, 0, desired_circuit_purpose
,
1736 need_uptime
, need_internal
);
1738 log_debug(LD_CIRC
, "one on the way!");
1740 extend_info_t
*extend_info
=NULL
;
1741 uint8_t new_circ_purpose
;
1742 const int n_pending
= count_pending_general_client_circuits();
1744 if (n_pending
>= options
->MaxClientCircuitsPending
) {
1745 static ratelim_t delay_limit
= RATELIM_INIT(10*60);
1747 if ((m
= rate_limit_log(&delay_limit
, approx_time()))) {
1748 log_notice(LD_APP
, "We'd like to launch a circuit to handle a "
1749 "connection, but we already have %d general-purpose client "
1750 "circuits pending. Waiting until some finish.%s",
1757 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
) {
1758 /* need to pick an intro point */
1759 rend_data_t
*rend_data
= ENTRY_TO_EDGE_CONN(conn
)->rend_data
;
1760 tor_assert(rend_data
);
1761 extend_info
= rend_client_get_random_intro(rend_data
);
1764 "No intro points for '%s': re-fetching service descriptor.",
1765 safe_str_client(rend_data
->onion_address
));
1766 rend_client_refetch_v2_renddesc(rend_data
);
1767 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_RENDDESC_WAIT
;
1770 log_info(LD_REND
,"Chose %s as intro point for '%s'.",
1771 extend_info_describe(extend_info
),
1772 safe_str_client(rend_data
->onion_address
));
1775 /* If we have specified a particular exit node for our
1776 * connection, then be sure to open a circuit to that exit node.
1778 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
1779 if (conn
->chosen_exit_name
) {
1781 int opt
= conn
->chosen_exit_optional
;
1782 r
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1783 if (r
&& node_has_descriptor(r
)) {
1784 /* We might want to connect to an IPv6 bridge for loading
1785 descriptors so we use the preferred address rather than
1787 extend_info
= extend_info_from_node(r
, conn
->want_onehop
? 1 : 0);
1789 log_debug(LD_DIR
, "considering %d, %s",
1790 want_onehop
, conn
->chosen_exit_name
);
1791 if (want_onehop
&& conn
->chosen_exit_name
[0] == '$') {
1792 /* We're asking for a one-hop circuit to a router that
1793 * we don't have a routerinfo about. Make up an extend_info. */
1794 char digest
[DIGEST_LEN
];
1795 char *hexdigest
= conn
->chosen_exit_name
+1;
1797 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
1798 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
)<0) {
1799 log_info(LD_DIR
, "Broken exit digest on tunnel conn. Closing.");
1802 if (tor_addr_parse(&addr
, conn
->socks_request
->address
) < 0) {
1803 log_info(LD_DIR
, "Broken address %s on tunnel conn. Closing.",
1804 escaped_safe_str_client(conn
->socks_request
->address
));
1807 extend_info
= extend_info_new(conn
->chosen_exit_name
+1,
1808 digest
, NULL
, NULL
, &addr
,
1809 conn
->socks_request
->port
);
1811 /* We will need an onion key for the router, and we
1812 * don't have one. Refuse or relax requirements. */
1813 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1814 "Requested exit point '%s' is not known. %s.",
1815 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1817 conn
->chosen_exit_optional
= 0;
1818 tor_free(conn
->chosen_exit_name
);
1819 /* Try again with no requested exit */
1820 return circuit_get_open_circ_or_launch(conn
,
1821 desired_circuit_purpose
,
1830 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
)
1831 new_circ_purpose
= CIRCUIT_PURPOSE_C_ESTABLISH_REND
;
1832 else if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
1833 new_circ_purpose
= CIRCUIT_PURPOSE_C_INTRODUCING
;
1835 new_circ_purpose
= desired_circuit_purpose
;
1837 if (options
->Tor2webMode
&&
1838 (new_circ_purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
||
1839 new_circ_purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
)) {
1844 int flags
= CIRCLAUNCH_NEED_CAPACITY
;
1845 if (want_onehop
) flags
|= CIRCLAUNCH_ONEHOP_TUNNEL
;
1846 if (need_uptime
) flags
|= CIRCLAUNCH_NEED_UPTIME
;
1847 if (need_internal
) flags
|= CIRCLAUNCH_IS_INTERNAL
;
1848 circ
= circuit_launch_by_extend_info(new_circ_purpose
, extend_info
,
1852 extend_info_free(extend_info
);
1854 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
1855 /* We just caused a circuit to get built because of this stream.
1856 * If this stream has caused a _lot_ of circuits to be built, that's
1857 * a bad sign: we should tell the user. */
1858 if (conn
->num_circuits_launched
< NUM_CIRCUITS_LAUNCHED_THRESHOLD
&&
1859 ++conn
->num_circuits_launched
== NUM_CIRCUITS_LAUNCHED_THRESHOLD
)
1860 log_info(LD_CIRC
, "The application request to %s:%d has launched "
1861 "%d circuits without finding one it likes.",
1862 escaped_safe_str_client(conn
->socks_request
->address
),
1863 conn
->socks_request
->port
,
1864 conn
->num_circuits_launched
);
1866 /* help predict this next time */
1867 rep_hist_note_used_internal(time(NULL
), need_uptime
, 1);
1869 /* write the service_id into circ */
1870 circ
->rend_data
= rend_data_dup(ENTRY_TO_EDGE_CONN(conn
)->rend_data
);
1871 if (circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
&&
1872 circ
->base_
.state
== CIRCUIT_STATE_OPEN
)
1873 rend_client_rendcirc_has_opened(circ
);
1876 } /* endif (!circ) */
1878 /* Mark the circuit with the isolation fields for this connection.
1879 * When the circuit arrives, we'll clear these flags: this is
1880 * just some internal bookkeeping to make sure that we have
1881 * launched enough circuits.
1883 connection_edge_update_circuit_isolation(conn
, circ
, 0);
1886 "No safe circuit (purpose %d) ready for edge "
1887 "connection; delaying.",
1888 desired_circuit_purpose
);
1894 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1897 cpath_is_on_circuit(origin_circuit_t
*circ
, crypt_path_t
*crypt_path
)
1899 crypt_path_t
*cpath
, *cpath_next
= NULL
;
1900 for (cpath
= circ
->cpath
; cpath_next
!= circ
->cpath
; cpath
= cpath_next
) {
1901 cpath_next
= cpath
->next
;
1902 if (crypt_path
== cpath
)
1908 /** Return true iff client-side optimistic data is supported. */
1910 optimistic_data_enabled(void)
1912 const or_options_t
*options
= get_options();
1913 if (options
->OptimisticData
< 0) {
1914 /* XXX023 consider having auto default to 1 rather than 0 before
1915 * the 0.2.3 branch goes stable. See bug 3617. -RD */
1916 const int32_t enabled
=
1917 networkstatus_get_param(NULL
, "UseOptimisticData", 0, 0, 1);
1918 return (int)enabled
;
1920 return options
->OptimisticData
;
1923 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1924 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1925 * hop in circ's cpath if <b>cpath</b> is NULL.
1928 link_apconn_to_circ(entry_connection_t
*apconn
, origin_circuit_t
*circ
,
1929 crypt_path_t
*cpath
)
1931 const node_t
*exitnode
;
1933 /* add it into the linked list of streams on this circuit */
1934 log_debug(LD_APP
|LD_CIRC
, "attaching new conn to circ. n_circ_id %u.",
1935 (unsigned)circ
->base_
.n_circ_id
);
1936 /* reset it, so we can measure circ timeouts */
1937 ENTRY_TO_CONN(apconn
)->timestamp_lastread
= time(NULL
);
1938 ENTRY_TO_EDGE_CONN(apconn
)->next_stream
= circ
->p_streams
;
1939 ENTRY_TO_EDGE_CONN(apconn
)->on_circuit
= TO_CIRCUIT(circ
);
1940 /* assert_connection_ok(conn, time(NULL)); */
1941 circ
->p_streams
= ENTRY_TO_EDGE_CONN(apconn
);
1943 if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn
))) {
1944 /* We are attaching a stream to a rendezvous circuit. That means
1945 * that an attempt to connect to a hidden service just
1946 * succeeded. Tell rendclient.c. */
1947 rend_client_note_connection_attempt_ended(
1948 ENTRY_TO_EDGE_CONN(apconn
)->rend_data
->onion_address
);
1951 if (cpath
) { /* we were given one; use it */
1952 tor_assert(cpath_is_on_circuit(circ
, cpath
));
1954 /* use the last hop in the circuit */
1955 tor_assert(circ
->cpath
);
1956 tor_assert(circ
->cpath
->prev
);
1957 tor_assert(circ
->cpath
->prev
->state
== CPATH_STATE_OPEN
);
1958 cpath
= circ
->cpath
->prev
;
1960 ENTRY_TO_EDGE_CONN(apconn
)->cpath_layer
= cpath
;
1962 circ
->isolation_any_streams_attached
= 1;
1963 connection_edge_update_circuit_isolation(apconn
, circ
, 0);
1965 /* See if we can use optimistic data on this circuit */
1966 if (cpath
->extend_info
&&
1967 (exitnode
= node_get_by_id(cpath
->extend_info
->identity_digest
)) &&
1969 /* Okay; we know what exit node this is. */
1970 if (optimistic_data_enabled() &&
1971 circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
&&
1972 exitnode
->rs
->version_supports_optimistic_data
)
1973 apconn
->may_use_optimistic_data
= 1;
1975 apconn
->may_use_optimistic_data
= 0;
1976 log_info(LD_APP
, "Looks like completed circuit to %s %s allow "
1977 "optimistic data for connection to %s",
1978 safe_str_client(node_describe(exitnode
)),
1979 apconn
->may_use_optimistic_data
? "does" : "doesn't",
1980 safe_str_client(apconn
->socks_request
->address
));
1984 /** Return true iff <b>address</b> is matched by one of the entries in
1985 * TrackHostExits. */
1987 hostname_in_track_host_exits(const or_options_t
*options
, const char *address
)
1989 if (!options
->TrackHostExits
)
1991 SMARTLIST_FOREACH_BEGIN(options
->TrackHostExits
, const char *, cp
) {
1992 if (cp
[0] == '.') { /* match end */
1993 if (cp
[1] == '\0' ||
1994 !strcasecmpend(address
, cp
) ||
1995 !strcasecmp(address
, &cp
[1]))
1997 } else if (strcasecmp(cp
, address
) == 0) {
2000 } SMARTLIST_FOREACH_END(cp
);
2004 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
2005 * the exit that we *did* choose for use by future connections to
2006 * <b>conn</b>'s destination.
2009 consider_recording_trackhost(const entry_connection_t
*conn
,
2010 const origin_circuit_t
*circ
)
2012 const or_options_t
*options
= get_options();
2013 char *new_address
= NULL
;
2014 char fp
[HEX_DIGEST_LEN
+1];
2016 /* Search the addressmap for this conn's destination. */
2017 /* If he's not in the address map.. */
2018 if (!options
->TrackHostExits
||
2019 addressmap_have_mapping(conn
->socks_request
->address
,
2020 options
->TrackHostExitsExpire
))
2021 return; /* nothing to track, or already mapped */
2023 if (!hostname_in_track_host_exits(options
, conn
->socks_request
->address
) ||
2024 !circ
->build_state
->chosen_exit
)
2027 /* write down the fingerprint of the chosen exit, not the nickname,
2028 * because the chosen exit might not be named. */
2029 base16_encode(fp
, sizeof(fp
),
2030 circ
->build_state
->chosen_exit
->identity_digest
, DIGEST_LEN
);
2032 /* Add this exit/hostname pair to the addressmap. */
2033 tor_asprintf(&new_address
, "%s.%s.exit",
2034 conn
->socks_request
->address
, fp
);
2036 addressmap_register(conn
->socks_request
->address
, new_address
,
2037 time(NULL
) + options
->TrackHostExitsExpire
,
2038 ADDRMAPSRC_TRACKEXIT
, 0, 0);
2041 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
2042 * begin or resolve cell as appropriate. Return values are as for
2043 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
2044 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2045 * <b>cpath</b> is NULL. */
2047 connection_ap_handshake_attach_chosen_circuit(entry_connection_t
*conn
,
2048 origin_circuit_t
*circ
,
2049 crypt_path_t
*cpath
)
2051 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
2053 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
||
2054 base_conn
->state
== AP_CONN_STATE_CONTROLLER_WAIT
);
2055 tor_assert(conn
->socks_request
);
2057 tor_assert(circ
->base_
.state
== CIRCUIT_STATE_OPEN
);
2059 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2061 if (!circ
->base_
.timestamp_dirty
)
2062 circ
->base_
.timestamp_dirty
= time(NULL
);
2064 pathbias_count_use_attempt(circ
);
2066 link_apconn_to_circ(conn
, circ
, cpath
);
2067 tor_assert(conn
->socks_request
);
2068 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
2069 if (!conn
->use_begindir
)
2070 consider_recording_trackhost(conn
, circ
);
2071 if (connection_ap_handshake_send_begin(conn
) < 0)
2074 if (connection_ap_handshake_send_resolve(conn
) < 0)
2081 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
2082 * we don't find one: if conn cannot be handled by any known nodes,
2083 * warn and return -1 (conn needs to die, and is maybe already marked);
2084 * else launch new circuit (if necessary) and return 0.
2085 * Otherwise, associate conn with a safe live circuit, do the
2086 * right next step, and return 1.
2088 /* XXXX this function should mark for close whenever it returns -1;
2089 * its callers shouldn't have to worry about that. */
2091 connection_ap_handshake_attach_circuit(entry_connection_t
*conn
)
2093 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
2099 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
2100 tor_assert(conn
->socks_request
);
2101 want_onehop
= conn
->want_onehop
;
2103 conn_age
= (int)(time(NULL
) - base_conn
->timestamp_created
);
2105 if (conn_age
>= get_options()->SocksTimeout
) {
2106 int severity
= (tor_addr_is_null(&base_conn
->addr
) && !base_conn
->port
) ?
2107 LOG_INFO
: LOG_NOTICE
;
2108 log_fn(severity
, LD_APP
,
2109 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
2110 conn_age
, safe_str_client(conn
->socks_request
->address
),
2111 conn
->socks_request
->port
);
2115 if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn
))) {
2116 /* we're a general conn */
2117 origin_circuit_t
*circ
=NULL
;
2119 if (conn
->chosen_exit_name
) {
2120 const node_t
*node
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
2121 int opt
= conn
->chosen_exit_optional
;
2122 if (!node
&& !want_onehop
) {
2123 /* We ran into this warning when trying to extend a circuit to a
2124 * hidden service directory for which we didn't have a router
2125 * descriptor. See flyspray task 767 for more details. We should
2126 * keep this in mind when deciding to use BEGIN_DIR cells for other
2127 * directory requests as well. -KL*/
2128 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
2129 "Requested exit point '%s' is not known. %s.",
2130 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
2132 conn
->chosen_exit_optional
= 0;
2133 tor_free(conn
->chosen_exit_name
);
2138 if (node
&& !connection_ap_can_use_exit(conn
, node
)) {
2139 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
2140 "Requested exit point '%s' is excluded or "
2141 "would refuse request. %s.",
2142 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
2144 conn
->chosen_exit_optional
= 0;
2145 tor_free(conn
->chosen_exit_name
);
2152 /* find the circuit that we should use, if there is one. */
2153 retval
= circuit_get_open_circ_or_launch(
2154 conn
, CIRCUIT_PURPOSE_C_GENERAL
, &circ
);
2155 if (retval
< 1) // XXX023 if we totally fail, this still returns 0 -RD
2158 log_debug(LD_APP
|LD_CIRC
,
2159 "Attaching apconn to circ %u (stream %d sec old).",
2160 (unsigned)circ
->base_
.n_circ_id
, conn_age
);
2161 /* print the circ's path, so people can figure out which circs are
2163 circuit_log_path(LOG_INFO
,LD_APP
|LD_CIRC
,circ
);
2165 /* We have found a suitable circuit for our conn. Hurray. */
2166 return connection_ap_handshake_attach_chosen_circuit(conn
, circ
, NULL
);
2168 } else { /* we're a rendezvous conn */
2169 origin_circuit_t
*rendcirc
=NULL
, *introcirc
=NULL
;
2171 tor_assert(!ENTRY_TO_EDGE_CONN(conn
)->cpath_layer
);
2173 /* start by finding a rendezvous circuit for us */
2175 retval
= circuit_get_open_circ_or_launch(
2176 conn
, CIRCUIT_PURPOSE_C_REND_JOINED
, &rendcirc
);
2177 if (retval
< 0) return -1; /* failed */
2180 tor_assert(rendcirc
);
2181 /* one is already established, attach */
2183 "rend joined circ %d already here. attaching. "
2184 "(stream %d sec old)",
2185 (unsigned)rendcirc
->base_
.n_circ_id
, conn_age
);
2186 /* Mark rendezvous circuits as 'newly dirty' every time you use
2187 * them, since the process of rebuilding a rendezvous circ is so
2188 * expensive. There is a tradeoff between linkability and
2189 * feasibility, at this point.
2191 rendcirc
->base_
.timestamp_dirty
= time(NULL
);
2193 /* We've also attempted to use them. If they fail, we need to
2194 * probe them for path bias */
2195 pathbias_count_use_attempt(rendcirc
);
2197 link_apconn_to_circ(conn
, rendcirc
, NULL
);
2198 if (connection_ap_handshake_send_begin(conn
) < 0)
2199 return 0; /* already marked, let them fade away */
2203 if (rendcirc
&& (rendcirc
->base_
.purpose
==
2204 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
)) {
2206 "pending-join circ %u already here, with intro ack. "
2207 "Stalling. (stream %d sec old)",
2208 (unsigned)rendcirc
->base_
.n_circ_id
, conn_age
);
2212 /* it's on its way. find an intro circ. */
2213 retval
= circuit_get_open_circ_or_launch(
2214 conn
, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
, &introcirc
);
2215 if (retval
< 0) return -1; /* failed */
2218 /* one has already sent the intro. keep waiting. */
2219 tor_assert(introcirc
);
2220 log_info(LD_REND
, "Intro circ %u present and awaiting ack (rend %u). "
2221 "Stalling. (stream %d sec old)",
2222 (unsigned)introcirc
->base_
.n_circ_id
,
2223 rendcirc
? (unsigned)rendcirc
->base_
.n_circ_id
: 0,
2228 /* now rendcirc and introcirc are each either undefined or not finished */
2230 if (rendcirc
&& introcirc
&&
2231 rendcirc
->base_
.purpose
== CIRCUIT_PURPOSE_C_REND_READY
) {
2233 "ready rend circ %u already here (no intro-ack yet on "
2234 "intro %u). (stream %d sec old)",
2235 (unsigned)rendcirc
->base_
.n_circ_id
,
2236 (unsigned)introcirc
->base_
.n_circ_id
, conn_age
);
2238 tor_assert(introcirc
->base_
.purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
2239 if (introcirc
->base_
.state
== CIRCUIT_STATE_OPEN
) {
2240 log_info(LD_REND
,"found open intro circ %u (rend %u); sending "
2241 "introduction. (stream %d sec old)",
2242 (unsigned)introcirc
->base_
.n_circ_id
,
2243 (unsigned)rendcirc
->base_
.n_circ_id
,
2245 switch (rend_client_send_introduction(introcirc
, rendcirc
)) {
2246 case 0: /* success */
2247 rendcirc
->base_
.timestamp_dirty
= time(NULL
);
2248 introcirc
->base_
.timestamp_dirty
= time(NULL
);
2250 pathbias_count_use_attempt(introcirc
);
2251 pathbias_count_use_attempt(rendcirc
);
2253 assert_circuit_ok(TO_CIRCUIT(rendcirc
));
2254 assert_circuit_ok(TO_CIRCUIT(introcirc
));
2256 case -1: /* transient error */
2258 case -2: /* permanent error */
2261 tor_fragile_assert();
2267 log_info(LD_REND
, "Intro (%u) and rend (%u) circs are not both ready. "
2268 "Stalling conn. (%d sec old)",
2269 introcirc
? (unsigned)introcirc
->base_
.n_circ_id
: 0,
2270 rendcirc
? (unsigned)rendcirc
->base_
.n_circ_id
: 0, conn_age
);
2275 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
2277 circuit_change_purpose(circuit_t
*circ
, uint8_t new_purpose
)
2279 uint8_t old_purpose
;
2280 /* Don't allow an OR circ to become an origin circ or vice versa. */
2281 tor_assert(!!(CIRCUIT_IS_ORIGIN(circ
)) ==
2282 !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose
)));
2284 if (circ
->purpose
== new_purpose
) return;
2286 if (CIRCUIT_IS_ORIGIN(circ
)) {
2287 char old_purpose_desc
[80] = "";
2289 strncpy(old_purpose_desc
, circuit_purpose_to_string(circ
->purpose
), 80-1);
2290 old_purpose_desc
[80-1] = '\0';
2293 "changing purpose of origin circ %d "
2294 "from \"%s\" (%d) to \"%s\" (%d)",
2295 TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
2298 circuit_purpose_to_string(new_purpose
),
2302 old_purpose
= circ
->purpose
;
2303 circ
->purpose
= new_purpose
;
2305 if (CIRCUIT_IS_ORIGIN(circ
)) {
2306 control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ
),
2311 /** Mark <b>circ</b> so that no more connections can be attached to it. */
2313 mark_circuit_unusable_for_new_conns(origin_circuit_t
*circ
)
2315 const or_options_t
*options
= get_options();
2318 /* XXXX025 This is a kludge; we're only keeping it around in case there's
2319 * something that doesn't check unusable_for_new_conns, and to avoid
2320 * deeper refactoring of our expiration logic. */
2321 if (! circ
->base_
.timestamp_dirty
)
2322 circ
->base_
.timestamp_dirty
= approx_time();
2323 if (options
->MaxCircuitDirtiness
>= circ
->base_
.timestamp_dirty
)
2324 circ
->base_
.timestamp_dirty
= 1; /* prevent underflow */
2326 circ
->base_
.timestamp_dirty
-= options
->MaxCircuitDirtiness
;
2328 circ
->unusable_for_new_conns
= 1;