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