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 */
9 * \brief Launch the right sort of circuits and attach streams to them.
13 #include "circuitbuild.h"
14 #include "circuitlist.h"
15 #include "circuituse.h"
17 #include "connection.h"
18 #include "connection_edge.h"
21 #include "rendclient.h"
22 #include "rendcommon.h"
23 #include "rendservice.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 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
41 circuit_is_acceptable(circuit_t
*circ
, edge_connection_t
*conn
,
42 int must_be_open
, uint8_t purpose
,
43 int need_uptime
, int need_internal
,
46 routerinfo_t
*exitrouter
;
47 cpath_build_state_t
*build_state
;
50 tor_assert(conn
->socks_request
);
52 if (!CIRCUIT_IS_ORIGIN(circ
))
53 return 0; /* this circ doesn't start at us */
54 if (must_be_open
&& (circ
->state
!= CIRCUIT_STATE_OPEN
|| !circ
->n_conn
))
55 return 0; /* ignore non-open circs */
56 if (circ
->marked_for_close
)
59 /* if this circ isn't our purpose, skip. */
60 if (purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
&& !must_be_open
) {
61 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_ESTABLISH_REND
&&
62 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_READY
&&
63 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
&&
64 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_JOINED
)
66 } else if (purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
&&
68 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCING
&&
69 circ
->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
72 if (purpose
!= circ
->purpose
)
76 if (purpose
== CIRCUIT_PURPOSE_C_GENERAL
)
77 if (circ
->timestamp_dirty
&&
78 circ
->timestamp_dirty
+get_options()->MaxCircuitDirtiness
<= now
)
81 /* decide if this circ is suitable for this conn */
83 /* for rend circs, circ->cpath->prev is not the last router in the
84 * circuit, it's the magical extra bob hop. so just check the nickname
85 * of the one we meant to finish at.
87 build_state
= TO_ORIGIN_CIRCUIT(circ
)->build_state
;
88 exitrouter
= build_state_get_exit_router(build_state
);
90 if (need_uptime
&& !build_state
->need_uptime
)
92 if (need_internal
!= build_state
->is_internal
)
95 if (purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
96 if (!exitrouter
&& !build_state
->onehop_tunnel
) {
97 log_debug(LD_CIRC
,"Not considering circuit with unknown router.");
98 return 0; /* this circuit is screwed and doesn't know it yet,
99 * or is a rendezvous circuit. */
101 if (build_state
->onehop_tunnel
) {
102 if (!conn
->want_onehop
) {
103 log_debug(LD_CIRC
,"Skipping one-hop circuit.");
106 tor_assert(conn
->chosen_exit_name
);
107 if (build_state
->chosen_exit
) {
108 char digest
[DIGEST_LEN
];
109 if (hexdigest_to_digest(conn
->chosen_exit_name
, digest
) < 0)
110 return 0; /* broken digest, we don't want it */
111 if (memcmp(digest
, build_state
->chosen_exit
->identity_digest
,
113 return 0; /* this is a circuit to somewhere else */
114 if (tor_digest_is_zero(digest
)) {
115 /* we don't know the digest; have to compare addr:port */
117 int r
= tor_addr_from_str(&addr
, conn
->socks_request
->address
);
119 !tor_addr_eq(&build_state
->chosen_exit
->addr
, &addr
) ||
120 build_state
->chosen_exit
->port
!= conn
->socks_request
->port
)
125 if (conn
->want_onehop
) {
126 /* don't use three-hop circuits -- that could hurt our anonymity. */
130 if (exitrouter
&& !connection_ap_can_use_exit(conn
, exitrouter
, 0)) {
131 /* can't exit from this router */
134 } else { /* not general */
135 origin_circuit_t
*ocirc
= TO_ORIGIN_CIRCUIT(circ
);
136 if ((conn
->rend_data
&& !ocirc
->rend_data
) ||
137 (!conn
->rend_data
&& ocirc
->rend_data
) ||
138 (conn
->rend_data
&& ocirc
->rend_data
&&
139 rend_cmp_service_ids(conn
->rend_data
->onion_address
,
140 ocirc
->rend_data
->onion_address
))) {
141 /* this circ is not for this conn */
148 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
149 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
152 circuit_is_better(circuit_t
*a
, circuit_t
*b
, uint8_t purpose
)
155 case CIRCUIT_PURPOSE_C_GENERAL
:
156 /* if it's used but less dirty it's best;
157 * else if it's more recently created it's best
159 if (b
->timestamp_dirty
) {
160 if (a
->timestamp_dirty
&&
161 a
->timestamp_dirty
> b
->timestamp_dirty
)
164 if (a
->timestamp_dirty
||
165 a
->timestamp_created
> b
->timestamp_created
)
167 if (CIRCUIT_IS_ORIGIN(b
) &&
168 TO_ORIGIN_CIRCUIT(b
)->build_state
->is_internal
)
172 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
173 /* the closer it is to ack_wait the better it is */
174 if (a
->purpose
> b
->purpose
)
177 case CIRCUIT_PURPOSE_C_REND_JOINED
:
178 /* the closer it is to rend_joined the better it is */
179 if (a
->purpose
> b
->purpose
)
186 /** Find the best circ that conn can use, preferably one which is
187 * dirty. Circ must not be too old.
189 * Conn must be defined.
191 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
193 * circ_purpose specifies what sort of circuit we must have.
194 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
196 * If it's REND_JOINED and must_be_open==0, then return the closest
197 * rendezvous-purposed circuit that you can find.
199 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
200 * closest introduce-purposed circuit that you can find.
202 static origin_circuit_t
*
203 circuit_get_best(edge_connection_t
*conn
, int must_be_open
, uint8_t purpose
,
204 int need_uptime
, int need_internal
)
206 circuit_t
*circ
, *best
=NULL
;
207 time_t now
= time(NULL
);
208 int intro_going_on_but_too_old
= 0;
212 tor_assert(purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
213 purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
||
214 purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
);
216 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
217 if (!circuit_is_acceptable(circ
,conn
,must_be_open
,purpose
,
218 need_uptime
,need_internal
,now
))
221 /* XXX022 make this 15 be a function of circuit finishing times we've
222 * seen lately, a la Fallon Chen's GSoC work -RD */
223 #define REND_PARALLEL_INTRO_DELAY 15
224 if (purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
&&
225 !must_be_open
&& circ
->state
!= CIRCUIT_STATE_OPEN
&&
226 circ
->timestamp_created
+ REND_PARALLEL_INTRO_DELAY
< now
) {
227 intro_going_on_but_too_old
= 1;
231 /* now this is an acceptable circ to hand back. but that doesn't
232 * mean it's the *best* circ to hand back. try to decide.
234 if (!best
|| circuit_is_better(circ
,best
,purpose
))
238 if (!best
&& intro_going_on_but_too_old
)
239 log_info(LD_REND
|LD_CIRC
, "There is an intro circuit being created "
240 "right now, but it has already taken quite a while. Starting "
243 return best
? TO_ORIGIN_CIRCUIT(best
) : NULL
;
246 /** Check whether, according to the policies in <b>options</b>, the
247 * circuit <b>circ</b> makes sense. */
248 /* XXXX currently only checks Exclude{Exit}Nodes. It should check more. */
250 circuit_conforms_to_options(const origin_circuit_t
*circ
,
251 const or_options_t
*options
)
253 const crypt_path_t
*cpath
, *cpath_next
= NULL
;
255 for (cpath
= circ
->cpath
; cpath
&& cpath_next
!= circ
->cpath
;
256 cpath
= cpath_next
) {
257 cpath_next
= cpath
->next
;
259 if (routerset_contains_extendinfo(options
->ExcludeNodes
,
263 if (cpath
->next
== circ
->cpath
) {
264 /* This is apparently the exit node. */
266 if (routerset_contains_extendinfo(options
->ExcludeExitNodes
,
274 /** Close all circuits that start at us, aren't open, and were born
275 * at least CircuitBuildTimeout seconds ago.
278 circuit_expire_building(time_t now
)
280 circuit_t
*victim
, *next_circ
= global_circuitlist
;
281 /* circ_times.timeout_ms and circ_times.close_ms are from
282 * circuit_build_times_get_initial_timeout() if we haven't computed
283 * custom timeouts yet */
284 time_t general_cutoff
= now
- tor_lround(circ_times
.timeout_ms
/1000);
285 time_t begindir_cutoff
= now
- tor_lround(circ_times
.timeout_ms
/2000);
286 time_t fourhop_cutoff
= now
- tor_lround(4*circ_times
.timeout_ms
/3000);
287 time_t cannibalize_cutoff
= now
- tor_lround(circ_times
.timeout_ms
/2000);
288 time_t close_cutoff
= now
- tor_lround(circ_times
.close_ms
/1000);
289 time_t introcirc_cutoff
= begindir_cutoff
;
290 cpath_build_state_t
*build_state
;
295 next_circ
= next_circ
->next
;
296 if (!CIRCUIT_IS_ORIGIN(victim
) || /* didn't originate here */
297 victim
->marked_for_close
) /* don't mess with marked circs */
300 build_state
= TO_ORIGIN_CIRCUIT(victim
)->build_state
;
301 if (build_state
&& build_state
->onehop_tunnel
)
302 cutoff
= begindir_cutoff
;
303 else if (build_state
&& build_state
->desired_path_len
== 4
304 && !TO_ORIGIN_CIRCUIT(victim
)->has_opened
)
305 cutoff
= fourhop_cutoff
;
306 else if (TO_ORIGIN_CIRCUIT(victim
)->has_opened
)
307 cutoff
= cannibalize_cutoff
;
308 else if (victim
->purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
)
309 cutoff
= introcirc_cutoff
;
310 else if (victim
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
)
311 cutoff
= close_cutoff
;
313 cutoff
= general_cutoff
;
315 if (victim
->timestamp_created
> cutoff
)
316 continue; /* it's still young, leave it alone */
319 /* some debug logs, to help track bugs */
320 if (victim
->purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
&&
321 victim
->timestamp_created
<= introcirc_cutoff
&&
322 victim
->timestamp_created
> general_cutoff
)
323 log_info(LD_REND
|LD_CIRC
, "Timing out introduction circuit which we "
324 "would not have done if it had been a general circuit.");
326 if (victim
->purpose
>= CIRCUIT_PURPOSE_C_INTRODUCING
&&
327 victim
->purpose
<= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
) {
328 if (!victim
->timestamp_dirty
)
329 log_fn(LOG_DEBUG
,"Considering %sopen purpose %d to %s (circid %d)."
331 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
332 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
335 log_fn(LOG_DEBUG
,"Considering %sopen purpose %d to %s (circid %d). "
336 "%d secs since dirty.",
337 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
338 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
340 (int)(now
- victim
->timestamp_dirty
));
344 /* if circ is !open, or if it's open but purpose is a non-finished
345 * intro or rend, then mark it for close */
346 if (victim
->state
== CIRCUIT_STATE_OPEN
) {
347 switch (victim
->purpose
) {
348 default: /* most open circuits can be left alone. */
349 continue; /* yes, continue inside a switch refers to the nearest
350 * enclosing loop. C is smart. */
351 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
352 case CIRCUIT_PURPOSE_C_INTRODUCING
:
353 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
354 break; /* too old, need to die */
355 case CIRCUIT_PURPOSE_C_REND_READY
:
356 /* it's a rend_ready circ -- has it already picked a query? */
357 /* c_rend_ready circs measure age since timestamp_dirty,
358 * because that's set when they switch purposes
360 if (TO_ORIGIN_CIRCUIT(victim
)->rend_data
||
361 victim
->timestamp_dirty
> cutoff
)
364 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
365 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
366 /* rend and intro circs become dirty each time they
367 * make an introduction attempt. so timestamp_dirty
368 * will reflect the time since the last attempt.
370 if (victim
->timestamp_dirty
> cutoff
)
374 } else { /* circuit not open, consider recording failure as timeout */
375 int first_hop_succeeded
= TO_ORIGIN_CIRCUIT(victim
)->cpath
&&
376 TO_ORIGIN_CIRCUIT(victim
)->cpath
->state
== CPATH_STATE_OPEN
;
378 if (TO_ORIGIN_CIRCUIT(victim
)->p_streams
!= NULL
) {
379 log_warn(LD_BUG
, "Circuit %d (purpose %d) has timed out, "
380 "yet has attached streams!",
381 TO_ORIGIN_CIRCUIT(victim
)->global_identifier
,
383 tor_fragile_assert();
387 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim
)) &&
388 circuit_build_times_enough_to_compute(&circ_times
)) {
389 /* Circuits are allowed to last longer for measurement.
390 * Switch their purpose and wait. */
391 if (victim
->purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
392 control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim
),
394 END_CIRC_REASON_TIMEOUT
);
395 victim
->purpose
= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
;
396 /* Record this failure to check for too many timeouts
397 * in a row. This function does not record a time value yet
398 * (we do that later); it only counts the fact that we did
400 circuit_build_times_count_timeout(&circ_times
,
401 first_hop_succeeded
);
406 * If the circuit build time is much greater than we would have cut
407 * it off at, we probably had a suspend event along this codepath,
408 * and we should discard the value.
410 if (now
- victim
->timestamp_created
> 2*circ_times
.close_ms
/1000+1) {
412 "Extremely large value for circuit build timeout: %lds. "
413 "Assuming clock jump. Purpose %d",
414 (long)(now
- victim
->timestamp_created
),
416 } else if (circuit_build_times_count_close(&circ_times
,
418 victim
->timestamp_created
)) {
419 circuit_build_times_set_timeout(&circ_times
);
425 log_info(LD_CIRC
,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
426 victim
->n_conn
->_base
.address
, victim
->n_conn
->_base
.port
,
428 victim
->state
, circuit_state_to_string(victim
->state
),
431 log_info(LD_CIRC
,"Abandoning circ %d (state %d:%s, purpose %d)",
432 victim
->n_circ_id
, victim
->state
,
433 circuit_state_to_string(victim
->state
), victim
->purpose
);
435 circuit_log_path(LOG_INFO
,LD_CIRC
,TO_ORIGIN_CIRCUIT(victim
));
436 if (victim
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
)
437 circuit_mark_for_close(victim
, END_CIRC_REASON_MEASUREMENT_EXPIRED
);
439 circuit_mark_for_close(victim
, END_CIRC_REASON_TIMEOUT
);
443 /** Remove any elements in <b>needed_ports</b> that are handled by an
444 * open or in-progress circuit.
447 circuit_remove_handled_ports(smartlist_t
*needed_ports
)
452 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
453 port
= smartlist_get(needed_ports
, i
);
455 if (circuit_stream_is_being_handled(NULL
, *port
,
456 MIN_CIRCUITS_HANDLING_STREAM
)) {
457 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
458 smartlist_del(needed_ports
, i
--);
461 log_debug(LD_CIRC
,"Port %d is not handled.", *port
);
466 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
467 * will have an acceptable exit node for exit stream <b>conn</b> if it
468 * is defined, else for "*:port".
472 circuit_stream_is_being_handled(edge_connection_t
*conn
,
473 uint16_t port
, int min
)
476 routerinfo_t
*exitrouter
;
478 time_t now
= time(NULL
);
479 int need_uptime
= smartlist_string_num_isin(get_options()->LongLivedPorts
,
480 conn
? conn
->socks_request
->port
: port
);
482 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
483 if (CIRCUIT_IS_ORIGIN(circ
) &&
484 !circ
->marked_for_close
&&
485 circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
&&
486 (!circ
->timestamp_dirty
||
487 circ
->timestamp_dirty
+ get_options()->MaxCircuitDirtiness
> now
)) {
488 cpath_build_state_t
*build_state
= TO_ORIGIN_CIRCUIT(circ
)->build_state
;
489 if (build_state
->is_internal
|| build_state
->onehop_tunnel
)
492 exitrouter
= build_state_get_exit_router(build_state
);
493 if (exitrouter
&& (!need_uptime
|| build_state
->need_uptime
)) {
496 ok
= connection_ap_can_use_exit(conn
, exitrouter
, 0);
498 addr_policy_result_t r
= compare_addr_to_addr_policy(
499 0, port
, exitrouter
->exit_policy
);
500 ok
= r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
;
512 /** Don't keep more than this many unused open circuits around. */
513 #define MAX_UNUSED_OPEN_CIRCUITS 14
515 /** Figure out how many circuits we have open that are clean. Make
516 * sure it's enough for all the upcoming behaviors we predict we'll have.
517 * But put an upper bound on the total number of circuits.
520 circuit_predict_and_launch_new(void)
523 int num
=0, num_internal
=0, num_uptime_internal
=0;
524 int hidserv_needs_uptime
=0, hidserv_needs_capacity
=1;
525 int port_needs_uptime
=0, port_needs_capacity
=1;
526 time_t now
= time(NULL
);
529 /* First, count how many of each type of circuit we have already. */
530 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
531 cpath_build_state_t
*build_state
;
532 if (!CIRCUIT_IS_ORIGIN(circ
))
534 if (circ
->marked_for_close
)
535 continue; /* don't mess with marked circs */
536 if (circ
->timestamp_dirty
)
537 continue; /* only count clean circs */
538 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
539 continue; /* only pay attention to general-purpose circs */
540 build_state
= TO_ORIGIN_CIRCUIT(circ
)->build_state
;
541 if (build_state
->onehop_tunnel
)
544 if (build_state
->is_internal
)
546 if (build_state
->need_uptime
&& build_state
->is_internal
)
547 num_uptime_internal
++;
550 /* If that's enough, then stop now. */
551 if (num
>= MAX_UNUSED_OPEN_CIRCUITS
)
552 return; /* we already have many, making more probably will hurt */
554 /* Second, see if we need any more exit circuits. */
555 /* check if we know of a port that's been requested recently
556 * and no circuit is currently available that can handle it. */
557 if (!circuit_all_predicted_ports_handled(now
, &port_needs_uptime
,
558 &port_needs_capacity
)) {
559 if (port_needs_uptime
)
560 flags
|= CIRCLAUNCH_NEED_UPTIME
;
561 if (port_needs_capacity
)
562 flags
|= CIRCLAUNCH_NEED_CAPACITY
;
564 "Have %d clean circs (%d internal), need another exit circ.",
566 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
, flags
);
570 /* Third, see if we need any more hidden service (server) circuits. */
571 if (num_rend_services() && num_uptime_internal
< 3) {
572 flags
= (CIRCLAUNCH_NEED_CAPACITY
| CIRCLAUNCH_NEED_UPTIME
|
573 CIRCLAUNCH_IS_INTERNAL
);
575 "Have %d clean circs (%d internal), need another internal "
576 "circ for my hidden service.",
578 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
, flags
);
582 /* Fourth, see if we need any more hidden service (client) circuits. */
583 if (rep_hist_get_predicted_internal(now
, &hidserv_needs_uptime
,
584 &hidserv_needs_capacity
) &&
585 ((num_uptime_internal
<2 && hidserv_needs_uptime
) ||
587 if (hidserv_needs_uptime
)
588 flags
|= CIRCLAUNCH_NEED_UPTIME
;
589 if (hidserv_needs_capacity
)
590 flags
|= CIRCLAUNCH_NEED_CAPACITY
;
591 flags
|= CIRCLAUNCH_IS_INTERNAL
;
593 "Have %d clean circs (%d uptime-internal, %d internal), need"
594 " another hidden service circ.",
595 num
, num_uptime_internal
, num_internal
);
596 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
, flags
);
600 /* Finally, check to see if we still need more circuits to learn
601 * a good build timeout. But if we're close to our max number we
602 * want, don't do another -- we want to leave a few slots open so
603 * we can still build circuits preemptively as needed. */
604 if (num
< MAX_UNUSED_OPEN_CIRCUITS
-2 &&
605 circuit_build_times_needs_circuits_now(&circ_times
)) {
606 flags
= CIRCLAUNCH_NEED_CAPACITY
;
608 "Have %d clean circs need another buildtime test circ.", num
);
609 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
, flags
);
614 /** Build a new test circuit every 5 minutes */
615 #define TESTING_CIRCUIT_INTERVAL 300
617 /** This function is called once a second, if router_have_min_dir_info() is
618 * true. Its job is to make sure all services we offer have enough circuits
619 * available. Some services just want enough circuits for current tasks,
620 * whereas others want a minimum set of idle circuits hanging around.
623 circuit_build_needed_circs(time_t now
)
625 static time_t time_to_new_circuit
= 0;
626 or_options_t
*options
= get_options();
628 /* launch a new circ for any pending streams that need one */
629 connection_ap_attach_pending();
631 /* make sure any hidden services have enough intro points */
632 rend_services_introduce();
634 if (time_to_new_circuit
< now
) {
635 circuit_reset_failure_count(1);
636 time_to_new_circuit
= now
+ options
->NewCircuitPeriod
;
637 if (proxy_mode(get_options()))
638 addressmap_clean(now
);
639 circuit_expire_old_circuits_clientside(now
);
641 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
642 circ
= circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL
);
643 if (get_options()->RunTesting
&&
645 circ
->timestamp_created
+ TESTING_CIRCUIT_INTERVAL
< now
) {
646 log_fn(LOG_INFO
,"Creating a new testing circuit.");
647 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
, 0);
651 if (!options
->DisablePredictedCircuits
)
652 circuit_predict_and_launch_new();
655 /** If the stream <b>conn</b> is a member of any of the linked
656 * lists of <b>circ</b>, then remove it from the list.
659 circuit_detach_stream(circuit_t
*circ
, edge_connection_t
*conn
)
661 edge_connection_t
*prevconn
;
666 conn
->cpath_layer
= NULL
; /* make sure we don't keep a stale pointer */
667 conn
->on_circuit
= NULL
;
669 if (CIRCUIT_IS_ORIGIN(circ
)) {
670 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
671 if (conn
== origin_circ
->p_streams
) {
672 origin_circ
->p_streams
= conn
->next_stream
;
676 for (prevconn
= origin_circ
->p_streams
;
677 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
678 prevconn
= prevconn
->next_stream
)
680 if (prevconn
&& prevconn
->next_stream
) {
681 prevconn
->next_stream
= conn
->next_stream
;
685 or_circuit_t
*or_circ
= TO_OR_CIRCUIT(circ
);
686 if (conn
== or_circ
->n_streams
) {
687 or_circ
->n_streams
= conn
->next_stream
;
690 if (conn
== or_circ
->resolving_streams
) {
691 or_circ
->resolving_streams
= conn
->next_stream
;
695 for (prevconn
= or_circ
->n_streams
;
696 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
697 prevconn
= prevconn
->next_stream
)
699 if (prevconn
&& prevconn
->next_stream
) {
700 prevconn
->next_stream
= conn
->next_stream
;
704 for (prevconn
= or_circ
->resolving_streams
;
705 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
706 prevconn
= prevconn
->next_stream
)
708 if (prevconn
&& prevconn
->next_stream
) {
709 prevconn
->next_stream
= conn
->next_stream
;
714 log_warn(LD_BUG
,"Edge connection not in circuit's list.");
715 /* Don't give an error here; it's harmless. */
716 tor_fragile_assert();
719 /** If we haven't yet decided on a good timeout value for circuit
720 * building, we close idles circuits aggressively so we can get more
722 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
724 /** Find each circuit that has been unused for too long, or dirty
725 * for too long and has no streams on it: mark it for close.
728 circuit_expire_old_circuits_clientside(time_t now
)
733 if (circuit_build_times_needs_circuits(&circ_times
)) {
734 /* Circuits should be shorter lived if we need more of them
735 * for learning a good build timeout */
736 cutoff
= now
- IDLE_TIMEOUT_WHILE_LEARNING
;
738 cutoff
= now
- get_options()->CircuitIdleTimeout
;
741 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
742 if (circ
->marked_for_close
|| !CIRCUIT_IS_ORIGIN(circ
))
744 /* If the circuit has been dirty for too long, and there are no streams
745 * on it, mark it for close.
747 if (circ
->timestamp_dirty
&&
748 circ
->timestamp_dirty
+ get_options()->MaxCircuitDirtiness
< now
&&
749 !TO_ORIGIN_CIRCUIT(circ
)->p_streams
/* nothing attached */ ) {
750 log_debug(LD_CIRC
, "Closing n_circ_id %d (dirty %d secs ago, "
752 circ
->n_circ_id
, (int)(now
- circ
->timestamp_dirty
),
754 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
755 } else if (!circ
->timestamp_dirty
&& circ
->state
== CIRCUIT_STATE_OPEN
) {
756 if (circ
->timestamp_created
< cutoff
) {
757 if (circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
758 circ
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
||
759 circ
->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
760 circ
->purpose
== CIRCUIT_PURPOSE_TESTING
||
761 (circ
->purpose
>= CIRCUIT_PURPOSE_C_INTRODUCING
&&
762 circ
->purpose
<= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
) ||
763 circ
->purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
) {
765 "Closing circuit that has been unused for %ld seconds.",
766 (long)(now
- circ
->timestamp_created
));
767 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
768 } else if (!TO_ORIGIN_CIRCUIT(circ
)->is_ancient
) {
769 /* Server-side rend joined circuits can end up really old, because
770 * they are reused by clients for longer than normal. The client
771 * controls their lifespan. (They never become dirty, because
772 * connection_exit_begin_conn() never marks anything as dirty.)
773 * Similarly, server-side intro circuits last a long time. */
774 if (circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
&&
775 circ
->purpose
!= CIRCUIT_PURPOSE_S_INTRO
) {
777 "Ancient non-dirty circuit %d is still around after "
778 "%ld seconds. Purpose: %d",
779 TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
780 (long)(now
- circ
->timestamp_created
),
782 /* FFFF implement a new circuit_purpose_to_string() so we don't
783 * just print out a number for circ->purpose */
784 TO_ORIGIN_CIRCUIT(circ
)->is_ancient
= 1;
792 /** How long do we wait before killing circuits with the properties
795 * Probably we could choose a number here as low as 5 to 10 seconds,
796 * since these circs are used for begindir, and a) generally you either
797 * ask another begindir question right after or you don't for a long time,
798 * b) clients at least through 0.2.1.x choose from the whole set of
799 * directory mirrors at each choice, and c) re-establishing a one-hop
800 * circuit via create-fast is a light operation assuming the TLS conn is
803 * I expect "b" to go away one day when we move to using directory
804 * guards, but I think "a" and "c" are good enough reasons that a low
805 * number is safe even then.
807 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
809 /** Find each non-origin circuit that has been unused for too long,
810 * has no streams on it, used a create_fast, and ends here: mark it
814 circuit_expire_old_circuits_serverside(time_t now
)
817 or_circuit_t
*or_circ
;
818 time_t cutoff
= now
- IDLE_ONE_HOP_CIRC_TIMEOUT
;
820 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
821 if (circ
->marked_for_close
|| CIRCUIT_IS_ORIGIN(circ
))
823 or_circ
= TO_OR_CIRCUIT(circ
);
824 /* If the circuit has been idle for too long, and there are no streams
825 * on it, and it ends here, and it used a create_fast, mark it for close.
827 if (or_circ
->is_first_hop
&& !circ
->n_conn
&&
828 !or_circ
->n_streams
&& !or_circ
->resolving_streams
&&
830 or_circ
->p_conn
->timestamp_last_added_nonpadding
<= cutoff
) {
831 log_info(LD_CIRC
, "Closing circ_id %d (empty %d secs ago)",
833 (int)(now
- or_circ
->p_conn
->timestamp_last_added_nonpadding
));
834 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
839 /** Number of testing circuits we want open before testing our bandwidth. */
840 #define NUM_PARALLEL_TESTING_CIRCS 4
842 /** True iff we've ever had enough testing circuits open to test our
844 static int have_performed_bandwidth_test
= 0;
846 /** Reset have_performed_bandwidth_test, so we'll start building
847 * testing circuits again so we can exercise our bandwidth. */
849 reset_bandwidth_test(void)
851 have_performed_bandwidth_test
= 0;
854 /** Return 1 if we've already exercised our bandwidth, or if we
855 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
856 * established or on the way. Else return 0.
859 circuit_enough_testing_circs(void)
864 if (have_performed_bandwidth_test
)
867 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
868 if (!circ
->marked_for_close
&& CIRCUIT_IS_ORIGIN(circ
) &&
869 circ
->purpose
== CIRCUIT_PURPOSE_TESTING
&&
870 circ
->state
== CIRCUIT_STATE_OPEN
)
873 return num
>= NUM_PARALLEL_TESTING_CIRCS
;
876 /** A testing circuit has completed. Take whatever stats we want.
877 * Noticing reachability is taken care of in onionskin_answer(),
878 * so there's no need to record anything here. But if we still want
879 * to do the bandwidth test, and we now have enough testing circuits
883 circuit_testing_opened(origin_circuit_t
*circ
)
885 if (have_performed_bandwidth_test
||
886 !check_whether_orport_reachable()) {
887 /* either we've already done everything we want with testing circuits,
888 * or this testing circuit became open due to a fluke, e.g. we picked
889 * a last hop where we already had the connection open due to an
890 * outgoing local circuit. */
891 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_AT_ORIGIN
);
892 } else if (circuit_enough_testing_circs()) {
893 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS
, time(NULL
));
894 have_performed_bandwidth_test
= 1;
896 consider_testing_reachability(1, 0);
899 /** A testing circuit has failed to build. Take whatever stats we want. */
901 circuit_testing_failed(origin_circuit_t
*circ
, int at_last_hop
)
903 if (server_mode(get_options()) && check_whether_orport_reachable())
907 "Our testing circuit (to see if your ORPort is reachable) "
908 "has failed. I'll try again later.");
910 /* These aren't used yet. */
915 /** The circuit <b>circ</b> has just become open. Take the next
916 * step: for rendezvous circuits, we pass circ to the appropriate
917 * function in rendclient or rendservice. For general circuits, we
918 * call connection_ap_attach_pending, which looks for pending streams
919 * that could use circ.
922 circuit_has_opened(origin_circuit_t
*circ
)
924 control_event_circuit_status(circ
, CIRC_EVENT_BUILT
, 0);
926 /* Remember that this circuit has finished building. Now if we start
927 * it building again later (e.g. by extending it), we will know not
928 * to consider its build time. */
929 circ
->has_opened
= 1;
931 switch (TO_CIRCUIT(circ
)->purpose
) {
932 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
933 rend_client_rendcirc_has_opened(circ
);
934 connection_ap_attach_pending();
936 case CIRCUIT_PURPOSE_C_INTRODUCING
:
937 rend_client_introcirc_has_opened(circ
);
939 case CIRCUIT_PURPOSE_C_GENERAL
:
940 /* Tell any AP connections that have been waiting for a new
941 * circuit that one is ready. */
942 connection_ap_attach_pending();
944 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
945 /* at Bob, waiting for introductions */
946 rend_service_intro_has_opened(circ
);
948 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
949 /* at Bob, connecting to rend point */
950 rend_service_rendezvous_has_opened(circ
);
952 case CIRCUIT_PURPOSE_TESTING
:
953 circuit_testing_opened(circ
);
956 * This won't happen in normal operation, but might happen if the
957 * controller did it. Just let it slide. */
961 /** Called whenever a circuit could not be successfully built.
964 circuit_build_failed(origin_circuit_t
*circ
)
966 /* we should examine circ and see if it failed because of
967 * the last hop or an earlier hop. then use this info below.
969 int failed_at_last_hop
= 0;
970 /* If the last hop isn't open, and the second-to-last is, we failed
971 * at the last hop. */
973 circ
->cpath
->prev
->state
!= CPATH_STATE_OPEN
&&
974 circ
->cpath
->prev
->prev
->state
== CPATH_STATE_OPEN
) {
975 failed_at_last_hop
= 1;
978 circ
->cpath
->state
!= CPATH_STATE_OPEN
) {
979 /* We failed at the first hop. If there's an OR connection
980 * to blame, blame it. Also, avoid this relay for a while, and
981 * fail any one-hop directory fetches destined for it. */
982 const char *n_conn_id
= circ
->cpath
->extend_info
->identity_digest
;
983 if (circ
->_base
.n_conn
) {
984 or_connection_t
*n_conn
= circ
->_base
.n_conn
;
986 "Our circuit failed to get a response from the first hop "
987 "(%s:%d). I'm going to try to rotate to a better connection.",
988 n_conn
->_base
.address
, n_conn
->_base
.port
);
989 n_conn
->is_bad_for_new_circs
= 1;
992 "Our circuit died before the first hop with no connection");
995 entry_guard_register_connect_status(n_conn_id
, 0, 1, time(NULL
));
996 /* if there are any one-hop streams waiting on this circuit, fail
997 * them now so they can retry elsewhere. */
998 connection_ap_fail_onehop(n_conn_id
, circ
->build_state
);
1002 switch (circ
->_base
.purpose
) {
1003 case CIRCUIT_PURPOSE_C_GENERAL
:
1004 /* If we never built the circuit, note it as a failure. */
1005 circuit_increment_failure_count();
1006 if (failed_at_last_hop
) {
1007 /* Make sure any streams that demand our last hop as their exit
1008 * know that it's unlikely to happen. */
1009 circuit_discard_optional_exit_enclaves(circ
->cpath
->prev
->extend_info
);
1012 case CIRCUIT_PURPOSE_TESTING
:
1013 circuit_testing_failed(circ
, failed_at_last_hop
);
1015 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1016 /* at Bob, waiting for introductions */
1017 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
) {
1018 circuit_increment_failure_count();
1020 /* no need to care here, because bob will rebuild intro
1021 * points periodically. */
1023 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1024 /* at Alice, connecting to intro point */
1025 /* Don't increment failure count, since Bob may have picked
1026 * the introduction point maliciously */
1027 /* Alice will pick a new intro point when this one dies, if
1028 * the stream in question still cares. No need to act here. */
1030 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1031 /* at Alice, waiting for Bob */
1032 circuit_increment_failure_count();
1033 /* Alice will pick a new rend point when this one dies, if
1034 * the stream in question still cares. No need to act here. */
1036 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1037 /* at Bob, connecting to rend point */
1038 /* Don't increment failure count, since Alice may have picked
1039 * the rendezvous point maliciously */
1041 "Couldn't connect to Alice's chosen rend point %s "
1043 escaped(build_state_get_exit_nickname(circ
->build_state
)),
1044 failed_at_last_hop
?"last":"non-last");
1045 rend_service_relaunch_rendezvous(circ
);
1048 * This won't happen in normal operation, but might happen if the
1049 * controller did it. Just let it slide. */
1053 /** Number of consecutive failures so far; should only be touched by
1054 * circuit_launch_new and circuit_*_failure_count.
1056 static int n_circuit_failures
= 0;
1057 /** Before the last time we called circuit_reset_failure_count(), were
1058 * there a lot of failures? */
1059 static int did_circs_fail_last_period
= 0;
1061 /** Don't retry launching a new circuit if we try this many times with no
1063 #define MAX_CIRCUIT_FAILURES 5
1065 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1066 * details on arguments. */
1068 circuit_launch_by_router(uint8_t purpose
,
1069 routerinfo_t
*exit
, int flags
)
1071 origin_circuit_t
*circ
;
1072 extend_info_t
*info
= NULL
;
1074 info
= extend_info_from_router(exit
);
1075 circ
= circuit_launch_by_extend_info(purpose
, info
, flags
);
1077 extend_info_free(info
);
1081 /** Launch a new circuit with purpose <b>purpose</b> and exit node
1082 * <b>extend_info</b> (or NULL to select a random exit node). If flags
1083 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
1084 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
1085 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
1086 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
1087 * Return the newly allocated circuit on success, or NULL on failure. */
1089 circuit_launch_by_extend_info(uint8_t purpose
,
1090 extend_info_t
*extend_info
,
1093 origin_circuit_t
*circ
;
1094 int onehop_tunnel
= (flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) != 0;
1096 if (!onehop_tunnel
&& !router_have_minimum_dir_info()) {
1097 log_debug(LD_CIRC
,"Haven't fetched enough directory info yet; canceling "
1102 if ((extend_info
|| purpose
!= CIRCUIT_PURPOSE_C_GENERAL
) &&
1103 purpose
!= CIRCUIT_PURPOSE_TESTING
&& !onehop_tunnel
) {
1104 /* see if there are appropriate circs available to cannibalize. */
1105 /* XXX if we're planning to add a hop, perhaps we want to look for
1106 * internal circs rather than exit circs? -RD */
1107 circ
= circuit_find_to_cannibalize(purpose
, extend_info
, flags
);
1109 log_info(LD_CIRC
,"Cannibalizing circ '%s' for purpose %d",
1110 build_state_get_exit_nickname(circ
->build_state
), purpose
);
1111 circ
->_base
.purpose
= purpose
;
1112 /* reset the birth date of this circ, else expire_building
1113 * will see it and think it's been trying to build since it
1115 circ
->_base
.timestamp_created
= time(NULL
);
1117 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1118 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1119 /* it's ready right now */
1121 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1122 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1123 case CIRCUIT_PURPOSE_C_GENERAL
:
1124 /* need to add a new hop */
1125 tor_assert(extend_info
);
1126 if (circuit_extend_to_new_exit(circ
, extend_info
) < 0)
1131 "unexpected purpose %d when cannibalizing a circ.",
1133 tor_fragile_assert();
1140 if (did_circs_fail_last_period
&&
1141 n_circuit_failures
> MAX_CIRCUIT_FAILURES
) {
1142 /* too many failed circs in a row. don't try. */
1143 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1147 /* try a circ. if it fails, circuit_mark_for_close will increment
1148 * n_circuit_failures */
1149 return circuit_establish_circuit(purpose
, extend_info
, flags
);
1152 /** Record another failure at opening a general circuit. When we have
1153 * too many, we'll stop trying for the remainder of this minute.
1156 circuit_increment_failure_count(void)
1158 ++n_circuit_failures
;
1159 log_debug(LD_CIRC
,"n_circuit_failures now %d.",n_circuit_failures
);
1162 /** Reset the failure count for opening general circuits. This means
1163 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1167 circuit_reset_failure_count(int timeout
)
1169 if (timeout
&& n_circuit_failures
> MAX_CIRCUIT_FAILURES
)
1170 did_circs_fail_last_period
= 1;
1172 did_circs_fail_last_period
= 0;
1173 n_circuit_failures
= 0;
1176 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1177 * there isn't one, and there isn't one on the way, launch one and return
1178 * 0. If it will never work, return -1.
1180 * Write the found or in-progress or launched circ into *circp.
1183 circuit_get_open_circ_or_launch(edge_connection_t
*conn
,
1184 uint8_t desired_circuit_purpose
,
1185 origin_circuit_t
**circp
)
1187 origin_circuit_t
*circ
;
1188 int check_exit_policy
;
1189 int need_uptime
, need_internal
;
1191 or_options_t
*options
= get_options();
1195 tor_assert(conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1197 conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
&&
1198 !conn
->use_begindir
&&
1199 !connection_edge_is_rendezvous_stream(conn
);
1200 want_onehop
= conn
->want_onehop
;
1202 need_uptime
= !conn
->want_onehop
&& !conn
->use_begindir
&&
1203 smartlist_string_num_isin(options
->LongLivedPorts
,
1204 conn
->socks_request
->port
);
1205 need_internal
= desired_circuit_purpose
!= CIRCUIT_PURPOSE_C_GENERAL
;
1207 circ
= circuit_get_best(conn
, 1, desired_circuit_purpose
,
1208 need_uptime
, need_internal
);
1212 return 1; /* we're happy */
1215 if (!want_onehop
&& !router_have_minimum_dir_info()) {
1216 if (!connection_get_by_type(CONN_TYPE_DIR
)) {
1217 int severity
= LOG_NOTICE
;
1218 /* FFFF if this is a tunneled directory fetch, don't yell
1219 * as loudly. the user doesn't even know it's happening. */
1220 if (options
->UseBridges
&& bridges_known_but_down()) {
1221 log_fn(severity
, LD_APP
|LD_DIR
,
1222 "Application request when we haven't used client functionality "
1223 "lately. Optimistically trying known bridges again.");
1224 bridges_retry_all();
1225 } else if (!options
->UseBridges
|| any_bridge_descriptors_known()) {
1226 log_fn(severity
, LD_APP
|LD_DIR
,
1227 "Application request when we haven't used client functionality "
1228 "lately. Optimistically trying directory fetches again.");
1229 routerlist_retry_directory_downloads(time(NULL
));
1232 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1233 * 1, or when all directory attempts fail and directory_all_unreachable()
1239 /* Do we need to check exit policy? */
1240 if (check_exit_policy
) {
1241 if (!conn
->chosen_exit_name
) {
1244 if (tor_inet_aton(conn
->socks_request
->address
, &in
))
1245 addr
= ntohl(in
.s_addr
);
1246 if (router_exit_policy_all_routers_reject(addr
,
1247 conn
->socks_request
->port
,
1250 "No Tor server allows exit to %s:%d. Rejecting.",
1251 safe_str_client(conn
->socks_request
->address
),
1252 conn
->socks_request
->port
);
1256 /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
1257 routerinfo_t
*router
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1258 int opt
= conn
->chosen_exit_optional
;
1259 if (router
&& !connection_ap_can_use_exit(conn
, router
, 0)) {
1260 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1261 "Requested exit point '%s' would refuse request. %s.",
1262 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1264 conn
->chosen_exit_optional
= 0;
1265 tor_free(conn
->chosen_exit_name
);
1267 return circuit_get_open_circ_or_launch(conn
,
1268 desired_circuit_purpose
,
1276 /* is one already on the way? */
1277 circ
= circuit_get_best(conn
, 0, desired_circuit_purpose
,
1278 need_uptime
, need_internal
);
1280 log_debug(LD_CIRC
, "one on the way!");
1282 extend_info_t
*extend_info
=NULL
;
1283 uint8_t new_circ_purpose
;
1285 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
) {
1286 /* need to pick an intro point */
1287 tor_assert(conn
->rend_data
);
1288 extend_info
= rend_client_get_random_intro(conn
->rend_data
);
1291 "No intro points for '%s': re-fetching service descriptor.",
1292 safe_str_client(conn
->rend_data
->onion_address
));
1293 rend_client_refetch_v2_renddesc(conn
->rend_data
);
1294 conn
->_base
.state
= AP_CONN_STATE_RENDDESC_WAIT
;
1297 log_info(LD_REND
,"Chose '%s' as intro point for '%s'.",
1298 extend_info
->nickname
,
1299 safe_str_client(conn
->rend_data
->onion_address
));
1302 /* If we have specified a particular exit node for our
1303 * connection, then be sure to open a circuit to that exit node.
1305 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
1306 if (conn
->chosen_exit_name
) {
1308 int opt
= conn
->chosen_exit_optional
;
1309 r
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1311 extend_info
= extend_info_from_router(r
);
1313 log_debug(LD_DIR
, "considering %d, %s",
1314 want_onehop
, conn
->chosen_exit_name
);
1315 if (want_onehop
&& conn
->chosen_exit_name
[0] == '$') {
1316 /* We're asking for a one-hop circuit to a router that
1317 * we don't have a routerinfo about. Make up an extend_info. */
1318 char digest
[DIGEST_LEN
];
1319 char *hexdigest
= conn
->chosen_exit_name
+1;
1321 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
1322 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
)<0) {
1323 log_info(LD_DIR
, "Broken exit digest on tunnel conn. Closing.");
1326 if (tor_addr_from_str(&addr
, conn
->socks_request
->address
) < 0) {
1327 log_info(LD_DIR
, "Broken address %s on tunnel conn. Closing.",
1328 escaped_safe_str_client(conn
->socks_request
->address
));
1331 extend_info
= extend_info_alloc(conn
->chosen_exit_name
+1,
1332 digest
, NULL
, &addr
,
1333 conn
->socks_request
->port
);
1335 /* We will need an onion key for the router, and we
1336 * don't have one. Refuse or relax requirements. */
1337 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1338 "Requested exit point '%s' is not known. %s.",
1339 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1341 conn
->chosen_exit_optional
= 0;
1342 tor_free(conn
->chosen_exit_name
);
1343 /* Try again with no requested exit */
1344 return circuit_get_open_circ_or_launch(conn
,
1345 desired_circuit_purpose
,
1354 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
)
1355 new_circ_purpose
= CIRCUIT_PURPOSE_C_ESTABLISH_REND
;
1356 else if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
1357 new_circ_purpose
= CIRCUIT_PURPOSE_C_INTRODUCING
;
1359 new_circ_purpose
= desired_circuit_purpose
;
1362 int flags
= CIRCLAUNCH_NEED_CAPACITY
;
1363 if (want_onehop
) flags
|= CIRCLAUNCH_ONEHOP_TUNNEL
;
1364 if (need_uptime
) flags
|= CIRCLAUNCH_NEED_UPTIME
;
1365 if (need_internal
) flags
|= CIRCLAUNCH_IS_INTERNAL
;
1366 circ
= circuit_launch_by_extend_info(new_circ_purpose
, extend_info
,
1370 extend_info_free(extend_info
);
1372 if (desired_circuit_purpose
!= CIRCUIT_PURPOSE_C_GENERAL
) {
1373 /* help predict this next time */
1374 rep_hist_note_used_internal(time(NULL
), need_uptime
, 1);
1376 /* write the service_id into circ */
1377 circ
->rend_data
= rend_data_dup(conn
->rend_data
);
1378 if (circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
&&
1379 circ
->_base
.state
== CIRCUIT_STATE_OPEN
)
1380 rend_client_rendcirc_has_opened(circ
);
1386 "No safe circuit (purpose %d) ready for edge "
1387 "connection; delaying.",
1388 desired_circuit_purpose
);
1393 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1396 cpath_is_on_circuit(origin_circuit_t
*circ
, crypt_path_t
*crypt_path
)
1398 crypt_path_t
*cpath
, *cpath_next
= NULL
;
1399 for (cpath
= circ
->cpath
; cpath_next
!= circ
->cpath
; cpath
= cpath_next
) {
1400 cpath_next
= cpath
->next
;
1401 if (crypt_path
== cpath
)
1407 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1408 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1409 * hop in circ's cpath if <b>cpath</b> is NULL.
1412 link_apconn_to_circ(edge_connection_t
*apconn
, origin_circuit_t
*circ
,
1413 crypt_path_t
*cpath
)
1415 /* add it into the linked list of streams on this circuit */
1416 log_debug(LD_APP
|LD_CIRC
, "attaching new conn to circ. n_circ_id %d.",
1417 circ
->_base
.n_circ_id
);
1418 /* reset it, so we can measure circ timeouts */
1419 apconn
->_base
.timestamp_lastread
= time(NULL
);
1420 apconn
->next_stream
= circ
->p_streams
;
1421 apconn
->on_circuit
= TO_CIRCUIT(circ
);
1422 /* assert_connection_ok(conn, time(NULL)); */
1423 circ
->p_streams
= apconn
;
1425 if (cpath
) { /* we were given one; use it */
1426 tor_assert(cpath_is_on_circuit(circ
, cpath
));
1427 apconn
->cpath_layer
= cpath
;
1428 } else { /* use the last hop in the circuit */
1429 tor_assert(circ
->cpath
);
1430 tor_assert(circ
->cpath
->prev
);
1431 tor_assert(circ
->cpath
->prev
->state
== CPATH_STATE_OPEN
);
1432 apconn
->cpath_layer
= circ
->cpath
->prev
;
1436 /** If an exit wasn't specifically chosen, save the history for future
1439 consider_recording_trackhost(edge_connection_t
*conn
, origin_circuit_t
*circ
)
1441 int found_needle
= 0;
1442 or_options_t
*options
= get_options();
1445 char fp
[HEX_DIGEST_LEN
+1];
1447 /* Search the addressmap for this conn's destination. */
1448 /* If he's not in the address map.. */
1449 if (!options
->TrackHostExits
||
1450 addressmap_have_mapping(conn
->socks_request
->address
,
1451 options
->TrackHostExitsExpire
))
1452 return; /* nothing to track, or already mapped */
1454 SMARTLIST_FOREACH(options
->TrackHostExits
, const char *, cp
, {
1455 if (cp
[0] == '.') { /* match end */
1456 if (cp
[1] == '\0' ||
1457 !strcasecmpend(conn
->socks_request
->address
, cp
) ||
1458 !strcasecmp(conn
->socks_request
->address
, &cp
[1]))
1460 } else if (strcasecmp(cp
, conn
->socks_request
->address
) == 0) {
1465 if (!found_needle
|| !circ
->build_state
->chosen_exit
)
1468 /* write down the fingerprint of the chosen exit, not the nickname,
1469 * because the chosen exit might not be named. */
1470 base16_encode(fp
, sizeof(fp
),
1471 circ
->build_state
->chosen_exit
->identity_digest
, DIGEST_LEN
);
1473 /* Add this exit/hostname pair to the addressmap. */
1474 len
= strlen(conn
->socks_request
->address
) + 1 /* '.' */ +
1475 strlen(fp
) + 1 /* '.' */ +
1476 strlen("exit") + 1 /* '\0' */;
1477 new_address
= tor_malloc(len
);
1479 tor_snprintf(new_address
, len
, "%s.%s.exit",
1480 conn
->socks_request
->address
, fp
);
1482 addressmap_register(conn
->socks_request
->address
, new_address
,
1483 time(NULL
) + options
->TrackHostExitsExpire
,
1484 ADDRMAPSRC_TRACKEXIT
);
1487 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1488 * begin or resolve cell as appropriate. Return values are as for
1489 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1490 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1491 * <b>cpath</b> is NULL. */
1493 connection_ap_handshake_attach_chosen_circuit(edge_connection_t
*conn
,
1494 origin_circuit_t
*circ
,
1495 crypt_path_t
*cpath
)
1498 tor_assert(conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
||
1499 conn
->_base
.state
== AP_CONN_STATE_CONTROLLER_WAIT
);
1500 tor_assert(conn
->socks_request
);
1502 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_OPEN
);
1504 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1506 if (!circ
->_base
.timestamp_dirty
)
1507 circ
->_base
.timestamp_dirty
= time(NULL
);
1509 link_apconn_to_circ(conn
, circ
, cpath
);
1510 tor_assert(conn
->socks_request
);
1511 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
1512 if (!conn
->use_begindir
)
1513 consider_recording_trackhost(conn
, circ
);
1514 if (connection_ap_handshake_send_begin(conn
) < 0)
1517 if (connection_ap_handshake_send_resolve(conn
) < 0)
1524 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1525 * we don't find one: if conn cannot be handled by any known nodes,
1526 * warn and return -1 (conn needs to die, and is maybe already marked);
1527 * else launch new circuit (if necessary) and return 0.
1528 * Otherwise, associate conn with a safe live circuit, do the
1529 * right next step, and return 1.
1531 /* XXXX this function should mark for close whenever it returns -1;
1532 * its callers shouldn't have to worry about that. */
1534 connection_ap_handshake_attach_circuit(edge_connection_t
*conn
)
1541 tor_assert(conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1542 tor_assert(conn
->socks_request
);
1543 want_onehop
= conn
->want_onehop
;
1545 conn_age
= (int)(time(NULL
) - conn
->_base
.timestamp_created
);
1547 if (conn_age
>= get_options()->SocksTimeout
) {
1548 int severity
= (tor_addr_is_null(&conn
->_base
.addr
) && !conn
->_base
.port
) ?
1549 LOG_INFO
: LOG_NOTICE
;
1550 log_fn(severity
, LD_APP
,
1551 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1552 conn_age
, safe_str_client(conn
->socks_request
->address
),
1553 conn
->socks_request
->port
);
1557 if (!connection_edge_is_rendezvous_stream(conn
)) { /* we're a general conn */
1558 origin_circuit_t
*circ
=NULL
;
1560 if (conn
->chosen_exit_name
) {
1561 routerinfo_t
*router
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1562 int opt
= conn
->chosen_exit_optional
;
1563 if (!router
&& !want_onehop
) {
1564 /* We ran into this warning when trying to extend a circuit to a
1565 * hidden service directory for which we didn't have a router
1566 * descriptor. See flyspray task 767 for more details. We should
1567 * keep this in mind when deciding to use BEGIN_DIR cells for other
1568 * directory requests as well. -KL*/
1569 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1570 "Requested exit point '%s' is not known. %s.",
1571 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1573 conn
->chosen_exit_optional
= 0;
1574 tor_free(conn
->chosen_exit_name
);
1579 if (router
&& !connection_ap_can_use_exit(conn
, router
, 0)) {
1580 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1581 "Requested exit point '%s' would refuse request. %s.",
1582 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1584 conn
->chosen_exit_optional
= 0;
1585 tor_free(conn
->chosen_exit_name
);
1592 /* find the circuit that we should use, if there is one. */
1593 retval
= circuit_get_open_circ_or_launch(
1594 conn
, CIRCUIT_PURPOSE_C_GENERAL
, &circ
);
1595 if (retval
< 1) // XXX021 if we totally fail, this still returns 0 -RD
1598 log_debug(LD_APP
|LD_CIRC
,
1599 "Attaching apconn to circ %d (stream %d sec old).",
1600 circ
->_base
.n_circ_id
, conn_age
);
1601 /* print the circ's path, so people can figure out which circs are
1603 circuit_log_path(LOG_INFO
,LD_APP
|LD_CIRC
,circ
);
1605 /* We have found a suitable circuit for our conn. Hurray. */
1606 return connection_ap_handshake_attach_chosen_circuit(conn
, circ
, NULL
);
1608 } else { /* we're a rendezvous conn */
1609 origin_circuit_t
*rendcirc
=NULL
, *introcirc
=NULL
;
1611 tor_assert(!conn
->cpath_layer
);
1613 /* start by finding a rendezvous circuit for us */
1615 retval
= circuit_get_open_circ_or_launch(
1616 conn
, CIRCUIT_PURPOSE_C_REND_JOINED
, &rendcirc
);
1617 if (retval
< 0) return -1; /* failed */
1620 tor_assert(rendcirc
);
1621 /* one is already established, attach */
1623 "rend joined circ %d already here. attaching. "
1624 "(stream %d sec old)",
1625 rendcirc
->_base
.n_circ_id
, conn_age
);
1626 /* Mark rendezvous circuits as 'newly dirty' every time you use
1627 * them, since the process of rebuilding a rendezvous circ is so
1628 * expensive. There is a tradeoff between linkability and
1629 * feasibility, at this point.
1631 rendcirc
->_base
.timestamp_dirty
= time(NULL
);
1632 link_apconn_to_circ(conn
, rendcirc
, NULL
);
1633 if (connection_ap_handshake_send_begin(conn
) < 0)
1634 return 0; /* already marked, let them fade away */
1638 if (rendcirc
&& (rendcirc
->_base
.purpose
==
1639 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
)) {
1641 "pending-join circ %d already here, with intro ack. "
1642 "Stalling. (stream %d sec old)",
1643 rendcirc
->_base
.n_circ_id
, conn_age
);
1647 /* it's on its way. find an intro circ. */
1648 retval
= circuit_get_open_circ_or_launch(
1649 conn
, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
, &introcirc
);
1650 if (retval
< 0) return -1; /* failed */
1653 /* one has already sent the intro. keep waiting. */
1654 circuit_t
*c
= NULL
;
1655 tor_assert(introcirc
);
1656 log_info(LD_REND
, "Intro circ %d present and awaiting ack (rend %d). "
1657 "Stalling. (stream %d sec old)",
1658 introcirc
->_base
.n_circ_id
,
1659 rendcirc
? rendcirc
->_base
.n_circ_id
: 0,
1661 /* abort parallel intro circs, if any */
1662 for (c
= global_circuitlist
; c
; c
= c
->next
) {
1663 if (c
->purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
&&
1664 !c
->marked_for_close
&& CIRCUIT_IS_ORIGIN(c
)) {
1665 origin_circuit_t
*oc
= TO_ORIGIN_CIRCUIT(c
);
1666 if (oc
->rend_data
&&
1667 !rend_cmp_service_ids(conn
->rend_data
->onion_address
,
1668 oc
->rend_data
->onion_address
)) {
1669 log_info(LD_REND
|LD_CIRC
, "Closing introduction circuit that we "
1670 "built in parallel.");
1671 circuit_mark_for_close(c
, END_CIRC_REASON_TIMEOUT
);
1678 /* now rendcirc and introcirc are each either undefined or not finished */
1680 if (rendcirc
&& introcirc
&&
1681 rendcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_REND_READY
) {
1683 "ready rend circ %d already here (no intro-ack yet on "
1684 "intro %d). (stream %d sec old)",
1685 rendcirc
->_base
.n_circ_id
,
1686 introcirc
->_base
.n_circ_id
, conn_age
);
1688 tor_assert(introcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
1689 if (introcirc
->_base
.state
== CIRCUIT_STATE_OPEN
) {
1690 log_info(LD_REND
,"found open intro circ %d (rend %d); sending "
1691 "introduction. (stream %d sec old)",
1692 introcirc
->_base
.n_circ_id
, rendcirc
->_base
.n_circ_id
,
1694 if (rend_client_send_introduction(introcirc
, rendcirc
) < 0) {
1697 rendcirc
->_base
.timestamp_dirty
= time(NULL
);
1698 introcirc
->_base
.timestamp_dirty
= time(NULL
);
1699 assert_circuit_ok(TO_CIRCUIT(rendcirc
));
1700 assert_circuit_ok(TO_CIRCUIT(introcirc
));
1705 log_info(LD_REND
, "Intro (%d) and rend (%d) circs are not both ready. "
1706 "Stalling conn. (%d sec old)",
1707 introcirc
? introcirc
->_base
.n_circ_id
: 0,
1708 rendcirc
? rendcirc
->_base
.n_circ_id
: 0, conn_age
);