Logs and debug info that I used for finding bug 16844
[tor.git] / src / or / circuituse.c
bloba3b71974ca2576dc495324233c16aef33a025c34
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-2015, 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 streams to them.
10 **/
12 #include "or.h"
13 #include "addressmap.h"
14 #include "channel.h"
15 #include "circpathbias.h"
16 #include "circuitbuild.h"
17 #include "circuitlist.h"
18 #include "circuitstats.h"
19 #include "circuituse.h"
20 #include "config.h"
21 #include "connection.h"
22 #include "connection_edge.h"
23 #include "control.h"
24 #include "entrynodes.h"
25 #include "nodelist.h"
26 #include "networkstatus.h"
27 #include "policies.h"
28 #include "rendclient.h"
29 #include "rendcommon.h"
30 #include "rendservice.h"
31 #include "rephist.h"
32 #include "router.h"
33 #include "routerlist.h"
35 static void circuit_expire_old_circuits_clientside(void);
36 static void circuit_increment_failure_count(void);
38 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
39 * Else return 0.
41 static int
42 circuit_is_acceptable(const origin_circuit_t *origin_circ,
43 const entry_connection_t *conn,
44 int must_be_open, uint8_t purpose,
45 int need_uptime, int need_internal,
46 time_t now)
48 const circuit_t *circ = TO_CIRCUIT(origin_circ);
49 const node_t *exitnode;
50 cpath_build_state_t *build_state;
51 tor_assert(circ);
52 tor_assert(conn);
53 tor_assert(conn->socks_request);
55 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
56 return 0; /* ignore non-open circs */
57 if (circ->marked_for_close)
58 return 0;
60 /* if this circ isn't our purpose, skip. */
61 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
62 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
63 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
64 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
65 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
66 return 0;
67 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
68 !must_be_open) {
69 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
70 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
71 return 0;
72 } else {
73 if (purpose != circ->purpose)
74 return 0;
77 /* If this is a timed-out hidden service circuit, skip it. */
78 if (origin_circ->hs_circ_has_timed_out) {
79 return 0;
82 if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
83 purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
84 if (circ->timestamp_dirty &&
85 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
86 return 0;
89 if (origin_circ->unusable_for_new_conns)
90 return 0;
92 /* decide if this circ is suitable for this conn */
94 /* for rend circs, circ->cpath->prev is not the last router in the
95 * circuit, it's the magical extra bob hop. so just check the nickname
96 * of the one we meant to finish at.
98 build_state = origin_circ->build_state;
99 exitnode = build_state_get_exit_node(build_state);
101 if (need_uptime && !build_state->need_uptime)
102 return 0;
103 if (need_internal != build_state->is_internal)
104 return 0;
106 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
107 tor_addr_t addr;
108 const int family = tor_addr_parse(&addr, conn->socks_request->address);
109 if (!exitnode && !build_state->onehop_tunnel) {
110 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
111 return 0; /* this circuit is screwed and doesn't know it yet,
112 * or is a rendezvous circuit. */
114 if (build_state->onehop_tunnel) {
115 if (!conn->want_onehop) {
116 log_debug(LD_CIRC,"Skipping one-hop circuit.");
117 return 0;
119 tor_assert(conn->chosen_exit_name);
120 if (build_state->chosen_exit) {
121 char digest[DIGEST_LEN];
122 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
123 return 0; /* broken digest, we don't want it */
124 if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
125 DIGEST_LEN))
126 return 0; /* this is a circuit to somewhere else */
127 if (tor_digest_is_zero(digest)) {
128 /* we don't know the digest; have to compare addr:port */
129 if (family < 0 ||
130 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
131 build_state->chosen_exit->port != conn->socks_request->port)
132 return 0;
135 } else {
136 if (conn->want_onehop) {
137 /* don't use three-hop circuits -- that could hurt our anonymity. */
138 return 0;
141 if (origin_circ->prepend_policy && family != -1) {
142 int r = compare_tor_addr_to_addr_policy(&addr,
143 conn->socks_request->port,
144 origin_circ->prepend_policy);
145 if (r == ADDR_POLICY_REJECTED)
146 return 0;
148 if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
149 /* can't exit from this router */
150 return 0;
152 } else { /* not general */
153 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
154 if ((edge_conn->rend_data && !origin_circ->rend_data) ||
155 (!edge_conn->rend_data && origin_circ->rend_data) ||
156 (edge_conn->rend_data && origin_circ->rend_data &&
157 rend_cmp_service_ids(edge_conn->rend_data->onion_address,
158 origin_circ->rend_data->onion_address))) {
159 /* this circ is not for this conn */
160 return 0;
164 if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
165 /* conn needs to be isolated from other conns that have already used
166 * origin_circ */
167 return 0;
170 return 1;
173 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
174 * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
176 static int
177 circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
178 const entry_connection_t *conn)
180 const circuit_t *a = TO_CIRCUIT(oa);
181 const circuit_t *b = TO_CIRCUIT(ob);
182 const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
183 int a_bits, b_bits;
185 /* If one of the circuits was allowed to live due to relaxing its timeout,
186 * it is definitely worse (it's probably a much slower path). */
187 if (oa->relaxed_timeout && !ob->relaxed_timeout)
188 return 0; /* ob is better. It's not relaxed. */
189 if (!oa->relaxed_timeout && ob->relaxed_timeout)
190 return 1; /* oa is better. It's not relaxed. */
192 switch (purpose) {
193 case CIRCUIT_PURPOSE_C_GENERAL:
194 /* if it's used but less dirty it's best;
195 * else if it's more recently created it's best
197 if (b->timestamp_dirty) {
198 if (a->timestamp_dirty &&
199 a->timestamp_dirty > b->timestamp_dirty)
200 return 1;
201 } else {
202 if (a->timestamp_dirty ||
203 timercmp(&a->timestamp_began, &b->timestamp_began, OP_GT))
204 return 1;
205 if (ob->build_state->is_internal)
206 /* XXX023 what the heck is this internal thing doing here. I
207 * think we can get rid of it. circuit_is_acceptable() already
208 * makes sure that is_internal is exactly what we need it to
209 * be. -RD */
210 return 1;
212 break;
213 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
214 /* the closer it is to ack_wait the better it is */
215 if (a->purpose > b->purpose)
216 return 1;
217 break;
218 case CIRCUIT_PURPOSE_C_REND_JOINED:
219 /* the closer it is to rend_joined the better it is */
220 if (a->purpose > b->purpose)
221 return 1;
222 break;
225 /* XXXX023 Maybe this check should get a higher priority to avoid
226 * using up circuits too rapidly. */
228 a_bits = connection_edge_update_circuit_isolation(conn,
229 (origin_circuit_t*)oa, 1);
230 b_bits = connection_edge_update_circuit_isolation(conn,
231 (origin_circuit_t*)ob, 1);
232 /* if x_bits < 0, then we have not used x for anything; better not to dirty
233 * a connection if we can help it. */
234 if (a_bits < 0) {
235 return 0;
236 } else if (b_bits < 0) {
237 return 1;
239 a_bits &= ~ oa->isolation_flags_mixed;
240 a_bits &= ~ ob->isolation_flags_mixed;
241 if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
242 /* The fewer new restrictions we need to make on a circuit for stream
243 * isolation, the better. */
244 return 1;
247 return 0;
250 /** Find the best circ that conn can use, preferably one which is
251 * dirty. Circ must not be too old.
253 * Conn must be defined.
255 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
257 * circ_purpose specifies what sort of circuit we must have.
258 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
260 * If it's REND_JOINED and must_be_open==0, then return the closest
261 * rendezvous-purposed circuit that you can find.
263 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
264 * closest introduce-purposed circuit that you can find.
266 static origin_circuit_t *
267 circuit_get_best(const entry_connection_t *conn,
268 int must_be_open, uint8_t purpose,
269 int need_uptime, int need_internal)
271 origin_circuit_t *best=NULL;
272 struct timeval now;
273 int intro_going_on_but_too_old = 0;
275 tor_assert(conn);
277 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
278 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
279 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
281 tor_gettimeofday(&now);
283 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
284 origin_circuit_t *origin_circ;
285 if (!CIRCUIT_IS_ORIGIN(circ))
286 continue;
287 origin_circ = TO_ORIGIN_CIRCUIT(circ);
289 /* Log an info message if we're going to launch a new intro circ in
290 * parallel */
291 if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
292 !must_be_open && origin_circ->hs_circ_has_timed_out) {
293 intro_going_on_but_too_old = 1;
294 continue;
297 if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
298 need_uptime,need_internal, (time_t)now.tv_sec))
299 continue;
301 /* now this is an acceptable circ to hand back. but that doesn't
302 * mean it's the *best* circ to hand back. try to decide.
304 if (!best || circuit_is_better(origin_circ,best,conn))
305 best = origin_circ;
307 SMARTLIST_FOREACH_END(circ);
309 if (!best && intro_going_on_but_too_old)
310 log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
311 "right now, but it has already taken quite a while. Starting "
312 "one in parallel.");
314 return best;
317 /** Return the number of not-yet-open general-purpose origin circuits. */
318 static int
319 count_pending_general_client_circuits(void)
321 int count = 0;
323 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
324 if (circ->marked_for_close ||
325 circ->state == CIRCUIT_STATE_OPEN ||
326 circ->purpose != CIRCUIT_PURPOSE_C_GENERAL ||
327 !CIRCUIT_IS_ORIGIN(circ))
328 continue;
330 ++count;
332 SMARTLIST_FOREACH_END(circ);
334 return count;
337 #if 0
338 /** Check whether, according to the policies in <b>options</b>, the
339 * circuit <b>circ</b> makes sense. */
340 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
341 * Also, it doesn't have the right definition of an exit circuit. Also,
342 * it's never called. */
344 circuit_conforms_to_options(const origin_circuit_t *circ,
345 const or_options_t *options)
347 const crypt_path_t *cpath, *cpath_next = NULL;
349 /* first check if it includes any excluded nodes */
350 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
351 cpath_next = cpath->next;
352 if (routerset_contains_extendinfo(options->ExcludeNodes,
353 cpath->extend_info))
354 return 0;
357 /* then consider the final hop */
358 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
359 circ->cpath->prev->extend_info))
360 return 0;
362 return 1;
364 #endif
366 /** Close all circuits that start at us, aren't open, and were born
367 * at least CircuitBuildTimeout seconds ago.
369 void
370 circuit_expire_building(void)
372 /* circ_times.timeout_ms and circ_times.close_ms are from
373 * circuit_build_times_get_initial_timeout() if we haven't computed
374 * custom timeouts yet */
375 struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
376 close_cutoff, extremely_old_cutoff, hs_extremely_old_cutoff,
377 cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff;
378 const or_options_t *options = get_options();
379 struct timeval now;
380 cpath_build_state_t *build_state;
381 int any_opened_circs = 0;
383 tor_gettimeofday(&now);
385 /* Check to see if we have any opened circuits. If we don't,
386 * we want to be more lenient with timeouts, in case the
387 * user has relocated and/or changed network connections.
388 * See bug #3443. */
389 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, next_circ) {
390 if (!CIRCUIT_IS_ORIGIN(next_circ) || /* didn't originate here */
391 next_circ->marked_for_close) { /* don't mess with marked circs */
392 continue;
395 if (TO_ORIGIN_CIRCUIT(next_circ)->has_opened &&
396 next_circ->state == CIRCUIT_STATE_OPEN &&
397 TO_ORIGIN_CIRCUIT(next_circ)->build_state &&
398 TO_ORIGIN_CIRCUIT(next_circ)->build_state->desired_path_len
399 == DEFAULT_ROUTE_LEN) {
400 any_opened_circs = 1;
401 break;
403 } SMARTLIST_FOREACH_END(next_circ);
405 #define SET_CUTOFF(target, msec) do { \
406 long ms = tor_lround(msec); \
407 struct timeval diff; \
408 diff.tv_sec = ms / 1000; \
409 diff.tv_usec = (int)((ms % 1000) * 1000); \
410 timersub(&now, &diff, &target); \
411 } while (0)
414 * Because circuit build timeout is calculated only based on 3 hop
415 * general purpose circuit construction, we need to scale the timeout
416 * to make it properly apply to longer circuits, and circuits of
417 * certain usage types. The following diagram illustrates how we
418 * derive the scaling below. In short, we calculate the number
419 * of times our telescoping-based circuit construction causes cells
420 * to traverse each link for the circuit purpose types in question,
421 * and then assume each link is equivalent.
423 * OP --a--> A --b--> B --c--> C
424 * OP --a--> A --b--> B --c--> C --d--> D
426 * Let h = a = b = c = d
428 * Three hops (general_cutoff)
429 * RTTs = 3a + 2b + c
430 * RTTs = 6h
431 * Cannibalized:
432 * RTTs = a+b+c+d
433 * RTTs = 4h
434 * Four hops:
435 * RTTs = 4a + 3b + 2c + d
436 * RTTs = 10h
437 * Client INTRODUCE1+ACK: // XXX: correct?
438 * RTTs = 5a + 4b + 3c + 2d
439 * RTTs = 14h
440 * Server intro:
441 * RTTs = 4a + 3b + 2c
442 * RTTs = 9h
444 SET_CUTOFF(general_cutoff, get_circuit_build_timeout_ms());
445 SET_CUTOFF(begindir_cutoff, get_circuit_build_timeout_ms());
447 /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
448 * 4th hop. */
449 SET_CUTOFF(fourhop_cutoff, get_circuit_build_timeout_ms() * (10/6.0) + 1000);
451 /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
452 * Use the stream cutoff (more or less). */
453 SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
455 /* Be lenient with cannibalized circs. They already survived the official
456 * CBT, and they're usually not performance-critical. */
457 SET_CUTOFF(cannibalized_cutoff,
458 MAX(get_circuit_build_close_time_ms()*(4/6.0),
459 options->CircuitStreamTimeout * 1000) + 1000);
461 /* Intro circs have an extra round trip (and are also 4 hops long) */
462 SET_CUTOFF(c_intro_cutoff, get_circuit_build_timeout_ms() * (14/6.0) + 1000);
464 /* Server intro circs have an extra round trip */
465 SET_CUTOFF(s_intro_cutoff, get_circuit_build_timeout_ms() * (9/6.0) + 1000);
467 SET_CUTOFF(close_cutoff, get_circuit_build_close_time_ms());
468 SET_CUTOFF(extremely_old_cutoff, get_circuit_build_close_time_ms()*2 + 1000);
470 SET_CUTOFF(hs_extremely_old_cutoff,
471 MAX(get_circuit_build_close_time_ms()*2 + 1000,
472 options->SocksTimeout * 1000));
474 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *,victim) {
475 struct timeval cutoff;
476 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
477 victim->marked_for_close) /* don't mess with marked circs */
478 continue;
480 /* If we haven't yet started the first hop, it means we don't have
481 * any orconns available, and thus have not started counting time yet
482 * for this circuit. See circuit_deliver_create_cell() and uses of
483 * timestamp_began.
485 * Continue to wait in this case. The ORConn should timeout
486 * independently and kill us then.
488 if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
489 continue;
492 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
493 if (build_state && build_state->onehop_tunnel)
494 cutoff = begindir_cutoff;
495 else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
496 cutoff = close_cutoff;
497 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
498 victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
499 cutoff = c_intro_cutoff;
500 else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
501 cutoff = s_intro_cutoff;
502 else if (victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
503 cutoff = stream_cutoff;
504 else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
505 cutoff = close_cutoff;
506 else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
507 victim->state != CIRCUIT_STATE_OPEN)
508 cutoff = cannibalized_cutoff;
509 else if (build_state && build_state->desired_path_len >= 4)
510 cutoff = fourhop_cutoff;
511 else
512 cutoff = general_cutoff;
514 if (TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)
515 cutoff = hs_extremely_old_cutoff;
517 if (timercmp(&victim->timestamp_began, &cutoff, OP_GT))
518 continue; /* it's still young, leave it alone */
520 /* We need to double-check the opened state here because
521 * we don't want to consider opened 1-hop dircon circuits for
522 * deciding when to relax the timeout, but we *do* want to relax
523 * those circuits too if nothing else is opened *and* they still
524 * aren't either. */
525 if (!any_opened_circs && victim->state != CIRCUIT_STATE_OPEN) {
526 /* It's still young enough that we wouldn't close it, right? */
527 if (timercmp(&victim->timestamp_began, &close_cutoff, OP_GT)) {
528 if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
529 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
530 == CPATH_STATE_OPEN;
531 log_info(LD_CIRC,
532 "No circuits are opened. Relaxing timeout for circuit %d "
533 "(a %s %d-hop circuit in state %s with channel state %s). "
534 "%d guards are live.",
535 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
536 circuit_purpose_to_string(victim->purpose),
537 TO_ORIGIN_CIRCUIT(victim)->build_state ?
538 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
540 circuit_state_to_string(victim->state),
541 channel_state_to_string(victim->n_chan->state),
542 num_live_entry_guards(0));
544 /* We count the timeout here for CBT, because technically this
545 * was a timeout, and the timeout value needs to reset if we
546 * see enough of them. Note this means we also need to avoid
547 * double-counting below, too. */
548 circuit_build_times_count_timeout(get_circuit_build_times_mutable(),
549 first_hop_succeeded);
550 TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
552 continue;
553 } else {
554 static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
555 const double build_close_ms = get_circuit_build_close_time_ms();
556 log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
557 "No circuits are opened. Relaxed timeout for circuit %d "
558 "(a %s %d-hop circuit in state %s with channel state %s) to "
559 "%ldms. However, it appears the circuit has timed out "
560 "anyway. %d guards are live.",
561 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
562 circuit_purpose_to_string(victim->purpose),
563 TO_ORIGIN_CIRCUIT(victim)->build_state ?
564 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
566 circuit_state_to_string(victim->state),
567 channel_state_to_string(victim->n_chan->state),
568 (long)build_close_ms,
569 num_live_entry_guards(0));
573 #if 0
574 /* some debug logs, to help track bugs */
575 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
576 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
577 if (!victim->timestamp_dirty)
578 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
579 "(clean).",
580 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
581 victim->purpose, victim->build_state->chosen_exit_name,
582 victim->n_circ_id);
583 else
584 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
585 "%d secs since dirty.",
586 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
587 victim->purpose, victim->build_state->chosen_exit_name,
588 victim->n_circ_id,
589 (int)(now - victim->timestamp_dirty));
591 #endif
593 /* if circ is !open, or if it's open but purpose is a non-finished
594 * intro or rend, then mark it for close */
595 if (victim->state == CIRCUIT_STATE_OPEN) {
596 switch (victim->purpose) {
597 default: /* most open circuits can be left alone. */
598 continue; /* yes, continue inside a switch refers to the nearest
599 * enclosing loop. C is smart. */
600 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
601 break; /* too old, need to die */
602 case CIRCUIT_PURPOSE_C_REND_READY:
603 /* it's a rend_ready circ -- has it already picked a query? */
604 /* c_rend_ready circs measure age since timestamp_dirty,
605 * because that's set when they switch purposes
607 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
608 victim->timestamp_dirty > cutoff.tv_sec)
609 continue;
610 break;
611 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
612 /* Open path bias testing circuits are given a long
613 * time to complete the test, but not forever */
614 TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
615 break;
616 case CIRCUIT_PURPOSE_C_INTRODUCING:
617 /* We keep old introducing circuits around for
618 * a while in parallel, and they can end up "opened".
619 * We decide below if we're going to mark them timed
620 * out and eventually close them.
622 break;
623 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
624 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
625 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
626 /* rend and intro circs become dirty each time they
627 * make an introduction attempt. so timestamp_dirty
628 * will reflect the time since the last attempt.
630 if (victim->timestamp_dirty > cutoff.tv_sec)
631 continue;
632 break;
634 } else { /* circuit not open, consider recording failure as timeout */
635 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
636 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
638 if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
639 log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
640 "yet has attached streams!",
641 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
642 victim->purpose,
643 circuit_purpose_to_string(victim->purpose));
644 tor_fragile_assert();
645 continue;
648 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
649 circuit_build_times_enough_to_compute(get_circuit_build_times())) {
650 /* Circuits are allowed to last longer for measurement.
651 * Switch their purpose and wait. */
652 if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
653 control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim),
654 CIRC_EVENT_FAILED,
655 END_CIRC_REASON_TIMEOUT);
656 circuit_change_purpose(victim, CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT);
657 /* Record this failure to check for too many timeouts
658 * in a row. This function does not record a time value yet
659 * (we do that later); it only counts the fact that we did
660 * have a timeout. We also want to avoid double-counting
661 * already "relaxed" circuits, which are counted above. */
662 if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
663 circuit_build_times_count_timeout(
664 get_circuit_build_times_mutable(),
665 first_hop_succeeded);
667 continue;
671 * If the circuit build time is much greater than we would have cut
672 * it off at, we probably had a suspend event along this codepath,
673 * and we should discard the value.
675 if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, OP_LT)) {
676 log_notice(LD_CIRC,
677 "Extremely large value for circuit build timeout: %lds. "
678 "Assuming clock jump. Purpose %d (%s)",
679 (long)(now.tv_sec - victim->timestamp_began.tv_sec),
680 victim->purpose,
681 circuit_purpose_to_string(victim->purpose));
682 } else if (circuit_build_times_count_close(
683 get_circuit_build_times_mutable(),
684 first_hop_succeeded,
685 (time_t)victim->timestamp_created.tv_sec)) {
686 circuit_build_times_set_timeout(get_circuit_build_times_mutable());
691 /* If this is a hidden service client circuit which is far enough
692 * along in connecting to its destination, and we haven't already
693 * flagged it as 'timed out', and the user has not told us to
694 * close such circs immediately on timeout, flag it as 'timed out'
695 * so we'll launch another intro or rend circ, but don't mark it
696 * for close yet.
698 * (Circs flagged as 'timed out' are given a much longer timeout
699 * period above, so we won't close them in the next call to
700 * circuit_expire_building.) */
701 if (!(options->CloseHSClientCircuitsImmediatelyOnTimeout) &&
702 !(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)) {
703 switch (victim->purpose) {
704 case CIRCUIT_PURPOSE_C_REND_READY:
705 /* We only want to spare a rend circ if it has been specified in
706 * an INTRODUCE1 cell sent to a hidden service. A circ's
707 * pending_final_cpath field is non-NULL iff it is a rend circ
708 * and we have tried to send an INTRODUCE1 cell specifying it.
709 * Thus, if the pending_final_cpath field *is* NULL, then we
710 * want to not spare it. */
711 if (TO_ORIGIN_CIRCUIT(victim)->build_state &&
712 TO_ORIGIN_CIRCUIT(victim)->build_state->pending_final_cpath ==
713 NULL)
714 break;
715 /* fallthrough! */
716 case CIRCUIT_PURPOSE_C_INTRODUCING:
717 /* connection_ap_handshake_attach_circuit() will relaunch for us */
718 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
719 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
720 /* If we have reached this line, we want to spare the circ for now. */
721 log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
722 "as timed-out HS circ",
723 (unsigned)victim->n_circ_id,
724 victim->state, circuit_state_to_string(victim->state),
725 victim->purpose);
726 TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
727 continue;
728 default:
729 break;
733 /* If this is a service-side rendezvous circuit which is far
734 * enough along in connecting to its destination, consider sparing
735 * it. */
736 if (!(options->CloseHSServiceRendCircuitsImmediatelyOnTimeout) &&
737 !(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
738 victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
739 log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
740 "as timed-out HS circ; relaunching rendezvous attempt.",
741 (unsigned)victim->n_circ_id,
742 victim->state, circuit_state_to_string(victim->state),
743 victim->purpose);
744 TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
745 rend_service_relaunch_rendezvous(TO_ORIGIN_CIRCUIT(victim));
746 continue;
749 if (victim->n_chan)
750 log_info(LD_CIRC,
751 "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
752 "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
753 channel_get_canonical_remote_descr(victim->n_chan),
754 (unsigned)victim->n_circ_id,
755 TO_ORIGIN_CIRCUIT(victim)->has_opened,
756 victim->state, circuit_state_to_string(victim->state),
757 victim->purpose,
758 TO_ORIGIN_CIRCUIT(victim)->build_state ?
759 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
760 -1);
761 else
762 log_info(LD_CIRC,
763 "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
764 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
765 (unsigned)victim->n_circ_id,
766 TO_ORIGIN_CIRCUIT(victim)->has_opened,
767 victim->state,
768 circuit_state_to_string(victim->state), victim->purpose,
769 TO_ORIGIN_CIRCUIT(victim)->build_state ?
770 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
771 -1);
773 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
774 if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
775 circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
776 else
777 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
779 pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
780 } SMARTLIST_FOREACH_END(victim);
783 /** For debugging #8387: track when we last called
784 * circuit_expire_old_circuits_clientside. */
785 static time_t last_expired_clientside_circuits = 0;
788 * As a diagnostic for bug 8387, log information about how many one-hop
789 * circuits we have around that have been there for at least <b>age</b>
790 * seconds. Log a few of them.
792 void
793 circuit_log_ancient_one_hop_circuits(int age)
795 #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
796 time_t now = time(NULL);
797 time_t cutoff = now - age;
798 int n_found = 0;
799 smartlist_t *log_these = smartlist_new();
801 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
802 const origin_circuit_t *ocirc;
803 if (! CIRCUIT_IS_ORIGIN(circ))
804 continue;
805 if (circ->timestamp_created.tv_sec >= cutoff)
806 continue;
807 ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
809 if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
810 ++n_found;
812 if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
813 smartlist_add(log_these, (origin_circuit_t*) ocirc);
816 SMARTLIST_FOREACH_END(circ);
818 if (n_found == 0)
819 goto done;
821 log_notice(LD_HEARTBEAT,
822 "Diagnostic for issue 8387: Found %d one-hop circuits more "
823 "than %d seconds old! Logging %d...",
824 n_found, age, smartlist_len(log_these));
826 SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
827 char created[ISO_TIME_LEN+1];
828 int stream_num;
829 const edge_connection_t *conn;
830 char *dirty = NULL;
831 const circuit_t *circ = TO_CIRCUIT(ocirc);
833 format_local_iso_time(created,
834 (time_t)circ->timestamp_created.tv_sec);
836 if (circ->timestamp_dirty) {
837 char dirty_since[ISO_TIME_LEN+1];
838 format_local_iso_time(dirty_since, circ->timestamp_dirty);
840 tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
841 dirty_since, (long)(now - circ->timestamp_dirty),
842 (long) get_options()->MaxCircuitDirtiness);
843 } else {
844 dirty = tor_strdup("Not marked dirty");
847 log_notice(LD_HEARTBEAT, " #%d created at %s. %s, %s. %s for close. "
848 "Package window: %d. "
849 "%s for new conns. %s.",
850 ocirc_sl_idx,
851 created,
852 circuit_state_to_string(circ->state),
853 circuit_purpose_to_string(circ->purpose),
854 circ->marked_for_close ? "Marked" : "Not marked",
855 circ->package_window,
856 ocirc->unusable_for_new_conns ? "Not usable" : "usable",
857 dirty);
858 tor_free(dirty);
860 stream_num = 0;
861 for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
862 const connection_t *c = TO_CONN(conn);
863 char stream_created[ISO_TIME_LEN+1];
864 if (++stream_num >= 5)
865 break;
867 format_local_iso_time(stream_created, c->timestamp_created);
869 log_notice(LD_HEARTBEAT, " Stream#%d created at %s. "
870 "%s conn in state %s. "
871 "It is %slinked and %sreading from a linked connection %p. "
872 "Package window %d. "
873 "%s for close (%s:%d). Hold-open is %sset. "
874 "Has %ssent RELAY_END. %s on circuit.",
875 stream_num,
876 stream_created,
877 conn_type_to_string(c->type),
878 conn_state_to_string(c->type, c->state),
879 c->linked ? "" : "not ",
880 c->reading_from_linked_conn ? "": "not",
881 c->linked_conn,
882 conn->package_window,
883 c->marked_for_close ? "Marked" : "Not marked",
884 c->marked_for_close_file ? c->marked_for_close_file : "--",
885 c->marked_for_close,
886 c->hold_open_until_flushed ? "" : "not ",
887 conn->edge_has_sent_end ? "" : "not ",
888 conn->edge_blocked_on_circ ? "Blocked" : "Not blocked");
889 if (! c->linked_conn)
890 continue;
892 c = c->linked_conn;
894 log_notice(LD_HEARTBEAT, " Linked to %s connection in state %s "
895 "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
896 conn_type_to_string(c->type),
897 conn_state_to_string(c->type, c->state),
898 c->purpose,
899 c->marked_for_close ? "Marked" : "Not marked",
900 c->marked_for_close_file ? c->marked_for_close_file : "--",
901 c->marked_for_close,
902 c->hold_open_until_flushed ? "" : "not ");
904 } SMARTLIST_FOREACH_END(ocirc);
906 log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
907 "circuit_expire_old_circuits_clientside().",
908 (long)(now - last_expired_clientside_circuits));
910 done:
911 smartlist_free(log_these);
914 /** Remove any elements in <b>needed_ports</b> that are handled by an
915 * open or in-progress circuit.
917 void
918 circuit_remove_handled_ports(smartlist_t *needed_ports)
920 int i;
921 uint16_t *port;
923 for (i = 0; i < smartlist_len(needed_ports); ++i) {
924 port = smartlist_get(needed_ports, i);
925 tor_assert(*port);
926 if (circuit_stream_is_being_handled(NULL, *port,
927 MIN_CIRCUITS_HANDLING_STREAM)) {
928 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
929 smartlist_del(needed_ports, i--);
930 tor_free(port);
931 } else {
932 log_debug(LD_CIRC,"Port %d is not handled.", *port);
937 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
938 * will have an acceptable exit node for exit stream <b>conn</b> if it
939 * is defined, else for "*:port".
940 * Else return 0.
943 circuit_stream_is_being_handled(entry_connection_t *conn,
944 uint16_t port, int min)
946 const node_t *exitnode;
947 int num=0;
948 time_t now = time(NULL);
949 int need_uptime = smartlist_contains_int_as_string(
950 get_options()->LongLivedPorts,
951 conn ? conn->socks_request->port : port);
953 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
954 if (CIRCUIT_IS_ORIGIN(circ) &&
955 !circ->marked_for_close &&
956 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
957 (!circ->timestamp_dirty ||
958 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
959 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
960 cpath_build_state_t *build_state = origin_circ->build_state;
961 if (build_state->is_internal || build_state->onehop_tunnel)
962 continue;
963 if (origin_circ->unusable_for_new_conns)
964 continue;
966 exitnode = build_state_get_exit_node(build_state);
967 if (exitnode && (!need_uptime || build_state->need_uptime)) {
968 int ok;
969 if (conn) {
970 ok = connection_ap_can_use_exit(conn, exitnode);
971 } else {
972 addr_policy_result_t r;
973 r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
974 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
976 if (ok) {
977 if (++num >= min)
978 return 1;
983 SMARTLIST_FOREACH_END(circ);
984 return 0;
987 /** Don't keep more than this many unused open circuits around. */
988 #define MAX_UNUSED_OPEN_CIRCUITS 14
990 /** Figure out how many circuits we have open that are clean. Make
991 * sure it's enough for all the upcoming behaviors we predict we'll have.
992 * But put an upper bound on the total number of circuits.
994 static void
995 circuit_predict_and_launch_new(void)
997 int num=0, num_internal=0, num_uptime_internal=0;
998 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
999 int port_needs_uptime=0, port_needs_capacity=1;
1000 time_t now = time(NULL);
1001 int flags = 0;
1003 /* First, count how many of each type of circuit we have already. */
1004 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1005 cpath_build_state_t *build_state;
1006 origin_circuit_t *origin_circ;
1007 if (!CIRCUIT_IS_ORIGIN(circ))
1008 continue;
1009 if (circ->marked_for_close)
1010 continue; /* don't mess with marked circs */
1011 if (circ->timestamp_dirty)
1012 continue; /* only count clean circs */
1013 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
1014 continue; /* only pay attention to general-purpose circs */
1015 origin_circ = TO_ORIGIN_CIRCUIT(circ);
1016 if (origin_circ->unusable_for_new_conns)
1017 continue;
1018 build_state = origin_circ->build_state;
1019 if (build_state->onehop_tunnel)
1020 continue;
1021 num++;
1022 if (build_state->is_internal)
1023 num_internal++;
1024 if (build_state->need_uptime && build_state->is_internal)
1025 num_uptime_internal++;
1027 SMARTLIST_FOREACH_END(circ);
1029 /* If that's enough, then stop now. */
1030 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
1031 return; /* we already have many, making more probably will hurt */
1033 /* Second, see if we need any more exit circuits. */
1034 /* check if we know of a port that's been requested recently
1035 * and no circuit is currently available that can handle it.
1036 * Exits (obviously) require an exit circuit. */
1037 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
1038 &port_needs_capacity)
1039 && router_have_consensus_path() == CONSENSUS_PATH_EXIT) {
1040 if (port_needs_uptime)
1041 flags |= CIRCLAUNCH_NEED_UPTIME;
1042 if (port_needs_capacity)
1043 flags |= CIRCLAUNCH_NEED_CAPACITY;
1044 log_info(LD_CIRC,
1045 "Have %d clean circs (%d internal), need another exit circ.",
1046 num, num_internal);
1047 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1048 return;
1051 /* Third, see if we need any more hidden service (server) circuits.
1052 * HS servers only need an internal circuit. */
1053 if (num_rend_services() && num_uptime_internal < 3
1054 && router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
1055 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
1056 CIRCLAUNCH_IS_INTERNAL);
1057 log_info(LD_CIRC,
1058 "Have %d clean circs (%d internal), need another internal "
1059 "circ for my hidden service.",
1060 num, num_internal);
1061 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1062 return;
1065 /* Fourth, see if we need any more hidden service (client) circuits.
1066 * HS clients only need an internal circuit. */
1067 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
1068 &hidserv_needs_capacity) &&
1069 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
1070 num_internal<2)
1071 && router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
1072 if (hidserv_needs_uptime)
1073 flags |= CIRCLAUNCH_NEED_UPTIME;
1074 if (hidserv_needs_capacity)
1075 flags |= CIRCLAUNCH_NEED_CAPACITY;
1076 flags |= CIRCLAUNCH_IS_INTERNAL;
1077 log_info(LD_CIRC,
1078 "Have %d clean circs (%d uptime-internal, %d internal), need"
1079 " another hidden service circ.",
1080 num, num_uptime_internal, num_internal);
1081 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1082 return;
1085 /* Finally, check to see if we still need more circuits to learn
1086 * a good build timeout. But if we're close to our max number we
1087 * want, don't do another -- we want to leave a few slots open so
1088 * we can still build circuits preemptively as needed.
1089 * XXXX make the assumption that build timeout streams should be
1090 * created whenever we can build internal circuits. */
1091 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
1092 if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
1093 ! circuit_build_times_disabled() &&
1094 circuit_build_times_needs_circuits_now(get_circuit_build_times())) {
1095 flags = CIRCLAUNCH_NEED_CAPACITY;
1096 /* if there are no exits in the consensus, make timeout
1097 * circuits internal */
1098 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
1099 flags |= CIRCLAUNCH_IS_INTERNAL;
1100 log_info(LD_CIRC,
1101 "Have %d clean circs need another buildtime test circ.", num);
1102 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
1103 return;
1108 /** Build a new test circuit every 5 minutes */
1109 #define TESTING_CIRCUIT_INTERVAL 300
1111 /** This function is called once a second, if router_have_min_dir_info() is
1112 * true. Its job is to make sure all services we offer have enough circuits
1113 * available. Some services just want enough circuits for current tasks,
1114 * whereas others want a minimum set of idle circuits hanging around.
1116 void
1117 circuit_build_needed_circs(time_t now)
1119 const or_options_t *options = get_options();
1121 /* launch a new circ for any pending streams that need one
1122 * XXXX make the assumption that (some) AP streams (i.e. HS clients)
1123 * don't require an exit circuit, review in #13814.
1124 * This allows HSs to function in a consensus without exits. */
1125 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
1126 connection_ap_attach_pending();
1128 /* make sure any hidden services have enough intro points
1129 * HS intro point streams only require an internal circuit */
1130 if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
1131 rend_consider_services_intro_points();
1133 circuit_expire_old_circs_as_needed(now);
1135 if (!options->DisablePredictedCircuits)
1136 circuit_predict_and_launch_new();
1140 * Called once a second either directly or from
1141 * circuit_build_needed_circs(). As appropriate (once per NewCircuitPeriod)
1142 * resets failure counts and expires old circuits.
1144 void
1145 circuit_expire_old_circs_as_needed(time_t now)
1147 static time_t time_to_expire_and_reset = 0;
1149 if (time_to_expire_and_reset < now) {
1150 circuit_reset_failure_count(1);
1151 time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
1152 if (proxy_mode(get_options()))
1153 addressmap_clean(now);
1154 circuit_expire_old_circuits_clientside();
1156 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
1158 /* If we ever re-enable, this has to move into
1159 * circuit_build_needed_circs */
1161 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
1162 if (get_options()->RunTesting &&
1163 circ &&
1164 circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
1165 log_fn(LOG_INFO,"Creating a new testing circuit.");
1166 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
1168 #endif
1172 /** If the stream <b>conn</b> is a member of any of the linked
1173 * lists of <b>circ</b>, then remove it from the list.
1175 void
1176 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
1178 edge_connection_t *prevconn;
1180 tor_assert(circ);
1181 tor_assert(conn);
1183 if (conn->base_.type == CONN_TYPE_AP) {
1184 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1185 entry_conn->may_use_optimistic_data = 0;
1187 conn->cpath_layer = NULL; /* don't keep a stale pointer */
1188 conn->on_circuit = NULL;
1190 if (CIRCUIT_IS_ORIGIN(circ)) {
1191 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1192 int removed = 0;
1193 if (conn == origin_circ->p_streams) {
1194 origin_circ->p_streams = conn->next_stream;
1195 removed = 1;
1196 } else {
1197 for (prevconn = origin_circ->p_streams;
1198 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1199 prevconn = prevconn->next_stream)
1201 if (prevconn && prevconn->next_stream) {
1202 prevconn->next_stream = conn->next_stream;
1203 removed = 1;
1206 if (removed) {
1207 log_debug(LD_APP, "Removing stream %d from circ %u",
1208 conn->stream_id, (unsigned)circ->n_circ_id);
1210 /* If the stream was removed, and it was a rend stream, decrement the
1211 * number of streams on the circuit associated with the rend service.
1213 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1214 tor_assert(origin_circ->rend_data);
1215 origin_circ->rend_data->nr_streams--;
1217 return;
1219 } else {
1220 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1221 if (conn == or_circ->n_streams) {
1222 or_circ->n_streams = conn->next_stream;
1223 return;
1225 if (conn == or_circ->resolving_streams) {
1226 or_circ->resolving_streams = conn->next_stream;
1227 return;
1230 for (prevconn = or_circ->n_streams;
1231 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1232 prevconn = prevconn->next_stream)
1234 if (prevconn && prevconn->next_stream) {
1235 prevconn->next_stream = conn->next_stream;
1236 return;
1239 for (prevconn = or_circ->resolving_streams;
1240 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1241 prevconn = prevconn->next_stream)
1243 if (prevconn && prevconn->next_stream) {
1244 prevconn->next_stream = conn->next_stream;
1245 return;
1249 log_warn(LD_BUG,"Edge connection not in circuit's list.");
1250 /* Don't give an error here; it's harmless. */
1251 tor_fragile_assert();
1254 /** If we haven't yet decided on a good timeout value for circuit
1255 * building, we close idles circuits aggressively so we can get more
1256 * data points. */
1257 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
1259 /** Find each circuit that has been unused for too long, or dirty
1260 * for too long and has no streams on it: mark it for close.
1262 static void
1263 circuit_expire_old_circuits_clientside(void)
1265 struct timeval cutoff, now;
1267 tor_gettimeofday(&now);
1268 cutoff = now;
1269 last_expired_clientside_circuits = now.tv_sec;
1271 if (! circuit_build_times_disabled() &&
1272 circuit_build_times_needs_circuits(get_circuit_build_times())) {
1273 /* Circuits should be shorter lived if we need more of them
1274 * for learning a good build timeout */
1275 cutoff.tv_sec -= IDLE_TIMEOUT_WHILE_LEARNING;
1276 } else {
1277 cutoff.tv_sec -= get_options()->CircuitIdleTimeout;
1280 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1281 if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
1282 continue;
1283 /* If the circuit has been dirty for too long, and there are no streams
1284 * on it, mark it for close.
1286 if (circ->timestamp_dirty &&
1287 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
1288 now.tv_sec &&
1289 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
1290 log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
1291 "purpose %d)",
1292 (unsigned)circ->n_circ_id,
1293 (long)(now.tv_sec - circ->timestamp_dirty),
1294 circ->purpose);
1295 /* Don't do this magic for testing circuits. Their death is governed
1296 * by circuit_expire_building */
1297 if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
1298 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1299 } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
1300 if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
1301 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
1302 circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
1303 circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1304 circ->purpose == CIRCUIT_PURPOSE_TESTING ||
1305 (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
1306 circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
1307 circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
1308 log_debug(LD_CIRC,
1309 "Closing circuit that has been unused for %ld msec.",
1310 tv_mdiff(&circ->timestamp_began, &now));
1311 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1312 } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
1313 /* Server-side rend joined circuits can end up really old, because
1314 * they are reused by clients for longer than normal. The client
1315 * controls their lifespan. (They never become dirty, because
1316 * connection_exit_begin_conn() never marks anything as dirty.)
1317 * Similarly, server-side intro circuits last a long time. */
1318 if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
1319 circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
1320 log_notice(LD_CIRC,
1321 "Ancient non-dirty circuit %d is still around after "
1322 "%ld milliseconds. Purpose: %d (%s)",
1323 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1324 tv_mdiff(&circ->timestamp_began, &now),
1325 circ->purpose,
1326 circuit_purpose_to_string(circ->purpose));
1327 TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
1332 } SMARTLIST_FOREACH_END(circ);
1335 /** How long do we wait before killing circuits with the properties
1336 * described below?
1338 * Probably we could choose a number here as low as 5 to 10 seconds,
1339 * since these circs are used for begindir, and a) generally you either
1340 * ask another begindir question right after or you don't for a long time,
1341 * b) clients at least through 0.2.1.x choose from the whole set of
1342 * directory mirrors at each choice, and c) re-establishing a one-hop
1343 * circuit via create-fast is a light operation assuming the TLS conn is
1344 * still there.
1346 * I expect "b" to go away one day when we move to using directory
1347 * guards, but I think "a" and "c" are good enough reasons that a low
1348 * number is safe even then.
1350 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
1352 /** Find each non-origin circuit that has been unused for too long,
1353 * has no streams on it, used a create_fast, and ends here: mark it
1354 * for close.
1356 void
1357 circuit_expire_old_circuits_serverside(time_t now)
1359 or_circuit_t *or_circ;
1360 time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
1362 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1363 if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
1364 continue;
1365 or_circ = TO_OR_CIRCUIT(circ);
1366 /* If the circuit has been idle for too long, and there are no streams
1367 * on it, and it ends here, and it used a create_fast, mark it for close.
1369 if (or_circ->is_first_hop && !circ->n_chan &&
1370 !or_circ->n_streams && !or_circ->resolving_streams &&
1371 or_circ->p_chan &&
1372 channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
1373 log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
1374 (unsigned)or_circ->p_circ_id,
1375 (int)(now - channel_when_last_xmit(or_circ->p_chan)));
1376 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1379 SMARTLIST_FOREACH_END(circ);
1382 /** Number of testing circuits we want open before testing our bandwidth. */
1383 #define NUM_PARALLEL_TESTING_CIRCS 4
1385 /** True iff we've ever had enough testing circuits open to test our
1386 * bandwidth. */
1387 static int have_performed_bandwidth_test = 0;
1389 /** Reset have_performed_bandwidth_test, so we'll start building
1390 * testing circuits again so we can exercise our bandwidth. */
1391 void
1392 reset_bandwidth_test(void)
1394 have_performed_bandwidth_test = 0;
1397 /** Return 1 if we've already exercised our bandwidth, or if we
1398 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
1399 * established or on the way. Else return 0.
1402 circuit_enough_testing_circs(void)
1404 int num = 0;
1406 if (have_performed_bandwidth_test)
1407 return 1;
1409 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1410 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
1411 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
1412 circ->state == CIRCUIT_STATE_OPEN)
1413 num++;
1415 SMARTLIST_FOREACH_END(circ);
1416 return num >= NUM_PARALLEL_TESTING_CIRCS;
1419 /** A testing circuit has completed. Take whatever stats we want.
1420 * Noticing reachability is taken care of in onionskin_answer(),
1421 * so there's no need to record anything here. But if we still want
1422 * to do the bandwidth test, and we now have enough testing circuits
1423 * open, do it.
1425 static void
1426 circuit_testing_opened(origin_circuit_t *circ)
1428 if (have_performed_bandwidth_test ||
1429 !check_whether_orport_reachable()) {
1430 /* either we've already done everything we want with testing circuits,
1431 * or this testing circuit became open due to a fluke, e.g. we picked
1432 * a last hop where we already had the connection open due to an
1433 * outgoing local circuit. */
1434 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
1435 } else if (circuit_enough_testing_circs()) {
1436 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
1437 have_performed_bandwidth_test = 1;
1438 } else
1439 consider_testing_reachability(1, 0);
1442 /** A testing circuit has failed to build. Take whatever stats we want. */
1443 static void
1444 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
1446 if (server_mode(get_options()) && check_whether_orport_reachable())
1447 return;
1449 log_info(LD_GENERAL,
1450 "Our testing circuit (to see if your ORPort is reachable) "
1451 "has failed. I'll try again later.");
1453 /* These aren't used yet. */
1454 (void)circ;
1455 (void)at_last_hop;
1458 /** The circuit <b>circ</b> has just become open. Take the next
1459 * step: for rendezvous circuits, we pass circ to the appropriate
1460 * function in rendclient or rendservice. For general circuits, we
1461 * call connection_ap_attach_pending, which looks for pending streams
1462 * that could use circ.
1464 void
1465 circuit_has_opened(origin_circuit_t *circ)
1467 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
1469 /* Remember that this circuit has finished building. Now if we start
1470 * it building again later (e.g. by extending it), we will know not
1471 * to consider its build time. */
1472 circ->has_opened = 1;
1474 switch (TO_CIRCUIT(circ)->purpose) {
1475 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1476 rend_client_rendcirc_has_opened(circ);
1477 /* Start building an intro circ if we don't have one yet. */
1478 connection_ap_attach_pending();
1479 /* This isn't a call to circuit_try_attaching_streams because a
1480 * circuit in _C_ESTABLISH_REND state isn't connected to its
1481 * hidden service yet, thus we can't attach streams to it yet,
1482 * thus circuit_try_attaching_streams would always clear the
1483 * circuit's isolation state. circuit_try_attaching_streams is
1484 * called later, when the rend circ enters _C_REND_JOINED
1485 * state. */
1486 break;
1487 case CIRCUIT_PURPOSE_C_INTRODUCING:
1488 rend_client_introcirc_has_opened(circ);
1489 break;
1490 case CIRCUIT_PURPOSE_C_GENERAL:
1491 /* Tell any AP connections that have been waiting for a new
1492 * circuit that one is ready. */
1493 circuit_try_attaching_streams(circ);
1494 break;
1495 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1496 /* at Bob, waiting for introductions */
1497 rend_service_intro_has_opened(circ);
1498 break;
1499 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1500 /* at Bob, connecting to rend point */
1501 rend_service_rendezvous_has_opened(circ);
1502 break;
1503 case CIRCUIT_PURPOSE_TESTING:
1504 circuit_testing_opened(circ);
1505 break;
1506 /* default:
1507 * This won't happen in normal operation, but might happen if the
1508 * controller did it. Just let it slide. */
1512 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
1513 * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
1514 static int
1515 circuit_try_clearing_isolation_state(origin_circuit_t *circ)
1517 if (/* The circuit may have become non-open if it was cannibalized.*/
1518 circ->base_.state == CIRCUIT_STATE_OPEN &&
1519 /* If !isolation_values_set, there is nothing to clear. */
1520 circ->isolation_values_set &&
1521 /* It's not legal to clear a circuit's isolation info if it's ever had
1522 * streams attached */
1523 !circ->isolation_any_streams_attached) {
1524 /* If we have any isolation information set on this circuit, and
1525 * we didn't manage to attach any streams to it, then we can
1526 * and should clear it and try again. */
1527 circuit_clear_isolation(circ);
1528 return 1;
1529 } else {
1530 return 0;
1534 /** Called when a circuit becomes ready for streams to be attached to
1535 * it. */
1536 void
1537 circuit_try_attaching_streams(origin_circuit_t *circ)
1539 /* Attach streams to this circuit if we can. */
1540 connection_ap_attach_pending();
1542 /* The call to circuit_try_clearing_isolation_state here will do
1543 * nothing and return 0 if we didn't attach any streams to circ
1544 * above. */
1545 if (circuit_try_clearing_isolation_state(circ)) {
1546 /* Maybe *now* we can attach some streams to this circuit. */
1547 connection_ap_attach_pending();
1551 /** Called whenever a circuit could not be successfully built.
1553 void
1554 circuit_build_failed(origin_circuit_t *circ)
1556 channel_t *n_chan = NULL;
1557 /* we should examine circ and see if it failed because of
1558 * the last hop or an earlier hop. then use this info below.
1560 int failed_at_last_hop = 0;
1561 /* If the last hop isn't open, and the second-to-last is, we failed
1562 * at the last hop. */
1563 if (circ->cpath &&
1564 circ->cpath->prev->state != CPATH_STATE_OPEN &&
1565 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
1566 failed_at_last_hop = 1;
1568 if (circ->cpath &&
1569 circ->cpath->state != CPATH_STATE_OPEN &&
1570 ! circ->base_.received_destroy) {
1571 /* We failed at the first hop for some reason other than a DESTROY cell.
1572 * If there's an OR connection to blame, blame it. Also, avoid this relay
1573 * for a while, and fail any one-hop directory fetches destined for it. */
1574 const char *n_chan_id = circ->cpath->extend_info->identity_digest;
1575 int already_marked = 0;
1576 if (circ->base_.n_chan) {
1577 n_chan = circ->base_.n_chan;
1579 if (n_chan->is_bad_for_new_circs) {
1580 /* We only want to blame this router when a fresh healthy
1581 * connection fails. So don't mark this router as newly failed,
1582 * since maybe this was just an old circuit attempt that's
1583 * finally timing out now. Also, there's no need to blow away
1584 * circuits/streams/etc, since the failure of an unhealthy conn
1585 * doesn't tell us much about whether a healthy conn would
1586 * succeed. */
1587 already_marked = 1;
1589 log_info(LD_OR,
1590 "Our circuit failed to get a response from the first hop "
1591 "(%s). I'm going to try to rotate to a better connection.",
1592 channel_get_canonical_remote_descr(n_chan));
1593 n_chan->is_bad_for_new_circs = 1;
1594 } else {
1595 log_info(LD_OR,
1596 "Our circuit died before the first hop with no connection");
1598 if (n_chan_id && !already_marked) {
1599 entry_guard_register_connect_status(n_chan_id, 0, 1, time(NULL));
1600 /* if there are any one-hop streams waiting on this circuit, fail
1601 * them now so they can retry elsewhere. */
1602 connection_ap_fail_onehop(n_chan_id, circ->build_state);
1606 switch (circ->base_.purpose) {
1607 case CIRCUIT_PURPOSE_C_GENERAL:
1608 /* If we never built the circuit, note it as a failure. */
1609 circuit_increment_failure_count();
1610 if (failed_at_last_hop) {
1611 /* Make sure any streams that demand our last hop as their exit
1612 * know that it's unlikely to happen. */
1613 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
1615 break;
1616 case CIRCUIT_PURPOSE_TESTING:
1617 circuit_testing_failed(circ, failed_at_last_hop);
1618 break;
1619 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1620 /* at Bob, waiting for introductions */
1621 if (circ->base_.state != CIRCUIT_STATE_OPEN) {
1622 circuit_increment_failure_count();
1624 /* no need to care here, because bob will rebuild intro
1625 * points periodically. */
1626 break;
1627 case CIRCUIT_PURPOSE_C_INTRODUCING:
1628 /* at Alice, connecting to intro point */
1629 /* Don't increment failure count, since Bob may have picked
1630 * the introduction point maliciously */
1631 /* Alice will pick a new intro point when this one dies, if
1632 * the stream in question still cares. No need to act here. */
1633 break;
1634 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1635 /* at Alice, waiting for Bob */
1636 circuit_increment_failure_count();
1637 /* Alice will pick a new rend point when this one dies, if
1638 * the stream in question still cares. No need to act here. */
1639 break;
1640 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1641 /* at Bob, connecting to rend point */
1642 /* Don't increment failure count, since Alice may have picked
1643 * the rendezvous point maliciously */
1644 log_info(LD_REND,
1645 "Couldn't connect to Alice's chosen rend point %s "
1646 "(%s hop failed).",
1647 escaped(build_state_get_exit_nickname(circ->build_state)),
1648 failed_at_last_hop?"last":"non-last");
1649 rend_service_relaunch_rendezvous(circ);
1650 break;
1651 /* default:
1652 * This won't happen in normal operation, but might happen if the
1653 * controller did it. Just let it slide. */
1657 /** Number of consecutive failures so far; should only be touched by
1658 * circuit_launch_new and circuit_*_failure_count.
1660 static int n_circuit_failures = 0;
1661 /** Before the last time we called circuit_reset_failure_count(), were
1662 * there a lot of failures? */
1663 static int did_circs_fail_last_period = 0;
1665 /** Don't retry launching a new circuit if we try this many times with no
1666 * success. */
1667 #define MAX_CIRCUIT_FAILURES 5
1669 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1670 * details on arguments. */
1671 origin_circuit_t *
1672 circuit_launch(uint8_t purpose, int flags)
1674 return circuit_launch_by_extend_info(purpose, NULL, flags);
1677 /** DOCDOC */
1678 static int
1679 have_enough_path_info(int need_exit)
1681 if (need_exit)
1682 return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
1683 else
1684 return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
1687 /** Launch a new circuit with purpose <b>purpose</b> and exit node
1688 * <b>extend_info</b> (or NULL to select a random exit node). If flags
1689 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
1690 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
1691 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
1692 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
1693 * Return the newly allocated circuit on success, or NULL on failure. */
1694 origin_circuit_t *
1695 circuit_launch_by_extend_info(uint8_t purpose,
1696 extend_info_t *extend_info,
1697 int flags)
1699 origin_circuit_t *circ;
1700 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
1701 int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
1702 int need_specific_rp = 0;
1704 if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
1705 log_debug(LD_CIRC,"Haven't %s yet; canceling "
1706 "circuit launch.",
1707 !router_have_minimum_dir_info() ?
1708 "fetched enough directory info" :
1709 "received a consensus with exits");
1710 return NULL;
1713 /* If Tor2webRendezvousPoints is enabled and we are dealing with an
1714 RP circuit, we want a specific RP node so we shouldn't canibalize
1715 an already existing circuit. */
1716 if (get_options()->Tor2webRendezvousPoints &&
1717 purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
1718 need_specific_rp = 1;
1721 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
1722 purpose != CIRCUIT_PURPOSE_TESTING &&
1723 !onehop_tunnel && !need_specific_rp) {
1724 /* see if there are appropriate circs available to cannibalize. */
1725 /* XXX if we're planning to add a hop, perhaps we want to look for
1726 * internal circs rather than exit circs? -RD */
1727 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
1728 if (circ) {
1729 uint8_t old_purpose = circ->base_.purpose;
1730 struct timeval old_timestamp_began = circ->base_.timestamp_began;
1732 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d (%s)",
1733 build_state_get_exit_nickname(circ->build_state), purpose,
1734 circuit_purpose_to_string(purpose));
1736 if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
1737 purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
1738 circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
1739 /* Path bias: Cannibalized rends pre-emptively count as a
1740 * successfully built but unused closed circuit. We don't
1741 * wait until the extend (or the close) because the rend
1742 * point could be malicious.
1744 * Same deal goes for client side introductions. Clients
1745 * can be manipulated to connect repeatedly to them
1746 * (especially web clients).
1748 * If we decide to probe the initial portion of these circs,
1749 * (up to the adversary's final hop), we need to remove this,
1750 * or somehow mark the circuit with a special path state.
1753 /* This must be called before the purpose change */
1754 pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
1757 circuit_change_purpose(TO_CIRCUIT(circ), purpose);
1758 /* Reset the start date of this circ, else expire_building
1759 * will see it and think it's been trying to build since it
1760 * began.
1762 * Technically, the code should reset this when the
1763 * create cell is finally sent, but we're close enough
1764 * here. */
1765 tor_gettimeofday(&circ->base_.timestamp_began);
1767 control_event_circuit_cannibalized(circ, old_purpose,
1768 &old_timestamp_began);
1770 switch (purpose) {
1771 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1772 /* it's ready right now */
1773 break;
1774 case CIRCUIT_PURPOSE_C_INTRODUCING:
1775 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1776 case CIRCUIT_PURPOSE_C_GENERAL:
1777 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1778 /* need to add a new hop */
1779 tor_assert(extend_info);
1780 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
1781 return NULL;
1782 break;
1783 default:
1784 log_warn(LD_BUG,
1785 "unexpected purpose %d when cannibalizing a circ.",
1786 purpose);
1787 tor_fragile_assert();
1788 return NULL;
1790 return circ;
1794 if (did_circs_fail_last_period &&
1795 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
1796 /* too many failed circs in a row. don't try. */
1797 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1798 return NULL;
1801 /* try a circ. if it fails, circuit_mark_for_close will increment
1802 * n_circuit_failures */
1803 return circuit_establish_circuit(purpose, extend_info, flags);
1806 /** Record another failure at opening a general circuit. When we have
1807 * too many, we'll stop trying for the remainder of this minute.
1809 static void
1810 circuit_increment_failure_count(void)
1812 ++n_circuit_failures;
1813 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
1816 /** Reset the failure count for opening general circuits. This means
1817 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1818 * stopping again.
1820 void
1821 circuit_reset_failure_count(int timeout)
1823 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
1824 did_circs_fail_last_period = 1;
1825 else
1826 did_circs_fail_last_period = 0;
1827 n_circuit_failures = 0;
1830 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1831 * there isn't one, and there isn't one on the way, launch one and return
1832 * 0. If it will never work, return -1.
1834 * Write the found or in-progress or launched circ into *circp.
1836 static int
1837 circuit_get_open_circ_or_launch(entry_connection_t *conn,
1838 uint8_t desired_circuit_purpose,
1839 origin_circuit_t **circp)
1841 origin_circuit_t *circ;
1842 int check_exit_policy;
1843 int need_uptime, need_internal;
1844 int want_onehop;
1845 const or_options_t *options = get_options();
1847 tor_assert(conn);
1848 tor_assert(circp);
1849 if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
1850 connection_t *c = ENTRY_TO_CONN(conn);
1851 log_err(LD_BUG, "Connection state mismatch: wanted "
1852 "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
1853 c->state, conn_state_to_string(c->type, c->state));
1855 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
1856 check_exit_policy =
1857 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
1858 !conn->use_begindir &&
1859 !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
1860 want_onehop = conn->want_onehop;
1862 need_uptime = !conn->want_onehop && !conn->use_begindir &&
1863 smartlist_contains_int_as_string(options->LongLivedPorts,
1864 conn->socks_request->port);
1866 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
1867 need_internal = 1;
1868 else if (conn->use_begindir || conn->want_onehop)
1869 need_internal = 1;
1870 else
1871 need_internal = 0;
1873 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
1874 need_uptime, need_internal);
1876 if (circ) {
1877 *circp = circ;
1878 return 1; /* we're happy */
1881 int have_path = have_enough_path_info(!need_internal);
1883 if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
1884 if (!connection_get_by_type(CONN_TYPE_DIR)) {
1885 int severity = LOG_NOTICE;
1886 /* FFFF if this is a tunneled directory fetch, don't yell
1887 * as loudly. the user doesn't even know it's happening. */
1888 if (entry_list_is_constrained(options) &&
1889 entries_known_but_down(options)) {
1890 log_fn(severity, LD_APP|LD_DIR,
1891 "Application request when we haven't %s. "
1892 "Optimistically trying known %s again.",
1893 !router_have_minimum_dir_info() ?
1894 "used client functionality lately" :
1895 "received a consensus with exits",
1896 options->UseBridges ? "bridges" : "entrynodes");
1897 entries_retry_all(options);
1898 } else if (!options->UseBridges || any_bridge_descriptors_known()) {
1899 log_fn(severity, LD_APP|LD_DIR,
1900 "Application request when we haven't %s. "
1901 "Optimistically trying directory fetches again.",
1902 !router_have_minimum_dir_info() ?
1903 "used client functionality lately" :
1904 "received a consensus with exits");
1905 routerlist_retry_directory_downloads(time(NULL));
1908 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1909 * 1, or when all directory attempts fail and directory_all_unreachable()
1910 * kills it.
1912 return 0;
1915 /* Do we need to check exit policy? */
1916 if (check_exit_policy) {
1917 if (!conn->chosen_exit_name) {
1918 struct in_addr in;
1919 tor_addr_t addr, *addrp=NULL;
1920 if (tor_inet_aton(conn->socks_request->address, &in)) {
1921 tor_addr_from_in(&addr, &in);
1922 addrp = &addr;
1924 if (router_exit_policy_all_nodes_reject(addrp,
1925 conn->socks_request->port,
1926 need_uptime)) {
1927 log_notice(LD_APP,
1928 "No Tor server allows exit to %s:%d. Rejecting.",
1929 safe_str_client(conn->socks_request->address),
1930 conn->socks_request->port);
1931 return -1;
1933 } else {
1934 /* XXXX024 Duplicates checks in connection_ap_handshake_attach_circuit:
1935 * refactor into a single function? */
1936 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
1937 int opt = conn->chosen_exit_optional;
1938 if (node && !connection_ap_can_use_exit(conn, node)) {
1939 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1940 "Requested exit point '%s' is excluded or "
1941 "would refuse request. %s.",
1942 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1943 if (opt) {
1944 conn->chosen_exit_optional = 0;
1945 tor_free(conn->chosen_exit_name);
1946 /* Try again. */
1947 return circuit_get_open_circ_or_launch(conn,
1948 desired_circuit_purpose,
1949 circp);
1951 return -1;
1956 /* is one already on the way? */
1957 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
1958 need_uptime, need_internal);
1959 if (circ)
1960 log_debug(LD_CIRC, "one on the way!");
1961 if (!circ) {
1962 extend_info_t *extend_info=NULL;
1963 uint8_t new_circ_purpose;
1964 const int n_pending = count_pending_general_client_circuits();
1966 if (n_pending >= options->MaxClientCircuitsPending) {
1967 static ratelim_t delay_limit = RATELIM_INIT(10*60);
1968 char *m;
1969 if ((m = rate_limit_log(&delay_limit, approx_time()))) {
1970 log_notice(LD_APP, "We'd like to launch a circuit to handle a "
1971 "connection, but we already have %d general-purpose client "
1972 "circuits pending. Waiting until some finish.%s",
1973 n_pending, m);
1974 tor_free(m);
1976 return 0;
1979 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1980 /* need to pick an intro point */
1981 rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
1982 tor_assert(rend_data);
1983 extend_info = rend_client_get_random_intro(rend_data);
1984 if (!extend_info) {
1985 log_info(LD_REND,
1986 "No intro points for '%s': re-fetching service descriptor.",
1987 safe_str_client(rend_data->onion_address));
1988 rend_client_refetch_v2_renddesc(rend_data);
1989 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
1990 return 0;
1992 log_info(LD_REND,"Chose %s as intro point for '%s'.",
1993 extend_info_describe(extend_info),
1994 safe_str_client(rend_data->onion_address));
1997 /* If we have specified a particular exit node for our
1998 * connection, then be sure to open a circuit to that exit node.
2000 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
2001 if (conn->chosen_exit_name) {
2002 const node_t *r;
2003 int opt = conn->chosen_exit_optional;
2004 r = node_get_by_nickname(conn->chosen_exit_name, 1);
2005 if (r && node_has_descriptor(r)) {
2006 /* We might want to connect to an IPv6 bridge for loading
2007 descriptors so we use the preferred address rather than
2008 the primary. */
2009 extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
2010 } else {
2011 log_debug(LD_DIR, "considering %d, %s",
2012 want_onehop, conn->chosen_exit_name);
2013 if (want_onehop && conn->chosen_exit_name[0] == '$') {
2014 /* We're asking for a one-hop circuit to a router that
2015 * we don't have a routerinfo about. Make up an extend_info. */
2016 char digest[DIGEST_LEN];
2017 char *hexdigest = conn->chosen_exit_name+1;
2018 tor_addr_t addr;
2019 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2020 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
2021 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
2022 return -1;
2024 if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
2025 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
2026 escaped_safe_str_client(conn->socks_request->address));
2027 return -1;
2029 extend_info = extend_info_new(conn->chosen_exit_name+1,
2030 digest, NULL, NULL, &addr,
2031 conn->socks_request->port);
2032 } else {
2033 /* We will need an onion key for the router, and we
2034 * don't have one. Refuse or relax requirements. */
2035 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2036 "Requested exit point '%s' is not known. %s.",
2037 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2038 if (opt) {
2039 conn->chosen_exit_optional = 0;
2040 tor_free(conn->chosen_exit_name);
2041 /* Try again with no requested exit */
2042 return circuit_get_open_circ_or_launch(conn,
2043 desired_circuit_purpose,
2044 circp);
2046 return -1;
2052 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
2053 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
2054 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
2055 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
2056 else
2057 new_circ_purpose = desired_circuit_purpose;
2059 #ifdef ENABLE_TOR2WEB_MODE
2060 if (options->Tor2webMode &&
2061 (new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
2062 new_circ_purpose == CIRCUIT_PURPOSE_C_INTRODUCING)) {
2063 want_onehop = 1;
2065 #endif
2068 int flags = CIRCLAUNCH_NEED_CAPACITY;
2069 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
2070 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2071 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
2072 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
2073 flags);
2076 extend_info_free(extend_info);
2078 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
2079 /* We just caused a circuit to get built because of this stream.
2080 * If this stream has caused a _lot_ of circuits to be built, that's
2081 * a bad sign: we should tell the user. */
2082 if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
2083 ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
2084 log_info(LD_CIRC, "The application request to %s:%d has launched "
2085 "%d circuits without finding one it likes.",
2086 escaped_safe_str_client(conn->socks_request->address),
2087 conn->socks_request->port,
2088 conn->num_circuits_launched);
2089 } else {
2090 /* help predict this next time */
2091 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
2092 if (circ) {
2093 /* write the service_id into circ */
2094 circ->rend_data = rend_data_dup(ENTRY_TO_EDGE_CONN(conn)->rend_data);
2095 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2096 circ->base_.state == CIRCUIT_STATE_OPEN)
2097 circuit_has_opened(circ);
2100 } /* endif (!circ) */
2101 if (circ) {
2102 /* Mark the circuit with the isolation fields for this connection.
2103 * When the circuit arrives, we'll clear these flags: this is
2104 * just some internal bookkeeping to make sure that we have
2105 * launched enough circuits.
2107 connection_edge_update_circuit_isolation(conn, circ, 0);
2108 } else {
2109 log_info(LD_APP,
2110 "No safe circuit (purpose %d) ready for edge "
2111 "connection; delaying.",
2112 desired_circuit_purpose);
2114 *circp = circ;
2115 return 0;
2118 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
2119 * <b>circ</b>. */
2120 static int
2121 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
2123 crypt_path_t *cpath, *cpath_next = NULL;
2124 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2125 cpath_next = cpath->next;
2126 if (crypt_path == cpath)
2127 return 1;
2129 return 0;
2132 /** Return true iff client-side optimistic data is supported. */
2133 static int
2134 optimistic_data_enabled(void)
2136 const or_options_t *options = get_options();
2137 if (options->OptimisticData < 0) {
2138 /* XXX023 consider having auto default to 1 rather than 0 before
2139 * the 0.2.3 branch goes stable. See bug 3617. -RD */
2140 const int32_t enabled =
2141 networkstatus_get_param(NULL, "UseOptimisticData", 0, 0, 1);
2142 return (int)enabled;
2144 return options->OptimisticData;
2147 /** Attach the AP stream <b>apconn</b> to circ's linked list of
2148 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
2149 * hop in circ's cpath if <b>cpath</b> is NULL.
2151 static void
2152 link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
2153 crypt_path_t *cpath)
2155 const node_t *exitnode = NULL;
2157 /* add it into the linked list of streams on this circuit */
2158 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
2159 (unsigned)circ->base_.n_circ_id);
2160 /* reset it, so we can measure circ timeouts */
2161 ENTRY_TO_CONN(apconn)->timestamp_lastread = time(NULL);
2162 ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
2163 ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
2164 /* assert_connection_ok(conn, time(NULL)); */
2165 circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
2167 if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
2168 /* We are attaching a stream to a rendezvous circuit. That means
2169 * that an attempt to connect to a hidden service just
2170 * succeeded. Tell rendclient.c. */
2171 rend_client_note_connection_attempt_ended(
2172 ENTRY_TO_EDGE_CONN(apconn)->rend_data);
2175 if (cpath) { /* we were given one; use it */
2176 tor_assert(cpath_is_on_circuit(circ, cpath));
2177 } else {
2178 /* use the last hop in the circuit */
2179 tor_assert(circ->cpath);
2180 tor_assert(circ->cpath->prev);
2181 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
2182 cpath = circ->cpath->prev;
2184 ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
2186 circ->isolation_any_streams_attached = 1;
2187 connection_edge_update_circuit_isolation(apconn, circ, 0);
2189 /* Compute the exitnode if possible, for logging below */
2190 if (cpath->extend_info)
2191 exitnode = node_get_by_id(cpath->extend_info->identity_digest);
2193 /* See if we can use optimistic data on this circuit */
2194 if (optimistic_data_enabled() &&
2195 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2196 circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED))
2197 apconn->may_use_optimistic_data = 1;
2198 else
2199 apconn->may_use_optimistic_data = 0;
2200 log_info(LD_APP, "Looks like completed circuit to %s %s allow "
2201 "optimistic data for connection to %s",
2202 circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ?
2203 /* node_describe() does the right thing if exitnode is NULL */
2204 safe_str_client(node_describe(exitnode)) :
2205 "hidden service",
2206 apconn->may_use_optimistic_data ? "does" : "doesn't",
2207 safe_str_client(apconn->socks_request->address));
2210 /** Return true iff <b>address</b> is matched by one of the entries in
2211 * TrackHostExits. */
2213 hostname_in_track_host_exits(const or_options_t *options, const char *address)
2215 if (!options->TrackHostExits)
2216 return 0;
2217 SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
2218 if (cp[0] == '.') { /* match end */
2219 if (cp[1] == '\0' ||
2220 !strcasecmpend(address, cp) ||
2221 !strcasecmp(address, &cp[1]))
2222 return 1;
2223 } else if (strcasecmp(cp, address) == 0) {
2224 return 1;
2226 } SMARTLIST_FOREACH_END(cp);
2227 return 0;
2230 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
2231 * the exit that we *did* choose for use by future connections to
2232 * <b>conn</b>'s destination.
2234 static void
2235 consider_recording_trackhost(const entry_connection_t *conn,
2236 const origin_circuit_t *circ)
2238 const or_options_t *options = get_options();
2239 char *new_address = NULL;
2240 char fp[HEX_DIGEST_LEN+1];
2242 /* Search the addressmap for this conn's destination. */
2243 /* If he's not in the address map.. */
2244 if (!options->TrackHostExits ||
2245 addressmap_have_mapping(conn->socks_request->address,
2246 options->TrackHostExitsExpire))
2247 return; /* nothing to track, or already mapped */
2249 if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
2250 !circ->build_state->chosen_exit)
2251 return;
2253 /* write down the fingerprint of the chosen exit, not the nickname,
2254 * because the chosen exit might not be named. */
2255 base16_encode(fp, sizeof(fp),
2256 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
2258 /* Add this exit/hostname pair to the addressmap. */
2259 tor_asprintf(&new_address, "%s.%s.exit",
2260 conn->socks_request->address, fp);
2262 addressmap_register(conn->socks_request->address, new_address,
2263 time(NULL) + options->TrackHostExitsExpire,
2264 ADDRMAPSRC_TRACKEXIT, 0, 0);
2267 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
2268 * begin or resolve cell as appropriate. Return values are as for
2269 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
2270 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2271 * <b>cpath</b> is NULL. */
2273 connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
2274 origin_circuit_t *circ,
2275 crypt_path_t *cpath)
2277 connection_t *base_conn = ENTRY_TO_CONN(conn);
2278 tor_assert(conn);
2279 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
2280 base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
2281 tor_assert(conn->socks_request);
2282 tor_assert(circ);
2283 tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
2285 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2287 if (!circ->base_.timestamp_dirty)
2288 circ->base_.timestamp_dirty = time(NULL);
2290 pathbias_count_use_attempt(circ);
2292 link_apconn_to_circ(conn, circ, cpath);
2293 tor_assert(conn->socks_request);
2294 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
2295 if (!conn->use_begindir)
2296 consider_recording_trackhost(conn, circ);
2297 if (connection_ap_handshake_send_begin(conn) < 0)
2298 return -1;
2299 } else {
2300 if (connection_ap_handshake_send_resolve(conn) < 0)
2301 return -1;
2304 return 1;
2307 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
2308 * we don't find one: if conn cannot be handled by any known nodes,
2309 * warn and return -1 (conn needs to die, and is maybe already marked);
2310 * else launch new circuit (if necessary) and return 0.
2311 * Otherwise, associate conn with a safe live circuit, do the
2312 * right next step, and return 1.
2314 /* XXXX this function should mark for close whenever it returns -1;
2315 * its callers shouldn't have to worry about that. */
2317 connection_ap_handshake_attach_circuit(entry_connection_t *conn)
2319 connection_t *base_conn = ENTRY_TO_CONN(conn);
2320 int retval;
2321 int conn_age;
2322 int want_onehop;
2324 tor_assert(conn);
2325 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2326 tor_assert(conn->socks_request);
2327 want_onehop = conn->want_onehop;
2329 conn_age = (int)(time(NULL) - base_conn->timestamp_created);
2331 if (conn_age >= get_options()->SocksTimeout) {
2332 int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
2333 LOG_INFO : LOG_NOTICE;
2334 log_fn(severity, LD_APP,
2335 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
2336 conn_age, safe_str_client(conn->socks_request->address),
2337 conn->socks_request->port);
2338 return -1;
2341 if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
2342 /* we're a general conn */
2343 origin_circuit_t *circ=NULL;
2345 if (conn->chosen_exit_name) {
2346 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
2347 int opt = conn->chosen_exit_optional;
2348 if (!node && !want_onehop) {
2349 /* We ran into this warning when trying to extend a circuit to a
2350 * hidden service directory for which we didn't have a router
2351 * descriptor. See flyspray task 767 for more details. We should
2352 * keep this in mind when deciding to use BEGIN_DIR cells for other
2353 * directory requests as well. -KL*/
2354 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2355 "Requested exit point '%s' is not known. %s.",
2356 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2357 if (opt) {
2358 conn->chosen_exit_optional = 0;
2359 tor_free(conn->chosen_exit_name);
2360 return 0;
2362 return -1;
2364 if (node && !connection_ap_can_use_exit(conn, node)) {
2365 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2366 "Requested exit point '%s' is excluded or "
2367 "would refuse request. %s.",
2368 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2369 if (opt) {
2370 conn->chosen_exit_optional = 0;
2371 tor_free(conn->chosen_exit_name);
2372 return 0;
2374 return -1;
2378 /* find the circuit that we should use, if there is one. */
2379 retval = circuit_get_open_circ_or_launch(
2380 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
2381 if (retval < 1) // XXX023 if we totally fail, this still returns 0 -RD
2382 return retval;
2384 log_debug(LD_APP|LD_CIRC,
2385 "Attaching apconn to circ %u (stream %d sec old).",
2386 (unsigned)circ->base_.n_circ_id, conn_age);
2387 /* print the circ's path, so people can figure out which circs are
2388 * sucking. */
2389 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
2391 /* We have found a suitable circuit for our conn. Hurray. */
2392 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
2394 } else { /* we're a rendezvous conn */
2395 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
2397 tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
2399 /* start by finding a rendezvous circuit for us */
2401 retval = circuit_get_open_circ_or_launch(
2402 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
2403 if (retval < 0) return -1; /* failed */
2405 if (retval > 0) {
2406 tor_assert(rendcirc);
2407 /* one is already established, attach */
2408 log_info(LD_REND,
2409 "rend joined circ %u already here. attaching. "
2410 "(stream %d sec old)",
2411 (unsigned)rendcirc->base_.n_circ_id, conn_age);
2412 /* Mark rendezvous circuits as 'newly dirty' every time you use
2413 * them, since the process of rebuilding a rendezvous circ is so
2414 * expensive. There is a tradeoff between linkability and
2415 * feasibility, at this point.
2417 rendcirc->base_.timestamp_dirty = time(NULL);
2419 /* We've also attempted to use them. If they fail, we need to
2420 * probe them for path bias */
2421 pathbias_count_use_attempt(rendcirc);
2423 link_apconn_to_circ(conn, rendcirc, NULL);
2424 if (connection_ap_handshake_send_begin(conn) < 0)
2425 return 0; /* already marked, let them fade away */
2426 return 1;
2429 /* At this point we need to re-check the state, since it's possible that
2430 * our call to circuit_get_open_circ_or_launch() changed the connection's
2431 * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
2432 * re-fetch the descriptor.
2434 if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2435 log_info(LD_REND, "This connection is no longer ready to attach; its "
2436 "state changed."
2437 "(We probably have to re-fetch its descriptor.)");
2438 return 0;
2441 if (rendcirc && (rendcirc->base_.purpose ==
2442 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
2443 log_info(LD_REND,
2444 "pending-join circ %u already here, with intro ack. "
2445 "Stalling. (stream %d sec old)",
2446 (unsigned)rendcirc->base_.n_circ_id, conn_age);
2447 return 0;
2450 /* it's on its way. find an intro circ. */
2451 retval = circuit_get_open_circ_or_launch(
2452 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
2453 if (retval < 0) return -1; /* failed */
2455 if (retval > 0) {
2456 /* one has already sent the intro. keep waiting. */
2457 tor_assert(introcirc);
2458 log_info(LD_REND, "Intro circ %u present and awaiting ack (rend %u). "
2459 "Stalling. (stream %d sec old)",
2460 (unsigned)introcirc->base_.n_circ_id,
2461 rendcirc ? (unsigned)rendcirc->base_.n_circ_id : 0,
2462 conn_age);
2463 return 0;
2466 /* now rendcirc and introcirc are each either undefined or not finished */
2468 if (rendcirc && introcirc &&
2469 rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
2470 log_info(LD_REND,
2471 "ready rend circ %u already here (no intro-ack yet on "
2472 "intro %u). (stream %d sec old)",
2473 (unsigned)rendcirc->base_.n_circ_id,
2474 (unsigned)introcirc->base_.n_circ_id, conn_age);
2476 tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2477 if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
2478 log_info(LD_REND,"found open intro circ %u (rend %u); sending "
2479 "introduction. (stream %d sec old)",
2480 (unsigned)introcirc->base_.n_circ_id,
2481 (unsigned)rendcirc->base_.n_circ_id,
2482 conn_age);
2483 switch (rend_client_send_introduction(introcirc, rendcirc)) {
2484 case 0: /* success */
2485 rendcirc->base_.timestamp_dirty = time(NULL);
2486 introcirc->base_.timestamp_dirty = time(NULL);
2488 pathbias_count_use_attempt(introcirc);
2489 pathbias_count_use_attempt(rendcirc);
2491 assert_circuit_ok(TO_CIRCUIT(rendcirc));
2492 assert_circuit_ok(TO_CIRCUIT(introcirc));
2493 return 0;
2494 case -1: /* transient error */
2495 return 0;
2496 case -2: /* permanent error */
2497 return -1;
2498 default: /* oops */
2499 tor_fragile_assert();
2500 return -1;
2505 log_info(LD_REND, "Intro (%u) and rend (%u) circs are not both ready. "
2506 "Stalling conn. (%d sec old)",
2507 introcirc ? (unsigned)introcirc->base_.n_circ_id : 0,
2508 rendcirc ? (unsigned)rendcirc->base_.n_circ_id : 0, conn_age);
2509 return 0;
2513 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
2514 void
2515 circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
2517 uint8_t old_purpose;
2518 /* Don't allow an OR circ to become an origin circ or vice versa. */
2519 tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
2520 !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
2522 if (circ->purpose == new_purpose) return;
2524 if (CIRCUIT_IS_ORIGIN(circ)) {
2525 char old_purpose_desc[80] = "";
2527 strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
2528 old_purpose_desc[80-1] = '\0';
2530 log_debug(LD_CIRC,
2531 "changing purpose of origin circ %d "
2532 "from \"%s\" (%d) to \"%s\" (%d)",
2533 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
2534 old_purpose_desc,
2535 circ->purpose,
2536 circuit_purpose_to_string(new_purpose),
2537 new_purpose);
2540 old_purpose = circ->purpose;
2541 circ->purpose = new_purpose;
2543 if (CIRCUIT_IS_ORIGIN(circ)) {
2544 control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
2545 old_purpose);
2549 /** Mark <b>circ</b> so that no more connections can be attached to it. */
2550 void
2551 mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
2553 const or_options_t *options = get_options();
2554 tor_assert(circ);
2556 /* XXXX025 This is a kludge; we're only keeping it around in case there's
2557 * something that doesn't check unusable_for_new_conns, and to avoid
2558 * deeper refactoring of our expiration logic. */
2559 if (! circ->base_.timestamp_dirty)
2560 circ->base_.timestamp_dirty = approx_time();
2561 if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
2562 circ->base_.timestamp_dirty = 1; /* prevent underflow */
2563 else
2564 circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
2566 circ->unusable_for_new_conns = 1;