Convert circuituse, command, config, connection, relay, router, test to new logging...
[tor.git] / src / or / circuituse.c
blob8c98d7e302dd2ea804a9da67e02b52d599fb9fc0
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 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 and attach streams to them.
11 **/
13 #define NEW_LOG_INTERFACE
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 */
22 extern int has_fetched_directory; /* from main.c */
24 /********* END VARIABLES ************/
26 static void circuit_expire_old_circuits(void);
27 static void circuit_increment_failure_count(void);
29 /* Return 1 if <b>circ</b> could be returned by circuit_get_best().
30 * Else return 0.
32 static int
33 circuit_is_acceptable(circuit_t *circ,
34 connection_t *conn,
35 int must_be_open,
36 uint8_t purpose,
37 time_t now)
39 routerinfo_t *exitrouter;
40 tor_assert(circ);
41 tor_assert(conn);
42 tor_assert(conn->socks_request);
44 if (!CIRCUIT_IS_ORIGIN(circ))
45 return 0; /* this circ doesn't start at us */
46 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
47 return 0; /* ignore non-open circs */
48 if (circ->marked_for_close)
49 return 0;
51 /* if this circ isn't our purpose, skip. */
52 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
53 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
54 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
55 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
56 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
57 return 0;
58 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT && !must_be_open) {
59 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
60 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
61 return 0;
62 } else {
63 if (purpose != circ->purpose)
64 return 0;
67 if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
68 if (circ->timestamp_dirty &&
69 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
70 return 0;
72 /* decide if this circ is suitable for this conn */
74 /* for rend circs, circ->cpath->prev is not the last router in the
75 * circuit, it's the magical extra bob hop. so just check the nickname
76 * of the one we meant to finish at.
78 exitrouter = build_state_get_exit_router(circ->build_state);
80 if (!circ->build_state->need_uptime &&
81 smartlist_string_num_isin(get_options()->LongLivedPorts,
82 conn->socks_request->port))
83 return 0;
85 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
86 if (!exitrouter) {
87 debug(LD_CIRC,"Not considering circuit with unknown router.");
88 return 0; /* this circuit is screwed and doesn't know it yet,
89 * or is a rendezvous circuit. */
91 if (!connection_ap_can_use_exit(conn, exitrouter)) {
92 /* can't exit from this router */
93 return 0;
95 } else { /* not general */
96 if (rend_cmp_service_ids(conn->rend_query, circ->rend_query)) {
97 /* this circ is not for this conn */
98 return 0;
101 return 1;
104 /* Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
105 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
107 static int
108 circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
110 switch (purpose) {
111 case CIRCUIT_PURPOSE_C_GENERAL:
112 /* if it's used but less dirty it's best;
113 * else if it's more recently created it's best
115 if (b->timestamp_dirty) {
116 if (a->timestamp_dirty &&
117 a->timestamp_dirty > b->timestamp_dirty)
118 return 1;
119 } else {
120 if (a->timestamp_dirty ||
121 b->build_state->is_internal ||
122 a->timestamp_created > b->timestamp_created)
123 return 1;
125 break;
126 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
127 /* the closer it is to ack_wait the better it is */
128 if (a->purpose > b->purpose)
129 return 1;
130 break;
131 case CIRCUIT_PURPOSE_C_REND_JOINED:
132 /* the closer it is to rend_joined the better it is */
133 if (a->purpose > b->purpose)
134 return 1;
135 break;
137 return 0;
140 /** Find the best circ that conn can use, preferably one which is
141 * dirty. Circ must not be too old.
143 * Conn must be defined.
145 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
147 * circ_purpose specifies what sort of circuit we must have.
148 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
150 * If it's REND_JOINED and must_be_open==0, then return the closest
151 * rendezvous-purposed circuit that you can find.
153 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
154 * closest introduce-purposed circuit that you can find.
156 static circuit_t *
157 circuit_get_best(connection_t *conn, int must_be_open, uint8_t purpose)
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,now))
170 continue;
172 /* now this is an acceptable circ to hand back. but that doesn't
173 * mean it's the *best* circ to hand back. try to decide.
175 if (!best || circuit_is_better(circ,best,purpose))
176 best = circ;
179 return best;
182 /** If we find a circuit that isn't open yet and was born this many
183 * seconds ago, then assume something went wrong, and cull it.
185 #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 30
187 /** Close all circuits that start at us, aren't open, and were born
188 * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago.
190 void
191 circuit_expire_building(time_t now)
193 circuit_t *victim, *circ = global_circuitlist;
195 while (circ) {
196 victim = circ;
197 circ = circ->next;
198 if (!CIRCUIT_IS_ORIGIN(victim))
199 continue; /* didn't originate here */
200 if (victim->marked_for_close)
201 continue; /* don't mess with marked circs */
202 if (victim->timestamp_created + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)
203 continue; /* it's young still, don't mess with it */
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). (clean).",
211 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
212 victim->purpose, victim->build_state->chosen_exit_name,
213 victim->n_circ_id);
214 else
215 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). %d secs since dirty.",
216 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
217 victim->purpose, victim->build_state->chosen_exit_name,
218 victim->n_circ_id,
219 (int)(now - victim->timestamp_dirty));
221 #endif
223 /* if circ is !open, or if it's open but purpose is a non-finished
224 * intro or rend, then mark it for close */
225 if (victim->state != CIRCUIT_STATE_OPEN ||
226 victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
227 victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
228 victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
230 /* it's a rend_ready circ, but it's already picked a query */
231 (victim->purpose == CIRCUIT_PURPOSE_C_REND_READY &&
232 victim->rend_query[0]) ||
234 /* c_rend_ready circs measure age since timestamp_dirty,
235 * because that's set when they switch purposes
237 /* rend and intro circs become dirty each time they
238 * make an introduction attempt. so timestamp_dirty
239 * will reflect the time since the last attempt.
241 ((victim->purpose == CIRCUIT_PURPOSE_C_REND_READY ||
242 victim->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED ||
243 victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
244 victim->timestamp_dirty + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)) {
245 if (victim->n_conn)
246 info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
247 victim->n_conn->address, victim->n_port, victim->n_circ_id,
248 victim->state, circuit_state_to_string(victim->state), victim->purpose);
249 else
250 info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
251 victim->n_circ_id, victim->state,
252 circuit_state_to_string(victim->state), victim->purpose);
254 circuit_log_path(LOG_INFO,LD_CIRC,victim);
255 circuit_mark_for_close(victim);
260 /** Remove any elements in <b>needed_ports</b> that are handled by an
261 * open or in-progress circuit.
263 void
264 circuit_remove_handled_ports(smartlist_t *needed_ports)
266 int i;
267 uint16_t *port;
269 for (i = 0; i < smartlist_len(needed_ports); ++i) {
270 port = smartlist_get(needed_ports, i);
271 tor_assert(*port);
272 if (circuit_stream_is_being_handled(NULL, *port, 2)) {
273 // debug(LD_CIRC,"Port %d is already being handled; removing.", port);
274 smartlist_del(needed_ports, i--);
275 tor_free(port);
276 } else {
277 debug(LD_CIRC,"Port %d is not handled.", *port);
282 /** Return 1 if at least <b>min</b> general-purpose circuits will have
283 * an acceptable exit node for conn if conn is defined, else for "*:port".
284 * Else return 0.
287 circuit_stream_is_being_handled(connection_t *conn, uint16_t port, int min)
289 circuit_t *circ;
290 routerinfo_t *exitrouter;
291 int num=0;
292 time_t now = time(NULL);
293 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
294 conn ? conn->socks_request->port : port);
296 for (circ=global_circuitlist;circ;circ = circ->next) {
297 if (CIRCUIT_IS_ORIGIN(circ) &&
298 !circ->marked_for_close &&
299 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
300 (!circ->timestamp_dirty ||
301 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now)) {
302 exitrouter = build_state_get_exit_router(circ->build_state);
303 if (exitrouter &&
304 (!need_uptime || circ->build_state->need_uptime)) {
305 int ok;
306 if (conn) {
307 ok = connection_ap_can_use_exit(conn, exitrouter);
308 } else {
309 addr_policy_result_t r =
310 router_compare_addr_to_addr_policy(0, port, exitrouter->exit_policy);
311 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
313 if (ok) {
314 if (++num >= min)
315 return 1;
320 return 0;
323 /** Don't keep more than 10 unused open circuits around. */
324 #define MAX_UNUSED_OPEN_CIRCUITS 10
326 /** Figure out how many circuits we have open that are clean. Make
327 * sure it's enough for all the upcoming behaviors we predict we'll have.
328 * But if we have too many, close the not-so-useful ones.
330 static void
331 circuit_predict_and_launch_new(void)
333 circuit_t *circ;
334 int num=0, num_internal=0, num_uptime_internal=0;
335 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
336 int port_needs_uptime=0, port_needs_capacity=1;
337 time_t now = time(NULL);
339 /* First, count how many of each type of circuit we have already. */
340 for (circ=global_circuitlist;circ;circ = circ->next) {
341 if (!CIRCUIT_IS_ORIGIN(circ))
342 continue;
343 if (circ->marked_for_close)
344 continue; /* don't mess with marked circs */
345 if (circ->timestamp_dirty)
346 continue; /* only count clean circs */
347 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
348 continue; /* only pay attention to general-purpose circs */
349 num++;
350 if (circ->build_state->is_internal)
351 num_internal++;
352 if (circ->build_state->need_uptime && circ->build_state->is_internal)
353 num_uptime_internal++;
356 /* If that's enough, then stop now. */
357 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
358 return; /* we already have many, making more probably will hurt */
360 /* Second, see if we need any more exit circuits. */
361 /* check if we know of a port that's been requested recently
362 * and no circuit is currently available that can handle it. */
363 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
364 &port_needs_capacity)) {
365 info(LD_CIRC,"Have %d clean circs (%d internal), need another exit circ.",
366 num, num_internal);
367 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
368 port_needs_uptime, port_needs_capacity, 0);
369 return;
372 /* Third, see if we need any more hidden service (server) circuits. */
373 if (num_rend_services() && num_uptime_internal < 3) {
374 info(LD_CIRC,"Have %d clean circs (%d internal), need another internal circ for my hidden service.",
375 num, num_internal);
376 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
377 1, 1, 1);
378 return;
381 /* Fourth, see if we need any more hidden service (client) circuits. */
382 if (rep_hist_get_predicted_hidserv(now, &hidserv_needs_uptime,
383 &hidserv_needs_capacity) &&
384 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
385 num_internal<2)) {
386 info(LD_CIRC,"Have %d clean circs (%d uptime-internal, %d internal),"
387 " need another hidserv circ.", num, num_uptime_internal, num_internal);
388 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
389 hidserv_needs_uptime, hidserv_needs_capacity, 1);
390 return;
394 /** Build a new test circuit every 5 minutes */
395 #define TESTING_CIRCUIT_INTERVAL 300
397 /** This function is called once a second. Its job is to make sure
398 * all services we offer have enough circuits available. Some
399 * services just want enough circuits for current tasks, whereas
400 * others want a minimum set of idle circuits hanging around.
402 void
403 circuit_build_needed_circs(time_t now)
405 static long time_to_new_circuit = 0;
407 /* launch a new circ for any pending streams that need one */
408 connection_ap_attach_pending();
410 /* make sure any hidden services have enough intro points */
411 if (has_fetched_directory)
412 rend_services_introduce();
414 if (time_to_new_circuit < now) {
415 circuit_reset_failure_count(1);
416 time_to_new_circuit = now + get_options()->NewCircuitPeriod;
417 if (proxy_mode(get_options()))
418 addressmap_clean(now);
419 circuit_expire_old_circuits();
421 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
422 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
423 if (get_options()->RunTesting &&
424 circ &&
425 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
426 log_fn(LOG_INFO,"Creating a new testing circuit.");
427 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0, 0, 0);
429 #endif
431 circuit_predict_and_launch_new();
434 /** If the stream <b>conn</b> is a member of any of the linked
435 * lists of <b>circ</b>, then remove it from the list.
437 void
438 circuit_detach_stream(circuit_t *circ, connection_t *conn)
440 connection_t *prevconn;
442 tor_assert(circ);
443 tor_assert(conn);
445 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
446 conn->on_circuit = NULL;
448 if (conn == circ->p_streams) {
449 circ->p_streams = conn->next_stream;
450 return;
452 if (conn == circ->n_streams) {
453 circ->n_streams = conn->next_stream;
454 return;
456 if (conn == circ->resolving_streams) {
457 circ->resolving_streams = conn->next_stream;
458 return;
461 for (prevconn = circ->p_streams;
462 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
463 prevconn = prevconn->next_stream)
465 if (prevconn && prevconn->next_stream) {
466 prevconn->next_stream = conn->next_stream;
467 return;
470 for (prevconn = circ->n_streams;
471 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
472 prevconn = prevconn->next_stream)
474 if (prevconn && prevconn->next_stream) {
475 prevconn->next_stream = conn->next_stream;
476 return;
479 for (prevconn = circ->resolving_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 err(LD_BUG,"edge conn not in circuit's list?");
489 tor_assert(0); /* should never get here */
492 /** Notify the global circuit list that <b>conn</b> is about to be
493 * removed and then freed.
495 * If it's an OR conn, then mark-for-close all the circuits that use
496 * that conn.
498 * If it's an edge conn, then detach it from its circ, so we don't
499 * try to reference it later.
501 void
502 circuit_about_to_close_connection(connection_t *conn)
504 /* currently, we assume it's too late to flush conn's buf here.
505 * down the road, maybe we'll consider that eof doesn't mean can't-write
507 circuit_t *circ;
509 switch (conn->type) {
510 case CONN_TYPE_OR:
511 /* Inform any pending (not attached) circs that they should give up. */
512 circuit_n_conn_done(conn, 0);
513 /* Now close all the attached circuits on it. */
514 while ((circ = circuit_get_by_conn(conn))) {
515 if (circ->n_conn == conn)
516 /* it's closing in front of us */
517 circuit_set_circid_orconn(circ, 0, NULL, P_CONN_CHANGED);
518 if (circ->p_conn == conn)
519 /* it's closing behind us */
520 circuit_set_circid_orconn(circ, 0, NULL, N_CONN_CHANGED);
521 circuit_mark_for_close(circ);
523 return;
524 case CONN_TYPE_AP:
525 case CONN_TYPE_EXIT:
527 /* It's an edge conn. Need to remove it from the linked list of
528 * conn's for this circuit. Confirm that 'end' relay command has
529 * been sent. But don't kill the circuit.
532 circ = circuit_get_by_edge_conn(conn);
533 if (!circ)
534 return;
536 circuit_detach_stream(circ, conn);
538 } /* end switch */
541 /** Find each circuit that has been dirty for too long, and has
542 * no streams on it: mark it for close.
544 static void
545 circuit_expire_old_circuits(void)
547 circuit_t *circ;
548 time_t now = time(NULL);
550 for (circ = global_circuitlist; circ; circ = circ->next) {
551 if (circ->marked_for_close)
552 continue;
553 /* If the circuit has been dirty for too long, and there are no streams
554 * on it, mark it for close.
556 if (circ->timestamp_dirty &&
557 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
558 CIRCUIT_IS_ORIGIN(circ) &&
559 !circ->p_streams /* nothing attached */ ) {
560 debug(LD_CIRC,"Closing n_circ_id %d (dirty %d secs ago, purp %d)",
561 circ->n_circ_id, (int)(now - circ->timestamp_dirty), circ->purpose);
562 /* (only general and purpose_c circs can get dirty) */
563 tor_assert(!circ->n_streams);
564 tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
565 circuit_mark_for_close(circ);
566 } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
567 circ->state == CIRCUIT_STATE_OPEN &&
568 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
569 #define CIRCUIT_UNUSED_CIRC_TIMEOUT 3600 /* an hour */
570 if (circ->timestamp_created + CIRCUIT_UNUSED_CIRC_TIMEOUT < now) {
571 debug(LD_CIRC,"Closing circuit that has been unused for %d seconds.",
572 (int)(now - circ->timestamp_created));
573 circuit_mark_for_close(circ);
579 /** A testing circuit has completed. Take whatever stats we want. */
580 static void
581 circuit_testing_opened(circuit_t *circ)
583 /* For now, we only use testing circuits to see if our ORPort is
584 reachable. But we remember reachability in onionskin_answer(),
585 so there's no need to record anything here. Just close the circ. */
586 circuit_mark_for_close(circ);
589 /** A testing circuit has failed to build. Take whatever stats we want. */
590 static void
591 circuit_testing_failed(circuit_t *circ, int at_last_hop)
593 #if 0
594 routerinfo_t *me = router_get_my_routerinfo();
596 if (!at_last_hop)
597 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
598 else
599 #endif
600 info(LD_GENERAL,"Our testing circuit (to see if your ORPort is reachable) has failed. I'll try again later.");
603 /** The circuit <b>circ</b> has just become open. Take the next
604 * step: for rendezvous circuits, we pass circ to the appropriate
605 * function in rendclient or rendservice. For general circuits, we
606 * call connection_ap_attach_pending, which looks for pending streams
607 * that could use circ.
609 void
610 circuit_has_opened(circuit_t *circ)
612 control_event_circuit_status(circ, CIRC_EVENT_BUILT);
614 switch (circ->purpose) {
615 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
616 rend_client_rendcirc_has_opened(circ);
617 connection_ap_attach_pending();
618 break;
619 case CIRCUIT_PURPOSE_C_INTRODUCING:
620 rend_client_introcirc_has_opened(circ);
621 break;
622 case CIRCUIT_PURPOSE_C_GENERAL:
623 /* Tell any AP connections that have been waiting for a new
624 * circuit that one is ready. */
625 connection_ap_attach_pending();
626 break;
627 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
628 /* at Bob, waiting for introductions */
629 rend_service_intro_has_opened(circ);
630 break;
631 case CIRCUIT_PURPOSE_S_CONNECT_REND:
632 /* at Bob, connecting to rend point */
633 rend_service_rendezvous_has_opened(circ);
634 break;
635 case CIRCUIT_PURPOSE_TESTING:
636 circuit_testing_opened(circ);
637 break;
638 default:
639 err(LD_BUG,"unhandled purpose %d",circ->purpose);
640 tor_assert(0);
644 /** Called whenever a circuit could not be successfully built.
646 void
647 circuit_build_failed(circuit_t *circ)
649 /* we should examine circ and see if it failed because of
650 * the last hop or an earlier hop. then use this info below.
652 int failed_at_last_hop = 0;
653 /* If the last hop isn't open, and the second-to-last is, we failed
654 * at the last hop. */
655 if (circ->cpath &&
656 circ->cpath->prev->state != CPATH_STATE_OPEN &&
657 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
658 failed_at_last_hop = 1;
661 switch (circ->purpose) {
662 case CIRCUIT_PURPOSE_C_GENERAL:
663 if (circ->state != CIRCUIT_STATE_OPEN) {
664 /* If we never built the circuit, note it as a failure. */
665 /* Note that we can't just check circ->cpath here, because if
666 * circuit-building failed immediately, it won't be set yet. */
667 circuit_increment_failure_count();
669 break;
670 case CIRCUIT_PURPOSE_TESTING:
671 circuit_testing_failed(circ, failed_at_last_hop);
672 break;
673 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
674 /* at Bob, waiting for introductions */
675 if (circ->state != CIRCUIT_STATE_OPEN) {
676 circuit_increment_failure_count();
678 /* no need to care here, because bob will rebuild intro
679 * points periodically. */
680 break;
681 case CIRCUIT_PURPOSE_C_INTRODUCING:
682 /* at Alice, connecting to intro point */
683 /* Don't increment failure count, since Bob may have picked
684 * the introduction point maliciously */
685 /* Alice will pick a new intro point when this one dies, if
686 * the stream in question still cares. No need to act here. */
687 break;
688 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
689 /* at Alice, waiting for Bob */
690 if (circ->state != CIRCUIT_STATE_OPEN) {
691 circuit_increment_failure_count();
693 /* Alice will pick a new rend point when this one dies, if
694 * the stream in question still cares. No need to act here. */
695 break;
696 case CIRCUIT_PURPOSE_S_CONNECT_REND:
697 /* at Bob, connecting to rend point */
698 /* Don't increment failure count, since Alice may have picked
699 * the rendezvous point maliciously */
700 info(LD_REND,
701 "Couldn't connect to Alice's chosen rend point %s (%s hop failed).",
702 build_state_get_exit_nickname(circ->build_state),
703 failed_at_last_hop?"last":"non-last");
704 rend_service_relaunch_rendezvous(circ);
705 break;
706 default:
707 /* Other cases are impossible, since this function is only called with
708 * unbuilt circuits. */
709 tor_assert(0);
713 /** Number of consecutive failures so far; should only be touched by
714 * circuit_launch_new and circuit_*_failure_count.
716 static int n_circuit_failures = 0;
717 static int did_circs_fail_last_period = 0;
719 /** Don't retry launching a new circuit if we try this many times with no
720 * success. */
721 #define MAX_CIRCUIT_FAILURES 5
723 /** Launch a new circuit; see circuit_launch_by_extend_info() for
724 * details on arguments. */
725 circuit_t *
726 circuit_launch_by_router(uint8_t purpose, routerinfo_t *exit,
727 int need_uptime, int need_capacity, int internal)
729 circuit_t *circ;
730 extend_info_t *info = NULL;
731 if (exit)
732 info = extend_info_from_router(exit);
733 circ = circuit_launch_by_extend_info(purpose, info, need_uptime, need_capacity,
734 internal);
735 if (info)
736 extend_info_free(info);
737 return circ;
740 /** Launch a new circuit with purpose <b>purpose</b> and exit node <b>info</b>
741 * (or NULL to select a random exit node). If <b>need_uptime</b> is true,
742 * choose among routers with high uptime. If <b>need_capacity</b> is true,
743 * choose among routers with high bandwidth. If <b>internal</b> is true, the
744 * last hop need not be an exit node. Return the newly allocated circuit on
745 * success, or NULL on failure. */
746 circuit_t *
747 circuit_launch_by_extend_info(uint8_t purpose, extend_info_t *info,
748 int need_uptime, int need_capacity, int internal)
750 circuit_t *circ;
752 if (!has_fetched_directory) {
753 debug(LD_CIRC,"Haven't fetched directory yet; canceling circuit launch.");
754 return NULL;
757 if ((info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
758 purpose != CIRCUIT_PURPOSE_TESTING) {
759 /* see if there are appropriate circs available to cannibalize. */
760 if ((circ = circuit_get_clean_open(CIRCUIT_PURPOSE_C_GENERAL, need_uptime,
761 need_capacity, internal))) {
762 info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
763 build_state_get_exit_nickname(circ->build_state), purpose);
764 circ->purpose = purpose;
765 /* reset the birth date of this circ, else expire_building
766 * will see it and think it's been trying to build since it
767 * began. */
768 circ->timestamp_created = time(NULL);
769 switch (purpose) {
770 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
771 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
772 /* it's ready right now */
773 break;
774 case CIRCUIT_PURPOSE_C_INTRODUCING:
775 case CIRCUIT_PURPOSE_S_CONNECT_REND:
776 case CIRCUIT_PURPOSE_C_GENERAL:
777 /* need to add a new hop */
778 tor_assert(info);
779 if (circuit_extend_to_new_exit(circ, info) < 0)
780 return NULL;
781 break;
782 default:
783 warn(LD_BUG, "Bug: unexpected purpose %d when cannibalizing a general circ.", purpose);
784 tor_fragile_assert();
785 return NULL;
787 return circ;
791 if (did_circs_fail_last_period &&
792 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
793 /* too many failed circs in a row. don't try. */
794 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
795 return NULL;
798 /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
799 return circuit_establish_circuit(purpose, info,
800 need_uptime, need_capacity, internal);
803 /** Launch a new circuit; see circuit_launch_by_extend_info() for
804 * details on arguments. */
805 circuit_t *
806 circuit_launch_by_nickname(uint8_t purpose, const char *exit_nickname,
807 int need_uptime, int need_capacity, int internal)
809 routerinfo_t *router = NULL;
811 if (exit_nickname) {
812 router = router_get_by_nickname(exit_nickname, 1);
813 if (!router) {
814 /*XXXXNM domain? */
815 warn(LD_GENERAL, "No such OR as '%s'", exit_nickname);
816 return NULL;
819 return circuit_launch_by_router(purpose, router,
820 need_uptime, need_capacity, internal);
823 /** Record another failure at opening a general circuit. When we have
824 * too many, we'll stop trying for the remainder of this minute.
826 static void
827 circuit_increment_failure_count(void)
829 ++n_circuit_failures;
830 debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
833 /** Reset the failure count for opening general circuits. This means
834 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
835 * stopping again.
837 void
838 circuit_reset_failure_count(int timeout)
840 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
841 did_circs_fail_last_period = 1;
842 else
843 did_circs_fail_last_period = 0;
844 n_circuit_failures = 0;
847 /** Find an open circ that we're happy with: return 1. If there isn't
848 * one, and there isn't one on the way, launch one and return 0. If it
849 * will never work, return -1.
851 * Write the found or in-progress or launched circ into *circp.
853 static int
854 circuit_get_open_circ_or_launch(connection_t *conn,
855 uint8_t desired_circuit_purpose,
856 circuit_t **circp)
858 circuit_t *circ;
859 int is_resolve;
860 int need_uptime;
862 tor_assert(conn);
863 tor_assert(circp);
864 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
865 is_resolve = conn->socks_request->command == SOCKS_COMMAND_RESOLVE;
867 circ = circuit_get_best(conn, 1, desired_circuit_purpose);
869 if (circ) {
870 *circp = circ;
871 return 1; /* we're happy */
874 if (!has_fetched_directory) {
875 if (!connection_get_by_type(CONN_TYPE_DIR)) {
876 notice(LD_APP|LD_DIR,"Application request when we're believed to be offline. Optimistically trying directory fetches again.");
877 router_reset_status_download_failures();
878 router_reset_descriptor_download_failures();
879 update_networkstatus_downloads(time(NULL));
881 /* XXXX011 NM This should be a generic "retry all directory fetches". */
882 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1); /*XXXX011NM*/
884 /* the stream will be dealt with when has_fetched_directory becomes
885 * 1, or when all directory attempts fail and directory_all_unreachable()
886 * kills it.
888 return 0;
891 need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
892 conn->socks_request->port);
894 /* Do we need to check exit policy? */
895 if (!is_resolve && !connection_edge_is_rendezvous_stream(conn)) {
896 struct in_addr in;
897 uint32_t addr = 0;
898 if (tor_inet_aton(conn->socks_request->address, &in))
899 addr = ntohl(in.s_addr);
900 if (router_exit_policy_all_routers_reject(addr, conn->socks_request->port,
901 need_uptime)) {
902 /* LD_GENERAL? LD_APP? ???? NM */
903 notice(LD_CIRC,"No Tor server exists that allows exit to %s:%d. Rejecting.",
904 safe_str(conn->socks_request->address), conn->socks_request->port);
905 return -1;
909 /* is one already on the way? */
910 circ = circuit_get_best(conn, 0, desired_circuit_purpose);
911 if (!circ) {
912 extend_info_t *extend_info=NULL;
913 uint8_t new_circ_purpose;
914 int is_internal;
916 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
917 /* need to pick an intro point */
918 extend_info = rend_client_get_random_intro(conn->rend_query);
919 if (!extend_info) {
920 info(LD_REND,"No intro points for '%s': refetching service descriptor.",
921 safe_str(conn->rend_query));
922 rend_client_refetch_renddesc(conn->rend_query);
923 conn->state = AP_CONN_STATE_RENDDESC_WAIT;
924 return 0;
926 info(LD_REND,"Chose %s as intro point for %s.",
927 extend_info->nickname, safe_str(conn->rend_query));
930 /* If we have specified a particular exit node for our
931 * connection, then be sure to open a circuit to that exit node.
933 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
934 if (conn->chosen_exit_name) {
935 routerinfo_t *r;
936 if (!(r = router_get_by_nickname(conn->chosen_exit_name, 1))) {
937 /*XXXX NM domain? */
938 notice(LD_CIRC,"Requested exit point '%s' is not known. Closing.",
939 conn->chosen_exit_name);
940 return -1;
942 extend_info = extend_info_from_router(r);
946 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
947 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
948 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
949 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
950 else
951 new_circ_purpose = desired_circuit_purpose;
953 is_internal = (new_circ_purpose != CIRCUIT_PURPOSE_C_GENERAL || is_resolve);
954 circ = circuit_launch_by_extend_info(
955 new_circ_purpose, extend_info, need_uptime, 1, is_internal);
956 if (extend_info)
957 extend_info_free(extend_info);
959 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
960 /* help predict this next time */
961 rep_hist_note_used_hidserv(time(NULL), need_uptime, 1);
962 if (circ) {
963 /* write the service_id into circ */
964 strlcpy(circ->rend_query, conn->rend_query, sizeof(circ->rend_query));
965 if (circ->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
966 circ->state == CIRCUIT_STATE_OPEN)
967 rend_client_rendcirc_has_opened(circ);
971 if (!circ)
972 info(LD_APP,
973 "No safe circuit (purpose %d) ready for edge connection; delaying.",
974 desired_circuit_purpose);
975 *circp = circ;
976 return 0;
979 /** Attach the AP stream <b>apconn</b> to circ's linked list of
980 * p_streams. Also set apconn's cpath_layer to the last hop in
981 * circ's cpath.
983 static void
984 link_apconn_to_circ(connection_t *apconn, circuit_t *circ)
986 /* add it into the linked list of streams on this circuit */
987 debug(LD_APP|LD_CIRC,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
988 apconn->timestamp_lastread = time(NULL); /* reset it, so we can measure circ timeouts */
989 apconn->next_stream = circ->p_streams;
990 apconn->on_circuit = circ;
991 /* assert_connection_ok(conn, time(NULL)); */
992 circ->p_streams = apconn;
994 tor_assert(CIRCUIT_IS_ORIGIN(circ));
995 tor_assert(circ->cpath);
996 tor_assert(circ->cpath->prev);
997 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
998 apconn->cpath_layer = circ->cpath->prev;
1001 /** If an exit wasn't specifically chosen, save the history for future
1002 * use */
1003 static void
1004 consider_recording_trackhost(connection_t *conn, circuit_t *circ)
1006 int found_needle = 0;
1007 char *str;
1008 or_options_t *options = get_options();
1009 size_t len;
1010 char *new_address;
1012 /* Search the addressmap for this conn's destination. */
1013 /* If he's not in the address map.. */
1014 if (!options->TrackHostExits ||
1015 addressmap_already_mapped(conn->socks_request->address))
1016 return; /* nothing to track, or already mapped */
1018 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1019 if (cp[0] == '.') { /* match end */
1020 /* XXX strstr is probably really bad here */
1021 if ((str = strstr(conn->socks_request->address, &cp[1]))) {
1022 if (str == conn->socks_request->address
1023 || strcmp(str, &cp[1]) == 0) {
1024 found_needle = 1;
1027 } else if (strcmp(cp, conn->socks_request->address) == 0) {
1028 found_needle = 1;
1032 if (!found_needle || !circ->build_state->chosen_exit)
1033 return;
1035 /* Add this exit/hostname pair to the addressmap. */
1036 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1037 strlen(circ->build_state->chosen_exit->nickname) + 1 /* '.' */ +
1038 strlen("exit") + 1 /* '\0' */;
1039 new_address = tor_malloc(len);
1041 tor_snprintf(new_address, len, "%s.%s.exit",
1042 conn->socks_request->address,
1043 circ->build_state->chosen_exit->nickname);
1045 addressmap_register(conn->socks_request->address, new_address,
1046 time(NULL) + options->TrackHostExitsExpire);
1049 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and
1050 * send a begin or resolve cell as appropriate. Return values are as
1051 * for connection_ap_handshake_attach_circuit. */
1053 connection_ap_handshake_attach_chosen_circuit(connection_t *conn,
1054 circuit_t *circ)
1056 tor_assert(conn);
1057 tor_assert(conn->type == CONN_TYPE_AP);
1058 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
1059 conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
1060 tor_assert(conn->socks_request);
1061 tor_assert(circ);
1062 tor_assert(circ->state == CIRCUIT_STATE_OPEN);
1064 conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1066 if (!circ->timestamp_dirty)
1067 circ->timestamp_dirty = time(NULL);
1069 link_apconn_to_circ(conn, circ);
1070 tor_assert(conn->socks_request);
1071 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
1072 consider_recording_trackhost(conn, circ);
1073 if (connection_ap_handshake_send_begin(conn, circ)<0)
1074 return -1;
1075 } else {
1076 if (connection_ap_handshake_send_resolve(conn, circ)<0)
1077 return -1;
1080 return 1;
1083 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1084 * we don't find one: if conn cannot be handled by any known nodes,
1085 * warn and return -1 (conn needs to die);
1086 * else launch new circuit (if necessary) and return 0.
1087 * Otherwise, associate conn with a safe live circuit, do the
1088 * right next step, and return 1.
1091 connection_ap_handshake_attach_circuit(connection_t *conn)
1093 int retval;
1094 int conn_age;
1096 tor_assert(conn);
1097 tor_assert(conn->type == CONN_TYPE_AP);
1098 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
1099 tor_assert(conn->socks_request);
1101 conn_age = time(NULL) - conn->timestamp_created;
1102 if (conn_age > CONN_AP_MAX_ATTACH_DELAY) {
1103 notice(LD_APP,"Tried for %d seconds to get a connection to %s:%d. Giving up.",
1104 conn_age, safe_str(conn->socks_request->address),
1105 conn->socks_request->port);
1106 return -1;
1109 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1110 circuit_t *circ=NULL;
1112 if (conn->chosen_exit_name) {
1113 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1114 if (!router) {
1115 warn(LD_APP,"Requested exit point '%s' is not known. Closing.",
1116 conn->chosen_exit_name);
1117 return -1;
1119 if (!connection_ap_can_use_exit(conn, router)) {
1120 warn(LD_APP, "Requested exit point '%s' would refuse request. Closing.",
1121 conn->chosen_exit_name);
1122 return -1;
1126 /* find the circuit that we should use, if there is one. */
1127 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1128 if (retval < 1)
1129 return retval;
1131 debug(LD_APP|LD_CIRC,"Attaching apconn to circ %d (stream %d sec old).",
1132 circ->n_circ_id, conn_age);
1133 /* here, print the circ's path. so people can figure out which circs are sucking. */
1134 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1136 /* We have found a suitable circuit for our conn. Hurray. */
1137 return connection_ap_handshake_attach_chosen_circuit(conn, circ);
1139 } else { /* we're a rendezvous conn */
1140 circuit_t *rendcirc=NULL, *introcirc=NULL;
1142 tor_assert(!conn->cpath_layer);
1144 /* start by finding a rendezvous circuit for us */
1146 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1147 if (retval < 0) return -1; /* failed */
1149 if (retval > 0) {
1150 tor_assert(rendcirc);
1151 /* one is already established, attach */
1152 info(LD_REND,
1153 "rend joined circ %d already here. attaching. (stream %d sec old)",
1154 rendcirc->n_circ_id, conn_age);
1155 /* Mark rendezvous circuits as 'newly dirty' every time you use
1156 * them, since the process of rebuilding a rendezvous circ is so
1157 * expensive. There is a tradeoffs between linkability and
1158 * feasibility, at this point.
1160 rendcirc->timestamp_dirty = time(NULL);
1161 link_apconn_to_circ(conn, rendcirc);
1162 if (connection_ap_handshake_send_begin(conn, rendcirc) < 0)
1163 return 0; /* already marked, let them fade away */
1164 return 1;
1167 if (rendcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
1168 info(LD_REND,"pending-join circ %d already here, with intro ack. Stalling. (stream %d sec old)", rendcirc->n_circ_id, conn_age);
1169 return 0;
1172 /* it's on its way. find an intro circ. */
1173 retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1174 if (retval < 0) return -1; /* failed */
1176 if (retval > 0) {
1177 /* one has already sent the intro. keep waiting. */
1178 tor_assert(introcirc);
1179 info(LD_REND,
1180 "Intro circ %d present and awaiting ack (rend %d). Stalling. (stream %d sec old)",
1181 introcirc->n_circ_id, rendcirc ? rendcirc->n_circ_id : 0, conn_age);
1182 return 0;
1185 /* now rendcirc and introcirc are each either undefined or not finished */
1187 if (rendcirc && introcirc && rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1188 info(LD_REND,"ready rend circ %d already here (no intro-ack yet on intro %d). (stream %d sec old)",
1189 rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
1191 tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1192 if (introcirc->state == CIRCUIT_STATE_OPEN) {
1193 info(LD_REND,"found open intro circ %d (rend %d); sending introduction. (stream %d sec old)",
1194 introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
1195 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1196 return -1;
1198 rendcirc->timestamp_dirty = time(NULL);
1199 introcirc->timestamp_dirty = time(NULL);
1200 assert_circuit_ok(rendcirc);
1201 assert_circuit_ok(introcirc);
1202 return 0;
1206 info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. Stalling conn. (%d sec old)",
1207 introcirc ? introcirc->n_circ_id : 0,
1208 rendcirc ? rendcirc->n_circ_id : 0, conn_age);
1209 return 0;