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