Bug 6572: Use timestamp_created for liveness sanity checks.
[tor.git] / src / or / circuituse.c
blob14576f13d657b66767e30fa12e91d0e15ada243c
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
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 "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuitstats.h"
18 #include "circuituse.h"
19 #include "config.h"
20 #include "connection.h"
21 #include "connection_edge.h"
22 #include "control.h"
23 #include "entrynodes.h"
24 #include "nodelist.h"
25 #include "networkstatus.h"
26 #include "policies.h"
27 #include "rendclient.h"
28 #include "rendcommon.h"
29 #include "rendservice.h"
30 #include "rephist.h"
31 #include "router.h"
32 #include "routerlist.h"
34 /********* START VARIABLES **********/
36 extern circuit_t *global_circuitlist; /* from circuitlist.c */
38 /********* END VARIABLES ************/
40 static void circuit_expire_old_circuits_clientside(void);
41 static void circuit_increment_failure_count(void);
43 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
44 * Else return 0.
46 static int
47 circuit_is_acceptable(const origin_circuit_t *origin_circ,
48 const entry_connection_t *conn,
49 int must_be_open, uint8_t purpose,
50 int need_uptime, int need_internal,
51 time_t now)
53 const circuit_t *circ = TO_CIRCUIT(origin_circ);
54 const node_t *exitnode;
55 cpath_build_state_t *build_state;
56 tor_assert(circ);
57 tor_assert(conn);
58 tor_assert(conn->socks_request);
60 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
61 return 0; /* ignore non-open circs */
62 if (circ->marked_for_close)
63 return 0;
65 /* if this circ isn't our purpose, skip. */
66 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
67 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
68 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
69 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
70 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
71 return 0;
72 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
73 !must_be_open) {
74 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
75 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
76 return 0;
77 } else {
78 if (purpose != circ->purpose)
79 return 0;
82 /* If this is a timed-out hidden service circuit, skip it. */
83 if (origin_circ->hs_circ_has_timed_out) {
84 return 0;
87 if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
88 purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
89 if (circ->timestamp_dirty &&
90 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
91 return 0;
94 if (origin_circ->unusable_for_new_conns)
95 return 0;
97 /* decide if this circ is suitable for this conn */
99 /* for rend circs, circ->cpath->prev is not the last router in the
100 * circuit, it's the magical extra bob hop. so just check the nickname
101 * of the one we meant to finish at.
103 build_state = origin_circ->build_state;
104 exitnode = build_state_get_exit_node(build_state);
106 if (need_uptime && !build_state->need_uptime)
107 return 0;
108 if (need_internal != build_state->is_internal)
109 return 0;
111 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
112 tor_addr_t addr;
113 const int family = tor_addr_parse(&addr, conn->socks_request->address);
114 if (!exitnode && !build_state->onehop_tunnel) {
115 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
116 return 0; /* this circuit is screwed and doesn't know it yet,
117 * or is a rendezvous circuit. */
119 if (build_state->onehop_tunnel) {
120 if (!conn->want_onehop) {
121 log_debug(LD_CIRC,"Skipping one-hop circuit.");
122 return 0;
124 tor_assert(conn->chosen_exit_name);
125 if (build_state->chosen_exit) {
126 char digest[DIGEST_LEN];
127 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
128 return 0; /* broken digest, we don't want it */
129 if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
130 DIGEST_LEN))
131 return 0; /* this is a circuit to somewhere else */
132 if (tor_digest_is_zero(digest)) {
133 /* we don't know the digest; have to compare addr:port */
134 if (family < 0 ||
135 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
136 build_state->chosen_exit->port != conn->socks_request->port)
137 return 0;
140 } else {
141 if (conn->want_onehop) {
142 /* don't use three-hop circuits -- that could hurt our anonymity. */
143 return 0;
146 if (origin_circ->prepend_policy && family != -1) {
147 int r = compare_tor_addr_to_addr_policy(&addr,
148 conn->socks_request->port,
149 origin_circ->prepend_policy);
150 if (r == ADDR_POLICY_REJECTED)
151 return 0;
153 if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
154 /* can't exit from this router */
155 return 0;
157 } else { /* not general */
158 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
159 if ((edge_conn->rend_data && !origin_circ->rend_data) ||
160 (!edge_conn->rend_data && origin_circ->rend_data) ||
161 (edge_conn->rend_data && origin_circ->rend_data &&
162 rend_cmp_service_ids(edge_conn->rend_data->onion_address,
163 origin_circ->rend_data->onion_address))) {
164 /* this circ is not for this conn */
165 return 0;
169 if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
170 /* conn needs to be isolated from other conns that have already used
171 * origin_circ */
172 return 0;
175 return 1;
178 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
179 * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
181 static int
182 circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
183 const entry_connection_t *conn)
185 const circuit_t *a = TO_CIRCUIT(oa);
186 const circuit_t *b = TO_CIRCUIT(ob);
187 const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
188 int a_bits, b_bits;
190 /* If one of the circuits was allowed to live due to relaxing its timeout,
191 * it is definitely worse (it's probably a much slower path). */
192 if (oa->relaxed_timeout && !ob->relaxed_timeout)
193 return 0; /* ob is better. It's not relaxed. */
194 if (!oa->relaxed_timeout && ob->relaxed_timeout)
195 return 1; /* oa is better. It's not relaxed. */
197 switch (purpose) {
198 case CIRCUIT_PURPOSE_C_GENERAL:
199 /* if it's used but less dirty it's best;
200 * else if it's more recently created it's best
202 if (b->timestamp_dirty) {
203 if (a->timestamp_dirty &&
204 a->timestamp_dirty > b->timestamp_dirty)
205 return 1;
206 } else {
207 if (a->timestamp_dirty ||
208 timercmp(&a->timestamp_began, &b->timestamp_began, >))
209 return 1;
210 if (ob->build_state->is_internal)
211 /* XXX023 what the heck is this internal thing doing here. I
212 * think we can get rid of it. circuit_is_acceptable() already
213 * makes sure that is_internal is exactly what we need it to
214 * be. -RD */
215 return 1;
217 break;
218 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
219 /* the closer it is to ack_wait the better it is */
220 if (a->purpose > b->purpose)
221 return 1;
222 break;
223 case CIRCUIT_PURPOSE_C_REND_JOINED:
224 /* the closer it is to rend_joined the better it is */
225 if (a->purpose > b->purpose)
226 return 1;
227 break;
230 /* XXXX023 Maybe this check should get a higher priority to avoid
231 * using up circuits too rapidly. */
233 a_bits = connection_edge_update_circuit_isolation(conn,
234 (origin_circuit_t*)oa, 1);
235 b_bits = connection_edge_update_circuit_isolation(conn,
236 (origin_circuit_t*)ob, 1);
237 /* if x_bits < 0, then we have not used x for anything; better not to dirty
238 * a connection if we can help it. */
239 if (a_bits < 0) {
240 return 0;
241 } else if (b_bits < 0) {
242 return 1;
244 a_bits &= ~ oa->isolation_flags_mixed;
245 a_bits &= ~ ob->isolation_flags_mixed;
246 if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
247 /* The fewer new restrictions we need to make on a circuit for stream
248 * isolation, the better. */
249 return 1;
252 return 0;
255 /** Find the best circ that conn can use, preferably one which is
256 * dirty. Circ must not be too old.
258 * Conn must be defined.
260 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
262 * circ_purpose specifies what sort of circuit we must have.
263 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
265 * If it's REND_JOINED and must_be_open==0, then return the closest
266 * rendezvous-purposed circuit that you can find.
268 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
269 * closest introduce-purposed circuit that you can find.
271 static origin_circuit_t *
272 circuit_get_best(const entry_connection_t *conn,
273 int must_be_open, uint8_t purpose,
274 int need_uptime, int need_internal)
276 circuit_t *circ;
277 origin_circuit_t *best=NULL;
278 struct timeval now;
279 int intro_going_on_but_too_old = 0;
281 tor_assert(conn);
283 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
284 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
285 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
287 tor_gettimeofday(&now);
289 for (circ=global_circuitlist;circ;circ = circ->next) {
290 origin_circuit_t *origin_circ;
291 if (!CIRCUIT_IS_ORIGIN(circ))
292 continue;
293 origin_circ = TO_ORIGIN_CIRCUIT(circ);
295 /* Log an info message if we're going to launch a new intro circ in
296 * parallel */
297 if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
298 !must_be_open && origin_circ->hs_circ_has_timed_out) {
299 intro_going_on_but_too_old = 1;
300 continue;
303 if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
304 need_uptime,need_internal,now.tv_sec))
305 continue;
307 /* now this is an acceptable circ to hand back. but that doesn't
308 * mean it's the *best* circ to hand back. try to decide.
310 if (!best || circuit_is_better(origin_circ,best,conn))
311 best = origin_circ;
314 if (!best && intro_going_on_but_too_old)
315 log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
316 "right now, but it has already taken quite a while. Starting "
317 "one in parallel.");
319 return best;
322 /** Return the number of not-yet-open general-purpose origin circuits. */
323 static int
324 count_pending_general_client_circuits(void)
326 const circuit_t *circ;
328 int count = 0;
330 for (circ = global_circuitlist; circ; circ = circ->next) {
331 if (circ->marked_for_close ||
332 circ->state == CIRCUIT_STATE_OPEN ||
333 circ->purpose != CIRCUIT_PURPOSE_C_GENERAL ||
334 !CIRCUIT_IS_ORIGIN(circ))
335 continue;
337 ++count;
340 return count;
343 #if 0
344 /** Check whether, according to the policies in <b>options</b>, the
345 * circuit <b>circ</b> makes sense. */
346 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
347 * Also, it doesn't have the right definition of an exit circuit. Also,
348 * it's never called. */
350 circuit_conforms_to_options(const origin_circuit_t *circ,
351 const or_options_t *options)
353 const crypt_path_t *cpath, *cpath_next = NULL;
355 /* first check if it includes any excluded nodes */
356 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
357 cpath_next = cpath->next;
358 if (routerset_contains_extendinfo(options->ExcludeNodes,
359 cpath->extend_info))
360 return 0;
363 /* then consider the final hop */
364 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
365 circ->cpath->prev->extend_info))
366 return 0;
368 return 1;
370 #endif
372 /** Close all circuits that start at us, aren't open, and were born
373 * at least CircuitBuildTimeout seconds ago.
375 void
376 circuit_expire_building(void)
378 circuit_t *victim, *next_circ = global_circuitlist;
379 /* circ_times.timeout_ms and circ_times.close_ms are from
380 * circuit_build_times_get_initial_timeout() if we haven't computed
381 * custom timeouts yet */
382 struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
383 close_cutoff, extremely_old_cutoff, hs_extremely_old_cutoff,
384 cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff;
385 const or_options_t *options = get_options();
386 struct timeval now;
387 cpath_build_state_t *build_state;
388 int any_opened_circs = 0;
390 tor_gettimeofday(&now);
392 /* Check to see if we have any opened circuits. If we don't,
393 * we want to be more lenient with timeouts, in case the
394 * user has relocated and/or changed network connections.
395 * See bug #3443. */
396 while (next_circ) {
397 if (!CIRCUIT_IS_ORIGIN(next_circ) || /* didn't originate here */
398 next_circ->marked_for_close) { /* don't mess with marked circs */
399 next_circ = next_circ->next;
400 continue;
403 if (TO_ORIGIN_CIRCUIT(next_circ)->has_opened &&
404 next_circ->state == CIRCUIT_STATE_OPEN &&
405 TO_ORIGIN_CIRCUIT(next_circ)->build_state &&
406 TO_ORIGIN_CIRCUIT(next_circ)->build_state->desired_path_len
407 == DEFAULT_ROUTE_LEN) {
408 any_opened_circs = 1;
409 break;
411 next_circ = next_circ->next;
413 next_circ = global_circuitlist;
415 #define SET_CUTOFF(target, msec) do { \
416 long ms = tor_lround(msec); \
417 struct timeval diff; \
418 diff.tv_sec = ms / 1000; \
419 diff.tv_usec = (int)((ms % 1000) * 1000); \
420 timersub(&now, &diff, &target); \
421 } while (0)
424 * Because circuit build timeout is calculated only based on 3 hop
425 * general purpose circuit construction, we need to scale the timeout
426 * to make it properly apply to longer circuits, and circuits of
427 * certain usage types. The following diagram illustrates how we
428 * derive the scaling below. In short, we calculate the number
429 * of times our telescoping-based circuit construction causes cells
430 * to traverse each link for the circuit purpose types in question,
431 * and then assume each link is equivalent.
433 * OP --a--> A --b--> B --c--> C
434 * OP --a--> A --b--> B --c--> C --d--> D
436 * Let h = a = b = c = d
438 * Three hops (general_cutoff)
439 * RTTs = 3a + 2b + c
440 * RTTs = 6h
441 * Cannibalized:
442 * RTTs = a+b+c+d
443 * RTTs = 4h
444 * Four hops:
445 * RTTs = 4a + 3b + 2c + d
446 * RTTs = 10h
447 * Client INTRODUCE1+ACK: // XXX: correct?
448 * RTTs = 5a + 4b + 3c + 2d
449 * RTTs = 14h
450 * Server intro:
451 * RTTs = 4a + 3b + 2c
452 * RTTs = 9h
454 SET_CUTOFF(general_cutoff, circ_times.timeout_ms);
455 SET_CUTOFF(begindir_cutoff, circ_times.timeout_ms);
457 /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
458 * 4th hop. */
459 SET_CUTOFF(fourhop_cutoff, circ_times.timeout_ms * (10/6.0) + 1000);
461 /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
462 * Use the stream cutoff (more or less). */
463 SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
465 /* Be lenient with cannibalized circs. They already survived the official
466 * CBT, and they're usually not performance-critical. */
467 SET_CUTOFF(cannibalized_cutoff,
468 MAX(circ_times.close_ms*(4/6.0),
469 options->CircuitStreamTimeout * 1000) + 1000);
471 /* Intro circs have an extra round trip (and are also 4 hops long) */
472 SET_CUTOFF(c_intro_cutoff, circ_times.timeout_ms * (14/6.0) + 1000);
474 /* Server intro circs have an extra round trip */
475 SET_CUTOFF(s_intro_cutoff, circ_times.timeout_ms * (9/6.0) + 1000);
477 SET_CUTOFF(close_cutoff, circ_times.close_ms);
478 SET_CUTOFF(extremely_old_cutoff, circ_times.close_ms*2 + 1000);
480 SET_CUTOFF(hs_extremely_old_cutoff,
481 MAX(circ_times.close_ms*2 + 1000,
482 options->SocksTimeout * 1000));
484 while (next_circ) {
485 struct timeval cutoff;
486 victim = next_circ;
487 next_circ = next_circ->next;
488 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
489 victim->marked_for_close) /* don't mess with marked circs */
490 continue;
492 /* If we haven't yet started the first hop, it means we don't have
493 * any orconns available, and thus have not started counting time yet
494 * for this circuit. See circuit_deliver_create_cell() and uses of
495 * timestamp_began.
497 * Continue to wait in this case. The ORConn should timeout
498 * independently and kill us then.
500 if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
501 continue;
504 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
505 if (build_state && build_state->onehop_tunnel)
506 cutoff = begindir_cutoff;
507 else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
508 cutoff = close_cutoff;
509 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
510 victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
511 cutoff = c_intro_cutoff;
512 else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
513 cutoff = s_intro_cutoff;
514 else if (victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
515 cutoff = stream_cutoff;
516 else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
517 cutoff = close_cutoff;
518 else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
519 victim->state != CIRCUIT_STATE_OPEN)
520 cutoff = cannibalized_cutoff;
521 else if (build_state && build_state->desired_path_len >= 4)
522 cutoff = fourhop_cutoff;
523 else
524 cutoff = general_cutoff;
526 if (TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)
527 cutoff = hs_extremely_old_cutoff;
529 if (timercmp(&victim->timestamp_began, &cutoff, >))
530 continue; /* it's still young, leave it alone */
532 if (!any_opened_circs) {
533 /* It's still young enough that we wouldn't close it, right? */
534 if (timercmp(&victim->timestamp_began, &close_cutoff, >)) {
535 if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
536 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
537 == CPATH_STATE_OPEN;
538 log_info(LD_CIRC,
539 "No circuits are opened. Relaxing timeout for "
540 "a circuit with channel state %s. %d guards are live.",
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(&circ_times, first_hop_succeeded);
549 TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
551 continue;
552 } else {
553 static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
554 log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
555 "No circuits are opened. Relaxed timeout for "
556 "a circuit with channel state %s to %ldms. "
557 "However, it appears the circuit has timed out anyway. "
558 "%d guards are live.",
559 channel_state_to_string(victim->n_chan->state),
560 (long)circ_times.close_ms, num_live_entry_guards(0));
564 #if 0
565 /* some debug logs, to help track bugs */
566 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
567 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
568 if (!victim->timestamp_dirty)
569 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
570 "(clean).",
571 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
572 victim->purpose, victim->build_state->chosen_exit_name,
573 victim->n_circ_id);
574 else
575 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
576 "%d secs since dirty.",
577 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
578 victim->purpose, victim->build_state->chosen_exit_name,
579 victim->n_circ_id,
580 (int)(now - victim->timestamp_dirty));
582 #endif
584 /* if circ is !open, or if it's open but purpose is a non-finished
585 * intro or rend, then mark it for close */
586 if (victim->state == CIRCUIT_STATE_OPEN) {
587 switch (victim->purpose) {
588 default: /* most open circuits can be left alone. */
589 continue; /* yes, continue inside a switch refers to the nearest
590 * enclosing loop. C is smart. */
591 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
592 break; /* too old, need to die */
593 case CIRCUIT_PURPOSE_C_REND_READY:
594 /* it's a rend_ready circ -- has it already picked a query? */
595 /* c_rend_ready circs measure age since timestamp_dirty,
596 * because that's set when they switch purposes
598 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
599 victim->timestamp_dirty > cutoff.tv_sec)
600 continue;
601 break;
602 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
603 /* Open path bias testing circuits are given a long
604 * time to complete the test, but not forever */
605 TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
606 break;
607 case CIRCUIT_PURPOSE_C_INTRODUCING:
608 /* We keep old introducing circuits around for
609 * a while in parallel, and they can end up "opened".
610 * We decide below if we're going to mark them timed
611 * out and eventually close them.
613 break;
614 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
615 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
616 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
617 /* rend and intro circs become dirty each time they
618 * make an introduction attempt. so timestamp_dirty
619 * will reflect the time since the last attempt.
621 if (victim->timestamp_dirty > cutoff.tv_sec)
622 continue;
623 break;
625 } else { /* circuit not open, consider recording failure as timeout */
626 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
627 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
629 if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
630 log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
631 "yet has attached streams!",
632 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
633 victim->purpose,
634 circuit_purpose_to_string(victim->purpose));
635 tor_fragile_assert();
636 continue;
639 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
640 circuit_build_times_enough_to_compute(&circ_times)) {
641 /* Circuits are allowed to last longer for measurement.
642 * Switch their purpose and wait. */
643 if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
644 control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim),
645 CIRC_EVENT_FAILED,
646 END_CIRC_REASON_TIMEOUT);
647 circuit_change_purpose(victim, CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT);
648 /* Record this failure to check for too many timeouts
649 * in a row. This function does not record a time value yet
650 * (we do that later); it only counts the fact that we did
651 * have a timeout. We also want to avoid double-counting
652 * already "relaxed" circuits, which are counted above. */
653 if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
654 circuit_build_times_count_timeout(&circ_times,
655 first_hop_succeeded);
657 continue;
661 * If the circuit build time is much greater than we would have cut
662 * it off at, we probably had a suspend event along this codepath,
663 * and we should discard the value.
665 if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, <)) {
666 log_notice(LD_CIRC,
667 "Extremely large value for circuit build timeout: %lds. "
668 "Assuming clock jump. Purpose %d (%s)",
669 (long)(now.tv_sec - victim->timestamp_began.tv_sec),
670 victim->purpose,
671 circuit_purpose_to_string(victim->purpose));
672 } else if (circuit_build_times_count_close(&circ_times,
673 first_hop_succeeded,
674 victim->timestamp_created.tv_sec)) {
675 circuit_build_times_set_timeout(&circ_times);
680 /* If this is a hidden service client circuit which is far enough
681 * along in connecting to its destination, and we haven't already
682 * flagged it as 'timed out', and the user has not told us to
683 * close such circs immediately on timeout, flag it as 'timed out'
684 * so we'll launch another intro or rend circ, but don't mark it
685 * for close yet.
687 * (Circs flagged as 'timed out' are given a much longer timeout
688 * period above, so we won't close them in the next call to
689 * circuit_expire_building.) */
690 if (!(options->CloseHSClientCircuitsImmediatelyOnTimeout) &&
691 !(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)) {
692 switch (victim->purpose) {
693 case CIRCUIT_PURPOSE_C_REND_READY:
694 /* We only want to spare a rend circ if it has been specified in
695 * an INTRODUCE1 cell sent to a hidden service. A circ's
696 * pending_final_cpath field is non-NULL iff it is a rend circ
697 * and we have tried to send an INTRODUCE1 cell specifying it.
698 * Thus, if the pending_final_cpath field *is* NULL, then we
699 * want to not spare it. */
700 if (TO_ORIGIN_CIRCUIT(victim)->build_state->pending_final_cpath ==
701 NULL)
702 break;
703 /* fallthrough! */
704 case CIRCUIT_PURPOSE_C_INTRODUCING:
705 /* connection_ap_handshake_attach_circuit() will relaunch for us */
706 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
707 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
708 /* If we have reached this line, we want to spare the circ for now. */
709 log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
710 "as timed-out HS circ",
711 (unsigned)victim->n_circ_id,
712 victim->state, circuit_state_to_string(victim->state),
713 victim->purpose);
714 TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
715 continue;
716 default:
717 break;
721 /* If this is a service-side rendezvous circuit which is far
722 * enough along in connecting to its destination, consider sparing
723 * it. */
724 if (!(options->CloseHSServiceRendCircuitsImmediatelyOnTimeout) &&
725 !(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
726 victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
727 log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
728 "as timed-out HS circ; relaunching rendezvous attempt.",
729 (unsigned)victim->n_circ_id,
730 victim->state, circuit_state_to_string(victim->state),
731 victim->purpose);
732 TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out = 1;
733 rend_service_relaunch_rendezvous(TO_ORIGIN_CIRCUIT(victim));
734 continue;
737 if (victim->n_chan)
738 log_info(LD_CIRC,
739 "Abandoning circ %u %s:%d (state %d,%d:%s, purpose %d, "
740 "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
741 channel_get_canonical_remote_descr(victim->n_chan),
742 (unsigned)victim->n_circ_id,
743 TO_ORIGIN_CIRCUIT(victim)->has_opened,
744 victim->state, circuit_state_to_string(victim->state),
745 victim->purpose,
746 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len);
747 else
748 log_info(LD_CIRC,
749 "Abandoning circ %u %d (state %d,%d:%s, purpose %d, len %d)",
750 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
751 (unsigned)victim->n_circ_id,
752 TO_ORIGIN_CIRCUIT(victim)->has_opened,
753 victim->state,
754 circuit_state_to_string(victim->state), victim->purpose,
755 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len);
757 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
758 if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
759 circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
760 else
761 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
763 pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
767 /** Remove any elements in <b>needed_ports</b> that are handled by an
768 * open or in-progress circuit.
770 void
771 circuit_remove_handled_ports(smartlist_t *needed_ports)
773 int i;
774 uint16_t *port;
776 for (i = 0; i < smartlist_len(needed_ports); ++i) {
777 port = smartlist_get(needed_ports, i);
778 tor_assert(*port);
779 if (circuit_stream_is_being_handled(NULL, *port,
780 MIN_CIRCUITS_HANDLING_STREAM)) {
781 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
782 smartlist_del(needed_ports, i--);
783 tor_free(port);
784 } else {
785 log_debug(LD_CIRC,"Port %d is not handled.", *port);
790 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
791 * will have an acceptable exit node for exit stream <b>conn</b> if it
792 * is defined, else for "*:port".
793 * Else return 0.
796 circuit_stream_is_being_handled(entry_connection_t *conn,
797 uint16_t port, int min)
799 circuit_t *circ;
800 const node_t *exitnode;
801 int num=0;
802 time_t now = time(NULL);
803 int need_uptime = smartlist_contains_int_as_string(
804 get_options()->LongLivedPorts,
805 conn ? conn->socks_request->port : port);
807 for (circ=global_circuitlist;circ;circ = circ->next) {
808 if (CIRCUIT_IS_ORIGIN(circ) &&
809 !circ->marked_for_close &&
810 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
811 (!circ->timestamp_dirty ||
812 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
813 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
814 cpath_build_state_t *build_state = origin_circ->build_state;
815 if (build_state->is_internal || build_state->onehop_tunnel)
816 continue;
817 if (!origin_circ->unusable_for_new_conns)
818 continue;
820 exitnode = build_state_get_exit_node(build_state);
821 if (exitnode && (!need_uptime || build_state->need_uptime)) {
822 int ok;
823 if (conn) {
824 ok = connection_ap_can_use_exit(conn, exitnode);
825 } else {
826 addr_policy_result_t r;
827 r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
828 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
830 if (ok) {
831 if (++num >= min)
832 return 1;
837 return 0;
840 /** Don't keep more than this many unused open circuits around. */
841 #define MAX_UNUSED_OPEN_CIRCUITS 14
843 /** Figure out how many circuits we have open that are clean. Make
844 * sure it's enough for all the upcoming behaviors we predict we'll have.
845 * But put an upper bound on the total number of circuits.
847 static void
848 circuit_predict_and_launch_new(void)
850 circuit_t *circ;
851 int num=0, num_internal=0, num_uptime_internal=0;
852 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
853 int port_needs_uptime=0, port_needs_capacity=1;
854 time_t now = time(NULL);
855 int flags = 0;
857 /* First, count how many of each type of circuit we have already. */
858 for (circ=global_circuitlist;circ;circ = circ->next) {
859 cpath_build_state_t *build_state;
860 origin_circuit_t *origin_circ;
861 if (!CIRCUIT_IS_ORIGIN(circ))
862 continue;
863 if (circ->marked_for_close)
864 continue; /* don't mess with marked circs */
865 if (circ->timestamp_dirty)
866 continue; /* only count clean circs */
867 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
868 continue; /* only pay attention to general-purpose circs */
869 origin_circ = TO_ORIGIN_CIRCUIT(circ);
870 if (origin_circ->unusable_for_new_conns)
871 continue;
872 build_state = origin_circ->build_state;
873 if (build_state->onehop_tunnel)
874 continue;
875 num++;
876 if (build_state->is_internal)
877 num_internal++;
878 if (build_state->need_uptime && build_state->is_internal)
879 num_uptime_internal++;
882 /* If that's enough, then stop now. */
883 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
884 return; /* we already have many, making more probably will hurt */
886 /* Second, see if we need any more exit circuits. */
887 /* check if we know of a port that's been requested recently
888 * and no circuit is currently available that can handle it. */
889 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
890 &port_needs_capacity)) {
891 if (port_needs_uptime)
892 flags |= CIRCLAUNCH_NEED_UPTIME;
893 if (port_needs_capacity)
894 flags |= CIRCLAUNCH_NEED_CAPACITY;
895 log_info(LD_CIRC,
896 "Have %d clean circs (%d internal), need another exit circ.",
897 num, num_internal);
898 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
899 return;
902 /* Third, see if we need any more hidden service (server) circuits. */
903 if (num_rend_services() && num_uptime_internal < 3) {
904 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
905 CIRCLAUNCH_IS_INTERNAL);
906 log_info(LD_CIRC,
907 "Have %d clean circs (%d internal), need another internal "
908 "circ for my hidden service.",
909 num, num_internal);
910 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
911 return;
914 /* Fourth, see if we need any more hidden service (client) circuits. */
915 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
916 &hidserv_needs_capacity) &&
917 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
918 num_internal<2)) {
919 if (hidserv_needs_uptime)
920 flags |= CIRCLAUNCH_NEED_UPTIME;
921 if (hidserv_needs_capacity)
922 flags |= CIRCLAUNCH_NEED_CAPACITY;
923 flags |= CIRCLAUNCH_IS_INTERNAL;
924 log_info(LD_CIRC,
925 "Have %d clean circs (%d uptime-internal, %d internal), need"
926 " another hidden service circ.",
927 num, num_uptime_internal, num_internal);
928 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
929 return;
932 /* Finally, check to see if we still need more circuits to learn
933 * a good build timeout. But if we're close to our max number we
934 * want, don't do another -- we want to leave a few slots open so
935 * we can still build circuits preemptively as needed. */
936 if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
937 get_options()->LearnCircuitBuildTimeout &&
938 circuit_build_times_needs_circuits_now(&circ_times)) {
939 flags = CIRCLAUNCH_NEED_CAPACITY;
940 log_info(LD_CIRC,
941 "Have %d clean circs need another buildtime test circ.", num);
942 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
943 return;
947 /** Build a new test circuit every 5 minutes */
948 #define TESTING_CIRCUIT_INTERVAL 300
950 /** This function is called once a second, if router_have_min_dir_info() is
951 * true. Its job is to make sure all services we offer have enough circuits
952 * available. Some services just want enough circuits for current tasks,
953 * whereas others want a minimum set of idle circuits hanging around.
955 void
956 circuit_build_needed_circs(time_t now)
958 static time_t time_to_new_circuit = 0;
959 const or_options_t *options = get_options();
961 /* launch a new circ for any pending streams that need one */
962 connection_ap_attach_pending();
964 /* make sure any hidden services have enough intro points */
965 rend_services_introduce();
967 if (time_to_new_circuit < now) {
968 circuit_reset_failure_count(1);
969 time_to_new_circuit = now + options->NewCircuitPeriod;
970 if (proxy_mode(get_options()))
971 addressmap_clean(now);
972 circuit_expire_old_circuits_clientside();
974 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
975 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
976 if (get_options()->RunTesting &&
977 circ &&
978 circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
979 log_fn(LOG_INFO,"Creating a new testing circuit.");
980 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
982 #endif
984 if (!options->DisablePredictedCircuits)
985 circuit_predict_and_launch_new();
988 /** If the stream <b>conn</b> is a member of any of the linked
989 * lists of <b>circ</b>, then remove it from the list.
991 void
992 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
994 edge_connection_t *prevconn;
996 tor_assert(circ);
997 tor_assert(conn);
999 if (conn->base_.type == CONN_TYPE_AP) {
1000 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1001 entry_conn->may_use_optimistic_data = 0;
1003 conn->cpath_layer = NULL; /* don't keep a stale pointer */
1004 conn->on_circuit = NULL;
1006 if (CIRCUIT_IS_ORIGIN(circ)) {
1007 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1008 if (conn == origin_circ->p_streams) {
1009 origin_circ->p_streams = conn->next_stream;
1010 return;
1013 for (prevconn = origin_circ->p_streams;
1014 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1015 prevconn = prevconn->next_stream)
1017 if (prevconn && prevconn->next_stream) {
1018 prevconn->next_stream = conn->next_stream;
1019 return;
1021 } else {
1022 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1023 if (conn == or_circ->n_streams) {
1024 or_circ->n_streams = conn->next_stream;
1025 return;
1027 if (conn == or_circ->resolving_streams) {
1028 or_circ->resolving_streams = conn->next_stream;
1029 return;
1032 for (prevconn = or_circ->n_streams;
1033 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1034 prevconn = prevconn->next_stream)
1036 if (prevconn && prevconn->next_stream) {
1037 prevconn->next_stream = conn->next_stream;
1038 return;
1041 for (prevconn = or_circ->resolving_streams;
1042 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1043 prevconn = prevconn->next_stream)
1045 if (prevconn && prevconn->next_stream) {
1046 prevconn->next_stream = conn->next_stream;
1047 return;
1051 log_warn(LD_BUG,"Edge connection not in circuit's list.");
1052 /* Don't give an error here; it's harmless. */
1053 tor_fragile_assert();
1056 /** If we haven't yet decided on a good timeout value for circuit
1057 * building, we close idles circuits aggressively so we can get more
1058 * data points. */
1059 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
1061 /** Find each circuit that has been unused for too long, or dirty
1062 * for too long and has no streams on it: mark it for close.
1064 static void
1065 circuit_expire_old_circuits_clientside(void)
1067 circuit_t *circ;
1068 struct timeval cutoff, now;
1070 tor_gettimeofday(&now);
1071 cutoff = now;
1073 if (get_options()->LearnCircuitBuildTimeout &&
1074 circuit_build_times_needs_circuits(&circ_times)) {
1075 /* Circuits should be shorter lived if we need more of them
1076 * for learning a good build timeout */
1077 cutoff.tv_sec -= IDLE_TIMEOUT_WHILE_LEARNING;
1078 } else {
1079 cutoff.tv_sec -= get_options()->CircuitIdleTimeout;
1082 for (circ = global_circuitlist; circ; circ = circ->next) {
1083 if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
1084 continue;
1085 /* If the circuit has been dirty for too long, and there are no streams
1086 * on it, mark it for close.
1088 if (circ->timestamp_dirty &&
1089 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
1090 now.tv_sec &&
1091 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
1092 log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
1093 "purpose %d)",
1094 (unsigned)circ->n_circ_id,
1095 (long)(now.tv_sec - circ->timestamp_dirty),
1096 circ->purpose);
1097 /* Don't do this magic for testing circuits. Their death is governed
1098 * by circuit_expire_building */
1099 if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
1100 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1101 } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
1102 if (timercmp(&circ->timestamp_began, &cutoff, <)) {
1103 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
1104 circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
1105 circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1106 circ->purpose == CIRCUIT_PURPOSE_TESTING ||
1107 (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
1108 circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
1109 circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
1110 log_debug(LD_CIRC,
1111 "Closing circuit that has been unused for %ld msec.",
1112 tv_mdiff(&circ->timestamp_began, &now));
1113 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1114 } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
1115 /* Server-side rend joined circuits can end up really old, because
1116 * they are reused by clients for longer than normal. The client
1117 * controls their lifespan. (They never become dirty, because
1118 * connection_exit_begin_conn() never marks anything as dirty.)
1119 * Similarly, server-side intro circuits last a long time. */
1120 if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
1121 circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
1122 log_notice(LD_CIRC,
1123 "Ancient non-dirty circuit %d is still around after "
1124 "%ld milliseconds. Purpose: %d (%s)",
1125 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1126 tv_mdiff(&circ->timestamp_began, &now),
1127 circ->purpose,
1128 circuit_purpose_to_string(circ->purpose));
1129 TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
1137 /** How long do we wait before killing circuits with the properties
1138 * described below?
1140 * Probably we could choose a number here as low as 5 to 10 seconds,
1141 * since these circs are used for begindir, and a) generally you either
1142 * ask another begindir question right after or you don't for a long time,
1143 * b) clients at least through 0.2.1.x choose from the whole set of
1144 * directory mirrors at each choice, and c) re-establishing a one-hop
1145 * circuit via create-fast is a light operation assuming the TLS conn is
1146 * still there.
1148 * I expect "b" to go away one day when we move to using directory
1149 * guards, but I think "a" and "c" are good enough reasons that a low
1150 * number is safe even then.
1152 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
1154 /** Find each non-origin circuit that has been unused for too long,
1155 * has no streams on it, used a create_fast, and ends here: mark it
1156 * for close.
1158 void
1159 circuit_expire_old_circuits_serverside(time_t now)
1161 circuit_t *circ;
1162 or_circuit_t *or_circ;
1163 time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
1165 for (circ = global_circuitlist; circ; circ = circ->next) {
1166 if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
1167 continue;
1168 or_circ = TO_OR_CIRCUIT(circ);
1169 /* If the circuit has been idle for too long, and there are no streams
1170 * on it, and it ends here, and it used a create_fast, mark it for close.
1172 if (or_circ->is_first_hop && !circ->n_chan &&
1173 !or_circ->n_streams && !or_circ->resolving_streams &&
1174 or_circ->p_chan &&
1175 channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
1176 log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
1177 (unsigned)or_circ->p_circ_id,
1178 (int)(now - channel_when_last_xmit(or_circ->p_chan)));
1179 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1184 /** Number of testing circuits we want open before testing our bandwidth. */
1185 #define NUM_PARALLEL_TESTING_CIRCS 4
1187 /** True iff we've ever had enough testing circuits open to test our
1188 * bandwidth. */
1189 static int have_performed_bandwidth_test = 0;
1191 /** Reset have_performed_bandwidth_test, so we'll start building
1192 * testing circuits again so we can exercise our bandwidth. */
1193 void
1194 reset_bandwidth_test(void)
1196 have_performed_bandwidth_test = 0;
1199 /** Return 1 if we've already exercised our bandwidth, or if we
1200 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
1201 * established or on the way. Else return 0.
1204 circuit_enough_testing_circs(void)
1206 circuit_t *circ;
1207 int num = 0;
1209 if (have_performed_bandwidth_test)
1210 return 1;
1212 for (circ = global_circuitlist; circ; circ = circ->next) {
1213 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
1214 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
1215 circ->state == CIRCUIT_STATE_OPEN)
1216 num++;
1218 return num >= NUM_PARALLEL_TESTING_CIRCS;
1221 /** A testing circuit has completed. Take whatever stats we want.
1222 * Noticing reachability is taken care of in onionskin_answer(),
1223 * so there's no need to record anything here. But if we still want
1224 * to do the bandwidth test, and we now have enough testing circuits
1225 * open, do it.
1227 static void
1228 circuit_testing_opened(origin_circuit_t *circ)
1230 if (have_performed_bandwidth_test ||
1231 !check_whether_orport_reachable()) {
1232 /* either we've already done everything we want with testing circuits,
1233 * or this testing circuit became open due to a fluke, e.g. we picked
1234 * a last hop where we already had the connection open due to an
1235 * outgoing local circuit. */
1236 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
1237 } else if (circuit_enough_testing_circs()) {
1238 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
1239 have_performed_bandwidth_test = 1;
1240 } else
1241 consider_testing_reachability(1, 0);
1244 /** A testing circuit has failed to build. Take whatever stats we want. */
1245 static void
1246 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
1248 if (server_mode(get_options()) && check_whether_orport_reachable())
1249 return;
1251 log_info(LD_GENERAL,
1252 "Our testing circuit (to see if your ORPort is reachable) "
1253 "has failed. I'll try again later.");
1255 /* These aren't used yet. */
1256 (void)circ;
1257 (void)at_last_hop;
1260 /** The circuit <b>circ</b> has just become open. Take the next
1261 * step: for rendezvous circuits, we pass circ to the appropriate
1262 * function in rendclient or rendservice. For general circuits, we
1263 * call connection_ap_attach_pending, which looks for pending streams
1264 * that could use circ.
1266 void
1267 circuit_has_opened(origin_circuit_t *circ)
1269 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
1271 /* Remember that this circuit has finished building. Now if we start
1272 * it building again later (e.g. by extending it), we will know not
1273 * to consider its build time. */
1274 circ->has_opened = 1;
1276 switch (TO_CIRCUIT(circ)->purpose) {
1277 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1278 rend_client_rendcirc_has_opened(circ);
1279 /* Start building an intro circ if we don't have one yet. */
1280 connection_ap_attach_pending();
1281 /* This isn't a call to circuit_try_attaching_streams because a
1282 * circuit in _C_ESTABLISH_REND state isn't connected to its
1283 * hidden service yet, thus we can't attach streams to it yet,
1284 * thus circuit_try_attaching_streams would always clear the
1285 * circuit's isolation state. circuit_try_attaching_streams is
1286 * called later, when the rend circ enters _C_REND_JOINED
1287 * state. */
1288 break;
1289 case CIRCUIT_PURPOSE_C_INTRODUCING:
1290 rend_client_introcirc_has_opened(circ);
1291 break;
1292 case CIRCUIT_PURPOSE_C_GENERAL:
1293 /* Tell any AP connections that have been waiting for a new
1294 * circuit that one is ready. */
1295 circuit_try_attaching_streams(circ);
1296 break;
1297 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1298 /* at Bob, waiting for introductions */
1299 rend_service_intro_has_opened(circ);
1300 break;
1301 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1302 /* at Bob, connecting to rend point */
1303 rend_service_rendezvous_has_opened(circ);
1304 break;
1305 case CIRCUIT_PURPOSE_TESTING:
1306 circuit_testing_opened(circ);
1307 break;
1308 /* default:
1309 * This won't happen in normal operation, but might happen if the
1310 * controller did it. Just let it slide. */
1314 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
1315 * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
1316 static int
1317 circuit_try_clearing_isolation_state(origin_circuit_t *circ)
1319 if (/* The circuit may have become non-open if it was cannibalized.*/
1320 circ->base_.state == CIRCUIT_STATE_OPEN &&
1321 /* If !isolation_values_set, there is nothing to clear. */
1322 circ->isolation_values_set &&
1323 /* It's not legal to clear a circuit's isolation info if it's ever had
1324 * streams attached */
1325 !circ->isolation_any_streams_attached) {
1326 /* If we have any isolation information set on this circuit, and
1327 * we didn't manage to attach any streams to it, then we can
1328 * and should clear it and try again. */
1329 circuit_clear_isolation(circ);
1330 return 1;
1331 } else {
1332 return 0;
1336 /** Called when a circuit becomes ready for streams to be attached to
1337 * it. */
1338 void
1339 circuit_try_attaching_streams(origin_circuit_t *circ)
1341 /* Attach streams to this circuit if we can. */
1342 connection_ap_attach_pending();
1344 /* The call to circuit_try_clearing_isolation_state here will do
1345 * nothing and return 0 if we didn't attach any streams to circ
1346 * above. */
1347 if (circuit_try_clearing_isolation_state(circ)) {
1348 /* Maybe *now* we can attach some streams to this circuit. */
1349 connection_ap_attach_pending();
1353 /** Called whenever a circuit could not be successfully built.
1355 void
1356 circuit_build_failed(origin_circuit_t *circ)
1358 channel_t *n_chan = NULL;
1359 /* we should examine circ and see if it failed because of
1360 * the last hop or an earlier hop. then use this info below.
1362 int failed_at_last_hop = 0;
1363 /* If the last hop isn't open, and the second-to-last is, we failed
1364 * at the last hop. */
1365 if (circ->cpath &&
1366 circ->cpath->prev->state != CPATH_STATE_OPEN &&
1367 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
1368 failed_at_last_hop = 1;
1370 if (circ->cpath &&
1371 circ->cpath->state != CPATH_STATE_OPEN) {
1372 /* We failed at the first hop. If there's an OR connection
1373 * to blame, blame it. Also, avoid this relay for a while, and
1374 * fail any one-hop directory fetches destined for it. */
1375 const char *n_chan_id = circ->cpath->extend_info->identity_digest;
1376 int already_marked = 0;
1377 if (circ->base_.n_chan) {
1378 n_chan = circ->base_.n_chan;
1380 if (n_chan->is_bad_for_new_circs) {
1381 /* We only want to blame this router when a fresh healthy
1382 * connection fails. So don't mark this router as newly failed,
1383 * since maybe this was just an old circuit attempt that's
1384 * finally timing out now. Also, there's no need to blow away
1385 * circuits/streams/etc, since the failure of an unhealthy conn
1386 * doesn't tell us much about whether a healthy conn would
1387 * succeed. */
1388 already_marked = 1;
1390 log_info(LD_OR,
1391 "Our circuit failed to get a response from the first hop "
1392 "(%s). I'm going to try to rotate to a better connection.",
1393 channel_get_canonical_remote_descr(n_chan));
1394 n_chan->is_bad_for_new_circs = 1;
1395 } else {
1396 log_info(LD_OR,
1397 "Our circuit died before the first hop with no connection");
1399 if (n_chan_id && !already_marked) {
1400 entry_guard_register_connect_status(n_chan_id, 0, 1, time(NULL));
1401 /* if there are any one-hop streams waiting on this circuit, fail
1402 * them now so they can retry elsewhere. */
1403 connection_ap_fail_onehop(n_chan_id, circ->build_state);
1407 switch (circ->base_.purpose) {
1408 case CIRCUIT_PURPOSE_C_GENERAL:
1409 /* If we never built the circuit, note it as a failure. */
1410 circuit_increment_failure_count();
1411 if (failed_at_last_hop) {
1412 /* Make sure any streams that demand our last hop as their exit
1413 * know that it's unlikely to happen. */
1414 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
1416 break;
1417 case CIRCUIT_PURPOSE_TESTING:
1418 circuit_testing_failed(circ, failed_at_last_hop);
1419 break;
1420 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1421 /* at Bob, waiting for introductions */
1422 if (circ->base_.state != CIRCUIT_STATE_OPEN) {
1423 circuit_increment_failure_count();
1425 /* no need to care here, because bob will rebuild intro
1426 * points periodically. */
1427 break;
1428 case CIRCUIT_PURPOSE_C_INTRODUCING:
1429 /* at Alice, connecting to intro point */
1430 /* Don't increment failure count, since Bob may have picked
1431 * the introduction point maliciously */
1432 /* Alice will pick a new intro point when this one dies, if
1433 * the stream in question still cares. No need to act here. */
1434 break;
1435 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1436 /* at Alice, waiting for Bob */
1437 circuit_increment_failure_count();
1438 /* Alice will pick a new rend point when this one dies, if
1439 * the stream in question still cares. No need to act here. */
1440 break;
1441 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1442 /* at Bob, connecting to rend point */
1443 /* Don't increment failure count, since Alice may have picked
1444 * the rendezvous point maliciously */
1445 log_info(LD_REND,
1446 "Couldn't connect to Alice's chosen rend point %s "
1447 "(%s hop failed).",
1448 escaped(build_state_get_exit_nickname(circ->build_state)),
1449 failed_at_last_hop?"last":"non-last");
1450 rend_service_relaunch_rendezvous(circ);
1451 break;
1452 /* default:
1453 * This won't happen in normal operation, but might happen if the
1454 * controller did it. Just let it slide. */
1458 /** Number of consecutive failures so far; should only be touched by
1459 * circuit_launch_new and circuit_*_failure_count.
1461 static int n_circuit_failures = 0;
1462 /** Before the last time we called circuit_reset_failure_count(), were
1463 * there a lot of failures? */
1464 static int did_circs_fail_last_period = 0;
1466 /** Don't retry launching a new circuit if we try this many times with no
1467 * success. */
1468 #define MAX_CIRCUIT_FAILURES 5
1470 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1471 * details on arguments. */
1472 origin_circuit_t *
1473 circuit_launch(uint8_t purpose, int flags)
1475 return circuit_launch_by_extend_info(purpose, NULL, flags);
1478 /** Launch a new circuit with purpose <b>purpose</b> and exit node
1479 * <b>extend_info</b> (or NULL to select a random exit node). If flags
1480 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
1481 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
1482 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
1483 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
1484 * Return the newly allocated circuit on success, or NULL on failure. */
1485 origin_circuit_t *
1486 circuit_launch_by_extend_info(uint8_t purpose,
1487 extend_info_t *extend_info,
1488 int flags)
1490 origin_circuit_t *circ;
1491 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
1493 if (!onehop_tunnel && !router_have_minimum_dir_info()) {
1494 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
1495 "circuit launch.");
1496 return NULL;
1499 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
1500 purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
1501 /* see if there are appropriate circs available to cannibalize. */
1502 /* XXX if we're planning to add a hop, perhaps we want to look for
1503 * internal circs rather than exit circs? -RD */
1504 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
1505 if (circ) {
1506 uint8_t old_purpose = circ->base_.purpose;
1507 struct timeval old_timestamp_began;
1509 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d (%s)",
1510 build_state_get_exit_nickname(circ->build_state), purpose,
1511 circuit_purpose_to_string(purpose));
1513 if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
1514 purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
1515 circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
1516 /* Path bias: Cannibalized rends pre-emptively count as a
1517 * successfully built but unused closed circuit. We don't
1518 * wait until the extend (or the close) because the rend
1519 * point could be malicious.
1521 * Same deal goes for client side introductions. Clients
1522 * can be manipulated to connect repeatedly to them
1523 * (especially web clients).
1525 * If we decide to probe the initial portion of these circs,
1526 * (up to the adversary's final hop), we need to remove this,
1527 * or somehow mark the circuit with a special path state.
1530 /* This must be called before the purpose change */
1531 pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
1534 circuit_change_purpose(TO_CIRCUIT(circ), purpose);
1535 /* Reset the start date of this circ, else expire_building
1536 * will see it and think it's been trying to build since it
1537 * began.
1539 * Technically, the code should reset this when the
1540 * create cell is finally sent, but we're close enough
1541 * here. */
1542 tor_gettimeofday(&circ->base_.timestamp_began);
1544 control_event_circuit_cannibalized(circ, old_purpose,
1545 &old_timestamp_began);
1547 switch (purpose) {
1548 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1549 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1550 /* it's ready right now */
1551 break;
1552 case CIRCUIT_PURPOSE_C_INTRODUCING:
1553 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1554 case CIRCUIT_PURPOSE_C_GENERAL:
1555 /* need to add a new hop */
1556 tor_assert(extend_info);
1557 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
1558 return NULL;
1559 break;
1560 default:
1561 log_warn(LD_BUG,
1562 "unexpected purpose %d when cannibalizing a circ.",
1563 purpose);
1564 tor_fragile_assert();
1565 return NULL;
1567 return circ;
1571 if (did_circs_fail_last_period &&
1572 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
1573 /* too many failed circs in a row. don't try. */
1574 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1575 return NULL;
1578 /* try a circ. if it fails, circuit_mark_for_close will increment
1579 * n_circuit_failures */
1580 return circuit_establish_circuit(purpose, extend_info, flags);
1583 /** Record another failure at opening a general circuit. When we have
1584 * too many, we'll stop trying for the remainder of this minute.
1586 static void
1587 circuit_increment_failure_count(void)
1589 ++n_circuit_failures;
1590 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
1593 /** Reset the failure count for opening general circuits. This means
1594 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1595 * stopping again.
1597 void
1598 circuit_reset_failure_count(int timeout)
1600 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
1601 did_circs_fail_last_period = 1;
1602 else
1603 did_circs_fail_last_period = 0;
1604 n_circuit_failures = 0;
1607 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1608 * there isn't one, and there isn't one on the way, launch one and return
1609 * 0. If it will never work, return -1.
1611 * Write the found or in-progress or launched circ into *circp.
1613 static int
1614 circuit_get_open_circ_or_launch(entry_connection_t *conn,
1615 uint8_t desired_circuit_purpose,
1616 origin_circuit_t **circp)
1618 origin_circuit_t *circ;
1619 int check_exit_policy;
1620 int need_uptime, need_internal;
1621 int want_onehop;
1622 const or_options_t *options = get_options();
1624 tor_assert(conn);
1625 tor_assert(circp);
1626 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
1627 check_exit_policy =
1628 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
1629 !conn->use_begindir &&
1630 !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
1631 want_onehop = conn->want_onehop;
1633 need_uptime = !conn->want_onehop && !conn->use_begindir &&
1634 smartlist_contains_int_as_string(options->LongLivedPorts,
1635 conn->socks_request->port);
1637 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
1638 need_internal = 1;
1639 else if (conn->use_begindir || conn->want_onehop)
1640 need_internal = 1;
1641 else
1642 need_internal = 0;
1644 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
1645 need_uptime, need_internal);
1647 if (circ) {
1648 *circp = circ;
1649 return 1; /* we're happy */
1652 if (!want_onehop && !router_have_minimum_dir_info()) {
1653 if (!connection_get_by_type(CONN_TYPE_DIR)) {
1654 int severity = LOG_NOTICE;
1655 /* FFFF if this is a tunneled directory fetch, don't yell
1656 * as loudly. the user doesn't even know it's happening. */
1657 if (entry_list_is_constrained(options) &&
1658 entries_known_but_down(options)) {
1659 log_fn(severity, LD_APP|LD_DIR,
1660 "Application request when we haven't used client functionality "
1661 "lately. Optimistically trying known %s again.",
1662 options->UseBridges ? "bridges" : "entrynodes");
1663 entries_retry_all(options);
1664 } else if (!options->UseBridges || any_bridge_descriptors_known()) {
1665 log_fn(severity, LD_APP|LD_DIR,
1666 "Application request when we haven't used client functionality "
1667 "lately. Optimistically trying directory fetches again.");
1668 routerlist_retry_directory_downloads(time(NULL));
1671 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1672 * 1, or when all directory attempts fail and directory_all_unreachable()
1673 * kills it.
1675 return 0;
1678 /* Do we need to check exit policy? */
1679 if (check_exit_policy) {
1680 if (!conn->chosen_exit_name) {
1681 struct in_addr in;
1682 tor_addr_t addr, *addrp=NULL;
1683 if (tor_inet_aton(conn->socks_request->address, &in)) {
1684 tor_addr_from_in(&addr, &in);
1685 addrp = &addr;
1687 if (router_exit_policy_all_nodes_reject(addrp,
1688 conn->socks_request->port,
1689 need_uptime)) {
1690 log_notice(LD_APP,
1691 "No Tor server allows exit to %s:%d. Rejecting.",
1692 safe_str_client(conn->socks_request->address),
1693 conn->socks_request->port);
1694 return -1;
1696 } else {
1697 /* XXXX024 Duplicates checks in connection_ap_handshake_attach_circuit:
1698 * refactor into a single function? */
1699 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
1700 int opt = conn->chosen_exit_optional;
1701 if (node && !connection_ap_can_use_exit(conn, node)) {
1702 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1703 "Requested exit point '%s' is excluded or "
1704 "would refuse request. %s.",
1705 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1706 if (opt) {
1707 conn->chosen_exit_optional = 0;
1708 tor_free(conn->chosen_exit_name);
1709 /* Try again. */
1710 return circuit_get_open_circ_or_launch(conn,
1711 desired_circuit_purpose,
1712 circp);
1714 return -1;
1719 /* is one already on the way? */
1720 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
1721 need_uptime, need_internal);
1722 if (circ)
1723 log_debug(LD_CIRC, "one on the way!");
1724 if (!circ) {
1725 extend_info_t *extend_info=NULL;
1726 uint8_t new_circ_purpose;
1727 const int n_pending = count_pending_general_client_circuits();
1729 if (n_pending >= options->MaxClientCircuitsPending) {
1730 static ratelim_t delay_limit = RATELIM_INIT(10*60);
1731 char *m;
1732 if ((m = rate_limit_log(&delay_limit, approx_time()))) {
1733 log_notice(LD_APP, "We'd like to launch a circuit to handle a "
1734 "connection, but we already have %d general-purpose client "
1735 "circuits pending. Waiting until some finish.%s",
1736 n_pending, m);
1737 tor_free(m);
1739 return 0;
1742 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1743 /* need to pick an intro point */
1744 rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
1745 tor_assert(rend_data);
1746 extend_info = rend_client_get_random_intro(rend_data);
1747 if (!extend_info) {
1748 log_info(LD_REND,
1749 "No intro points for '%s': re-fetching service descriptor.",
1750 safe_str_client(rend_data->onion_address));
1751 rend_client_refetch_v2_renddesc(rend_data);
1752 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
1753 return 0;
1755 log_info(LD_REND,"Chose %s as intro point for '%s'.",
1756 extend_info_describe(extend_info),
1757 safe_str_client(rend_data->onion_address));
1760 /* If we have specified a particular exit node for our
1761 * connection, then be sure to open a circuit to that exit node.
1763 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1764 if (conn->chosen_exit_name) {
1765 const node_t *r;
1766 int opt = conn->chosen_exit_optional;
1767 r = node_get_by_nickname(conn->chosen_exit_name, 1);
1768 if (r && node_has_descriptor(r)) {
1769 /* We might want to connect to an IPv6 bridge for loading
1770 descriptors so we use the preferred address rather than
1771 the primary. */
1772 extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
1773 } else {
1774 log_debug(LD_DIR, "considering %d, %s",
1775 want_onehop, conn->chosen_exit_name);
1776 if (want_onehop && conn->chosen_exit_name[0] == '$') {
1777 /* We're asking for a one-hop circuit to a router that
1778 * we don't have a routerinfo about. Make up an extend_info. */
1779 char digest[DIGEST_LEN];
1780 char *hexdigest = conn->chosen_exit_name+1;
1781 tor_addr_t addr;
1782 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
1783 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
1784 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
1785 return -1;
1787 if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
1788 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
1789 escaped_safe_str_client(conn->socks_request->address));
1790 return -1;
1792 extend_info = extend_info_new(conn->chosen_exit_name+1,
1793 digest, NULL, NULL, &addr,
1794 conn->socks_request->port);
1795 } else {
1796 /* We will need an onion key for the router, and we
1797 * don't have one. Refuse or relax requirements. */
1798 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1799 "Requested exit point '%s' is not known. %s.",
1800 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1801 if (opt) {
1802 conn->chosen_exit_optional = 0;
1803 tor_free(conn->chosen_exit_name);
1804 /* Try again with no requested exit */
1805 return circuit_get_open_circ_or_launch(conn,
1806 desired_circuit_purpose,
1807 circp);
1809 return -1;
1815 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
1816 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
1817 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1818 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
1819 else
1820 new_circ_purpose = desired_circuit_purpose;
1822 if (options->Tor2webMode &&
1823 (new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
1824 new_circ_purpose == CIRCUIT_PURPOSE_C_INTRODUCING)) {
1825 want_onehop = 1;
1829 int flags = CIRCLAUNCH_NEED_CAPACITY;
1830 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
1831 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1832 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
1833 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
1834 flags);
1837 extend_info_free(extend_info);
1839 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1840 /* We just caused a circuit to get built because of this stream.
1841 * If this stream has caused a _lot_ of circuits to be built, that's
1842 * a bad sign: we should tell the user. */
1843 if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
1844 ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
1845 log_info(LD_CIRC, "The application request to %s:%d has launched "
1846 "%d circuits without finding one it likes.",
1847 escaped_safe_str_client(conn->socks_request->address),
1848 conn->socks_request->port,
1849 conn->num_circuits_launched);
1850 } else {
1851 /* help predict this next time */
1852 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1853 if (circ) {
1854 /* write the service_id into circ */
1855 circ->rend_data = rend_data_dup(ENTRY_TO_EDGE_CONN(conn)->rend_data);
1856 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1857 circ->base_.state == CIRCUIT_STATE_OPEN)
1858 rend_client_rendcirc_has_opened(circ);
1861 } /* endif (!circ) */
1862 if (circ) {
1863 /* Mark the circuit with the isolation fields for this connection.
1864 * When the circuit arrives, we'll clear these flags: this is
1865 * just some internal bookkeeping to make sure that we have
1866 * launched enough circuits.
1868 connection_edge_update_circuit_isolation(conn, circ, 0);
1869 } else {
1870 log_info(LD_APP,
1871 "No safe circuit (purpose %d) ready for edge "
1872 "connection; delaying.",
1873 desired_circuit_purpose);
1875 *circp = circ;
1876 return 0;
1879 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1880 * <b>circ</b>. */
1881 static int
1882 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
1884 crypt_path_t *cpath, *cpath_next = NULL;
1885 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1886 cpath_next = cpath->next;
1887 if (crypt_path == cpath)
1888 return 1;
1890 return 0;
1893 /** Return true iff client-side optimistic data is supported. */
1894 static int
1895 optimistic_data_enabled(void)
1897 const or_options_t *options = get_options();
1898 if (options->OptimisticData < 0) {
1899 /* XXX023 consider having auto default to 1 rather than 0 before
1900 * the 0.2.3 branch goes stable. See bug 3617. -RD */
1901 const int32_t enabled =
1902 networkstatus_get_param(NULL, "UseOptimisticData", 0, 0, 1);
1903 return (int)enabled;
1905 return options->OptimisticData;
1908 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1909 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1910 * hop in circ's cpath if <b>cpath</b> is NULL.
1912 static void
1913 link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
1914 crypt_path_t *cpath)
1916 const node_t *exitnode;
1918 /* add it into the linked list of streams on this circuit */
1919 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
1920 (unsigned)circ->base_.n_circ_id);
1921 /* reset it, so we can measure circ timeouts */
1922 ENTRY_TO_CONN(apconn)->timestamp_lastread = time(NULL);
1923 ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
1924 ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
1925 /* assert_connection_ok(conn, time(NULL)); */
1926 circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
1928 if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
1929 /* We are attaching a stream to a rendezvous circuit. That means
1930 * that an attempt to connect to a hidden service just
1931 * succeeded. Tell rendclient.c. */
1932 rend_client_note_connection_attempt_ended(
1933 ENTRY_TO_EDGE_CONN(apconn)->rend_data->onion_address);
1936 if (cpath) { /* we were given one; use it */
1937 tor_assert(cpath_is_on_circuit(circ, cpath));
1938 } else {
1939 /* use the last hop in the circuit */
1940 tor_assert(circ->cpath);
1941 tor_assert(circ->cpath->prev);
1942 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1943 cpath = circ->cpath->prev;
1945 ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
1947 circ->isolation_any_streams_attached = 1;
1948 connection_edge_update_circuit_isolation(apconn, circ, 0);
1950 /* See if we can use optimistic data on this circuit */
1951 if (cpath->extend_info &&
1952 (exitnode = node_get_by_id(cpath->extend_info->identity_digest)) &&
1953 exitnode->rs) {
1954 /* Okay; we know what exit node this is. */
1955 if (optimistic_data_enabled() &&
1956 circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL &&
1957 exitnode->rs->version_supports_optimistic_data)
1958 apconn->may_use_optimistic_data = 1;
1959 else
1960 apconn->may_use_optimistic_data = 0;
1961 log_info(LD_APP, "Looks like completed circuit to %s %s allow "
1962 "optimistic data for connection to %s",
1963 safe_str_client(node_describe(exitnode)),
1964 apconn->may_use_optimistic_data ? "does" : "doesn't",
1965 safe_str_client(apconn->socks_request->address));
1969 /** Return true iff <b>address</b> is matched by one of the entries in
1970 * TrackHostExits. */
1972 hostname_in_track_host_exits(const or_options_t *options, const char *address)
1974 if (!options->TrackHostExits)
1975 return 0;
1976 SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
1977 if (cp[0] == '.') { /* match end */
1978 if (cp[1] == '\0' ||
1979 !strcasecmpend(address, cp) ||
1980 !strcasecmp(address, &cp[1]))
1981 return 1;
1982 } else if (strcasecmp(cp, address) == 0) {
1983 return 1;
1985 } SMARTLIST_FOREACH_END(cp);
1986 return 0;
1989 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
1990 * the exit that we *did* choose for use by future connections to
1991 * <b>conn</b>'s destination.
1993 static void
1994 consider_recording_trackhost(const entry_connection_t *conn,
1995 const origin_circuit_t *circ)
1997 const or_options_t *options = get_options();
1998 char *new_address = NULL;
1999 char fp[HEX_DIGEST_LEN+1];
2001 /* Search the addressmap for this conn's destination. */
2002 /* If he's not in the address map.. */
2003 if (!options->TrackHostExits ||
2004 addressmap_have_mapping(conn->socks_request->address,
2005 options->TrackHostExitsExpire))
2006 return; /* nothing to track, or already mapped */
2008 if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
2009 !circ->build_state->chosen_exit)
2010 return;
2012 /* write down the fingerprint of the chosen exit, not the nickname,
2013 * because the chosen exit might not be named. */
2014 base16_encode(fp, sizeof(fp),
2015 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
2017 /* Add this exit/hostname pair to the addressmap. */
2018 tor_asprintf(&new_address, "%s.%s.exit",
2019 conn->socks_request->address, fp);
2021 addressmap_register(conn->socks_request->address, new_address,
2022 time(NULL) + options->TrackHostExitsExpire,
2023 ADDRMAPSRC_TRACKEXIT, 0, 0);
2026 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
2027 * begin or resolve cell as appropriate. Return values are as for
2028 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
2029 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2030 * <b>cpath</b> is NULL. */
2032 connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
2033 origin_circuit_t *circ,
2034 crypt_path_t *cpath)
2036 connection_t *base_conn = ENTRY_TO_CONN(conn);
2037 tor_assert(conn);
2038 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
2039 base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
2040 tor_assert(conn->socks_request);
2041 tor_assert(circ);
2042 tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
2044 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2046 if (!circ->base_.timestamp_dirty)
2047 circ->base_.timestamp_dirty = time(NULL);
2049 pathbias_count_use_attempt(circ);
2051 link_apconn_to_circ(conn, circ, cpath);
2052 tor_assert(conn->socks_request);
2053 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
2054 if (!conn->use_begindir)
2055 consider_recording_trackhost(conn, circ);
2056 if (connection_ap_handshake_send_begin(conn) < 0)
2057 return -1;
2058 } else {
2059 if (connection_ap_handshake_send_resolve(conn) < 0)
2060 return -1;
2063 return 1;
2066 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
2067 * we don't find one: if conn cannot be handled by any known nodes,
2068 * warn and return -1 (conn needs to die, and is maybe already marked);
2069 * else launch new circuit (if necessary) and return 0.
2070 * Otherwise, associate conn with a safe live circuit, do the
2071 * right next step, and return 1.
2073 /* XXXX this function should mark for close whenever it returns -1;
2074 * its callers shouldn't have to worry about that. */
2076 connection_ap_handshake_attach_circuit(entry_connection_t *conn)
2078 connection_t *base_conn = ENTRY_TO_CONN(conn);
2079 int retval;
2080 int conn_age;
2081 int want_onehop;
2083 tor_assert(conn);
2084 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2085 tor_assert(conn->socks_request);
2086 want_onehop = conn->want_onehop;
2088 conn_age = (int)(time(NULL) - base_conn->timestamp_created);
2090 if (conn_age >= get_options()->SocksTimeout) {
2091 int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
2092 LOG_INFO : LOG_NOTICE;
2093 log_fn(severity, LD_APP,
2094 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
2095 conn_age, safe_str_client(conn->socks_request->address),
2096 conn->socks_request->port);
2097 return -1;
2100 if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
2101 /* we're a general conn */
2102 origin_circuit_t *circ=NULL;
2104 if (conn->chosen_exit_name) {
2105 const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
2106 int opt = conn->chosen_exit_optional;
2107 if (!node && !want_onehop) {
2108 /* We ran into this warning when trying to extend a circuit to a
2109 * hidden service directory for which we didn't have a router
2110 * descriptor. See flyspray task 767 for more details. We should
2111 * keep this in mind when deciding to use BEGIN_DIR cells for other
2112 * directory requests as well. -KL*/
2113 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2114 "Requested exit point '%s' is not known. %s.",
2115 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2116 if (opt) {
2117 conn->chosen_exit_optional = 0;
2118 tor_free(conn->chosen_exit_name);
2119 return 0;
2121 return -1;
2123 if (node && !connection_ap_can_use_exit(conn, node)) {
2124 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2125 "Requested exit point '%s' is excluded or "
2126 "would refuse request. %s.",
2127 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2128 if (opt) {
2129 conn->chosen_exit_optional = 0;
2130 tor_free(conn->chosen_exit_name);
2131 return 0;
2133 return -1;
2137 /* find the circuit that we should use, if there is one. */
2138 retval = circuit_get_open_circ_or_launch(
2139 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
2140 if (retval < 1) // XXX023 if we totally fail, this still returns 0 -RD
2141 return retval;
2143 log_debug(LD_APP|LD_CIRC,
2144 "Attaching apconn to circ %u (stream %d sec old).",
2145 (unsigned)circ->base_.n_circ_id, conn_age);
2146 /* print the circ's path, so people can figure out which circs are
2147 * sucking. */
2148 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
2150 /* We have found a suitable circuit for our conn. Hurray. */
2151 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
2153 } else { /* we're a rendezvous conn */
2154 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
2156 tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
2158 /* start by finding a rendezvous circuit for us */
2160 retval = circuit_get_open_circ_or_launch(
2161 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
2162 if (retval < 0) return -1; /* failed */
2164 if (retval > 0) {
2165 tor_assert(rendcirc);
2166 /* one is already established, attach */
2167 log_info(LD_REND,
2168 "rend joined circ %d already here. attaching. "
2169 "(stream %d sec old)",
2170 (unsigned)rendcirc->base_.n_circ_id, conn_age);
2171 /* Mark rendezvous circuits as 'newly dirty' every time you use
2172 * them, since the process of rebuilding a rendezvous circ is so
2173 * expensive. There is a tradeoff between linkability and
2174 * feasibility, at this point.
2176 rendcirc->base_.timestamp_dirty = time(NULL);
2178 /* We've also attempted to use them. If they fail, we need to
2179 * probe them for path bias */
2180 pathbias_count_use_attempt(rendcirc);
2182 link_apconn_to_circ(conn, rendcirc, NULL);
2183 if (connection_ap_handshake_send_begin(conn) < 0)
2184 return 0; /* already marked, let them fade away */
2185 return 1;
2188 if (rendcirc && (rendcirc->base_.purpose ==
2189 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
2190 log_info(LD_REND,
2191 "pending-join circ %u already here, with intro ack. "
2192 "Stalling. (stream %d sec old)",
2193 (unsigned)rendcirc->base_.n_circ_id, conn_age);
2194 return 0;
2197 /* it's on its way. find an intro circ. */
2198 retval = circuit_get_open_circ_or_launch(
2199 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
2200 if (retval < 0) return -1; /* failed */
2202 if (retval > 0) {
2203 /* one has already sent the intro. keep waiting. */
2204 tor_assert(introcirc);
2205 log_info(LD_REND, "Intro circ %u present and awaiting ack (rend %u). "
2206 "Stalling. (stream %d sec old)",
2207 (unsigned)introcirc->base_.n_circ_id,
2208 rendcirc ? (unsigned)rendcirc->base_.n_circ_id : 0,
2209 conn_age);
2210 return 0;
2213 /* now rendcirc and introcirc are each either undefined or not finished */
2215 if (rendcirc && introcirc &&
2216 rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
2217 log_info(LD_REND,
2218 "ready rend circ %u already here (no intro-ack yet on "
2219 "intro %u). (stream %d sec old)",
2220 (unsigned)rendcirc->base_.n_circ_id,
2221 (unsigned)introcirc->base_.n_circ_id, conn_age);
2223 tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2224 if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
2225 log_info(LD_REND,"found open intro circ %u (rend %u); sending "
2226 "introduction. (stream %d sec old)",
2227 (unsigned)introcirc->base_.n_circ_id,
2228 (unsigned)rendcirc->base_.n_circ_id,
2229 conn_age);
2230 switch (rend_client_send_introduction(introcirc, rendcirc)) {
2231 case 0: /* success */
2232 rendcirc->base_.timestamp_dirty = time(NULL);
2233 introcirc->base_.timestamp_dirty = time(NULL);
2235 pathbias_count_use_attempt(introcirc);
2236 pathbias_count_use_attempt(rendcirc);
2238 assert_circuit_ok(TO_CIRCUIT(rendcirc));
2239 assert_circuit_ok(TO_CIRCUIT(introcirc));
2240 return 0;
2241 case -1: /* transient error */
2242 return 0;
2243 case -2: /* permanent error */
2244 return -1;
2245 default: /* oops */
2246 tor_fragile_assert();
2247 return -1;
2252 log_info(LD_REND, "Intro (%u) and rend (%u) circs are not both ready. "
2253 "Stalling conn. (%d sec old)",
2254 introcirc ? (unsigned)introcirc->base_.n_circ_id : 0,
2255 rendcirc ? (unsigned)rendcirc->base_.n_circ_id : 0, conn_age);
2256 return 0;
2260 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
2261 void
2262 circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
2264 uint8_t old_purpose;
2265 /* Don't allow an OR circ to become an origin circ or vice versa. */
2266 tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
2267 !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
2269 if (circ->purpose == new_purpose) return;
2271 if (CIRCUIT_IS_ORIGIN(circ)) {
2272 char old_purpose_desc[80] = "";
2274 strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
2275 old_purpose_desc[80-1] = '\0';
2277 log_debug(LD_CIRC,
2278 "changing purpose of origin circ %d "
2279 "from \"%s\" (%d) to \"%s\" (%d)",
2280 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
2281 old_purpose_desc,
2282 circ->purpose,
2283 circuit_purpose_to_string(new_purpose),
2284 new_purpose);
2287 old_purpose = circ->purpose;
2288 circ->purpose = new_purpose;
2290 if (CIRCUIT_IS_ORIGIN(circ)) {
2291 control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
2292 old_purpose);
2296 /** Mark <b>circ</b> so that no more connections can be attached to it. */
2297 void
2298 mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
2300 const or_options_t *options = get_options();
2301 tor_assert(circ);
2303 /* XXXX025 This is a kludge; we're only keeping it around in case there's
2304 * something that doesn't check unusable_for_new_conns, and to avoid
2305 * deeper refactoring of our expiration logic. */
2306 if (! circ->base_.timestamp_dirty)
2307 circ->base_.timestamp_dirty = approx_time();
2308 if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
2309 circ->base_.timestamp_dirty = 1; /* prevent underflow */
2310 else
2311 circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
2313 circ->unusable_for_new_conns = 1;