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