More cleanups noticed by weasel; also, remove macros that nobody uses.
[tor.git] / src / or / circuituse.c
blobd19a415c9aca3b98ffc36ff1fde799c63d5d9b97
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, 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 /** Longest time to wait for a circuit before closing an AP connection */
17 #define CONN_AP_MAX_ATTACH_DELAY 59
19 /********* START VARIABLES **********/
21 extern circuit_t *global_circuitlist; /* from circuitlist.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
32 circuit_is_acceptable(circuit_t *circ, connection_t *conn,
33 int must_be_open, uint8_t purpose,
34 int need_uptime, int need_internal,
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 &&
57 !must_be_open) {
58 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
59 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
60 return 0;
61 } else {
62 if (purpose != circ->purpose)
63 return 0;
66 if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
67 if (circ->timestamp_dirty &&
68 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
69 return 0;
71 /* decide if this circ is suitable for this conn */
73 /* for rend circs, circ->cpath->prev is not the last router in the
74 * circuit, it's the magical extra bob hop. so just check the nickname
75 * of the one we meant to finish at.
77 exitrouter = build_state_get_exit_router(circ->build_state);
79 if (need_uptime && !circ->build_state->need_uptime)
80 return 0;
81 if (need_internal != circ->build_state->is_internal)
82 return 0;
84 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
85 if (!exitrouter) {
86 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
87 return 0; /* this circuit is screwed and doesn't know it yet,
88 * or is a rendezvous circuit. */
90 if (!connection_ap_can_use_exit(conn, exitrouter)) {
91 /* can't exit from this router */
92 return 0;
94 } else { /* not general */
95 if (rend_cmp_service_ids(conn->rend_query, circ->rend_query)) {
96 /* this circ is not for this conn */
97 return 0;
100 return 1;
103 /* Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
104 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
106 static int
107 circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
109 switch (purpose) {
110 case CIRCUIT_PURPOSE_C_GENERAL:
111 /* if it's used but less dirty it's best;
112 * else if it's more recently created it's best
114 if (b->timestamp_dirty) {
115 if (a->timestamp_dirty &&
116 a->timestamp_dirty > b->timestamp_dirty)
117 return 1;
118 } else {
119 if (a->timestamp_dirty ||
120 b->build_state->is_internal ||
121 a->timestamp_created > b->timestamp_created)
122 return 1;
124 break;
125 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
126 /* the closer it is to ack_wait the better it is */
127 if (a->purpose > b->purpose)
128 return 1;
129 break;
130 case CIRCUIT_PURPOSE_C_REND_JOINED:
131 /* the closer it is to rend_joined the better it is */
132 if (a->purpose > b->purpose)
133 return 1;
134 break;
136 return 0;
139 /** Find the best circ that conn can use, preferably one which is
140 * dirty. Circ must not be too old.
142 * Conn must be defined.
144 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
146 * circ_purpose specifies what sort of circuit we must have.
147 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
149 * If it's REND_JOINED and must_be_open==0, then return the closest
150 * rendezvous-purposed circuit that you can find.
152 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
153 * closest introduce-purposed circuit that you can find.
155 static circuit_t *
156 circuit_get_best(connection_t *conn, int must_be_open, uint8_t purpose,
157 int need_uptime, int need_internal)
159 circuit_t *circ, *best=NULL;
160 time_t now = time(NULL);
162 tor_assert(conn);
164 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
165 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
166 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
168 for (circ=global_circuitlist;circ;circ = circ->next) {
169 if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
170 need_uptime,need_internal,now))
171 continue;
173 /* now this is an acceptable circ to hand back. but that doesn't
174 * mean it's the *best* circ to hand back. try to decide.
176 if (!best || circuit_is_better(circ,best,purpose))
177 best = circ;
180 return best;
183 /** If we find a circuit that isn't open yet and was born this many
184 * seconds ago, then assume something went wrong, and cull it.
186 #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 30
188 /** Close all circuits that start at us, aren't open, and were born
189 * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago.
191 void
192 circuit_expire_building(time_t now)
194 circuit_t *victim, *circ = global_circuitlist;
195 time_t cutoff = now - MIN_SECONDS_BEFORE_EXPIRING_CIRC;
197 while (circ) {
198 victim = circ;
199 circ = circ->next;
200 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
201 victim->timestamp_created > cutoff || /* Not old enough to expire */
202 victim->marked_for_close) /* don't mess with marked circs */
203 continue;
205 #if 0
206 /* some debug logs, to help track bugs */
207 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
208 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
209 if (!victim->timestamp_dirty)
210 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d)."
211 "(clean).",
212 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
213 victim->purpose, victim->build_state->chosen_exit_name,
214 victim->n_circ_id);
215 else
216 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). "
217 "%d secs since dirty.",
218 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
219 victim->purpose, victim->build_state->chosen_exit_name,
220 victim->n_circ_id,
221 (int)(now - victim->timestamp_dirty));
223 #endif
225 /* if circ is !open, or if it's open but purpose is a non-finished
226 * intro or rend, then mark it for close */
227 if (victim->state == CIRCUIT_STATE_OPEN) {
228 switch (victim->purpose) {
229 default: /* most open circuits can be left alone. */
230 continue; /* yes, continue inside a switch refers to the nearest
231 * enclosing loop. C is smart. */
232 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
233 case CIRCUIT_PURPOSE_C_INTRODUCING:
234 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
235 break; /* too old, need to die */
236 case CIRCUIT_PURPOSE_C_REND_READY:
237 /* it's a rend_ready circ -- has it already picked a query? */
238 /* c_rend_ready circs measure age since timestamp_dirty,
239 * because that's set when they switch purposes
241 if (!victim->rend_query[0] || victim->timestamp_dirty > cutoff)
242 continue;
243 break;
244 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
245 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
246 /* rend and intro circs become dirty each time they
247 * make an introduction attempt. so timestamp_dirty
248 * will reflect the time since the last attempt.
250 if (victim->timestamp_dirty > cutoff)
251 continue;
252 break;
256 if (victim->n_conn)
257 log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
258 victim->n_conn->address, victim->n_port, victim->n_circ_id,
259 victim->state, circuit_state_to_string(victim->state),
260 victim->purpose);
261 else
262 log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
263 victim->n_circ_id, victim->state,
264 circuit_state_to_string(victim->state), victim->purpose);
266 circuit_log_path(LOG_INFO,LD_CIRC,victim);
267 circuit_mark_for_close(victim, END_CIRC_AT_ORIGIN);
271 /** Remove any elements in <b>needed_ports</b> that are handled by an
272 * open or in-progress circuit.
274 void
275 circuit_remove_handled_ports(smartlist_t *needed_ports)
277 int i;
278 uint16_t *port;
280 for (i = 0; i < smartlist_len(needed_ports); ++i) {
281 port = smartlist_get(needed_ports, i);
282 tor_assert(*port);
283 if (circuit_stream_is_being_handled(NULL, *port, 2)) {
284 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
285 smartlist_del(needed_ports, i--);
286 tor_free(port);
287 } else {
288 log_debug(LD_CIRC,"Port %d is not handled.", *port);
293 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
294 * will have an acceptable exit node for exit stream <b>conn</b> if it
295 * is defined, else for "*:port".
296 * Else return 0.
299 circuit_stream_is_being_handled(connection_t *conn, uint16_t port, int min)
301 circuit_t *circ;
302 routerinfo_t *exitrouter;
303 int num=0;
304 time_t now = time(NULL);
305 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
306 conn ? conn->socks_request->port : port);
308 for (circ=global_circuitlist;circ;circ = circ->next) {
309 if (CIRCUIT_IS_ORIGIN(circ) &&
310 !circ->marked_for_close &&
311 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
312 !circ->build_state->is_internal &&
313 (!circ->timestamp_dirty ||
314 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
315 exitrouter = build_state_get_exit_router(circ->build_state);
316 if (exitrouter &&
317 (!need_uptime || circ->build_state->need_uptime)) {
318 int ok;
319 if (conn) {
320 ok = connection_ap_can_use_exit(conn, exitrouter);
321 } else {
322 addr_policy_result_t r = router_compare_addr_to_addr_policy(
323 0, port, exitrouter->exit_policy);
324 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
326 if (ok) {
327 if (++num >= min)
328 return 1;
333 return 0;
336 /** Don't keep more than this many unused open circuits around. */
337 #define MAX_UNUSED_OPEN_CIRCUITS 12
339 /** Figure out how many circuits we have open that are clean. Make
340 * sure it's enough for all the upcoming behaviors we predict we'll have.
341 * But if we have too many, close the not-so-useful ones.
343 static void
344 circuit_predict_and_launch_new(void)
346 circuit_t *circ;
347 int num=0, num_internal=0, num_uptime_internal=0;
348 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
349 int port_needs_uptime=0, port_needs_capacity=1;
350 time_t now = time(NULL);
352 /* First, count how many of each type of circuit we have already. */
353 for (circ=global_circuitlist;circ;circ = circ->next) {
354 if (!CIRCUIT_IS_ORIGIN(circ))
355 continue;
356 if (circ->marked_for_close)
357 continue; /* don't mess with marked circs */
358 if (circ->timestamp_dirty)
359 continue; /* only count clean circs */
360 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
361 continue; /* only pay attention to general-purpose circs */
362 num++;
363 if (circ->build_state->is_internal)
364 num_internal++;
365 if (circ->build_state->need_uptime && circ->build_state->is_internal)
366 num_uptime_internal++;
369 /* If that's enough, then stop now. */
370 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
371 return; /* we already have many, making more probably will hurt */
373 /* Second, see if we need any more exit circuits. */
374 /* check if we know of a port that's been requested recently
375 * and no circuit is currently available that can handle it. */
376 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
377 &port_needs_capacity)) {
378 log_info(LD_CIRC,
379 "Have %d clean circs (%d internal), need another exit circ.",
380 num, num_internal);
381 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
382 port_needs_uptime, port_needs_capacity, 0);
383 return;
386 /* Third, see if we need any more hidden service (server) circuits. */
387 if (num_rend_services() && num_uptime_internal < 3) {
388 log_info(LD_CIRC,
389 "Have %d clean circs (%d internal), need another internal "
390 "circ for my hidden service.",
391 num, num_internal);
392 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
393 1, 1, 1);
394 return;
397 /* Fourth, see if we need any more hidden service (client) circuits. */
398 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
399 &hidserv_needs_capacity) &&
400 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
401 num_internal<2)) {
402 log_info(LD_CIRC,
403 "Have %d clean circs (%d uptime-internal, %d internal), need"
404 " another hidserv circ.",
405 num, num_uptime_internal, num_internal);
406 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
407 hidserv_needs_uptime, hidserv_needs_capacity, 1);
408 return;
412 /** Build a new test circuit every 5 minutes */
413 #define TESTING_CIRCUIT_INTERVAL 300
415 /** This function is called once a second. Its job is to make sure
416 * all services we offer have enough circuits available. Some
417 * services just want enough circuits for current tasks, whereas
418 * others want a minimum set of idle circuits hanging around.
420 void
421 circuit_build_needed_circs(time_t now)
423 static long time_to_new_circuit = 0;
425 /* launch a new circ for any pending streams that need one */
426 connection_ap_attach_pending();
428 /* make sure any hidden services have enough intro points */
429 if (router_have_minimum_dir_info())
430 rend_services_introduce();
432 if (time_to_new_circuit < now) {
433 circuit_reset_failure_count(1);
434 time_to_new_circuit = now + get_options()->NewCircuitPeriod;
435 if (proxy_mode(get_options()))
436 addressmap_clean(now);
437 circuit_expire_old_circuits();
439 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
440 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
441 if (get_options()->RunTesting &&
442 circ &&
443 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
444 log_fn(LOG_INFO,"Creating a new testing circuit.");
445 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0, 0, 0);
447 #endif
449 circuit_predict_and_launch_new();
452 /** If the stream <b>conn</b> is a member of any of the linked
453 * lists of <b>circ</b>, then remove it from the list.
455 void
456 circuit_detach_stream(circuit_t *circ, connection_t *conn)
458 connection_t *prevconn;
460 tor_assert(circ);
461 tor_assert(conn);
463 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
464 conn->on_circuit = NULL;
466 if (conn == circ->p_streams) {
467 circ->p_streams = conn->next_stream;
468 return;
470 if (conn == circ->n_streams) {
471 circ->n_streams = conn->next_stream;
472 return;
474 if (conn == circ->resolving_streams) {
475 circ->resolving_streams = conn->next_stream;
476 return;
479 for (prevconn = circ->p_streams;
480 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
481 prevconn = prevconn->next_stream)
483 if (prevconn && prevconn->next_stream) {
484 prevconn->next_stream = conn->next_stream;
485 return;
488 for (prevconn = circ->n_streams;
489 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
490 prevconn = prevconn->next_stream)
492 if (prevconn && prevconn->next_stream) {
493 prevconn->next_stream = conn->next_stream;
494 return;
497 for (prevconn = circ->resolving_streams;
498 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
499 prevconn = prevconn->next_stream)
501 if (prevconn && prevconn->next_stream) {
502 prevconn->next_stream = conn->next_stream;
503 return;
506 log_err(LD_BUG,"edge conn not in circuit's list?");
507 tor_assert(0); /* should never get here */
510 /** Notify the global circuit list that <b>conn</b> is about to be
511 * removed and then freed.
513 * If it's an OR conn, then mark-for-close all the circuits that use
514 * that conn.
516 * If it's an edge conn, then detach it from its circ, so we don't
517 * try to reference it later.
519 void
520 circuit_about_to_close_connection(connection_t *conn)
522 /* currently, we assume it's too late to flush conn's buf here.
523 * down the road, maybe we'll consider that eof doesn't mean can't-write
525 switch (conn->type) {
526 case CONN_TYPE_OR: {
527 /* Inform any pending (not attached) circs that they should give up. */
528 circuit_n_conn_done(conn, 0);
529 /* Now close all the attached circuits on it. */
530 circuit_unlink_all_from_or_conn(conn, END_CIRC_REASON_OR_CONN_CLOSED);
531 return;
533 case CONN_TYPE_AP:
534 case CONN_TYPE_EXIT: {
535 circuit_t *circ;
536 /* It's an edge conn. Need to remove it from the linked list of
537 * conn's for this circuit. Confirm that 'end' relay command has
538 * been sent. But don't kill the circuit.
541 circ = circuit_get_by_edge_conn(conn);
542 if (!circ)
543 return;
545 circuit_detach_stream(circ, conn);
547 } /* end switch */
550 /** How old do we let an unused circuit get before expiring it? */
551 #define CIRCUIT_UNUSED_CIRC_TIMEOUT (60*60)
553 /** Find each circuit that has been dirty for too long, and has
554 * no streams on it: mark it for close.
556 static void
557 circuit_expire_old_circuits(void)
559 circuit_t *circ;
560 time_t now = time(NULL);
562 for (circ = global_circuitlist; circ; circ = circ->next) {
563 if (circ->marked_for_close)
564 continue;
565 /* If the circuit has been dirty for too long, and there are no streams
566 * on it, mark it for close.
568 if (circ->timestamp_dirty &&
569 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
570 CIRCUIT_IS_ORIGIN(circ) &&
571 !circ->p_streams /* nothing attached */ ) {
572 log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, purp %d)",
573 circ->n_circ_id, (int)(now - circ->timestamp_dirty),
574 circ->purpose);
575 /* (only general and purpose_c circs can get dirty) */
576 tor_assert(!circ->n_streams);
577 tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
578 circuit_mark_for_close(circ, END_CIRC_AT_ORIGIN);
579 } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
580 circ->state == CIRCUIT_STATE_OPEN &&
581 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
582 if (circ->timestamp_created + CIRCUIT_UNUSED_CIRC_TIMEOUT < now) {
583 log_debug(LD_CIRC,
584 "Closing circuit that has been unused for %d seconds.",
585 (int)(now - circ->timestamp_created));
586 circuit_mark_for_close(circ, END_CIRC_AT_ORIGIN);
592 /** A testing circuit has completed. Take whatever stats we want. */
593 static void
594 circuit_testing_opened(circuit_t *circ)
596 /* For now, we only use testing circuits to see if our ORPort is
597 reachable. But we remember reachability in onionskin_answer(),
598 so there's no need to record anything here. Just close the circ. */
599 circuit_mark_for_close(circ, END_CIRC_AT_ORIGIN);
602 /** A testing circuit has failed to build. Take whatever stats we want. */
603 static void
604 circuit_testing_failed(circuit_t *circ, int at_last_hop)
606 #if 0
607 routerinfo_t *me = router_get_my_routerinfo();
609 if (!at_last_hop)
610 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
611 else
612 #endif
613 log_info(LD_GENERAL,
614 "Our testing circuit (to see if your ORPort is reachable) "
615 "has failed. I'll try again later.");
618 /** The circuit <b>circ</b> has just become open. Take the next
619 * step: for rendezvous circuits, we pass circ to the appropriate
620 * function in rendclient or rendservice. For general circuits, we
621 * call connection_ap_attach_pending, which looks for pending streams
622 * that could use circ.
624 void
625 circuit_has_opened(circuit_t *circ)
627 control_event_circuit_status(circ, CIRC_EVENT_BUILT);
629 switch (circ->purpose) {
630 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
631 rend_client_rendcirc_has_opened(circ);
632 connection_ap_attach_pending();
633 break;
634 case CIRCUIT_PURPOSE_C_INTRODUCING:
635 rend_client_introcirc_has_opened(circ);
636 break;
637 case CIRCUIT_PURPOSE_C_GENERAL:
638 /* Tell any AP connections that have been waiting for a new
639 * circuit that one is ready. */
640 connection_ap_attach_pending();
641 break;
642 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
643 /* at Bob, waiting for introductions */
644 rend_service_intro_has_opened(circ);
645 break;
646 case CIRCUIT_PURPOSE_S_CONNECT_REND:
647 /* at Bob, connecting to rend point */
648 rend_service_rendezvous_has_opened(circ);
649 break;
650 case CIRCUIT_PURPOSE_TESTING:
651 circuit_testing_opened(circ);
652 break;
653 default:
654 log_err(LD_BUG,"unhandled purpose %d",circ->purpose);
655 tor_assert(0);
659 /** Called whenever a circuit could not be successfully built.
661 void
662 circuit_build_failed(circuit_t *circ)
664 /* we should examine circ and see if it failed because of
665 * the last hop or an earlier hop. then use this info below.
667 int failed_at_last_hop = 0;
668 /* If the last hop isn't open, and the second-to-last is, we failed
669 * at the last hop. */
670 if (circ->cpath &&
671 circ->cpath->prev->state != CPATH_STATE_OPEN &&
672 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
673 failed_at_last_hop = 1;
675 if (circ->cpath &&
676 circ->cpath->state != CPATH_STATE_OPEN) {
677 /* We failed at the first hop. If there's an OR connection
678 to blame, blame it. */
679 connection_t *n_conn = NULL;
680 if (circ->n_conn) {
681 n_conn = circ->n_conn;
682 } else if (circ->state == CIRCUIT_STATE_OR_WAIT) {
683 /* we have to hunt for it */
684 n_conn = connection_or_get_by_identity_digest(circ->n_conn_id_digest);
686 if (n_conn) {
687 log_info(LD_OR,
688 "Our circuit failed to get a response from the first hop "
689 "(%s:%d). I'm going to try to rotate to a better connection.",
690 n_conn->address, n_conn->port);
691 n_conn->is_obsolete = 1;
692 entry_guard_set_status(n_conn->identity_digest, 0);
696 switch (circ->purpose) {
697 case CIRCUIT_PURPOSE_C_GENERAL:
698 if (circ->state != CIRCUIT_STATE_OPEN) {
699 /* If we never built the circuit, note it as a failure. */
700 /* Note that we can't just check circ->cpath here, because if
701 * circuit-building failed immediately, it won't be set yet. */
702 circuit_increment_failure_count();
704 break;
705 case CIRCUIT_PURPOSE_TESTING:
706 circuit_testing_failed(circ, failed_at_last_hop);
707 break;
708 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
709 /* at Bob, waiting for introductions */
710 if (circ->state != CIRCUIT_STATE_OPEN) {
711 circuit_increment_failure_count();
713 /* no need to care here, because bob will rebuild intro
714 * points periodically. */
715 break;
716 case CIRCUIT_PURPOSE_C_INTRODUCING:
717 /* at Alice, connecting to intro point */
718 /* Don't increment failure count, since Bob may have picked
719 * the introduction point maliciously */
720 /* Alice will pick a new intro point when this one dies, if
721 * the stream in question still cares. No need to act here. */
722 break;
723 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
724 /* at Alice, waiting for Bob */
725 if (circ->state != CIRCUIT_STATE_OPEN) {
726 circuit_increment_failure_count();
728 /* Alice will pick a new rend point when this one dies, if
729 * the stream in question still cares. No need to act here. */
730 break;
731 case CIRCUIT_PURPOSE_S_CONNECT_REND:
732 /* at Bob, connecting to rend point */
733 /* Don't increment failure count, since Alice may have picked
734 * the rendezvous point maliciously */
735 log_info(LD_REND,
736 "Couldn't connect to Alice's chosen rend point %s "
737 "(%s hop failed).",
738 escaped(build_state_get_exit_nickname(circ->build_state)),
739 failed_at_last_hop?"last":"non-last");
740 rend_service_relaunch_rendezvous(circ);
741 break;
742 default:
743 /* Other cases are impossible, since this function is only called with
744 * unbuilt circuits. */
745 tor_assert(0);
749 /** Number of consecutive failures so far; should only be touched by
750 * circuit_launch_new and circuit_*_failure_count.
752 static int n_circuit_failures = 0;
753 static int did_circs_fail_last_period = 0;
755 /** Don't retry launching a new circuit if we try this many times with no
756 * success. */
757 #define MAX_CIRCUIT_FAILURES 5
759 /** Launch a new circuit; see circuit_launch_by_extend_info() for
760 * details on arguments. */
761 circuit_t *
762 circuit_launch_by_router(uint8_t purpose, routerinfo_t *exit,
763 int need_uptime, int need_capacity, int internal)
765 circuit_t *circ;
766 extend_info_t *info = NULL;
767 if (exit)
768 info = extend_info_from_router(exit);
769 circ = circuit_launch_by_extend_info(
770 purpose, info, need_uptime, need_capacity, internal);
771 if (info)
772 extend_info_free(info);
773 return circ;
776 /** Launch a new circuit with purpose <b>purpose</b> and exit node <b>info</b>
777 * (or NULL to select a random exit node). If <b>need_uptime</b> is true,
778 * choose among routers with high uptime. If <b>need_capacity</b> is true,
779 * choose among routers with high bandwidth. If <b>internal</b> is true, the
780 * last hop need not be an exit node. Return the newly allocated circuit on
781 * success, or NULL on failure. */
782 circuit_t *
783 circuit_launch_by_extend_info(uint8_t purpose, extend_info_t *extend_info,
784 int need_uptime, int need_capacity, int internal)
786 circuit_t *circ;
788 if (!router_have_minimum_dir_info()) {
789 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
790 "circuit launch.");
791 return NULL;
794 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
795 purpose != CIRCUIT_PURPOSE_TESTING) {
796 /* see if there are appropriate circs available to cannibalize. */
797 circ = circuit_find_to_cannibalize(CIRCUIT_PURPOSE_C_GENERAL, extend_info,
798 need_uptime, need_capacity, internal);
799 if (circ) {
800 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
801 build_state_get_exit_nickname(circ->build_state), purpose);
802 circ->purpose = purpose;
803 /* reset the birth date of this circ, else expire_building
804 * will see it and think it's been trying to build since it
805 * began. */
806 circ->timestamp_created = time(NULL);
807 switch (purpose) {
808 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
809 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
810 /* it's ready right now */
811 break;
812 case CIRCUIT_PURPOSE_C_INTRODUCING:
813 case CIRCUIT_PURPOSE_S_CONNECT_REND:
814 case CIRCUIT_PURPOSE_C_GENERAL:
815 /* need to add a new hop */
816 tor_assert(extend_info);
817 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
818 return NULL;
819 break;
820 default:
821 log_warn(LD_BUG,
822 "Bug: unexpected purpose %d when cannibalizing a circ.",
823 purpose);
824 tor_fragile_assert();
825 return NULL;
827 return circ;
831 if (did_circs_fail_last_period &&
832 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
833 /* too many failed circs in a row. don't try. */
834 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
835 return NULL;
838 /* try a circ. if it fails, circuit_mark_for_close will increment
839 * n_circuit_failures */
840 return circuit_establish_circuit(purpose, extend_info,
841 need_uptime, need_capacity, internal);
844 /** Launch a new circuit; see circuit_launch_by_extend_info() for
845 * details on arguments. */
846 circuit_t *
847 circuit_launch_by_nickname(uint8_t purpose, const char *exit_nickname,
848 int need_uptime, int need_capacity, int internal)
850 routerinfo_t *router = NULL;
852 if (exit_nickname) {
853 router = router_get_by_nickname(exit_nickname, 1);
854 if (!router) {
855 /*XXXXNM domain? */
856 log_warn(LD_GENERAL, "No such OR as '%s'", exit_nickname);
857 return NULL;
860 return circuit_launch_by_router(purpose, router,
861 need_uptime, need_capacity, internal);
864 /** Record another failure at opening a general circuit. When we have
865 * too many, we'll stop trying for the remainder of this minute.
867 static void
868 circuit_increment_failure_count(void)
870 ++n_circuit_failures;
871 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
874 /** Reset the failure count for opening general circuits. This means
875 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
876 * stopping again.
878 void
879 circuit_reset_failure_count(int timeout)
881 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
882 did_circs_fail_last_period = 1;
883 else
884 did_circs_fail_last_period = 0;
885 n_circuit_failures = 0;
888 /** Find an open circ that we're happy with: return 1. If there isn't
889 * one, and there isn't one on the way, launch one and return 0. If it
890 * will never work, return -1.
892 * Write the found or in-progress or launched circ into *circp.
894 static int
895 circuit_get_open_circ_or_launch(connection_t *conn,
896 uint8_t desired_circuit_purpose,
897 circuit_t **circp)
899 circuit_t *circ;
900 int is_resolve;
901 int need_uptime, need_internal;
903 tor_assert(conn);
904 tor_assert(circp);
905 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
906 is_resolve = conn->socks_request->command == SOCKS_COMMAND_RESOLVE;
908 need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
909 conn->socks_request->port);
910 need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
912 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
913 need_uptime, need_internal);
915 if (circ) {
916 *circp = circ;
917 return 1; /* we're happy */
920 if (!router_have_minimum_dir_info()) {
921 if (!connection_get_by_type(CONN_TYPE_DIR)) {
922 log_notice(LD_APP|LD_DIR,
923 "Application request when we're believed to be "
924 "offline. Optimistically trying directory fetches again.");
925 router_reset_status_download_failures();
926 router_reset_descriptor_download_failures();
927 update_networkstatus_downloads(time(NULL));
928 update_router_descriptor_downloads(time(NULL));
930 /* the stream will be dealt with when router_have_minimum_dir_info becomes
931 * 1, or when all directory attempts fail and directory_all_unreachable()
932 * kills it.
934 return 0;
937 /* Do we need to check exit policy? */
938 if (!is_resolve && !connection_edge_is_rendezvous_stream(conn)) {
939 struct in_addr in;
940 uint32_t addr = 0;
941 if (tor_inet_aton(conn->socks_request->address, &in))
942 addr = ntohl(in.s_addr);
943 if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port,
944 need_uptime)) {
945 log_notice(LD_APP,
946 "No Tor server exists that allows exit to %s:%d. Rejecting.",
947 safe_str(conn->socks_request->address),
948 conn->socks_request->port);
949 return -1;
953 /* is one already on the way? */
954 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
955 need_uptime, need_internal);
956 if (!circ) {
957 extend_info_t *extend_info=NULL;
958 uint8_t new_circ_purpose;
960 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
961 /* need to pick an intro point */
962 extend_info = rend_client_get_random_intro(conn->rend_query);
963 if (!extend_info) {
964 log_info(LD_REND,
965 "No intro points for '%s': refetching service descriptor.",
966 safe_str(conn->rend_query));
967 rend_client_refetch_renddesc(conn->rend_query);
968 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
969 return 0;
971 log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
972 extend_info->nickname, safe_str(conn->rend_query));
975 /* If we have specified a particular exit node for our
976 * connection, then be sure to open a circuit to that exit node.
978 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
979 if (conn->chosen_exit_name) {
980 routerinfo_t *r;
981 if (!(r = router_get_by_nickname(conn->chosen_exit_name, 1))) {
982 /*XXXX NM domain? */
983 log_notice(LD_CIRC,
984 "Requested exit point '%s' is not known. Closing.",
985 conn->chosen_exit_name);
986 return -1;
988 extend_info = extend_info_from_router(r);
992 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
993 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
994 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
995 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
996 else
997 new_circ_purpose = desired_circuit_purpose;
999 circ = circuit_launch_by_extend_info(
1000 new_circ_purpose, extend_info, need_uptime, 1, need_internal);
1001 if (extend_info)
1002 extend_info_free(extend_info);
1004 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
1005 /* help predict this next time */
1006 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1007 if (circ) {
1008 /* write the service_id into circ */
1009 strlcpy(circ->rend_query, conn->rend_query, sizeof(circ->rend_query));
1010 if (circ->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1011 circ->state == CIRCUIT_STATE_OPEN)
1012 rend_client_rendcirc_has_opened(circ);
1016 if (!circ)
1017 log_info(LD_APP,
1018 "No safe circuit (purpose %d) ready for edge "
1019 "connection; delaying.",
1020 desired_circuit_purpose);
1021 *circp = circ;
1022 return 0;
1025 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1026 * p_streams. Also set apconn's cpath_layer to the last hop in
1027 * circ's cpath.
1029 static void
1030 link_apconn_to_circ(connection_t *apconn, circuit_t *circ)
1032 /* add it into the linked list of streams on this circuit */
1033 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
1034 circ->n_circ_id);
1035 /* reset it, so we can measure circ timeouts */
1036 apconn->timestamp_lastread = time(NULL);
1037 apconn->next_stream = circ->p_streams;
1038 apconn->on_circuit = circ;
1039 /* assert_connection_ok(conn, time(NULL)); */
1040 circ->p_streams = apconn;
1042 tor_assert(CIRCUIT_IS_ORIGIN(circ));
1043 tor_assert(circ->cpath);
1044 tor_assert(circ->cpath->prev);
1045 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1046 apconn->cpath_layer = circ->cpath->prev;
1049 /** If an exit wasn't specifically chosen, save the history for future
1050 * use. */
1051 static void
1052 consider_recording_trackhost(connection_t *conn, circuit_t *circ)
1054 int found_needle = 0;
1055 char *str;
1056 or_options_t *options = get_options();
1057 size_t len;
1058 char *new_address;
1059 char fp[HEX_DIGEST_LEN+1];
1061 /* Search the addressmap for this conn's destination. */
1062 /* If he's not in the address map.. */
1063 if (!options->TrackHostExits ||
1064 addressmap_already_mapped(conn->socks_request->address))
1065 return; /* nothing to track, or already mapped */
1067 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1068 if (cp[0] == '.') { /* match end */
1069 /* XXX strstr is probably really bad here */
1070 if ((str = strstr(conn->socks_request->address, &cp[1]))) {
1071 if (str == conn->socks_request->address
1072 || strcmp(str, &cp[1]) == 0) {
1073 found_needle = 1;
1076 } else if (strcmp(cp, conn->socks_request->address) == 0) {
1077 found_needle = 1;
1081 if (!found_needle || !circ->build_state->chosen_exit)
1082 return;
1084 /* write down the fingerprint of the chosen exit, not the nickname,
1085 * because the chosen exit might not be verified. */
1086 base16_encode(fp, sizeof(fp),
1087 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
1089 /* Add this exit/hostname pair to the addressmap. */
1090 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1091 strlen(fp) + 1 /* '.' */ +
1092 strlen("exit") + 1 /* '\0' */;
1093 new_address = tor_malloc(len);
1095 tor_snprintf(new_address, len, "%s.%s.exit",
1096 conn->socks_request->address, fp);
1098 addressmap_register(conn->socks_request->address, new_address,
1099 time(NULL) + options->TrackHostExitsExpire);
1102 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and
1103 * send a begin or resolve cell as appropriate. Return values are as
1104 * for connection_ap_handshake_attach_circuit. */
1106 connection_ap_handshake_attach_chosen_circuit(connection_t *conn,
1107 circuit_t *circ)
1109 tor_assert(conn);
1110 tor_assert(conn->type == CONN_TYPE_AP);
1111 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
1112 conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
1113 tor_assert(conn->socks_request);
1114 tor_assert(circ);
1115 tor_assert(circ->state == CIRCUIT_STATE_OPEN);
1117 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1119 if (!circ->timestamp_dirty)
1120 circ->timestamp_dirty = time(NULL);
1122 link_apconn_to_circ(conn, circ);
1123 tor_assert(conn->socks_request);
1124 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
1125 consider_recording_trackhost(conn, circ);
1126 if (connection_ap_handshake_send_begin(conn, circ)<0)
1127 return -1;
1128 } else {
1129 if (connection_ap_handshake_send_resolve(conn, circ)<0)
1130 return -1;
1133 return 1;
1136 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1137 * we don't find one: if conn cannot be handled by any known nodes,
1138 * warn and return -1 (conn needs to die);
1139 * else launch new circuit (if necessary) and return 0.
1140 * Otherwise, associate conn with a safe live circuit, do the
1141 * right next step, and return 1.
1144 connection_ap_handshake_attach_circuit(connection_t *conn)
1146 int retval;
1147 int conn_age;
1149 tor_assert(conn);
1150 tor_assert(conn->type == CONN_TYPE_AP);
1151 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1152 tor_assert(conn->socks_request);
1154 conn_age = time(NULL) - conn->timestamp_created;
1155 if (conn_age > CONN_AP_MAX_ATTACH_DELAY) {
1156 log_notice(LD_APP,
1157 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1158 conn_age, safe_str(conn->socks_request->address),
1159 conn->socks_request->port);
1160 return -1;
1163 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1164 circuit_t *circ=NULL;
1166 if (conn->chosen_exit_name) {
1167 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1168 if (!router) {
1169 log_warn(LD_APP,
1170 "Requested exit point '%s' is not known. Closing.",
1171 conn->chosen_exit_name);
1172 return -1;
1174 if (!connection_ap_can_use_exit(conn, router)) {
1175 log_warn(LD_APP,
1176 "Requested exit point '%s' would refuse request. Closing.",
1177 conn->chosen_exit_name);
1178 return -1;
1182 /* find the circuit that we should use, if there is one. */
1183 retval = circuit_get_open_circ_or_launch(
1184 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1185 if (retval < 1)
1186 return retval;
1188 log_debug(LD_APP|LD_CIRC,
1189 "Attaching apconn to circ %d (stream %d sec old).",
1190 circ->n_circ_id, conn_age);
1191 /* here, print the circ's path. so people can figure out which circs are
1192 * sucking. */
1193 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1195 /* We have found a suitable circuit for our conn. Hurray. */
1196 return connection_ap_handshake_attach_chosen_circuit(conn, circ);
1198 } else { /* we're a rendezvous conn */
1199 circuit_t *rendcirc=NULL, *introcirc=NULL;
1201 tor_assert(!conn->cpath_layer);
1203 /* start by finding a rendezvous circuit for us */
1205 retval = circuit_get_open_circ_or_launch(
1206 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1207 if (retval < 0) return -1; /* failed */
1209 if (retval > 0) {
1210 tor_assert(rendcirc);
1211 /* one is already established, attach */
1212 log_info(LD_REND,
1213 "rend joined circ %d already here. attaching. "
1214 "(stream %d sec old)",
1215 rendcirc->n_circ_id, conn_age);
1216 /* Mark rendezvous circuits as 'newly dirty' every time you use
1217 * them, since the process of rebuilding a rendezvous circ is so
1218 * expensive. There is a tradeoffs between linkability and
1219 * feasibility, at this point.
1221 rendcirc->timestamp_dirty = time(NULL);
1222 link_apconn_to_circ(conn, rendcirc);
1223 if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
1224 return 0; /* already marked, let them fade away */
1225 return 1;
1228 if (rendcirc && (rendcirc->purpose ==
1229 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
1230 log_info(LD_REND,
1231 "pending-join circ %d already here, with intro ack. "
1232 "Stalling. (stream %d sec old)",
1233 rendcirc->n_circ_id, conn_age);
1234 return 0;
1237 /* it's on its way. find an intro circ. */
1238 retval = circuit_get_open_circ_or_launch(
1239 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1240 if (retval < 0) return -1; /* failed */
1242 if (retval > 0) {
1243 /* one has already sent the intro. keep waiting. */
1244 tor_assert(introcirc);
1245 log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
1246 "Stalling. (stream %d sec old)",
1247 introcirc->n_circ_id, rendcirc ? rendcirc->n_circ_id : 0,
1248 conn_age);
1249 return 0;
1252 /* now rendcirc and introcirc are each either undefined or not finished */
1254 if (rendcirc && introcirc &&
1255 rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1256 log_info(LD_REND,
1257 "ready rend circ %d already here (no intro-ack yet on "
1258 "intro %d). (stream %d sec old)",
1259 rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
1261 tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1262 if (introcirc->state == CIRCUIT_STATE_OPEN) {
1263 log_info(LD_REND,"found open intro circ %d (rend %d); sending "
1264 "introduction. (stream %d sec old)",
1265 introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
1266 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1267 return -1;
1269 rendcirc->timestamp_dirty = time(NULL);
1270 introcirc->timestamp_dirty = time(NULL);
1271 assert_circuit_ok(rendcirc);
1272 assert_circuit_ok(introcirc);
1273 return 0;
1277 log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
1278 "Stalling conn. (%d sec old)",
1279 introcirc ? introcirc->n_circ_id : 0,
1280 rendcirc ? rendcirc->n_circ_id : 0, conn_age);
1281 return 0;