Simplify the math to round up to the next multiple of some value.
[tor/rransom.git] / src / or / circuituse.c
bloba2110a4da42c08c0a8bada68c70ee2b8a01e7b15
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-2009, 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 purpose %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 purpose %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 hidden service 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, "
646 "purpose %d)",
647 circ->n_circ_id, (int)(now - circ->timestamp_dirty),
648 circ->purpose);
649 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
650 } else if (!circ->timestamp_dirty &&
651 circ->state == CIRCUIT_STATE_OPEN &&
652 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
653 if (circ->timestamp_created < cutoff) {
654 log_debug(LD_CIRC,
655 "Closing circuit that has been unused for %d seconds.",
656 (int)(now - circ->timestamp_created));
657 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
663 /** Number of testing circuits we want open before testing our bandwidth. */
664 #define NUM_PARALLEL_TESTING_CIRCS 4
666 /** True iff we've ever had enough testing circuits open to test our
667 * bandwidth. */
668 static int have_performed_bandwidth_test = 0;
670 /** Reset have_performed_bandwidth_test, so we'll start building
671 * testing circuits again so we can exercise our bandwidth. */
672 void
673 reset_bandwidth_test(void)
675 have_performed_bandwidth_test = 0;
678 /** Return 1 if we've already exercised our bandwidth, or if we
679 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
680 * established or on the way. Else return 0.
683 circuit_enough_testing_circs(void)
685 circuit_t *circ;
686 int num = 0;
688 if (have_performed_bandwidth_test)
689 return 1;
691 for (circ = global_circuitlist; circ; circ = circ->next) {
692 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
693 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
694 circ->state == CIRCUIT_STATE_OPEN)
695 num++;
697 return num >= NUM_PARALLEL_TESTING_CIRCS;
700 /** A testing circuit has completed. Take whatever stats we want.
701 * Noticing reachability is taken care of in onionskin_answer(),
702 * so there's no need to record anything here. But if we still want
703 * to do the bandwidth test, and we now have enough testing circuits
704 * open, do it.
706 static void
707 circuit_testing_opened(origin_circuit_t *circ)
709 if (have_performed_bandwidth_test ||
710 !check_whether_orport_reachable()) {
711 /* either we've already done everything we want with testing circuits,
712 * or this testing circuit became open due to a fluke, e.g. we picked
713 * a last hop where we already had the connection open due to an
714 * outgoing local circuit. */
715 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
716 } else if (circuit_enough_testing_circs()) {
717 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
718 have_performed_bandwidth_test = 1;
719 } else
720 consider_testing_reachability(1, 0);
723 /** A testing circuit has failed to build. Take whatever stats we want. */
724 static void
725 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
727 routerinfo_t *me = router_get_my_routerinfo();
728 if (server_mode(get_options()) && check_whether_orport_reachable())
729 return;
730 if (!me)
731 return;
733 log_info(LD_GENERAL,
734 "Our testing circuit (to see if your ORPort is reachable) "
735 "has failed. I'll try again later.");
736 control_event_server_status(LOG_WARN, "REACHABILITY_FAILED ORADDRESS=%s:%d",
737 me->address, me->or_port);
739 /* These aren't used yet. */
740 (void)circ;
741 (void)at_last_hop;
744 /** The circuit <b>circ</b> has just become open. Take the next
745 * step: for rendezvous circuits, we pass circ to the appropriate
746 * function in rendclient or rendservice. For general circuits, we
747 * call connection_ap_attach_pending, which looks for pending streams
748 * that could use circ.
750 void
751 circuit_has_opened(origin_circuit_t *circ)
753 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
755 switch (TO_CIRCUIT(circ)->purpose) {
756 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
757 rend_client_rendcirc_has_opened(circ);
758 connection_ap_attach_pending();
759 break;
760 case CIRCUIT_PURPOSE_C_INTRODUCING:
761 rend_client_introcirc_has_opened(circ);
762 break;
763 case CIRCUIT_PURPOSE_C_GENERAL:
764 /* Tell any AP connections that have been waiting for a new
765 * circuit that one is ready. */
766 connection_ap_attach_pending();
767 break;
768 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
769 /* at Bob, waiting for introductions */
770 rend_service_intro_has_opened(circ);
771 break;
772 case CIRCUIT_PURPOSE_S_CONNECT_REND:
773 /* at Bob, connecting to rend point */
774 rend_service_rendezvous_has_opened(circ);
775 break;
776 case CIRCUIT_PURPOSE_TESTING:
777 circuit_testing_opened(circ);
778 break;
779 /* default:
780 * This won't happen in normal operation, but might happen if the
781 * controller did it. Just let it slide. */
785 /** Called whenever a circuit could not be successfully built.
787 void
788 circuit_build_failed(origin_circuit_t *circ)
790 /* we should examine circ and see if it failed because of
791 * the last hop or an earlier hop. then use this info below.
793 int failed_at_last_hop = 0;
794 /* If the last hop isn't open, and the second-to-last is, we failed
795 * at the last hop. */
796 if (circ->cpath &&
797 circ->cpath->prev->state != CPATH_STATE_OPEN &&
798 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
799 failed_at_last_hop = 1;
801 if (circ->cpath &&
802 circ->cpath->state != CPATH_STATE_OPEN) {
803 /* We failed at the first hop. If there's an OR connection
804 * to blame, blame it. Also, avoid this relay for a while, and
805 * fail any one-hop directory fetches destined for it. */
806 const char *n_conn_id = circ->cpath->extend_info->identity_digest;
807 if (circ->_base.n_conn) {
808 or_connection_t *n_conn = circ->_base.n_conn;
809 log_info(LD_OR,
810 "Our circuit failed to get a response from the first hop "
811 "(%s:%d). I'm going to try to rotate to a better connection.",
812 n_conn->_base.address, n_conn->_base.port);
813 n_conn->is_bad_for_new_circs = 1;
815 if (n_conn_id) {
816 entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
817 /* if there are any one-hop streams waiting on this circuit, fail
818 * them now so they can retry elsewhere. */
819 connection_ap_fail_onehop(n_conn_id, circ->build_state);
823 switch (circ->_base.purpose) {
824 case CIRCUIT_PURPOSE_C_GENERAL:
825 /* If we never built the circuit, note it as a failure. */
826 circuit_increment_failure_count();
827 if (failed_at_last_hop) {
828 /* Make sure any streams that demand our last hop as their exit
829 * know that it's unlikely to happen. */
830 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
832 break;
833 case CIRCUIT_PURPOSE_TESTING:
834 circuit_testing_failed(circ, failed_at_last_hop);
835 break;
836 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
837 /* at Bob, waiting for introductions */
838 if (circ->_base.state != CIRCUIT_STATE_OPEN) {
839 circuit_increment_failure_count();
841 /* no need to care here, because bob will rebuild intro
842 * points periodically. */
843 break;
844 case CIRCUIT_PURPOSE_C_INTRODUCING:
845 /* at Alice, connecting to intro point */
846 /* Don't increment failure count, since Bob may have picked
847 * the introduction point maliciously */
848 /* Alice will pick a new intro point when this one dies, if
849 * the stream in question still cares. No need to act here. */
850 break;
851 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
852 /* at Alice, waiting for Bob */
853 circuit_increment_failure_count();
854 /* Alice will pick a new rend point when this one dies, if
855 * the stream in question still cares. No need to act here. */
856 break;
857 case CIRCUIT_PURPOSE_S_CONNECT_REND:
858 /* at Bob, connecting to rend point */
859 /* Don't increment failure count, since Alice may have picked
860 * the rendezvous point maliciously */
861 log_info(LD_REND,
862 "Couldn't connect to Alice's chosen rend point %s "
863 "(%s hop failed).",
864 escaped(build_state_get_exit_nickname(circ->build_state)),
865 failed_at_last_hop?"last":"non-last");
866 rend_service_relaunch_rendezvous(circ);
867 break;
868 /* default:
869 * This won't happen in normal operation, but might happen if the
870 * controller did it. Just let it slide. */
874 /** Number of consecutive failures so far; should only be touched by
875 * circuit_launch_new and circuit_*_failure_count.
877 static int n_circuit_failures = 0;
878 /** Before the last time we called circuit_reset_failure_count(), were
879 * there a lot of failures? */
880 static int did_circs_fail_last_period = 0;
882 /** Don't retry launching a new circuit if we try this many times with no
883 * success. */
884 #define MAX_CIRCUIT_FAILURES 5
886 /** Launch a new circuit; see circuit_launch_by_extend_info() for
887 * details on arguments. */
888 origin_circuit_t *
889 circuit_launch_by_router(uint8_t purpose,
890 routerinfo_t *exit, int flags)
892 origin_circuit_t *circ;
893 extend_info_t *info = NULL;
894 if (exit)
895 info = extend_info_from_router(exit);
896 circ = circuit_launch_by_extend_info(purpose, info, flags);
897 if (info)
898 extend_info_free(info);
899 return circ;
902 /** Launch a new circuit with purpose <b>purpose</b> and exit node
903 * <b>extend_info</b> (or NULL to select a random exit node). If flags
904 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
905 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
906 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
907 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
908 * Return the newly allocated circuit on success, or NULL on failure. */
909 origin_circuit_t *
910 circuit_launch_by_extend_info(uint8_t purpose,
911 extend_info_t *extend_info,
912 int flags)
914 origin_circuit_t *circ;
915 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
917 if (!onehop_tunnel && !router_have_minimum_dir_info()) {
918 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
919 "circuit launch.");
920 return NULL;
923 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
924 purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
925 /* see if there are appropriate circs available to cannibalize. */
926 /* XXX if we're planning to add a hop, perhaps we want to look for
927 * internal circs rather than exit circs? -RD */
928 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
929 if (circ) {
930 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
931 build_state_get_exit_nickname(circ->build_state), purpose);
932 circ->_base.purpose = purpose;
933 /* reset the birth date of this circ, else expire_building
934 * will see it and think it's been trying to build since it
935 * began. */
936 circ->_base.timestamp_created = time(NULL);
937 switch (purpose) {
938 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
939 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
940 /* it's ready right now */
941 break;
942 case CIRCUIT_PURPOSE_C_INTRODUCING:
943 case CIRCUIT_PURPOSE_S_CONNECT_REND:
944 case CIRCUIT_PURPOSE_C_GENERAL:
945 /* need to add a new hop */
946 tor_assert(extend_info);
947 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
948 return NULL;
949 break;
950 default:
951 log_warn(LD_BUG,
952 "unexpected purpose %d when cannibalizing a circ.",
953 purpose);
954 tor_fragile_assert();
955 return NULL;
957 return circ;
961 if (did_circs_fail_last_period &&
962 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
963 /* too many failed circs in a row. don't try. */
964 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
965 return NULL;
968 /* try a circ. if it fails, circuit_mark_for_close will increment
969 * n_circuit_failures */
970 return circuit_establish_circuit(purpose, extend_info, flags);
973 /** Record another failure at opening a general circuit. When we have
974 * too many, we'll stop trying for the remainder of this minute.
976 static void
977 circuit_increment_failure_count(void)
979 ++n_circuit_failures;
980 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
983 /** Reset the failure count for opening general circuits. This means
984 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
985 * stopping again.
987 void
988 circuit_reset_failure_count(int timeout)
990 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
991 did_circs_fail_last_period = 1;
992 else
993 did_circs_fail_last_period = 0;
994 n_circuit_failures = 0;
997 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
998 * there isn't one, and there isn't one on the way, launch one and return
999 * 0. If it will never work, return -1.
1001 * Write the found or in-progress or launched circ into *circp.
1003 static int
1004 circuit_get_open_circ_or_launch(edge_connection_t *conn,
1005 uint8_t desired_circuit_purpose,
1006 origin_circuit_t **circp)
1008 origin_circuit_t *circ;
1009 int check_exit_policy;
1010 int need_uptime, need_internal;
1011 int want_onehop;
1012 or_options_t *options = get_options();
1014 tor_assert(conn);
1015 tor_assert(circp);
1016 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1017 check_exit_policy =
1018 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
1019 !conn->use_begindir &&
1020 !connection_edge_is_rendezvous_stream(conn);
1021 want_onehop = conn->want_onehop;
1023 need_uptime = !conn->want_onehop && !conn->use_begindir &&
1024 smartlist_string_num_isin(options->LongLivedPorts,
1025 conn->socks_request->port);
1026 need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
1028 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
1029 need_uptime, need_internal);
1031 if (circ) {
1032 *circp = circ;
1033 return 1; /* we're happy */
1036 if (!want_onehop && !router_have_minimum_dir_info()) {
1037 if (!connection_get_by_type(CONN_TYPE_DIR)) {
1038 int severity = LOG_NOTICE;
1039 /* FFFF if this is a tunneled directory fetch, don't yell
1040 * as loudly. the user doesn't even know it's happening. */
1041 if (options->UseBridges && bridges_known_but_down()) {
1042 log_fn(severity, LD_APP|LD_DIR,
1043 "Application request when we're believed to be "
1044 "offline. Optimistically trying known bridges again.");
1045 bridges_retry_all();
1046 } else if (!options->UseBridges || any_bridge_descriptors_known()) {
1047 log_fn(severity, LD_APP|LD_DIR,
1048 "Application request when we're believed to be "
1049 "offline. Optimistically trying directory fetches again.");
1050 routerlist_retry_directory_downloads(time(NULL));
1053 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1054 * 1, or when all directory attempts fail and directory_all_unreachable()
1055 * kills it.
1057 return 0;
1060 /* Do we need to check exit policy? */
1061 if (check_exit_policy) {
1062 if (!conn->chosen_exit_name) {
1063 struct in_addr in;
1064 uint32_t addr = 0;
1065 if (tor_inet_aton(conn->socks_request->address, &in))
1066 addr = ntohl(in.s_addr);
1067 if (router_exit_policy_all_routers_reject(addr,
1068 conn->socks_request->port,
1069 need_uptime)) {
1070 log_notice(LD_APP,
1071 "No Tor server allows exit to %s:%d. Rejecting.",
1072 safe_str(conn->socks_request->address),
1073 conn->socks_request->port);
1074 return -1;
1076 } else {
1077 /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
1078 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1079 int opt = conn->chosen_exit_optional;
1080 if (router && !connection_ap_can_use_exit(conn, router)) {
1081 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1082 "Requested exit point '%s' would refuse request. %s.",
1083 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1084 if (opt) {
1085 conn->chosen_exit_optional = 0;
1086 tor_free(conn->chosen_exit_name);
1087 /* Try again. */
1088 return circuit_get_open_circ_or_launch(conn,
1089 desired_circuit_purpose,
1090 circp);
1092 return -1;
1097 /* is one already on the way? */
1098 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
1099 need_uptime, need_internal);
1100 if (circ)
1101 log_debug(LD_CIRC, "one on the way!");
1102 if (!circ) {
1103 extend_info_t *extend_info=NULL;
1104 uint8_t new_circ_purpose;
1106 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1107 /* need to pick an intro point */
1108 tor_assert(conn->rend_data);
1109 extend_info = rend_client_get_random_intro(conn->rend_data);
1110 if (!extend_info) {
1111 log_info(LD_REND,
1112 "No intro points for '%s': re-fetching service descriptor.",
1113 safe_str(conn->rend_data->onion_address));
1114 rend_client_refetch_v2_renddesc(conn->rend_data);
1115 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1116 return 0;
1118 log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
1119 extend_info->nickname,
1120 safe_str(conn->rend_data->onion_address));
1123 /* If we have specified a particular exit node for our
1124 * connection, then be sure to open a circuit to that exit node.
1126 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1127 if (conn->chosen_exit_name) {
1128 routerinfo_t *r;
1129 int opt = conn->chosen_exit_optional;
1130 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1131 if (r) {
1132 extend_info = extend_info_from_router(r);
1133 } else {
1134 log_debug(LD_DIR, "considering %d, %s",
1135 want_onehop, conn->chosen_exit_name);
1136 if (want_onehop && conn->chosen_exit_name[0] == '$') {
1137 /* We're asking for a one-hop circuit to a router that
1138 * we don't have a routerinfo about. Make up an extend_info. */
1139 char digest[DIGEST_LEN];
1140 char *hexdigest = conn->chosen_exit_name+1;
1141 tor_addr_t addr;
1142 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
1143 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
1144 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
1145 return -1;
1147 if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
1148 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
1149 escaped_safe_str(conn->socks_request->address));
1150 return -1;
1152 extend_info = extend_info_alloc(conn->chosen_exit_name+1,
1153 digest, NULL, &addr,
1154 conn->socks_request->port);
1155 } else {
1156 /* We will need an onion key for the router, and we
1157 * don't have one. Refuse or relax requirements. */
1158 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1159 "Requested exit point '%s' is not known. %s.",
1160 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1161 if (opt) {
1162 conn->chosen_exit_optional = 0;
1163 tor_free(conn->chosen_exit_name);
1164 /* Try again with no requested exit */
1165 return circuit_get_open_circ_or_launch(conn,
1166 desired_circuit_purpose,
1167 circp);
1169 return -1;
1175 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
1176 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
1177 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1178 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
1179 else
1180 new_circ_purpose = desired_circuit_purpose;
1183 int flags = CIRCLAUNCH_NEED_CAPACITY;
1184 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
1185 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1186 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
1187 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
1188 flags);
1191 if (extend_info)
1192 extend_info_free(extend_info);
1194 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
1195 /* help predict this next time */
1196 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1197 if (circ) {
1198 /* write the service_id into circ */
1199 circ->rend_data = rend_data_dup(conn->rend_data);
1200 if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1201 circ->_base.state == CIRCUIT_STATE_OPEN)
1202 rend_client_rendcirc_has_opened(circ);
1206 if (!circ)
1207 log_info(LD_APP,
1208 "No safe circuit (purpose %d) ready for edge "
1209 "connection; delaying.",
1210 desired_circuit_purpose);
1211 *circp = circ;
1212 return 0;
1215 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1216 * <b>circ</b>. */
1217 static int
1218 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
1220 crypt_path_t *cpath, *cpath_next = NULL;
1221 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1222 cpath_next = cpath->next;
1223 if (crypt_path == cpath)
1224 return 1;
1226 return 0;
1229 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1230 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1231 * hop in circ's cpath if <b>cpath</b> is NULL.
1233 static void
1234 link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
1235 crypt_path_t *cpath)
1237 /* add it into the linked list of streams on this circuit */
1238 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
1239 circ->_base.n_circ_id);
1240 /* reset it, so we can measure circ timeouts */
1241 apconn->_base.timestamp_lastread = time(NULL);
1242 apconn->next_stream = circ->p_streams;
1243 apconn->on_circuit = TO_CIRCUIT(circ);
1244 /* assert_connection_ok(conn, time(NULL)); */
1245 circ->p_streams = apconn;
1247 if (cpath) { /* we were given one; use it */
1248 tor_assert(cpath_is_on_circuit(circ, cpath));
1249 apconn->cpath_layer = cpath;
1250 } else { /* use the last hop in the circuit */
1251 tor_assert(circ->cpath);
1252 tor_assert(circ->cpath->prev);
1253 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1254 apconn->cpath_layer = circ->cpath->prev;
1258 /** If an exit wasn't specifically chosen, save the history for future
1259 * use. */
1260 static void
1261 consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
1263 int found_needle = 0;
1264 or_options_t *options = get_options();
1265 size_t len;
1266 char *new_address;
1267 char fp[HEX_DIGEST_LEN+1];
1269 /* Search the addressmap for this conn's destination. */
1270 /* If he's not in the address map.. */
1271 if (!options->TrackHostExits ||
1272 addressmap_have_mapping(conn->socks_request->address,
1273 options->TrackHostExitsExpire))
1274 return; /* nothing to track, or already mapped */
1276 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1277 if (cp[0] == '.') { /* match end */
1278 if (cp[1] == '\0' ||
1279 !strcasecmpend(conn->socks_request->address, cp) ||
1280 !strcasecmp(conn->socks_request->address, &cp[1]))
1281 found_needle = 1;
1282 } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
1283 found_needle = 1;
1287 if (!found_needle || !circ->build_state->chosen_exit)
1288 return;
1290 /* write down the fingerprint of the chosen exit, not the nickname,
1291 * because the chosen exit might not be named. */
1292 base16_encode(fp, sizeof(fp),
1293 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
1295 /* Add this exit/hostname pair to the addressmap. */
1296 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1297 strlen(fp) + 1 /* '.' */ +
1298 strlen("exit") + 1 /* '\0' */;
1299 new_address = tor_malloc(len);
1301 tor_snprintf(new_address, len, "%s.%s.exit",
1302 conn->socks_request->address, fp);
1304 addressmap_register(conn->socks_request->address, new_address,
1305 time(NULL) + options->TrackHostExitsExpire,
1306 ADDRMAPSRC_TRACKEXIT);
1309 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1310 * begin or resolve cell as appropriate. Return values are as for
1311 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1312 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1313 * <b>cpath</b> is NULL. */
1315 connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
1316 origin_circuit_t *circ,
1317 crypt_path_t *cpath)
1319 tor_assert(conn);
1320 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
1321 conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
1322 tor_assert(conn->socks_request);
1323 tor_assert(circ);
1324 tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
1326 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1328 if (!circ->_base.timestamp_dirty)
1329 circ->_base.timestamp_dirty = time(NULL);
1331 link_apconn_to_circ(conn, circ, cpath);
1332 tor_assert(conn->socks_request);
1333 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
1334 if (!conn->use_begindir)
1335 consider_recording_trackhost(conn, circ);
1336 if (connection_ap_handshake_send_begin(conn) < 0)
1337 return -1;
1338 } else {
1339 if (connection_ap_handshake_send_resolve(conn) < 0)
1340 return -1;
1343 return 1;
1346 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1347 * we don't find one: if conn cannot be handled by any known nodes,
1348 * warn and return -1 (conn needs to die, and is maybe already marked);
1349 * else launch new circuit (if necessary) and return 0.
1350 * Otherwise, associate conn with a safe live circuit, do the
1351 * right next step, and return 1.
1353 /* XXXX this function should mark for close whenever it returns -1;
1354 * its callers shouldn't have to worry about that. */
1356 connection_ap_handshake_attach_circuit(edge_connection_t *conn)
1358 int retval;
1359 int conn_age;
1360 int want_onehop;
1362 tor_assert(conn);
1363 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1364 tor_assert(conn->socks_request);
1365 want_onehop = conn->want_onehop;
1367 conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
1369 if (conn_age >= get_options()->SocksTimeout) {
1370 int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
1371 LOG_INFO : LOG_NOTICE;
1372 log_fn(severity, LD_APP,
1373 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1374 conn_age, safe_str(conn->socks_request->address),
1375 conn->socks_request->port);
1376 return -1;
1379 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1380 origin_circuit_t *circ=NULL;
1382 if (conn->chosen_exit_name) {
1383 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1384 int opt = conn->chosen_exit_optional;
1385 if (!router && !want_onehop) {
1386 /* We ran into this warning when trying to extend a circuit to a
1387 * hidden service directory for which we didn't have a router
1388 * descriptor. See flyspray task 767 for more details. We should
1389 * keep this in mind when deciding to use BEGIN_DIR cells for other
1390 * directory requests as well. -KL*/
1391 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1392 "Requested exit point '%s' is not known. %s.",
1393 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1394 if (opt) {
1395 conn->chosen_exit_optional = 0;
1396 tor_free(conn->chosen_exit_name);
1397 return 0;
1399 return -1;
1401 if (router && !connection_ap_can_use_exit(conn, router)) {
1402 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1403 "Requested exit point '%s' would refuse request. %s.",
1404 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1405 if (opt) {
1406 conn->chosen_exit_optional = 0;
1407 tor_free(conn->chosen_exit_name);
1408 return 0;
1410 return -1;
1414 /* find the circuit that we should use, if there is one. */
1415 retval = circuit_get_open_circ_or_launch(
1416 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1417 if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
1418 return retval;
1420 log_debug(LD_APP|LD_CIRC,
1421 "Attaching apconn to circ %d (stream %d sec old).",
1422 circ->_base.n_circ_id, conn_age);
1423 /* print the circ's path, so people can figure out which circs are
1424 * sucking. */
1425 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1427 /* We have found a suitable circuit for our conn. Hurray. */
1428 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
1430 } else { /* we're a rendezvous conn */
1431 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
1433 tor_assert(!conn->cpath_layer);
1435 /* start by finding a rendezvous circuit for us */
1437 retval = circuit_get_open_circ_or_launch(
1438 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1439 if (retval < 0) return -1; /* failed */
1441 if (retval > 0) {
1442 tor_assert(rendcirc);
1443 /* one is already established, attach */
1444 log_info(LD_REND,
1445 "rend joined circ %d already here. attaching. "
1446 "(stream %d sec old)",
1447 rendcirc->_base.n_circ_id, conn_age);
1448 /* Mark rendezvous circuits as 'newly dirty' every time you use
1449 * them, since the process of rebuilding a rendezvous circ is so
1450 * expensive. There is a tradeoff between linkability and
1451 * feasibility, at this point.
1453 rendcirc->_base.timestamp_dirty = time(NULL);
1454 link_apconn_to_circ(conn, rendcirc, NULL);
1455 if (connection_ap_handshake_send_begin(conn) < 0)
1456 return 0; /* already marked, let them fade away */
1457 return 1;
1460 if (rendcirc && (rendcirc->_base.purpose ==
1461 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
1462 log_info(LD_REND,
1463 "pending-join circ %d already here, with intro ack. "
1464 "Stalling. (stream %d sec old)",
1465 rendcirc->_base.n_circ_id, conn_age);
1466 return 0;
1469 /* it's on its way. find an intro circ. */
1470 retval = circuit_get_open_circ_or_launch(
1471 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1472 if (retval < 0) return -1; /* failed */
1474 if (retval > 0) {
1475 /* one has already sent the intro. keep waiting. */
1476 circuit_t *c = NULL;
1477 tor_assert(introcirc);
1478 log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
1479 "Stalling. (stream %d sec old)",
1480 introcirc->_base.n_circ_id,
1481 rendcirc ? rendcirc->_base.n_circ_id : 0,
1482 conn_age);
1483 /* abort parallel intro circs, if any */
1484 for (c = global_circuitlist; c; c = c->next) {
1485 if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
1486 !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
1487 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
1488 if (oc->rend_data &&
1489 !rend_cmp_service_ids(conn->rend_data->onion_address,
1490 oc->rend_data->onion_address)) {
1491 log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
1492 "built in parallel.");
1493 circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
1497 return 0;
1500 /* now rendcirc and introcirc are each either undefined or not finished */
1502 if (rendcirc && introcirc &&
1503 rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1504 log_info(LD_REND,
1505 "ready rend circ %d already here (no intro-ack yet on "
1506 "intro %d). (stream %d sec old)",
1507 rendcirc->_base.n_circ_id,
1508 introcirc->_base.n_circ_id, conn_age);
1510 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1511 if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
1512 log_info(LD_REND,"found open intro circ %d (rend %d); sending "
1513 "introduction. (stream %d sec old)",
1514 introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
1515 conn_age);
1516 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1517 return -1;
1519 rendcirc->_base.timestamp_dirty = time(NULL);
1520 introcirc->_base.timestamp_dirty = time(NULL);
1521 assert_circuit_ok(TO_CIRCUIT(rendcirc));
1522 assert_circuit_ok(TO_CIRCUIT(introcirc));
1523 return 0;
1527 log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
1528 "Stalling conn. (%d sec old)",
1529 introcirc ? introcirc->_base.n_circ_id : 0,
1530 rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
1531 return 0;