tor  0.4.0.1-alpha
circuituse.c
Go to the documentation of this file.
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-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
30 #include "core/or/or.h"
31 #include "app/config/config.h"
33 #include "core/or/channel.h"
34 #include "core/or/circuitbuild.h"
35 #include "core/or/circuitlist.h"
36 #include "core/or/circuitstats.h"
37 #include "core/or/circuituse.h"
38 #include "core/or/circuitpadding.h"
40 #include "core/or/policies.h"
41 #include "feature/client/addressmap.h"
42 #include "feature/client/bridges.h"
43 #include "feature/client/circpathbias.h"
47 #include "feature/hs/hs_circuit.h"
48 #include "feature/hs/hs_client.h"
49 #include "feature/hs/hs_common.h"
50 #include "feature/hs/hs_ident.h"
51 #include "feature/hs/hs_stats.h"
57 #include "feature/relay/selftest.h"
61 #include "feature/stats/predict_ports.h"
62 #include "lib/math/fp.h"
63 #include "lib/time/tvdiff.h"
64 
65 #include "core/or/cpath_build_state_st.h"
66 #include "feature/dircommon/dir_connection_st.h"
67 #include "core/or/entry_connection_st.h"
68 #include "core/or/extend_info_st.h"
69 #include "core/or/or_circuit_st.h"
70 #include "core/or/origin_circuit_st.h"
71 #include "core/or/socks_request_st.h"
72 
74 static void circuit_increment_failure_count(void);
75 
79 static int
81  const origin_circuit_t *origin_circ)
82 {
83  /* Check if this is a v2 rendezvous circ/stream */
84  if ((edge_conn->rend_data && !origin_circ->rend_data) ||
85  (!edge_conn->rend_data && origin_circ->rend_data) ||
86  (edge_conn->rend_data && origin_circ->rend_data &&
87  rend_cmp_service_ids(rend_data_get_address(edge_conn->rend_data),
88  rend_data_get_address(origin_circ->rend_data)))) {
89  /* this circ is not for this conn */
90  return 0;
91  }
92 
93  /* Check if this is a v3 rendezvous circ/stream */
94  if ((edge_conn->hs_ident && !origin_circ->hs_ident) ||
95  (!edge_conn->hs_ident && origin_circ->hs_ident) ||
96  (edge_conn->hs_ident && origin_circ->hs_ident &&
97  !ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
98  &origin_circ->hs_ident->identity_pk))) {
99  /* this circ is not for this conn */
100  return 0;
101  }
102 
103  return 1;
104 }
105 
109 static int
111  const entry_connection_t *conn,
112  int must_be_open, uint8_t purpose,
113  int need_uptime, int need_internal,
114  time_t now)
115 {
116  const circuit_t *circ = TO_CIRCUIT(origin_circ);
117  const node_t *exitnode;
118  cpath_build_state_t *build_state;
119  tor_assert(circ);
120  tor_assert(conn);
121  tor_assert(conn->socks_request);
122 
123  if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
124  return 0; /* ignore non-open circs */
125  if (circ->marked_for_close)
126  return 0;
127 
128  /* if this circ isn't our purpose, skip. */
129  if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
134  return 0;
135  } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
136  !must_be_open) {
137  if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
139  return 0;
140  } else {
141  if (purpose != circ->purpose)
142  return 0;
143  }
144 
145  /* If this is a timed-out hidden service circuit, skip it. */
146  if (origin_circ->hs_circ_has_timed_out) {
147  return 0;
148  }
149 
150  if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
151  purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
152  purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
153  purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
154  purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
155  if (circ->timestamp_dirty &&
156  circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
157  return 0;
158  }
159 
160  if (origin_circ->unusable_for_new_conns)
161  return 0;
162 
163  /* decide if this circ is suitable for this conn */
164 
165  /* for rend circs, circ->cpath->prev is not the last router in the
166  * circuit, it's the magical extra service hop. so just check the nickname
167  * of the one we meant to finish at.
168  */
169  build_state = origin_circ->build_state;
170  exitnode = build_state_get_exit_node(build_state);
171 
172  if (need_uptime && !build_state->need_uptime)
173  return 0;
174  if (need_internal != build_state->is_internal)
175  return 0;
176 
177  if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
178  purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
179  purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
180  tor_addr_t addr;
181  const int family = tor_addr_parse(&addr, conn->socks_request->address);
182  if (!exitnode && !build_state->onehop_tunnel) {
183  log_debug(LD_CIRC,"Not considering circuit with unknown router.");
184  return 0; /* this circuit is screwed and doesn't know it yet,
185  * or is a rendezvous circuit. */
186  }
187  if (build_state->onehop_tunnel) {
188  if (!conn->want_onehop) {
189  log_debug(LD_CIRC,"Skipping one-hop circuit.");
190  return 0;
191  }
193  if (build_state->chosen_exit) {
194  char digest[DIGEST_LEN];
195  if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
196  return 0; /* broken digest, we don't want it */
197  if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
198  DIGEST_LEN))
199  return 0; /* this is a circuit to somewhere else */
200  if (tor_digest_is_zero(digest)) {
201  /* we don't know the digest; have to compare addr:port */
202  if (family < 0 ||
203  !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
204  build_state->chosen_exit->port != conn->socks_request->port)
205  return 0;
206  }
207  }
208  } else {
209  if (conn->want_onehop) {
210  /* don't use three-hop circuits -- that could hurt our anonymity. */
211  return 0;
212  }
213  }
214  if (origin_circ->prepend_policy && family != -1) {
215  int r = compare_tor_addr_to_addr_policy(&addr,
216  conn->socks_request->port,
217  origin_circ->prepend_policy);
218  if (r == ADDR_POLICY_REJECTED)
219  return 0;
220  }
221  if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
222  /* can't exit from this router */
223  return 0;
224  }
225  } else { /* not general: this might be a rend circuit */
226  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
227  if (!circuit_matches_with_rend_stream(edge_conn, origin_circ)) {
228  return 0;
229  }
230  }
231 
232  if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
233  /* conn needs to be isolated from other conns that have already used
234  * origin_circ */
235  return 0;
236  }
237 
238  return 1;
239 }
240 
244 static int
246  const entry_connection_t *conn)
247 {
248  const circuit_t *a = TO_CIRCUIT(oa);
249  const circuit_t *b = TO_CIRCUIT(ob);
250  const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
251  int a_bits, b_bits;
252 
253  /* If one of the circuits was allowed to live due to relaxing its timeout,
254  * it is definitely worse (it's probably a much slower path). */
255  if (oa->relaxed_timeout && !ob->relaxed_timeout)
256  return 0; /* ob is better. It's not relaxed. */
257  if (!oa->relaxed_timeout && ob->relaxed_timeout)
258  return 1; /* oa is better. It's not relaxed. */
259 
260  switch (purpose) {
264  /* if it's used but less dirty it's best;
265  * else if it's more recently created it's best
266  */
267  if (b->timestamp_dirty) {
268  if (a->timestamp_dirty &&
270  return 1;
271  } else {
272  if (a->timestamp_dirty ||
273  timercmp(&a->timestamp_began, &b->timestamp_began, OP_GT))
274  return 1;
275  if (ob->build_state->is_internal)
276  /* XXXX++ what the heck is this internal thing doing here. I
277  * think we can get rid of it. circuit_is_acceptable() already
278  * makes sure that is_internal is exactly what we need it to
279  * be. -RD */
280  return 1;
281  }
282  break;
284  /* the closer it is to ack_wait the better it is */
285  if (a->purpose > b->purpose)
286  return 1;
287  break;
289  /* the closer it is to rend_joined the better it is */
290  if (a->purpose > b->purpose)
291  return 1;
292  break;
293  }
294 
295  /* XXXX Maybe this check should get a higher priority to avoid
296  * using up circuits too rapidly. */
297 
299  (origin_circuit_t*)oa, 1);
301  (origin_circuit_t*)ob, 1);
302  /* if x_bits < 0, then we have not used x for anything; better not to dirty
303  * a connection if we can help it. */
304  if (a_bits < 0) {
305  return 0;
306  } else if (b_bits < 0) {
307  return 1;
308  }
309  a_bits &= ~ oa->isolation_flags_mixed;
310  a_bits &= ~ ob->isolation_flags_mixed;
311  if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
312  /* The fewer new restrictions we need to make on a circuit for stream
313  * isolation, the better. */
314  return 1;
315  }
316 
317  return 0;
318 }
319 
336 static origin_circuit_t *
338  int must_be_open, uint8_t purpose,
339  int need_uptime, int need_internal)
340 {
341  origin_circuit_t *best=NULL;
342  struct timeval now;
343  int intro_going_on_but_too_old = 0;
344 
345  tor_assert(conn);
346 
348  purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
349  purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
350  purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
352  purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
353 
354  tor_gettimeofday(&now);
355 
356  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
357  origin_circuit_t *origin_circ;
358  if (!CIRCUIT_IS_ORIGIN(circ))
359  continue;
360  origin_circ = TO_ORIGIN_CIRCUIT(circ);
361 
362  /* Log an info message if we're going to launch a new intro circ in
363  * parallel */
364  if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
365  !must_be_open && origin_circ->hs_circ_has_timed_out &&
366  !circ->marked_for_close) {
367  intro_going_on_but_too_old = 1;
368  continue;
369  }
370 
371  if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
372  need_uptime,need_internal, (time_t)now.tv_sec))
373  continue;
374 
375  /* now this is an acceptable circ to hand back. but that doesn't
376  * mean it's the *best* circ to hand back. try to decide.
377  */
378  if (!best || circuit_is_better(origin_circ,best,conn))
379  best = origin_circ;
380  }
381  SMARTLIST_FOREACH_END(circ);
382 
383  if (!best && intro_going_on_but_too_old)
384  log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
385  "right now, but it has already taken quite a while. Starting "
386  "one in parallel.");
387 
388  return best;
389 }
390 
392 static int
394 {
395  int count = 0;
396 
397  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
398  if (circ->marked_for_close ||
399  circ->state == CIRCUIT_STATE_OPEN ||
401  !CIRCUIT_IS_ORIGIN(circ))
402  continue;
403 
404  ++count;
405  }
406  SMARTLIST_FOREACH_END(circ);
407 
408  return count;
409 }
410 
411 #if 0
412 
414 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
415  * Also, it doesn't have the right definition of an exit circuit. Also,
416  * it's never called. */
417 int
418 circuit_conforms_to_options(const origin_circuit_t *circ,
419  const or_options_t *options)
420 {
421  const crypt_path_t *cpath, *cpath_next = NULL;
422 
423  /* first check if it includes any excluded nodes */
424  for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
425  cpath_next = cpath->next;
427  cpath->extend_info))
428  return 0;
429  }
430 
431  /* then consider the final hop */
433  circ->cpath->prev->extend_info))
434  return 0;
435 
436  return 1;
437 }
438 #endif /* 0 */
439 
452 void
454 {
455  /* circ_times.timeout_ms and circ_times.close_ms are from
456  * circuit_build_times_get_initial_timeout() if we haven't computed
457  * custom timeouts yet */
458  struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
459  close_cutoff, extremely_old_cutoff, hs_extremely_old_cutoff,
460  cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff;
461  const or_options_t *options = get_options();
462  struct timeval now;
463  cpath_build_state_t *build_state;
464  int any_opened_circs = 0;
465 
466  tor_gettimeofday(&now);
467 
468  /* Check to see if we have any opened circuits. If we don't,
469  * we want to be more lenient with timeouts, in case the
470  * user has relocated and/or changed network connections.
471  * See bug #3443. */
472  any_opened_circs = circuit_any_opened_circuits();
473 
474 #define SET_CUTOFF(target, msec) do { \
475  long ms = tor_lround(msec); \
476  struct timeval diff; \
477  diff.tv_sec = ms / 1000; \
478  diff.tv_usec = (int)((ms % 1000) * 1000); \
479  timersub(&now, &diff, &target); \
480  } while (0)
481 
513  SET_CUTOFF(general_cutoff, get_circuit_build_timeout_ms());
514  SET_CUTOFF(begindir_cutoff, get_circuit_build_timeout_ms());
515 
516  // TODO: We should probably use route_len_for_purpose() here instead,
517  // except that does not count the extra round trip for things like server
518  // intros and rends.
519 
520  /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
521  * 4th hop. */
522  SET_CUTOFF(fourhop_cutoff, get_circuit_build_timeout_ms() * (10/6.0) + 1000);
523 
524  /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
525  * Use the stream cutoff (more or less). */
526  SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
527 
528  /* Be lenient with cannibalized circs. They already survived the official
529  * CBT, and they're usually not performance-critical. */
530  SET_CUTOFF(cannibalized_cutoff,
532  options->CircuitStreamTimeout * 1000) + 1000);
533 
534  /* Intro circs have an extra round trip (and are also 4 hops long) */
535  SET_CUTOFF(c_intro_cutoff, get_circuit_build_timeout_ms() * (14/6.0) + 1000);
536 
537  /* Server intro circs have an extra round trip */
538  SET_CUTOFF(s_intro_cutoff, get_circuit_build_timeout_ms() * (9/6.0) + 1000);
539 
540  SET_CUTOFF(close_cutoff, get_circuit_build_close_time_ms());
541  SET_CUTOFF(extremely_old_cutoff, get_circuit_build_close_time_ms()*2 + 1000);
542 
543  SET_CUTOFF(hs_extremely_old_cutoff,
545  options->SocksTimeout * 1000));
546 
547  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *,victim) {
548  struct timeval cutoff;
549  if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
550  victim->marked_for_close) /* don't mess with marked circs */
551  continue;
552 
553  /* If we haven't yet started the first hop, it means we don't have
554  * any orconns available, and thus have not started counting time yet
555  * for this circuit. See circuit_deliver_create_cell() and uses of
556  * timestamp_began.
557  *
558  * Continue to wait in this case. The ORConn should timeout
559  * independently and kill us then.
560  */
561  if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
562  continue;
563  }
564 
565  build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
566  if (build_state && build_state->onehop_tunnel)
567  cutoff = begindir_cutoff;
568  else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
569  cutoff = close_cutoff;
570  else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
571  cutoff = c_intro_cutoff;
572  else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
573  cutoff = s_intro_cutoff;
574  else if (victim->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND)
575  cutoff = stream_cutoff;
576  else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
577  cutoff = close_cutoff;
578  else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
579  victim->state != CIRCUIT_STATE_OPEN)
580  cutoff = cannibalized_cutoff;
581  else if (build_state && build_state->desired_path_len >= 4)
582  cutoff = fourhop_cutoff;
583  else
584  cutoff = general_cutoff;
585 
586  if (TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)
587  cutoff = hs_extremely_old_cutoff;
588 
589  if (timercmp(&victim->timestamp_began, &cutoff, OP_GT))
590  continue; /* it's still young, leave it alone */
591 
592  /* We need to double-check the opened state here because
593  * we don't want to consider opened 1-hop dircon circuits for
594  * deciding when to relax the timeout, but we *do* want to relax
595  * those circuits too if nothing else is opened *and* they still
596  * aren't either. */
597  if (!any_opened_circs && victim->state != CIRCUIT_STATE_OPEN) {
598  /* It's still young enough that we wouldn't close it, right? */
599  if (timercmp(&victim->timestamp_began, &close_cutoff, OP_GT)) {
600  if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
601  int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
602  == CPATH_STATE_OPEN;
603  log_info(LD_CIRC,
604  "No circuits are opened. Relaxing timeout for circuit %d "
605  "(a %s %d-hop circuit in state %s with channel state %s).",
606  TO_ORIGIN_CIRCUIT(victim)->global_identifier,
607  circuit_purpose_to_string(victim->purpose),
608  TO_ORIGIN_CIRCUIT(victim)->build_state ?
609  TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
610  -1,
611  circuit_state_to_string(victim->state),
612  victim->n_chan ?
613  channel_state_to_string(victim->n_chan->state) : "none");
614 
615  /* We count the timeout here for CBT, because technically this
616  * was a timeout, and the timeout value needs to reset if we
617  * see enough of them. Note this means we also need to avoid
618  * double-counting below, too. */
620  first_hop_succeeded);
621  TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
622  }
623  continue;
624  } else {
625  static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
626  const double build_close_ms = get_circuit_build_close_time_ms();
627  log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
628  "No circuits are opened. Relaxed timeout for circuit %d "
629  "(a %s %d-hop circuit in state %s with channel state %s) to "
630  "%ldms. However, it appears the circuit has timed out "
631  "anyway.",
632  TO_ORIGIN_CIRCUIT(victim)->global_identifier,
633  circuit_purpose_to_string(victim->purpose),
634  TO_ORIGIN_CIRCUIT(victim)->build_state ?
635  TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
636  -1,
637  circuit_state_to_string(victim->state),
638  victim->n_chan ?
639  channel_state_to_string(victim->n_chan->state) : "none",
640  (long)build_close_ms);
641  }
642  }
643 
644 #if 0
645  /* some debug logs, to help track bugs */
646  if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
647  victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
648  if (!victim->timestamp_dirty)
649  log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
650  "(clean).",
651  victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
652  victim->purpose, victim->build_state->chosen_exit_name,
653  victim->n_circ_id);
654  else
655  log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
656  "%d secs since dirty.",
657  victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
658  victim->purpose, victim->build_state->chosen_exit_name,
659  victim->n_circ_id,
660  (int)(now - victim->timestamp_dirty));
661  }
662 #endif /* 0 */
663 
664  /* if circ is !open, or if it's open but purpose is a non-finished
665  * intro or rend, then mark it for close */
666  if (victim->state == CIRCUIT_STATE_OPEN) {
667  switch (victim->purpose) {
668  default: /* most open circuits can be left alone. */
669  continue; /* yes, continue inside a switch refers to the nearest
670  * enclosing loop. C is smart. */
672  break; /* too old, need to die */
674  /* it's a rend_ready circ -- has it already picked a query? */
675  /* c_rend_ready circs measure age since timestamp_dirty,
676  * because that's set when they switch purposes
677  */
678  if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
679  TO_ORIGIN_CIRCUIT(victim)->hs_ident ||
680  victim->timestamp_dirty > cutoff.tv_sec)
681  continue;
682  break;
684  /* Open path bias testing circuits are given a long
685  * time to complete the test, but not forever */
686  TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
687  break;
689  /* That purpose means that the intro point circuit has been opened
690  * successfully but the INTRODUCE1 cell hasn't been sent yet because
691  * the client is waiting for the rendezvous point circuit to open.
692  * Keep this circuit open while waiting for the rendezvous circuit.
693  * We let the circuit idle timeout take care of cleaning this
694  * circuit if it never used. */
695  continue;
699  /* rend and intro circs become dirty each time they
700  * make an introduction attempt. so timestamp_dirty
701  * will reflect the time since the last attempt.
702  */
703  if (victim->timestamp_dirty > cutoff.tv_sec)
704  continue;
705  break;
706  }
707  } else { /* circuit not open, consider recording failure as timeout */
708  int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
709  TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
710 
711  if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
712  log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
713  "yet has attached streams!",
714  TO_ORIGIN_CIRCUIT(victim)->global_identifier,
715  victim->purpose,
716  circuit_purpose_to_string(victim->purpose));
718  continue;
719  }
720 
723 
724  log_info(LD_CIRC,
725  "Deciding to count the timeout for circuit %"PRIu32"\n",
726  TO_ORIGIN_CIRCUIT(victim)->global_identifier);
727 
728  /* Circuits are allowed to last longer for measurement.
729  * Switch their purpose and wait. */
730  if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
732  victim));
733  continue;
734  }
735 
736  /*
737  * If the circuit build time is much greater than we would have cut
738  * it off at, we probably had a suspend event along this codepath,
739  * and we should discard the value.
740  */
741  if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, OP_LT)) {
742  log_notice(LD_CIRC,
743  "Extremely large value for circuit build timeout: %lds. "
744  "Assuming clock jump. Purpose %d (%s)",
745  (long)(now.tv_sec - victim->timestamp_began.tv_sec),
746  victim->purpose,
747  circuit_purpose_to_string(victim->purpose));
750  first_hop_succeeded,
751  (time_t)victim->timestamp_created.tv_sec)) {
753  }
754  }
755  }
756 
757  /* If this is a hidden service client circuit which is far enough along in
758  * connecting to its destination, and we haven't already flagged it as
759  * 'timed out', flag it so we'll launch another intro or rend circ, but
760  * don't mark it for close yet.
761  *
762  * (Circs flagged as 'timed out' are given a much longer timeout
763  * period above, so we won't close them in the next call to
764  * circuit_expire_building.) */
765  if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out)) {
766  switch (victim->purpose) {
768  /* We only want to spare a rend circ if it has been specified in
769  * an INTRODUCE1 cell sent to a hidden service. A circ's
770  * pending_final_cpath field is non-NULL iff it is a rend circ
771  * and we have tried to send an INTRODUCE1 cell specifying it.
772  * Thus, if the pending_final_cpath field *is* NULL, then we
773  * want to not spare it. */
774  if (TO_ORIGIN_CIRCUIT(victim)->build_state &&
775  TO_ORIGIN_CIRCUIT(victim)->build_state->pending_final_cpath ==
776  NULL)
777  break;
778  /* fallthrough! */
781  /* If we have reached this line, we want to spare the circ for now. */
782  log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
783  "as timed-out HS circ",
784  (unsigned)victim->n_circ_id,
785  victim->state, circuit_state_to_string(victim->state),
786  victim->purpose);
788  continue;
789  default:
790  break;
791  }
792  }
793 
794  /* If this is a service-side rendezvous circuit which is far
795  * enough along in connecting to its destination, consider sparing
796  * it. */
797  if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
798  victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
799  log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
800  "as timed-out HS circ; relaunching rendezvous attempt.",
801  (unsigned)victim->n_circ_id,
802  victim->state, circuit_state_to_string(victim->state),
803  victim->purpose);
805  hs_circ_retry_service_rendezvous_point(TO_ORIGIN_CIRCUIT(victim));
806  continue;
807  }
808 
809  if (victim->n_chan)
810  log_info(LD_CIRC,
811  "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
812  "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
813  channel_get_canonical_remote_descr(victim->n_chan),
814  (unsigned)victim->n_circ_id,
815  TO_ORIGIN_CIRCUIT(victim)->has_opened,
816  victim->state, circuit_state_to_string(victim->state),
817  victim->purpose,
818  TO_ORIGIN_CIRCUIT(victim)->build_state ?
819  TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
820  -1);
821  else
822  log_info(LD_CIRC,
823  "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
824  TO_ORIGIN_CIRCUIT(victim)->global_identifier,
825  (unsigned)victim->n_circ_id,
826  TO_ORIGIN_CIRCUIT(victim)->has_opened,
827  victim->state,
828  circuit_state_to_string(victim->state), victim->purpose,
829  TO_ORIGIN_CIRCUIT(victim)->build_state ?
830  TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
831  -1);
832 
834  if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
835  circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
836  else
837  circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
838 
840  } SMARTLIST_FOREACH_END(victim);
841 }
842 
848 void
850 {
852  origin_circuit_t *, circ) {
853  if (TO_CIRCUIT(circ)->marked_for_close)
854  continue;
855  if (circ->guard_state == NULL)
856  continue;
858  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
859  } SMARTLIST_FOREACH_END(circ);
860 }
861 
865 
872 void
874 {
875 #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
876  time_t now = time(NULL);
877  time_t cutoff = now - age;
878  int n_found = 0;
879  smartlist_t *log_these = smartlist_new();
880  const or_options_t *options = get_options();
881 
882  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
883  const origin_circuit_t *ocirc;
884  if (! CIRCUIT_IS_ORIGIN(circ))
885  continue;
886  if (circ->timestamp_created.tv_sec >= cutoff)
887  continue;
888  /* Single Onion Services deliberately make long term one-hop intro
889  * and rendezvous connections. Don't log the established ones. */
890  if (rend_service_allow_non_anonymous_connection(options) &&
891  (circ->purpose == CIRCUIT_PURPOSE_S_INTRO ||
892  circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED))
893  continue;
894  ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
895 
896  if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
897  ++n_found;
898 
899  if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
900  smartlist_add(log_these, (origin_circuit_t*) ocirc);
901  }
902  }
903  SMARTLIST_FOREACH_END(circ);
904 
905  if (n_found == 0)
906  goto done;
907 
908  log_notice(LD_HEARTBEAT,
909  "Diagnostic for issue 8387: Found %d one-hop circuits more "
910  "than %d seconds old! Logging %d...",
911  n_found, age, smartlist_len(log_these));
912 
913  SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
914  char created[ISO_TIME_LEN+1];
915  int stream_num;
916  const edge_connection_t *conn;
917  char *dirty = NULL;
918  const circuit_t *circ = TO_CIRCUIT(ocirc);
919 
920  format_local_iso_time(created,
921  (time_t)circ->timestamp_created.tv_sec);
922 
923  if (circ->timestamp_dirty) {
924  char dirty_since[ISO_TIME_LEN+1];
925  format_local_iso_time(dirty_since, circ->timestamp_dirty);
926 
927  tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
928  dirty_since, (long)(now - circ->timestamp_dirty),
929  (long) options->MaxCircuitDirtiness);
930  } else {
931  dirty = tor_strdup("Not marked dirty");
932  }
933 
934  log_notice(LD_HEARTBEAT, " #%d created at %s. %s, %s. %s for close. "
935  "Package window: %d. "
936  "%s for new conns. %s.",
937  ocirc_sl_idx,
938  created,
941  circ->marked_for_close ? "Marked" : "Not marked",
942  circ->package_window,
943  ocirc->unusable_for_new_conns ? "Not usable" : "usable",
944  dirty);
945  tor_free(dirty);
946 
947  stream_num = 0;
948  for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
949  const connection_t *c = TO_CONN(conn);
950  char stream_created[ISO_TIME_LEN+1];
951  if (++stream_num >= 5)
952  break;
953 
954  format_local_iso_time(stream_created, c->timestamp_created);
955 
956  log_notice(LD_HEARTBEAT, " Stream#%d created at %s. "
957  "%s conn in state %s. "
958  "It is %slinked and %sreading from a linked connection %p. "
959  "Package window %d. "
960  "%s for close (%s:%d). Hold-open is %sset. "
961  "Has %ssent RELAY_END. %s on circuit.",
962  stream_num,
963  stream_created,
966  c->linked ? "" : "not ",
967  c->reading_from_linked_conn ? "": "not",
968  c->linked_conn,
969  conn->package_window,
970  c->marked_for_close ? "Marked" : "Not marked",
972  c->marked_for_close,
973  c->hold_open_until_flushed ? "" : "not ",
974  conn->edge_has_sent_end ? "" : "not ",
975  conn->edge_blocked_on_circ ? "Blocked" : "Not blocked");
976  if (! c->linked_conn)
977  continue;
978 
979  c = c->linked_conn;
980 
981  log_notice(LD_HEARTBEAT, " Linked to %s connection in state %s "
982  "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
985  c->purpose,
986  c->marked_for_close ? "Marked" : "Not marked",
988  c->marked_for_close,
989  c->hold_open_until_flushed ? "" : "not ");
990  }
991  } SMARTLIST_FOREACH_END(ocirc);
992 
993  log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
994  "circuit_expire_old_circuits_clientside().",
995  (long)(now - last_expired_clientside_circuits));
996 
997  done:
998  smartlist_free(log_these);
999 }
1000 
1004 void
1006 {
1007  int i;
1008  uint16_t *port;
1009 
1010  for (i = 0; i < smartlist_len(needed_ports); ++i) {
1011  port = smartlist_get(needed_ports, i);
1012  tor_assert(*port);
1013  if (circuit_stream_is_being_handled(NULL, *port,
1015  log_debug(LD_CIRC,"Port %d is already being handled; removing.", *port);
1016  smartlist_del(needed_ports, i--);
1017  tor_free(port);
1018  } else {
1019  log_debug(LD_CIRC,"Port %d is not handled.", *port);
1020  }
1021  }
1022 }
1023 
1029 int
1031  uint16_t port, int min)
1032 {
1033  const node_t *exitnode;
1034  int num=0;
1035  time_t now = time(NULL);
1036  int need_uptime = smartlist_contains_int_as_string(
1037  get_options()->LongLivedPorts,
1038  conn ? conn->socks_request->port : port);
1039 
1040  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1041  if (CIRCUIT_IS_ORIGIN(circ) &&
1042  !circ->marked_for_close &&
1043  circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
1044  (!circ->timestamp_dirty ||
1045  circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
1046  origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1047  cpath_build_state_t *build_state = origin_circ->build_state;
1048  if (build_state->is_internal || build_state->onehop_tunnel)
1049  continue;
1050  if (origin_circ->unusable_for_new_conns)
1051  continue;
1052  if (origin_circ->isolation_values_set &&
1053  (conn == NULL ||
1054  !connection_edge_compatible_with_circuit(conn, origin_circ)))
1055  continue;
1056 
1057  exitnode = build_state_get_exit_node(build_state);
1058  if (exitnode && (!need_uptime || build_state->need_uptime)) {
1059  int ok;
1060  if (conn) {
1061  ok = connection_ap_can_use_exit(conn, exitnode);
1062  } else {
1064  r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
1066  }
1067  if (ok) {
1068  if (++num >= min)
1069  return 1;
1070  }
1071  }
1072  }
1073  }
1074  SMARTLIST_FOREACH_END(circ);
1075  return 0;
1076 }
1077 
1079 #define MAX_UNUSED_OPEN_CIRCUITS 14
1080 
1081 /* Return true if a circuit is available for use, meaning that it is open,
1082  * clean, usable for new multi-hop connections, and a general purpose origin
1083  * circuit.
1084  * Accept any kind of circuit, return false if the above conditions are not
1085  * met. */
1086 STATIC int
1087 circuit_is_available_for_use(const circuit_t *circ)
1088 {
1089  const origin_circuit_t *origin_circ;
1090  cpath_build_state_t *build_state;
1091 
1092  if (!CIRCUIT_IS_ORIGIN(circ))
1093  return 0; /* We first filter out only origin circuits before doing the
1094  following checks. */
1095  if (circ->marked_for_close)
1096  return 0; /* Don't mess with marked circs */
1097  if (circ->timestamp_dirty)
1098  return 0; /* Only count clean circs */
1099  if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1101  return 0; /* We only pay attention to general purpose circuits.
1102  General purpose circuits are always origin circuits. */
1103 
1104  origin_circ = CONST_TO_ORIGIN_CIRCUIT(circ);
1105  if (origin_circ->unusable_for_new_conns)
1106  return 0;
1107 
1108  build_state = origin_circ->build_state;
1109  if (build_state->onehop_tunnel)
1110  return 0;
1111 
1112  return 1;
1113 }
1114 
1115 /* Return true if we need any more exit circuits.
1116  * needs_uptime and needs_capacity are set only if we need more exit circuits.
1117  * Check if we know of a port that's been requested recently and no circuit
1118  * is currently available that can handle it. */
1119 STATIC int
1120 needs_exit_circuits(time_t now, int *needs_uptime, int *needs_capacity)
1121 {
1122  return (!circuit_all_predicted_ports_handled(now, needs_uptime,
1123  needs_capacity) &&
1124  router_have_consensus_path() == CONSENSUS_PATH_EXIT);
1125 }
1126 
1127 /* Hidden services need at least this many internal circuits */
1128 #define SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS 3
1129 
1130 /* Return true if we need any more hidden service server circuits.
1131  * HS servers only need an internal circuit. */
1132 STATIC int
1133 needs_hs_server_circuits(time_t now, int num_uptime_internal)
1134 {
1135  if (!rend_num_services() && !hs_service_get_num_services()) {
1136  /* No services, we don't need anything. */
1137  goto no_need;
1138  }
1139 
1140  if (num_uptime_internal >= SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS) {
1141  /* We have sufficient amount of internal circuit. */
1142  goto no_need;
1143  }
1144 
1145  if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN) {
1146  /* Consensus hasn't been checked or might be invalid so requesting
1147  * internal circuits is not wise. */
1148  goto no_need;
1149  }
1150 
1151  /* At this point, we need a certain amount of circuits and we will most
1152  * likely use them for rendezvous so we note down the use of internal
1153  * circuit for our prediction for circuit needing uptime and capacity. */
1154  rep_hist_note_used_internal(now, 1, 1);
1155 
1156  return 1;
1157  no_need:
1158  return 0;
1159 }
1160 
1161 /* We need at least this many internal circuits for hidden service clients */
1162 #define SUFFICIENT_INTERNAL_HS_CLIENTS 3
1163 
1164 /* We need at least this much uptime for internal circuits for hidden service
1165  * clients */
1166 #define SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS 2
1167 
1168 /* Return true if we need any more hidden service client circuits.
1169  * HS clients only need an internal circuit. */
1170 STATIC int
1171 needs_hs_client_circuits(time_t now, int *needs_uptime, int *needs_capacity,
1172  int num_internal, int num_uptime_internal)
1173 {
1174  int used_internal_recently = rep_hist_get_predicted_internal(now,
1175  needs_uptime,
1176  needs_capacity);
1177  int requires_uptime = num_uptime_internal <
1178  SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS &&
1179  needs_uptime;
1180 
1181  return (used_internal_recently &&
1182  (requires_uptime || num_internal < SUFFICIENT_INTERNAL_HS_CLIENTS) &&
1183  router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN);
1184 }
1185 
1186 /* This is how many circuits can be opened concurrently during the cbt learning
1187  * phase. This number cannot exceed the tor-wide MAX_UNUSED_OPEN_CIRCUITS. */
1188 #define DFLT_CBT_UNUSED_OPEN_CIRCS (10)
1189 #define MIN_CBT_UNUSED_OPEN_CIRCS 0
1190 #define MAX_CBT_UNUSED_OPEN_CIRCS MAX_UNUSED_OPEN_CIRCUITS
1191 
1192 /* Return true if we need more circuits for a good build timeout.
1193  * XXXX make the assumption that build timeout streams should be
1194  * created whenever we can build internal circuits. */
1195 STATIC int
1196 needs_circuits_for_build(int num)
1197 {
1198  if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
1199  if (num < networkstatus_get_param(NULL, "cbtmaxopencircs",
1200  DFLT_CBT_UNUSED_OPEN_CIRCS,
1201  MIN_CBT_UNUSED_OPEN_CIRCS,
1202  MAX_CBT_UNUSED_OPEN_CIRCS) &&
1203  !circuit_build_times_disabled(get_options()) &&
1205  return 1;
1206  }
1207  }
1208  return 0;
1209 }
1210 
1215 static void
1217 {
1218  /* K.I.S.S. implementation of bug #23101: If we are using
1219  * vanguards or pinned middles, pre-build a specific purpose
1220  * for HS circs. */
1223  } else {
1224  /* If no vanguards, then no HS-specific prebuilt circuits are needed.
1225  * Normal GENERAL circs are fine */
1227  }
1228 }
1229 
1234 static void
1236 {
1237  int num=0, num_internal=0, num_uptime_internal=0;
1238  int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
1239  int port_needs_uptime=0, port_needs_capacity=1;
1240  time_t now = time(NULL);
1241  int flags = 0;
1242 
1243  /* Count how many of each type of circuit we currently have. */
1244  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1245  if (!circuit_is_available_for_use(circ))
1246  continue;
1247 
1248  num++;
1249 
1250  cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
1251  if (build_state->is_internal)
1252  num_internal++;
1253  if (build_state->need_uptime && build_state->is_internal)
1254  num_uptime_internal++;
1255  }
1256  SMARTLIST_FOREACH_END(circ);
1257 
1258  /* If that's enough, then stop now. */
1259  if (num >= MAX_UNUSED_OPEN_CIRCUITS)
1260  return;
1261 
1262  if (needs_exit_circuits(now, &port_needs_uptime, &port_needs_capacity)) {
1263  if (port_needs_uptime)
1264  flags |= CIRCLAUNCH_NEED_UPTIME;
1265  if (port_needs_capacity)
1266  flags |= CIRCLAUNCH_NEED_CAPACITY;
1267 
1268  log_info(LD_CIRC,
1269  "Have %d clean circs (%d internal), need another exit circ.",
1270  num, num_internal);
1272  return;
1273  }
1274 
1275  if (needs_hs_server_circuits(now, num_uptime_internal)) {
1278 
1279  log_info(LD_CIRC,
1280  "Have %d clean circs (%d internal), need another internal "
1281  "circ for my hidden service.",
1282  num, num_internal);
1284  return;
1285  }
1286 
1287  if (needs_hs_client_circuits(now, &hidserv_needs_uptime,
1288  &hidserv_needs_capacity,
1289  num_internal, num_uptime_internal))
1290  {
1291  if (hidserv_needs_uptime)
1292  flags |= CIRCLAUNCH_NEED_UPTIME;
1293  if (hidserv_needs_capacity)
1294  flags |= CIRCLAUNCH_NEED_CAPACITY;
1295  flags |= CIRCLAUNCH_IS_INTERNAL;
1296 
1297  log_info(LD_CIRC,
1298  "Have %d clean circs (%d uptime-internal, %d internal), need"
1299  " another hidden service circ.",
1300  num, num_uptime_internal, num_internal);
1301 
1303  return;
1304  }
1305 
1306  if (needs_circuits_for_build(num)) {
1307  flags = CIRCLAUNCH_NEED_CAPACITY;
1308  /* if there are no exits in the consensus, make timeout
1309  * circuits internal */
1310  if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
1311  flags |= CIRCLAUNCH_IS_INTERNAL;
1312 
1313  log_info(LD_CIRC,
1314  "Have %d clean circs need another buildtime test circ.", num);
1316  return;
1317  }
1318 }
1319 
1321 #define TESTING_CIRCUIT_INTERVAL 300
1322 
1328 void
1330 {
1331  const or_options_t *options = get_options();
1332 
1333  /* launch a new circ for any pending streams that need one
1334  * XXXX make the assumption that (some) AP streams (i.e. HS clients)
1335  * don't require an exit circuit, review in #13814.
1336  * This allows HSs to function in a consensus without exits. */
1337  if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
1339 
1341 
1342  if (!options->DisablePredictedCircuits)
1344 }
1345 
1351 void
1353 {
1354  static time_t time_to_expire_and_reset = 0;
1355 
1356  if (time_to_expire_and_reset < now) {
1358  time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
1359  if (proxy_mode(get_options()))
1360  addressmap_clean(now);
1362 
1363 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
1364 
1365  /* If we ever re-enable, this has to move into
1366  * circuit_build_needed_circs */
1367 
1368  circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
1369  if (get_options()->RunTesting &&
1370  circ &&
1371  circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
1372  log_fn(LOG_INFO,"Creating a new testing circuit.");
1374  }
1375 #endif /* 0 */
1376  }
1377 }
1378 
1382 void
1384 {
1385  edge_connection_t *prevconn;
1386 
1387  tor_assert(circ);
1388  tor_assert(conn);
1389 
1390  if (conn->base_.type == CONN_TYPE_AP) {
1391  entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1392  entry_conn->may_use_optimistic_data = 0;
1393  }
1394  conn->cpath_layer = NULL; /* don't keep a stale pointer */
1395  conn->on_circuit = NULL;
1396 
1397  if (CIRCUIT_IS_ORIGIN(circ)) {
1398  origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1399  int removed = 0;
1400  if (conn == origin_circ->p_streams) {
1401  origin_circ->p_streams = conn->next_stream;
1402  removed = 1;
1403  } else {
1404  for (prevconn = origin_circ->p_streams;
1405  prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1406  prevconn = prevconn->next_stream)
1407  ;
1408  if (prevconn && prevconn->next_stream) {
1409  prevconn->next_stream = conn->next_stream;
1410  removed = 1;
1411  }
1412  }
1413  if (removed) {
1414  log_debug(LD_APP, "Removing stream %d from circ %u",
1415  conn->stream_id, (unsigned)circ->n_circ_id);
1416 
1417  /* If the stream was removed, and it was a rend stream, decrement the
1418  * number of streams on the circuit associated with the rend service.
1419  */
1420  if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1421  hs_dec_rdv_stream_counter(origin_circ);
1422  }
1423 
1424  /* If there are no more streams on this circ, tell circpad */
1425  if (!origin_circ->p_streams)
1427 
1428  return;
1429  }
1430  } else {
1431  or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1432  if (conn == or_circ->n_streams) {
1433  or_circ->n_streams = conn->next_stream;
1434  return;
1435  }
1436  if (conn == or_circ->resolving_streams) {
1437  or_circ->resolving_streams = conn->next_stream;
1438  return;
1439  }
1440 
1441  for (prevconn = or_circ->n_streams;
1442  prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1443  prevconn = prevconn->next_stream)
1444  ;
1445  if (prevconn && prevconn->next_stream) {
1446  prevconn->next_stream = conn->next_stream;
1447  return;
1448  }
1449 
1450  for (prevconn = or_circ->resolving_streams;
1451  prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1452  prevconn = prevconn->next_stream)
1453  ;
1454  if (prevconn && prevconn->next_stream) {
1455  prevconn->next_stream = conn->next_stream;
1456  return;
1457  }
1458  }
1459 
1460  log_warn(LD_BUG,"Edge connection not in circuit's list.");
1461  /* Don't give an error here; it's harmless. */
1463 }
1464 
1468 static void
1470 {
1471  struct timeval cutoff, now;
1472 
1473  tor_gettimeofday(&now);
1474  last_expired_clientside_circuits = now.tv_sec;
1475 
1476  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1477  if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
1478  continue;
1479 
1480  cutoff = now;
1481  cutoff.tv_sec -= TO_ORIGIN_CIRCUIT(circ)->circuit_idle_timeout;
1482 
1483  /* If the circuit has been dirty for too long, and there are no streams
1484  * on it, mark it for close.
1485  */
1486  if (circ->timestamp_dirty &&
1487  circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
1488  now.tv_sec &&
1489  !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
1490  log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
1491  "purpose %d)",
1492  (unsigned)circ->n_circ_id,
1493  (long)(now.tv_sec - circ->timestamp_dirty),
1494  circ->purpose);
1495  /* Don't do this magic for testing circuits. Their death is governed
1496  * by circuit_expire_building */
1497  if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
1498  circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1499  } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
1500  if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
1501  if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
1502  circ->purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1503  circ->purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1504  circ->purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1505  circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
1506  circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1507  circ->purpose == CIRCUIT_PURPOSE_TESTING ||
1508  (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
1509  circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
1510  circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
1511  log_info(LD_CIRC,
1512  "Closing circuit %"PRIu32
1513  " that has been unused for %ld msec.",
1514  TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1515  tv_mdiff(&circ->timestamp_began, &now));
1516  circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1517  } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
1518  /* Server-side rend joined circuits can end up really old, because
1519  * they are reused by clients for longer than normal. The client
1520  * controls their lifespan. (They never become dirty, because
1521  * connection_exit_begin_conn() never marks anything as dirty.)
1522  * Similarly, server-side intro circuits last a long time. */
1523  if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
1524  circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
1525  log_notice(LD_CIRC,
1526  "Ancient non-dirty circuit %d is still around after "
1527  "%ld milliseconds. Purpose: %d (%s)",
1528  TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1529  tv_mdiff(&circ->timestamp_began, &now),
1530  circ->purpose,
1531  circuit_purpose_to_string(circ->purpose));
1532  TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
1533  }
1534  }
1535  }
1536  }
1537  } SMARTLIST_FOREACH_END(circ);
1538 }
1539 
1555 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
1556 
1561 void
1563 {
1564  or_circuit_t *or_circ;
1565  time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
1566 
1567  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1568  if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
1569  continue;
1570  or_circ = TO_OR_CIRCUIT(circ);
1571  /* If the circuit has been idle for too long, and there are no streams
1572  * on it, and it ends here, and it used a create_fast, mark it for close.
1573  */
1574  if (or_circ->p_chan && channel_is_client(or_circ->p_chan) &&
1575  !circ->n_chan &&
1576  !or_circ->n_streams && !or_circ->resolving_streams &&
1577  channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
1578  log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
1579  (unsigned)or_circ->p_circ_id,
1580  (int)(now - channel_when_last_xmit(or_circ->p_chan)));
1581  circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1582  }
1583  }
1584  SMARTLIST_FOREACH_END(circ);
1585 }
1586 
1588 #define NUM_PARALLEL_TESTING_CIRCS 4
1589 
1593 
1596 void
1598 {
1600 }
1601 
1606 int
1608 {
1609  int num = 0;
1610 
1612  return 1;
1613 
1614  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1615  if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
1616  circ->purpose == CIRCUIT_PURPOSE_TESTING &&
1617  circ->state == CIRCUIT_STATE_OPEN)
1618  num++;
1619  }
1620  SMARTLIST_FOREACH_END(circ);
1621  return num >= NUM_PARALLEL_TESTING_CIRCS;
1622 }
1623 
1630 static void
1632 {
1634  !check_whether_orport_reachable(get_options())) {
1635  /* either we've already done everything we want with testing circuits,
1636  * or this testing circuit became open due to a fluke, e.g. we picked
1637  * a last hop where we already had the connection open due to an
1638  * outgoing local circuit. */
1639  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
1640  } else if (circuit_enough_testing_circs()) {
1643  } else
1645 }
1646 
1648 static void
1650 {
1651  const or_options_t *options = get_options();
1652  if (server_mode(options) && check_whether_orport_reachable(options))
1653  return;
1654 
1655  log_info(LD_GENERAL,
1656  "Our testing circuit (to see if your ORPort is reachable) "
1657  "has failed. I'll try again later.");
1658 
1659  /* These aren't used yet. */
1660  (void)circ;
1661  (void)at_last_hop;
1662 }
1663 
1670 void
1672 {
1673  circuit_event_status(circ, CIRC_EVENT_BUILT, 0);
1674 
1675  /* Remember that this circuit has finished building. Now if we start
1676  * it building again later (e.g. by extending it), we will know not
1677  * to consider its build time. */
1678  circ->has_opened = 1;
1679 
1680  switch (TO_CIRCUIT(circ)->purpose) {
1682  hs_client_circuit_has_opened(circ);
1683  /* Start building an intro circ if we don't have one yet. */
1685  /* This isn't a call to circuit_try_attaching_streams because a
1686  * circuit in _C_ESTABLISH_REND state isn't connected to its
1687  * hidden service yet, thus we can't attach streams to it yet,
1688  * thus circuit_try_attaching_streams would always clear the
1689  * circuit's isolation state. circuit_try_attaching_streams is
1690  * called later, when the rend circ enters _C_REND_JOINED
1691  * state. */
1692  break;
1694  hs_client_circuit_has_opened(circ);
1695  break;
1699  /* Tell any AP connections that have been waiting for a new
1700  * circuit that one is ready. */
1702  break;
1704  /* at the service, waiting for introductions */
1705  hs_service_circuit_has_opened(circ);
1706  break;
1708  /* at the service, connecting to rend point */
1709  hs_service_circuit_has_opened(circ);
1710  break;
1712  circuit_testing_opened(circ);
1713  break;
1714  /* default:
1715  * This won't happen in normal operation, but might happen if the
1716  * controller did it. Just let it slide. */
1717  }
1718 }
1719 
1722 static int
1724 {
1725  if (/* The circuit may have become non-open if it was cannibalized.*/
1726  circ->base_.state == CIRCUIT_STATE_OPEN &&
1727  /* If !isolation_values_set, there is nothing to clear. */
1728  circ->isolation_values_set &&
1729  /* It's not legal to clear a circuit's isolation info if it's ever had
1730  * streams attached */
1732  /* If we have any isolation information set on this circuit, and
1733  * we didn't manage to attach any streams to it, then we can
1734  * and should clear it and try again. */
1736  return 1;
1737  } else {
1738  return 0;
1739  }
1740 }
1741 
1744 void
1746 {
1747  /* Attach streams to this circuit if we can. */
1749 
1750  /* The call to circuit_try_clearing_isolation_state here will do
1751  * nothing and return 0 if we didn't attach any streams to circ
1752  * above. */
1754  /* Maybe *now* we can attach some streams to this circuit. */
1756  }
1757 }
1758 
1761 void
1763 {
1764  channel_t *n_chan = NULL;
1765  /* we should examine circ and see if it failed because of
1766  * the last hop or an earlier hop. then use this info below.
1767  */
1768  int failed_at_last_hop = 0;
1769 
1770  /* First, check to see if this was a path failure, rather than build
1771  * failure.
1772  *
1773  * Note that we deliberately use circuit_get_cpath_len() (and not
1774  * circuit_get_cpath_opened_len()) because we only want to ensure
1775  * that a full path is *chosen*. This is different than a full path
1776  * being *built*. We only want to count *build* failures below.
1777  *
1778  * Path selection failures can happen spuriously for a number
1779  * of reasons (such as aggressive/invalid user-specified path
1780  * restrictions in the torrc, insufficient microdescriptors, and
1781  * non-user reasons like exitpolicy issues), and so should not be
1782  * counted as failures below.
1783  */
1784  if (circuit_get_cpath_len(circ) < circ->build_state->desired_path_len) {
1785  static ratelim_t pathfail_limit = RATELIM_INIT(3600);
1786  log_fn_ratelim(&pathfail_limit, LOG_NOTICE, LD_CIRC,
1787  "Our circuit %u (id: %" PRIu32 ") died due to an invalid "
1788  "selected path, purpose %s. This may be a torrc "
1789  "configuration issue, or a bug.",
1790  TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1791  circuit_purpose_to_string(TO_CIRCUIT(circ)->purpose));
1792 
1793  /* If the path failed on an RP, retry it. */
1794  if (TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
1795  hs_circ_retry_service_rendezvous_point(circ);
1796 
1797  /* In all other cases, just bail. The rest is just failure accounting
1798  * that we don't want to do */
1799  return;
1800  }
1801 
1802  /* If the last hop isn't open, and the second-to-last is, we failed
1803  * at the last hop. */
1804  if (circ->cpath &&
1805  circ->cpath->prev->state != CPATH_STATE_OPEN &&
1806  circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
1807  failed_at_last_hop = 1;
1808  }
1809 
1810  /* Check if we failed at first hop */
1811  if (circ->cpath &&
1812  circ->cpath->state != CPATH_STATE_OPEN &&
1813  ! circ->base_.received_destroy) {
1814  /* We failed at the first hop for some reason other than a DESTROY cell.
1815  * If there's an OR connection to blame, blame it. Also, avoid this relay
1816  * for a while, and fail any one-hop directory fetches destined for it. */
1817  const char *n_chan_ident = circ->cpath->extend_info->identity_digest;
1818  tor_assert(n_chan_ident);
1819  int already_marked = 0;
1820  if (circ->base_.n_chan) {
1821  n_chan = circ->base_.n_chan;
1822 
1823  if (n_chan->is_bad_for_new_circs) {
1824  /* We only want to blame this router when a fresh healthy
1825  * connection fails. So don't mark this router as newly failed,
1826  * since maybe this was just an old circuit attempt that's
1827  * finally timing out now. Also, there's no need to blow away
1828  * circuits/streams/etc, since the failure of an unhealthy conn
1829  * doesn't tell us much about whether a healthy conn would
1830  * succeed. */
1831  already_marked = 1;
1832  }
1833  log_info(LD_OR,
1834  "Our circuit %u (id: %" PRIu32 ") failed to get a response "
1835  "from the first hop (%s). I'm going to try to rotate to a "
1836  "better connection.",
1837  TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1839  n_chan->is_bad_for_new_circs = 1;
1840  } else {
1841  log_info(LD_OR,
1842  "Our circuit %u (id: %" PRIu32 ") died before the first hop "
1843  "with no connection",
1844  TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier);
1845  }
1846  if (!already_marked) {
1847  /*
1848  * If we have guard state (new guard API) and our path selection
1849  * code actually chose a full path, then blame the failure of this
1850  * circuit on the guard.
1851  */
1852  if (circ->guard_state)
1854  /* if there are any one-hop streams waiting on this circuit, fail
1855  * them now so they can retry elsewhere. */
1856  connection_ap_fail_onehop(n_chan_ident, circ->build_state);
1857  }
1858  }
1859 
1860  switch (circ->base_.purpose) {
1864  /* If we never built the circuit, note it as a failure. */
1866  if (failed_at_last_hop) {
1867  /* Make sure any streams that demand our last hop as their exit
1868  * know that it's unlikely to happen. */
1870  }
1871  break;
1873  circuit_testing_failed(circ, failed_at_last_hop);
1874  break;
1876  /* at the service, waiting for introductions */
1877  if (circ->base_.state != CIRCUIT_STATE_OPEN) {
1879  }
1880  /* no need to care here, because the service will rebuild intro
1881  * points periodically. */
1882  break;
1884  /* at the client, connecting to intro point */
1885  /* Don't increment failure count, since the service may have picked
1886  * the introduction point maliciously */
1887  /* The client will pick a new intro point when this one dies, if
1888  * the stream in question still cares. No need to act here. */
1889  break;
1891  /* at the client, waiting for the service */
1893  /* the client will pick a new rend point when this one dies, if
1894  * the stream in question still cares. No need to act here. */
1895  break;
1897  /* at the service, connecting to rend point */
1898  /* Don't increment failure count, since the client may have picked
1899  * the rendezvous point maliciously */
1900  log_info(LD_REND,
1901  "Couldn't connect to the client's chosen rend point %s "
1902  "(%s hop failed).",
1904  failed_at_last_hop?"last":"non-last");
1905  hs_circ_retry_service_rendezvous_point(circ);
1906  break;
1907  /* default:
1908  * This won't happen in normal operation, but might happen if the
1909  * controller did it. Just let it slide. */
1910  }
1911 }
1912 
1916 static int n_circuit_failures = 0;
1920 
1923 #define MAX_CIRCUIT_FAILURES 5
1924 
1928 circuit_launch(uint8_t purpose, int flags)
1929 {
1930  return circuit_launch_by_extend_info(purpose, NULL, flags);
1931 }
1932 
1933 /* Do we have enough descriptors to build paths?
1934  * If need_exit is true, return 1 if we can build exit paths.
1935  * (We need at least one Exit in the consensus to build exit paths.)
1936  * If need_exit is false, return 1 if we can build internal paths.
1937  */
1938 static int
1939 have_enough_path_info(int need_exit)
1940 {
1941  if (need_exit)
1942  return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
1943  else
1944  return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
1945 }
1946 
1950 int
1952 {
1953  if (purpose == CIRCUIT_PURPOSE_HS_VANGUARDS) {
1954  return 1;
1955  }
1956 
1957  /* Client-side purpose */
1958  if (purpose >= CIRCUIT_PURPOSE_C_HS_MIN_ &&
1959  purpose <= CIRCUIT_PURPOSE_C_HS_MAX_) {
1960  return 1;
1961  }
1962 
1963  /* Service-side purpose */
1964  if (purpose >= CIRCUIT_PURPOSE_S_HS_MIN_ &&
1965  purpose <= CIRCUIT_PURPOSE_S_HS_MAX_) {
1966  return 1;
1967  }
1968 
1969  return 0;
1970 }
1971 
1982 int
1984 {
1985  const or_options_t *options = get_options();
1986 
1987  /* Only hidden service circuits use vanguards */
1988  if (!circuit_purpose_is_hidden_service(purpose))
1989  return 0;
1990 
1991  /* Pinned middles are effectively vanguards */
1992  if (options->HSLayer2Nodes || options->HSLayer3Nodes)
1993  return 1;
1994 
1995  return 0;
1996 }
1997 
2004 static int
2005 circuit_should_cannibalize_to_build(uint8_t purpose_to_build,
2006  int has_extend_info,
2007  int onehop_tunnel)
2008 {
2009 
2010  /* Do not try to cannibalize if this is a one hop circuit. */
2011  if (onehop_tunnel) {
2012  return 0;
2013  }
2014 
2015  /* Don't try to cannibalize for general purpose circuits that do not
2016  * specify a custom exit. */
2017  if (purpose_to_build == CIRCUIT_PURPOSE_C_GENERAL && !has_extend_info) {
2018  return 0;
2019  }
2020 
2021  /* Don't cannibalize for testing circuits. We want to see if they
2022  * complete normally. Also don't cannibalize for vanguard-purpose
2023  * circuits, since those are specially pre-built for later
2024  * cannibalization by the actual specific circuit types that need
2025  * vanguards.
2026  */
2027  if (purpose_to_build == CIRCUIT_PURPOSE_TESTING ||
2028  purpose_to_build == CIRCUIT_PURPOSE_HS_VANGUARDS) {
2029  return 0;
2030  }
2031 
2032  /* For vanguards, the server-side intro circ is not cannibalized
2033  * because we pre-build 4 hop HS circuits, and it only needs a 3 hop
2034  * circuit. It is also long-lived, so it is more important that
2035  * it have lower latency than get built fast.
2036  */
2037  if (circuit_should_use_vanguards(purpose_to_build) &&
2038  purpose_to_build == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
2039  return 0;
2040  }
2041 
2042  return 1;
2043 }
2044 
2054  extend_info_t *extend_info,
2055  int flags)
2056 {
2057  origin_circuit_t *circ;
2058  int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
2059  int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
2060 
2061  /* Keep some stats about our attempts to launch HS rendezvous circuits */
2062  if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
2064  }
2065 
2066  if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
2067  log_debug(LD_CIRC,"Haven't %s yet; canceling "
2068  "circuit launch.",
2069  !router_have_minimum_dir_info() ?
2070  "fetched enough directory info" :
2071  "received a consensus with exits");
2072  return NULL;
2073  }
2074 
2075  /* If we can/should cannibalize another circuit to build this one,
2076  * then do so. */
2078  extend_info != NULL,
2079  onehop_tunnel)) {
2080  /* see if there are appropriate circs available to cannibalize. */
2081  /* XXX if we're planning to add a hop, perhaps we want to look for
2082  * internal circs rather than exit circs? -RD */
2083  circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
2084  if (circ) {
2085  uint8_t old_purpose = circ->base_.purpose;
2086  struct timeval old_timestamp_began = circ->base_.timestamp_began;
2087 
2088  log_info(LD_CIRC, "Cannibalizing circ %u (id: %" PRIu32 ") for "
2089  "purpose %d (%s)",
2090  TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier, purpose,
2091  circuit_purpose_to_string(purpose));
2092 
2093  if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2094  purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
2095  circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
2096  /* Path bias: Cannibalized rends pre-emptively count as a
2097  * successfully built but unused closed circuit. We don't
2098  * wait until the extend (or the close) because the rend
2099  * point could be malicious.
2100  *
2101  * Same deal goes for client side introductions. Clients
2102  * can be manipulated to connect repeatedly to them
2103  * (especially web clients).
2104  *
2105  * If we decide to probe the initial portion of these circs,
2106  * (up to the adversary's final hop), we need to remove this,
2107  * or somehow mark the circuit with a special path state.
2108  */
2109 
2110  /* This must be called before the purpose change */
2111  pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
2112  }
2113 
2114  circuit_change_purpose(TO_CIRCUIT(circ), purpose);
2115  /* Reset the start date of this circ, else expire_building
2116  * will see it and think it's been trying to build since it
2117  * began.
2118  *
2119  * Technically, the code should reset this when the
2120  * create cell is finally sent, but we're close enough
2121  * here. */
2122  tor_gettimeofday(&circ->base_.timestamp_began);
2123 
2124  control_event_circuit_cannibalized(circ, old_purpose,
2125  &old_timestamp_began);
2126 
2127  switch (purpose) {
2129  /* it's ready right now */
2130  break;
2137  /* need to add a new hop */
2138  tor_assert(extend_info);
2139  if (circuit_extend_to_new_exit(circ, extend_info) < 0)
2140  return NULL;
2141  break;
2142  default:
2143  log_warn(LD_BUG,
2144  "unexpected purpose %d when cannibalizing a circ.",
2145  purpose);
2147  return NULL;
2148  }
2149  return circ;
2150  }
2151  }
2152 
2155  /* too many failed circs in a row. don't try. */
2156 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
2157  return NULL;
2158  }
2159 
2160  /* try a circ. if it fails, circuit_mark_for_close will increment
2161  * n_circuit_failures */
2162  return circuit_establish_circuit(purpose, extend_info, flags);
2163 }
2164 
2168 static void
2170 {
2172  log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
2173 }
2174 
2179 void
2181 {
2182  if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
2184  else
2186  n_circuit_failures = 0;
2187 }
2188 
2195 static int
2197  uint8_t desired_circuit_purpose,
2198  origin_circuit_t **circp)
2199 {
2200  origin_circuit_t *circ;
2201  int check_exit_policy;
2202  int need_uptime, need_internal;
2203  int want_onehop;
2204  const or_options_t *options = get_options();
2205 
2206  tor_assert(conn);
2207  tor_assert(circp);
2208  if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2209  connection_t *c = ENTRY_TO_CONN(conn);
2210  log_err(LD_BUG, "Connection state mismatch: wanted "
2211  "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
2212  c->state, conn_state_to_string(c->type, c->state));
2213  }
2215 
2216  /* Will the exit policy of the exit node apply to this stream? */
2217  check_exit_policy =
2218  conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
2219  !conn->use_begindir &&
2220  !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
2221 
2222  /* Does this connection want a one-hop circuit? */
2223  want_onehop = conn->want_onehop;
2224 
2225  /* Do we need a high-uptime circuit? */
2226  need_uptime = !conn->want_onehop && !conn->use_begindir &&
2228  conn->socks_request->port);
2229 
2230  /* Do we need an "internal" circuit? */
2231  if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
2232  need_internal = 1;
2233  else if (conn->use_begindir || conn->want_onehop)
2234  need_internal = 1;
2235  else
2236  need_internal = 0;
2237 
2238  /* We now know what kind of circuit we need. See if there is an
2239  * open circuit that we can use for this stream */
2240  circ = circuit_get_best(conn, 1 /* Insist on open circuits */,
2241  desired_circuit_purpose,
2242  need_uptime, need_internal);
2243 
2244  if (circ) {
2245  /* We got a circuit that will work for this stream! We can return it. */
2246  *circp = circ;
2247  return 1; /* we're happy */
2248  }
2249 
2250  /* Okay, there's no circuit open that will work for this stream. Let's
2251  * see if there's an in-progress circuit or if we have to launch one */
2252 
2253  /* Do we know enough directory info to build circuits at all? */
2254  int have_path = have_enough_path_info(!need_internal);
2255 
2256  if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
2257  /* If we don't have enough directory information, we can't build
2258  * multihop circuits.
2259  */
2261  int severity = LOG_NOTICE;
2262  /* Retry some stuff that might help the connection work. */
2263  /* If we are configured with EntryNodes or UseBridges */
2264  if (entry_list_is_constrained(options)) {
2265  /* Retry all our guards / bridges.
2266  * guards_retry_optimistic() always returns true here. */
2267  int rv = guards_retry_optimistic(options);
2268  tor_assert_nonfatal_once(rv);
2269  log_fn(severity, LD_APP|LD_DIR,
2270  "Application request when we haven't %s. "
2271  "Optimistically trying known %s again.",
2272  !router_have_minimum_dir_info() ?
2273  "used client functionality lately" :
2274  "received a consensus with exits",
2275  options->UseBridges ? "bridges" : "entrynodes");
2276  } else {
2277  /* Getting directory documents doesn't help much if we have a limited
2278  * number of guards */
2279  tor_assert_nonfatal(!options->UseBridges);
2280  tor_assert_nonfatal(!options->EntryNodes);
2281  /* Retry our directory fetches, so we have a fresh set of guard info */
2282  log_fn(severity, LD_APP|LD_DIR,
2283  "Application request when we haven't %s. "
2284  "Optimistically trying directory fetches again.",
2285  !router_have_minimum_dir_info() ?
2286  "used client functionality lately" :
2287  "received a consensus with exits");
2289  }
2290  }
2291  /* Since we didn't have enough directory info, we can't attach now. The
2292  * stream will be dealt with when router_have_minimum_dir_info becomes 1,
2293  * or when all directory attempts fail and directory_all_unreachable()
2294  * kills it.
2295  */
2296  return 0;
2297  }
2298 
2299  /* Check whether the exit policy of the chosen exit, or the exit policies
2300  * of _all_ nodes, would forbid this node. */
2301  if (check_exit_policy) {
2302  if (!conn->chosen_exit_name) {
2303  struct in_addr in;
2304  tor_addr_t addr, *addrp=NULL;
2305  if (tor_inet_aton(conn->socks_request->address, &in)) {
2306  tor_addr_from_in(&addr, &in);
2307  addrp = &addr;
2308  }
2310  conn->socks_request->port,
2311  need_uptime)) {
2312  log_notice(LD_APP,
2313  "No Tor server allows exit to %s:%d. Rejecting.",
2315  conn->socks_request->port);
2316  return -1;
2317  }
2318  } else {
2319  /* XXXX Duplicates checks in connection_ap_handshake_attach_circuit:
2320  * refactor into a single function. */
2321  const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2322  int opt = conn->chosen_exit_optional;
2323  if (node && !connection_ap_can_use_exit(conn, node)) {
2324  log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2325  "Requested exit point '%s' is excluded or "
2326  "would refuse request. %s.",
2327  conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2328  if (opt) {
2329  conn->chosen_exit_optional = 0;
2330  tor_free(conn->chosen_exit_name);
2331  /* Try again. */
2332  return circuit_get_open_circ_or_launch(conn,
2333  desired_circuit_purpose,
2334  circp);
2335  }
2336  return -1;
2337  }
2338  }
2339  }
2340 
2341  /* Now, check whether there already a circuit on the way that could handle
2342  * this stream. This check matches the one above, but this time we
2343  * do not require that the circuit will work. */
2344  circ = circuit_get_best(conn, 0 /* don't insist on open circuits */,
2345  desired_circuit_purpose,
2346  need_uptime, need_internal);
2347  if (circ)
2348  log_debug(LD_CIRC, "one on the way!");
2349 
2350  if (!circ) {
2351  /* No open or in-progress circuit could handle this stream! We
2352  * will have to launch one!
2353  */
2354 
2355  /* The chosen exit node, if there is one. */
2356  extend_info_t *extend_info=NULL;
2357  const int n_pending = count_pending_general_client_circuits();
2358 
2359  /* Do we have too many pending circuits? */
2360  if (n_pending >= options->MaxClientCircuitsPending) {
2361  static ratelim_t delay_limit = RATELIM_INIT(10*60);
2362  char *m;
2363  if ((m = rate_limit_log(&delay_limit, approx_time()))) {
2364  log_notice(LD_APP, "We'd like to launch a circuit to handle a "
2365  "connection, but we already have %d general-purpose client "
2366  "circuits pending. Waiting until some finish.%s",
2367  n_pending, m);
2368  tor_free(m);
2369  }
2370  return 0;
2371  }
2372 
2373  /* If this is a hidden service trying to start an introduction point,
2374  * handle that case. */
2375  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
2376  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2377  /* need to pick an intro point */
2378  extend_info = hs_client_get_random_intro_from_edge(edge_conn);
2379  if (!extend_info) {
2380  log_info(LD_REND, "No intro points: re-fetching service descriptor.");
2381  if (edge_conn->rend_data) {
2383  } else {
2384  hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
2385  }
2387  return 0;
2388  }
2389  log_info(LD_REND,"Chose %s as intro point for '%s'.",
2390  extend_info_describe(extend_info),
2391  (edge_conn->rend_data) ?
2392  safe_str_client(rend_data_get_address(edge_conn->rend_data)) :
2393  "service");
2394  }
2395 
2396  /* If we have specified a particular exit node for our
2397  * connection, then be sure to open a circuit to that exit node.
2398  */
2399  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2400  desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2401  desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
2402  if (conn->chosen_exit_name) {
2403  const node_t *r;
2404  int opt = conn->chosen_exit_optional;
2405  r = node_get_by_nickname(conn->chosen_exit_name, 0);
2406  if (r && node_has_preferred_descriptor(r, conn->want_onehop ? 1 : 0)) {
2407  /* We might want to connect to an IPv6 bridge for loading
2408  descriptors so we use the preferred address rather than
2409  the primary. */
2410  extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
2411  if (!extend_info) {
2412  log_warn(LD_CIRC,"Could not make a one-hop connection to %s. "
2413  "Discarding this circuit.", conn->chosen_exit_name);
2414  return -1;
2415  }
2416  } else { /* ! (r && node_has_preferred_descriptor(...)) */
2417  log_debug(LD_DIR, "considering %d, %s",
2418  want_onehop, conn->chosen_exit_name);
2419  if (want_onehop && conn->chosen_exit_name[0] == '$') {
2420  /* We're asking for a one-hop circuit to a router that
2421  * we don't have a routerinfo about. Make up an extend_info. */
2422  /* XXX prop220: we need to make chosen_exit_name able to
2423  * encode both key formats. This is not absolutely critical
2424  * since this is just for one-hop circuits, but we should
2425  * still get it done */
2426  char digest[DIGEST_LEN];
2427  char *hexdigest = conn->chosen_exit_name+1;
2428  tor_addr_t addr;
2429  if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2430  base16_decode(digest,DIGEST_LEN,
2431  hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN) {
2432  log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
2433  return -1;
2434  }
2435  if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
2436  log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
2438  return -1;
2439  }
2440  /* XXXX prop220 add a workaround for ed25519 ID below*/
2441  extend_info = extend_info_new(conn->chosen_exit_name+1,
2442  digest,
2443  NULL, /* Ed25519 ID */
2444  NULL, NULL, /* onion keys */
2445  &addr, conn->socks_request->port);
2446  } else { /* ! (want_onehop && conn->chosen_exit_name[0] == '$') */
2447  /* We will need an onion key for the router, and we
2448  * don't have one. Refuse or relax requirements. */
2449  log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2450  "Requested exit point '%s' is not known. %s.",
2451  conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2452  if (opt) {
2453  conn->chosen_exit_optional = 0;
2454  tor_free(conn->chosen_exit_name);
2455  /* Try again with no requested exit */
2456  return circuit_get_open_circ_or_launch(conn,
2457  desired_circuit_purpose,
2458  circp);
2459  }
2460  return -1;
2461  }
2462  }
2463  }
2464  } /* Done checking for general circutis with chosen exits. */
2465 
2466  /* What purpose do we need to launch this circuit with? */
2467  uint8_t new_circ_purpose;
2468  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
2469  new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
2470  else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
2471  new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
2472  else
2473  new_circ_purpose = desired_circuit_purpose;
2474 
2475  /* Determine what kind of a circuit to launch, and actually launch it. */
2476  {
2477  int flags = CIRCLAUNCH_NEED_CAPACITY;
2478  if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
2479  if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2480  if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
2481 
2482  /* If we are about to pick a v3 RP right now, make sure we pick a
2483  * rendezvous point that supports the v3 protocol! */
2484  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED &&
2485  new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2486  ENTRY_TO_EDGE_CONN(conn)->hs_ident) {
2487  flags |= CIRCLAUNCH_IS_V3_RP;
2488  log_info(LD_GENERAL, "Getting rendezvous circuit to v3 service!");
2489  }
2490 
2491  circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
2492  flags);
2493  }
2494 
2495  extend_info_free(extend_info);
2496 
2497  /* Now trigger things that need to happen when we launch circuits */
2498 
2499  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2500  desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2501  desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST) {
2502  /* We just caused a circuit to get built because of this stream.
2503  * If this stream has caused a _lot_ of circuits to be built, that's
2504  * a bad sign: we should tell the user. */
2505  if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
2506  ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
2507  log_info(LD_CIRC, "The application request to %s:%d has launched "
2508  "%d circuits without finding one it likes.",
2510  conn->socks_request->port,
2511  conn->num_circuits_launched);
2512  } else {
2513  /* help predict this next time */
2514  rep_hist_note_used_internal(time(NULL), need_uptime, 1);
2515  if (circ) {
2516  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2517  if (edge_conn->rend_data) {
2518  /* write the service_id into circ */
2519  circ->rend_data = rend_data_dup(edge_conn->rend_data);
2520  } else if (edge_conn->hs_ident) {
2521  circ->hs_ident =
2522  hs_ident_circuit_new(&edge_conn->hs_ident->identity_pk,
2523  HS_IDENT_CIRCUIT_INTRO);
2524  }
2525  if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2526  circ->base_.state == CIRCUIT_STATE_OPEN)
2527  circuit_has_opened(circ);
2528  }
2529  }
2530  } /* endif (!circ) */
2531 
2532  /* We either found a good circuit, or launched a new circuit, or failed to
2533  * do so. Report success, and delay. */
2534 
2535  if (circ) {
2536  /* Mark the circuit with the isolation fields for this connection.
2537  * When the circuit arrives, we'll clear these flags: this is
2538  * just some internal bookkeeping to make sure that we have
2539  * launched enough circuits.
2540  */
2542  } else {
2543  log_info(LD_APP,
2544  "No safe circuit (purpose %d) ready for edge "
2545  "connection; delaying.",
2546  desired_circuit_purpose);
2547  }
2548  *circp = circ;
2549  return 0;
2550 }
2551 
2554 static int
2556 {
2557  crypt_path_t *cpath, *cpath_next = NULL;
2558  for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2559  cpath_next = cpath->next;
2560  if (crypt_path == cpath)
2561  return 1;
2562  }
2563  return 0;
2564 }
2565 
2567 static int
2569 {
2570  const or_options_t *options = get_options();
2571  if (options->OptimisticData < 0) {
2572  /* Note: this default was 0 before #18815 was merged. We can't take the
2573  * parameter out of the consensus until versions before that are all
2574  * obsolete. */
2575  const int32_t enabled =
2576  networkstatus_get_param(NULL, "UseOptimisticData", /*default*/ 1, 0, 1);
2577  return (int)enabled;
2578  }
2579  return options->OptimisticData;
2580 }
2581 
2586 static void
2588  crypt_path_t *cpath)
2589 {
2590  const node_t *exitnode = NULL;
2591 
2592  /* add it into the linked list of streams on this circuit */
2593  log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
2594  (unsigned)circ->base_.n_circ_id);
2595 
2596  /* If this is the first stream on this circuit, tell circpad
2597  * that streams are attached */
2598  if (!circ->p_streams)
2600 
2601  /* reset it, so we can measure circ timeouts */
2602  ENTRY_TO_CONN(apconn)->timestamp_last_read_allowed = time(NULL);
2603  ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
2604  ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
2605  /* assert_connection_ok(conn, time(NULL)); */
2606  circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
2607 
2608  if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
2609  /* We are attaching a stream to a rendezvous circuit. That means
2610  * that an attempt to connect to a hidden service just
2611  * succeeded. Tell rendclient.c. */
2612  hs_client_note_connection_attempt_succeeded(ENTRY_TO_EDGE_CONN(apconn));
2613  }
2614 
2615  if (cpath) { /* we were given one; use it */
2616  tor_assert(cpath_is_on_circuit(circ, cpath));
2617  } else {
2618  /* use the last hop in the circuit */
2619  tor_assert(circ->cpath);
2620  tor_assert(circ->cpath->prev);
2621  tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
2622  cpath = circ->cpath->prev;
2623  }
2624  ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
2625 
2628 
2629  /* Compute the exitnode if possible, for logging below */
2630  if (cpath->extend_info)
2631  exitnode = node_get_by_id(cpath->extend_info->identity_digest);
2632 
2633  /* See if we can use optimistic data on this circuit */
2634  if (optimistic_data_enabled() &&
2635  (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2636  circ->base_.purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2637  circ->base_.purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2638  circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED))
2639  apconn->may_use_optimistic_data = 1;
2640  else
2641  apconn->may_use_optimistic_data = 0;
2642  log_info(LD_APP, "Looks like completed circuit to %s %s allow "
2643  "optimistic data for connection to %s",
2644  circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ?
2645  /* node_describe() does the right thing if exitnode is NULL */
2646  safe_str_client(node_describe(exitnode)) :
2647  "hidden service",
2648  apconn->may_use_optimistic_data ? "does" : "doesn't",
2650 }
2651 
2654 int
2655 hostname_in_track_host_exits(const or_options_t *options, const char *address)
2656 {
2657  if (!options->TrackHostExits)
2658  return 0;
2659  SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
2660  if (cp[0] == '.') { /* match end */
2661  if (cp[1] == '\0' ||
2662  !strcasecmpend(address, cp) ||
2663  !strcasecmp(address, &cp[1]))
2664  return 1;
2665  } else if (strcasecmp(cp, address) == 0) {
2666  return 1;
2667  }
2668  } SMARTLIST_FOREACH_END(cp);
2669  return 0;
2670 }
2671 
2676 static void
2678  const origin_circuit_t *circ)
2679 {
2680  const or_options_t *options = get_options();
2681  char *new_address = NULL;
2682  char fp[HEX_DIGEST_LEN+1];
2683 
2684  /* Search the addressmap for this conn's destination. */
2685  /* If they're not in the address map.. */
2686  if (!options->TrackHostExits ||
2688  options->TrackHostExitsExpire))
2689  return; /* nothing to track, or already mapped */
2690 
2691  if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
2692  !circ->build_state->chosen_exit)
2693  return;
2694 
2695  /* write down the fingerprint of the chosen exit, not the nickname,
2696  * because the chosen exit might not be named. */
2697  base16_encode(fp, sizeof(fp),
2699 
2700  /* Add this exit/hostname pair to the addressmap. */
2701  tor_asprintf(&new_address, "%s.%s.exit",
2702  conn->socks_request->address, fp);
2703 
2704  addressmap_register(conn->socks_request->address, new_address,
2705  time(NULL) + options->TrackHostExitsExpire,
2706  ADDRMAPSRC_TRACKEXIT, 0, 0);
2707 }
2708 
2714 int
2716  origin_circuit_t *circ,
2717  crypt_path_t *cpath)
2718 {
2719  connection_t *base_conn = ENTRY_TO_CONN(conn);
2720  tor_assert(conn);
2722  base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
2723  tor_assert(conn->socks_request);
2724  tor_assert(circ);
2725  tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
2726 
2727  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2728 
2729  if (!circ->base_.timestamp_dirty ||
2730  ((conn->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
2731  (conn->entry_cfg.socks_iso_keep_alive) &&
2732  (conn->socks_request->usernamelen ||
2733  conn->socks_request->passwordlen))) {
2734  /* When stream isolation is in use and controlled by an application
2735  * we are willing to keep using the stream. */
2736  circ->base_.timestamp_dirty = approx_time();
2737  }
2738 
2740 
2741  /* Now, actually link the connection. */
2742  link_apconn_to_circ(conn, circ, cpath);
2743 
2744  tor_assert(conn->socks_request);
2745  if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
2746  if (!conn->use_begindir)
2747  consider_recording_trackhost(conn, circ);
2748  if (connection_ap_handshake_send_begin(conn) < 0)
2749  return -1;
2750  } else {
2752  return -1;
2753  }
2754 
2755  return 1;
2756 }
2757 
2766 static int
2768 {
2769  const connection_t *base_conn = ENTRY_TO_CONN(conn);
2770  tor_assert_nonfatal(!connection_edge_is_rendezvous_stream(
2771  ENTRY_TO_EDGE_CONN(conn)));
2772 
2773  if (base_conn->linked_conn &&
2774  base_conn->linked_conn->type == CONN_TYPE_DIR) {
2775  /* Set a custom purpose for hsdir activity */
2776  if (base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2 ||
2779  } else if (base_conn->linked_conn->purpose
2781  base_conn->linked_conn->purpose
2784  }
2785  }
2786 
2787  /* All other purposes are general for now */
2789 }
2790 
2797 /* XXXX this function should mark for close whenever it returns -1;
2798  * its callers shouldn't have to worry about that. */
2799 int
2801 {
2802  connection_t *base_conn = ENTRY_TO_CONN(conn);
2803  int retval;
2804  int conn_age;
2805  int want_onehop;
2806 
2807  tor_assert(conn);
2809  tor_assert(conn->socks_request);
2810  want_onehop = conn->want_onehop;
2811 
2812  conn_age = (int)(time(NULL) - base_conn->timestamp_created);
2813 
2814  /* Is this connection so old that we should give up on it? */
2815  if (conn_age >= get_options()->SocksTimeout) {
2816  int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
2817  LOG_INFO : LOG_NOTICE;
2818  log_fn(severity, LD_APP,
2819  "Tried for %d seconds to get a connection to %s:%d. Giving up.",
2820  conn_age, safe_str_client(conn->socks_request->address),
2821  conn->socks_request->port);
2822  return -1;
2823  }
2824 
2825  /* We handle "general" (non-onion) connections much more straightforwardly.
2826  */
2827  if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
2828  /* we're a general conn */
2829  origin_circuit_t *circ=NULL;
2830 
2831  /* Are we linked to a dir conn that aims to fetch a consensus?
2832  * We check here because the conn might no longer be needed. */
2833  if (base_conn->linked_conn &&
2834  base_conn->linked_conn->type == CONN_TYPE_DIR &&
2836 
2837  /* Yes we are. Is there a consensus fetch farther along than us? */
2838  if (networkstatus_consensus_is_already_downloading(
2839  TO_DIR_CONN(base_conn->linked_conn)->requested_resource)) {
2840  /* We're doing the "multiple consensus fetch attempts" game from
2841  * proposal 210, and we're late to the party. Just close this conn.
2842  * The circuit and TLS conn that we made will time out after a while
2843  * if nothing else wants to use them. */
2844  log_info(LD_DIR, "Closing extra consensus fetch (to %s) since one "
2845  "is already downloading.", base_conn->linked_conn->address);
2846  return -1;
2847  }
2848  }
2849 
2850  /* If we have a chosen exit, we need to use a circuit that's
2851  * open to that exit. See what exit we meant, and whether we can use it.
2852  */
2853  if (conn->chosen_exit_name) {
2854  const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2855  int opt = conn->chosen_exit_optional;
2856  if (!node && !want_onehop) {
2857  /* We ran into this warning when trying to extend a circuit to a
2858  * hidden service directory for which we didn't have a router
2859  * descriptor. See flyspray task 767 for more details. We should
2860  * keep this in mind when deciding to use BEGIN_DIR cells for other
2861  * directory requests as well. -KL*/
2862  log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2863  "Requested exit point '%s' is not known. %s.",
2864  conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2865  if (opt) {
2866  /* If we are allowed to ignore the .exit request, do so */
2867  conn->chosen_exit_optional = 0;
2868  tor_free(conn->chosen_exit_name);
2869  return 0;
2870  }
2871  return -1;
2872  }
2873  if (node && !connection_ap_can_use_exit(conn, node)) {
2874  log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2875  "Requested exit point '%s' is excluded or "
2876  "would refuse request. %s.",
2877  conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2878  if (opt) {
2879  /* If we are allowed to ignore the .exit request, do so */
2880  conn->chosen_exit_optional = 0;
2881  tor_free(conn->chosen_exit_name);
2882  return 0;
2883  }
2884  return -1;
2885  }
2886  }
2887 
2888  /* Find the circuit that we should use, if there is one. Otherwise
2889  * launch it
2890  */
2891  retval = circuit_get_open_circ_or_launch(conn,
2893  &circ);
2894 
2895  if (retval < 1) {
2896  /* We were either told "-1" (complete failure) or 0 (circuit in
2897  * progress); we can't attach this stream yet. */
2898  return retval;
2899  }
2900 
2901  log_debug(LD_APP|LD_CIRC,
2902  "Attaching apconn to circ %u (stream %d sec old).",
2903  (unsigned)circ->base_.n_circ_id, conn_age);
2904  /* print the circ's path, so clients can figure out which circs are
2905  * sucking. */
2907 
2908  /* We have found a suitable circuit for our conn. Hurray. Do
2909  * the attachment. */
2910  return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
2911 
2912  } else { /* we're a rendezvous conn */
2913  origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
2914 
2915  tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
2916 
2917  /* start by finding a rendezvous circuit for us */
2918 
2920  conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
2921  if (retval < 0) return -1; /* failed */
2922 
2923  if (retval > 0) {
2924  tor_assert(rendcirc);
2925  /* one is already established, attach */
2926  log_info(LD_REND,
2927  "rend joined circ %u (id: %" PRIu32 ") already here. "
2928  "Attaching. (stream %d sec old)",
2929  (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2930  rendcirc->global_identifier, conn_age);
2931  /* Mark rendezvous circuits as 'newly dirty' every time you use
2932  * them, since the process of rebuilding a rendezvous circ is so
2933  * expensive. There is a tradeoff between linkability and
2934  * feasibility, at this point.
2935  */
2936  rendcirc->base_.timestamp_dirty = time(NULL);
2937 
2938  /* We've also attempted to use them. If they fail, we need to
2939  * probe them for path bias */
2940  pathbias_count_use_attempt(rendcirc);
2941 
2942  link_apconn_to_circ(conn, rendcirc, NULL);
2943  if (connection_ap_handshake_send_begin(conn) < 0)
2944  return 0; /* already marked, let them fade away */
2945  return 1;
2946  }
2947 
2948  /* At this point we need to re-check the state, since it's possible that
2949  * our call to circuit_get_open_circ_or_launch() changed the connection's
2950  * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
2951  * re-fetch the descriptor.
2952  */
2953  if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2954  log_info(LD_REND, "This connection is no longer ready to attach; its "
2955  "state changed."
2956  "(We probably have to re-fetch its descriptor.)");
2957  return 0;
2958  }
2959 
2960  if (rendcirc && (rendcirc->base_.purpose ==
2962  log_info(LD_REND,
2963  "pending-join circ %u (id: %" PRIu32 ") already here, with "
2964  "intro ack. Stalling. (stream %d sec old)",
2965  (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2966  rendcirc->global_identifier, conn_age);
2967  return 0;
2968  }
2969 
2970  /* it's on its way. find an intro circ. */
2972  conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
2973  if (retval < 0) return -1; /* failed */
2974 
2975  if (retval > 0) {
2976  /* one has already sent the intro. keep waiting. */
2977  tor_assert(introcirc);
2978  log_info(LD_REND, "Intro circ %u (id: %" PRIu32 ") present and "
2979  "awaiting ACK. Rend circuit %u (id: %" PRIu32 "). "
2980  "Stalling. (stream %d sec old)",
2981  (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
2982  introcirc->global_identifier,
2983  rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
2984  rendcirc ? rendcirc->global_identifier : 0,
2985  conn_age);
2986  return 0;
2987  }
2988 
2989  /* now rendcirc and introcirc are each either undefined or not finished */
2990 
2991  if (rendcirc && introcirc &&
2992  rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
2993  log_info(LD_REND,
2994  "ready rend circ %u (id: %" PRIu32 ") already here. No"
2995  "intro-ack yet on intro %u (id: %" PRIu32 "). "
2996  "(stream %d sec old)",
2997  (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2998  rendcirc->global_identifier,
2999  (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
3000  introcirc->global_identifier, conn_age);
3001 
3002  tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
3003  if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
3004  int ret;
3005  log_info(LD_REND, "Found open intro circ %u (id: %" PRIu32 "). "
3006  "Rend circuit %u (id: %" PRIu32 "); Sending "
3007  "introduction. (stream %d sec old)",
3008  (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
3009  introcirc->global_identifier,
3010  (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
3011  rendcirc->global_identifier, conn_age);
3012  ret = hs_client_send_introduce1(introcirc, rendcirc);
3013  switch (ret) {
3014  case 0: /* success */
3015  rendcirc->base_.timestamp_dirty = time(NULL);
3016  introcirc->base_.timestamp_dirty = time(NULL);
3017 
3018  pathbias_count_use_attempt(introcirc);
3019  pathbias_count_use_attempt(rendcirc);
3020 
3021  assert_circuit_ok(TO_CIRCUIT(rendcirc));
3022  assert_circuit_ok(TO_CIRCUIT(introcirc));
3023  return 0;
3024  case -1: /* transient error */
3025  return 0;
3026  case -2: /* permanent error */
3027  return -1;
3028  default: /* oops */
3030  return -1;
3031  }
3032  }
3033  }
3034 
3035  log_info(LD_REND, "Intro %u (id: %" PRIu32 ") and rend circuit %u "
3036  "(id: %" PRIu32 ") circuits are not both ready. "
3037  "Stalling conn. (%d sec old)",
3038  introcirc ? (unsigned) TO_CIRCUIT(introcirc)->n_circ_id : 0,
3039  introcirc ? introcirc->global_identifier : 0,
3040  rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
3041  rendcirc ? rendcirc->global_identifier : 0, conn_age);
3042  return 0;
3043  }
3044 }
3045 
3047 void
3048 circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
3049 {
3050  uint8_t old_purpose;
3051  /* Don't allow an OR circ to become an origin circ or vice versa. */
3052  tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
3053  !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
3054 
3055  if (circ->purpose == new_purpose) return;
3056 
3057  if (CIRCUIT_IS_ORIGIN(circ)) {
3058  char old_purpose_desc[80] = "";
3059 
3060  strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
3061  old_purpose_desc[80-1] = '\0';
3062 
3063  log_debug(LD_CIRC,
3064  "changing purpose of origin circ %d "
3065  "from \"%s\" (%d) to \"%s\" (%d)",
3066  TO_ORIGIN_CIRCUIT(circ)->global_identifier,
3067  old_purpose_desc,
3068  circ->purpose,
3069  circuit_purpose_to_string(new_purpose),
3070  new_purpose);
3071  }
3072 
3073  old_purpose = circ->purpose;
3074  circ->purpose = new_purpose;
3075 
3076  if (CIRCUIT_IS_ORIGIN(circ)) {
3078  old_purpose);
3079 
3081  }
3082 }
3083 
3085 void
3087 {
3088  const or_options_t *options = get_options();
3089  tor_assert(circ);
3090 
3091  /* XXXX This is a kludge; we're only keeping it around in case there's
3092  * something that doesn't check unusable_for_new_conns, and to avoid
3093  * deeper refactoring of our expiration logic. */
3094  if (! circ->base_.timestamp_dirty)
3095  circ->base_.timestamp_dirty = approx_time();
3096  if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
3097  circ->base_.timestamp_dirty = 1; /* prevent underflow */
3098  else
3099  circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
3100 
3101  circ->unusable_for_new_conns = 1;
3102 }
3103 
3109 void
3110 circuit_sent_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
3111 {
3112  if (!circ) return;
3113 
3114  tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE);
3115 
3117  tor_add_u32_nowrap(circ->n_delivered_written_circ_bw, relay_body_len);
3119  tor_add_u32_nowrap(circ->n_overhead_written_circ_bw,
3120  RELAY_PAYLOAD_SIZE-relay_body_len);
3121 }
3122 
3128 void
3129 circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
3130 {
3131  if (!circ) return;
3132 
3133  tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE);
3134 
3135  circ->n_delivered_read_circ_bw =
3136  tor_add_u32_nowrap(circ->n_delivered_read_circ_bw, relay_body_len);
3137  circ->n_overhead_read_circ_bw =
3138  tor_add_u32_nowrap(circ->n_overhead_read_circ_bw,
3139  RELAY_PAYLOAD_SIZE-relay_body_len);
3140 }
#define RELAY_PAYLOAD_SIZE
Definition: or.h:605
static void circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
Definition: circuituse.c:1649
#define CIRCUIT_PURPOSE_C_INTRODUCING
Definition: circuitlist.h:74
void rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
#define DIR_PURPOSE_UPLOAD_HSDESC
Definition: directory.h:72
Header file for circuitstats.c.
int channel_is_client(const channel_t *chan)
Definition: channel.c:2913
#define CIRCLAUNCH_ONEHOP_TUNNEL
Definition: circuituse.h:39
Header file for rendcommon.c.
#define CIRCLAUNCH_IS_INTERNAL
Definition: circuituse.h:46
rend_data_t * rend_data
origin_circuit_t * circuit_launch(uint8_t purpose, int flags)
Definition: circuituse.c:1928
struct circuit_guard_state_t * guard_state
const char * channel_get_canonical_remote_descr(channel_t *chan)
Definition: channel.c:2836
#define CIRCUIT_PURPOSE_IS_ORIGIN(p)
Definition: circuitlist.h:136
#define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
Definition: circuitlist.h:94
int routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
Definition: routerset.c:289
int rend_num_services(void)
Definition: rendservice.c:183
int connection_edge_update_circuit_isolation(const entry_connection_t *conn, origin_circuit_t *circ, int dry_run)
Header file containing common data for the whole HS subsytem.
#define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
Definition: circuitlist.h:87
int package_window
Definition: circuit_st.h:107
unsigned int hs_circ_has_timed_out
Header file for circuitbuild.c.
extend_info_t * extend_info_new(const char *nickname, const char *rsa_id_digest, const ed25519_public_key_t *ed_id, crypto_pk_t *onion_key, const curve25519_public_key_t *ntor_key, const tor_addr_t *addr, uint16_t port)
uint32_t n_delivered_written_circ_bw
Definition: node_st.h:28
struct smartlist_t * LongLivedPorts
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define TO_CONN(c)
Definition: or.h:735
path_state_bitfield_t path_state
static void consider_recording_trackhost(const entry_connection_t *conn, const origin_circuit_t *circ)
Definition: circuituse.c:2677
extend_info_t * extend_info_from_node(const node_t *node, int for_direct_connect)
#define IDLE_ONE_HOP_CIRC_TIMEOUT
Definition: circuituse.c:1555
void circuit_try_attaching_streams(origin_circuit_t *circ)
Definition: circuituse.c:1745
addr_policy_result_t
Definition: policies.h:38
Header file containing client data for the HS subsytem.
tor_addr_t addr
struct crypt_path_t * next
Definition: crypt_path_st.h:58
void pathbias_count_timeout(origin_circuit_t *circ)
void format_local_iso_time(char *buf, time_t t)
Definition: time_fmt.c:281
int MaxCircuitDirtiness
routerset_t * EntryNodes
Definition: or_options_st.h:78
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:154
#define MAX_UNUSED_OPEN_CIRCUITS
Definition: circuituse.c:1079
uint16_t marked_for_close
Definition: circuit_st.h:154
Header file for connection.c.
static int optimistic_data_enabled(void)
Definition: circuituse.c:2568
#define LD_GENERAL
Definition: log.h:58
int addressmap_have_mapping(const char *address, int update_expiry)
Definition: addressmap.c:545
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:143
#define CIRCLAUNCH_NEED_UPTIME
Definition: circuituse.h:41
time_t channel_when_last_xmit(channel_t *chan)
Definition: channel.c:3288
int rend_cmp_service_ids(const char *one, const char *two)
Definition: rendcommon.c:48
addr_policy_result_t compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port, const node_t *node)
Definition: policies.c:2918
uint8_t state
Definition: connection_st.h:44
const char * circuit_purpose_to_string(uint8_t purpose)
Definition: circuitlist.c:896
#define LOG_INFO
Definition: log.h:41
Header file for describe.c.
int DisablePredictedCircuits
Header file for nodelist.c.
crypt_path_t * cpath
Header file for directory.c.
int circuit_purpose_is_hidden_service(uint8_t purpose)
Definition: circuituse.c:1951
void smartlist_add(smartlist_t *sl, void *element)
#define timercmp(tv1, tv2, op)
Definition: timeval.h:59
char address[MAX_SOCKS_ADDR_LEN]
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:41
void circuit_expire_building(void)
Definition: circuituse.c:453
const char * safe_str_client(const char *address)
Definition: config.c:1059
void hs_stats_note_service_rendezvous_launch(void)
Definition: hs_stats.c:47
#define TO_CIRCUIT(x)
Definition: or.h:947
#define CIRCUIT_PURPOSE_C_REND_READY
Definition: circuitlist.h:84
Header file for config.c.
unsigned int relaxed_timeout
void router_do_reachability_checks(int test_or, int test_dir)
Definition: selftest.c:171
int circuit_stream_is_being_handled(entry_connection_t *conn, uint16_t port, int min)
Definition: circuituse.c:1030
int circuit_build_times_needs_circuits_now(const circuit_build_times_t *cbt)
static void circuit_expire_old_circuits_clientside(void)
Definition: circuituse.c:1469
const char * conn_type_to_string(int type)
Definition: connection.c:241
struct connection_t * linked_conn
int tor_inet_aton(const char *str, struct in_addr *addr)
Definition: inaddr.c:38
long tv_mdiff(const struct timeval *start, const struct timeval *end)
Definition: tvdiff.c:102
#define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
Definition: circuitlist.h:100
unsigned int reading_from_linked_conn
Definition: connection_st.h:73
const char * channel_state_to_string(channel_state_t state)
Definition: channel.c:315
uint16_t port
int circuit_event_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
Definition: circuitlist.c:496
int circuit_timeout_want_to_count_circ(const origin_circuit_t *circ)
Definition: circuitbuild.c:843
void connection_ap_mark_as_waiting_for_renddesc(entry_connection_t *entry_conn)
void circuit_build_times_count_timeout(circuit_build_times_t *cbt, int did_onehop)
static int have_performed_bandwidth_test
Definition: circuituse.c:1592
unsigned int is_ancient
#define tor_free(p)
Definition: malloc.h:52
#define tor_fragile_assert()
Definition: util_bug.h:221
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1244
#define LOG_NOTICE
Definition: log.h:46
int smartlist_contains_int_as_string(const smartlist_t *sl, int num)
Definition: smartlist.c:147
void circuit_build_needed_circs(time_t now)
Definition: circuituse.c:1329
const char * conn_state_to_string(int type, int state)
Definition: connection.c:273
#define DIR_PURPOSE_FETCH_CONSENSUS
Definition: directory.h:56
Header for tvdiff.c.
int MaxClientCircuitsPending
int circuit_get_cpath_len(origin_circuit_t *circ)
Definition: circuitlist.c:2039
uint8_t purpose
Definition: circuit_st.h:102
static void circuit_testing_opened(origin_circuit_t *circ)
Definition: circuituse.c:1631
Header file for hs_stats.c.
#define TESTING_CIRCUIT_INTERVAL
Definition: circuituse.c:1321
struct smartlist_t * TrackHostExits
int connection_ap_handshake_attach_circuit(entry_connection_t *conn)
Definition: circuituse.c:2800
origin_circuit_t * circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
Definition: circuitbuild.c:480
unsigned int purpose
Definition: connection_st.h:46
uint32_t n_overhead_read_circ_bw
#define tor_addr_from_in(dest, in)
Definition: address.h:291
int entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
Definition: entrynodes.c:2744
routerset_t * ExcludeExitNodes
Definition: or_options_st.h:88
#define ENTRY_TO_CONN(c)
Definition: or.h:738
void router_perform_bandwidth_test(int num_circs, time_t now)
Definition: selftest.c:276
static int n_circuit_failures
Definition: circuituse.c:1916
void connection_ap_attach_pending(int retry)
#define CIRCUIT_PURPOSE_C_HSDIR_GET
Definition: circuitlist.h:91
#define CIRCLAUNCH_IS_V3_RP
Definition: circuituse.h:49
unsigned int linked
Definition: connection_st.h:70
int circuit_should_use_vanguards(uint8_t purpose)
Definition: circuituse.c:1983
socks_request_t * socks_request
smartlist_t * circuit_get_global_origin_circuit_list(void)
Definition: circuitlist.c:699
unsigned int num_circuits_launched
#define MIN_CIRCUITS_HANDLING_STREAM
Definition: or.h:180
struct crypt_path_t * cpath_layer
Header file for policies.c.
int control_event_circuit_purpose_changed(origin_circuit_t *circ, int old_purpose)
Definition: control.c:5769
channel_t * p_chan
Definition: or_circuit_st.h:35
void entry_guard_failed(circuit_guard_state_t **guard_state_p)
Definition: entrynodes.c:2480
int ed25519_pubkey_eq(const ed25519_public_key_t *key1, const ed25519_public_key_t *key2)
#define LD_APP
Definition: log.h:74
Header file for channel.c.
tor_assert(buffer)
void circuit_build_times_set_timeout(circuit_build_times_t *cbt)
edge_connection_t * n_streams
Definition: or_circuit_st.h:42
void circuit_expire_old_circuits_serverside(time_t now)
Definition: circuituse.c:1562
origin_circuit_t * circuit_find_to_cannibalize(uint8_t purpose_to_produce, extend_info_t *info, int flags)
Definition: circuitlist.c:1901
#define NUM_PARALLEL_TESTING_CIRCS
Definition: circuituse.c:1588
int strcasecmpend(const char *s1, const char *s2)
Definition: util_string.c:258
void circpad_machine_event_circ_has_streams(origin_circuit_t *circ)
Header for fp.c.
time_t timestamp_dirty
Definition: circuit_st.h:152
#define END_CIRC_REASON_MEASUREMENT_EXPIRED
Definition: or.h:300
#define LD_CIRC
Definition: log.h:78
uint8_t state
Definition: circuit_st.h:101
void circuit_sent_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
Definition: circuituse.c:3110
Header file for routermode.c.
int connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit_node)
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
routerset_t * ExcludeNodes
Definition: or_options_st.h:84
circid_t n_circ_id
Definition: circuit_st.h:67
int connection_edge_compatible_with_circuit(const entry_connection_t *conn, const origin_circuit_t *circ)
unsigned int received_destroy
Definition: circuit_st.h:99
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition: directory.c:77
#define ISO_SOCKSAUTH
Definition: or.h:960
Header file for circuitpadding.c.
static time_t last_expired_clientside_circuits
Definition: circuituse.c:864
#define DIGEST_LEN
Definition: digest_sizes.h:20
double get_circuit_build_timeout_ms(void)
Definition: circuitstats.c:104
uint32_t n_delivered_read_circ_bw
#define CIRCUIT_PURPOSE_TESTING
Definition: circuitlist.h:115
const char * node_describe(const node_t *node)
Definition: describe.c:101
Header file for circuitbuild.c.
#define END_CIRC_AT_ORIGIN
Definition: or.h:305
Master header file for Tor-specific functionality.
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:31
void circuit_discard_optional_exit_enclaves(extend_info_t *info)
#define DIR_PURPOSE_FETCH_HSDESC
Definition: directory.h:74
void circpad_machine_event_circ_has_no_streams(origin_circuit_t *circ)
Header file for circuitbuild.c.
connection_t * connection_get_by_type(int type)
Definition: connection.c:4444
static void circuit_increment_failure_count(void)
Definition: circuituse.c:2169
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1185
void circuit_build_times_mark_circ_as_measurement_only(origin_circuit_t *circ)
Definition: circuitstats.c:640
uint16_t marked_for_close
unsigned int chosen_exit_optional
#define AP_CONN_STATE_CIRCUIT_WAIT
unsigned int is_bad_for_new_circs
Definition: channel.h:425
int hexdigest_to_digest(const char *hexdigest, char *digest)
Definition: routerlist.c:663
int rep_hist_get_predicted_internal(time_t now, int *need_uptime, int *need_capacity)
Header file containing circuit and connection identifier data for the whole HS subsytem.
#define LOG_WARN
Definition: log.h:49
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:758
unsigned int type
Definition: connection_st.h:45
unsigned int edge_has_sent_end
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:260
static int count_pending_general_client_circuits(void)
Definition: circuituse.c:393
Header file for circuituse.c.
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:476
static int circuit_get_open_circ_or_launch(entry_connection_t *conn, uint8_t desired_circuit_purpose, origin_circuit_t **circp)
Definition: circuituse.c:2196
void circuit_clear_isolation(origin_circuit_t *circ)
const node_t * build_state_get_exit_node(cpath_build_state_t *state)
#define CIRCUIT_PURPOSE_C_ESTABLISH_REND
Definition: circuitlist.h:82
void smartlist_del(smartlist_t *sl, int idx)
void addressmap_clean(time_t now)
Definition: addressmap.c:321
circid_t p_circ_id
Definition: or_circuit_st.h:31
void circuit_remove_handled_ports(smartlist_t *needed_ports)
Definition: circuituse.c:1005
#define CIRCUIT_PURPOSE_S_CONNECT_REND
Definition: circuitlist.h:106
#define LD_REND
Definition: log.h:80
routerset_t * HSLayer2Nodes
Header file for circuitlist.c.
#define CIRCUIT_PURPOSE_PATH_BIAS_TESTING
Definition: circuitlist.h:119
void circuit_expire_old_circs_as_needed(time_t now)
Definition: circuituse.c:1352
Header file for rendservice.c.
void circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
Definition: circuitbuild.c:358
static int connection_ap_get_nonrend_circ_purpose(const entry_connection_t *conn)
Definition: circuituse.c:2767
#define LD_OR
Definition: log.h:88
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
void circuit_expire_waiting_for_better_guard(void)
Definition: circuituse.c:849
int hostname_in_track_host_exits(const or_options_t *options, const char *address)
Definition: circuituse.c:2655
#define CIRCLAUNCH_NEED_CAPACITY
Definition: circuituse.h:43
int pathbias_check_close(origin_circuit_t *ocirc, int reason)
int connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
#define CIRCUIT_PURPOSE_S_INTRO
Definition: circuitlist.h:103
int control_event_circuit_cannibalized(origin_circuit_t *circ, int old_purpose, const struct timeval *old_tv_created)
Definition: control.c:5783
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
#define LD_DIR
Definition: log.h:84
#define CIRCUIT_PURPOSE_HS_VANGUARDS
Definition: circuitlist.h:127
void addressmap_register(const char *address, char *new_address, time_t expires, addressmap_entry_source_t source, const int wildcard_addr, const int wildcard_new_addr)
Definition: addressmap.c:577
Header file containing circuit data for the whole HS subsytem.
struct crypt_path_t * prev
Definition: crypt_path_st.h:61
cpath_build_state_t * build_state
int circuit_build_times_enough_to_compute(const circuit_build_times_t *cbt)
Definition: circuitstats.c:258
Header file for connection_edge.c.
void circuit_log_ancient_one_hop_circuits(int age)
Definition: circuituse.c:873
int TrackHostExitsExpire
routerset_t * HSLayer3Nodes
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:163
void circuit_has_opened(origin_circuit_t *circ)
Definition: circuituse.c:1671
const char * circuit_state_to_string(int state)
Definition: circuitlist.c:758
#define MAX_CIRCUIT_FAILURES
Definition: circuituse.c:1923
static int circuit_try_clearing_isolation_state(origin_circuit_t *circ)
Definition: circuituse.c:1723
struct hs_ident_circuit_t * hs_ident
static int cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
Definition: circuituse.c:2555
origin_circuit_t * circuit_launch_by_extend_info(uint8_t purpose, extend_info_t *extend_info, int flags)
Definition: circuituse.c:2053
edge_connection_t * p_streams
char identity_digest[DIGEST_LEN]
unsigned int has_opened
#define CIRCUIT_PURPOSE_S_HSDIR_POST
Definition: circuitlist.h:111
const char * escaped(const char *s)
Definition: escape.c:126
#define DIR_PURPOSE_UPLOAD_RENDDESC_V2
Definition: directory.h:65
edge_connection_t * resolving_streams
Definition: or_circuit_st.h:45
void hs_client_note_connection_attempt_succeeded(const edge_connection_t *conn)
Definition: hs_client.c:1242
#define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
Definition: circuitlist.h:77
void routerlist_retry_directory_downloads(time_t now)
Definition: routerlist.c:2223
#define CIRCUIT_PURPOSE_C_REND_JOINED
Definition: circuitlist.h:89
int hs_client_refetch_hsdesc(const ed25519_public_key_t *identity_pk)
Definition: hs_client.c:1345
uint8_t state
Definition: crypt_path_st.h:54
void circuit_build_failed(origin_circuit_t *circ)
Definition: circuituse.c:1762
circuit_build_times_t * get_circuit_build_times_mutable(void)
Definition: circuitstats.c:88
struct timeval timestamp_began
Definition: circuit_st.h:130
#define log_fn(severity, domain, args,...)
Definition: log.h:255
unsigned int isolation_values_set
#define AP_CONN_STATE_CONTROLLER_WAIT
int circuit_build_times_count_close(circuit_build_times_t *cbt, int did_onehop, time_t start_time)
static int circuit_should_cannibalize_to_build(uint8_t purpose_to_build, int has_extend_info, int onehop_tunnel)
Definition: circuituse.c:2005
void mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
Definition: circuituse.c:3086
static void circuit_launch_predicted_hs_circ(int flags)
Definition: circuituse.c:1216
int connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
Definition: circuituse.c:2715
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:151
Header file for control.c.
#define tor_addr_eq(a, b)
Definition: address.h:244
double get_circuit_build_close_time_ms(void)
Definition: circuitstats.c:96
void circuit_reset_failure_count(int timeout)
Definition: circuituse.c:2180
unsigned int hold_open_until_flushed
Definition: connection_st.h:56
unsigned int socks_iso_keep_alive
const circuit_build_times_t * get_circuit_build_times(void)
Definition: circuitstats.c:81
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:71
time_t approx_time(void)
Definition: approx_time.c:32
void connection_ap_fail_onehop(const char *failed_digest, cpath_build_state_t *build_state)
unsigned int isolation_any_streams_attached
smartlist_t * prepend_policy
#define LOG_DEBUG
Definition: log.h:38
int router_exit_policy_all_nodes_reject(const tor_addr_t *addr, uint16_t port, int need_uptime)
Definition: nodelist.c:2114
void pathbias_count_use_attempt(origin_circuit_t *circ)
Definition: circpathbias.c:596
static int circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob, const entry_connection_t *conn)
Definition: circuituse.c:245
const char * marked_for_close_file
time_t timestamp_created
extend_info_t * extend_info
Definition: crypt_path_st.h:47
int n_bits_set_u8(uint8_t v)
Definition: bits.c:72
void circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
Definition: circuituse.c:3048
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:504
Header file for selftest.c.
struct timeval timestamp_created
Definition: circuit_st.h:133
#define MAX(a, b)
Definition: cmp.h:22
#define CONN_TYPE_DIR
Definition: connection.h:35
struct circuit_t * on_circuit
int entry_list_is_constrained(const or_options_t *options)
Definition: entrynodes.c:3270
unsigned int edge_blocked_on_circ
void reset_bandwidth_test(void)
Definition: circuituse.c:1597
void circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
Definition: circuituse.c:3129
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1383
int connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
uint32_t n_overhead_written_circ_bw
extend_info_t * chosen_exit
static origin_circuit_t * circuit_get_best(const entry_connection_t *conn, int must_be_open, uint8_t purpose, int need_uptime, int need_internal)
Definition: circuituse.c:337
struct edge_connection_t * next_stream
tor_addr_t addr
unsigned int may_use_optimistic_data
#define CIRCUIT_PURPOSE_S_REND_JOINED
Definition: circuitlist.h:109
#define CONN_TYPE_AP
Definition: connection.h:31
Header file for rendclient.c.
int circuit_any_opened_circuits(void)
Definition: circuitlist.c:714
int circuit_enough_testing_circs(void)
Definition: circuituse.c:1607
static void link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ, crypt_path_t *cpath)
Definition: circuituse.c:2587
rend_data_t * rend_data
int guards_retry_optimistic(const or_options_t *options)
Definition: entrynodes.c:3708
void rend_client_refetch_v2_renddesc(rend_data_t *rend_query)
Definition: rendclient.c:697
static void circuit_predict_and_launch_new(void)
Definition: circuituse.c:1235
const char * build_state_get_exit_nickname(cpath_build_state_t *state)
int proxy_mode(const or_options_t *options)
Definition: routermode.c:30
static int circuit_matches_with_rend_stream(const edge_connection_t *edge_conn, const origin_circuit_t *origin_circ)
Definition: circuituse.c:80
#define DIR_PURPOSE_FETCH_RENDDESC_V2
Definition: directory.h:68
int check_whether_orport_reachable(const or_options_t *options)
Definition: selftest.c:74
void connection_ap_rescan_and_attach_pending(void)
#define CIRCUIT_PURPOSE_COUNTS_TOWARDS_MAXPENDING(p)
Definition: circuitlist.h:156
#define LD_HEARTBEAT
Definition: log.h:99
Header file for networkstatus.c.
#define LD_BUG
Definition: log.h:82
int circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
static int circuit_is_acceptable(const origin_circuit_t *origin_circ, const entry_connection_t *conn, int must_be_open, uint8_t purpose, int need_uptime, int need_internal, time_t now)
Definition: circuituse.c:110
Header file for routerlist.c.
static int did_circs_fail_last_period
Definition: circuituse.c:1919
int circuit_build_times_disabled(const or_options_t *options)
Definition: circuitstats.c:120
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1089
channel_t * n_chan
Definition: circuit_st.h:58
void circpad_machine_event_circ_purpose_changed(origin_circuit_t *circ)