1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Launch the right sort of circuits and attach streams to them.
14 /********* START VARIABLES **********/
16 extern circuit_t
*global_circuitlist
; /* from circuitlist.c */
18 /********* END VARIABLES ************/
20 static void circuit_expire_old_circuits_clientside(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 purpose %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 purpose %d to %s (circid %d). "
308 "%d secs since dirty.",
309 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
310 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
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 hidden service 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 time_t time_to_new_circuit
= 0;
534 or_options_t
*options
= get_options();
536 /* launch a new circ for any pending streams that need one */
537 connection_ap_attach_pending();
539 /* make sure any hidden services have enough intro points */
540 rend_services_introduce();
542 if (time_to_new_circuit
< now
) {
543 circuit_reset_failure_count(1);
544 time_to_new_circuit
= now
+ options
->NewCircuitPeriod
;
545 if (proxy_mode(get_options()))
546 addressmap_clean(now
);
547 circuit_expire_old_circuits_clientside(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_clientside(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, "
647 circ
->n_circ_id
, (int)(now
- circ
->timestamp_dirty
),
649 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
650 } else if (!circ
->timestamp_dirty
&&
651 circ
->state
== CIRCUIT_STATE_OPEN
&&
652 circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
653 if (circ
->timestamp_created
< cutoff
) {
655 "Closing circuit that has been unused for %d seconds.",
656 (int)(now
- circ
->timestamp_created
));
657 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
663 /** How long do we wait before killing circuits with the properties
666 * Probably we could choose a number here as low as 5 to 10 seconds,
667 * since these circs are used for begindir, and a) generally you either
668 * ask another begindir question right after or you don't for a long time,
669 * b) clients at least through 0.2.1.x choose from the whole set of
670 * directory mirrors at each choice, and c) re-establishing a one-hop
671 * circuit via create-fast is a light operation assuming the TLS conn is
674 * I expect "b" to go away one day when we move to using directory
675 * guards, but I think "a" and "c" are good enough reasons that a low
676 * number is safe even then.
678 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
680 /** Find each non-origin circuit that has been unused for too long,
681 * has no streams on it, used a create_fast, and ends here: mark it
685 circuit_expire_old_circuits_serverside(time_t now
)
688 or_circuit_t
*or_circ
;
689 time_t cutoff
= now
- IDLE_ONE_HOP_CIRC_TIMEOUT
;
691 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
692 if (circ
->marked_for_close
|| CIRCUIT_IS_ORIGIN(circ
))
694 or_circ
= TO_OR_CIRCUIT(circ
);
695 /* If the circuit has been idle for too long, and there are no streams
696 * on it, and it ends here, and it used a create_fast, mark it for close.
698 if (or_circ
->is_first_hop
&& !circ
->n_conn
&&
699 !or_circ
->n_streams
&& !or_circ
->resolving_streams
&&
701 or_circ
->p_conn
->timestamp_last_added_nonpadding
<= cutoff
) {
702 log_info(LD_CIRC
, "Closing circ_id %d (empty %d secs ago)",
704 (int)(now
- or_circ
->p_conn
->timestamp_last_added_nonpadding
));
705 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
710 /** Number of testing circuits we want open before testing our bandwidth. */
711 #define NUM_PARALLEL_TESTING_CIRCS 4
713 /** True iff we've ever had enough testing circuits open to test our
715 static int have_performed_bandwidth_test
= 0;
717 /** Reset have_performed_bandwidth_test, so we'll start building
718 * testing circuits again so we can exercise our bandwidth. */
720 reset_bandwidth_test(void)
722 have_performed_bandwidth_test
= 0;
725 /** Return 1 if we've already exercised our bandwidth, or if we
726 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
727 * established or on the way. Else return 0.
730 circuit_enough_testing_circs(void)
735 if (have_performed_bandwidth_test
)
738 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
739 if (!circ
->marked_for_close
&& CIRCUIT_IS_ORIGIN(circ
) &&
740 circ
->purpose
== CIRCUIT_PURPOSE_TESTING
&&
741 circ
->state
== CIRCUIT_STATE_OPEN
)
744 return num
>= NUM_PARALLEL_TESTING_CIRCS
;
747 /** A testing circuit has completed. Take whatever stats we want.
748 * Noticing reachability is taken care of in onionskin_answer(),
749 * so there's no need to record anything here. But if we still want
750 * to do the bandwidth test, and we now have enough testing circuits
754 circuit_testing_opened(origin_circuit_t
*circ
)
756 if (have_performed_bandwidth_test
||
757 !check_whether_orport_reachable()) {
758 /* either we've already done everything we want with testing circuits,
759 * or this testing circuit became open due to a fluke, e.g. we picked
760 * a last hop where we already had the connection open due to an
761 * outgoing local circuit. */
762 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_AT_ORIGIN
);
763 } else if (circuit_enough_testing_circs()) {
764 router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS
, time(NULL
));
765 have_performed_bandwidth_test
= 1;
767 consider_testing_reachability(1, 0);
770 /** A testing circuit has failed to build. Take whatever stats we want. */
772 circuit_testing_failed(origin_circuit_t
*circ
, int at_last_hop
)
774 if (server_mode(get_options()) && check_whether_orport_reachable())
778 "Our testing circuit (to see if your ORPort is reachable) "
779 "has failed. I'll try again later.");
781 /* These aren't used yet. */
786 /** The circuit <b>circ</b> has just become open. Take the next
787 * step: for rendezvous circuits, we pass circ to the appropriate
788 * function in rendclient or rendservice. For general circuits, we
789 * call connection_ap_attach_pending, which looks for pending streams
790 * that could use circ.
793 circuit_has_opened(origin_circuit_t
*circ
)
795 control_event_circuit_status(circ
, CIRC_EVENT_BUILT
, 0);
797 switch (TO_CIRCUIT(circ
)->purpose
) {
798 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
799 rend_client_rendcirc_has_opened(circ
);
800 connection_ap_attach_pending();
802 case CIRCUIT_PURPOSE_C_INTRODUCING
:
803 rend_client_introcirc_has_opened(circ
);
805 case CIRCUIT_PURPOSE_C_GENERAL
:
806 /* Tell any AP connections that have been waiting for a new
807 * circuit that one is ready. */
808 connection_ap_attach_pending();
810 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
811 /* at Bob, waiting for introductions */
812 rend_service_intro_has_opened(circ
);
814 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
815 /* at Bob, connecting to rend point */
816 rend_service_rendezvous_has_opened(circ
);
818 case CIRCUIT_PURPOSE_TESTING
:
819 circuit_testing_opened(circ
);
822 * This won't happen in normal operation, but might happen if the
823 * controller did it. Just let it slide. */
827 /** Called whenever a circuit could not be successfully built.
830 circuit_build_failed(origin_circuit_t
*circ
)
832 /* we should examine circ and see if it failed because of
833 * the last hop or an earlier hop. then use this info below.
835 int failed_at_last_hop
= 0;
836 /* If the last hop isn't open, and the second-to-last is, we failed
837 * at the last hop. */
839 circ
->cpath
->prev
->state
!= CPATH_STATE_OPEN
&&
840 circ
->cpath
->prev
->prev
->state
== CPATH_STATE_OPEN
) {
841 failed_at_last_hop
= 1;
844 circ
->cpath
->state
!= CPATH_STATE_OPEN
) {
845 /* We failed at the first hop. If there's an OR connection
846 * to blame, blame it. Also, avoid this relay for a while, and
847 * fail any one-hop directory fetches destined for it. */
848 const char *n_conn_id
= circ
->cpath
->extend_info
->identity_digest
;
849 if (circ
->_base
.n_conn
) {
850 or_connection_t
*n_conn
= circ
->_base
.n_conn
;
852 "Our circuit failed to get a response from the first hop "
853 "(%s:%d). I'm going to try to rotate to a better connection.",
854 n_conn
->_base
.address
, n_conn
->_base
.port
);
855 n_conn
->is_bad_for_new_circs
= 1;
858 entry_guard_register_connect_status(n_conn_id
, 0, 1, time(NULL
));
859 /* if there are any one-hop streams waiting on this circuit, fail
860 * them now so they can retry elsewhere. */
861 connection_ap_fail_onehop(n_conn_id
, circ
->build_state
);
865 switch (circ
->_base
.purpose
) {
866 case CIRCUIT_PURPOSE_C_GENERAL
:
867 /* If we never built the circuit, note it as a failure. */
868 circuit_increment_failure_count();
869 if (failed_at_last_hop
) {
870 /* Make sure any streams that demand our last hop as their exit
871 * know that it's unlikely to happen. */
872 circuit_discard_optional_exit_enclaves(circ
->cpath
->prev
->extend_info
);
875 case CIRCUIT_PURPOSE_TESTING
:
876 circuit_testing_failed(circ
, failed_at_last_hop
);
878 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
879 /* at Bob, waiting for introductions */
880 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
) {
881 circuit_increment_failure_count();
883 /* no need to care here, because bob will rebuild intro
884 * points periodically. */
886 case CIRCUIT_PURPOSE_C_INTRODUCING
:
887 /* at Alice, connecting to intro point */
888 /* Don't increment failure count, since Bob may have picked
889 * the introduction point maliciously */
890 /* Alice will pick a new intro point when this one dies, if
891 * the stream in question still cares. No need to act here. */
893 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
894 /* at Alice, waiting for Bob */
895 circuit_increment_failure_count();
896 /* Alice will pick a new rend point when this one dies, if
897 * the stream in question still cares. No need to act here. */
899 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
900 /* at Bob, connecting to rend point */
901 /* Don't increment failure count, since Alice may have picked
902 * the rendezvous point maliciously */
904 "Couldn't connect to Alice's chosen rend point %s "
906 escaped(build_state_get_exit_nickname(circ
->build_state
)),
907 failed_at_last_hop
?"last":"non-last");
908 rend_service_relaunch_rendezvous(circ
);
911 * This won't happen in normal operation, but might happen if the
912 * controller did it. Just let it slide. */
916 /** Number of consecutive failures so far; should only be touched by
917 * circuit_launch_new and circuit_*_failure_count.
919 static int n_circuit_failures
= 0;
920 /** Before the last time we called circuit_reset_failure_count(), were
921 * there a lot of failures? */
922 static int did_circs_fail_last_period
= 0;
924 /** Don't retry launching a new circuit if we try this many times with no
926 #define MAX_CIRCUIT_FAILURES 5
928 /** Launch a new circuit; see circuit_launch_by_extend_info() for
929 * details on arguments. */
931 circuit_launch_by_router(uint8_t purpose
,
932 routerinfo_t
*exit
, int flags
)
934 origin_circuit_t
*circ
;
935 extend_info_t
*info
= NULL
;
937 info
= extend_info_from_router(exit
);
938 circ
= circuit_launch_by_extend_info(purpose
, info
, flags
);
940 extend_info_free(info
);
944 /** Launch a new circuit with purpose <b>purpose</b> and exit node
945 * <b>extend_info</b> (or NULL to select a random exit node). If flags
946 * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
947 * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
948 * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
949 * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
950 * Return the newly allocated circuit on success, or NULL on failure. */
952 circuit_launch_by_extend_info(uint8_t purpose
,
953 extend_info_t
*extend_info
,
956 origin_circuit_t
*circ
;
957 int onehop_tunnel
= (flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) != 0;
959 if (!onehop_tunnel
&& !router_have_minimum_dir_info()) {
960 log_debug(LD_CIRC
,"Haven't fetched enough directory info yet; canceling "
965 if ((extend_info
|| purpose
!= CIRCUIT_PURPOSE_C_GENERAL
) &&
966 purpose
!= CIRCUIT_PURPOSE_TESTING
&& !onehop_tunnel
) {
967 /* see if there are appropriate circs available to cannibalize. */
968 /* XXX if we're planning to add a hop, perhaps we want to look for
969 * internal circs rather than exit circs? -RD */
970 circ
= circuit_find_to_cannibalize(purpose
, extend_info
, flags
);
972 log_info(LD_CIRC
,"Cannibalizing circ '%s' for purpose %d",
973 build_state_get_exit_nickname(circ
->build_state
), purpose
);
974 circ
->_base
.purpose
= purpose
;
975 /* reset the birth date of this circ, else expire_building
976 * will see it and think it's been trying to build since it
978 circ
->_base
.timestamp_created
= time(NULL
);
980 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
981 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
982 /* it's ready right now */
984 case CIRCUIT_PURPOSE_C_INTRODUCING
:
985 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
986 case CIRCUIT_PURPOSE_C_GENERAL
:
987 /* need to add a new hop */
988 tor_assert(extend_info
);
989 if (circuit_extend_to_new_exit(circ
, extend_info
) < 0)
994 "unexpected purpose %d when cannibalizing a circ.",
996 tor_fragile_assert();
1003 if (did_circs_fail_last_period
&&
1004 n_circuit_failures
> MAX_CIRCUIT_FAILURES
) {
1005 /* too many failed circs in a row. don't try. */
1006 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
1010 /* try a circ. if it fails, circuit_mark_for_close will increment
1011 * n_circuit_failures */
1012 return circuit_establish_circuit(purpose
, extend_info
, flags
);
1015 /** Record another failure at opening a general circuit. When we have
1016 * too many, we'll stop trying for the remainder of this minute.
1019 circuit_increment_failure_count(void)
1021 ++n_circuit_failures
;
1022 log_debug(LD_CIRC
,"n_circuit_failures now %d.",n_circuit_failures
);
1025 /** Reset the failure count for opening general circuits. This means
1026 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
1030 circuit_reset_failure_count(int timeout
)
1032 if (timeout
&& n_circuit_failures
> MAX_CIRCUIT_FAILURES
)
1033 did_circs_fail_last_period
= 1;
1035 did_circs_fail_last_period
= 0;
1036 n_circuit_failures
= 0;
1039 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
1040 * there isn't one, and there isn't one on the way, launch one and return
1041 * 0. If it will never work, return -1.
1043 * Write the found or in-progress or launched circ into *circp.
1046 circuit_get_open_circ_or_launch(edge_connection_t
*conn
,
1047 uint8_t desired_circuit_purpose
,
1048 origin_circuit_t
**circp
)
1050 origin_circuit_t
*circ
;
1051 int check_exit_policy
;
1052 int need_uptime
, need_internal
;
1054 or_options_t
*options
= get_options();
1058 tor_assert(conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1060 conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
&&
1061 !conn
->use_begindir
&&
1062 !connection_edge_is_rendezvous_stream(conn
);
1063 want_onehop
= conn
->want_onehop
;
1065 need_uptime
= !conn
->want_onehop
&& !conn
->use_begindir
&&
1066 smartlist_string_num_isin(options
->LongLivedPorts
,
1067 conn
->socks_request
->port
);
1068 need_internal
= desired_circuit_purpose
!= CIRCUIT_PURPOSE_C_GENERAL
;
1070 circ
= circuit_get_best(conn
, 1, desired_circuit_purpose
,
1071 need_uptime
, need_internal
);
1075 return 1; /* we're happy */
1078 if (!want_onehop
&& !router_have_minimum_dir_info()) {
1079 if (!connection_get_by_type(CONN_TYPE_DIR
)) {
1080 int severity
= LOG_NOTICE
;
1081 /* FFFF if this is a tunneled directory fetch, don't yell
1082 * as loudly. the user doesn't even know it's happening. */
1083 if (options
->UseBridges
&& bridges_known_but_down()) {
1084 log_fn(severity
, LD_APP
|LD_DIR
,
1085 "Application request when we're believed to be "
1086 "offline. Optimistically trying known bridges again.");
1087 bridges_retry_all();
1088 } else if (!options
->UseBridges
|| any_bridge_descriptors_known()) {
1089 log_fn(severity
, LD_APP
|LD_DIR
,
1090 "Application request when we're believed to be "
1091 "offline. Optimistically trying directory fetches again.");
1092 routerlist_retry_directory_downloads(time(NULL
));
1095 /* the stream will be dealt with when router_have_minimum_dir_info becomes
1096 * 1, or when all directory attempts fail and directory_all_unreachable()
1102 /* Do we need to check exit policy? */
1103 if (check_exit_policy
) {
1104 if (!conn
->chosen_exit_name
) {
1107 if (tor_inet_aton(conn
->socks_request
->address
, &in
))
1108 addr
= ntohl(in
.s_addr
);
1109 if (router_exit_policy_all_routers_reject(addr
,
1110 conn
->socks_request
->port
,
1113 "No Tor server allows exit to %s:%d. Rejecting.",
1114 safe_str(conn
->socks_request
->address
),
1115 conn
->socks_request
->port
);
1119 /* XXXX022 Duplicates checks in connection_ap_handshake_attach_circuit */
1120 routerinfo_t
*router
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1121 int opt
= conn
->chosen_exit_optional
;
1122 if (router
&& !connection_ap_can_use_exit(conn
, router
)) {
1123 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1124 "Requested exit point '%s' would refuse request. %s.",
1125 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1127 conn
->chosen_exit_optional
= 0;
1128 tor_free(conn
->chosen_exit_name
);
1130 return circuit_get_open_circ_or_launch(conn
,
1131 desired_circuit_purpose
,
1139 /* is one already on the way? */
1140 circ
= circuit_get_best(conn
, 0, desired_circuit_purpose
,
1141 need_uptime
, need_internal
);
1143 log_debug(LD_CIRC
, "one on the way!");
1145 extend_info_t
*extend_info
=NULL
;
1146 uint8_t new_circ_purpose
;
1148 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
) {
1149 /* need to pick an intro point */
1150 tor_assert(conn
->rend_data
);
1151 extend_info
= rend_client_get_random_intro(conn
->rend_data
);
1154 "No intro points for '%s': re-fetching service descriptor.",
1155 safe_str(conn
->rend_data
->onion_address
));
1156 /* Fetch both, v0 and v2 rend descriptors in parallel. Use whichever
1157 * arrives first. Exception: When using client authorization, only
1158 * fetch v2 descriptors.*/
1159 rend_client_refetch_v2_renddesc(conn
->rend_data
);
1160 if (conn
->rend_data
->auth_type
== REND_NO_AUTH
)
1161 rend_client_refetch_renddesc(conn
->rend_data
->onion_address
);
1162 conn
->_base
.state
= AP_CONN_STATE_RENDDESC_WAIT
;
1165 log_info(LD_REND
,"Chose '%s' as intro point for '%s'.",
1166 extend_info
->nickname
,
1167 safe_str(conn
->rend_data
->onion_address
));
1170 /* If we have specified a particular exit node for our
1171 * connection, then be sure to open a circuit to that exit node.
1173 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
1174 if (conn
->chosen_exit_name
) {
1176 int opt
= conn
->chosen_exit_optional
;
1177 r
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1179 extend_info
= extend_info_from_router(r
);
1181 log_debug(LD_DIR
, "considering %d, %s",
1182 want_onehop
, conn
->chosen_exit_name
);
1183 if (want_onehop
&& conn
->chosen_exit_name
[0] == '$') {
1184 /* We're asking for a one-hop circuit to a router that
1185 * we don't have a routerinfo about. Make up an extend_info. */
1186 char digest
[DIGEST_LEN
];
1187 char *hexdigest
= conn
->chosen_exit_name
+1;
1189 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
1190 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
)<0) {
1191 log_info(LD_DIR
, "Broken exit digest on tunnel conn. Closing.");
1194 if (tor_addr_from_str(&addr
, conn
->socks_request
->address
) < 0) {
1195 log_info(LD_DIR
, "Broken address %s on tunnel conn. Closing.",
1196 escaped_safe_str(conn
->socks_request
->address
));
1199 extend_info
= extend_info_alloc(conn
->chosen_exit_name
+1,
1200 digest
, NULL
, &addr
,
1201 conn
->socks_request
->port
);
1203 /* We will need an onion key for the router, and we
1204 * don't have one. Refuse or relax requirements. */
1205 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1206 "Requested exit point '%s' is not known. %s.",
1207 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1209 conn
->chosen_exit_optional
= 0;
1210 tor_free(conn
->chosen_exit_name
);
1211 /* Try again with no requested exit */
1212 return circuit_get_open_circ_or_launch(conn
,
1213 desired_circuit_purpose
,
1222 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
)
1223 new_circ_purpose
= CIRCUIT_PURPOSE_C_ESTABLISH_REND
;
1224 else if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
1225 new_circ_purpose
= CIRCUIT_PURPOSE_C_INTRODUCING
;
1227 new_circ_purpose
= desired_circuit_purpose
;
1230 int flags
= CIRCLAUNCH_NEED_CAPACITY
;
1231 if (want_onehop
) flags
|= CIRCLAUNCH_ONEHOP_TUNNEL
;
1232 if (need_uptime
) flags
|= CIRCLAUNCH_NEED_UPTIME
;
1233 if (need_internal
) flags
|= CIRCLAUNCH_IS_INTERNAL
;
1234 circ
= circuit_launch_by_extend_info(new_circ_purpose
, extend_info
,
1239 extend_info_free(extend_info
);
1241 if (desired_circuit_purpose
!= CIRCUIT_PURPOSE_C_GENERAL
) {
1242 /* help predict this next time */
1243 rep_hist_note_used_internal(time(NULL
), need_uptime
, 1);
1245 /* write the service_id into circ */
1246 circ
->rend_data
= rend_data_dup(conn
->rend_data
);
1247 if (circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
&&
1248 circ
->_base
.state
== CIRCUIT_STATE_OPEN
)
1249 rend_client_rendcirc_has_opened(circ
);
1255 "No safe circuit (purpose %d) ready for edge "
1256 "connection; delaying.",
1257 desired_circuit_purpose
);
1262 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
1265 cpath_is_on_circuit(origin_circuit_t
*circ
, crypt_path_t
*crypt_path
)
1267 crypt_path_t
*cpath
, *cpath_next
= NULL
;
1268 for (cpath
= circ
->cpath
; cpath_next
!= circ
->cpath
; cpath
= cpath_next
) {
1269 cpath_next
= cpath
->next
;
1270 if (crypt_path
== cpath
)
1276 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1277 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
1278 * hop in circ's cpath if <b>cpath</b> is NULL.
1281 link_apconn_to_circ(edge_connection_t
*apconn
, origin_circuit_t
*circ
,
1282 crypt_path_t
*cpath
)
1284 /* add it into the linked list of streams on this circuit */
1285 log_debug(LD_APP
|LD_CIRC
, "attaching new conn to circ. n_circ_id %d.",
1286 circ
->_base
.n_circ_id
);
1287 /* reset it, so we can measure circ timeouts */
1288 apconn
->_base
.timestamp_lastread
= time(NULL
);
1289 apconn
->next_stream
= circ
->p_streams
;
1290 apconn
->on_circuit
= TO_CIRCUIT(circ
);
1291 /* assert_connection_ok(conn, time(NULL)); */
1292 circ
->p_streams
= apconn
;
1294 if (cpath
) { /* we were given one; use it */
1295 tor_assert(cpath_is_on_circuit(circ
, cpath
));
1296 apconn
->cpath_layer
= cpath
;
1297 } else { /* use the last hop in the circuit */
1298 tor_assert(circ
->cpath
);
1299 tor_assert(circ
->cpath
->prev
);
1300 tor_assert(circ
->cpath
->prev
->state
== CPATH_STATE_OPEN
);
1301 apconn
->cpath_layer
= circ
->cpath
->prev
;
1305 /** If an exit wasn't specifically chosen, save the history for future
1308 consider_recording_trackhost(edge_connection_t
*conn
, origin_circuit_t
*circ
)
1310 int found_needle
= 0;
1311 or_options_t
*options
= get_options();
1314 char fp
[HEX_DIGEST_LEN
+1];
1316 /* Search the addressmap for this conn's destination. */
1317 /* If he's not in the address map.. */
1318 if (!options
->TrackHostExits
||
1319 addressmap_have_mapping(conn
->socks_request
->address
,
1320 options
->TrackHostExitsExpire
))
1321 return; /* nothing to track, or already mapped */
1323 SMARTLIST_FOREACH(options
->TrackHostExits
, const char *, cp
, {
1324 if (cp
[0] == '.') { /* match end */
1325 if (cp
[1] == '\0' ||
1326 !strcasecmpend(conn
->socks_request
->address
, cp
) ||
1327 !strcasecmp(conn
->socks_request
->address
, &cp
[1]))
1329 } else if (strcasecmp(cp
, conn
->socks_request
->address
) == 0) {
1334 if (!found_needle
|| !circ
->build_state
->chosen_exit
)
1337 /* write down the fingerprint of the chosen exit, not the nickname,
1338 * because the chosen exit might not be named. */
1339 base16_encode(fp
, sizeof(fp
),
1340 circ
->build_state
->chosen_exit
->identity_digest
, DIGEST_LEN
);
1342 /* Add this exit/hostname pair to the addressmap. */
1343 len
= strlen(conn
->socks_request
->address
) + 1 /* '.' */ +
1344 strlen(fp
) + 1 /* '.' */ +
1345 strlen("exit") + 1 /* '\0' */;
1346 new_address
= tor_malloc(len
);
1348 tor_snprintf(new_address
, len
, "%s.%s.exit",
1349 conn
->socks_request
->address
, fp
);
1351 addressmap_register(conn
->socks_request
->address
, new_address
,
1352 time(NULL
) + options
->TrackHostExitsExpire
,
1353 ADDRMAPSRC_TRACKEXIT
);
1356 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
1357 * begin or resolve cell as appropriate. Return values are as for
1358 * connection_ap_handshake_attach_circuit. The stream will exit from the hop
1359 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1360 * <b>cpath</b> is NULL. */
1362 connection_ap_handshake_attach_chosen_circuit(edge_connection_t
*conn
,
1363 origin_circuit_t
*circ
,
1364 crypt_path_t
*cpath
)
1367 tor_assert(conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
||
1368 conn
->_base
.state
== AP_CONN_STATE_CONTROLLER_WAIT
);
1369 tor_assert(conn
->socks_request
);
1371 tor_assert(circ
->_base
.state
== CIRCUIT_STATE_OPEN
);
1373 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1375 if (!circ
->_base
.timestamp_dirty
)
1376 circ
->_base
.timestamp_dirty
= time(NULL
);
1378 link_apconn_to_circ(conn
, circ
, cpath
);
1379 tor_assert(conn
->socks_request
);
1380 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
1381 if (!conn
->use_begindir
)
1382 consider_recording_trackhost(conn
, circ
);
1383 if (connection_ap_handshake_send_begin(conn
) < 0)
1386 if (connection_ap_handshake_send_resolve(conn
) < 0)
1393 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1394 * we don't find one: if conn cannot be handled by any known nodes,
1395 * warn and return -1 (conn needs to die, and is maybe already marked);
1396 * else launch new circuit (if necessary) and return 0.
1397 * Otherwise, associate conn with a safe live circuit, do the
1398 * right next step, and return 1.
1400 /* XXXX this function should mark for close whenever it returns -1;
1401 * its callers shouldn't have to worry about that. */
1403 connection_ap_handshake_attach_circuit(edge_connection_t
*conn
)
1410 tor_assert(conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1411 tor_assert(conn
->socks_request
);
1412 want_onehop
= conn
->want_onehop
;
1414 conn_age
= (int)(time(NULL
) - conn
->_base
.timestamp_created
);
1416 if (conn_age
>= get_options()->SocksTimeout
) {
1417 int severity
= (tor_addr_is_null(&conn
->_base
.addr
) && !conn
->_base
.port
) ?
1418 LOG_INFO
: LOG_NOTICE
;
1419 log_fn(severity
, LD_APP
,
1420 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1421 conn_age
, safe_str(conn
->socks_request
->address
),
1422 conn
->socks_request
->port
);
1426 if (!connection_edge_is_rendezvous_stream(conn
)) { /* we're a general conn */
1427 origin_circuit_t
*circ
=NULL
;
1429 if (conn
->chosen_exit_name
) {
1430 routerinfo_t
*router
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1431 int opt
= conn
->chosen_exit_optional
;
1432 if (!router
&& !want_onehop
) {
1433 /* We ran into this warning when trying to extend a circuit to a
1434 * hidden service directory for which we didn't have a router
1435 * descriptor. See flyspray task 767 for more details. We should
1436 * keep this in mind when deciding to use BEGIN_DIR cells for other
1437 * directory requests as well. -KL*/
1438 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1439 "Requested exit point '%s' is not known. %s.",
1440 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1442 conn
->chosen_exit_optional
= 0;
1443 tor_free(conn
->chosen_exit_name
);
1448 if (router
&& !connection_ap_can_use_exit(conn
, router
)) {
1449 log_fn(opt
? LOG_INFO
: LOG_WARN
, LD_APP
,
1450 "Requested exit point '%s' would refuse request. %s.",
1451 conn
->chosen_exit_name
, opt
? "Trying others" : "Closing");
1453 conn
->chosen_exit_optional
= 0;
1454 tor_free(conn
->chosen_exit_name
);
1461 /* find the circuit that we should use, if there is one. */
1462 retval
= circuit_get_open_circ_or_launch(
1463 conn
, CIRCUIT_PURPOSE_C_GENERAL
, &circ
);
1464 if (retval
< 1) // XXX021 if we totally fail, this still returns 0 -RD
1467 log_debug(LD_APP
|LD_CIRC
,
1468 "Attaching apconn to circ %d (stream %d sec old).",
1469 circ
->_base
.n_circ_id
, conn_age
);
1470 /* print the circ's path, so people can figure out which circs are
1472 circuit_log_path(LOG_INFO
,LD_APP
|LD_CIRC
,circ
);
1474 /* We have found a suitable circuit for our conn. Hurray. */
1475 return connection_ap_handshake_attach_chosen_circuit(conn
, circ
, NULL
);
1477 } else { /* we're a rendezvous conn */
1478 origin_circuit_t
*rendcirc
=NULL
, *introcirc
=NULL
;
1480 tor_assert(!conn
->cpath_layer
);
1482 /* start by finding a rendezvous circuit for us */
1484 retval
= circuit_get_open_circ_or_launch(
1485 conn
, CIRCUIT_PURPOSE_C_REND_JOINED
, &rendcirc
);
1486 if (retval
< 0) return -1; /* failed */
1489 tor_assert(rendcirc
);
1490 /* one is already established, attach */
1492 "rend joined circ %d already here. attaching. "
1493 "(stream %d sec old)",
1494 rendcirc
->_base
.n_circ_id
, conn_age
);
1495 /* Mark rendezvous circuits as 'newly dirty' every time you use
1496 * them, since the process of rebuilding a rendezvous circ is so
1497 * expensive. There is a tradeoff between linkability and
1498 * feasibility, at this point.
1500 rendcirc
->_base
.timestamp_dirty
= time(NULL
);
1501 link_apconn_to_circ(conn
, rendcirc
, NULL
);
1502 if (connection_ap_handshake_send_begin(conn
) < 0)
1503 return 0; /* already marked, let them fade away */
1507 if (rendcirc
&& (rendcirc
->_base
.purpose
==
1508 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
)) {
1510 "pending-join circ %d already here, with intro ack. "
1511 "Stalling. (stream %d sec old)",
1512 rendcirc
->_base
.n_circ_id
, conn_age
);
1516 /* it's on its way. find an intro circ. */
1517 retval
= circuit_get_open_circ_or_launch(
1518 conn
, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
, &introcirc
);
1519 if (retval
< 0) return -1; /* failed */
1522 /* one has already sent the intro. keep waiting. */
1523 circuit_t
*c
= NULL
;
1524 tor_assert(introcirc
);
1525 log_info(LD_REND
, "Intro circ %d present and awaiting ack (rend %d). "
1526 "Stalling. (stream %d sec old)",
1527 introcirc
->_base
.n_circ_id
,
1528 rendcirc
? rendcirc
->_base
.n_circ_id
: 0,
1530 /* abort parallel intro circs, if any */
1531 for (c
= global_circuitlist
; c
; c
= c
->next
) {
1532 if (c
->purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
&&
1533 !c
->marked_for_close
&& CIRCUIT_IS_ORIGIN(c
)) {
1534 origin_circuit_t
*oc
= TO_ORIGIN_CIRCUIT(c
);
1535 if (oc
->rend_data
&&
1536 !rend_cmp_service_ids(conn
->rend_data
->onion_address
,
1537 oc
->rend_data
->onion_address
)) {
1538 log_info(LD_REND
|LD_CIRC
, "Closing introduction circuit that we "
1539 "built in parallel.");
1540 circuit_mark_for_close(c
, END_CIRC_REASON_TIMEOUT
);
1547 /* now rendcirc and introcirc are each either undefined or not finished */
1549 if (rendcirc
&& introcirc
&&
1550 rendcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_REND_READY
) {
1552 "ready rend circ %d already here (no intro-ack yet on "
1553 "intro %d). (stream %d sec old)",
1554 rendcirc
->_base
.n_circ_id
,
1555 introcirc
->_base
.n_circ_id
, conn_age
);
1557 tor_assert(introcirc
->_base
.purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
1558 if (introcirc
->_base
.state
== CIRCUIT_STATE_OPEN
) {
1559 log_info(LD_REND
,"found open intro circ %d (rend %d); sending "
1560 "introduction. (stream %d sec old)",
1561 introcirc
->_base
.n_circ_id
, rendcirc
->_base
.n_circ_id
,
1563 if (rend_client_send_introduction(introcirc
, rendcirc
) < 0) {
1566 rendcirc
->_base
.timestamp_dirty
= time(NULL
);
1567 introcirc
->_base
.timestamp_dirty
= time(NULL
);
1568 assert_circuit_ok(TO_CIRCUIT(rendcirc
));
1569 assert_circuit_ok(TO_CIRCUIT(introcirc
));
1574 log_info(LD_REND
, "Intro (%d) and rend (%d) circs are not both ready. "
1575 "Stalling conn. (%d sec old)",
1576 introcirc
? introcirc
->_base
.n_circ_id
: 0,
1577 rendcirc
? rendcirc
->_base
.n_circ_id
: 0, conn_age
);