Move the predicted ports code out of rephist.c
[tor.git] / src / core / or / circuituse.c
blob088358a4d68e8650834b1e6041d582324e7fba2f
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-2018, 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/connection_edge.h"
39 #include "core/or/policies.h"
40 #include "feature/client/addressmap.h"
41 #include "feature/client/bridges.h"
42 #include "feature/client/circpathbias.h"
43 #include "feature/client/entrynodes.h"
44 #include "feature/control/control.h"
45 #include "feature/dircommon/directory.h"
46 #include "feature/hs/hs_circuit.h"
47 #include "feature/hs/hs_client.h"
48 #include "feature/hs/hs_common.h"
49 #include "feature/hs/hs_ident.h"
50 #include "feature/hs/hs_stats.h"
51 #include "feature/nodelist/describe.h"
52 #include "feature/nodelist/networkstatus.h"
53 #include "feature/nodelist/nodelist.h"
54 #include "feature/nodelist/routerlist.h"
55 #include "feature/relay/routermode.h"
56 #include "feature/relay/selftest.h"
57 #include "feature/rend/rendclient.h"
58 #include "feature/rend/rendcommon.h"
59 #include "feature/rend/rendservice.h"
60 #include "feature/stats/predict_ports.h"
61 #include "lib/math/fp.h"
62 #include "lib/time/tvdiff.h"
64 #include "core/or/cpath_build_state_st.h"
65 #include "feature/dircommon/dir_connection_st.h"
66 #include "core/or/entry_connection_st.h"
67 #include "core/or/extend_info_st.h"
68 #include "core/or/or_circuit_st.h"
69 #include "core/or/origin_circuit_st.h"
70 #include "core/or/socks_request_st.h"
72 static void circuit_expire_old_circuits_clientside(void);
73 static void circuit_increment_failure_count(void);
75 /** Check whether the hidden service destination of the stream at
76 * <b>edge_conn</b> is the same as the destination of the circuit at
77 * <b>origin_circ</b>. */
78 static int
79 circuit_matches_with_rend_stream(const edge_connection_t *edge_conn,
80 const origin_circuit_t *origin_circ)
82 /* Check if this is a v2 rendezvous circ/stream */
83 if ((edge_conn->rend_data && !origin_circ->rend_data) ||
84 (!edge_conn->rend_data && origin_circ->rend_data) ||
85 (edge_conn->rend_data && origin_circ->rend_data &&
86 rend_cmp_service_ids(rend_data_get_address(edge_conn->rend_data),
87 rend_data_get_address(origin_circ->rend_data)))) {
88 /* this circ is not for this conn */
89 return 0;
92 /* Check if this is a v3 rendezvous circ/stream */
93 if ((edge_conn->hs_ident && !origin_circ->hs_ident) ||
94 (!edge_conn->hs_ident && origin_circ->hs_ident) ||
95 (edge_conn->hs_ident && origin_circ->hs_ident &&
96 !ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
97 &origin_circ->hs_ident->identity_pk))) {
98 /* this circ is not for this conn */
99 return 0;
102 return 1;
105 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
106 * Else return 0.
108 static int
109 circuit_is_acceptable(const origin_circuit_t *origin_circ,
110 const entry_connection_t *conn,
111 int must_be_open, uint8_t purpose,
112 int need_uptime, int need_internal,
113 time_t now)
115 const circuit_t *circ = TO_CIRCUIT(origin_circ);
116 const node_t *exitnode;
117 cpath_build_state_t *build_state;
118 tor_assert(circ);
119 tor_assert(conn);
120 tor_assert(conn->socks_request);
122 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
123 return 0; /* ignore non-open circs */
124 if (circ->marked_for_close)
125 return 0;
127 /* if this circ isn't our purpose, skip. */
128 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
129 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
130 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
131 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
132 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
133 return 0;
134 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
135 !must_be_open) {
136 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
137 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
138 return 0;
139 } else {
140 if (purpose != circ->purpose)
141 return 0;
144 /* If this is a timed-out hidden service circuit, skip it. */
145 if (origin_circ->hs_circ_has_timed_out) {
146 return 0;
149 if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
150 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
151 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
152 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
153 purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
154 if (circ->timestamp_dirty &&
155 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
156 return 0;
159 if (origin_circ->unusable_for_new_conns)
160 return 0;
162 /* decide if this circ is suitable for this conn */
164 /* for rend circs, circ->cpath->prev is not the last router in the
165 * circuit, it's the magical extra service hop. so just check the nickname
166 * of the one we meant to finish at.
168 build_state = origin_circ->build_state;
169 exitnode = build_state_get_exit_node(build_state);
171 if (need_uptime && !build_state->need_uptime)
172 return 0;
173 if (need_internal != build_state->is_internal)
174 return 0;
176 if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
177 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
178 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
179 tor_addr_t addr;
180 const int family = tor_addr_parse(&addr, conn->socks_request->address);
181 if (!exitnode && !build_state->onehop_tunnel) {
182 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
183 return 0; /* this circuit is screwed and doesn't know it yet,
184 * or is a rendezvous circuit. */
186 if (build_state->onehop_tunnel) {
187 if (!conn->want_onehop) {
188 log_debug(LD_CIRC,"Skipping one-hop circuit.");
189 return 0;
191 tor_assert(conn->chosen_exit_name);
192 if (build_state->chosen_exit) {
193 char digest[DIGEST_LEN];
194 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
195 return 0; /* broken digest, we don't want it */
196 if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
197 DIGEST_LEN))
198 return 0; /* this is a circuit to somewhere else */
199 if (tor_digest_is_zero(digest)) {
200 /* we don't know the digest; have to compare addr:port */
201 if (family < 0 ||
202 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
203 build_state->chosen_exit->port != conn->socks_request->port)
204 return 0;
207 } else {
208 if (conn->want_onehop) {
209 /* don't use three-hop circuits -- that could hurt our anonymity. */
210 return 0;
213 if (origin_circ->prepend_policy && family != -1) {
214 int r = compare_tor_addr_to_addr_policy(&addr,
215 conn->socks_request->port,
216 origin_circ->prepend_policy);
217 if (r == ADDR_POLICY_REJECTED)
218 return 0;
220 if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
221 /* can't exit from this router */
222 return 0;
224 } else { /* not general: this might be a rend circuit */
225 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
226 if (!circuit_matches_with_rend_stream(edge_conn, origin_circ)) {
227 return 0;
231 if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
232 /* conn needs to be isolated from other conns that have already used
233 * origin_circ */
234 return 0;
237 return 1;
240 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
241 * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
243 static int
244 circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
245 const entry_connection_t *conn)
247 const circuit_t *a = TO_CIRCUIT(oa);
248 const circuit_t *b = TO_CIRCUIT(ob);
249 const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
250 int a_bits, b_bits;
252 /* If one of the circuits was allowed to live due to relaxing its timeout,
253 * it is definitely worse (it's probably a much slower path). */
254 if (oa->relaxed_timeout && !ob->relaxed_timeout)
255 return 0; /* ob is better. It's not relaxed. */
256 if (!oa->relaxed_timeout && ob->relaxed_timeout)
257 return 1; /* oa is better. It's not relaxed. */
259 switch (purpose) {
260 case CIRCUIT_PURPOSE_S_HSDIR_POST:
261 case CIRCUIT_PURPOSE_C_HSDIR_GET:
262 case CIRCUIT_PURPOSE_C_GENERAL:
263 /* if it's used but less dirty it's best;
264 * else if it's more recently created it's best
266 if (b->timestamp_dirty) {
267 if (a->timestamp_dirty &&
268 a->timestamp_dirty > b->timestamp_dirty)
269 return 1;
270 } else {
271 if (a->timestamp_dirty ||
272 timercmp(&a->timestamp_began, &b->timestamp_began, OP_GT))
273 return 1;
274 if (ob->build_state->is_internal)
275 /* XXXX++ what the heck is this internal thing doing here. I
276 * think we can get rid of it. circuit_is_acceptable() already
277 * makes sure that is_internal is exactly what we need it to
278 * be. -RD */
279 return 1;
281 break;
282 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
283 /* the closer it is to ack_wait the better it is */
284 if (a->purpose > b->purpose)
285 return 1;
286 break;
287 case CIRCUIT_PURPOSE_C_REND_JOINED:
288 /* the closer it is to rend_joined the better it is */
289 if (a->purpose > b->purpose)
290 return 1;
291 break;
294 /* XXXX Maybe this check should get a higher priority to avoid
295 * using up circuits too rapidly. */
297 a_bits = connection_edge_update_circuit_isolation(conn,
298 (origin_circuit_t*)oa, 1);
299 b_bits = connection_edge_update_circuit_isolation(conn,
300 (origin_circuit_t*)ob, 1);
301 /* if x_bits < 0, then we have not used x for anything; better not to dirty
302 * a connection if we can help it. */
303 if (a_bits < 0) {
304 return 0;
305 } else if (b_bits < 0) {
306 return 1;
308 a_bits &= ~ oa->isolation_flags_mixed;
309 a_bits &= ~ ob->isolation_flags_mixed;
310 if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
311 /* The fewer new restrictions we need to make on a circuit for stream
312 * isolation, the better. */
313 return 1;
316 return 0;
319 /** Find the best circ that conn can use, preferably one which is
320 * dirty. Circ must not be too old.
322 * Conn must be defined.
324 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
326 * circ_purpose specifies what sort of circuit we must have.
327 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
329 * If it's REND_JOINED and must_be_open==0, then return the closest
330 * rendezvous-purposed circuit that you can find.
332 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
333 * closest introduce-purposed circuit that you can find.
335 static origin_circuit_t *
336 circuit_get_best(const entry_connection_t *conn,
337 int must_be_open, uint8_t purpose,
338 int need_uptime, int need_internal)
340 origin_circuit_t *best=NULL;
341 struct timeval now;
342 int intro_going_on_but_too_old = 0;
344 tor_assert(conn);
346 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
347 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
348 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
349 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
350 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
351 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
353 tor_gettimeofday(&now);
355 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
356 origin_circuit_t *origin_circ;
357 if (!CIRCUIT_IS_ORIGIN(circ))
358 continue;
359 origin_circ = TO_ORIGIN_CIRCUIT(circ);
361 /* Log an info message if we're going to launch a new intro circ in
362 * parallel */
363 if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
364 !must_be_open && origin_circ->hs_circ_has_timed_out &&
365 !circ->marked_for_close) {
366 intro_going_on_but_too_old = 1;
367 continue;
370 if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
371 need_uptime,need_internal, (time_t)now.tv_sec))
372 continue;
374 /* now this is an acceptable circ to hand back. but that doesn't
375 * mean it's the *best* circ to hand back. try to decide.
377 if (!best || circuit_is_better(origin_circ,best,conn))
378 best = origin_circ;
380 SMARTLIST_FOREACH_END(circ);
382 if (!best && intro_going_on_but_too_old)
383 log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
384 "right now, but it has already taken quite a while. Starting "
385 "one in parallel.");
387 return best;
390 /** Return the number of not-yet-open general-purpose origin circuits. */
391 static int
392 count_pending_general_client_circuits(void)
394 int count = 0;
396 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
397 if (circ->marked_for_close ||
398 circ->state == CIRCUIT_STATE_OPEN ||
399 !CIRCUIT_PURPOSE_COUNTS_TOWARDS_MAXPENDING(circ->purpose) ||
400 !CIRCUIT_IS_ORIGIN(circ))
401 continue;
403 ++count;
405 SMARTLIST_FOREACH_END(circ);
407 return count;
410 #if 0
411 /** Check whether, according to the policies in <b>options</b>, the
412 * circuit <b>circ</b> makes sense. */
413 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
414 * Also, it doesn't have the right definition of an exit circuit. Also,
415 * it's never called. */
417 circuit_conforms_to_options(const origin_circuit_t *circ,
418 const or_options_t *options)
420 const crypt_path_t *cpath, *cpath_next = NULL;
422 /* first check if it includes any excluded nodes */
423 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
424 cpath_next = cpath->next;
425 if (routerset_contains_extendinfo(options->ExcludeNodes,
426 cpath->extend_info))
427 return 0;
430 /* then consider the final hop */
431 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
432 circ->cpath->prev->extend_info))
433 return 0;
435 return 1;
437 #endif /* 0 */
440 * Close all circuits that start at us, aren't open, and were born
441 * at least CircuitBuildTimeout seconds ago.
443 * TODO: This function is now partially redundant to
444 * circuit_build_times_handle_completed_hop(), but that function only
445 * covers circuits up to and including 3 hops that are still actually
446 * completing hops. However, circuit_expire_building() also handles longer
447 * circuits, as well as circuits that are completely stalled.
448 * In the future (after prop247/other path selection revamping), we probably
449 * want to eliminate this rats nest in favor of a simpler approach.
451 void
452 circuit_expire_building(void)
454 /* circ_times.timeout_ms and circ_times.close_ms are from
455 * circuit_build_times_get_initial_timeout() if we haven't computed
456 * custom timeouts yet */
457 struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
458 close_cutoff, extremely_old_cutoff, hs_extremely_old_cutoff,
459 cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff;
460 const or_options_t *options = get_options();
461 struct timeval now;
462 cpath_build_state_t *build_state;
463 int any_opened_circs = 0;
465 tor_gettimeofday(&now);
467 /* Check to see if we have any opened circuits. If we don't,
468 * we want to be more lenient with timeouts, in case the
469 * user has relocated and/or changed network connections.
470 * See bug #3443. */
471 any_opened_circs = circuit_any_opened_circuits();
473 #define SET_CUTOFF(target, msec) do { \
474 long ms = tor_lround(msec); \
475 struct timeval diff; \
476 diff.tv_sec = ms / 1000; \
477 diff.tv_usec = (int)((ms % 1000) * 1000); \
478 timersub(&now, &diff, &target); \
479 } while (0)
482 * Because circuit build timeout is calculated only based on 3 hop
483 * general purpose circuit construction, we need to scale the timeout
484 * to make it properly apply to longer circuits, and circuits of
485 * certain usage types. The following diagram illustrates how we
486 * derive the scaling below. In short, we calculate the number
487 * of times our telescoping-based circuit construction causes cells
488 * to traverse each link for the circuit purpose types in question,
489 * and then assume each link is equivalent.
491 * OP --a--> A --b--> B --c--> C
492 * OP --a--> A --b--> B --c--> C --d--> D
494 * Let h = a = b = c = d
496 * Three hops (general_cutoff)
497 * RTTs = 3a + 2b + c
498 * RTTs = 6h
499 * Cannibalized:
500 * RTTs = a+b+c+d
501 * RTTs = 4h
502 * Four hops:
503 * RTTs = 4a + 3b + 2c + d
504 * RTTs = 10h
505 * Client INTRODUCE1+ACK: // XXX: correct?
506 * RTTs = 5a + 4b + 3c + 2d
507 * RTTs = 14h
508 * Server intro:
509 * RTTs = 4a + 3b + 2c
510 * RTTs = 9h
512 SET_CUTOFF(general_cutoff, get_circuit_build_timeout_ms());
513 SET_CUTOFF(begindir_cutoff, get_circuit_build_timeout_ms());
515 // TODO: We should probably use route_len_for_purpose() here instead,
516 // except that does not count the extra round trip for things like server
517 // intros and rends.
519 /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
520 * 4th hop. */
521 SET_CUTOFF(fourhop_cutoff, get_circuit_build_timeout_ms() * (10/6.0) + 1000);
523 /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
524 * Use the stream cutoff (more or less). */
525 SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
527 /* Be lenient with cannibalized circs. They already survived the official
528 * CBT, and they're usually not performance-critical. */
529 SET_CUTOFF(cannibalized_cutoff,
530 MAX(get_circuit_build_close_time_ms()*(4/6.0),
531 options->CircuitStreamTimeout * 1000) + 1000);
533 /* Intro circs have an extra round trip (and are also 4 hops long) */
534 SET_CUTOFF(c_intro_cutoff, get_circuit_build_timeout_ms() * (14/6.0) + 1000);
536 /* Server intro circs have an extra round trip */
537 SET_CUTOFF(s_intro_cutoff, get_circuit_build_timeout_ms() * (9/6.0) + 1000);
539 SET_CUTOFF(close_cutoff, get_circuit_build_close_time_ms());
540 SET_CUTOFF(extremely_old_cutoff, get_circuit_build_close_time_ms()*2 + 1000);
542 SET_CUTOFF(hs_extremely_old_cutoff,
543 MAX(get_circuit_build_close_time_ms()*2 + 1000,
544 options->SocksTimeout * 1000));
546 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *,victim) {
547 struct timeval cutoff;
548 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
549 victim->marked_for_close) /* don't mess with marked circs */
550 continue;
552 /* If we haven't yet started the first hop, it means we don't have
553 * any orconns available, and thus have not started counting time yet
554 * for this circuit. See circuit_deliver_create_cell() and uses of
555 * timestamp_began.
557 * Continue to wait in this case. The ORConn should timeout
558 * independently and kill us then.
560 if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
561 continue;
564 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
565 if (build_state && build_state->onehop_tunnel)
566 cutoff = begindir_cutoff;
567 else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
568 cutoff = close_cutoff;
569 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
570 cutoff = c_intro_cutoff;
571 else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
572 cutoff = s_intro_cutoff;
573 else if (victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
574 cutoff = stream_cutoff;
575 else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
576 cutoff = close_cutoff;
577 else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
578 victim->state != CIRCUIT_STATE_OPEN)
579 cutoff = cannibalized_cutoff;
580 else if (build_state && build_state->desired_path_len >= 4)
581 cutoff = fourhop_cutoff;
582 else
583 cutoff = general_cutoff;
585 if (TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)
586 cutoff = hs_extremely_old_cutoff;
588 if (timercmp(&victim->timestamp_began, &cutoff, OP_GT))
589 continue; /* it's still young, leave it alone */
591 /* We need to double-check the opened state here because
592 * we don't want to consider opened 1-hop dircon circuits for
593 * deciding when to relax the timeout, but we *do* want to relax
594 * those circuits too if nothing else is opened *and* they still
595 * aren't either. */
596 if (!any_opened_circs && victim->state != CIRCUIT_STATE_OPEN) {
597 /* It's still young enough that we wouldn't close it, right? */
598 if (timercmp(&victim->timestamp_began, &close_cutoff, OP_GT)) {
599 if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
600 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
601 == CPATH_STATE_OPEN;
602 log_info(LD_CIRC,
603 "No circuits are opened. Relaxing timeout for circuit %d "
604 "(a %s %d-hop circuit in state %s with channel state %s).",
605 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
606 circuit_purpose_to_string(victim->purpose),
607 TO_ORIGIN_CIRCUIT(victim)->build_state ?
608 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
610 circuit_state_to_string(victim->state),
611 victim->n_chan ?
612 channel_state_to_string(victim->n_chan->state) : "none");
614 /* We count the timeout here for CBT, because technically this
615 * was a timeout, and the timeout value needs to reset if we
616 * see enough of them. Note this means we also need to avoid
617 * double-counting below, too. */
618 circuit_build_times_count_timeout(get_circuit_build_times_mutable(),
619 first_hop_succeeded);
620 TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
622 continue;
623 } else {
624 static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
625 const double build_close_ms = get_circuit_build_close_time_ms();
626 log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
627 "No circuits are opened. Relaxed timeout for circuit %d "
628 "(a %s %d-hop circuit in state %s with channel state %s) to "
629 "%ldms. However, it appears the circuit has timed out "
630 "anyway.",
631 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
632 circuit_purpose_to_string(victim->purpose),
633 TO_ORIGIN_CIRCUIT(victim)->build_state ?
634 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
636 circuit_state_to_string(victim->state),
637 victim->n_chan ?
638 channel_state_to_string(victim->n_chan->state) : "none",
639 (long)build_close_ms);
643 #if 0
644 /* some debug logs, to help track bugs */
645 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
646 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
647 if (!victim->timestamp_dirty)
648 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
649 "(clean).",
650 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
651 victim->purpose, victim->build_state->chosen_exit_name,
652 victim->n_circ_id);
653 else
654 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
655 "%d secs since dirty.",
656 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
657 victim->purpose, victim->build_state->chosen_exit_name,
658 victim->n_circ_id,
659 (int)(now - victim->timestamp_dirty));
661 #endif /* 0 */
663 /* if circ is !open, or if it's open but purpose is a non-finished
664 * intro or rend, then mark it for close */
665 if (victim->state == CIRCUIT_STATE_OPEN) {
666 switch (victim->purpose) {
667 default: /* most open circuits can be left alone. */
668 continue; /* yes, continue inside a switch refers to the nearest
669 * enclosing loop. C is smart. */
670 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
671 break; /* too old, need to die */
672 case CIRCUIT_PURPOSE_C_REND_READY:
673 /* it's a rend_ready circ -- has it already picked a query? */
674 /* c_rend_ready circs measure age since timestamp_dirty,
675 * because that's set when they switch purposes
677 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
678 TO_ORIGIN_CIRCUIT(victim)->hs_ident ||
679 victim->timestamp_dirty > cutoff.tv_sec)
680 continue;
681 break;
682 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
683 /* Open path bias testing circuits are given a long
684 * time to complete the test, but not forever */
685 TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
686 break;
687 case CIRCUIT_PURPOSE_C_INTRODUCING:
688 /* That purpose means that the intro point circuit has been opened
689 * successfully but the INTRODUCE1 cell hasn't been sent yet because
690 * the client is waiting for the rendezvous point circuit to open.
691 * Keep this circuit open while waiting for the rendezvous circuit.
692 * We let the circuit idle timeout take care of cleaning this
693 * circuit if it never used. */
694 continue;
695 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
696 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
697 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
698 /* rend and intro circs become dirty each time they
699 * make an introduction attempt. so timestamp_dirty
700 * will reflect the time since the last attempt.
702 if (victim->timestamp_dirty > cutoff.tv_sec)
703 continue;
704 break;
706 } else { /* circuit not open, consider recording failure as timeout */
707 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
708 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
710 if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
711 log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
712 "yet has attached streams!",
713 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
714 victim->purpose,
715 circuit_purpose_to_string(victim->purpose));
716 tor_fragile_assert();
717 continue;
720 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
721 circuit_build_times_enough_to_compute(get_circuit_build_times())) {
723 log_info(LD_CIRC,
724 "Deciding to count the timeout for circuit %"PRIu32"\n",
725 TO_ORIGIN_CIRCUIT(victim)->global_identifier);
727 /* Circuits are allowed to last longer for measurement.
728 * Switch their purpose and wait. */
729 if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
730 circuit_build_times_mark_circ_as_measurement_only(TO_ORIGIN_CIRCUIT(
731 victim));
732 continue;
736 * If the circuit build time is much greater than we would have cut
737 * it off at, we probably had a suspend event along this codepath,
738 * and we should discard the value.
740 if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, OP_LT)) {
741 log_notice(LD_CIRC,
742 "Extremely large value for circuit build timeout: %lds. "
743 "Assuming clock jump. Purpose %d (%s)",
744 (long)(now.tv_sec - victim->timestamp_began.tv_sec),
745 victim->purpose,
746 circuit_purpose_to_string(victim->purpose));
747 } else if (circuit_build_times_count_close(
748 get_circuit_build_times_mutable(),
749 first_hop_succeeded,
750 (time_t)victim->timestamp_created.tv_sec)) {
751 circuit_build_times_set_timeout(get_circuit_build_times_mutable());
756 /* If this is a hidden service client circuit which is far enough along in
757 * connecting to its destination, and we haven't already flagged it as
758 * 'timed out', flag it so we'll launch another intro or rend circ, but
759 * don't mark it for close yet.
761 * (Circs flagged as 'timed out' are given a much longer timeout
762 * period above, so we won't close them in the next call to
763 * circuit_expire_building.) */
764 if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)) {
765 switch (victim->purpose) {
766 case CIRCUIT_PURPOSE_C_REND_READY:
767 /* We only want to spare a rend circ if it has been specified in
768 * an INTRODUCE1 cell sent to a hidden service. A circ's
769 * pending_final_cpath field is non-NULL iff it is a rend circ
770 * and we have tried to send an INTRODUCE1 cell specifying it.
771 * Thus, if the pending_final_cpath field *is* NULL, then we
772 * want to not spare it. */
773 if (TO_ORIGIN_CIRCUIT(victim)->build_state &&
774 TO_ORIGIN_CIRCUIT(victim)->build_state->pending_final_cpath ==
775 NULL)
776 break;
777 /* fallthrough! */
778 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
779 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
780 /* If we have reached this line, we want to spare the circ for now. */
781 log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
782 "as timed-out HS circ",
783 (unsigned)victim->n_circ_id,
784 victim->state, circuit_state_to_string(victim->state),
785 victim->purpose);
786 TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
787 continue;
788 default:
789 break;
793 /* If this is a service-side rendezvous circuit which is far
794 * enough along in connecting to its destination, consider sparing
795 * it. */
796 if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
797 victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
798 log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
799 "as timed-out HS circ; relaunching rendezvous attempt.",
800 (unsigned)victim->n_circ_id,
801 victim->state, circuit_state_to_string(victim->state),
802 victim->purpose);
803 TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
804 hs_circ_retry_service_rendezvous_point(TO_ORIGIN_CIRCUIT(victim));
805 continue;
808 if (victim->n_chan)
809 log_info(LD_CIRC,
810 "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
811 "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
812 channel_get_canonical_remote_descr(victim->n_chan),
813 (unsigned)victim->n_circ_id,
814 TO_ORIGIN_CIRCUIT(victim)->has_opened,
815 victim->state, circuit_state_to_string(victim->state),
816 victim->purpose,
817 TO_ORIGIN_CIRCUIT(victim)->build_state ?
818 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
819 -1);
820 else
821 log_info(LD_CIRC,
822 "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
823 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
824 (unsigned)victim->n_circ_id,
825 TO_ORIGIN_CIRCUIT(victim)->has_opened,
826 victim->state,
827 circuit_state_to_string(victim->state), victim->purpose,
828 TO_ORIGIN_CIRCUIT(victim)->build_state ?
829 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
830 -1);
832 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
833 if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
834 circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
835 else
836 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
838 pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
839 } SMARTLIST_FOREACH_END(victim);
843 * Mark for close all circuits that start here, that were built through a
844 * guard we weren't sure if we wanted to use, and that have been waiting
845 * around for way too long.
847 void
848 circuit_expire_waiting_for_better_guard(void)
850 SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
851 origin_circuit_t *, circ) {
852 if (TO_CIRCUIT(circ)->marked_for_close)
853 continue;
854 if (circ->guard_state == NULL)
855 continue;
856 if (entry_guard_state_should_expire(circ->guard_state))
857 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
858 } SMARTLIST_FOREACH_END(circ);
861 /** For debugging #8387: track when we last called
862 * circuit_expire_old_circuits_clientside. */
863 static time_t last_expired_clientside_circuits = 0;
866 * As a diagnostic for bug 8387, log information about how many one-hop
867 * circuits we have around that have been there for at least <b>age</b>
868 * seconds. Log a few of them. Ignores Single Onion Service intro, it is
869 * expected to be long-term one-hop circuits.
871 void
872 circuit_log_ancient_one_hop_circuits(int age)
874 #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
875 time_t now = time(NULL);
876 time_t cutoff = now - age;
877 int n_found = 0;
878 smartlist_t *log_these = smartlist_new();
879 const or_options_t *options = get_options();
881 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
882 const origin_circuit_t *ocirc;
883 if (! CIRCUIT_IS_ORIGIN(circ))
884 continue;
885 if (circ->timestamp_created.tv_sec >= cutoff)
886 continue;
887 /* Single Onion Services deliberately make long term one-hop intro
888 * and rendezvous connections. Don't log the established ones. */
889 if (rend_service_allow_non_anonymous_connection(options) &&
890 (circ->purpose == CIRCUIT_PURPOSE_S_INTRO ||
891 circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED))
892 continue;
893 ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
895 if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
896 ++n_found;
898 if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
899 smartlist_add(log_these, (origin_circuit_t*) ocirc);
902 SMARTLIST_FOREACH_END(circ);
904 if (n_found == 0)
905 goto done;
907 log_notice(LD_HEARTBEAT,
908 "Diagnostic for issue 8387: Found %d one-hop circuits more "
909 "than %d seconds old! Logging %d...",
910 n_found, age, smartlist_len(log_these));
912 SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
913 char created[ISO_TIME_LEN+1];
914 int stream_num;
915 const edge_connection_t *conn;
916 char *dirty = NULL;
917 const circuit_t *circ = TO_CIRCUIT(ocirc);
919 format_local_iso_time(created,
920 (time_t)circ->timestamp_created.tv_sec);
922 if (circ->timestamp_dirty) {
923 char dirty_since[ISO_TIME_LEN+1];
924 format_local_iso_time(dirty_since, circ->timestamp_dirty);
926 tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
927 dirty_since, (long)(now - circ->timestamp_dirty),
928 (long) options->MaxCircuitDirtiness);
929 } else {
930 dirty = tor_strdup("Not marked dirty");
933 log_notice(LD_HEARTBEAT, " #%d created at %s. %s, %s. %s for close. "
934 "Package window: %d. "
935 "%s for new conns. %s.",
936 ocirc_sl_idx,
937 created,
938 circuit_state_to_string(circ->state),
939 circuit_purpose_to_string(circ->purpose),
940 circ->marked_for_close ? "Marked" : "Not marked",
941 circ->package_window,
942 ocirc->unusable_for_new_conns ? "Not usable" : "usable",
943 dirty);
944 tor_free(dirty);
946 stream_num = 0;
947 for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
948 const connection_t *c = TO_CONN(conn);
949 char stream_created[ISO_TIME_LEN+1];
950 if (++stream_num >= 5)
951 break;
953 format_local_iso_time(stream_created, c->timestamp_created);
955 log_notice(LD_HEARTBEAT, " Stream#%d created at %s. "
956 "%s conn in state %s. "
957 "It is %slinked and %sreading from a linked connection %p. "
958 "Package window %d. "
959 "%s for close (%s:%d). Hold-open is %sset. "
960 "Has %ssent RELAY_END. %s on circuit.",
961 stream_num,
962 stream_created,
963 conn_type_to_string(c->type),
964 conn_state_to_string(c->type, c->state),
965 c->linked ? "" : "not ",
966 c->reading_from_linked_conn ? "": "not",
967 c->linked_conn,
968 conn->package_window,
969 c->marked_for_close ? "Marked" : "Not marked",
970 c->marked_for_close_file ? c->marked_for_close_file : "--",
971 c->marked_for_close,
972 c->hold_open_until_flushed ? "" : "not ",
973 conn->edge_has_sent_end ? "" : "not ",
974 conn->edge_blocked_on_circ ? "Blocked" : "Not blocked");
975 if (! c->linked_conn)
976 continue;
978 c = c->linked_conn;
980 log_notice(LD_HEARTBEAT, " Linked to %s connection in state %s "
981 "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
982 conn_type_to_string(c->type),
983 conn_state_to_string(c->type, c->state),
984 c->purpose,
985 c->marked_for_close ? "Marked" : "Not marked",
986 c->marked_for_close_file ? c->marked_for_close_file : "--",
987 c->marked_for_close,
988 c->hold_open_until_flushed ? "" : "not ");
990 } SMARTLIST_FOREACH_END(ocirc);
992 log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
993 "circuit_expire_old_circuits_clientside().",
994 (long)(now - last_expired_clientside_circuits));
996 done:
997 smartlist_free(log_these);
1000 /** Remove any elements in <b>needed_ports</b> that are handled by an
1001 * open or in-progress circuit.
1003 void
1004 circuit_remove_handled_ports(smartlist_t *needed_ports)
1006 int i;
1007 uint16_t *port;
1009 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1010 port = smartlist_get(needed_ports, i);
1011 tor_assert(*port);
1012 if (circuit_stream_is_being_handled(NULL, *port,
1013 MIN_CIRCUITS_HANDLING_STREAM)) {
1014 log_debug(LD_CIRC,"Port %d is already being handled; removing.", *port);
1015 smartlist_del(needed_ports, i--);
1016 tor_free(port);
1017 } else {
1018 log_debug(LD_CIRC,"Port %d is not handled.", *port);
1023 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
1024 * will have an acceptable exit node for exit stream <b>conn</b> if it
1025 * is defined, else for "*:port".
1026 * Else return 0.
1029 circuit_stream_is_being_handled(entry_connection_t *conn,
1030 uint16_t port, int min)
1032 const node_t *exitnode;
1033 int num=0;
1034 time_t now = time(NULL);
1035 int need_uptime = smartlist_contains_int_as_string(
1036 get_options()->LongLivedPorts,
1037 conn ? conn->socks_request->port : port);
1039 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1040 if (CIRCUIT_IS_ORIGIN(circ) &&
1041 !circ->marked_for_close &&
1042 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
1043 (!circ->timestamp_dirty ||
1044 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
1045 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1046 cpath_build_state_t *build_state = origin_circ->build_state;
1047 if (build_state->is_internal || build_state->onehop_tunnel)
1048 continue;
1049 if (origin_circ->unusable_for_new_conns)
1050 continue;
1051 if (origin_circ->isolation_values_set &&
1052 (conn == NULL ||
1053 !connection_edge_compatible_with_circuit(conn, origin_circ)))
1054 continue;
1056 exitnode = build_state_get_exit_node(build_state);
1057 if (exitnode && (!need_uptime || build_state->need_uptime)) {
1058 int ok;
1059 if (conn) {
1060 ok = connection_ap_can_use_exit(conn, exitnode);
1061 } else {
1062 addr_policy_result_t r;
1063 r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
1064 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
1066 if (ok) {
1067 if (++num >= min)
1068 return 1;
1073 SMARTLIST_FOREACH_END(circ);
1074 return 0;
1077 /** Don't keep more than this many unused open circuits around. */
1078 #define MAX_UNUSED_OPEN_CIRCUITS 14
1080 /* Return true if a circuit is available for use, meaning that it is open,
1081 * clean, usable for new multi-hop connections, and a general purpose origin
1082 * circuit.
1083 * Accept any kind of circuit, return false if the above conditions are not
1084 * met. */
1085 STATIC int
1086 circuit_is_available_for_use(const circuit_t *circ)
1088 const origin_circuit_t *origin_circ;
1089 cpath_build_state_t *build_state;
1091 if (!CIRCUIT_IS_ORIGIN(circ))
1092 return 0; /* We first filter out only origin circuits before doing the
1093 following checks. */
1094 if (circ->marked_for_close)
1095 return 0; /* Don't mess with marked circs */
1096 if (circ->timestamp_dirty)
1097 return 0; /* Only count clean circs */
1098 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1099 circ->purpose != CIRCUIT_PURPOSE_HS_VANGUARDS)
1100 return 0; /* We only pay attention to general purpose circuits.
1101 General purpose circuits are always origin circuits. */
1103 origin_circ = CONST_TO_ORIGIN_CIRCUIT(circ);
1104 if (origin_circ->unusable_for_new_conns)
1105 return 0;
1107 build_state = origin_circ->build_state;
1108 if (build_state->onehop_tunnel)
1109 return 0;
1111 return 1;
1114 /* Return true if we need any more exit circuits.
1115 * needs_uptime and needs_capacity are set only if we need more exit circuits.
1116 * Check if we know of a port that's been requested recently and no circuit
1117 * is currently available that can handle it. */
1118 STATIC int
1119 needs_exit_circuits(time_t now, int *needs_uptime, int *needs_capacity)
1121 return (!circuit_all_predicted_ports_handled(now, needs_uptime,
1122 needs_capacity) &&
1123 router_have_consensus_path() == CONSENSUS_PATH_EXIT);
1126 /* Hidden services need at least this many internal circuits */
1127 #define SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS 3
1129 /* Return true if we need any more hidden service server circuits.
1130 * HS servers only need an internal circuit. */
1131 STATIC int
1132 needs_hs_server_circuits(time_t now, int num_uptime_internal)
1134 if (!rend_num_services() && !hs_service_get_num_services()) {
1135 /* No services, we don't need anything. */
1136 goto no_need;
1139 if (num_uptime_internal >= SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS) {
1140 /* We have sufficient amount of internal circuit. */
1141 goto no_need;
1144 if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN) {
1145 /* Consensus hasn't been checked or might be invalid so requesting
1146 * internal circuits is not wise. */
1147 goto no_need;
1150 /* At this point, we need a certain amount of circuits and we will most
1151 * likely use them for rendezvous so we note down the use of internal
1152 * circuit for our prediction for circuit needing uptime and capacity. */
1153 rep_hist_note_used_internal(now, 1, 1);
1155 return 1;
1156 no_need:
1157 return 0;
1160 /* We need at least this many internal circuits for hidden service clients */
1161 #define SUFFICIENT_INTERNAL_HS_CLIENTS 3
1163 /* We need at least this much uptime for internal circuits for hidden service
1164 * clients */
1165 #define SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS 2
1167 /* Return true if we need any more hidden service client circuits.
1168 * HS clients only need an internal circuit. */
1169 STATIC int
1170 needs_hs_client_circuits(time_t now, int *needs_uptime, int *needs_capacity,
1171 int num_internal, int num_uptime_internal)
1173 int used_internal_recently = rep_hist_get_predicted_internal(now,
1174 needs_uptime,
1175 needs_capacity);
1176 int requires_uptime = num_uptime_internal <
1177 SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS &&
1178 needs_uptime;
1180 return (used_internal_recently &&
1181 (requires_uptime || num_internal < SUFFICIENT_INTERNAL_HS_CLIENTS) &&
1182 router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN);
1185 /* This is how many circuits can be opened concurrently during the cbt learning
1186 * phase. This number cannot exceed the tor-wide MAX_UNUSED_OPEN_CIRCUITS. */
1187 #define DFLT_CBT_UNUSED_OPEN_CIRCS (10)
1188 #define MIN_CBT_UNUSED_OPEN_CIRCS 0
1189 #define MAX_CBT_UNUSED_OPEN_CIRCS MAX_UNUSED_OPEN_CIRCUITS
1191 /* Return true if we need more circuits for a good build timeout.
1192 * XXXX make the assumption that build timeout streams should be
1193 * created whenever we can build internal circuits. */
1194 STATIC int
1195 needs_circuits_for_build(int num)
1197 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
1198 if (num < networkstatus_get_param(NULL, "cbtmaxopencircs",
1199 DFLT_CBT_UNUSED_OPEN_CIRCS,
1200 MIN_CBT_UNUSED_OPEN_CIRCS,
1201 MAX_CBT_UNUSED_OPEN_CIRCS) &&
1202 !circuit_build_times_disabled(get_options()) &&
1203 circuit_build_times_needs_circuits_now(get_circuit_build_times())) {
1204 return 1;
1207 return 0;
1211 * Launch the appropriate type of predicted circuit for hidden
1212 * services, depending on our options.
1214 static void
1215 circuit_launch_predicted_hs_circ(int flags)
1217 /* K.I.S.S. implementation of bug #23101: If we are using
1218 * vanguards or pinned middles, pre-build a specific purpose
1219 * for HS circs. */
1220 if (circuit_should_use_vanguards(CIRCUIT_PURPOSE_HS_VANGUARDS)) {
1221 circuit_launch(CIRCUIT_PURPOSE_HS_VANGUARDS, flags);
1222 } else {
1223 /* If no vanguards, then no HS-specific prebuilt circuits are needed.
1224 * Normal GENERAL circs are fine */
1225 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1229 /** Determine how many circuits we have open that are clean,
1230 * Make sure it's enough for all the upcoming behaviors we predict we'll have.
1231 * But put an upper bound on the total number of circuits.
1233 static void
1234 circuit_predict_and_launch_new(void)
1236 int num=0, num_internal=0, num_uptime_internal=0;
1237 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
1238 int port_needs_uptime=0, port_needs_capacity=1;
1239 time_t now = time(NULL);
1240 int flags = 0;
1242 /* Count how many of each type of circuit we currently have. */
1243 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1244 if (!circuit_is_available_for_use(circ))
1245 continue;
1247 num++;
1249 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
1250 if (build_state->is_internal)
1251 num_internal++;
1252 if (build_state->need_uptime && build_state->is_internal)
1253 num_uptime_internal++;
1255 SMARTLIST_FOREACH_END(circ);
1257 /* If that's enough, then stop now. */
1258 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
1259 return;
1261 if (needs_exit_circuits(now, &port_needs_uptime, &port_needs_capacity)) {
1262 if (port_needs_uptime)
1263 flags |= CIRCLAUNCH_NEED_UPTIME;
1264 if (port_needs_capacity)
1265 flags |= CIRCLAUNCH_NEED_CAPACITY;
1267 log_info(LD_CIRC,
1268 "Have %d clean circs (%d internal), need another exit circ.",
1269 num, num_internal);
1270 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1271 return;
1274 if (needs_hs_server_circuits(now, num_uptime_internal)) {
1275 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
1276 CIRCLAUNCH_IS_INTERNAL);
1278 log_info(LD_CIRC,
1279 "Have %d clean circs (%d internal), need another internal "
1280 "circ for my hidden service.",
1281 num, num_internal);
1282 circuit_launch_predicted_hs_circ(flags);
1283 return;
1286 if (needs_hs_client_circuits(now, &hidserv_needs_uptime,
1287 &hidserv_needs_capacity,
1288 num_internal, num_uptime_internal))
1290 if (hidserv_needs_uptime)
1291 flags |= CIRCLAUNCH_NEED_UPTIME;
1292 if (hidserv_needs_capacity)
1293 flags |= CIRCLAUNCH_NEED_CAPACITY;
1294 flags |= CIRCLAUNCH_IS_INTERNAL;
1296 log_info(LD_CIRC,
1297 "Have %d clean circs (%d uptime-internal, %d internal), need"
1298 " another hidden service circ.",
1299 num, num_uptime_internal, num_internal);
1301 circuit_launch_predicted_hs_circ(flags);
1302 return;
1305 if (needs_circuits_for_build(num)) {
1306 flags = CIRCLAUNCH_NEED_CAPACITY;
1307 /* if there are no exits in the consensus, make timeout
1308 * circuits internal */
1309 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
1310 flags |= CIRCLAUNCH_IS_INTERNAL;
1312 log_info(LD_CIRC,
1313 "Have %d clean circs need another buildtime test circ.", num);
1314 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1315 return;
1319 /** Build a new test circuit every 5 minutes */
1320 #define TESTING_CIRCUIT_INTERVAL 300
1322 /** This function is called once a second, if router_have_minimum_dir_info()
1323 * is true. Its job is to make sure all services we offer have enough circuits
1324 * available. Some services just want enough circuits for current tasks,
1325 * whereas others want a minimum set of idle circuits hanging around.
1327 void
1328 circuit_build_needed_circs(time_t now)
1330 const or_options_t *options = get_options();
1332 /* launch a new circ for any pending streams that need one
1333 * XXXX make the assumption that (some) AP streams (i.e. HS clients)
1334 * don't require an exit circuit, review in #13814.
1335 * This allows HSs to function in a consensus without exits. */
1336 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
1337 connection_ap_rescan_and_attach_pending();
1339 circuit_expire_old_circs_as_needed(now);
1341 if (!options->DisablePredictedCircuits)
1342 circuit_predict_and_launch_new();
1346 * Called once a second either directly or from
1347 * circuit_build_needed_circs(). As appropriate (once per NewCircuitPeriod)
1348 * resets failure counts and expires old circuits.
1350 void
1351 circuit_expire_old_circs_as_needed(time_t now)
1353 static time_t time_to_expire_and_reset = 0;
1355 if (time_to_expire_and_reset < now) {
1356 circuit_reset_failure_count(1);
1357 time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
1358 if (proxy_mode(get_options()))
1359 addressmap_clean(now);
1360 circuit_expire_old_circuits_clientside();
1362 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
1364 /* If we ever re-enable, this has to move into
1365 * circuit_build_needed_circs */
1367 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
1368 if (get_options()->RunTesting &&
1369 circ &&
1370 circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
1371 log_fn(LOG_INFO,"Creating a new testing circuit.");
1372 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
1374 #endif /* 0 */
1378 /** If the stream <b>conn</b> is a member of any of the linked
1379 * lists of <b>circ</b>, then remove it from the list.
1381 void
1382 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
1384 edge_connection_t *prevconn;
1386 tor_assert(circ);
1387 tor_assert(conn);
1389 if (conn->base_.type == CONN_TYPE_AP) {
1390 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1391 entry_conn->may_use_optimistic_data = 0;
1393 conn->cpath_layer = NULL; /* don't keep a stale pointer */
1394 conn->on_circuit = NULL;
1396 if (CIRCUIT_IS_ORIGIN(circ)) {
1397 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1398 int removed = 0;
1399 if (conn == origin_circ->p_streams) {
1400 origin_circ->p_streams = conn->next_stream;
1401 removed = 1;
1402 } else {
1403 for (prevconn = origin_circ->p_streams;
1404 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1405 prevconn = prevconn->next_stream)
1407 if (prevconn && prevconn->next_stream) {
1408 prevconn->next_stream = conn->next_stream;
1409 removed = 1;
1412 if (removed) {
1413 log_debug(LD_APP, "Removing stream %d from circ %u",
1414 conn->stream_id, (unsigned)circ->n_circ_id);
1416 /* If the stream was removed, and it was a rend stream, decrement the
1417 * number of streams on the circuit associated with the rend service.
1419 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1420 hs_dec_rdv_stream_counter(origin_circ);
1422 return;
1424 } else {
1425 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1426 if (conn == or_circ->n_streams) {
1427 or_circ->n_streams = conn->next_stream;
1428 return;
1430 if (conn == or_circ->resolving_streams) {
1431 or_circ->resolving_streams = conn->next_stream;
1432 return;
1435 for (prevconn = or_circ->n_streams;
1436 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1437 prevconn = prevconn->next_stream)
1439 if (prevconn && prevconn->next_stream) {
1440 prevconn->next_stream = conn->next_stream;
1441 return;
1444 for (prevconn = or_circ->resolving_streams;
1445 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1446 prevconn = prevconn->next_stream)
1448 if (prevconn && prevconn->next_stream) {
1449 prevconn->next_stream = conn->next_stream;
1450 return;
1454 log_warn(LD_BUG,"Edge connection not in circuit's list.");
1455 /* Don't give an error here; it's harmless. */
1456 tor_fragile_assert();
1459 /** Find each circuit that has been unused for too long, or dirty
1460 * for too long and has no streams on it: mark it for close.
1462 static void
1463 circuit_expire_old_circuits_clientside(void)
1465 struct timeval cutoff, now;
1467 tor_gettimeofday(&now);
1468 last_expired_clientside_circuits = now.tv_sec;
1470 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1471 if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
1472 continue;
1474 cutoff = now;
1475 cutoff.tv_sec -= TO_ORIGIN_CIRCUIT(circ)->circuit_idle_timeout;
1477 /* If the circuit has been dirty for too long, and there are no streams
1478 * on it, mark it for close.
1480 if (circ->timestamp_dirty &&
1481 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
1482 now.tv_sec &&
1483 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
1484 log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
1485 "purpose %d)",
1486 (unsigned)circ->n_circ_id,
1487 (long)(now.tv_sec - circ->timestamp_dirty),
1488 circ->purpose);
1489 /* Don't do this magic for testing circuits. Their death is governed
1490 * by circuit_expire_building */
1491 if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
1492 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1493 } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
1494 if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
1495 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
1496 circ->purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1497 circ->purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1498 circ->purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1499 circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
1500 circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1501 circ->purpose == CIRCUIT_PURPOSE_TESTING ||
1502 (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
1503 circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
1504 circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
1505 log_info(LD_CIRC,
1506 "Closing circuit %"PRIu32
1507 " that has been unused for %ld msec.",
1508 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1509 tv_mdiff(&circ->timestamp_began, &now));
1510 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1511 } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
1512 /* Server-side rend joined circuits can end up really old, because
1513 * they are reused by clients for longer than normal. The client
1514 * controls their lifespan. (They never become dirty, because
1515 * connection_exit_begin_conn() never marks anything as dirty.)
1516 * Similarly, server-side intro circuits last a long time. */
1517 if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
1518 circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
1519 log_notice(LD_CIRC,
1520 "Ancient non-dirty circuit %d is still around after "
1521 "%ld milliseconds. Purpose: %d (%s)",
1522 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1523 tv_mdiff(&circ->timestamp_began, &now),
1524 circ->purpose,
1525 circuit_purpose_to_string(circ->purpose));
1526 TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
1531 } SMARTLIST_FOREACH_END(circ);
1534 /** How long do we wait before killing circuits with the properties
1535 * described below?
1537 * Probably we could choose a number here as low as 5 to 10 seconds,
1538 * since these circs are used for begindir, and a) generally you either
1539 * ask another begindir question right after or you don't for a long time,
1540 * b) clients at least through 0.2.1.x choose from the whole set of
1541 * directory mirrors at each choice, and c) re-establishing a one-hop
1542 * circuit via create-fast is a light operation assuming the TLS conn is
1543 * still there.
1545 * I expect "b" to go away one day when we move to using directory
1546 * guards, but I think "a" and "c" are good enough reasons that a low
1547 * number is safe even then.
1549 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
1551 /** Find each non-origin circuit that has been unused for too long,
1552 * has no streams on it, came from a client, and ends here: mark it
1553 * for close.
1555 void
1556 circuit_expire_old_circuits_serverside(time_t now)
1558 or_circuit_t *or_circ;
1559 time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
1561 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1562 if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
1563 continue;
1564 or_circ = TO_OR_CIRCUIT(circ);
1565 /* If the circuit has been idle for too long, and there are no streams
1566 * on it, and it ends here, and it used a create_fast, mark it for close.
1568 if (or_circ->p_chan && channel_is_client(or_circ->p_chan) &&
1569 !circ->n_chan &&
1570 !or_circ->n_streams && !or_circ->resolving_streams &&
1571 channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
1572 log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
1573 (unsigned)or_circ->p_circ_id,
1574 (int)(now - channel_when_last_xmit(or_circ->p_chan)));
1575 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1578 SMARTLIST_FOREACH_END(circ);
1581 /** Number of testing circuits we want open before testing our bandwidth. */
1582 #define NUM_PARALLEL_TESTING_CIRCS 4
1584 /** True iff we've ever had enough testing circuits open to test our
1585 * bandwidth. */
1586 static int have_performed_bandwidth_test = 0;
1588 /** Reset have_performed_bandwidth_test, so we'll start building
1589 * testing circuits again so we can exercise our bandwidth. */
1590 void
1591 reset_bandwidth_test(void)
1593 have_performed_bandwidth_test = 0;
1596 /** Return 1 if we've already exercised our bandwidth, or if we
1597 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
1598 * established or on the way. Else return 0.
1601 circuit_enough_testing_circs(void)
1603 int num = 0;
1605 if (have_performed_bandwidth_test)
1606 return 1;
1608 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1609 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
1610 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
1611 circ->state == CIRCUIT_STATE_OPEN)
1612 num++;
1614 SMARTLIST_FOREACH_END(circ);
1615 return num >= NUM_PARALLEL_TESTING_CIRCS;
1618 /** A testing circuit has completed. Take whatever stats we want.
1619 * Noticing reachability is taken care of in onionskin_answer(),
1620 * so there's no need to record anything here. But if we still want
1621 * to do the bandwidth test, and we now have enough testing circuits
1622 * open, do it.
1624 static void
1625 circuit_testing_opened(origin_circuit_t *circ)
1627 if (have_performed_bandwidth_test ||
1628 !check_whether_orport_reachable(get_options())) {
1629 /* either we've already done everything we want with testing circuits,
1630 * or this testing circuit became open due to a fluke, e.g. we picked
1631 * a last hop where we already had the connection open due to an
1632 * outgoing local circuit. */
1633 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
1634 } else if (circuit_enough_testing_circs()) {
1635 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
1636 have_performed_bandwidth_test = 1;
1637 } else
1638 router_do_reachability_checks(1, 0);
1641 /** A testing circuit has failed to build. Take whatever stats we want. */
1642 static void
1643 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
1645 const or_options_t *options = get_options();
1646 if (server_mode(options) && check_whether_orport_reachable(options))
1647 return;
1649 log_info(LD_GENERAL,
1650 "Our testing circuit (to see if your ORPort is reachable) "
1651 "has failed. I'll try again later.");
1653 /* These aren't used yet. */
1654 (void)circ;
1655 (void)at_last_hop;
1658 /** The circuit <b>circ</b> has just become open. Take the next
1659 * step: for rendezvous circuits, we pass circ to the appropriate
1660 * function in rendclient or rendservice. For general circuits, we
1661 * call connection_ap_attach_pending, which looks for pending streams
1662 * that could use circ.
1664 void
1665 circuit_has_opened(origin_circuit_t *circ)
1667 control_event_circuit_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_C_GENERAL:
1691 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1692 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1693 /* Tell any AP connections that have been waiting for a new
1694 * circuit that one is ready. */
1695 circuit_try_attaching_streams(circ);
1696 break;
1697 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1698 /* at the service, waiting for introductions */
1699 hs_service_circuit_has_opened(circ);
1700 break;
1701 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1702 /* at the service, connecting to rend point */
1703 hs_service_circuit_has_opened(circ);
1704 break;
1705 case CIRCUIT_PURPOSE_TESTING:
1706 circuit_testing_opened(circ);
1707 break;
1708 /* default:
1709 * This won't happen in normal operation, but might happen if the
1710 * controller did it. Just let it slide. */
1714 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
1715 * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
1716 static int
1717 circuit_try_clearing_isolation_state(origin_circuit_t *circ)
1719 if (/* The circuit may have become non-open if it was cannibalized.*/
1720 circ->base_.state == CIRCUIT_STATE_OPEN &&
1721 /* If !isolation_values_set, there is nothing to clear. */
1722 circ->isolation_values_set &&
1723 /* It's not legal to clear a circuit's isolation info if it's ever had
1724 * streams attached */
1725 !circ->isolation_any_streams_attached) {
1726 /* If we have any isolation information set on this circuit, and
1727 * we didn't manage to attach any streams to it, then we can
1728 * and should clear it and try again. */
1729 circuit_clear_isolation(circ);
1730 return 1;
1731 } else {
1732 return 0;
1736 /** Called when a circuit becomes ready for streams to be attached to
1737 * it. */
1738 void
1739 circuit_try_attaching_streams(origin_circuit_t *circ)
1741 /* Attach streams to this circuit if we can. */
1742 connection_ap_attach_pending(1);
1744 /* The call to circuit_try_clearing_isolation_state here will do
1745 * nothing and return 0 if we didn't attach any streams to circ
1746 * above. */
1747 if (circuit_try_clearing_isolation_state(circ)) {
1748 /* Maybe *now* we can attach some streams to this circuit. */
1749 connection_ap_attach_pending(1);
1753 /** Called whenever a circuit could not be successfully built.
1755 void
1756 circuit_build_failed(origin_circuit_t *circ)
1758 channel_t *n_chan = NULL;
1759 /* we should examine circ and see if it failed because of
1760 * the last hop or an earlier hop. then use this info below.
1762 int failed_at_last_hop = 0;
1764 /* First, check to see if this was a path failure, rather than build
1765 * failure.
1767 * Note that we deliberately use circuit_get_cpath_len() (and not
1768 * circuit_get_cpath_opened_len()) because we only want to ensure
1769 * that a full path is *chosen*. This is different than a full path
1770 * being *built*. We only want to count *build* failures below.
1772 * Path selection failures can happen spuriously for a number
1773 * of reasons (such as aggressive/invalid user-specified path
1774 * restrictions in the torrc, insufficient microdescriptors, and
1775 * non-user reasons like exitpolicy issues), and so should not be
1776 * counted as failures below.
1778 if (circuit_get_cpath_len(circ) < circ->build_state->desired_path_len) {
1779 static ratelim_t pathfail_limit = RATELIM_INIT(3600);
1780 log_fn_ratelim(&pathfail_limit, LOG_NOTICE, LD_CIRC,
1781 "Our circuit %u (id: %" PRIu32 ") died due to an invalid "
1782 "selected path, purpose %s. This may be a torrc "
1783 "configuration issue, or a bug.",
1784 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1785 circuit_purpose_to_string(TO_CIRCUIT(circ)->purpose));
1787 /* If the path failed on an RP, retry it. */
1788 if (TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
1789 hs_circ_retry_service_rendezvous_point(circ);
1791 /* In all other cases, just bail. The rest is just failure accounting
1792 * that we don't want to do */
1793 return;
1796 /* If the last hop isn't open, and the second-to-last is, we failed
1797 * at the last hop. */
1798 if (circ->cpath &&
1799 circ->cpath->prev->state != CPATH_STATE_OPEN &&
1800 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
1801 failed_at_last_hop = 1;
1804 /* Check if we failed at first hop */
1805 if (circ->cpath &&
1806 circ->cpath->state != CPATH_STATE_OPEN &&
1807 ! circ->base_.received_destroy) {
1808 /* We failed at the first hop for some reason other than a DESTROY cell.
1809 * If there's an OR connection to blame, blame it. Also, avoid this relay
1810 * for a while, and fail any one-hop directory fetches destined for it. */
1811 const char *n_chan_ident = circ->cpath->extend_info->identity_digest;
1812 tor_assert(n_chan_ident);
1813 int already_marked = 0;
1814 if (circ->base_.n_chan) {
1815 n_chan = circ->base_.n_chan;
1817 if (n_chan->is_bad_for_new_circs) {
1818 /* We only want to blame this router when a fresh healthy
1819 * connection fails. So don't mark this router as newly failed,
1820 * since maybe this was just an old circuit attempt that's
1821 * finally timing out now. Also, there's no need to blow away
1822 * circuits/streams/etc, since the failure of an unhealthy conn
1823 * doesn't tell us much about whether a healthy conn would
1824 * succeed. */
1825 already_marked = 1;
1827 log_info(LD_OR,
1828 "Our circuit %u (id: %" PRIu32 ") failed to get a response "
1829 "from the first hop (%s). I'm going to try to rotate to a "
1830 "better connection.",
1831 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1832 channel_get_canonical_remote_descr(n_chan));
1833 n_chan->is_bad_for_new_circs = 1;
1834 } else {
1835 log_info(LD_OR,
1836 "Our circuit %u (id: %" PRIu32 ") died before the first hop "
1837 "with no connection",
1838 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier);
1840 if (!already_marked) {
1842 * If we have guard state (new guard API) and our path selection
1843 * code actually chose a full path, then blame the failure of this
1844 * circuit on the guard.
1846 if (circ->guard_state)
1847 entry_guard_failed(&circ->guard_state);
1848 /* if there are any one-hop streams waiting on this circuit, fail
1849 * them now so they can retry elsewhere. */
1850 connection_ap_fail_onehop(n_chan_ident, circ->build_state);
1854 switch (circ->base_.purpose) {
1855 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1856 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1857 case CIRCUIT_PURPOSE_C_GENERAL:
1858 /* If we never built the circuit, note it as a failure. */
1859 circuit_increment_failure_count();
1860 if (failed_at_last_hop) {
1861 /* Make sure any streams that demand our last hop as their exit
1862 * know that it's unlikely to happen. */
1863 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
1865 break;
1866 case CIRCUIT_PURPOSE_TESTING:
1867 circuit_testing_failed(circ, failed_at_last_hop);
1868 break;
1869 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1870 /* at the service, waiting for introductions */
1871 if (circ->base_.state != CIRCUIT_STATE_OPEN) {
1872 circuit_increment_failure_count();
1874 /* no need to care here, because the service will rebuild intro
1875 * points periodically. */
1876 break;
1877 case CIRCUIT_PURPOSE_C_INTRODUCING:
1878 /* at the client, connecting to intro point */
1879 /* Don't increment failure count, since the service may have picked
1880 * the introduction point maliciously */
1881 /* The client will pick a new intro point when this one dies, if
1882 * the stream in question still cares. No need to act here. */
1883 break;
1884 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1885 /* at the client, waiting for the service */
1886 circuit_increment_failure_count();
1887 /* the client will pick a new rend point when this one dies, if
1888 * the stream in question still cares. No need to act here. */
1889 break;
1890 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1891 /* at the service, connecting to rend point */
1892 /* Don't increment failure count, since the client may have picked
1893 * the rendezvous point maliciously */
1894 log_info(LD_REND,
1895 "Couldn't connect to the client's chosen rend point %s "
1896 "(%s hop failed).",
1897 escaped(build_state_get_exit_nickname(circ->build_state)),
1898 failed_at_last_hop?"last":"non-last");
1899 hs_circ_retry_service_rendezvous_point(circ);
1900 break;
1901 /* default:
1902 * This won't happen in normal operation, but might happen if the
1903 * controller did it. Just let it slide. */
1907 /** Number of consecutive failures so far; should only be touched by
1908 * circuit_launch_new and circuit_*_failure_count.
1910 static int n_circuit_failures = 0;
1911 /** Before the last time we called circuit_reset_failure_count(), were
1912 * there a lot of failures? */
1913 static int did_circs_fail_last_period = 0;
1915 /** Don't retry launching a new circuit if we try this many times with no
1916 * success. */
1917 #define MAX_CIRCUIT_FAILURES 5
1919 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1920 * details on arguments. */
1921 origin_circuit_t *
1922 circuit_launch(uint8_t purpose, int flags)
1924 return circuit_launch_by_extend_info(purpose, NULL, flags);
1927 /* Do we have enough descriptors to build paths?
1928 * If need_exit is true, return 1 if we can build exit paths.
1929 * (We need at least one Exit in the consensus to build exit paths.)
1930 * If need_exit is false, return 1 if we can build internal paths.
1932 static int
1933 have_enough_path_info(int need_exit)
1935 if (need_exit)
1936 return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
1937 else
1938 return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
1942 * Tell us if a circuit is a hidden service circuit.
1945 circuit_purpose_is_hidden_service(uint8_t purpose)
1947 if (purpose == CIRCUIT_PURPOSE_HS_VANGUARDS) {
1948 return 1;
1951 /* Client-side purpose */
1952 if (purpose >= CIRCUIT_PURPOSE_C_HS_MIN_ &&
1953 purpose <= CIRCUIT_PURPOSE_C_HS_MAX_) {
1954 return 1;
1957 /* Service-side purpose */
1958 if (purpose >= CIRCUIT_PURPOSE_S_HS_MIN_ &&
1959 purpose <= CIRCUIT_PURPOSE_S_HS_MAX_) {
1960 return 1;
1963 return 0;
1967 * Return true if this circuit purpose should use vanguards
1968 * or pinned Layer2 or Layer3 guards.
1970 * This function takes both the circuit purpose and the
1971 * torrc options for pinned middles/vanguards into account
1972 * (ie: the circuit must be a hidden service circuit and
1973 * vanguards/pinned middles must be enabled for it to return
1974 * true).
1977 circuit_should_use_vanguards(uint8_t purpose)
1979 const or_options_t *options = get_options();
1981 /* Only hidden service circuits use vanguards */
1982 if (!circuit_purpose_is_hidden_service(purpose))
1983 return 0;
1985 /* Pinned middles are effectively vanguards */
1986 if (options->HSLayer2Nodes || options->HSLayer3Nodes)
1987 return 1;
1989 return 0;
1993 * Return true for the set of conditions for which it is OK to use
1994 * a cannibalized circuit.
1996 * Don't cannibalize for onehops, or certain purposes.
1998 static int
1999 circuit_should_cannibalize_to_build(uint8_t purpose_to_build,
2000 int has_extend_info,
2001 int onehop_tunnel)
2004 /* Do not try to cannibalize if this is a one hop circuit. */
2005 if (onehop_tunnel) {
2006 return 0;
2009 /* Don't try to cannibalize for general purpose circuits that do not
2010 * specify a custom exit. */
2011 if (purpose_to_build == CIRCUIT_PURPOSE_C_GENERAL && !has_extend_info) {
2012 return 0;
2015 /* Don't cannibalize for testing circuits. We want to see if they
2016 * complete normally. Also don't cannibalize for vanguard-purpose
2017 * circuits, since those are specially pre-built for later
2018 * cannibalization by the actual specific circuit types that need
2019 * vanguards.
2021 if (purpose_to_build == CIRCUIT_PURPOSE_TESTING ||
2022 purpose_to_build == CIRCUIT_PURPOSE_HS_VANGUARDS) {
2023 return 0;
2026 /* For vanguards, the server-side intro circ is not cannibalized
2027 * because we pre-build 4 hop HS circuits, and it only needs a 3 hop
2028 * circuit. It is also long-lived, so it is more important that
2029 * it have lower latency than get built fast.
2031 if (circuit_should_use_vanguards(purpose_to_build) &&
2032 purpose_to_build == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
2033 return 0;
2036 return 1;
2039 /** Launch a new circuit with purpose <b>purpose</b> and exit node
2040 * <b>extend_info</b> (or NULL to select a random exit node). If flags
2041 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
2042 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
2043 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
2044 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
2045 * Return the newly allocated circuit on success, or NULL on failure. */
2046 origin_circuit_t *
2047 circuit_launch_by_extend_info(uint8_t purpose,
2048 extend_info_t *extend_info,
2049 int flags)
2051 origin_circuit_t *circ;
2052 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
2053 int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
2055 /* Keep some stats about our attempts to launch HS rendezvous circuits */
2056 if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
2057 hs_stats_note_service_rendezvous_launch();
2060 if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
2061 log_debug(LD_CIRC,"Haven't %s yet; canceling "
2062 "circuit launch.",
2063 !router_have_minimum_dir_info() ?
2064 "fetched enough directory info" :
2065 "received a consensus with exits");
2066 return NULL;
2069 /* If we can/should cannibalize another circuit to build this one,
2070 * then do so. */
2071 if (circuit_should_cannibalize_to_build(purpose,
2072 extend_info != NULL,
2073 onehop_tunnel)) {
2074 /* see if there are appropriate circs available to cannibalize. */
2075 /* XXX if we're planning to add a hop, perhaps we want to look for
2076 * internal circs rather than exit circs? -RD */
2077 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
2078 if (circ) {
2079 uint8_t old_purpose = circ->base_.purpose;
2080 struct timeval old_timestamp_began = circ->base_.timestamp_began;
2082 log_info(LD_CIRC, "Cannibalizing circ %u (id: %" PRIu32 ") for "
2083 "purpose %d (%s)",
2084 TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier, purpose,
2085 circuit_purpose_to_string(purpose));
2087 if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2088 purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
2089 circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
2090 /* Path bias: Cannibalized rends pre-emptively count as a
2091 * successfully built but unused closed circuit. We don't
2092 * wait until the extend (or the close) because the rend
2093 * point could be malicious.
2095 * Same deal goes for client side introductions. Clients
2096 * can be manipulated to connect repeatedly to them
2097 * (especially web clients).
2099 * If we decide to probe the initial portion of these circs,
2100 * (up to the adversary's final hop), we need to remove this,
2101 * or somehow mark the circuit with a special path state.
2104 /* This must be called before the purpose change */
2105 pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
2108 circuit_change_purpose(TO_CIRCUIT(circ), purpose);
2109 /* Reset the start date of this circ, else expire_building
2110 * will see it and think it's been trying to build since it
2111 * began.
2113 * Technically, the code should reset this when the
2114 * create cell is finally sent, but we're close enough
2115 * here. */
2116 tor_gettimeofday(&circ->base_.timestamp_began);
2118 control_event_circuit_cannibalized(circ, old_purpose,
2119 &old_timestamp_began);
2121 switch (purpose) {
2122 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
2123 /* it's ready right now */
2124 break;
2125 case CIRCUIT_PURPOSE_C_INTRODUCING:
2126 case CIRCUIT_PURPOSE_S_CONNECT_REND:
2127 case CIRCUIT_PURPOSE_C_GENERAL:
2128 case CIRCUIT_PURPOSE_S_HSDIR_POST:
2129 case CIRCUIT_PURPOSE_C_HSDIR_GET:
2130 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
2131 /* need to add a new hop */
2132 tor_assert(extend_info);
2133 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
2134 return NULL;
2135 break;
2136 default:
2137 log_warn(LD_BUG,
2138 "unexpected purpose %d when cannibalizing a circ.",
2139 purpose);
2140 tor_fragile_assert();
2141 return NULL;
2143 return circ;
2147 if (did_circs_fail_last_period &&
2148 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
2149 /* too many failed circs in a row. don't try. */
2150 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
2151 return NULL;
2154 /* try a circ. if it fails, circuit_mark_for_close will increment
2155 * n_circuit_failures */
2156 return circuit_establish_circuit(purpose, extend_info, flags);
2159 /** Record another failure at opening a general circuit. When we have
2160 * too many, we'll stop trying for the remainder of this minute.
2162 static void
2163 circuit_increment_failure_count(void)
2165 ++n_circuit_failures;
2166 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
2169 /** Reset the failure count for opening general circuits. This means
2170 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
2171 * stopping again.
2173 void
2174 circuit_reset_failure_count(int timeout)
2176 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
2177 did_circs_fail_last_period = 1;
2178 else
2179 did_circs_fail_last_period = 0;
2180 n_circuit_failures = 0;
2183 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
2184 * there isn't one, and there isn't one on the way, launch one and return
2185 * 0. If it will never work, return -1.
2187 * Write the found or in-progress or launched circ into *circp.
2189 static int
2190 circuit_get_open_circ_or_launch(entry_connection_t *conn,
2191 uint8_t desired_circuit_purpose,
2192 origin_circuit_t **circp)
2194 origin_circuit_t *circ;
2195 int check_exit_policy;
2196 int need_uptime, need_internal;
2197 int want_onehop;
2198 const or_options_t *options = get_options();
2200 tor_assert(conn);
2201 tor_assert(circp);
2202 if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2203 connection_t *c = ENTRY_TO_CONN(conn);
2204 log_err(LD_BUG, "Connection state mismatch: wanted "
2205 "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
2206 c->state, conn_state_to_string(c->type, c->state));
2208 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
2210 /* Will the exit policy of the exit node apply to this stream? */
2211 check_exit_policy =
2212 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2213 !conn->use_begindir &&
2214 !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
2216 /* Does this connection want a one-hop circuit? */
2217 want_onehop = conn->want_onehop;
2219 /* Do we need a high-uptime circuit? */
2220 need_uptime = !conn->want_onehop && !conn->use_begindir &&
2221 smartlist_contains_int_as_string(options->LongLivedPorts,
2222 conn->socks_request->port);
2224 /* Do we need an "internal" circuit? */
2225 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
2226 need_internal = 1;
2227 else if (conn->use_begindir || conn->want_onehop)
2228 need_internal = 1;
2229 else
2230 need_internal = 0;
2232 /* We now know what kind of circuit we need. See if there is an
2233 * open circuit that we can use for this stream */
2234 circ = circuit_get_best(conn, 1 /* Insist on open circuits */,
2235 desired_circuit_purpose,
2236 need_uptime, need_internal);
2238 if (circ) {
2239 /* We got a circuit that will work for this stream! We can return it. */
2240 *circp = circ;
2241 return 1; /* we're happy */
2244 /* Okay, there's no circuit open that will work for this stream. Let's
2245 * see if there's an in-progress circuit or if we have to launch one */
2247 /* Do we know enough directory info to build circuits at all? */
2248 int have_path = have_enough_path_info(!need_internal);
2250 if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
2251 /* If we don't have enough directory information, we can't build
2252 * multihop circuits.
2254 if (!connection_get_by_type(CONN_TYPE_DIR)) {
2255 int severity = LOG_NOTICE;
2256 /* Retry some stuff that might help the connection work. */
2257 /* If we are configured with EntryNodes or UseBridges */
2258 if (entry_list_is_constrained(options)) {
2259 /* Retry all our guards / bridges.
2260 * guards_retry_optimistic() always returns true here. */
2261 int rv = guards_retry_optimistic(options);
2262 tor_assert_nonfatal_once(rv);
2263 log_fn(severity, LD_APP|LD_DIR,
2264 "Application request when we haven't %s. "
2265 "Optimistically trying known %s again.",
2266 !router_have_minimum_dir_info() ?
2267 "used client functionality lately" :
2268 "received a consensus with exits",
2269 options->UseBridges ? "bridges" : "entrynodes");
2270 } else {
2271 /* Getting directory documents doesn't help much if we have a limited
2272 * number of guards */
2273 tor_assert_nonfatal(!options->UseBridges);
2274 tor_assert_nonfatal(!options->EntryNodes);
2275 /* Retry our directory fetches, so we have a fresh set of guard info */
2276 log_fn(severity, LD_APP|LD_DIR,
2277 "Application request when we haven't %s. "
2278 "Optimistically trying directory fetches again.",
2279 !router_have_minimum_dir_info() ?
2280 "used client functionality lately" :
2281 "received a consensus with exits");
2282 routerlist_retry_directory_downloads(time(NULL));
2285 /* Since we didn't have enough directory info, we can't attach now. The
2286 * stream will be dealt with when router_have_minimum_dir_info becomes 1,
2287 * or when all directory attempts fail and directory_all_unreachable()
2288 * kills it.
2290 return 0;
2293 /* Check whether the exit policy of the chosen exit, or the exit policies
2294 * of _all_ nodes, would forbid this node. */
2295 if (check_exit_policy) {
2296 if (!conn->chosen_exit_name) {
2297 struct in_addr in;
2298 tor_addr_t addr, *addrp=NULL;
2299 if (tor_inet_aton(conn->socks_request->address, &in)) {
2300 tor_addr_from_in(&addr, &in);
2301 addrp = &addr;
2303 if (router_exit_policy_all_nodes_reject(addrp,
2304 conn->socks_request->port,
2305 need_uptime)) {
2306 log_notice(LD_APP,
2307 "No Tor server allows exit to %s:%d. Rejecting.",
2308 safe_str_client(conn->socks_request->address),
2309 conn->socks_request->port);
2310 return -1;
2312 } else {
2313 /* XXXX Duplicates checks in connection_ap_handshake_attach_circuit:
2314 * refactor into a single function. */
2315 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2316 int opt = conn->chosen_exit_optional;
2317 if (node && !connection_ap_can_use_exit(conn, node)) {
2318 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2319 "Requested exit point '%s' is excluded or "
2320 "would refuse request. %s.",
2321 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2322 if (opt) {
2323 conn->chosen_exit_optional = 0;
2324 tor_free(conn->chosen_exit_name);
2325 /* Try again. */
2326 return circuit_get_open_circ_or_launch(conn,
2327 desired_circuit_purpose,
2328 circp);
2330 return -1;
2335 /* Now, check whether there already a circuit on the way that could handle
2336 * this stream. This check matches the one above, but this time we
2337 * do not require that the circuit will work. */
2338 circ = circuit_get_best(conn, 0 /* don't insist on open circuits */,
2339 desired_circuit_purpose,
2340 need_uptime, need_internal);
2341 if (circ)
2342 log_debug(LD_CIRC, "one on the way!");
2344 if (!circ) {
2345 /* No open or in-progress circuit could handle this stream! We
2346 * will have to launch one!
2349 /* The chosen exit node, if there is one. */
2350 extend_info_t *extend_info=NULL;
2351 const int n_pending = count_pending_general_client_circuits();
2353 /* Do we have too many pending circuits? */
2354 if (n_pending >= options->MaxClientCircuitsPending) {
2355 static ratelim_t delay_limit = RATELIM_INIT(10*60);
2356 char *m;
2357 if ((m = rate_limit_log(&delay_limit, approx_time()))) {
2358 log_notice(LD_APP, "We'd like to launch a circuit to handle a "
2359 "connection, but we already have %d general-purpose client "
2360 "circuits pending. Waiting until some finish.%s",
2361 n_pending, m);
2362 tor_free(m);
2364 return 0;
2367 /* If this is a hidden service trying to start an introduction point,
2368 * handle that case. */
2369 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
2370 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2371 /* need to pick an intro point */
2372 extend_info = hs_client_get_random_intro_from_edge(edge_conn);
2373 if (!extend_info) {
2374 log_info(LD_REND, "No intro points: re-fetching service descriptor.");
2375 if (edge_conn->rend_data) {
2376 rend_client_refetch_v2_renddesc(edge_conn->rend_data);
2377 } else {
2378 hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
2380 connection_ap_mark_as_non_pending_circuit(conn);
2381 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
2382 return 0;
2384 log_info(LD_REND,"Chose %s as intro point for '%s'.",
2385 extend_info_describe(extend_info),
2386 (edge_conn->rend_data) ?
2387 safe_str_client(rend_data_get_address(edge_conn->rend_data)) :
2388 "service");
2391 /* If we have specified a particular exit node for our
2392 * connection, then be sure to open a circuit to that exit node.
2394 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2395 desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2396 desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
2397 if (conn->chosen_exit_name) {
2398 const node_t *r;
2399 int opt = conn->chosen_exit_optional;
2400 r = node_get_by_nickname(conn->chosen_exit_name, 0);
2401 if (r && node_has_preferred_descriptor(r, conn->want_onehop ? 1 : 0)) {
2402 /* We might want to connect to an IPv6 bridge for loading
2403 descriptors so we use the preferred address rather than
2404 the primary. */
2405 extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
2406 if (!extend_info) {
2407 log_warn(LD_CIRC,"Could not make a one-hop connection to %s. "
2408 "Discarding this circuit.", conn->chosen_exit_name);
2409 return -1;
2411 } else { /* ! (r && node_has_preferred_descriptor(...)) */
2412 log_debug(LD_DIR, "considering %d, %s",
2413 want_onehop, conn->chosen_exit_name);
2414 if (want_onehop && conn->chosen_exit_name[0] == '$') {
2415 /* We're asking for a one-hop circuit to a router that
2416 * we don't have a routerinfo about. Make up an extend_info. */
2417 /* XXX prop220: we need to make chosen_exit_name able to
2418 * encode both key formats. This is not absolutely critical
2419 * since this is just for one-hop circuits, but we should
2420 * still get it done */
2421 char digest[DIGEST_LEN];
2422 char *hexdigest = conn->chosen_exit_name+1;
2423 tor_addr_t addr;
2424 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2425 base16_decode(digest,DIGEST_LEN,
2426 hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN) {
2427 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
2428 return -1;
2430 if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
2431 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
2432 escaped_safe_str_client(conn->socks_request->address));
2433 return -1;
2435 /* XXXX prop220 add a workaround for ed25519 ID below*/
2436 extend_info = extend_info_new(conn->chosen_exit_name+1,
2437 digest,
2438 NULL, /* Ed25519 ID */
2439 NULL, NULL, /* onion keys */
2440 &addr, conn->socks_request->port);
2441 } else { /* ! (want_onehop && conn->chosen_exit_name[0] == '$') */
2442 /* We will need an onion key for the router, and we
2443 * don't have one. Refuse or relax requirements. */
2444 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2445 "Requested exit point '%s' is not known. %s.",
2446 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2447 if (opt) {
2448 conn->chosen_exit_optional = 0;
2449 tor_free(conn->chosen_exit_name);
2450 /* Try again with no requested exit */
2451 return circuit_get_open_circ_or_launch(conn,
2452 desired_circuit_purpose,
2453 circp);
2455 return -1;
2459 } /* Done checking for general circutis with chosen exits. */
2461 /* What purpose do we need to launch this circuit with? */
2462 uint8_t new_circ_purpose;
2463 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
2464 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
2465 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
2466 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
2467 else
2468 new_circ_purpose = desired_circuit_purpose;
2470 /* Determine what kind of a circuit to launch, and actually launch it. */
2472 int flags = CIRCLAUNCH_NEED_CAPACITY;
2473 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
2474 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2475 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
2477 /* If we are about to pick a v3 RP right now, make sure we pick a
2478 * rendezvous point that supports the v3 protocol! */
2479 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED &&
2480 new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2481 ENTRY_TO_EDGE_CONN(conn)->hs_ident) {
2482 flags |= CIRCLAUNCH_IS_V3_RP;
2483 log_info(LD_GENERAL, "Getting rendezvous circuit to v3 service!");
2486 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
2487 flags);
2490 extend_info_free(extend_info);
2492 /* Now trigger things that need to happen when we launch circuits */
2494 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2495 desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2496 desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST) {
2497 /* We just caused a circuit to get built because of this stream.
2498 * If this stream has caused a _lot_ of circuits to be built, that's
2499 * a bad sign: we should tell the user. */
2500 if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
2501 ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
2502 log_info(LD_CIRC, "The application request to %s:%d has launched "
2503 "%d circuits without finding one it likes.",
2504 escaped_safe_str_client(conn->socks_request->address),
2505 conn->socks_request->port,
2506 conn->num_circuits_launched);
2507 } else {
2508 /* help predict this next time */
2509 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
2510 if (circ) {
2511 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2512 if (edge_conn->rend_data) {
2513 /* write the service_id into circ */
2514 circ->rend_data = rend_data_dup(edge_conn->rend_data);
2515 } else if (edge_conn->hs_ident) {
2516 circ->hs_ident =
2517 hs_ident_circuit_new(&edge_conn->hs_ident->identity_pk,
2518 HS_IDENT_CIRCUIT_INTRO);
2520 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2521 circ->base_.state == CIRCUIT_STATE_OPEN)
2522 circuit_has_opened(circ);
2525 } /* endif (!circ) */
2527 /* We either found a good circuit, or launched a new circuit, or failed to
2528 * do so. Report success, and delay. */
2530 if (circ) {
2531 /* Mark the circuit with the isolation fields for this connection.
2532 * When the circuit arrives, we'll clear these flags: this is
2533 * just some internal bookkeeping to make sure that we have
2534 * launched enough circuits.
2536 connection_edge_update_circuit_isolation(conn, circ, 0);
2537 } else {
2538 log_info(LD_APP,
2539 "No safe circuit (purpose %d) ready for edge "
2540 "connection; delaying.",
2541 desired_circuit_purpose);
2543 *circp = circ;
2544 return 0;
2547 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
2548 * <b>circ</b>. */
2549 static int
2550 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
2552 crypt_path_t *cpath, *cpath_next = NULL;
2553 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2554 cpath_next = cpath->next;
2555 if (crypt_path == cpath)
2556 return 1;
2558 return 0;
2561 /** Return true iff client-side optimistic data is supported. */
2562 static int
2563 optimistic_data_enabled(void)
2565 const or_options_t *options = get_options();
2566 if (options->OptimisticData < 0) {
2567 /* Note: this default was 0 before #18815 was merged. We can't take the
2568 * parameter out of the consensus until versions before that are all
2569 * obsolete. */
2570 const int32_t enabled =
2571 networkstatus_get_param(NULL, "UseOptimisticData", /*default*/ 1, 0, 1);
2572 return (int)enabled;
2574 return options->OptimisticData;
2577 /** Attach the AP stream <b>apconn</b> to circ's linked list of
2578 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
2579 * hop in circ's cpath if <b>cpath</b> is NULL.
2581 static void
2582 link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
2583 crypt_path_t *cpath)
2585 const node_t *exitnode = NULL;
2587 /* add it into the linked list of streams on this circuit */
2588 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
2589 (unsigned)circ->base_.n_circ_id);
2590 /* reset it, so we can measure circ timeouts */
2591 ENTRY_TO_CONN(apconn)->timestamp_last_read_allowed = time(NULL);
2592 ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
2593 ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
2594 /* assert_connection_ok(conn, time(NULL)); */
2595 circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
2597 if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
2598 /* We are attaching a stream to a rendezvous circuit. That means
2599 * that an attempt to connect to a hidden service just
2600 * succeeded. Tell rendclient.c. */
2601 hs_client_note_connection_attempt_succeeded(ENTRY_TO_EDGE_CONN(apconn));
2604 if (cpath) { /* we were given one; use it */
2605 tor_assert(cpath_is_on_circuit(circ, cpath));
2606 } else {
2607 /* use the last hop in the circuit */
2608 tor_assert(circ->cpath);
2609 tor_assert(circ->cpath->prev);
2610 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
2611 cpath = circ->cpath->prev;
2613 ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
2615 circ->isolation_any_streams_attached = 1;
2616 connection_edge_update_circuit_isolation(apconn, circ, 0);
2618 /* Compute the exitnode if possible, for logging below */
2619 if (cpath->extend_info)
2620 exitnode = node_get_by_id(cpath->extend_info->identity_digest);
2622 /* See if we can use optimistic data on this circuit */
2623 if (optimistic_data_enabled() &&
2624 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2625 circ->base_.purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2626 circ->base_.purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2627 circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED))
2628 apconn->may_use_optimistic_data = 1;
2629 else
2630 apconn->may_use_optimistic_data = 0;
2631 log_info(LD_APP, "Looks like completed circuit to %s %s allow "
2632 "optimistic data for connection to %s",
2633 circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ?
2634 /* node_describe() does the right thing if exitnode is NULL */
2635 safe_str_client(node_describe(exitnode)) :
2636 "hidden service",
2637 apconn->may_use_optimistic_data ? "does" : "doesn't",
2638 safe_str_client(apconn->socks_request->address));
2641 /** Return true iff <b>address</b> is matched by one of the entries in
2642 * TrackHostExits. */
2644 hostname_in_track_host_exits(const or_options_t *options, const char *address)
2646 if (!options->TrackHostExits)
2647 return 0;
2648 SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
2649 if (cp[0] == '.') { /* match end */
2650 if (cp[1] == '\0' ||
2651 !strcasecmpend(address, cp) ||
2652 !strcasecmp(address, &cp[1]))
2653 return 1;
2654 } else if (strcasecmp(cp, address) == 0) {
2655 return 1;
2657 } SMARTLIST_FOREACH_END(cp);
2658 return 0;
2661 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
2662 * the exit that we *did* choose for use by future connections to
2663 * <b>conn</b>'s destination.
2665 static void
2666 consider_recording_trackhost(const entry_connection_t *conn,
2667 const origin_circuit_t *circ)
2669 const or_options_t *options = get_options();
2670 char *new_address = NULL;
2671 char fp[HEX_DIGEST_LEN+1];
2673 /* Search the addressmap for this conn's destination. */
2674 /* If they're not in the address map.. */
2675 if (!options->TrackHostExits ||
2676 addressmap_have_mapping(conn->socks_request->address,
2677 options->TrackHostExitsExpire))
2678 return; /* nothing to track, or already mapped */
2680 if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
2681 !circ->build_state->chosen_exit)
2682 return;
2684 /* write down the fingerprint of the chosen exit, not the nickname,
2685 * because the chosen exit might not be named. */
2686 base16_encode(fp, sizeof(fp),
2687 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
2689 /* Add this exit/hostname pair to the addressmap. */
2690 tor_asprintf(&new_address, "%s.%s.exit",
2691 conn->socks_request->address, fp);
2693 addressmap_register(conn->socks_request->address, new_address,
2694 time(NULL) + options->TrackHostExitsExpire,
2695 ADDRMAPSRC_TRACKEXIT, 0, 0);
2698 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
2699 * begin or resolve cell as appropriate. Return values are as for
2700 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
2701 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2702 * <b>cpath</b> is NULL. */
2704 connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
2705 origin_circuit_t *circ,
2706 crypt_path_t *cpath)
2708 connection_t *base_conn = ENTRY_TO_CONN(conn);
2709 tor_assert(conn);
2710 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
2711 base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
2712 tor_assert(conn->socks_request);
2713 tor_assert(circ);
2714 tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
2716 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2718 if (!circ->base_.timestamp_dirty ||
2719 ((conn->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
2720 (conn->entry_cfg.socks_iso_keep_alive) &&
2721 (conn->socks_request->usernamelen ||
2722 conn->socks_request->passwordlen))) {
2723 /* When stream isolation is in use and controlled by an application
2724 * we are willing to keep using the stream. */
2725 circ->base_.timestamp_dirty = approx_time();
2728 pathbias_count_use_attempt(circ);
2730 /* Now, actually link the connection. */
2731 link_apconn_to_circ(conn, circ, cpath);
2733 tor_assert(conn->socks_request);
2734 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
2735 if (!conn->use_begindir)
2736 consider_recording_trackhost(conn, circ);
2737 if (connection_ap_handshake_send_begin(conn) < 0)
2738 return -1;
2739 } else {
2740 if (connection_ap_handshake_send_resolve(conn) < 0)
2741 return -1;
2744 return 1;
2748 * Return an appropriate circuit purpose for non-rend streams.
2749 * We don't handle rends here because a rend stream triggers two
2750 * circuit builds with different purposes, so it is handled elsewhere.
2752 * This function just figures out what type of hsdir activity this is,
2753 * and tells us. Everything else is general.
2755 static int
2756 connection_ap_get_nonrend_circ_purpose(const entry_connection_t *conn)
2758 const connection_t *base_conn = ENTRY_TO_CONN(conn);
2759 tor_assert_nonfatal(!connection_edge_is_rendezvous_stream(
2760 ENTRY_TO_EDGE_CONN(conn)));
2762 if (base_conn->linked_conn &&
2763 base_conn->linked_conn->type == CONN_TYPE_DIR) {
2764 /* Set a custom purpose for hsdir activity */
2765 if (base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2 ||
2766 base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_HSDESC) {
2767 return CIRCUIT_PURPOSE_S_HSDIR_POST;
2768 } else if (base_conn->linked_conn->purpose
2769 == DIR_PURPOSE_FETCH_RENDDESC_V2 ||
2770 base_conn->linked_conn->purpose
2771 == DIR_PURPOSE_FETCH_HSDESC) {
2772 return CIRCUIT_PURPOSE_C_HSDIR_GET;
2776 /* All other purposes are general for now */
2777 return CIRCUIT_PURPOSE_C_GENERAL;
2780 /** Try to find a safe live circuit for stream <b>conn</b>. If we find one,
2781 * attach the stream, send appropriate cells, and return 1. Otherwise,
2782 * try to launch new circuit(s) for the stream. If we can launch
2783 * circuits, return 0. Otherwise, if we simply can't proceed with
2784 * this stream, return -1. (conn needs to die, and is maybe already marked).
2786 /* XXXX this function should mark for close whenever it returns -1;
2787 * its callers shouldn't have to worry about that. */
2789 connection_ap_handshake_attach_circuit(entry_connection_t *conn)
2791 connection_t *base_conn = ENTRY_TO_CONN(conn);
2792 int retval;
2793 int conn_age;
2794 int want_onehop;
2796 tor_assert(conn);
2797 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2798 tor_assert(conn->socks_request);
2799 want_onehop = conn->want_onehop;
2801 conn_age = (int)(time(NULL) - base_conn->timestamp_created);
2803 /* Is this connection so old that we should give up on it? */
2804 if (conn_age >= get_options()->SocksTimeout) {
2805 int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
2806 LOG_INFO : LOG_NOTICE;
2807 log_fn(severity, LD_APP,
2808 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
2809 conn_age, safe_str_client(conn->socks_request->address),
2810 conn->socks_request->port);
2811 return -1;
2814 /* We handle "general" (non-onion) connections much more straightforwardly.
2816 if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
2817 /* we're a general conn */
2818 origin_circuit_t *circ=NULL;
2820 /* Are we linked to a dir conn that aims to fetch a consensus?
2821 * We check here because the conn might no longer be needed. */
2822 if (base_conn->linked_conn &&
2823 base_conn->linked_conn->type == CONN_TYPE_DIR &&
2824 base_conn->linked_conn->purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
2826 /* Yes we are. Is there a consensus fetch farther along than us? */
2827 if (networkstatus_consensus_is_already_downloading(
2828 TO_DIR_CONN(base_conn->linked_conn)->requested_resource)) {
2829 /* We're doing the "multiple consensus fetch attempts" game from
2830 * proposal 210, and we're late to the party. Just close this conn.
2831 * The circuit and TLS conn that we made will time out after a while
2832 * if nothing else wants to use them. */
2833 log_info(LD_DIR, "Closing extra consensus fetch (to %s) since one "
2834 "is already downloading.", base_conn->linked_conn->address);
2835 return -1;
2839 /* If we have a chosen exit, we need to use a circuit that's
2840 * open to that exit. See what exit we meant, and whether we can use it.
2842 if (conn->chosen_exit_name) {
2843 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2844 int opt = conn->chosen_exit_optional;
2845 if (!node && !want_onehop) {
2846 /* We ran into this warning when trying to extend a circuit to a
2847 * hidden service directory for which we didn't have a router
2848 * descriptor. See flyspray task 767 for more details. We should
2849 * keep this in mind when deciding to use BEGIN_DIR cells for other
2850 * directory requests as well. -KL*/
2851 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2852 "Requested exit point '%s' is not known. %s.",
2853 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2854 if (opt) {
2855 /* If we are allowed to ignore the .exit request, do so */
2856 conn->chosen_exit_optional = 0;
2857 tor_free(conn->chosen_exit_name);
2858 return 0;
2860 return -1;
2862 if (node && !connection_ap_can_use_exit(conn, node)) {
2863 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2864 "Requested exit point '%s' is excluded or "
2865 "would refuse request. %s.",
2866 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2867 if (opt) {
2868 /* If we are allowed to ignore the .exit request, do so */
2869 conn->chosen_exit_optional = 0;
2870 tor_free(conn->chosen_exit_name);
2871 return 0;
2873 return -1;
2877 /* Find the circuit that we should use, if there is one. Otherwise
2878 * launch it
2880 retval = circuit_get_open_circ_or_launch(conn,
2881 connection_ap_get_nonrend_circ_purpose(conn),
2882 &circ);
2884 if (retval < 1) {
2885 /* We were either told "-1" (complete failure) or 0 (circuit in
2886 * progress); we can't attach this stream yet. */
2887 return retval;
2890 log_debug(LD_APP|LD_CIRC,
2891 "Attaching apconn to circ %u (stream %d sec old).",
2892 (unsigned)circ->base_.n_circ_id, conn_age);
2893 /* print the circ's path, so clients can figure out which circs are
2894 * sucking. */
2895 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
2897 /* We have found a suitable circuit for our conn. Hurray. Do
2898 * the attachment. */
2899 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
2901 } else { /* we're a rendezvous conn */
2902 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
2904 tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
2906 /* start by finding a rendezvous circuit for us */
2908 retval = circuit_get_open_circ_or_launch(
2909 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
2910 if (retval < 0) return -1; /* failed */
2912 if (retval > 0) {
2913 tor_assert(rendcirc);
2914 /* one is already established, attach */
2915 log_info(LD_REND,
2916 "rend joined circ %u (id: %" PRIu32 ") already here. "
2917 "Attaching. (stream %d sec old)",
2918 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2919 rendcirc->global_identifier, conn_age);
2920 /* Mark rendezvous circuits as 'newly dirty' every time you use
2921 * them, since the process of rebuilding a rendezvous circ is so
2922 * expensive. There is a tradeoff between linkability and
2923 * feasibility, at this point.
2925 rendcirc->base_.timestamp_dirty = time(NULL);
2927 /* We've also attempted to use them. If they fail, we need to
2928 * probe them for path bias */
2929 pathbias_count_use_attempt(rendcirc);
2931 link_apconn_to_circ(conn, rendcirc, NULL);
2932 if (connection_ap_handshake_send_begin(conn) < 0)
2933 return 0; /* already marked, let them fade away */
2934 return 1;
2937 /* At this point we need to re-check the state, since it's possible that
2938 * our call to circuit_get_open_circ_or_launch() changed the connection's
2939 * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
2940 * re-fetch the descriptor.
2942 if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2943 log_info(LD_REND, "This connection is no longer ready to attach; its "
2944 "state changed."
2945 "(We probably have to re-fetch its descriptor.)");
2946 return 0;
2949 if (rendcirc && (rendcirc->base_.purpose ==
2950 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
2951 log_info(LD_REND,
2952 "pending-join circ %u (id: %" PRIu32 ") already here, with "
2953 "intro ack. Stalling. (stream %d sec old)",
2954 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2955 rendcirc->global_identifier, conn_age);
2956 return 0;
2959 /* it's on its way. find an intro circ. */
2960 retval = circuit_get_open_circ_or_launch(
2961 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
2962 if (retval < 0) return -1; /* failed */
2964 if (retval > 0) {
2965 /* one has already sent the intro. keep waiting. */
2966 tor_assert(introcirc);
2967 log_info(LD_REND, "Intro circ %u (id: %" PRIu32 ") present and "
2968 "awaiting ACK. Rend circuit %u (id: %" PRIu32 "). "
2969 "Stalling. (stream %d sec old)",
2970 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
2971 introcirc->global_identifier,
2972 rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
2973 rendcirc ? rendcirc->global_identifier : 0,
2974 conn_age);
2975 return 0;
2978 /* now rendcirc and introcirc are each either undefined or not finished */
2980 if (rendcirc && introcirc &&
2981 rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
2982 log_info(LD_REND,
2983 "ready rend circ %u (id: %" PRIu32 ") already here. No"
2984 "intro-ack yet on intro %u (id: %" PRIu32 "). "
2985 "(stream %d sec old)",
2986 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2987 rendcirc->global_identifier,
2988 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
2989 introcirc->global_identifier, conn_age);
2991 tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2992 if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
2993 int ret;
2994 log_info(LD_REND, "Found open intro circ %u (id: %" PRIu32 "). "
2995 "Rend circuit %u (id: %" PRIu32 "); Sending "
2996 "introduction. (stream %d sec old)",
2997 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
2998 introcirc->global_identifier,
2999 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
3000 rendcirc->global_identifier, conn_age);
3001 ret = hs_client_send_introduce1(introcirc, rendcirc);
3002 switch (ret) {
3003 case 0: /* success */
3004 rendcirc->base_.timestamp_dirty = time(NULL);
3005 introcirc->base_.timestamp_dirty = time(NULL);
3007 pathbias_count_use_attempt(introcirc);
3008 pathbias_count_use_attempt(rendcirc);
3010 assert_circuit_ok(TO_CIRCUIT(rendcirc));
3011 assert_circuit_ok(TO_CIRCUIT(introcirc));
3012 return 0;
3013 case -1: /* transient error */
3014 return 0;
3015 case -2: /* permanent error */
3016 return -1;
3017 default: /* oops */
3018 tor_fragile_assert();
3019 return -1;
3024 log_info(LD_REND, "Intro %u (id: %" PRIu32 ") and rend circuit %u "
3025 "(id: %" PRIu32 ") circuits are not both ready. "
3026 "Stalling conn. (%d sec old)",
3027 introcirc ? (unsigned) TO_CIRCUIT(introcirc)->n_circ_id : 0,
3028 introcirc ? introcirc->global_identifier : 0,
3029 rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
3030 rendcirc ? rendcirc->global_identifier : 0, conn_age);
3031 return 0;
3035 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
3036 void
3037 circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
3039 uint8_t old_purpose;
3040 /* Don't allow an OR circ to become an origin circ or vice versa. */
3041 tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
3042 !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
3044 if (circ->purpose == new_purpose) return;
3046 if (CIRCUIT_IS_ORIGIN(circ)) {
3047 char old_purpose_desc[80] = "";
3049 strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
3050 old_purpose_desc[80-1] = '\0';
3052 log_debug(LD_CIRC,
3053 "changing purpose of origin circ %d "
3054 "from \"%s\" (%d) to \"%s\" (%d)",
3055 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
3056 old_purpose_desc,
3057 circ->purpose,
3058 circuit_purpose_to_string(new_purpose),
3059 new_purpose);
3062 old_purpose = circ->purpose;
3063 circ->purpose = new_purpose;
3065 if (CIRCUIT_IS_ORIGIN(circ)) {
3066 control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
3067 old_purpose);
3071 /** Mark <b>circ</b> so that no more connections can be attached to it. */
3072 void
3073 mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
3075 const or_options_t *options = get_options();
3076 tor_assert(circ);
3078 /* XXXX This is a kludge; we're only keeping it around in case there's
3079 * something that doesn't check unusable_for_new_conns, and to avoid
3080 * deeper refactoring of our expiration logic. */
3081 if (! circ->base_.timestamp_dirty)
3082 circ->base_.timestamp_dirty = approx_time();
3083 if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
3084 circ->base_.timestamp_dirty = 1; /* prevent underflow */
3085 else
3086 circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
3088 circ->unusable_for_new_conns = 1;
3092 * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
3093 * the valid delivered written fields and the overhead field,
3094 * respectively.
3096 void
3097 circuit_sent_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
3099 if (!circ) return;
3101 tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE);
3103 circ->n_delivered_written_circ_bw =
3104 tor_add_u32_nowrap(circ->n_delivered_written_circ_bw, relay_body_len);
3105 circ->n_overhead_written_circ_bw =
3106 tor_add_u32_nowrap(circ->n_overhead_written_circ_bw,
3107 RELAY_PAYLOAD_SIZE-relay_body_len);
3111 * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
3112 * the valid delivered read field and the overhead field,
3113 * respectively.
3115 void
3116 circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
3118 if (!circ) return;
3120 tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE);
3122 circ->n_delivered_read_circ_bw =
3123 tor_add_u32_nowrap(circ->n_delivered_read_circ_bw, relay_body_len);
3124 circ->n_overhead_read_circ_bw =
3125 tor_add_u32_nowrap(circ->n_overhead_read_circ_bw,
3126 RELAY_PAYLOAD_SIZE-relay_body_len);