Forward port changelog
[tor.git] / src / or / circuituse.c
blob0cf3651d7ed9d0e4d1f441a7628661233d9f677f
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char circuituse_c_id[] = "$Id$";
8 /**
9 * \file circuituse.c
10 * \brief Launch the right sort of circuits, attach streams to them.
11 **/
13 #include "or.h"
15 /** Longest time to wait for a circuit before closing an AP connection */
16 #define CONN_AP_MAX_ATTACH_DELAY 59
18 /********* START VARIABLES **********/
20 extern circuit_t *global_circuitlist; /* from circuitlist.c */
21 extern int has_fetched_directory; /* from main.c */
23 /********* END VARIABLES ************/
25 static void circuit_expire_old_circuits(void);
26 static void circuit_increment_failure_count(void);
28 /* Return 1 if <b>circ</b> could be returned by circuit_get_best().
29 * Else return 0.
31 static int circuit_is_acceptable(circuit_t *circ,
32 connection_t *conn,
33 int must_be_open,
34 uint8_t purpose,
35 time_t now)
37 routerinfo_t *exitrouter;
38 tor_assert(circ);
39 tor_assert(conn);
40 tor_assert(conn->socks_request);
42 if (!CIRCUIT_IS_ORIGIN(circ))
43 return 0; /* this circ doesn't start at us */
44 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
45 return 0; /* ignore non-open circs */
46 if (circ->marked_for_close)
47 return 0;
49 /* if this circ isn't our purpose, skip. */
50 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
51 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
52 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
53 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
54 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
55 return 0;
56 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT && !must_be_open) {
57 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
58 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
59 return 0;
60 } else {
61 if (purpose != circ->purpose)
62 return 0;
65 if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
66 if (circ->timestamp_dirty &&
67 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
68 return 0;
70 /* decide if this circ is suitable for this conn */
72 /* for rend circs, circ->cpath->prev is not the last router in the
73 * circuit, it's the magical extra bob hop. so just check the nickname
74 * of the one we meant to finish at.
76 exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
78 if (!exitrouter) {
79 log_fn(LOG_INFO,"Skipping broken circ (exit router vanished)");
80 return 0; /* this circuit is screwed and doesn't know it yet */
83 if (!circ->build_state->need_uptime &&
84 smartlist_string_num_isin(get_options()->LongLivedPorts,
85 conn->socks_request->port))
86 return 0;
88 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
89 if (!connection_ap_can_use_exit(conn, exitrouter)) {
90 /* can't exit from this router */
91 return 0;
93 } else { /* not general */
94 if (rend_cmp_service_ids(conn->rend_query, circ->rend_query)) {
95 /* this circ is not for this conn */
96 return 0;
99 return 1;
102 /* Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
103 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
105 static int circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
107 switch (purpose) {
108 case CIRCUIT_PURPOSE_C_GENERAL:
109 /* if it's used but less dirty it's best;
110 * else if it's more recently created it's best
112 if (b->timestamp_dirty) {
113 if (a->timestamp_dirty &&
114 a->timestamp_dirty > b->timestamp_dirty)
115 return 1;
116 } else {
117 if (a->timestamp_dirty ||
118 b->build_state->is_internal ||
119 a->timestamp_created > b->timestamp_created)
120 return 1;
122 break;
123 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
124 /* the closer it is to ack_wait the better it is */
125 if (a->purpose > b->purpose)
126 return 1;
127 break;
128 case CIRCUIT_PURPOSE_C_REND_JOINED:
129 /* the closer it is to rend_joined the better it is */
130 if (a->purpose > b->purpose)
131 return 1;
132 break;
134 return 0;
137 /** Find the best circ that conn can use, preferably one which is
138 * dirty. Circ must not be too old.
140 * Conn must be defined.
142 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
144 * circ_purpose specifies what sort of circuit we must have.
145 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
147 * If it's REND_JOINED and must_be_open==0, then return the closest
148 * rendezvous-purposed circuit that you can find.
150 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
151 * closest introduce-purposed circuit that you can find.
153 static circuit_t *
154 circuit_get_best(connection_t *conn, int must_be_open, uint8_t purpose)
156 circuit_t *circ, *best=NULL;
157 time_t now = time(NULL);
159 tor_assert(conn);
161 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
162 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
163 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
165 for (circ=global_circuitlist;circ;circ = circ->next) {
166 if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,now))
167 continue;
169 /* now this is an acceptable circ to hand back. but that doesn't
170 * mean it's the *best* circ to hand back. try to decide.
172 if (!best || circuit_is_better(circ,best,purpose))
173 best = circ;
176 return best;
179 /** If we find a circuit that isn't open yet and was born this many
180 * seconds ago, then assume something went wrong, and cull it.
182 #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 30
184 /** Close all circuits that start at us, aren't open, and were born
185 * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago.
187 void circuit_expire_building(time_t now) {
188 circuit_t *victim, *circ = global_circuitlist;
190 while (circ) {
191 victim = circ;
192 circ = circ->next;
193 if (!CIRCUIT_IS_ORIGIN(victim))
194 continue; /* didn't originate here */
195 if (victim->marked_for_close)
196 continue; /* don't mess with marked circs */
197 if (victim->timestamp_created + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)
198 continue; /* it's young still, don't mess with it */
200 #if 0
201 /* some debug logs, to help track bugs */
202 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
203 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
204 if (!victim->timestamp_dirty)
205 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). (clean).",
206 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
207 victim->purpose, victim->build_state->chosen_exit_name,
208 victim->n_circ_id);
209 else
210 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). %d secs since dirty.",
211 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
212 victim->purpose, victim->build_state->chosen_exit_name,
213 victim->n_circ_id,
214 (int)(now - victim->timestamp_dirty));
216 #endif
218 /* if circ is !open, or if it's open but purpose is a non-finished
219 * intro or rend, then mark it for close */
220 if (victim->state != CIRCUIT_STATE_OPEN ||
221 victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
222 victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
223 victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
225 /* it's a rend_ready circ, but it's already picked a query */
226 (victim->purpose == CIRCUIT_PURPOSE_C_REND_READY &&
227 victim->rend_query[0]) ||
229 /* c_rend_ready circs measure age since timestamp_dirty,
230 * because that's set when they switch purposes
232 /* rend and intro circs become dirty each time they
233 * make an introduction attempt. so timestamp_dirty
234 * will reflect the time since the last attempt.
236 ((victim->purpose == CIRCUIT_PURPOSE_C_REND_READY ||
237 victim->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED ||
238 victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
239 victim->timestamp_dirty + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)) {
240 if (victim->n_conn)
241 log_fn(LOG_INFO,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
242 victim->n_conn->address, victim->n_port, victim->n_circ_id,
243 victim->state, circuit_state_to_string[victim->state], victim->purpose);
244 else
245 log_fn(LOG_INFO,"Abandoning circ %d (state %d:%s, purpose %d)", victim->n_circ_id,
246 victim->state, circuit_state_to_string[victim->state], victim->purpose);
247 circuit_log_path(LOG_INFO,victim);
248 circuit_mark_for_close(victim);
253 /** Remove any elements in <b>needed_ports</b> that are handled by an
254 * open or in-progress circuit.
256 void
257 circuit_remove_handled_ports(smartlist_t *needed_ports) {
258 int i;
259 uint16_t *port;
261 for (i = 0; i < smartlist_len(needed_ports); ++i) {
262 port = smartlist_get(needed_ports, i);
263 tor_assert(*port);
264 if (circuit_stream_is_being_handled(NULL, *port, 2)) {
265 // log_fn(LOG_DEBUG,"Port %d is already being handled; removing.", port);
266 smartlist_del(needed_ports, i--);
267 tor_free(port);
268 } else {
269 log_fn(LOG_DEBUG,"Port %d is not handled.", *port);
274 /** Return 1 if at least <b>min</b> general-purpose circuits will have
275 * an acceptable exit node for conn if conn is defined, else for "*:port".
276 * Else return 0.
278 int circuit_stream_is_being_handled(connection_t *conn, uint16_t port, int min) {
279 circuit_t *circ;
280 routerinfo_t *exitrouter;
281 int num=0;
282 time_t now = time(NULL);
283 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
284 conn ? conn->socks_request->port : port);
286 for (circ=global_circuitlist;circ;circ = circ->next) {
287 if (CIRCUIT_IS_ORIGIN(circ) &&
288 !circ->marked_for_close &&
289 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
290 (!circ->timestamp_dirty ||
291 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now)) {
292 exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
293 if (exitrouter &&
294 (!need_uptime || circ->build_state->need_uptime) &&
295 ((conn && connection_ap_can_use_exit(conn, exitrouter)) ||
296 (!conn &&
297 router_compare_addr_to_addr_policy(0, port, exitrouter->exit_policy) !=
298 ADDR_POLICY_REJECTED))) {
299 if (++num >= min)
300 return 1;
304 return 0;
307 /** Don't keep more than 10 unused open circuits around. */
308 #define MAX_UNUSED_OPEN_CIRCUITS 10
310 /** Figure out how many circuits we have open that are clean. Make
311 * sure it's enough for all the upcoming behaviors we predict we'll have.
312 * But if we have too many, close the not-so-useful ones.
314 static void
315 circuit_predict_and_launch_new(void)
317 circuit_t *circ;
318 int num=0, num_internal=0, num_uptime_internal=0;
319 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
320 int port_needs_uptime=0, port_needs_capacity=1;
321 int need_ports, need_hidserv;
322 time_t now = time(NULL);
324 /* check if we know of a port that's been requested recently
325 * and no circuit is currently available that can handle it. */
326 need_ports = !circuit_all_predicted_ports_handled(now, &port_needs_uptime,
327 &port_needs_capacity);
329 need_hidserv = rep_hist_get_predicted_hidserv(now, &hidserv_needs_uptime,
330 &hidserv_needs_capacity);
332 for (circ=global_circuitlist;circ;circ = circ->next) {
333 if (!CIRCUIT_IS_ORIGIN(circ))
334 continue;
335 if (circ->marked_for_close)
336 continue; /* don't mess with marked circs */
337 if (circ->timestamp_dirty)
338 continue; /* only count clean circs */
339 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
340 continue; /* only pay attention to general-purpose circs */
341 num++;
342 if (circ->build_state->is_internal)
343 num_internal++;
344 if (circ->build_state->need_uptime && circ->build_state->is_internal)
345 num_uptime_internal++;
348 if (num < MAX_UNUSED_OPEN_CIRCUITS) {
349 /* perhaps we want another */
350 if (need_ports) {
351 log_fn(LOG_INFO,"Have %d clean circs (%d internal), need another exit circ.",
352 num, num_internal);
353 circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL,
354 port_needs_uptime, port_needs_capacity, 0);
355 } else if (need_hidserv &&
356 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
357 num_internal<2)) {
358 log_fn(LOG_INFO,"Have %d clean circs (%d uptime-internal, %d internal),"
359 " need another hidserv circ.", num, num_uptime_internal, num_internal);
360 circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL,
361 hidserv_needs_uptime, hidserv_needs_capacity, 1);
366 /** Build a new test circuit every 5 minutes */
367 #define TESTING_CIRCUIT_INTERVAL 300
369 /** This function is called once a second. Its job is to make sure
370 * all services we offer have enough circuits available. Some
371 * services just want enough circuits for current tasks, whereas
372 * others want a minimum set of idle circuits hanging around.
374 void circuit_build_needed_circs(time_t now) {
375 static long time_to_new_circuit = 0;
377 /* launch a new circ for any pending streams that need one */
378 connection_ap_attach_pending();
380 /* make sure any hidden services have enough intro points */
381 if (has_fetched_directory)
382 rend_services_introduce();
384 if (time_to_new_circuit < now) {
385 circuit_reset_failure_count(1);
386 time_to_new_circuit = now + get_options()->NewCircuitPeriod;
387 if (proxy_mode(get_options()))
388 client_dns_clean();
389 circuit_expire_old_circuits();
391 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
392 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
393 if (get_options()->RunTesting &&
394 circ &&
395 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
396 log_fn(LOG_INFO,"Creating a new testing circuit.");
397 circuit_launch_by_identity(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0, 0, 0);
399 #endif
401 circuit_predict_and_launch_new();
404 /** If the stream <b>conn</b> is a member of any of the linked
405 * lists of <b>circ</b>, then remove it from the list.
407 void circuit_detach_stream(circuit_t *circ, connection_t *conn) {
408 connection_t *prevconn;
410 tor_assert(circ);
411 tor_assert(conn);
413 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
415 if (conn == circ->p_streams) {
416 circ->p_streams = conn->next_stream;
417 return;
419 if (conn == circ->n_streams) {
420 circ->n_streams = conn->next_stream;
421 return;
423 if (conn == circ->resolving_streams) {
424 circ->resolving_streams = conn->next_stream;
425 return;
428 for (prevconn = circ->p_streams;
429 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
430 prevconn = prevconn->next_stream)
432 if (prevconn && prevconn->next_stream) {
433 prevconn->next_stream = conn->next_stream;
434 return;
437 for (prevconn = circ->n_streams;
438 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
439 prevconn = prevconn->next_stream)
441 if (prevconn && prevconn->next_stream) {
442 prevconn->next_stream = conn->next_stream;
443 return;
446 for (prevconn = circ->resolving_streams;
447 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
448 prevconn = prevconn->next_stream)
450 if (prevconn && prevconn->next_stream) {
451 prevconn->next_stream = conn->next_stream;
452 return;
455 log_fn(LOG_ERR,"edge conn not in circuit's list?");
456 tor_assert(0); /* should never get here */
459 /** Notify the global circuit list that <b>conn</b> is about to be
460 * removed and then freed.
462 * If it's an OR conn, then mark-for-close all the circuits that use
463 * that conn.
465 * If it's an edge conn, then detach it from its circ, so we don't
466 * try to reference it later.
468 void circuit_about_to_close_connection(connection_t *conn) {
469 /* currently, we assume it's too late to flush conn's buf here.
470 * down the road, maybe we'll consider that eof doesn't mean can't-write
472 circuit_t *circ;
474 switch (conn->type) {
475 case CONN_TYPE_OR:
476 if (conn->state != OR_CONN_STATE_OPEN) {
477 /* Inform any pending (not attached) circs that they should give up. */
478 circuit_n_conn_done(conn, 0);
480 /* Now close all the attached circuits on it. */
481 while ((circ = circuit_get_by_conn(conn))) {
482 if (circ->n_conn == conn) /* it's closing in front of us */
483 circ->n_conn = NULL;
484 if (circ->p_conn == conn) /* it's closing behind us */
485 circ->p_conn = NULL;
486 circuit_mark_for_close(circ);
488 return;
489 case CONN_TYPE_AP:
490 case CONN_TYPE_EXIT:
492 /* It's an edge conn. Need to remove it from the linked list of
493 * conn's for this circuit. Confirm that 'end' relay command has
494 * been sent. But don't kill the circuit.
497 circ = circuit_get_by_conn(conn);
498 if (!circ)
499 return;
501 circuit_detach_stream(circ, conn);
503 } /* end switch */
506 /** Find each circuit that has been dirty for too long, and has
507 * no streams on it: mark it for close.
509 static void
510 circuit_expire_old_circuits(void)
512 circuit_t *circ;
513 time_t now = time(NULL);
515 for (circ = global_circuitlist; circ; circ = circ->next) {
516 if (circ->marked_for_close)
517 continue;
518 /* If the circuit has been dirty for too long, and there are no streams
519 * on it, mark it for close.
521 if (circ->timestamp_dirty &&
522 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
523 CIRCUIT_IS_ORIGIN(circ) &&
524 !circ->p_streams /* nothing attached */ ) {
525 log_fn(LOG_DEBUG,"Closing n_circ_id %d (dirty %d secs ago, purp %d)",circ->n_circ_id,
526 (int)(now - circ->timestamp_dirty), circ->purpose);
527 /* (only general and purpose_c circs can get dirty) */
528 tor_assert(!circ->n_streams);
529 tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
530 circuit_mark_for_close(circ);
531 } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
532 circ->state == CIRCUIT_STATE_OPEN &&
533 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
534 #define CIRCUIT_UNUSED_CIRC_TIMEOUT 3600 /* an hour */
535 if (circ->timestamp_created + CIRCUIT_UNUSED_CIRC_TIMEOUT < now) {
536 log_fn(LOG_DEBUG,"Closing circuit that has been unused for %d seconds.",
537 (int)(now - circ->timestamp_created));
538 circuit_mark_for_close(circ);
544 /** The circuit <b>circ</b> has just become open. Take the next
545 * step: for rendezvous circuits, we pass circ to the appropriate
546 * function in rendclient or rendservice. For general circuits, we
547 * call connection_ap_attach_pending, which looks for pending streams
548 * that could use circ.
550 void circuit_has_opened(circuit_t *circ) {
552 control_event_circuit_status(circ, CIRC_EVENT_BUILT);
554 switch (circ->purpose) {
555 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
556 rend_client_rendcirc_has_opened(circ);
557 connection_ap_attach_pending();
558 break;
559 case CIRCUIT_PURPOSE_C_INTRODUCING:
560 rend_client_introcirc_has_opened(circ);
561 break;
562 case CIRCUIT_PURPOSE_C_GENERAL:
563 /* Tell any AP connections that have been waiting for a new
564 * circuit that one is ready. */
565 connection_ap_attach_pending();
566 break;
567 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
568 /* at Bob, waiting for introductions */
569 rend_service_intro_has_opened(circ);
570 break;
571 case CIRCUIT_PURPOSE_S_CONNECT_REND:
572 /* at Bob, connecting to rend point */
573 rend_service_rendezvous_has_opened(circ);
574 break;
575 default:
576 log_fn(LOG_ERR,"unhandled purpose %d",circ->purpose);
577 tor_assert(0);
581 /*~ Called whenever a circuit could not be successfully built.
583 void circuit_build_failed(circuit_t *circ) {
585 /* we should examine circ and see if it failed because of
586 * the last hop or an earlier hop. then use this info below.
588 int failed_at_last_hop = 0;
589 /* If the last hop isn't open, and the second-to-last is, we failed
590 * at the last hop. */
591 if (circ->cpath &&
592 circ->cpath->prev->state != CPATH_STATE_OPEN &&
593 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
594 failed_at_last_hop = 1;
597 switch (circ->purpose) {
598 case CIRCUIT_PURPOSE_C_GENERAL:
599 if (circ->state != CIRCUIT_STATE_OPEN) {
600 /* If we never built the circuit, note it as a failure. */
601 /* Note that we can't just check circ->cpath here, because if
602 * circuit-building failed immediately, it won't be set yet. */
603 circuit_increment_failure_count();
605 break;
606 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
607 /* at Bob, waiting for introductions */
608 if (circ->state != CIRCUIT_STATE_OPEN) {
609 circuit_increment_failure_count();
611 /* no need to care here, because bob will rebuild intro
612 * points periodically. */
613 break;
614 case CIRCUIT_PURPOSE_C_INTRODUCING:
615 /* at Alice, connecting to intro point */
616 /* Don't increment failure count, since Bob may have picked
617 * the introduction point maliciously */
618 /* Alice will pick a new intro point when this one dies, if
619 * the stream in question still cares. No need to act here. */
620 break;
621 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
622 /* at Alice, waiting for Bob */
623 if (circ->state != CIRCUIT_STATE_OPEN) {
624 circuit_increment_failure_count();
626 /* Alice will pick a new rend point when this one dies, if
627 * the stream in question still cares. No need to act here. */
628 break;
629 case CIRCUIT_PURPOSE_S_CONNECT_REND:
630 /* at Bob, connecting to rend point */
631 /* Don't increment failure count, since Alice may have picked
632 * the rendezvous point maliciously */
633 if (failed_at_last_hop) {
634 log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s. Sucks to be Alice.", circ->build_state->chosen_exit_name);
635 } else {
636 log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s, because an earlier node failed.",
637 circ->build_state->chosen_exit_name);
638 rend_service_relaunch_rendezvous(circ);
640 break;
641 default:
642 /* Other cases are impossible, since this function is only called with
643 * unbuilt circuits. */
644 tor_assert(0);
648 /** Number of consecutive failures so far; should only be touched by
649 * circuit_launch_new and circuit_*_failure_count.
651 static int n_circuit_failures = 0;
652 static int did_circs_fail_last_period = 0;
654 /** Don't retry launching a new circuit if we try this many times with no
655 * success. */
656 #define MAX_CIRCUIT_FAILURES 5
658 circuit_t *
659 circuit_launch_by_identity(uint8_t purpose, const char *exit_digest,
660 int need_uptime, int need_capacity, int internal)
662 circuit_t *circ;
664 if (!has_fetched_directory) {
665 log_fn(LOG_DEBUG,"Haven't fetched directory yet; canceling circuit launch.");
666 return NULL;
669 if (purpose != CIRCUIT_PURPOSE_C_GENERAL) {
670 /* see if there are appropriate circs available to cannibalize. */
671 if ((circ = circuit_get_clean_open(CIRCUIT_PURPOSE_C_GENERAL, need_uptime,
672 need_capacity, internal))) {
673 log_fn(LOG_INFO,"Cannibalizing circ '%s' for purpose %d",
674 circ->build_state->chosen_exit_name, purpose);
675 circ->purpose = purpose;
676 /* reset the birth date of this circ, else expire_building
677 * will see it and think it's been trying to build since it
678 * began. */
679 circ->timestamp_created = time(NULL);
680 switch (purpose) {
681 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
682 /* it's ready right now */
683 /* XXX should we call control_event_circuit_status() here? */
684 rend_client_rendcirc_has_opened(circ);
685 break;
686 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
687 /* it's ready right now */
688 rend_service_intro_has_opened(circ);
689 break;
690 case CIRCUIT_PURPOSE_C_INTRODUCING:
691 case CIRCUIT_PURPOSE_S_CONNECT_REND:
692 /* need to add a new hop */
693 tor_assert(exit_digest);
694 if (circuit_append_new_hop(circ, NULL, exit_digest) < 0)
695 return NULL;
696 break;
697 default:
698 log_fn(LOG_WARN,"Bug: unexpected purpose %d when cannibalizing a general circ.",
699 purpose);
700 #ifdef TOR_FRAGILE
701 tor_assert(0);
702 #endif
703 return NULL;
705 return circ;
709 if (did_circs_fail_last_period &&
710 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
711 /* too many failed circs in a row. don't try. */
712 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
713 return NULL;
716 /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
717 return circuit_establish_circuit(purpose, exit_digest,
718 need_uptime, need_capacity, internal);
721 /** Launch a new circuit and return a pointer to it. Return NULL if you failed. */
722 circuit_t *
723 circuit_launch_by_nickname(uint8_t purpose, const char *exit_nickname,
724 int need_uptime, int need_capacity, int internal)
726 const char *digest = NULL;
728 if (exit_nickname) {
729 routerinfo_t *r = router_get_by_nickname(exit_nickname);
730 if (!r) {
731 log_fn(LOG_WARN, "No such OR as '%s'", exit_nickname);
732 return NULL;
734 digest = r->identity_digest;
736 return circuit_launch_by_identity(purpose, digest,
737 need_uptime, need_capacity, internal);
740 /** Record another failure at opening a general circuit. When we have
741 * too many, we'll stop trying for the remainder of this minute.
743 static void circuit_increment_failure_count(void) {
744 ++n_circuit_failures;
745 log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
748 /** Reset the failure count for opening general circuits. This means
749 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
750 * stopping again.
752 void circuit_reset_failure_count(int timeout) {
753 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
754 did_circs_fail_last_period = 1;
755 else
756 did_circs_fail_last_period = 0;
757 n_circuit_failures = 0;
760 /** Find an open circ that we're happy with: return 1. If there isn't
761 * one, and there isn't one on the way, launch one and return 0. If it
762 * will never work, return -1.
764 * Write the found or in-progress or launched circ into *circp.
766 static int
767 circuit_get_open_circ_or_launch(connection_t *conn,
768 uint8_t desired_circuit_purpose,
769 circuit_t **circp) {
770 circuit_t *circ;
771 uint32_t addr;
772 int is_resolve;
773 int need_uptime;
775 tor_assert(conn);
776 tor_assert(circp);
777 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
778 is_resolve = conn->socks_request->command == SOCKS_COMMAND_RESOLVE;
780 circ = circuit_get_best(conn, 1, desired_circuit_purpose);
782 if (circ) {
783 *circp = circ;
784 return 1; /* we're happy */
787 if (!has_fetched_directory) {
788 if (!connection_get_by_type(CONN_TYPE_DIR)) {
789 log_fn(LOG_NOTICE,"Application request when we're believed to be offline. Optimistically trying again.");
790 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
792 /* the stream will be dealt with when has_fetched_directory becomes
793 * 1, or when all directory attempts fail and directory_all_unreachable()
794 * kills it.
796 return 0;
799 need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
800 conn->socks_request->port);
802 /* Do we need to check exit policy? */
803 if (!is_resolve && !connection_edge_is_rendezvous_stream(conn)) {
804 addr = client_dns_lookup_entry(conn->socks_request->address);
805 if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port,
806 need_uptime)) {
807 log_fn(LOG_NOTICE,"No Tor server exists that allows exit to %s:%d. Rejecting.",
808 conn->socks_request->address, conn->socks_request->port);
809 return -1;
813 /* is one already on the way? */
814 circ = circuit_get_best(conn, 0, desired_circuit_purpose);
815 if (!circ) {
816 char *exitname=NULL;
817 uint8_t new_circ_purpose;
818 int is_internal;
820 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
821 /* need to pick an intro point */
822 try_an_intro_point:
823 exitname = rend_client_get_random_intro(conn->rend_query);
824 if (!exitname) {
825 log_fn(LOG_INFO,"No intro points for '%s': refetching service descriptor.",
826 conn->rend_query);
827 rend_client_refetch_renddesc(conn->rend_query);
828 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
829 return 0;
831 if (!router_get_by_nickname(exitname)) {
832 log_fn(LOG_NOTICE,"Advertised intro point '%s' is not recognized for '%s'. Skipping over.",
833 exitname, conn->rend_query);
834 rend_client_remove_intro_point(exitname, conn->rend_query);
835 tor_free(exitname);
836 goto try_an_intro_point;
838 log_fn(LOG_INFO,"Chose %s as intro point for %s.", exitname, conn->rend_query);
841 /* If we have specified a particular exit node for our
842 * connection, then be sure to open a circuit to that exit node.
844 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
845 if (conn->chosen_exit_name) {
846 exitname = tor_strdup(conn->chosen_exit_name);
847 if (!router_get_by_nickname(exitname)) {
848 log_fn(LOG_NOTICE,"Requested exit point '%s' is not known. Closing.", exitname);
849 tor_free(exitname);
850 return -1;
855 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
856 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
857 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
858 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
859 else
860 new_circ_purpose = desired_circuit_purpose;
862 is_internal = (new_circ_purpose != CIRCUIT_PURPOSE_C_GENERAL || is_resolve);
863 circ = circuit_launch_by_nickname(new_circ_purpose, exitname, need_uptime,
864 1, is_internal);
865 tor_free(exitname);
867 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
868 /* help predict this next time */
869 rep_hist_note_used_hidserv(time(NULL), need_uptime, 1);
870 if (circ) {
871 /* write the service_id into circ */
872 strlcpy(circ->rend_query, conn->rend_query, sizeof(circ->rend_query));
876 if (!circ)
877 log_fn(LOG_INFO,"No safe circuit (purpose %d) ready for edge connection; delaying.",
878 desired_circuit_purpose);
879 *circp = circ;
880 return 0;
883 /** Attach the AP stream <b>apconn</b> to circ's linked list of
884 * p_streams. Also set apconn's cpath_layer to the last hop in
885 * circ's cpath.
887 static void link_apconn_to_circ(connection_t *apconn, circuit_t *circ) {
888 /* add it into the linked list of streams on this circuit */
889 log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
890 apconn->timestamp_lastread = time(NULL); /* reset it, so we can measure circ timeouts */
891 apconn->next_stream = circ->p_streams;
892 /* assert_connection_ok(conn, time(NULL)); */
893 circ->p_streams = apconn;
895 tor_assert(CIRCUIT_IS_ORIGIN(circ));
896 tor_assert(circ->cpath);
897 tor_assert(circ->cpath->prev);
898 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
899 apconn->cpath_layer = circ->cpath->prev;
902 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
903 * we don't find one: if conn cannot be handled by any known nodes,
904 * warn and return -1 (conn needs to die);
905 * else launch new circuit (if necessary) and return 0.
906 * Otherwise, associate conn with a safe live circuit, do the
907 * right next step, and return 1.
909 int connection_ap_handshake_attach_circuit(connection_t *conn) {
910 int retval;
911 int conn_age;
913 tor_assert(conn);
914 tor_assert(conn->type == CONN_TYPE_AP);
915 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
916 tor_assert(conn->socks_request);
918 conn_age = time(NULL) - conn->timestamp_created;
919 if (conn_age > CONN_AP_MAX_ATTACH_DELAY) {
920 log_fn(LOG_NOTICE,"Giving up on unattached conn (%d sec old).", conn_age);
921 return -1;
924 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
925 circuit_t *circ=NULL;
927 if (conn->chosen_exit_name) {
928 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name);
929 if (!router) {
930 log_fn(LOG_WARN,"Requested exit point '%s' is not known. Closing.",
931 conn->chosen_exit_name);
932 return -1;
934 if (!connection_ap_can_use_exit(conn, router)) {
935 log_fn(LOG_WARN, "Requested exit point '%s' would refuse request. Closing.",
936 conn->chosen_exit_name);
937 return -1;
941 /* find the circuit that we should use, if there is one. */
942 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
943 if (retval < 1)
944 return retval;
946 /* We have found a suitable circuit for our conn. Hurray. */
947 tor_assert(circ);
949 log_fn(LOG_DEBUG,"Attaching apconn to general circ %d (stream %d sec old).",
950 circ->n_circ_id, conn_age);
951 /* here, print the circ's path. so people can figure out which circs are sucking. */
952 circuit_log_path(LOG_INFO,circ);
954 if (!circ->timestamp_dirty)
955 circ->timestamp_dirty = time(NULL);
957 link_apconn_to_circ(conn, circ);
958 tor_assert(conn->socks_request);
959 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
960 // consider_recording_trackhost(conn, circ);
961 connection_ap_handshake_send_begin(conn, circ);
962 } else {
963 connection_ap_handshake_send_resolve(conn, circ);
966 return 1;
967 } else { /* we're a rendezvous conn */
968 circuit_t *rendcirc=NULL, *introcirc=NULL;
970 tor_assert(!conn->cpath_layer);
972 /* start by finding a rendezvous circuit for us */
974 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
975 if (retval < 0) return -1; /* failed */
977 if (retval > 0) {
978 tor_assert(rendcirc);
979 /* one is already established, attach */
980 log_fn(LOG_INFO,"rend joined circ %d already here. attaching. (stream %d sec old)",
981 rendcirc->n_circ_id, conn_age);
982 /* Mark rendezvous circuits as 'newly dirty' every time you use
983 * them, since the process of rebuilding a rendezvous circ is so
984 * expensive. There is a tradeoffs between linkability and
985 * feasibility, at this point.
987 rendcirc->timestamp_dirty = time(NULL);
988 link_apconn_to_circ(conn, rendcirc);
989 if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
990 return 0; /* already marked, let them fade away */
991 return 1;
994 if (rendcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
995 log_fn(LOG_INFO,"pending-join circ %d already here, with intro ack. Stalling. (stream %d sec old)", rendcirc->n_circ_id, conn_age);
996 return 0;
999 /* it's on its way. find an intro circ. */
1000 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1001 if (retval < 0) return -1; /* failed */
1003 if (retval > 0) {
1004 /* one has already sent the intro. keep waiting. */
1005 tor_assert(introcirc);
1006 log_fn(LOG_INFO,"Intro circ %d present and awaiting ack (rend %d). Stalling. (stream %d sec old)",
1007 introcirc->n_circ_id, rendcirc ? rendcirc->n_circ_id : 0, conn_age);
1008 return 0;
1011 /* now rendcirc and introcirc are each either undefined or not finished */
1013 if (rendcirc && introcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1014 log_fn(LOG_INFO,"ready rend circ %d already here (no intro-ack yet on intro %d). (stream %d sec old)",
1015 rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
1017 tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1018 if (introcirc->state == CIRCUIT_STATE_OPEN) {
1019 log_fn(LOG_INFO,"found open intro circ %d (rend %d); sending introduction. (stream %d sec old)",
1020 introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
1021 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1022 return -1;
1024 rendcirc->timestamp_dirty = time(NULL);
1025 introcirc->timestamp_dirty = time(NULL);
1026 assert_circuit_ok(rendcirc);
1027 assert_circuit_ok(introcirc);
1028 return 0;
1032 log_fn(LOG_INFO,"Intro (%d) and rend (%d) circs are not both ready. Stalling conn. (%d sec old)",
1033 introcirc ? introcirc->n_circ_id : 0,
1034 rendcirc ? rendcirc->n_circ_id : 0, conn_age);
1035 return 0;