Create rephist.h
[tor/rransom.git] / src / or / circuituse.c
bloba3f10a8841043da9863c0e524eff0df118475f24
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-2010, 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"
13 #include "circuitbuild.h"
14 #include "circuitlist.h"
15 #include "circuituse.h"
16 #include "config.h"
17 #include "connection.h"
18 #include "connection_edge.h"
19 #include "control.h"
20 #include "policies.h"
21 #include "rendclient.h"
22 #include "rendcommon.h"
23 #include "rendservice.h"
24 #include "rephist.h"
25 #include "router.h"
26 #include "routerlist.h"
28 /********* START VARIABLES **********/
30 extern circuit_t *global_circuitlist; /* from circuitlist.c */
32 /********* END VARIABLES ************/
34 static void circuit_expire_old_circuits_clientside(time_t now);
35 static void circuit_increment_failure_count(void);
37 long int lround(double x);
39 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
40 * Else return 0.
42 static int
43 circuit_is_acceptable(circuit_t *circ, edge_connection_t *conn,
44 int must_be_open, uint8_t purpose,
45 int need_uptime, int need_internal,
46 time_t now)
48 routerinfo_t *exitrouter;
49 cpath_build_state_t *build_state;
50 tor_assert(circ);
51 tor_assert(conn);
52 tor_assert(conn->socks_request);
54 if (!CIRCUIT_IS_ORIGIN(circ))
55 return 0; /* this circ doesn't start at us */
56 if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
57 return 0; /* ignore non-open circs */
58 if (circ->marked_for_close)
59 return 0;
61 /* if this circ isn't our purpose, skip. */
62 if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
63 if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
64 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
65 circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
66 circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
67 return 0;
68 } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
69 !must_be_open) {
70 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
71 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
72 return 0;
73 } else {
74 if (purpose != circ->purpose)
75 return 0;
78 if (purpose == CIRCUIT_PURPOSE_C_GENERAL)
79 if (circ->timestamp_dirty &&
80 circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
81 return 0;
83 /* decide if this circ is suitable for this conn */
85 /* for rend circs, circ->cpath->prev is not the last router in the
86 * circuit, it's the magical extra bob hop. so just check the nickname
87 * of the one we meant to finish at.
89 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
90 exitrouter = build_state_get_exit_router(build_state);
92 if (need_uptime && !build_state->need_uptime)
93 return 0;
94 if (need_internal != build_state->is_internal)
95 return 0;
97 if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
98 if (!exitrouter && !build_state->onehop_tunnel) {
99 log_debug(LD_CIRC,"Not considering circuit with unknown router.");
100 return 0; /* this circuit is screwed and doesn't know it yet,
101 * or is a rendezvous circuit. */
103 if (build_state->onehop_tunnel) {
104 if (!conn->want_onehop) {
105 log_debug(LD_CIRC,"Skipping one-hop circuit.");
106 return 0;
108 tor_assert(conn->chosen_exit_name);
109 if (build_state->chosen_exit) {
110 char digest[DIGEST_LEN];
111 if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
112 return 0; /* broken digest, we don't want it */
113 if (memcmp(digest, build_state->chosen_exit->identity_digest,
114 DIGEST_LEN))
115 return 0; /* this is a circuit to somewhere else */
116 if (tor_digest_is_zero(digest)) {
117 /* we don't know the digest; have to compare addr:port */
118 tor_addr_t addr;
119 int r = tor_addr_from_str(&addr, conn->socks_request->address);
120 if (r < 0 ||
121 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
122 build_state->chosen_exit->port != conn->socks_request->port)
123 return 0;
126 } else {
127 if (conn->want_onehop) {
128 /* don't use three-hop circuits -- that could hurt our anonymity. */
129 return 0;
132 if (exitrouter && !connection_ap_can_use_exit(conn, exitrouter, 0)) {
133 /* can't exit from this router */
134 return 0;
136 } else { /* not general */
137 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
138 if ((conn->rend_data && !ocirc->rend_data) ||
139 (!conn->rend_data && ocirc->rend_data) ||
140 (conn->rend_data && ocirc->rend_data &&
141 rend_cmp_service_ids(conn->rend_data->onion_address,
142 ocirc->rend_data->onion_address))) {
143 /* this circ is not for this conn */
144 return 0;
147 return 1;
150 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
151 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
153 static int
154 circuit_is_better(circuit_t *a, circuit_t *b, uint8_t purpose)
156 switch (purpose) {
157 case CIRCUIT_PURPOSE_C_GENERAL:
158 /* if it's used but less dirty it's best;
159 * else if it's more recently created it's best
161 if (b->timestamp_dirty) {
162 if (a->timestamp_dirty &&
163 a->timestamp_dirty > b->timestamp_dirty)
164 return 1;
165 } else {
166 if (a->timestamp_dirty ||
167 a->timestamp_created > b->timestamp_created)
168 return 1;
169 if (CIRCUIT_IS_ORIGIN(b) &&
170 TO_ORIGIN_CIRCUIT(b)->build_state->is_internal)
171 return 1;
173 break;
174 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
175 /* the closer it is to ack_wait the better it is */
176 if (a->purpose > b->purpose)
177 return 1;
178 break;
179 case CIRCUIT_PURPOSE_C_REND_JOINED:
180 /* the closer it is to rend_joined the better it is */
181 if (a->purpose > b->purpose)
182 return 1;
183 break;
185 return 0;
188 /** Find the best circ that conn can use, preferably one which is
189 * dirty. Circ must not be too old.
191 * Conn must be defined.
193 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
195 * circ_purpose specifies what sort of circuit we must have.
196 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
198 * If it's REND_JOINED and must_be_open==0, then return the closest
199 * rendezvous-purposed circuit that you can find.
201 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
202 * closest introduce-purposed circuit that you can find.
204 static origin_circuit_t *
205 circuit_get_best(edge_connection_t *conn, int must_be_open, uint8_t purpose,
206 int need_uptime, int need_internal)
208 circuit_t *circ, *best=NULL;
209 time_t now = time(NULL);
210 int intro_going_on_but_too_old = 0;
212 tor_assert(conn);
214 tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
215 purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
216 purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
218 for (circ=global_circuitlist;circ;circ = circ->next) {
219 if (!circuit_is_acceptable(circ,conn,must_be_open,purpose,
220 need_uptime,need_internal,now))
221 continue;
223 /* XXX022 make this 15 be a function of circuit finishing times we've
224 * seen lately, a la Fallon Chen's GSoC work -RD */
225 #define REND_PARALLEL_INTRO_DELAY 15
226 if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
227 !must_be_open && circ->state != CIRCUIT_STATE_OPEN &&
228 circ->timestamp_created + REND_PARALLEL_INTRO_DELAY < now) {
229 intro_going_on_but_too_old = 1;
230 continue;
233 /* now this is an acceptable circ to hand back. but that doesn't
234 * mean it's the *best* circ to hand back. try to decide.
236 if (!best || circuit_is_better(circ,best,purpose))
237 best = circ;
240 if (!best && intro_going_on_but_too_old)
241 log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
242 "right now, but it has already taken quite a while. Starting "
243 "one in parallel.");
245 return best ? TO_ORIGIN_CIRCUIT(best) : NULL;
248 /** Check whether, according to the policies in <b>options</b>, the
249 * circuit <b>circ</b> makes sense. */
250 /* XXXX currently only checks Exclude{Exit}Nodes. It should check more. */
252 circuit_conforms_to_options(const origin_circuit_t *circ,
253 const or_options_t *options)
255 const crypt_path_t *cpath, *cpath_next = NULL;
257 for (cpath = circ->cpath; cpath && cpath_next != circ->cpath;
258 cpath = cpath_next) {
259 cpath_next = cpath->next;
261 if (routerset_contains_extendinfo(options->ExcludeNodes,
262 cpath->extend_info))
263 return 0;
265 if (cpath->next == circ->cpath) {
266 /* This is apparently the exit node. */
268 if (routerset_contains_extendinfo(options->ExcludeExitNodes,
269 cpath->extend_info))
270 return 0;
273 return 1;
276 /** Close all circuits that start at us, aren't open, and were born
277 * at least CircuitBuildTimeout seconds ago.
279 void
280 circuit_expire_building(time_t now)
282 circuit_t *victim, *next_circ = global_circuitlist;
283 /* circ_times.timeout is BUILD_TIMEOUT_INITIAL_VALUE if we haven't
284 * decided on a customized one yet */
285 time_t general_cutoff = now - lround(circ_times.timeout_ms/1000);
286 time_t begindir_cutoff = now - lround(circ_times.timeout_ms/2000);
287 time_t close_cutoff = now - lround(circ_times.close_ms/1000);
288 time_t introcirc_cutoff = begindir_cutoff;
289 cpath_build_state_t *build_state;
291 while (next_circ) {
292 time_t cutoff;
293 victim = next_circ;
294 next_circ = next_circ->next;
295 if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
296 victim->marked_for_close) /* don't mess with marked circs */
297 continue;
299 build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
300 if (build_state && build_state->onehop_tunnel)
301 cutoff = begindir_cutoff;
302 else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
303 cutoff = introcirc_cutoff;
304 else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
305 cutoff = close_cutoff;
306 else
307 cutoff = general_cutoff;
309 if (victim->timestamp_created > cutoff)
310 continue; /* it's still young, leave it alone */
312 #if 0
313 /* some debug logs, to help track bugs */
314 if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
315 victim->timestamp_created <= introcirc_cutoff &&
316 victim->timestamp_created > general_cutoff)
317 log_info(LD_REND|LD_CIRC, "Timing out introduction circuit which we "
318 "would not have done if it had been a general circuit.");
320 if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
321 victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
322 if (!victim->timestamp_dirty)
323 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
324 "(clean).",
325 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
326 victim->purpose, victim->build_state->chosen_exit_name,
327 victim->n_circ_id);
328 else
329 log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
330 "%d secs since dirty.",
331 victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
332 victim->purpose, victim->build_state->chosen_exit_name,
333 victim->n_circ_id,
334 (int)(now - victim->timestamp_dirty));
336 #endif
338 /* if circ is !open, or if it's open but purpose is a non-finished
339 * intro or rend, then mark it for close */
340 if (victim->state == CIRCUIT_STATE_OPEN) {
341 switch (victim->purpose) {
342 default: /* most open circuits can be left alone. */
343 continue; /* yes, continue inside a switch refers to the nearest
344 * enclosing loop. C is smart. */
345 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
346 case CIRCUIT_PURPOSE_C_INTRODUCING:
347 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
348 break; /* too old, need to die */
349 case CIRCUIT_PURPOSE_C_REND_READY:
350 /* it's a rend_ready circ -- has it already picked a query? */
351 /* c_rend_ready circs measure age since timestamp_dirty,
352 * because that's set when they switch purposes
354 if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
355 victim->timestamp_dirty > cutoff)
356 continue;
357 break;
358 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
359 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
360 /* rend and intro circs become dirty each time they
361 * make an introduction attempt. so timestamp_dirty
362 * will reflect the time since the last attempt.
364 if (victim->timestamp_dirty > cutoff)
365 continue;
366 break;
368 } else { /* circuit not open, consider recording failure as timeout */
369 int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
370 TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
372 if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
373 log_warn(LD_BUG, "Circuit %d (purpose %d) has timed out, "
374 "yet has attached streams!",
375 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
376 victim->purpose);
377 tor_fragile_assert();
378 continue;
381 /* circuits are allowed to last longer for measurement.
382 * Switch their purpose and wait. */
383 if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
384 victim->purpose = CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT;
385 circuit_build_times_count_timeout(&circ_times,
386 first_hop_succeeded);
387 continue;
391 * If the circuit build time is much greater than we would have cut
392 * it off at, we probably had a suspend event along this codepath,
393 * and we should discard the value.
395 if (now - victim->timestamp_created > 2*circ_times.close_ms/1000+1) {
396 log_notice(LD_CIRC,
397 "Extremely large value for circuit build timeout: %lds. "
398 "Assuming clock jump.",
399 (long)(now - victim->timestamp_created));
400 } else if (circuit_build_times_count_close(&circ_times,
401 first_hop_succeeded,
402 victim->timestamp_created)) {
403 circuit_build_times_set_timeout(&circ_times);
407 if (victim->n_conn)
408 log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
409 victim->n_conn->_base.address, victim->n_conn->_base.port,
410 victim->n_circ_id,
411 victim->state, circuit_state_to_string(victim->state),
412 victim->purpose);
413 else
414 log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
415 victim->n_circ_id, victim->state,
416 circuit_state_to_string(victim->state), victim->purpose);
418 circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
419 circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
423 /** Remove any elements in <b>needed_ports</b> that are handled by an
424 * open or in-progress circuit.
426 void
427 circuit_remove_handled_ports(smartlist_t *needed_ports)
429 int i;
430 uint16_t *port;
432 for (i = 0; i < smartlist_len(needed_ports); ++i) {
433 port = smartlist_get(needed_ports, i);
434 tor_assert(*port);
435 if (circuit_stream_is_being_handled(NULL, *port,
436 MIN_CIRCUITS_HANDLING_STREAM)) {
437 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
438 smartlist_del(needed_ports, i--);
439 tor_free(port);
440 } else {
441 log_debug(LD_CIRC,"Port %d is not handled.", *port);
446 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
447 * will have an acceptable exit node for exit stream <b>conn</b> if it
448 * is defined, else for "*:port".
449 * Else return 0.
452 circuit_stream_is_being_handled(edge_connection_t *conn,
453 uint16_t port, int min)
455 circuit_t *circ;
456 routerinfo_t *exitrouter;
457 int num=0;
458 time_t now = time(NULL);
459 int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
460 conn ? conn->socks_request->port : port);
462 for (circ=global_circuitlist;circ;circ = circ->next) {
463 if (CIRCUIT_IS_ORIGIN(circ) &&
464 !circ->marked_for_close &&
465 circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
466 (!circ->timestamp_dirty ||
467 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
468 cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
469 if (build_state->is_internal || build_state->onehop_tunnel)
470 continue;
472 exitrouter = build_state_get_exit_router(build_state);
473 if (exitrouter && (!need_uptime || build_state->need_uptime)) {
474 int ok;
475 if (conn) {
476 ok = connection_ap_can_use_exit(conn, exitrouter, 0);
477 } else {
478 addr_policy_result_t r = compare_addr_to_addr_policy(
479 0, port, exitrouter->exit_policy);
480 ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
482 if (ok) {
483 if (++num >= min)
484 return 1;
489 return 0;
492 /** Don't keep more than this many unused open circuits around. */
493 #define MAX_UNUSED_OPEN_CIRCUITS 14
495 /** Figure out how many circuits we have open that are clean. Make
496 * sure it's enough for all the upcoming behaviors we predict we'll have.
497 * But put an upper bound on the total number of circuits.
499 static void
500 circuit_predict_and_launch_new(void)
502 circuit_t *circ;
503 int num=0, num_internal=0, num_uptime_internal=0;
504 int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
505 int port_needs_uptime=0, port_needs_capacity=1;
506 time_t now = time(NULL);
507 int flags = 0;
509 /* First, count how many of each type of circuit we have already. */
510 for (circ=global_circuitlist;circ;circ = circ->next) {
511 cpath_build_state_t *build_state;
512 if (!CIRCUIT_IS_ORIGIN(circ))
513 continue;
514 if (circ->marked_for_close)
515 continue; /* don't mess with marked circs */
516 if (circ->timestamp_dirty)
517 continue; /* only count clean circs */
518 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
519 continue; /* only pay attention to general-purpose circs */
520 build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
521 if (build_state->onehop_tunnel)
522 continue;
523 num++;
524 if (build_state->is_internal)
525 num_internal++;
526 if (build_state->need_uptime && build_state->is_internal)
527 num_uptime_internal++;
530 /* If that's enough, then stop now. */
531 if (num >= MAX_UNUSED_OPEN_CIRCUITS)
532 return; /* we already have many, making more probably will hurt */
534 /* Second, see if we need any more exit circuits. */
535 /* check if we know of a port that's been requested recently
536 * and no circuit is currently available that can handle it. */
537 if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
538 &port_needs_capacity)) {
539 if (port_needs_uptime)
540 flags |= CIRCLAUNCH_NEED_UPTIME;
541 if (port_needs_capacity)
542 flags |= CIRCLAUNCH_NEED_CAPACITY;
543 log_info(LD_CIRC,
544 "Have %d clean circs (%d internal), need another exit circ.",
545 num, num_internal);
546 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
547 return;
550 /* Third, see if we need any more hidden service (server) circuits. */
551 if (num_rend_services() && num_uptime_internal < 3) {
552 flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
553 CIRCLAUNCH_IS_INTERNAL);
554 log_info(LD_CIRC,
555 "Have %d clean circs (%d internal), need another internal "
556 "circ for my hidden service.",
557 num, num_internal);
558 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
559 return;
562 /* Fourth, see if we need any more hidden service (client) circuits. */
563 if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
564 &hidserv_needs_capacity) &&
565 ((num_uptime_internal<2 && hidserv_needs_uptime) ||
566 num_internal<2)) {
567 if (hidserv_needs_uptime)
568 flags |= CIRCLAUNCH_NEED_UPTIME;
569 if (hidserv_needs_capacity)
570 flags |= CIRCLAUNCH_NEED_CAPACITY;
571 flags |= CIRCLAUNCH_IS_INTERNAL;
572 log_info(LD_CIRC,
573 "Have %d clean circs (%d uptime-internal, %d internal), need"
574 " another hidden service circ.",
575 num, num_uptime_internal, num_internal);
576 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
577 return;
580 /* Finally, check to see if we still need more circuits to learn
581 * a good build timeout. But if we're close to our max number we
582 * want, don't do another -- we want to leave a few slots open so
583 * we can still build circuits preemptively as needed. */
584 if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
585 circuit_build_times_needs_circuits_now(&circ_times)) {
586 flags = CIRCLAUNCH_NEED_CAPACITY;
587 log_info(LD_CIRC,
588 "Have %d clean circs need another buildtime test circ.", num);
589 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, flags);
590 return;
594 /** Build a new test circuit every 5 minutes */
595 #define TESTING_CIRCUIT_INTERVAL 300
597 /** This function is called once a second, if router_have_min_dir_info() is
598 * true. Its job is to make sure all services we offer have enough circuits
599 * available. Some services just want enough circuits for current tasks,
600 * whereas others want a minimum set of idle circuits hanging around.
602 void
603 circuit_build_needed_circs(time_t now)
605 static time_t time_to_new_circuit = 0;
606 or_options_t *options = get_options();
608 /* launch a new circ for any pending streams that need one */
609 connection_ap_attach_pending();
611 /* make sure any hidden services have enough intro points */
612 rend_services_introduce();
614 if (time_to_new_circuit < now) {
615 circuit_reset_failure_count(1);
616 time_to_new_circuit = now + options->NewCircuitPeriod;
617 if (proxy_mode(get_options()))
618 addressmap_clean(now);
619 circuit_expire_old_circuits_clientside(now);
621 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
622 circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
623 if (get_options()->RunTesting &&
624 circ &&
625 circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
626 log_fn(LOG_INFO,"Creating a new testing circuit.");
627 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL, NULL, 0);
629 #endif
631 if (!options->DisablePredictedCircuits)
632 circuit_predict_and_launch_new();
635 /** If the stream <b>conn</b> is a member of any of the linked
636 * lists of <b>circ</b>, then remove it from the list.
638 void
639 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
641 edge_connection_t *prevconn;
643 tor_assert(circ);
644 tor_assert(conn);
646 conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
647 conn->on_circuit = NULL;
649 if (CIRCUIT_IS_ORIGIN(circ)) {
650 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
651 if (conn == origin_circ->p_streams) {
652 origin_circ->p_streams = conn->next_stream;
653 return;
656 for (prevconn = origin_circ->p_streams;
657 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
658 prevconn = prevconn->next_stream)
660 if (prevconn && prevconn->next_stream) {
661 prevconn->next_stream = conn->next_stream;
662 return;
664 } else {
665 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
666 if (conn == or_circ->n_streams) {
667 or_circ->n_streams = conn->next_stream;
668 return;
670 if (conn == or_circ->resolving_streams) {
671 or_circ->resolving_streams = conn->next_stream;
672 return;
675 for (prevconn = or_circ->n_streams;
676 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
677 prevconn = prevconn->next_stream)
679 if (prevconn && prevconn->next_stream) {
680 prevconn->next_stream = conn->next_stream;
681 return;
684 for (prevconn = or_circ->resolving_streams;
685 prevconn && prevconn->next_stream && prevconn->next_stream != conn;
686 prevconn = prevconn->next_stream)
688 if (prevconn && prevconn->next_stream) {
689 prevconn->next_stream = conn->next_stream;
690 return;
694 log_warn(LD_BUG,"Edge connection not in circuit's list.");
695 /* Don't give an error here; it's harmless. */
696 tor_fragile_assert();
699 /** If we haven't yet decided on a good timeout value for circuit
700 * building, we close idles circuits aggressively so we can get more
701 * data points. */
702 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
704 /** Find each circuit that has been unused for too long, or dirty
705 * for too long and has no streams on it: mark it for close.
707 static void
708 circuit_expire_old_circuits_clientside(time_t now)
710 circuit_t *circ;
711 time_t cutoff;
713 if (circuit_build_times_needs_circuits(&circ_times)) {
714 /* Circuits should be shorter lived if we need more of them
715 * for learning a good build timeout */
716 cutoff = now - IDLE_TIMEOUT_WHILE_LEARNING;
717 } else {
718 cutoff = now - get_options()->CircuitIdleTimeout;
721 for (circ = global_circuitlist; circ; circ = circ->next) {
722 if (circ->marked_for_close || ! CIRCUIT_IS_ORIGIN(circ))
723 continue;
724 /* If the circuit has been dirty for too long, and there are no streams
725 * on it, mark it for close.
727 if (circ->timestamp_dirty &&
728 circ->timestamp_dirty + get_options()->MaxCircuitDirtiness < now &&
729 !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
730 log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %d secs ago, "
731 "purpose %d)",
732 circ->n_circ_id, (int)(now - circ->timestamp_dirty),
733 circ->purpose);
734 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
735 } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
736 if (circ->timestamp_created < cutoff) {
737 if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
738 circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
739 circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
740 circ->purpose == CIRCUIT_PURPOSE_TESTING ||
741 (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
742 circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
743 circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
744 log_debug(LD_CIRC,
745 "Closing circuit that has been unused for %ld seconds.",
746 (long)(now - circ->timestamp_created));
747 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
748 } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
749 log_notice(LD_CIRC,
750 "Ancient non-dirty circuit %d is still around after "
751 "%ld seconds. Purpose: %d",
752 TO_ORIGIN_CIRCUIT(circ)->global_identifier,
753 (long)(now - circ->timestamp_created),
754 circ->purpose);
755 TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
762 /** How long do we wait before killing circuits with the properties
763 * described below?
765 * Probably we could choose a number here as low as 5 to 10 seconds,
766 * since these circs are used for begindir, and a) generally you either
767 * ask another begindir question right after or you don't for a long time,
768 * b) clients at least through 0.2.1.x choose from the whole set of
769 * directory mirrors at each choice, and c) re-establishing a one-hop
770 * circuit via create-fast is a light operation assuming the TLS conn is
771 * still there.
773 * I expect "b" to go away one day when we move to using directory
774 * guards, but I think "a" and "c" are good enough reasons that a low
775 * number is safe even then.
777 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
779 /** Find each non-origin circuit that has been unused for too long,
780 * has no streams on it, used a create_fast, and ends here: mark it
781 * for close.
783 void
784 circuit_expire_old_circuits_serverside(time_t now)
786 circuit_t *circ;
787 or_circuit_t *or_circ;
788 time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
790 for (circ = global_circuitlist; circ; circ = circ->next) {
791 if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
792 continue;
793 or_circ = TO_OR_CIRCUIT(circ);
794 /* If the circuit has been idle for too long, and there are no streams
795 * on it, and it ends here, and it used a create_fast, mark it for close.
797 if (or_circ->is_first_hop && !circ->n_conn &&
798 !or_circ->n_streams && !or_circ->resolving_streams &&
799 or_circ->p_conn &&
800 or_circ->p_conn->timestamp_last_added_nonpadding <= cutoff) {
801 log_info(LD_CIRC, "Closing circ_id %d (empty %d secs ago)",
802 or_circ->p_circ_id,
803 (int)(now - or_circ->p_conn->timestamp_last_added_nonpadding));
804 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
809 /** Number of testing circuits we want open before testing our bandwidth. */
810 #define NUM_PARALLEL_TESTING_CIRCS 4
812 /** True iff we've ever had enough testing circuits open to test our
813 * bandwidth. */
814 static int have_performed_bandwidth_test = 0;
816 /** Reset have_performed_bandwidth_test, so we'll start building
817 * testing circuits again so we can exercise our bandwidth. */
818 void
819 reset_bandwidth_test(void)
821 have_performed_bandwidth_test = 0;
824 /** Return 1 if we've already exercised our bandwidth, or if we
825 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
826 * established or on the way. Else return 0.
829 circuit_enough_testing_circs(void)
831 circuit_t *circ;
832 int num = 0;
834 if (have_performed_bandwidth_test)
835 return 1;
837 for (circ = global_circuitlist; circ; circ = circ->next) {
838 if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
839 circ->purpose == CIRCUIT_PURPOSE_TESTING &&
840 circ->state == CIRCUIT_STATE_OPEN)
841 num++;
843 return num >= NUM_PARALLEL_TESTING_CIRCS;
846 /** A testing circuit has completed. Take whatever stats we want.
847 * Noticing reachability is taken care of in onionskin_answer(),
848 * so there's no need to record anything here. But if we still want
849 * to do the bandwidth test, and we now have enough testing circuits
850 * open, do it.
852 static void
853 circuit_testing_opened(origin_circuit_t *circ)
855 if (have_performed_bandwidth_test ||
856 !check_whether_orport_reachable()) {
857 /* either we've already done everything we want with testing circuits,
858 * or this testing circuit became open due to a fluke, e.g. we picked
859 * a last hop where we already had the connection open due to an
860 * outgoing local circuit. */
861 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
862 } else if (circuit_enough_testing_circs()) {
863 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
864 have_performed_bandwidth_test = 1;
865 } else
866 consider_testing_reachability(1, 0);
869 /** A testing circuit has failed to build. Take whatever stats we want. */
870 static void
871 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
873 if (server_mode(get_options()) && check_whether_orport_reachable())
874 return;
876 log_info(LD_GENERAL,
877 "Our testing circuit (to see if your ORPort is reachable) "
878 "has failed. I'll try again later.");
880 /* These aren't used yet. */
881 (void)circ;
882 (void)at_last_hop;
885 /** The circuit <b>circ</b> has just become open. Take the next
886 * step: for rendezvous circuits, we pass circ to the appropriate
887 * function in rendclient or rendservice. For general circuits, we
888 * call connection_ap_attach_pending, which looks for pending streams
889 * that could use circ.
891 void
892 circuit_has_opened(origin_circuit_t *circ)
894 control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
896 switch (TO_CIRCUIT(circ)->purpose) {
897 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
898 rend_client_rendcirc_has_opened(circ);
899 connection_ap_attach_pending();
900 break;
901 case CIRCUIT_PURPOSE_C_INTRODUCING:
902 rend_client_introcirc_has_opened(circ);
903 break;
904 case CIRCUIT_PURPOSE_C_GENERAL:
905 /* Tell any AP connections that have been waiting for a new
906 * circuit that one is ready. */
907 connection_ap_attach_pending();
908 break;
909 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
910 /* at Bob, waiting for introductions */
911 rend_service_intro_has_opened(circ);
912 break;
913 case CIRCUIT_PURPOSE_S_CONNECT_REND:
914 /* at Bob, connecting to rend point */
915 rend_service_rendezvous_has_opened(circ);
916 break;
917 case CIRCUIT_PURPOSE_TESTING:
918 circuit_testing_opened(circ);
919 break;
920 /* default:
921 * This won't happen in normal operation, but might happen if the
922 * controller did it. Just let it slide. */
926 /** Called whenever a circuit could not be successfully built.
928 void
929 circuit_build_failed(origin_circuit_t *circ)
931 /* we should examine circ and see if it failed because of
932 * the last hop or an earlier hop. then use this info below.
934 int failed_at_last_hop = 0;
935 /* If the last hop isn't open, and the second-to-last is, we failed
936 * at the last hop. */
937 if (circ->cpath &&
938 circ->cpath->prev->state != CPATH_STATE_OPEN &&
939 circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
940 failed_at_last_hop = 1;
942 if (circ->cpath &&
943 circ->cpath->state != CPATH_STATE_OPEN) {
944 /* We failed at the first hop. If there's an OR connection
945 * to blame, blame it. Also, avoid this relay for a while, and
946 * fail any one-hop directory fetches destined for it. */
947 const char *n_conn_id = circ->cpath->extend_info->identity_digest;
948 if (circ->_base.n_conn) {
949 or_connection_t *n_conn = circ->_base.n_conn;
950 log_info(LD_OR,
951 "Our circuit failed to get a response from the first hop "
952 "(%s:%d). I'm going to try to rotate to a better connection.",
953 n_conn->_base.address, n_conn->_base.port);
954 n_conn->is_bad_for_new_circs = 1;
955 } else {
956 log_info(LD_OR,
957 "Our circuit died before the first hop with no connection");
959 if (n_conn_id) {
960 entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
961 /* if there are any one-hop streams waiting on this circuit, fail
962 * them now so they can retry elsewhere. */
963 connection_ap_fail_onehop(n_conn_id, circ->build_state);
967 switch (circ->_base.purpose) {
968 case CIRCUIT_PURPOSE_C_GENERAL:
969 /* If we never built the circuit, note it as a failure. */
970 circuit_increment_failure_count();
971 if (failed_at_last_hop) {
972 /* Make sure any streams that demand our last hop as their exit
973 * know that it's unlikely to happen. */
974 circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
976 break;
977 case CIRCUIT_PURPOSE_TESTING:
978 circuit_testing_failed(circ, failed_at_last_hop);
979 break;
980 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
981 /* at Bob, waiting for introductions */
982 if (circ->_base.state != CIRCUIT_STATE_OPEN) {
983 circuit_increment_failure_count();
985 /* no need to care here, because bob will rebuild intro
986 * points periodically. */
987 break;
988 case CIRCUIT_PURPOSE_C_INTRODUCING:
989 /* at Alice, connecting to intro point */
990 /* Don't increment failure count, since Bob may have picked
991 * the introduction point maliciously */
992 /* Alice will pick a new intro point when this one dies, if
993 * the stream in question still cares. No need to act here. */
994 break;
995 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
996 /* at Alice, waiting for Bob */
997 circuit_increment_failure_count();
998 /* Alice will pick a new rend point when this one dies, if
999 * the stream in question still cares. No need to act here. */
1000 break;
1001 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1002 /* at Bob, connecting to rend point */
1003 /* Don't increment failure count, since Alice may have picked
1004 * the rendezvous point maliciously */
1005 log_info(LD_REND,
1006 "Couldn't connect to Alice's chosen rend point %s "
1007 "(%s hop failed).",
1008 escaped(build_state_get_exit_nickname(circ->build_state)),
1009 failed_at_last_hop?"last":"non-last");
1010 rend_service_relaunch_rendezvous(circ);
1011 break;
1012 /* default:
1013 * This won't happen in normal operation, but might happen if the
1014 * controller did it. Just let it slide. */
1018 /** Number of consecutive failures so far; should only be touched by
1019 * circuit_launch_new and circuit_*_failure_count.
1021 static int n_circuit_failures = 0;
1022 /** Before the last time we called circuit_reset_failure_count(), were
1023 * there a lot of failures? */
1024 static int did_circs_fail_last_period = 0;
1026 /** Don't retry launching a new circuit if we try this many times with no
1027 * success. */
1028 #define MAX_CIRCUIT_FAILURES 5
1030 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1031 * details on arguments. */
1032 origin_circuit_t *
1033 circuit_launch_by_router(uint8_t purpose,
1034 routerinfo_t *exit, int flags)
1036 origin_circuit_t *circ;
1037 extend_info_t *info = NULL;
1038 if (exit)
1039 info = extend_info_from_router(exit);
1040 circ = circuit_launch_by_extend_info(purpose, info, flags);
1042 extend_info_free(info);
1043 return circ;
1046 /** Launch a new circuit with purpose <b>purpose</b> and exit node
1047 * <b>extend_info</b> (or NULL to select a random exit node). If flags
1048 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
1049 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
1050 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
1051 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
1052 * Return the newly allocated circuit on success, or NULL on failure. */
1053 origin_circuit_t *
1054 circuit_launch_by_extend_info(uint8_t purpose,
1055 extend_info_t *extend_info,
1056 int flags)
1058 origin_circuit_t *circ;
1059 int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
1061 if (!onehop_tunnel && !router_have_minimum_dir_info()) {
1062 log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
1063 "circuit launch.");
1064 return NULL;
1067 if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
1068 purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
1069 /* see if there are appropriate circs available to cannibalize. */
1070 /* XXX if we're planning to add a hop, perhaps we want to look for
1071 * internal circs rather than exit circs? -RD */
1072 circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
1073 if (circ) {
1074 log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d",
1075 build_state_get_exit_nickname(circ->build_state), purpose);
1076 circ->_base.purpose = purpose;
1077 /* reset the birth date of this circ, else expire_building
1078 * will see it and think it's been trying to build since it
1079 * began. */
1080 circ->_base.timestamp_created = time(NULL);
1081 switch (purpose) {
1082 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1083 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1084 /* it's ready right now */
1085 break;
1086 case CIRCUIT_PURPOSE_C_INTRODUCING:
1087 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1088 case CIRCUIT_PURPOSE_C_GENERAL:
1089 /* need to add a new hop */
1090 tor_assert(extend_info);
1091 if (circuit_extend_to_new_exit(circ, extend_info) < 0)
1092 return NULL;
1093 break;
1094 default:
1095 log_warn(LD_BUG,
1096 "unexpected purpose %d when cannibalizing a circ.",
1097 purpose);
1098 tor_fragile_assert();
1099 return NULL;
1101 return circ;
1105 if (did_circs_fail_last_period &&
1106 n_circuit_failures > MAX_CIRCUIT_FAILURES) {
1107 /* too many failed circs in a row. don't try. */
1108 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1109 return NULL;
1112 /* try a circ. if it fails, circuit_mark_for_close will increment
1113 * n_circuit_failures */
1114 return circuit_establish_circuit(purpose, extend_info, flags);
1117 /** Record another failure at opening a general circuit. When we have
1118 * too many, we'll stop trying for the remainder of this minute.
1120 static void
1121 circuit_increment_failure_count(void)
1123 ++n_circuit_failures;
1124 log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
1127 /** Reset the failure count for opening general circuits. This means
1128 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1129 * stopping again.
1131 void
1132 circuit_reset_failure_count(int timeout)
1134 if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
1135 did_circs_fail_last_period = 1;
1136 else
1137 did_circs_fail_last_period = 0;
1138 n_circuit_failures = 0;
1141 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1142 * there isn't one, and there isn't one on the way, launch one and return
1143 * 0. If it will never work, return -1.
1145 * Write the found or in-progress or launched circ into *circp.
1147 static int
1148 circuit_get_open_circ_or_launch(edge_connection_t *conn,
1149 uint8_t desired_circuit_purpose,
1150 origin_circuit_t **circp)
1152 origin_circuit_t *circ;
1153 int check_exit_policy;
1154 int need_uptime, need_internal;
1155 int want_onehop;
1156 or_options_t *options = get_options();
1158 tor_assert(conn);
1159 tor_assert(circp);
1160 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1161 check_exit_policy =
1162 conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
1163 !conn->use_begindir &&
1164 !connection_edge_is_rendezvous_stream(conn);
1165 want_onehop = conn->want_onehop;
1167 need_uptime = !conn->want_onehop && !conn->use_begindir &&
1168 smartlist_string_num_isin(options->LongLivedPorts,
1169 conn->socks_request->port);
1170 need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
1172 circ = circuit_get_best(conn, 1, desired_circuit_purpose,
1173 need_uptime, need_internal);
1175 if (circ) {
1176 *circp = circ;
1177 return 1; /* we're happy */
1180 if (!want_onehop && !router_have_minimum_dir_info()) {
1181 if (!connection_get_by_type(CONN_TYPE_DIR)) {
1182 int severity = LOG_NOTICE;
1183 /* FFFF if this is a tunneled directory fetch, don't yell
1184 * as loudly. the user doesn't even know it's happening. */
1185 if (options->UseBridges && bridges_known_but_down()) {
1186 log_fn(severity, LD_APP|LD_DIR,
1187 "Application request when we're believed to be "
1188 "offline. Optimistically trying known bridges again.");
1189 bridges_retry_all();
1190 } else if (!options->UseBridges || any_bridge_descriptors_known()) {
1191 log_fn(severity, LD_APP|LD_DIR,
1192 "Application request when we're believed to be "
1193 "offline. Optimistically trying directory fetches again.");
1194 routerlist_retry_directory_downloads(time(NULL));
1197 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1198 * 1, or when all directory attempts fail and directory_all_unreachable()
1199 * kills it.
1201 return 0;
1204 /* Do we need to check exit policy? */
1205 if (check_exit_policy) {
1206 if (!conn->chosen_exit_name) {
1207 struct in_addr in;
1208 uint32_t addr = 0;
1209 if (tor_inet_aton(conn->socks_request->address, &in))
1210 addr = ntohl(in.s_addr);
1211 if (router_exit_policy_all_routers_reject(addr,
1212 conn->socks_request->port,
1213 need_uptime)) {
1214 log_notice(LD_APP,
1215 "No Tor server allows exit to %s:%d. Rejecting.",
1216 safe_str_client(conn->socks_request->address),
1217 conn->socks_request->port);
1218 return -1;
1220 } else {
1221 /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
1222 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1223 int opt = conn->chosen_exit_optional;
1224 if (router && !connection_ap_can_use_exit(conn, router, 0)) {
1225 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1226 "Requested exit point '%s' would refuse request. %s.",
1227 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1228 if (opt) {
1229 conn->chosen_exit_optional = 0;
1230 tor_free(conn->chosen_exit_name);
1231 /* Try again. */
1232 return circuit_get_open_circ_or_launch(conn,
1233 desired_circuit_purpose,
1234 circp);
1236 return -1;
1241 /* is one already on the way? */
1242 circ = circuit_get_best(conn, 0, desired_circuit_purpose,
1243 need_uptime, need_internal);
1244 if (circ)
1245 log_debug(LD_CIRC, "one on the way!");
1246 if (!circ) {
1247 extend_info_t *extend_info=NULL;
1248 uint8_t new_circ_purpose;
1250 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1251 /* need to pick an intro point */
1252 tor_assert(conn->rend_data);
1253 extend_info = rend_client_get_random_intro(conn->rend_data);
1254 if (!extend_info) {
1255 log_info(LD_REND,
1256 "No intro points for '%s': re-fetching service descriptor.",
1257 safe_str_client(conn->rend_data->onion_address));
1258 rend_client_refetch_v2_renddesc(conn->rend_data);
1259 conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
1260 return 0;
1262 log_info(LD_REND,"Chose '%s' as intro point for '%s'.",
1263 extend_info->nickname,
1264 safe_str_client(conn->rend_data->onion_address));
1267 /* If we have specified a particular exit node for our
1268 * connection, then be sure to open a circuit to that exit node.
1270 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
1271 if (conn->chosen_exit_name) {
1272 routerinfo_t *r;
1273 int opt = conn->chosen_exit_optional;
1274 r = router_get_by_nickname(conn->chosen_exit_name, 1);
1275 if (r) {
1276 extend_info = extend_info_from_router(r);
1277 } else {
1278 log_debug(LD_DIR, "considering %d, %s",
1279 want_onehop, conn->chosen_exit_name);
1280 if (want_onehop && conn->chosen_exit_name[0] == '$') {
1281 /* We're asking for a one-hop circuit to a router that
1282 * we don't have a routerinfo about. Make up an extend_info. */
1283 char digest[DIGEST_LEN];
1284 char *hexdigest = conn->chosen_exit_name+1;
1285 tor_addr_t addr;
1286 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
1287 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
1288 log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
1289 return -1;
1291 if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
1292 log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
1293 escaped_safe_str_client(conn->socks_request->address));
1294 return -1;
1296 extend_info = extend_info_alloc(conn->chosen_exit_name+1,
1297 digest, NULL, &addr,
1298 conn->socks_request->port);
1299 } else {
1300 /* We will need an onion key for the router, and we
1301 * don't have one. Refuse or relax requirements. */
1302 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1303 "Requested exit point '%s' is not known. %s.",
1304 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1305 if (opt) {
1306 conn->chosen_exit_optional = 0;
1307 tor_free(conn->chosen_exit_name);
1308 /* Try again with no requested exit */
1309 return circuit_get_open_circ_or_launch(conn,
1310 desired_circuit_purpose,
1311 circp);
1313 return -1;
1319 if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
1320 new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
1321 else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1322 new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
1323 else
1324 new_circ_purpose = desired_circuit_purpose;
1327 int flags = CIRCLAUNCH_NEED_CAPACITY;
1328 if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
1329 if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
1330 if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
1331 circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
1332 flags);
1335 extend_info_free(extend_info);
1337 if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL) {
1338 /* help predict this next time */
1339 rep_hist_note_used_internal(time(NULL), need_uptime, 1);
1340 if (circ) {
1341 /* write the service_id into circ */
1342 circ->rend_data = rend_data_dup(conn->rend_data);
1343 if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
1344 circ->_base.state == CIRCUIT_STATE_OPEN)
1345 rend_client_rendcirc_has_opened(circ);
1349 if (!circ)
1350 log_info(LD_APP,
1351 "No safe circuit (purpose %d) ready for edge "
1352 "connection; delaying.",
1353 desired_circuit_purpose);
1354 *circp = circ;
1355 return 0;
1358 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1359 * <b>circ</b>. */
1360 static int
1361 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
1363 crypt_path_t *cpath, *cpath_next = NULL;
1364 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1365 cpath_next = cpath->next;
1366 if (crypt_path == cpath)
1367 return 1;
1369 return 0;
1372 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1373 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1374 * hop in circ's cpath if <b>cpath</b> is NULL.
1376 static void
1377 link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
1378 crypt_path_t *cpath)
1380 /* add it into the linked list of streams on this circuit */
1381 log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
1382 circ->_base.n_circ_id);
1383 /* reset it, so we can measure circ timeouts */
1384 apconn->_base.timestamp_lastread = time(NULL);
1385 apconn->next_stream = circ->p_streams;
1386 apconn->on_circuit = TO_CIRCUIT(circ);
1387 /* assert_connection_ok(conn, time(NULL)); */
1388 circ->p_streams = apconn;
1390 if (cpath) { /* we were given one; use it */
1391 tor_assert(cpath_is_on_circuit(circ, cpath));
1392 apconn->cpath_layer = cpath;
1393 } else { /* use the last hop in the circuit */
1394 tor_assert(circ->cpath);
1395 tor_assert(circ->cpath->prev);
1396 tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
1397 apconn->cpath_layer = circ->cpath->prev;
1401 /** If an exit wasn't specifically chosen, save the history for future
1402 * use. */
1403 static void
1404 consider_recording_trackhost(edge_connection_t *conn, origin_circuit_t *circ)
1406 int found_needle = 0;
1407 or_options_t *options = get_options();
1408 size_t len;
1409 char *new_address;
1410 char fp[HEX_DIGEST_LEN+1];
1412 /* Search the addressmap for this conn's destination. */
1413 /* If he's not in the address map.. */
1414 if (!options->TrackHostExits ||
1415 addressmap_have_mapping(conn->socks_request->address,
1416 options->TrackHostExitsExpire))
1417 return; /* nothing to track, or already mapped */
1419 SMARTLIST_FOREACH(options->TrackHostExits, const char *, cp, {
1420 if (cp[0] == '.') { /* match end */
1421 if (cp[1] == '\0' ||
1422 !strcasecmpend(conn->socks_request->address, cp) ||
1423 !strcasecmp(conn->socks_request->address, &cp[1]))
1424 found_needle = 1;
1425 } else if (strcasecmp(cp, conn->socks_request->address) == 0) {
1426 found_needle = 1;
1430 if (!found_needle || !circ->build_state->chosen_exit)
1431 return;
1433 /* write down the fingerprint of the chosen exit, not the nickname,
1434 * because the chosen exit might not be named. */
1435 base16_encode(fp, sizeof(fp),
1436 circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
1438 /* Add this exit/hostname pair to the addressmap. */
1439 len = strlen(conn->socks_request->address) + 1 /* '.' */ +
1440 strlen(fp) + 1 /* '.' */ +
1441 strlen("exit") + 1 /* '\0' */;
1442 new_address = tor_malloc(len);
1444 tor_snprintf(new_address, len, "%s.%s.exit",
1445 conn->socks_request->address, fp);
1447 addressmap_register(conn->socks_request->address, new_address,
1448 time(NULL) + options->TrackHostExitsExpire,
1449 ADDRMAPSRC_TRACKEXIT);
1452 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1453 * begin or resolve cell as appropriate. Return values are as for
1454 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1455 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1456 * <b>cpath</b> is NULL. */
1458 connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
1459 origin_circuit_t *circ,
1460 crypt_path_t *cpath)
1462 tor_assert(conn);
1463 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
1464 conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
1465 tor_assert(conn->socks_request);
1466 tor_assert(circ);
1467 tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
1469 conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
1471 if (!circ->_base.timestamp_dirty)
1472 circ->_base.timestamp_dirty = time(NULL);
1474 link_apconn_to_circ(conn, circ, cpath);
1475 tor_assert(conn->socks_request);
1476 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
1477 if (!conn->use_begindir)
1478 consider_recording_trackhost(conn, circ);
1479 if (connection_ap_handshake_send_begin(conn) < 0)
1480 return -1;
1481 } else {
1482 if (connection_ap_handshake_send_resolve(conn) < 0)
1483 return -1;
1486 return 1;
1489 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1490 * we don't find one: if conn cannot be handled by any known nodes,
1491 * warn and return -1 (conn needs to die, and is maybe already marked);
1492 * else launch new circuit (if necessary) and return 0.
1493 * Otherwise, associate conn with a safe live circuit, do the
1494 * right next step, and return 1.
1496 /* XXXX this function should mark for close whenever it returns -1;
1497 * its callers shouldn't have to worry about that. */
1499 connection_ap_handshake_attach_circuit(edge_connection_t *conn)
1501 int retval;
1502 int conn_age;
1503 int want_onehop;
1505 tor_assert(conn);
1506 tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
1507 tor_assert(conn->socks_request);
1508 want_onehop = conn->want_onehop;
1510 conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
1512 if (conn_age >= get_options()->SocksTimeout) {
1513 int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
1514 LOG_INFO : LOG_NOTICE;
1515 log_fn(severity, LD_APP,
1516 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1517 conn_age, safe_str_client(conn->socks_request->address),
1518 conn->socks_request->port);
1519 return -1;
1522 if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
1523 origin_circuit_t *circ=NULL;
1525 if (conn->chosen_exit_name) {
1526 routerinfo_t *router = router_get_by_nickname(conn->chosen_exit_name, 1);
1527 int opt = conn->chosen_exit_optional;
1528 if (!router && !want_onehop) {
1529 /* We ran into this warning when trying to extend a circuit to a
1530 * hidden service directory for which we didn't have a router
1531 * descriptor. See flyspray task 767 for more details. We should
1532 * keep this in mind when deciding to use BEGIN_DIR cells for other
1533 * directory requests as well. -KL*/
1534 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1535 "Requested exit point '%s' is not known. %s.",
1536 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1537 if (opt) {
1538 conn->chosen_exit_optional = 0;
1539 tor_free(conn->chosen_exit_name);
1540 return 0;
1542 return -1;
1544 if (router && !connection_ap_can_use_exit(conn, router, 0)) {
1545 log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
1546 "Requested exit point '%s' would refuse request. %s.",
1547 conn->chosen_exit_name, opt ? "Trying others" : "Closing");
1548 if (opt) {
1549 conn->chosen_exit_optional = 0;
1550 tor_free(conn->chosen_exit_name);
1551 return 0;
1553 return -1;
1557 /* find the circuit that we should use, if there is one. */
1558 retval = circuit_get_open_circ_or_launch(
1559 conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
1560 if (retval < 1) // XXX021 if we totally fail, this still returns 0 -RD
1561 return retval;
1563 log_debug(LD_APP|LD_CIRC,
1564 "Attaching apconn to circ %d (stream %d sec old).",
1565 circ->_base.n_circ_id, conn_age);
1566 /* print the circ's path, so people can figure out which circs are
1567 * sucking. */
1568 circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
1570 /* We have found a suitable circuit for our conn. Hurray. */
1571 return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
1573 } else { /* we're a rendezvous conn */
1574 origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
1576 tor_assert(!conn->cpath_layer);
1578 /* start by finding a rendezvous circuit for us */
1580 retval = circuit_get_open_circ_or_launch(
1581 conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
1582 if (retval < 0) return -1; /* failed */
1584 if (retval > 0) {
1585 tor_assert(rendcirc);
1586 /* one is already established, attach */
1587 log_info(LD_REND,
1588 "rend joined circ %d already here. attaching. "
1589 "(stream %d sec old)",
1590 rendcirc->_base.n_circ_id, conn_age);
1591 /* Mark rendezvous circuits as 'newly dirty' every time you use
1592 * them, since the process of rebuilding a rendezvous circ is so
1593 * expensive. There is a tradeoff between linkability and
1594 * feasibility, at this point.
1596 rendcirc->_base.timestamp_dirty = time(NULL);
1597 link_apconn_to_circ(conn, rendcirc, NULL);
1598 if (connection_ap_handshake_send_begin(conn) < 0)
1599 return 0; /* already marked, let them fade away */
1600 return 1;
1603 if (rendcirc && (rendcirc->_base.purpose ==
1604 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
1605 log_info(LD_REND,
1606 "pending-join circ %d already here, with intro ack. "
1607 "Stalling. (stream %d sec old)",
1608 rendcirc->_base.n_circ_id, conn_age);
1609 return 0;
1612 /* it's on its way. find an intro circ. */
1613 retval = circuit_get_open_circ_or_launch(
1614 conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
1615 if (retval < 0) return -1; /* failed */
1617 if (retval > 0) {
1618 /* one has already sent the intro. keep waiting. */
1619 circuit_t *c = NULL;
1620 tor_assert(introcirc);
1621 log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
1622 "Stalling. (stream %d sec old)",
1623 introcirc->_base.n_circ_id,
1624 rendcirc ? rendcirc->_base.n_circ_id : 0,
1625 conn_age);
1626 /* abort parallel intro circs, if any */
1627 for (c = global_circuitlist; c; c = c->next) {
1628 if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
1629 !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
1630 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
1631 if (oc->rend_data &&
1632 !rend_cmp_service_ids(conn->rend_data->onion_address,
1633 oc->rend_data->onion_address)) {
1634 log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
1635 "built in parallel.");
1636 circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
1640 return 0;
1643 /* now rendcirc and introcirc are each either undefined or not finished */
1645 if (rendcirc && introcirc &&
1646 rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1647 log_info(LD_REND,
1648 "ready rend circ %d already here (no intro-ack yet on "
1649 "intro %d). (stream %d sec old)",
1650 rendcirc->_base.n_circ_id,
1651 introcirc->_base.n_circ_id, conn_age);
1653 tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
1654 if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
1655 log_info(LD_REND,"found open intro circ %d (rend %d); sending "
1656 "introduction. (stream %d sec old)",
1657 introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
1658 conn_age);
1659 if (rend_client_send_introduction(introcirc, rendcirc) < 0) {
1660 return -1;
1662 rendcirc->_base.timestamp_dirty = time(NULL);
1663 introcirc->_base.timestamp_dirty = time(NULL);
1664 assert_circuit_ok(TO_CIRCUIT(rendcirc));
1665 assert_circuit_ok(TO_CIRCUIT(introcirc));
1666 return 0;
1670 log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
1671 "Stalling conn. (%d sec old)",
1672 introcirc ? introcirc->_base.n_circ_id : 0,
1673 rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
1674 return 0;