dirvote: Handling adding vote and signature if module is disabled
[tor.git] / src / or / circuituse.c
blob47e29c28dd2b42324e79ebbe4331e344da405a0a
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-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file circuituse.c
9 * \brief Launch the right sort of circuits and attach the right streams to
10 * them.
12 * As distinct from circuitlist.c, which manages lookups to find circuits, and
13 * circuitbuild.c, which handles the logistics of circuit construction, this
14 * module keeps track of which streams can be attached to which circuits (in
15 * circuit_get_best()), and attaches streams to circuits (with
16 * circuit_try_attaching_streams(), connection_ap_handshake_attach_circuit(),
17 * and connection_ap_handshake_attach_chosen_circuit() ).
19 * This module also makes sure that we are building circuits for all of the
20 * predicted ports, using circuit_remove_handled_ports(),
21 * circuit_stream_is_being_handled(), and circuit_build_needed_cirs(). It
22 * handles launching circuits for specific targets using
23 * circuit_launch_by_extend_info().
25 * This is also where we handle expiring circuits that have been around for
26 * too long without actually completing, along with the circuit_build_timeout
27 * logic in circuitstats.c.
28 **/
30 #include "or.h"
31 #include "addressmap.h"
32 #include "bridges.h"
33 #include "channel.h"
34 #include "circpathbias.h"
35 #include "circuitbuild.h"
36 #include "circuitlist.h"
37 #include "circuitstats.h"
38 #include "circuituse.h"
39 #include "config.h"
40 #include "connection.h"
41 #include "connection_edge.h"
42 #include "control.h"
43 #include "entrynodes.h"
44 #include "hs_common.h"
45 #include "hs_client.h"
46 #include "hs_circuit.h"
47 #include "hs_ident.h"
48 #include "hs_stats.h"
49 #include "nodelist.h"
50 #include "networkstatus.h"
51 #include "policies.h"
52 #include "rendclient.h"
53 #include "rendcommon.h"
54 #include "rendservice.h"
55 #include "rephist.h"
56 #include "router.h"
57 #include "routerlist.h"
59 static void circuit_expire_old_circuits_clientside(void);
60 static void circuit_increment_failure_count(void);
62 /** Check whether the hidden service destination of the stream at
63 * <b>edge_conn</b> is the same as the destination of the circuit at
64 * <b>origin_circ</b>. */
65 static int
66 circuit_matches_with_rend_stream(const edge_connection_t *edge_conn,
67 const origin_circuit_t *origin_circ)
69 /* Check if this is a v2 rendezvous circ/stream */
70 if ((edge_conn->rend_data && !origin_circ->rend_data) ||
71 (!edge_conn->rend_data && origin_circ->rend_data) ||
72 (edge_conn->rend_data && origin_circ->rend_data &&
73 rend_cmp_service_ids(rend_data_get_address(edge_conn->rend_data),
74 rend_data_get_address(origin_circ->rend_data)))) {
75 /* this circ is not for this conn */
76 return 0;
79 /* Check if this is a v3 rendezvous circ/stream */
80 if ((edge_conn->hs_ident && !origin_circ->hs_ident) ||
81 (!edge_conn->hs_ident && origin_circ->hs_ident) ||
82 (edge_conn->hs_ident && origin_circ->hs_ident &&
83 !ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
84 &origin_circ->hs_ident->identity_pk))) {
85 /* this circ is not for this conn */
86 return 0;
89 return 1;
92 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
93 * Else return 0.
95 static int
96 circuit_is_acceptable(const origin_circuit_t *origin_circ,
97 const entry_connection_t *conn,
98 int must_be_open, uint8_t purpose,
99 int need_uptime, int need_internal,
100 time_t now)
102 const circuit_t *circ = TO_CIRCUIT(origin_circ);
103 const node_t *exitnode;
104 cpath_build_state_t *build_state;
105 tor_assert(circ);
106 tor_assert(conn);
107 tor_assert(conn->socks_request);
109 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
110 return 0; /* ignore non-open circs */
111 if (circ->marked_for_close)
112 return 0;
114 /* if this circ isn't our purpose, skip. */
115 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
116 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
117 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
118 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
119 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
120 return 0;
121 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
122 !must_be_open) {
123 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
124 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
125 return 0;
126 } else {
127 if (purpose != circ->purpose)
128 return 0;
131 /* If this is a timed-out hidden service circuit, skip it. */
132 if (origin_circ->hs_circ_has_timed_out) {
133 return 0;
136 if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
137 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
138 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
139 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
140 purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
141 if (circ->timestamp_dirty &&
142 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
143 return 0;
146 if (origin_circ->unusable_for_new_conns)
147 return 0;
149 /* decide if this circ is suitable for this conn */
151 /* for rend circs, circ->cpath->prev is not the last router in the
152 * circuit, it's the magical extra service hop. so just check the nickname
153 * of the one we meant to finish at.
155 build_state = origin_circ->build_state;
156 exitnode = build_state_get_exit_node(build_state);
158 if (need_uptime && !build_state->need_uptime)
159 return 0;
160 if (need_internal != build_state->is_internal)
161 return 0;
163 if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
164 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
165 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
166 tor_addr_t addr;
167 const int family = tor_addr_parse(&addr, conn->socks_request->address);
168 if (!exitnode && !build_state->onehop_tunnel) {
169 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
170 return 0; /* this circuit is screwed and doesn't know it yet,
171 * or is a rendezvous circuit. */
173 if (build_state->onehop_tunnel) {
174 if (!conn->want_onehop) {
175 log_debug(LD_CIRC,"Skipping one-hop circuit.");
176 return 0;
178 tor_assert(conn->chosen_exit_name);
179 if (build_state->chosen_exit) {
180 char digest[DIGEST_LEN];
181 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
182 return 0; /* broken digest, we don't want it */
183 if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
184 DIGEST_LEN))
185 return 0; /* this is a circuit to somewhere else */
186 if (tor_digest_is_zero(digest)) {
187 /* we don't know the digest; have to compare addr:port */
188 if (family < 0 ||
189 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
190 build_state->chosen_exit->port != conn->socks_request->port)
191 return 0;
194 } else {
195 if (conn->want_onehop) {
196 /* don't use three-hop circuits -- that could hurt our anonymity. */
197 return 0;
200 if (origin_circ->prepend_policy && family != -1) {
201 int r = compare_tor_addr_to_addr_policy(&addr,
202 conn->socks_request->port,
203 origin_circ->prepend_policy);
204 if (r == ADDR_POLICY_REJECTED)
205 return 0;
207 if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
208 /* can't exit from this router */
209 return 0;
211 } else { /* not general: this might be a rend circuit */
212 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
213 if (!circuit_matches_with_rend_stream(edge_conn, origin_circ)) {
214 return 0;
218 if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
219 /* conn needs to be isolated from other conns that have already used
220 * origin_circ */
221 return 0;
224 return 1;
227 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
228 * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
230 static int
231 circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
232 const entry_connection_t *conn)
234 const circuit_t *a = TO_CIRCUIT(oa);
235 const circuit_t *b = TO_CIRCUIT(ob);
236 const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
237 int a_bits, b_bits;
239 /* If one of the circuits was allowed to live due to relaxing its timeout,
240 * it is definitely worse (it's probably a much slower path). */
241 if (oa->relaxed_timeout && !ob->relaxed_timeout)
242 return 0; /* ob is better. It's not relaxed. */
243 if (!oa->relaxed_timeout && ob->relaxed_timeout)
244 return 1; /* oa is better. It's not relaxed. */
246 switch (purpose) {
247 case CIRCUIT_PURPOSE_S_HSDIR_POST:
248 case CIRCUIT_PURPOSE_C_HSDIR_GET:
249 case CIRCUIT_PURPOSE_C_GENERAL:
250 /* if it's used but less dirty it's best;
251 * else if it's more recently created it's best
253 if (b->timestamp_dirty) {
254 if (a->timestamp_dirty &&
255 a->timestamp_dirty > b->timestamp_dirty)
256 return 1;
257 } else {
258 if (a->timestamp_dirty ||
259 timercmp(&a->timestamp_began, &b->timestamp_began, OP_GT))
260 return 1;
261 if (ob->build_state->is_internal)
262 /* XXXX++ what the heck is this internal thing doing here. I
263 * think we can get rid of it. circuit_is_acceptable() already
264 * makes sure that is_internal is exactly what we need it to
265 * be. -RD */
266 return 1;
268 break;
269 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
270 /* the closer it is to ack_wait the better it is */
271 if (a->purpose > b->purpose)
272 return 1;
273 break;
274 case CIRCUIT_PURPOSE_C_REND_JOINED:
275 /* the closer it is to rend_joined the better it is */
276 if (a->purpose > b->purpose)
277 return 1;
278 break;
281 /* XXXX Maybe this check should get a higher priority to avoid
282 * using up circuits too rapidly. */
284 a_bits = connection_edge_update_circuit_isolation(conn,
285 (origin_circuit_t*)oa, 1);
286 b_bits = connection_edge_update_circuit_isolation(conn,
287 (origin_circuit_t*)ob, 1);
288 /* if x_bits < 0, then we have not used x for anything; better not to dirty
289 * a connection if we can help it. */
290 if (a_bits < 0) {
291 return 0;
292 } else if (b_bits < 0) {
293 return 1;
295 a_bits &= ~ oa->isolation_flags_mixed;
296 a_bits &= ~ ob->isolation_flags_mixed;
297 if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
298 /* The fewer new restrictions we need to make on a circuit for stream
299 * isolation, the better. */
300 return 1;
303 return 0;
306 /** Find the best circ that conn can use, preferably one which is
307 * dirty. Circ must not be too old.
309 * Conn must be defined.
311 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
313 * circ_purpose specifies what sort of circuit we must have.
314 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
316 * If it's REND_JOINED and must_be_open==0, then return the closest
317 * rendezvous-purposed circuit that you can find.
319 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
320 * closest introduce-purposed circuit that you can find.
322 static origin_circuit_t *
323 circuit_get_best(const entry_connection_t *conn,
324 int must_be_open, uint8_t purpose,
325 int need_uptime, int need_internal)
327 origin_circuit_t *best=NULL;
328 struct timeval now;
329 int intro_going_on_but_too_old = 0;
331 tor_assert(conn);
333 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
334 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
335 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
336 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
337 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
338 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
340 tor_gettimeofday(&now);
342 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
343 origin_circuit_t *origin_circ;
344 if (!CIRCUIT_IS_ORIGIN(circ))
345 continue;
346 origin_circ = TO_ORIGIN_CIRCUIT(circ);
348 /* Log an info message if we're going to launch a new intro circ in
349 * parallel */
350 if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
351 !must_be_open && origin_circ->hs_circ_has_timed_out &&
352 !circ->marked_for_close) {
353 intro_going_on_but_too_old = 1;
354 continue;
357 if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
358 need_uptime,need_internal, (time_t)now.tv_sec))
359 continue;
361 /* now this is an acceptable circ to hand back. but that doesn't
362 * mean it's the *best* circ to hand back. try to decide.
364 if (!best || circuit_is_better(origin_circ,best,conn))
365 best = origin_circ;
367 SMARTLIST_FOREACH_END(circ);
369 if (!best && intro_going_on_but_too_old)
370 log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
371 "right now, but it has already taken quite a while. Starting "
372 "one in parallel.");
374 return best;
377 /** Return the number of not-yet-open general-purpose origin circuits. */
378 static int
379 count_pending_general_client_circuits(void)
381 int count = 0;
383 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
384 if (circ->marked_for_close ||
385 circ->state == CIRCUIT_STATE_OPEN ||
386 !CIRCUIT_PURPOSE_COUNTS_TOWARDS_MAXPENDING(circ->purpose) ||
387 !CIRCUIT_IS_ORIGIN(circ))
388 continue;
390 ++count;
392 SMARTLIST_FOREACH_END(circ);
394 return count;
397 #if 0
398 /** Check whether, according to the policies in <b>options</b>, the
399 * circuit <b>circ</b> makes sense. */
400 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
401 * Also, it doesn't have the right definition of an exit circuit. Also,
402 * it's never called. */
404 circuit_conforms_to_options(const origin_circuit_t *circ,
405 const or_options_t *options)
407 const crypt_path_t *cpath, *cpath_next = NULL;
409 /* first check if it includes any excluded nodes */
410 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
411 cpath_next = cpath->next;
412 if (routerset_contains_extendinfo(options->ExcludeNodes,
413 cpath->extend_info))
414 return 0;
417 /* then consider the final hop */
418 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
419 circ->cpath->prev->extend_info))
420 return 0;
422 return 1;
424 #endif /* 0 */
427 * Close all circuits that start at us, aren't open, and were born
428 * at least CircuitBuildTimeout seconds ago.
430 * TODO: This function is now partially redundant to
431 * circuit_build_times_handle_completed_hop(), but that function only
432 * covers circuits up to and including 3 hops that are still actually
433 * completing hops. However, circuit_expire_building() also handles longer
434 * circuits, as well as circuits that are completely stalled.
435 * In the future (after prop247/other path selection revamping), we probably
436 * want to eliminate this rats nest in favor of a simpler approach.
438 void
439 circuit_expire_building(void)
441 /* circ_times.timeout_ms and circ_times.close_ms are from
442 * circuit_build_times_get_initial_timeout() if we haven't computed
443 * custom timeouts yet */
444 struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
445 close_cutoff, extremely_old_cutoff, hs_extremely_old_cutoff,
446 cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff;
447 const or_options_t *options = get_options();
448 struct timeval now;
449 cpath_build_state_t *build_state;
450 int any_opened_circs = 0;
452 tor_gettimeofday(&now);
454 /* Check to see if we have any opened circuits. If we don't,
455 * we want to be more lenient with timeouts, in case the
456 * user has relocated and/or changed network connections.
457 * See bug #3443. */
458 any_opened_circs = circuit_any_opened_circuits();
460 #define SET_CUTOFF(target, msec) do { \
461 long ms = tor_lround(msec); \
462 struct timeval diff; \
463 diff.tv_sec = ms / 1000; \
464 diff.tv_usec = (int)((ms % 1000) * 1000); \
465 timersub(&now, &diff, &target); \
466 } while (0)
469 * Because circuit build timeout is calculated only based on 3 hop
470 * general purpose circuit construction, we need to scale the timeout
471 * to make it properly apply to longer circuits, and circuits of
472 * certain usage types. The following diagram illustrates how we
473 * derive the scaling below. In short, we calculate the number
474 * of times our telescoping-based circuit construction causes cells
475 * to traverse each link for the circuit purpose types in question,
476 * and then assume each link is equivalent.
478 * OP --a--> A --b--> B --c--> C
479 * OP --a--> A --b--> B --c--> C --d--> D
481 * Let h = a = b = c = d
483 * Three hops (general_cutoff)
484 * RTTs = 3a + 2b + c
485 * RTTs = 6h
486 * Cannibalized:
487 * RTTs = a+b+c+d
488 * RTTs = 4h
489 * Four hops:
490 * RTTs = 4a + 3b + 2c + d
491 * RTTs = 10h
492 * Client INTRODUCE1+ACK: // XXX: correct?
493 * RTTs = 5a + 4b + 3c + 2d
494 * RTTs = 14h
495 * Server intro:
496 * RTTs = 4a + 3b + 2c
497 * RTTs = 9h
499 SET_CUTOFF(general_cutoff, get_circuit_build_timeout_ms());
500 SET_CUTOFF(begindir_cutoff, get_circuit_build_timeout_ms());
502 // TODO: We should probably use route_len_for_purpose() here instead,
503 // except that does not count the extra round trip for things like server
504 // intros and rends.
506 /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
507 * 4th hop. */
508 SET_CUTOFF(fourhop_cutoff, get_circuit_build_timeout_ms() * (10/6.0) + 1000);
510 /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
511 * Use the stream cutoff (more or less). */
512 SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
514 /* Be lenient with cannibalized circs. They already survived the official
515 * CBT, and they're usually not performance-critical. */
516 SET_CUTOFF(cannibalized_cutoff,
517 MAX(get_circuit_build_close_time_ms()*(4/6.0),
518 options->CircuitStreamTimeout * 1000) + 1000);
520 /* Intro circs have an extra round trip (and are also 4 hops long) */
521 SET_CUTOFF(c_intro_cutoff, get_circuit_build_timeout_ms() * (14/6.0) + 1000);
523 /* Server intro circs have an extra round trip */
524 SET_CUTOFF(s_intro_cutoff, get_circuit_build_timeout_ms() * (9/6.0) + 1000);
526 SET_CUTOFF(close_cutoff, get_circuit_build_close_time_ms());
527 SET_CUTOFF(extremely_old_cutoff, get_circuit_build_close_time_ms()*2 + 1000);
529 SET_CUTOFF(hs_extremely_old_cutoff,
530 MAX(get_circuit_build_close_time_ms()*2 + 1000,
531 options->SocksTimeout * 1000));
533 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *,victim) {
534 struct timeval cutoff;
535 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
536 victim->marked_for_close) /* don't mess with marked circs */
537 continue;
539 /* If we haven't yet started the first hop, it means we don't have
540 * any orconns available, and thus have not started counting time yet
541 * for this circuit. See circuit_deliver_create_cell() and uses of
542 * timestamp_began.
544 * Continue to wait in this case. The ORConn should timeout
545 * independently and kill us then.
547 if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
548 continue;
551 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
552 if (build_state && build_state->onehop_tunnel)
553 cutoff = begindir_cutoff;
554 else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
555 cutoff = close_cutoff;
556 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
557 cutoff = c_intro_cutoff;
558 else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
559 cutoff = s_intro_cutoff;
560 else if (victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
561 cutoff = stream_cutoff;
562 else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
563 cutoff = close_cutoff;
564 else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
565 victim->state != CIRCUIT_STATE_OPEN)
566 cutoff = cannibalized_cutoff;
567 else if (build_state && build_state->desired_path_len >= 4)
568 cutoff = fourhop_cutoff;
569 else
570 cutoff = general_cutoff;
572 if (TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)
573 cutoff = hs_extremely_old_cutoff;
575 if (timercmp(&victim->timestamp_began, &cutoff, OP_GT))
576 continue; /* it's still young, leave it alone */
578 /* We need to double-check the opened state here because
579 * we don't want to consider opened 1-hop dircon circuits for
580 * deciding when to relax the timeout, but we *do* want to relax
581 * those circuits too if nothing else is opened *and* they still
582 * aren't either. */
583 if (!any_opened_circs && victim->state != CIRCUIT_STATE_OPEN) {
584 /* It's still young enough that we wouldn't close it, right? */
585 if (timercmp(&victim->timestamp_began, &close_cutoff, OP_GT)) {
586 if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
587 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
588 == CPATH_STATE_OPEN;
589 log_info(LD_CIRC,
590 "No circuits are opened. Relaxing timeout for circuit %d "
591 "(a %s %d-hop circuit in state %s with channel state %s).",
592 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
593 circuit_purpose_to_string(victim->purpose),
594 TO_ORIGIN_CIRCUIT(victim)->build_state ?
595 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
597 circuit_state_to_string(victim->state),
598 victim->n_chan ?
599 channel_state_to_string(victim->n_chan->state) : "none");
601 /* We count the timeout here for CBT, because technically this
602 * was a timeout, and the timeout value needs to reset if we
603 * see enough of them. Note this means we also need to avoid
604 * double-counting below, too. */
605 circuit_build_times_count_timeout(get_circuit_build_times_mutable(),
606 first_hop_succeeded);
607 TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
609 continue;
610 } else {
611 static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
612 const double build_close_ms = get_circuit_build_close_time_ms();
613 log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
614 "No circuits are opened. Relaxed timeout for circuit %d "
615 "(a %s %d-hop circuit in state %s with channel state %s) to "
616 "%ldms. However, it appears the circuit has timed out "
617 "anyway.",
618 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
619 circuit_purpose_to_string(victim->purpose),
620 TO_ORIGIN_CIRCUIT(victim)->build_state ?
621 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
623 circuit_state_to_string(victim->state),
624 victim->n_chan ?
625 channel_state_to_string(victim->n_chan->state) : "none",
626 (long)build_close_ms);
630 #if 0
631 /* some debug logs, to help track bugs */
632 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
633 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
634 if (!victim->timestamp_dirty)
635 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
636 "(clean).",
637 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
638 victim->purpose, victim->build_state->chosen_exit_name,
639 victim->n_circ_id);
640 else
641 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
642 "%d secs since dirty.",
643 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
644 victim->purpose, victim->build_state->chosen_exit_name,
645 victim->n_circ_id,
646 (int)(now - victim->timestamp_dirty));
648 #endif /* 0 */
650 /* if circ is !open, or if it's open but purpose is a non-finished
651 * intro or rend, then mark it for close */
652 if (victim->state == CIRCUIT_STATE_OPEN) {
653 switch (victim->purpose) {
654 default: /* most open circuits can be left alone. */
655 continue; /* yes, continue inside a switch refers to the nearest
656 * enclosing loop. C is smart. */
657 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
658 break; /* too old, need to die */
659 case CIRCUIT_PURPOSE_C_REND_READY:
660 /* it's a rend_ready circ -- has it already picked a query? */
661 /* c_rend_ready circs measure age since timestamp_dirty,
662 * because that's set when they switch purposes
664 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
665 TO_ORIGIN_CIRCUIT(victim)->hs_ident ||
666 victim->timestamp_dirty > cutoff.tv_sec)
667 continue;
668 break;
669 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
670 /* Open path bias testing circuits are given a long
671 * time to complete the test, but not forever */
672 TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
673 break;
674 case CIRCUIT_PURPOSE_C_INTRODUCING:
675 /* That purpose means that the intro point circuit has been opened
676 * successfully but the INTRODUCE1 cell hasn't been sent yet because
677 * the client is waiting for the rendezvous point circuit to open.
678 * Keep this circuit open while waiting for the rendezvous circuit.
679 * We let the circuit idle timeout take care of cleaning this
680 * circuit if it never used. */
681 continue;
682 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
683 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
684 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
685 /* rend and intro circs become dirty each time they
686 * make an introduction attempt. so timestamp_dirty
687 * will reflect the time since the last attempt.
689 if (victim->timestamp_dirty > cutoff.tv_sec)
690 continue;
691 break;
693 } else { /* circuit not open, consider recording failure as timeout */
694 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
695 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
697 if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
698 log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
699 "yet has attached streams!",
700 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
701 victim->purpose,
702 circuit_purpose_to_string(victim->purpose));
703 tor_fragile_assert();
704 continue;
707 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
708 circuit_build_times_enough_to_compute(get_circuit_build_times())) {
710 log_info(LD_CIRC,
711 "Deciding to count the timeout for circuit "U64_FORMAT"\n",
712 U64_PRINTF_ARG(
713 TO_ORIGIN_CIRCUIT(victim)->global_identifier));
715 /* Circuits are allowed to last longer for measurement.
716 * Switch their purpose and wait. */
717 if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
718 circuit_build_times_mark_circ_as_measurement_only(TO_ORIGIN_CIRCUIT(
719 victim));
720 continue;
724 * If the circuit build time is much greater than we would have cut
725 * it off at, we probably had a suspend event along this codepath,
726 * and we should discard the value.
728 if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, OP_LT)) {
729 log_notice(LD_CIRC,
730 "Extremely large value for circuit build timeout: %lds. "
731 "Assuming clock jump. Purpose %d (%s)",
732 (long)(now.tv_sec - victim->timestamp_began.tv_sec),
733 victim->purpose,
734 circuit_purpose_to_string(victim->purpose));
735 } else if (circuit_build_times_count_close(
736 get_circuit_build_times_mutable(),
737 first_hop_succeeded,
738 (time_t)victim->timestamp_created.tv_sec)) {
739 circuit_build_times_set_timeout(get_circuit_build_times_mutable());
744 /* If this is a hidden service client circuit which is far enough along in
745 * connecting to its destination, and we haven't already flagged it as
746 * 'timed out', flag it so we'll launch another intro or rend circ, but
747 * don't mark it for close yet.
749 * (Circs flagged as 'timed out' are given a much longer timeout
750 * period above, so we won't close them in the next call to
751 * circuit_expire_building.) */
752 if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)) {
753 switch (victim->purpose) {
754 case CIRCUIT_PURPOSE_C_REND_READY:
755 /* We only want to spare a rend circ if it has been specified in
756 * an INTRODUCE1 cell sent to a hidden service. A circ's
757 * pending_final_cpath field is non-NULL iff it is a rend circ
758 * and we have tried to send an INTRODUCE1 cell specifying it.
759 * Thus, if the pending_final_cpath field *is* NULL, then we
760 * want to not spare it. */
761 if (TO_ORIGIN_CIRCUIT(victim)->build_state &&
762 TO_ORIGIN_CIRCUIT(victim)->build_state->pending_final_cpath ==
763 NULL)
764 break;
765 /* fallthrough! */
766 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
767 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
768 /* If we have reached this line, we want to spare the circ for now. */
769 log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
770 "as timed-out HS circ",
771 (unsigned)victim->n_circ_id,
772 victim->state, circuit_state_to_string(victim->state),
773 victim->purpose);
774 TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
775 continue;
776 default:
777 break;
781 /* If this is a service-side rendezvous circuit which is far
782 * enough along in connecting to its destination, consider sparing
783 * it. */
784 if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
785 victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
786 log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
787 "as timed-out HS circ; relaunching rendezvous attempt.",
788 (unsigned)victim->n_circ_id,
789 victim->state, circuit_state_to_string(victim->state),
790 victim->purpose);
791 TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
792 hs_circ_retry_service_rendezvous_point(TO_ORIGIN_CIRCUIT(victim));
793 continue;
796 if (victim->n_chan)
797 log_info(LD_CIRC,
798 "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
799 "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
800 channel_get_canonical_remote_descr(victim->n_chan),
801 (unsigned)victim->n_circ_id,
802 TO_ORIGIN_CIRCUIT(victim)->has_opened,
803 victim->state, circuit_state_to_string(victim->state),
804 victim->purpose,
805 TO_ORIGIN_CIRCUIT(victim)->build_state ?
806 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
807 -1);
808 else
809 log_info(LD_CIRC,
810 "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
811 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
812 (unsigned)victim->n_circ_id,
813 TO_ORIGIN_CIRCUIT(victim)->has_opened,
814 victim->state,
815 circuit_state_to_string(victim->state), victim->purpose,
816 TO_ORIGIN_CIRCUIT(victim)->build_state ?
817 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
818 -1);
820 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
821 if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
822 circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
823 else
824 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
826 pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
827 } SMARTLIST_FOREACH_END(victim);
831 * Mark for close all circuits that start here, that were built through a
832 * guard we weren't sure if we wanted to use, and that have been waiting
833 * around for way too long.
835 void
836 circuit_expire_waiting_for_better_guard(void)
838 SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
839 origin_circuit_t *, circ) {
840 if (TO_CIRCUIT(circ)->marked_for_close)
841 continue;
842 if (circ->guard_state == NULL)
843 continue;
844 if (entry_guard_state_should_expire(circ->guard_state))
845 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
846 } SMARTLIST_FOREACH_END(circ);
849 /** For debugging #8387: track when we last called
850 * circuit_expire_old_circuits_clientside. */
851 static time_t last_expired_clientside_circuits = 0;
854 * As a diagnostic for bug 8387, log information about how many one-hop
855 * circuits we have around that have been there for at least <b>age</b>
856 * seconds. Log a few of them.
857 * Ignores Single Onion Service intro and Tor2web redezvous circuits, they are
858 * expected to be long-term one-hop circuits.
860 void
861 circuit_log_ancient_one_hop_circuits(int age)
863 #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
864 time_t now = time(NULL);
865 time_t cutoff = now - age;
866 int n_found = 0;
867 smartlist_t *log_these = smartlist_new();
868 const or_options_t *options = get_options();
870 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
871 const origin_circuit_t *ocirc;
872 if (! CIRCUIT_IS_ORIGIN(circ))
873 continue;
874 if (circ->timestamp_created.tv_sec >= cutoff)
875 continue;
876 /* Single Onion Services deliberately make long term one-hop intro
877 * and rendezvous connections. Don't log the established ones. */
878 if (rend_service_allow_non_anonymous_connection(options) &&
879 (circ->purpose == CIRCUIT_PURPOSE_S_INTRO ||
880 circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED))
881 continue;
882 /* Tor2web deliberately makes long term one-hop rend connections,
883 * particularly when Tor2webRendezvousPoints is used. We only ignore
884 * active rend point connections, if we take a long time to rendezvous,
885 * that's worth logging. */
886 if (rend_client_allow_non_anonymous_connection(options) &&
887 circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
888 continue;
889 ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
891 if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
892 ++n_found;
894 if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
895 smartlist_add(log_these, (origin_circuit_t*) ocirc);
898 SMARTLIST_FOREACH_END(circ);
900 if (n_found == 0)
901 goto done;
903 log_notice(LD_HEARTBEAT,
904 "Diagnostic for issue 8387: Found %d one-hop circuits more "
905 "than %d seconds old! Logging %d...",
906 n_found, age, smartlist_len(log_these));
908 SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
909 char created[ISO_TIME_LEN+1];
910 int stream_num;
911 const edge_connection_t *conn;
912 char *dirty = NULL;
913 const circuit_t *circ = TO_CIRCUIT(ocirc);
915 format_local_iso_time(created,
916 (time_t)circ->timestamp_created.tv_sec);
918 if (circ->timestamp_dirty) {
919 char dirty_since[ISO_TIME_LEN+1];
920 format_local_iso_time(dirty_since, circ->timestamp_dirty);
922 tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
923 dirty_since, (long)(now - circ->timestamp_dirty),
924 (long) options->MaxCircuitDirtiness);
925 } else {
926 dirty = tor_strdup("Not marked dirty");
929 log_notice(LD_HEARTBEAT, " #%d created at %s. %s, %s. %s for close. "
930 "Package window: %d. "
931 "%s for new conns. %s.",
932 ocirc_sl_idx,
933 created,
934 circuit_state_to_string(circ->state),
935 circuit_purpose_to_string(circ->purpose),
936 circ->marked_for_close ? "Marked" : "Not marked",
937 circ->package_window,
938 ocirc->unusable_for_new_conns ? "Not usable" : "usable",
939 dirty);
940 tor_free(dirty);
942 stream_num = 0;
943 for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
944 const connection_t *c = TO_CONN(conn);
945 char stream_created[ISO_TIME_LEN+1];
946 if (++stream_num >= 5)
947 break;
949 format_local_iso_time(stream_created, c->timestamp_created);
951 log_notice(LD_HEARTBEAT, " Stream#%d created at %s. "
952 "%s conn in state %s. "
953 "It is %slinked and %sreading from a linked connection %p. "
954 "Package window %d. "
955 "%s for close (%s:%d). Hold-open is %sset. "
956 "Has %ssent RELAY_END. %s on circuit.",
957 stream_num,
958 stream_created,
959 conn_type_to_string(c->type),
960 conn_state_to_string(c->type, c->state),
961 c->linked ? "" : "not ",
962 c->reading_from_linked_conn ? "": "not",
963 c->linked_conn,
964 conn->package_window,
965 c->marked_for_close ? "Marked" : "Not marked",
966 c->marked_for_close_file ? c->marked_for_close_file : "--",
967 c->marked_for_close,
968 c->hold_open_until_flushed ? "" : "not ",
969 conn->edge_has_sent_end ? "" : "not ",
970 conn->edge_blocked_on_circ ? "Blocked" : "Not blocked");
971 if (! c->linked_conn)
972 continue;
974 c = c->linked_conn;
976 log_notice(LD_HEARTBEAT, " Linked to %s connection in state %s "
977 "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
978 conn_type_to_string(c->type),
979 conn_state_to_string(c->type, c->state),
980 c->purpose,
981 c->marked_for_close ? "Marked" : "Not marked",
982 c->marked_for_close_file ? c->marked_for_close_file : "--",
983 c->marked_for_close,
984 c->hold_open_until_flushed ? "" : "not ");
986 } SMARTLIST_FOREACH_END(ocirc);
988 log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
989 "circuit_expire_old_circuits_clientside().",
990 (long)(now - last_expired_clientside_circuits));
992 done:
993 smartlist_free(log_these);
996 /** Remove any elements in <b>needed_ports</b> that are handled by an
997 * open or in-progress circuit.
999 void
1000 circuit_remove_handled_ports(smartlist_t *needed_ports)
1002 int i;
1003 uint16_t *port;
1005 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1006 port = smartlist_get(needed_ports, i);
1007 tor_assert(*port);
1008 if (circuit_stream_is_being_handled(NULL, *port,
1009 MIN_CIRCUITS_HANDLING_STREAM)) {
1010 log_debug(LD_CIRC,"Port %d is already being handled; removing.", *port);
1011 smartlist_del(needed_ports, i--);
1012 tor_free(port);
1013 } else {
1014 log_debug(LD_CIRC,"Port %d is not handled.", *port);
1019 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
1020 * will have an acceptable exit node for exit stream <b>conn</b> if it
1021 * is defined, else for "*:port".
1022 * Else return 0.
1025 circuit_stream_is_being_handled(entry_connection_t *conn,
1026 uint16_t port, int min)
1028 const node_t *exitnode;
1029 int num=0;
1030 time_t now = time(NULL);
1031 int need_uptime = smartlist_contains_int_as_string(
1032 get_options()->LongLivedPorts,
1033 conn ? conn->socks_request->port : port);
1035 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1036 if (CIRCUIT_IS_ORIGIN(circ) &&
1037 !circ->marked_for_close &&
1038 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
1039 (!circ->timestamp_dirty ||
1040 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
1041 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1042 cpath_build_state_t *build_state = origin_circ->build_state;
1043 if (build_state->is_internal || build_state->onehop_tunnel)
1044 continue;
1045 if (origin_circ->unusable_for_new_conns)
1046 continue;
1047 if (origin_circ->isolation_values_set &&
1048 (conn == NULL ||
1049 !connection_edge_compatible_with_circuit(conn, origin_circ)))
1050 continue;
1052 exitnode = build_state_get_exit_node(build_state);
1053 if (exitnode && (!need_uptime || build_state->need_uptime)) {
1054 int ok;
1055 if (conn) {
1056 ok = connection_ap_can_use_exit(conn, exitnode);
1057 } else {
1058 addr_policy_result_t r;
1059 r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
1060 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
1062 if (ok) {
1063 if (++num >= min)
1064 return 1;
1069 SMARTLIST_FOREACH_END(circ);
1070 return 0;
1073 /** Don't keep more than this many unused open circuits around. */
1074 #define MAX_UNUSED_OPEN_CIRCUITS 14
1076 /* Return true if a circuit is available for use, meaning that it is open,
1077 * clean, usable for new multi-hop connections, and a general purpose origin
1078 * circuit.
1079 * Accept any kind of circuit, return false if the above conditions are not
1080 * met. */
1081 STATIC int
1082 circuit_is_available_for_use(const circuit_t *circ)
1084 const origin_circuit_t *origin_circ;
1085 cpath_build_state_t *build_state;
1087 if (!CIRCUIT_IS_ORIGIN(circ))
1088 return 0; /* We first filter out only origin circuits before doing the
1089 following checks. */
1090 if (circ->marked_for_close)
1091 return 0; /* Don't mess with marked circs */
1092 if (circ->timestamp_dirty)
1093 return 0; /* Only count clean circs */
1094 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1095 circ->purpose != CIRCUIT_PURPOSE_HS_VANGUARDS)
1096 return 0; /* We only pay attention to general purpose circuits.
1097 General purpose circuits are always origin circuits. */
1099 origin_circ = CONST_TO_ORIGIN_CIRCUIT(circ);
1100 if (origin_circ->unusable_for_new_conns)
1101 return 0;
1103 build_state = origin_circ->build_state;
1104 if (build_state->onehop_tunnel)
1105 return 0;
1107 return 1;
1110 /* Return true if we need any more exit circuits.
1111 * needs_uptime and needs_capacity are set only if we need more exit circuits.
1112 * Check if we know of a port that's been requested recently and no circuit
1113 * is currently available that can handle it. */
1114 STATIC int
1115 needs_exit_circuits(time_t now, int *needs_uptime, int *needs_capacity)
1117 return (!circuit_all_predicted_ports_handled(now, needs_uptime,
1118 needs_capacity) &&
1119 router_have_consensus_path() == CONSENSUS_PATH_EXIT);
1122 /* Hidden services need at least this many internal circuits */
1123 #define SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS 3
1125 /* Return true if we need any more hidden service server circuits.
1126 * HS servers only need an internal circuit. */
1127 STATIC int
1128 needs_hs_server_circuits(time_t now, int num_uptime_internal)
1130 if (!rend_num_services() && !hs_service_get_num_services()) {
1131 /* No services, we don't need anything. */
1132 goto no_need;
1135 if (num_uptime_internal >= SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS) {
1136 /* We have sufficient amount of internal circuit. */
1137 goto no_need;
1140 if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN) {
1141 /* Consensus hasn't been checked or might be invalid so requesting
1142 * internal circuits is not wise. */
1143 goto no_need;
1146 /* At this point, we need a certain amount of circuits and we will most
1147 * likely use them for rendezvous so we note down the use of internal
1148 * circuit for our prediction for circuit needing uptime and capacity. */
1149 rep_hist_note_used_internal(now, 1, 1);
1151 return 1;
1152 no_need:
1153 return 0;
1156 /* We need at least this many internal circuits for hidden service clients */
1157 #define SUFFICIENT_INTERNAL_HS_CLIENTS 3
1159 /* We need at least this much uptime for internal circuits for hidden service
1160 * clients */
1161 #define SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS 2
1163 /* Return true if we need any more hidden service client circuits.
1164 * HS clients only need an internal circuit. */
1165 STATIC int
1166 needs_hs_client_circuits(time_t now, int *needs_uptime, int *needs_capacity,
1167 int num_internal, int num_uptime_internal)
1169 int used_internal_recently = rep_hist_get_predicted_internal(now,
1170 needs_uptime,
1171 needs_capacity);
1172 int requires_uptime = num_uptime_internal <
1173 SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS &&
1174 needs_uptime;
1176 return (used_internal_recently &&
1177 (requires_uptime || num_internal < SUFFICIENT_INTERNAL_HS_CLIENTS) &&
1178 router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN);
1181 /* This is how many circuits can be opened concurrently during the cbt learning
1182 * phase. This number cannot exceed the tor-wide MAX_UNUSED_OPEN_CIRCUITS. */
1183 #define DFLT_CBT_UNUSED_OPEN_CIRCS (10)
1184 #define MIN_CBT_UNUSED_OPEN_CIRCS 0
1185 #define MAX_CBT_UNUSED_OPEN_CIRCS MAX_UNUSED_OPEN_CIRCUITS
1187 /* Return true if we need more circuits for a good build timeout.
1188 * XXXX make the assumption that build timeout streams should be
1189 * created whenever we can build internal circuits. */
1190 STATIC int
1191 needs_circuits_for_build(int num)
1193 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
1194 if (num < networkstatus_get_param(NULL, "cbtmaxopencircs",
1195 DFLT_CBT_UNUSED_OPEN_CIRCS,
1196 MIN_CBT_UNUSED_OPEN_CIRCS,
1197 MAX_CBT_UNUSED_OPEN_CIRCS) &&
1198 !circuit_build_times_disabled(get_options()) &&
1199 circuit_build_times_needs_circuits_now(get_circuit_build_times())) {
1200 return 1;
1203 return 0;
1207 * Launch the appropriate type of predicted circuit for hidden
1208 * services, depending on our options.
1210 static void
1211 circuit_launch_predicted_hs_circ(int flags)
1213 /* K.I.S.S. implementation of bug #23101: If we are using
1214 * vanguards or pinned middles, pre-build a specific purpose
1215 * for HS circs. */
1216 if (circuit_should_use_vanguards(CIRCUIT_PURPOSE_HS_VANGUARDS)) {
1217 circuit_launch(CIRCUIT_PURPOSE_HS_VANGUARDS, flags);
1218 } else {
1219 /* If no vanguards, then no HS-specific prebuilt circuits are needed.
1220 * Normal GENERAL circs are fine */
1221 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1225 /** Determine how many circuits we have open that are clean,
1226 * Make sure it's enough for all the upcoming behaviors we predict we'll have.
1227 * But put an upper bound on the total number of circuits.
1229 static void
1230 circuit_predict_and_launch_new(void)
1232 int num=0, num_internal=0, num_uptime_internal=0;
1233 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
1234 int port_needs_uptime=0, port_needs_capacity=1;
1235 time_t now = time(NULL);
1236 int flags = 0;
1238 /* Count how many of each type of circuit we currently have. */
1239 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1240 if (!circuit_is_available_for_use(circ))
1241 continue;
1243 num++;
1245 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
1246 if (build_state->is_internal)
1247 num_internal++;
1248 if (build_state->need_uptime && build_state->is_internal)
1249 num_uptime_internal++;
1251 SMARTLIST_FOREACH_END(circ);
1253 /* If that's enough, then stop now. */
1254 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
1255 return;
1257 if (needs_exit_circuits(now, &port_needs_uptime, &port_needs_capacity)) {
1258 if (port_needs_uptime)
1259 flags |= CIRCLAUNCH_NEED_UPTIME;
1260 if (port_needs_capacity)
1261 flags |= CIRCLAUNCH_NEED_CAPACITY;
1263 log_info(LD_CIRC,
1264 "Have %d clean circs (%d internal), need another exit circ.",
1265 num, num_internal);
1266 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1267 return;
1270 if (needs_hs_server_circuits(now, num_uptime_internal)) {
1271 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
1272 CIRCLAUNCH_IS_INTERNAL);
1274 log_info(LD_CIRC,
1275 "Have %d clean circs (%d internal), need another internal "
1276 "circ for my hidden service.",
1277 num, num_internal);
1278 circuit_launch_predicted_hs_circ(flags);
1279 return;
1282 if (needs_hs_client_circuits(now, &hidserv_needs_uptime,
1283 &hidserv_needs_capacity,
1284 num_internal, num_uptime_internal))
1286 if (hidserv_needs_uptime)
1287 flags |= CIRCLAUNCH_NEED_UPTIME;
1288 if (hidserv_needs_capacity)
1289 flags |= CIRCLAUNCH_NEED_CAPACITY;
1290 flags |= CIRCLAUNCH_IS_INTERNAL;
1292 log_info(LD_CIRC,
1293 "Have %d clean circs (%d uptime-internal, %d internal), need"
1294 " another hidden service circ.",
1295 num, num_uptime_internal, num_internal);
1297 circuit_launch_predicted_hs_circ(flags);
1298 return;
1301 if (needs_circuits_for_build(num)) {
1302 flags = CIRCLAUNCH_NEED_CAPACITY;
1303 /* if there are no exits in the consensus, make timeout
1304 * circuits internal */
1305 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
1306 flags |= CIRCLAUNCH_IS_INTERNAL;
1308 log_info(LD_CIRC,
1309 "Have %d clean circs need another buildtime test circ.", num);
1310 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1311 return;
1315 /** Build a new test circuit every 5 minutes */
1316 #define TESTING_CIRCUIT_INTERVAL 300
1318 /** This function is called once a second, if router_have_minimum_dir_info()
1319 * is true. Its job is to make sure all services we offer have enough circuits
1320 * available. Some services just want enough circuits for current tasks,
1321 * whereas others want a minimum set of idle circuits hanging around.
1323 void
1324 circuit_build_needed_circs(time_t now)
1326 const or_options_t *options = get_options();
1328 /* launch a new circ for any pending streams that need one
1329 * XXXX make the assumption that (some) AP streams (i.e. HS clients)
1330 * don't require an exit circuit, review in #13814.
1331 * This allows HSs to function in a consensus without exits. */
1332 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
1333 connection_ap_rescan_and_attach_pending();
1335 circuit_expire_old_circs_as_needed(now);
1337 if (!options->DisablePredictedCircuits)
1338 circuit_predict_and_launch_new();
1342 * Called once a second either directly or from
1343 * circuit_build_needed_circs(). As appropriate (once per NewCircuitPeriod)
1344 * resets failure counts and expires old circuits.
1346 void
1347 circuit_expire_old_circs_as_needed(time_t now)
1349 static time_t time_to_expire_and_reset = 0;
1351 if (time_to_expire_and_reset < now) {
1352 circuit_reset_failure_count(1);
1353 time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
1354 if (proxy_mode(get_options()))
1355 addressmap_clean(now);
1356 circuit_expire_old_circuits_clientside();
1358 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
1360 /* If we ever re-enable, this has to move into
1361 * circuit_build_needed_circs */
1363 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
1364 if (get_options()->RunTesting &&
1365 circ &&
1366 circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
1367 log_fn(LOG_INFO,"Creating a new testing circuit.");
1368 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
1370 #endif /* 0 */
1374 /** If the stream <b>conn</b> is a member of any of the linked
1375 * lists of <b>circ</b>, then remove it from the list.
1377 void
1378 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
1380 edge_connection_t *prevconn;
1382 tor_assert(circ);
1383 tor_assert(conn);
1385 if (conn->base_.type == CONN_TYPE_AP) {
1386 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1387 entry_conn->may_use_optimistic_data = 0;
1389 conn->cpath_layer = NULL; /* don't keep a stale pointer */
1390 conn->on_circuit = NULL;
1392 if (CIRCUIT_IS_ORIGIN(circ)) {
1393 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1394 int removed = 0;
1395 if (conn == origin_circ->p_streams) {
1396 origin_circ->p_streams = conn->next_stream;
1397 removed = 1;
1398 } else {
1399 for (prevconn = origin_circ->p_streams;
1400 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1401 prevconn = prevconn->next_stream)
1403 if (prevconn && prevconn->next_stream) {
1404 prevconn->next_stream = conn->next_stream;
1405 removed = 1;
1408 if (removed) {
1409 log_debug(LD_APP, "Removing stream %d from circ %u",
1410 conn->stream_id, (unsigned)circ->n_circ_id);
1412 /* If the stream was removed, and it was a rend stream, decrement the
1413 * number of streams on the circuit associated with the rend service.
1415 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1416 hs_dec_rdv_stream_counter(origin_circ);
1418 return;
1420 } else {
1421 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1422 if (conn == or_circ->n_streams) {
1423 or_circ->n_streams = conn->next_stream;
1424 return;
1426 if (conn == or_circ->resolving_streams) {
1427 or_circ->resolving_streams = conn->next_stream;
1428 return;
1431 for (prevconn = or_circ->n_streams;
1432 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1433 prevconn = prevconn->next_stream)
1435 if (prevconn && prevconn->next_stream) {
1436 prevconn->next_stream = conn->next_stream;
1437 return;
1440 for (prevconn = or_circ->resolving_streams;
1441 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1442 prevconn = prevconn->next_stream)
1444 if (prevconn && prevconn->next_stream) {
1445 prevconn->next_stream = conn->next_stream;
1446 return;
1450 log_warn(LD_BUG,"Edge connection not in circuit's list.");
1451 /* Don't give an error here; it's harmless. */
1452 tor_fragile_assert();
1455 /** Find each circuit that has been unused for too long, or dirty
1456 * for too long and has no streams on it: mark it for close.
1458 static void
1459 circuit_expire_old_circuits_clientside(void)
1461 struct timeval cutoff, now;
1463 tor_gettimeofday(&now);
1464 last_expired_clientside_circuits = now.tv_sec;
1466 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1467 if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
1468 continue;
1470 cutoff = now;
1471 cutoff.tv_sec -= TO_ORIGIN_CIRCUIT(circ)->circuit_idle_timeout;
1473 /* If the circuit has been dirty for too long, and there are no streams
1474 * on it, mark it for close.
1476 if (circ->timestamp_dirty &&
1477 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
1478 now.tv_sec &&
1479 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
1480 log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
1481 "purpose %d)",
1482 (unsigned)circ->n_circ_id,
1483 (long)(now.tv_sec - circ->timestamp_dirty),
1484 circ->purpose);
1485 /* Don't do this magic for testing circuits. Their death is governed
1486 * by circuit_expire_building */
1487 if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
1488 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1489 } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
1490 if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
1491 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
1492 circ->purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1493 circ->purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1494 circ->purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1495 circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
1496 circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1497 circ->purpose == CIRCUIT_PURPOSE_TESTING ||
1498 (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
1499 circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
1500 circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
1501 log_info(LD_CIRC,
1502 "Closing circuit "U64_FORMAT
1503 " that has been unused for %ld msec.",
1504 U64_PRINTF_ARG(TO_ORIGIN_CIRCUIT(circ)->global_identifier),
1505 tv_mdiff(&circ->timestamp_began, &now));
1506 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1507 } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
1508 /* Server-side rend joined circuits can end up really old, because
1509 * they are reused by clients for longer than normal. The client
1510 * controls their lifespan. (They never become dirty, because
1511 * connection_exit_begin_conn() never marks anything as dirty.)
1512 * Similarly, server-side intro circuits last a long time. */
1513 if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
1514 circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
1515 log_notice(LD_CIRC,
1516 "Ancient non-dirty circuit %d is still around after "
1517 "%ld milliseconds. Purpose: %d (%s)",
1518 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1519 tv_mdiff(&circ->timestamp_began, &now),
1520 circ->purpose,
1521 circuit_purpose_to_string(circ->purpose));
1522 TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
1527 } SMARTLIST_FOREACH_END(circ);
1530 /** How long do we wait before killing circuits with the properties
1531 * described below?
1533 * Probably we could choose a number here as low as 5 to 10 seconds,
1534 * since these circs are used for begindir, and a) generally you either
1535 * ask another begindir question right after or you don't for a long time,
1536 * b) clients at least through 0.2.1.x choose from the whole set of
1537 * directory mirrors at each choice, and c) re-establishing a one-hop
1538 * circuit via create-fast is a light operation assuming the TLS conn is
1539 * still there.
1541 * I expect "b" to go away one day when we move to using directory
1542 * guards, but I think "a" and "c" are good enough reasons that a low
1543 * number is safe even then.
1545 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
1547 /** Find each non-origin circuit that has been unused for too long,
1548 * has no streams on it, came from a client, and ends here: mark it
1549 * for close.
1551 void
1552 circuit_expire_old_circuits_serverside(time_t now)
1554 or_circuit_t *or_circ;
1555 time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
1557 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1558 if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
1559 continue;
1560 or_circ = TO_OR_CIRCUIT(circ);
1561 /* If the circuit has been idle for too long, and there are no streams
1562 * on it, and it ends here, and it used a create_fast, mark it for close.
1564 if (or_circ->p_chan && channel_is_client(or_circ->p_chan) &&
1565 !circ->n_chan &&
1566 !or_circ->n_streams && !or_circ->resolving_streams &&
1567 channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
1568 log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
1569 (unsigned)or_circ->p_circ_id,
1570 (int)(now - channel_when_last_xmit(or_circ->p_chan)));
1571 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1574 SMARTLIST_FOREACH_END(circ);
1577 /** Number of testing circuits we want open before testing our bandwidth. */
1578 #define NUM_PARALLEL_TESTING_CIRCS 4
1580 /** True iff we've ever had enough testing circuits open to test our
1581 * bandwidth. */
1582 static int have_performed_bandwidth_test = 0;
1584 /** Reset have_performed_bandwidth_test, so we'll start building
1585 * testing circuits again so we can exercise our bandwidth. */
1586 void
1587 reset_bandwidth_test(void)
1589 have_performed_bandwidth_test = 0;
1592 /** Return 1 if we've already exercised our bandwidth, or if we
1593 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
1594 * established or on the way. Else return 0.
1597 circuit_enough_testing_circs(void)
1599 int num = 0;
1601 if (have_performed_bandwidth_test)
1602 return 1;
1604 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1605 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
1606 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
1607 circ->state == CIRCUIT_STATE_OPEN)
1608 num++;
1610 SMARTLIST_FOREACH_END(circ);
1611 return num >= NUM_PARALLEL_TESTING_CIRCS;
1614 /** A testing circuit has completed. Take whatever stats we want.
1615 * Noticing reachability is taken care of in onionskin_answer(),
1616 * so there's no need to record anything here. But if we still want
1617 * to do the bandwidth test, and we now have enough testing circuits
1618 * open, do it.
1620 static void
1621 circuit_testing_opened(origin_circuit_t *circ)
1623 if (have_performed_bandwidth_test ||
1624 !check_whether_orport_reachable(get_options())) {
1625 /* either we've already done everything we want with testing circuits,
1626 * or this testing circuit became open due to a fluke, e.g. we picked
1627 * a last hop where we already had the connection open due to an
1628 * outgoing local circuit. */
1629 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
1630 } else if (circuit_enough_testing_circs()) {
1631 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
1632 have_performed_bandwidth_test = 1;
1633 } else
1634 router_do_reachability_checks(1, 0);
1637 /** A testing circuit has failed to build. Take whatever stats we want. */
1638 static void
1639 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
1641 const or_options_t *options = get_options();
1642 if (server_mode(options) && check_whether_orport_reachable(options))
1643 return;
1645 log_info(LD_GENERAL,
1646 "Our testing circuit (to see if your ORPort is reachable) "
1647 "has failed. I'll try again later.");
1649 /* These aren't used yet. */
1650 (void)circ;
1651 (void)at_last_hop;
1654 /** The circuit <b>circ</b> has just become open. Take the next
1655 * step: for rendezvous circuits, we pass circ to the appropriate
1656 * function in rendclient or rendservice. For general circuits, we
1657 * call connection_ap_attach_pending, which looks for pending streams
1658 * that could use circ.
1660 void
1661 circuit_has_opened(origin_circuit_t *circ)
1663 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
1665 /* Remember that this circuit has finished building. Now if we start
1666 * it building again later (e.g. by extending it), we will know not
1667 * to consider its build time. */
1668 circ->has_opened = 1;
1670 switch (TO_CIRCUIT(circ)->purpose) {
1671 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1672 hs_client_circuit_has_opened(circ);
1673 /* Start building an intro circ if we don't have one yet. */
1674 connection_ap_attach_pending(1);
1675 /* This isn't a call to circuit_try_attaching_streams because a
1676 * circuit in _C_ESTABLISH_REND state isn't connected to its
1677 * hidden service yet, thus we can't attach streams to it yet,
1678 * thus circuit_try_attaching_streams would always clear the
1679 * circuit's isolation state. circuit_try_attaching_streams is
1680 * called later, when the rend circ enters _C_REND_JOINED
1681 * state. */
1682 break;
1683 case CIRCUIT_PURPOSE_C_INTRODUCING:
1684 hs_client_circuit_has_opened(circ);
1685 break;
1686 case CIRCUIT_PURPOSE_C_GENERAL:
1687 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1688 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1689 /* Tell any AP connections that have been waiting for a new
1690 * circuit that one is ready. */
1691 circuit_try_attaching_streams(circ);
1692 break;
1693 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1694 /* at the service, waiting for introductions */
1695 hs_service_circuit_has_opened(circ);
1696 break;
1697 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1698 /* at the service, connecting to rend point */
1699 hs_service_circuit_has_opened(circ);
1700 break;
1701 case CIRCUIT_PURPOSE_TESTING:
1702 circuit_testing_opened(circ);
1703 break;
1704 /* default:
1705 * This won't happen in normal operation, but might happen if the
1706 * controller did it. Just let it slide. */
1710 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
1711 * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
1712 static int
1713 circuit_try_clearing_isolation_state(origin_circuit_t *circ)
1715 if (/* The circuit may have become non-open if it was cannibalized.*/
1716 circ->base_.state == CIRCUIT_STATE_OPEN &&
1717 /* If !isolation_values_set, there is nothing to clear. */
1718 circ->isolation_values_set &&
1719 /* It's not legal to clear a circuit's isolation info if it's ever had
1720 * streams attached */
1721 !circ->isolation_any_streams_attached) {
1722 /* If we have any isolation information set on this circuit, and
1723 * we didn't manage to attach any streams to it, then we can
1724 * and should clear it and try again. */
1725 circuit_clear_isolation(circ);
1726 return 1;
1727 } else {
1728 return 0;
1732 /** Called when a circuit becomes ready for streams to be attached to
1733 * it. */
1734 void
1735 circuit_try_attaching_streams(origin_circuit_t *circ)
1737 /* Attach streams to this circuit if we can. */
1738 connection_ap_attach_pending(1);
1740 /* The call to circuit_try_clearing_isolation_state here will do
1741 * nothing and return 0 if we didn't attach any streams to circ
1742 * above. */
1743 if (circuit_try_clearing_isolation_state(circ)) {
1744 /* Maybe *now* we can attach some streams to this circuit. */
1745 connection_ap_attach_pending(1);
1749 /** Called whenever a circuit could not be successfully built.
1751 void
1752 circuit_build_failed(origin_circuit_t *circ)
1754 channel_t *n_chan = NULL;
1755 /* we should examine circ and see if it failed because of
1756 * the last hop or an earlier hop. then use this info below.
1758 int failed_at_last_hop = 0;
1759 /* If the last hop isn't open, and the second-to-last is, we failed
1760 * at the last hop. */
1761 if (circ->cpath &&
1762 circ->cpath->prev->state != CPATH_STATE_OPEN &&
1763 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
1764 failed_at_last_hop = 1;
1767 /* Check if we failed at first hop */
1768 if (circ->cpath &&
1769 circ->cpath->state != CPATH_STATE_OPEN &&
1770 ! circ->base_.received_destroy) {
1771 /* We failed at the first hop for some reason other than a DESTROY cell.
1772 * If there's an OR connection to blame, blame it. Also, avoid this relay
1773 * for a while, and fail any one-hop directory fetches destined for it. */
1774 const char *n_chan_ident = circ->cpath->extend_info->identity_digest;
1775 tor_assert(n_chan_ident);
1776 int already_marked = 0;
1777 if (circ->base_.n_chan) {
1778 n_chan = circ->base_.n_chan;
1780 if (n_chan->is_bad_for_new_circs) {
1781 /* We only want to blame this router when a fresh healthy
1782 * connection fails. So don't mark this router as newly failed,
1783 * since maybe this was just an old circuit attempt that's
1784 * finally timing out now. Also, there's no need to blow away
1785 * circuits/streams/etc, since the failure of an unhealthy conn
1786 * doesn't tell us much about whether a healthy conn would
1787 * succeed. */
1788 already_marked = 1;
1790 log_info(LD_OR,
1791 "Our circuit %u (id: %" PRIu32 ") failed to get a response "
1792 "from the first hop (%s). I'm going to try to rotate to a "
1793 "better connection.",
1794 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1795 channel_get_canonical_remote_descr(n_chan));
1796 n_chan->is_bad_for_new_circs = 1;
1797 } else {
1798 log_info(LD_OR,
1799 "Our circuit %u (id: %" PRIu32 ") died before the first hop "
1800 "with no connection",
1801 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier);
1803 if (!already_marked) {
1805 * If we have guard state (new guard API) and our path selection
1806 * code actually chose a full path, then blame the failure of this
1807 * circuit on the guard.
1809 * Note that we deliberately use circuit_get_cpath_len() (and not
1810 * circuit_get_cpath_opened_len()) because we only want to ensure
1811 * that a full path is *chosen*. This is different than a full path
1812 * being *built*. We only want to blame *build* failures on this
1813 * guard. Path selection failures can happen spuriously for a number
1814 * of reasons (such as aggressive/invalid user-specified path
1815 * restrictions in the torrc, as well as non-user reasons like
1816 * exitpolicy issues), and so should not be counted here.
1818 if (circ->guard_state &&
1819 circuit_get_cpath_len(circ) >= circ->build_state->desired_path_len)
1820 entry_guard_failed(&circ->guard_state);
1821 /* if there are any one-hop streams waiting on this circuit, fail
1822 * them now so they can retry elsewhere. */
1823 connection_ap_fail_onehop(n_chan_ident, circ->build_state);
1827 switch (circ->base_.purpose) {
1828 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1829 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1830 case CIRCUIT_PURPOSE_C_GENERAL:
1831 /* If we never built the circuit, note it as a failure. */
1832 circuit_increment_failure_count();
1833 if (failed_at_last_hop) {
1834 /* Make sure any streams that demand our last hop as their exit
1835 * know that it's unlikely to happen. */
1836 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
1838 break;
1839 case CIRCUIT_PURPOSE_TESTING:
1840 circuit_testing_failed(circ, failed_at_last_hop);
1841 break;
1842 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1843 /* at the service, waiting for introductions */
1844 if (circ->base_.state != CIRCUIT_STATE_OPEN) {
1845 circuit_increment_failure_count();
1847 /* no need to care here, because the service will rebuild intro
1848 * points periodically. */
1849 break;
1850 case CIRCUIT_PURPOSE_C_INTRODUCING:
1851 /* at the client, connecting to intro point */
1852 /* Don't increment failure count, since the service may have picked
1853 * the introduction point maliciously */
1854 /* The client will pick a new intro point when this one dies, if
1855 * the stream in question still cares. No need to act here. */
1856 break;
1857 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1858 /* at the client, waiting for the service */
1859 circuit_increment_failure_count();
1860 /* the client will pick a new rend point when this one dies, if
1861 * the stream in question still cares. No need to act here. */
1862 break;
1863 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1864 /* at the service, connecting to rend point */
1865 /* Don't increment failure count, since the client may have picked
1866 * the rendezvous point maliciously */
1867 log_info(LD_REND,
1868 "Couldn't connect to the client's chosen rend point %s "
1869 "(%s hop failed).",
1870 escaped(build_state_get_exit_nickname(circ->build_state)),
1871 failed_at_last_hop?"last":"non-last");
1872 hs_circ_retry_service_rendezvous_point(circ);
1873 break;
1874 /* default:
1875 * This won't happen in normal operation, but might happen if the
1876 * controller did it. Just let it slide. */
1880 /** Number of consecutive failures so far; should only be touched by
1881 * circuit_launch_new and circuit_*_failure_count.
1883 static int n_circuit_failures = 0;
1884 /** Before the last time we called circuit_reset_failure_count(), were
1885 * there a lot of failures? */
1886 static int did_circs_fail_last_period = 0;
1888 /** Don't retry launching a new circuit if we try this many times with no
1889 * success. */
1890 #define MAX_CIRCUIT_FAILURES 5
1892 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1893 * details on arguments. */
1894 origin_circuit_t *
1895 circuit_launch(uint8_t purpose, int flags)
1897 return circuit_launch_by_extend_info(purpose, NULL, flags);
1900 /* Do we have enough descriptors to build paths?
1901 * If need_exit is true, return 1 if we can build exit paths.
1902 * (We need at least one Exit in the consensus to build exit paths.)
1903 * If need_exit is false, return 1 if we can build internal paths.
1905 static int
1906 have_enough_path_info(int need_exit)
1908 if (need_exit)
1909 return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
1910 else
1911 return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
1915 * Tell us if a circuit is a hidden service circuit.
1918 circuit_purpose_is_hidden_service(uint8_t purpose)
1920 if (purpose == CIRCUIT_PURPOSE_HS_VANGUARDS) {
1921 return 1;
1924 /* Client-side purpose */
1925 if (purpose >= CIRCUIT_PURPOSE_C_HS_MIN_ &&
1926 purpose <= CIRCUIT_PURPOSE_C_HS_MAX_) {
1927 return 1;
1930 /* Service-side purpose */
1931 if (purpose >= CIRCUIT_PURPOSE_S_HS_MIN_ &&
1932 purpose <= CIRCUIT_PURPOSE_S_HS_MAX_) {
1933 return 1;
1936 return 0;
1940 * Return true if this circuit purpose should use vanguards
1941 * or pinned Layer2 or Layer3 guards.
1943 * This function takes both the circuit purpose and the
1944 * torrc options for pinned middles/vanguards into account
1945 * (ie: the circuit must be a hidden service circuit and
1946 * vanguards/pinned middles must be enabled for it to return
1947 * true).
1950 circuit_should_use_vanguards(uint8_t purpose)
1952 const or_options_t *options = get_options();
1954 /* Only hidden service circuits use vanguards */
1955 if (!circuit_purpose_is_hidden_service(purpose))
1956 return 0;
1958 /* Pinned middles are effectively vanguards */
1959 if (options->HSLayer2Nodes || options->HSLayer3Nodes)
1960 return 1;
1962 return 0;
1966 * Return true for the set of conditions for which it is OK to use
1967 * a cannibalized circuit.
1969 * Don't cannibalize for onehops, or tor2web, or certain purposes.
1971 static int
1972 circuit_should_cannibalize_to_build(uint8_t purpose_to_build,
1973 int has_extend_info,
1974 int onehop_tunnel,
1975 int need_specific_rp)
1978 /* Do not try to cannibalize if this is a one hop circuit, or
1979 * is a tor2web/special rp. */
1980 if (onehop_tunnel || need_specific_rp) {
1981 return 0;
1984 /* Don't try to cannibalize for general purpose circuits that do not
1985 * specify a custom exit. */
1986 if (purpose_to_build == CIRCUIT_PURPOSE_C_GENERAL && !has_extend_info) {
1987 return 0;
1990 /* Don't cannibalize for testing circuits. We want to see if they
1991 * complete normally. Also don't cannibalize for vanguard-purpose
1992 * circuits, since those are specially pre-built for later
1993 * cannibalization by the actual specific circuit types that need
1994 * vanguards.
1996 if (purpose_to_build == CIRCUIT_PURPOSE_TESTING ||
1997 purpose_to_build == CIRCUIT_PURPOSE_HS_VANGUARDS) {
1998 return 0;
2001 /* For vanguards, the server-side intro circ is not cannibalized
2002 * because we pre-build 4 hop HS circuits, and it only needs a 3 hop
2003 * circuit. It is also long-lived, so it is more important that
2004 * it have lower latency than get built fast.
2006 if (circuit_should_use_vanguards(purpose_to_build) &&
2007 purpose_to_build == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
2008 return 0;
2011 return 1;
2014 /** Launch a new circuit with purpose <b>purpose</b> and exit node
2015 * <b>extend_info</b> (or NULL to select a random exit node). If flags
2016 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
2017 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
2018 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
2019 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
2020 * Return the newly allocated circuit on success, or NULL on failure. */
2021 origin_circuit_t *
2022 circuit_launch_by_extend_info(uint8_t purpose,
2023 extend_info_t *extend_info,
2024 int flags)
2026 origin_circuit_t *circ;
2027 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
2028 int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
2029 int need_specific_rp = 0;
2031 /* Keep some stats about our attempts to launch HS rendezvous circuits */
2032 if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
2033 hs_stats_note_service_rendezvous_launch();
2036 if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
2037 log_debug(LD_CIRC,"Haven't %s yet; canceling "
2038 "circuit launch.",
2039 !router_have_minimum_dir_info() ?
2040 "fetched enough directory info" :
2041 "received a consensus with exits");
2042 return NULL;
2045 /* If Tor2webRendezvousPoints is enabled and we are dealing with an
2046 RP circuit, we want a specific RP node so we shouldn't canibalize
2047 an already existing circuit. */
2048 if (get_options()->Tor2webRendezvousPoints &&
2049 purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
2050 need_specific_rp = 1;
2053 /* If we can/should cannibalize another circuit to build this one,
2054 * then do so. */
2055 if (circuit_should_cannibalize_to_build(purpose,
2056 extend_info != NULL,
2057 onehop_tunnel,
2058 need_specific_rp)) {
2059 /* see if there are appropriate circs available to cannibalize. */
2060 /* XXX if we're planning to add a hop, perhaps we want to look for
2061 * internal circs rather than exit circs? -RD */
2062 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
2063 if (circ) {
2064 uint8_t old_purpose = circ->base_.purpose;
2065 struct timeval old_timestamp_began = circ->base_.timestamp_began;
2067 log_info(LD_CIRC, "Cannibalizing circ %u (id: %" PRIu32 ") for "
2068 "purpose %d (%s)",
2069 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier, purpose,
2070 circuit_purpose_to_string(purpose));
2072 if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2073 purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
2074 circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
2075 /* Path bias: Cannibalized rends pre-emptively count as a
2076 * successfully built but unused closed circuit. We don't
2077 * wait until the extend (or the close) because the rend
2078 * point could be malicious.
2080 * Same deal goes for client side introductions. Clients
2081 * can be manipulated to connect repeatedly to them
2082 * (especially web clients).
2084 * If we decide to probe the initial portion of these circs,
2085 * (up to the adversary's final hop), we need to remove this,
2086 * or somehow mark the circuit with a special path state.
2089 /* This must be called before the purpose change */
2090 pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
2093 circuit_change_purpose(TO_CIRCUIT(circ), purpose);
2094 /* Reset the start date of this circ, else expire_building
2095 * will see it and think it's been trying to build since it
2096 * began.
2098 * Technically, the code should reset this when the
2099 * create cell is finally sent, but we're close enough
2100 * here. */
2101 tor_gettimeofday(&circ->base_.timestamp_began);
2103 control_event_circuit_cannibalized(circ, old_purpose,
2104 &old_timestamp_began);
2106 switch (purpose) {
2107 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
2108 /* it's ready right now */
2109 break;
2110 case CIRCUIT_PURPOSE_C_INTRODUCING:
2111 case CIRCUIT_PURPOSE_S_CONNECT_REND:
2112 case CIRCUIT_PURPOSE_C_GENERAL:
2113 case CIRCUIT_PURPOSE_S_HSDIR_POST:
2114 case CIRCUIT_PURPOSE_C_HSDIR_GET:
2115 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
2116 /* need to add a new hop */
2117 tor_assert(extend_info);
2118 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
2119 return NULL;
2120 break;
2121 default:
2122 log_warn(LD_BUG,
2123 "unexpected purpose %d when cannibalizing a circ.",
2124 purpose);
2125 tor_fragile_assert();
2126 return NULL;
2128 return circ;
2132 if (did_circs_fail_last_period &&
2133 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
2134 /* too many failed circs in a row. don't try. */
2135 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
2136 return NULL;
2139 /* try a circ. if it fails, circuit_mark_for_close will increment
2140 * n_circuit_failures */
2141 return circuit_establish_circuit(purpose, extend_info, flags);
2144 /** Record another failure at opening a general circuit. When we have
2145 * too many, we'll stop trying for the remainder of this minute.
2147 static void
2148 circuit_increment_failure_count(void)
2150 ++n_circuit_failures;
2151 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
2154 /** Reset the failure count for opening general circuits. This means
2155 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
2156 * stopping again.
2158 void
2159 circuit_reset_failure_count(int timeout)
2161 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
2162 did_circs_fail_last_period = 1;
2163 else
2164 did_circs_fail_last_period = 0;
2165 n_circuit_failures = 0;
2168 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
2169 * there isn't one, and there isn't one on the way, launch one and return
2170 * 0. If it will never work, return -1.
2172 * Write the found or in-progress or launched circ into *circp.
2174 static int
2175 circuit_get_open_circ_or_launch(entry_connection_t *conn,
2176 uint8_t desired_circuit_purpose,
2177 origin_circuit_t **circp)
2179 origin_circuit_t *circ;
2180 int check_exit_policy;
2181 int need_uptime, need_internal;
2182 int want_onehop;
2183 const or_options_t *options = get_options();
2185 tor_assert(conn);
2186 tor_assert(circp);
2187 if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2188 connection_t *c = ENTRY_TO_CONN(conn);
2189 log_err(LD_BUG, "Connection state mismatch: wanted "
2190 "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
2191 c->state, conn_state_to_string(c->type, c->state));
2193 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
2195 /* Will the exit policy of the exit node apply to this stream? */
2196 check_exit_policy =
2197 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2198 !conn->use_begindir &&
2199 !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
2201 /* Does this connection want a one-hop circuit? */
2202 want_onehop = conn->want_onehop;
2204 /* Do we need a high-uptime circuit? */
2205 need_uptime = !conn->want_onehop && !conn->use_begindir &&
2206 smartlist_contains_int_as_string(options->LongLivedPorts,
2207 conn->socks_request->port);
2209 /* Do we need an "internal" circuit? */
2210 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
2211 need_internal = 1;
2212 else if (conn->use_begindir || conn->want_onehop)
2213 need_internal = 1;
2214 else
2215 need_internal = 0;
2217 /* We now know what kind of circuit we need. See if there is an
2218 * open circuit that we can use for this stream */
2219 circ = circuit_get_best(conn, 1 /* Insist on open circuits */,
2220 desired_circuit_purpose,
2221 need_uptime, need_internal);
2223 if (circ) {
2224 /* We got a circuit that will work for this stream! We can return it. */
2225 *circp = circ;
2226 return 1; /* we're happy */
2229 /* Okay, there's no circuit open that will work for this stream. Let's
2230 * see if there's an in-progress circuit or if we have to launch one */
2232 /* Do we know enough directory info to build circuits at all? */
2233 int have_path = have_enough_path_info(!need_internal);
2235 if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
2236 /* If we don't have enough directory information, we can't build
2237 * multihop circuits.
2239 if (!connection_get_by_type(CONN_TYPE_DIR)) {
2240 int severity = LOG_NOTICE;
2241 /* Retry some stuff that might help the connection work. */
2242 /* If we are configured with EntryNodes or UseBridges */
2243 if (entry_list_is_constrained(options)) {
2244 /* Retry all our guards / bridges.
2245 * guards_retry_optimistic() always returns true here. */
2246 int rv = guards_retry_optimistic(options);
2247 tor_assert_nonfatal_once(rv);
2248 log_fn(severity, LD_APP|LD_DIR,
2249 "Application request when we haven't %s. "
2250 "Optimistically trying known %s again.",
2251 !router_have_minimum_dir_info() ?
2252 "used client functionality lately" :
2253 "received a consensus with exits",
2254 options->UseBridges ? "bridges" : "entrynodes");
2255 } else {
2256 /* Getting directory documents doesn't help much if we have a limited
2257 * number of guards */
2258 tor_assert_nonfatal(!options->UseBridges);
2259 tor_assert_nonfatal(!options->EntryNodes);
2260 /* Retry our directory fetches, so we have a fresh set of guard info */
2261 log_fn(severity, LD_APP|LD_DIR,
2262 "Application request when we haven't %s. "
2263 "Optimistically trying directory fetches again.",
2264 !router_have_minimum_dir_info() ?
2265 "used client functionality lately" :
2266 "received a consensus with exits");
2267 routerlist_retry_directory_downloads(time(NULL));
2270 /* Since we didn't have enough directory info, we can't attach now. The
2271 * stream will be dealt with when router_have_minimum_dir_info becomes 1,
2272 * or when all directory attempts fail and directory_all_unreachable()
2273 * kills it.
2275 return 0;
2278 /* Check whether the exit policy of the chosen exit, or the exit policies
2279 * of _all_ nodes, would forbid this node. */
2280 if (check_exit_policy) {
2281 if (!conn->chosen_exit_name) {
2282 struct in_addr in;
2283 tor_addr_t addr, *addrp=NULL;
2284 if (tor_inet_aton(conn->socks_request->address, &in)) {
2285 tor_addr_from_in(&addr, &in);
2286 addrp = &addr;
2288 if (router_exit_policy_all_nodes_reject(addrp,
2289 conn->socks_request->port,
2290 need_uptime)) {
2291 log_notice(LD_APP,
2292 "No Tor server allows exit to %s:%d. Rejecting.",
2293 safe_str_client(conn->socks_request->address),
2294 conn->socks_request->port);
2295 return -1;
2297 } else {
2298 /* XXXX Duplicates checks in connection_ap_handshake_attach_circuit:
2299 * refactor into a single function. */
2300 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2301 int opt = conn->chosen_exit_optional;
2302 if (node && !connection_ap_can_use_exit(conn, node)) {
2303 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2304 "Requested exit point '%s' is excluded or "
2305 "would refuse request. %s.",
2306 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2307 if (opt) {
2308 conn->chosen_exit_optional = 0;
2309 tor_free(conn->chosen_exit_name);
2310 /* Try again. */
2311 return circuit_get_open_circ_or_launch(conn,
2312 desired_circuit_purpose,
2313 circp);
2315 return -1;
2320 /* Now, check whether there already a circuit on the way that could handle
2321 * this stream. This check matches the one above, but this time we
2322 * do not require that the circuit will work. */
2323 circ = circuit_get_best(conn, 0 /* don't insist on open circuits */,
2324 desired_circuit_purpose,
2325 need_uptime, need_internal);
2326 if (circ)
2327 log_debug(LD_CIRC, "one on the way!");
2329 if (!circ) {
2330 /* No open or in-progress circuit could handle this stream! We
2331 * will have to launch one!
2334 /* The chosen exit node, if there is one. */
2335 extend_info_t *extend_info=NULL;
2336 const int n_pending = count_pending_general_client_circuits();
2338 /* Do we have too many pending circuits? */
2339 if (n_pending >= options->MaxClientCircuitsPending) {
2340 static ratelim_t delay_limit = RATELIM_INIT(10*60);
2341 char *m;
2342 if ((m = rate_limit_log(&delay_limit, approx_time()))) {
2343 log_notice(LD_APP, "We'd like to launch a circuit to handle a "
2344 "connection, but we already have %d general-purpose client "
2345 "circuits pending. Waiting until some finish.%s",
2346 n_pending, m);
2347 tor_free(m);
2349 return 0;
2352 /* If this is a hidden service trying to start an introduction point,
2353 * handle that case. */
2354 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
2355 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2356 /* need to pick an intro point */
2357 extend_info = hs_client_get_random_intro_from_edge(edge_conn);
2358 if (!extend_info) {
2359 log_info(LD_REND, "No intro points: re-fetching service descriptor.");
2360 if (edge_conn->rend_data) {
2361 rend_client_refetch_v2_renddesc(edge_conn->rend_data);
2362 } else {
2363 hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
2365 connection_ap_mark_as_non_pending_circuit(conn);
2366 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
2367 return 0;
2369 log_info(LD_REND,"Chose %s as intro point for '%s'.",
2370 extend_info_describe(extend_info),
2371 (edge_conn->rend_data) ?
2372 safe_str_client(rend_data_get_address(edge_conn->rend_data)) :
2373 "service");
2376 /* If we have specified a particular exit node for our
2377 * connection, then be sure to open a circuit to that exit node.
2379 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2380 desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2381 desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
2382 if (conn->chosen_exit_name) {
2383 const node_t *r;
2384 int opt = conn->chosen_exit_optional;
2385 r = node_get_by_nickname(conn->chosen_exit_name, 0);
2386 if (r && node_has_preferred_descriptor(r, conn->want_onehop ? 1 : 0)) {
2387 /* We might want to connect to an IPv6 bridge for loading
2388 descriptors so we use the preferred address rather than
2389 the primary. */
2390 extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
2391 if (!extend_info) {
2392 log_warn(LD_CIRC,"Could not make a one-hop connection to %s. "
2393 "Discarding this circuit.", conn->chosen_exit_name);
2394 return -1;
2396 } else { /* ! (r && node_has_preferred_descriptor(...)) */
2397 log_debug(LD_DIR, "considering %d, %s",
2398 want_onehop, conn->chosen_exit_name);
2399 if (want_onehop && conn->chosen_exit_name[0] == '$') {
2400 /* We're asking for a one-hop circuit to a router that
2401 * we don't have a routerinfo about. Make up an extend_info. */
2402 /* XXX prop220: we need to make chosen_exit_name able to
2403 * encode both key formats. This is not absolutely critical
2404 * since this is just for one-hop circuits, but we should
2405 * still get it done */
2406 char digest[DIGEST_LEN];
2407 char *hexdigest = conn->chosen_exit_name+1;
2408 tor_addr_t addr;
2409 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2410 base16_decode(digest,DIGEST_LEN,
2411 hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN) {
2412 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
2413 return -1;
2415 if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
2416 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
2417 escaped_safe_str_client(conn->socks_request->address));
2418 return -1;
2420 /* XXXX prop220 add a workaround for ed25519 ID below*/
2421 extend_info = extend_info_new(conn->chosen_exit_name+1,
2422 digest,
2423 NULL, /* Ed25519 ID */
2424 NULL, NULL, /* onion keys */
2425 &addr, conn->socks_request->port);
2426 } else { /* ! (want_onehop && conn->chosen_exit_name[0] == '$') */
2427 /* We will need an onion key for the router, and we
2428 * don't have one. Refuse or relax requirements. */
2429 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2430 "Requested exit point '%s' is not known. %s.",
2431 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2432 if (opt) {
2433 conn->chosen_exit_optional = 0;
2434 tor_free(conn->chosen_exit_name);
2435 /* Try again with no requested exit */
2436 return circuit_get_open_circ_or_launch(conn,
2437 desired_circuit_purpose,
2438 circp);
2440 return -1;
2444 } /* Done checking for general circutis with chosen exits. */
2446 /* What purpose do we need to launch this circuit with? */
2447 uint8_t new_circ_purpose;
2448 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
2449 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
2450 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
2451 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
2452 else
2453 new_circ_purpose = desired_circuit_purpose;
2455 #ifdef ENABLE_TOR2WEB_MODE
2456 /* If tor2Web is on, then hidden service requests should be one-hop.
2458 if (options->Tor2webMode &&
2459 (new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
2460 new_circ_purpose == CIRCUIT_PURPOSE_C_INTRODUCING)) {
2461 want_onehop = 1;
2463 #endif /* defined(ENABLE_TOR2WEB_MODE) */
2465 /* Determine what kind of a circuit to launch, and actually launch it. */
2467 int flags = CIRCLAUNCH_NEED_CAPACITY;
2468 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
2469 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2470 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
2472 /* If we are about to pick a v3 RP right now, make sure we pick a
2473 * rendezvous point that supports the v3 protocol! */
2474 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED &&
2475 new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2476 ENTRY_TO_EDGE_CONN(conn)->hs_ident) {
2477 flags |= CIRCLAUNCH_IS_V3_RP;
2478 log_info(LD_GENERAL, "Getting rendezvous circuit to v3 service!");
2481 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
2482 flags);
2485 extend_info_free(extend_info);
2487 /* Now trigger things that need to happen when we launch circuits */
2489 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2490 desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2491 desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST) {
2492 /* We just caused a circuit to get built because of this stream.
2493 * If this stream has caused a _lot_ of circuits to be built, that's
2494 * a bad sign: we should tell the user. */
2495 if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
2496 ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
2497 log_info(LD_CIRC, "The application request to %s:%d has launched "
2498 "%d circuits without finding one it likes.",
2499 escaped_safe_str_client(conn->socks_request->address),
2500 conn->socks_request->port,
2501 conn->num_circuits_launched);
2502 } else {
2503 /* help predict this next time */
2504 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
2505 if (circ) {
2506 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2507 if (edge_conn->rend_data) {
2508 /* write the service_id into circ */
2509 circ->rend_data = rend_data_dup(edge_conn->rend_data);
2510 } else if (edge_conn->hs_ident) {
2511 circ->hs_ident =
2512 hs_ident_circuit_new(&edge_conn->hs_ident->identity_pk,
2513 HS_IDENT_CIRCUIT_INTRO);
2515 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2516 circ->base_.state == CIRCUIT_STATE_OPEN)
2517 circuit_has_opened(circ);
2520 } /* endif (!circ) */
2522 /* We either found a good circuit, or launched a new circuit, or failed to
2523 * do so. Report success, and delay. */
2525 if (circ) {
2526 /* Mark the circuit with the isolation fields for this connection.
2527 * When the circuit arrives, we'll clear these flags: this is
2528 * just some internal bookkeeping to make sure that we have
2529 * launched enough circuits.
2531 connection_edge_update_circuit_isolation(conn, circ, 0);
2532 } else {
2533 log_info(LD_APP,
2534 "No safe circuit (purpose %d) ready for edge "
2535 "connection; delaying.",
2536 desired_circuit_purpose);
2538 *circp = circ;
2539 return 0;
2542 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
2543 * <b>circ</b>. */
2544 static int
2545 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
2547 crypt_path_t *cpath, *cpath_next = NULL;
2548 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2549 cpath_next = cpath->next;
2550 if (crypt_path == cpath)
2551 return 1;
2553 return 0;
2556 /** Return true iff client-side optimistic data is supported. */
2557 static int
2558 optimistic_data_enabled(void)
2560 const or_options_t *options = get_options();
2561 if (options->OptimisticData < 0) {
2562 /* Note: this default was 0 before #18815 was merged. We can't take the
2563 * parameter out of the consensus until versions before that are all
2564 * obsolete. */
2565 const int32_t enabled =
2566 networkstatus_get_param(NULL, "UseOptimisticData", /*default*/ 1, 0, 1);
2567 return (int)enabled;
2569 return options->OptimisticData;
2572 /** Attach the AP stream <b>apconn</b> to circ's linked list of
2573 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
2574 * hop in circ's cpath if <b>cpath</b> is NULL.
2576 static void
2577 link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
2578 crypt_path_t *cpath)
2580 const node_t *exitnode = NULL;
2582 /* add it into the linked list of streams on this circuit */
2583 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
2584 (unsigned)circ->base_.n_circ_id);
2585 /* reset it, so we can measure circ timeouts */
2586 ENTRY_TO_CONN(apconn)->timestamp_last_read_allowed = time(NULL);
2587 ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
2588 ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
2589 /* assert_connection_ok(conn, time(NULL)); */
2590 circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
2592 if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
2593 /* We are attaching a stream to a rendezvous circuit. That means
2594 * that an attempt to connect to a hidden service just
2595 * succeeded. Tell rendclient.c. */
2596 hs_client_note_connection_attempt_succeeded(ENTRY_TO_EDGE_CONN(apconn));
2599 if (cpath) { /* we were given one; use it */
2600 tor_assert(cpath_is_on_circuit(circ, cpath));
2601 } else {
2602 /* use the last hop in the circuit */
2603 tor_assert(circ->cpath);
2604 tor_assert(circ->cpath->prev);
2605 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
2606 cpath = circ->cpath->prev;
2608 ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
2610 circ->isolation_any_streams_attached = 1;
2611 connection_edge_update_circuit_isolation(apconn, circ, 0);
2613 /* Compute the exitnode if possible, for logging below */
2614 if (cpath->extend_info)
2615 exitnode = node_get_by_id(cpath->extend_info->identity_digest);
2617 /* See if we can use optimistic data on this circuit */
2618 if (optimistic_data_enabled() &&
2619 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2620 circ->base_.purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2621 circ->base_.purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2622 circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED))
2623 apconn->may_use_optimistic_data = 1;
2624 else
2625 apconn->may_use_optimistic_data = 0;
2626 log_info(LD_APP, "Looks like completed circuit to %s %s allow "
2627 "optimistic data for connection to %s",
2628 circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ?
2629 /* node_describe() does the right thing if exitnode is NULL */
2630 safe_str_client(node_describe(exitnode)) :
2631 "hidden service",
2632 apconn->may_use_optimistic_data ? "does" : "doesn't",
2633 safe_str_client(apconn->socks_request->address));
2636 /** Return true iff <b>address</b> is matched by one of the entries in
2637 * TrackHostExits. */
2639 hostname_in_track_host_exits(const or_options_t *options, const char *address)
2641 if (!options->TrackHostExits)
2642 return 0;
2643 SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
2644 if (cp[0] == '.') { /* match end */
2645 if (cp[1] == '\0' ||
2646 !strcasecmpend(address, cp) ||
2647 !strcasecmp(address, &cp[1]))
2648 return 1;
2649 } else if (strcasecmp(cp, address) == 0) {
2650 return 1;
2652 } SMARTLIST_FOREACH_END(cp);
2653 return 0;
2656 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
2657 * the exit that we *did* choose for use by future connections to
2658 * <b>conn</b>'s destination.
2660 static void
2661 consider_recording_trackhost(const entry_connection_t *conn,
2662 const origin_circuit_t *circ)
2664 const or_options_t *options = get_options();
2665 char *new_address = NULL;
2666 char fp[HEX_DIGEST_LEN+1];
2668 /* Search the addressmap for this conn's destination. */
2669 /* If they're not in the address map.. */
2670 if (!options->TrackHostExits ||
2671 addressmap_have_mapping(conn->socks_request->address,
2672 options->TrackHostExitsExpire))
2673 return; /* nothing to track, or already mapped */
2675 if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
2676 !circ->build_state->chosen_exit)
2677 return;
2679 /* write down the fingerprint of the chosen exit, not the nickname,
2680 * because the chosen exit might not be named. */
2681 base16_encode(fp, sizeof(fp),
2682 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
2684 /* Add this exit/hostname pair to the addressmap. */
2685 tor_asprintf(&new_address, "%s.%s.exit",
2686 conn->socks_request->address, fp);
2688 addressmap_register(conn->socks_request->address, new_address,
2689 time(NULL) + options->TrackHostExitsExpire,
2690 ADDRMAPSRC_TRACKEXIT, 0, 0);
2693 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
2694 * begin or resolve cell as appropriate. Return values are as for
2695 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
2696 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2697 * <b>cpath</b> is NULL. */
2699 connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
2700 origin_circuit_t *circ,
2701 crypt_path_t *cpath)
2703 connection_t *base_conn = ENTRY_TO_CONN(conn);
2704 tor_assert(conn);
2705 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
2706 base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
2707 tor_assert(conn->socks_request);
2708 tor_assert(circ);
2709 tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
2711 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2713 if (!circ->base_.timestamp_dirty ||
2714 ((conn->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
2715 (conn->entry_cfg.socks_iso_keep_alive) &&
2716 (conn->socks_request->usernamelen ||
2717 conn->socks_request->passwordlen))) {
2718 /* When stream isolation is in use and controlled by an application
2719 * we are willing to keep using the stream. */
2720 circ->base_.timestamp_dirty = approx_time();
2723 pathbias_count_use_attempt(circ);
2725 /* Now, actually link the connection. */
2726 link_apconn_to_circ(conn, circ, cpath);
2728 tor_assert(conn->socks_request);
2729 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
2730 if (!conn->use_begindir)
2731 consider_recording_trackhost(conn, circ);
2732 if (connection_ap_handshake_send_begin(conn) < 0)
2733 return -1;
2734 } else {
2735 if (connection_ap_handshake_send_resolve(conn) < 0)
2736 return -1;
2739 return 1;
2743 * Return an appropriate circuit purpose for non-rend streams.
2744 * We don't handle rends here because a rend stream triggers two
2745 * circuit builds with different purposes, so it is handled elsewhere.
2747 * This function just figures out what type of hsdir activity this is,
2748 * and tells us. Everything else is general.
2750 static int
2751 connection_ap_get_nonrend_circ_purpose(const entry_connection_t *conn)
2753 const connection_t *base_conn = ENTRY_TO_CONN(conn);
2754 tor_assert_nonfatal(!connection_edge_is_rendezvous_stream(
2755 ENTRY_TO_EDGE_CONN(conn)));
2757 if (base_conn->linked_conn &&
2758 base_conn->linked_conn->type == CONN_TYPE_DIR) {
2759 /* Set a custom purpose for hsdir activity */
2760 if (base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2 ||
2761 base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_HSDESC) {
2762 return CIRCUIT_PURPOSE_S_HSDIR_POST;
2763 } else if (base_conn->linked_conn->purpose
2764 == DIR_PURPOSE_FETCH_RENDDESC_V2 ||
2765 base_conn->linked_conn->purpose
2766 == DIR_PURPOSE_FETCH_HSDESC) {
2767 return CIRCUIT_PURPOSE_C_HSDIR_GET;
2771 /* All other purposes are general for now */
2772 return CIRCUIT_PURPOSE_C_GENERAL;
2775 /** Try to find a safe live circuit for stream <b>conn</b>. If we find one,
2776 * attach the stream, send appropriate cells, and return 1. Otherwise,
2777 * try to launch new circuit(s) for the stream. If we can launch
2778 * circuits, return 0. Otherwise, if we simply can't proceed with
2779 * this stream, return -1. (conn needs to die, and is maybe already marked).
2781 /* XXXX this function should mark for close whenever it returns -1;
2782 * its callers shouldn't have to worry about that. */
2784 connection_ap_handshake_attach_circuit(entry_connection_t *conn)
2786 connection_t *base_conn = ENTRY_TO_CONN(conn);
2787 int retval;
2788 int conn_age;
2789 int want_onehop;
2791 tor_assert(conn);
2792 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2793 tor_assert(conn->socks_request);
2794 want_onehop = conn->want_onehop;
2796 conn_age = (int)(time(NULL) - base_conn->timestamp_created);
2798 /* Is this connection so old that we should give up on it? */
2799 if (conn_age >= get_options()->SocksTimeout) {
2800 int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
2801 LOG_INFO : LOG_NOTICE;
2802 log_fn(severity, LD_APP,
2803 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
2804 conn_age, safe_str_client(conn->socks_request->address),
2805 conn->socks_request->port);
2806 return -1;
2809 /* We handle "general" (non-onion) connections much more straightforwardly.
2811 if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
2812 /* we're a general conn */
2813 origin_circuit_t *circ=NULL;
2815 /* Are we linked to a dir conn that aims to fetch a consensus?
2816 * We check here because the conn might no longer be needed. */
2817 if (base_conn->linked_conn &&
2818 base_conn->linked_conn->type == CONN_TYPE_DIR &&
2819 base_conn->linked_conn->purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
2821 /* Yes we are. Is there a consensus fetch farther along than us? */
2822 if (networkstatus_consensus_is_already_downloading(
2823 TO_DIR_CONN(base_conn->linked_conn)->requested_resource)) {
2824 /* We're doing the "multiple consensus fetch attempts" game from
2825 * proposal 210, and we're late to the party. Just close this conn.
2826 * The circuit and TLS conn that we made will time out after a while
2827 * if nothing else wants to use them. */
2828 log_info(LD_DIR, "Closing extra consensus fetch (to %s) since one "
2829 "is already downloading.", base_conn->linked_conn->address);
2830 return -1;
2834 /* If we have a chosen exit, we need to use a circuit that's
2835 * open to that exit. See what exit we meant, and whether we can use it.
2837 if (conn->chosen_exit_name) {
2838 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2839 int opt = conn->chosen_exit_optional;
2840 if (!node && !want_onehop) {
2841 /* We ran into this warning when trying to extend a circuit to a
2842 * hidden service directory for which we didn't have a router
2843 * descriptor. See flyspray task 767 for more details. We should
2844 * keep this in mind when deciding to use BEGIN_DIR cells for other
2845 * directory requests as well. -KL*/
2846 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2847 "Requested exit point '%s' is not known. %s.",
2848 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2849 if (opt) {
2850 /* If we are allowed to ignore the .exit request, do so */
2851 conn->chosen_exit_optional = 0;
2852 tor_free(conn->chosen_exit_name);
2853 return 0;
2855 return -1;
2857 if (node && !connection_ap_can_use_exit(conn, node)) {
2858 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2859 "Requested exit point '%s' is excluded or "
2860 "would refuse request. %s.",
2861 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2862 if (opt) {
2863 /* If we are allowed to ignore the .exit request, do so */
2864 conn->chosen_exit_optional = 0;
2865 tor_free(conn->chosen_exit_name);
2866 return 0;
2868 return -1;
2872 /* Find the circuit that we should use, if there is one. Otherwise
2873 * launch it
2875 retval = circuit_get_open_circ_or_launch(conn,
2876 connection_ap_get_nonrend_circ_purpose(conn),
2877 &circ);
2879 if (retval < 1) {
2880 /* We were either told "-1" (complete failure) or 0 (circuit in
2881 * progress); we can't attach this stream yet. */
2882 return retval;
2885 log_debug(LD_APP|LD_CIRC,
2886 "Attaching apconn to circ %u (stream %d sec old).",
2887 (unsigned)circ->base_.n_circ_id, conn_age);
2888 /* print the circ's path, so clients can figure out which circs are
2889 * sucking. */
2890 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
2892 /* We have found a suitable circuit for our conn. Hurray. Do
2893 * the attachment. */
2894 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
2896 } else { /* we're a rendezvous conn */
2897 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
2899 tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
2901 /* start by finding a rendezvous circuit for us */
2903 retval = circuit_get_open_circ_or_launch(
2904 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
2905 if (retval < 0) return -1; /* failed */
2907 if (retval > 0) {
2908 tor_assert(rendcirc);
2909 /* one is already established, attach */
2910 log_info(LD_REND,
2911 "rend joined circ %u (id: %" PRIu32 ") already here. "
2912 "Attaching. (stream %d sec old)",
2913 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2914 rendcirc->global_identifier, conn_age);
2915 /* Mark rendezvous circuits as 'newly dirty' every time you use
2916 * them, since the process of rebuilding a rendezvous circ is so
2917 * expensive. There is a tradeoff between linkability and
2918 * feasibility, at this point.
2920 rendcirc->base_.timestamp_dirty = time(NULL);
2922 /* We've also attempted to use them. If they fail, we need to
2923 * probe them for path bias */
2924 pathbias_count_use_attempt(rendcirc);
2926 link_apconn_to_circ(conn, rendcirc, NULL);
2927 if (connection_ap_handshake_send_begin(conn) < 0)
2928 return 0; /* already marked, let them fade away */
2929 return 1;
2932 /* At this point we need to re-check the state, since it's possible that
2933 * our call to circuit_get_open_circ_or_launch() changed the connection's
2934 * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
2935 * re-fetch the descriptor.
2937 if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2938 log_info(LD_REND, "This connection is no longer ready to attach; its "
2939 "state changed."
2940 "(We probably have to re-fetch its descriptor.)");
2941 return 0;
2944 if (rendcirc && (rendcirc->base_.purpose ==
2945 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
2946 log_info(LD_REND,
2947 "pending-join circ %u (id: %" PRIu32 ") already here, with "
2948 "intro ack. Stalling. (stream %d sec old)",
2949 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2950 rendcirc->global_identifier, conn_age);
2951 return 0;
2954 /* it's on its way. find an intro circ. */
2955 retval = circuit_get_open_circ_or_launch(
2956 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
2957 if (retval < 0) return -1; /* failed */
2959 if (retval > 0) {
2960 /* one has already sent the intro. keep waiting. */
2961 tor_assert(introcirc);
2962 log_info(LD_REND, "Intro circ %u (id: %" PRIu32 ") present and "
2963 "awaiting ACK. Rend circuit %u (id: %" PRIu32 "). "
2964 "Stalling. (stream %d sec old)",
2965 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
2966 introcirc->global_identifier,
2967 rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
2968 rendcirc ? rendcirc->global_identifier : 0,
2969 conn_age);
2970 return 0;
2973 /* now rendcirc and introcirc are each either undefined or not finished */
2975 if (rendcirc && introcirc &&
2976 rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
2977 log_info(LD_REND,
2978 "ready rend circ %u (id: %" PRIu32 ") already here. No"
2979 "intro-ack yet on intro %u (id: %" PRIu32 "). "
2980 "(stream %d sec old)",
2981 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2982 rendcirc->global_identifier,
2983 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
2984 introcirc->global_identifier, conn_age);
2986 tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2987 if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
2988 int ret;
2989 log_info(LD_REND, "Found open intro circ %u (id: %" PRIu32 "). "
2990 "Rend circuit %u (id: %" PRIu32 "); Sending "
2991 "introduction. (stream %d sec old)",
2992 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
2993 introcirc->global_identifier,
2994 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2995 rendcirc->global_identifier, conn_age);
2996 ret = hs_client_send_introduce1(introcirc, rendcirc);
2997 switch (ret) {
2998 case 0: /* success */
2999 rendcirc->base_.timestamp_dirty = time(NULL);
3000 introcirc->base_.timestamp_dirty = time(NULL);
3002 pathbias_count_use_attempt(introcirc);
3003 pathbias_count_use_attempt(rendcirc);
3005 assert_circuit_ok(TO_CIRCUIT(rendcirc));
3006 assert_circuit_ok(TO_CIRCUIT(introcirc));
3007 return 0;
3008 case -1: /* transient error */
3009 return 0;
3010 case -2: /* permanent error */
3011 return -1;
3012 default: /* oops */
3013 tor_fragile_assert();
3014 return -1;
3019 log_info(LD_REND, "Intro %u (id: %" PRIu32 ") and rend circuit %u "
3020 "(id: %" PRIu32 ") circuits are not both ready. "
3021 "Stalling conn. (%d sec old)",
3022 introcirc ? (unsigned) TO_CIRCUIT(introcirc)->n_circ_id : 0,
3023 introcirc ? introcirc->global_identifier : 0,
3024 rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
3025 rendcirc ? rendcirc->global_identifier : 0, conn_age);
3026 return 0;
3030 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
3031 void
3032 circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
3034 uint8_t old_purpose;
3035 /* Don't allow an OR circ to become an origin circ or vice versa. */
3036 tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
3037 !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
3039 if (circ->purpose == new_purpose) return;
3041 if (CIRCUIT_IS_ORIGIN(circ)) {
3042 char old_purpose_desc[80] = "";
3044 strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
3045 old_purpose_desc[80-1] = '\0';
3047 log_debug(LD_CIRC,
3048 "changing purpose of origin circ %d "
3049 "from \"%s\" (%d) to \"%s\" (%d)",
3050 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
3051 old_purpose_desc,
3052 circ->purpose,
3053 circuit_purpose_to_string(new_purpose),
3054 new_purpose);
3057 old_purpose = circ->purpose;
3058 circ->purpose = new_purpose;
3060 if (CIRCUIT_IS_ORIGIN(circ)) {
3061 control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
3062 old_purpose);
3066 /** Mark <b>circ</b> so that no more connections can be attached to it. */
3067 void
3068 mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
3070 const or_options_t *options = get_options();
3071 tor_assert(circ);
3073 /* XXXX This is a kludge; we're only keeping it around in case there's
3074 * something that doesn't check unusable_for_new_conns, and to avoid
3075 * deeper refactoring of our expiration logic. */
3076 if (! circ->base_.timestamp_dirty)
3077 circ->base_.timestamp_dirty = approx_time();
3078 if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
3079 circ->base_.timestamp_dirty = 1; /* prevent underflow */
3080 else
3081 circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
3083 circ->unusable_for_new_conns = 1;