Merge branch 'safelogging2'
[tor.git] / src / or / circuituse.c
blob145aefe9844b3a937a01d55645f46fa9fe4f33f4
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-2009, 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(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)) {
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 introcirc_cutoff = begindir_cutoff;
274 cpath_build_state_t *build_state;
276 while (next_circ) {
277 time_t cutoff;
278 victim = next_circ;
279 next_circ = next_circ->next;
280 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
281 victim->marked_for_close) /* don't mess with marked circs */
282 continue;
284 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
285 if (build_state && build_state->onehop_tunnel)
286 cutoff = begindir_cutoff;
287 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
288 cutoff = introcirc_cutoff;
289 else
290 cutoff = general_cutoff;
291 if (victim->timestamp_created > cutoff)
292 continue; /* it's still young, leave it alone */
294 #if 0
295 /* some debug logs, to help track bugs */
296 if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
297 victim->timestamp_created <= introcirc_cutoff &&
298 victim->timestamp_created > general_cutoff)
299 log_info(LD_REND|LD_CIRC, "Timing out introduction circuit which we "
300 "would not have done if it had been a general circuit.");
302 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
303 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
304 if (!victim->timestamp_dirty)
305 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
306 "(clean).",
307 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
308 victim->purpose, victim->build_state->chosen_exit_name,
309 victim->n_circ_id);
310 else
311 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
312 "%d secs since dirty.",
313 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
314 victim->purpose, victim->build_state->chosen_exit_name,
315 victim->n_circ_id,
316 (int)(now - victim->timestamp_dirty));
318 #endif
320 /* if circ is !open, or if it's open but purpose is a non-finished
321 * intro or rend, then mark it for close */
322 if (victim->state == CIRCUIT_STATE_OPEN) {
323 switch (victim->purpose) {
324 default: /* most open circuits can be left alone. */
325 continue; /* yes, continue inside a switch refers to the nearest
326 * enclosing loop. C is smart. */
327 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
328 case CIRCUIT_PURPOSE_C_INTRODUCING:
329 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
330 break; /* too old, need to die */
331 case CIRCUIT_PURPOSE_C_REND_READY:
332 /* it's a rend_ready circ -- has it already picked a query? */
333 /* c_rend_ready circs measure age since timestamp_dirty,
334 * because that's set when they switch purposes
336 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
337 victim->timestamp_dirty > cutoff)
338 continue;
339 break;
340 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
341 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
342 /* rend and intro circs become dirty each time they
343 * make an introduction attempt. so timestamp_dirty
344 * will reflect the time since the last attempt.
346 if (victim->timestamp_dirty > cutoff)
347 continue;
348 break;
350 } else { /* circuit not open, consider recording failure as timeout */
351 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
352 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
353 if (circuit_build_times_add_timeout(&circ_times, first_hop_succeeded,
354 victim->timestamp_created))
355 circuit_build_times_set_timeout(&circ_times);
358 if (victim->n_conn)
359 log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
360 victim->n_conn->_base.address, victim->n_conn->_base.port,
361 victim->n_circ_id,
362 victim->state, circuit_state_to_string(victim->state),
363 victim->purpose);
364 else
365 log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
366 victim->n_circ_id, victim->state,
367 circuit_state_to_string(victim->state), victim->purpose);
369 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
370 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
374 /** Remove any elements in <b>needed_ports</b> that are handled by an
375 * open or in-progress circuit.
377 void
378 circuit_remove_handled_ports(smartlist_t *needed_ports)
380 int i;
381 uint16_t *port;
383 for (i = 0; i < smartlist_len(needed_ports); ++i) {
384 port = smartlist_get(needed_ports, i);
385 tor_assert(*port);
386 if (circuit_stream_is_being_handled(NULL, *port,
387 MIN_CIRCUITS_HANDLING_STREAM)) {
388 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
389 smartlist_del(needed_ports, i--);
390 tor_free(port);
391 } else {
392 log_debug(LD_CIRC,"Port %d is not handled.", *port);
397 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
398 * will have an acceptable exit node for exit stream <b>conn</b> if it
399 * is defined, else for "*:port".
400 * Else return 0.
403 circuit_stream_is_being_handled(edge_connection_t *conn,
404 uint16_t port, int min)
406 circuit_t *circ;
407 routerinfo_t *exitrouter;
408 int num=0;
409 time_t now = time(NULL);
410 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
411 conn ? conn->socks_request->port : port);
413 for (circ=global_circuitlist;circ;circ = circ->next) {
414 if (CIRCUIT_IS_ORIGIN(circ) &&
415 !circ->marked_for_close &&
416 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
417 (!circ->timestamp_dirty ||
418 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
419 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
420 if (build_state->is_internal || build_state->onehop_tunnel)
421 continue;
423 exitrouter = build_state_get_exit_router(build_state);
424 if (exitrouter && (!need_uptime || build_state->need_uptime)) {
425 int ok;
426 if (conn) {
427 ok = connection_ap_can_use_exit(conn, exitrouter);
428 } else {
429 addr_policy_result_t r = compare_addr_to_addr_policy(
430 0, port, exitrouter->exit_policy);
431 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
433 if (ok) {
434 if (++num >= min)
435 return 1;
440 return 0;
443 /** Don't keep more than this many unused open circuits around. */
444 #define MAX_UNUSED_OPEN_CIRCUITS 14
446 /** Figure out how many circuits we have open that are clean. Make
447 * sure it's enough for all the upcoming behaviors we predict we'll have.
448 * But put an upper bound on the total number of circuits.
450 static void
451 circuit_predict_and_launch_new(void)
453 circuit_t *circ;
454 int num=0, num_internal=0, num_uptime_internal=0;
455 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
456 int port_needs_uptime=0, port_needs_capacity=1;
457 time_t now = time(NULL);
458 int flags = 0;
460 /* First, count how many of each type of circuit we have already. */
461 for (circ=global_circuitlist;circ;circ = circ->next) {
462 cpath_build_state_t *build_state;
463 if (!CIRCUIT_IS_ORIGIN(circ))
464 continue;
465 if (circ->marked_for_close)
466 continue; /* don't mess with marked circs */
467 if (circ->timestamp_dirty)
468 continue; /* only count clean circs */
469 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
470 continue; /* only pay attention to general-purpose circs */
471 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
472 if (build_state->onehop_tunnel)
473 continue;
474 num++;
475 if (build_state->is_internal)
476 num_internal++;
477 if (build_state->need_uptime && build_state->is_internal)
478 num_uptime_internal++;
481 /* If that's enough, then stop now. */
482 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
483 return; /* we already have many, making more probably will hurt */
485 /* Second, see if we need any more exit circuits. */
486 /* check if we know of a port that's been requested recently
487 * and no circuit is currently available that can handle it. */
488 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
489 &port_needs_capacity)) {
490 if (port_needs_uptime)
491 flags |= CIRCLAUNCH_NEED_UPTIME;
492 if (port_needs_capacity)
493 flags |= CIRCLAUNCH_NEED_CAPACITY;
494 log_info(LD_CIRC,
495 "Have %d clean circs (%d internal), need another exit circ.",
496 num, num_internal);
497 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
498 return;
501 /* Third, see if we need any more hidden service (server) circuits. */
502 if (num_rend_services() && num_uptime_internal < 3) {
503 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
504 CIRCLAUNCH_IS_INTERNAL);
505 log_info(LD_CIRC,
506 "Have %d clean circs (%d internal), need another internal "
507 "circ for my hidden service.",
508 num, num_internal);
509 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
510 return;
513 /* Fourth, see if we need any more hidden service (client) circuits. */
514 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
515 &hidserv_needs_capacity) &&
516 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
517 num_internal<2)) {
518 if (hidserv_needs_uptime)
519 flags |= CIRCLAUNCH_NEED_UPTIME;
520 if (hidserv_needs_capacity)
521 flags |= CIRCLAUNCH_NEED_CAPACITY;
522 flags |= CIRCLAUNCH_IS_INTERNAL;
523 log_info(LD_CIRC,
524 "Have %d clean circs (%d uptime-internal, %d internal), need"
525 " another hidden service circ.",
526 num, num_uptime_internal, num_internal);
527 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
528 return;
531 /* Finally, check to see if we still need more circuits to learn
532 * a good build timeout. But if we're close to our max number we
533 * want, don't do another -- we want to leave a few slots open so
534 * we can still build circuits preemptively as needed. */
535 if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
536 circuit_build_times_needs_circuits_now(&circ_times)) {
537 flags = CIRCLAUNCH_NEED_CAPACITY;
538 log_info(LD_CIRC,
539 "Have %d clean circs need another buildtime test circ.", num);
540 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
541 return;
545 /** Build a new test circuit every 5 minutes */
546 #define TESTING_CIRCUIT_INTERVAL 300
548 /** This function is called once a second, if router_have_min_dir_info() is
549 * true. Its job is to make sure all services we offer have enough circuits
550 * available. Some services just want enough circuits for current tasks,
551 * whereas others want a minimum set of idle circuits hanging around.
553 void
554 circuit_build_needed_circs(time_t now)
556 static time_t time_to_new_circuit = 0;
557 or_options_t *options = get_options();
559 /* launch a new circ for any pending streams that need one */
560 connection_ap_attach_pending();
562 /* make sure any hidden services have enough intro points */
563 rend_services_introduce();
565 if (time_to_new_circuit < now) {
566 circuit_reset_failure_count(1);
567 time_to_new_circuit = now + options->NewCircuitPeriod;
568 if (proxy_mode(get_options()))
569 addressmap_clean(now);
570 circuit_expire_old_circuits(now);
572 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
573 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
574 if (get_options()->RunTesting &&
575 circ &&
576 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
577 log_fn(LOG_INFO,"Creating a new testing circuit.");
578 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0);
580 #endif
582 if (!options->DisablePredictedCircuits)
583 circuit_predict_and_launch_new();
586 /** If the stream <b>conn</b> is a member of any of the linked
587 * lists of <b>circ</b>, then remove it from the list.
589 void
590 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
592 edge_connection_t *prevconn;
594 tor_assert(circ);
595 tor_assert(conn);
597 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
598 conn->on_circuit = NULL;
600 if (CIRCUIT_IS_ORIGIN(circ)) {
601 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
602 if (conn == origin_circ->p_streams) {
603 origin_circ->p_streams = conn->next_stream;
604 return;
607 for (prevconn = origin_circ->p_streams;
608 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
609 prevconn = prevconn->next_stream)
611 if (prevconn && prevconn->next_stream) {
612 prevconn->next_stream = conn->next_stream;
613 return;
615 } else {
616 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
617 if (conn == or_circ->n_streams) {
618 or_circ->n_streams = conn->next_stream;
619 return;
621 if (conn == or_circ->resolving_streams) {
622 or_circ->resolving_streams = conn->next_stream;
623 return;
626 for (prevconn = or_circ->n_streams;
627 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
628 prevconn = prevconn->next_stream)
630 if (prevconn && prevconn->next_stream) {
631 prevconn->next_stream = conn->next_stream;
632 return;
635 for (prevconn = or_circ->resolving_streams;
636 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
637 prevconn = prevconn->next_stream)
639 if (prevconn && prevconn->next_stream) {
640 prevconn->next_stream = conn->next_stream;
641 return;
645 log_warn(LD_BUG,"Edge connection not in circuit's list.");
646 /* Don't give an error here; it's harmless. */
647 tor_fragile_assert();
650 /** If we haven't yet decided on a good timeout value for circuit
651 * building, we close idles circuits aggressively so we can get more
652 * data points. */
653 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
655 /** Find each circuit that has been unused for too long, or dirty
656 * for too long and has no streams on it: mark it for close.
658 static void
659 circuit_expire_old_circuits(time_t now)
661 circuit_t *circ;
662 time_t cutoff;
664 if (circuit_build_times_needs_circuits(&circ_times)) {
665 /* Circuits should be shorter lived if we need more of them
666 * for learning a good build timeout */
667 cutoff = now - IDLE_TIMEOUT_WHILE_LEARNING;
668 } else {
669 cutoff = now - get_options()->CircuitIdleTimeout;
672 for (circ = global_circuitlist; circ; circ = circ->next) {
673 if (circ->marked_for_close || ! CIRCUIT_IS_ORIGIN(circ))
674 continue;
675 /* If the circuit has been dirty for too long, and there are no streams
676 * on it, mark it for close.
678 if (circ->timestamp_dirty &&
679 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
680 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
681 log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, "
682 "purpose %d)",
683 circ->n_circ_id, (int)(now - circ->timestamp_dirty),
684 circ->purpose);
685 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
686 } else if (!circ->timestamp_dirty &&
687 circ->state == CIRCUIT_STATE_OPEN &&
688 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
689 if (circ->timestamp_created < cutoff) {
690 log_debug(LD_CIRC,
691 "Closing circuit that has been unused for %d seconds.",
692 (int)(now - circ->timestamp_created));
693 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
699 /** Number of testing circuits we want open before testing our bandwidth. */
700 #define NUM_PARALLEL_TESTING_CIRCS 4
702 /** True iff we've ever had enough testing circuits open to test our
703 * bandwidth. */
704 static int have_performed_bandwidth_test = 0;
706 /** Reset have_performed_bandwidth_test, so we'll start building
707 * testing circuits again so we can exercise our bandwidth. */
708 void
709 reset_bandwidth_test(void)
711 have_performed_bandwidth_test = 0;
714 /** Return 1 if we've already exercised our bandwidth, or if we
715 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
716 * established or on the way. Else return 0.
719 circuit_enough_testing_circs(void)
721 circuit_t *circ;
722 int num = 0;
724 if (have_performed_bandwidth_test)
725 return 1;
727 for (circ = global_circuitlist; circ; circ = circ->next) {
728 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
729 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
730 circ->state == CIRCUIT_STATE_OPEN)
731 num++;
733 return num >= NUM_PARALLEL_TESTING_CIRCS;
736 /** A testing circuit has completed. Take whatever stats we want.
737 * Noticing reachability is taken care of in onionskin_answer(),
738 * so there's no need to record anything here. But if we still want
739 * to do the bandwidth test, and we now have enough testing circuits
740 * open, do it.
742 static void
743 circuit_testing_opened(origin_circuit_t *circ)
745 if (have_performed_bandwidth_test ||
746 !check_whether_orport_reachable()) {
747 /* either we've already done everything we want with testing circuits,
748 * or this testing circuit became open due to a fluke, e.g. we picked
749 * a last hop where we already had the connection open due to an
750 * outgoing local circuit. */
751 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
752 } else if (circuit_enough_testing_circs()) {
753 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
754 have_performed_bandwidth_test = 1;
755 } else
756 consider_testing_reachability(1, 0);
759 /** A testing circuit has failed to build. Take whatever stats we want. */
760 static void
761 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
763 if (server_mode(get_options()) && check_whether_orport_reachable())
764 return;
766 log_info(LD_GENERAL,
767 "Our testing circuit (to see if your ORPort is reachable) "
768 "has failed. I'll try again later.");
770 /* These aren't used yet. */
771 (void)circ;
772 (void)at_last_hop;
775 /** The circuit <b>circ</b> has just become open. Take the next
776 * step: for rendezvous circuits, we pass circ to the appropriate
777 * function in rendclient or rendservice. For general circuits, we
778 * call connection_ap_attach_pending, which looks for pending streams
779 * that could use circ.
781 void
782 circuit_has_opened(origin_circuit_t *circ)
784 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
786 switch (TO_CIRCUIT(circ)->purpose) {
787 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
788 rend_client_rendcirc_has_opened(circ);
789 connection_ap_attach_pending();
790 break;
791 case CIRCUIT_PURPOSE_C_INTRODUCING:
792 rend_client_introcirc_has_opened(circ);
793 break;
794 case CIRCUIT_PURPOSE_C_GENERAL:
795 /* Tell any AP connections that have been waiting for a new
796 * circuit that one is ready. */
797 connection_ap_attach_pending();
798 break;
799 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
800 /* at Bob, waiting for introductions */
801 rend_service_intro_has_opened(circ);
802 break;
803 case CIRCUIT_PURPOSE_S_CONNECT_REND:
804 /* at Bob, connecting to rend point */
805 rend_service_rendezvous_has_opened(circ);
806 break;
807 case CIRCUIT_PURPOSE_TESTING:
808 circuit_testing_opened(circ);
809 break;
810 /* default:
811 * This won't happen in normal operation, but might happen if the
812 * controller did it. Just let it slide. */
816 /** Called whenever a circuit could not be successfully built.
818 void
819 circuit_build_failed(origin_circuit_t *circ)
821 /* we should examine circ and see if it failed because of
822 * the last hop or an earlier hop. then use this info below.
824 int failed_at_last_hop = 0;
825 /* If the last hop isn't open, and the second-to-last is, we failed
826 * at the last hop. */
827 if (circ->cpath &&
828 circ->cpath->prev->state != CPATH_STATE_OPEN &&
829 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
830 failed_at_last_hop = 1;
832 if (circ->cpath &&
833 circ->cpath->state != CPATH_STATE_OPEN) {
834 /* We failed at the first hop. If there's an OR connection
835 * to blame, blame it. Also, avoid this relay for a while, and
836 * fail any one-hop directory fetches destined for it. */
837 const char *n_conn_id = circ->cpath->extend_info->identity_digest;
838 if (circ->_base.n_conn) {
839 or_connection_t *n_conn = circ->_base.n_conn;
840 log_info(LD_OR,
841 "Our circuit failed to get a response from the first hop "
842 "(%s:%d). I'm going to try to rotate to a better connection.",
843 n_conn->_base.address, n_conn->_base.port);
844 n_conn->is_bad_for_new_circs = 1;
845 } else {
846 log_info(LD_OR,
847 "Our circuit died before the first hop with no connection");
849 if (n_conn_id) {
850 entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
851 /* if there are any one-hop streams waiting on this circuit, fail
852 * them now so they can retry elsewhere. */
853 connection_ap_fail_onehop(n_conn_id, circ->build_state);
857 switch (circ->_base.purpose) {
858 case CIRCUIT_PURPOSE_C_GENERAL:
859 /* If we never built the circuit, note it as a failure. */
860 circuit_increment_failure_count();
861 if (failed_at_last_hop) {
862 /* Make sure any streams that demand our last hop as their exit
863 * know that it's unlikely to happen. */
864 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
866 break;
867 case CIRCUIT_PURPOSE_TESTING:
868 circuit_testing_failed(circ, failed_at_last_hop);
869 break;
870 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
871 /* at Bob, waiting for introductions */
872 if (circ->_base.state != CIRCUIT_STATE_OPEN) {
873 circuit_increment_failure_count();
875 /* no need to care here, because bob will rebuild intro
876 * points periodically. */
877 break;
878 case CIRCUIT_PURPOSE_C_INTRODUCING:
879 /* at Alice, connecting to intro point */
880 /* Don't increment failure count, since Bob may have picked
881 * the introduction point maliciously */
882 /* Alice will pick a new intro point when this one dies, if
883 * the stream in question still cares. No need to act here. */
884 break;
885 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
886 /* at Alice, waiting for Bob */
887 circuit_increment_failure_count();
888 /* Alice will pick a new rend point when this one dies, if
889 * the stream in question still cares. No need to act here. */
890 break;
891 case CIRCUIT_PURPOSE_S_CONNECT_REND:
892 /* at Bob, connecting to rend point */
893 /* Don't increment failure count, since Alice may have picked
894 * the rendezvous point maliciously */
895 log_info(LD_REND,
896 "Couldn't connect to Alice's chosen rend point %s "
897 "(%s hop failed).",
898 escaped(build_state_get_exit_nickname(circ->build_state)),
899 failed_at_last_hop?"last":"non-last");
900 rend_service_relaunch_rendezvous(circ);
901 break;
902 /* default:
903 * This won't happen in normal operation, but might happen if the
904 * controller did it. Just let it slide. */
908 /** Number of consecutive failures so far; should only be touched by
909 * circuit_launch_new and circuit_*_failure_count.
911 static int n_circuit_failures = 0;
912 /** Before the last time we called circuit_reset_failure_count(), were
913 * there a lot of failures? */
914 static int did_circs_fail_last_period = 0;
916 /** Don't retry launching a new circuit if we try this many times with no
917 * success. */
918 #define MAX_CIRCUIT_FAILURES 5
920 /** Launch a new circuit; see circuit_launch_by_extend_info() for
921 * details on arguments. */
922 origin_circuit_t *
923 circuit_launch_by_router(uint8_t purpose,
924 routerinfo_t *exit, int flags)
926 origin_circuit_t *circ;
927 extend_info_t *info = NULL;
928 if (exit)
929 info = extend_info_from_router(exit);
930 circ = circuit_launch_by_extend_info(purpose, info, flags);
932 extend_info_free(info);
933 return circ;
936 /** Launch a new circuit with purpose <b>purpose</b> and exit node
937 * <b>extend_info</b> (or NULL to select a random exit node). If flags
938 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
939 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
940 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
941 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
942 * Return the newly allocated circuit on success, or NULL on failure. */
943 origin_circuit_t *
944 circuit_launch_by_extend_info(uint8_t purpose,
945 extend_info_t *extend_info,
946 int flags)
948 origin_circuit_t *circ;
949 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
951 if (!onehop_tunnel && !router_have_minimum_dir_info()) {
952 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
953 "circuit launch.");
954 return NULL;
957 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
958 purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
959 /* see if there are appropriate circs available to cannibalize. */
960 /* XXX if we're planning to add a hop, perhaps we want to look for
961 * internal circs rather than exit circs? -RD */
962 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
963 if (circ) {
964 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
965 build_state_get_exit_nickname(circ->build_state), purpose);
966 circ->_base.purpose = purpose;
967 /* reset the birth date of this circ, else expire_building
968 * will see it and think it's been trying to build since it
969 * began. */
970 circ->_base.timestamp_created = time(NULL);
971 switch (purpose) {
972 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
973 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
974 /* it's ready right now */
975 break;
976 case CIRCUIT_PURPOSE_C_INTRODUCING:
977 case CIRCUIT_PURPOSE_S_CONNECT_REND:
978 case CIRCUIT_PURPOSE_C_GENERAL:
979 /* need to add a new hop */
980 tor_assert(extend_info);
981 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
982 return NULL;
983 break;
984 default:
985 log_warn(LD_BUG,
986 "unexpected purpose %d when cannibalizing a circ.",
987 purpose);
988 tor_fragile_assert();
989 return NULL;
991 return circ;
995 if (did_circs_fail_last_period &&
996 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
997 /* too many failed circs in a row. don't try. */
998 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
999 return NULL;
1002 /* try a circ. if it fails, circuit_mark_for_close will increment
1003 * n_circuit_failures */
1004 return circuit_establish_circuit(purpose, extend_info, flags);
1007 /** Record another failure at opening a general circuit. When we have
1008 * too many, we'll stop trying for the remainder of this minute.
1010 static void
1011 circuit_increment_failure_count(void)
1013 ++n_circuit_failures;
1014 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
1017 /** Reset the failure count for opening general circuits. This means
1018 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1019 * stopping again.
1021 void
1022 circuit_reset_failure_count(int timeout)
1024 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
1025 did_circs_fail_last_period = 1;
1026 else
1027 did_circs_fail_last_period = 0;
1028 n_circuit_failures = 0;
1031 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1032 * there isn't one, and there isn't one on the way, launch one and return
1033 * 0. If it will never work, return -1.
1035 * Write the found or in-progress or launched circ into *circp.
1037 static int
1038 circuit_get_open_circ_or_launch(edge_connection_t *conn,
1039 uint8_t desired_circuit_purpose,
1040 origin_circuit_t **circp)
1042 origin_circuit_t *circ;
1043 int check_exit_policy;
1044 int need_uptime, need_internal;
1045 int want_onehop;
1046 or_options_t *options = get_options();
1048 tor_assert(conn);
1049 tor_assert(circp);
1050 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1051 check_exit_policy =
1052 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
1053 !conn->use_begindir &&
1054 !connection_edge_is_rendezvous_stream(conn);
1055 want_onehop = conn->want_onehop;
1057 need_uptime = !conn->want_onehop && !conn->use_begindir &&
1058 smartlist_string_num_isin(options->LongLivedPorts,
1059 conn->socks_request->port);
1060 need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
1062 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
1063 need_uptime, need_internal);
1065 if (circ) {
1066 *circp = circ;
1067 return 1; /* we're happy */
1070 if (!want_onehop && !router_have_minimum_dir_info()) {
1071 if (!connection_get_by_type(CONN_TYPE_DIR)) {
1072 int severity = LOG_NOTICE;
1073 /* FFFF if this is a tunneled directory fetch, don't yell
1074 * as loudly. the user doesn't even know it's happening. */
1075 if (options->UseBridges && bridges_known_but_down()) {
1076 log_fn(severity, LD_APP|LD_DIR,
1077 "Application request when we're believed to be "
1078 "offline. Optimistically trying known bridges again.");
1079 bridges_retry_all();
1080 } else if (!options->UseBridges || any_bridge_descriptors_known()) {
1081 log_fn(severity, LD_APP|LD_DIR,
1082 "Application request when we're believed to be "
1083 "offline. Optimistically trying directory fetches again.");
1084 routerlist_retry_directory_downloads(time(NULL));
1087 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1088 * 1, or when all directory attempts fail and directory_all_unreachable()
1089 * kills it.
1091 return 0;
1094 /* Do we need to check exit policy? */
1095 if (check_exit_policy) {
1096 if (!conn->chosen_exit_name) {
1097 struct in_addr in;
1098 uint32_t addr = 0;
1099 if (tor_inet_aton(conn->socks_request->address, &in))
1100 addr = ntohl(in.s_addr);
1101 if (router_exit_policy_all_routers_reject(addr,
1102 conn->socks_request->port,
1103 need_uptime)) {
1104 log_notice(LD_APP,
1105 "No Tor server allows exit to %s:%d. Rejecting.",
1106 safe_str_client(conn->socks_request->address),
1107 conn->socks_request->port);
1108 return -1;
1110 } else {
1111 /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
1112 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1113 int opt = conn->chosen_exit_optional;
1114 if (router && !connection_ap_can_use_exit(conn, router)) {
1115 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1116 "Requested exit point '%s' would refuse request. %s.",
1117 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1118 if (opt) {
1119 conn->chosen_exit_optional = 0;
1120 tor_free(conn->chosen_exit_name);
1121 /* Try again. */
1122 return circuit_get_open_circ_or_launch(conn,
1123 desired_circuit_purpose,
1124 circp);
1126 return -1;
1131 /* is one already on the way? */
1132 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
1133 need_uptime, need_internal);
1134 if (circ)
1135 log_debug(LD_CIRC, "one on the way!");
1136 if (!circ) {
1137 extend_info_t *extend_info=NULL;
1138 uint8_t new_circ_purpose;
1140 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1141 /* need to pick an intro point */
1142 tor_assert(conn->rend_data);
1143 extend_info = rend_client_get_random_intro(conn->rend_data);
1144 if (!extend_info) {
1145 log_info(LD_REND,
1146 "No intro points for '%s': re-fetching service descriptor.",
1147 safe_str_client(conn->rend_data->onion_address));
1148 rend_client_refetch_v2_renddesc(conn->rend_data);
1149 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1150 return 0;
1152 log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
1153 extend_info->nickname,
1154 safe_str_client(conn->rend_data->onion_address));
1157 /* If we have specified a particular exit node for our
1158 * connection, then be sure to open a circuit to that exit node.
1160 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1161 if (conn->chosen_exit_name) {
1162 routerinfo_t *r;
1163 int opt = conn->chosen_exit_optional;
1164 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1165 if (r) {
1166 extend_info = extend_info_from_router(r);
1167 } else {
1168 log_debug(LD_DIR, "considering %d, %s",
1169 want_onehop, conn->chosen_exit_name);
1170 if (want_onehop && conn->chosen_exit_name[0] == '$') {
1171 /* We're asking for a one-hop circuit to a router that
1172 * we don't have a routerinfo about. Make up an extend_info. */
1173 char digest[DIGEST_LEN];
1174 char *hexdigest = conn->chosen_exit_name+1;
1175 tor_addr_t addr;
1176 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
1177 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
1178 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
1179 return -1;
1181 if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
1182 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
1183 escaped_safe_str_client(conn->socks_request->address));
1184 return -1;
1186 extend_info = extend_info_alloc(conn->chosen_exit_name+1,
1187 digest, NULL, &addr,
1188 conn->socks_request->port);
1189 } else {
1190 /* We will need an onion key for the router, and we
1191 * don't have one. Refuse or relax requirements. */
1192 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1193 "Requested exit point '%s' is not known. %s.",
1194 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1195 if (opt) {
1196 conn->chosen_exit_optional = 0;
1197 tor_free(conn->chosen_exit_name);
1198 /* Try again with no requested exit */
1199 return circuit_get_open_circ_or_launch(conn,
1200 desired_circuit_purpose,
1201 circp);
1203 return -1;
1209 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
1210 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
1211 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1212 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
1213 else
1214 new_circ_purpose = desired_circuit_purpose;
1217 int flags = CIRCLAUNCH_NEED_CAPACITY;
1218 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
1219 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1220 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
1221 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
1222 flags);
1225 extend_info_free(extend_info);
1227 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
1228 /* help predict this next time */
1229 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1230 if (circ) {
1231 /* write the service_id into circ */
1232 circ->rend_data = rend_data_dup(conn->rend_data);
1233 if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1234 circ->_base.state == CIRCUIT_STATE_OPEN)
1235 rend_client_rendcirc_has_opened(circ);
1239 if (!circ)
1240 log_info(LD_APP,
1241 "No safe circuit (purpose %d) ready for edge "
1242 "connection; delaying.",
1243 desired_circuit_purpose);
1244 *circp = circ;
1245 return 0;
1248 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1249 * <b>circ</b>. */
1250 static int
1251 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
1253 crypt_path_t *cpath, *cpath_next = NULL;
1254 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1255 cpath_next = cpath->next;
1256 if (crypt_path == cpath)
1257 return 1;
1259 return 0;
1262 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1263 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1264 * hop in circ's cpath if <b>cpath</b> is NULL.
1266 static void
1267 link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
1268 crypt_path_t *cpath)
1270 /* add it into the linked list of streams on this circuit */
1271 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
1272 circ->_base.n_circ_id);
1273 /* reset it, so we can measure circ timeouts */
1274 apconn->_base.timestamp_lastread = time(NULL);
1275 apconn->next_stream = circ->p_streams;
1276 apconn->on_circuit = TO_CIRCUIT(circ);
1277 /* assert_connection_ok(conn, time(NULL)); */
1278 circ->p_streams = apconn;
1280 if (cpath) { /* we were given one; use it */
1281 tor_assert(cpath_is_on_circuit(circ, cpath));
1282 apconn->cpath_layer = cpath;
1283 } else { /* use the last hop in the circuit */
1284 tor_assert(circ->cpath);
1285 tor_assert(circ->cpath->prev);
1286 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1287 apconn->cpath_layer = circ->cpath->prev;
1291 /** If an exit wasn't specifically chosen, save the history for future
1292 * use. */
1293 static void
1294 consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
1296 int found_needle = 0;
1297 or_options_t *options = get_options();
1298 size_t len;
1299 char *new_address;
1300 char fp[HEX_DIGEST_LEN+1];
1302 /* Search the addressmap for this conn's destination. */
1303 /* If he's not in the address map.. */
1304 if (!options->TrackHostExits ||
1305 addressmap_have_mapping(conn->socks_request->address,
1306 options->TrackHostExitsExpire))
1307 return; /* nothing to track, or already mapped */
1309 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1310 if (cp[0] == '.') { /* match end */
1311 if (cp[1] == '\0' ||
1312 !strcasecmpend(conn->socks_request->address, cp) ||
1313 !strcasecmp(conn->socks_request->address, &cp[1]))
1314 found_needle = 1;
1315 } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
1316 found_needle = 1;
1320 if (!found_needle || !circ->build_state->chosen_exit)
1321 return;
1323 /* write down the fingerprint of the chosen exit, not the nickname,
1324 * because the chosen exit might not be named. */
1325 base16_encode(fp, sizeof(fp),
1326 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
1328 /* Add this exit/hostname pair to the addressmap. */
1329 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1330 strlen(fp) + 1 /* '.' */ +
1331 strlen("exit") + 1 /* '\0' */;
1332 new_address = tor_malloc(len);
1334 tor_snprintf(new_address, len, "%s.%s.exit",
1335 conn->socks_request->address, fp);
1337 addressmap_register(conn->socks_request->address, new_address,
1338 time(NULL) + options->TrackHostExitsExpire,
1339 ADDRMAPSRC_TRACKEXIT);
1342 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1343 * begin or resolve cell as appropriate. Return values are as for
1344 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1345 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1346 * <b>cpath</b> is NULL. */
1348 connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
1349 origin_circuit_t *circ,
1350 crypt_path_t *cpath)
1352 tor_assert(conn);
1353 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
1354 conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
1355 tor_assert(conn->socks_request);
1356 tor_assert(circ);
1357 tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
1359 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1361 if (!circ->_base.timestamp_dirty)
1362 circ->_base.timestamp_dirty = time(NULL);
1364 link_apconn_to_circ(conn, circ, cpath);
1365 tor_assert(conn->socks_request);
1366 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
1367 if (!conn->use_begindir)
1368 consider_recording_trackhost(conn, circ);
1369 if (connection_ap_handshake_send_begin(conn) < 0)
1370 return -1;
1371 } else {
1372 if (connection_ap_handshake_send_resolve(conn) < 0)
1373 return -1;
1376 return 1;
1379 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1380 * we don't find one: if conn cannot be handled by any known nodes,
1381 * warn and return -1 (conn needs to die, and is maybe already marked);
1382 * else launch new circuit (if necessary) and return 0.
1383 * Otherwise, associate conn with a safe live circuit, do the
1384 * right next step, and return 1.
1386 /* XXXX this function should mark for close whenever it returns -1;
1387 * its callers shouldn't have to worry about that. */
1389 connection_ap_handshake_attach_circuit(edge_connection_t *conn)
1391 int retval;
1392 int conn_age;
1393 int want_onehop;
1395 tor_assert(conn);
1396 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1397 tor_assert(conn->socks_request);
1398 want_onehop = conn->want_onehop;
1400 conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
1402 if (conn_age >= get_options()->SocksTimeout) {
1403 int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
1404 LOG_INFO : LOG_NOTICE;
1405 log_fn(severity, LD_APP,
1406 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1407 conn_age, safe_str_client(conn->socks_request->address),
1408 conn->socks_request->port);
1409 return -1;
1412 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1413 origin_circuit_t *circ=NULL;
1415 if (conn->chosen_exit_name) {
1416 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1417 int opt = conn->chosen_exit_optional;
1418 if (!router && !want_onehop) {
1419 /* We ran into this warning when trying to extend a circuit to a
1420 * hidden service directory for which we didn't have a router
1421 * descriptor. See flyspray task 767 for more details. We should
1422 * keep this in mind when deciding to use BEGIN_DIR cells for other
1423 * directory requests as well. -KL*/
1424 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1425 "Requested exit point '%s' is not known. %s.",
1426 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1427 if (opt) {
1428 conn->chosen_exit_optional = 0;
1429 tor_free(conn->chosen_exit_name);
1430 return 0;
1432 return -1;
1434 if (router && !connection_ap_can_use_exit(conn, router)) {
1435 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1436 "Requested exit point '%s' would refuse request. %s.",
1437 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1438 if (opt) {
1439 conn->chosen_exit_optional = 0;
1440 tor_free(conn->chosen_exit_name);
1441 return 0;
1443 return -1;
1447 /* find the circuit that we should use, if there is one. */
1448 retval = circuit_get_open_circ_or_launch(
1449 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1450 if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
1451 return retval;
1453 log_debug(LD_APP|LD_CIRC,
1454 "Attaching apconn to circ %d (stream %d sec old).",
1455 circ->_base.n_circ_id, conn_age);
1456 /* print the circ's path, so people can figure out which circs are
1457 * sucking. */
1458 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1460 /* We have found a suitable circuit for our conn. Hurray. */
1461 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
1463 } else { /* we're a rendezvous conn */
1464 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
1466 tor_assert(!conn->cpath_layer);
1468 /* start by finding a rendezvous circuit for us */
1470 retval = circuit_get_open_circ_or_launch(
1471 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1472 if (retval < 0) return -1; /* failed */
1474 if (retval > 0) {
1475 tor_assert(rendcirc);
1476 /* one is already established, attach */
1477 log_info(LD_REND,
1478 "rend joined circ %d already here. attaching. "
1479 "(stream %d sec old)",
1480 rendcirc->_base.n_circ_id, conn_age);
1481 /* Mark rendezvous circuits as 'newly dirty' every time you use
1482 * them, since the process of rebuilding a rendezvous circ is so
1483 * expensive. There is a tradeoff between linkability and
1484 * feasibility, at this point.
1486 rendcirc->_base.timestamp_dirty = time(NULL);
1487 link_apconn_to_circ(conn, rendcirc, NULL);
1488 if (connection_ap_handshake_send_begin(conn) < 0)
1489 return 0; /* already marked, let them fade away */
1490 return 1;
1493 if (rendcirc && (rendcirc->_base.purpose ==
1494 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
1495 log_info(LD_REND,
1496 "pending-join circ %d already here, with intro ack. "
1497 "Stalling. (stream %d sec old)",
1498 rendcirc->_base.n_circ_id, conn_age);
1499 return 0;
1502 /* it's on its way. find an intro circ. */
1503 retval = circuit_get_open_circ_or_launch(
1504 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1505 if (retval < 0) return -1; /* failed */
1507 if (retval > 0) {
1508 /* one has already sent the intro. keep waiting. */
1509 circuit_t *c = NULL;
1510 tor_assert(introcirc);
1511 log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
1512 "Stalling. (stream %d sec old)",
1513 introcirc->_base.n_circ_id,
1514 rendcirc ? rendcirc->_base.n_circ_id : 0,
1515 conn_age);
1516 /* abort parallel intro circs, if any */
1517 for (c = global_circuitlist; c; c = c->next) {
1518 if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
1519 !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
1520 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
1521 if (oc->rend_data &&
1522 !rend_cmp_service_ids(conn->rend_data->onion_address,
1523 oc->rend_data->onion_address)) {
1524 log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
1525 "built in parallel.");
1526 circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
1530 return 0;
1533 /* now rendcirc and introcirc are each either undefined or not finished */
1535 if (rendcirc && introcirc &&
1536 rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1537 log_info(LD_REND,
1538 "ready rend circ %d already here (no intro-ack yet on "
1539 "intro %d). (stream %d sec old)",
1540 rendcirc->_base.n_circ_id,
1541 introcirc->_base.n_circ_id, conn_age);
1543 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1544 if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
1545 log_info(LD_REND,"found open intro circ %d (rend %d); sending "
1546 "introduction. (stream %d sec old)",
1547 introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
1548 conn_age);
1549 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1550 return -1;
1552 rendcirc->_base.timestamp_dirty = time(NULL);
1553 introcirc->_base.timestamp_dirty = time(NULL);
1554 assert_circuit_ok(TO_CIRCUIT(rendcirc));
1555 assert_circuit_ok(TO_CIRCUIT(introcirc));
1556 return 0;
1560 log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
1561 "Stalling conn. (%d sec old)",
1562 introcirc ? introcirc->_base.n_circ_id : 0,
1563 rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
1564 return 0;