Make new logging stuff work on windows; fix a couple of windows typos.
[tor.git] / src / or / circuituse.c
blobd46537ace790c4a675170d96ceb072619a23d3be
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 #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
32 circuit_is_acceptable(circuit_t *circ,
33 connection_t *conn,
34 int must_be_open,
35 uint8_t purpose,
36 time_t now)
38 routerinfo_t *exitrouter;
39 tor_assert(circ);
40 tor_assert(conn);
41 tor_assert(conn->socks_request);
43 if (!CIRCUIT_IS_ORIGIN(circ))
44 return 0; /* this circ doesn't start at us */
45 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
46 return 0; /* ignore non-open circs */
47 if (circ->marked_for_close)
48 return 0;
50 /* if this circ isn't our purpose, skip. */
51 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
52 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
53 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
54 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
55 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
56 return 0;
57 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT && !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 (!circ->build_state->need_uptime &&
80 smartlist_string_num_isin(get_options()->LongLivedPorts,
81 conn->socks_request->port))
82 return 0;
84 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
85 if (!exitrouter) {
86 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)
158 circuit_t *circ, *best=NULL;
159 time_t now = time(NULL);
161 tor_assert(conn);
163 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
164 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
165 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
167 for (circ=global_circuitlist;circ;circ = circ->next) {
168 if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,now))
169 continue;
171 /* now this is an acceptable circ to hand back. but that doesn't
172 * mean it's the *best* circ to hand back. try to decide.
174 if (!best || circuit_is_better(circ,best,purpose))
175 best = circ;
178 return best;
181 /** If we find a circuit that isn't open yet and was born this many
182 * seconds ago, then assume something went wrong, and cull it.
184 #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 30
186 /** Close all circuits that start at us, aren't open, and were born
187 * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago.
189 void
190 circuit_expire_building(time_t now)
192 circuit_t *victim, *circ = global_circuitlist;
194 while (circ) {
195 victim = circ;
196 circ = circ->next;
197 if (!CIRCUIT_IS_ORIGIN(victim))
198 continue; /* didn't originate here */
199 if (victim->marked_for_close)
200 continue; /* don't mess with marked circs */
201 if (victim->timestamp_created + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)
202 continue; /* it's young still, don't mess with it */
204 #if 0
205 /* some debug logs, to help track bugs */
206 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
207 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
208 if (!victim->timestamp_dirty)
209 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). (clean).",
210 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
211 victim->purpose, victim->build_state->chosen_exit_name,
212 victim->n_circ_id);
213 else
214 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). %d secs since dirty.",
215 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
216 victim->purpose, victim->build_state->chosen_exit_name,
217 victim->n_circ_id,
218 (int)(now - victim->timestamp_dirty));
220 #endif
222 /* if circ is !open, or if it's open but purpose is a non-finished
223 * intro or rend, then mark it for close */
224 if (victim->state != CIRCUIT_STATE_OPEN ||
225 victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
226 victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
227 victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
229 /* it's a rend_ready circ, but it's already picked a query */
230 (victim->purpose == CIRCUIT_PURPOSE_C_REND_READY &&
231 victim->rend_query[0]) ||
233 /* c_rend_ready circs measure age since timestamp_dirty,
234 * because that's set when they switch purposes
236 /* rend and intro circs become dirty each time they
237 * make an introduction attempt. so timestamp_dirty
238 * will reflect the time since the last attempt.
240 ((victim->purpose == CIRCUIT_PURPOSE_C_REND_READY ||
241 victim->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED ||
242 victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
243 victim->timestamp_dirty + MIN_SECONDS_BEFORE_EXPIRING_CIRC > now)) {
244 if (victim->n_conn)
245 info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
246 victim->n_conn->address, victim->n_port, victim->n_circ_id,
247 victim->state, circuit_state_to_string(victim->state), victim->purpose);
248 else
249 info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
250 victim->n_circ_id, victim->state,
251 circuit_state_to_string(victim->state), victim->purpose);
253 circuit_log_path(LOG_INFO,LD_CIRC,victim);
254 circuit_mark_for_close(victim);
259 /** Remove any elements in <b>needed_ports</b> that are handled by an
260 * open or in-progress circuit.
262 void
263 circuit_remove_handled_ports(smartlist_t *needed_ports)
265 int i;
266 uint16_t *port;
268 for (i = 0; i < smartlist_len(needed_ports); ++i) {
269 port = smartlist_get(needed_ports, i);
270 tor_assert(*port);
271 if (circuit_stream_is_being_handled(NULL, *port, 2)) {
272 // debug(LD_CIRC,"Port %d is already being handled; removing.", port);
273 smartlist_del(needed_ports, i--);
274 tor_free(port);
275 } else {
276 debug(LD_CIRC,"Port %d is not handled.", *port);
281 /** Return 1 if at least <b>min</b> general-purpose circuits will have
282 * an acceptable exit node for conn if conn is defined, else for "*:port".
283 * Else return 0.
286 circuit_stream_is_being_handled(connection_t *conn, uint16_t port, int min)
288 circuit_t *circ;
289 routerinfo_t *exitrouter;
290 int num=0;
291 time_t now = time(NULL);
292 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
293 conn ? conn->socks_request->port : port);
295 for (circ=global_circuitlist;circ;circ = circ->next) {
296 if (CIRCUIT_IS_ORIGIN(circ) &&
297 !circ->marked_for_close &&
298 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
299 (!circ->timestamp_dirty ||
300 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now)) {
301 exitrouter = build_state_get_exit_router(circ->build_state);
302 if (exitrouter &&
303 (!need_uptime || circ->build_state->need_uptime)) {
304 int ok;
305 if (conn) {
306 ok = connection_ap_can_use_exit(conn, exitrouter);
307 } else {
308 addr_policy_result_t r =
309 router_compare_addr_to_addr_policy(0, port, exitrouter->exit_policy);
310 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
312 if (ok) {
313 if (++num >= min)
314 return 1;
319 return 0;
322 /** Don't keep more than 10 unused open circuits around. */
323 #define MAX_UNUSED_OPEN_CIRCUITS 10
325 /** Figure out how many circuits we have open that are clean. Make
326 * sure it's enough for all the upcoming behaviors we predict we'll have.
327 * But if we have too many, close the not-so-useful ones.
329 static void
330 circuit_predict_and_launch_new(void)
332 circuit_t *circ;
333 int num=0, num_internal=0, num_uptime_internal=0;
334 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
335 int port_needs_uptime=0, port_needs_capacity=1;
336 time_t now = time(NULL);
338 /* First, count how many of each type of circuit we have already. */
339 for (circ=global_circuitlist;circ;circ = circ->next) {
340 if (!CIRCUIT_IS_ORIGIN(circ))
341 continue;
342 if (circ->marked_for_close)
343 continue; /* don't mess with marked circs */
344 if (circ->timestamp_dirty)
345 continue; /* only count clean circs */
346 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
347 continue; /* only pay attention to general-purpose circs */
348 num++;
349 if (circ->build_state->is_internal)
350 num_internal++;
351 if (circ->build_state->need_uptime && circ->build_state->is_internal)
352 num_uptime_internal++;
355 /* If that's enough, then stop now. */
356 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
357 return; /* we already have many, making more probably will hurt */
359 /* Second, see if we need any more exit circuits. */
360 /* check if we know of a port that's been requested recently
361 * and no circuit is currently available that can handle it. */
362 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
363 &port_needs_capacity)) {
364 info(LD_CIRC,"Have %d clean circs (%d internal), need another exit circ.",
365 num, num_internal);
366 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
367 port_needs_uptime, port_needs_capacity, 0);
368 return;
371 /* Third, see if we need any more hidden service (server) circuits. */
372 if (num_rend_services() && num_uptime_internal < 3) {
373 info(LD_CIRC,"Have %d clean circs (%d internal), need another internal circ for my hidden service.",
374 num, num_internal);
375 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
376 1, 1, 1);
377 return;
380 /* Fourth, see if we need any more hidden service (client) circuits. */
381 if (rep_hist_get_predicted_hidserv(now, &hidserv_needs_uptime,
382 &hidserv_needs_capacity) &&
383 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
384 num_internal<2)) {
385 info(LD_CIRC,"Have %d clean circs (%d uptime-internal, %d internal),"
386 " need another hidserv circ.", num, num_uptime_internal, num_internal);
387 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL,
388 hidserv_needs_uptime, hidserv_needs_capacity, 1);
389 return;
393 /** Build a new test circuit every 5 minutes */
394 #define TESTING_CIRCUIT_INTERVAL 300
396 /** This function is called once a second. Its job is to make sure
397 * all services we offer have enough circuits available. Some
398 * services just want enough circuits for current tasks, whereas
399 * others want a minimum set of idle circuits hanging around.
401 void
402 circuit_build_needed_circs(time_t now)
404 static long time_to_new_circuit = 0;
406 /* launch a new circ for any pending streams that need one */
407 connection_ap_attach_pending();
409 /* make sure any hidden services have enough intro points */
410 if (has_fetched_directory)
411 rend_services_introduce();
413 if (time_to_new_circuit < now) {
414 circuit_reset_failure_count(1);
415 time_to_new_circuit = now + get_options()->NewCircuitPeriod;
416 if (proxy_mode(get_options()))
417 addressmap_clean(now);
418 circuit_expire_old_circuits();
420 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
421 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
422 if (get_options()->RunTesting &&
423 circ &&
424 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
425 log_fn(LOG_INFO,"Creating a new testing circuit.");
426 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0, 0, 0);
428 #endif
430 circuit_predict_and_launch_new();
433 /** If the stream <b>conn</b> is a member of any of the linked
434 * lists of <b>circ</b>, then remove it from the list.
436 void
437 circuit_detach_stream(circuit_t *circ, connection_t *conn)
439 connection_t *prevconn;
441 tor_assert(circ);
442 tor_assert(conn);
444 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
445 conn->on_circuit = NULL;
447 if (conn == circ->p_streams) {
448 circ->p_streams = conn->next_stream;
449 return;
451 if (conn == circ->n_streams) {
452 circ->n_streams = conn->next_stream;
453 return;
455 if (conn == circ->resolving_streams) {
456 circ->resolving_streams = conn->next_stream;
457 return;
460 for (prevconn = circ->p_streams;
461 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
462 prevconn = prevconn->next_stream)
464 if (prevconn && prevconn->next_stream) {
465 prevconn->next_stream = conn->next_stream;
466 return;
469 for (prevconn = circ->n_streams;
470 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
471 prevconn = prevconn->next_stream)
473 if (prevconn && prevconn->next_stream) {
474 prevconn->next_stream = conn->next_stream;
475 return;
478 for (prevconn = circ->resolving_streams;
479 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
480 prevconn = prevconn->next_stream)
482 if (prevconn && prevconn->next_stream) {
483 prevconn->next_stream = conn->next_stream;
484 return;
487 err(LD_BUG,"edge conn not in circuit's list?");
488 tor_assert(0); /* should never get here */
491 /** Notify the global circuit list that <b>conn</b> is about to be
492 * removed and then freed.
494 * If it's an OR conn, then mark-for-close all the circuits that use
495 * that conn.
497 * If it's an edge conn, then detach it from its circ, so we don't
498 * try to reference it later.
500 void
501 circuit_about_to_close_connection(connection_t *conn)
503 /* currently, we assume it's too late to flush conn's buf here.
504 * down the road, maybe we'll consider that eof doesn't mean can't-write
506 circuit_t *circ;
508 switch (conn->type) {
509 case CONN_TYPE_OR:
510 /* Inform any pending (not attached) circs that they should give up. */
511 circuit_n_conn_done(conn, 0);
512 /* Now close all the attached circuits on it. */
513 while ((circ = circuit_get_by_conn(conn))) {
514 if (circ->n_conn == conn)
515 /* it's closing in front of us */
516 circuit_set_circid_orconn(circ, 0, NULL, P_CONN_CHANGED);
517 if (circ->p_conn == conn)
518 /* it's closing behind us */
519 circuit_set_circid_orconn(circ, 0, NULL, N_CONN_CHANGED);
520 circuit_mark_for_close(circ);
522 return;
523 case CONN_TYPE_AP:
524 case CONN_TYPE_EXIT:
526 /* It's an edge conn. Need to remove it from the linked list of
527 * conn's for this circuit. Confirm that 'end' relay command has
528 * been sent. But don't kill the circuit.
531 circ = circuit_get_by_edge_conn(conn);
532 if (!circ)
533 return;
535 circuit_detach_stream(circ, conn);
537 } /* end switch */
540 /** Find each circuit that has been dirty for too long, and has
541 * no streams on it: mark it for close.
543 static void
544 circuit_expire_old_circuits(void)
546 circuit_t *circ;
547 time_t now = time(NULL);
549 for (circ = global_circuitlist; circ; circ = circ->next) {
550 if (circ->marked_for_close)
551 continue;
552 /* If the circuit has been dirty for too long, and there are no streams
553 * on it, mark it for close.
555 if (circ->timestamp_dirty &&
556 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
557 CIRCUIT_IS_ORIGIN(circ) &&
558 !circ->p_streams /* nothing attached */ ) {
559 debug(LD_CIRC,"Closing n_circ_id %d (dirty %d secs ago, purp %d)",
560 circ->n_circ_id, (int)(now - circ->timestamp_dirty), circ->purpose);
561 /* (only general and purpose_c circs can get dirty) */
562 tor_assert(!circ->n_streams);
563 tor_assert(circ->purpose <= CIRCUIT_PURPOSE_C_REND_JOINED);
564 circuit_mark_for_close(circ);
565 } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
566 circ->state == CIRCUIT_STATE_OPEN &&
567 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
568 #define CIRCUIT_UNUSED_CIRC_TIMEOUT 3600 /* an hour */
569 if (circ->timestamp_created + CIRCUIT_UNUSED_CIRC_TIMEOUT < now) {
570 debug(LD_CIRC,"Closing circuit that has been unused for %d seconds.",
571 (int)(now - circ->timestamp_created));
572 circuit_mark_for_close(circ);
578 /** A testing circuit has completed. Take whatever stats we want. */
579 static void
580 circuit_testing_opened(circuit_t *circ)
582 /* For now, we only use testing circuits to see if our ORPort is
583 reachable. But we remember reachability in onionskin_answer(),
584 so there's no need to record anything here. Just close the circ. */
585 circuit_mark_for_close(circ);
588 /** A testing circuit has failed to build. Take whatever stats we want. */
589 static void
590 circuit_testing_failed(circuit_t *circ, int at_last_hop)
592 #if 0
593 routerinfo_t *me = router_get_my_routerinfo();
595 if (!at_last_hop)
596 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
597 else
598 #endif
599 info(LD_GENERAL,"Our testing circuit (to see if your ORPort is reachable) has failed. I'll try again later.");
602 /** The circuit <b>circ</b> has just become open. Take the next
603 * step: for rendezvous circuits, we pass circ to the appropriate
604 * function in rendclient or rendservice. For general circuits, we
605 * call connection_ap_attach_pending, which looks for pending streams
606 * that could use circ.
608 void
609 circuit_has_opened(circuit_t *circ)
611 control_event_circuit_status(circ, CIRC_EVENT_BUILT);
613 switch (circ->purpose) {
614 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
615 rend_client_rendcirc_has_opened(circ);
616 connection_ap_attach_pending();
617 break;
618 case CIRCUIT_PURPOSE_C_INTRODUCING:
619 rend_client_introcirc_has_opened(circ);
620 break;
621 case CIRCUIT_PURPOSE_C_GENERAL:
622 /* Tell any AP connections that have been waiting for a new
623 * circuit that one is ready. */
624 connection_ap_attach_pending();
625 break;
626 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
627 /* at Bob, waiting for introductions */
628 rend_service_intro_has_opened(circ);
629 break;
630 case CIRCUIT_PURPOSE_S_CONNECT_REND:
631 /* at Bob, connecting to rend point */
632 rend_service_rendezvous_has_opened(circ);
633 break;
634 case CIRCUIT_PURPOSE_TESTING:
635 circuit_testing_opened(circ);
636 break;
637 default:
638 err(LD_BUG,"unhandled purpose %d",circ->purpose);
639 tor_assert(0);
643 /** Called whenever a circuit could not be successfully built.
645 void
646 circuit_build_failed(circuit_t *circ)
648 /* we should examine circ and see if it failed because of
649 * the last hop or an earlier hop. then use this info below.
651 int failed_at_last_hop = 0;
652 /* If the last hop isn't open, and the second-to-last is, we failed
653 * at the last hop. */
654 if (circ->cpath &&
655 circ->cpath->prev->state != CPATH_STATE_OPEN &&
656 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
657 failed_at_last_hop = 1;
660 switch (circ->purpose) {
661 case CIRCUIT_PURPOSE_C_GENERAL:
662 if (circ->state != CIRCUIT_STATE_OPEN) {
663 /* If we never built the circuit, note it as a failure. */
664 /* Note that we can't just check circ->cpath here, because if
665 * circuit-building failed immediately, it won't be set yet. */
666 circuit_increment_failure_count();
668 break;
669 case CIRCUIT_PURPOSE_TESTING:
670 circuit_testing_failed(circ, failed_at_last_hop);
671 break;
672 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
673 /* at Bob, waiting for introductions */
674 if (circ->state != CIRCUIT_STATE_OPEN) {
675 circuit_increment_failure_count();
677 /* no need to care here, because bob will rebuild intro
678 * points periodically. */
679 break;
680 case CIRCUIT_PURPOSE_C_INTRODUCING:
681 /* at Alice, connecting to intro point */
682 /* Don't increment failure count, since Bob may have picked
683 * the introduction point maliciously */
684 /* Alice will pick a new intro point when this one dies, if
685 * the stream in question still cares. No need to act here. */
686 break;
687 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
688 /* at Alice, waiting for Bob */
689 if (circ->state != CIRCUIT_STATE_OPEN) {
690 circuit_increment_failure_count();
692 /* Alice will pick a new rend point when this one dies, if
693 * the stream in question still cares. No need to act here. */
694 break;
695 case CIRCUIT_PURPOSE_S_CONNECT_REND:
696 /* at Bob, connecting to rend point */
697 /* Don't increment failure count, since Alice may have picked
698 * the rendezvous point maliciously */
699 info(LD_REND,
700 "Couldn't connect to Alice's chosen rend point %s (%s hop failed).",
701 build_state_get_exit_nickname(circ->build_state),
702 failed_at_last_hop?"last":"non-last");
703 rend_service_relaunch_rendezvous(circ);
704 break;
705 default:
706 /* Other cases are impossible, since this function is only called with
707 * unbuilt circuits. */
708 tor_assert(0);
712 /** Number of consecutive failures so far; should only be touched by
713 * circuit_launch_new and circuit_*_failure_count.
715 static int n_circuit_failures = 0;
716 static int did_circs_fail_last_period = 0;
718 /** Don't retry launching a new circuit if we try this many times with no
719 * success. */
720 #define MAX_CIRCUIT_FAILURES 5
722 /** Launch a new circuit; see circuit_launch_by_extend_info() for
723 * details on arguments. */
724 circuit_t *
725 circuit_launch_by_router(uint8_t purpose, routerinfo_t *exit,
726 int need_uptime, int need_capacity, int internal)
728 circuit_t *circ;
729 extend_info_t *info = NULL;
730 if (exit)
731 info = extend_info_from_router(exit);
732 circ = circuit_launch_by_extend_info(purpose, info, need_uptime, need_capacity,
733 internal);
734 if (info)
735 extend_info_free(info);
736 return circ;
739 /** Launch a new circuit with purpose <b>purpose</b> and exit node <b>info</b>
740 * (or NULL to select a random exit node). If <b>need_uptime</b> is true,
741 * choose among routers with high uptime. If <b>need_capacity</b> is true,
742 * choose among routers with high bandwidth. If <b>internal</b> is true, the
743 * last hop need not be an exit node. Return the newly allocated circuit on
744 * success, or NULL on failure. */
745 circuit_t *
746 circuit_launch_by_extend_info(uint8_t purpose, extend_info_t *extend_info,
747 int need_uptime, int need_capacity, int internal)
749 circuit_t *circ;
751 if (!has_fetched_directory) {
752 debug(LD_CIRC,"Haven't fetched directory yet; canceling circuit launch.");
753 return NULL;
756 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
757 purpose != CIRCUIT_PURPOSE_TESTING) {
758 /* see if there are appropriate circs available to cannibalize. */
759 circ = circuit_find_to_cannibalize(CIRCUIT_PURPOSE_C_GENERAL, extend_info,
760 need_uptime, need_capacity, internal);
761 if (circ) {
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(extend_info);
779 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
780 return NULL;
781 break;
782 default:
783 warn(LD_BUG, "Bug: unexpected purpose %d when cannibalizing a 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, extend_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;