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-2012, 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 "networkstatus.h"
23 #include "rendclient.h"
24 #include "rendcommon.h"
25 #include "rendservice.h"
28 #include "routerlist.h"
30 /********* START VARIABLES **********/
32 extern circuit_t
*global_circuitlist
; /* from circuitlist.c */
34 /********* END VARIABLES ************/
36 static void circuit_expire_old_circuits_clientside(void);
37 static void circuit_increment_failure_count(void);
39 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
43 circuit_is_acceptable(const origin_circuit_t
*origin_circ
,
44 const entry_connection_t
*conn
,
45 int must_be_open
, uint8_t purpose
,
46 int need_uptime
, int need_internal
,
49 const circuit_t
*circ
= TO_CIRCUIT(origin_circ
);
50 const node_t
*exitnode
;
51 cpath_build_state_t
*build_state
;
54 tor_assert(conn
->socks_request
);
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
)
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
)
68 } else if (purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
&&
70 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCING
&&
71 circ
->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
74 if (purpose
!= circ
->purpose
)
78 /* If this is a timed-out hidden service circuit, skip it. */
79 if (origin_circ
->hs_circ_has_timed_out
) {
83 if (purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
84 purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
)
85 if (circ
->timestamp_dirty
&&
86 circ
->timestamp_dirty
+get_options()->MaxCircuitDirtiness
<= now
)
89 /* decide if this circ is suitable for this conn */
91 /* for rend circs, circ->cpath->prev is not the last router in the
92 * circuit, it's the magical extra bob hop. so just check the nickname
93 * of the one we meant to finish at.
95 build_state
= origin_circ
->build_state
;
96 exitnode
= build_state_get_exit_node(build_state
);
98 if (need_uptime
&& !build_state
->need_uptime
)
100 if (need_internal
!= build_state
->is_internal
)
103 if (purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
104 if (!exitnode
&& !build_state
->onehop_tunnel
) {
105 log_debug(LD_CIRC
,"Not considering circuit with unknown router.");
106 return 0; /* this circuit is screwed and doesn't know it yet,
107 * or is a rendezvous circuit. */
109 if (build_state
->onehop_tunnel
) {
110 if (!conn
->want_onehop
) {
111 log_debug(LD_CIRC
,"Skipping one-hop circuit.");
114 tor_assert(conn
->chosen_exit_name
);
115 if (build_state
->chosen_exit
) {
116 char digest
[DIGEST_LEN
];
117 if (hexdigest_to_digest(conn
->chosen_exit_name
, digest
) < 0)
118 return 0; /* broken digest, we don't want it */
119 if (tor_memneq(digest
, build_state
->chosen_exit
->identity_digest
,
121 return 0; /* this is a circuit to somewhere else */
122 if (tor_digest_is_zero(digest
)) {
123 /* we don't know the digest; have to compare addr:port */
125 int r
= tor_addr_parse(&addr
, conn
->socks_request
->address
);
127 !tor_addr_eq(&build_state
->chosen_exit
->addr
, &addr
) ||
128 build_state
->chosen_exit
->port
!= conn
->socks_request
->port
)
133 if (conn
->want_onehop
) {
134 /* don't use three-hop circuits -- that could hurt our anonymity. */
138 if (exitnode
&& !connection_ap_can_use_exit(conn
, exitnode
)) {
139 /* can't exit from this router */
142 } else { /* not general */
143 const edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
144 if ((edge_conn
->rend_data
&& !origin_circ
->rend_data
) ||
145 (!edge_conn
->rend_data
&& origin_circ
->rend_data
) ||
146 (edge_conn
->rend_data
&& origin_circ
->rend_data
&&
147 rend_cmp_service_ids(edge_conn
->rend_data
->onion_address
,
148 origin_circ
->rend_data
->onion_address
))) {
149 /* this circ is not for this conn */
154 if (!connection_edge_compatible_with_circuit(conn
, origin_circ
)) {
155 /* conn needs to be isolated from other conns that have already used
163 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
164 * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
167 circuit_is_better(const origin_circuit_t
*oa
, const origin_circuit_t
*ob
,
168 const entry_connection_t
*conn
)
170 const circuit_t
*a
= TO_CIRCUIT(oa
);
171 const circuit_t
*b
= TO_CIRCUIT(ob
);
172 const uint8_t purpose
= ENTRY_TO_CONN(conn
)->purpose
;
176 case CIRCUIT_PURPOSE_C_GENERAL
:
177 /* if it's used but less dirty it's best;
178 * else if it's more recently created it's best
180 if (b
->timestamp_dirty
) {
181 if (a
->timestamp_dirty
&&
182 a
->timestamp_dirty
> b
->timestamp_dirty
)
185 if (a
->timestamp_dirty
||
186 timercmp(&a
->timestamp_created
, &b
->timestamp_created
, >))
188 if (ob
->build_state
->is_internal
)
189 /* XXX023 what the heck is this internal thing doing here. I
190 * think we can get rid of it. circuit_is_acceptable() already
191 * makes sure that is_internal is exactly what we need it to
196 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
197 /* the closer it is to ack_wait the better it is */
198 if (a
->purpose
> b
->purpose
)
201 case CIRCUIT_PURPOSE_C_REND_JOINED
:
202 /* the closer it is to rend_joined the better it is */
203 if (a
->purpose
> b
->purpose
)
208 /* XXXX023 Maybe this check should get a higher priority to avoid
209 * using up circuits too rapidly. */
211 a_bits
= connection_edge_update_circuit_isolation(conn
,
212 (origin_circuit_t
*)oa
, 1);
213 b_bits
= connection_edge_update_circuit_isolation(conn
,
214 (origin_circuit_t
*)ob
, 1);
215 /* if x_bits < 0, then we have not used x for anything; better not to dirty
216 * a connection if we can help it. */
219 } else if (b_bits
< 0) {
222 a_bits
&= ~ oa
->isolation_flags_mixed
;
223 a_bits
&= ~ ob
->isolation_flags_mixed
;
224 if (n_bits_set_u8(a_bits
) < n_bits_set_u8(b_bits
)) {
225 /* The fewer new restrictions we need to make on a circuit for stream
226 * isolation, the better. */
233 /** Find the best circ that conn can use, preferably one which is
234 * dirty. Circ must not be too old.
236 * Conn must be defined.
238 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
240 * circ_purpose specifies what sort of circuit we must have.
241 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
243 * If it's REND_JOINED and must_be_open==0, then return the closest
244 * rendezvous-purposed circuit that you can find.
246 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
247 * closest introduce-purposed circuit that you can find.
249 static origin_circuit_t
*
250 circuit_get_best(const entry_connection_t
*conn
,
251 int must_be_open
, uint8_t purpose
,
252 int need_uptime
, int need_internal
)
255 origin_circuit_t
*best
=NULL
;
257 int intro_going_on_but_too_old
= 0;
261 tor_assert(purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
262 purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
||
263 purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
);
265 tor_gettimeofday(&now
);
267 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
268 origin_circuit_t
*origin_circ
;
269 if (!CIRCUIT_IS_ORIGIN(circ
))
271 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
272 if (!circuit_is_acceptable(origin_circ
,conn
,must_be_open
,purpose
,
273 need_uptime
,need_internal
,now
.tv_sec
))
276 if (purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
&&
277 !must_be_open
&& circ
->state
!= CIRCUIT_STATE_OPEN
&&
278 tv_mdiff(&now
, &circ
->timestamp_created
) > circ_times
.timeout_ms
) {
279 intro_going_on_but_too_old
= 1;
283 /* now this is an acceptable circ to hand back. but that doesn't
284 * mean it's the *best* circ to hand back. try to decide.
286 if (!best
|| circuit_is_better(origin_circ
,best
,conn
))
290 if (!best
&& intro_going_on_but_too_old
)
291 log_info(LD_REND
|LD_CIRC
, "There is an intro circuit being created "
292 "right now, but it has already taken quite a while. Starting "
298 /** Return the number of not-yet-open general-purpose origin circuits. */
300 count_pending_general_client_circuits(void)
302 const circuit_t
*circ
;
306 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
307 if (circ
->marked_for_close
||
308 circ
->state
== CIRCUIT_STATE_OPEN
||
309 circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
||
310 !CIRCUIT_IS_ORIGIN(circ
))
320 /** Check whether, according to the policies in <b>options</b>, the
321 * circuit <b>circ</b> makes sense. */
322 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
323 * Also, it doesn't have the right definition of an exit circuit. Also,
324 * it's never called. */
326 circuit_conforms_to_options(const origin_circuit_t
*circ
,
327 const or_options_t
*options
)
329 const crypt_path_t
*cpath
, *cpath_next
= NULL
;
331 /* first check if it includes any excluded nodes */
332 for (cpath
= circ
->cpath
; cpath_next
!= circ
->cpath
; cpath
= cpath_next
) {
333 cpath_next
= cpath
->next
;
334 if (routerset_contains_extendinfo(options
->ExcludeNodes
,
339 /* then consider the final hop */
340 if (routerset_contains_extendinfo(options
->ExcludeExitNodes
,
341 circ
->cpath
->prev
->extend_info
))
348 /** Close all circuits that start at us, aren't open, and were born
349 * at least CircuitBuildTimeout seconds ago.
352 circuit_expire_building(void)
354 circuit_t
*victim
, *next_circ
= global_circuitlist
;
355 /* circ_times.timeout_ms and circ_times.close_ms are from
356 * circuit_build_times_get_initial_timeout() if we haven't computed
357 * custom timeouts yet */
358 struct timeval general_cutoff
, begindir_cutoff
, fourhop_cutoff
,
359 cannibalize_cutoff
, close_cutoff
, extremely_old_cutoff
,
360 hs_extremely_old_cutoff
;
361 const or_options_t
*options
= get_options();
363 cpath_build_state_t
*build_state
;
365 tor_gettimeofday(&now
);
366 #define SET_CUTOFF(target, msec) do { \
367 long ms = tor_lround(msec); \
368 struct timeval diff; \
369 diff.tv_sec = ms / 1000; \
370 diff.tv_usec = (int)((ms % 1000) * 1000); \
371 timersub(&now, &diff, &target); \
374 SET_CUTOFF(general_cutoff
, circ_times
.timeout_ms
);
375 SET_CUTOFF(begindir_cutoff
, circ_times
.timeout_ms
);
376 SET_CUTOFF(fourhop_cutoff
, circ_times
.timeout_ms
* (4/3.0));
377 SET_CUTOFF(cannibalize_cutoff
, circ_times
.timeout_ms
/ 2.0);
378 SET_CUTOFF(close_cutoff
, circ_times
.close_ms
);
379 SET_CUTOFF(extremely_old_cutoff
, circ_times
.close_ms
*2 + 1000);
381 SET_CUTOFF(hs_extremely_old_cutoff
,
382 MAX(circ_times
.close_ms
*2 + 1000,
383 options
->SocksTimeout
* 1000));
386 struct timeval cutoff
;
388 next_circ
= next_circ
->next
;
389 if (!CIRCUIT_IS_ORIGIN(victim
) || /* didn't originate here */
390 victim
->marked_for_close
) /* don't mess with marked circs */
393 build_state
= TO_ORIGIN_CIRCUIT(victim
)->build_state
;
394 if (build_state
&& build_state
->onehop_tunnel
)
395 cutoff
= begindir_cutoff
;
396 else if (build_state
&& build_state
->desired_path_len
== 4
397 && !TO_ORIGIN_CIRCUIT(victim
)->has_opened
)
398 cutoff
= fourhop_cutoff
;
399 else if (TO_ORIGIN_CIRCUIT(victim
)->has_opened
)
400 cutoff
= cannibalize_cutoff
;
401 else if (victim
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
)
402 cutoff
= close_cutoff
;
404 cutoff
= general_cutoff
;
406 if (TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
)
407 cutoff
= hs_extremely_old_cutoff
;
409 if (timercmp(&victim
->timestamp_created
, &cutoff
, >))
410 continue; /* it's still young, leave it alone */
413 /* some debug logs, to help track bugs */
414 if (victim
->purpose
>= CIRCUIT_PURPOSE_C_INTRODUCING
&&
415 victim
->purpose
<= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
) {
416 if (!victim
->timestamp_dirty
)
417 log_fn(LOG_DEBUG
,"Considering %sopen purpose %d to %s (circid %d)."
419 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
420 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
423 log_fn(LOG_DEBUG
,"Considering %sopen purpose %d to %s (circid %d). "
424 "%d secs since dirty.",
425 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
426 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
428 (int)(now
- victim
->timestamp_dirty
));
432 /* if circ is !open, or if it's open but purpose is a non-finished
433 * intro or rend, then mark it for close */
434 if (victim
->state
== CIRCUIT_STATE_OPEN
) {
435 switch (victim
->purpose
) {
436 default: /* most open circuits can be left alone. */
437 continue; /* yes, continue inside a switch refers to the nearest
438 * enclosing loop. C is smart. */
439 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
440 case CIRCUIT_PURPOSE_C_INTRODUCING
:
441 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
442 break; /* too old, need to die */
443 case CIRCUIT_PURPOSE_C_REND_READY
:
444 /* it's a rend_ready circ -- has it already picked a query? */
445 /* c_rend_ready circs measure age since timestamp_dirty,
446 * because that's set when they switch purposes
448 if (TO_ORIGIN_CIRCUIT(victim
)->rend_data
||
449 victim
->timestamp_dirty
> cutoff
.tv_sec
)
452 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
453 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
454 /* rend and intro circs become dirty each time they
455 * make an introduction attempt. so timestamp_dirty
456 * will reflect the time since the last attempt.
458 if (victim
->timestamp_dirty
> cutoff
.tv_sec
)
462 } else { /* circuit not open, consider recording failure as timeout */
463 int first_hop_succeeded
= TO_ORIGIN_CIRCUIT(victim
)->cpath
&&
464 TO_ORIGIN_CIRCUIT(victim
)->cpath
->state
== CPATH_STATE_OPEN
;
466 if (TO_ORIGIN_CIRCUIT(victim
)->p_streams
!= NULL
) {
467 log_warn(LD_BUG
, "Circuit %d (purpose %d, %s) has timed out, "
468 "yet has attached streams!",
469 TO_ORIGIN_CIRCUIT(victim
)->global_identifier
,
471 circuit_purpose_to_string(victim
->purpose
));
472 tor_fragile_assert();
476 if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim
)) &&
477 circuit_build_times_enough_to_compute(&circ_times
)) {
478 /* Circuits are allowed to last longer for measurement.
479 * Switch their purpose and wait. */
480 if (victim
->purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
481 control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim
),
483 END_CIRC_REASON_TIMEOUT
);
484 circuit_change_purpose(victim
, CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
);
485 /* Record this failure to check for too many timeouts
486 * in a row. This function does not record a time value yet
487 * (we do that later); it only counts the fact that we did
489 circuit_build_times_count_timeout(&circ_times
,
490 first_hop_succeeded
);
495 * If the circuit build time is much greater than we would have cut
496 * it off at, we probably had a suspend event along this codepath,
497 * and we should discard the value.
499 if (timercmp(&victim
->timestamp_created
, &extremely_old_cutoff
, <)) {
501 "Extremely large value for circuit build timeout: %lds. "
502 "Assuming clock jump. Purpose %d (%s)",
503 (long)(now
.tv_sec
- victim
->timestamp_created
.tv_sec
),
505 circuit_purpose_to_string(victim
->purpose
));
506 } else if (circuit_build_times_count_close(&circ_times
,
508 victim
->timestamp_created
.tv_sec
)) {
509 circuit_build_times_set_timeout(&circ_times
);
514 /* If this is a hidden service client circuit which is far enough
515 * along in connecting to its destination, and we haven't already
516 * flagged it as 'timed out', and the user has not told us to
517 * close such circs immediately on timeout, flag it as 'timed out'
518 * so we'll launch another intro or rend circ, but don't mark it
521 * (Circs flagged as 'timed out' are given a much longer timeout
522 * period above, so we won't close them in the next call to
523 * circuit_expire_building.) */
524 if (!(options
->CloseHSClientCircuitsImmediatelyOnTimeout
) &&
525 !(TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
)) {
526 switch (victim
->purpose
) {
527 case CIRCUIT_PURPOSE_C_REND_READY
:
528 /* We only want to spare a rend circ if it has been specified in
529 * an INTRODUCE1 cell sent to a hidden service. A circ's
530 * pending_final_cpath field is non-NULL iff it is a rend circ
531 * and we have tried to send an INTRODUCE1 cell specifying it.
532 * Thus, if the pending_final_cpath field *is* NULL, then we
533 * want to not spare it. */
534 if (TO_ORIGIN_CIRCUIT(victim
)->build_state
->pending_final_cpath
==
537 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
538 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
539 /* If we have reached this line, we want to spare the circ for now. */
540 log_info(LD_CIRC
,"Marking circ %d (state %d:%s, purpose %d) "
541 "as timed-out HS circ",
543 victim
->state
, circuit_state_to_string(victim
->state
),
545 TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
= 1;
552 /* If this is a service-side rendezvous circuit which is far
553 * enough along in connecting to its destination, consider sparing
555 if (!(options
->CloseHSServiceRendCircuitsImmediatelyOnTimeout
) &&
556 !(TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
) &&
557 victim
->purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
) {
558 log_info(LD_CIRC
,"Marking circ %d (state %d:%s, purpose %d) "
559 "as timed-out HS circ; relaunching rendezvous attempt.",
561 victim
->state
, circuit_state_to_string(victim
->state
),
563 TO_ORIGIN_CIRCUIT(victim
)->hs_circ_has_timed_out
= 1;
564 rend_service_relaunch_rendezvous(TO_ORIGIN_CIRCUIT(victim
));
569 log_info(LD_CIRC
,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
570 victim
->n_conn
->_base
.address
, victim
->n_conn
->_base
.port
,
572 victim
->state
, circuit_state_to_string(victim
->state
),
575 log_info(LD_CIRC
,"Abandoning circ %d (state %d:%s, purpose %d)",
576 victim
->n_circ_id
, victim
->state
,
577 circuit_state_to_string(victim
->state
), victim
->purpose
);
579 circuit_log_path(LOG_INFO
,LD_CIRC
,TO_ORIGIN_CIRCUIT(victim
));
580 if (victim
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
)
581 circuit_mark_for_close(victim
, END_CIRC_REASON_MEASUREMENT_EXPIRED
);
583 circuit_mark_for_close(victim
, END_CIRC_REASON_TIMEOUT
);
587 /** Remove any elements in <b>needed_ports</b> that are handled by an
588 * open or in-progress circuit.
591 circuit_remove_handled_ports(smartlist_t
*needed_ports
)
596 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
597 port
= smartlist_get(needed_ports
, i
);
599 if (circuit_stream_is_being_handled(NULL
, *port
,
600 MIN_CIRCUITS_HANDLING_STREAM
)) {
601 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
602 smartlist_del(needed_ports
, i
--);
605 log_debug(LD_CIRC
,"Port %d is not handled.", *port
);
610 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
611 * will have an acceptable exit node for exit stream <b>conn</b> if it
612 * is defined, else for "*:port".
616 circuit_stream_is_being_handled(entry_connection_t
*conn
,
617 uint16_t port
, int min
)
620 const node_t
*exitnode
;
622 time_t now
= time(NULL
);
623 int need_uptime
= smartlist_string_num_isin(get_options()->LongLivedPorts
,
624 conn
? conn
->socks_request
->port
: port
);
626 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
627 if (CIRCUIT_IS_ORIGIN(circ
) &&
628 !circ
->marked_for_close
&&
629 circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
&&
630 (!circ
->timestamp_dirty
||
631 circ
->timestamp_dirty
+ get_options()->MaxCircuitDirtiness
> now
)) {
632 cpath_build_state_t
*build_state
= TO_ORIGIN_CIRCUIT(circ
)->build_state
;
633 if (build_state
->is_internal
|| build_state
->onehop_tunnel
)
636 exitnode
= build_state_get_exit_node(build_state
);
637 if (exitnode
&& (!need_uptime
|| build_state
->need_uptime
)) {
640 ok
= connection_ap_can_use_exit(conn
, exitnode
);
642 addr_policy_result_t r
;
643 r
= compare_tor_addr_to_node_policy(NULL
, port
, exitnode
);
644 ok
= r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
;
656 /** Don't keep more than this many unused open circuits around. */
657 #define MAX_UNUSED_OPEN_CIRCUITS 14
659 /** Figure out how many circuits we have open that are clean. Make
660 * sure it's enough for all the upcoming behaviors we predict we'll have.
661 * But put an upper bound on the total number of circuits.
664 circuit_predict_and_launch_new(void)
667 int num
=0, num_internal
=0, num_uptime_internal
=0;
668 int hidserv_needs_uptime
=0, hidserv_needs_capacity
=1;
669 int port_needs_uptime
=0, port_needs_capacity
=1;
670 time_t now
= time(NULL
);
673 /* First, count how many of each type of circuit we have already. */
674 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
675 cpath_build_state_t
*build_state
;
676 if (!CIRCUIT_IS_ORIGIN(circ
))
678 if (circ
->marked_for_close
)
679 continue; /* don't mess with marked circs */
680 if (circ
->timestamp_dirty
)
681 continue; /* only count clean circs */
682 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
683 continue; /* only pay attention to general-purpose circs */
684 build_state
= TO_ORIGIN_CIRCUIT(circ
)->build_state
;
685 if (build_state
->onehop_tunnel
)
688 if (build_state
->is_internal
)
690 if (build_state
->need_uptime
&& build_state
->is_internal
)
691 num_uptime_internal
++;
694 /* If that's enough, then stop now. */
695 if (num
>= MAX_UNUSED_OPEN_CIRCUITS
)
696 return; /* we already have many, making more probably will hurt */
698 /* Second, see if we need any more exit circuits. */
699 /* check if we know of a port that's been requested recently
700 * and no circuit is currently available that can handle it. */
701 if (!circuit_all_predicted_ports_handled(now
, &port_needs_uptime
,
702 &port_needs_capacity
)) {
703 if (port_needs_uptime
)
704 flags
|= CIRCLAUNCH_NEED_UPTIME
;
705 if (port_needs_capacity
)
706 flags
|= CIRCLAUNCH_NEED_CAPACITY
;
708 "Have %d clean circs (%d internal), need another exit circ.",
710 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, flags
);
714 /* Third, see if we need any more hidden service (server) circuits. */
715 if (num_rend_services() && num_uptime_internal
< 3) {
716 flags
= (CIRCLAUNCH_NEED_CAPACITY
| CIRCLAUNCH_NEED_UPTIME
|
717 CIRCLAUNCH_IS_INTERNAL
);
719 "Have %d clean circs (%d internal), need another internal "
720 "circ for my hidden service.",
722 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, flags
);
726 /* Fourth, see if we need any more hidden service (client) circuits. */
727 if (rep_hist_get_predicted_internal(now
, &hidserv_needs_uptime
,
728 &hidserv_needs_capacity
) &&
729 ((num_uptime_internal
<2 && hidserv_needs_uptime
) ||
731 if (hidserv_needs_uptime
)
732 flags
|= CIRCLAUNCH_NEED_UPTIME
;
733 if (hidserv_needs_capacity
)
734 flags
|= CIRCLAUNCH_NEED_CAPACITY
;
735 flags
|= CIRCLAUNCH_IS_INTERNAL
;
737 "Have %d clean circs (%d uptime-internal, %d internal), need"
738 " another hidden service circ.",
739 num
, num_uptime_internal
, num_internal
);
740 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, flags
);
744 /* Finally, check to see if we still need more circuits to learn
745 * a good build timeout. But if we're close to our max number we
746 * want, don't do another -- we want to leave a few slots open so
747 * we can still build circuits preemptively as needed. */
748 if (num
< MAX_UNUSED_OPEN_CIRCUITS
-2 &&
749 ! circuit_build_times_disabled() &&
750 circuit_build_times_needs_circuits_now(&circ_times
)) {
751 flags
= CIRCLAUNCH_NEED_CAPACITY
;
753 "Have %d clean circs need another buildtime test circ.", num
);
754 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, flags
);
759 /** Build a new test circuit every 5 minutes */
760 #define TESTING_CIRCUIT_INTERVAL 300
762 /** This function is called once a second, if router_have_min_dir_info() is
763 * true. Its job is to make sure all services we offer have enough circuits
764 * available. Some services just want enough circuits for current tasks,
765 * whereas others want a minimum set of idle circuits hanging around.
768 circuit_build_needed_circs(time_t now
)
770 static time_t time_to_new_circuit
= 0;
771 const or_options_t
*options
= get_options();
773 /* launch a new circ for any pending streams that need one */
774 connection_ap_attach_pending();
776 /* make sure any hidden services have enough intro points */
777 rend_services_introduce();
779 if (time_to_new_circuit
< now
) {
780 circuit_reset_failure_count(1);
781 time_to_new_circuit
= now
+ options
->NewCircuitPeriod
;
782 if (proxy_mode(get_options()))
783 addressmap_clean(now
);
784 circuit_expire_old_circuits_clientside();
786 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
787 circ
= circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL
);
788 if (get_options()->RunTesting
&&
790 circ
->timestamp_created
.tv_sec
+ TESTING_CIRCUIT_INTERVAL
< now
) {
791 log_fn(LOG_INFO
,"Creating a new testing circuit.");
792 circuit_launch(CIRCUIT_PURPOSE_C_GENERAL
, 0);
796 if (!options
->DisablePredictedCircuits
)
797 circuit_predict_and_launch_new();
800 /** If the stream <b>conn</b> is a member of any of the linked
801 * lists of <b>circ</b>, then remove it from the list.
804 circuit_detach_stream(circuit_t
*circ
, edge_connection_t
*conn
)
806 edge_connection_t
*prevconn
;
811 if (conn
->_base
.type
== CONN_TYPE_AP
) {
812 entry_connection_t
*entry_conn
= EDGE_TO_ENTRY_CONN(conn
);
813 entry_conn
->may_use_optimistic_data
= 0;
815 conn
->cpath_layer
= NULL
; /* don't keep a stale pointer */
816 conn
->on_circuit
= NULL
;
818 if (CIRCUIT_IS_ORIGIN(circ
)) {
819 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
820 if (conn
== origin_circ
->p_streams
) {
821 origin_circ
->p_streams
= conn
->next_stream
;
825 for (prevconn
= origin_circ
->p_streams
;
826 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
827 prevconn
= prevconn
->next_stream
)
829 if (prevconn
&& prevconn
->next_stream
) {
830 prevconn
->next_stream
= conn
->next_stream
;
834 or_circuit_t
*or_circ
= TO_OR_CIRCUIT(circ
);
835 if (conn
== or_circ
->n_streams
) {
836 or_circ
->n_streams
= conn
->next_stream
;
839 if (conn
== or_circ
->resolving_streams
) {
840 or_circ
->resolving_streams
= conn
->next_stream
;
844 for (prevconn
= or_circ
->n_streams
;
845 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
846 prevconn
= prevconn
->next_stream
)
848 if (prevconn
&& prevconn
->next_stream
) {
849 prevconn
->next_stream
= conn
->next_stream
;
853 for (prevconn
= or_circ
->resolving_streams
;
854 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
855 prevconn
= prevconn
->next_stream
)
857 if (prevconn
&& prevconn
->next_stream
) {
858 prevconn
->next_stream
= conn
->next_stream
;
863 log_warn(LD_BUG
,"Edge connection not in circuit's list.");
864 /* Don't give an error here; it's harmless. */
865 tor_fragile_assert();
868 /** If we haven't yet decided on a good timeout value for circuit
869 * building, we close idles circuits aggressively so we can get more
871 #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
873 /** Find each circuit that has been unused for too long, or dirty
874 * for too long and has no streams on it: mark it for close.
877 circuit_expire_old_circuits_clientside(void)
880 struct timeval cutoff
, now
;
882 tor_gettimeofday(&now
);
885 if (! circuit_build_times_disabled() &&
886 circuit_build_times_needs_circuits(&circ_times
)) {
887 /* Circuits should be shorter lived if we need more of them
888 * for learning a good build timeout */
889 cutoff
.tv_sec
-= IDLE_TIMEOUT_WHILE_LEARNING
;
891 cutoff
.tv_sec
-= get_options()->CircuitIdleTimeout
;
894 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
895 if (circ
->marked_for_close
|| !CIRCUIT_IS_ORIGIN(circ
))
897 /* If the circuit has been dirty for too long, and there are no streams
898 * on it, mark it for close.
900 if (circ
->timestamp_dirty
&&
901 circ
->timestamp_dirty
+ get_options()->MaxCircuitDirtiness
<
903 !TO_ORIGIN_CIRCUIT(circ
)->p_streams
/* nothing attached */ ) {
904 log_debug(LD_CIRC
, "Closing n_circ_id %d (dirty %ld sec ago, "
906 circ
->n_circ_id
, (long)(now
.tv_sec
- circ
->timestamp_dirty
),
908 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
909 } else if (!circ
->timestamp_dirty
&& circ
->state
== CIRCUIT_STATE_OPEN
) {
910 if (timercmp(&circ
->timestamp_created
, &cutoff
, <)) {
911 if (circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
912 circ
->purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
||
913 circ
->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
914 circ
->purpose
== CIRCUIT_PURPOSE_TESTING
||
915 (circ
->purpose
>= CIRCUIT_PURPOSE_C_INTRODUCING
&&
916 circ
->purpose
<= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
) ||
917 circ
->purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
) {
919 "Closing circuit that has been unused for %ld msec.",
920 tv_mdiff(&circ
->timestamp_created
, &now
));
921 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
922 } else if (!TO_ORIGIN_CIRCUIT(circ
)->is_ancient
) {
923 /* Server-side rend joined circuits can end up really old, because
924 * they are reused by clients for longer than normal. The client
925 * controls their lifespan. (They never become dirty, because
926 * connection_exit_begin_conn() never marks anything as dirty.)
927 * Similarly, server-side intro circuits last a long time. */
928 if (circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
&&
929 circ
->purpose
!= CIRCUIT_PURPOSE_S_INTRO
) {
931 "Ancient non-dirty circuit %d is still around after "
932 "%ld milliseconds. Purpose: %d (%s)",
933 TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
934 tv_mdiff(&circ
->timestamp_created
, &now
),
936 circuit_purpose_to_string(circ
->purpose
));
937 TO_ORIGIN_CIRCUIT(circ
)->is_ancient
= 1;
945 /** How long do we wait before killing circuits with the properties
948 * Probably we could choose a number here as low as 5 to 10 seconds,
949 * since these circs are used for begindir, and a) generally you either
950 * ask another begindir question right after or you don't for a long time,
951 * b) clients at least through 0.2.1.x choose from the whole set of
952 * directory mirrors at each choice, and c) re-establishing a one-hop
953 * circuit via create-fast is a light operation assuming the TLS conn is
956 * I expect "b" to go away one day when we move to using directory
957 * guards, but I think "a" and "c" are good enough reasons that a low
958 * number is safe even then.
960 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
962 /** Find each non-origin circuit that has been unused for too long,
963 * has no streams on it, used a create_fast, and ends here: mark it
967 circuit_expire_old_circuits_serverside(time_t now
)
970 or_circuit_t
*or_circ
;
971 time_t cutoff
= now
- IDLE_ONE_HOP_CIRC_TIMEOUT
;
973 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
974 if (circ
->marked_for_close
|| CIRCUIT_IS_ORIGIN(circ
))
976 or_circ
= TO_OR_CIRCUIT(circ
);
977 /* If the circuit has been idle for too long, and there are no streams
978 * on it, and it ends here, and it used a create_fast, mark it for close.
980 if (or_circ
->is_first_hop
&& !circ
->n_conn
&&
981 !or_circ
->n_streams
&& !or_circ
->resolving_streams
&&
983 or_circ
->p_conn
->timestamp_last_added_nonpadding
<= cutoff
) {
984 log_info(LD_CIRC
, "Closing circ_id %d (empty %d secs ago)",
986 (int)(now
- or_circ
->p_conn
->timestamp_last_added_nonpadding
));
987 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
992 /** Number of testing circuits we want open before testing our bandwidth. */
993 #define NUM_PARALLEL_TESTING_CIRCS 4
995 /** True iff we've ever had enough testing circuits open to test our
997 static int have_performed_bandwidth_test
= 0;
999 /** Reset have_performed_bandwidth_test, so we'll start building
1000 * testing circuits again so we can exercise our bandwidth. */
1002 reset_bandwidth_test(void)
1004 have_performed_bandwidth_test
= 0;
1007 /** Return 1 if we've already exercised our bandwidth, or if we
1008 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
1009 * established or on the way. Else return 0.
1012 circuit_enough_testing_circs(void)
1017 if (have_performed_bandwidth_test
)
1020 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
1021 if (!circ
->marked_for_close
&& CIRCUIT_IS_ORIGIN(circ
) &&
1022 circ
->purpose
== CIRCUIT_PURPOSE_TESTING
&&
1023 circ
->state
== CIRCUIT_STATE_OPEN
)
1026 return num
>= NUM_PARALLEL_TESTING_CIRCS
;
1029 /** A testing circuit has completed. Take whatever stats we want.
1030 * Noticing reachability is taken care of in onionskin_answer(),
1031 * so there's no need to record anything here. But if we still want
1032 * to do the bandwidth test, and we now have enough testing circuits
1036 circuit_testing_opened(origin_circuit_t
*circ
)
1038 if (have_performed_bandwidth_test
||
1039 !check_whether_orport_reachable()) {
1040 /* either we've already done everything we want with testing circuits,
1041 * or this testing circuit became open due to a fluke, e.g. we picked
1042 * a last hop where we already had the connection open due to an
1043 * outgoing local circuit. */
1044 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_AT_ORIGIN
);
1045 } else if (circuit_enough_testing_circs()) {
1046 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS
, time(NULL
));
1047 have_performed_bandwidth_test
= 1;
1049 consider_testing_reachability(1, 0);
1052 /** A testing circuit has failed to build. Take whatever stats we want. */
1054 circuit_testing_failed(origin_circuit_t
*circ
, int at_last_hop
)
1056 if (server_mode(get_options()) && check_whether_orport_reachable())
1059 log_info(LD_GENERAL
,
1060 "Our testing circuit (to see if your ORPort is reachable) "
1061 "has failed. I'll try again later.");
1063 /* These aren't used yet. */
1068 /** The circuit <b>circ</b> has just become open. Take the next
1069 * step: for rendezvous circuits, we pass circ to the appropriate
1070 * function in rendclient or rendservice. For general circuits, we
1071 * call connection_ap_attach_pending, which looks for pending streams
1072 * that could use circ.
1075 circuit_has_opened(origin_circuit_t
*circ
)
1077 control_event_circuit_status(circ
, CIRC_EVENT_BUILT
, 0);
1079 /* Remember that this circuit has finished building. Now if we start
1080 * it building again later (e.g. by extending it), we will know not
1081 * to consider its build time. */
1082 circ
->has_opened
= 1;
1084 switch (TO_CIRCUIT(circ
)->purpose
) {
1085 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1086 rend_client_rendcirc_has_opened(circ
);
1087 /* Start building an intro circ if we don't have one yet. */
1088 connection_ap_attach_pending();
1089 /* This isn't a call to circuit_try_attaching_streams because a
1090 * circuit in _C_ESTABLISH_REND state isn't connected to its
1091 * hidden service yet, thus we can't attach streams to it yet,
1092 * thus circuit_try_attaching_streams would always clear the
1093 * circuit's isolation state. circuit_try_attaching_streams is
1094 * called later, when the rend circ enters _C_REND_JOINED
1097 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1098 rend_client_introcirc_has_opened(circ
);
1100 case CIRCUIT_PURPOSE_C_GENERAL
:
1101 /* Tell any AP connections that have been waiting for a new
1102 * circuit that one is ready. */
1103 circuit_try_attaching_streams(circ
);
1105 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1106 /* at Bob, waiting for introductions */
1107 rend_service_intro_has_opened(circ
);
1109 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1110 /* at Bob, connecting to rend point */
1111 rend_service_rendezvous_has_opened(circ
);
1113 case CIRCUIT_PURPOSE_TESTING
:
1114 circuit_testing_opened(circ
);
1117 * This won't happen in normal operation, but might happen if the
1118 * controller did it. Just let it slide. */
1122 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
1123 * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
1125 circuit_try_clearing_isolation_state(origin_circuit_t
*circ
)
1127 if (/* The circuit may have become non-open if it was cannibalized.*/
1128 circ
->_base
.state
== CIRCUIT_STATE_OPEN
&&
1129 /* If !isolation_values_set, there is nothing to clear. */
1130 circ
->isolation_values_set
&&
1131 /* It's not legal to clear a circuit's isolation info if it's ever had
1132 * streams attached */
1133 !circ
->isolation_any_streams_attached
) {
1134 /* If we have any isolation information set on this circuit, and
1135 * we didn't manage to attach any streams to it, then we can
1136 * and should clear it and try again. */
1137 circuit_clear_isolation(circ
);
1144 /** Called when a circuit becomes ready for streams to be attached to
1147 circuit_try_attaching_streams(origin_circuit_t
*circ
)
1149 /* Attach streams to this circuit if we can. */
1150 connection_ap_attach_pending();
1152 /* The call to circuit_try_clearing_isolation_state here will do
1153 * nothing and return 0 if we didn't attach any streams to circ
1155 if (circuit_try_clearing_isolation_state(circ
)) {
1156 /* Maybe *now* we can attach some streams to this circuit. */
1157 connection_ap_attach_pending();
1161 /** Called whenever a circuit could not be successfully built.
1164 circuit_build_failed(origin_circuit_t
*circ
)
1166 /* we should examine circ and see if it failed because of
1167 * the last hop or an earlier hop. then use this info below.
1169 int failed_at_last_hop
= 0;
1170 /* If the last hop isn't open, and the second-to-last is, we failed
1171 * at the last hop. */
1173 circ
->cpath
->prev
->state
!= CPATH_STATE_OPEN
&&
1174 circ
->cpath
->prev
->prev
->state
== CPATH_STATE_OPEN
) {
1175 failed_at_last_hop
= 1;
1178 circ
->cpath
->state
!= CPATH_STATE_OPEN
) {
1179 /* We failed at the first hop. If there's an OR connection
1180 * to blame, blame it. Also, avoid this relay for a while, and
1181 * fail any one-hop directory fetches destined for it. */
1182 const char *n_conn_id
= circ
->cpath
->extend_info
->identity_digest
;
1183 int already_marked
= 0;
1184 if (circ
->_base
.n_conn
) {
1185 or_connection_t
*n_conn
= circ
->_base
.n_conn
;
1186 if (n_conn
->is_bad_for_new_circs
) {
1187 /* We only want to blame this router when a fresh healthy
1188 * connection fails. So don't mark this router as newly failed,
1189 * since maybe this was just an old circuit attempt that's
1190 * finally timing out now. Also, there's no need to blow away
1191 * circuits/streams/etc, since the failure of an unhealthy conn
1192 * doesn't tell us much about whether a healthy conn would
1197 "Our circuit failed to get a response from the first hop "
1198 "(%s:%d). I'm going to try to rotate to a better connection.",
1199 n_conn
->_base
.address
, n_conn
->_base
.port
);
1200 n_conn
->is_bad_for_new_circs
= 1;
1203 "Our circuit died before the first hop with no connection");
1205 if (n_conn_id
&& !already_marked
) {
1206 entry_guard_register_connect_status(n_conn_id
, 0, 1, time(NULL
));
1207 /* if there are any one-hop streams waiting on this circuit, fail
1208 * them now so they can retry elsewhere. */
1209 connection_ap_fail_onehop(n_conn_id
, circ
->build_state
);
1213 switch (circ
->_base
.purpose
) {
1214 case CIRCUIT_PURPOSE_C_GENERAL
:
1215 /* If we never built the circuit, note it as a failure. */
1216 circuit_increment_failure_count();
1217 if (failed_at_last_hop
) {
1218 /* Make sure any streams that demand our last hop as their exit
1219 * know that it's unlikely to happen. */
1220 circuit_discard_optional_exit_enclaves(circ
->cpath
->prev
->extend_info
);
1223 case CIRCUIT_PURPOSE_TESTING
:
1224 circuit_testing_failed(circ
, failed_at_last_hop
);
1226 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1227 /* at Bob, waiting for introductions */
1228 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
) {
1229 circuit_increment_failure_count();
1231 /* no need to care here, because bob will rebuild intro
1232 * points periodically. */
1234 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1235 /* at Alice, connecting to intro point */
1236 /* Don't increment failure count, since Bob may have picked
1237 * the introduction point maliciously */
1238 /* Alice will pick a new intro point when this one dies, if
1239 * the stream in question still cares. No need to act here. */
1241 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1242 /* at Alice, waiting for Bob */
1243 circuit_increment_failure_count();
1244 /* Alice will pick a new rend point when this one dies, if
1245 * the stream in question still cares. No need to act here. */
1247 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1248 /* at Bob, connecting to rend point */
1249 /* Don't increment failure count, since Alice may have picked
1250 * the rendezvous point maliciously */
1252 "Couldn't connect to Alice's chosen rend point %s "
1254 escaped(build_state_get_exit_nickname(circ
->build_state
)),
1255 failed_at_last_hop
?"last":"non-last");
1256 rend_service_relaunch_rendezvous(circ
);
1259 * This won't happen in normal operation, but might happen if the
1260 * controller did it. Just let it slide. */
1264 /** Number of consecutive failures so far; should only be touched by
1265 * circuit_launch_new and circuit_*_failure_count.
1267 static int n_circuit_failures
= 0;
1268 /** Before the last time we called circuit_reset_failure_count(), were
1269 * there a lot of failures? */
1270 static int did_circs_fail_last_period
= 0;
1272 /** Don't retry launching a new circuit if we try this many times with no
1274 #define MAX_CIRCUIT_FAILURES 5
1276 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1277 * details on arguments. */
1279 circuit_launch(uint8_t purpose
, int flags
)
1281 return circuit_launch_by_extend_info(purpose
, NULL
, flags
);
1284 /** Launch a new circuit with purpose <b>purpose</b> and exit node
1285 * <b>extend_info</b> (or NULL to select a random exit node). If flags
1286 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
1287 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
1288 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
1289 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
1290 * Return the newly allocated circuit on success, or NULL on failure. */
1292 circuit_launch_by_extend_info(uint8_t purpose
,
1293 extend_info_t
*extend_info
,
1296 origin_circuit_t
*circ
;
1297 int onehop_tunnel
= (flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) != 0;
1299 if (!onehop_tunnel
&& !router_have_minimum_dir_info()) {
1300 log_debug(LD_CIRC
,"Haven't fetched enough directory info yet; canceling "
1305 if ((extend_info
|| purpose
!= CIRCUIT_PURPOSE_C_GENERAL
) &&
1306 purpose
!= CIRCUIT_PURPOSE_TESTING
&& !onehop_tunnel
) {
1307 /* see if there are appropriate circs available to cannibalize. */
1308 /* XXX if we're planning to add a hop, perhaps we want to look for
1309 * internal circs rather than exit circs? -RD */
1310 circ
= circuit_find_to_cannibalize(purpose
, extend_info
, flags
);
1312 uint8_t old_purpose
= circ
->_base
.purpose
;
1313 struct timeval old_timestamp_created
= circ
->_base
.timestamp_created
;
1315 log_info(LD_CIRC
,"Cannibalizing circ '%s' for purpose %d (%s)",
1316 build_state_get_exit_nickname(circ
->build_state
), purpose
,
1317 circuit_purpose_to_string(purpose
));
1319 circuit_change_purpose(TO_CIRCUIT(circ
), purpose
);
1320 /* reset the birth date of this circ, else expire_building
1321 * will see it and think it's been trying to build since it
1323 tor_gettimeofday(&circ
->_base
.timestamp_created
);
1325 control_event_circuit_cannibalized(circ
, old_purpose
,
1326 &old_timestamp_created
);
1329 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1330 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1331 /* it's ready right now */
1333 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1334 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1335 case CIRCUIT_PURPOSE_C_GENERAL
:
1336 /* need to add a new hop */
1337 tor_assert(extend_info
);
1338 if (circuit_extend_to_new_exit(circ
, extend_info
) < 0)
1343 "unexpected purpose %d when cannibalizing a circ.",
1345 tor_fragile_assert();
1352 if (did_circs_fail_last_period
&&
1353 n_circuit_failures
> MAX_CIRCUIT_FAILURES
) {
1354 /* too many failed circs in a row. don't try. */
1355 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1359 /* try a circ. if it fails, circuit_mark_for_close will increment
1360 * n_circuit_failures */
1361 return circuit_establish_circuit(purpose
, extend_info
, flags
);
1364 /** Record another failure at opening a general circuit. When we have
1365 * too many, we'll stop trying for the remainder of this minute.
1368 circuit_increment_failure_count(void)
1370 ++n_circuit_failures
;
1371 log_debug(LD_CIRC
,"n_circuit_failures now %d.",n_circuit_failures
);
1374 /** Reset the failure count for opening general circuits. This means
1375 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1379 circuit_reset_failure_count(int timeout
)
1381 if (timeout
&& n_circuit_failures
> MAX_CIRCUIT_FAILURES
)
1382 did_circs_fail_last_period
= 1;
1384 did_circs_fail_last_period
= 0;
1385 n_circuit_failures
= 0;
1388 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1389 * there isn't one, and there isn't one on the way, launch one and return
1390 * 0. If it will never work, return -1.
1392 * Write the found or in-progress or launched circ into *circp.
1395 circuit_get_open_circ_or_launch(entry_connection_t
*conn
,
1396 uint8_t desired_circuit_purpose
,
1397 origin_circuit_t
**circp
)
1399 origin_circuit_t
*circ
;
1400 int check_exit_policy
;
1401 int need_uptime
, need_internal
;
1403 const or_options_t
*options
= get_options();
1407 tor_assert(ENTRY_TO_CONN(conn
)->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1409 conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
&&
1410 !conn
->use_begindir
&&
1411 !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn
));
1412 want_onehop
= conn
->want_onehop
;
1414 need_uptime
= !conn
->want_onehop
&& !conn
->use_begindir
&&
1415 smartlist_string_num_isin(options
->LongLivedPorts
,
1416 conn
->socks_request
->port
);
1418 if (desired_circuit_purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
1420 else if (conn
->use_begindir
|| conn
->want_onehop
)
1425 circ
= circuit_get_best(conn
, 1, desired_circuit_purpose
,
1426 need_uptime
, need_internal
);
1430 return 1; /* we're happy */
1433 if (!want_onehop
&& !router_have_minimum_dir_info()) {
1434 if (!connection_get_by_type(CONN_TYPE_DIR
)) {
1435 int severity
= LOG_NOTICE
;
1436 /* FFFF if this is a tunneled directory fetch, don't yell
1437 * as loudly. the user doesn't even know it's happening. */
1438 if (entry_list_is_constrained(options
) &&
1439 entries_known_but_down(options
)) {
1440 log_fn(severity
, LD_APP
|LD_DIR
,
1441 "Application request when we haven't used client functionality "
1442 "lately. Optimistically trying known %s again.",
1443 options
->UseBridges
? "bridges" : "entrynodes");
1444 entries_retry_all(options
);
1445 } else if (!options
->UseBridges
|| any_bridge_descriptors_known()) {
1446 log_fn(severity
, LD_APP
|LD_DIR
,
1447 "Application request when we haven't used client functionality "
1448 "lately. Optimistically trying directory fetches again.");
1449 routerlist_retry_directory_downloads(time(NULL
));
1452 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1453 * 1, or when all directory attempts fail and directory_all_unreachable()
1459 /* Do we need to check exit policy? */
1460 if (check_exit_policy
) {
1461 if (!conn
->chosen_exit_name
) {
1463 tor_addr_t addr
, *addrp
=NULL
;
1464 if (tor_inet_aton(conn
->socks_request
->address
, &in
)) {
1465 tor_addr_from_in(&addr
, &in
);
1468 if (router_exit_policy_all_nodes_reject(addrp
,
1469 conn
->socks_request
->port
,
1472 "No Tor server allows exit to %s:%d. Rejecting.",
1473 safe_str_client(conn
->socks_request
->address
),
1474 conn
->socks_request
->port
);
1478 /* XXXX024 Duplicates checks in connection_ap_handshake_attach_circuit:
1479 * refactor into a single function? */
1480 const node_t
*node
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1481 int opt
= conn
->chosen_exit_optional
;
1482 if (node
&& !connection_ap_can_use_exit(conn
, node
)) {
1483 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1484 "Requested exit point '%s' is excluded or "
1485 "would refuse request. %s.",
1486 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1488 conn
->chosen_exit_optional
= 0;
1489 tor_free(conn
->chosen_exit_name
);
1491 return circuit_get_open_circ_or_launch(conn
,
1492 desired_circuit_purpose
,
1500 /* is one already on the way? */
1501 circ
= circuit_get_best(conn
, 0, desired_circuit_purpose
,
1502 need_uptime
, need_internal
);
1504 log_debug(LD_CIRC
, "one on the way!");
1506 extend_info_t
*extend_info
=NULL
;
1507 uint8_t new_circ_purpose
;
1508 const int n_pending
= count_pending_general_client_circuits();
1510 if (n_pending
>= options
->MaxClientCircuitsPending
) {
1511 static ratelim_t delay_limit
= RATELIM_INIT(10*60);
1513 if ((m
= rate_limit_log(&delay_limit
, approx_time()))) {
1514 log_notice(LD_APP
, "We'd like to launch a circuit to handle a "
1515 "connection, but we already have %d general-purpose client "
1516 "circuits pending. Waiting until some finish.",
1523 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
) {
1524 /* need to pick an intro point */
1525 rend_data_t
*rend_data
= ENTRY_TO_EDGE_CONN(conn
)->rend_data
;
1526 tor_assert(rend_data
);
1527 extend_info
= rend_client_get_random_intro(rend_data
);
1530 "No intro points for '%s': re-fetching service descriptor.",
1531 safe_str_client(rend_data
->onion_address
));
1532 rend_client_refetch_v2_renddesc(rend_data
);
1533 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_RENDDESC_WAIT
;
1536 log_info(LD_REND
,"Chose %s as intro point for '%s'.",
1537 extend_info_describe(extend_info
),
1538 safe_str_client(rend_data
->onion_address
));
1541 /* If we have specified a particular exit node for our
1542 * connection, then be sure to open a circuit to that exit node.
1544 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
1545 if (conn
->chosen_exit_name
) {
1547 int opt
= conn
->chosen_exit_optional
;
1548 r
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1549 if (r
&& node_has_descriptor(r
)) {
1550 /* We might want to connect to an IPv6 bridge for loading
1551 descriptors so we use the preferred address rather than
1553 extend_info
= extend_info_from_node(r
, conn
->want_onehop
? 1 : 0);
1555 log_debug(LD_DIR
, "considering %d, %s",
1556 want_onehop
, conn
->chosen_exit_name
);
1557 if (want_onehop
&& conn
->chosen_exit_name
[0] == '$') {
1558 /* We're asking for a one-hop circuit to a router that
1559 * we don't have a routerinfo about. Make up an extend_info. */
1560 char digest
[DIGEST_LEN
];
1561 char *hexdigest
= conn
->chosen_exit_name
+1;
1563 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
1564 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
)<0) {
1565 log_info(LD_DIR
, "Broken exit digest on tunnel conn. Closing.");
1568 if (tor_addr_parse(&addr
, conn
->socks_request
->address
) < 0) {
1569 log_info(LD_DIR
, "Broken address %s on tunnel conn. Closing.",
1570 escaped_safe_str_client(conn
->socks_request
->address
));
1573 extend_info
= extend_info_alloc(conn
->chosen_exit_name
+1,
1574 digest
, NULL
, &addr
,
1575 conn
->socks_request
->port
);
1577 /* We will need an onion key for the router, and we
1578 * don't have one. Refuse or relax requirements. */
1579 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1580 "Requested exit point '%s' is not known. %s.",
1581 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1583 conn
->chosen_exit_optional
= 0;
1584 tor_free(conn
->chosen_exit_name
);
1585 /* Try again with no requested exit */
1586 return circuit_get_open_circ_or_launch(conn
,
1587 desired_circuit_purpose
,
1596 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
)
1597 new_circ_purpose
= CIRCUIT_PURPOSE_C_ESTABLISH_REND
;
1598 else if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
1599 new_circ_purpose
= CIRCUIT_PURPOSE_C_INTRODUCING
;
1601 new_circ_purpose
= desired_circuit_purpose
;
1603 if (options
->Tor2webMode
&&
1604 (new_circ_purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
||
1605 new_circ_purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
)) {
1610 int flags
= CIRCLAUNCH_NEED_CAPACITY
;
1611 if (want_onehop
) flags
|= CIRCLAUNCH_ONEHOP_TUNNEL
;
1612 if (need_uptime
) flags
|= CIRCLAUNCH_NEED_UPTIME
;
1613 if (need_internal
) flags
|= CIRCLAUNCH_IS_INTERNAL
;
1614 circ
= circuit_launch_by_extend_info(new_circ_purpose
, extend_info
,
1618 extend_info_free(extend_info
);
1620 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
1621 /* We just caused a circuit to get built because of this stream.
1622 * If this stream has caused a _lot_ of circuits to be built, that's
1623 * a bad sign: we should tell the user. */
1624 if (conn
->num_circuits_launched
< NUM_CIRCUITS_LAUNCHED_THRESHOLD
&&
1625 ++conn
->num_circuits_launched
== NUM_CIRCUITS_LAUNCHED_THRESHOLD
)
1626 log_info(LD_CIRC
, "The application request to %s:%d has launched "
1627 "%d circuits without finding one it likes.",
1628 escaped_safe_str_client(conn
->socks_request
->address
),
1629 conn
->socks_request
->port
,
1630 conn
->num_circuits_launched
);
1632 /* help predict this next time */
1633 rep_hist_note_used_internal(time(NULL
), need_uptime
, 1);
1635 /* write the service_id into circ */
1636 circ
->rend_data
= rend_data_dup(ENTRY_TO_EDGE_CONN(conn
)->rend_data
);
1637 if (circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
&&
1638 circ
->_base
.state
== CIRCUIT_STATE_OPEN
)
1639 rend_client_rendcirc_has_opened(circ
);
1642 } /* endif (!circ) */
1644 /* Mark the circuit with the isolation fields for this connection.
1645 * When the circuit arrives, we'll clear these flags: this is
1646 * just some internal bookkeeping to make sure that we have
1647 * launched enough circuits.
1649 connection_edge_update_circuit_isolation(conn
, circ
, 0);
1652 "No safe circuit (purpose %d) ready for edge "
1653 "connection; delaying.",
1654 desired_circuit_purpose
);
1660 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1663 cpath_is_on_circuit(origin_circuit_t
*circ
, crypt_path_t
*crypt_path
)
1665 crypt_path_t
*cpath
, *cpath_next
= NULL
;
1666 for (cpath
= circ
->cpath
; cpath_next
!= circ
->cpath
; cpath
= cpath_next
) {
1667 cpath_next
= cpath
->next
;
1668 if (crypt_path
== cpath
)
1674 /** Return true iff client-side optimistic data is supported. */
1676 optimistic_data_enabled(void)
1678 const or_options_t
*options
= get_options();
1679 if (options
->OptimisticData
< 0) {
1680 /* XXX023 consider having auto default to 1 rather than 0 before
1681 * the 0.2.3 branch goes stable. See bug 3617. -RD */
1682 const int32_t enabled
=
1683 networkstatus_get_param(NULL
, "UseOptimisticData", 0, 0, 1);
1684 return (int)enabled
;
1686 return options
->OptimisticData
;
1689 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1690 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1691 * hop in circ's cpath if <b>cpath</b> is NULL.
1694 link_apconn_to_circ(entry_connection_t
*apconn
, origin_circuit_t
*circ
,
1695 crypt_path_t
*cpath
)
1697 const node_t
*exitnode
;
1699 /* add it into the linked list of streams on this circuit */
1700 log_debug(LD_APP
|LD_CIRC
, "attaching new conn to circ. n_circ_id %d.",
1701 circ
->_base
.n_circ_id
);
1702 /* reset it, so we can measure circ timeouts */
1703 ENTRY_TO_CONN(apconn
)->timestamp_lastread
= time(NULL
);
1704 ENTRY_TO_EDGE_CONN(apconn
)->next_stream
= circ
->p_streams
;
1705 ENTRY_TO_EDGE_CONN(apconn
)->on_circuit
= TO_CIRCUIT(circ
);
1706 /* assert_connection_ok(conn, time(NULL)); */
1707 circ
->p_streams
= ENTRY_TO_EDGE_CONN(apconn
);
1709 if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn
))) {
1710 /* We are attaching a stream to a rendezvous circuit. That means
1711 * that an attempt to connect to a hidden service just
1712 * succeeded. Tell rendclient.c. */
1713 rend_client_note_connection_attempt_ended(
1714 ENTRY_TO_EDGE_CONN(apconn
)->rend_data
->onion_address
);
1717 if (cpath
) { /* we were given one; use it */
1718 tor_assert(cpath_is_on_circuit(circ
, cpath
));
1720 /* use the last hop in the circuit */
1721 tor_assert(circ
->cpath
);
1722 tor_assert(circ
->cpath
->prev
);
1723 tor_assert(circ
->cpath
->prev
->state
== CPATH_STATE_OPEN
);
1724 cpath
= circ
->cpath
->prev
;
1726 ENTRY_TO_EDGE_CONN(apconn
)->cpath_layer
= cpath
;
1728 circ
->isolation_any_streams_attached
= 1;
1729 connection_edge_update_circuit_isolation(apconn
, circ
, 0);
1731 /* See if we can use optimistic data on this circuit */
1732 if (cpath
->extend_info
&&
1733 (exitnode
= node_get_by_id(cpath
->extend_info
->identity_digest
)) &&
1735 /* Okay; we know what exit node this is. */
1736 if (optimistic_data_enabled() &&
1737 circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
&&
1738 exitnode
->rs
->version_supports_optimistic_data
)
1739 apconn
->may_use_optimistic_data
= 1;
1741 apconn
->may_use_optimistic_data
= 0;
1742 log_info(LD_APP
, "Looks like completed circuit to %s %s allow "
1743 "optimistic data for connection to %s",
1744 safe_str_client(node_describe(exitnode
)),
1745 apconn
->may_use_optimistic_data
? "does" : "doesn't",
1746 safe_str_client(apconn
->socks_request
->address
));
1750 /** Return true iff <b>address</b> is matched by one of the entries in
1751 * TrackHostExits. */
1753 hostname_in_track_host_exits(const or_options_t
*options
, const char *address
)
1755 if (!options
->TrackHostExits
)
1757 SMARTLIST_FOREACH_BEGIN(options
->TrackHostExits
, const char *, cp
) {
1758 if (cp
[0] == '.') { /* match end */
1759 if (cp
[1] == '\0' ||
1760 !strcasecmpend(address
, cp
) ||
1761 !strcasecmp(address
, &cp
[1]))
1763 } else if (strcasecmp(cp
, address
) == 0) {
1766 } SMARTLIST_FOREACH_END(cp
);
1770 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
1771 * the exit that we *did* choose for use by future connections to
1772 * <b>conn</b>'s destination.
1775 consider_recording_trackhost(const entry_connection_t
*conn
,
1776 const origin_circuit_t
*circ
)
1778 const or_options_t
*options
= get_options();
1779 char *new_address
= NULL
;
1780 char fp
[HEX_DIGEST_LEN
+1];
1782 /* Search the addressmap for this conn's destination. */
1783 /* If he's not in the address map.. */
1784 if (!options
->TrackHostExits
||
1785 addressmap_have_mapping(conn
->socks_request
->address
,
1786 options
->TrackHostExitsExpire
))
1787 return; /* nothing to track, or already mapped */
1789 if (!hostname_in_track_host_exits(options
, conn
->socks_request
->address
) ||
1790 !circ
->build_state
->chosen_exit
)
1793 /* write down the fingerprint of the chosen exit, not the nickname,
1794 * because the chosen exit might not be named. */
1795 base16_encode(fp
, sizeof(fp
),
1796 circ
->build_state
->chosen_exit
->identity_digest
, DIGEST_LEN
);
1798 /* Add this exit/hostname pair to the addressmap. */
1799 tor_asprintf(&new_address
, "%s.%s.exit",
1800 conn
->socks_request
->address
, fp
);
1802 addressmap_register(conn
->socks_request
->address
, new_address
,
1803 time(NULL
) + options
->TrackHostExitsExpire
,
1804 ADDRMAPSRC_TRACKEXIT
, 0, 0);
1807 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1808 * begin or resolve cell as appropriate. Return values are as for
1809 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1810 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1811 * <b>cpath</b> is NULL. */
1813 connection_ap_handshake_attach_chosen_circuit(entry_connection_t
*conn
,
1814 origin_circuit_t
*circ
,
1815 crypt_path_t
*cpath
)
1817 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
1819 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
||
1820 base_conn
->state
== AP_CONN_STATE_CONTROLLER_WAIT
);
1821 tor_assert(conn
->socks_request
);
1823 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_OPEN
);
1825 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1827 if (!circ
->_base
.timestamp_dirty
)
1828 circ
->_base
.timestamp_dirty
= time(NULL
);
1830 link_apconn_to_circ(conn
, circ
, cpath
);
1831 tor_assert(conn
->socks_request
);
1832 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
1833 if (!conn
->use_begindir
)
1834 consider_recording_trackhost(conn
, circ
);
1835 if (connection_ap_handshake_send_begin(conn
) < 0)
1838 if (connection_ap_handshake_send_resolve(conn
) < 0)
1845 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1846 * we don't find one: if conn cannot be handled by any known nodes,
1847 * warn and return -1 (conn needs to die, and is maybe already marked);
1848 * else launch new circuit (if necessary) and return 0.
1849 * Otherwise, associate conn with a safe live circuit, do the
1850 * right next step, and return 1.
1852 /* XXXX this function should mark for close whenever it returns -1;
1853 * its callers shouldn't have to worry about that. */
1855 connection_ap_handshake_attach_circuit(entry_connection_t
*conn
)
1857 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
1863 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1864 tor_assert(conn
->socks_request
);
1865 want_onehop
= conn
->want_onehop
;
1867 conn_age
= (int)(time(NULL
) - base_conn
->timestamp_created
);
1869 if (conn_age
>= get_options()->SocksTimeout
) {
1870 int severity
= (tor_addr_is_null(&base_conn
->addr
) && !base_conn
->port
) ?
1871 LOG_INFO
: LOG_NOTICE
;
1872 log_fn(severity
, LD_APP
,
1873 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1874 conn_age
, safe_str_client(conn
->socks_request
->address
),
1875 conn
->socks_request
->port
);
1879 if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn
))) {
1880 /* we're a general conn */
1881 origin_circuit_t
*circ
=NULL
;
1883 if (conn
->chosen_exit_name
) {
1884 const node_t
*node
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1885 int opt
= conn
->chosen_exit_optional
;
1886 if (!node
&& !want_onehop
) {
1887 /* We ran into this warning when trying to extend a circuit to a
1888 * hidden service directory for which we didn't have a router
1889 * descriptor. See flyspray task 767 for more details. We should
1890 * keep this in mind when deciding to use BEGIN_DIR cells for other
1891 * directory requests as well. -KL*/
1892 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1893 "Requested exit point '%s' is not known. %s.",
1894 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1896 conn
->chosen_exit_optional
= 0;
1897 tor_free(conn
->chosen_exit_name
);
1902 if (node
&& !connection_ap_can_use_exit(conn
, node
)) {
1903 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1904 "Requested exit point '%s' is excluded or "
1905 "would refuse request. %s.",
1906 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1908 conn
->chosen_exit_optional
= 0;
1909 tor_free(conn
->chosen_exit_name
);
1916 /* find the circuit that we should use, if there is one. */
1917 retval
= circuit_get_open_circ_or_launch(
1918 conn
, CIRCUIT_PURPOSE_C_GENERAL
, &circ
);
1919 if (retval
< 1) // XXX023 if we totally fail, this still returns 0 -RD
1922 log_debug(LD_APP
|LD_CIRC
,
1923 "Attaching apconn to circ %d (stream %d sec old).",
1924 circ
->_base
.n_circ_id
, conn_age
);
1925 /* print the circ's path, so people can figure out which circs are
1927 circuit_log_path(LOG_INFO
,LD_APP
|LD_CIRC
,circ
);
1929 /* We have found a suitable circuit for our conn. Hurray. */
1930 return connection_ap_handshake_attach_chosen_circuit(conn
, circ
, NULL
);
1932 } else { /* we're a rendezvous conn */
1933 origin_circuit_t
*rendcirc
=NULL
, *introcirc
=NULL
;
1935 tor_assert(!ENTRY_TO_EDGE_CONN(conn
)->cpath_layer
);
1937 /* start by finding a rendezvous circuit for us */
1939 retval
= circuit_get_open_circ_or_launch(
1940 conn
, CIRCUIT_PURPOSE_C_REND_JOINED
, &rendcirc
);
1941 if (retval
< 0) return -1; /* failed */
1944 tor_assert(rendcirc
);
1945 /* one is already established, attach */
1947 "rend joined circ %d already here. attaching. "
1948 "(stream %d sec old)",
1949 rendcirc
->_base
.n_circ_id
, conn_age
);
1950 /* Mark rendezvous circuits as 'newly dirty' every time you use
1951 * them, since the process of rebuilding a rendezvous circ is so
1952 * expensive. There is a tradeoff between linkability and
1953 * feasibility, at this point.
1955 rendcirc
->_base
.timestamp_dirty
= time(NULL
);
1956 link_apconn_to_circ(conn
, rendcirc
, NULL
);
1957 if (connection_ap_handshake_send_begin(conn
) < 0)
1958 return 0; /* already marked, let them fade away */
1962 if (rendcirc
&& (rendcirc
->_base
.purpose
==
1963 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
)) {
1965 "pending-join circ %d already here, with intro ack. "
1966 "Stalling. (stream %d sec old)",
1967 rendcirc
->_base
.n_circ_id
, conn_age
);
1971 /* it's on its way. find an intro circ. */
1972 retval
= circuit_get_open_circ_or_launch(
1973 conn
, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
, &introcirc
);
1974 if (retval
< 0) return -1; /* failed */
1977 /* one has already sent the intro. keep waiting. */
1978 circuit_t
*c
= NULL
;
1979 tor_assert(introcirc
);
1980 log_info(LD_REND
, "Intro circ %d present and awaiting ack (rend %d). "
1981 "Stalling. (stream %d sec old)",
1982 introcirc
->_base
.n_circ_id
,
1983 rendcirc
? rendcirc
->_base
.n_circ_id
: 0,
1985 /* abort parallel intro circs, if any */
1986 for (c
= global_circuitlist
; c
; c
= c
->next
) {
1987 if (c
->purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
&&
1988 !c
->marked_for_close
&& CIRCUIT_IS_ORIGIN(c
)) {
1989 origin_circuit_t
*oc
= TO_ORIGIN_CIRCUIT(c
);
1990 if (oc
->rend_data
&&
1991 !rend_cmp_service_ids(
1992 ENTRY_TO_EDGE_CONN(conn
)->rend_data
->onion_address
,
1993 oc
->rend_data
->onion_address
)) {
1994 log_info(LD_REND
|LD_CIRC
, "Closing introduction circuit that we "
1995 "built in parallel.");
1996 circuit_mark_for_close(c
, END_CIRC_REASON_TIMEOUT
);
2003 /* now rendcirc and introcirc are each either undefined or not finished */
2005 if (rendcirc
&& introcirc
&&
2006 rendcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_REND_READY
) {
2008 "ready rend circ %d already here (no intro-ack yet on "
2009 "intro %d). (stream %d sec old)",
2010 rendcirc
->_base
.n_circ_id
,
2011 introcirc
->_base
.n_circ_id
, conn_age
);
2013 tor_assert(introcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
2014 if (introcirc
->_base
.state
== CIRCUIT_STATE_OPEN
) {
2015 log_info(LD_REND
,"found open intro circ %d (rend %d); sending "
2016 "introduction. (stream %d sec old)",
2017 introcirc
->_base
.n_circ_id
, rendcirc
->_base
.n_circ_id
,
2019 switch (rend_client_send_introduction(introcirc
, rendcirc
)) {
2020 case 0: /* success */
2021 rendcirc
->_base
.timestamp_dirty
= time(NULL
);
2022 introcirc
->_base
.timestamp_dirty
= time(NULL
);
2023 assert_circuit_ok(TO_CIRCUIT(rendcirc
));
2024 assert_circuit_ok(TO_CIRCUIT(introcirc
));
2026 case -1: /* transient error */
2028 case -2: /* permanent error */
2031 tor_fragile_assert();
2037 log_info(LD_REND
, "Intro (%d) and rend (%d) circs are not both ready. "
2038 "Stalling conn. (%d sec old)",
2039 introcirc
? introcirc
->_base
.n_circ_id
: 0,
2040 rendcirc
? rendcirc
->_base
.n_circ_id
: 0, conn_age
);
2045 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
2047 circuit_change_purpose(circuit_t
*circ
, uint8_t new_purpose
)
2049 uint8_t old_purpose
;
2050 /* Don't allow an OR circ to become an origin circ or vice versa. */
2051 tor_assert(!!(CIRCUIT_IS_ORIGIN(circ
)) ==
2052 !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose
)));
2054 if (circ
->purpose
== new_purpose
) return;
2056 if (CIRCUIT_IS_ORIGIN(circ
)) {
2057 char old_purpose_desc
[80] = "";
2059 strncpy(old_purpose_desc
, circuit_purpose_to_string(circ
->purpose
), 80-1);
2060 old_purpose_desc
[80-1] = '\0';
2063 "changing purpose of origin circ %d "
2064 "from \"%s\" (%d) to \"%s\" (%d)",
2065 TO_ORIGIN_CIRCUIT(circ
)->global_identifier
,
2068 circuit_purpose_to_string(new_purpose
),
2072 old_purpose
= circ
->purpose
;
2073 circ
->purpose
= new_purpose
;
2075 if (CIRCUIT_IS_ORIGIN(circ
)) {
2076 control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ
),