re-enable reachability testing stuff.
[tor.git] / src / or / circuituse.c
blob7eb5f597c4a8212fba03bf4ca29eadfb30d70337
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 addressmap_clean(now);
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 /** A testing circuit has completed. Take whatever stats we want. */
545 static void
546 circuit_testing_opened(circuit_t *circ) {
547 /* For now, we only use testing circuits to see if our ORPort is
548 reachable. But we remember reachability in onionskin_answer(),
549 so there's no need to record anything here. Just close the circ. */
550 circuit_mark_for_close(circ);
553 /** A testing circuit has failed to build. Take whatever stats we want. */
554 static void
555 circuit_testing_failed(circuit_t *circ, int at_last_hop) {
556 routerinfo_t *me = router_get_my_routerinfo();
558 if (!at_last_hop)
559 circuit_launch_by_identity(CIRCUIT_PURPOSE_TESTING, me->identity_digest, 0, 0, 1);
560 else
561 log_fn(LOG_INFO,"Our testing circuit (to see if your ORPort is reachable) has failed. I'll try again later.");
564 /** The circuit <b>circ</b> has just become open. Take the next
565 * step: for rendezvous circuits, we pass circ to the appropriate
566 * function in rendclient or rendservice. For general circuits, we
567 * call connection_ap_attach_pending, which looks for pending streams
568 * that could use circ.
570 void circuit_has_opened(circuit_t *circ) {
572 control_event_circuit_status(circ, CIRC_EVENT_BUILT);
574 switch (circ->purpose) {
575 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
576 rend_client_rendcirc_has_opened(circ);
577 connection_ap_attach_pending();
578 break;
579 case CIRCUIT_PURPOSE_C_INTRODUCING:
580 rend_client_introcirc_has_opened(circ);
581 break;
582 case CIRCUIT_PURPOSE_C_GENERAL:
583 /* Tell any AP connections that have been waiting for a new
584 * circuit that one is ready. */
585 connection_ap_attach_pending();
586 break;
587 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
588 /* at Bob, waiting for introductions */
589 rend_service_intro_has_opened(circ);
590 break;
591 case CIRCUIT_PURPOSE_S_CONNECT_REND:
592 /* at Bob, connecting to rend point */
593 rend_service_rendezvous_has_opened(circ);
594 break;
595 case CIRCUIT_PURPOSE_TESTING:
596 circuit_testing_opened(circ);
597 break;
598 default:
599 log_fn(LOG_ERR,"unhandled purpose %d",circ->purpose);
600 tor_assert(0);
604 /*~ Called whenever a circuit could not be successfully built.
606 void circuit_build_failed(circuit_t *circ) {
608 /* we should examine circ and see if it failed because of
609 * the last hop or an earlier hop. then use this info below.
611 int failed_at_last_hop = 0;
612 /* If the last hop isn't open, and the second-to-last is, we failed
613 * at the last hop. */
614 if (circ->cpath &&
615 circ->cpath->prev->state != CPATH_STATE_OPEN &&
616 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
617 failed_at_last_hop = 1;
620 switch (circ->purpose) {
621 case CIRCUIT_PURPOSE_C_GENERAL:
622 if (circ->state != CIRCUIT_STATE_OPEN) {
623 /* If we never built the circuit, note it as a failure. */
624 /* Note that we can't just check circ->cpath here, because if
625 * circuit-building failed immediately, it won't be set yet. */
626 circuit_increment_failure_count();
628 break;
629 case CIRCUIT_PURPOSE_TESTING:
630 circuit_testing_failed(circ, failed_at_last_hop);
631 break;
632 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
633 /* at Bob, waiting for introductions */
634 if (circ->state != CIRCUIT_STATE_OPEN) {
635 circuit_increment_failure_count();
637 /* no need to care here, because bob will rebuild intro
638 * points periodically. */
639 break;
640 case CIRCUIT_PURPOSE_C_INTRODUCING:
641 /* at Alice, connecting to intro point */
642 /* Don't increment failure count, since Bob may have picked
643 * the introduction point maliciously */
644 /* Alice will pick a new intro point when this one dies, if
645 * the stream in question still cares. No need to act here. */
646 break;
647 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
648 /* at Alice, waiting for Bob */
649 if (circ->state != CIRCUIT_STATE_OPEN) {
650 circuit_increment_failure_count();
652 /* Alice will pick a new rend point when this one dies, if
653 * the stream in question still cares. No need to act here. */
654 break;
655 case CIRCUIT_PURPOSE_S_CONNECT_REND:
656 /* at Bob, connecting to rend point */
657 /* Don't increment failure count, since Alice may have picked
658 * the rendezvous point maliciously */
659 if (failed_at_last_hop) {
660 log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s. Sucks to be Alice.", circ->build_state->chosen_exit_name);
661 } else {
662 log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s, because an earlier node failed.",
663 circ->build_state->chosen_exit_name);
664 rend_service_relaunch_rendezvous(circ);
666 break;
667 default:
668 /* Other cases are impossible, since this function is only called with
669 * unbuilt circuits. */
670 tor_assert(0);
674 /** Number of consecutive failures so far; should only be touched by
675 * circuit_launch_new and circuit_*_failure_count.
677 static int n_circuit_failures = 0;
678 static int did_circs_fail_last_period = 0;
680 /** Don't retry launching a new circuit if we try this many times with no
681 * success. */
682 #define MAX_CIRCUIT_FAILURES 5
684 circuit_t *
685 circuit_launch_by_identity(uint8_t purpose, const char *exit_digest,
686 int need_uptime, int need_capacity, int internal)
688 circuit_t *circ;
690 if (!has_fetched_directory) {
691 log_fn(LOG_DEBUG,"Haven't fetched directory yet; canceling circuit launch.");
692 return NULL;
695 if (purpose != CIRCUIT_PURPOSE_C_GENERAL &&
696 purpose != CIRCUIT_PURPOSE_TESTING) {
697 /* see if there are appropriate circs available to cannibalize. */
698 if ((circ = circuit_get_clean_open(CIRCUIT_PURPOSE_C_GENERAL, need_uptime,
699 need_capacity, internal))) {
700 log_fn(LOG_INFO,"Cannibalizing circ '%s' for purpose %d",
701 circ->build_state->chosen_exit_name, purpose);
702 circ->purpose = purpose;
703 /* reset the birth date of this circ, else expire_building
704 * will see it and think it's been trying to build since it
705 * began. */
706 circ->timestamp_created = time(NULL);
707 switch (purpose) {
708 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
709 /* it's ready right now */
710 /* XXX should we call control_event_circuit_status() here? */
711 rend_client_rendcirc_has_opened(circ);
712 break;
713 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
714 /* it's ready right now */
715 rend_service_intro_has_opened(circ);
716 break;
717 case CIRCUIT_PURPOSE_C_INTRODUCING:
718 case CIRCUIT_PURPOSE_S_CONNECT_REND:
719 /* need to add a new hop */
720 tor_assert(exit_digest);
721 if (circuit_append_new_hop(circ, NULL, exit_digest) < 0)
722 return NULL;
723 break;
724 default:
725 log_fn(LOG_WARN,"Bug: unexpected purpose %d when cannibalizing a general circ.",
726 purpose);
727 #ifdef TOR_FRAGILE
728 tor_assert(0);
729 #endif
730 return NULL;
732 return circ;
736 if (did_circs_fail_last_period &&
737 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
738 /* too many failed circs in a row. don't try. */
739 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
740 return NULL;
743 /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
744 return circuit_establish_circuit(purpose, exit_digest,
745 need_uptime, need_capacity, internal);
748 /** Launch a new circuit and return a pointer to it. Return NULL if you failed. */
749 circuit_t *
750 circuit_launch_by_nickname(uint8_t purpose, const char *exit_nickname,
751 int need_uptime, int need_capacity, int internal)
753 const char *digest = NULL;
755 if (exit_nickname) {
756 routerinfo_t *r = router_get_by_nickname(exit_nickname);
757 if (!r) {
758 log_fn(LOG_WARN, "No such OR as '%s'", exit_nickname);
759 return NULL;
761 digest = r->identity_digest;
763 return circuit_launch_by_identity(purpose, digest,
764 need_uptime, need_capacity, internal);
767 /** Record another failure at opening a general circuit. When we have
768 * too many, we'll stop trying for the remainder of this minute.
770 static void circuit_increment_failure_count(void) {
771 ++n_circuit_failures;
772 log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
775 /** Reset the failure count for opening general circuits. This means
776 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
777 * stopping again.
779 void circuit_reset_failure_count(int timeout) {
780 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
781 did_circs_fail_last_period = 1;
782 else
783 did_circs_fail_last_period = 0;
784 n_circuit_failures = 0;
787 /** Find an open circ that we're happy with: return 1. If there isn't
788 * one, and there isn't one on the way, launch one and return 0. If it
789 * will never work, return -1.
791 * Write the found or in-progress or launched circ into *circp.
793 static int
794 circuit_get_open_circ_or_launch(connection_t *conn,
795 uint8_t desired_circuit_purpose,
796 circuit_t **circp) {
797 circuit_t *circ;
798 int is_resolve;
799 int need_uptime;
801 tor_assert(conn);
802 tor_assert(circp);
803 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
804 is_resolve = conn->socks_request->command == SOCKS_COMMAND_RESOLVE;
806 circ = circuit_get_best(conn, 1, desired_circuit_purpose);
808 if (circ) {
809 *circp = circ;
810 return 1; /* we're happy */
813 if (!has_fetched_directory) {
814 if (!connection_get_by_type(CONN_TYPE_DIR)) {
815 log_fn(LOG_NOTICE,"Application request when we're believed to be offline. Optimistically trying again.");
816 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
818 /* the stream will be dealt with when has_fetched_directory becomes
819 * 1, or when all directory attempts fail and directory_all_unreachable()
820 * kills it.
822 return 0;
825 need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
826 conn->socks_request->port);
828 /* Do we need to check exit policy? */
829 if (!is_resolve && !connection_edge_is_rendezvous_stream(conn)) {
830 struct in_addr in;
831 uint32_t addr = 0;
832 if (tor_inet_aton(conn->socks_request->address, &in))
833 addr = ntohl(in.s_addr);
834 if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port,
835 need_uptime)) {
836 log_fn(LOG_NOTICE,"No Tor server exists that allows exit to %s:%d. Rejecting.",
837 conn->socks_request->address, conn->socks_request->port);
838 return -1;
842 /* is one already on the way? */
843 circ = circuit_get_best(conn, 0, desired_circuit_purpose);
844 if (!circ) {
845 char *exitname=NULL;
846 uint8_t new_circ_purpose;
847 int is_internal;
849 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
850 /* need to pick an intro point */
851 try_an_intro_point:
852 exitname = rend_client_get_random_intro(conn->rend_query);
853 if (!exitname) {
854 log_fn(LOG_INFO,"No intro points for '%s': refetching service descriptor.",
855 conn->rend_query);
856 rend_client_refetch_renddesc(conn->rend_query);
857 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
858 return 0;
860 if (!router_get_by_nickname(exitname)) {
861 log_fn(LOG_NOTICE,"Advertised intro point '%s' is not recognized for '%s'. Skipping over.",
862 exitname, conn->rend_query);
863 rend_client_remove_intro_point(exitname, conn->rend_query);
864 tor_free(exitname);
865 goto try_an_intro_point;
867 log_fn(LOG_INFO,"Chose %s as intro point for %s.", exitname, conn->rend_query);
870 /* If we have specified a particular exit node for our
871 * connection, then be sure to open a circuit to that exit node.
873 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
874 if (conn->chosen_exit_name) {
875 exitname = tor_strdup(conn->chosen_exit_name);
876 if (!router_get_by_nickname(exitname)) {
877 log_fn(LOG_NOTICE,"Requested exit point '%s' is not known. Closing.", exitname);
878 tor_free(exitname);
879 return -1;
884 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
885 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
886 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
887 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
888 else
889 new_circ_purpose = desired_circuit_purpose;
891 is_internal = (new_circ_purpose != CIRCUIT_PURPOSE_C_GENERAL || is_resolve);
892 circ = circuit_launch_by_nickname(new_circ_purpose, exitname, need_uptime,
893 1, is_internal);
894 tor_free(exitname);
896 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
897 /* help predict this next time */
898 rep_hist_note_used_hidserv(time(NULL), need_uptime, 1);
899 if (circ) {
900 /* write the service_id into circ */
901 strlcpy(circ->rend_query, conn->rend_query, sizeof(circ->rend_query));
905 if (!circ)
906 log_fn(LOG_INFO,"No safe circuit (purpose %d) ready for edge connection; delaying.",
907 desired_circuit_purpose);
908 *circp = circ;
909 return 0;
912 /** Attach the AP stream <b>apconn</b> to circ's linked list of
913 * p_streams. Also set apconn's cpath_layer to the last hop in
914 * circ's cpath.
916 static void link_apconn_to_circ(connection_t *apconn, circuit_t *circ) {
917 /* add it into the linked list of streams on this circuit */
918 log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
919 apconn->timestamp_lastread = time(NULL); /* reset it, so we can measure circ timeouts */
920 apconn->next_stream = circ->p_streams;
921 /* assert_connection_ok(conn, time(NULL)); */
922 circ->p_streams = apconn;
924 tor_assert(CIRCUIT_IS_ORIGIN(circ));
925 tor_assert(circ->cpath);
926 tor_assert(circ->cpath->prev);
927 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
928 apconn->cpath_layer = circ->cpath->prev;
931 /** If an exit wasn't specifically chosen, save the history for future
932 * use */
933 static void
934 consider_recording_trackhost(connection_t *conn, circuit_t *circ) {
935 int found_needle = 0;
936 char *str;
937 or_options_t *options = get_options();
938 size_t len;
939 char *new_address;
941 /* Search the addressmap for this conn's destination. */
942 /* If he's not in the address map.. */
943 if (!options->TrackHostExits ||
944 addressmap_already_mapped(conn->socks_request->address))
945 return; /* nothing to track, or already mapped */
947 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
948 if (cp[0] == '.') { /* match end */
949 /* XXX strstr is probably really bad here */
950 if ((str = strstr(conn->socks_request->address, &cp[1]))) {
951 if (str == conn->socks_request->address
952 || strcmp(str, &cp[1]) == 0) {
953 found_needle = 1;
956 } else if (strcmp(cp, conn->socks_request->address) == 0) {
957 found_needle = 1;
961 if (!found_needle)
962 return;
964 /* Add this exit/hostname pair to the addressmap. */
965 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
966 strlen(circ->build_state->chosen_exit_name) + 1 /* '.' */ +
967 strlen("exit") + 1 /* '\0' */;
968 new_address = tor_malloc(len);
970 tor_snprintf(new_address, len, "%s.%s.exit",
971 conn->socks_request->address,
972 circ->build_state->chosen_exit_name);
974 addressmap_register(conn->socks_request->address, new_address,
975 time(NULL) + options->TrackHostExitsExpire);
978 /* DOCDOC. Return as for connection_ap_handshake_attach_chosen_circuit. */
980 connection_ap_handshake_attach_chosen_circuit(connection_t *conn,
981 circuit_t *circ)
983 tor_assert(conn);
984 tor_assert(conn->type == CONN_TYPE_AP);
985 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
986 conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
987 tor_assert(conn->socks_request);
988 tor_assert(circ);
990 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
992 if (!circ->timestamp_dirty)
993 circ->timestamp_dirty = time(NULL);
995 link_apconn_to_circ(conn, circ);
996 tor_assert(conn->socks_request);
997 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
998 consider_recording_trackhost(conn, circ);
999 connection_ap_handshake_send_begin(conn, circ);
1000 } else {
1001 connection_ap_handshake_send_resolve(conn, circ);
1004 return 1;
1007 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1008 * we don't find one: if conn cannot be handled by any known nodes,
1009 * warn and return -1 (conn needs to die);
1010 * else launch new circuit (if necessary) and return 0.
1011 * Otherwise, associate conn with a safe live circuit, do the
1012 * right next step, and return 1.
1014 int connection_ap_handshake_attach_circuit(connection_t *conn) {
1015 int retval;
1016 int conn_age;
1018 tor_assert(conn);
1019 tor_assert(conn->type == CONN_TYPE_AP);
1020 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1021 tor_assert(conn->socks_request);
1023 conn_age = time(NULL) - conn->timestamp_created;
1024 if (conn_age > CONN_AP_MAX_ATTACH_DELAY) {
1025 log_fn(LOG_NOTICE,"Giving up on unattached conn (%d sec old).", conn_age);
1026 return -1;
1029 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1030 circuit_t *circ=NULL;
1032 if (conn->chosen_exit_name) {
1033 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name);
1034 if (!router) {
1035 log_fn(LOG_WARN,"Requested exit point '%s' is not known. Closing.",
1036 conn->chosen_exit_name);
1037 return -1;
1039 if (!connection_ap_can_use_exit(conn, router)) {
1040 log_fn(LOG_WARN, "Requested exit point '%s' would refuse request. Closing.",
1041 conn->chosen_exit_name);
1042 return -1;
1046 /* find the circuit that we should use, if there is one. */
1047 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1048 if (retval < 1)
1049 return retval;
1051 log_fn(LOG_DEBUG,"Attaching apconn to circ %d (stream %d sec old).",
1052 circ->n_circ_id, conn_age);
1053 /* here, print the circ's path. so people can figure out which circs are sucking. */
1054 circuit_log_path(LOG_INFO,circ);
1056 /* We have found a suitable circuit for our conn. Hurray. */
1057 return connection_ap_handshake_attach_chosen_circuit(conn, circ);
1059 } else { /* we're a rendezvous conn */
1060 circuit_t *rendcirc=NULL, *introcirc=NULL;
1062 tor_assert(!conn->cpath_layer);
1064 /* start by finding a rendezvous circuit for us */
1066 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1067 if (retval < 0) return -1; /* failed */
1069 if (retval > 0) {
1070 tor_assert(rendcirc);
1071 /* one is already established, attach */
1072 log_fn(LOG_INFO,"rend joined circ %d already here. attaching. (stream %d sec old)",
1073 rendcirc->n_circ_id, conn_age);
1074 /* Mark rendezvous circuits as 'newly dirty' every time you use
1075 * them, since the process of rebuilding a rendezvous circ is so
1076 * expensive. There is a tradeoffs between linkability and
1077 * feasibility, at this point.
1079 rendcirc->timestamp_dirty = time(NULL);
1080 link_apconn_to_circ(conn, rendcirc);
1081 if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
1082 return 0; /* already marked, let them fade away */
1083 return 1;
1086 if (rendcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
1087 log_fn(LOG_INFO,"pending-join circ %d already here, with intro ack. Stalling. (stream %d sec old)", rendcirc->n_circ_id, conn_age);
1088 return 0;
1091 /* it's on its way. find an intro circ. */
1092 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1093 if (retval < 0) return -1; /* failed */
1095 if (retval > 0) {
1096 /* one has already sent the intro. keep waiting. */
1097 tor_assert(introcirc);
1098 log_fn(LOG_INFO,"Intro circ %d present and awaiting ack (rend %d). Stalling. (stream %d sec old)",
1099 introcirc->n_circ_id, rendcirc ? rendcirc->n_circ_id : 0, conn_age);
1100 return 0;
1103 /* now rendcirc and introcirc are each either undefined or not finished */
1105 if (rendcirc && introcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1106 log_fn(LOG_INFO,"ready rend circ %d already here (no intro-ack yet on intro %d). (stream %d sec old)",
1107 rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
1109 tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1110 if (introcirc->state == CIRCUIT_STATE_OPEN) {
1111 log_fn(LOG_INFO,"found open intro circ %d (rend %d); sending introduction. (stream %d sec old)",
1112 introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
1113 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1114 return -1;
1116 rendcirc->timestamp_dirty = time(NULL);
1117 introcirc->timestamp_dirty = time(NULL);
1118 assert_circuit_ok(rendcirc);
1119 assert_circuit_ok(introcirc);
1120 return 0;
1124 log_fn(LOG_INFO,"Intro (%d) and rend (%d) circs are not both ready. Stalling conn. (%d sec old)",
1125 introcirc ? introcirc->n_circ_id : 0,
1126 rendcirc ? rendcirc->n_circ_id : 0, conn_age);
1127 return 0;