1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char circuituse_c_id
[] =
11 * \brief Launch the right sort of circuits and attach streams to them.
16 /** Longest time to wait for a circuit before closing an AP connection */
17 #define CONN_AP_MAX_ATTACH_DELAY 59
19 /********* START VARIABLES **********/
21 extern circuit_t
*global_circuitlist
; /* from circuitlist.c */
23 /********* END VARIABLES ************/
25 static void circuit_expire_old_circuits(void);
26 static void circuit_increment_failure_count(void);
28 /* Return 1 if <b>circ</b> could be returned by circuit_get_best().
32 circuit_is_acceptable(circuit_t
*circ
, connection_t
*conn
,
33 int must_be_open
, uint8_t purpose
,
34 int need_uptime
, int need_internal
,
37 routerinfo_t
*exitrouter
;
40 tor_assert(conn
->socks_request
);
42 if (!CIRCUIT_IS_ORIGIN(circ
))
43 return 0; /* this circ doesn't start at us */
44 if (must_be_open
&& (circ
->state
!= CIRCUIT_STATE_OPEN
|| !circ
->n_conn
))
45 return 0; /* ignore non-open circs */
46 if (circ
->marked_for_close
)
49 /* if this circ isn't our purpose, skip. */
50 if (purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
&& !must_be_open
) {
51 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_ESTABLISH_REND
&&
52 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_READY
&&
53 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
&&
54 circ
->purpose
!= CIRCUIT_PURPOSE_C_REND_JOINED
)
56 } else if (purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
&&
58 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCING
&&
59 circ
->purpose
!= CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
62 if (purpose
!= circ
->purpose
)
66 if (purpose
== CIRCUIT_PURPOSE_C_GENERAL
)
67 if (circ
->timestamp_dirty
&&
68 circ
->timestamp_dirty
+get_options()->MaxCircuitDirtiness
<= now
)
71 /* decide if this circ is suitable for this conn */
73 /* for rend circs, circ->cpath->prev is not the last router in the
74 * circuit, it's the magical extra bob hop. so just check the nickname
75 * of the one we meant to finish at.
77 exitrouter
= build_state_get_exit_router(circ
->build_state
);
79 if (need_uptime
&& !circ
->build_state
->need_uptime
)
81 if (need_internal
!= circ
->build_state
->is_internal
)
84 if (purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
86 log_debug(LD_CIRC
,"Not considering circuit with unknown router.");
87 return 0; /* this circuit is screwed and doesn't know it yet,
88 * or is a rendezvous circuit. */
90 if (!connection_ap_can_use_exit(conn
, exitrouter
)) {
91 /* can't exit from this router */
94 } else { /* not general */
95 if (rend_cmp_service_ids(conn
->rend_query
, circ
->rend_query
)) {
96 /* this circ is not for this conn */
103 /* Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
104 * <b>purpose</b>, and return 0 otherwise. Used by circuit_get_best.
107 circuit_is_better(circuit_t
*a
, circuit_t
*b
, uint8_t purpose
)
110 case CIRCUIT_PURPOSE_C_GENERAL
:
111 /* if it's used but less dirty it's best;
112 * else if it's more recently created it's best
114 if (b
->timestamp_dirty
) {
115 if (a
->timestamp_dirty
&&
116 a
->timestamp_dirty
> b
->timestamp_dirty
)
119 if (a
->timestamp_dirty
||
120 b
->build_state
->is_internal
||
121 a
->timestamp_created
> b
->timestamp_created
)
125 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
126 /* the closer it is to ack_wait the better it is */
127 if (a
->purpose
> b
->purpose
)
130 case CIRCUIT_PURPOSE_C_REND_JOINED
:
131 /* the closer it is to rend_joined the better it is */
132 if (a
->purpose
> b
->purpose
)
139 /** Find the best circ that conn can use, preferably one which is
140 * dirty. Circ must not be too old.
142 * Conn must be defined.
144 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
146 * circ_purpose specifies what sort of circuit we must have.
147 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
149 * If it's REND_JOINED and must_be_open==0, then return the closest
150 * rendezvous-purposed circuit that you can find.
152 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
153 * closest introduce-purposed circuit that you can find.
156 circuit_get_best(connection_t
*conn
, int must_be_open
, uint8_t purpose
,
157 int need_uptime
, int need_internal
)
159 circuit_t
*circ
, *best
=NULL
;
160 time_t now
= time(NULL
);
164 tor_assert(purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
165 purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
||
166 purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
);
168 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
169 if (!circuit_is_acceptable(circ
,conn
,must_be_open
,purpose
,
170 need_uptime
,need_internal
,now
))
173 /* now this is an acceptable circ to hand back. but that doesn't
174 * mean it's the *best* circ to hand back. try to decide.
176 if (!best
|| circuit_is_better(circ
,best
,purpose
))
183 /** If we find a circuit that isn't open yet and was born this many
184 * seconds ago, then assume something went wrong, and cull it.
186 #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 30
188 /** Close all circuits that start at us, aren't open, and were born
189 * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago.
192 circuit_expire_building(time_t now
)
194 circuit_t
*victim
, *circ
= global_circuitlist
;
195 time_t cutoff
= now
- MIN_SECONDS_BEFORE_EXPIRING_CIRC
;
200 if (!CIRCUIT_IS_ORIGIN(victim
) || /* didn't originate here */
201 victim
->timestamp_created
> cutoff
|| /* Not old enough to expire */
202 victim
->marked_for_close
) /* don't mess with marked circs */
206 /* some debug logs, to help track bugs */
207 if (victim
->purpose
>= CIRCUIT_PURPOSE_C_INTRODUCING
&&
208 victim
->purpose
<= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
) {
209 if (!victim
->timestamp_dirty
)
210 log_fn(LOG_DEBUG
,"Considering %sopen purp %d to %s (circid %d)."
212 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
213 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
216 log_fn(LOG_DEBUG
,"Considering %sopen purp %d to %s (circid %d). "
217 "%d secs since dirty.",
218 victim
->state
== CIRCUIT_STATE_OPEN
? "" : "non",
219 victim
->purpose
, victim
->build_state
->chosen_exit_name
,
221 (int)(now
- victim
->timestamp_dirty
));
225 /* if circ is !open, or if it's open but purpose is a non-finished
226 * intro or rend, then mark it for close */
227 if (victim
->state
== CIRCUIT_STATE_OPEN
) {
228 switch (victim
->purpose
) {
229 default: /* most open circuits can be left alone. */
230 continue; /* yes, continue inside a switch refers to the nearest
231 * enclosing loop. C is smart. */
232 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
233 case CIRCUIT_PURPOSE_C_INTRODUCING
:
234 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
235 break; /* too old, need to die */
236 case CIRCUIT_PURPOSE_C_REND_READY
:
237 /* it's a rend_ready circ -- has it already picked a query? */
238 /* c_rend_ready circs measure age since timestamp_dirty,
239 * because that's set when they switch purposes
241 if (!victim
->rend_query
[0] || victim
->timestamp_dirty
> cutoff
)
244 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
245 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
246 /* rend and intro circs become dirty each time they
247 * make an introduction attempt. so timestamp_dirty
248 * will reflect the time since the last attempt.
250 if (victim
->timestamp_dirty
> cutoff
)
257 log_info(LD_CIRC
,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
258 victim
->n_conn
->address
, victim
->n_port
, victim
->n_circ_id
,
259 victim
->state
, circuit_state_to_string(victim
->state
),
262 log_info(LD_CIRC
,"Abandoning circ %d (state %d:%s, purpose %d)",
263 victim
->n_circ_id
, victim
->state
,
264 circuit_state_to_string(victim
->state
), victim
->purpose
);
266 circuit_log_path(LOG_INFO
,LD_CIRC
,victim
);
267 circuit_mark_for_close(victim
, END_CIRC_AT_ORIGIN
);
271 /** Remove any elements in <b>needed_ports</b> that are handled by an
272 * open or in-progress circuit.
275 circuit_remove_handled_ports(smartlist_t
*needed_ports
)
280 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
281 port
= smartlist_get(needed_ports
, i
);
283 if (circuit_stream_is_being_handled(NULL
, *port
, 2)) {
284 // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
285 smartlist_del(needed_ports
, i
--);
288 log_debug(LD_CIRC
,"Port %d is not handled.", *port
);
293 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
294 * will have an acceptable exit node for exit stream <b>conn</b> if it
295 * is defined, else for "*:port".
299 circuit_stream_is_being_handled(connection_t
*conn
, uint16_t port
, int min
)
302 routerinfo_t
*exitrouter
;
304 time_t now
= time(NULL
);
305 int need_uptime
= smartlist_string_num_isin(get_options()->LongLivedPorts
,
306 conn
? conn
->socks_request
->port
: port
);
308 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
309 if (CIRCUIT_IS_ORIGIN(circ
) &&
310 !circ
->marked_for_close
&&
311 circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
&&
312 !circ
->build_state
->is_internal
&&
313 (!circ
->timestamp_dirty
||
314 circ
->timestamp_dirty
+ get_options()->MaxCircuitDirtiness
> now
)) {
315 exitrouter
= build_state_get_exit_router(circ
->build_state
);
317 (!need_uptime
|| circ
->build_state
->need_uptime
)) {
320 ok
= connection_ap_can_use_exit(conn
, exitrouter
);
322 addr_policy_result_t r
= router_compare_addr_to_addr_policy(
323 0, port
, exitrouter
->exit_policy
);
324 ok
= r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
;
336 /** Don't keep more than this many unused open circuits around. */
337 #define MAX_UNUSED_OPEN_CIRCUITS 12
339 /** Figure out how many circuits we have open that are clean. Make
340 * sure it's enough for all the upcoming behaviors we predict we'll have.
341 * But if we have too many, close the not-so-useful ones.
344 circuit_predict_and_launch_new(void)
347 int num
=0, num_internal
=0, num_uptime_internal
=0;
348 int hidserv_needs_uptime
=0, hidserv_needs_capacity
=1;
349 int port_needs_uptime
=0, port_needs_capacity
=1;
350 time_t now
= time(NULL
);
352 /* First, count how many of each type of circuit we have already. */
353 for (circ
=global_circuitlist
;circ
;circ
= circ
->next
) {
354 if (!CIRCUIT_IS_ORIGIN(circ
))
356 if (circ
->marked_for_close
)
357 continue; /* don't mess with marked circs */
358 if (circ
->timestamp_dirty
)
359 continue; /* only count clean circs */
360 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
361 continue; /* only pay attention to general-purpose circs */
363 if (circ
->build_state
->is_internal
)
365 if (circ
->build_state
->need_uptime
&& circ
->build_state
->is_internal
)
366 num_uptime_internal
++;
369 /* If that's enough, then stop now. */
370 if (num
>= MAX_UNUSED_OPEN_CIRCUITS
)
371 return; /* we already have many, making more probably will hurt */
373 /* Second, see if we need any more exit circuits. */
374 /* check if we know of a port that's been requested recently
375 * and no circuit is currently available that can handle it. */
376 if (!circuit_all_predicted_ports_handled(now
, &port_needs_uptime
,
377 &port_needs_capacity
)) {
379 "Have %d clean circs (%d internal), need another exit circ.",
381 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
,
382 port_needs_uptime
, port_needs_capacity
, 0);
386 /* Third, see if we need any more hidden service (server) circuits. */
387 if (num_rend_services() && num_uptime_internal
< 3) {
389 "Have %d clean circs (%d internal), need another internal "
390 "circ for my hidden service.",
392 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
,
397 /* Fourth, see if we need any more hidden service (client) circuits. */
398 if (rep_hist_get_predicted_internal(now
, &hidserv_needs_uptime
,
399 &hidserv_needs_capacity
) &&
400 ((num_uptime_internal
<2 && hidserv_needs_uptime
) ||
403 "Have %d clean circs (%d uptime-internal, %d internal), need"
404 " another hidserv circ.",
405 num
, num_uptime_internal
, num_internal
);
406 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
,
407 hidserv_needs_uptime
, hidserv_needs_capacity
, 1);
412 /** Build a new test circuit every 5 minutes */
413 #define TESTING_CIRCUIT_INTERVAL 300
415 /** This function is called once a second. Its job is to make sure
416 * all services we offer have enough circuits available. Some
417 * services just want enough circuits for current tasks, whereas
418 * others want a minimum set of idle circuits hanging around.
421 circuit_build_needed_circs(time_t now
)
423 static long time_to_new_circuit
= 0;
425 /* launch a new circ for any pending streams that need one */
426 connection_ap_attach_pending();
428 /* make sure any hidden services have enough intro points */
429 if (router_have_minimum_dir_info())
430 rend_services_introduce();
432 if (time_to_new_circuit
< now
) {
433 circuit_reset_failure_count(1);
434 time_to_new_circuit
= now
+ get_options()->NewCircuitPeriod
;
435 if (proxy_mode(get_options()))
436 addressmap_clean(now
);
437 circuit_expire_old_circuits();
439 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
440 circ
= circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL
);
441 if (get_options()->RunTesting
&&
443 circ
->timestamp_created
+ TESTING_CIRCUIT_INTERVAL
< now
) {
444 log_fn(LOG_INFO
,"Creating a new testing circuit.");
445 circuit_launch_by_router(CIRCUIT_PURPOSE_C_GENERAL
, NULL
, 0, 0, 0);
449 circuit_predict_and_launch_new();
452 /** If the stream <b>conn</b> is a member of any of the linked
453 * lists of <b>circ</b>, then remove it from the list.
456 circuit_detach_stream(circuit_t
*circ
, connection_t
*conn
)
458 connection_t
*prevconn
;
463 conn
->cpath_layer
= NULL
; /* make sure we don't keep a stale pointer */
464 conn
->on_circuit
= NULL
;
466 if (conn
== circ
->p_streams
) {
467 circ
->p_streams
= conn
->next_stream
;
470 if (conn
== circ
->n_streams
) {
471 circ
->n_streams
= conn
->next_stream
;
474 if (conn
== circ
->resolving_streams
) {
475 circ
->resolving_streams
= conn
->next_stream
;
479 for (prevconn
= circ
->p_streams
;
480 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
481 prevconn
= prevconn
->next_stream
)
483 if (prevconn
&& prevconn
->next_stream
) {
484 prevconn
->next_stream
= conn
->next_stream
;
488 for (prevconn
= circ
->n_streams
;
489 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
490 prevconn
= prevconn
->next_stream
)
492 if (prevconn
&& prevconn
->next_stream
) {
493 prevconn
->next_stream
= conn
->next_stream
;
497 for (prevconn
= circ
->resolving_streams
;
498 prevconn
&& prevconn
->next_stream
&& prevconn
->next_stream
!= conn
;
499 prevconn
= prevconn
->next_stream
)
501 if (prevconn
&& prevconn
->next_stream
) {
502 prevconn
->next_stream
= conn
->next_stream
;
506 log_err(LD_BUG
,"edge conn not in circuit's list?");
507 tor_assert(0); /* should never get here */
510 /** Notify the global circuit list that <b>conn</b> is about to be
511 * removed and then freed.
513 * If it's an OR conn, then mark-for-close all the circuits that use
516 * If it's an edge conn, then detach it from its circ, so we don't
517 * try to reference it later.
520 circuit_about_to_close_connection(connection_t
*conn
)
522 /* currently, we assume it's too late to flush conn's buf here.
523 * down the road, maybe we'll consider that eof doesn't mean can't-write
525 switch (conn
->type
) {
527 /* Inform any pending (not attached) circs that they should give up. */
528 circuit_n_conn_done(conn
, 0);
529 /* Now close all the attached circuits on it. */
530 circuit_unlink_all_from_or_conn(conn
, END_CIRC_REASON_OR_CONN_CLOSED
);
534 case CONN_TYPE_EXIT
: {
536 /* It's an edge conn. Need to remove it from the linked list of
537 * conn's for this circuit. Confirm that 'end' relay command has
538 * been sent. But don't kill the circuit.
541 circ
= circuit_get_by_edge_conn(conn
);
545 circuit_detach_stream(circ
, conn
);
550 /** How old do we let an unused circuit get before expiring it? */
551 #define CIRCUIT_UNUSED_CIRC_TIMEOUT (60*60)
553 /** Find each circuit that has been dirty for too long, and has
554 * no streams on it: mark it for close.
557 circuit_expire_old_circuits(void)
560 time_t now
= time(NULL
);
562 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
563 if (circ
->marked_for_close
)
565 /* If the circuit has been dirty for too long, and there are no streams
566 * on it, mark it for close.
568 if (circ
->timestamp_dirty
&&
569 circ
->timestamp_dirty
+ get_options()->MaxCircuitDirtiness
< now
&&
570 CIRCUIT_IS_ORIGIN(circ
) &&
571 !circ
->p_streams
/* nothing attached */ ) {
572 log_debug(LD_CIRC
, "Closing n_circ_id %d (dirty %d secs ago, purp %d)",
573 circ
->n_circ_id
, (int)(now
- circ
->timestamp_dirty
),
575 /* (only general and purpose_c circs can get dirty) */
576 tor_assert(!circ
->n_streams
);
577 tor_assert(circ
->purpose
<= CIRCUIT_PURPOSE_C_REND_JOINED
);
578 circuit_mark_for_close(circ
, END_CIRC_AT_ORIGIN
);
579 } else if (!circ
->timestamp_dirty
&& CIRCUIT_IS_ORIGIN(circ
) &&
580 circ
->state
== CIRCUIT_STATE_OPEN
&&
581 circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
582 if (circ
->timestamp_created
+ CIRCUIT_UNUSED_CIRC_TIMEOUT
< now
) {
584 "Closing circuit that has been unused for %d seconds.",
585 (int)(now
- circ
->timestamp_created
));
586 circuit_mark_for_close(circ
, END_CIRC_AT_ORIGIN
);
592 /** A testing circuit has completed. Take whatever stats we want. */
594 circuit_testing_opened(circuit_t
*circ
)
596 /* For now, we only use testing circuits to see if our ORPort is
597 reachable. But we remember reachability in onionskin_answer(),
598 so there's no need to record anything here. Just close the circ. */
599 circuit_mark_for_close(circ
, END_CIRC_AT_ORIGIN
);
602 /** A testing circuit has failed to build. Take whatever stats we want. */
604 circuit_testing_failed(circuit_t
*circ
, int at_last_hop
)
607 routerinfo_t
*me
= router_get_my_routerinfo();
610 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, me
, 0, 1, 1);
614 "Our testing circuit (to see if your ORPort is reachable) "
615 "has failed. I'll try again later.");
618 /** The circuit <b>circ</b> has just become open. Take the next
619 * step: for rendezvous circuits, we pass circ to the appropriate
620 * function in rendclient or rendservice. For general circuits, we
621 * call connection_ap_attach_pending, which looks for pending streams
622 * that could use circ.
625 circuit_has_opened(circuit_t
*circ
)
627 control_event_circuit_status(circ
, CIRC_EVENT_BUILT
);
629 switch (circ
->purpose
) {
630 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
631 rend_client_rendcirc_has_opened(circ
);
632 connection_ap_attach_pending();
634 case CIRCUIT_PURPOSE_C_INTRODUCING
:
635 rend_client_introcirc_has_opened(circ
);
637 case CIRCUIT_PURPOSE_C_GENERAL
:
638 /* Tell any AP connections that have been waiting for a new
639 * circuit that one is ready. */
640 connection_ap_attach_pending();
642 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
643 /* at Bob, waiting for introductions */
644 rend_service_intro_has_opened(circ
);
646 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
647 /* at Bob, connecting to rend point */
648 rend_service_rendezvous_has_opened(circ
);
650 case CIRCUIT_PURPOSE_TESTING
:
651 circuit_testing_opened(circ
);
654 log_err(LD_BUG
,"unhandled purpose %d",circ
->purpose
);
659 /** Called whenever a circuit could not be successfully built.
662 circuit_build_failed(circuit_t
*circ
)
664 /* we should examine circ and see if it failed because of
665 * the last hop or an earlier hop. then use this info below.
667 int failed_at_last_hop
= 0;
668 /* If the last hop isn't open, and the second-to-last is, we failed
669 * at the last hop. */
671 circ
->cpath
->prev
->state
!= CPATH_STATE_OPEN
&&
672 circ
->cpath
->prev
->prev
->state
== CPATH_STATE_OPEN
) {
673 failed_at_last_hop
= 1;
676 circ
->cpath
->state
!= CPATH_STATE_OPEN
) {
677 /* We failed at the first hop. If there's an OR connection
678 to blame, blame it. */
679 connection_t
*n_conn
= NULL
;
681 n_conn
= circ
->n_conn
;
682 } else if (circ
->state
== CIRCUIT_STATE_OR_WAIT
) {
683 /* we have to hunt for it */
684 n_conn
= connection_or_get_by_identity_digest(circ
->n_conn_id_digest
);
688 "Our circuit failed to get a response from the first hop "
689 "(%s:%d). I'm going to try to rotate to a better connection.",
690 n_conn
->address
, n_conn
->port
);
691 n_conn
->is_obsolete
= 1;
692 entry_guard_set_status(n_conn
->identity_digest
, 0);
696 switch (circ
->purpose
) {
697 case CIRCUIT_PURPOSE_C_GENERAL
:
698 if (circ
->state
!= CIRCUIT_STATE_OPEN
) {
699 /* If we never built the circuit, note it as a failure. */
700 /* Note that we can't just check circ->cpath here, because if
701 * circuit-building failed immediately, it won't be set yet. */
702 circuit_increment_failure_count();
705 case CIRCUIT_PURPOSE_TESTING
:
706 circuit_testing_failed(circ
, failed_at_last_hop
);
708 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
709 /* at Bob, waiting for introductions */
710 if (circ
->state
!= CIRCUIT_STATE_OPEN
) {
711 circuit_increment_failure_count();
713 /* no need to care here, because bob will rebuild intro
714 * points periodically. */
716 case CIRCUIT_PURPOSE_C_INTRODUCING
:
717 /* at Alice, connecting to intro point */
718 /* Don't increment failure count, since Bob may have picked
719 * the introduction point maliciously */
720 /* Alice will pick a new intro point when this one dies, if
721 * the stream in question still cares. No need to act here. */
723 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
724 /* at Alice, waiting for Bob */
725 if (circ
->state
!= CIRCUIT_STATE_OPEN
) {
726 circuit_increment_failure_count();
728 /* Alice will pick a new rend point when this one dies, if
729 * the stream in question still cares. No need to act here. */
731 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
732 /* at Bob, connecting to rend point */
733 /* Don't increment failure count, since Alice may have picked
734 * the rendezvous point maliciously */
736 "Couldn't connect to Alice's chosen rend point %s "
738 escaped(build_state_get_exit_nickname(circ
->build_state
)),
739 failed_at_last_hop
?"last":"non-last");
740 rend_service_relaunch_rendezvous(circ
);
743 /* Other cases are impossible, since this function is only called with
744 * unbuilt circuits. */
749 /** Number of consecutive failures so far; should only be touched by
750 * circuit_launch_new and circuit_*_failure_count.
752 static int n_circuit_failures
= 0;
753 static int did_circs_fail_last_period
= 0;
755 /** Don't retry launching a new circuit if we try this many times with no
757 #define MAX_CIRCUIT_FAILURES 5
759 /** Launch a new circuit; see circuit_launch_by_extend_info() for
760 * details on arguments. */
762 circuit_launch_by_router(uint8_t purpose
, routerinfo_t
*exit
,
763 int need_uptime
, int need_capacity
, int internal
)
766 extend_info_t
*info
= NULL
;
768 info
= extend_info_from_router(exit
);
769 circ
= circuit_launch_by_extend_info(
770 purpose
, info
, need_uptime
, need_capacity
, internal
);
772 extend_info_free(info
);
776 /** Launch a new circuit with purpose <b>purpose</b> and exit node <b>info</b>
777 * (or NULL to select a random exit node). If <b>need_uptime</b> is true,
778 * choose among routers with high uptime. If <b>need_capacity</b> is true,
779 * choose among routers with high bandwidth. If <b>internal</b> is true, the
780 * last hop need not be an exit node. Return the newly allocated circuit on
781 * success, or NULL on failure. */
783 circuit_launch_by_extend_info(uint8_t purpose
, extend_info_t
*extend_info
,
784 int need_uptime
, int need_capacity
, int internal
)
788 if (!router_have_minimum_dir_info()) {
789 log_debug(LD_CIRC
,"Haven't fetched enough directory info yet; canceling "
794 if ((extend_info
|| purpose
!= CIRCUIT_PURPOSE_C_GENERAL
) &&
795 purpose
!= CIRCUIT_PURPOSE_TESTING
) {
796 /* see if there are appropriate circs available to cannibalize. */
797 circ
= circuit_find_to_cannibalize(CIRCUIT_PURPOSE_C_GENERAL
, extend_info
,
798 need_uptime
, need_capacity
, internal
);
800 log_info(LD_CIRC
,"Cannibalizing circ '%s' for purpose %d",
801 build_state_get_exit_nickname(circ
->build_state
), purpose
);
802 circ
->purpose
= purpose
;
803 /* reset the birth date of this circ, else expire_building
804 * will see it and think it's been trying to build since it
806 circ
->timestamp_created
= time(NULL
);
808 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
809 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
810 /* it's ready right now */
812 case CIRCUIT_PURPOSE_C_INTRODUCING
:
813 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
814 case CIRCUIT_PURPOSE_C_GENERAL
:
815 /* need to add a new hop */
816 tor_assert(extend_info
);
817 if (circuit_extend_to_new_exit(circ
, extend_info
) < 0)
822 "Bug: unexpected purpose %d when cannibalizing a circ.",
824 tor_fragile_assert();
831 if (did_circs_fail_last_period
&&
832 n_circuit_failures
> MAX_CIRCUIT_FAILURES
) {
833 /* too many failed circs in a row. don't try. */
834 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
838 /* try a circ. if it fails, circuit_mark_for_close will increment
839 * n_circuit_failures */
840 return circuit_establish_circuit(purpose
, extend_info
,
841 need_uptime
, need_capacity
, internal
);
844 /** Launch a new circuit; see circuit_launch_by_extend_info() for
845 * details on arguments. */
847 circuit_launch_by_nickname(uint8_t purpose
, const char *exit_nickname
,
848 int need_uptime
, int need_capacity
, int internal
)
850 routerinfo_t
*router
= NULL
;
853 router
= router_get_by_nickname(exit_nickname
, 1);
856 log_warn(LD_GENERAL
, "No such OR as '%s'", exit_nickname
);
860 return circuit_launch_by_router(purpose
, router
,
861 need_uptime
, need_capacity
, internal
);
864 /** Record another failure at opening a general circuit. When we have
865 * too many, we'll stop trying for the remainder of this minute.
868 circuit_increment_failure_count(void)
870 ++n_circuit_failures
;
871 log_debug(LD_CIRC
,"n_circuit_failures now %d.",n_circuit_failures
);
874 /** Reset the failure count for opening general circuits. This means
875 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
879 circuit_reset_failure_count(int timeout
)
881 if (timeout
&& n_circuit_failures
> MAX_CIRCUIT_FAILURES
)
882 did_circs_fail_last_period
= 1;
884 did_circs_fail_last_period
= 0;
885 n_circuit_failures
= 0;
888 /** Find an open circ that we're happy with: return 1. If there isn't
889 * one, and there isn't one on the way, launch one and return 0. If it
890 * will never work, return -1.
892 * Write the found or in-progress or launched circ into *circp.
895 circuit_get_open_circ_or_launch(connection_t
*conn
,
896 uint8_t desired_circuit_purpose
,
901 int need_uptime
, need_internal
;
905 tor_assert(conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
906 is_resolve
= conn
->socks_request
->command
== SOCKS_COMMAND_RESOLVE
;
908 need_uptime
= smartlist_string_num_isin(get_options()->LongLivedPorts
,
909 conn
->socks_request
->port
);
910 need_internal
= desired_circuit_purpose
!= CIRCUIT_PURPOSE_C_GENERAL
;
912 circ
= circuit_get_best(conn
, 1, desired_circuit_purpose
,
913 need_uptime
, need_internal
);
917 return 1; /* we're happy */
920 if (!router_have_minimum_dir_info()) {
921 if (!connection_get_by_type(CONN_TYPE_DIR
)) {
922 log_notice(LD_APP
|LD_DIR
,
923 "Application request when we're believed to be "
924 "offline. Optimistically trying directory fetches again.");
925 router_reset_status_download_failures();
926 router_reset_descriptor_download_failures();
927 update_networkstatus_downloads(time(NULL
));
928 update_router_descriptor_downloads(time(NULL
));
930 /* the stream will be dealt with when router_have_minimum_dir_info becomes
931 * 1, or when all directory attempts fail and directory_all_unreachable()
937 /* Do we need to check exit policy? */
938 if (!is_resolve
&& !connection_edge_is_rendezvous_stream(conn
)) {
941 if (tor_inet_aton(conn
->socks_request
->address
, &in
))
942 addr
= ntohl(in
.s_addr
);
943 if (router_exit_policy_all_routers_reject(addr
, conn
->socks_request
->port
,
946 "No Tor server exists that allows exit to %s:%d. Rejecting.",
947 safe_str(conn
->socks_request
->address
),
948 conn
->socks_request
->port
);
953 /* is one already on the way? */
954 circ
= circuit_get_best(conn
, 0, desired_circuit_purpose
,
955 need_uptime
, need_internal
);
957 extend_info_t
*extend_info
=NULL
;
958 uint8_t new_circ_purpose
;
960 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
) {
961 /* need to pick an intro point */
962 extend_info
= rend_client_get_random_intro(conn
->rend_query
);
965 "No intro points for '%s': refetching service descriptor.",
966 safe_str(conn
->rend_query
));
967 rend_client_refetch_renddesc(conn
->rend_query
);
968 conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
971 log_info(LD_REND
,"Chose '%s' as intro point for '%s'.",
972 extend_info
->nickname
, safe_str(conn
->rend_query
));
975 /* If we have specified a particular exit node for our
976 * connection, then be sure to open a circuit to that exit node.
978 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_GENERAL
) {
979 if (conn
->chosen_exit_name
) {
981 if (!(r
= router_get_by_nickname(conn
->chosen_exit_name
, 1))) {
984 "Requested exit point '%s' is not known. Closing.",
985 conn
->chosen_exit_name
);
988 extend_info
= extend_info_from_router(r
);
992 if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
)
993 new_circ_purpose
= CIRCUIT_PURPOSE_C_ESTABLISH_REND
;
994 else if (desired_circuit_purpose
== CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
)
995 new_circ_purpose
= CIRCUIT_PURPOSE_C_INTRODUCING
;
997 new_circ_purpose
= desired_circuit_purpose
;
999 circ
= circuit_launch_by_extend_info(
1000 new_circ_purpose
, extend_info
, need_uptime
, 1, need_internal
);
1002 extend_info_free(extend_info
);
1004 if (desired_circuit_purpose
!= CIRCUIT_PURPOSE_C_GENERAL
) {
1005 /* help predict this next time */
1006 rep_hist_note_used_internal(time(NULL
), need_uptime
, 1);
1008 /* write the service_id into circ */
1009 strlcpy(circ
->rend_query
, conn
->rend_query
, sizeof(circ
->rend_query
));
1010 if (circ
->purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
&&
1011 circ
->state
== CIRCUIT_STATE_OPEN
)
1012 rend_client_rendcirc_has_opened(circ
);
1018 "No safe circuit (purpose %d) ready for edge "
1019 "connection; delaying.",
1020 desired_circuit_purpose
);
1025 /** Attach the AP stream <b>apconn</b> to circ's linked list of
1026 * p_streams. Also set apconn's cpath_layer to the last hop in
1030 link_apconn_to_circ(connection_t
*apconn
, circuit_t
*circ
)
1032 /* add it into the linked list of streams on this circuit */
1033 log_debug(LD_APP
|LD_CIRC
, "attaching new conn to circ. n_circ_id %d.",
1035 /* reset it, so we can measure circ timeouts */
1036 apconn
->timestamp_lastread
= time(NULL
);
1037 apconn
->next_stream
= circ
->p_streams
;
1038 apconn
->on_circuit
= circ
;
1039 /* assert_connection_ok(conn, time(NULL)); */
1040 circ
->p_streams
= apconn
;
1042 tor_assert(CIRCUIT_IS_ORIGIN(circ
));
1043 tor_assert(circ
->cpath
);
1044 tor_assert(circ
->cpath
->prev
);
1045 tor_assert(circ
->cpath
->prev
->state
== CPATH_STATE_OPEN
);
1046 apconn
->cpath_layer
= circ
->cpath
->prev
;
1049 /** If an exit wasn't specifically chosen, save the history for future
1052 consider_recording_trackhost(connection_t
*conn
, circuit_t
*circ
)
1054 int found_needle
= 0;
1056 or_options_t
*options
= get_options();
1059 char fp
[HEX_DIGEST_LEN
+1];
1061 /* Search the addressmap for this conn's destination. */
1062 /* If he's not in the address map.. */
1063 if (!options
->TrackHostExits
||
1064 addressmap_already_mapped(conn
->socks_request
->address
))
1065 return; /* nothing to track, or already mapped */
1067 SMARTLIST_FOREACH(options
->TrackHostExits
, const char *, cp
, {
1068 if (cp
[0] == '.') { /* match end */
1069 /* XXX strstr is probably really bad here */
1070 if ((str
= strstr(conn
->socks_request
->address
, &cp
[1]))) {
1071 if (str
== conn
->socks_request
->address
1072 || strcmp(str
, &cp
[1]) == 0) {
1076 } else if (strcmp(cp
, conn
->socks_request
->address
) == 0) {
1081 if (!found_needle
|| !circ
->build_state
->chosen_exit
)
1084 /* write down the fingerprint of the chosen exit, not the nickname,
1085 * because the chosen exit might not be verified. */
1086 base16_encode(fp
, sizeof(fp
),
1087 circ
->build_state
->chosen_exit
->identity_digest
, DIGEST_LEN
);
1089 /* Add this exit/hostname pair to the addressmap. */
1090 len
= strlen(conn
->socks_request
->address
) + 1 /* '.' */ +
1091 strlen(fp
) + 1 /* '.' */ +
1092 strlen("exit") + 1 /* '\0' */;
1093 new_address
= tor_malloc(len
);
1095 tor_snprintf(new_address
, len
, "%s.%s.exit",
1096 conn
->socks_request
->address
, fp
);
1098 addressmap_register(conn
->socks_request
->address
, new_address
,
1099 time(NULL
) + options
->TrackHostExitsExpire
);
1102 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and
1103 * send a begin or resolve cell as appropriate. Return values are as
1104 * for connection_ap_handshake_attach_circuit. */
1106 connection_ap_handshake_attach_chosen_circuit(connection_t
*conn
,
1110 tor_assert(conn
->type
== CONN_TYPE_AP
);
1111 tor_assert(conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
||
1112 conn
->state
== AP_CONN_STATE_CONTROLLER_WAIT
);
1113 tor_assert(conn
->socks_request
);
1115 tor_assert(circ
->state
== CIRCUIT_STATE_OPEN
);
1117 conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1119 if (!circ
->timestamp_dirty
)
1120 circ
->timestamp_dirty
= time(NULL
);
1122 link_apconn_to_circ(conn
, circ
);
1123 tor_assert(conn
->socks_request
);
1124 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
1125 consider_recording_trackhost(conn
, circ
);
1126 if (connection_ap_handshake_send_begin(conn
, circ
)<0)
1129 if (connection_ap_handshake_send_resolve(conn
, circ
)<0)
1136 /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
1137 * we don't find one: if conn cannot be handled by any known nodes,
1138 * warn and return -1 (conn needs to die);
1139 * else launch new circuit (if necessary) and return 0.
1140 * Otherwise, associate conn with a safe live circuit, do the
1141 * right next step, and return 1.
1144 connection_ap_handshake_attach_circuit(connection_t
*conn
)
1150 tor_assert(conn
->type
== CONN_TYPE_AP
);
1151 tor_assert(conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1152 tor_assert(conn
->socks_request
);
1154 conn_age
= time(NULL
) - conn
->timestamp_created
;
1155 if (conn_age
> CONN_AP_MAX_ATTACH_DELAY
) {
1157 "Tried for %d seconds to get a connection to %s:%d. Giving up.",
1158 conn_age
, safe_str(conn
->socks_request
->address
),
1159 conn
->socks_request
->port
);
1163 if (!connection_edge_is_rendezvous_stream(conn
)) { /* we're a general conn */
1164 circuit_t
*circ
=NULL
;
1166 if (conn
->chosen_exit_name
) {
1167 routerinfo_t
*router
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1170 "Requested exit point '%s' is not known. Closing.",
1171 conn
->chosen_exit_name
);
1174 if (!connection_ap_can_use_exit(conn
, router
)) {
1176 "Requested exit point '%s' would refuse request. Closing.",
1177 conn
->chosen_exit_name
);
1182 /* find the circuit that we should use, if there is one. */
1183 retval
= circuit_get_open_circ_or_launch(
1184 conn
, CIRCUIT_PURPOSE_C_GENERAL
, &circ
);
1188 log_debug(LD_APP
|LD_CIRC
,
1189 "Attaching apconn to circ %d (stream %d sec old).",
1190 circ
->n_circ_id
, conn_age
);
1191 /* here, print the circ's path. so people can figure out which circs are
1193 circuit_log_path(LOG_INFO
,LD_APP
|LD_CIRC
,circ
);
1195 /* We have found a suitable circuit for our conn. Hurray. */
1196 return connection_ap_handshake_attach_chosen_circuit(conn
, circ
);
1198 } else { /* we're a rendezvous conn */
1199 circuit_t
*rendcirc
=NULL
, *introcirc
=NULL
;
1201 tor_assert(!conn
->cpath_layer
);
1203 /* start by finding a rendezvous circuit for us */
1205 retval
= circuit_get_open_circ_or_launch(
1206 conn
, CIRCUIT_PURPOSE_C_REND_JOINED
, &rendcirc
);
1207 if (retval
< 0) return -1; /* failed */
1210 tor_assert(rendcirc
);
1211 /* one is already established, attach */
1213 "rend joined circ %d already here. attaching. "
1214 "(stream %d sec old)",
1215 rendcirc
->n_circ_id
, conn_age
);
1216 /* Mark rendezvous circuits as 'newly dirty' every time you use
1217 * them, since the process of rebuilding a rendezvous circ is so
1218 * expensive. There is a tradeoffs between linkability and
1219 * feasibility, at this point.
1221 rendcirc
->timestamp_dirty
= time(NULL
);
1222 link_apconn_to_circ(conn
, rendcirc
);
1223 if (connection_ap_handshake_send_begin(conn
, rendcirc
) < 0)
1224 return 0; /* already marked, let them fade away */
1228 if (rendcirc
&& (rendcirc
->purpose
==
1229 CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
)) {
1231 "pending-join circ %d already here, with intro ack. "
1232 "Stalling. (stream %d sec old)",
1233 rendcirc
->n_circ_id
, conn_age
);
1237 /* it's on its way. find an intro circ. */
1238 retval
= circuit_get_open_circ_or_launch(
1239 conn
, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
, &introcirc
);
1240 if (retval
< 0) return -1; /* failed */
1243 /* one has already sent the intro. keep waiting. */
1244 tor_assert(introcirc
);
1245 log_info(LD_REND
, "Intro circ %d present and awaiting ack (rend %d). "
1246 "Stalling. (stream %d sec old)",
1247 introcirc
->n_circ_id
, rendcirc
? rendcirc
->n_circ_id
: 0,
1252 /* now rendcirc and introcirc are each either undefined or not finished */
1254 if (rendcirc
&& introcirc
&&
1255 rendcirc
->purpose
== CIRCUIT_PURPOSE_C_REND_READY
) {
1257 "ready rend circ %d already here (no intro-ack yet on "
1258 "intro %d). (stream %d sec old)",
1259 rendcirc
->n_circ_id
, introcirc
->n_circ_id
, conn_age
);
1261 tor_assert(introcirc
->purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
1262 if (introcirc
->state
== CIRCUIT_STATE_OPEN
) {
1263 log_info(LD_REND
,"found open intro circ %d (rend %d); sending "
1264 "introduction. (stream %d sec old)",
1265 introcirc
->n_circ_id
, rendcirc
->n_circ_id
, conn_age
);
1266 if (rend_client_send_introduction(introcirc
, rendcirc
) < 0) {
1269 rendcirc
->timestamp_dirty
= time(NULL
);
1270 introcirc
->timestamp_dirty
= time(NULL
);
1271 assert_circuit_ok(rendcirc
);
1272 assert_circuit_ok(introcirc
);
1277 log_info(LD_REND
, "Intro (%d) and rend (%d) circs are not both ready. "
1278 "Stalling conn. (%d sec old)",
1279 introcirc
? introcirc
->n_circ_id
: 0,
1280 rendcirc
? rendcirc
->n_circ_id
: 0, conn_age
);