Tor  0.4.4.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-2020, 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,
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 iff it has been specified in an
779  * INTRODUCE1 cell sent to a hidden service. */
780  if (!hs_circ_is_rend_sent_in_intro1(CONST_TO_ORIGIN_CIRCUIT(victim))) {
781  break;
782  }
783  /* fallthrough! */
786  /* If we have reached this line, we want to spare the circ for now. */
787  log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
788  "as timed-out HS circ",
789  (unsigned)victim->n_circ_id,
790  victim->state, circuit_state_to_string(victim->state),
791  victim->purpose);
793  continue;
794  default:
795  break;
796  }
797  }
798 
799  /* If this is a service-side rendezvous circuit which is far
800  * enough along in connecting to its destination, consider sparing
801  * it. */
802  if (!(TO_ORIGIN_CIRCUIT(victim)->hs_circ_has_timed_out) &&
803  victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
804  log_info(LD_CIRC,"Marking circ %u (state %d:%s, purpose %d) "
805  "as timed-out HS circ; relaunching rendezvous attempt.",
806  (unsigned)victim->n_circ_id,
807  victim->state, circuit_state_to_string(victim->state),
808  victim->purpose);
811  continue;
812  }
813 
814  if (victim->n_chan)
815  log_info(LD_CIRC,
816  "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
817  "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
818  channel_get_canonical_remote_descr(victim->n_chan),
819  (unsigned)victim->n_circ_id,
820  TO_ORIGIN_CIRCUIT(victim)->has_opened,
821  victim->state, circuit_state_to_string(victim->state),
822  victim->purpose,
823  TO_ORIGIN_CIRCUIT(victim)->build_state ?
824  TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
825  -1);
826  else
827  log_info(LD_CIRC,
828  "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
829  TO_ORIGIN_CIRCUIT(victim)->global_identifier,
830  (unsigned)victim->n_circ_id,
831  TO_ORIGIN_CIRCUIT(victim)->has_opened,
832  victim->state,
833  circuit_state_to_string(victim->state), victim->purpose,
834  TO_ORIGIN_CIRCUIT(victim)->build_state ?
835  TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
836  -1);
837 
839  if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
840  circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
841  else
842  circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
843 
845  } SMARTLIST_FOREACH_END(victim);
846 }
847 
848 /**
849  * Mark for close all circuits that start here, that were built through a
850  * guard we weren't sure if we wanted to use, and that have been waiting
851  * around for way too long.
852  */
853 void
855 {
857  origin_circuit_t *, circ) {
858  if (TO_CIRCUIT(circ)->marked_for_close)
859  continue;
860  if (circ->guard_state == NULL)
861  continue;
863  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
864  } SMARTLIST_FOREACH_END(circ);
865 }
866 
867 /** For debugging #8387: track when we last called
868  * circuit_expire_old_circuits_clientside. */
870 
871 /**
872  * As a diagnostic for bug 8387, log information about how many one-hop
873  * circuits we have around that have been there for at least <b>age</b>
874  * seconds. Log a few of them. Ignores Single Onion Service intro, it is
875  * expected to be long-term one-hop circuits.
876  */
877 void
879 {
880 #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
881  time_t now = time(NULL);
882  time_t cutoff = now - age;
883  int n_found = 0;
884  smartlist_t *log_these = smartlist_new();
885  const or_options_t *options = get_options();
886 
888  const origin_circuit_t *ocirc;
889  if (! CIRCUIT_IS_ORIGIN(circ))
890  continue;
891  if (circ->timestamp_created.tv_sec >= cutoff)
892  continue;
893  /* Single Onion Services deliberately make long term one-hop intro
894  * and rendezvous connections. Don't log the established ones. */
895  if (rend_service_allow_non_anonymous_connection(options) &&
896  (circ->purpose == CIRCUIT_PURPOSE_S_INTRO ||
897  circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED))
898  continue;
899  ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
900 
901  if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
902  ++n_found;
903 
904  if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
905  smartlist_add(log_these, (origin_circuit_t*) ocirc);
906  }
907  }
908  SMARTLIST_FOREACH_END(circ);
909 
910  if (n_found == 0)
911  goto done;
912 
913  log_notice(LD_HEARTBEAT,
914  "Diagnostic for issue 8387: Found %d one-hop circuits more "
915  "than %d seconds old! Logging %d...",
916  n_found, age, smartlist_len(log_these));
917 
918  SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
919  char created[ISO_TIME_LEN+1];
920  int stream_num;
921  const edge_connection_t *conn;
922  char *dirty = NULL;
923  const circuit_t *circ = TO_CIRCUIT(ocirc);
924 
925  format_local_iso_time(created,
926  (time_t)circ->timestamp_created.tv_sec);
927 
928  if (circ->timestamp_dirty) {
929  char dirty_since[ISO_TIME_LEN+1];
930  format_local_iso_time(dirty_since, circ->timestamp_dirty);
931 
932  tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
933  dirty_since, (long)(now - circ->timestamp_dirty),
934  (long) options->MaxCircuitDirtiness);
935  } else {
936  dirty = tor_strdup("Not marked dirty");
937  }
938 
939  log_notice(LD_HEARTBEAT, " #%d created at %s. %s, %s. %s for close. "
940  "Package window: %d. "
941  "%s for new conns. %s.",
942  ocirc_sl_idx,
943  created,
946  circ->marked_for_close ? "Marked" : "Not marked",
947  circ->package_window,
948  ocirc->unusable_for_new_conns ? "Not usable" : "usable",
949  dirty);
950  tor_free(dirty);
951 
952  stream_num = 0;
953  for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
954  const connection_t *c = TO_CONN(conn);
955  char stream_created[ISO_TIME_LEN+1];
956  if (++stream_num >= 5)
957  break;
958 
959  format_local_iso_time(stream_created, c->timestamp_created);
960 
961  log_notice(LD_HEARTBEAT, " Stream#%d created at %s. "
962  "%s conn in state %s. "
963  "It is %slinked and %sreading from a linked connection %p. "
964  "Package window %d. "
965  "%s for close (%s:%d). Hold-open is %sset. "
966  "Has %ssent RELAY_END. %s on circuit.",
967  stream_num,
968  stream_created,
971  c->linked ? "" : "not ",
972  c->reading_from_linked_conn ? "": "not",
973  c->linked_conn,
974  conn->package_window,
975  c->marked_for_close ? "Marked" : "Not marked",
977  c->marked_for_close,
978  c->hold_open_until_flushed ? "" : "not ",
979  conn->edge_has_sent_end ? "" : "not ",
980  conn->edge_blocked_on_circ ? "Blocked" : "Not blocked");
981  if (! c->linked_conn)
982  continue;
983 
984  c = c->linked_conn;
985 
986  log_notice(LD_HEARTBEAT, " Linked to %s connection in state %s "
987  "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
990  c->purpose,
991  c->marked_for_close ? "Marked" : "Not marked",
993  c->marked_for_close,
994  c->hold_open_until_flushed ? "" : "not ");
995  }
996  } SMARTLIST_FOREACH_END(ocirc);
997 
998  log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
999  "circuit_expire_old_circuits_clientside().",
1000  (long)(now - last_expired_clientside_circuits));
1001 
1002  done:
1003  smartlist_free(log_these);
1004 }
1005 
1006 /** Remove any elements in <b>needed_ports</b> that are handled by an
1007  * open or in-progress circuit.
1008  */
1009 void
1011 {
1012  int i;
1013  uint16_t *port;
1014 
1015  for (i = 0; i < smartlist_len(needed_ports); ++i) {
1016  port = smartlist_get(needed_ports, i);
1017  tor_assert(*port);
1018  if (circuit_stream_is_being_handled(NULL, *port,
1020  log_debug(LD_CIRC,"Port %d is already being handled; removing.", *port);
1021  smartlist_del(needed_ports, i--);
1022  tor_free(port);
1023  } else {
1024  log_debug(LD_CIRC,"Port %d is not handled.", *port);
1025  }
1026  }
1027 }
1028 
1029 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
1030  * will have an acceptable exit node for exit stream <b>conn</b> if it
1031  * is defined, else for "*:port".
1032  * Else return 0.
1033  */
1034 int
1036  uint16_t port, int min)
1037 {
1038  const node_t *exitnode;
1039  int num=0;
1040  time_t now = time(NULL);
1041  int need_uptime = smartlist_contains_int_as_string(
1042  get_options()->LongLivedPorts,
1043  conn ? conn->socks_request->port : port);
1044 
1046  if (CIRCUIT_IS_ORIGIN(circ) &&
1047  !circ->marked_for_close &&
1048  circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
1049  (!circ->timestamp_dirty ||
1050  circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
1051  origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1052  cpath_build_state_t *build_state = origin_circ->build_state;
1053  if (build_state->is_internal || build_state->onehop_tunnel)
1054  continue;
1055  if (origin_circ->unusable_for_new_conns)
1056  continue;
1057  if (origin_circ->isolation_values_set &&
1058  (conn == NULL ||
1059  !connection_edge_compatible_with_circuit(conn, origin_circ)))
1060  continue;
1061 
1062  exitnode = build_state_get_exit_node(build_state);
1063  if (exitnode && (!need_uptime || build_state->need_uptime)) {
1064  int ok;
1065  if (conn) {
1066  ok = connection_ap_can_use_exit(conn, exitnode);
1067  } else {
1069  r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
1071  }
1072  if (ok) {
1073  if (++num >= min)
1074  return 1;
1075  }
1076  }
1077  }
1078  }
1079  SMARTLIST_FOREACH_END(circ);
1080  return 0;
1081 }
1082 
1083 /** Don't keep more than this many unused open circuits around. */
1084 #define MAX_UNUSED_OPEN_CIRCUITS 14
1085 
1086 /* Return true if a circuit is available for use, meaning that it is open,
1087  * clean, usable for new multi-hop connections, and a general purpose origin
1088  * circuit.
1089  * Accept any kind of circuit, return false if the above conditions are not
1090  * met. */
1091 STATIC int
1092 circuit_is_available_for_use(const circuit_t *circ)
1093 {
1094  const origin_circuit_t *origin_circ;
1095  cpath_build_state_t *build_state;
1096 
1097  if (!CIRCUIT_IS_ORIGIN(circ))
1098  return 0; /* We first filter out only origin circuits before doing the
1099  following checks. */
1100  if (circ->marked_for_close)
1101  return 0; /* Don't mess with marked circs */
1102  if (circ->timestamp_dirty)
1103  return 0; /* Only count clean circs */
1104  if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1106  return 0; /* We only pay attention to general purpose circuits.
1107  General purpose circuits are always origin circuits. */
1108 
1109  origin_circ = CONST_TO_ORIGIN_CIRCUIT(circ);
1110  if (origin_circ->unusable_for_new_conns)
1111  return 0;
1112 
1113  build_state = origin_circ->build_state;
1114  if (build_state->onehop_tunnel)
1115  return 0;
1116 
1117  return 1;
1118 }
1119 
1120 /* Return true if we need any more exit circuits.
1121  * needs_uptime and needs_capacity are set only if we need more exit circuits.
1122  * Check if we know of a port that's been requested recently and no circuit
1123  * is currently available that can handle it. */
1124 STATIC int
1125 needs_exit_circuits(time_t now, int *needs_uptime, int *needs_capacity)
1126 {
1127  return (!circuit_all_predicted_ports_handled(now, needs_uptime,
1128  needs_capacity) &&
1129  router_have_consensus_path() == CONSENSUS_PATH_EXIT);
1130 }
1131 
1132 /* Hidden services need at least this many internal circuits */
1133 #define SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS 3
1134 
1135 /* Return true if we need any more hidden service server circuits.
1136  * HS servers only need an internal circuit. */
1137 STATIC int
1138 needs_hs_server_circuits(time_t now, int num_uptime_internal)
1139 {
1141  /* No services, we don't need anything. */
1142  goto no_need;
1143  }
1144 
1145  if (num_uptime_internal >= SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS) {
1146  /* We have sufficient amount of internal circuit. */
1147  goto no_need;
1148  }
1149 
1150  if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN) {
1151  /* Consensus hasn't been checked or might be invalid so requesting
1152  * internal circuits is not wise. */
1153  goto no_need;
1154  }
1155 
1156  /* At this point, we need a certain amount of circuits and we will most
1157  * likely use them for rendezvous so we note down the use of internal
1158  * circuit for our prediction for circuit needing uptime and capacity. */
1159  rep_hist_note_used_internal(now, 1, 1);
1160 
1161  return 1;
1162  no_need:
1163  return 0;
1164 }
1165 
1166 /* We need at least this many internal circuits for hidden service clients */
1167 #define SUFFICIENT_INTERNAL_HS_CLIENTS 3
1168 
1169 /* We need at least this much uptime for internal circuits for hidden service
1170  * clients */
1171 #define SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS 2
1172 
1173 /* Return true if we need any more hidden service client circuits.
1174  * HS clients only need an internal circuit. */
1175 STATIC int
1176 needs_hs_client_circuits(time_t now, int *needs_uptime, int *needs_capacity,
1177  int num_internal, int num_uptime_internal)
1178 {
1179  int used_internal_recently = rep_hist_get_predicted_internal(now,
1180  needs_uptime,
1181  needs_capacity);
1182  int requires_uptime = num_uptime_internal <
1183  SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS &&
1184  needs_uptime;
1185 
1186  return (used_internal_recently &&
1187  (requires_uptime || num_internal < SUFFICIENT_INTERNAL_HS_CLIENTS) &&
1188  router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN);
1189 }
1190 
1191 /* This is how many circuits can be opened concurrently during the cbt learning
1192  * phase. This number cannot exceed the tor-wide MAX_UNUSED_OPEN_CIRCUITS. */
1193 #define DFLT_CBT_UNUSED_OPEN_CIRCS (10)
1194 #define MIN_CBT_UNUSED_OPEN_CIRCS 0
1195 #define MAX_CBT_UNUSED_OPEN_CIRCS MAX_UNUSED_OPEN_CIRCUITS
1196 
1197 /* Return true if we need more circuits for a good build timeout.
1198  * XXXX make the assumption that build timeout streams should be
1199  * created whenever we can build internal circuits. */
1200 STATIC int
1201 needs_circuits_for_build(int num)
1202 {
1203  if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
1204  if (num < networkstatus_get_param(NULL, "cbtmaxopencircs",
1205  DFLT_CBT_UNUSED_OPEN_CIRCS,
1206  MIN_CBT_UNUSED_OPEN_CIRCS,
1207  MAX_CBT_UNUSED_OPEN_CIRCS) &&
1210  return 1;
1211  }
1212  }
1213  return 0;
1214 }
1215 
1216 /**
1217  * Launch the appropriate type of predicted circuit for hidden
1218  * services, depending on our options.
1219  */
1220 static void
1222 {
1223  /* K.I.S.S. implementation of bug #23101: If we are using
1224  * vanguards or pinned middles, pre-build a specific purpose
1225  * for HS circs. */
1228  } else {
1229  /* If no vanguards, then no HS-specific prebuilt circuits are needed.
1230  * Normal GENERAL circs are fine */
1232  }
1233 }
1234 
1235 /** Determine how many circuits we have open that are clean,
1236  * Make sure it's enough for all the upcoming behaviors we predict we'll have.
1237  * But put an upper bound on the total number of circuits.
1238  */
1239 static void
1241 {
1242  int num=0, num_internal=0, num_uptime_internal=0;
1243  int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
1244  int port_needs_uptime=0, port_needs_capacity=1;
1245  time_t now = time(NULL);
1246  int flags = 0;
1247 
1248  /* Count how many of each type of circuit we currently have. */
1250  if (!circuit_is_available_for_use(circ))
1251  continue;
1252 
1253  num++;
1254 
1255  cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
1256  if (build_state->is_internal)
1257  num_internal++;
1258  if (build_state->need_uptime && build_state->is_internal)
1259  num_uptime_internal++;
1260  }
1261  SMARTLIST_FOREACH_END(circ);
1262 
1263  /* If that's enough, then stop now. */
1264  if (num >= MAX_UNUSED_OPEN_CIRCUITS)
1265  return;
1266 
1267  if (needs_exit_circuits(now, &port_needs_uptime, &port_needs_capacity)) {
1268  if (port_needs_uptime)
1269  flags |= CIRCLAUNCH_NEED_UPTIME;
1270  if (port_needs_capacity)
1271  flags |= CIRCLAUNCH_NEED_CAPACITY;
1272 
1273  log_info(LD_CIRC,
1274  "Have %d clean circs (%d internal), need another exit circ.",
1275  num, num_internal);
1277  return;
1278  }
1279 
1280  if (needs_hs_server_circuits(now, num_uptime_internal)) {
1283 
1284  log_info(LD_CIRC,
1285  "Have %d clean circs (%d internal), need another internal "
1286  "circ for my hidden service.",
1287  num, num_internal);
1289  return;
1290  }
1291 
1292  if (needs_hs_client_circuits(now, &hidserv_needs_uptime,
1293  &hidserv_needs_capacity,
1294  num_internal, num_uptime_internal))
1295  {
1296  if (hidserv_needs_uptime)
1297  flags |= CIRCLAUNCH_NEED_UPTIME;
1298  if (hidserv_needs_capacity)
1299  flags |= CIRCLAUNCH_NEED_CAPACITY;
1300  flags |= CIRCLAUNCH_IS_INTERNAL;
1301 
1302  log_info(LD_CIRC,
1303  "Have %d clean circs (%d uptime-internal, %d internal), need"
1304  " another hidden service circ.",
1305  num, num_uptime_internal, num_internal);
1306 
1308  return;
1309  }
1310 
1311  if (needs_circuits_for_build(num)) {
1312  flags = CIRCLAUNCH_NEED_CAPACITY;
1313  /* if there are no exits in the consensus, make timeout
1314  * circuits internal */
1315  if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
1316  flags |= CIRCLAUNCH_IS_INTERNAL;
1317 
1318  log_info(LD_CIRC,
1319  "Have %d clean circs need another buildtime test circ.", num);
1321  return;
1322  }
1323 }
1324 
1325 /** Build a new test circuit every 5 minutes */
1326 #define TESTING_CIRCUIT_INTERVAL 300
1327 
1328 /** This function is called once a second, if router_have_minimum_dir_info()
1329  * is true. Its job is to make sure all services we offer have enough circuits
1330  * available. Some services just want enough circuits for current tasks,
1331  * whereas others want a minimum set of idle circuits hanging around.
1332  */
1333 void
1335 {
1336  const or_options_t *options = get_options();
1337 
1338  /* launch a new circ for any pending streams that need one
1339  * XXXX make the assumption that (some) AP streams (i.e. HS clients)
1340  * don't require an exit circuit, review in #13814.
1341  * This allows HSs to function in a consensus without exits. */
1342  if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
1344 
1346 
1347  if (!options->DisablePredictedCircuits)
1349 }
1350 
1351 /**
1352  * Called once a second either directly or from
1353  * circuit_build_needed_circs(). As appropriate (once per NewCircuitPeriod)
1354  * resets failure counts and expires old circuits.
1355  */
1356 void
1358 {
1359  static time_t time_to_expire_and_reset = 0;
1360 
1361  if (time_to_expire_and_reset < now) {
1363  time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
1364  if (proxy_mode(get_options()))
1365  addressmap_clean(now);
1367 
1368 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
1369 
1370  /* If we ever re-enable, this has to move into
1371  * circuit_build_needed_circs */
1372 
1373  circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
1374  if (get_options()->RunTesting &&
1375  circ &&
1376  circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
1377  log_fn(LOG_INFO,"Creating a new testing circuit.");
1379  }
1380 #endif /* 0 */
1381  }
1382 }
1383 
1384 /** If the stream <b>conn</b> is a member of any of the linked
1385  * lists of <b>circ</b>, then remove it from the list.
1386  */
1387 void
1389 {
1390  edge_connection_t *prevconn;
1391 
1392  tor_assert(circ);
1393  tor_assert(conn);
1394 
1395  if (conn->base_.type == CONN_TYPE_AP) {
1396  entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
1397  entry_conn->may_use_optimistic_data = 0;
1398  }
1399  conn->cpath_layer = NULL; /* don't keep a stale pointer */
1400  conn->on_circuit = NULL;
1401 
1402  if (CIRCUIT_IS_ORIGIN(circ)) {
1403  origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
1404  int removed = 0;
1405  if (conn == origin_circ->p_streams) {
1406  origin_circ->p_streams = conn->next_stream;
1407  removed = 1;
1408  } else {
1409  for (prevconn = origin_circ->p_streams;
1410  prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1411  prevconn = prevconn->next_stream)
1412  ;
1413  if (prevconn && prevconn->next_stream) {
1414  prevconn->next_stream = conn->next_stream;
1415  removed = 1;
1416  }
1417  }
1418  if (removed) {
1419  log_debug(LD_APP, "Removing stream %d from circ %u",
1420  conn->stream_id, (unsigned)circ->n_circ_id);
1421 
1422  /* If the stream was removed, and it was a rend stream, decrement the
1423  * number of streams on the circuit associated with the rend service.
1424  */
1425  if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
1426  hs_dec_rdv_stream_counter(origin_circ);
1427  }
1428 
1429  /* If there are no more streams on this circ, tell circpad */
1430  if (!origin_circ->p_streams)
1432 
1433  return;
1434  }
1435  } else {
1436  or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1437  if (conn == or_circ->n_streams) {
1438  or_circ->n_streams = conn->next_stream;
1439  return;
1440  }
1441  if (conn == or_circ->resolving_streams) {
1442  or_circ->resolving_streams = conn->next_stream;
1443  return;
1444  }
1445 
1446  for (prevconn = or_circ->n_streams;
1447  prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1448  prevconn = prevconn->next_stream)
1449  ;
1450  if (prevconn && prevconn->next_stream) {
1451  prevconn->next_stream = conn->next_stream;
1452  return;
1453  }
1454 
1455  for (prevconn = or_circ->resolving_streams;
1456  prevconn && prevconn->next_stream && prevconn->next_stream != conn;
1457  prevconn = prevconn->next_stream)
1458  ;
1459  if (prevconn && prevconn->next_stream) {
1460  prevconn->next_stream = conn->next_stream;
1461  return;
1462  }
1463  }
1464 
1465  log_warn(LD_BUG,"Edge connection not in circuit's list.");
1466  /* Don't give an error here; it's harmless. */
1468 }
1469 
1470 /** Find each circuit that has been unused for too long, or dirty
1471  * for too long and has no streams on it: mark it for close.
1472  */
1473 STATIC void
1475 {
1476  struct timeval cutoff, now;
1477 
1478  tor_gettimeofday(&now);
1479  last_expired_clientside_circuits = now.tv_sec;
1480 
1482  if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
1483  continue;
1484 
1485  cutoff = now;
1486  cutoff.tv_sec -= TO_ORIGIN_CIRCUIT(circ)->circuit_idle_timeout;
1487 
1488  /* If the circuit has been dirty for too long, and there are no streams
1489  * on it, mark it for close.
1490  */
1491  if (circ->timestamp_dirty &&
1492  circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
1493  now.tv_sec &&
1494  !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
1495  log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
1496  "purpose %d)",
1497  (unsigned)circ->n_circ_id,
1498  (long)(now.tv_sec - circ->timestamp_dirty),
1499  circ->purpose);
1500  /* Don't do this magic for testing circuits. Their death is governed
1501  * by circuit_expire_building */
1502  if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
1503  circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1504  } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
1505  if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
1506  if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
1507  circ->purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1508  circ->purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1509  circ->purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1510  circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
1511  circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1512  circ->purpose == CIRCUIT_PURPOSE_TESTING ||
1513  circ->purpose == CIRCUIT_PURPOSE_C_CIRCUIT_PADDING ||
1514  (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
1515  circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
1516  circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
1517  log_info(LD_CIRC,
1518  "Closing circuit %"PRIu32
1519  " that has been unused for %ld msec.",
1520  TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1521  tv_mdiff(&circ->timestamp_began, &now));
1522  circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1523  } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
1524  /* Server-side rend joined circuits can end up really old, because
1525  * they are reused by clients for longer than normal. The client
1526  * controls their lifespan. (They never become dirty, because
1527  * connection_exit_begin_conn() never marks anything as dirty.)
1528  * Similarly, server-side intro circuits last a long time. */
1529  if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
1530  circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
1531  log_notice(LD_CIRC,
1532  "Ancient non-dirty circuit %d is still around after "
1533  "%ld milliseconds. Purpose: %d (%s)",
1534  TO_ORIGIN_CIRCUIT(circ)->global_identifier,
1535  tv_mdiff(&circ->timestamp_began, &now),
1536  circ->purpose,
1537  circuit_purpose_to_string(circ->purpose));
1538  TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
1539  }
1540  }
1541  }
1542  }
1543  } SMARTLIST_FOREACH_END(circ);
1544 }
1545 
1546 /** How long do we wait before killing circuits with the properties
1547  * described below?
1548  *
1549  * Probably we could choose a number here as low as 5 to 10 seconds,
1550  * since these circs are used for begindir, and a) generally you either
1551  * ask another begindir question right after or you don't for a long time,
1552  * b) clients at least through 0.2.1.x choose from the whole set of
1553  * directory mirrors at each choice, and c) re-establishing a one-hop
1554  * circuit via create-fast is a light operation assuming the TLS conn is
1555  * still there.
1556  *
1557  * I expect "b" to go away one day when we move to using directory
1558  * guards, but I think "a" and "c" are good enough reasons that a low
1559  * number is safe even then.
1560  */
1561 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
1562 
1563 /** Find each non-origin circuit that has been unused for too long,
1564  * has no streams on it, came from a client, and ends here: mark it
1565  * for close.
1566  */
1567 void
1569 {
1570  or_circuit_t *or_circ;
1571  time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
1572 
1574  if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
1575  continue;
1576  or_circ = TO_OR_CIRCUIT(circ);
1577  /* If the circuit has been idle for too long, and there are no streams
1578  * on it, and it ends here, and it used a create_fast, mark it for close.
1579  *
1580  * Also if there is a rend_splice on it, it's a single onion service
1581  * circuit and we should not close it.
1582  */
1583  if (or_circ->p_chan && channel_is_client(or_circ->p_chan) &&
1584  !circ->n_chan &&
1585  !or_circ->n_streams && !or_circ->resolving_streams &&
1586  !or_circ->rend_splice &&
1587  channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
1588  log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
1589  (unsigned)or_circ->p_circ_id,
1590  (int)(now - channel_when_last_xmit(or_circ->p_chan)));
1591  circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1592  }
1593  }
1594  SMARTLIST_FOREACH_END(circ);
1595 }
1596 
1597 /** Number of testing circuits we want open before testing our bandwidth. */
1598 #define NUM_PARALLEL_TESTING_CIRCS 4
1599 
1600 /** True iff we've ever had enough testing circuits open to test our
1601  * bandwidth. */
1603 
1604 /** Reset have_performed_bandwidth_test, so we'll start building
1605  * testing circuits again so we can exercise our bandwidth. */
1606 void
1608 {
1610 }
1611 
1612 /** Return 1 if we've already exercised our bandwidth, or if we
1613  * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
1614  * established or on the way. Else return 0.
1615  */
1616 int
1618 {
1619  int num = 0;
1620 
1622  return 1;
1623 
1625  if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
1626  circ->purpose == CIRCUIT_PURPOSE_TESTING &&
1627  circ->state == CIRCUIT_STATE_OPEN)
1628  num++;
1629  }
1630  SMARTLIST_FOREACH_END(circ);
1631  return num >= NUM_PARALLEL_TESTING_CIRCS;
1632 }
1633 
1634 /** A testing circuit has completed. Take whatever stats we want.
1635  * Noticing reachability is taken care of in onionskin_answer(),
1636  * so there's no need to record anything here. But if we still want
1637  * to do the bandwidth test, and we now have enough testing circuits
1638  * open, do it.
1639  */
1640 static void
1642 {
1645  /* either we've already done everything we want with testing circuits,
1646  * or this testing circuit became open due to a fluke, e.g. we picked
1647  * a last hop where we already had the connection open due to an
1648  * outgoing local circuit. */
1649  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
1650  } else if (circuit_enough_testing_circs()) {
1653  } else
1655 }
1656 
1657 /** A testing circuit has failed to build. Take whatever stats we want. */
1658 static void
1660 {
1661  const or_options_t *options = get_options();
1662  if (server_mode(options) && check_whether_orport_reachable(options))
1663  return;
1664 
1665  log_info(LD_GENERAL,
1666  "Our testing circuit (to see if your ORPort is reachable) "
1667  "has failed. I'll try again later.");
1668 
1669  /* These aren't used yet. */
1670  (void)circ;
1671  (void)at_last_hop;
1672 }
1673 
1674 /** The circuit <b>circ</b> has just become open. Take the next
1675  * step: for rendezvous circuits, we pass circ to the appropriate
1676  * function in rendclient or rendservice. For general circuits, we
1677  * call connection_ap_attach_pending, which looks for pending streams
1678  * that could use circ.
1679  */
1680 void
1682 {
1683  circuit_event_status(circ, CIRC_EVENT_BUILT, 0);
1684 
1685  /* Remember that this circuit has finished building. Now if we start
1686  * it building again later (e.g. by extending it), we will know not
1687  * to consider its build time. */
1688  circ->has_opened = 1;
1689 
1690  switch (TO_CIRCUIT(circ)->purpose) {
1693  /* Start building an intro circ if we don't have one yet. */
1695  /* This isn't a call to circuit_try_attaching_streams because a
1696  * circuit in _C_ESTABLISH_REND state isn't connected to its
1697  * hidden service yet, thus we can't attach streams to it yet,
1698  * thus circuit_try_attaching_streams would always clear the
1699  * circuit's isolation state. circuit_try_attaching_streams is
1700  * called later, when the rend circ enters _C_REND_JOINED
1701  * state. */
1702  break;
1705  break;
1709  /* Tell any AP connections that have been waiting for a new
1710  * circuit that one is ready. */
1712  break;
1714  /* at the service, waiting for introductions */
1716  break;
1718  /* at the service, connecting to rend point */
1720  break;
1722  circuit_testing_opened(circ);
1723  break;
1724  /* default:
1725  * This won't happen in normal operation, but might happen if the
1726  * controller did it. Just let it slide. */
1727  }
1728 }
1729 
1730 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
1731  * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
1732 static int
1734 {
1735  if (/* The circuit may have become non-open if it was cannibalized.*/
1736  circ->base_.state == CIRCUIT_STATE_OPEN &&
1737  /* If !isolation_values_set, there is nothing to clear. */
1738  circ->isolation_values_set &&
1739  /* It's not legal to clear a circuit's isolation info if it's ever had
1740  * streams attached */
1742  /* If we have any isolation information set on this circuit, and
1743  * we didn't manage to attach any streams to it, then we can
1744  * and should clear it and try again. */
1746  return 1;
1747  } else {
1748  return 0;
1749  }
1750 }
1751 
1752 /** Called when a circuit becomes ready for streams to be attached to
1753  * it. */
1754 void
1756 {
1757  /* Attach streams to this circuit if we can. */
1759 
1760  /* The call to circuit_try_clearing_isolation_state here will do
1761  * nothing and return 0 if we didn't attach any streams to circ
1762  * above. */
1764  /* Maybe *now* we can attach some streams to this circuit. */
1766  }
1767 }
1768 
1769 /** Called whenever a circuit could not be successfully built.
1770  */
1771 void
1773 {
1774  channel_t *n_chan = NULL;
1775  /* we should examine circ and see if it failed because of
1776  * the last hop or an earlier hop. then use this info below.
1777  */
1778  int failed_at_last_hop = 0;
1779 
1780  /* First, check to see if this was a path failure, rather than build
1781  * failure.
1782  *
1783  * Note that we deliberately use circuit_get_cpath_len() (and not
1784  * circuit_get_cpath_opened_len()) because we only want to ensure
1785  * that a full path is *chosen*. This is different than a full path
1786  * being *built*. We only want to count *build* failures below.
1787  *
1788  * Path selection failures can happen spuriously for a number
1789  * of reasons (such as aggressive/invalid user-specified path
1790  * restrictions in the torrc, insufficient microdescriptors, and
1791  * non-user reasons like exitpolicy issues), and so should not be
1792  * counted as failures below.
1793  */
1794  if (circuit_get_cpath_len(circ) < circ->build_state->desired_path_len) {
1795  static ratelim_t pathfail_limit = RATELIM_INIT(3600);
1796  log_fn_ratelim(&pathfail_limit, LOG_NOTICE, LD_CIRC,
1797  "Our circuit %u (id: %" PRIu32 ") died due to an invalid "
1798  "selected path, purpose %s. This may be a torrc "
1799  "configuration issue, or a bug.",
1800  TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1801  circuit_purpose_to_string(TO_CIRCUIT(circ)->purpose));
1802 
1803  /* If the path failed on an RP, retry it. */
1804  if (TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND)
1806 
1807  /* In all other cases, just bail. The rest is just failure accounting
1808  * that we don't want to do */
1809  return;
1810  }
1811 
1812  /* If the last hop isn't open, and the second-to-last is, we failed
1813  * at the last hop. */
1814  if (circ->cpath &&
1815  circ->cpath->prev->state != CPATH_STATE_OPEN &&
1816  circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
1817  failed_at_last_hop = 1;
1818  }
1819 
1820  /* Check if we failed at first hop */
1821  if (circ->cpath &&
1822  circ->cpath->state != CPATH_STATE_OPEN &&
1823  ! circ->base_.received_destroy) {
1824  /* We failed at the first hop for some reason other than a DESTROY cell.
1825  * If there's an OR connection to blame, blame it. Also, avoid this relay
1826  * for a while, and fail any one-hop directory fetches destined for it. */
1827  const char *n_chan_ident = circ->cpath->extend_info->identity_digest;
1828  tor_assert(n_chan_ident);
1829  int already_marked = 0;
1830  if (circ->base_.n_chan) {
1831  n_chan = circ->base_.n_chan;
1832 
1833  if (n_chan->is_bad_for_new_circs) {
1834  /* We only want to blame this router when a fresh healthy
1835  * connection fails. So don't mark this router as newly failed,
1836  * since maybe this was just an old circuit attempt that's
1837  * finally timing out now. Also, there's no need to blow away
1838  * circuits/streams/etc, since the failure of an unhealthy conn
1839  * doesn't tell us much about whether a healthy conn would
1840  * succeed. */
1841  already_marked = 1;
1842  }
1843  log_info(LD_OR,
1844  "Our circuit %u (id: %" PRIu32 ") failed to get a response "
1845  "from the first hop (%s). I'm going to try to rotate to a "
1846  "better connection.",
1847  TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
1849  n_chan->is_bad_for_new_circs = 1;
1850  } else {
1851  log_info(LD_OR,
1852  "Our circuit %u (id: %" PRIu32 ") died before the first hop "
1853  "with no connection",
1854  TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier);
1855  }
1856  if (!already_marked) {
1857  /*
1858  * If we have guard state (new guard API) and our path selection
1859  * code actually chose a full path, then blame the failure of this
1860  * circuit on the guard.
1861  */
1862  if (circ->guard_state)
1864  /* if there are any one-hop streams waiting on this circuit, fail
1865  * them now so they can retry elsewhere. */
1866  connection_ap_fail_onehop(n_chan_ident, circ->build_state);
1867  }
1868  }
1869 
1870  switch (circ->base_.purpose) {
1874  /* If we never built the circuit, note it as a failure. */
1876  if (failed_at_last_hop) {
1877  /* Make sure any streams that demand our last hop as their exit
1878  * know that it's unlikely to happen. */
1880  }
1881  break;
1883  circuit_testing_failed(circ, failed_at_last_hop);
1884  break;
1886  /* at the service, waiting for introductions */
1887  if (circ->base_.state != CIRCUIT_STATE_OPEN) {
1889  }
1890  /* no need to care here, because the service will rebuild intro
1891  * points periodically. */
1892  break;
1894  /* at the client, connecting to intro point */
1895  /* Don't increment failure count, since the service may have picked
1896  * the introduction point maliciously */
1897  /* The client will pick a new intro point when this one dies, if
1898  * the stream in question still cares. No need to act here. */
1899  break;
1901  /* at the client, waiting for the service */
1903  /* the client will pick a new rend point when this one dies, if
1904  * the stream in question still cares. No need to act here. */
1905  break;
1907  /* at the service, connecting to rend point */
1908  /* Don't increment failure count, since the client may have picked
1909  * the rendezvous point maliciously */
1910  log_info(LD_REND,
1911  "Couldn't connect to the client's chosen rend point %s "
1912  "(%s hop failed).",
1914  failed_at_last_hop?"last":"non-last");
1916  break;
1917  /* default:
1918  * This won't happen in normal operation, but might happen if the
1919  * controller did it. Just let it slide. */
1920  }
1921 }
1922 
1923 /** Number of consecutive failures so far; should only be touched by
1924  * circuit_launch_new and circuit_*_failure_count.
1925  */
1926 static int n_circuit_failures = 0;
1927 /** Before the last time we called circuit_reset_failure_count(), were
1928  * there a lot of failures? */
1930 
1931 /** Don't retry launching a new circuit if we try this many times with no
1932  * success. */
1933 #define MAX_CIRCUIT_FAILURES 5
1934 
1935 /** Launch a new circuit; see circuit_launch_by_extend_info() for
1936  * details on arguments. */
1938 circuit_launch(uint8_t purpose, int flags)
1939 {
1940  return circuit_launch_by_extend_info(purpose, NULL, flags);
1941 }
1942 
1943 /* Do we have enough descriptors to build paths?
1944  * If need_exit is true, return 1 if we can build exit paths.
1945  * (We need at least one Exit in the consensus to build exit paths.)
1946  * If need_exit is false, return 1 if we can build internal paths.
1947  */
1948 static int
1949 have_enough_path_info(int need_exit)
1950 {
1951  if (need_exit)
1952  return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
1953  else
1954  return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
1955 }
1956 
1957 /**
1958  * Tell us if a circuit is a hidden service circuit.
1959  */
1960 int
1962 {
1963  /* HS Vanguard purpose. */
1964  if (circuit_purpose_is_hs_vanguards(purpose)) {
1965  return 1;
1966  }
1967 
1968  /* Client-side purpose */
1969  if (circuit_purpose_is_hs_client(purpose)) {
1970  return 1;
1971  }
1972 
1973  /* Service-side purpose */
1974  if (circuit_purpose_is_hs_service(purpose)) {
1975  return 1;
1976  }
1977 
1978  return 0;
1979 }
1980 
1981 /** Retrun true iff the given circuit is an HS client circuit. */
1982 bool
1983 circuit_purpose_is_hs_client(const uint8_t purpose)
1984 {
1985  return (purpose >= CIRCUIT_PURPOSE_C_HS_MIN_ &&
1986  purpose <= CIRCUIT_PURPOSE_C_HS_MAX_);
1987 }
1988 
1989 /** Retrun true iff the given circuit is an HS service circuit. */
1990 bool
1991 circuit_purpose_is_hs_service(const uint8_t purpose)
1992 {
1993  return (purpose >= CIRCUIT_PURPOSE_S_HS_MIN_ &&
1994  purpose <= CIRCUIT_PURPOSE_S_HS_MAX_);
1995 }
1996 
1997 /** Retrun true iff the given circuit is an HS Vanguards circuit. */
1998 bool
1999 circuit_purpose_is_hs_vanguards(const uint8_t purpose)
2000 {
2001  return (purpose == CIRCUIT_PURPOSE_HS_VANGUARDS);
2002 }
2003 
2004 /** Retrun true iff the given circuit is an HS v2 circuit. */
2005 bool
2007 {
2008  return (CIRCUIT_IS_ORIGIN(circ) &&
2009  (CONST_TO_ORIGIN_CIRCUIT(circ)->rend_data != NULL));
2010 }
2011 
2012 /** Retrun true iff the given circuit is an HS v3 circuit. */
2013 bool
2015 {
2016  return (CIRCUIT_IS_ORIGIN(circ) &&
2017  (CONST_TO_ORIGIN_CIRCUIT(circ)->hs_ident != NULL));
2018 }
2019 
2020 /**
2021  * Return true if this circuit purpose should use vanguards
2022  * or pinned Layer2 or Layer3 guards.
2023  *
2024  * This function takes both the circuit purpose and the
2025  * torrc options for pinned middles/vanguards into account
2026  * (ie: the circuit must be a hidden service circuit and
2027  * vanguards/pinned middles must be enabled for it to return
2028  * true).
2029  */
2030 int
2032 {
2033  const or_options_t *options = get_options();
2034 
2035  /* Only hidden service circuits use vanguards */
2036  if (!circuit_purpose_is_hidden_service(purpose))
2037  return 0;
2038 
2039  /* Pinned middles are effectively vanguards */
2040  if (options->HSLayer2Nodes || options->HSLayer3Nodes)
2041  return 1;
2042 
2043  return 0;
2044 }
2045 
2046 /**
2047  * Return true for the set of conditions for which it is OK to use
2048  * a cannibalized circuit.
2049  *
2050  * Don't cannibalize for onehops, or certain purposes.
2051  */
2052 static int
2053 circuit_should_cannibalize_to_build(uint8_t purpose_to_build,
2054  int has_extend_info,
2055  int onehop_tunnel)
2056 {
2057 
2058  /* Do not try to cannibalize if this is a one hop circuit. */
2059  if (onehop_tunnel) {
2060  return 0;
2061  }
2062 
2063  /* Don't try to cannibalize for general purpose circuits that do not
2064  * specify a custom exit. */
2065  if (purpose_to_build == CIRCUIT_PURPOSE_C_GENERAL && !has_extend_info) {
2066  return 0;
2067  }
2068 
2069  /* Don't cannibalize for testing circuits. We want to see if they
2070  * complete normally. Also don't cannibalize for vanguard-purpose
2071  * circuits, since those are specially pre-built for later
2072  * cannibalization by the actual specific circuit types that need
2073  * vanguards.
2074  */
2075  if (purpose_to_build == CIRCUIT_PURPOSE_TESTING ||
2076  purpose_to_build == CIRCUIT_PURPOSE_HS_VANGUARDS) {
2077  return 0;
2078  }
2079 
2080  /* For vanguards, the server-side intro circ is not cannibalized
2081  * because we pre-build 4 hop HS circuits, and it only needs a 3 hop
2082  * circuit. It is also long-lived, so it is more important that
2083  * it have lower latency than get built fast.
2084  */
2085  if (circuit_should_use_vanguards(purpose_to_build) &&
2086  purpose_to_build == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
2087  return 0;
2088  }
2089 
2090  return 1;
2091 }
2092 
2093 /** Launch a new circuit with purpose <b>purpose</b> and exit node
2094  * <b>extend_info</b> (or NULL to select a random exit node). If flags
2095  * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
2096  * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
2097  * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
2098  * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
2099  * Return the newly allocated circuit on success, or NULL on failure. */
2102  extend_info_t *extend_info,
2103  int flags)
2104 {
2105  origin_circuit_t *circ;
2106  int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
2107  int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
2108 
2109  /* Keep some stats about our attempts to launch HS rendezvous circuits */
2110  if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
2112  }
2113 
2114  if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
2115  log_debug(LD_CIRC,"Haven't %s yet; canceling "
2116  "circuit launch.",
2118  "fetched enough directory info" :
2119  "received a consensus with exits");
2120  return NULL;
2121  }
2122 
2123  /* If we can/should cannibalize another circuit to build this one,
2124  * then do so. */
2126  extend_info != NULL,
2127  onehop_tunnel)) {
2128  /* see if there are appropriate circs available to cannibalize. */
2129  /* XXX if we're planning to add a hop, perhaps we want to look for
2130  * internal circs rather than exit circs? -RD */
2131  circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
2132  if (circ) {
2133  uint8_t old_purpose = circ->base_.purpose;
2134  struct timeval old_timestamp_began = circ->base_.timestamp_began;
2135 
2136  log_info(LD_CIRC, "Cannibalizing circ %u (id: %" PRIu32 ") for "
2137  "purpose %d (%s)",
2138  TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier, purpose,
2139  circuit_purpose_to_string(purpose));
2140 
2141  if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2142  purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
2144  /* Path bias: Cannibalized rends pre-emptively count as a
2145  * successfully built but unused closed circuit. We don't
2146  * wait until the extend (or the close) because the rend
2147  * point could be malicious.
2148  *
2149  * Same deal goes for client side introductions. Clients
2150  * can be manipulated to connect repeatedly to them
2151  * (especially web clients).
2152  *
2153  * If we decide to probe the initial portion of these circs,
2154  * (up to the adversary's final hop), we need to remove this,
2155  * or somehow mark the circuit with a special path state.
2156  */
2157 
2158  /* This must be called before the purpose change */
2159  pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
2160  }
2161 
2162  circuit_change_purpose(TO_CIRCUIT(circ), purpose);
2163  /* Reset the start date of this circ, else expire_building
2164  * will see it and think it's been trying to build since it
2165  * began.
2166  *
2167  * Technically, the code should reset this when the
2168  * create cell is finally sent, but we're close enough
2169  * here. */
2170  tor_gettimeofday(&circ->base_.timestamp_began);
2171 
2172  control_event_circuit_cannibalized(circ, old_purpose,
2173  &old_timestamp_began);
2174 
2175  switch (purpose) {
2177  /* it's ready right now */
2178  break;
2185  /* need to add a new hop */
2186  tor_assert(extend_info);
2187  if (circuit_extend_to_new_exit(circ, extend_info) < 0)
2188  return NULL;
2189  break;
2190  default:
2191  log_warn(LD_BUG,
2192  "unexpected purpose %d when cannibalizing a circ.",
2193  purpose);
2195  return NULL;
2196  }
2197  return circ;
2198  }
2199  }
2200 
2203  /* too many failed circs in a row. don't try. */
2204 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
2205  return NULL;
2206  }
2207 
2208  /* try a circ. if it fails, circuit_mark_for_close will increment
2209  * n_circuit_failures */
2210  return circuit_establish_circuit(purpose, extend_info, flags);
2211 }
2212 
2213 /** Record another failure at opening a general circuit. When we have
2214  * too many, we'll stop trying for the remainder of this minute.
2215  */
2216 static void
2218 {
2220  log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
2221 }
2222 
2223 /** Reset the failure count for opening general circuits. This means
2224  * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
2225  * stopping again.
2226  */
2227 void
2229 {
2230  if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
2232  else
2234  n_circuit_failures = 0;
2235 }
2236 
2237 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
2238  * there isn't one, and there isn't one on the way, launch one and return
2239  * 0. If it will never work, return -1.
2240  *
2241  * Write the found or in-progress or launched circ into *circp.
2242  */
2243 static int
2245  uint8_t desired_circuit_purpose,
2246  origin_circuit_t **circp)
2247 {
2248  origin_circuit_t *circ;
2249  int check_exit_policy;
2250  int need_uptime, need_internal;
2251  int want_onehop;
2252  const or_options_t *options = get_options();
2253 
2254  tor_assert(conn);
2255  tor_assert(circp);
2256  if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
2257  connection_t *c = ENTRY_TO_CONN(conn);
2258  log_err(LD_BUG, "Connection state mismatch: wanted "
2259  "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
2260  c->state, conn_state_to_string(c->type, c->state));
2261  }
2263 
2264  /* Will the exit policy of the exit node apply to this stream? */
2265  check_exit_policy =
2267  !conn->use_begindir &&
2269 
2270  /* Does this connection want a one-hop circuit? */
2271  want_onehop = conn->want_onehop;
2272 
2273  /* Do we need a high-uptime circuit? */
2274  need_uptime = !conn->want_onehop && !conn->use_begindir &&
2276  conn->socks_request->port);
2277 
2278  /* Do we need an "internal" circuit? */
2279  if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
2280  need_internal = 1;
2281  else if (conn->use_begindir || conn->want_onehop)
2282  need_internal = 1;
2283  else
2284  need_internal = 0;
2285 
2286  /* We now know what kind of circuit we need. See if there is an
2287  * open circuit that we can use for this stream */
2288  circ = circuit_get_best(conn, 1 /* Insist on open circuits */,
2289  desired_circuit_purpose,
2290  need_uptime, need_internal);
2291 
2292  if (circ) {
2293  /* We got a circuit that will work for this stream! We can return it. */
2294  *circp = circ;
2295  return 1; /* we're happy */
2296  }
2297 
2298  /* Okay, there's no circuit open that will work for this stream. Let's
2299  * see if there's an in-progress circuit or if we have to launch one */
2300 
2301  /* Do we know enough directory info to build circuits at all? */
2302  int have_path = have_enough_path_info(!need_internal);
2303 
2304  if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
2305  /* If we don't have enough directory information, we can't build
2306  * multihop circuits.
2307  */
2309  int severity = LOG_NOTICE;
2310  /* Retry some stuff that might help the connection work. */
2311  /* If we are configured with EntryNodes or UseBridges */
2312  if (entry_list_is_constrained(options)) {
2313  /* Retry all our guards / bridges.
2314  * guards_retry_optimistic() always returns true here. */
2315  int rv = guards_retry_optimistic(options);
2316  tor_assert_nonfatal_once(rv);
2317  log_fn(severity, LD_APP|LD_DIR,
2318  "Application request when we haven't %s. "
2319  "Optimistically trying known %s again.",
2321  "used client functionality lately" :
2322  "received a consensus with exits",
2323  options->UseBridges ? "bridges" : "entrynodes");
2324  } else {
2325  /* Getting directory documents doesn't help much if we have a limited
2326  * number of guards */
2327  tor_assert_nonfatal(!options->UseBridges);
2328  tor_assert_nonfatal(!options->EntryNodes);
2329  /* Retry our directory fetches, so we have a fresh set of guard info */
2330  log_fn(severity, LD_APP|LD_DIR,
2331  "Application request when we haven't %s. "
2332  "Optimistically trying directory fetches again.",
2334  "used client functionality lately" :
2335  "received a consensus with exits");
2337  }
2338  }
2339  /* Since we didn't have enough directory info, we can't attach now. The
2340  * stream will be dealt with when router_have_minimum_dir_info becomes 1,
2341  * or when all directory attempts fail and directory_all_unreachable()
2342  * kills it.
2343  */
2344  return 0;
2345  }
2346 
2347  /* Check whether the exit policy of the chosen exit, or the exit policies
2348  * of _all_ nodes, would forbid this node. */
2349  if (check_exit_policy) {
2350  if (!conn->chosen_exit_name) {
2351  struct in_addr in;
2352  tor_addr_t addr, *addrp=NULL;
2353  if (tor_inet_aton(conn->socks_request->address, &in)) {
2354  tor_addr_from_in(&addr, &in);
2355  addrp = &addr;
2356  }
2358  conn->socks_request->port,
2359  need_uptime)) {
2360  log_notice(LD_APP,
2361  "No Tor server allows exit to %s:%d. Rejecting.",
2362  safe_str_client(conn->socks_request->address),
2363  conn->socks_request->port);
2364  return -1;
2365  }
2366  } else {
2367  /* XXXX Duplicates checks in connection_ap_handshake_attach_circuit:
2368  * refactor into a single function. */
2369  const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2370  int opt = conn->chosen_exit_optional;
2371  if (node && !connection_ap_can_use_exit(conn, node)) {
2372  log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2373  "Requested exit point '%s' is excluded or "
2374  "would refuse request. %s.",
2375  conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2376  if (opt) {
2377  conn->chosen_exit_optional = 0;
2378  tor_free(conn->chosen_exit_name);
2379  /* Try again. */
2380  return circuit_get_open_circ_or_launch(conn,
2381  desired_circuit_purpose,
2382  circp);
2383  }
2384  return -1;
2385  }
2386  }
2387  }
2388 
2389  /* Now, check whether there already a circuit on the way that could handle
2390  * this stream. This check matches the one above, but this time we
2391  * do not require that the circuit will work. */
2392  circ = circuit_get_best(conn, 0 /* don't insist on open circuits */,
2393  desired_circuit_purpose,
2394  need_uptime, need_internal);
2395  if (circ)
2396  log_debug(LD_CIRC, "one on the way!");
2397 
2398  if (!circ) {
2399  /* No open or in-progress circuit could handle this stream! We
2400  * will have to launch one!
2401  */
2402 
2403  /* The chosen exit node, if there is one. */
2404  extend_info_t *extend_info=NULL;
2405  const int n_pending = count_pending_general_client_circuits();
2406 
2407  /* Do we have too many pending circuits? */
2408  if (n_pending >= options->MaxClientCircuitsPending) {
2409  static ratelim_t delay_limit = RATELIM_INIT(10*60);
2410  char *m;
2411  if ((m = rate_limit_log(&delay_limit, approx_time()))) {
2412  log_notice(LD_APP, "We'd like to launch a circuit to handle a "
2413  "connection, but we already have %d general-purpose client "
2414  "circuits pending. Waiting until some finish.%s",
2415  n_pending, m);
2416  tor_free(m);
2417  }
2418  return 0;
2419  }
2420 
2421  /* If this is a hidden service trying to start an introduction point,
2422  * handle that case. */
2423  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
2424  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2425  /* need to pick an intro point */
2426  extend_info = hs_client_get_random_intro_from_edge(edge_conn);
2427  if (!extend_info) {
2428  log_info(LD_REND, "No intro points: re-fetching service descriptor.");
2429  if (edge_conn->rend_data) {
2431  } else {
2432  hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
2433  }
2435  return 0;
2436  }
2437  log_info(LD_REND,"Chose %s as intro point for '%s'.",
2438  extend_info_describe(extend_info),
2439  (edge_conn->rend_data) ?
2440  safe_str_client(rend_data_get_address(edge_conn->rend_data)) :
2441  "service");
2442  }
2443 
2444  /* If we have specified a particular exit node for our
2445  * connection, then be sure to open a circuit to that exit node.
2446  */
2447  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2448  desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2449  desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
2450  if (conn->chosen_exit_name) {
2451  const node_t *r;
2452  int opt = conn->chosen_exit_optional;
2453  r = node_get_by_nickname(conn->chosen_exit_name, 0);
2454  if (r && node_has_preferred_descriptor(r, conn->want_onehop ? 1 : 0)) {
2455  /* We might want to connect to an IPv6 bridge for loading
2456  descriptors so we use the preferred address rather than
2457  the primary. */
2458  extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
2459  if (!extend_info) {
2460  log_warn(LD_CIRC,"Could not make a one-hop connection to %s. "
2461  "Discarding this circuit.", conn->chosen_exit_name);
2462  return -1;
2463  }
2464  } else { /* ! (r && node_has_preferred_descriptor(...)) */
2465  log_debug(LD_DIR, "considering %d, %s",
2466  want_onehop, conn->chosen_exit_name);
2467  if (want_onehop && conn->chosen_exit_name[0] == '$') {
2468  /* We're asking for a one-hop circuit to a router that
2469  * we don't have a routerinfo about. Make up an extend_info. */
2470  /* XXX prop220: we need to make chosen_exit_name able to
2471  * encode both key formats. This is not absolutely critical
2472  * since this is just for one-hop circuits, but we should
2473  * still get it done */
2474  char digest[DIGEST_LEN];
2475  char *hexdigest = conn->chosen_exit_name+1;
2476  tor_addr_t addr;
2477  if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2478  base16_decode(digest,DIGEST_LEN,
2479  hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN) {
2480  log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
2481  return -1;
2482  }
2483  if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
2484  log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
2486  return -1;
2487  }
2488  /* XXXX prop220 add a workaround for ed25519 ID below*/
2489  extend_info = extend_info_new(conn->chosen_exit_name+1,
2490  digest,
2491  NULL, /* Ed25519 ID */
2492  NULL, NULL, /* onion keys */
2493  &addr, conn->socks_request->port);
2494  } else { /* ! (want_onehop && conn->chosen_exit_name[0] == '$') */
2495  /* We will need an onion key for the router, and we
2496  * don't have one. Refuse or relax requirements. */
2497  log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2498  "Requested exit point '%s' is not known. %s.",
2499  conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2500  if (opt) {
2501  conn->chosen_exit_optional = 0;
2502  tor_free(conn->chosen_exit_name);
2503  /* Try again with no requested exit */
2504  return circuit_get_open_circ_or_launch(conn,
2505  desired_circuit_purpose,
2506  circp);
2507  }
2508  return -1;
2509  }
2510  }
2511  }
2512  } /* Done checking for general circutis with chosen exits. */
2513 
2514  /* What purpose do we need to launch this circuit with? */
2515  uint8_t new_circ_purpose;
2516  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
2517  new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
2518  else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
2519  new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
2520  else
2521  new_circ_purpose = desired_circuit_purpose;
2522 
2523  /* Determine what kind of a circuit to launch, and actually launch it. */
2524  {
2525  int flags = CIRCLAUNCH_NEED_CAPACITY;
2526  if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
2527  if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2528  if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
2529 
2530  /* If we are about to pick a v3 RP right now, make sure we pick a
2531  * rendezvous point that supports the v3 protocol! */
2532  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED &&
2533  new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2534  ENTRY_TO_EDGE_CONN(conn)->hs_ident) {
2535  flags |= CIRCLAUNCH_IS_V3_RP;
2536  log_info(LD_GENERAL, "Getting rendezvous circuit to v3 service!");
2537  }
2538 
2539  circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
2540  flags);
2541  }
2542 
2543  extend_info_free(extend_info);
2544 
2545  /* Now trigger things that need to happen when we launch circuits */
2546 
2547  if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2548  desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2549  desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST) {
2550  /* We just caused a circuit to get built because of this stream.
2551  * If this stream has caused a _lot_ of circuits to be built, that's
2552  * a bad sign: we should tell the user. */
2553  if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
2554  ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
2555  log_info(LD_CIRC, "The application request to %s:%d has launched "
2556  "%d circuits without finding one it likes.",
2558  conn->socks_request->port,
2559  conn->num_circuits_launched);
2560  } else {
2561  /* help predict this next time */
2562  rep_hist_note_used_internal(time(NULL), need_uptime, 1);
2563  if (circ) {
2564  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2565  if (edge_conn->rend_data) {
2566  /* write the service_id into circ */
2567  circ->rend_data = rend_data_dup(edge_conn->rend_data);
2568  } else if (edge_conn->hs_ident) {
2569  circ->hs_ident =
2570  hs_ident_circuit_new(&edge_conn->hs_ident->identity_pk);
2571  }
2572  if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
2573  circ->base_.state == CIRCUIT_STATE_OPEN)
2574  circuit_has_opened(circ);
2575  }
2576  }
2577  } /* endif (!circ) */
2578 
2579  /* We either found a good circuit, or launched a new circuit, or failed to
2580  * do so. Report success, and delay. */
2581 
2582  if (circ) {
2583  /* Mark the circuit with the isolation fields for this connection.
2584  * When the circuit arrives, we'll clear these flags: this is
2585  * just some internal bookkeeping to make sure that we have
2586  * launched enough circuits.
2587  */
2589  } else {
2590  log_info(LD_APP,
2591  "No safe circuit (purpose %d) ready for edge "
2592  "connection; delaying.",
2593  desired_circuit_purpose);
2594  }
2595  *circp = circ;
2596  return 0;
2597 }
2598 
2599 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
2600  * <b>circ</b>. */
2601 static int
2603 {
2604  crypt_path_t *cpath, *cpath_next = NULL;
2605  for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2606  cpath_next = cpath->next;
2607  if (crypt_path == cpath)
2608  return 1;
2609  }
2610  return 0;
2611 }
2612 
2613 /** Return true iff client-side optimistic data is supported. */
2614 static int
2616 {
2617  const or_options_t *options = get_options();
2618  if (options->OptimisticData < 0) {
2619  /* Note: this default was 0 before #18815 was merged. We can't take the
2620  * parameter out of the consensus until versions before that are all
2621  * obsolete. */
2622  const int32_t enabled =
2623  networkstatus_get_param(NULL, "UseOptimisticData", /*default*/ 1, 0, 1);
2624  return (int)enabled;
2625  }
2626  return options->OptimisticData;
2627 }
2628 
2629 /** Attach the AP stream <b>apconn</b> to circ's linked list of
2630  * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
2631  * hop in circ's cpath if <b>cpath</b> is NULL.
2632  */
2633 static void
2635  crypt_path_t *cpath)
2636 {
2637  const node_t *exitnode = NULL;
2638 
2639  /* add it into the linked list of streams on this circuit */
2640  log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
2641  (unsigned)circ->base_.n_circ_id);
2642 
2643  /* If this is the first stream on this circuit, tell circpad
2644  * that streams are attached */
2645  if (!circ->p_streams)
2647 
2648  /* reset it, so we can measure circ timeouts */
2649  ENTRY_TO_CONN(apconn)->timestamp_last_read_allowed = time(NULL);
2650  ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
2651  ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
2652  /* assert_connection_ok(conn, time(NULL)); */
2653  circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
2654 
2656  /* We are attaching a stream to a rendezvous circuit. That means
2657  * that an attempt to connect to a hidden service just
2658  * succeeded. Tell rendclient.c. */
2660  }
2661 
2662  if (cpath) { /* we were given one; use it */
2663  tor_assert(cpath_is_on_circuit(circ, cpath));
2664  } else {
2665  /* use the last hop in the circuit */
2666  tor_assert(circ->cpath);
2667  tor_assert(circ->cpath->prev);
2668  tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
2669  cpath = circ->cpath->prev;
2670  }
2671  ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
2672 
2675 
2676  /* Compute the exitnode if possible, for logging below */
2677  if (cpath->extend_info)
2678  exitnode = node_get_by_id(cpath->extend_info->identity_digest);
2679 
2680  /* See if we can use optimistic data on this circuit */
2681  if (optimistic_data_enabled() &&
2682  (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
2683  circ->base_.purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
2684  circ->base_.purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
2685  circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED))
2686  apconn->may_use_optimistic_data = 1;
2687  else
2688  apconn->may_use_optimistic_data = 0;
2689  log_info(LD_APP, "Looks like completed circuit to %s %s allow "
2690  "optimistic data for connection to %s",
2691  circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ?
2692  /* node_describe() does the right thing if exitnode is NULL */
2693  safe_str_client(node_describe(exitnode)) :
2694  "hidden service",
2695  apconn->may_use_optimistic_data ? "does" : "doesn't",
2696  safe_str_client(apconn->socks_request->address));
2697 }
2698 
2699 /** Return true iff <b>address</b> is matched by one of the entries in
2700  * TrackHostExits. */
2701 int
2702 hostname_in_track_host_exits(const or_options_t *options, const char *address)
2703 {
2704  if (!options->TrackHostExits)
2705  return 0;
2706  SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
2707  if (cp[0] == '.') { /* match end */
2708  if (cp[1] == '\0' ||
2709  !strcasecmpend(address, cp) ||
2710  !strcasecmp(address, &cp[1]))
2711  return 1;
2712  } else if (strcasecmp(cp, address) == 0) {
2713  return 1;
2714  }
2715  } SMARTLIST_FOREACH_END(cp);
2716  return 0;
2717 }
2718 
2719 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
2720  * the exit that we *did* choose for use by future connections to
2721  * <b>conn</b>'s destination.
2722  */
2723 static void
2725  const origin_circuit_t *circ)
2726 {
2727  const or_options_t *options = get_options();
2728  char *new_address = NULL;
2729  char fp[HEX_DIGEST_LEN+1];
2730 
2731  /* Search the addressmap for this conn's destination. */
2732  /* If they're not in the address map.. */
2733  if (!options->TrackHostExits ||
2735  options->TrackHostExitsExpire))
2736  return; /* nothing to track, or already mapped */
2737 
2738  if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
2739  !circ->build_state->chosen_exit)
2740  return;
2741 
2742  /* write down the fingerprint of the chosen exit, not the nickname,
2743  * because the chosen exit might not be named. */
2744  base16_encode(fp, sizeof(fp),
2746 
2747  /* Add this exit/hostname pair to the addressmap. */
2748  tor_asprintf(&new_address, "%s.%s.exit",
2749  conn->socks_request->address, fp);
2750 
2751  addressmap_register(conn->socks_request->address, new_address,
2752  time(NULL) + options->TrackHostExitsExpire,
2753  ADDRMAPSRC_TRACKEXIT, 0, 0);
2754 }
2755 
2756 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
2757  * begin or resolve cell as appropriate. Return values are as for
2758  * connection_ap_handshake_attach_circuit. The stream will exit from the hop
2759  * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2760  * <b>cpath</b> is NULL. */
2761 int
2763  origin_circuit_t *circ,
2764  crypt_path_t *cpath)
2765 {
2766  connection_t *base_conn = ENTRY_TO_CONN(conn);
2767  tor_assert(conn);
2769  base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
2770  tor_assert(conn->socks_request);
2771  tor_assert(circ);
2772  tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
2773 
2774  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2775 
2776  if (!circ->base_.timestamp_dirty ||
2777  ((conn->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
2778  (conn->entry_cfg.socks_iso_keep_alive) &&
2779  (conn->socks_request->usernamelen ||
2780  conn->socks_request->passwordlen))) {
2781  /* When stream isolation is in use and controlled by an application
2782  * we are willing to keep using the stream. */
2783  circ->base_.timestamp_dirty = approx_time();
2784  }
2785 
2787 
2788  /* Now, actually link the connection. */
2789  link_apconn_to_circ(conn, circ, cpath);
2790 
2791  tor_assert(conn->socks_request);
2793  if (!conn->use_begindir)
2794  consider_recording_trackhost(conn, circ);
2795  if (connection_ap_handshake_send_begin(conn) < 0)
2796  return -1;
2797  } else {
2799  return -1;
2800  }
2801 
2802  return 1;
2803 }
2804 
2805 /**
2806  * Return an appropriate circuit purpose for non-rend streams.
2807  * We don't handle rends here because a rend stream triggers two
2808  * circuit builds with different purposes, so it is handled elsewhere.
2809  *
2810  * This function just figures out what type of hsdir activity this is,
2811  * and tells us. Everything else is general.
2812  */
2813 static int
2815 {
2816  const connection_t *base_conn = ENTRY_TO_CONN(conn);
2817  tor_assert_nonfatal(!connection_edge_is_rendezvous_stream(
2818  ENTRY_TO_EDGE_CONN(conn)));
2819 
2820  if (base_conn->linked_conn &&
2821  base_conn->linked_conn->type == CONN_TYPE_DIR) {
2822  /* Set a custom purpose for hsdir activity */
2823  if (base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2 ||
2826  } else if (base_conn->linked_conn->purpose
2828  base_conn->linked_conn->purpose
2831  }
2832  }
2833 
2834  /* All other purposes are general for now */
2836 }
2837 
2838 /** Try to find a safe live circuit for stream <b>conn</b>. If we find one,
2839  * attach the stream, send appropriate cells, and return 1. Otherwise,
2840  * try to launch new circuit(s) for the stream. If we can launch
2841  * circuits, return 0. Otherwise, if we simply can't proceed with
2842  * this stream, return -1. (conn needs to die, and is maybe already marked).
2843  */
2844 /* XXXX this function should mark for close whenever it returns -1;
2845  * its callers shouldn't have to worry about that. */
2846 int
2848 {
2849  connection_t *base_conn = ENTRY_TO_CONN(conn);
2850  int retval;
2851  int conn_age;
2852  int want_onehop;
2853 
2854  tor_assert(conn);
2856  tor_assert(conn->socks_request);
2857  want_onehop = conn->want_onehop;
2858 
2859  conn_age = (int)(time(NULL) - base_conn->timestamp_created);
2860 
2861  /* Is this connection so old that we should give up on it? */
2862  if (conn_age >= get_options()->SocksTimeout) {
2863  int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
2864  LOG_INFO : LOG_NOTICE;
2865  log_fn(severity, LD_APP,
2866  "Tried for %d seconds to get a connection to %s:%d. Giving up.",
2867  conn_age, safe_str_client(conn->socks_request->address),
2868  conn->socks_request->port);
2869  return -1;
2870  }
2871 
2872  /* We handle "general" (non-onion) connections much more straightforwardly.
2873  */
2875  /* we're a general conn */
2876  origin_circuit_t *circ=NULL;
2877 
2878  /* Are we linked to a dir conn that aims to fetch a consensus?
2879  * We check here because the conn might no longer be needed. */
2880  if (base_conn->linked_conn &&
2881  base_conn->linked_conn->type == CONN_TYPE_DIR &&
2883 
2884  /* Yes we are. Is there a consensus fetch farther along than us? */
2885  if (networkstatus_consensus_is_already_downloading(
2886  TO_DIR_CONN(base_conn->linked_conn)->requested_resource)) {
2887  /* We're doing the "multiple consensus fetch attempts" game from
2888  * proposal 210, and we're late to the party. Just close this conn.
2889  * The circuit and TLS conn that we made will time out after a while
2890  * if nothing else wants to use them. */
2891  log_info(LD_DIR, "Closing extra consensus fetch (to %s) since one "
2892  "is already downloading.", base_conn->linked_conn->address);
2893  return -1;
2894  }
2895  }
2896 
2897  /* If we have a chosen exit, we need to use a circuit that's
2898  * open to that exit. See what exit we meant, and whether we can use it.
2899  */
2900  if (conn->chosen_exit_name) {
2901  const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
2902  int opt = conn->chosen_exit_optional;
2903  if (!node && !want_onehop) {
2904  /* We ran into this warning when trying to extend a circuit to a
2905  * hidden service directory for which we didn't have a router
2906  * descriptor. See flyspray task 767 for more details. We should
2907  * keep this in mind when deciding to use BEGIN_DIR cells for other
2908  * directory requests as well. -KL*/
2909  log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2910  "Requested exit point '%s' is not known. %s.",
2911  conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2912  if (opt) {
2913  /* If we are allowed to ignore the .exit request, do so */
2914  conn->chosen_exit_optional = 0;
2915  tor_free(conn->chosen_exit_name);
2916  return 0;
2917  }
2918  return -1;
2919  }
2920  if (node && !connection_ap_can_use_exit(conn, node)) {
2921  log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
2922  "Requested exit point '%s' is excluded or "
2923  "would refuse request. %s.",
2924  conn->chosen_exit_name, opt ? "Trying others" : "Closing");
2925  if (opt) {
2926  /* If we are allowed to ignore the .exit request, do so */
2927  conn->chosen_exit_optional = 0;
2928  tor_free(conn->chosen_exit_name);
2929  return 0;
2930  }
2931  return -1;
2932  }
2933  }
2934 
2935  /* Find the circuit that we should use, if there is one. Otherwise
2936  * launch it
2937  */
2938  retval = circuit_get_open_circ_or_launch(conn,
2940  &circ);
2941 
2942  if (retval < 1) {
2943  /* We were either told "-1" (complete failure) or 0 (circuit in
2944  * progress); we can't attach this stream yet. */
2945  return retval;
2946  }
2947 
2948  log_debug(LD_APP|LD_CIRC,
2949  "Attaching apconn to circ %u (stream %d sec old).",
2950  (unsigned)circ->base_.n_circ_id, conn_age);
2951  /* print the circ's path, so clients can figure out which circs are
2952  * sucking. */
2954 
2955  /* We have found a suitable circuit for our conn. Hurray. Do
2956  * the attachment. */
2957  return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
2958 
2959  } else { /* we're a rendezvous conn */
2960  origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
2961 
2962  tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
2963 
2964  /* start by finding a rendezvous circuit for us */
2965 
2967  conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
2968  if (retval < 0) return -1; /* failed */
2969 
2970  if (retval > 0) {
2971  tor_assert(rendcirc);
2972  /* one is already established, attach */
2973  log_info(LD_REND,
2974  "rend joined circ %u (id: %" PRIu32 ") already here. "
2975  "Attaching. (stream %d sec old)",
2976  (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
2977  rendcirc->global_identifier, conn_age);
2978  /* Mark rendezvous circuits as 'newly dirty' every time you use
2979  * them, since the process of rebuilding a rendezvous circ is so
2980  * expensive. There is a tradeoff between linkability and
2981  * feasibility, at this point.
2982  */
2983  rendcirc->base_.timestamp_dirty = time(NULL);
2984 
2985  /* We've also attempted to use them. If they fail, we need to
2986  * probe them for path bias */
2987  pathbias_count_use_attempt(rendcirc);
2988 
2989  link_apconn_to_circ(conn, rendcirc, NULL);
2990  if (connection_ap_handshake_send_begin(conn) < 0)
2991  return 0; /* already marked, let them fade away */
2992  return 1;
2993  }
2994 
2995  /* At this point we need to re-check the state, since it's possible that
2996  * our call to circuit_get_open_circ_or_launch() changed the connection's
2997  * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
2998  * re-fetch the descriptor.
2999  */
3000  if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
3001  log_info(LD_REND, "This connection is no longer ready to attach; its "
3002  "state changed."
3003  "(We probably have to re-fetch its descriptor.)");
3004  return 0;
3005  }
3006 
3007  if (rendcirc && (rendcirc->base_.purpose ==
3009  log_info(LD_REND,
3010  "pending-join circ %u (id: %" PRIu32 ") already here, with "
3011  "intro ack. Stalling. (stream %d sec old)",
3012  (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
3013  rendcirc->global_identifier, conn_age);
3014  return 0;
3015  }
3016 
3017  /* it's on its way. find an intro circ. */
3019  conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
3020  if (retval < 0) return -1; /* failed */
3021 
3022  if (retval > 0) {
3023  /* one has already sent the intro. keep waiting. */
3024  tor_assert(introcirc);
3025  log_info(LD_REND, "Intro circ %u (id: %" PRIu32 ") present and "
3026  "awaiting ACK. Rend circuit %u (id: %" PRIu32 "). "
3027  "Stalling. (stream %d sec old)",
3028  (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
3029  introcirc->global_identifier,
3030  rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
3031  rendcirc ? rendcirc->global_identifier : 0,
3032  conn_age);
3033  return 0;
3034  }
3035 
3036  /* now rendcirc and introcirc are each either undefined or not finished */
3037 
3038  if (rendcirc && introcirc &&
3039  rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
3040  log_info(LD_REND,
3041  "ready rend circ %u (id: %" PRIu32 ") already here. No"
3042  "intro-ack yet on intro %u (id: %" PRIu32 "). "
3043  "(stream %d sec old)",
3044  (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
3045  rendcirc->global_identifier,
3046  (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
3047  introcirc->global_identifier, conn_age);
3048 
3049  tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
3050  if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
3051  int ret;
3052  log_info(LD_REND, "Found open intro circ %u (id: %" PRIu32 "). "
3053  "Rend circuit %u (id: %" PRIu32 "); Sending "
3054  "introduction. (stream %d sec old)",
3055  (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
3056  introcirc->global_identifier,
3057  (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
3058  rendcirc->global_identifier, conn_age);
3059  ret = hs_client_send_introduce1(introcirc, rendcirc);
3060  switch (ret) {
3061  case 0: /* success */
3062  rendcirc->base_.timestamp_dirty = time(NULL);
3063  introcirc->base_.timestamp_dirty = time(NULL);
3064 
3065  pathbias_count_use_attempt(introcirc);
3066  pathbias_count_use_attempt(rendcirc);
3067 
3068  assert_circuit_ok(TO_CIRCUIT(rendcirc));
3069  assert_circuit_ok(TO_CIRCUIT(introcirc));
3070  return 0;
3071  case -1: /* transient error */
3072  return 0;
3073  case -2: /* permanent error */
3074  return -1;
3075  default: /* oops */
3077  return -1;
3078  }
3079  }
3080  }
3081 
3082  log_info(LD_REND, "Intro %u (id: %" PRIu32 ") and rend circuit %u "
3083  "(id: %" PRIu32 ") circuits are not both ready. "
3084  "Stalling conn. (%d sec old)",
3085  introcirc ? (unsigned) TO_CIRCUIT(introcirc)->n_circ_id : 0,
3086  introcirc ? introcirc->global_identifier : 0,
3087  rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
3088  rendcirc ? rendcirc->global_identifier : 0, conn_age);
3089  return 0;
3090  }
3091 }
3092 
3093 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
3094 void
3095 circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
3096 {
3097  uint8_t old_purpose;
3098  /* Don't allow an OR circ to become an origin circ or vice versa. */
3099  tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
3100  !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
3101 
3102  if (circ->purpose == new_purpose) return;
3103 
3104  if (CIRCUIT_IS_ORIGIN(circ)) {
3105  char old_purpose_desc[80] = "";
3106 
3107  strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
3108  old_purpose_desc[80-1] = '\0';
3109 
3110  log_debug(LD_CIRC,
3111  "changing purpose of origin circ %d "
3112  "from \"%s\" (%d) to \"%s\" (%d)",
3113  TO_ORIGIN_CIRCUIT(circ)->global_identifier,
3114  old_purpose_desc,
3115  circ->purpose,
3116  circuit_purpose_to_string(new_purpose),
3117  new_purpose);
3118 
3119  /* Take specific actions if we are repurposing a hidden service circuit. */
3121  !circuit_purpose_is_hidden_service(new_purpose)) {
3123  }
3124  }
3125 
3126  old_purpose = circ->purpose;
3127  circ->purpose = new_purpose;
3128 
3129  if (CIRCUIT_IS_ORIGIN(circ)) {
3131  old_purpose);
3132 
3134  }
3135 }
3136 
3137 /** Mark <b>circ</b> so that no more connections can be attached to it. */
3138 void
3140 {
3141  const or_options_t *options = get_options();
3142  tor_assert(circ);
3143 
3144  /* XXXX This is a kludge; we're only keeping it around in case there's
3145  * something that doesn't check unusable_for_new_conns, and to avoid
3146  * deeper refactoring of our expiration logic. */
3147  if (! circ->base_.timestamp_dirty)
3148  circ->base_.timestamp_dirty = approx_time();
3149  if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
3150  circ->base_.timestamp_dirty = 1; /* prevent underflow */
3151  else
3152  circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
3153 
3154  circ->unusable_for_new_conns = 1;
3155 }
3156 
3157 /**
3158  * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
3159  * the valid delivered written fields and the overhead field,
3160  * respectively.
3161  */
3162 void
3163 circuit_sent_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
3164 {
3165  if (!circ) return;
3166 
3167  tor_assertf_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE,
3168  "Wrong relay_body_len: %d (should be at most %d)",
3169  relay_body_len, RELAY_PAYLOAD_SIZE);
3170 
3172  tor_add_u32_nowrap(circ->n_delivered_written_circ_bw, relay_body_len);
3174  tor_add_u32_nowrap(circ->n_overhead_written_circ_bw,
3175  RELAY_PAYLOAD_SIZE-relay_body_len);
3176 }
3177 
3178 /**
3179  * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
3180  * the valid delivered read field and the overhead field,
3181  * respectively.
3182  */
3183 void
3184 circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
3185 {
3186  if (!circ) return;
3187 
3188  tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE);
3189 
3190  circ->n_delivered_read_circ_bw =
3191  tor_add_u32_nowrap(circ->n_delivered_read_circ_bw, relay_body_len);
3192  circ->n_overhead_read_circ_bw =
3193  tor_add_u32_nowrap(circ->n_overhead_read_circ_bw,
3194  RELAY_PAYLOAD_SIZE-relay_body_len);
3195 }
#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:1659
#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:2900
#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:1938
const char * channel_get_canonical_remote_descr(channel_t *chan)
Definition: channel.c:2823
#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:185
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:69
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:34
#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:2724
extend_info_t * extend_info_from_node(const node_t *node, int for_direct_connect)
#define IDLE_ONE_HOP_CIRC_TIMEOUT
Definition: circuituse.c:1561
tor_addr_t addr
void circuit_try_attaching_streams(origin_circuit_t *circ)
Definition: circuituse.c:1755
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:104
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:1084
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:2064
static int optimistic_data_enabled(void)
Definition: circuituse.c:2615
#define LD_GENERAL
Definition: log.h:62
int addressmap_have_mapping(const char *address, int update_expiry)
Definition: addressmap.c:544
#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:3275
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:2937
void hs_circ_cleanup_on_repurpose(circuit_t *circ)
Definition: hs_circuit.c:1347
bool hs_circ_is_rend_sent_in_intro1(const origin_circuit_t *circ)
Definition: hs_circuit.c:1369
bool circuit_is_hs_v3(const circuit_t *circ)
Definition: circuituse.c:2014
const char * circuit_purpose_to_string(uint8_t purpose)
Definition: circuitlist.c:900
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:110
uint8_t purpose
Definition: circuit_st.h:111
unsigned int chosen_exit_optional
Header file for directory.c.
int circuit_purpose_is_hidden_service(uint8_t purpose)
Definition: circuituse.c:1961
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:2755
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:165
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:170
int circuit_stream_is_being_handled(entry_connection_t *conn, uint16_t port, int min)
Definition: circuituse.c:1035
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:245
const or_options_t * get_options(void)
Definition: config.c:925
crypt_path_t * cpath
#define tor_assert(expr)
Definition: util_bug.h:102
struct crypt_path_t * prev
Definition: crypt_path_st.h:75
struct routerset_t * EntryNodes
Definition: or_options_st.h:83
int tor_inet_aton(const char *str, struct in_addr *addr)
Definition: inaddr.c:40
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:314
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:498
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:1602
int MaxCircuitDirtiness
#define tor_free(p)
Definition: malloc.h:52
uint16_t marked_for_close
Definition: circuit_st.h:189
#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:1378
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:1550
#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:1334
const char * conn_state_to_string(int type, int state)
Definition: connection.c:277
#define DIR_PURPOSE_FETCH_CONSENSUS
Definition: directory.h:56
Header for tvdiff.c.
struct timeval timestamp_created
Definition: circuit_st.h:168
int circuit_get_cpath_len(origin_circuit_t *circ)
Definition: circuitlist.c:2040
static void circuit_testing_opened(origin_circuit_t *circ)
Definition: circuituse.c:1641
Header file for hs_stats.c.
smartlist_t * smartlist_new(void)
#define TESTING_CIRCUIT_INTERVAL
Definition: circuituse.c:1326
struct routerset_t * ExcludeNodes
Definition: or_options_st.h:89
int connection_ap_handshake_attach_circuit(entry_connection_t *conn)
Definition: circuituse.c:2847
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:303
struct connection_t * linked_conn
int entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
Definition: entrynodes.c:2750
#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:275
struct or_circuit_t * rend_splice
Definition: or_circuit_st.h:50
int router_have_minimum_dir_info(void)
Definition: nodelist.c:2324
static int n_circuit_failures
Definition: circuituse.c:1926
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:691
int circuit_should_use_vanguards(uint8_t purpose)
Definition: circuituse.c:2031
smartlist_t * circuit_get_global_origin_circuit_list(void)
Definition: circuitlist.c:700
#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:2482
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:2395
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:1568
origin_circuit_t * circuit_find_to_cannibalize(uint8_t purpose_to_produce, extend_info_t *info, int flags)
Definition: circuitlist.c:1902
#define NUM_PARALLEL_TESTING_CIRCS
Definition: circuituse.c:1598
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:4014
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:3163
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
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
Header file for circuitpadding.c.
static time_t last_expired_clientside_circuits
Definition: circuituse.c:869
#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:1839
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:4581
static void circuit_increment_failure_count(void)
Definition: circuituse.c:2217
struct routerset_t * HSLayer2Nodes
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1260
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:664
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.
bool circuit_purpose_is_hs_vanguards(const uint8_t purpose)
Definition: circuituse.c:1999
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:2244
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
bool circuit_is_hs_v2(const circuit_t *circ)
Definition: circuituse.c:2006
time_t timestamp_created
void smartlist_del(smartlist_t *sl, int idx)
void addressmap_clean(time_t now)
Definition: addressmap.c:320
void circuit_remove_handled_ports(smartlist_t *needed_ports)
Definition: circuituse.c:1010
#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:1357
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:2814
#define LD_OR
Definition: log.h:92
rend_data_t * rend_data_dup(const rend_data_t *data)
Definition: hs_common.c:386
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
void circuit_expire_waiting_for_better_guard(void)
Definition: circuituse.c:854
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:1013
unsigned int edge_has_sent_end
int hostname_in_track_host_exits(const or_options_t *options, const char *address)
Definition: circuituse.c:2702
#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:576
Header file containing circuit data for the whole HS subsytem.
struct routerset_t * ExcludeExitNodes
Definition: or_options_st.h:93
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:878
unsigned int hs_circ_has_timed_out
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:165
void circuit_has_opened(origin_circuit_t *circ)
Definition: circuituse.c:1681
channel_t * p_chan
Definition: or_circuit_st.h:37
int package_window
Definition: circuit_st.h:116
const char * circuit_state_to_string(int state)
Definition: circuitlist.c:759
const char * rend_data_get_address(const rend_data_t *rend_data)
Definition: hs_common.c:528
#define MAX_CIRCUIT_FAILURES
Definition: circuituse.c:1933
static int circuit_try_clearing_isolation_state(origin_circuit_t *circ)
Definition: circuituse.c:1733
static int cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
Definition: circuituse.c:2602
origin_circuit_t * circuit_launch_by_extend_info(uint8_t purpose, extend_info_t *extend_info, int flags)
Definition: circuituse.c:2101
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:1474
void hs_client_note_connection_attempt_succeeded(const edge_connection_t *conn)
Definition: hs_client.c:1927
#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:2227
#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:2033
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:1772
void hs_client_circuit_has_opened(origin_circuit_t *circ)
Definition: hs_client.c:2076
circuit_build_times_t * get_circuit_build_times_mutable(void)
Definition: circuitstats.c:89
bool circuit_purpose_is_hs_client(const uint8_t purpose)
Definition: circuituse.c:1983
#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:2053
void mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
Definition: circuituse.c:3139
static void circuit_launch_predicted_hs_circ(int flags)
Definition: circuituse.c:1221
int connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
Definition: circuituse.c:2762
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:153
unsigned int hold_open_until_flushed
Definition: connection_st.h:61
#define tor_addr_eq(a, b)
Definition: address.h:253
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:2228
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:187
#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:2247
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:3795
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:78
Client request structure.
void circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
Definition: circuituse.c:3095
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:53
int connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
int entry_list_is_constrained(const or_options_t *options)
Definition: entrynodes.c:3276
void reset_bandwidth_test(void)
Definition: circuituse.c:1607
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:3184
consensus_path_type_t router_have_consensus_path(void)
Definition: nodelist.c:2357
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1388
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
unsigned int is_bad_for_new_circs
Definition: channel.h:424
struct routerset_t * HSLayer3Nodes
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:710
#define CIRCUIT_PURPOSE_S_REND_JOINED
Definition: circuitlist.h:112
struct hs_ident_circuit_t * hs_ident
#define CONN_TYPE_AP
Definition: connection.h:49
Header file for rendclient.c.
int circuit_any_opened_circuits(void)
Definition: circuitlist.c:715
int circuit_enough_testing_circs(void)
Definition: circuituse.c:1617
socks_request_t * socks_request
Header file for control_events.c.
bool circuit_purpose_is_hs_service(const uint8_t purpose)
Definition: circuituse.c:1991
static void link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ, crypt_path_t *cpath)
Definition: circuituse.c:2634
int guards_retry_optimistic(const or_options_t *options)
Definition: entrynodes.c:3717
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:1240
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:73
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:1929
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:1116
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)