Merge branch 'fix-changelogs' into 'main'
[tor.git] / src / core / or / circuituse.c
blob37c6cc3782975e13ea8310a9cc9c57925750652d
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-2021, 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 "core/or/or.h"
31 #include "app/config/config.h"
32 #include "core/mainloop/connection.h"
33 #include "core/or/channel.h"
34 #include "core/or/circuitbuild.h"
35 #include "core/or/circuitlist.h"
36 #include "core/or/circuitstats.h"
37 #include "core/or/circuituse.h"
38 #include "core/or/circuitpadding.h"
39 #include "core/or/conflux_pool.h"
40 #include "core/or/connection_edge.h"
41 #include "core/or/extendinfo.h"
42 #include "core/or/policies.h"
43 #include "core/or/trace_probes_circuit.h"
44 #include "feature/client/addressmap.h"
45 #include "feature/client/bridges.h"
46 #include "feature/client/circpathbias.h"
47 #include "feature/client/entrynodes.h"
48 #include "feature/client/proxymode.h"
49 #include "feature/control/control_events.h"
50 #include "feature/dircommon/directory.h"
51 #include "feature/hs/hs_circuit.h"
52 #include "feature/hs/hs_client.h"
53 #include "feature/hs/hs_common.h"
54 #include "feature/hs/hs_ident.h"
55 #include "feature/hs/hs_metrics.h"
56 #include "feature/hs/hs_stats.h"
57 #include "feature/nodelist/describe.h"
58 #include "feature/nodelist/networkstatus.h"
59 #include "feature/nodelist/nodelist.h"
60 #include "feature/nodelist/routerlist.h"
61 #include "feature/relay/routermode.h"
62 #include "feature/relay/selftest.h"
63 #include "feature/stats/predict_ports.h"
64 #include "lib/math/fp.h"
65 #include "lib/time/tvdiff.h"
66 #include "lib/trace/events.h"
67 #include "src/core/mainloop/mainloop.h"
68 #include "core/or/conflux.h"
70 #include "core/or/cpath_build_state_st.h"
71 #include "feature/dircommon/dir_connection_st.h"
72 #include "core/or/entry_connection_st.h"
73 #include "core/or/extend_info_st.h"
74 #include "core/or/or_circuit_st.h"
75 #include "core/or/origin_circuit_st.h"
76 #include "core/or/socks_request_st.h"
78 #include "core/or/conflux_util.h"
80 STATIC void circuit_expire_old_circuits_clientside(void);
81 static void circuit_increment_failure_count(void);
83 /** Check whether the hidden service destination of the stream at
84 * <b>edge_conn</b> is the same as the destination of the circuit at
85 * <b>origin_circ</b>. */
86 static int
87 circuit_matches_with_rend_stream(const edge_connection_t *edge_conn,
88 const origin_circuit_t *origin_circ)
90 /* Check if this is a v3 rendezvous circ/stream */
91 if ((edge_conn->hs_ident && !origin_circ->hs_ident) ||
92 (!edge_conn->hs_ident && origin_circ->hs_ident) ||
93 (edge_conn->hs_ident && origin_circ->hs_ident &&
94 !ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
95 &origin_circ->hs_ident->identity_pk))) {
96 /* this circ is not for this conn */
97 return 0;
100 return 1;
103 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
104 * Else return 0.
107 circuit_is_acceptable(const origin_circuit_t *origin_circ,
108 const entry_connection_t *conn,
109 int must_be_open, uint8_t purpose,
110 int need_uptime, int need_internal,
111 time_t now)
113 const circuit_t *circ = TO_CIRCUIT(origin_circ);
114 const node_t *exitnode;
115 cpath_build_state_t *build_state;
116 tor_assert(circ);
117 tor_assert(conn);
118 tor_assert(conn->socks_request);
120 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
121 return 0; /* ignore non-open circs */
122 if (circ->marked_for_close)
123 return 0;
125 /* if this circ isn't our purpose, skip. */
126 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
127 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
128 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
129 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
130 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
131 return 0;
132 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
133 !must_be_open) {
134 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
135 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
136 return 0;
137 } else {
138 if (purpose != circ->purpose)
139 return 0;
142 if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
143 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
144 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
145 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
146 purpose == CIRCUIT_PURPOSE_C_REND_JOINED ||
147 purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED) {
148 if (circ->timestamp_dirty &&
149 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
150 return 0;
153 if (origin_circ->unusable_for_new_conns)
154 return 0;
156 /* decide if this circ is suitable for this conn */
158 /* for rend circs, circ->cpath->prev is not the last router in the
159 * circuit, it's the magical extra service hop. so just check the nickname
160 * of the one we meant to finish at.
162 build_state = origin_circ->build_state;
163 exitnode = build_state_get_exit_node(build_state);
165 if (need_uptime && !build_state->need_uptime)
166 return 0;
167 if (need_internal != build_state->is_internal)
168 return 0;
170 if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
171 purpose == CIRCUIT_PURPOSE_CONFLUX_UNLINKED ||
172 purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED ||
173 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
174 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
175 tor_addr_t addr;
176 if (!exitnode && !build_state->onehop_tunnel) {
177 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
178 return 0; /* this circuit is screwed and doesn't know it yet,
179 * or is a rendezvous circuit. */
181 if (build_state->onehop_tunnel) {
182 if (!conn->want_onehop) {
183 log_debug(LD_CIRC,"Skipping one-hop circuit.");
184 return 0;
186 tor_assert(conn->chosen_exit_name);
187 if (build_state->chosen_exit) {
188 char digest[DIGEST_LEN];
189 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
190 return 0; /* broken digest, we don't want it */
191 if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
192 DIGEST_LEN))
193 return 0; /* this is a circuit to somewhere else */
194 if (tor_digest_is_zero(digest)) {
195 /* we don't know the digest; have to compare addr:port */
196 const int family = tor_addr_parse(&addr,
197 conn->socks_request->address);
198 if (family < 0 ||
199 !extend_info_has_orport(build_state->chosen_exit, &addr,
200 conn->socks_request->port))
201 return 0;
204 } else {
205 if (conn->want_onehop) {
206 /* don't use three-hop circuits -- that could hurt our anonymity. */
207 return 0;
210 if (origin_circ->prepend_policy) {
211 if (tor_addr_parse(&addr, conn->socks_request->address) != -1) {
212 int r = compare_tor_addr_to_addr_policy(&addr,
213 conn->socks_request->port,
214 origin_circ->prepend_policy);
215 if (r == ADDR_POLICY_REJECTED)
216 return 0;
219 if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
220 /* can't exit from this router */
221 return 0;
223 } else { /* not general: this might be a rend circuit */
224 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
225 if (!circuit_matches_with_rend_stream(edge_conn, origin_circ)) {
226 return 0;
230 if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
231 /* conn needs to be isolated from other conns that have already used
232 * origin_circ */
233 return 0;
236 return 1;
239 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
240 * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
242 static int
243 circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
244 const entry_connection_t *conn)
246 const circuit_t *a = TO_CIRCUIT(oa);
247 const circuit_t *b = TO_CIRCUIT(ob);
248 const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
249 int a_bits, b_bits;
251 /* If one of the circuits was allowed to live due to relaxing its timeout,
252 * it is definitely worse (it's probably a much slower path). */
253 if (oa->relaxed_timeout && !ob->relaxed_timeout)
254 return 0; /* ob is better. It's not relaxed. */
255 if (!oa->relaxed_timeout && ob->relaxed_timeout)
256 return 1; /* oa is better. It's not relaxed. */
258 switch (purpose) {
259 case CIRCUIT_PURPOSE_S_HSDIR_POST:
260 case CIRCUIT_PURPOSE_C_HSDIR_GET:
261 case CIRCUIT_PURPOSE_C_GENERAL:
262 /* if it's used but less dirty it's best;
263 * else if it's more recently created it's best
265 if (b->timestamp_dirty) {
266 if (a->timestamp_dirty &&
267 a->timestamp_dirty > b->timestamp_dirty)
268 return 1;
269 } else {
270 if (a->timestamp_dirty ||
271 timercmp(&a->timestamp_began, &b->timestamp_began, OP_GT))
272 return 1;
273 if (ob->build_state->is_internal)
274 /* XXXX++ what the heck is this internal thing doing here. I
275 * think we can get rid of it. circuit_is_acceptable() already
276 * makes sure that is_internal is exactly what we need it to
277 * be. -RD */
278 return 1;
280 break;
281 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
282 /* the closer it is to ack_wait the better it is */
283 if (a->purpose > b->purpose)
284 return 1;
285 break;
286 case CIRCUIT_PURPOSE_C_REND_JOINED:
287 /* the closer it is to rend_joined the better it is */
288 if (a->purpose > b->purpose)
289 return 1;
290 break;
293 /* XXXX Maybe this check should get a higher priority to avoid
294 * using up circuits too rapidly. */
296 a_bits = connection_edge_update_circuit_isolation(conn,
297 (origin_circuit_t*)oa, 1);
298 b_bits = connection_edge_update_circuit_isolation(conn,
299 (origin_circuit_t*)ob, 1);
300 /* if x_bits < 0, then we have not used x for anything; better not to dirty
301 * a connection if we can help it. */
302 if (a_bits < 0) {
303 return 0;
304 } else if (b_bits < 0) {
305 return 1;
307 a_bits &= ~ oa->isolation_flags_mixed;
308 a_bits &= ~ ob->isolation_flags_mixed;
309 if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
310 /* The fewer new restrictions we need to make on a circuit for stream
311 * isolation, the better. */
312 return 1;
315 return 0;
318 /** Find the best circ that conn can use, preferably one which is
319 * dirty. Circ must not be too old.
321 * Conn must be defined.
323 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
325 * circ_purpose specifies what sort of circuit we must have.
326 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
328 * If it's REND_JOINED and must_be_open==0, then return the closest
329 * rendezvous-purposed circuit that you can find.
331 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
332 * closest introduce-purposed circuit that you can find.
334 static origin_circuit_t *
335 circuit_get_best(const entry_connection_t *conn,
336 int must_be_open, uint8_t purpose,
337 int need_uptime, int need_internal)
339 origin_circuit_t *best=NULL;
340 struct timeval now;
341 time_t now_sec;
343 tor_assert(conn);
345 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
346 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
347 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
348 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
349 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
350 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
352 tor_gettimeofday(&now);
353 now_sec = now.tv_sec;
355 // Prefer pre-built conflux circuits here, if available but only for general
356 // purposes. We don't have onion service conflux support at the moment.
357 if (purpose == CIRCUIT_PURPOSE_C_GENERAL &&
358 (best = conflux_get_circ_for_conn(conn, now_sec))) {
359 return best;
362 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
363 origin_circuit_t *origin_circ;
364 if (!CIRCUIT_IS_ORIGIN(circ))
365 continue;
366 origin_circ = TO_ORIGIN_CIRCUIT(circ);
368 if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
369 need_uptime,need_internal, now_sec))
370 continue;
372 /* now this is an acceptable circ to hand back. but that doesn't
373 * mean it's the *best* circ to hand back. try to decide.
375 if (!best || circuit_is_better(origin_circ,best,conn))
376 best = origin_circ;
378 SMARTLIST_FOREACH_END(circ);
380 return best;
383 /** Return the number of not-yet-open general-purpose origin circuits. */
384 static int
385 count_pending_general_client_circuits(void)
387 int count = 0;
389 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
390 if (circ->marked_for_close ||
391 circ->state == CIRCUIT_STATE_OPEN ||
392 !CIRCUIT_PURPOSE_COUNTS_TOWARDS_MAXPENDING(circ->purpose) ||
393 !CIRCUIT_IS_ORIGIN(circ))
394 continue;
396 ++count;
398 SMARTLIST_FOREACH_END(circ);
400 return count;
403 #if 0
404 /** Check whether, according to the policies in <b>options</b>, the
405 * circuit <b>circ</b> makes sense. */
406 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
407 * Also, it doesn't have the right definition of an exit circuit. Also,
408 * it's never called. */
410 circuit_conforms_to_options(const origin_circuit_t *circ,
411 const or_options_t *options)
413 const crypt_path_t *cpath, *cpath_next = NULL;
415 /* first check if it includes any excluded nodes */
416 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
417 cpath_next = cpath->next;
418 if (routerset_contains_extendinfo(options->ExcludeNodes,
419 cpath->extend_info))
420 return 0;
423 /* then consider the final hop */
424 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
425 circ->cpath->prev->extend_info))
426 return 0;
428 return 1;
430 #endif /* 0 */
433 * Close all circuits that start at us, aren't open, and were born
434 * at least CircuitBuildTimeout seconds ago.
436 * TODO: This function is now partially redundant to
437 * circuit_build_times_handle_completed_hop(), but that function only
438 * covers circuits up to and including 3 hops that are still actually
439 * completing hops. However, circuit_expire_building() also handles longer
440 * circuits, as well as circuits that are completely stalled.
441 * In the future (after prop247/other path selection revamping), we probably
442 * want to eliminate this rats nest in favor of a simpler approach.
444 void
445 circuit_expire_building(void)
447 /* circ_times.timeout_ms and circ_times.close_ms are from
448 * circuit_build_times_get_initial_timeout() if we haven't computed
449 * custom timeouts yet */
450 struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
451 close_cutoff, extremely_old_cutoff,
452 cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff,
453 c_rend_ready_cutoff;
454 const or_options_t *options = get_options();
455 struct timeval now;
456 cpath_build_state_t *build_state;
457 int any_opened_circs = 0;
459 tor_gettimeofday(&now);
461 /* Check to see if we have any opened circuits. If we don't,
462 * we want to be more lenient with timeouts, in case the
463 * user has relocated and/or changed network connections.
464 * See bug #3443. */
465 any_opened_circs = circuit_any_opened_circuits();
467 #define SET_CUTOFF(target, msec) do { \
468 long ms = tor_lround(msec); \
469 struct timeval diff; \
470 diff.tv_sec = ms / 1000; \
471 diff.tv_usec = (int)((ms % 1000) * 1000); \
472 timersub(&now, &diff, &target); \
473 } while (0)
476 * Because circuit build timeout is calculated only based on 3 hop
477 * general purpose circuit construction, we need to scale the timeout
478 * to make it properly apply to longer circuits, and circuits of
479 * certain usage types. The following diagram illustrates how we
480 * derive the scaling below. In short, we calculate the number
481 * of times our telescoping-based circuit construction causes cells
482 * to traverse each link for the circuit purpose types in question,
483 * and then assume each link is equivalent.
485 * OP --a--> A --b--> B --c--> C
486 * OP --a--> A --b--> B --c--> C --d--> D
488 * Let h = a = b = c = d
490 * Three hops (general_cutoff)
491 * RTTs = 3a + 2b + c
492 * RTTs = 6h
493 * Cannibalized:
494 * RTTs = a+b+c+d
495 * RTTs = 4h
496 * Four hops:
497 * RTTs = 4a + 3b + 2c + d
498 * RTTs = 10h
499 * Client INTRODUCE1+ACK: // XXX: correct?
500 * RTTs = 5a + 4b + 3c + 2d
501 * RTTs = 14h
502 * Server intro:
503 * RTTs = 4a + 3b + 2c
504 * RTTs = 9h
506 SET_CUTOFF(general_cutoff, get_circuit_build_timeout_ms());
507 SET_CUTOFF(begindir_cutoff, get_circuit_build_timeout_ms());
509 // TODO: We should probably use route_len_for_purpose() here instead,
510 // except that does not count the extra round trip for things like server
511 // intros and rends.
513 /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
514 * 4th hop. */
515 SET_CUTOFF(fourhop_cutoff, get_circuit_build_timeout_ms() * (10/6.0) + 1000);
517 /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
518 * Use the stream cutoff (more or less). */
519 SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
521 /* Be lenient with cannibalized circs. They already survived the official
522 * CBT, and they're usually not performance-critical. */
523 SET_CUTOFF(cannibalized_cutoff,
524 MAX(get_circuit_build_close_time_ms()*(4/6.0),
525 options->CircuitStreamTimeout * 1000) + 1000);
527 /* Intro circs have an extra round trip (and are also 4 hops long) */
528 SET_CUTOFF(c_intro_cutoff, get_circuit_build_timeout_ms() * (14/6.0) + 1000);
530 /* Server intro circs have an extra round trip */
531 SET_CUTOFF(s_intro_cutoff, get_circuit_build_timeout_ms() * (9/6.0) + 1000);
533 /* For circuit purpose set to: CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED.
535 * The cutoff of such circuit is very high because we end up in this state if
536 * once the INTRODUCE_ACK is received which could be before the service
537 * receives the INTRODUCE2 cell. The worst case is a full 3-hop latency
538 * (intro -> service), 4-hop circuit creation latency (service -> RP), and
539 * finally a 7-hop latency for the RENDEZVOUS2 cell to arrive (service ->
540 * client). */
541 SET_CUTOFF(c_rend_ready_cutoff, get_circuit_build_timeout_ms() * 3 + 1000);
543 SET_CUTOFF(close_cutoff, get_circuit_build_close_time_ms());
544 SET_CUTOFF(extremely_old_cutoff, get_circuit_build_close_time_ms()*2 + 1000);
546 bool fixed_time = circuit_build_times_disabled(get_options());
548 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *,victim) {
549 struct timeval cutoff;
551 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
552 victim->marked_for_close) /* don't mess with marked circs */
553 continue;
555 /* If we haven't yet started the first hop, it means we don't have
556 * any orconns available, and thus have not started counting time yet
557 * for this circuit. See circuit_deliver_create_cell() and uses of
558 * timestamp_began.
560 * Continue to wait in this case. The ORConn should timeout
561 * independently and kill us then.
563 if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
564 continue;
567 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
568 if (build_state && build_state->onehop_tunnel)
569 cutoff = begindir_cutoff;
570 else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
571 cutoff = close_cutoff;
572 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
573 cutoff = c_intro_cutoff;
574 else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
575 cutoff = s_intro_cutoff;
576 else if (victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
577 /* Service connecting to a rendezvous point is a four hop circuit. We set
578 * it explicitly here because this function is a clusterf***. */
579 cutoff = fourhop_cutoff;
580 } else if (victim->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
581 cutoff = c_rend_ready_cutoff;
582 else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
583 cutoff = close_cutoff;
584 else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
585 victim->state != CIRCUIT_STATE_OPEN)
586 cutoff = cannibalized_cutoff;
587 else if (build_state && build_state->desired_path_len >= 4)
588 cutoff = fourhop_cutoff;
589 else
590 cutoff = general_cutoff;
592 if (timercmp(&victim->timestamp_began, &cutoff, OP_GT))
593 continue; /* it's still young, leave it alone */
595 /* We need to double-check the opened state here because
596 * we don't want to consider opened 1-hop dircon circuits for
597 * deciding when to relax the timeout, but we *do* want to relax
598 * those circuits too if nothing else is opened *and* they still
599 * aren't either. */
600 if (!any_opened_circs && victim->state != CIRCUIT_STATE_OPEN) {
601 /* It's still young enough that we wouldn't close it, right? */
602 if (timercmp(&victim->timestamp_began, &close_cutoff, OP_GT)) {
603 if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
604 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
605 == CPATH_STATE_OPEN;
606 if (!fixed_time) {
607 log_info(LD_CIRC,
608 "No circuits are opened. Relaxing timeout for circuit %d "
609 "(a %s %d-hop circuit in state %s with channel state %s).",
610 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
611 circuit_purpose_to_string(victim->purpose),
612 TO_ORIGIN_CIRCUIT(victim)->build_state ?
613 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
615 circuit_state_to_string(victim->state),
616 victim->n_chan ?
617 channel_state_to_string(victim->n_chan->state) : "none");
620 /* We count the timeout here for CBT, because technically this
621 * was a timeout, and the timeout value needs to reset if we
622 * see enough of them. Note this means we also need to avoid
623 * double-counting below, too. */
624 circuit_build_times_count_timeout(get_circuit_build_times_mutable(),
625 first_hop_succeeded);
626 TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
628 continue;
629 } else {
630 static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
631 const double build_close_ms = get_circuit_build_close_time_ms();
632 if (!fixed_time) {
633 log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
634 "No circuits are opened. Relaxed timeout for circuit %d "
635 "(a %s %d-hop circuit in state %s with channel state %s) to "
636 "%ldms. However, it appears the circuit has timed out "
637 "anyway.",
638 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
639 circuit_purpose_to_string(victim->purpose),
640 TO_ORIGIN_CIRCUIT(victim)->build_state ?
641 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
643 circuit_state_to_string(victim->state),
644 victim->n_chan ?
645 channel_state_to_string(victim->n_chan->state) : "none",
646 (long)build_close_ms);
651 #if 0
652 /* some debug logs, to help track bugs */
653 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
654 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
655 if (!victim->timestamp_dirty)
656 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
657 "(clean).",
658 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
659 victim->purpose, victim->build_state->chosen_exit_name,
660 victim->n_circ_id);
661 else
662 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
663 "%d secs since dirty.",
664 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
665 victim->purpose, victim->build_state->chosen_exit_name,
666 victim->n_circ_id,
667 (int)(now - victim->timestamp_dirty));
669 #endif /* 0 */
671 /* if circ is !open, or if it's open but purpose is a non-finished
672 * intro or rend, then mark it for close */
673 if (victim->state == CIRCUIT_STATE_OPEN) {
674 switch (victim->purpose) {
675 default: /* most open circuits can be left alone. */
676 continue; /* yes, continue inside a switch refers to the nearest
677 * enclosing loop. C is smart. */
678 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
679 break; /* too old, need to die */
680 case CIRCUIT_PURPOSE_C_REND_READY:
681 /* it's a rend_ready circ -- has it already picked a query? */
682 /* c_rend_ready circs measure age since timestamp_dirty,
683 * because that's set when they switch purposes
685 if (TO_ORIGIN_CIRCUIT(victim)->hs_ident ||
686 victim->timestamp_dirty > cutoff.tv_sec)
687 continue;
688 break;
689 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
690 /* Open path bias testing circuits are given a long
691 * time to complete the test, but not forever */
692 TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
693 break;
694 case CIRCUIT_PURPOSE_C_INTRODUCING:
695 /* That purpose means that the intro point circuit has been opened
696 * successfully but the INTRODUCE1 cell hasn't been sent yet because
697 * the client is waiting for the rendezvous point circuit to open.
698 * Keep this circuit open while waiting for the rendezvous circuit.
699 * We let the circuit idle timeout take care of cleaning this
700 * circuit if it never used. */
701 continue;
702 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
703 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
704 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
705 /* rend and intro circs become dirty each time they
706 * make an introduction attempt. so timestamp_dirty
707 * will reflect the time since the last attempt.
709 if (victim->timestamp_dirty > cutoff.tv_sec)
710 continue;
711 break;
713 } else { /* circuit not open, consider recording failure as timeout */
714 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
715 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
716 if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
717 log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
718 "yet has attached streams!",
719 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
720 victim->purpose,
721 circuit_purpose_to_string(victim->purpose));
722 tor_fragile_assert();
723 continue;
726 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
727 circuit_build_times_enough_to_compute(get_circuit_build_times())) {
729 log_info(LD_CIRC,
730 "Deciding to count the timeout for circuit %"PRIu32,
731 TO_ORIGIN_CIRCUIT(victim)->global_identifier);
733 /* Circuits are allowed to last longer for measurement.
734 * Switch their purpose and wait. */
735 if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
736 circuit_build_times_mark_circ_as_measurement_only(TO_ORIGIN_CIRCUIT(
737 victim));
738 continue;
742 * If the circuit build time is much greater than we would have cut
743 * it off at, we probably had a suspend event along this codepath,
744 * and we should discard the value.
746 if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, OP_LT)) {
747 log_notice(LD_CIRC,
748 "Extremely large value for circuit build timeout: %lds. "
749 "Assuming clock jump. Purpose %d (%s)",
750 (long)(now.tv_sec - victim->timestamp_began.tv_sec),
751 victim->purpose,
752 circuit_purpose_to_string(victim->purpose));
753 } else if (circuit_build_times_count_close(
754 get_circuit_build_times_mutable(),
755 first_hop_succeeded,
756 (time_t)victim->timestamp_created.tv_sec)) {
757 circuit_build_times_set_timeout(get_circuit_build_times_mutable());
762 /* Special checks for onion service circuits. */
763 switch (victim->purpose) {
764 case CIRCUIT_PURPOSE_C_REND_READY:
765 /* We only want to spare a rend circ iff it has been specified in an
766 * INTRODUCE1 cell sent to a hidden service. */
767 if (hs_circ_is_rend_sent_in_intro1(CONST_TO_ORIGIN_CIRCUIT(victim))) {
768 continue;
770 break;
771 case CIRCUIT_PURPOSE_S_CONNECT_REND:
772 /* The connection to the rendezvous point has timed out, close it and
773 * retry if possible. */
774 log_info(LD_CIRC,"Rendezvous circ %u (state %d:%s, purpose %d) "
775 "as timed-out, closing it. Relaunching rendezvous attempt.",
776 (unsigned)victim->n_circ_id,
777 victim->state, circuit_state_to_string(victim->state),
778 victim->purpose);
779 /* We'll close as a timeout the victim circuit. The rendezvous point
780 * won't keep both circuits, it only keeps the newest (for the same
781 * cookie). */
782 break;
783 default:
784 break;
787 if (victim->n_chan)
788 log_info(LD_CIRC,
789 "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
790 "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
791 channel_describe_peer(victim->n_chan),
792 (unsigned)victim->n_circ_id,
793 TO_ORIGIN_CIRCUIT(victim)->has_opened,
794 victim->state, circuit_state_to_string(victim->state),
795 victim->purpose,
796 TO_ORIGIN_CIRCUIT(victim)->build_state ?
797 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
798 -1);
799 else
800 log_info(LD_CIRC,
801 "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
802 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
803 (unsigned)victim->n_circ_id,
804 TO_ORIGIN_CIRCUIT(victim)->has_opened,
805 victim->state,
806 circuit_state_to_string(victim->state), victim->purpose,
807 TO_ORIGIN_CIRCUIT(victim)->build_state ?
808 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
809 -1);
811 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
812 tor_trace(TR_SUBSYS(circuit), TR_EV(timeout), TO_ORIGIN_CIRCUIT(victim));
813 if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
814 circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
815 else
816 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
818 pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
819 } SMARTLIST_FOREACH_END(victim);
823 * Mark for close all circuits that start here, that were built through a
824 * guard we weren't sure if we wanted to use, and that have been waiting
825 * around for way too long.
827 void
828 circuit_expire_waiting_for_better_guard(void)
830 SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
831 origin_circuit_t *, circ) {
832 if (TO_CIRCUIT(circ)->marked_for_close)
833 continue;
834 if (circ->guard_state == NULL)
835 continue;
836 if (entry_guard_state_should_expire(circ->guard_state))
837 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
838 } SMARTLIST_FOREACH_END(circ);
841 /** For debugging #8387: track when we last called
842 * circuit_expire_old_circuits_clientside. */
843 static time_t last_expired_clientside_circuits = 0;
846 * As a diagnostic for bug 8387, log information about how many one-hop
847 * circuits we have around that have been there for at least <b>age</b>
848 * seconds. Log a few of them. Ignores Single Onion Service intro, it is
849 * expected to be long-term one-hop circuits.
851 void
852 circuit_log_ancient_one_hop_circuits(int age)
854 #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
855 time_t now = time(NULL);
856 time_t cutoff = now - age;
857 int n_found = 0;
858 smartlist_t *log_these = smartlist_new();
859 const or_options_t *options = get_options();
861 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
862 const origin_circuit_t *ocirc;
863 if (! CIRCUIT_IS_ORIGIN(circ))
864 continue;
865 if (circ->timestamp_created.tv_sec >= cutoff)
866 continue;
867 /* Single Onion Services deliberately make long term one-hop intro
868 * and rendezvous connections. Don't log the established ones. */
869 if (hs_service_allow_non_anonymous_connection(options) &&
870 (circ->purpose == CIRCUIT_PURPOSE_S_INTRO ||
871 circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED))
872 continue;
873 ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
875 if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
876 ++n_found;
878 if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
879 smartlist_add(log_these, (origin_circuit_t*) ocirc);
882 SMARTLIST_FOREACH_END(circ);
884 if (n_found == 0)
885 goto done;
887 log_notice(LD_HEARTBEAT,
888 "Diagnostic for issue 8387: Found %d one-hop circuits more "
889 "than %d seconds old! Logging %d...",
890 n_found, age, smartlist_len(log_these));
892 SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
893 char created[ISO_TIME_LEN+1];
894 int stream_num;
895 const edge_connection_t *conn;
896 char *dirty = NULL;
897 const circuit_t *circ = TO_CIRCUIT(ocirc);
899 format_local_iso_time(created,
900 (time_t)circ->timestamp_created.tv_sec);
902 if (circ->timestamp_dirty) {
903 char dirty_since[ISO_TIME_LEN+1];
904 format_local_iso_time(dirty_since, circ->timestamp_dirty);
906 tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
907 dirty_since, (long)(now - circ->timestamp_dirty),
908 (long) options->MaxCircuitDirtiness);
909 } else {
910 dirty = tor_strdup("Not marked dirty");
913 log_notice(LD_HEARTBEAT, " #%d created at %s. %s, %s. %s for close. "
914 "Package window: %d. "
915 "%s for new conns. %s.",
916 ocirc_sl_idx,
917 created,
918 circuit_state_to_string(circ->state),
919 circuit_purpose_to_string(circ->purpose),
920 circ->marked_for_close ? "Marked" : "Not marked",
921 circ->package_window,
922 ocirc->unusable_for_new_conns ? "Not usable" : "usable",
923 dirty);
924 tor_free(dirty);
926 stream_num = 0;
927 for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
928 const connection_t *c = TO_CONN(conn);
929 char stream_created[ISO_TIME_LEN+1];
930 if (++stream_num >= 5)
931 break;
933 format_local_iso_time(stream_created, c->timestamp_created);
935 log_notice(LD_HEARTBEAT, " Stream#%d created at %s. "
936 "%s conn in state %s. "
937 "It is %slinked and %sreading from a linked connection %p. "
938 "Package window %d. "
939 "%s for close (%s:%d). Hold-open is %sset. "
940 "Has %ssent RELAY_END. %s on circuit.",
941 stream_num,
942 stream_created,
943 conn_type_to_string(c->type),
944 conn_state_to_string(c->type, c->state),
945 c->linked ? "" : "not ",
946 c->reading_from_linked_conn ? "": "not",
947 c->linked_conn,
948 conn->package_window,
949 c->marked_for_close ? "Marked" : "Not marked",
950 c->marked_for_close_file ? c->marked_for_close_file : "--",
951 c->marked_for_close,
952 c->hold_open_until_flushed ? "" : "not ",
953 conn->edge_has_sent_end ? "" : "not ",
954 connection_is_reading(c) ? "Not blocked" : "Blocked");
955 if (! c->linked_conn)
956 continue;
958 c = c->linked_conn;
960 log_notice(LD_HEARTBEAT, " Linked to %s connection in state %s "
961 "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
962 conn_type_to_string(c->type),
963 conn_state_to_string(c->type, c->state),
964 c->purpose,
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 ");
970 } SMARTLIST_FOREACH_END(ocirc);
972 log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
973 "circuit_expire_old_circuits_clientside().",
974 (long)(now - last_expired_clientside_circuits));
976 done:
977 smartlist_free(log_these);
980 /** Remove any elements in <b>needed_ports</b> that are handled by an
981 * open or in-progress circuit.
983 void
984 circuit_remove_handled_ports(smartlist_t *needed_ports)
986 int i;
987 uint16_t *port;
989 for (i = 0; i < smartlist_len(needed_ports); ++i) {
990 port = smartlist_get(needed_ports, i);
991 tor_assert(*port);
992 if (circuit_stream_is_being_handled(NULL, *port,
993 MIN_CIRCUITS_HANDLING_STREAM)) {
994 log_debug(LD_CIRC,"Port %d is already being handled; removing.", *port);
995 smartlist_del(needed_ports, i--);
996 tor_free(port);
997 } else {
998 log_debug(LD_CIRC,"Port %d is not handled.", *port);
1003 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
1004 * will have an acceptable exit node for exit stream <b>conn</b> if it
1005 * is defined, else for "*:port".
1006 * Else return 0.
1009 circuit_stream_is_being_handled(entry_connection_t *conn,
1010 uint16_t port, int min)
1012 const node_t *exitnode;
1013 int num=0;
1014 time_t now = time(NULL);
1015 int need_uptime = smartlist_contains_int_as_string(
1016 get_options()->LongLivedPorts,
1017 conn ? conn->socks_request->port : port);
1019 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1020 if (CIRCUIT_IS_ORIGIN(circ) &&
1021 !circ->marked_for_close &&
1022 (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
1023 circ->purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED) &&
1024 (!circ->timestamp_dirty ||
1025 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
1026 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1027 cpath_build_state_t *build_state = origin_circ->build_state;
1028 if (build_state->is_internal || build_state->onehop_tunnel)
1029 continue;
1030 if (origin_circ->unusable_for_new_conns)
1031 continue;
1032 if (origin_circ->isolation_values_set &&
1033 (conn == NULL ||
1034 !connection_edge_compatible_with_circuit(conn, origin_circ)))
1035 continue;
1037 exitnode = build_state_get_exit_node(build_state);
1038 if (exitnode && (!need_uptime || build_state->need_uptime)) {
1039 int ok;
1040 if (conn) {
1041 ok = connection_ap_can_use_exit(conn, exitnode);
1042 } else {
1043 addr_policy_result_t r;
1044 r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
1045 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
1047 if (ok) {
1048 if (++num >= min)
1049 return 1;
1054 SMARTLIST_FOREACH_END(circ);
1055 return 0;
1058 /** Don't keep more than this many unused open circuits around. */
1059 #define MAX_UNUSED_OPEN_CIRCUITS 14
1061 /* Return true if a circuit is available for use, meaning that it is open,
1062 * clean, usable for new multi-hop connections, and a general purpose origin
1063 * circuit.
1064 * Accept any kind of circuit, return false if the above conditions are not
1065 * met. */
1066 STATIC int
1067 circuit_is_available_for_use(const circuit_t *circ)
1069 const origin_circuit_t *origin_circ;
1070 cpath_build_state_t *build_state;
1072 if (!CIRCUIT_IS_ORIGIN(circ))
1073 return 0; /* We first filter out only origin circuits before doing the
1074 following checks. */
1075 if (circ->marked_for_close)
1076 return 0; /* Don't mess with marked circs */
1077 if (circ->timestamp_dirty)
1078 return 0; /* Only count clean circs */
1079 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1080 circ->purpose != CIRCUIT_PURPOSE_HS_VANGUARDS)
1081 return 0; /* We only pay attention to general purpose circuits.
1082 General purpose circuits are always origin circuits. */
1084 origin_circ = CONST_TO_ORIGIN_CIRCUIT(circ);
1085 if (origin_circ->unusable_for_new_conns)
1086 return 0;
1088 build_state = origin_circ->build_state;
1089 if (build_state->onehop_tunnel)
1090 return 0;
1092 return 1;
1095 /* Return true if we need any more exit circuits.
1096 * needs_uptime and needs_capacity are set only if we need more exit circuits.
1097 * Check if we know of a port that's been requested recently and no circuit
1098 * is currently available that can handle it. */
1099 STATIC int
1100 needs_exit_circuits(time_t now, int *needs_uptime, int *needs_capacity)
1102 return (!circuit_all_predicted_ports_handled(now, needs_uptime,
1103 needs_capacity) &&
1104 router_have_consensus_path() == CONSENSUS_PATH_EXIT);
1107 /* Hidden services need at least this many internal circuits */
1108 #define SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS 3
1110 /* Return true if we need any more hidden service server circuits.
1111 * HS servers only need an internal circuit. */
1112 STATIC int
1113 needs_hs_server_circuits(time_t now, int num_uptime_internal)
1115 if (!hs_service_get_num_services()) {
1116 /* No services, we don't need anything. */
1117 goto no_need;
1120 if (num_uptime_internal >= SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS) {
1121 /* We have sufficient amount of internal circuit. */
1122 goto no_need;
1125 if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN) {
1126 /* Consensus hasn't been checked or might be invalid so requesting
1127 * internal circuits is not wise. */
1128 goto no_need;
1131 /* At this point, we need a certain amount of circuits and we will most
1132 * likely use them for rendezvous so we note down the use of internal
1133 * circuit for our prediction for circuit needing uptime and capacity. */
1134 rep_hist_note_used_internal(now, 1, 1);
1136 return 1;
1137 no_need:
1138 return 0;
1141 /* We need at least this many internal circuits for hidden service clients */
1142 #define SUFFICIENT_INTERNAL_HS_CLIENTS 3
1144 /* We need at least this much uptime for internal circuits for hidden service
1145 * clients */
1146 #define SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS 2
1148 /* Return true if we need any more hidden service client circuits.
1149 * HS clients only need an internal circuit. */
1150 STATIC int
1151 needs_hs_client_circuits(time_t now, int *needs_uptime, int *needs_capacity,
1152 int num_internal, int num_uptime_internal)
1154 int used_internal_recently = rep_hist_get_predicted_internal(now,
1155 needs_uptime,
1156 needs_capacity);
1157 int requires_uptime = num_uptime_internal <
1158 SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS &&
1159 needs_uptime;
1161 return (used_internal_recently &&
1162 (requires_uptime || num_internal < SUFFICIENT_INTERNAL_HS_CLIENTS) &&
1163 router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN);
1166 /* This is how many circuits can be opened concurrently during the cbt learning
1167 * phase. This number cannot exceed the tor-wide MAX_UNUSED_OPEN_CIRCUITS. */
1168 #define DFLT_CBT_UNUSED_OPEN_CIRCS (10)
1169 #define MIN_CBT_UNUSED_OPEN_CIRCS 0
1170 #define MAX_CBT_UNUSED_OPEN_CIRCS MAX_UNUSED_OPEN_CIRCUITS
1172 /* Return true if we need more circuits for a good build timeout.
1173 * XXXX make the assumption that build timeout streams should be
1174 * created whenever we can build internal circuits. */
1175 STATIC int
1176 needs_circuits_for_build(int num)
1178 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
1179 if (num < networkstatus_get_param(NULL, "cbtmaxopencircs",
1180 DFLT_CBT_UNUSED_OPEN_CIRCS,
1181 MIN_CBT_UNUSED_OPEN_CIRCS,
1182 MAX_CBT_UNUSED_OPEN_CIRCS) &&
1183 !circuit_build_times_disabled(get_options()) &&
1184 circuit_build_times_needs_circuits_now(get_circuit_build_times())) {
1185 return 1;
1188 return 0;
1191 /** Determine how many circuits we have open that are clean,
1192 * Make sure it's enough for all the upcoming behaviors we predict we'll have.
1193 * But put an upper bound on the total number of circuits.
1195 static void
1196 circuit_predict_and_launch_new(void)
1198 int num=0, num_internal=0, num_uptime_internal=0;
1199 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
1200 int port_needs_uptime=0, port_needs_capacity=1;
1201 time_t now = time(NULL);
1202 int flags = 0;
1204 /* Attempt to launch predicted conflux circuits. This is outside the HS or
1205 * Exit preemptive circuit set.
1206 * As with the other types of preemptive circuits, we only want to
1207 * launch them if we have predicted ports. (If we haven't needed a
1208 * circuit for a while, maybe we won't need one soon either.) */
1209 if (predicted_ports_prediction_time_remaining(now)) {
1210 conflux_predict_new(now);
1213 /* Count how many of each type of circuit we currently have. */
1214 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1215 if (!circuit_is_available_for_use(circ))
1216 continue;
1218 num++;
1220 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
1221 if (build_state->is_internal)
1222 num_internal++;
1223 if (build_state->need_uptime && build_state->is_internal)
1224 num_uptime_internal++;
1226 SMARTLIST_FOREACH_END(circ);
1228 /* If that's enough, then stop now. */
1229 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
1230 return;
1232 if (needs_exit_circuits(now, &port_needs_uptime, &port_needs_capacity)) {
1233 if (port_needs_uptime)
1234 flags |= CIRCLAUNCH_NEED_UPTIME;
1235 if (port_needs_capacity)
1236 flags |= CIRCLAUNCH_NEED_CAPACITY;
1238 log_info(LD_CIRC,
1239 "Have %d clean circs (%d internal), need another exit circ.",
1240 num, num_internal);
1242 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1243 return;
1246 if (needs_hs_server_circuits(now, num_uptime_internal)) {
1247 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
1248 CIRCLAUNCH_IS_INTERNAL);
1250 log_info(LD_CIRC,
1251 "Have %d clean circs (%d internal), need another internal "
1252 "circ for my hidden service.",
1253 num, num_internal);
1254 circuit_launch(CIRCUIT_PURPOSE_HS_VANGUARDS, flags);
1255 return;
1258 if (needs_hs_client_circuits(now, &hidserv_needs_uptime,
1259 &hidserv_needs_capacity,
1260 num_internal, num_uptime_internal))
1262 if (hidserv_needs_uptime)
1263 flags |= CIRCLAUNCH_NEED_UPTIME;
1264 if (hidserv_needs_capacity)
1265 flags |= CIRCLAUNCH_NEED_CAPACITY;
1266 flags |= CIRCLAUNCH_IS_INTERNAL;
1268 log_info(LD_CIRC,
1269 "Have %d clean circs (%d uptime-internal, %d internal), need"
1270 " another hidden service circ.",
1271 num, num_uptime_internal, num_internal);
1273 /* Always launch vanguards purpose circuits for HS clients,
1274 * for vanguards-lite. This prevents us from cannibalizing
1275 * to build these circuits (and thus not use vanguards). */
1276 circuit_launch(CIRCUIT_PURPOSE_HS_VANGUARDS, flags);
1277 return;
1280 if (needs_circuits_for_build(num)) {
1281 flags = CIRCLAUNCH_NEED_CAPACITY;
1282 /* if there are no exits in the consensus, make timeout
1283 * circuits internal */
1284 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
1285 flags |= CIRCLAUNCH_IS_INTERNAL;
1287 log_info(LD_CIRC,
1288 "Have %d clean circs need another buildtime test circ.", num);
1289 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1290 return;
1294 /** Build a new test circuit every 5 minutes */
1295 #define TESTING_CIRCUIT_INTERVAL 300
1297 /** This function is called once a second, if router_have_minimum_dir_info()
1298 * is true. Its job is to make sure all services we offer have enough circuits
1299 * available. Some services just want enough circuits for current tasks,
1300 * whereas others want a minimum set of idle circuits hanging around.
1302 void
1303 circuit_build_needed_circs(time_t now)
1305 const or_options_t *options = get_options();
1307 /* launch a new circ for any pending streams that need one
1308 * XXXX make the assumption that (some) AP streams (i.e. HS clients)
1309 * don't require an exit circuit, review in #13814.
1310 * This allows HSs to function in a consensus without exits. */
1311 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
1312 connection_ap_rescan_and_attach_pending();
1314 circuit_expire_old_circs_as_needed(now);
1316 if (!options->DisablePredictedCircuits)
1317 circuit_predict_and_launch_new();
1321 * Called once a second either directly or from
1322 * circuit_build_needed_circs(). As appropriate (once per NewCircuitPeriod)
1323 * resets failure counts and expires old circuits.
1325 void
1326 circuit_expire_old_circs_as_needed(time_t now)
1328 static time_t time_to_expire_and_reset = 0;
1330 if (time_to_expire_and_reset < now) {
1331 circuit_reset_failure_count(1);
1332 time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
1333 if (proxy_mode(get_options()))
1334 addressmap_clean(now);
1335 circuit_expire_old_circuits_clientside();
1337 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
1339 /* If we ever re-enable, this has to move into
1340 * circuit_build_needed_circs */
1342 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
1343 if (get_options()->RunTesting &&
1344 circ &&
1345 circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
1346 log_fn(LOG_INFO,"Creating a new testing circuit.");
1347 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
1349 #endif /* 0 */
1353 /** If the stream <b>conn</b> is a member of any of the linked
1354 * lists of <b>circ</b>, then remove it from the list.
1356 void
1357 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
1359 edge_connection_t *prevconn;
1361 tor_assert(circ);
1362 tor_assert(conn);
1364 if (conn->base_.type == CONN_TYPE_AP) {
1365 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1366 entry_conn->may_use_optimistic_data = 0;
1368 conn->cpath_layer = NULL; /* don't keep a stale pointer */
1369 conn->on_circuit = NULL;
1371 if (CIRCUIT_IS_ORIGIN(circ)) {
1372 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1373 int removed = 0;
1374 if (conn == origin_circ->p_streams) {
1375 origin_circ->p_streams = conn->next_stream;
1376 conflux_update_p_streams(origin_circ, conn->next_stream);
1377 removed = 1;
1378 } else {
1379 for (prevconn = origin_circ->p_streams;
1380 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1381 prevconn = prevconn->next_stream)
1383 if (prevconn && prevconn->next_stream) {
1384 prevconn->next_stream = conn->next_stream;
1385 removed = 1;
1388 if (removed) {
1389 log_debug(LD_APP, "Removing stream %d from circ %u",
1390 conn->stream_id, (unsigned)circ->n_circ_id);
1392 /* If the stream was removed, and it was a rend stream, decrement the
1393 * number of streams on the circuit associated with the rend service.
1395 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1396 hs_dec_rdv_stream_counter(origin_circ);
1399 /* If there are no more streams on this circ, tell circpad */
1400 if (!origin_circ->p_streams)
1401 circpad_machine_event_circ_has_no_streams(origin_circ);
1403 return;
1405 } else {
1406 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1407 if (conn == or_circ->n_streams) {
1408 or_circ->n_streams = conn->next_stream;
1409 conflux_update_n_streams(or_circ, conn->next_stream);
1410 return;
1412 if (conn == or_circ->resolving_streams) {
1413 or_circ->resolving_streams = conn->next_stream;
1414 conflux_update_resolving_streams(or_circ, conn->next_stream);
1415 return;
1418 for (prevconn = or_circ->n_streams;
1419 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1420 prevconn = prevconn->next_stream)
1422 if (prevconn && prevconn->next_stream) {
1423 prevconn->next_stream = conn->next_stream;
1424 return;
1427 for (prevconn = or_circ->resolving_streams;
1428 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1429 prevconn = prevconn->next_stream)
1431 if (prevconn && prevconn->next_stream) {
1432 prevconn->next_stream = conn->next_stream;
1433 return;
1437 log_warn(LD_BUG,"Edge connection not in circuit's list.");
1438 /* Don't give an error here; it's harmless. */
1439 tor_fragile_assert();
1442 /** Find each circuit that has been unused for too long, or dirty
1443 * for too long and has no streams on it: mark it for close.
1445 STATIC void
1446 circuit_expire_old_circuits_clientside(void)
1448 struct timeval cutoff, now;
1450 tor_gettimeofday(&now);
1451 last_expired_clientside_circuits = now.tv_sec;
1453 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1454 if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
1455 continue;
1457 cutoff = now;
1458 cutoff.tv_sec -= TO_ORIGIN_CIRCUIT(circ)->circuit_idle_timeout;
1460 /* If the circuit has been dirty for too long, and there are no streams
1461 * on it, mark it for close.
1463 if (circ->timestamp_dirty &&
1464 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
1465 now.tv_sec &&
1466 !connection_half_edges_waiting(TO_ORIGIN_CIRCUIT(circ)) &&
1467 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
1468 log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
1469 "purpose %d)",
1470 (unsigned)circ->n_circ_id,
1471 (long)(now.tv_sec - circ->timestamp_dirty),
1472 circ->purpose);
1473 /* Don't do this magic for testing circuits. Their death is governed
1474 * by circuit_expire_building */
1475 if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
1476 tor_trace(TR_SUBSYS(circuit), TR_EV(idle_timeout),
1477 TO_ORIGIN_CIRCUIT(circ));
1478 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1480 } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
1481 if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
1482 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
1483 circ->purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1484 circ->purpose == CIRCUIT_PURPOSE_CONFLUX_UNLINKED ||
1485 circ->purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED ||
1486 circ->purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1487 circ->purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1488 circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
1489 circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1490 circ->purpose == CIRCUIT_PURPOSE_TESTING ||
1491 circ->purpose == CIRCUIT_PURPOSE_C_CIRCUIT_PADDING ||
1492 (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
1493 circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
1494 circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
1495 log_info(LD_CIRC,
1496 "Closing circuit %"PRIu32
1497 " that has been unused for %ld msec.",
1498 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1499 tv_mdiff(&circ->timestamp_began, &now));
1500 tor_trace(TR_SUBSYS(circuit), TR_EV(idle_timeout),
1501 TO_ORIGIN_CIRCUIT(circ));
1502 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1503 } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
1504 /* Server-side rend joined circuits can end up really old, because
1505 * they are reused by clients for longer than normal. The client
1506 * controls their lifespan. (They never become dirty, because
1507 * connection_exit_begin_conn() never marks anything as dirty.)
1508 * Similarly, server-side intro circuits last a long time. */
1509 if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
1510 circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
1511 log_notice(LD_CIRC,
1512 "Ancient non-dirty circuit %d is still around after "
1513 "%ld milliseconds. Purpose: %d (%s)",
1514 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1515 tv_mdiff(&circ->timestamp_began, &now),
1516 circ->purpose,
1517 circuit_purpose_to_string(circ->purpose));
1518 TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
1523 } SMARTLIST_FOREACH_END(circ);
1526 /** How long do we wait before killing circuits with the properties
1527 * described below?
1529 * Probably we could choose a number here as low as 5 to 10 seconds,
1530 * since these circs are used for begindir, and a) generally you either
1531 * ask another begindir question right after or you don't for a long time,
1532 * b) clients at least through 0.2.1.x choose from the whole set of
1533 * directory mirrors at each choice, and c) re-establishing a one-hop
1534 * circuit via create-fast is a light operation assuming the TLS conn is
1535 * still there.
1537 * I expect "b" to go away one day when we move to using directory
1538 * guards, but I think "a" and "c" are good enough reasons that a low
1539 * number is safe even then.
1541 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
1543 /** Find each non-origin circuit that has been unused for too long,
1544 * has no streams on it, came from a client, and ends here: mark it
1545 * for close.
1547 void
1548 circuit_expire_old_circuits_serverside(time_t now)
1550 or_circuit_t *or_circ;
1551 time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
1553 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1554 if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
1555 continue;
1556 or_circ = TO_OR_CIRCUIT(circ);
1557 /* If the circuit has been idle for too long, and there are no streams
1558 * on it, and it ends here, and it used a create_fast, mark it for close.
1560 * Also if there is a rend_splice on it, it's a single onion service
1561 * circuit and we should not close it.
1563 if (or_circ->p_chan && channel_is_client(or_circ->p_chan) &&
1564 !circ->n_chan &&
1565 !or_circ->n_streams && !or_circ->resolving_streams &&
1566 !or_circ->rend_splice &&
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 !router_orport_seems_reachable(get_options(), AF_INET)) {
1625 /* either we've already done everything we want with testing circuits,
1626 * OR this IPv4 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 a
1628 * outgoing local circuit, OR this is an IPv6 self-test circuit, not
1629 * a bandwidth test circuit. */
1630 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
1631 } else if (circuit_enough_testing_circs()) {
1632 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
1633 have_performed_bandwidth_test = 1;
1634 } else {
1635 router_do_reachability_checks();
1639 /** A testing circuit has failed to build. Take whatever stats we want. */
1640 static void
1641 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
1643 const or_options_t *options = get_options();
1644 if (server_mode(options) &&
1645 router_all_orports_seem_reachable(options))
1646 return;
1648 log_info(LD_GENERAL,
1649 "Our testing circuit (to see if your ORPort is reachable) "
1650 "has failed. I'll try again later.");
1652 /* These aren't used yet. */
1653 (void)circ;
1654 (void)at_last_hop;
1657 /** The circuit <b>circ</b> has just become open. Take the next
1658 * step: for rendezvous circuits, we pass circ to the appropriate
1659 * function in rendclient or rendservice. For general circuits, we
1660 * call connection_ap_attach_pending, which looks for pending streams
1661 * that could use circ.
1663 void
1664 circuit_has_opened(origin_circuit_t *circ)
1666 tor_trace(TR_SUBSYS(circuit), TR_EV(opened), circ);
1667 circuit_event_status(circ, CIRC_EVENT_BUILT, 0);
1669 /* Remember that this circuit has finished building. Now if we start
1670 * it building again later (e.g. by extending it), we will know not
1671 * to consider its build time. */
1672 circ->has_opened = 1;
1674 switch (TO_CIRCUIT(circ)->purpose) {
1675 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1676 hs_client_circuit_has_opened(circ);
1677 /* Start building an intro circ if we don't have one yet. */
1678 connection_ap_attach_pending(1);
1679 /* This isn't a call to circuit_try_attaching_streams because a
1680 * circuit in _C_ESTABLISH_REND state isn't connected to its
1681 * hidden service yet, thus we can't attach streams to it yet,
1682 * thus circuit_try_attaching_streams would always clear the
1683 * circuit's isolation state. circuit_try_attaching_streams is
1684 * called later, when the rend circ enters _C_REND_JOINED
1685 * state. */
1686 break;
1687 case CIRCUIT_PURPOSE_C_INTRODUCING:
1688 hs_client_circuit_has_opened(circ);
1689 break;
1690 case CIRCUIT_PURPOSE_CONFLUX_UNLINKED:
1691 conflux_circuit_has_opened(circ);
1692 break;
1693 case CIRCUIT_PURPOSE_C_GENERAL:
1694 circuit_try_attaching_streams(circ);
1695 break;
1696 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1697 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1698 /* Tell any AP connections that have been waiting for a new
1699 * circuit that one is ready. */
1700 circuit_try_attaching_streams(circ);
1701 break;
1702 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1703 /* at the service, waiting for introductions */
1704 hs_service_circuit_has_opened(circ);
1705 break;
1706 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1707 /* at the service, connecting to rend point */
1708 hs_service_circuit_has_opened(circ);
1709 break;
1710 case CIRCUIT_PURPOSE_TESTING:
1711 circuit_testing_opened(circ);
1712 break;
1713 /* default:
1714 * This won't happen in normal operation, but might happen if the
1715 * controller did it. Just let it slide. */
1719 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
1720 * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
1721 static int
1722 circuit_try_clearing_isolation_state(origin_circuit_t *circ)
1724 if (/* The circuit may have become non-open if it was cannibalized.*/
1725 circ->base_.state == CIRCUIT_STATE_OPEN &&
1726 /* If !isolation_values_set, there is nothing to clear. */
1727 circ->isolation_values_set &&
1728 /* It's not legal to clear a circuit's isolation info if it's ever had
1729 * streams attached */
1730 !circ->isolation_any_streams_attached) {
1731 /* If we have any isolation information set on this circuit, and
1732 * we didn't manage to attach any streams to it, then we can
1733 * and should clear it and try again. */
1734 circuit_clear_isolation(circ);
1735 return 1;
1736 } else {
1737 return 0;
1741 /** Called when a circuit becomes ready for streams to be attached to
1742 * it. */
1743 void
1744 circuit_try_attaching_streams(origin_circuit_t *circ)
1746 /* Attach streams to this circuit if we can. */
1747 connection_ap_attach_pending(1);
1749 /* The call to circuit_try_clearing_isolation_state here will do
1750 * nothing and return 0 if we didn't attach any streams to circ
1751 * above. */
1752 if (circuit_try_clearing_isolation_state(circ)) {
1753 /* Maybe *now* we can attach some streams to this circuit. */
1754 connection_ap_attach_pending(1);
1758 /** Called whenever a circuit could not be successfully built.
1760 void
1761 circuit_build_failed(origin_circuit_t *circ)
1763 channel_t *n_chan = NULL;
1764 /* we should examine circ and see if it failed because of
1765 * the last hop or an earlier hop. then use this info below.
1767 int failed_at_last_hop = 0;
1769 /* First, check to see if this was a path failure, rather than build
1770 * failure.
1772 * Note that we deliberately use circuit_get_cpath_len() (and not
1773 * circuit_get_cpath_opened_len()) because we only want to ensure
1774 * that a full path is *chosen*. This is different than a full path
1775 * being *built*. We only want to count *build* failures below.
1777 * Path selection failures can happen spuriously for a number
1778 * of reasons (such as aggressive/invalid user-specified path
1779 * restrictions in the torrc, insufficient microdescriptors, and
1780 * non-user reasons like exitpolicy issues), and so should not be
1781 * counted as failures below.
1783 if (circuit_get_cpath_len(circ) < circ->build_state->desired_path_len) {
1784 static ratelim_t pathfail_limit = RATELIM_INIT(3600);
1785 log_fn_ratelim(&pathfail_limit, LOG_NOTICE, LD_CIRC,
1786 "Our circuit %u (id: %" PRIu32 ") died due to an invalid "
1787 "selected path, purpose %s. This may be a torrc "
1788 "configuration issue, or a bug.",
1789 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1790 circuit_purpose_to_string(TO_CIRCUIT(circ)->purpose));
1792 /* If the path failed on an RP, retry it. */
1793 if (TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
1794 hs_metrics_failed_rdv(&circ->hs_ident->identity_pk,
1795 HS_METRICS_ERR_RDV_PATH);
1796 hs_circ_retry_service_rendezvous_point(circ);
1799 /* In all other cases, just bail. The rest is just failure accounting
1800 * that we don't want to do */
1801 return;
1804 /* If the last hop isn't open, and the second-to-last is, we failed
1805 * at the last hop. */
1806 if (circ->cpath &&
1807 circ->cpath->prev->state != CPATH_STATE_OPEN &&
1808 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
1809 failed_at_last_hop = 1;
1812 /* Check if we failed at first hop */
1813 if (circ->cpath &&
1814 circ->cpath->state != CPATH_STATE_OPEN &&
1815 ! circ->base_.received_destroy) {
1816 /* We failed at the first hop for some reason other than a DESTROY cell.
1817 * If there's an OR connection to blame, blame it. Also, avoid this relay
1818 * for a while, and fail any one-hop directory fetches destined for it. */
1819 const char *n_chan_ident = circ->cpath->extend_info->identity_digest;
1820 tor_assert(n_chan_ident);
1821 int already_marked = 0;
1822 if (circ->base_.n_chan) {
1823 n_chan = circ->base_.n_chan;
1825 if (n_chan->is_bad_for_new_circs) {
1826 /* We only want to blame this router when a fresh healthy
1827 * connection fails. So don't mark this router as newly failed,
1828 * since maybe this was just an old circuit attempt that's
1829 * finally timing out now. Also, there's no need to blow away
1830 * circuits/streams/etc, since the failure of an unhealthy conn
1831 * doesn't tell us much about whether a healthy conn would
1832 * succeed. */
1833 already_marked = 1;
1835 log_info(LD_OR,
1836 "Our circuit %u (id: %" PRIu32 ") failed to get a response "
1837 "from the first hop (%s). I'm going to try to rotate to a "
1838 "better connection.",
1839 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1840 channel_describe_peer(n_chan));
1841 n_chan->is_bad_for_new_circs = 1;
1842 } else {
1843 log_info(LD_OR,
1844 "Our circuit %u (id: %" PRIu32 ") died before the first hop "
1845 "with no connection",
1846 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier);
1848 if (!already_marked) {
1850 * If we have guard state (new guard API) and our path selection
1851 * code actually chose a full path, then blame the failure of this
1852 * circuit on the guard.
1854 if (circ->guard_state)
1855 entry_guard_failed(&circ->guard_state);
1856 /* if there are any one-hop streams waiting on this circuit, fail
1857 * them now so they can retry elsewhere. */
1858 connection_ap_fail_onehop(n_chan_ident, circ->build_state);
1862 switch (circ->base_.purpose) {
1863 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1864 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1865 case CIRCUIT_PURPOSE_C_GENERAL:
1866 /* If we never built the circuit, note it as a failure. */
1867 circuit_increment_failure_count();
1868 if (failed_at_last_hop) {
1869 /* Make sure any streams that demand our last hop as their exit
1870 * know that it's unlikely to happen. */
1871 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
1873 break;
1874 case CIRCUIT_PURPOSE_TESTING:
1875 circuit_testing_failed(circ, failed_at_last_hop);
1876 break;
1877 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1878 /* at the service, waiting for introductions */
1879 if (circ->base_.state != CIRCUIT_STATE_OPEN) {
1880 circuit_increment_failure_count();
1882 /* no need to care here, because the service will rebuild intro
1883 * points periodically. */
1884 break;
1885 case CIRCUIT_PURPOSE_C_INTRODUCING:
1886 /* at the client, connecting to intro point */
1887 /* Don't increment failure count, since the service may have picked
1888 * the introduction point maliciously */
1889 /* The client will pick a new intro point when this one dies, if
1890 * the stream in question still cares. No need to act here. */
1891 break;
1892 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1893 /* at the client, waiting for the service */
1894 circuit_increment_failure_count();
1895 /* the client will pick a new rend point when this one dies, if
1896 * the stream in question still cares. No need to act here. */
1897 break;
1898 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1899 /* at the service, connecting to rend point */
1900 /* Don't increment failure count, since the client may have picked
1901 * the rendezvous point maliciously */
1902 log_info(LD_REND,
1903 "Couldn't connect to the client's chosen rend point %s "
1904 "(%s hop failed).",
1905 escaped(build_state_get_exit_nickname(circ->build_state)),
1906 failed_at_last_hop?"last":"non-last");
1908 hs_metrics_failed_rdv(&circ->hs_ident->identity_pk,
1909 HS_METRICS_ERR_RDV_RP_CONN_FAILURE);
1910 hs_circ_retry_service_rendezvous_point(circ);
1911 break;
1912 /* default:
1913 * This won't happen in normal operation, but might happen if the
1914 * controller did it. Just let it slide. */
1918 /** Number of consecutive failures so far; should only be touched by
1919 * circuit_launch_new and circuit_*_failure_count.
1921 static int n_circuit_failures = 0;
1922 /** Before the last time we called circuit_reset_failure_count(), were
1923 * there a lot of failures? */
1924 static int did_circs_fail_last_period = 0;
1926 /** Don't retry launching a new circuit if we try this many times with no
1927 * success. */
1928 #define MAX_CIRCUIT_FAILURES 5
1930 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1931 * details on arguments. */
1932 origin_circuit_t *
1933 circuit_launch(uint8_t purpose, int flags)
1935 return circuit_launch_by_extend_info(purpose, NULL, flags);
1938 /* Do we have enough descriptors to build paths?
1939 * If need_exit is true, return 1 if we can build exit paths.
1940 * (We need at least one Exit in the consensus to build exit paths.)
1941 * If need_exit is false, return 1 if we can build internal paths.
1943 static int
1944 have_enough_path_info(int need_exit)
1946 if (need_exit)
1947 return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
1948 else
1949 return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
1953 * Tell us if a circuit is a hidden service circuit.
1956 circuit_purpose_is_hidden_service(uint8_t purpose)
1958 /* HS Vanguard purpose. */
1959 if (circuit_purpose_is_hs_vanguards(purpose)) {
1960 return 1;
1963 /* Client-side purpose */
1964 if (circuit_purpose_is_hs_client(purpose)) {
1965 return 1;
1968 /* Service-side purpose */
1969 if (circuit_purpose_is_hs_service(purpose)) {
1970 return 1;
1973 return 0;
1976 /** Return true iff the given circuit is an HS client circuit. */
1977 bool
1978 circuit_purpose_is_hs_client(const uint8_t purpose)
1980 return (purpose >= CIRCUIT_PURPOSE_C_HS_MIN_ &&
1981 purpose <= CIRCUIT_PURPOSE_C_HS_MAX_);
1984 /** Return true iff the given circuit is an HS service circuit. */
1985 bool
1986 circuit_purpose_is_hs_service(const uint8_t purpose)
1988 return (purpose >= CIRCUIT_PURPOSE_S_HS_MIN_ &&
1989 purpose <= CIRCUIT_PURPOSE_S_HS_MAX_);
1992 /** Return true iff the given circuit is an HS Vanguards circuit. */
1993 bool
1994 circuit_purpose_is_hs_vanguards(const uint8_t purpose)
1996 return (purpose == CIRCUIT_PURPOSE_HS_VANGUARDS);
1999 /** Return true iff the given circuit is an HS v3 circuit. */
2000 bool
2001 circuit_is_hs_v3(const circuit_t *circ)
2003 return (CIRCUIT_IS_ORIGIN(circ) &&
2004 (CONST_TO_ORIGIN_CIRCUIT(circ)->hs_ident != NULL));
2008 * Return true if this circuit purpose should use vanguards
2009 * or pinned Layer2 or Layer3 guards.
2011 * This function takes both the circuit purpose and the
2012 * torrc options for pinned middles/vanguards into account
2013 * (ie: the circuit must be a hidden service circuit and
2014 * vanguards/pinned middles must be enabled for it to return
2015 * true).
2018 circuit_should_use_vanguards(uint8_t purpose)
2020 /* All hidden service circuits use either vanguards or
2021 * vanguards-lite. */
2022 if (circuit_purpose_is_hidden_service(purpose))
2023 return 1;
2025 /* Everything else is a normal circuit */
2026 return 0;
2030 * Return true for the set of conditions for which it is OK to use
2031 * a cannibalized circuit.
2033 * Don't cannibalize for onehops, or certain purposes.
2035 static int
2036 circuit_should_cannibalize_to_build(uint8_t purpose_to_build,
2037 int has_extend_info,
2038 int onehop_tunnel)
2041 /* Do not try to cannibalize if this is a one hop circuit. */
2042 if (onehop_tunnel) {
2043 return 0;
2046 /* Don't try to cannibalize for general purpose circuits that do not
2047 * specify a custom exit. */
2048 if (purpose_to_build == CIRCUIT_PURPOSE_C_GENERAL && !has_extend_info) {
2049 return 0;
2052 /* Don't cannibalize for testing circuits. We want to see if they
2053 * complete normally. Also don't cannibalize for vanguard-purpose
2054 * circuits, since those are specially pre-built for later
2055 * cannibalization by the actual specific circuit types that need
2056 * vanguards.
2058 if (purpose_to_build == CIRCUIT_PURPOSE_TESTING ||
2059 purpose_to_build == CIRCUIT_PURPOSE_HS_VANGUARDS) {
2060 return 0;
2063 /* The server-side intro circ is not cannibalized because it only
2064 * needs a 3 hop circuit. It is also long-lived, so it is more
2065 * important that it have lower latency than get built fast.
2067 if (purpose_to_build == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
2068 return 0;
2071 /* Do not cannibalize for conflux circuits */
2072 if (purpose_to_build == CIRCUIT_PURPOSE_CONFLUX_UNLINKED) {
2073 return 0;
2076 return 1;
2079 /** Launch a new circuit with purpose <b>purpose</b> and exit node
2080 * <b>extend_info</b> (or NULL to select a random exit node).
2082 * If flags contains:
2083 * - CIRCLAUNCH_ONEHOP_TUNNEL: the circuit will have only one hop;
2084 * - CIRCLAUNCH_NEED_UPTIME: choose routers with high uptime;
2085 * - CIRCLAUNCH_NEED_CAPACITY: choose routers with high bandwidth;
2086 * - CIRCLAUNCH_IS_IPV6_SELFTEST: the second-last hop must support IPv6
2087 * extends;
2088 * - CIRCLAUNCH_IS_INTERNAL: the last hop need not be an exit node;
2089 * - CIRCLAUNCH_IS_V3_RP: the last hop must support v3 onion service
2090 * rendezvous.
2092 * Return the newly allocated circuit on success, or NULL on failure. */
2093 origin_circuit_t *
2094 circuit_launch_by_extend_info(uint8_t purpose,
2095 extend_info_t *extend_info,
2096 int flags)
2098 origin_circuit_t *circ;
2099 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
2100 int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
2102 /* Keep some stats about our attempts to launch HS rendezvous circuits */
2103 if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
2104 hs_stats_note_service_rendezvous_launch();
2107 if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
2108 log_debug(LD_CIRC,"Haven't %s yet; canceling "
2109 "circuit launch.",
2110 !router_have_minimum_dir_info() ?
2111 "fetched enough directory info" :
2112 "received a consensus with exits");
2113 return NULL;
2116 /* If we can/should cannibalize another circuit to build this one,
2117 * then do so. */
2118 if (circuit_should_cannibalize_to_build(purpose,
2119 extend_info != NULL,
2120 onehop_tunnel)) {
2121 /* see if there are appropriate circs available to cannibalize. */
2122 /* XXX if we're planning to add a hop, perhaps we want to look for
2123 * internal circs rather than exit circs? -RD */
2124 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
2125 if (circ) {
2126 uint8_t old_purpose = circ->base_.purpose;
2127 struct timeval old_timestamp_began = circ->base_.timestamp_began;
2129 log_info(LD_CIRC, "Cannibalizing circ %u (id: %" PRIu32 ") for "
2130 "purpose %d (%s)",
2131 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier, purpose,
2132 circuit_purpose_to_string(purpose));
2134 if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2135 purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
2136 circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
2137 /* Path bias: Cannibalized rends pre-emptively count as a
2138 * successfully built but unused closed circuit. We don't
2139 * wait until the extend (or the close) because the rend
2140 * point could be malicious.
2142 * Same deal goes for client side introductions. Clients
2143 * can be manipulated to connect repeatedly to them
2144 * (especially web clients).
2146 * If we decide to probe the initial portion of these circs,
2147 * (up to the adversary's final hop), we need to remove this,
2148 * or somehow mark the circuit with a special path state.
2151 /* This must be called before the purpose change */
2152 pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
2155 circuit_change_purpose(TO_CIRCUIT(circ), purpose);
2156 /* Reset the start date of this circ, else expire_building
2157 * will see it and think it's been trying to build since it
2158 * began.
2160 * Technically, the code should reset this when the
2161 * create cell is finally sent, but we're close enough
2162 * here. */
2163 tor_gettimeofday(&circ->base_.timestamp_began);
2165 control_event_circuit_cannibalized(circ, old_purpose,
2166 &old_timestamp_began);
2168 switch (purpose) {
2169 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
2170 /* it's ready right now */
2171 break;
2172 case CIRCUIT_PURPOSE_C_INTRODUCING:
2173 case CIRCUIT_PURPOSE_S_CONNECT_REND:
2174 case CIRCUIT_PURPOSE_C_GENERAL:
2175 case CIRCUIT_PURPOSE_S_HSDIR_POST:
2176 case CIRCUIT_PURPOSE_C_HSDIR_GET:
2177 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
2178 /* need to add a new hop */
2179 tor_assert(extend_info);
2180 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
2181 return NULL;
2182 break;
2183 default:
2184 log_warn(LD_BUG,
2185 "unexpected purpose %d when cannibalizing a circ.",
2186 purpose);
2187 tor_fragile_assert();
2188 return NULL;
2191 tor_trace(TR_SUBSYS(circuit), TR_EV(cannibalized), circ);
2192 return circ;
2196 if (did_circs_fail_last_period &&
2197 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
2198 /* too many failed circs in a row. don't try. */
2199 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
2200 return NULL;
2203 /* try a circ. if it fails, circuit_mark_for_close will increment
2204 * n_circuit_failures */
2205 return circuit_establish_circuit(purpose, extend_info, flags);
2208 /** Record another failure at opening a general circuit. When we have
2209 * too many, we'll stop trying for the remainder of this minute.
2211 static void
2212 circuit_increment_failure_count(void)
2214 ++n_circuit_failures;
2215 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
2218 /** Reset the failure count for opening general circuits. This means
2219 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
2220 * stopping again.
2222 void
2223 circuit_reset_failure_count(int timeout)
2225 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
2226 did_circs_fail_last_period = 1;
2227 else
2228 did_circs_fail_last_period = 0;
2229 n_circuit_failures = 0;
2232 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
2233 * there isn't one, and there isn't one on the way, launch one and return
2234 * 0. If it will never work, return -1.
2236 * Write the found or in-progress or launched circ into *circp.
2238 static int
2239 circuit_get_open_circ_or_launch(entry_connection_t *conn,
2240 uint8_t desired_circuit_purpose,
2241 origin_circuit_t **circp)
2243 origin_circuit_t *circ;
2244 int check_exit_policy;
2245 int need_uptime, need_internal;
2246 int want_onehop;
2247 const or_options_t *options = get_options();
2249 tor_assert(conn);
2250 tor_assert(circp);
2251 if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2252 connection_t *c = ENTRY_TO_CONN(conn);
2253 log_err(LD_BUG, "Connection state mismatch: wanted "
2254 "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
2255 c->state, conn_state_to_string(c->type, c->state));
2257 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
2259 /* Will the exit policy of the exit node apply to this stream? */
2260 check_exit_policy =
2261 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2262 !conn->use_begindir &&
2263 !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
2265 /* Does this connection want a one-hop circuit? */
2266 want_onehop = conn->want_onehop;
2268 /* Do we need a high-uptime circuit? */
2269 need_uptime = !conn->want_onehop && !conn->use_begindir &&
2270 smartlist_contains_int_as_string(options->LongLivedPorts,
2271 conn->socks_request->port);
2273 /* Do we need an "internal" circuit? */
2274 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
2275 need_internal = 1;
2276 else if (conn->use_begindir || conn->want_onehop)
2277 need_internal = 1;
2278 else
2279 need_internal = 0;
2281 /* We now know what kind of circuit we need. See if there is an
2282 * open circuit that we can use for this stream */
2283 circ = circuit_get_best(conn, 1 /* Insist on open circuits */,
2284 desired_circuit_purpose,
2285 need_uptime, need_internal);
2287 if (circ) {
2288 /* We got a circuit that will work for this stream! We can return it. */
2289 *circp = circ;
2290 return 1; /* we're happy */
2293 /* Okay, there's no circuit open that will work for this stream. Let's
2294 * see if there's an in-progress circuit or if we have to launch one */
2296 /* Do we know enough directory info to build circuits at all? */
2297 int have_path = have_enough_path_info(!need_internal);
2299 if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
2300 /* If we don't have enough directory information, we can't build
2301 * multihop circuits.
2303 if (!connection_get_by_type(CONN_TYPE_DIR)) {
2304 int severity = LOG_NOTICE;
2305 /* Retry some stuff that might help the connection work. */
2306 /* If we are configured with EntryNodes or UseBridges */
2307 if (entry_list_is_constrained(options)) {
2308 /* Retry all our guards / bridges.
2309 * guards_retry_optimistic() always returns true here. */
2310 int rv = guards_retry_optimistic(options);
2311 tor_assert_nonfatal_once(rv);
2312 log_fn(severity, LD_APP|LD_DIR,
2313 "Application request when we haven't %s. "
2314 "Optimistically trying known %s again.",
2315 !router_have_minimum_dir_info() ?
2316 "used client functionality lately" :
2317 "received a consensus with exits",
2318 options->UseBridges ? "bridges" : "entrynodes");
2319 } else {
2320 /* Getting directory documents doesn't help much if we have a limited
2321 * number of guards */
2322 tor_assert_nonfatal(!options->UseBridges);
2323 tor_assert_nonfatal(!options->EntryNodes);
2324 /* Retry our directory fetches, so we have a fresh set of guard info */
2325 log_fn(severity, LD_APP|LD_DIR,
2326 "Application request when we haven't %s. "
2327 "Optimistically trying directory fetches again.",
2328 !router_have_minimum_dir_info() ?
2329 "used client functionality lately" :
2330 "received a consensus with exits");
2331 routerlist_retry_directory_downloads(time(NULL));
2334 /* Since we didn't have enough directory info, we can't attach now. The
2335 * stream will be dealt with when router_have_minimum_dir_info becomes 1,
2336 * or when all directory attempts fail and directory_all_unreachable()
2337 * kills it.
2339 return 0;
2342 /* Check whether the exit policy of the chosen exit, or the exit policies
2343 * of _all_ nodes, would forbid this node. */
2344 if (check_exit_policy) {
2345 if (!conn->chosen_exit_name) {
2346 struct in_addr in;
2347 tor_addr_t addr, *addrp=NULL;
2348 if (tor_inet_aton(conn->socks_request->address, &in)) {
2349 tor_addr_from_in(&addr, &in);
2350 addrp = &addr;
2352 if (router_exit_policy_all_nodes_reject(addrp,
2353 conn->socks_request->port,
2354 need_uptime)) {
2355 log_notice(LD_APP,
2356 "No Tor server allows exit to %s:%d. Rejecting.",
2357 safe_str_client(conn->socks_request->address),
2358 conn->socks_request->port);
2359 return -1;
2361 } else {
2362 /* XXXX Duplicates checks in connection_ap_handshake_attach_circuit:
2363 * refactor into a single function. */
2364 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2365 int opt = conn->chosen_exit_optional;
2366 if (node && !connection_ap_can_use_exit(conn, node)) {
2367 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2368 "Requested exit point '%s' is excluded or "
2369 "would refuse request. %s.",
2370 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2371 if (opt) {
2372 conn->chosen_exit_optional = 0;
2373 tor_free(conn->chosen_exit_name);
2374 /* Try again. */
2375 return circuit_get_open_circ_or_launch(conn,
2376 desired_circuit_purpose,
2377 circp);
2379 return -1;
2384 /* Now, check whether there already a circuit on the way that could handle
2385 * this stream. This check matches the one above, but this time we
2386 * do not require that the circuit will work. */
2387 circ = circuit_get_best(conn, 0 /* don't insist on open circuits */,
2388 desired_circuit_purpose,
2389 need_uptime, need_internal);
2390 if (circ)
2391 log_debug(LD_CIRC, "one on the way!");
2393 if (!circ) {
2394 /* No open or in-progress circuit could handle this stream! We
2395 * will have to launch one!
2398 /* The chosen exit node, if there is one. */
2399 extend_info_t *extend_info=NULL;
2400 const int n_pending = count_pending_general_client_circuits();
2402 /* Do we have too many pending circuits? */
2403 if (n_pending >= options->MaxClientCircuitsPending) {
2404 static ratelim_t delay_limit = RATELIM_INIT(10*60);
2405 char *m;
2406 if ((m = rate_limit_log(&delay_limit, approx_time()))) {
2407 log_notice(LD_APP, "We'd like to launch a circuit to handle a "
2408 "connection, but we already have %d general-purpose client "
2409 "circuits pending. Waiting until some finish.%s",
2410 n_pending, m);
2411 tor_free(m);
2413 return 0;
2416 /* If this is a hidden service trying to start an introduction point,
2417 * handle that case. */
2418 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
2419 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2420 /* need to pick an intro point */
2421 extend_info = hs_client_get_random_intro_from_edge(edge_conn);
2422 if (!extend_info) {
2423 log_info(LD_REND, "No intro points: re-fetching service descriptor.");
2424 hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
2425 connection_ap_mark_as_waiting_for_renddesc(conn);
2426 return 0;
2428 log_info(LD_REND,"Chose %s as intro point for service",
2429 extend_info_describe(extend_info));
2432 /* If we have specified a particular exit node for our
2433 * connection, then be sure to open a circuit to that exit node.
2435 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2436 desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2437 desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
2438 if (conn->chosen_exit_name) {
2439 const node_t *r;
2440 int opt = conn->chosen_exit_optional;
2441 r = node_get_by_nickname(conn->chosen_exit_name, 0);
2442 if (r && node_has_preferred_descriptor(r, conn->want_onehop ? 1 : 0)) {
2443 /* We might want to connect to an IPv6 bridge for loading
2444 descriptors so we use the preferred address rather than
2445 the primary. */
2446 extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0,
2447 desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL);
2448 if (!extend_info) {
2449 log_warn(LD_CIRC,"Could not make a one-hop connection to %s. "
2450 "Discarding this circuit.", conn->chosen_exit_name);
2451 return -1;
2453 } else { /* ! (r && node_has_preferred_descriptor(...)) */
2454 log_debug(LD_DIR, "considering %d, %s",
2455 want_onehop, conn->chosen_exit_name);
2456 if (want_onehop && conn->chosen_exit_name[0] == '$') {
2457 /* We're asking for a one-hop circuit to a router that
2458 * we don't have a routerinfo about. Make up an extend_info. */
2459 /* XXX prop220: we need to make chosen_exit_name able to
2460 * encode both key formats. This is not absolutely critical
2461 * since this is just for one-hop circuits, but we should
2462 * still get it done */
2463 char digest[DIGEST_LEN];
2464 char *hexdigest = conn->chosen_exit_name+1;
2465 tor_addr_t addr;
2466 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2467 base16_decode(digest,DIGEST_LEN,
2468 hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN) {
2469 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
2470 return -1;
2472 if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
2473 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
2474 escaped_safe_str_client(conn->socks_request->address));
2475 return -1;
2477 /* XXXX prop220 add a workaround for ed25519 ID below*/
2478 extend_info = extend_info_new(conn->chosen_exit_name+1,
2479 digest,
2480 NULL, /* Ed25519 ID */
2481 NULL, /* onion keys */
2482 &addr, conn->socks_request->port,
2483 NULL,
2484 false);
2485 } else { /* ! (want_onehop && conn->chosen_exit_name[0] == '$') */
2486 /* We will need an onion key for the router, and we
2487 * don't have one. Refuse or relax requirements. */
2488 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2489 "Requested exit point '%s' is not known. %s.",
2490 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2491 if (opt) {
2492 conn->chosen_exit_optional = 0;
2493 tor_free(conn->chosen_exit_name);
2494 /* Try again with no requested exit */
2495 return circuit_get_open_circ_or_launch(conn,
2496 desired_circuit_purpose,
2497 circp);
2499 return -1;
2503 } /* Done checking for general circutis with chosen exits. */
2505 /* What purpose do we need to launch this circuit with? */
2506 uint8_t new_circ_purpose;
2507 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
2508 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
2509 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
2510 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
2511 else
2512 new_circ_purpose = desired_circuit_purpose;
2514 /* Determine what kind of a circuit to launch, and actually launch it. */
2516 int flags = CIRCLAUNCH_NEED_CAPACITY;
2517 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
2518 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2519 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
2521 /* If we are about to pick a v3 RP right now, make sure we pick a
2522 * rendezvous point that supports the v3 protocol! */
2523 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED &&
2524 new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2525 ENTRY_TO_EDGE_CONN(conn)->hs_ident) {
2526 flags |= CIRCLAUNCH_IS_V3_RP;
2527 log_info(LD_GENERAL, "Getting rendezvous circuit to v3 service!");
2530 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
2531 flags);
2534 extend_info_free(extend_info);
2536 /* Now trigger things that need to happen when we launch circuits */
2538 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2539 desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2540 desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST) {
2541 /* We just caused a circuit to get built because of this stream.
2542 * If this stream has caused a _lot_ of circuits to be built, that's
2543 * a bad sign: we should tell the user. */
2544 if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
2545 ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
2546 log_info(LD_CIRC, "The application request to %s:%d has launched "
2547 "%d circuits without finding one it likes.",
2548 escaped_safe_str_client(conn->socks_request->address),
2549 conn->socks_request->port,
2550 conn->num_circuits_launched);
2551 } else {
2552 /* help predict this next time */
2553 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
2554 if (circ) {
2555 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2556 if (edge_conn->hs_ident) {
2557 circ->hs_ident =
2558 hs_ident_circuit_new(&edge_conn->hs_ident->identity_pk);
2560 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
2561 if (hs_client_setup_intro_circ_auth_key(circ) < 0) {
2562 return 0;
2565 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2566 circ->base_.state == CIRCUIT_STATE_OPEN)
2567 circuit_has_opened(circ);
2570 } /* endif (!circ) */
2572 /* We either found a good circuit, or launched a new circuit, or failed to
2573 * do so. Report success, and delay. */
2575 if (circ) {
2576 /* Mark the circuit with the isolation fields for this connection.
2577 * When the circuit arrives, we'll clear these flags: this is
2578 * just some internal bookkeeping to make sure that we have
2579 * launched enough circuits.
2581 connection_edge_update_circuit_isolation(conn, circ, 0);
2582 } else {
2583 log_info(LD_APP,
2584 "No safe circuit (purpose %d) ready for edge "
2585 "connection; delaying.",
2586 desired_circuit_purpose);
2588 *circp = circ;
2589 return 0;
2592 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
2593 * <b>circ</b>.
2595 * WARNING: This function only validates that the cpath is on the *current*
2596 * circuit, for internal consistency checking. For codepaths involving streams,
2597 * or cpaths or layer_hints that could be from a different circuit due to
2598 * conflux, use edge_uses_cpath() or conflux_validate_source_hop() instead.
2600 static int
2601 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
2603 crypt_path_t *cpath, *cpath_next = NULL;
2604 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2605 cpath_next = cpath->next;
2606 if (crypt_path == cpath)
2607 return 1;
2609 return 0;
2612 /** Attach the AP stream <b>apconn</b> to circ's linked list of
2613 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
2614 * hop in circ's cpath if <b>cpath</b> is NULL.
2616 static void
2617 link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
2618 crypt_path_t *cpath)
2620 const node_t *exitnode = NULL;
2622 /* add it into the linked list of streams on this circuit */
2623 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
2624 (unsigned)circ->base_.n_circ_id);
2626 /* If this is the first stream on this circuit, tell circpad
2627 * that streams are attached */
2628 if (!circ->p_streams)
2629 circpad_machine_event_circ_has_streams(circ);
2631 /* reset it, so we can measure circ timeouts */
2632 ENTRY_TO_CONN(apconn)->timestamp_last_read_allowed = time(NULL);
2633 ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
2634 ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
2635 /* assert_connection_ok(conn, time(NULL)); */
2636 circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
2637 conflux_update_p_streams(circ, ENTRY_TO_EDGE_CONN(apconn));
2639 if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
2640 /* We are attaching a stream to a rendezvous circuit. That means
2641 * that an attempt to connect to a hidden service just
2642 * succeeded. Tell rendclient.c. */
2643 hs_client_note_connection_attempt_succeeded(ENTRY_TO_EDGE_CONN(apconn));
2646 if (cpath) { /* we were given one; use it */
2647 tor_assert(cpath_is_on_circuit(circ, cpath));
2648 } else {
2649 /* use the last hop in the circuit */
2650 tor_assert(circ->cpath);
2651 tor_assert(circ->cpath->prev);
2652 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
2653 cpath = circ->cpath->prev;
2655 ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
2657 circ->isolation_any_streams_attached = 1;
2658 connection_edge_update_circuit_isolation(apconn, circ, 0);
2660 /* Compute the exitnode if possible, for logging below */
2661 if (cpath->extend_info)
2662 exitnode = node_get_by_id(cpath->extend_info->identity_digest);
2664 /* See if we can use optimistic data on this circuit */
2665 // TODO-329-PURPOSE: Can conflux use optimistic data? Does
2666 // anything use optimistic data? Does anything use this?
2667 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2668 circ->base_.purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2669 circ->base_.purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2670 circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
2671 apconn->may_use_optimistic_data = 1;
2672 else
2673 apconn->may_use_optimistic_data = 0;
2674 log_info(LD_APP, "Looks like completed circuit to %s %s allow "
2675 "optimistic data for connection to %s",
2676 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2677 circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) ?
2678 /* node_describe() does the right thing if exitnode is NULL */
2679 safe_str_client(node_describe(exitnode)) :
2680 "hidden service",
2681 apconn->may_use_optimistic_data ? "does" : "doesn't",
2682 safe_str_client(apconn->socks_request->address));
2685 /** Return true iff <b>address</b> is matched by one of the entries in
2686 * TrackHostExits. */
2688 hostname_in_track_host_exits(const or_options_t *options, const char *address)
2690 if (!options->TrackHostExits)
2691 return 0;
2692 SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
2693 if (cp[0] == '.') { /* match end */
2694 if (cp[1] == '\0' ||
2695 !strcasecmpend(address, cp) ||
2696 !strcasecmp(address, &cp[1]))
2697 return 1;
2698 } else if (strcasecmp(cp, address) == 0) {
2699 return 1;
2701 } SMARTLIST_FOREACH_END(cp);
2702 return 0;
2705 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
2706 * the exit that we *did* choose for use by future connections to
2707 * <b>conn</b>'s destination.
2709 static void
2710 consider_recording_trackhost(const entry_connection_t *conn,
2711 const origin_circuit_t *circ)
2713 const or_options_t *options = get_options();
2714 char *new_address = NULL;
2715 char fp[HEX_DIGEST_LEN+1];
2716 uint64_t stream_id = 0;
2718 if (BUG(!conn)) {
2719 return;
2722 stream_id = ENTRY_TO_CONN(conn)->global_identifier;
2724 /* Search the addressmap for this conn's destination. */
2725 /* If they're not in the address map.. */
2726 if (!options->TrackHostExits ||
2727 addressmap_have_mapping(conn->socks_request->address,
2728 options->TrackHostExitsExpire))
2729 return; /* nothing to track, or already mapped */
2731 if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
2732 !circ->build_state->chosen_exit)
2733 return;
2735 /* write down the fingerprint of the chosen exit, not the nickname,
2736 * because the chosen exit might not be named. */
2737 base16_encode(fp, sizeof(fp),
2738 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
2740 /* Add this exit/hostname pair to the addressmap. */
2741 tor_asprintf(&new_address, "%s.%s.exit",
2742 conn->socks_request->address, fp);
2744 addressmap_register(conn->socks_request->address, new_address,
2745 time(NULL) + options->TrackHostExitsExpire,
2746 ADDRMAPSRC_TRACKEXIT, 0, 0, stream_id);
2749 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
2750 * begin or resolve cell as appropriate. Return values are as for
2751 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
2752 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2753 * <b>cpath</b> is NULL. */
2755 connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
2756 origin_circuit_t *circ,
2757 crypt_path_t *cpath)
2759 connection_t *base_conn = ENTRY_TO_CONN(conn);
2760 tor_assert(conn);
2761 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
2762 base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
2763 tor_assert(conn->socks_request);
2764 tor_assert(circ);
2765 tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
2767 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2769 if (!circ->base_.timestamp_dirty ||
2770 ((conn->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
2771 (conn->entry_cfg.socks_iso_keep_alive) &&
2772 (conn->socks_request->usernamelen ||
2773 conn->socks_request->passwordlen))) {
2774 /* When stream isolation is in use and controlled by an application
2775 * we are willing to keep using the stream. */
2776 circ->base_.timestamp_dirty = approx_time();
2777 if (TO_CIRCUIT(circ)->conflux) {
2778 conflux_sync_circ_fields(TO_CIRCUIT(circ)->conflux, circ);
2782 pathbias_count_use_attempt(circ);
2784 /* Now, actually link the connection. */
2785 link_apconn_to_circ(conn, circ, cpath);
2787 tor_assert(conn->socks_request);
2788 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
2789 if (!conn->use_begindir) {
2790 consider_recording_trackhost(conn, circ);
2792 if (connection_ap_handshake_send_begin(conn) < 0)
2793 return -1;
2794 } else {
2795 if (connection_ap_handshake_send_resolve(conn) < 0)
2796 return -1;
2799 return 1;
2803 * Return an appropriate circuit purpose for non-rend streams.
2804 * We don't handle rends here because a rend stream triggers two
2805 * circuit builds with different purposes, so it is handled elsewhere.
2807 * This function just figures out what type of hsdir activity this is,
2808 * and tells us. Everything else is general.
2810 static int
2811 connection_ap_get_nonrend_circ_purpose(const entry_connection_t *conn)
2813 const connection_t *base_conn = ENTRY_TO_CONN(conn);
2814 tor_assert_nonfatal(!connection_edge_is_rendezvous_stream(
2815 ENTRY_TO_EDGE_CONN(conn)));
2817 if (base_conn->linked_conn &&
2818 base_conn->linked_conn->type == CONN_TYPE_DIR) {
2819 /* Set a custom purpose for hsdir activity */
2820 if (base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_HSDESC) {
2821 return CIRCUIT_PURPOSE_S_HSDIR_POST;
2822 } else if (base_conn->linked_conn->purpose == DIR_PURPOSE_FETCH_HSDESC) {
2823 return CIRCUIT_PURPOSE_C_HSDIR_GET;
2827 /* All other purposes are general for now */
2828 return CIRCUIT_PURPOSE_C_GENERAL;
2831 /** Try to find a safe live circuit for stream <b>conn</b>. If we find one,
2832 * attach the stream, send appropriate cells, and return 1. Otherwise,
2833 * try to launch new circuit(s) for the stream. If we can launch
2834 * circuits, return 0. Otherwise, if we simply can't proceed with
2835 * this stream, return -1. (conn needs to die, and is maybe already marked).
2837 /* XXXX this function should mark for close whenever it returns -1;
2838 * its callers shouldn't have to worry about that. */
2840 connection_ap_handshake_attach_circuit(entry_connection_t *conn)
2842 connection_t *base_conn = ENTRY_TO_CONN(conn);
2843 int retval;
2844 int conn_age;
2845 int want_onehop;
2847 tor_assert(conn);
2848 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2849 tor_assert(conn->socks_request);
2850 want_onehop = conn->want_onehop;
2852 conn_age = (int)(time(NULL) - base_conn->timestamp_created);
2854 /* Is this connection so old that we should give up on it? Don't timeout if
2855 * this is a connection to an HS with PoW enabled because it can take an
2856 * arbitrary amount of time. */
2857 if (conn_age >= get_options()->SocksTimeout && !conn->hs_with_pow_conn) {
2858 int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
2859 LOG_INFO : LOG_NOTICE;
2860 log_fn(severity, LD_APP,
2861 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
2862 conn_age, safe_str_client(conn->socks_request->address),
2863 conn->socks_request->port);
2864 return -1;
2867 /* We handle "general" (non-onion) connections much more straightforwardly.
2869 if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
2870 /* we're a general conn */
2871 origin_circuit_t *circ=NULL;
2873 /* Are we linked to a dir conn that aims to fetch a consensus?
2874 * We check here because the conn might no longer be needed. */
2875 if (base_conn->linked_conn &&
2876 base_conn->linked_conn->type == CONN_TYPE_DIR &&
2877 base_conn->linked_conn->purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
2879 /* Yes we are. Is there a consensus fetch farther along than us? */
2880 if (networkstatus_consensus_is_already_downloading(
2881 TO_DIR_CONN(base_conn->linked_conn)->requested_resource)) {
2882 /* We're doing the "multiple consensus fetch attempts" game from
2883 * proposal 210, and we're late to the party. Just close this conn.
2884 * The circuit and TLS conn that we made will time out after a while
2885 * if nothing else wants to use them. */
2886 log_info(LD_DIR, "Closing extra consensus fetch (to %s) since one "
2887 "is already downloading.", base_conn->linked_conn->address);
2888 return -1;
2892 /* If we have a chosen exit, we need to use a circuit that's
2893 * open to that exit. See what exit we meant, and whether we can use it.
2895 if (conn->chosen_exit_name) {
2896 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2897 int opt = conn->chosen_exit_optional;
2898 if (!node && !want_onehop) {
2899 /* We ran into this warning when trying to extend a circuit to a
2900 * hidden service directory for which we didn't have a router
2901 * descriptor. See flyspray task 767 for more details. We should
2902 * keep this in mind when deciding to use BEGIN_DIR cells for other
2903 * directory requests as well. -KL*/
2904 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2905 "Requested exit point '%s' is not known. %s.",
2906 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2907 if (opt) {
2908 /* If we are allowed to ignore the .exit request, do so */
2909 conn->chosen_exit_optional = 0;
2910 tor_free(conn->chosen_exit_name);
2911 return 0;
2913 return -1;
2915 if (node && !connection_ap_can_use_exit(conn, node)) {
2916 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2917 "Requested exit point '%s' is excluded or "
2918 "would refuse request. %s.",
2919 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2920 if (opt) {
2921 /* If we are allowed to ignore the .exit request, do so */
2922 conn->chosen_exit_optional = 0;
2923 tor_free(conn->chosen_exit_name);
2924 return 0;
2926 return -1;
2930 /* Find the circuit that we should use, if there is one. Otherwise
2931 * launch it
2933 retval = circuit_get_open_circ_or_launch(conn,
2934 connection_ap_get_nonrend_circ_purpose(conn),
2935 &circ);
2937 if (retval < 1) {
2938 /* We were either told "-1" (complete failure) or 0 (circuit in
2939 * progress); we can't attach this stream yet. */
2940 return retval;
2943 log_debug(LD_APP|LD_CIRC,
2944 "Attaching apconn to circ %u (stream %d sec old).",
2945 (unsigned)circ->base_.n_circ_id, conn_age);
2946 /* print the circ's path, so clients can figure out which circs are
2947 * sucking. */
2948 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
2950 /* We have found a suitable circuit for our conn. Hurray. Do
2951 * the attachment. */
2952 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
2954 } else { /* we're a rendezvous conn */
2955 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
2957 tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
2959 /* start by finding a rendezvous circuit for us */
2961 retval = circuit_get_open_circ_or_launch(
2962 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
2963 if (retval < 0) return -1; /* failed */
2965 if (retval > 0) {
2966 tor_assert(rendcirc);
2967 /* one is already established, attach */
2968 log_info(LD_REND,
2969 "rend joined circ %u (id: %" PRIu32 ") already here. "
2970 "Attaching. (stream %d sec old)",
2971 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2972 rendcirc->global_identifier, conn_age);
2973 /* Mark rendezvous circuits as 'newly dirty' every time you use
2974 * them, since the process of rebuilding a rendezvous circ is so
2975 * expensive. There is a tradeoff between linkability and
2976 * feasibility, at this point.
2978 rendcirc->base_.timestamp_dirty = time(NULL);
2980 /* We've also attempted to use them. If they fail, we need to
2981 * probe them for path bias */
2982 pathbias_count_use_attempt(rendcirc);
2984 link_apconn_to_circ(conn, rendcirc, NULL);
2985 if (connection_ap_handshake_send_begin(conn) < 0)
2986 return 0; /* already marked, let them fade away */
2987 return 1;
2990 /* At this point we need to re-check the state, since it's possible that
2991 * our call to circuit_get_open_circ_or_launch() changed the connection's
2992 * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
2993 * re-fetch the descriptor.
2995 if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2996 log_info(LD_REND, "This connection is no longer ready to attach; its "
2997 "state changed."
2998 "(We probably have to re-fetch its descriptor.)");
2999 return 0;
3002 if (rendcirc && (rendcirc->base_.purpose ==
3003 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
3004 log_info(LD_REND,
3005 "pending-join circ %u (id: %" PRIu32 ") already here, with "
3006 "intro ack. Stalling. (stream %d sec old)",
3007 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
3008 rendcirc->global_identifier, conn_age);
3009 return 0;
3012 /* it's on its way. find an intro circ. */
3013 retval = circuit_get_open_circ_or_launch(
3014 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
3015 if (retval < 0) return -1; /* failed */
3017 if (rendcirc && introcirc) {
3018 /* Let's fill out the hs_ident fully as soon as possible, so that
3019 * unreachability counts can be updated properly even if circuits close
3020 * early. */
3021 tor_assert_nonfatal(!ed25519_public_key_is_zero(
3022 &introcirc->hs_ident->intro_auth_pk));
3023 ed25519_pubkey_copy(&rendcirc->hs_ident->intro_auth_pk,
3024 &introcirc->hs_ident->intro_auth_pk);
3027 if (retval > 0) {
3028 /* one has already sent the intro. keep waiting. */
3029 tor_assert(introcirc);
3030 log_info(LD_REND, "Intro circ %u (id: %" PRIu32 ") present and "
3031 "awaiting ACK. Rend circuit %u (id: %" PRIu32 "). "
3032 "Stalling. (stream %d sec old)",
3033 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
3034 introcirc->global_identifier,
3035 rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
3036 rendcirc ? rendcirc->global_identifier : 0,
3037 conn_age);
3038 return 0;
3041 /* now rendcirc and introcirc are each either undefined or not finished */
3043 if (rendcirc && introcirc &&
3044 rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
3045 log_info(LD_REND,
3046 "ready rend circ %u (id: %" PRIu32 ") already here. No"
3047 "intro-ack yet on intro %u (id: %" PRIu32 "). "
3048 "(stream %d sec old)",
3049 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
3050 rendcirc->global_identifier,
3051 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
3052 introcirc->global_identifier, conn_age);
3054 tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
3055 if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
3056 int ret;
3057 log_info(LD_REND, "Found open intro circ %u (id: %" PRIu32 "). "
3058 "Rend circuit %u (id: %" PRIu32 "); Considering "
3059 "sending introduction. (stream %d sec old)",
3060 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
3061 introcirc->global_identifier,
3062 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
3063 rendcirc->global_identifier, conn_age);
3064 ret = hs_client_send_introduce1(introcirc, rendcirc);
3065 switch (ret) {
3066 case 0: /* success */
3067 rendcirc->base_.timestamp_dirty = time(NULL);
3068 introcirc->base_.timestamp_dirty = time(NULL);
3070 pathbias_count_use_attempt(introcirc);
3071 pathbias_count_use_attempt(rendcirc);
3073 assert_circuit_ok(TO_CIRCUIT(rendcirc));
3074 assert_circuit_ok(TO_CIRCUIT(introcirc));
3075 return 0;
3076 case -1: /* transient error */
3077 return 0;
3078 case -2: /* permanent error */
3079 return -1;
3080 default: /* oops */
3081 tor_fragile_assert();
3082 return -1;
3087 log_info(LD_REND, "Intro %u (id: %" PRIu32 ") and rend circuit %u "
3088 "(id: %" PRIu32 ") circuits are not both ready. "
3089 "Stalling conn. (%d sec old)",
3090 introcirc ? (unsigned) TO_CIRCUIT(introcirc)->n_circ_id : 0,
3091 introcirc ? introcirc->global_identifier : 0,
3092 rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
3093 rendcirc ? rendcirc->global_identifier : 0, conn_age);
3094 return 0;
3098 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
3099 void
3100 circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
3102 uint8_t old_purpose;
3103 /* Don't allow an OR circ to become an origin circ or vice versa. */
3104 tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
3105 !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
3107 if (circ->purpose == new_purpose) return;
3109 /* If this is a conflux circuit, a purpose change means we have closed */
3110 if (CIRCUIT_IS_CONFLUX(circ)) {
3111 /* If we're not transitioning to the linked purpose, we're closed. */
3112 if (new_purpose != CIRCUIT_PURPOSE_CONFLUX_LINKED)
3113 conflux_circuit_has_closed(circ);
3116 if (CIRCUIT_IS_ORIGIN(circ)) {
3117 char old_purpose_desc[80] = "";
3119 strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
3120 old_purpose_desc[80-1] = '\0';
3122 log_debug(LD_CIRC,
3123 "changing purpose of origin circ %d "
3124 "from \"%s\" (%d) to \"%s\" (%d)",
3125 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
3126 old_purpose_desc,
3127 circ->purpose,
3128 circuit_purpose_to_string(new_purpose),
3129 new_purpose);
3131 /* Take specific actions if we are repurposing a hidden service circuit. */
3132 if (circuit_purpose_is_hidden_service(circ->purpose) &&
3133 !circuit_purpose_is_hidden_service(new_purpose)) {
3134 hs_circ_cleanup_on_repurpose(circ);
3138 old_purpose = circ->purpose;
3139 circ->purpose = new_purpose;
3140 tor_trace(TR_SUBSYS(circuit), TR_EV(change_purpose), circ, old_purpose,
3141 new_purpose);
3143 if (CIRCUIT_IS_ORIGIN(circ)) {
3144 control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
3145 old_purpose);
3147 circpad_machine_event_circ_purpose_changed(TO_ORIGIN_CIRCUIT(circ));
3151 /** Mark <b>circ</b> so that no more connections can be attached to it. */
3152 void
3153 mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
3155 const or_options_t *options = get_options();
3156 tor_assert(circ);
3158 /* XXXX This is a kludge; we're only keeping it around in case there's
3159 * something that doesn't check unusable_for_new_conns, and to avoid
3160 * deeper refactoring of our expiration logic. */
3161 if (! circ->base_.timestamp_dirty)
3162 circ->base_.timestamp_dirty = approx_time();
3163 if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
3164 circ->base_.timestamp_dirty = 1; /* prevent underflow */
3165 else
3166 circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
3168 circ->unusable_for_new_conns = 1;
3170 if (TO_CIRCUIT(circ)->conflux) {
3171 conflux_sync_circ_fields(TO_CIRCUIT(circ)->conflux, circ);
3176 * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
3177 * the valid delivered written fields and the overhead field,
3178 * respectively.
3180 void
3181 circuit_sent_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
3183 if (!circ) return;
3185 tor_assertf_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE,
3186 "Wrong relay_body_len: %d (should be at most %d)",
3187 relay_body_len, RELAY_PAYLOAD_SIZE);
3189 circ->n_delivered_written_circ_bw =
3190 tor_add_u32_nowrap(circ->n_delivered_written_circ_bw, relay_body_len);
3191 circ->n_overhead_written_circ_bw =
3192 tor_add_u32_nowrap(circ->n_overhead_written_circ_bw,
3193 RELAY_PAYLOAD_SIZE-relay_body_len);
3197 * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
3198 * the valid delivered read field and the overhead field,
3199 * respectively.
3201 void
3202 circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
3204 if (!circ) return;
3206 tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE);
3208 circ->n_delivered_read_circ_bw =
3209 tor_add_u32_nowrap(circ->n_delivered_read_circ_bw, relay_body_len);
3210 circ->n_overhead_read_circ_bw =
3211 tor_add_u32_nowrap(circ->n_overhead_read_circ_bw,
3212 RELAY_PAYLOAD_SIZE-relay_body_len);