no measurement circs if not enough build times
[tor.git] / src / or / circuituse.c
blob18ef0c824bd7928548521ffdfdbdd9972040e216
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-2010, 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 "circuitbuild.h"
14 #include "circuitlist.h"
15 #include "circuituse.h"
16 #include "config.h"
17 #include "connection.h"
18 #include "connection_edge.h"
19 #include "control.h"
20 #include "policies.h"
21 #include "rendclient.h"
22 #include "rendcommon.h"
23 #include "rendservice.h"
24 #include "rephist.h"
25 #include "router.h"
26 #include "routerlist.h"
28 /********* START VARIABLES **********/
30 extern circuit_t *global_circuitlist; /* from circuitlist.c */
32 /********* END VARIABLES ************/
34 static void circuit_expire_old_circuits_clientside(time_t now);
35 static void circuit_increment_failure_count(void);
37 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
38 * Else return 0.
40 static int
41 circuit_is_acceptable(circuit_t *circ, edge_connection_t *conn,
42 int must_be_open, uint8_t purpose,
43 int need_uptime, int need_internal,
44 time_t now)
46 routerinfo_t *exitrouter;
47 cpath_build_state_t *build_state;
48 tor_assert(circ);
49 tor_assert(conn);
50 tor_assert(conn->socks_request);
52 if (!CIRCUIT_IS_ORIGIN(circ))
53 return 0; /* this circ doesn't start at us */
54 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
55 return 0; /* ignore non-open circs */
56 if (circ->marked_for_close)
57 return 0;
59 /* if this circ isn't our purpose, skip. */
60 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
61 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
62 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
63 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
64 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
65 return 0;
66 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
67 !must_be_open) {
68 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
69 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
70 return 0;
71 } else {
72 if (purpose != circ->purpose)
73 return 0;
76 if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
77 if (circ->timestamp_dirty &&
78 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
79 return 0;
81 /* decide if this circ is suitable for this conn */
83 /* for rend circs, circ->cpath->prev is not the last router in the
84 * circuit, it's the magical extra bob hop. so just check the nickname
85 * of the one we meant to finish at.
87 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
88 exitrouter = build_state_get_exit_router(build_state);
90 if (need_uptime && !build_state->need_uptime)
91 return 0;
92 if (need_internal != build_state->is_internal)
93 return 0;
95 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
96 if (!exitrouter && !build_state->onehop_tunnel) {
97 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
98 return 0; /* this circuit is screwed and doesn't know it yet,
99 * or is a rendezvous circuit. */
101 if (build_state->onehop_tunnel) {
102 if (!conn->want_onehop) {
103 log_debug(LD_CIRC,"Skipping one-hop circuit.");
104 return 0;
106 tor_assert(conn->chosen_exit_name);
107 if (build_state->chosen_exit) {
108 char digest[DIGEST_LEN];
109 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
110 return 0; /* broken digest, we don't want it */
111 if (memcmp(digest, build_state->chosen_exit->identity_digest,
112 DIGEST_LEN))
113 return 0; /* this is a circuit to somewhere else */
114 if (tor_digest_is_zero(digest)) {
115 /* we don't know the digest; have to compare addr:port */
116 tor_addr_t addr;
117 int r = tor_addr_from_str(&addr, conn->socks_request->address);
118 if (r < 0 ||
119 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
120 build_state->chosen_exit->port != conn->socks_request->port)
121 return 0;
124 } else {
125 if (conn->want_onehop) {
126 /* don't use three-hop circuits -- that could hurt our anonymity. */
127 return 0;
130 if (exitrouter && !connection_ap_can_use_exit(conn, exitrouter, 0)) {
131 /* can't exit from this router */
132 return 0;
134 } else { /* not general */
135 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
136 if ((conn->rend_data && !ocirc->rend_data) ||
137 (!conn->rend_data && ocirc->rend_data) ||
138 (conn->rend_data && ocirc->rend_data &&
139 rend_cmp_service_ids(conn->rend_data->onion_address,
140 ocirc->rend_data->onion_address))) {
141 /* this circ is not for this conn */
142 return 0;
145 return 1;
148 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
149 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
151 static int
152 circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
154 switch (purpose) {
155 case CIRCUIT_PURPOSE_C_GENERAL:
156 /* if it's used but less dirty it's best;
157 * else if it's more recently created it's best
159 if (b->timestamp_dirty) {
160 if (a->timestamp_dirty &&
161 a->timestamp_dirty > b->timestamp_dirty)
162 return 1;
163 } else {
164 if (a->timestamp_dirty ||
165 a->timestamp_created > b->timestamp_created)
166 return 1;
167 if (CIRCUIT_IS_ORIGIN(b) &&
168 TO_ORIGIN_CIRCUIT(b)->build_state->is_internal)
169 return 1;
171 break;
172 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
173 /* the closer it is to ack_wait the better it is */
174 if (a->purpose > b->purpose)
175 return 1;
176 break;
177 case CIRCUIT_PURPOSE_C_REND_JOINED:
178 /* the closer it is to rend_joined the better it is */
179 if (a->purpose > b->purpose)
180 return 1;
181 break;
183 return 0;
186 /** Find the best circ that conn can use, preferably one which is
187 * dirty. Circ must not be too old.
189 * Conn must be defined.
191 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
193 * circ_purpose specifies what sort of circuit we must have.
194 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
196 * If it's REND_JOINED and must_be_open==0, then return the closest
197 * rendezvous-purposed circuit that you can find.
199 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
200 * closest introduce-purposed circuit that you can find.
202 static origin_circuit_t *
203 circuit_get_best(edge_connection_t *conn, int must_be_open, uint8_t purpose,
204 int need_uptime, int need_internal)
206 circuit_t *circ, *best=NULL;
207 time_t now = time(NULL);
208 int intro_going_on_but_too_old = 0;
210 tor_assert(conn);
212 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
213 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
214 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
216 for (circ=global_circuitlist;circ;circ = circ->next) {
217 if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
218 need_uptime,need_internal,now))
219 continue;
221 /* XXX022 make this 15 be a function of circuit finishing times we've
222 * seen lately, a la Fallon Chen's GSoC work -RD */
223 #define REND_PARALLEL_INTRO_DELAY 15
224 if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
225 !must_be_open && circ->state != CIRCUIT_STATE_OPEN &&
226 circ->timestamp_created + REND_PARALLEL_INTRO_DELAY < now) {
227 intro_going_on_but_too_old = 1;
228 continue;
231 /* now this is an acceptable circ to hand back. but that doesn't
232 * mean it's the *best* circ to hand back. try to decide.
234 if (!best || circuit_is_better(circ,best,purpose))
235 best = circ;
238 if (!best && intro_going_on_but_too_old)
239 log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
240 "right now, but it has already taken quite a while. Starting "
241 "one in parallel.");
243 return best ? TO_ORIGIN_CIRCUIT(best) : NULL;
246 /** Check whether, according to the policies in <b>options</b>, the
247 * circuit <b>circ</b> makes sense. */
248 /* XXXX currently only checks Exclude{Exit}Nodes. It should check more. */
250 circuit_conforms_to_options(const origin_circuit_t *circ,
251 const or_options_t *options)
253 const crypt_path_t *cpath, *cpath_next = NULL;
255 for (cpath = circ->cpath; cpath && cpath_next != circ->cpath;
256 cpath = cpath_next) {
257 cpath_next = cpath->next;
259 if (routerset_contains_extendinfo(options->ExcludeNodes,
260 cpath->extend_info))
261 return 0;
263 if (cpath->next == circ->cpath) {
264 /* This is apparently the exit node. */
266 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
267 cpath->extend_info))
268 return 0;
271 return 1;
274 /** Close all circuits that start at us, aren't open, and were born
275 * at least CircuitBuildTimeout seconds ago.
277 void
278 circuit_expire_building(time_t now)
280 circuit_t *victim, *next_circ = global_circuitlist;
281 /* circ_times.timeout_ms and circ_times.close_ms are from
282 * circuit_build_times_get_initial_timeout() if we haven't computed
283 * custom timeouts yet */
284 time_t general_cutoff = now - tor_lround(circ_times.timeout_ms/1000);
285 time_t begindir_cutoff = now - tor_lround(circ_times.timeout_ms/2000);
286 time_t fourhop_cutoff = now - tor_lround(4*circ_times.timeout_ms/3000);
287 time_t cannibalize_cutoff = now - tor_lround(circ_times.timeout_ms/2000);
288 time_t close_cutoff = now - tor_lround(circ_times.close_ms/1000);
289 time_t introcirc_cutoff = begindir_cutoff;
290 cpath_build_state_t *build_state;
292 while (next_circ) {
293 time_t cutoff;
294 victim = next_circ;
295 next_circ = next_circ->next;
296 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
297 victim->marked_for_close) /* don't mess with marked circs */
298 continue;
300 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
301 if (build_state && build_state->onehop_tunnel)
302 cutoff = begindir_cutoff;
303 else if (build_state && build_state->desired_path_len == 4
304 && !TO_ORIGIN_CIRCUIT(victim)->has_opened)
305 cutoff = fourhop_cutoff;
306 else if (TO_ORIGIN_CIRCUIT(victim)->has_opened)
307 cutoff = cannibalize_cutoff;
308 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
309 cutoff = introcirc_cutoff;
310 else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
311 cutoff = close_cutoff;
312 else
313 cutoff = general_cutoff;
315 if (victim->timestamp_created > cutoff)
316 continue; /* it's still young, leave it alone */
318 #if 0
319 /* some debug logs, to help track bugs */
320 if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
321 victim->timestamp_created <= introcirc_cutoff &&
322 victim->timestamp_created > general_cutoff)
323 log_info(LD_REND|LD_CIRC, "Timing out introduction circuit which we "
324 "would not have done if it had been a general circuit.");
326 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
327 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
328 if (!victim->timestamp_dirty)
329 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
330 "(clean).",
331 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
332 victim->purpose, victim->build_state->chosen_exit_name,
333 victim->n_circ_id);
334 else
335 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
336 "%d secs since dirty.",
337 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
338 victim->purpose, victim->build_state->chosen_exit_name,
339 victim->n_circ_id,
340 (int)(now - victim->timestamp_dirty));
342 #endif
344 /* if circ is !open, or if it's open but purpose is a non-finished
345 * intro or rend, then mark it for close */
346 if (victim->state == CIRCUIT_STATE_OPEN) {
347 switch (victim->purpose) {
348 default: /* most open circuits can be left alone. */
349 continue; /* yes, continue inside a switch refers to the nearest
350 * enclosing loop. C is smart. */
351 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
352 case CIRCUIT_PURPOSE_C_INTRODUCING:
353 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
354 break; /* too old, need to die */
355 case CIRCUIT_PURPOSE_C_REND_READY:
356 /* it's a rend_ready circ -- has it already picked a query? */
357 /* c_rend_ready circs measure age since timestamp_dirty,
358 * because that's set when they switch purposes
360 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
361 victim->timestamp_dirty > cutoff)
362 continue;
363 break;
364 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
365 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
366 /* rend and intro circs become dirty each time they
367 * make an introduction attempt. so timestamp_dirty
368 * will reflect the time since the last attempt.
370 if (victim->timestamp_dirty > cutoff)
371 continue;
372 break;
374 } else { /* circuit not open, consider recording failure as timeout */
375 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
376 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
378 if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
379 log_warn(LD_BUG, "Circuit %d (purpose %d) has timed out, "
380 "yet has attached streams!",
381 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
382 victim->purpose);
383 tor_fragile_assert();
384 continue;
387 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
388 circuit_build_times_enough_to_compute(&circ_times)) {
389 /* Circuits are allowed to last longer for measurement.
390 * Switch their purpose and wait. */
391 if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
392 control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim),
393 CIRC_EVENT_FAILED,
394 END_CIRC_REASON_TIMEOUT);
395 victim->purpose = CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT;
396 /* Record this failure to check for too many timeouts
397 * in a row. This function does not record a time value yet
398 * (we do that later); it only counts the fact that we did
399 * have a timeout. */
400 circuit_build_times_count_timeout(&circ_times,
401 first_hop_succeeded);
402 continue;
406 * If the circuit build time is much greater than we would have cut
407 * it off at, we probably had a suspend event along this codepath,
408 * and we should discard the value.
410 if (now - victim->timestamp_created > 2*circ_times.close_ms/1000+1) {
411 log_notice(LD_CIRC,
412 "Extremely large value for circuit build timeout: %lds. "
413 "Assuming clock jump. Purpose %d",
414 (long)(now - victim->timestamp_created),
415 victim->purpose);
416 } else if (circuit_build_times_count_close(&circ_times,
417 first_hop_succeeded,
418 victim->timestamp_created)) {
419 circuit_build_times_set_timeout(&circ_times);
424 if (victim->n_conn)
425 log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
426 victim->n_conn->_base.address, victim->n_conn->_base.port,
427 victim->n_circ_id,
428 victim->state, circuit_state_to_string(victim->state),
429 victim->purpose);
430 else
431 log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
432 victim->n_circ_id, victim->state,
433 circuit_state_to_string(victim->state), victim->purpose);
435 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
436 if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
437 circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
438 else
439 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
443 /** Remove any elements in <b>needed_ports</b> that are handled by an
444 * open or in-progress circuit.
446 void
447 circuit_remove_handled_ports(smartlist_t *needed_ports)
449 int i;
450 uint16_t *port;
452 for (i = 0; i < smartlist_len(needed_ports); ++i) {
453 port = smartlist_get(needed_ports, i);
454 tor_assert(*port);
455 if (circuit_stream_is_being_handled(NULL, *port,
456 MIN_CIRCUITS_HANDLING_STREAM)) {
457 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
458 smartlist_del(needed_ports, i--);
459 tor_free(port);
460 } else {
461 log_debug(LD_CIRC,"Port %d is not handled.", *port);
466 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
467 * will have an acceptable exit node for exit stream <b>conn</b> if it
468 * is defined, else for "*:port".
469 * Else return 0.
472 circuit_stream_is_being_handled(edge_connection_t *conn,
473 uint16_t port, int min)
475 circuit_t *circ;
476 routerinfo_t *exitrouter;
477 int num=0;
478 time_t now = time(NULL);
479 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
480 conn ? conn->socks_request->port : port);
482 for (circ=global_circuitlist;circ;circ = circ->next) {
483 if (CIRCUIT_IS_ORIGIN(circ) &&
484 !circ->marked_for_close &&
485 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
486 (!circ->timestamp_dirty ||
487 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
488 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
489 if (build_state->is_internal || build_state->onehop_tunnel)
490 continue;
492 exitrouter = build_state_get_exit_router(build_state);
493 if (exitrouter && (!need_uptime || build_state->need_uptime)) {
494 int ok;
495 if (conn) {
496 ok = connection_ap_can_use_exit(conn, exitrouter, 0);
497 } else {
498 addr_policy_result_t r = compare_addr_to_addr_policy(
499 0, port, exitrouter->exit_policy);
500 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
502 if (ok) {
503 if (++num >= min)
504 return 1;
509 return 0;
512 /** Don't keep more than this many unused open circuits around. */
513 #define MAX_UNUSED_OPEN_CIRCUITS 14
515 /** Figure out how many circuits we have open that are clean. Make
516 * sure it's enough for all the upcoming behaviors we predict we'll have.
517 * But put an upper bound on the total number of circuits.
519 static void
520 circuit_predict_and_launch_new(void)
522 circuit_t *circ;
523 int num=0, num_internal=0, num_uptime_internal=0;
524 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
525 int port_needs_uptime=0, port_needs_capacity=1;
526 time_t now = time(NULL);
527 int flags = 0;
529 /* First, count how many of each type of circuit we have already. */
530 for (circ=global_circuitlist;circ;circ = circ->next) {
531 cpath_build_state_t *build_state;
532 if (!CIRCUIT_IS_ORIGIN(circ))
533 continue;
534 if (circ->marked_for_close)
535 continue; /* don't mess with marked circs */
536 if (circ->timestamp_dirty)
537 continue; /* only count clean circs */
538 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
539 continue; /* only pay attention to general-purpose circs */
540 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
541 if (build_state->onehop_tunnel)
542 continue;
543 num++;
544 if (build_state->is_internal)
545 num_internal++;
546 if (build_state->need_uptime && build_state->is_internal)
547 num_uptime_internal++;
550 /* If that's enough, then stop now. */
551 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
552 return; /* we already have many, making more probably will hurt */
554 /* Second, see if we need any more exit circuits. */
555 /* check if we know of a port that's been requested recently
556 * and no circuit is currently available that can handle it. */
557 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
558 &port_needs_capacity)) {
559 if (port_needs_uptime)
560 flags |= CIRCLAUNCH_NEED_UPTIME;
561 if (port_needs_capacity)
562 flags |= CIRCLAUNCH_NEED_CAPACITY;
563 log_info(LD_CIRC,
564 "Have %d clean circs (%d internal), need another exit circ.",
565 num, num_internal);
566 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
567 return;
570 /* Third, see if we need any more hidden service (server) circuits. */
571 if (num_rend_services() && num_uptime_internal < 3) {
572 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
573 CIRCLAUNCH_IS_INTERNAL);
574 log_info(LD_CIRC,
575 "Have %d clean circs (%d internal), need another internal "
576 "circ for my hidden service.",
577 num, num_internal);
578 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
579 return;
582 /* Fourth, see if we need any more hidden service (client) circuits. */
583 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
584 &hidserv_needs_capacity) &&
585 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
586 num_internal<2)) {
587 if (hidserv_needs_uptime)
588 flags |= CIRCLAUNCH_NEED_UPTIME;
589 if (hidserv_needs_capacity)
590 flags |= CIRCLAUNCH_NEED_CAPACITY;
591 flags |= CIRCLAUNCH_IS_INTERNAL;
592 log_info(LD_CIRC,
593 "Have %d clean circs (%d uptime-internal, %d internal), need"
594 " another hidden service circ.",
595 num, num_uptime_internal, num_internal);
596 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
597 return;
600 /* Finally, check to see if we still need more circuits to learn
601 * a good build timeout. But if we're close to our max number we
602 * want, don't do another -- we want to leave a few slots open so
603 * we can still build circuits preemptively as needed. */
604 if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
605 circuit_build_times_needs_circuits_now(&circ_times)) {
606 flags = CIRCLAUNCH_NEED_CAPACITY;
607 log_info(LD_CIRC,
608 "Have %d clean circs need another buildtime test circ.", num);
609 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
610 return;
614 /** Build a new test circuit every 5 minutes */
615 #define TESTING_CIRCUIT_INTERVAL 300
617 /** This function is called once a second, if router_have_min_dir_info() is
618 * true. Its job is to make sure all services we offer have enough circuits
619 * available. Some services just want enough circuits for current tasks,
620 * whereas others want a minimum set of idle circuits hanging around.
622 void
623 circuit_build_needed_circs(time_t now)
625 static time_t time_to_new_circuit = 0;
626 or_options_t *options = get_options();
628 /* launch a new circ for any pending streams that need one */
629 connection_ap_attach_pending();
631 /* make sure any hidden services have enough intro points */
632 rend_services_introduce();
634 if (time_to_new_circuit < now) {
635 circuit_reset_failure_count(1);
636 time_to_new_circuit = now + options->NewCircuitPeriod;
637 if (proxy_mode(get_options()))
638 addressmap_clean(now);
639 circuit_expire_old_circuits_clientside(now);
641 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
642 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
643 if (get_options()->RunTesting &&
644 circ &&
645 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
646 log_fn(LOG_INFO,"Creating a new testing circuit.");
647 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0);
649 #endif
651 if (!options->DisablePredictedCircuits)
652 circuit_predict_and_launch_new();
655 /** If the stream <b>conn</b> is a member of any of the linked
656 * lists of <b>circ</b>, then remove it from the list.
658 void
659 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
661 edge_connection_t *prevconn;
663 tor_assert(circ);
664 tor_assert(conn);
666 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
667 conn->on_circuit = NULL;
669 if (CIRCUIT_IS_ORIGIN(circ)) {
670 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
671 if (conn == origin_circ->p_streams) {
672 origin_circ->p_streams = conn->next_stream;
673 return;
676 for (prevconn = origin_circ->p_streams;
677 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
678 prevconn = prevconn->next_stream)
680 if (prevconn && prevconn->next_stream) {
681 prevconn->next_stream = conn->next_stream;
682 return;
684 } else {
685 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
686 if (conn == or_circ->n_streams) {
687 or_circ->n_streams = conn->next_stream;
688 return;
690 if (conn == or_circ->resolving_streams) {
691 or_circ->resolving_streams = conn->next_stream;
692 return;
695 for (prevconn = or_circ->n_streams;
696 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
697 prevconn = prevconn->next_stream)
699 if (prevconn && prevconn->next_stream) {
700 prevconn->next_stream = conn->next_stream;
701 return;
704 for (prevconn = or_circ->resolving_streams;
705 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
706 prevconn = prevconn->next_stream)
708 if (prevconn && prevconn->next_stream) {
709 prevconn->next_stream = conn->next_stream;
710 return;
714 log_warn(LD_BUG,"Edge connection not in circuit's list.");
715 /* Don't give an error here; it's harmless. */
716 tor_fragile_assert();
719 /** If we haven't yet decided on a good timeout value for circuit
720 * building, we close idles circuits aggressively so we can get more
721 * data points. */
722 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
724 /** Find each circuit that has been unused for too long, or dirty
725 * for too long and has no streams on it: mark it for close.
727 static void
728 circuit_expire_old_circuits_clientside(time_t now)
730 circuit_t *circ;
731 time_t cutoff;
733 if (circuit_build_times_needs_circuits(&circ_times)) {
734 /* Circuits should be shorter lived if we need more of them
735 * for learning a good build timeout */
736 cutoff = now - IDLE_TIMEOUT_WHILE_LEARNING;
737 } else {
738 cutoff = now - get_options()->CircuitIdleTimeout;
741 for (circ = global_circuitlist; circ; circ = circ->next) {
742 if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
743 continue;
744 /* If the circuit has been dirty for too long, and there are no streams
745 * on it, mark it for close.
747 if (circ->timestamp_dirty &&
748 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
749 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
750 log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, "
751 "purpose %d)",
752 circ->n_circ_id, (int)(now - circ->timestamp_dirty),
753 circ->purpose);
754 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
755 } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
756 if (circ->timestamp_created < cutoff) {
757 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
758 circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
759 circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
760 circ->purpose == CIRCUIT_PURPOSE_TESTING ||
761 (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
762 circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
763 circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
764 log_debug(LD_CIRC,
765 "Closing circuit that has been unused for %ld seconds.",
766 (long)(now - circ->timestamp_created));
767 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
768 } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
769 /* Server-side rend joined circuits can end up really old, because
770 * they are reused by clients for longer than normal. The client
771 * controls their lifespan. (They never become dirty, because
772 * connection_exit_begin_conn() never marks anything as dirty.)
773 * Similarly, server-side intro circuits last a long time. */
774 if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
775 circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
776 log_notice(LD_CIRC,
777 "Ancient non-dirty circuit %d is still around after "
778 "%ld seconds. Purpose: %d",
779 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
780 (long)(now - circ->timestamp_created),
781 circ->purpose);
782 /* FFFF implement a new circuit_purpose_to_string() so we don't
783 * just print out a number for circ->purpose */
784 TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
792 /** How long do we wait before killing circuits with the properties
793 * described below?
795 * Probably we could choose a number here as low as 5 to 10 seconds,
796 * since these circs are used for begindir, and a) generally you either
797 * ask another begindir question right after or you don't for a long time,
798 * b) clients at least through 0.2.1.x choose from the whole set of
799 * directory mirrors at each choice, and c) re-establishing a one-hop
800 * circuit via create-fast is a light operation assuming the TLS conn is
801 * still there.
803 * I expect "b" to go away one day when we move to using directory
804 * guards, but I think "a" and "c" are good enough reasons that a low
805 * number is safe even then.
807 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
809 /** Find each non-origin circuit that has been unused for too long,
810 * has no streams on it, used a create_fast, and ends here: mark it
811 * for close.
813 void
814 circuit_expire_old_circuits_serverside(time_t now)
816 circuit_t *circ;
817 or_circuit_t *or_circ;
818 time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
820 for (circ = global_circuitlist; circ; circ = circ->next) {
821 if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
822 continue;
823 or_circ = TO_OR_CIRCUIT(circ);
824 /* If the circuit has been idle for too long, and there are no streams
825 * on it, and it ends here, and it used a create_fast, mark it for close.
827 if (or_circ->is_first_hop && !circ->n_conn &&
828 !or_circ->n_streams && !or_circ->resolving_streams &&
829 or_circ->p_conn &&
830 or_circ->p_conn->timestamp_last_added_nonpadding <= cutoff) {
831 log_info(LD_CIRC, "Closing circ_id %d (empty %d secs ago)",
832 or_circ->p_circ_id,
833 (int)(now - or_circ->p_conn->timestamp_last_added_nonpadding));
834 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
839 /** Number of testing circuits we want open before testing our bandwidth. */
840 #define NUM_PARALLEL_TESTING_CIRCS 4
842 /** True iff we've ever had enough testing circuits open to test our
843 * bandwidth. */
844 static int have_performed_bandwidth_test = 0;
846 /** Reset have_performed_bandwidth_test, so we'll start building
847 * testing circuits again so we can exercise our bandwidth. */
848 void
849 reset_bandwidth_test(void)
851 have_performed_bandwidth_test = 0;
854 /** Return 1 if we've already exercised our bandwidth, or if we
855 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
856 * established or on the way. Else return 0.
859 circuit_enough_testing_circs(void)
861 circuit_t *circ;
862 int num = 0;
864 if (have_performed_bandwidth_test)
865 return 1;
867 for (circ = global_circuitlist; circ; circ = circ->next) {
868 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
869 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
870 circ->state == CIRCUIT_STATE_OPEN)
871 num++;
873 return num >= NUM_PARALLEL_TESTING_CIRCS;
876 /** A testing circuit has completed. Take whatever stats we want.
877 * Noticing reachability is taken care of in onionskin_answer(),
878 * so there's no need to record anything here. But if we still want
879 * to do the bandwidth test, and we now have enough testing circuits
880 * open, do it.
882 static void
883 circuit_testing_opened(origin_circuit_t *circ)
885 if (have_performed_bandwidth_test ||
886 !check_whether_orport_reachable()) {
887 /* either we've already done everything we want with testing circuits,
888 * or this testing circuit became open due to a fluke, e.g. we picked
889 * a last hop where we already had the connection open due to an
890 * outgoing local circuit. */
891 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
892 } else if (circuit_enough_testing_circs()) {
893 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
894 have_performed_bandwidth_test = 1;
895 } else
896 consider_testing_reachability(1, 0);
899 /** A testing circuit has failed to build. Take whatever stats we want. */
900 static void
901 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
903 if (server_mode(get_options()) && check_whether_orport_reachable())
904 return;
906 log_info(LD_GENERAL,
907 "Our testing circuit (to see if your ORPort is reachable) "
908 "has failed. I'll try again later.");
910 /* These aren't used yet. */
911 (void)circ;
912 (void)at_last_hop;
915 /** The circuit <b>circ</b> has just become open. Take the next
916 * step: for rendezvous circuits, we pass circ to the appropriate
917 * function in rendclient or rendservice. For general circuits, we
918 * call connection_ap_attach_pending, which looks for pending streams
919 * that could use circ.
921 void
922 circuit_has_opened(origin_circuit_t *circ)
924 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
926 /* Remember that this circuit has finished building. Now if we start
927 * it building again later (e.g. by extending it), we will know not
928 * to consider its build time. */
929 circ->has_opened = 1;
931 switch (TO_CIRCUIT(circ)->purpose) {
932 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
933 rend_client_rendcirc_has_opened(circ);
934 connection_ap_attach_pending();
935 break;
936 case CIRCUIT_PURPOSE_C_INTRODUCING:
937 rend_client_introcirc_has_opened(circ);
938 break;
939 case CIRCUIT_PURPOSE_C_GENERAL:
940 /* Tell any AP connections that have been waiting for a new
941 * circuit that one is ready. */
942 connection_ap_attach_pending();
943 break;
944 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
945 /* at Bob, waiting for introductions */
946 rend_service_intro_has_opened(circ);
947 break;
948 case CIRCUIT_PURPOSE_S_CONNECT_REND:
949 /* at Bob, connecting to rend point */
950 rend_service_rendezvous_has_opened(circ);
951 break;
952 case CIRCUIT_PURPOSE_TESTING:
953 circuit_testing_opened(circ);
954 break;
955 /* default:
956 * This won't happen in normal operation, but might happen if the
957 * controller did it. Just let it slide. */
961 /** Called whenever a circuit could not be successfully built.
963 void
964 circuit_build_failed(origin_circuit_t *circ)
966 /* we should examine circ and see if it failed because of
967 * the last hop or an earlier hop. then use this info below.
969 int failed_at_last_hop = 0;
970 /* If the last hop isn't open, and the second-to-last is, we failed
971 * at the last hop. */
972 if (circ->cpath &&
973 circ->cpath->prev->state != CPATH_STATE_OPEN &&
974 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
975 failed_at_last_hop = 1;
977 if (circ->cpath &&
978 circ->cpath->state != CPATH_STATE_OPEN) {
979 /* We failed at the first hop. If there's an OR connection
980 * to blame, blame it. Also, avoid this relay for a while, and
981 * fail any one-hop directory fetches destined for it. */
982 const char *n_conn_id = circ->cpath->extend_info->identity_digest;
983 if (circ->_base.n_conn) {
984 or_connection_t *n_conn = circ->_base.n_conn;
985 log_info(LD_OR,
986 "Our circuit failed to get a response from the first hop "
987 "(%s:%d). I'm going to try to rotate to a better connection.",
988 n_conn->_base.address, n_conn->_base.port);
989 n_conn->is_bad_for_new_circs = 1;
990 } else {
991 log_info(LD_OR,
992 "Our circuit died before the first hop with no connection");
994 if (n_conn_id) {
995 entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
996 /* if there are any one-hop streams waiting on this circuit, fail
997 * them now so they can retry elsewhere. */
998 connection_ap_fail_onehop(n_conn_id, circ->build_state);
1002 switch (circ->_base.purpose) {
1003 case CIRCUIT_PURPOSE_C_GENERAL:
1004 /* If we never built the circuit, note it as a failure. */
1005 circuit_increment_failure_count();
1006 if (failed_at_last_hop) {
1007 /* Make sure any streams that demand our last hop as their exit
1008 * know that it's unlikely to happen. */
1009 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
1011 break;
1012 case CIRCUIT_PURPOSE_TESTING:
1013 circuit_testing_failed(circ, failed_at_last_hop);
1014 break;
1015 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1016 /* at Bob, waiting for introductions */
1017 if (circ->_base.state != CIRCUIT_STATE_OPEN) {
1018 circuit_increment_failure_count();
1020 /* no need to care here, because bob will rebuild intro
1021 * points periodically. */
1022 break;
1023 case CIRCUIT_PURPOSE_C_INTRODUCING:
1024 /* at Alice, connecting to intro point */
1025 /* Don't increment failure count, since Bob may have picked
1026 * the introduction point maliciously */
1027 /* Alice will pick a new intro point when this one dies, if
1028 * the stream in question still cares. No need to act here. */
1029 break;
1030 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1031 /* at Alice, waiting for Bob */
1032 circuit_increment_failure_count();
1033 /* Alice will pick a new rend point when this one dies, if
1034 * the stream in question still cares. No need to act here. */
1035 break;
1036 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1037 /* at Bob, connecting to rend point */
1038 /* Don't increment failure count, since Alice may have picked
1039 * the rendezvous point maliciously */
1040 log_info(LD_REND,
1041 "Couldn't connect to Alice's chosen rend point %s "
1042 "(%s hop failed).",
1043 escaped(build_state_get_exit_nickname(circ->build_state)),
1044 failed_at_last_hop?"last":"non-last");
1045 rend_service_relaunch_rendezvous(circ);
1046 break;
1047 /* default:
1048 * This won't happen in normal operation, but might happen if the
1049 * controller did it. Just let it slide. */
1053 /** Number of consecutive failures so far; should only be touched by
1054 * circuit_launch_new and circuit_*_failure_count.
1056 static int n_circuit_failures = 0;
1057 /** Before the last time we called circuit_reset_failure_count(), were
1058 * there a lot of failures? */
1059 static int did_circs_fail_last_period = 0;
1061 /** Don't retry launching a new circuit if we try this many times with no
1062 * success. */
1063 #define MAX_CIRCUIT_FAILURES 5
1065 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1066 * details on arguments. */
1067 origin_circuit_t *
1068 circuit_launch_by_router(uint8_t purpose,
1069 routerinfo_t *exit, int flags)
1071 origin_circuit_t *circ;
1072 extend_info_t *info = NULL;
1073 if (exit)
1074 info = extend_info_from_router(exit);
1075 circ = circuit_launch_by_extend_info(purpose, info, flags);
1077 extend_info_free(info);
1078 return circ;
1081 /** Launch a new circuit with purpose <b>purpose</b> and exit node
1082 * <b>extend_info</b> (or NULL to select a random exit node). If flags
1083 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
1084 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
1085 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
1086 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
1087 * Return the newly allocated circuit on success, or NULL on failure. */
1088 origin_circuit_t *
1089 circuit_launch_by_extend_info(uint8_t purpose,
1090 extend_info_t *extend_info,
1091 int flags)
1093 origin_circuit_t *circ;
1094 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
1096 if (!onehop_tunnel && !router_have_minimum_dir_info()) {
1097 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
1098 "circuit launch.");
1099 return NULL;
1102 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
1103 purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
1104 /* see if there are appropriate circs available to cannibalize. */
1105 /* XXX if we're planning to add a hop, perhaps we want to look for
1106 * internal circs rather than exit circs? -RD */
1107 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
1108 if (circ) {
1109 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
1110 build_state_get_exit_nickname(circ->build_state), purpose);
1111 circ->_base.purpose = purpose;
1112 /* reset the birth date of this circ, else expire_building
1113 * will see it and think it's been trying to build since it
1114 * began. */
1115 circ->_base.timestamp_created = time(NULL);
1116 switch (purpose) {
1117 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1118 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1119 /* it's ready right now */
1120 break;
1121 case CIRCUIT_PURPOSE_C_INTRODUCING:
1122 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1123 case CIRCUIT_PURPOSE_C_GENERAL:
1124 /* need to add a new hop */
1125 tor_assert(extend_info);
1126 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
1127 return NULL;
1128 break;
1129 default:
1130 log_warn(LD_BUG,
1131 "unexpected purpose %d when cannibalizing a circ.",
1132 purpose);
1133 tor_fragile_assert();
1134 return NULL;
1136 return circ;
1140 if (did_circs_fail_last_period &&
1141 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
1142 /* too many failed circs in a row. don't try. */
1143 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1144 return NULL;
1147 /* try a circ. if it fails, circuit_mark_for_close will increment
1148 * n_circuit_failures */
1149 return circuit_establish_circuit(purpose, extend_info, flags);
1152 /** Record another failure at opening a general circuit. When we have
1153 * too many, we'll stop trying for the remainder of this minute.
1155 static void
1156 circuit_increment_failure_count(void)
1158 ++n_circuit_failures;
1159 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
1162 /** Reset the failure count for opening general circuits. This means
1163 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1164 * stopping again.
1166 void
1167 circuit_reset_failure_count(int timeout)
1169 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
1170 did_circs_fail_last_period = 1;
1171 else
1172 did_circs_fail_last_period = 0;
1173 n_circuit_failures = 0;
1176 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1177 * there isn't one, and there isn't one on the way, launch one and return
1178 * 0. If it will never work, return -1.
1180 * Write the found or in-progress or launched circ into *circp.
1182 static int
1183 circuit_get_open_circ_or_launch(edge_connection_t *conn,
1184 uint8_t desired_circuit_purpose,
1185 origin_circuit_t **circp)
1187 origin_circuit_t *circ;
1188 int check_exit_policy;
1189 int need_uptime, need_internal;
1190 int want_onehop;
1191 or_options_t *options = get_options();
1193 tor_assert(conn);
1194 tor_assert(circp);
1195 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1196 check_exit_policy =
1197 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
1198 !conn->use_begindir &&
1199 !connection_edge_is_rendezvous_stream(conn);
1200 want_onehop = conn->want_onehop;
1202 need_uptime = !conn->want_onehop && !conn->use_begindir &&
1203 smartlist_string_num_isin(options->LongLivedPorts,
1204 conn->socks_request->port);
1205 need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
1207 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
1208 need_uptime, need_internal);
1210 if (circ) {
1211 *circp = circ;
1212 return 1; /* we're happy */
1215 if (!want_onehop && !router_have_minimum_dir_info()) {
1216 if (!connection_get_by_type(CONN_TYPE_DIR)) {
1217 int severity = LOG_NOTICE;
1218 /* FFFF if this is a tunneled directory fetch, don't yell
1219 * as loudly. the user doesn't even know it's happening. */
1220 if (options->UseBridges && bridges_known_but_down()) {
1221 log_fn(severity, LD_APP|LD_DIR,
1222 "Application request when we haven't used client functionality "
1223 "lately. Optimistically trying known bridges again.");
1224 bridges_retry_all();
1225 } else if (!options->UseBridges || any_bridge_descriptors_known()) {
1226 log_fn(severity, LD_APP|LD_DIR,
1227 "Application request when we haven't used client functionality "
1228 "lately. Optimistically trying directory fetches again.");
1229 routerlist_retry_directory_downloads(time(NULL));
1232 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1233 * 1, or when all directory attempts fail and directory_all_unreachable()
1234 * kills it.
1236 return 0;
1239 /* Do we need to check exit policy? */
1240 if (check_exit_policy) {
1241 if (!conn->chosen_exit_name) {
1242 struct in_addr in;
1243 uint32_t addr = 0;
1244 if (tor_inet_aton(conn->socks_request->address, &in))
1245 addr = ntohl(in.s_addr);
1246 if (router_exit_policy_all_routers_reject(addr,
1247 conn->socks_request->port,
1248 need_uptime)) {
1249 log_notice(LD_APP,
1250 "No Tor server allows exit to %s:%d. Rejecting.",
1251 safe_str_client(conn->socks_request->address),
1252 conn->socks_request->port);
1253 return -1;
1255 } else {
1256 /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
1257 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1258 int opt = conn->chosen_exit_optional;
1259 if (router && !connection_ap_can_use_exit(conn, router, 0)) {
1260 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1261 "Requested exit point '%s' would refuse request. %s.",
1262 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1263 if (opt) {
1264 conn->chosen_exit_optional = 0;
1265 tor_free(conn->chosen_exit_name);
1266 /* Try again. */
1267 return circuit_get_open_circ_or_launch(conn,
1268 desired_circuit_purpose,
1269 circp);
1271 return -1;
1276 /* is one already on the way? */
1277 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
1278 need_uptime, need_internal);
1279 if (circ)
1280 log_debug(LD_CIRC, "one on the way!");
1281 if (!circ) {
1282 extend_info_t *extend_info=NULL;
1283 uint8_t new_circ_purpose;
1285 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1286 /* need to pick an intro point */
1287 tor_assert(conn->rend_data);
1288 extend_info = rend_client_get_random_intro(conn->rend_data);
1289 if (!extend_info) {
1290 log_info(LD_REND,
1291 "No intro points for '%s': re-fetching service descriptor.",
1292 safe_str_client(conn->rend_data->onion_address));
1293 rend_client_refetch_v2_renddesc(conn->rend_data);
1294 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1295 return 0;
1297 log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
1298 extend_info->nickname,
1299 safe_str_client(conn->rend_data->onion_address));
1302 /* If we have specified a particular exit node for our
1303 * connection, then be sure to open a circuit to that exit node.
1305 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1306 if (conn->chosen_exit_name) {
1307 routerinfo_t *r;
1308 int opt = conn->chosen_exit_optional;
1309 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1310 if (r) {
1311 extend_info = extend_info_from_router(r);
1312 } else {
1313 log_debug(LD_DIR, "considering %d, %s",
1314 want_onehop, conn->chosen_exit_name);
1315 if (want_onehop && conn->chosen_exit_name[0] == '$') {
1316 /* We're asking for a one-hop circuit to a router that
1317 * we don't have a routerinfo about. Make up an extend_info. */
1318 char digest[DIGEST_LEN];
1319 char *hexdigest = conn->chosen_exit_name+1;
1320 tor_addr_t addr;
1321 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
1322 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
1323 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
1324 return -1;
1326 if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
1327 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
1328 escaped_safe_str_client(conn->socks_request->address));
1329 return -1;
1331 extend_info = extend_info_alloc(conn->chosen_exit_name+1,
1332 digest, NULL, &addr,
1333 conn->socks_request->port);
1334 } else {
1335 /* We will need an onion key for the router, and we
1336 * don't have one. Refuse or relax requirements. */
1337 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1338 "Requested exit point '%s' is not known. %s.",
1339 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1340 if (opt) {
1341 conn->chosen_exit_optional = 0;
1342 tor_free(conn->chosen_exit_name);
1343 /* Try again with no requested exit */
1344 return circuit_get_open_circ_or_launch(conn,
1345 desired_circuit_purpose,
1346 circp);
1348 return -1;
1354 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
1355 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
1356 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1357 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
1358 else
1359 new_circ_purpose = desired_circuit_purpose;
1362 int flags = CIRCLAUNCH_NEED_CAPACITY;
1363 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
1364 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1365 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
1366 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
1367 flags);
1370 extend_info_free(extend_info);
1372 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
1373 /* help predict this next time */
1374 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1375 if (circ) {
1376 /* write the service_id into circ */
1377 circ->rend_data = rend_data_dup(conn->rend_data);
1378 if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1379 circ->_base.state == CIRCUIT_STATE_OPEN)
1380 rend_client_rendcirc_has_opened(circ);
1384 if (!circ)
1385 log_info(LD_APP,
1386 "No safe circuit (purpose %d) ready for edge "
1387 "connection; delaying.",
1388 desired_circuit_purpose);
1389 *circp = circ;
1390 return 0;
1393 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1394 * <b>circ</b>. */
1395 static int
1396 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
1398 crypt_path_t *cpath, *cpath_next = NULL;
1399 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1400 cpath_next = cpath->next;
1401 if (crypt_path == cpath)
1402 return 1;
1404 return 0;
1407 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1408 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1409 * hop in circ's cpath if <b>cpath</b> is NULL.
1411 static void
1412 link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
1413 crypt_path_t *cpath)
1415 /* add it into the linked list of streams on this circuit */
1416 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
1417 circ->_base.n_circ_id);
1418 /* reset it, so we can measure circ timeouts */
1419 apconn->_base.timestamp_lastread = time(NULL);
1420 apconn->next_stream = circ->p_streams;
1421 apconn->on_circuit = TO_CIRCUIT(circ);
1422 /* assert_connection_ok(conn, time(NULL)); */
1423 circ->p_streams = apconn;
1425 if (cpath) { /* we were given one; use it */
1426 tor_assert(cpath_is_on_circuit(circ, cpath));
1427 apconn->cpath_layer = cpath;
1428 } else { /* use the last hop in the circuit */
1429 tor_assert(circ->cpath);
1430 tor_assert(circ->cpath->prev);
1431 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1432 apconn->cpath_layer = circ->cpath->prev;
1436 /** If an exit wasn't specifically chosen, save the history for future
1437 * use. */
1438 static void
1439 consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
1441 int found_needle = 0;
1442 or_options_t *options = get_options();
1443 size_t len;
1444 char *new_address;
1445 char fp[HEX_DIGEST_LEN+1];
1447 /* Search the addressmap for this conn's destination. */
1448 /* If he's not in the address map.. */
1449 if (!options->TrackHostExits ||
1450 addressmap_have_mapping(conn->socks_request->address,
1451 options->TrackHostExitsExpire))
1452 return; /* nothing to track, or already mapped */
1454 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1455 if (cp[0] == '.') { /* match end */
1456 if (cp[1] == '\0' ||
1457 !strcasecmpend(conn->socks_request->address, cp) ||
1458 !strcasecmp(conn->socks_request->address, &cp[1]))
1459 found_needle = 1;
1460 } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
1461 found_needle = 1;
1465 if (!found_needle || !circ->build_state->chosen_exit)
1466 return;
1468 /* write down the fingerprint of the chosen exit, not the nickname,
1469 * because the chosen exit might not be named. */
1470 base16_encode(fp, sizeof(fp),
1471 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
1473 /* Add this exit/hostname pair to the addressmap. */
1474 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1475 strlen(fp) + 1 /* '.' */ +
1476 strlen("exit") + 1 /* '\0' */;
1477 new_address = tor_malloc(len);
1479 tor_snprintf(new_address, len, "%s.%s.exit",
1480 conn->socks_request->address, fp);
1482 addressmap_register(conn->socks_request->address, new_address,
1483 time(NULL) + options->TrackHostExitsExpire,
1484 ADDRMAPSRC_TRACKEXIT);
1487 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1488 * begin or resolve cell as appropriate. Return values are as for
1489 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1490 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1491 * <b>cpath</b> is NULL. */
1493 connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
1494 origin_circuit_t *circ,
1495 crypt_path_t *cpath)
1497 tor_assert(conn);
1498 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
1499 conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
1500 tor_assert(conn->socks_request);
1501 tor_assert(circ);
1502 tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
1504 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1506 if (!circ->_base.timestamp_dirty)
1507 circ->_base.timestamp_dirty = time(NULL);
1509 link_apconn_to_circ(conn, circ, cpath);
1510 tor_assert(conn->socks_request);
1511 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
1512 if (!conn->use_begindir)
1513 consider_recording_trackhost(conn, circ);
1514 if (connection_ap_handshake_send_begin(conn) < 0)
1515 return -1;
1516 } else {
1517 if (connection_ap_handshake_send_resolve(conn) < 0)
1518 return -1;
1521 return 1;
1524 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1525 * we don't find one: if conn cannot be handled by any known nodes,
1526 * warn and return -1 (conn needs to die, and is maybe already marked);
1527 * else launch new circuit (if necessary) and return 0.
1528 * Otherwise, associate conn with a safe live circuit, do the
1529 * right next step, and return 1.
1531 /* XXXX this function should mark for close whenever it returns -1;
1532 * its callers shouldn't have to worry about that. */
1534 connection_ap_handshake_attach_circuit(edge_connection_t *conn)
1536 int retval;
1537 int conn_age;
1538 int want_onehop;
1540 tor_assert(conn);
1541 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1542 tor_assert(conn->socks_request);
1543 want_onehop = conn->want_onehop;
1545 conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
1547 if (conn_age >= get_options()->SocksTimeout) {
1548 int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
1549 LOG_INFO : LOG_NOTICE;
1550 log_fn(severity, LD_APP,
1551 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1552 conn_age, safe_str_client(conn->socks_request->address),
1553 conn->socks_request->port);
1554 return -1;
1557 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1558 origin_circuit_t *circ=NULL;
1560 if (conn->chosen_exit_name) {
1561 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1562 int opt = conn->chosen_exit_optional;
1563 if (!router && !want_onehop) {
1564 /* We ran into this warning when trying to extend a circuit to a
1565 * hidden service directory for which we didn't have a router
1566 * descriptor. See flyspray task 767 for more details. We should
1567 * keep this in mind when deciding to use BEGIN_DIR cells for other
1568 * directory requests as well. -KL*/
1569 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1570 "Requested exit point '%s' is not known. %s.",
1571 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1572 if (opt) {
1573 conn->chosen_exit_optional = 0;
1574 tor_free(conn->chosen_exit_name);
1575 return 0;
1577 return -1;
1579 if (router && !connection_ap_can_use_exit(conn, router, 0)) {
1580 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1581 "Requested exit point '%s' would refuse request. %s.",
1582 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1583 if (opt) {
1584 conn->chosen_exit_optional = 0;
1585 tor_free(conn->chosen_exit_name);
1586 return 0;
1588 return -1;
1592 /* find the circuit that we should use, if there is one. */
1593 retval = circuit_get_open_circ_or_launch(
1594 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1595 if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
1596 return retval;
1598 log_debug(LD_APP|LD_CIRC,
1599 "Attaching apconn to circ %d (stream %d sec old).",
1600 circ->_base.n_circ_id, conn_age);
1601 /* print the circ's path, so people can figure out which circs are
1602 * sucking. */
1603 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1605 /* We have found a suitable circuit for our conn. Hurray. */
1606 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
1608 } else { /* we're a rendezvous conn */
1609 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
1611 tor_assert(!conn->cpath_layer);
1613 /* start by finding a rendezvous circuit for us */
1615 retval = circuit_get_open_circ_or_launch(
1616 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1617 if (retval < 0) return -1; /* failed */
1619 if (retval > 0) {
1620 tor_assert(rendcirc);
1621 /* one is already established, attach */
1622 log_info(LD_REND,
1623 "rend joined circ %d already here. attaching. "
1624 "(stream %d sec old)",
1625 rendcirc->_base.n_circ_id, conn_age);
1626 /* Mark rendezvous circuits as 'newly dirty' every time you use
1627 * them, since the process of rebuilding a rendezvous circ is so
1628 * expensive. There is a tradeoff between linkability and
1629 * feasibility, at this point.
1631 rendcirc->_base.timestamp_dirty = time(NULL);
1632 link_apconn_to_circ(conn, rendcirc, NULL);
1633 if (connection_ap_handshake_send_begin(conn) < 0)
1634 return 0; /* already marked, let them fade away */
1635 return 1;
1638 if (rendcirc && (rendcirc->_base.purpose ==
1639 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
1640 log_info(LD_REND,
1641 "pending-join circ %d already here, with intro ack. "
1642 "Stalling. (stream %d sec old)",
1643 rendcirc->_base.n_circ_id, conn_age);
1644 return 0;
1647 /* it's on its way. find an intro circ. */
1648 retval = circuit_get_open_circ_or_launch(
1649 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1650 if (retval < 0) return -1; /* failed */
1652 if (retval > 0) {
1653 /* one has already sent the intro. keep waiting. */
1654 circuit_t *c = NULL;
1655 tor_assert(introcirc);
1656 log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
1657 "Stalling. (stream %d sec old)",
1658 introcirc->_base.n_circ_id,
1659 rendcirc ? rendcirc->_base.n_circ_id : 0,
1660 conn_age);
1661 /* abort parallel intro circs, if any */
1662 for (c = global_circuitlist; c; c = c->next) {
1663 if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
1664 !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
1665 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
1666 if (oc->rend_data &&
1667 !rend_cmp_service_ids(conn->rend_data->onion_address,
1668 oc->rend_data->onion_address)) {
1669 log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
1670 "built in parallel.");
1671 circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
1675 return 0;
1678 /* now rendcirc and introcirc are each either undefined or not finished */
1680 if (rendcirc && introcirc &&
1681 rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1682 log_info(LD_REND,
1683 "ready rend circ %d already here (no intro-ack yet on "
1684 "intro %d). (stream %d sec old)",
1685 rendcirc->_base.n_circ_id,
1686 introcirc->_base.n_circ_id, conn_age);
1688 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1689 if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
1690 log_info(LD_REND,"found open intro circ %d (rend %d); sending "
1691 "introduction. (stream %d sec old)",
1692 introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
1693 conn_age);
1694 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1695 return -1;
1697 rendcirc->_base.timestamp_dirty = time(NULL);
1698 introcirc->_base.timestamp_dirty = time(NULL);
1699 assert_circuit_ok(TO_CIRCUIT(rendcirc));
1700 assert_circuit_ok(TO_CIRCUIT(introcirc));
1701 return 0;
1705 log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
1706 "Stalling conn. (%d sec old)",
1707 introcirc ? introcirc->_base.n_circ_id : 0,
1708 rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
1709 return 0;