Possible fix for broken country settings in ExcludeExitNodes.
[tor/rransom.git] / src / or / circuituse.c
bloba1c8d1c148d1df4198c0f61a8526ca05ee904711
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file circuituse.c
9 * \brief Launch the right sort of circuits and attach streams to them.
10 **/
12 #include "or.h"
14 /********* START VARIABLES **********/
16 extern circuit_t *global_circuitlist; /* from circuitlist.c */
18 /********* END VARIABLES ************/
20 static void circuit_expire_old_circuits(time_t now);
21 static void circuit_increment_failure_count(void);
23 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
24 * Else return 0.
26 static int
27 circuit_is_acceptable(circuit_t *circ, edge_connection_t *conn,
28 int must_be_open, uint8_t purpose,
29 int need_uptime, int need_internal,
30 time_t now)
32 routerinfo_t *exitrouter;
33 cpath_build_state_t *build_state;
34 tor_assert(circ);
35 tor_assert(conn);
36 tor_assert(conn->socks_request);
38 if (!CIRCUIT_IS_ORIGIN(circ))
39 return 0; /* this circ doesn't start at us */
40 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
41 return 0; /* ignore non-open circs */
42 if (circ->marked_for_close)
43 return 0;
45 /* if this circ isn't our purpose, skip. */
46 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
47 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
48 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
49 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
50 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
51 return 0;
52 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
53 !must_be_open) {
54 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
55 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
56 return 0;
57 } else {
58 if (purpose != circ->purpose)
59 return 0;
62 if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
63 if (circ->timestamp_dirty &&
64 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
65 return 0;
67 /* decide if this circ is suitable for this conn */
69 /* for rend circs, circ->cpath->prev is not the last router in the
70 * circuit, it's the magical extra bob hop. so just check the nickname
71 * of the one we meant to finish at.
73 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
74 exitrouter = build_state_get_exit_router(build_state);
76 if (need_uptime && !build_state->need_uptime)
77 return 0;
78 if (need_internal != build_state->is_internal)
79 return 0;
81 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
82 if (!exitrouter && !build_state->onehop_tunnel) {
83 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
84 return 0; /* this circuit is screwed and doesn't know it yet,
85 * or is a rendezvous circuit. */
87 if (build_state->onehop_tunnel) {
88 if (!conn->want_onehop) {
89 log_debug(LD_CIRC,"Skipping one-hop circuit.");
90 return 0;
92 tor_assert(conn->chosen_exit_name);
93 if (build_state->chosen_exit) {
94 char digest[DIGEST_LEN];
95 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
96 return 0; /* broken digest, we don't want it */
97 if (memcmp(digest, build_state->chosen_exit->identity_digest,
98 DIGEST_LEN))
99 return 0; /* this is a circuit to somewhere else */
100 if (tor_digest_is_zero(digest)) {
101 /* we don't know the digest; have to compare addr:port */
102 tor_addr_t addr;
103 int r = tor_addr_from_str(&addr, conn->socks_request->address);
104 if (r < 0 ||
105 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
106 build_state->chosen_exit->port != conn->socks_request->port)
107 return 0;
110 } else {
111 if (conn->want_onehop) {
112 /* don't use three-hop circuits -- that could hurt our anonymity. */
113 return 0;
116 if (exitrouter && !connection_ap_can_use_exit(conn, exitrouter)) {
117 /* can't exit from this router */
118 return 0;
120 } else { /* not general */
121 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
122 if ((conn->rend_data && !ocirc->rend_data) ||
123 (!conn->rend_data && ocirc->rend_data) ||
124 (conn->rend_data && ocirc->rend_data &&
125 rend_cmp_service_ids(conn->rend_data->onion_address,
126 ocirc->rend_data->onion_address))) {
127 /* this circ is not for this conn */
128 return 0;
131 return 1;
134 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
135 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
137 static int
138 circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
140 switch (purpose) {
141 case CIRCUIT_PURPOSE_C_GENERAL:
142 /* if it's used but less dirty it's best;
143 * else if it's more recently created it's best
145 if (b->timestamp_dirty) {
146 if (a->timestamp_dirty &&
147 a->timestamp_dirty > b->timestamp_dirty)
148 return 1;
149 } else {
150 if (a->timestamp_dirty ||
151 a->timestamp_created > b->timestamp_created)
152 return 1;
153 if (CIRCUIT_IS_ORIGIN(b) &&
154 TO_ORIGIN_CIRCUIT(b)->build_state->is_internal)
155 return 1;
157 break;
158 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
159 /* the closer it is to ack_wait the better it is */
160 if (a->purpose > b->purpose)
161 return 1;
162 break;
163 case CIRCUIT_PURPOSE_C_REND_JOINED:
164 /* the closer it is to rend_joined the better it is */
165 if (a->purpose > b->purpose)
166 return 1;
167 break;
169 return 0;
172 /** Find the best circ that conn can use, preferably one which is
173 * dirty. Circ must not be too old.
175 * Conn must be defined.
177 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
179 * circ_purpose specifies what sort of circuit we must have.
180 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
182 * If it's REND_JOINED and must_be_open==0, then return the closest
183 * rendezvous-purposed circuit that you can find.
185 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
186 * closest introduce-purposed circuit that you can find.
188 static origin_circuit_t *
189 circuit_get_best(edge_connection_t *conn, int must_be_open, uint8_t purpose,
190 int need_uptime, int need_internal)
192 circuit_t *circ, *best=NULL;
193 time_t now = time(NULL);
194 int intro_going_on_but_too_old = 0;
196 tor_assert(conn);
198 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
199 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
200 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
202 for (circ=global_circuitlist;circ;circ = circ->next) {
203 if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
204 need_uptime,need_internal,now))
205 continue;
207 /* XXX022 make this 15 be a function of circuit finishing times we've
208 * seen lately, a la Fallon Chen's GSoC work -RD */
209 #define REND_PARALLEL_INTRO_DELAY 15
210 if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
211 !must_be_open && circ->state != CIRCUIT_STATE_OPEN &&
212 circ->timestamp_created + REND_PARALLEL_INTRO_DELAY < now) {
213 intro_going_on_but_too_old = 1;
214 continue;
217 /* now this is an acceptable circ to hand back. but that doesn't
218 * mean it's the *best* circ to hand back. try to decide.
220 if (!best || circuit_is_better(circ,best,purpose))
221 best = circ;
224 if (!best && intro_going_on_but_too_old)
225 log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
226 "right now, but it has already taken quite a while. Starting "
227 "one in parallel.");
229 return best ? TO_ORIGIN_CIRCUIT(best) : NULL;
232 /** Check whether, according to the policies in <b>options</b>, the
233 * circuit <b>circ</b> makes sense. */
234 /* XXXX currently only checks Exclude{Exit}Nodes. It should check more. */
236 circuit_conforms_to_options(const origin_circuit_t *circ,
237 const or_options_t *options)
239 const crypt_path_t *cpath, *cpath_next = NULL;
241 for (cpath = circ->cpath; cpath && cpath_next != circ->cpath;
242 cpath = cpath_next) {
243 cpath_next = cpath->next;
245 if (routerset_contains_extendinfo(options->ExcludeNodes,
246 cpath->extend_info))
247 return 0;
249 if (cpath->next == circ->cpath) {
250 /* This is apparently the exit node. */
252 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
253 cpath->extend_info))
254 return 0;
257 return 1;
260 /** Close all circuits that start at us, aren't open, and were born
261 * at least CircuitBuildTimeout seconds ago.
263 void
264 circuit_expire_building(time_t now)
266 circuit_t *victim, *circ = global_circuitlist;
267 time_t general_cutoff = now - get_options()->CircuitBuildTimeout;
268 time_t begindir_cutoff = now - get_options()->CircuitBuildTimeout/2;
269 time_t introcirc_cutoff = begindir_cutoff;
270 cpath_build_state_t *build_state;
272 while (circ) {
273 time_t cutoff;
274 victim = circ;
275 circ = circ->next;
276 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
277 victim->marked_for_close) /* don't mess with marked circs */
278 continue;
280 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
281 if (build_state && build_state->onehop_tunnel)
282 cutoff = begindir_cutoff;
283 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
284 cutoff = introcirc_cutoff;
285 else
286 cutoff = general_cutoff;
287 if (victim->timestamp_created > cutoff)
288 continue; /* it's still young, leave it alone */
290 #if 0
291 /* some debug logs, to help track bugs */
292 if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
293 victim->timestamp_created <= introcirc_cutoff &&
294 victim->timestamp_created > general_cutoff)
295 log_info(LD_REND|LD_CIRC, "Timing out introduction circuit which we "
296 "would not have done if it had been a general circuit.");
298 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
299 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
300 if (!victim->timestamp_dirty)
301 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d)."
302 "(clean).",
303 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
304 victim->purpose, victim->build_state->chosen_exit_name,
305 victim->n_circ_id);
306 else
307 log_fn(LOG_DEBUG,"Considering %sopen purp %d to %s (circid %d). "
308 "%d secs since dirty.",
309 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
310 victim->purpose, victim->build_state->chosen_exit_name,
311 victim->n_circ_id,
312 (int)(now - victim->timestamp_dirty));
314 #endif
316 /* if circ is !open, or if it's open but purpose is a non-finished
317 * intro or rend, then mark it for close */
318 if (victim->state == CIRCUIT_STATE_OPEN) {
319 switch (victim->purpose) {
320 default: /* most open circuits can be left alone. */
321 continue; /* yes, continue inside a switch refers to the nearest
322 * enclosing loop. C is smart. */
323 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
324 case CIRCUIT_PURPOSE_C_INTRODUCING:
325 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
326 break; /* too old, need to die */
327 case CIRCUIT_PURPOSE_C_REND_READY:
328 /* it's a rend_ready circ -- has it already picked a query? */
329 /* c_rend_ready circs measure age since timestamp_dirty,
330 * because that's set when they switch purposes
332 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
333 victim->timestamp_dirty > cutoff)
334 continue;
335 break;
336 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
337 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
338 /* rend and intro circs become dirty each time they
339 * make an introduction attempt. so timestamp_dirty
340 * will reflect the time since the last attempt.
342 if (victim->timestamp_dirty > cutoff)
343 continue;
344 break;
348 if (victim->n_conn)
349 log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
350 victim->n_conn->_base.address, victim->n_conn->_base.port,
351 victim->n_circ_id,
352 victim->state, circuit_state_to_string(victim->state),
353 victim->purpose);
354 else
355 log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
356 victim->n_circ_id, victim->state,
357 circuit_state_to_string(victim->state), victim->purpose);
359 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
360 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
364 /** Remove any elements in <b>needed_ports</b> that are handled by an
365 * open or in-progress circuit.
367 void
368 circuit_remove_handled_ports(smartlist_t *needed_ports)
370 int i;
371 uint16_t *port;
373 for (i = 0; i < smartlist_len(needed_ports); ++i) {
374 port = smartlist_get(needed_ports, i);
375 tor_assert(*port);
376 if (circuit_stream_is_being_handled(NULL, *port,
377 MIN_CIRCUITS_HANDLING_STREAM)) {
378 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
379 smartlist_del(needed_ports, i--);
380 tor_free(port);
381 } else {
382 log_debug(LD_CIRC,"Port %d is not handled.", *port);
387 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
388 * will have an acceptable exit node for exit stream <b>conn</b> if it
389 * is defined, else for "*:port".
390 * Else return 0.
393 circuit_stream_is_being_handled(edge_connection_t *conn,
394 uint16_t port, int min)
396 circuit_t *circ;
397 routerinfo_t *exitrouter;
398 int num=0;
399 time_t now = time(NULL);
400 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
401 conn ? conn->socks_request->port : port);
403 for (circ=global_circuitlist;circ;circ = circ->next) {
404 if (CIRCUIT_IS_ORIGIN(circ) &&
405 !circ->marked_for_close &&
406 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
407 (!circ->timestamp_dirty ||
408 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
409 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
410 if (build_state->is_internal || build_state->onehop_tunnel)
411 continue;
413 exitrouter = build_state_get_exit_router(build_state);
414 if (exitrouter && (!need_uptime || build_state->need_uptime)) {
415 int ok;
416 if (conn) {
417 ok = connection_ap_can_use_exit(conn, exitrouter);
418 } else {
419 addr_policy_result_t r = compare_addr_to_addr_policy(
420 0, port, exitrouter->exit_policy);
421 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
423 if (ok) {
424 if (++num >= min)
425 return 1;
430 return 0;
433 /** Don't keep more than this many unused open circuits around. */
434 #define MAX_UNUSED_OPEN_CIRCUITS 12
436 /** Figure out how many circuits we have open that are clean. Make
437 * sure it's enough for all the upcoming behaviors we predict we'll have.
438 * But if we have too many, close the not-so-useful ones.
440 static void
441 circuit_predict_and_launch_new(void)
443 circuit_t *circ;
444 int num=0, num_internal=0, num_uptime_internal=0;
445 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
446 int port_needs_uptime=0, port_needs_capacity=1;
447 time_t now = time(NULL);
448 int flags = 0;
450 /* First, count how many of each type of circuit we have already. */
451 for (circ=global_circuitlist;circ;circ = circ->next) {
452 cpath_build_state_t *build_state;
453 if (!CIRCUIT_IS_ORIGIN(circ))
454 continue;
455 if (circ->marked_for_close)
456 continue; /* don't mess with marked circs */
457 if (circ->timestamp_dirty)
458 continue; /* only count clean circs */
459 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
460 continue; /* only pay attention to general-purpose circs */
461 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
462 if (build_state->onehop_tunnel)
463 continue;
464 num++;
465 if (build_state->is_internal)
466 num_internal++;
467 if (build_state->need_uptime && build_state->is_internal)
468 num_uptime_internal++;
471 /* If that's enough, then stop now. */
472 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
473 return; /* we already have many, making more probably will hurt */
475 /* Second, see if we need any more exit circuits. */
476 /* check if we know of a port that's been requested recently
477 * and no circuit is currently available that can handle it. */
478 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
479 &port_needs_capacity)) {
480 if (port_needs_uptime)
481 flags |= CIRCLAUNCH_NEED_UPTIME;
482 if (port_needs_capacity)
483 flags |= CIRCLAUNCH_NEED_CAPACITY;
484 log_info(LD_CIRC,
485 "Have %d clean circs (%d internal), need another exit circ.",
486 num, num_internal);
487 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
488 return;
491 /* Third, see if we need any more hidden service (server) circuits. */
492 if (num_rend_services() && num_uptime_internal < 3) {
493 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
494 CIRCLAUNCH_IS_INTERNAL);
495 log_info(LD_CIRC,
496 "Have %d clean circs (%d internal), need another internal "
497 "circ for my hidden service.",
498 num, num_internal);
499 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
500 return;
503 /* Fourth, see if we need any more hidden service (client) circuits. */
504 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
505 &hidserv_needs_capacity) &&
506 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
507 num_internal<2)) {
508 if (hidserv_needs_uptime)
509 flags |= CIRCLAUNCH_NEED_UPTIME;
510 if (hidserv_needs_capacity)
511 flags |= CIRCLAUNCH_NEED_CAPACITY;
512 flags |= CIRCLAUNCH_IS_INTERNAL;
513 log_info(LD_CIRC,
514 "Have %d clean circs (%d uptime-internal, %d internal), need"
515 " another hidserv circ.",
516 num, num_uptime_internal, num_internal);
517 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
518 return;
522 /** Build a new test circuit every 5 minutes */
523 #define TESTING_CIRCUIT_INTERVAL 300
525 /** This function is called once a second, if router_have_min_dir_info() is
526 * true. Its job is to make sure all services we offer have enough circuits
527 * available. Some services just want enough circuits for current tasks,
528 * whereas others want a minimum set of idle circuits hanging around.
530 void
531 circuit_build_needed_circs(time_t now)
533 static time_t time_to_new_circuit = 0;
534 or_options_t *options = get_options();
536 /* launch a new circ for any pending streams that need one */
537 connection_ap_attach_pending();
539 /* make sure any hidden services have enough intro points */
540 rend_services_introduce();
542 if (time_to_new_circuit < now) {
543 circuit_reset_failure_count(1);
544 time_to_new_circuit = now + options->NewCircuitPeriod;
545 if (proxy_mode(get_options()))
546 addressmap_clean(now);
547 circuit_expire_old_circuits(now);
549 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
550 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
551 if (get_options()->RunTesting &&
552 circ &&
553 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
554 log_fn(LOG_INFO,"Creating a new testing circuit.");
555 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0);
557 #endif
559 if (!options->DisablePredictedCircuits)
560 circuit_predict_and_launch_new();
563 /** If the stream <b>conn</b> is a member of any of the linked
564 * lists of <b>circ</b>, then remove it from the list.
566 void
567 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
569 edge_connection_t *prevconn;
571 tor_assert(circ);
572 tor_assert(conn);
574 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
575 conn->on_circuit = NULL;
577 if (CIRCUIT_IS_ORIGIN(circ)) {
578 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
579 if (conn == origin_circ->p_streams) {
580 origin_circ->p_streams = conn->next_stream;
581 return;
584 for (prevconn = origin_circ->p_streams;
585 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
586 prevconn = prevconn->next_stream)
588 if (prevconn && prevconn->next_stream) {
589 prevconn->next_stream = conn->next_stream;
590 return;
592 } else {
593 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
594 if (conn == or_circ->n_streams) {
595 or_circ->n_streams = conn->next_stream;
596 return;
598 if (conn == or_circ->resolving_streams) {
599 or_circ->resolving_streams = conn->next_stream;
600 return;
603 for (prevconn = or_circ->n_streams;
604 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
605 prevconn = prevconn->next_stream)
607 if (prevconn && prevconn->next_stream) {
608 prevconn->next_stream = conn->next_stream;
609 return;
612 for (prevconn = or_circ->resolving_streams;
613 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
614 prevconn = prevconn->next_stream)
616 if (prevconn && prevconn->next_stream) {
617 prevconn->next_stream = conn->next_stream;
618 return;
622 log_warn(LD_BUG,"Edge connection not in circuit's list.");
623 /* Don't give an error here; it's harmless. */
624 tor_fragile_assert();
627 /** Find each circuit that has been unused for too long, or dirty
628 * for too long and has no streams on it: mark it for close.
630 static void
631 circuit_expire_old_circuits(time_t now)
633 circuit_t *circ;
634 time_t cutoff = now - get_options()->CircuitIdleTimeout;
636 for (circ = global_circuitlist; circ; circ = circ->next) {
637 if (circ->marked_for_close || ! CIRCUIT_IS_ORIGIN(circ))
638 continue;
639 /* If the circuit has been dirty for too long, and there are no streams
640 * on it, mark it for close.
642 if (circ->timestamp_dirty &&
643 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
644 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
645 log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, purp %d)",
646 circ->n_circ_id, (int)(now - circ->timestamp_dirty),
647 circ->purpose);
648 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
649 } else if (!circ->timestamp_dirty &&
650 circ->state == CIRCUIT_STATE_OPEN &&
651 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
652 if (circ->timestamp_created < cutoff) {
653 log_debug(LD_CIRC,
654 "Closing circuit that has been unused for %d seconds.",
655 (int)(now - circ->timestamp_created));
656 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
662 /** Number of testing circuits we want open before testing our bandwidth. */
663 #define NUM_PARALLEL_TESTING_CIRCS 4
665 /** True iff we've ever had enough testing circuits open to test our
666 * bandwidth. */
667 static int have_performed_bandwidth_test = 0;
669 /** Reset have_performed_bandwidth_test, so we'll start building
670 * testing circuits again so we can exercise our bandwidth. */
671 void
672 reset_bandwidth_test(void)
674 have_performed_bandwidth_test = 0;
677 /** Return 1 if we've already exercised our bandwidth, or if we
678 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
679 * established or on the way. Else return 0.
682 circuit_enough_testing_circs(void)
684 circuit_t *circ;
685 int num = 0;
687 if (have_performed_bandwidth_test)
688 return 1;
690 for (circ = global_circuitlist; circ; circ = circ->next) {
691 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
692 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
693 circ->state == CIRCUIT_STATE_OPEN)
694 num++;
696 return num >= NUM_PARALLEL_TESTING_CIRCS;
699 /** A testing circuit has completed. Take whatever stats we want.
700 * Noticing reachability is taken care of in onionskin_answer(),
701 * so there's no need to record anything here. But if we still want
702 * to do the bandwidth test, and we now have enough testing circuits
703 * open, do it.
705 static void
706 circuit_testing_opened(origin_circuit_t *circ)
708 if (have_performed_bandwidth_test ||
709 !check_whether_orport_reachable()) {
710 /* either we've already done everything we want with testing circuits,
711 * or this testing circuit became open due to a fluke, e.g. we picked
712 * a last hop where we already had the connection open due to an
713 * outgoing local circuit. */
714 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
715 } else if (circuit_enough_testing_circs()) {
716 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
717 have_performed_bandwidth_test = 1;
718 } else
719 consider_testing_reachability(1, 0);
722 /** A testing circuit has failed to build. Take whatever stats we want. */
723 static void
724 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
726 routerinfo_t *me = router_get_my_routerinfo();
727 if (server_mode(get_options()) && check_whether_orport_reachable())
728 return;
729 if (!me)
730 return;
732 log_info(LD_GENERAL,
733 "Our testing circuit (to see if your ORPort is reachable) "
734 "has failed. I'll try again later.");
735 control_event_server_status(LOG_WARN, "REACHABILITY_FAILED ORADDRESS=%s:%d",
736 me->address, me->or_port);
738 /* These aren't used yet. */
739 (void)circ;
740 (void)at_last_hop;
743 /** The circuit <b>circ</b> has just become open. Take the next
744 * step: for rendezvous circuits, we pass circ to the appropriate
745 * function in rendclient or rendservice. For general circuits, we
746 * call connection_ap_attach_pending, which looks for pending streams
747 * that could use circ.
749 void
750 circuit_has_opened(origin_circuit_t *circ)
752 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
754 switch (TO_CIRCUIT(circ)->purpose) {
755 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
756 rend_client_rendcirc_has_opened(circ);
757 connection_ap_attach_pending();
758 break;
759 case CIRCUIT_PURPOSE_C_INTRODUCING:
760 rend_client_introcirc_has_opened(circ);
761 break;
762 case CIRCUIT_PURPOSE_C_GENERAL:
763 /* Tell any AP connections that have been waiting for a new
764 * circuit that one is ready. */
765 connection_ap_attach_pending();
766 break;
767 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
768 /* at Bob, waiting for introductions */
769 rend_service_intro_has_opened(circ);
770 break;
771 case CIRCUIT_PURPOSE_S_CONNECT_REND:
772 /* at Bob, connecting to rend point */
773 rend_service_rendezvous_has_opened(circ);
774 break;
775 case CIRCUIT_PURPOSE_TESTING:
776 circuit_testing_opened(circ);
777 break;
778 /* default:
779 * This won't happen in normal operation, but might happen if the
780 * controller did it. Just let it slide. */
784 /** Called whenever a circuit could not be successfully built.
786 void
787 circuit_build_failed(origin_circuit_t *circ)
789 /* we should examine circ and see if it failed because of
790 * the last hop or an earlier hop. then use this info below.
792 int failed_at_last_hop = 0;
793 /* If the last hop isn't open, and the second-to-last is, we failed
794 * at the last hop. */
795 if (circ->cpath &&
796 circ->cpath->prev->state != CPATH_STATE_OPEN &&
797 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
798 failed_at_last_hop = 1;
800 if (circ->cpath &&
801 circ->cpath->state != CPATH_STATE_OPEN) {
802 /* We failed at the first hop. If there's an OR connection
803 * to blame, blame it. Also, avoid this relay for a while, and
804 * fail any one-hop directory fetches destined for it. */
805 const char *n_conn_id = circ->cpath->extend_info->identity_digest;
806 if (circ->_base.n_conn) {
807 or_connection_t *n_conn = circ->_base.n_conn;
808 log_info(LD_OR,
809 "Our circuit failed to get a response from the first hop "
810 "(%s:%d). I'm going to try to rotate to a better connection.",
811 n_conn->_base.address, n_conn->_base.port);
812 n_conn->is_bad_for_new_circs = 1;
814 if (n_conn_id) {
815 entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
816 /* if there are any one-hop streams waiting on this circuit, fail
817 * them now so they can retry elsewhere. */
818 connection_ap_fail_onehop(n_conn_id, circ->build_state);
822 switch (circ->_base.purpose) {
823 case CIRCUIT_PURPOSE_C_GENERAL:
824 /* If we never built the circuit, note it as a failure. */
825 circuit_increment_failure_count();
826 if (failed_at_last_hop) {
827 /* Make sure any streams that demand our last hop as their exit
828 * know that it's unlikely to happen. */
829 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
831 break;
832 case CIRCUIT_PURPOSE_TESTING:
833 circuit_testing_failed(circ, failed_at_last_hop);
834 break;
835 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
836 /* at Bob, waiting for introductions */
837 if (circ->_base.state != CIRCUIT_STATE_OPEN) {
838 circuit_increment_failure_count();
840 /* no need to care here, because bob will rebuild intro
841 * points periodically. */
842 break;
843 case CIRCUIT_PURPOSE_C_INTRODUCING:
844 /* at Alice, connecting to intro point */
845 /* Don't increment failure count, since Bob may have picked
846 * the introduction point maliciously */
847 /* Alice will pick a new intro point when this one dies, if
848 * the stream in question still cares. No need to act here. */
849 break;
850 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
851 /* at Alice, waiting for Bob */
852 circuit_increment_failure_count();
853 /* Alice will pick a new rend point when this one dies, if
854 * the stream in question still cares. No need to act here. */
855 break;
856 case CIRCUIT_PURPOSE_S_CONNECT_REND:
857 /* at Bob, connecting to rend point */
858 /* Don't increment failure count, since Alice may have picked
859 * the rendezvous point maliciously */
860 log_info(LD_REND,
861 "Couldn't connect to Alice's chosen rend point %s "
862 "(%s hop failed).",
863 escaped(build_state_get_exit_nickname(circ->build_state)),
864 failed_at_last_hop?"last":"non-last");
865 rend_service_relaunch_rendezvous(circ);
866 break;
867 /* default:
868 * This won't happen in normal operation, but might happen if the
869 * controller did it. Just let it slide. */
873 /** Number of consecutive failures so far; should only be touched by
874 * circuit_launch_new and circuit_*_failure_count.
876 static int n_circuit_failures = 0;
877 /** Before the last time we called circuit_reset_failure_count(), were
878 * there a lot of failures? */
879 static int did_circs_fail_last_period = 0;
881 /** Don't retry launching a new circuit if we try this many times with no
882 * success. */
883 #define MAX_CIRCUIT_FAILURES 5
885 /** Launch a new circuit; see circuit_launch_by_extend_info() for
886 * details on arguments. */
887 origin_circuit_t *
888 circuit_launch_by_router(uint8_t purpose,
889 routerinfo_t *exit, int flags)
891 origin_circuit_t *circ;
892 extend_info_t *info = NULL;
893 if (exit)
894 info = extend_info_from_router(exit);
895 circ = circuit_launch_by_extend_info(purpose, info, flags);
896 if (info)
897 extend_info_free(info);
898 return circ;
901 /** Launch a new circuit with purpose <b>purpose</b> and exit node
902 * <b>extend_info</b> (or NULL to select a random exit node). If flags
903 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
904 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
905 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
906 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
907 * Return the newly allocated circuit on success, or NULL on failure. */
908 origin_circuit_t *
909 circuit_launch_by_extend_info(uint8_t purpose,
910 extend_info_t *extend_info,
911 int flags)
913 origin_circuit_t *circ;
914 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
916 if (!onehop_tunnel && !router_have_minimum_dir_info()) {
917 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
918 "circuit launch.");
919 return NULL;
922 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
923 purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
924 /* see if there are appropriate circs available to cannibalize. */
925 /* XXX if we're planning to add a hop, perhaps we want to look for
926 * internal circs rather than exit circs? -RD */
927 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
928 if (circ) {
929 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
930 build_state_get_exit_nickname(circ->build_state), purpose);
931 circ->_base.purpose = purpose;
932 /* reset the birth date of this circ, else expire_building
933 * will see it and think it's been trying to build since it
934 * began. */
935 circ->_base.timestamp_created = time(NULL);
936 switch (purpose) {
937 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
938 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
939 /* it's ready right now */
940 break;
941 case CIRCUIT_PURPOSE_C_INTRODUCING:
942 case CIRCUIT_PURPOSE_S_CONNECT_REND:
943 case CIRCUIT_PURPOSE_C_GENERAL:
944 /* need to add a new hop */
945 tor_assert(extend_info);
946 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
947 return NULL;
948 break;
949 default:
950 log_warn(LD_BUG,
951 "unexpected purpose %d when cannibalizing a circ.",
952 purpose);
953 tor_fragile_assert();
954 return NULL;
956 return circ;
960 if (did_circs_fail_last_period &&
961 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
962 /* too many failed circs in a row. don't try. */
963 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
964 return NULL;
967 /* try a circ. if it fails, circuit_mark_for_close will increment
968 * n_circuit_failures */
969 return circuit_establish_circuit(purpose, extend_info, flags);
972 /** Record another failure at opening a general circuit. When we have
973 * too many, we'll stop trying for the remainder of this minute.
975 static void
976 circuit_increment_failure_count(void)
978 ++n_circuit_failures;
979 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
982 /** Reset the failure count for opening general circuits. This means
983 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
984 * stopping again.
986 void
987 circuit_reset_failure_count(int timeout)
989 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
990 did_circs_fail_last_period = 1;
991 else
992 did_circs_fail_last_period = 0;
993 n_circuit_failures = 0;
996 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
997 * there isn't one, and there isn't one on the way, launch one and return
998 * 0. If it will never work, return -1.
1000 * Write the found or in-progress or launched circ into *circp.
1002 static int
1003 circuit_get_open_circ_or_launch(edge_connection_t *conn,
1004 uint8_t desired_circuit_purpose,
1005 origin_circuit_t **circp)
1007 origin_circuit_t *circ;
1008 int check_exit_policy;
1009 int need_uptime, need_internal;
1010 int want_onehop;
1011 or_options_t *options = get_options();
1013 tor_assert(conn);
1014 tor_assert(circp);
1015 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1016 check_exit_policy =
1017 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
1018 !conn->use_begindir &&
1019 !connection_edge_is_rendezvous_stream(conn);
1020 want_onehop = conn->want_onehop;
1022 need_uptime = !conn->want_onehop && !conn->use_begindir &&
1023 smartlist_string_num_isin(options->LongLivedPorts,
1024 conn->socks_request->port);
1025 need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
1027 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
1028 need_uptime, need_internal);
1030 if (circ) {
1031 *circp = circ;
1032 return 1; /* we're happy */
1035 if (!want_onehop && !router_have_minimum_dir_info()) {
1036 if (!connection_get_by_type(CONN_TYPE_DIR)) {
1037 int severity = LOG_NOTICE;
1038 /* FFFF if this is a tunnelled directory fetch, don't yell
1039 * as loudly. the user doesn't even know it's happening. */
1040 if (options->UseBridges && bridges_known_but_down()) {
1041 log_fn(severity, LD_APP|LD_DIR,
1042 "Application request when we're believed to be "
1043 "offline. Optimistically trying known bridges again.");
1044 bridges_retry_all();
1045 } else if (!options->UseBridges || any_bridge_descriptors_known()) {
1046 log_fn(severity, LD_APP|LD_DIR,
1047 "Application request when we're believed to be "
1048 "offline. Optimistically trying directory fetches again.");
1049 routerlist_retry_directory_downloads(time(NULL));
1052 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1053 * 1, or when all directory attempts fail and directory_all_unreachable()
1054 * kills it.
1056 return 0;
1059 /* Do we need to check exit policy? */
1060 if (check_exit_policy) {
1061 if (!conn->chosen_exit_name) {
1062 struct in_addr in;
1063 uint32_t addr = 0;
1064 if (tor_inet_aton(conn->socks_request->address, &in))
1065 addr = ntohl(in.s_addr);
1066 if (router_exit_policy_all_routers_reject(addr,
1067 conn->socks_request->port,
1068 need_uptime)) {
1069 log_notice(LD_APP,
1070 "No Tor server allows exit to %s:%d. Rejecting.",
1071 safe_str(conn->socks_request->address),
1072 conn->socks_request->port);
1073 return -1;
1075 } else {
1076 /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
1077 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1078 int opt = conn->chosen_exit_optional;
1079 if (router && !connection_ap_can_use_exit(conn, router)) {
1080 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1081 "Requested exit point '%s' would refuse request. %s.",
1082 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1083 if (opt) {
1084 conn->chosen_exit_optional = 0;
1085 tor_free(conn->chosen_exit_name);
1086 /* Try again. */
1087 return circuit_get_open_circ_or_launch(conn,
1088 desired_circuit_purpose,
1089 circp);
1091 return -1;
1096 /* is one already on the way? */
1097 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
1098 need_uptime, need_internal);
1099 if (circ)
1100 log_debug(LD_CIRC, "one on the way!");
1101 if (!circ) {
1102 extend_info_t *extend_info=NULL;
1103 uint8_t new_circ_purpose;
1105 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1106 /* need to pick an intro point */
1107 tor_assert(conn->rend_data);
1108 extend_info = rend_client_get_random_intro(conn->rend_data);
1109 if (!extend_info) {
1110 log_info(LD_REND,
1111 "No intro points for '%s': refetching service descriptor.",
1112 safe_str(conn->rend_data->onion_address));
1113 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
1114 * arrives first. Exception: When using client authorization, only
1115 * fetch v2 descriptors.*/
1116 rend_client_refetch_v2_renddesc(conn->rend_data);
1117 if (conn->rend_data->auth_type == REND_NO_AUTH)
1118 rend_client_refetch_renddesc(conn->rend_data->onion_address);
1119 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1120 return 0;
1122 log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
1123 extend_info->nickname,
1124 safe_str(conn->rend_data->onion_address));
1127 /* If we have specified a particular exit node for our
1128 * connection, then be sure to open a circuit to that exit node.
1130 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1131 if (conn->chosen_exit_name) {
1132 routerinfo_t *r;
1133 int opt = conn->chosen_exit_optional;
1134 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1135 if (r) {
1136 extend_info = extend_info_from_router(r);
1137 } else {
1138 log_debug(LD_DIR, "considering %d, %s",
1139 want_onehop, conn->chosen_exit_name);
1140 if (want_onehop && conn->chosen_exit_name[0] == '$') {
1141 /* We're asking for a one-hop circuit to a router that
1142 * we don't have a routerinfo about. Make up an extend_info. */
1143 char digest[DIGEST_LEN];
1144 char *hexdigest = conn->chosen_exit_name+1;
1145 tor_addr_t addr;
1146 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
1147 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
1148 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
1149 return -1;
1151 if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
1152 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
1153 escaped_safe_str(conn->socks_request->address));
1154 return -1;
1156 extend_info = extend_info_alloc(conn->chosen_exit_name+1,
1157 digest, NULL, &addr,
1158 conn->socks_request->port);
1159 } else {
1160 /* We will need an onion key for the router, and we
1161 * don't have one. Refuse or relax requirements. */
1162 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1163 "Requested exit point '%s' is not known. %s.",
1164 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1165 if (opt) {
1166 conn->chosen_exit_optional = 0;
1167 tor_free(conn->chosen_exit_name);
1168 /* Try again with no requested exit */
1169 return circuit_get_open_circ_or_launch(conn,
1170 desired_circuit_purpose,
1171 circp);
1173 return -1;
1179 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
1180 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
1181 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1182 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
1183 else
1184 new_circ_purpose = desired_circuit_purpose;
1187 int flags = CIRCLAUNCH_NEED_CAPACITY;
1188 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
1189 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1190 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
1191 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
1192 flags);
1195 if (extend_info)
1196 extend_info_free(extend_info);
1198 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
1199 /* help predict this next time */
1200 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1201 if (circ) {
1202 /* write the service_id into circ */
1203 circ->rend_data = rend_data_dup(conn->rend_data);
1204 if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1205 circ->_base.state == CIRCUIT_STATE_OPEN)
1206 rend_client_rendcirc_has_opened(circ);
1210 if (!circ)
1211 log_info(LD_APP,
1212 "No safe circuit (purpose %d) ready for edge "
1213 "connection; delaying.",
1214 desired_circuit_purpose);
1215 *circp = circ;
1216 return 0;
1219 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1220 * <b>circ</b>. */
1221 static int
1222 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
1224 crypt_path_t *cpath, *cpath_next = NULL;
1225 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1226 cpath_next = cpath->next;
1227 if (crypt_path == cpath)
1228 return 1;
1230 return 0;
1233 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1234 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1235 * hop in circ's cpath if <b>cpath</b> is NULL.
1237 static void
1238 link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
1239 crypt_path_t *cpath)
1241 /* add it into the linked list of streams on this circuit */
1242 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
1243 circ->_base.n_circ_id);
1244 /* reset it, so we can measure circ timeouts */
1245 apconn->_base.timestamp_lastread = time(NULL);
1246 apconn->next_stream = circ->p_streams;
1247 apconn->on_circuit = TO_CIRCUIT(circ);
1248 /* assert_connection_ok(conn, time(NULL)); */
1249 circ->p_streams = apconn;
1251 if (cpath) { /* we were given one; use it */
1252 tor_assert(cpath_is_on_circuit(circ, cpath));
1253 apconn->cpath_layer = cpath;
1254 } else { /* use the last hop in the circuit */
1255 tor_assert(circ->cpath);
1256 tor_assert(circ->cpath->prev);
1257 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1258 apconn->cpath_layer = circ->cpath->prev;
1262 /** If an exit wasn't specifically chosen, save the history for future
1263 * use. */
1264 static void
1265 consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
1267 int found_needle = 0;
1268 or_options_t *options = get_options();
1269 size_t len;
1270 char *new_address;
1271 char fp[HEX_DIGEST_LEN+1];
1273 /* Search the addressmap for this conn's destination. */
1274 /* If he's not in the address map.. */
1275 if (!options->TrackHostExits ||
1276 addressmap_have_mapping(conn->socks_request->address,
1277 options->TrackHostExitsExpire))
1278 return; /* nothing to track, or already mapped */
1280 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1281 if (cp[0] == '.') { /* match end */
1282 if (cp[1] == '\0' ||
1283 !strcasecmpend(conn->socks_request->address, cp) ||
1284 !strcasecmp(conn->socks_request->address, &cp[1]))
1285 found_needle = 1;
1286 } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
1287 found_needle = 1;
1291 if (!found_needle || !circ->build_state->chosen_exit)
1292 return;
1294 /* write down the fingerprint of the chosen exit, not the nickname,
1295 * because the chosen exit might not be named. */
1296 base16_encode(fp, sizeof(fp),
1297 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
1299 /* Add this exit/hostname pair to the addressmap. */
1300 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1301 strlen(fp) + 1 /* '.' */ +
1302 strlen("exit") + 1 /* '\0' */;
1303 new_address = tor_malloc(len);
1305 tor_snprintf(new_address, len, "%s.%s.exit",
1306 conn->socks_request->address, fp);
1308 addressmap_register(conn->socks_request->address, new_address,
1309 time(NULL) + options->TrackHostExitsExpire,
1310 ADDRMAPSRC_TRACKEXIT);
1313 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1314 * begin or resolve cell as appropriate. Return values are as for
1315 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1316 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1317 * <b>cpath</b> is NULL. */
1319 connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
1320 origin_circuit_t *circ,
1321 crypt_path_t *cpath)
1323 tor_assert(conn);
1324 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
1325 conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
1326 tor_assert(conn->socks_request);
1327 tor_assert(circ);
1328 tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
1330 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1332 if (!circ->_base.timestamp_dirty)
1333 circ->_base.timestamp_dirty = time(NULL);
1335 link_apconn_to_circ(conn, circ, cpath);
1336 tor_assert(conn->socks_request);
1337 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
1338 if (!conn->use_begindir)
1339 consider_recording_trackhost(conn, circ);
1340 if (connection_ap_handshake_send_begin(conn) < 0)
1341 return -1;
1342 } else {
1343 if (connection_ap_handshake_send_resolve(conn) < 0)
1344 return -1;
1347 return 1;
1350 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1351 * we don't find one: if conn cannot be handled by any known nodes,
1352 * warn and return -1 (conn needs to die, and is maybe already marked);
1353 * else launch new circuit (if necessary) and return 0.
1354 * Otherwise, associate conn with a safe live circuit, do the
1355 * right next step, and return 1.
1357 /* XXXX this function should mark for close whenever it returns -1;
1358 * its callers shouldn't have to worry about that. */
1360 connection_ap_handshake_attach_circuit(edge_connection_t *conn)
1362 int retval;
1363 int conn_age;
1364 int want_onehop;
1366 tor_assert(conn);
1367 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1368 tor_assert(conn->socks_request);
1369 want_onehop = conn->want_onehop;
1371 conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
1373 if (conn_age >= get_options()->SocksTimeout) {
1374 int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
1375 LOG_INFO : LOG_NOTICE;
1376 log_fn(severity, LD_APP,
1377 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1378 conn_age, safe_str(conn->socks_request->address),
1379 conn->socks_request->port);
1380 return -1;
1383 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1384 origin_circuit_t *circ=NULL;
1386 if (conn->chosen_exit_name) {
1387 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1388 int opt = conn->chosen_exit_optional;
1389 if (!router && !want_onehop) {
1390 /* We ran into this warning when trying to extend a circuit to a
1391 * hidden service directory for which we didn't have a router
1392 * descriptor. See flyspray task 767 for more details. We should
1393 * keep this in mind when deciding to use BEGIN_DIR cells for other
1394 * directory requests as well. -KL*/
1395 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1396 "Requested exit point '%s' is not known. %s.",
1397 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1398 if (opt) {
1399 conn->chosen_exit_optional = 0;
1400 tor_free(conn->chosen_exit_name);
1401 return 0;
1403 return -1;
1405 if (router && !connection_ap_can_use_exit(conn, router)) {
1406 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1407 "Requested exit point '%s' would refuse request. %s.",
1408 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1409 if (opt) {
1410 conn->chosen_exit_optional = 0;
1411 tor_free(conn->chosen_exit_name);
1412 return 0;
1414 return -1;
1418 /* find the circuit that we should use, if there is one. */
1419 retval = circuit_get_open_circ_or_launch(
1420 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1421 if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
1422 return retval;
1424 log_debug(LD_APP|LD_CIRC,
1425 "Attaching apconn to circ %d (stream %d sec old).",
1426 circ->_base.n_circ_id, conn_age);
1427 /* print the circ's path, so people can figure out which circs are
1428 * sucking. */
1429 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1431 /* We have found a suitable circuit for our conn. Hurray. */
1432 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
1434 } else { /* we're a rendezvous conn */
1435 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
1437 tor_assert(!conn->cpath_layer);
1439 /* start by finding a rendezvous circuit for us */
1441 retval = circuit_get_open_circ_or_launch(
1442 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1443 if (retval < 0) return -1; /* failed */
1445 if (retval > 0) {
1446 tor_assert(rendcirc);
1447 /* one is already established, attach */
1448 log_info(LD_REND,
1449 "rend joined circ %d already here. attaching. "
1450 "(stream %d sec old)",
1451 rendcirc->_base.n_circ_id, conn_age);
1452 /* Mark rendezvous circuits as 'newly dirty' every time you use
1453 * them, since the process of rebuilding a rendezvous circ is so
1454 * expensive. There is a tradeoffs between linkability and
1455 * feasibility, at this point.
1457 rendcirc->_base.timestamp_dirty = time(NULL);
1458 link_apconn_to_circ(conn, rendcirc, NULL);
1459 if (connection_ap_handshake_send_begin(conn) < 0)
1460 return 0; /* already marked, let them fade away */
1461 return 1;
1464 if (rendcirc && (rendcirc->_base.purpose ==
1465 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
1466 log_info(LD_REND,
1467 "pending-join circ %d already here, with intro ack. "
1468 "Stalling. (stream %d sec old)",
1469 rendcirc->_base.n_circ_id, conn_age);
1470 return 0;
1473 /* it's on its way. find an intro circ. */
1474 retval = circuit_get_open_circ_or_launch(
1475 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1476 if (retval < 0) return -1; /* failed */
1478 if (retval > 0) {
1479 /* one has already sent the intro. keep waiting. */
1480 circuit_t *c = NULL;
1481 tor_assert(introcirc);
1482 log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
1483 "Stalling. (stream %d sec old)",
1484 introcirc->_base.n_circ_id,
1485 rendcirc ? rendcirc->_base.n_circ_id : 0,
1486 conn_age);
1487 /* abort parallel intro circs, if any */
1488 for (c = global_circuitlist; c; c = c->next) {
1489 if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
1490 !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
1491 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
1492 if (oc->rend_data &&
1493 !rend_cmp_service_ids(conn->rend_data->onion_address,
1494 oc->rend_data->onion_address)) {
1495 log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
1496 "built in parallel.");
1497 circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
1501 return 0;
1504 /* now rendcirc and introcirc are each either undefined or not finished */
1506 if (rendcirc && introcirc &&
1507 rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1508 log_info(LD_REND,
1509 "ready rend circ %d already here (no intro-ack yet on "
1510 "intro %d). (stream %d sec old)",
1511 rendcirc->_base.n_circ_id,
1512 introcirc->_base.n_circ_id, conn_age);
1514 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1515 if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
1516 log_info(LD_REND,"found open intro circ %d (rend %d); sending "
1517 "introduction. (stream %d sec old)",
1518 introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
1519 conn_age);
1520 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1521 return -1;
1523 rendcirc->_base.timestamp_dirty = time(NULL);
1524 introcirc->_base.timestamp_dirty = time(NULL);
1525 assert_circuit_ok(TO_CIRCUIT(rendcirc));
1526 assert_circuit_ok(TO_CIRCUIT(introcirc));
1527 return 0;
1531 log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
1532 "Stalling conn. (%d sec old)",
1533 introcirc ? introcirc->_base.n_circ_id : 0,
1534 rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
1535 return 0;