bump to 0.2.2.14-alpha-dev
[tor/rransom.git] / src / or / circuituse.c
blob50800aec5d52c03e2123fa4f54eb40743a47bb58
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"
14 /********* START VARIABLES **********/
16 extern circuit_t *global_circuitlist; /* from circuitlist.c */
18 /********* END VARIABLES ************/
20 static void circuit_expire_old_circuits_clientside(time_t now);
21 static void circuit_increment_failure_count(void);
23 long int lround(double x);
25 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
26 * Else return 0.
28 static int
29 circuit_is_acceptable(circuit_t *circ, edge_connection_t *conn,
30 int must_be_open, uint8_t purpose,
31 int need_uptime, int need_internal,
32 time_t now)
34 routerinfo_t *exitrouter;
35 cpath_build_state_t *build_state;
36 tor_assert(circ);
37 tor_assert(conn);
38 tor_assert(conn->socks_request);
40 if (!CIRCUIT_IS_ORIGIN(circ))
41 return 0; /* this circ doesn't start at us */
42 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
43 return 0; /* ignore non-open circs */
44 if (circ->marked_for_close)
45 return 0;
47 /* if this circ isn't our purpose, skip. */
48 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
49 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
50 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
51 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
52 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
53 return 0;
54 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
55 !must_be_open) {
56 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
57 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
58 return 0;
59 } else {
60 if (purpose != circ->purpose)
61 return 0;
64 if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
65 if (circ->timestamp_dirty &&
66 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
67 return 0;
69 /* decide if this circ is suitable for this conn */
71 /* for rend circs, circ->cpath->prev is not the last router in the
72 * circuit, it's the magical extra bob hop. so just check the nickname
73 * of the one we meant to finish at.
75 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
76 exitrouter = build_state_get_exit_router(build_state);
78 if (need_uptime && !build_state->need_uptime)
79 return 0;
80 if (need_internal != build_state->is_internal)
81 return 0;
83 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
84 if (!exitrouter && !build_state->onehop_tunnel) {
85 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
86 return 0; /* this circuit is screwed and doesn't know it yet,
87 * or is a rendezvous circuit. */
89 if (build_state->onehop_tunnel) {
90 if (!conn->want_onehop) {
91 log_debug(LD_CIRC,"Skipping one-hop circuit.");
92 return 0;
94 tor_assert(conn->chosen_exit_name);
95 if (build_state->chosen_exit) {
96 char digest[DIGEST_LEN];
97 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
98 return 0; /* broken digest, we don't want it */
99 if (memcmp(digest, build_state->chosen_exit->identity_digest,
100 DIGEST_LEN))
101 return 0; /* this is a circuit to somewhere else */
102 if (tor_digest_is_zero(digest)) {
103 /* we don't know the digest; have to compare addr:port */
104 tor_addr_t addr;
105 int r = tor_addr_from_str(&addr, conn->socks_request->address);
106 if (r < 0 ||
107 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
108 build_state->chosen_exit->port != conn->socks_request->port)
109 return 0;
112 } else {
113 if (conn->want_onehop) {
114 /* don't use three-hop circuits -- that could hurt our anonymity. */
115 return 0;
118 if (exitrouter && !connection_ap_can_use_exit(conn, exitrouter, 0)) {
119 /* can't exit from this router */
120 return 0;
122 } else { /* not general */
123 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
124 if ((conn->rend_data && !ocirc->rend_data) ||
125 (!conn->rend_data && ocirc->rend_data) ||
126 (conn->rend_data && ocirc->rend_data &&
127 rend_cmp_service_ids(conn->rend_data->onion_address,
128 ocirc->rend_data->onion_address))) {
129 /* this circ is not for this conn */
130 return 0;
133 return 1;
136 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
137 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
139 static int
140 circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
142 switch (purpose) {
143 case CIRCUIT_PURPOSE_C_GENERAL:
144 /* if it's used but less dirty it's best;
145 * else if it's more recently created it's best
147 if (b->timestamp_dirty) {
148 if (a->timestamp_dirty &&
149 a->timestamp_dirty > b->timestamp_dirty)
150 return 1;
151 } else {
152 if (a->timestamp_dirty ||
153 a->timestamp_created > b->timestamp_created)
154 return 1;
155 if (CIRCUIT_IS_ORIGIN(b) &&
156 TO_ORIGIN_CIRCUIT(b)->build_state->is_internal)
157 return 1;
159 break;
160 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
161 /* the closer it is to ack_wait the better it is */
162 if (a->purpose > b->purpose)
163 return 1;
164 break;
165 case CIRCUIT_PURPOSE_C_REND_JOINED:
166 /* the closer it is to rend_joined the better it is */
167 if (a->purpose > b->purpose)
168 return 1;
169 break;
171 return 0;
174 /** Find the best circ that conn can use, preferably one which is
175 * dirty. Circ must not be too old.
177 * Conn must be defined.
179 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
181 * circ_purpose specifies what sort of circuit we must have.
182 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
184 * If it's REND_JOINED and must_be_open==0, then return the closest
185 * rendezvous-purposed circuit that you can find.
187 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
188 * closest introduce-purposed circuit that you can find.
190 static origin_circuit_t *
191 circuit_get_best(edge_connection_t *conn, int must_be_open, uint8_t purpose,
192 int need_uptime, int need_internal)
194 circuit_t *circ, *best=NULL;
195 time_t now = time(NULL);
196 int intro_going_on_but_too_old = 0;
198 tor_assert(conn);
200 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
201 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
202 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
204 for (circ=global_circuitlist;circ;circ = circ->next) {
205 if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
206 need_uptime,need_internal,now))
207 continue;
209 /* XXX022 make this 15 be a function of circuit finishing times we've
210 * seen lately, a la Fallon Chen's GSoC work -RD */
211 #define REND_PARALLEL_INTRO_DELAY 15
212 if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
213 !must_be_open && circ->state != CIRCUIT_STATE_OPEN &&
214 circ->timestamp_created + REND_PARALLEL_INTRO_DELAY < now) {
215 intro_going_on_but_too_old = 1;
216 continue;
219 /* now this is an acceptable circ to hand back. but that doesn't
220 * mean it's the *best* circ to hand back. try to decide.
222 if (!best || circuit_is_better(circ,best,purpose))
223 best = circ;
226 if (!best && intro_going_on_but_too_old)
227 log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
228 "right now, but it has already taken quite a while. Starting "
229 "one in parallel.");
231 return best ? TO_ORIGIN_CIRCUIT(best) : NULL;
234 /** Check whether, according to the policies in <b>options</b>, the
235 * circuit <b>circ</b> makes sense. */
236 /* XXXX currently only checks Exclude{Exit}Nodes. It should check more. */
238 circuit_conforms_to_options(const origin_circuit_t *circ,
239 const or_options_t *options)
241 const crypt_path_t *cpath, *cpath_next = NULL;
243 for (cpath = circ->cpath; cpath && cpath_next != circ->cpath;
244 cpath = cpath_next) {
245 cpath_next = cpath->next;
247 if (routerset_contains_extendinfo(options->ExcludeNodes,
248 cpath->extend_info))
249 return 0;
251 if (cpath->next == circ->cpath) {
252 /* This is apparently the exit node. */
254 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
255 cpath->extend_info))
256 return 0;
259 return 1;
262 /** Close all circuits that start at us, aren't open, and were born
263 * at least CircuitBuildTimeout seconds ago.
265 void
266 circuit_expire_building(time_t now)
268 circuit_t *victim, *next_circ = global_circuitlist;
269 /* circ_times.timeout is BUILD_TIMEOUT_INITIAL_VALUE if we haven't
270 * decided on a customized one yet */
271 time_t general_cutoff = now - lround(circ_times.timeout_ms/1000);
272 time_t begindir_cutoff = now - lround(circ_times.timeout_ms/2000);
273 time_t close_cutoff = now - lround(circ_times.close_ms/1000);
274 time_t introcirc_cutoff = begindir_cutoff;
275 cpath_build_state_t *build_state;
277 while (next_circ) {
278 time_t cutoff;
279 victim = next_circ;
280 next_circ = next_circ->next;
281 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
282 victim->marked_for_close) /* don't mess with marked circs */
283 continue;
285 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
286 if (build_state && build_state->onehop_tunnel)
287 cutoff = begindir_cutoff;
288 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
289 cutoff = introcirc_cutoff;
290 else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
291 cutoff = close_cutoff;
292 else
293 cutoff = general_cutoff;
295 if (victim->timestamp_created > cutoff)
296 continue; /* it's still young, leave it alone */
298 #if 0
299 /* some debug logs, to help track bugs */
300 if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
301 victim->timestamp_created <= introcirc_cutoff &&
302 victim->timestamp_created > general_cutoff)
303 log_info(LD_REND|LD_CIRC, "Timing out introduction circuit which we "
304 "would not have done if it had been a general circuit.");
306 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
307 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
308 if (!victim->timestamp_dirty)
309 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
310 "(clean).",
311 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
312 victim->purpose, victim->build_state->chosen_exit_name,
313 victim->n_circ_id);
314 else
315 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
316 "%d secs since dirty.",
317 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
318 victim->purpose, victim->build_state->chosen_exit_name,
319 victim->n_circ_id,
320 (int)(now - victim->timestamp_dirty));
322 #endif
324 /* if circ is !open, or if it's open but purpose is a non-finished
325 * intro or rend, then mark it for close */
326 if (victim->state == CIRCUIT_STATE_OPEN) {
327 switch (victim->purpose) {
328 default: /* most open circuits can be left alone. */
329 continue; /* yes, continue inside a switch refers to the nearest
330 * enclosing loop. C is smart. */
331 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
332 case CIRCUIT_PURPOSE_C_INTRODUCING:
333 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
334 break; /* too old, need to die */
335 case CIRCUIT_PURPOSE_C_REND_READY:
336 /* it's a rend_ready circ -- has it already picked a query? */
337 /* c_rend_ready circs measure age since timestamp_dirty,
338 * because that's set when they switch purposes
340 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
341 victim->timestamp_dirty > cutoff)
342 continue;
343 break;
344 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
345 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
346 /* rend and intro circs become dirty each time they
347 * make an introduction attempt. so timestamp_dirty
348 * will reflect the time since the last attempt.
350 if (victim->timestamp_dirty > cutoff)
351 continue;
352 break;
354 } else { /* circuit not open, consider recording failure as timeout */
355 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
356 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
358 if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
359 log_warn(LD_BUG, "Circuit %d (purpose %d) has timed out, "
360 "yet has attached streams!",
361 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
362 victim->purpose);
363 tor_fragile_assert();
364 continue;
367 /* circuits are allowed to last longer for measurement.
368 * Switch their purpose and wait. */
369 if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
370 victim->purpose = CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT;
371 circuit_build_times_count_timeout(&circ_times,
372 first_hop_succeeded);
373 continue;
377 * If the circuit build time is much greater than we would have cut
378 * it off at, we probably had a suspend event along this codepath,
379 * and we should discard the value.
381 if (now - victim->timestamp_created > 2*circ_times.close_ms/1000+1) {
382 log_notice(LD_CIRC,
383 "Extremely large value for circuit build timeout: %lds. "
384 "Assuming clock jump.",
385 (long)(now - victim->timestamp_created));
386 } else if (circuit_build_times_count_close(&circ_times,
387 first_hop_succeeded,
388 victim->timestamp_created)) {
389 circuit_build_times_set_timeout(&circ_times);
393 if (victim->n_conn)
394 log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
395 victim->n_conn->_base.address, victim->n_conn->_base.port,
396 victim->n_circ_id,
397 victim->state, circuit_state_to_string(victim->state),
398 victim->purpose);
399 else
400 log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
401 victim->n_circ_id, victim->state,
402 circuit_state_to_string(victim->state), victim->purpose);
404 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
405 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
409 /** Remove any elements in <b>needed_ports</b> that are handled by an
410 * open or in-progress circuit.
412 void
413 circuit_remove_handled_ports(smartlist_t *needed_ports)
415 int i;
416 uint16_t *port;
418 for (i = 0; i < smartlist_len(needed_ports); ++i) {
419 port = smartlist_get(needed_ports, i);
420 tor_assert(*port);
421 if (circuit_stream_is_being_handled(NULL, *port,
422 MIN_CIRCUITS_HANDLING_STREAM)) {
423 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
424 smartlist_del(needed_ports, i--);
425 tor_free(port);
426 } else {
427 log_debug(LD_CIRC,"Port %d is not handled.", *port);
432 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
433 * will have an acceptable exit node for exit stream <b>conn</b> if it
434 * is defined, else for "*:port".
435 * Else return 0.
438 circuit_stream_is_being_handled(edge_connection_t *conn,
439 uint16_t port, int min)
441 circuit_t *circ;
442 routerinfo_t *exitrouter;
443 int num=0;
444 time_t now = time(NULL);
445 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
446 conn ? conn->socks_request->port : port);
448 for (circ=global_circuitlist;circ;circ = circ->next) {
449 if (CIRCUIT_IS_ORIGIN(circ) &&
450 !circ->marked_for_close &&
451 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
452 (!circ->timestamp_dirty ||
453 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
454 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
455 if (build_state->is_internal || build_state->onehop_tunnel)
456 continue;
458 exitrouter = build_state_get_exit_router(build_state);
459 if (exitrouter && (!need_uptime || build_state->need_uptime)) {
460 int ok;
461 if (conn) {
462 ok = connection_ap_can_use_exit(conn, exitrouter, 0);
463 } else {
464 addr_policy_result_t r = compare_addr_to_addr_policy(
465 0, port, exitrouter->exit_policy);
466 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
468 if (ok) {
469 if (++num >= min)
470 return 1;
475 return 0;
478 /** Don't keep more than this many unused open circuits around. */
479 #define MAX_UNUSED_OPEN_CIRCUITS 14
481 /** Figure out how many circuits we have open that are clean. Make
482 * sure it's enough for all the upcoming behaviors we predict we'll have.
483 * But put an upper bound on the total number of circuits.
485 static void
486 circuit_predict_and_launch_new(void)
488 circuit_t *circ;
489 int num=0, num_internal=0, num_uptime_internal=0;
490 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
491 int port_needs_uptime=0, port_needs_capacity=1;
492 time_t now = time(NULL);
493 int flags = 0;
495 /* First, count how many of each type of circuit we have already. */
496 for (circ=global_circuitlist;circ;circ = circ->next) {
497 cpath_build_state_t *build_state;
498 if (!CIRCUIT_IS_ORIGIN(circ))
499 continue;
500 if (circ->marked_for_close)
501 continue; /* don't mess with marked circs */
502 if (circ->timestamp_dirty)
503 continue; /* only count clean circs */
504 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
505 continue; /* only pay attention to general-purpose circs */
506 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
507 if (build_state->onehop_tunnel)
508 continue;
509 num++;
510 if (build_state->is_internal)
511 num_internal++;
512 if (build_state->need_uptime && build_state->is_internal)
513 num_uptime_internal++;
516 /* If that's enough, then stop now. */
517 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
518 return; /* we already have many, making more probably will hurt */
520 /* Second, see if we need any more exit circuits. */
521 /* check if we know of a port that's been requested recently
522 * and no circuit is currently available that can handle it. */
523 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
524 &port_needs_capacity)) {
525 if (port_needs_uptime)
526 flags |= CIRCLAUNCH_NEED_UPTIME;
527 if (port_needs_capacity)
528 flags |= CIRCLAUNCH_NEED_CAPACITY;
529 log_info(LD_CIRC,
530 "Have %d clean circs (%d internal), need another exit circ.",
531 num, num_internal);
532 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
533 return;
536 /* Third, see if we need any more hidden service (server) circuits. */
537 if (num_rend_services() && num_uptime_internal < 3) {
538 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
539 CIRCLAUNCH_IS_INTERNAL);
540 log_info(LD_CIRC,
541 "Have %d clean circs (%d internal), need another internal "
542 "circ for my hidden service.",
543 num, num_internal);
544 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
545 return;
548 /* Fourth, see if we need any more hidden service (client) circuits. */
549 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
550 &hidserv_needs_capacity) &&
551 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
552 num_internal<2)) {
553 if (hidserv_needs_uptime)
554 flags |= CIRCLAUNCH_NEED_UPTIME;
555 if (hidserv_needs_capacity)
556 flags |= CIRCLAUNCH_NEED_CAPACITY;
557 flags |= CIRCLAUNCH_IS_INTERNAL;
558 log_info(LD_CIRC,
559 "Have %d clean circs (%d uptime-internal, %d internal), need"
560 " another hidden service circ.",
561 num, num_uptime_internal, num_internal);
562 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
563 return;
566 /* Finally, check to see if we still need more circuits to learn
567 * a good build timeout. But if we're close to our max number we
568 * want, don't do another -- we want to leave a few slots open so
569 * we can still build circuits preemptively as needed. */
570 if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
571 circuit_build_times_needs_circuits_now(&circ_times)) {
572 flags = CIRCLAUNCH_NEED_CAPACITY;
573 log_info(LD_CIRC,
574 "Have %d clean circs need another buildtime test circ.", num);
575 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
576 return;
580 /** Build a new test circuit every 5 minutes */
581 #define TESTING_CIRCUIT_INTERVAL 300
583 /** This function is called once a second, if router_have_min_dir_info() is
584 * true. Its job is to make sure all services we offer have enough circuits
585 * available. Some services just want enough circuits for current tasks,
586 * whereas others want a minimum set of idle circuits hanging around.
588 void
589 circuit_build_needed_circs(time_t now)
591 static time_t time_to_new_circuit = 0;
592 or_options_t *options = get_options();
594 /* launch a new circ for any pending streams that need one */
595 connection_ap_attach_pending();
597 /* make sure any hidden services have enough intro points */
598 rend_services_introduce();
600 if (time_to_new_circuit < now) {
601 circuit_reset_failure_count(1);
602 time_to_new_circuit = now + options->NewCircuitPeriod;
603 if (proxy_mode(get_options()))
604 addressmap_clean(now);
605 circuit_expire_old_circuits_clientside(now);
607 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
608 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
609 if (get_options()->RunTesting &&
610 circ &&
611 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
612 log_fn(LOG_INFO,"Creating a new testing circuit.");
613 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0);
615 #endif
617 if (!options->DisablePredictedCircuits)
618 circuit_predict_and_launch_new();
621 /** If the stream <b>conn</b> is a member of any of the linked
622 * lists of <b>circ</b>, then remove it from the list.
624 void
625 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
627 edge_connection_t *prevconn;
629 tor_assert(circ);
630 tor_assert(conn);
632 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
633 conn->on_circuit = NULL;
635 if (CIRCUIT_IS_ORIGIN(circ)) {
636 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
637 if (conn == origin_circ->p_streams) {
638 origin_circ->p_streams = conn->next_stream;
639 return;
642 for (prevconn = origin_circ->p_streams;
643 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
644 prevconn = prevconn->next_stream)
646 if (prevconn && prevconn->next_stream) {
647 prevconn->next_stream = conn->next_stream;
648 return;
650 } else {
651 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
652 if (conn == or_circ->n_streams) {
653 or_circ->n_streams = conn->next_stream;
654 return;
656 if (conn == or_circ->resolving_streams) {
657 or_circ->resolving_streams = conn->next_stream;
658 return;
661 for (prevconn = or_circ->n_streams;
662 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
663 prevconn = prevconn->next_stream)
665 if (prevconn && prevconn->next_stream) {
666 prevconn->next_stream = conn->next_stream;
667 return;
670 for (prevconn = or_circ->resolving_streams;
671 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
672 prevconn = prevconn->next_stream)
674 if (prevconn && prevconn->next_stream) {
675 prevconn->next_stream = conn->next_stream;
676 return;
680 log_warn(LD_BUG,"Edge connection not in circuit's list.");
681 /* Don't give an error here; it's harmless. */
682 tor_fragile_assert();
685 /** If we haven't yet decided on a good timeout value for circuit
686 * building, we close idles circuits aggressively so we can get more
687 * data points. */
688 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
690 /** Find each circuit that has been unused for too long, or dirty
691 * for too long and has no streams on it: mark it for close.
693 static void
694 circuit_expire_old_circuits_clientside(time_t now)
696 circuit_t *circ;
697 time_t cutoff;
699 if (circuit_build_times_needs_circuits(&circ_times)) {
700 /* Circuits should be shorter lived if we need more of them
701 * for learning a good build timeout */
702 cutoff = now - IDLE_TIMEOUT_WHILE_LEARNING;
703 } else {
704 cutoff = now - get_options()->CircuitIdleTimeout;
707 for (circ = global_circuitlist; circ; circ = circ->next) {
708 if (circ->marked_for_close || ! CIRCUIT_IS_ORIGIN(circ))
709 continue;
710 /* If the circuit has been dirty for too long, and there are no streams
711 * on it, mark it for close.
713 if (circ->timestamp_dirty &&
714 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
715 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
716 log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, "
717 "purpose %d)",
718 circ->n_circ_id, (int)(now - circ->timestamp_dirty),
719 circ->purpose);
720 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
721 } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
722 if (circ->timestamp_created < cutoff) {
723 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
724 circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
725 circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
726 circ->purpose == CIRCUIT_PURPOSE_TESTING ||
727 (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
728 circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
729 circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
730 log_debug(LD_CIRC,
731 "Closing circuit that has been unused for %ld seconds.",
732 (long)(now - circ->timestamp_created));
733 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
734 } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
735 log_notice(LD_CIRC,
736 "Ancient non-dirty circuit %d is still around after "
737 "%ld seconds. Purpose: %d",
738 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
739 (long)(now - circ->timestamp_created),
740 circ->purpose);
741 TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
748 /** How long do we wait before killing circuits with the properties
749 * described below?
751 * Probably we could choose a number here as low as 5 to 10 seconds,
752 * since these circs are used for begindir, and a) generally you either
753 * ask another begindir question right after or you don't for a long time,
754 * b) clients at least through 0.2.1.x choose from the whole set of
755 * directory mirrors at each choice, and c) re-establishing a one-hop
756 * circuit via create-fast is a light operation assuming the TLS conn is
757 * still there.
759 * I expect "b" to go away one day when we move to using directory
760 * guards, but I think "a" and "c" are good enough reasons that a low
761 * number is safe even then.
763 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
765 /** Find each non-origin circuit that has been unused for too long,
766 * has no streams on it, used a create_fast, and ends here: mark it
767 * for close.
769 void
770 circuit_expire_old_circuits_serverside(time_t now)
772 circuit_t *circ;
773 or_circuit_t *or_circ;
774 time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
776 for (circ = global_circuitlist; circ; circ = circ->next) {
777 if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
778 continue;
779 or_circ = TO_OR_CIRCUIT(circ);
780 /* If the circuit has been idle for too long, and there are no streams
781 * on it, and it ends here, and it used a create_fast, mark it for close.
783 if (or_circ->is_first_hop && !circ->n_conn &&
784 !or_circ->n_streams && !or_circ->resolving_streams &&
785 or_circ->p_conn &&
786 or_circ->p_conn->timestamp_last_added_nonpadding <= cutoff) {
787 log_info(LD_CIRC, "Closing circ_id %d (empty %d secs ago)",
788 or_circ->p_circ_id,
789 (int)(now - or_circ->p_conn->timestamp_last_added_nonpadding));
790 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
795 /** Number of testing circuits we want open before testing our bandwidth. */
796 #define NUM_PARALLEL_TESTING_CIRCS 4
798 /** True iff we've ever had enough testing circuits open to test our
799 * bandwidth. */
800 static int have_performed_bandwidth_test = 0;
802 /** Reset have_performed_bandwidth_test, so we'll start building
803 * testing circuits again so we can exercise our bandwidth. */
804 void
805 reset_bandwidth_test(void)
807 have_performed_bandwidth_test = 0;
810 /** Return 1 if we've already exercised our bandwidth, or if we
811 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
812 * established or on the way. Else return 0.
815 circuit_enough_testing_circs(void)
817 circuit_t *circ;
818 int num = 0;
820 if (have_performed_bandwidth_test)
821 return 1;
823 for (circ = global_circuitlist; circ; circ = circ->next) {
824 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
825 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
826 circ->state == CIRCUIT_STATE_OPEN)
827 num++;
829 return num >= NUM_PARALLEL_TESTING_CIRCS;
832 /** A testing circuit has completed. Take whatever stats we want.
833 * Noticing reachability is taken care of in onionskin_answer(),
834 * so there's no need to record anything here. But if we still want
835 * to do the bandwidth test, and we now have enough testing circuits
836 * open, do it.
838 static void
839 circuit_testing_opened(origin_circuit_t *circ)
841 if (have_performed_bandwidth_test ||
842 !check_whether_orport_reachable()) {
843 /* either we've already done everything we want with testing circuits,
844 * or this testing circuit became open due to a fluke, e.g. we picked
845 * a last hop where we already had the connection open due to an
846 * outgoing local circuit. */
847 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
848 } else if (circuit_enough_testing_circs()) {
849 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
850 have_performed_bandwidth_test = 1;
851 } else
852 consider_testing_reachability(1, 0);
855 /** A testing circuit has failed to build. Take whatever stats we want. */
856 static void
857 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
859 if (server_mode(get_options()) && check_whether_orport_reachable())
860 return;
862 log_info(LD_GENERAL,
863 "Our testing circuit (to see if your ORPort is reachable) "
864 "has failed. I'll try again later.");
866 /* These aren't used yet. */
867 (void)circ;
868 (void)at_last_hop;
871 /** The circuit <b>circ</b> has just become open. Take the next
872 * step: for rendezvous circuits, we pass circ to the appropriate
873 * function in rendclient or rendservice. For general circuits, we
874 * call connection_ap_attach_pending, which looks for pending streams
875 * that could use circ.
877 void
878 circuit_has_opened(origin_circuit_t *circ)
880 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
882 switch (TO_CIRCUIT(circ)->purpose) {
883 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
884 rend_client_rendcirc_has_opened(circ);
885 connection_ap_attach_pending();
886 break;
887 case CIRCUIT_PURPOSE_C_INTRODUCING:
888 rend_client_introcirc_has_opened(circ);
889 break;
890 case CIRCUIT_PURPOSE_C_GENERAL:
891 /* Tell any AP connections that have been waiting for a new
892 * circuit that one is ready. */
893 connection_ap_attach_pending();
894 break;
895 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
896 /* at Bob, waiting for introductions */
897 rend_service_intro_has_opened(circ);
898 break;
899 case CIRCUIT_PURPOSE_S_CONNECT_REND:
900 /* at Bob, connecting to rend point */
901 rend_service_rendezvous_has_opened(circ);
902 break;
903 case CIRCUIT_PURPOSE_TESTING:
904 circuit_testing_opened(circ);
905 break;
906 /* default:
907 * This won't happen in normal operation, but might happen if the
908 * controller did it. Just let it slide. */
912 /** Called whenever a circuit could not be successfully built.
914 void
915 circuit_build_failed(origin_circuit_t *circ)
917 /* we should examine circ and see if it failed because of
918 * the last hop or an earlier hop. then use this info below.
920 int failed_at_last_hop = 0;
921 /* If the last hop isn't open, and the second-to-last is, we failed
922 * at the last hop. */
923 if (circ->cpath &&
924 circ->cpath->prev->state != CPATH_STATE_OPEN &&
925 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
926 failed_at_last_hop = 1;
928 if (circ->cpath &&
929 circ->cpath->state != CPATH_STATE_OPEN) {
930 /* We failed at the first hop. If there's an OR connection
931 * to blame, blame it. Also, avoid this relay for a while, and
932 * fail any one-hop directory fetches destined for it. */
933 const char *n_conn_id = circ->cpath->extend_info->identity_digest;
934 if (circ->_base.n_conn) {
935 or_connection_t *n_conn = circ->_base.n_conn;
936 log_info(LD_OR,
937 "Our circuit failed to get a response from the first hop "
938 "(%s:%d). I'm going to try to rotate to a better connection.",
939 n_conn->_base.address, n_conn->_base.port);
940 n_conn->is_bad_for_new_circs = 1;
941 } else {
942 log_info(LD_OR,
943 "Our circuit died before the first hop with no connection");
945 if (n_conn_id) {
946 entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
947 /* if there are any one-hop streams waiting on this circuit, fail
948 * them now so they can retry elsewhere. */
949 connection_ap_fail_onehop(n_conn_id, circ->build_state);
953 switch (circ->_base.purpose) {
954 case CIRCUIT_PURPOSE_C_GENERAL:
955 /* If we never built the circuit, note it as a failure. */
956 circuit_increment_failure_count();
957 if (failed_at_last_hop) {
958 /* Make sure any streams that demand our last hop as their exit
959 * know that it's unlikely to happen. */
960 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
962 break;
963 case CIRCUIT_PURPOSE_TESTING:
964 circuit_testing_failed(circ, failed_at_last_hop);
965 break;
966 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
967 /* at Bob, waiting for introductions */
968 if (circ->_base.state != CIRCUIT_STATE_OPEN) {
969 circuit_increment_failure_count();
971 /* no need to care here, because bob will rebuild intro
972 * points periodically. */
973 break;
974 case CIRCUIT_PURPOSE_C_INTRODUCING:
975 /* at Alice, connecting to intro point */
976 /* Don't increment failure count, since Bob may have picked
977 * the introduction point maliciously */
978 /* Alice will pick a new intro point when this one dies, if
979 * the stream in question still cares. No need to act here. */
980 break;
981 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
982 /* at Alice, waiting for Bob */
983 circuit_increment_failure_count();
984 /* Alice will pick a new rend point when this one dies, if
985 * the stream in question still cares. No need to act here. */
986 break;
987 case CIRCUIT_PURPOSE_S_CONNECT_REND:
988 /* at Bob, connecting to rend point */
989 /* Don't increment failure count, since Alice may have picked
990 * the rendezvous point maliciously */
991 log_info(LD_REND,
992 "Couldn't connect to Alice's chosen rend point %s "
993 "(%s hop failed).",
994 escaped(build_state_get_exit_nickname(circ->build_state)),
995 failed_at_last_hop?"last":"non-last");
996 rend_service_relaunch_rendezvous(circ);
997 break;
998 /* default:
999 * This won't happen in normal operation, but might happen if the
1000 * controller did it. Just let it slide. */
1004 /** Number of consecutive failures so far; should only be touched by
1005 * circuit_launch_new and circuit_*_failure_count.
1007 static int n_circuit_failures = 0;
1008 /** Before the last time we called circuit_reset_failure_count(), were
1009 * there a lot of failures? */
1010 static int did_circs_fail_last_period = 0;
1012 /** Don't retry launching a new circuit if we try this many times with no
1013 * success. */
1014 #define MAX_CIRCUIT_FAILURES 5
1016 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1017 * details on arguments. */
1018 origin_circuit_t *
1019 circuit_launch_by_router(uint8_t purpose,
1020 routerinfo_t *exit, int flags)
1022 origin_circuit_t *circ;
1023 extend_info_t *info = NULL;
1024 if (exit)
1025 info = extend_info_from_router(exit);
1026 circ = circuit_launch_by_extend_info(purpose, info, flags);
1028 extend_info_free(info);
1029 return circ;
1032 /** Launch a new circuit with purpose <b>purpose</b> and exit node
1033 * <b>extend_info</b> (or NULL to select a random exit node). If flags
1034 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
1035 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
1036 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
1037 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
1038 * Return the newly allocated circuit on success, or NULL on failure. */
1039 origin_circuit_t *
1040 circuit_launch_by_extend_info(uint8_t purpose,
1041 extend_info_t *extend_info,
1042 int flags)
1044 origin_circuit_t *circ;
1045 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
1047 if (!onehop_tunnel && !router_have_minimum_dir_info()) {
1048 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
1049 "circuit launch.");
1050 return NULL;
1053 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
1054 purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
1055 /* see if there are appropriate circs available to cannibalize. */
1056 /* XXX if we're planning to add a hop, perhaps we want to look for
1057 * internal circs rather than exit circs? -RD */
1058 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
1059 if (circ) {
1060 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
1061 build_state_get_exit_nickname(circ->build_state), purpose);
1062 circ->_base.purpose = purpose;
1063 /* reset the birth date of this circ, else expire_building
1064 * will see it and think it's been trying to build since it
1065 * began. */
1066 circ->_base.timestamp_created = time(NULL);
1067 switch (purpose) {
1068 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1069 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1070 /* it's ready right now */
1071 break;
1072 case CIRCUIT_PURPOSE_C_INTRODUCING:
1073 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1074 case CIRCUIT_PURPOSE_C_GENERAL:
1075 /* need to add a new hop */
1076 tor_assert(extend_info);
1077 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
1078 return NULL;
1079 break;
1080 default:
1081 log_warn(LD_BUG,
1082 "unexpected purpose %d when cannibalizing a circ.",
1083 purpose);
1084 tor_fragile_assert();
1085 return NULL;
1087 return circ;
1091 if (did_circs_fail_last_period &&
1092 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
1093 /* too many failed circs in a row. don't try. */
1094 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1095 return NULL;
1098 /* try a circ. if it fails, circuit_mark_for_close will increment
1099 * n_circuit_failures */
1100 return circuit_establish_circuit(purpose, extend_info, flags);
1103 /** Record another failure at opening a general circuit. When we have
1104 * too many, we'll stop trying for the remainder of this minute.
1106 static void
1107 circuit_increment_failure_count(void)
1109 ++n_circuit_failures;
1110 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
1113 /** Reset the failure count for opening general circuits. This means
1114 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1115 * stopping again.
1117 void
1118 circuit_reset_failure_count(int timeout)
1120 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
1121 did_circs_fail_last_period = 1;
1122 else
1123 did_circs_fail_last_period = 0;
1124 n_circuit_failures = 0;
1127 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1128 * there isn't one, and there isn't one on the way, launch one and return
1129 * 0. If it will never work, return -1.
1131 * Write the found or in-progress or launched circ into *circp.
1133 static int
1134 circuit_get_open_circ_or_launch(edge_connection_t *conn,
1135 uint8_t desired_circuit_purpose,
1136 origin_circuit_t **circp)
1138 origin_circuit_t *circ;
1139 int check_exit_policy;
1140 int need_uptime, need_internal;
1141 int want_onehop;
1142 or_options_t *options = get_options();
1144 tor_assert(conn);
1145 tor_assert(circp);
1146 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1147 check_exit_policy =
1148 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
1149 !conn->use_begindir &&
1150 !connection_edge_is_rendezvous_stream(conn);
1151 want_onehop = conn->want_onehop;
1153 need_uptime = !conn->want_onehop && !conn->use_begindir &&
1154 smartlist_string_num_isin(options->LongLivedPorts,
1155 conn->socks_request->port);
1156 need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
1158 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
1159 need_uptime, need_internal);
1161 if (circ) {
1162 *circp = circ;
1163 return 1; /* we're happy */
1166 if (!want_onehop && !router_have_minimum_dir_info()) {
1167 if (!connection_get_by_type(CONN_TYPE_DIR)) {
1168 int severity = LOG_NOTICE;
1169 /* FFFF if this is a tunneled directory fetch, don't yell
1170 * as loudly. the user doesn't even know it's happening. */
1171 if (options->UseBridges && bridges_known_but_down()) {
1172 log_fn(severity, LD_APP|LD_DIR,
1173 "Application request when we're believed to be "
1174 "offline. Optimistically trying known bridges again.");
1175 bridges_retry_all();
1176 } else if (!options->UseBridges || any_bridge_descriptors_known()) {
1177 log_fn(severity, LD_APP|LD_DIR,
1178 "Application request when we're believed to be "
1179 "offline. Optimistically trying directory fetches again.");
1180 routerlist_retry_directory_downloads(time(NULL));
1183 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1184 * 1, or when all directory attempts fail and directory_all_unreachable()
1185 * kills it.
1187 return 0;
1190 /* Do we need to check exit policy? */
1191 if (check_exit_policy) {
1192 if (!conn->chosen_exit_name) {
1193 struct in_addr in;
1194 uint32_t addr = 0;
1195 if (tor_inet_aton(conn->socks_request->address, &in))
1196 addr = ntohl(in.s_addr);
1197 if (router_exit_policy_all_routers_reject(addr,
1198 conn->socks_request->port,
1199 need_uptime)) {
1200 log_notice(LD_APP,
1201 "No Tor server allows exit to %s:%d. Rejecting.",
1202 safe_str_client(conn->socks_request->address),
1203 conn->socks_request->port);
1204 return -1;
1206 } else {
1207 /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
1208 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1209 int opt = conn->chosen_exit_optional;
1210 if (router && !connection_ap_can_use_exit(conn, router, 0)) {
1211 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1212 "Requested exit point '%s' would refuse request. %s.",
1213 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1214 if (opt) {
1215 conn->chosen_exit_optional = 0;
1216 tor_free(conn->chosen_exit_name);
1217 /* Try again. */
1218 return circuit_get_open_circ_or_launch(conn,
1219 desired_circuit_purpose,
1220 circp);
1222 return -1;
1227 /* is one already on the way? */
1228 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
1229 need_uptime, need_internal);
1230 if (circ)
1231 log_debug(LD_CIRC, "one on the way!");
1232 if (!circ) {
1233 extend_info_t *extend_info=NULL;
1234 uint8_t new_circ_purpose;
1236 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1237 /* need to pick an intro point */
1238 tor_assert(conn->rend_data);
1239 extend_info = rend_client_get_random_intro(conn->rend_data);
1240 if (!extend_info) {
1241 log_info(LD_REND,
1242 "No intro points for '%s': re-fetching service descriptor.",
1243 safe_str_client(conn->rend_data->onion_address));
1244 rend_client_refetch_v2_renddesc(conn->rend_data);
1245 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1246 return 0;
1248 log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
1249 extend_info->nickname,
1250 safe_str_client(conn->rend_data->onion_address));
1253 /* If we have specified a particular exit node for our
1254 * connection, then be sure to open a circuit to that exit node.
1256 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1257 if (conn->chosen_exit_name) {
1258 routerinfo_t *r;
1259 int opt = conn->chosen_exit_optional;
1260 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1261 if (r) {
1262 extend_info = extend_info_from_router(r);
1263 } else {
1264 log_debug(LD_DIR, "considering %d, %s",
1265 want_onehop, conn->chosen_exit_name);
1266 if (want_onehop && conn->chosen_exit_name[0] == '$') {
1267 /* We're asking for a one-hop circuit to a router that
1268 * we don't have a routerinfo about. Make up an extend_info. */
1269 char digest[DIGEST_LEN];
1270 char *hexdigest = conn->chosen_exit_name+1;
1271 tor_addr_t addr;
1272 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
1273 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
1274 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
1275 return -1;
1277 if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
1278 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
1279 escaped_safe_str_client(conn->socks_request->address));
1280 return -1;
1282 extend_info = extend_info_alloc(conn->chosen_exit_name+1,
1283 digest, NULL, &addr,
1284 conn->socks_request->port);
1285 } else {
1286 /* We will need an onion key for the router, and we
1287 * don't have one. Refuse or relax requirements. */
1288 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1289 "Requested exit point '%s' is not known. %s.",
1290 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1291 if (opt) {
1292 conn->chosen_exit_optional = 0;
1293 tor_free(conn->chosen_exit_name);
1294 /* Try again with no requested exit */
1295 return circuit_get_open_circ_or_launch(conn,
1296 desired_circuit_purpose,
1297 circp);
1299 return -1;
1305 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
1306 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
1307 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1308 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
1309 else
1310 new_circ_purpose = desired_circuit_purpose;
1313 int flags = CIRCLAUNCH_NEED_CAPACITY;
1314 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
1315 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1316 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
1317 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
1318 flags);
1321 extend_info_free(extend_info);
1323 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
1324 /* help predict this next time */
1325 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1326 if (circ) {
1327 /* write the service_id into circ */
1328 circ->rend_data = rend_data_dup(conn->rend_data);
1329 if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1330 circ->_base.state == CIRCUIT_STATE_OPEN)
1331 rend_client_rendcirc_has_opened(circ);
1335 if (!circ)
1336 log_info(LD_APP,
1337 "No safe circuit (purpose %d) ready for edge "
1338 "connection; delaying.",
1339 desired_circuit_purpose);
1340 *circp = circ;
1341 return 0;
1344 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1345 * <b>circ</b>. */
1346 static int
1347 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
1349 crypt_path_t *cpath, *cpath_next = NULL;
1350 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1351 cpath_next = cpath->next;
1352 if (crypt_path == cpath)
1353 return 1;
1355 return 0;
1358 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1359 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1360 * hop in circ's cpath if <b>cpath</b> is NULL.
1362 static void
1363 link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
1364 crypt_path_t *cpath)
1366 /* add it into the linked list of streams on this circuit */
1367 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
1368 circ->_base.n_circ_id);
1369 /* reset it, so we can measure circ timeouts */
1370 apconn->_base.timestamp_lastread = time(NULL);
1371 apconn->next_stream = circ->p_streams;
1372 apconn->on_circuit = TO_CIRCUIT(circ);
1373 /* assert_connection_ok(conn, time(NULL)); */
1374 circ->p_streams = apconn;
1376 if (cpath) { /* we were given one; use it */
1377 tor_assert(cpath_is_on_circuit(circ, cpath));
1378 apconn->cpath_layer = cpath;
1379 } else { /* use the last hop in the circuit */
1380 tor_assert(circ->cpath);
1381 tor_assert(circ->cpath->prev);
1382 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1383 apconn->cpath_layer = circ->cpath->prev;
1387 /** If an exit wasn't specifically chosen, save the history for future
1388 * use. */
1389 static void
1390 consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
1392 int found_needle = 0;
1393 or_options_t *options = get_options();
1394 size_t len;
1395 char *new_address;
1396 char fp[HEX_DIGEST_LEN+1];
1398 /* Search the addressmap for this conn's destination. */
1399 /* If he's not in the address map.. */
1400 if (!options->TrackHostExits ||
1401 addressmap_have_mapping(conn->socks_request->address,
1402 options->TrackHostExitsExpire))
1403 return; /* nothing to track, or already mapped */
1405 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1406 if (cp[0] == '.') { /* match end */
1407 if (cp[1] == '\0' ||
1408 !strcasecmpend(conn->socks_request->address, cp) ||
1409 !strcasecmp(conn->socks_request->address, &cp[1]))
1410 found_needle = 1;
1411 } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
1412 found_needle = 1;
1416 if (!found_needle || !circ->build_state->chosen_exit)
1417 return;
1419 /* write down the fingerprint of the chosen exit, not the nickname,
1420 * because the chosen exit might not be named. */
1421 base16_encode(fp, sizeof(fp),
1422 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
1424 /* Add this exit/hostname pair to the addressmap. */
1425 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1426 strlen(fp) + 1 /* '.' */ +
1427 strlen("exit") + 1 /* '\0' */;
1428 new_address = tor_malloc(len);
1430 tor_snprintf(new_address, len, "%s.%s.exit",
1431 conn->socks_request->address, fp);
1433 addressmap_register(conn->socks_request->address, new_address,
1434 time(NULL) + options->TrackHostExitsExpire,
1435 ADDRMAPSRC_TRACKEXIT);
1438 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1439 * begin or resolve cell as appropriate. Return values are as for
1440 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1441 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1442 * <b>cpath</b> is NULL. */
1444 connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
1445 origin_circuit_t *circ,
1446 crypt_path_t *cpath)
1448 tor_assert(conn);
1449 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
1450 conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
1451 tor_assert(conn->socks_request);
1452 tor_assert(circ);
1453 tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
1455 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1457 if (!circ->_base.timestamp_dirty)
1458 circ->_base.timestamp_dirty = time(NULL);
1460 link_apconn_to_circ(conn, circ, cpath);
1461 tor_assert(conn->socks_request);
1462 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
1463 if (!conn->use_begindir)
1464 consider_recording_trackhost(conn, circ);
1465 if (connection_ap_handshake_send_begin(conn) < 0)
1466 return -1;
1467 } else {
1468 if (connection_ap_handshake_send_resolve(conn) < 0)
1469 return -1;
1472 return 1;
1475 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1476 * we don't find one: if conn cannot be handled by any known nodes,
1477 * warn and return -1 (conn needs to die, and is maybe already marked);
1478 * else launch new circuit (if necessary) and return 0.
1479 * Otherwise, associate conn with a safe live circuit, do the
1480 * right next step, and return 1.
1482 /* XXXX this function should mark for close whenever it returns -1;
1483 * its callers shouldn't have to worry about that. */
1485 connection_ap_handshake_attach_circuit(edge_connection_t *conn)
1487 int retval;
1488 int conn_age;
1489 int want_onehop;
1491 tor_assert(conn);
1492 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1493 tor_assert(conn->socks_request);
1494 want_onehop = conn->want_onehop;
1496 conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
1498 if (conn_age >= get_options()->SocksTimeout) {
1499 int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
1500 LOG_INFO : LOG_NOTICE;
1501 log_fn(severity, LD_APP,
1502 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1503 conn_age, safe_str_client(conn->socks_request->address),
1504 conn->socks_request->port);
1505 return -1;
1508 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1509 origin_circuit_t *circ=NULL;
1511 if (conn->chosen_exit_name) {
1512 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1513 int opt = conn->chosen_exit_optional;
1514 if (!router && !want_onehop) {
1515 /* We ran into this warning when trying to extend a circuit to a
1516 * hidden service directory for which we didn't have a router
1517 * descriptor. See flyspray task 767 for more details. We should
1518 * keep this in mind when deciding to use BEGIN_DIR cells for other
1519 * directory requests as well. -KL*/
1520 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1521 "Requested exit point '%s' is not known. %s.",
1522 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1523 if (opt) {
1524 conn->chosen_exit_optional = 0;
1525 tor_free(conn->chosen_exit_name);
1526 return 0;
1528 return -1;
1530 if (router && !connection_ap_can_use_exit(conn, router, 0)) {
1531 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1532 "Requested exit point '%s' would refuse request. %s.",
1533 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1534 if (opt) {
1535 conn->chosen_exit_optional = 0;
1536 tor_free(conn->chosen_exit_name);
1537 return 0;
1539 return -1;
1543 /* find the circuit that we should use, if there is one. */
1544 retval = circuit_get_open_circ_or_launch(
1545 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1546 if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
1547 return retval;
1549 log_debug(LD_APP|LD_CIRC,
1550 "Attaching apconn to circ %d (stream %d sec old).",
1551 circ->_base.n_circ_id, conn_age);
1552 /* print the circ's path, so people can figure out which circs are
1553 * sucking. */
1554 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1556 /* We have found a suitable circuit for our conn. Hurray. */
1557 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
1559 } else { /* we're a rendezvous conn */
1560 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
1562 tor_assert(!conn->cpath_layer);
1564 /* start by finding a rendezvous circuit for us */
1566 retval = circuit_get_open_circ_or_launch(
1567 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1568 if (retval < 0) return -1; /* failed */
1570 if (retval > 0) {
1571 tor_assert(rendcirc);
1572 /* one is already established, attach */
1573 log_info(LD_REND,
1574 "rend joined circ %d already here. attaching. "
1575 "(stream %d sec old)",
1576 rendcirc->_base.n_circ_id, conn_age);
1577 /* Mark rendezvous circuits as 'newly dirty' every time you use
1578 * them, since the process of rebuilding a rendezvous circ is so
1579 * expensive. There is a tradeoff between linkability and
1580 * feasibility, at this point.
1582 rendcirc->_base.timestamp_dirty = time(NULL);
1583 link_apconn_to_circ(conn, rendcirc, NULL);
1584 if (connection_ap_handshake_send_begin(conn) < 0)
1585 return 0; /* already marked, let them fade away */
1586 return 1;
1589 if (rendcirc && (rendcirc->_base.purpose ==
1590 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
1591 log_info(LD_REND,
1592 "pending-join circ %d already here, with intro ack. "
1593 "Stalling. (stream %d sec old)",
1594 rendcirc->_base.n_circ_id, conn_age);
1595 return 0;
1598 /* it's on its way. find an intro circ. */
1599 retval = circuit_get_open_circ_or_launch(
1600 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1601 if (retval < 0) return -1; /* failed */
1603 if (retval > 0) {
1604 /* one has already sent the intro. keep waiting. */
1605 circuit_t *c = NULL;
1606 tor_assert(introcirc);
1607 log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
1608 "Stalling. (stream %d sec old)",
1609 introcirc->_base.n_circ_id,
1610 rendcirc ? rendcirc->_base.n_circ_id : 0,
1611 conn_age);
1612 /* abort parallel intro circs, if any */
1613 for (c = global_circuitlist; c; c = c->next) {
1614 if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
1615 !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
1616 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
1617 if (oc->rend_data &&
1618 !rend_cmp_service_ids(conn->rend_data->onion_address,
1619 oc->rend_data->onion_address)) {
1620 log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
1621 "built in parallel.");
1622 circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
1626 return 0;
1629 /* now rendcirc and introcirc are each either undefined or not finished */
1631 if (rendcirc && introcirc &&
1632 rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1633 log_info(LD_REND,
1634 "ready rend circ %d already here (no intro-ack yet on "
1635 "intro %d). (stream %d sec old)",
1636 rendcirc->_base.n_circ_id,
1637 introcirc->_base.n_circ_id, conn_age);
1639 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1640 if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
1641 log_info(LD_REND,"found open intro circ %d (rend %d); sending "
1642 "introduction. (stream %d sec old)",
1643 introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
1644 conn_age);
1645 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1646 return -1;
1648 rendcirc->_base.timestamp_dirty = time(NULL);
1649 introcirc->_base.timestamp_dirty = time(NULL);
1650 assert_circuit_ok(TO_CIRCUIT(rendcirc));
1651 assert_circuit_ok(TO_CIRCUIT(introcirc));
1652 return 0;
1656 log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
1657 "Stalling conn. (%d sec old)",
1658 introcirc ? introcirc->_base.n_circ_id : 0,
1659 rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
1660 return 0;