r14602@catbus: nickm | 2007-08-16 13:33:27 -0400
[tor.git] / src / or / circuituse.c
blobb145474079ab9b2e38bbb16ea0a9c97235e5f09c
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char circuituse_c_id[] =
7 "$Id$";
9 /**
10 * \file circuituse.c
11 * \brief Launch the right sort of circuits and attach streams to them.
12 **/
14 #include "or.h"
16 /********* START VARIABLES **********/
18 extern circuit_t *global_circuitlist; /* from circuitlist.c */
20 /********* END VARIABLES ************/
22 static void circuit_expire_old_circuits(time_t now);
23 static void circuit_increment_failure_count(void);
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->socks_request->command != SOCKS_COMMAND_CONNECT_DIR) {
91 log_debug(LD_CIRC,"Skipping one-hop circuit.");
92 return 0;
94 } else {
95 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT_DIR) {
96 /* don't use three-hop circuits -- that could hurt our anonymity. */
97 log_debug(LD_CIRC,"Skipping multi-hop circuit for CONNECT_DIR.");
98 return 0;
101 if (exitrouter && !connection_ap_can_use_exit(conn, exitrouter)) {
102 /* can't exit from this router */
103 return 0;
105 } else { /* not general */
106 if (rend_cmp_service_ids(conn->rend_query,
107 TO_ORIGIN_CIRCUIT(circ)->rend_query)) {
108 /* this circ is not for this conn */
109 return 0;
112 return 1;
115 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
116 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
118 static int
119 circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
121 switch (purpose) {
122 case CIRCUIT_PURPOSE_C_GENERAL:
123 /* if it's used but less dirty it's best;
124 * else if it's more recently created it's best
126 if (b->timestamp_dirty) {
127 if (a->timestamp_dirty &&
128 a->timestamp_dirty > b->timestamp_dirty)
129 return 1;
130 } else {
131 if (a->timestamp_dirty ||
132 a->timestamp_created > b->timestamp_created)
133 return 1;
134 if (CIRCUIT_IS_ORIGIN(b) &&
135 TO_ORIGIN_CIRCUIT(b)->build_state->is_internal)
136 return 1;
138 break;
139 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
140 /* the closer it is to ack_wait the better it is */
141 if (a->purpose > b->purpose)
142 return 1;
143 break;
144 case CIRCUIT_PURPOSE_C_REND_JOINED:
145 /* the closer it is to rend_joined the better it is */
146 if (a->purpose > b->purpose)
147 return 1;
148 break;
150 return 0;
153 /** Find the best circ that conn can use, preferably one which is
154 * dirty. Circ must not be too old.
156 * Conn must be defined.
158 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
160 * circ_purpose specifies what sort of circuit we must have.
161 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
163 * If it's REND_JOINED and must_be_open==0, then return the closest
164 * rendezvous-purposed circuit that you can find.
166 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
167 * closest introduce-purposed circuit that you can find.
169 static origin_circuit_t *
170 circuit_get_best(edge_connection_t *conn, int must_be_open, uint8_t purpose,
171 int need_uptime, int need_internal)
173 circuit_t *circ, *best=NULL;
174 time_t now = time(NULL);
176 tor_assert(conn);
178 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
179 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
180 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
182 for (circ=global_circuitlist;circ;circ = circ->next) {
183 if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
184 need_uptime,need_internal,now))
185 continue;
187 /* now this is an acceptable circ to hand back. but that doesn't
188 * mean it's the *best* circ to hand back. try to decide.
190 if (!best || circuit_is_better(circ,best,purpose))
191 best = circ;
194 return best ? TO_ORIGIN_CIRCUIT(best) : NULL;
197 /** Close all circuits that start at us, aren't open, and were born
198 * at least CircuitBuildTimeout seconds ago.
200 void
201 circuit_expire_building(time_t now)
203 circuit_t *victim, *circ = global_circuitlist;
204 time_t cutoff = now - get_options()->CircuitBuildTimeout;
206 while (circ) {
207 victim = circ;
208 circ = circ->next;
209 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
210 victim->timestamp_created > cutoff || /* Not old enough to expire */
211 victim->marked_for_close) /* don't mess with marked circs */
212 continue;
214 #if 0
215 /* some debug logs, to help track bugs */
216 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
217 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
218 if (!victim->timestamp_dirty)
219 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d)."
220 "(clean).",
221 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
222 victim->purpose, victim->build_state->chosen_exit_name,
223 victim->n_circ_id);
224 else
225 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). "
226 "%d secs since dirty.",
227 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
228 victim->purpose, victim->build_state->chosen_exit_name,
229 victim->n_circ_id,
230 (int)(now - victim->timestamp_dirty));
232 #endif
234 /* if circ is !open, or if it's open but purpose is a non-finished
235 * intro or rend, then mark it for close */
236 if (victim->state == CIRCUIT_STATE_OPEN) {
237 switch (victim->purpose) {
238 default: /* most open circuits can be left alone. */
239 continue; /* yes, continue inside a switch refers to the nearest
240 * enclosing loop. C is smart. */
241 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
242 case CIRCUIT_PURPOSE_C_INTRODUCING:
243 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
244 break; /* too old, need to die */
245 case CIRCUIT_PURPOSE_C_REND_READY:
246 /* it's a rend_ready circ -- has it already picked a query? */
247 /* c_rend_ready circs measure age since timestamp_dirty,
248 * because that's set when they switch purposes
250 if (TO_ORIGIN_CIRCUIT(victim)->rend_query[0] ||
251 victim->timestamp_dirty > cutoff)
252 continue;
253 break;
254 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
255 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
256 /* rend and intro circs become dirty each time they
257 * make an introduction attempt. so timestamp_dirty
258 * will reflect the time since the last attempt.
260 if (victim->timestamp_dirty > cutoff)
261 continue;
262 break;
266 if (victim->n_conn)
267 log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
268 victim->n_conn->_base.address, victim->n_port,
269 victim->n_circ_id,
270 victim->state, circuit_state_to_string(victim->state),
271 victim->purpose);
272 else
273 log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
274 victim->n_circ_id, victim->state,
275 circuit_state_to_string(victim->state), victim->purpose);
277 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
278 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
282 /** Remove any elements in <b>needed_ports</b> that are handled by an
283 * open or in-progress circuit.
285 void
286 circuit_remove_handled_ports(smartlist_t *needed_ports)
288 int i;
289 uint16_t *port;
291 for (i = 0; i < smartlist_len(needed_ports); ++i) {
292 port = smartlist_get(needed_ports, i);
293 tor_assert(*port);
294 if (circuit_stream_is_being_handled(NULL, *port,
295 MIN_CIRCUITS_HANDLING_STREAM)) {
296 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
297 smartlist_del(needed_ports, i--);
298 tor_free(port);
299 } else {
300 log_debug(LD_CIRC,"Port %d is not handled.", *port);
305 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
306 * will have an acceptable exit node for exit stream <b>conn</b> if it
307 * is defined, else for "*:port".
308 * Else return 0.
311 circuit_stream_is_being_handled(edge_connection_t *conn,
312 uint16_t port, int min)
314 circuit_t *circ;
315 routerinfo_t *exitrouter;
316 int num=0;
317 time_t now = time(NULL);
318 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
319 conn ? conn->socks_request->port : port);
321 for (circ=global_circuitlist;circ;circ = circ->next) {
322 if (CIRCUIT_IS_ORIGIN(circ) &&
323 !circ->marked_for_close &&
324 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
325 (!circ->timestamp_dirty ||
326 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
327 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
328 if (build_state->is_internal || build_state->onehop_tunnel)
329 continue;
331 exitrouter = build_state_get_exit_router(build_state);
332 if (exitrouter && (!need_uptime || build_state->need_uptime)) {
333 int ok;
334 if (conn) {
335 ok = connection_ap_can_use_exit(conn, exitrouter);
336 } else {
337 addr_policy_result_t r = compare_addr_to_addr_policy(
338 0, port, exitrouter->exit_policy);
339 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
341 if (ok) {
342 if (++num >= min)
343 return 1;
348 return 0;
351 /** Don't keep more than this many unused open circuits around. */
352 #define MAX_UNUSED_OPEN_CIRCUITS 12
354 /** Figure out how many circuits we have open that are clean. Make
355 * sure it's enough for all the upcoming behaviors we predict we'll have.
356 * But if we have too many, close the not-so-useful ones.
358 static void
359 circuit_predict_and_launch_new(void)
361 circuit_t *circ;
362 int num=0, num_internal=0, num_uptime_internal=0;
363 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
364 int port_needs_uptime=0, port_needs_capacity=1;
365 time_t now = time(NULL);
367 /* First, count how many of each type of circuit we have already. */
368 for (circ=global_circuitlist;circ;circ = circ->next) {
369 cpath_build_state_t *build_state;
370 if (!CIRCUIT_IS_ORIGIN(circ))
371 continue;
372 if (circ->marked_for_close)
373 continue; /* don't mess with marked circs */
374 if (circ->timestamp_dirty)
375 continue; /* only count clean circs */
376 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
377 continue; /* only pay attention to general-purpose circs */
378 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
379 if (build_state->onehop_tunnel)
380 continue;
381 num++;
382 if (build_state->is_internal)
383 num_internal++;
384 if (build_state->need_uptime && build_state->is_internal)
385 num_uptime_internal++;
388 /* If that's enough, then stop now. */
389 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
390 return; /* we already have many, making more probably will hurt */
392 /* Second, see if we need any more exit circuits. */
393 /* check if we know of a port that's been requested recently
394 * and no circuit is currently available that can handle it. */
395 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
396 &port_needs_capacity)) {
397 log_info(LD_CIRC,
398 "Have %d clean circs (%d internal), need another exit circ.",
399 num, num_internal);
400 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, 0, NULL,
401 port_needs_uptime, port_needs_capacity, 0);
402 return;
405 /* Third, see if we need any more hidden service (server) circuits. */
406 if (num_rend_services() && num_uptime_internal < 3) {
407 log_info(LD_CIRC,
408 "Have %d clean circs (%d internal), need another internal "
409 "circ for my hidden service.",
410 num, num_internal);
411 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, 0, NULL,
412 1, 1, 1);
413 return;
416 /* Fourth, see if we need any more hidden service (client) circuits. */
417 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
418 &hidserv_needs_capacity) &&
419 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
420 num_internal<2)) {
421 log_info(LD_CIRC,
422 "Have %d clean circs (%d uptime-internal, %d internal), need"
423 " another hidserv circ.",
424 num, num_uptime_internal, num_internal);
425 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, 0, NULL,
426 hidserv_needs_uptime, hidserv_needs_capacity, 1);
427 return;
431 /** Build a new test circuit every 5 minutes */
432 #define TESTING_CIRCUIT_INTERVAL 300
434 /** This function is called once a second, if router_have_min_dir_info() is
435 * true. Its job is to make sure all services we offer have enough circuits
436 * available. Some services just want enough circuits for current tasks,
437 * whereas others want a minimum set of idle circuits hanging around.
439 void
440 circuit_build_needed_circs(time_t now)
442 static long time_to_new_circuit = 0;
444 /* launch a new circ for any pending streams that need one */
445 connection_ap_attach_pending();
447 /* make sure any hidden services have enough intro points */
448 rend_services_introduce();
450 if (time_to_new_circuit < now) {
451 circuit_reset_failure_count(1);
452 time_to_new_circuit = now + get_options()->NewCircuitPeriod;
453 if (proxy_mode(get_options()))
454 addressmap_clean(now);
455 circuit_expire_old_circuits(now);
457 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
458 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
459 if (get_options()->RunTesting &&
460 circ &&
461 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
462 log_fn(LOG_INFO,"Creating a new testing circuit.");
463 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, 0, NULL, 0, 0, 0);
465 #endif
467 circuit_predict_and_launch_new();
470 /** If the stream <b>conn</b> is a member of any of the linked
471 * lists of <b>circ</b>, then remove it from the list.
473 void
474 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
476 edge_connection_t *prevconn;
478 tor_assert(circ);
479 tor_assert(conn);
481 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
482 conn->on_circuit = NULL;
484 if (CIRCUIT_IS_ORIGIN(circ)) {
485 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
486 if (conn == origin_circ->p_streams) {
487 origin_circ->p_streams = conn->next_stream;
488 return;
491 for (prevconn = origin_circ->p_streams;
492 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
493 prevconn = prevconn->next_stream)
495 if (prevconn && prevconn->next_stream) {
496 prevconn->next_stream = conn->next_stream;
497 return;
499 } else {
500 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
501 if (conn == or_circ->n_streams) {
502 or_circ->n_streams = conn->next_stream;
503 return;
505 if (conn == or_circ->resolving_streams) {
506 or_circ->resolving_streams = conn->next_stream;
507 return;
510 for (prevconn = or_circ->n_streams;
511 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
512 prevconn = prevconn->next_stream)
514 if (prevconn && prevconn->next_stream) {
515 prevconn->next_stream = conn->next_stream;
516 return;
519 for (prevconn = or_circ->resolving_streams;
520 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
521 prevconn = prevconn->next_stream)
523 if (prevconn && prevconn->next_stream) {
524 prevconn->next_stream = conn->next_stream;
525 return;
529 log_err(LD_BUG,"edge conn not in circuit's list?");
530 tor_assert(0); /* should never get here */
533 /** Find each circuit that has been unused for too long, or dirty
534 * for too long and has no streams on it: mark it for close.
536 static void
537 circuit_expire_old_circuits(time_t now)
539 circuit_t *circ;
540 time_t cutoff = now - get_options()->CircuitIdleTimeout;
542 for (circ = global_circuitlist; circ; circ = circ->next) {
543 if (circ->marked_for_close || ! CIRCUIT_IS_ORIGIN(circ))
544 continue;
545 /* If the circuit has been dirty for too long, and there are no streams
546 * on it, mark it for close.
548 if (circ->timestamp_dirty &&
549 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
550 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
551 log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, purp %d)",
552 circ->n_circ_id, (int)(now - circ->timestamp_dirty),
553 circ->purpose);
554 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
555 } else if (!circ->timestamp_dirty &&
556 circ->state == CIRCUIT_STATE_OPEN &&
557 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
558 if (circ->timestamp_created < cutoff) {
559 log_debug(LD_CIRC,
560 "Closing circuit that has been unused for %d seconds.",
561 (int)(now - circ->timestamp_created));
562 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
568 /** Number of testing circuits we want open before testing our bandwidth. */
569 #define NUM_PARALLEL_TESTING_CIRCS 4
571 /** True iff we've ever had enough testing circuits open to test our
572 * bandwidth. */
573 static int have_performed_bandwidth_test = 0;
575 /** Reset have_performed_bandwidth_test, so we'll start building
576 * testing circuits again so we can exercise our bandwidth. */
577 void
578 reset_bandwidth_test(void)
580 have_performed_bandwidth_test = 0;
583 /** Return 1 if we've already exercised our bandwidth, or if we
584 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
585 * established or on the way. Else return 0.
588 circuit_enough_testing_circs(void)
590 circuit_t *circ;
591 int num = 0;
593 if (have_performed_bandwidth_test)
594 return 1;
596 for (circ = global_circuitlist; circ; circ = circ->next) {
597 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
598 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
599 circ->state == CIRCUIT_STATE_OPEN)
600 num++;
602 return num >= NUM_PARALLEL_TESTING_CIRCS;
605 /** A testing circuit has completed. Take whatever stats we want.
606 * Noticing reachability is taken care of in onionskin_answer(),
607 * so there's no need to record anything here. But if we still want
608 * to do the bandwidth test, and we now have enough testing circuits
609 * open, do it.
611 static void
612 circuit_testing_opened(origin_circuit_t *circ)
614 if (have_performed_bandwidth_test) {
615 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
616 } else if (circuit_enough_testing_circs()) {
617 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
618 have_performed_bandwidth_test = 1;
619 } else
620 consider_testing_reachability(1, 0);
623 /** A testing circuit has failed to build. Take whatever stats we want. */
624 static void
625 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
627 routerinfo_t *me = router_get_my_routerinfo();
628 if (server_mode(get_options()) && check_whether_orport_reachable())
629 return;
630 if (!me)
631 return;
633 log_info(LD_GENERAL,
634 "Our testing circuit (to see if your ORPort is reachable) "
635 "has failed. I'll try again later.");
636 control_event_server_status(LOG_WARN, "REACHABILITY_FAILED ORADDRESS=%s:%d",
637 me->address, me->or_port);
639 /* These aren't used yet. */
640 (void)circ;
641 (void)at_last_hop;
644 /** The circuit <b>circ</b> has just become open. Take the next
645 * step: for rendezvous circuits, we pass circ to the appropriate
646 * function in rendclient or rendservice. For general circuits, we
647 * call connection_ap_attach_pending, which looks for pending streams
648 * that could use circ.
650 void
651 circuit_has_opened(origin_circuit_t *circ)
653 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
655 switch (TO_CIRCUIT(circ)->purpose) {
656 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
657 rend_client_rendcirc_has_opened(circ);
658 connection_ap_attach_pending();
659 break;
660 case CIRCUIT_PURPOSE_C_INTRODUCING:
661 rend_client_introcirc_has_opened(circ);
662 break;
663 case CIRCUIT_PURPOSE_C_GENERAL:
664 /* Tell any AP connections that have been waiting for a new
665 * circuit that one is ready. */
666 connection_ap_attach_pending();
667 break;
668 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
669 /* at Bob, waiting for introductions */
670 rend_service_intro_has_opened(circ);
671 break;
672 case CIRCUIT_PURPOSE_S_CONNECT_REND:
673 /* at Bob, connecting to rend point */
674 rend_service_rendezvous_has_opened(circ);
675 break;
676 case CIRCUIT_PURPOSE_TESTING:
677 circuit_testing_opened(circ);
678 break;
679 /* default:
680 * This won't happen in normal operation, but might happen if the
681 * controller did it. Just let it slide. */
685 /** Called whenever a circuit could not be successfully built.
687 void
688 circuit_build_failed(origin_circuit_t *circ)
690 /* we should examine circ and see if it failed because of
691 * the last hop or an earlier hop. then use this info below.
693 int failed_at_last_hop = 0;
694 /* If the last hop isn't open, and the second-to-last is, we failed
695 * at the last hop. */
696 if (circ->cpath &&
697 circ->cpath->prev->state != CPATH_STATE_OPEN &&
698 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
699 failed_at_last_hop = 1;
701 if (circ->cpath &&
702 circ->cpath->state != CPATH_STATE_OPEN) {
703 /* We failed at the first hop. If there's an OR connection
704 to blame, blame it. */
705 or_connection_t *n_conn = NULL;
706 if (circ->_base.n_conn) {
707 n_conn = circ->_base.n_conn;
708 } else if (circ->_base.state == CIRCUIT_STATE_OR_WAIT) {
709 /* we have to hunt for it */
710 n_conn = connection_or_get_by_identity_digest(
711 circ->_base.n_conn_id_digest);
713 if (n_conn) {
714 log_info(LD_OR,
715 "Our circuit failed to get a response from the first hop "
716 "(%s:%d). I'm going to try to rotate to a better connection.",
717 n_conn->_base.address, n_conn->_base.port);
718 n_conn->_base.or_is_obsolete = 1;
719 entry_guard_register_connect_status(n_conn->identity_digest, 0,
720 time(NULL));
724 switch (circ->_base.purpose) {
725 case CIRCUIT_PURPOSE_C_GENERAL:
726 /* If we never built the circuit, note it as a failure. */
727 circuit_increment_failure_count();
728 if (failed_at_last_hop) {
729 /* Make sure any streams that demand our last hop as their exit
730 * know that it's unlikely to happen. */
731 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
733 break;
734 case CIRCUIT_PURPOSE_TESTING:
735 circuit_testing_failed(circ, failed_at_last_hop);
736 break;
737 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
738 /* at Bob, waiting for introductions */
739 if (circ->_base.state != CIRCUIT_STATE_OPEN) {
740 circuit_increment_failure_count();
742 /* no need to care here, because bob will rebuild intro
743 * points periodically. */
744 break;
745 case CIRCUIT_PURPOSE_C_INTRODUCING:
746 /* at Alice, connecting to intro point */
747 /* Don't increment failure count, since Bob may have picked
748 * the introduction point maliciously */
749 /* Alice will pick a new intro point when this one dies, if
750 * the stream in question still cares. No need to act here. */
751 break;
752 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
753 /* at Alice, waiting for Bob */
754 circuit_increment_failure_count();
755 /* Alice will pick a new rend point when this one dies, if
756 * the stream in question still cares. No need to act here. */
757 break;
758 case CIRCUIT_PURPOSE_S_CONNECT_REND:
759 /* at Bob, connecting to rend point */
760 /* Don't increment failure count, since Alice may have picked
761 * the rendezvous point maliciously */
762 log_info(LD_REND,
763 "Couldn't connect to Alice's chosen rend point %s "
764 "(%s hop failed).",
765 escaped(build_state_get_exit_nickname(circ->build_state)),
766 failed_at_last_hop?"last":"non-last");
767 rend_service_relaunch_rendezvous(circ);
768 break;
769 /* default:
770 * This won't happen in normal operation, but might happen if the
771 * controller did it. Just let it slide. */
775 /** Number of consecutive failures so far; should only be touched by
776 * circuit_launch_new and circuit_*_failure_count.
778 static int n_circuit_failures = 0;
779 /** Before the last time we called circuit_reset_failure_count(), were
780 * there a lot of failures? */
781 static int did_circs_fail_last_period = 0;
783 /** Don't retry launching a new circuit if we try this many times with no
784 * success. */
785 #define MAX_CIRCUIT_FAILURES 5
787 /** Launch a new circuit; see circuit_launch_by_extend_info() for
788 * details on arguments. */
789 origin_circuit_t *
790 circuit_launch_by_router(uint8_t purpose, int onehop_tunnel,
791 routerinfo_t *exit, int need_uptime,
792 int need_capacity, int internal)
794 origin_circuit_t *circ;
795 extend_info_t *info = NULL;
796 if (exit)
797 info = extend_info_from_router(exit);
798 circ = circuit_launch_by_extend_info(
799 purpose, onehop_tunnel, info, need_uptime, need_capacity, internal);
800 if (info)
801 extend_info_free(info);
802 return circ;
805 /** Launch a new circuit with purpose <b>purpose</b> and exit node <b>info</b>
806 * (or NULL to select a random exit node). If <b>need_uptime</b> is true,
807 * choose among routers with high uptime. If <b>need_capacity</b> is true,
808 * choose among routers with high bandwidth. If <b>internal</b> is true, the
809 * last hop need not be an exit node. Return the newly allocated circuit on
810 * success, or NULL on failure. */
811 origin_circuit_t *
812 circuit_launch_by_extend_info(uint8_t purpose, int onehop_tunnel,
813 extend_info_t *extend_info, int need_uptime,
814 int need_capacity, int internal)
816 origin_circuit_t *circ;
818 if (!onehop_tunnel && !router_have_minimum_dir_info()) {
819 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
820 "circuit launch.");
821 return NULL;
824 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
825 purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
826 /* see if there are appropriate circs available to cannibalize. */
827 circ = circuit_find_to_cannibalize(CIRCUIT_PURPOSE_C_GENERAL, extend_info,
828 need_uptime, need_capacity, internal);
829 if (circ) {
830 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
831 build_state_get_exit_nickname(circ->build_state), purpose);
832 circ->_base.purpose = purpose;
833 /* reset the birth date of this circ, else expire_building
834 * will see it and think it's been trying to build since it
835 * began. */
836 circ->_base.timestamp_created = time(NULL);
837 switch (purpose) {
838 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
839 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
840 /* it's ready right now */
841 break;
842 case CIRCUIT_PURPOSE_C_INTRODUCING:
843 case CIRCUIT_PURPOSE_S_CONNECT_REND:
844 case CIRCUIT_PURPOSE_C_GENERAL:
845 /* need to add a new hop */
846 tor_assert(extend_info);
847 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
848 return NULL;
849 break;
850 default:
851 log_warn(LD_BUG,
852 "Bug: unexpected purpose %d when cannibalizing a circ.",
853 purpose);
854 tor_fragile_assert();
855 return NULL;
857 return circ;
861 if (did_circs_fail_last_period &&
862 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
863 /* too many failed circs in a row. don't try. */
864 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
865 return NULL;
868 /* try a circ. if it fails, circuit_mark_for_close will increment
869 * n_circuit_failures */
870 return circuit_establish_circuit(purpose, onehop_tunnel, extend_info,
871 need_uptime, need_capacity, internal);
874 /** Launch a new circuit; see circuit_launch_by_extend_info() for
875 * details on arguments. */
876 origin_circuit_t *
877 circuit_launch_by_nickname(uint8_t purpose, int onehop_tunnel,
878 const char *exit_nickname,
879 int need_uptime, int need_capacity, int internal)
881 routerinfo_t *router = NULL;
883 if (exit_nickname) {
884 router = router_get_by_nickname(exit_nickname, 1);
885 if (!router) {
886 log_warn(LD_GENERAL, "Trying to launch circ by nickname, but "
887 "no such OR as '%s'", exit_nickname);
888 return NULL;
891 return circuit_launch_by_router(purpose, onehop_tunnel, router,
892 need_uptime, need_capacity, internal);
895 /** Record another failure at opening a general circuit. When we have
896 * too many, we'll stop trying for the remainder of this minute.
898 static void
899 circuit_increment_failure_count(void)
901 ++n_circuit_failures;
902 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
905 /** Reset the failure count for opening general circuits. This means
906 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
907 * stopping again.
909 void
910 circuit_reset_failure_count(int timeout)
912 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
913 did_circs_fail_last_period = 1;
914 else
915 did_circs_fail_last_period = 0;
916 n_circuit_failures = 0;
919 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
920 * there isn't one, and there isn't one on the way, launch one and return
921 * 0. If it will never work, return -1.
923 * Write the found or in-progress or launched circ into *circp.
925 static int
926 circuit_get_open_circ_or_launch(edge_connection_t *conn,
927 uint8_t desired_circuit_purpose,
928 origin_circuit_t **circp)
930 origin_circuit_t *circ;
931 int check_exit_policy;
932 int need_uptime, need_internal;
933 int want_onehop;
935 tor_assert(conn);
936 tor_assert(circp);
937 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
938 check_exit_policy =
939 (conn->socks_request->command == SOCKS_COMMAND_CONNECT) &&
940 !connection_edge_is_rendezvous_stream(conn);
941 want_onehop = conn->socks_request->command == SOCKS_COMMAND_CONNECT_DIR;
943 need_uptime = (conn->socks_request->command == SOCKS_COMMAND_CONNECT) &&
944 smartlist_string_num_isin(get_options()->LongLivedPorts,
945 conn->socks_request->port);
946 need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
948 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
949 need_uptime, need_internal);
951 if (circ) {
952 *circp = circ;
953 return 1; /* we're happy */
956 if (!want_onehop && !router_have_minimum_dir_info()) {
957 if (!connection_get_by_type(CONN_TYPE_DIR)) {
958 log_notice(LD_APP|LD_DIR,
959 "Application request when we're believed to be "
960 "offline. Optimistically trying directory fetches again.");
961 router_reset_status_download_failures();
962 router_reset_descriptor_download_failures();
963 update_networkstatus_downloads(time(NULL));
964 update_router_descriptor_downloads(time(NULL));
966 /* the stream will be dealt with when router_have_minimum_dir_info becomes
967 * 1, or when all directory attempts fail and directory_all_unreachable()
968 * kills it.
970 return 0;
973 /* Do we need to check exit policy? */
974 if (check_exit_policy) {
975 struct in_addr in;
976 uint32_t addr = 0;
977 if (tor_inet_aton(conn->socks_request->address, &in))
978 addr = ntohl(in.s_addr);
979 if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port,
980 need_uptime)) {
981 log_notice(LD_APP,
982 "No Tor server exists that allows exit to %s:%d. Rejecting.",
983 safe_str(conn->socks_request->address),
984 conn->socks_request->port);
985 return -1;
989 /* is one already on the way? */
990 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
991 need_uptime, need_internal);
992 if (!circ) {
993 extend_info_t *extend_info=NULL;
994 uint8_t new_circ_purpose;
996 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
997 /* need to pick an intro point */
998 extend_info = rend_client_get_random_intro(conn->rend_query);
999 if (!extend_info) {
1000 log_info(LD_REND,
1001 "No intro points for '%s': refetching service descriptor.",
1002 safe_str(conn->rend_query));
1003 rend_client_refetch_renddesc(conn->rend_query);
1004 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1005 return 0;
1007 log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
1008 extend_info->nickname, safe_str(conn->rend_query));
1011 /* If we have specified a particular exit node for our
1012 * connection, then be sure to open a circuit to that exit node.
1014 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1015 if (conn->chosen_exit_name) {
1016 routerinfo_t *r;
1017 int opt = conn->_base.chosen_exit_optional;
1018 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1019 if (r) {
1020 extend_info = extend_info_from_router(r);
1021 } else {
1022 log_debug(LD_DIR, "considering %d, %s",
1023 want_onehop, conn->chosen_exit_name);
1024 if (want_onehop && conn->chosen_exit_name[0] == '$') {
1025 /* We're asking for a one-hop circuit to a router that
1026 * we don't have a routerinfo about. Hope we have a
1027 * routerstatus or equivalent. */
1028 routerstatus_t *s =
1029 routerstatus_get_by_hexdigest(conn->chosen_exit_name+1);
1030 if (s) {
1031 extend_info = extend_info_from_routerstatus(s);
1032 } else {
1033 log_warn(LD_APP,
1034 "Requested router '%s' is not known. Closing.",
1035 conn->chosen_exit_name);
1036 return -1;
1038 } else {
1039 /* We will need an onion key for the router, and we
1040 * don't have one. Refuse or relax requirements. */
1041 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1042 "Requested exit point '%s' is not known. %s.",
1043 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1044 if (opt) {
1045 conn->_base.chosen_exit_optional = 0;
1046 tor_free(conn->chosen_exit_name);
1047 return 0;
1049 return -1;
1055 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
1056 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
1057 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1058 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
1059 else
1060 new_circ_purpose = desired_circuit_purpose;
1062 circ = circuit_launch_by_extend_info(
1063 new_circ_purpose, want_onehop, extend_info,
1064 need_uptime, 1, need_internal);
1065 if (extend_info)
1066 extend_info_free(extend_info);
1068 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
1069 /* help predict this next time */
1070 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1071 if (circ) {
1072 /* write the service_id into circ */
1073 strlcpy(circ->rend_query, conn->rend_query, sizeof(circ->rend_query));
1074 if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1075 circ->_base.state == CIRCUIT_STATE_OPEN)
1076 rend_client_rendcirc_has_opened(circ);
1080 if (!circ)
1081 log_info(LD_APP,
1082 "No safe circuit (purpose %d) ready for edge "
1083 "connection; delaying.",
1084 desired_circuit_purpose);
1085 *circp = circ;
1086 return 0;
1089 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1090 * p_streams. Also set apconn's cpath_layer to the last hop in
1091 * circ's cpath.
1093 static void
1094 link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ)
1096 /* add it into the linked list of streams on this circuit */
1097 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
1098 circ->_base.n_circ_id);
1099 /* reset it, so we can measure circ timeouts */
1100 apconn->_base.timestamp_lastread = time(NULL);
1101 apconn->next_stream = circ->p_streams;
1102 apconn->on_circuit = TO_CIRCUIT(circ);
1103 /* assert_connection_ok(conn, time(NULL)); */
1104 circ->p_streams = apconn;
1106 tor_assert(circ->cpath);
1107 tor_assert(circ->cpath->prev);
1108 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1109 apconn->cpath_layer = circ->cpath->prev;
1112 /** If an exit wasn't specifically chosen, save the history for future
1113 * use. */
1114 static void
1115 consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
1117 int found_needle = 0;
1118 or_options_t *options = get_options();
1119 size_t len;
1120 char *new_address;
1121 char fp[HEX_DIGEST_LEN+1];
1123 /* Search the addressmap for this conn's destination. */
1124 /* If he's not in the address map.. */
1125 if (!options->TrackHostExits ||
1126 addressmap_have_mapping(conn->socks_request->address))
1127 return; /* nothing to track, or already mapped */
1129 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1130 if (cp[0] == '.') { /* match end */
1131 if (!strcasecmpend(conn->socks_request->address, cp) ||
1132 !strcasecmp(conn->socks_request->address, &cp[1]))
1133 found_needle = 1;
1134 } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
1135 found_needle = 1;
1139 if (!found_needle || !circ->build_state->chosen_exit)
1140 return;
1142 /* write down the fingerprint of the chosen exit, not the nickname,
1143 * because the chosen exit might not be named. */
1144 base16_encode(fp, sizeof(fp),
1145 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
1147 /* Add this exit/hostname pair to the addressmap. */
1148 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1149 strlen(fp) + 1 /* '.' */ +
1150 strlen("exit") + 1 /* '\0' */;
1151 new_address = tor_malloc(len);
1153 tor_snprintf(new_address, len, "%s.%s.exit",
1154 conn->socks_request->address, fp);
1156 addressmap_register(conn->socks_request->address, new_address,
1157 time(NULL) + options->TrackHostExitsExpire);
1160 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and
1161 * send a begin or resolve cell as appropriate. Return values are as
1162 * for connection_ap_handshake_attach_circuit. */
1164 connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
1165 origin_circuit_t *circ)
1167 tor_assert(conn);
1168 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
1169 conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
1170 tor_assert(conn->socks_request);
1171 tor_assert(circ);
1172 tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
1174 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1176 if (!circ->_base.timestamp_dirty)
1177 circ->_base.timestamp_dirty = time(NULL);
1179 link_apconn_to_circ(conn, circ);
1180 tor_assert(conn->socks_request);
1181 switch (conn->socks_request->command) {
1182 case SOCKS_COMMAND_CONNECT:
1183 consider_recording_trackhost(conn, circ);
1184 /* fall through */
1185 case SOCKS_COMMAND_CONNECT_DIR:
1186 if (connection_ap_handshake_send_begin(conn, circ)<0)
1187 return -1;
1188 break;
1189 default:
1190 if (connection_ap_handshake_send_resolve(conn, circ)<0)
1191 return -1;
1194 return 1;
1197 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1198 * we don't find one: if conn cannot be handled by any known nodes,
1199 * warn and return -1 (conn needs to die);
1200 * else launch new circuit (if necessary) and return 0.
1201 * Otherwise, associate conn with a safe live circuit, do the
1202 * right next step, and return 1.
1205 connection_ap_handshake_attach_circuit(edge_connection_t *conn)
1207 int retval;
1208 int conn_age;
1209 int want_onehop;
1211 tor_assert(conn);
1212 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1213 tor_assert(conn->socks_request);
1214 want_onehop = conn->socks_request->command == SOCKS_COMMAND_CONNECT_DIR;
1216 conn_age = time(NULL) - conn->_base.timestamp_created;
1218 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1219 origin_circuit_t *circ=NULL;
1221 if (conn->chosen_exit_name) {
1222 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1223 int opt = conn->_base.chosen_exit_optional;
1224 if (!router && !want_onehop) {
1225 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1226 "Requested exit point '%s' is not known. %s.",
1227 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1228 if (opt) {
1229 conn->_base.chosen_exit_optional = 0;
1230 tor_free(conn->chosen_exit_name);
1231 return 0;
1233 return -1;
1235 if (router && !connection_ap_can_use_exit(conn, router)) {
1236 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1237 "Requested exit point '%s' would refuse request. %s.",
1238 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1239 if (opt) {
1240 conn->_base.chosen_exit_optional = 0;
1241 tor_free(conn->chosen_exit_name);
1242 return 0;
1244 return -1;
1248 /* find the circuit that we should use, if there is one. */
1249 retval = circuit_get_open_circ_or_launch(
1250 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1251 if (retval < 1)
1252 return retval;
1254 log_debug(LD_APP|LD_CIRC,
1255 "Attaching apconn to circ %d (stream %d sec old).",
1256 circ->_base.n_circ_id, conn_age);
1257 /* here, print the circ's path. so people can figure out which circs are
1258 * sucking. */
1259 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1261 /* We have found a suitable circuit for our conn. Hurray. */
1262 return connection_ap_handshake_attach_chosen_circuit(conn, circ);
1264 } else { /* we're a rendezvous conn */
1265 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
1267 tor_assert(!conn->cpath_layer);
1269 /* start by finding a rendezvous circuit for us */
1271 retval = circuit_get_open_circ_or_launch(
1272 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1273 if (retval < 0) return -1; /* failed */
1275 if (retval > 0) {
1276 tor_assert(rendcirc);
1277 /* one is already established, attach */
1278 log_info(LD_REND,
1279 "rend joined circ %d already here. attaching. "
1280 "(stream %d sec old)",
1281 rendcirc->_base.n_circ_id, conn_age);
1282 /* Mark rendezvous circuits as 'newly dirty' every time you use
1283 * them, since the process of rebuilding a rendezvous circ is so
1284 * expensive. There is a tradeoffs between linkability and
1285 * feasibility, at this point.
1287 rendcirc->_base.timestamp_dirty = time(NULL);
1288 link_apconn_to_circ(conn, rendcirc);
1289 if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
1290 return 0; /* already marked, let them fade away */
1291 return 1;
1294 if (rendcirc && (rendcirc->_base.purpose ==
1295 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
1296 log_info(LD_REND,
1297 "pending-join circ %d already here, with intro ack. "
1298 "Stalling. (stream %d sec old)",
1299 rendcirc->_base.n_circ_id, conn_age);
1300 return 0;
1303 /* it's on its way. find an intro circ. */
1304 retval = circuit_get_open_circ_or_launch(
1305 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1306 if (retval < 0) return -1; /* failed */
1308 if (retval > 0) {
1309 /* one has already sent the intro. keep waiting. */
1310 tor_assert(introcirc);
1311 log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
1312 "Stalling. (stream %d sec old)",
1313 introcirc->_base.n_circ_id,
1314 rendcirc ? rendcirc->_base.n_circ_id : 0,
1315 conn_age);
1316 return 0;
1319 /* now rendcirc and introcirc are each either undefined or not finished */
1321 if (rendcirc && introcirc &&
1322 rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1323 log_info(LD_REND,
1324 "ready rend circ %d already here (no intro-ack yet on "
1325 "intro %d). (stream %d sec old)",
1326 rendcirc->_base.n_circ_id,
1327 introcirc->_base.n_circ_id, conn_age);
1329 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1330 if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
1331 log_info(LD_REND,"found open intro circ %d (rend %d); sending "
1332 "introduction. (stream %d sec old)",
1333 introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
1334 conn_age);
1335 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1336 return -1;
1338 rendcirc->_base.timestamp_dirty = time(NULL);
1339 introcirc->_base.timestamp_dirty = time(NULL);
1340 assert_circuit_ok(TO_CIRCUIT(rendcirc));
1341 assert_circuit_ok(TO_CIRCUIT(introcirc));
1342 return 0;
1346 log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
1347 "Stalling conn. (%d sec old)",
1348 introcirc ? introcirc->_base.n_circ_id : 0,
1349 rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
1350 return 0;