Tor 0.4.9.2-alpha-dev
All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
circuitbuild.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-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file circuitbuild.c
9 *
10 * \brief Implements the details of building circuits (by choosing paths,
11 * constructing/sending create/extend cells, and so on).
12 *
13 * On the client side, this module handles launching circuits. Circuit
14 * launches are started from circuit_establish_circuit(), called from
15 * circuit_launch_by_extend_info()). To choose the path the circuit will
16 * take, onion_extend_cpath() calls into a maze of node selection functions.
17 *
18 * Once the circuit is ready to be launched, the first hop is treated as a
19 * special case with circuit_handle_first_hop(), since it might need to open a
20 * channel. As the channel opens, and later as CREATED and RELAY_EXTENDED
21 * cells arrive, the client will invoke circuit_send_next_onion_skin() to send
22 * CREATE or RELAY_EXTEND cells.
23 *
24 * The server side is handled in feature/relay/circuitbuild_relay.c.
25 **/
26
27#define CIRCUITBUILD_PRIVATE
28#define OCIRC_EVENT_PRIVATE
29
30#include "core/or/or.h"
31#include "app/config/config.h"
32#include "lib/confmgt/confmgt.h"
33#include "core/crypto/hs_ntor.h"
38#include "core/or/channel.h"
40#include "core/or/circuitlist.h"
42#include "core/or/circuituse.h"
44#include "core/or/command.h"
48#include "core/or/extendinfo.h"
49#include "core/or/onion.h"
50#include "core/or/ocirc_event.h"
51#include "core/or/policies.h"
52#include "core/or/relay.h"
53#include "core/or/trace_probes_circuit.h"
54#include "core/or/crypt_path.h"
55#include "core/or/protover.h"
57#include "feature/client/circpathbias.h"
75#include "lib/trace/events.h"
77
78#include "core/or/cell_st.h"
83#include "core/or/or_circuit_st.h"
85
86#include "trunnel/extension.h"
87#include "trunnel/congestion_control.h"
88#include "trunnel/subproto_request.h"
89
93 crypt_path_t *hop);
95 uint8_t purpose,
97 crypt_path_t *head,
98 int cur_len);
99
100/** This function tries to get a channel to the specified endpoint,
101 * and then calls command_setup_channel() to give it the right
102 * callbacks.
103 */
106{
107 channel_t *chan;
108
109 const tor_addr_port_t *orport = extend_info_pick_orport(ei);
110 if (!orport)
111 return NULL;
112 const char *id_digest = ei->identity_digest;
113 const ed25519_public_key_t *ed_id = &ei->ed_identity;
114
115 chan = channel_connect(&orport->addr, orport->port, id_digest, ed_id);
116 if (chan) command_setup_channel(chan);
117
118 return chan;
119}
120
121/** Search for a value for circ_id that we can use on <b>chan</b> for an
122 * outbound circuit, until we get a circ_id that is not in use by any other
123 * circuit on that conn.
124 *
125 * Return it, or 0 if can't get a unique circ_id.
126 */
129{
130/* This number is chosen somewhat arbitrarily; see comment below for more
131 * info. When the space is 80% full, it gives a one-in-a-million failure
132 * chance; when the space is 90% full, it gives a one-in-850 chance; and when
133 * the space is 95% full, it gives a one-in-26 failure chance. That seems
134 * okay, though you could make a case IMO for anything between N=32 and
135 * N=256. */
136#define MAX_CIRCID_ATTEMPTS 64
137 int in_use;
138 unsigned n_with_circ = 0, n_pending_destroy = 0, n_weird_pending_destroy = 0;
139 circid_t test_circ_id;
140 circid_t attempts=0;
141 circid_t high_bit, max_range, mask;
142 int64_t pending_destroy_time_total = 0;
143 int64_t pending_destroy_time_max = 0;
144
145 tor_assert(chan);
146
147 if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
148 log_warn(LD_BUG,
149 "Trying to pick a circuit ID for a connection from "
150 "a client with no identity.");
151 return 0;
152 }
153 max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
154 mask = max_range - 1;
155 high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
156 do {
157 if (++attempts > MAX_CIRCID_ATTEMPTS) {
158 /* Make sure we don't loop forever because all circuit IDs are used.
159 *
160 * Once, we would try until we had tried every possible circuit ID. But
161 * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
162 * circuit IDs, and then give up.
163 *
164 * This potentially causes us to give up early if our circuit ID space
165 * is nearly full. If we have N circuit IDs in use, then we will reject
166 * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
167 * This means that in practice, a few percent of our circuit ID capacity
168 * will go unused.
169 *
170 * The alternative here, though, is to do a linear search over the
171 * whole circuit ID space every time we extend a circuit, which is
172 * not so great either.
173 */
174 int64_t queued_destroys;
176 approx_time());
177 if (m == NULL)
178 return 0; /* This message has been rate-limited away. */
179 if (n_pending_destroy)
180 pending_destroy_time_total /= n_pending_destroy;
181 log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
182 "circID support, with %u inbound and %u outbound circuits. "
183 "Found %u circuit IDs in use by circuits, and %u with "
184 "pending destroy cells. (%u of those were marked bogusly.) "
185 "The ones with pending destroy cells "
186 "have been marked unusable for an average of %ld seconds "
187 "and a maximum of %ld seconds. This channel is %ld seconds "
188 "old. Failing a circuit.%s",
189 chan->wide_circ_ids ? "with" : "without",
190 chan->num_p_circuits, chan->num_n_circuits,
191 n_with_circ, n_pending_destroy, n_weird_pending_destroy,
192 (long)pending_destroy_time_total,
193 (long)pending_destroy_time_max,
194 (long)(approx_time() - chan->timestamp_created),
195 m);
196 tor_free(m);
197
198 if (!chan->cmux) {
199 /* This warning should be impossible. */
200 log_warn(LD_BUG, " This channel somehow has no cmux on it!");
201 return 0;
202 }
203
204 /* analysis so far on 12184 suggests that we're running out of circuit
205 IDs because it looks like we have too many pending destroy
206 cells. Let's see how many we really have pending.
207 */
208 queued_destroys = circuitmux_count_queued_destroy_cells(chan,
209 chan->cmux);
210
211 log_warn(LD_CIRC, " Circuitmux on this channel has %u circuits, "
212 "of which %u are active. It says it has %"PRId64
213 " destroy cells queued.",
216 (queued_destroys));
217
218 /* Change this into "if (1)" in order to get more information about
219 * possible failure modes here. You'll need to know how to use gdb with
220 * Tor: this will make Tor exit with an assertion failure if the cmux is
221 * corrupt. */
222 if (0)
223 circuitmux_assert_okay(chan->cmux);
224
226
227 return 0;
228 }
229
230 do {
231 crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
232 test_circ_id &= mask;
233 } while (test_circ_id == 0);
234
235 test_circ_id |= high_bit;
236
237 in_use = circuit_id_in_use_on_channel(test_circ_id, chan);
238 if (in_use == 1)
239 ++n_with_circ;
240 else if (in_use == 2) {
241 time_t since_when;
242 ++n_pending_destroy;
243 since_when =
245 if (since_when) {
246 time_t waiting = approx_time() - since_when;
247 pending_destroy_time_total += waiting;
248 if (waiting > pending_destroy_time_max)
249 pending_destroy_time_max = waiting;
250 } else {
251 ++n_weird_pending_destroy;
252 }
253 }
254 } while (in_use);
255 return test_circ_id;
256}
257
258/** If <b>verbose</b> is false, allocate and return a comma-separated list of
259 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
260 * list information about link status in a more verbose format using spaces.
261 * If <b>verbose_names</b> is false, give hex digests; if <b>verbose_names</b>
262 * is true, use $DIGEST=Name style names.
263 */
264static char *
265circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
266{
267 crypt_path_t *hop;
268 smartlist_t *elements;
269 const char *states[] = {"closed", "waiting for keys", "open"};
270 char *s;
271
272 elements = smartlist_new();
273
274 if (verbose) {
275 const char *nickname = build_state_get_exit_nickname(circ->build_state);
276 smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
277 circ->build_state->is_internal ? "internal" : "exit",
278 circ->build_state->need_uptime ? " (high-uptime)" : "",
280 circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
281 circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
282 (nickname?nickname:"*unnamed*"));
283 }
284
285 hop = circ->cpath;
286 do {
287 char *elt;
288 const char *id;
289 const node_t *node;
290 if (!hop)
291 break;
292 if (!verbose && hop->state != CPATH_STATE_OPEN)
293 break;
294 if (!hop->extend_info)
295 break;
296 id = hop->extend_info->identity_digest;
297 if (verbose_names) {
298 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
299 if ((node = node_get_by_id(id))) {
300 node_get_verbose_nickname(node, elt);
301 } else if (is_legal_nickname(hop->extend_info->nickname)) {
302 elt[0] = '$';
304 elt[HEX_DIGEST_LEN+1]= '~';
305 strlcpy(elt+HEX_DIGEST_LEN+2,
307 } else {
308 elt[0] = '$';
310 }
311 } else { /* ! verbose_names */
312 elt = tor_malloc(HEX_DIGEST_LEN+2);
313 elt[0] = '$';
315 }
316 tor_assert(elt);
317 if (verbose) {
318 tor_assert(hop->state <= 2);
319 smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
320 tor_free(elt);
321 } else {
322 smartlist_add(elements, elt);
323 }
324 hop = hop->next;
325 } while (hop != circ->cpath);
326
327 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
328 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
329 smartlist_free(elements);
330 return s;
331}
332
333/** If <b>verbose</b> is false, allocate and return a comma-separated
334 * list of the currently built elements of <b>circ</b>. If
335 * <b>verbose</b> is true, also list information about link status in
336 * a more verbose format using spaces.
337 */
338char *
340{
341 return circuit_list_path_impl(circ, verbose, 0);
342}
343
344/** Allocate and return a comma-separated list of the currently built elements
345 * of <b>circ</b>, giving each as a verbose nickname.
346 */
347char *
349{
350 return circuit_list_path_impl(circ, 0, 1);
351}
352
353/** Log, at severity <b>severity</b>, the nicknames of each router in
354 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
355 * exit point.
356 */
357void
358circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
359{
360 char *s = circuit_list_path(circ,1);
361 tor_log(severity,domain,"%s",s);
362 tor_free(s);
363}
364
365/** Return 1 iff every node in circ's cpath definitely supports ntor. */
366static int
368{
369 crypt_path_t *head, *cpath;
370
371 cpath = head = circ->cpath;
372 do {
373 /* if the extend_info is missing, we can't tell if it supports ntor */
374 if (!cpath->extend_info) {
375 return 0;
376 }
377
378 /* if the key is blank, it definitely doesn't support ntor */
379 if (!extend_info_supports_ntor(cpath->extend_info)) {
380 return 0;
381 }
382 cpath = cpath->next;
383 } while (cpath != head);
384
385 return 1;
386}
387
388/** Pick all the entries in our cpath. Stop and return 0 when we're
389 * happy, or return -1 if an error occurs. */
390static int
392{
393 int r = 0;
394
395 /* onion_extend_cpath assumes these are non-NULL */
396 tor_assert(circ);
397 tor_assert(circ->build_state);
398
399 while (r == 0) {
400 r = onion_extend_cpath(circ);
401 if (r < 0) {
402 log_info(LD_CIRC,"Generating cpath hop failed.");
403 return -1;
404 }
405 }
406
407 /* The path is complete */
408 tor_assert(r == 1);
409
410 /* Does every node in this path support ntor? */
411 int path_supports_ntor = circuit_cpath_supports_ntor(circ);
412
413 /* We would like every path to support ntor, but we have to allow for some
414 * edge cases. */
416
417 if (circuit_get_cpath_len(circ) == 1) {
418 /* Allow for bootstrapping: when we're fetching directly from a fallback,
419 * authority, or bridge, we have no way of knowing its ntor onion key
420 * before we connect to it. So instead, we try connecting, and end up using
421 * CREATE_FAST. */
422 tor_assert(circ->cpath);
424 const node_t *node = node_get_by_id(
426 /* If we don't know the node and its descriptor, we must be bootstrapping.
427 */
428 if (!node || !node_has_preferred_descriptor(node, 1)) {
429 return 0;
430 }
431 }
432
433 if (BUG(!path_supports_ntor)) {
434 /* If we're building a multi-hop path, and it's not one of the HS or
435 * bootstrapping exceptions, and it doesn't support ntor, something has
436 * gone wrong. */
437 return -1;
438 }
439
440 return 0;
441}
442
443/** Create and return a new origin circuit. Initialize its purpose and
444 * build-state based on our arguments. The <b>flags</b> argument is a
445 * bitfield of CIRCLAUNCH_* flags, see circuit_launch_by_extend_info() for
446 * more details. */
448origin_circuit_init(uint8_t purpose, int flags)
449{
450 /* sets circ->p_circ_id and circ->p_chan */
453 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
455 ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
456 circ->build_state->need_uptime =
457 ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
459 ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
460 circ->build_state->is_internal =
461 ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
463 ((flags & CIRCLAUNCH_IS_IPV6_SELFTEST) ? 1 : 0);
465 ((flags & CIRCLAUNCH_NEED_CONFLUX) ? 1 : 0);
466 circ->base_.purpose = purpose;
467 return circ;
468}
469
470/** Build a new circuit for <b>purpose</b>. If <b>exit</b> is defined, then use
471 * that as your exit router, else choose a suitable exit node. The <b>flags</b>
472 * argument is a bitfield of CIRCLAUNCH_* flags, see
473 * circuit_launch_by_extend_info() for more details.
474 *
475 * Also launch a connection to the first OR in the chosen path, if
476 * it's not open already.
477 */
479circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
480{
481 origin_circuit_t *circ;
482 int err_reason = 0;
483
484 circ = origin_circuit_init(purpose, flags);
485
486 if (onion_pick_cpath_exit(circ, exit_ei) < 0 ||
487 onion_populate_cpath(circ) < 0) {
488 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
489 return NULL;
490 }
491
492 circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
493
494 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
495 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
496 return NULL;
497 }
498
499 tor_trace(TR_SUBSYS(circuit), TR_EV(establish), circ);
500 return circ;
501}
502
503/**
504 * Build a new conflux circuit for <b>purpose</b>. If <b>exit</b> is defined,
505 * then use that as your exit router, else choose a suitable exit node.
506 * The <b>flags</b> argument is a bitfield of CIRCLAUNCH_* flags, see
507 * circuit_launch_by_extend_info() for more details.
508 *
509 * Also launch a connection to the first OR in the chosen path, if
510 * it's not open already.
511 */
513circuit_establish_circuit_conflux,(const uint8_t *conflux_nonce,
514 uint8_t purpose, extend_info_t *exit_ei,
515 int flags))
516{
517 origin_circuit_t *circ;
518 int err_reason = 0;
519
520 /* Right now, only conflux client circuits use this function */
522
523 circ = origin_circuit_init(purpose, flags);
524 TO_CIRCUIT(circ)->conflux_pending_nonce =
525 tor_memdup(conflux_nonce, DIGEST256_LEN);
526
527 if (onion_pick_cpath_exit(circ, exit_ei) < 0 ||
528 onion_populate_cpath(circ) < 0) {
529 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
530 return NULL;
531 }
532
533 circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
534
535 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
536 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
537 return NULL;
538 }
539
540 tor_trace(TR_SUBSYS(circuit), TR_EV(establish), circ);
541 return circ;
542}
543
544/** Return the guard state associated with <b>circ</b>, which may be NULL. */
545circuit_guard_state_t *
547{
548 return circ->guard_state;
549}
550
551/**
552 * Helper function to publish a channel association message
553 *
554 * circuit_handle_first_hop() calls this to notify subscribers about a
555 * channel launch event, which associates a circuit with a channel.
556 * This doesn't always correspond to an assignment of the circuit's
557 * n_chan field, because that seems to be only for fully-open
558 * channels.
559 **/
560static void
562{
563 ocirc_chan_msg_t *msg = tor_malloc(sizeof(*msg));
564
565 msg->gid = circ->global_identifier;
566 msg->chan = chan->global_identifier;
567 msg->onehop = circ->build_state->onehop_tunnel;
568
569 ocirc_chan_publish(msg);
570}
571
572/** Start establishing the first hop of our circuit. Figure out what
573 * OR we should connect to, and if necessary start the connection to
574 * it. If we're already connected, then send the 'create' cell.
575 * Return 0 for ok, -reason if circ should be marked-for-close. */
576int
578{
579 crypt_path_t *firsthop;
580 channel_t *n_chan;
581 int err_reason = 0;
582 const char *msg = NULL;
583 int should_launch = 0;
584 const or_options_t *options = get_options();
585
586 firsthop = cpath_get_next_non_open_hop(circ->cpath);
587 tor_assert(firsthop);
588 tor_assert(firsthop->extend_info);
589
590 /* Some bridges are on private addresses. Others pass a dummy private
591 * address to the pluggable transport, which ignores it.
592 * Deny the connection if:
593 * - the address is internal, and
594 * - we're not connecting to a configured bridge, and
595 * - we're not configured to allow extends to private addresses. */
598 !options->ExtendAllowPrivateAddresses) {
599 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
600 "Client asked me to connect directly to a private address");
601 return -END_CIRC_REASON_TORPROTOCOL;
602 }
603
604 /* now see if we're already connected to the first OR in 'route' */
605 const tor_addr_port_t *orport4 =
606 extend_info_get_orport(firsthop->extend_info, AF_INET);
607 const tor_addr_port_t *orport6 =
608 extend_info_get_orport(firsthop->extend_info, AF_INET6);
609 n_chan = channel_get_for_extend(
610 firsthop->extend_info->identity_digest,
611 &firsthop->extend_info->ed_identity,
612 orport4 ? &orport4->addr : NULL,
613 orport6 ? &orport6->addr : NULL,
614 true,
615 &msg,
616 &should_launch);
617
618 if (!n_chan) {
619 /* not currently connected in a useful way. */
620 log_info(LD_CIRC, "Next router is %s: %s",
621 safe_str_client(extend_info_describe(firsthop->extend_info)),
622 msg?msg:"???");
623 circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
624
625 if (should_launch) {
626 n_chan = channel_connect_for_circuit(firsthop->extend_info);
627 if (!n_chan) { /* connect failed, forget the whole thing */
628 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
629 return -END_CIRC_REASON_CONNECTFAILED;
630 }
631 /* We didn't find a channel, but we're launching one for an origin
632 * circuit. (If we decided not to launch a channel, then we found at
633 * least one once good in-progress channel use for this circuit, and
634 * marked it in channel_get_for_extend().) */
636 circuit_chan_publish(circ, n_chan);
637 }
638
639 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
640 /* return success. The onion/circuit/etc will be taken care of
641 * automatically (may already have been) whenever n_chan reaches
642 * OR_CONN_STATE_OPEN.
643 */
644 return 0;
645 } else { /* it's already open. use it. */
646 tor_assert(!circ->base_.n_hop);
647 circ->base_.n_chan = n_chan;
648 /* We found a channel, and we're using it for an origin circuit. */
650 circuit_chan_publish(circ, n_chan);
651 log_debug(LD_CIRC,"Conn open for %s. Delivering first onion skin.",
652 safe_str_client(extend_info_describe(firsthop->extend_info)));
653 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
654 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
655 circ->base_.n_chan = NULL;
656 return err_reason;
657 }
658 }
659 return 0;
660}
661
662/** Find any circuits that are waiting on <b>or_conn</b> to become
663 * open and get them to send their create cells forward.
664 *
665 * Status is 1 if connect succeeded, or 0 if connect failed.
666 *
667 * Close_origin_circuits is 1 if we should close all the origin circuits
668 * through this channel, or 0 otherwise. (This happens when we want to retry
669 * an older guard.)
670 */
671void
672circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
673{
674 smartlist_t *pending_circs;
675 int err_reason = 0;
676
677 tor_assert(chan);
678
679 log_debug(LD_CIRC,"chan to %s, status=%d",
680 channel_describe_peer(chan), status);
681
682 pending_circs = smartlist_new();
683 circuit_get_all_pending_on_channel(pending_circs, chan);
684
685 SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
686 {
687 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
688 * leaving them in in case it's possible for the status of a circuit to
689 * change as we're going down the list. */
690 if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
691 circ->state != CIRCUIT_STATE_CHAN_WAIT)
692 continue;
693
694 const char *rsa_ident = NULL;
695 const ed25519_public_key_t *ed_ident = NULL;
696 if (! tor_digest_is_zero(circ->n_hop->identity_digest)) {
697 rsa_ident = circ->n_hop->identity_digest;
698 }
699 if (! ed25519_public_key_is_zero(&circ->n_hop->ed_identity)) {
700 ed_ident = &circ->n_hop->ed_identity;
701 }
702
703 if (rsa_ident == NULL && ed_ident == NULL) {
704 /* Look at addr/port. This is an unkeyed connection. */
705 if (!channel_matches_extend_info(chan, circ->n_hop))
706 continue;
707 } else {
708 /* We expected a key or keys. See if they matched. */
709 if (!channel_remote_identity_matches(chan, rsa_ident, ed_ident))
710 continue;
711
712 /* If the channel is canonical, great. If not, it needs to match
713 * the requested address exactly. */
714 if (! chan->is_canonical &&
715 ! channel_matches_extend_info(chan, circ->n_hop)) {
716 continue;
717 }
718 }
719 if (!status) { /* chan failed; close circ */
720 log_info(LD_CIRC,"Channel failed; closing circ.");
721 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
722 continue;
723 }
724
725 if (close_origin_circuits && CIRCUIT_IS_ORIGIN(circ)) {
726 log_info(LD_CIRC,"Channel deprecated for origin circs; closing circ.");
727 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
728 continue;
729 }
730 log_debug(LD_CIRC, "Found circ, sending create cell.");
731 /* circuit_deliver_create_cell will set n_circ_id and add us to
732 * chan_circuid_circuit_map, so we don't need to call
733 * set_circid_chan here. */
734 circ->n_chan = chan;
735 extend_info_free(circ->n_hop);
736 circ->n_hop = NULL;
737
738 if (CIRCUIT_IS_ORIGIN(circ)) {
739 if ((err_reason =
741 log_info(LD_CIRC,
742 "send_next_onion_skin failed; circuit marked for closing.");
743 circuit_mark_for_close(circ, -err_reason);
744 continue;
745 /* XXX could this be bad, eg if next_onion_skin failed because conn
746 * died? */
747 }
748 } else {
749 /* pull the create cell out of circ->n_chan_create_cell, and send it */
750 tor_assert(circ->n_chan_create_cell);
751 if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
752 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
753 continue;
754 }
755 tor_free(circ->n_chan_create_cell);
757 }
758 }
759 SMARTLIST_FOREACH_END(circ);
760
761 smartlist_free(pending_circs);
762}
763
764/** Find a new circid that isn't currently in use on the circ->n_chan
765 * for the outgoing
766 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
767 * circuit. If <b>relayed</b> is true, this is a create cell somebody
768 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
769 * it. Return -1 if we failed to find a suitable circid, else return 0.
770 */
771MOCK_IMPL(int,
773 const struct create_cell_t *create_cell,
774 int relayed))
775{
776 cell_t cell;
777 circid_t id;
778 int r;
779
780 tor_assert(circ);
781 tor_assert(circ->n_chan);
782 tor_assert(create_cell);
783 tor_assert(create_cell->cell_type == CELL_CREATE ||
784 create_cell->cell_type == CELL_CREATE_FAST ||
785 create_cell->cell_type == CELL_CREATE2);
786
788 if (!id) {
789 static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
790 log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
791 "failed to get unique circID.");
792 goto error;
793 }
794
795 tor_assert_nonfatal_once(circ->n_chan->is_canonical);
796
797 memset(&cell, 0, sizeof(cell_t));
798 r = relayed ? create_cell_format_relayed(&cell, create_cell)
799 : create_cell_format(&cell, create_cell);
800 if (r < 0) {
801 log_warn(LD_CIRC,"Couldn't format create cell");
802 goto error;
803 }
804 log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
805 circuit_set_n_circid_chan(circ, id, circ->n_chan);
806 cell.circ_id = circ->n_circ_id;
807
808 if (append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
809 CELL_DIRECTION_OUT, 0) < 0) {
810 return -1;
811 }
812
813 if (CIRCUIT_IS_ORIGIN(circ)) {
814 /* Update began timestamp for circuits starting their first hop */
815 if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
816 if (!CHANNEL_IS_OPEN(circ->n_chan)) {
817 log_warn(LD_CIRC,
818 "Got first hop for a circuit without an opened channel. "
819 "State: %s.", channel_state_to_string(circ->n_chan->state));
821 }
822
824 }
825
826 /* mark it so it gets better rate limiting treatment. */
828 }
829
830 return 0;
831 error:
832 circ->n_chan = NULL;
833 return -1;
834}
835
836/** Return true iff we should send a create_fast cell to start building a
837 * given circuit */
838static inline bool
840{
841 tor_assert(circ->cpath);
843
844 return ! circuit_has_usable_onion_key(circ);
845}
846
847/**
848 * Return true if <b>circ</b> is the type of circuit we want to count
849 * timeouts from.
850 *
851 * In particular, we want to consider any circuit that plans to build
852 * at least 3 hops (but maybe more), but has 3 or fewer hops built
853 * so far.
854 *
855 * We still want to consider circuits before 3 hops, because we need
856 * to decide if we should convert them to a measurement circuit in
857 * circuit_build_times_handle_completed_hop(), rather than letting
858 * slow circuits get killed right away.
859 */
860int
862{
863 return !circ->has_opened
866}
867
868/** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
869 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
870 * accordingly.
871 * Note that TAP handshakes in CREATE cells are only used for direct
872 * connections:
873 * - from Single Onions to rend points not in the service's consensus.
874 * This is checked in onion_populate_cpath. */
875static void
876circuit_pick_create_handshake(uint8_t *cell_type_out,
877 uint16_t *handshake_type_out,
878 const extend_info_t *ei)
879{
880 /* torspec says: In general, clients SHOULD use CREATE whenever they are
881 * using the TAP handshake, and CREATE2 otherwise. */
882 *cell_type_out = CELL_CREATE2;
883 /* Only use ntor v3 with exits that support congestion control,
884 * and only when it is enabled. */
887 *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR_V3;
888 else if (ei->enable_cgo)
889 *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR_V3;
890 else
891 *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
892}
893
894/** Decide whether to use a TAP or ntor handshake for extending to <b>ei</b>
895 * and set *<b>handshake_type_out</b> accordingly. Decide whether we should
896 * use an EXTEND2 or an EXTEND cell to do so, and set *<b>cell_type_out</b>
897 * and *<b>create_cell_type_out</b> accordingly.
898 * Note that TAP handshakes in EXTEND cells are only used:
899 * - from clients to intro points, and
900 * - from hidden services to rend points.
901 * This is checked in onion_populate_cpath.
902 */
903static void
904circuit_pick_extend_handshake(uint8_t *cell_type_out,
905 uint8_t *create_cell_type_out,
906 uint16_t *handshake_type_out,
907 const extend_info_t *ei)
908{
909 uint8_t t;
910 circuit_pick_create_handshake(&t, handshake_type_out, ei);
911
912 *cell_type_out = RELAY_COMMAND_EXTEND2;
913 *create_cell_type_out = CELL_CREATE2;
914}
915
916/**
917 * Return true iff <b>circ</b> is allowed
918 * to have no guard configured, even if the circuit is multihop
919 * and guards are enabled.
920 */
921static int
923{
924 if (BUG(!circ))
925 return 0;
926
927 if (circ->first_hop_from_controller) {
928 /* The controller picked the first hop: that bypasses the guard system. */
929 return 1;
930 }
931
932 switch (circ->base_.purpose) {
935 /* Testing circuits may omit guards because they're measuring
936 * liveness or performance, and don't want guards to interfere. */
937 return 1;
938 default:
939 /* All other multihop circuits should use guards if guards are
940 * enabled. */
941 return 0;
942 }
943}
944
945/** This is the backbone function for building circuits.
946 *
947 * If circ's first hop is closed, then we need to build a create
948 * cell and send it forward.
949 *
950 * Otherwise, if circ's cpath still has any non-open hops, we need to
951 * build a relay extend cell and send it forward to the next non-open hop.
952 *
953 * If all hops on the cpath are open, we're done building the circuit
954 * and we should do housekeeping for the newly opened circuit.
955 *
956 * Return -reason if we want to tear down circ, else return 0.
957 */
958int
960{
961 tor_assert(circ);
962
963 if (circ->cpath->state == CPATH_STATE_CLOSED) {
964 /* Case one: we're on the first hop. */
966 }
967
968 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
970
973
975
976 if (hop) {
977 /* Case two: we're on a hop after the first. */
978 return circuit_send_intermediate_onion_skin(circ, hop);
979 }
980
981 /* Case three: the circuit is finished. Do housekeeping tasks on it. */
983 return circuit_build_no_more_hops(circ);
984}
985
986/**
987 * Called from circuit_send_next_onion_skin() when we find ourselves connected
988 * to the first hop in <b>circ</b>: Send a CREATE or CREATE2 or CREATE_FAST
989 * cell to that hop. Return 0 on success; -reason on failure (if the circuit
990 * should be torn down).
991 */
992static int
994{
995 int fast;
996 int len;
997 const node_t *node;
998 create_cell_t cc;
999 memset(&cc, 0, sizeof(cc));
1000
1001 log_debug(LD_CIRC,"First skin; sending create cell.");
1002
1003 if (circ->build_state->onehop_tunnel) {
1004 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
1005 } else {
1006 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
1007
1008 /* If this is not a one-hop tunnel, the channel is being used
1009 * for traffic that wants anonymity and protection from traffic
1010 * analysis (such as netflow record retention). That means we want
1011 * to pad it.
1012 */
1013 if (circ->base_.n_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS)
1014 circ->base_.n_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
1015 }
1016
1017 node = node_get_by_id(circ->base_.n_chan->identity_digest);
1019 if (!fast) {
1020 /* We know the right onion key: we should send a create cell. */
1022 circ->cpath->extend_info);
1023 } else {
1024 /* We don't know an onion key, so we need to fall back to CREATE_FAST. */
1025 cc.cell_type = CELL_CREATE_FAST;
1026 cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
1027 }
1028
1030 circ->cpath->extend_info,
1031 &circ->cpath->handshake_state,
1032 cc.onionskin,
1033 sizeof(cc.onionskin));
1034 if (len < 0) {
1035 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
1036 return - END_CIRC_REASON_INTERNAL;
1037 }
1038 cc.handshake_len = len;
1039
1040 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
1041 return - END_CIRC_REASON_RESOURCELIMIT;
1042 tor_trace(TR_SUBSYS(circuit), TR_EV(first_onion_skin), circ, circ->cpath);
1043
1044 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
1046 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
1047 fast ? "CREATE_FAST" : "CREATE",
1048 node ? node_describe(node) : "<unnamed>");
1049 return 0;
1050}
1051
1052/**
1053 * Called from circuit_send_next_onion_skin() when we find that we have no
1054 * more hops: mark the circuit as finished, and perform the necessary
1055 * bookkeeping. Return 0 on success; -reason on failure (if the circuit
1056 * should be torn down).
1057 */
1058static int
1060{
1061 guard_usable_t r;
1062 if (! circ->guard_state) {
1063 if (circuit_get_cpath_len(circ) != 1 &&
1064 ! circuit_may_omit_guard(circ) &&
1065 get_options()->UseEntryGuards) {
1066 log_warn(LD_BUG, "%d-hop circuit %p with purpose %d has no "
1067 "guard state",
1068 circuit_get_cpath_len(circ), circ, circ->base_.purpose);
1069 }
1070 r = GUARD_USABLE_NOW;
1071 } else {
1073 }
1074 const int is_usable_for_streams = (r == GUARD_USABLE_NOW);
1075 if (r == GUARD_USABLE_NOW) {
1077 } else if (r == GUARD_MAYBE_USABLE_LATER) {
1078 // Wait till either a better guard succeeds, or till
1079 // all better guards fail.
1081 } else {
1082 tor_assert_nonfatal(r == GUARD_USABLE_NEVER);
1083 return - END_CIRC_REASON_INTERNAL;
1084 }
1085
1086 /* XXXX #21422 -- the rest of this branch needs careful thought!
1087 * Some of the things here need to happen when a circuit becomes
1088 * mechanically open; some need to happen when it is actually usable.
1089 * I think I got them right, but more checking would be wise. -NM
1090 */
1091
1092 log_info(LD_CIRC,"circuit built!");
1094
1095 if (circ->build_state->onehop_tunnel || circ->has_opened) {
1096 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
1097 }
1098
1100 if (is_usable_for_streams)
1101 circuit_has_opened(circ); /* do other actions as necessary */
1102
1104 const or_options_t *options = get_options();
1106 /* FFFF Log a count of known routers here */
1107 log_info(LD_GENERAL,
1108 "Tor has successfully opened a circuit. "
1109 "Looks like client functionality is working.");
1110 control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
1111 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
1113 if (server_mode(options) &&
1114 !router_all_orports_seem_reachable(options)) {
1116 }
1117 }
1118
1119 /* We're done with measurement circuits here. Just close them */
1120 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
1121 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
1122 }
1123 return 0;
1124}
1125
1126/**
1127 * Called from circuit_send_next_onion_skin() when we find that we have a hop
1128 * other than the first that we need to extend to: use <b>hop</b>'s
1129 * information to extend the circuit another step. Return 0 on success;
1130 * -reason on failure (if the circuit should be torn down).
1131 */
1132static int
1134 crypt_path_t *hop)
1135{
1136 int len;
1137 extend_cell_t ec;
1138 /* Relays and bridges can send IPv6 extends. But for clients, it's an
1139 * obvious version distinguisher. */
1140 const bool include_ipv6 = server_mode(get_options());
1141 memset(&ec, 0, sizeof(ec));
1144
1145 log_debug(LD_CIRC,"starting to send subsequent skin.");
1146
1150 hop->extend_info);
1151
1152 const tor_addr_port_t *orport4 =
1153 extend_info_get_orport(hop->extend_info, AF_INET);
1154 const tor_addr_port_t *orport6 =
1155 extend_info_get_orport(hop->extend_info, AF_INET6);
1156 int n_addrs_set = 0;
1157 if (orport4) {
1158 tor_addr_copy(&ec.orport_ipv4.addr, &orport4->addr);
1159 ec.orport_ipv4.port = orport4->port;
1160 ++n_addrs_set;
1161 }
1162 if (orport6 && include_ipv6) {
1163 tor_addr_copy(&ec.orport_ipv6.addr, &orport6->addr);
1164 ec.orport_ipv6.port = orport6->port;
1165 ++n_addrs_set;
1166 }
1167
1168 if (n_addrs_set == 0) {
1169 log_warn(LD_BUG, "No supported address family found in extend_info.");
1170 return - END_CIRC_REASON_INTERNAL;
1171 }
1172 memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
1173 /* Set the ED25519 identity too -- it will only get included
1174 * in the extend2 cell if we're configured to use it, though. */
1176
1178 hop->extend_info,
1179 &hop->handshake_state,
1181 sizeof(ec.create_cell.onionskin));
1182 if (len < 0) {
1183 log_warn(LD_CIRC,"onion_skin_create failed.");
1184 return - END_CIRC_REASON_INTERNAL;
1185 }
1186 ec.create_cell.handshake_len = len;
1187
1188 log_info(LD_CIRC,"Sending extend relay cell.");
1189 {
1190 uint8_t command = 0;
1191 uint16_t payload_len=0;
1192 uint8_t payload[RELAY_PAYLOAD_SIZE_MAX];
1193 if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
1194 log_warn(LD_CIRC,"Couldn't format extend cell");
1195 return -END_CIRC_REASON_INTERNAL;
1196 }
1197
1198 if (payload_len > circuit_max_relay_payload(
1199 TO_CIRCUIT(circ), hop->prev, command)) {
1200 log_warn(LD_BUG, "Generated a too-long extend cell");
1201 return -END_CIRC_REASON_INTERNAL;
1202 }
1203
1204 /* send it to hop->prev, because that relay will transfer
1205 * it to a create cell and then send to hop */
1206 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1207 command,
1208 (char*)payload, payload_len,
1209 hop->prev) < 0)
1210 return 0; /* circuit is closed */
1211 }
1212 hop->state = CPATH_STATE_AWAITING_KEYS;
1213 tor_trace(TR_SUBSYS(circuit), TR_EV(intermediate_onion_skin), circ, hop);
1214 return 0;
1215}
1216
1217/** Our clock just jumped by <b>seconds_elapsed</b>. If <b>was_idle</b> is
1218 * true, then the monotonic time matches; otherwise it doesn't. Assume
1219 * something has also gone wrong with our network: notify the user, and
1220 * abandon all not-yet-used circuits. */
1221void
1222circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
1223{
1224 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
1225 if (was_idle) {
1226 tor_log(severity, LD_GENERAL, "Tor has been idle for %"PRId64
1227 " seconds; assuming established circuits no longer work.",
1228 (seconds_elapsed));
1229 } else {
1230 tor_log(severity, LD_GENERAL,
1231 "Your system clock just jumped %"PRId64" seconds %s; "
1232 "assuming established circuits no longer work.",
1233 (
1234 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed),
1235 seconds_elapsed >=0 ? "forward" : "backward");
1236 }
1237 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%"PRId64
1238 " IDLE=%d",
1239 (seconds_elapsed), was_idle?1:0);
1240 /* so we log when it works again */
1242 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
1243 "CLOCK_JUMPED");
1246 if (seconds_elapsed < 0) {
1247 /* Restart all the timers in case we jumped a long way into the past. */
1249 }
1250}
1251
1252/** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
1253 * (The body of <b>reply</b> varies depending on what sort of handshake
1254 * this is.)
1255 *
1256 * Calculate the appropriate keys and digests, make sure KH is
1257 * correct, and initialize this hop of the cpath.
1258 *
1259 * Return - reason if we want to mark circ for close, else return 0.
1260 */
1261int
1263 const created_cell_t *reply)
1264{
1265 char keys[MAX_RELAY_KEY_MATERIAL_LEN];
1266 crypt_path_t *hop;
1267 int rv;
1268
1269 if ((rv = pathbias_count_build_attempt(circ)) < 0) {
1270 log_warn(LD_CIRC, "pathbias_count_build_attempt failed: %d", rv);
1271 return rv;
1272 }
1273
1274 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
1275 hop = circ->cpath;
1276 } else {
1278 if (!hop) { /* got an extended when we're all done? */
1279 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
1280 return - END_CIRC_REASON_TORPROTOCOL;
1281 }
1282 }
1283 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
1284
1285 circuit_params_t params;
1286 size_t keylen = sizeof(keys);
1287 {
1288 const char *msg = NULL;
1289
1291 &hop->handshake_state,
1292 reply->reply, reply->handshake_len,
1293 (uint8_t*)keys, &keylen,
1294 (uint8_t*)hop->rend_circ_nonce,
1295 &params,
1296 &msg) < 0) {
1297 if (msg)
1298 log_warn(LD_CIRC,"onion_skin_client_handshake failed: %s", msg);
1299 return -END_CIRC_REASON_TORPROTOCOL;
1300 }
1301 }
1302
1305 hop, keys, keylen)<0) {
1306 return -END_CIRC_REASON_TORPROTOCOL;
1307 }
1308 hop->relay_cell_format = params.cell_fmt;
1309
1310 if (params.cc_enabled) {
1311 int circ_len = circuit_get_cpath_len(circ);
1312
1313 if (circ_len == DEFAULT_ROUTE_LEN &&
1315 hop->ccontrol = congestion_control_new(&params, CC_PATH_EXIT);
1316 } else if (circ_len == SBWS_ROUTE_LEN &&
1317 circuit_get_cpath_hop(circ, SBWS_ROUTE_LEN) == hop) {
1318 hop->ccontrol = congestion_control_new(&params, CC_PATH_SBWS);
1319 } else {
1320 if (circ_len > DEFAULT_ROUTE_LEN) {
1321 /* This can happen for unknown reasons; cannibalization codepaths
1322 * don't seem able to do it, so there is some magic way that hops can
1323 * still get added. Perhaps some cases of circuit pre-build that change
1324 * purpose? */
1325 log_info(LD_CIRC,
1326 "Unexpected path length %d for exit circuit %d, purpose %d",
1327 circ_len, circ->global_identifier,
1328 TO_CIRCUIT(circ)->purpose);
1329 hop->ccontrol = congestion_control_new(&params, CC_PATH_EXIT);
1330 } else {
1331 /* This is likely directory requests, which should block on orconn
1332 * before congestion control, but let's give them the lower sbws
1333 * param set anyway just in case. */
1334 log_info(LD_CIRC,
1335 "Unexpected path length %d for exit circuit %d, purpose %d",
1336 circ_len, circ->global_identifier,
1337 TO_CIRCUIT(circ)->purpose);
1338
1339 hop->ccontrol = congestion_control_new(&params, CC_PATH_SBWS);
1340 }
1341 }
1342 }
1343
1344 hop->state = CPATH_STATE_OPEN;
1345 log_info(LD_CIRC,"Finished building circuit hop:");
1347 circuit_event_status(circ, CIRC_EVENT_EXTENDED, 0);
1348
1349 return 0;
1350}
1351
1352/** We received a relay truncated cell on circ.
1353 *
1354 * Since we don't send truncates currently, getting a truncated
1355 * means that a connection broke or an extend failed. For now,
1356 * just give up: force circ to close, and return 0.
1357 */
1358int
1360{
1361// crypt_path_t *victim;
1362// connection_t *stream;
1363
1364 tor_assert(circ);
1365
1366 /* XXX Since we don't send truncates currently, getting a truncated
1367 * means that a connection broke or an extend failed. For now,
1368 * just give up.
1369 */
1370 circuit_mark_for_close(TO_CIRCUIT(circ),
1372 return 0;
1373
1374#if 0
1375 while (layer->next != circ->cpath) {
1376 /* we need to clear out layer->next */
1377 victim = layer->next;
1378 log_debug(LD_CIRC, "Killing a layer of the cpath.");
1379
1380 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
1381 if (stream->cpath_layer == victim) {
1382 log_info(LD_APP, "Marking stream %d for close because of truncate.",
1383 stream->stream_id);
1384 /* no need to send 'end' relay cells,
1385 * because the other side's already dead
1386 */
1387 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
1388 }
1389 }
1390
1391 layer->next = victim->next;
1392 cpath_free(victim);
1393 }
1394
1395 log_info(LD_CIRC, "finished");
1396 return 0;
1397#endif /* 0 */
1398}
1399
1400/** Helper for new_route_len(). Choose a circuit length for purpose
1401 * <b>purpose</b>: DEFAULT_ROUTE_LEN (+ 1 if someone else chose the
1402 * exit). If someone else chose the exit, they could be colluding
1403 * with the exit, so add a randomly selected node to preserve
1404 * anonymity.
1405 *
1406 * Here, "exit node" sometimes means an OR acting as an internal
1407 * endpoint, rather than as a relay to an external endpoint. This
1408 * means there need to be at least DEFAULT_ROUTE_LEN routers between
1409 * us and the internal endpoint to preserve the same anonymity
1410 * properties that we would get when connecting to an external
1411 * endpoint. These internal endpoints can include:
1412 *
1413 * - Connections to a directory of hidden services
1414 * (CIRCUIT_PURPOSE_C_GENERAL)
1415 *
1416 * - A client connecting to an introduction point, which the hidden
1417 * service picked (CIRCUIT_PURPOSE_C_INTRODUCING, via
1418 * circuit_get_open_circ_or_launch() which rewrites it from
1419 * CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1420 *
1421 * - A hidden service connecting to a rendezvous point, which the
1422 * client picked (CIRCUIT_PURPOSE_S_CONNECT_REND.
1423 *
1424 * There are currently two situations where we picked the exit node
1425 * ourselves, making DEFAULT_ROUTE_LEN a safe circuit length:
1426 *
1427 * - We are a hidden service connecting to an introduction point
1428 * (CIRCUIT_PURPOSE_S_ESTABLISH_INTRO).
1429 *
1430 * - We are a router testing its own reachabiity
1431 * (CIRCUIT_PURPOSE_TESTING, via router_do_reachability_checks())
1432 *
1433 * onion_pick_cpath_exit() bypasses us (by not calling
1434 * new_route_len()) in the one-hop tunnel case, so we don't need to
1435 * handle that.
1436 */
1437int
1438route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
1439{
1440 int routelen = DEFAULT_ROUTE_LEN;
1441 int known_purpose = 0;
1442
1443 /* If we're using L3 vanguards, we need longer paths for onion services */
1444 if (circuit_purpose_is_hidden_service(purpose) &&
1445 get_options()->HSLayer3Nodes) {
1446 /* Clients want an extra hop for rends to avoid linkability.
1447 * Services want it for intro points to avoid publishing their
1448 * layer3 guards. They want it for hsdir posts to use
1449 * their full layer3 guard set for those connections.
1450 * Ex: C - G - L2 - L3 - R
1451 * S - G - L2 - L3 - HSDIR
1452 * S - G - L2 - L3 - I
1453 */
1454 if (purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
1455 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1456 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1458 return routelen+1;
1459
1460 /* For connections to hsdirs, clients want two extra hops
1461 * when using layer3 guards, to avoid linkability.
1462 * Same goes for intro points. Note that the route len
1463 * includes the intro point or hsdir, hence the +2.
1464 * Ex: C - G - L2 - L3 - M - I
1465 * C - G - L2 - L3 - M - HSDIR
1466 * S - G - L2 - L3 - M - R
1467 */
1468 if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
1469 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1471 return routelen+2;
1472 }
1473
1474 if (!exit_ei)
1475 return routelen;
1476
1477 switch (purpose) {
1478 /* These purposes connect to a router that we chose, so DEFAULT_ROUTE_LEN
1479 * is safe: */
1482 /* router reachability testing */
1483 known_purpose = 1;
1484 break;
1485
1486 /* These purposes connect to a router that someone else
1487 * might have chosen, so add an extra hop to protect anonymity. */
1491 /* connecting to hidden service directory */
1493 /* client connecting to introduction point */
1495 /* hidden service connecting to rendezvous point */
1497 /* hidden service connecting to intro point. In this case we want an extra
1498 hop to avoid linkability attacks by the introduction point. */
1499 known_purpose = 1;
1500 routelen++;
1501 break;
1502
1503 default:
1504 /* Got a purpose not listed above along with a chosen exit.
1505 * Increase the circuit length by one anyway for safety. */
1506 routelen++;
1507 break;
1508 }
1509
1510 if (BUG(exit_ei && !known_purpose)) {
1511 log_warn(LD_BUG, "Unhandled purpose %d with a chosen exit; "
1512 "assuming routelen %d.", purpose, routelen);
1513 }
1514 return routelen;
1515}
1516
1517/** Choose a length for a circuit of purpose <b>purpose</b> and check
1518 * if enough routers are available.
1519 *
1520 * If the routerlist <b>nodes</b> doesn't have enough routers
1521 * to handle the desired path length, return -1.
1522 */
1523STATIC int
1524new_route_len(uint8_t purpose, extend_info_t *exit_ei,
1525 const smartlist_t *nodes)
1526{
1527 int routelen;
1528
1529 tor_assert(nodes);
1530
1531 routelen = route_len_for_purpose(purpose, exit_ei);
1532
1533 int num_acceptable_direct = count_acceptable_nodes(nodes, 1);
1534 int num_acceptable_indirect = count_acceptable_nodes(nodes, 0);
1535
1536 log_debug(LD_CIRC,"Chosen route length %d (%d direct and %d indirect "
1537 "routers suitable).", routelen, num_acceptable_direct,
1538 num_acceptable_indirect);
1539
1540 if (num_acceptable_direct < 1 || num_acceptable_indirect < routelen - 1) {
1541 log_info(LD_CIRC,
1542 "Not enough acceptable routers (%d/%d direct and %d/%d "
1543 "indirect routers suitable). Discarding this circuit.",
1544 num_acceptable_direct, routelen,
1545 num_acceptable_indirect, routelen);
1546 return -1;
1547 }
1548
1549 return routelen;
1550}
1551
1552/** Return a newly allocated list of uint16_t * for each predicted port not
1553 * handled by a current circuit. */
1554static smartlist_t *
1556{
1559 return dest;
1560}
1561
1562/** Return 1 if we already have circuits present or on the way for
1563 * all anticipated ports. Return 0 if we should make more.
1564 *
1565 * If we're returning 0, set need_uptime and need_capacity to
1566 * indicate any requirements that the unhandled ports have.
1567 */
1568MOCK_IMPL(int,
1569circuit_all_predicted_ports_handled, (time_t now, int *need_uptime,
1570 int *need_capacity))
1571{
1572 int i, enough;
1573 uint16_t *port;
1575 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1576 tor_assert(need_uptime);
1577 tor_assert(need_capacity);
1578 // Always predict need_capacity
1579 *need_capacity = 1;
1580 enough = (smartlist_len(sl) == 0);
1581 for (i = 0; i < smartlist_len(sl); ++i) {
1582 port = smartlist_get(sl, i);
1583 if (smartlist_contains_int_as_string(LongLivedServices, *port))
1584 *need_uptime = 1;
1585 tor_free(port);
1586 }
1587 smartlist_free(sl);
1588 return enough;
1589}
1590
1591/** Return 1 if <b>node</b> can handle one or more of the ports in
1592 * <b>needed_ports</b>, else return 0.
1593 */
1594static int
1595node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
1596{ /* XXXX MOVE */
1597 int i;
1598 uint16_t port;
1599
1600 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1602 /* alignment issues aren't a worry for this dereference, since
1603 needed_ports is explicitly a smartlist of uint16_t's */
1604 port = *(uint16_t *)smartlist_get(needed_ports, i);
1605 tor_assert(port);
1606 if (node)
1607 r = compare_tor_addr_to_node_policy(NULL, port, node);
1608 else
1609 continue;
1611 return 1;
1612 }
1613 return 0;
1614}
1615
1616/** Return true iff <b>conn</b> needs another general circuit to be
1617 * built. */
1618static int
1620{
1621 entry_connection_t *entry;
1622 if (conn->type != CONN_TYPE_AP)
1623 return 0;
1624 entry = TO_ENTRY_CONN(conn);
1625
1626 if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1627 !conn->marked_for_close &&
1628 !(entry->want_onehop) && /* ignore one-hop streams */
1629 !(entry->use_begindir) && /* ignore targeted dir fetches */
1630 !(entry->chosen_exit_name) && /* ignore defined streams */
1634 return 1;
1635 return 0;
1636}
1637
1638/** Return a pointer to a suitable router to be the exit node for the
1639 * general-purpose circuit we're about to build.
1640 *
1641 * Look through the connection array, and choose a router that maximizes
1642 * the number of pending streams that can exit from this router.
1643 *
1644 * Return NULL if we can't find any suitable routers.
1645 */
1646static const node_t *
1648{
1649 int *n_supported;
1650 int n_pending_connections = 0;
1651 smartlist_t *connections;
1652 int best_support = -1;
1653 int n_best_support=0;
1654 const or_options_t *options = get_options();
1655 const smartlist_t *the_nodes;
1656 const node_t *selected_node=NULL;
1657 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
1658 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
1659
1660 /* We should not require guard flags on exits. */
1661 IF_BUG_ONCE(flags & CRN_NEED_GUARD)
1662 return NULL;
1663
1664 /* We reject single-hop exits for all node positions. */
1665 IF_BUG_ONCE(flags & CRN_DIRECT_CONN)
1666 return NULL;
1667
1668 /* We only want exits to extend if we cannibalize the circuit.
1669 * But we don't require IPv6 extends yet. */
1670 IF_BUG_ONCE(flags & CRN_INITIATE_IPV6_EXTEND)
1671 return NULL;
1672
1673 connections = get_connection_array();
1674
1675 /* Count how many connections are waiting for a circuit to be built.
1676 * We use this for log messages now, but in the future we may depend on it.
1677 */
1678 SMARTLIST_FOREACH(connections, connection_t *, conn,
1679 {
1681 ++n_pending_connections;
1682 });
1683// log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1684// n_pending_connections);
1685 /* Now we count, for each of the routers in the directory, how many
1686 * of the pending connections could possibly exit from that
1687 * router (n_supported[i]). (We can't be sure about cases where we
1688 * don't know the IP address of the pending connection.)
1689 *
1690 * -1 means "Don't use this router at all."
1691 */
1692 the_nodes = nodelist_get_list();
1693 n_supported = tor_calloc(smartlist_len(the_nodes), sizeof(int));
1694 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1695 const int i = node_sl_idx;
1696 if (router_digest_is_me(node->identity)) {
1697 n_supported[i] = -1;
1698// log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1699 /* XXX there's probably a reverse predecessor attack here, but
1700 * it's slow. should we take this out? -RD
1701 */
1702 continue;
1703 }
1704 if (!router_can_choose_node(node, flags)) {
1705 n_supported[i] = -1;
1706 continue;
1707 }
1708 if (node->is_bad_exit) {
1709 n_supported[i] = -1;
1710 continue; /* skip routers that are known to be down or bad exits */
1711 }
1712 if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
1713 n_supported[i] = -1;
1714 continue; /* user asked us not to use it, no matter what */
1715 }
1716 if (options->ExitNodes &&
1717 !routerset_contains_node(options->ExitNodes, node)) {
1718 n_supported[i] = -1;
1719 continue; /* not one of our chosen exit nodes */
1720 }
1721 if (node_exit_policy_rejects_all(node)) {
1722 n_supported[i] = -1;
1723// log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1724// router->nickname, i);
1725 continue; /* skip routers that reject all */
1726 }
1727 n_supported[i] = 0;
1728 /* iterate over connections */
1729 SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
1731 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1732 if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
1733 ++n_supported[i];
1734// log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1735// router->nickname, i, n_supported[i]);
1736 } else {
1737// log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1738// router->nickname, i);
1739 }
1740 } SMARTLIST_FOREACH_END(conn);
1741 if (n_pending_connections > 0 && n_supported[i] == 0) {
1742 /* Leave best_support at -1 if that's where it is, so we can
1743 * distinguish it later. */
1744 continue;
1745 }
1746 if (n_supported[i] > best_support) {
1747 /* If this router is better than previous ones, remember its index
1748 * and goodness, and start counting how many routers are this good. */
1749 best_support = n_supported[i]; n_best_support=1;
1750// log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1751// router->nickname);
1752 } else if (n_supported[i] == best_support) {
1753 /* If this router is _as good_ as the best one, just increment the
1754 * count of equally good routers.*/
1755 ++n_best_support;
1756 }
1757 } SMARTLIST_FOREACH_END(node);
1758 log_info(LD_CIRC,
1759 "Found %d servers that might support %d/%d pending connections.",
1760 n_best_support, best_support >= 0 ? best_support : 0,
1761 n_pending_connections);
1762
1763 /* If any routers definitely support any pending connections, choose one
1764 * at random. */
1765 if (best_support > 0) {
1766 smartlist_t *supporting = smartlist_new();
1767
1768 SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
1769 if (n_supported[node_sl_idx] == best_support)
1770 smartlist_add(supporting, (void*)node);
1771 });
1772
1773 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1774 smartlist_free(supporting);
1775 } else {
1776 /* Either there are no pending connections, or no routers even seem to
1777 * possibly support any of them. Choose a router at random that satisfies
1778 * at least one predicted exit port. */
1779
1780 int attempt;
1781 smartlist_t *needed_ports, *supporting;
1782
1783 if (best_support == -1) {
1784 if (need_uptime || need_capacity) {
1785 log_info(LD_CIRC,
1786 "We couldn't find any live%s%s routers; falling back "
1787 "to list of all routers.",
1788 need_capacity?", fast":"",
1789 need_uptime?", stable":"");
1790 tor_free(n_supported);
1791 flags &= ~(CRN_NEED_UPTIME|CRN_NEED_CAPACITY);
1792 return choose_good_exit_server_general(flags);
1793 }
1794 log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
1795 "choosing a doomed exit at random.",
1796 options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
1797 }
1798 supporting = smartlist_new();
1799 needed_ports = circuit_get_unhandled_ports(time(NULL));
1800 for (attempt = 0; attempt < 2; attempt++) {
1801 /* try once to pick only from routers that satisfy a needed port,
1802 * then if there are none, pick from any that support exiting. */
1803 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1804 if (n_supported[node_sl_idx] != -1 &&
1805 (attempt || node_handles_some_port(node, needed_ports))) {
1806// log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1807// try, router->nickname);
1808 smartlist_add(supporting, (void*)node);
1809 }
1810 } SMARTLIST_FOREACH_END(node);
1811
1812 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1813 if (selected_node)
1814 break;
1815 smartlist_clear(supporting);
1816 /* If we reach this point, we can't actually support any unhandled
1817 * predicted ports, so clear all the remaining ones. */
1818 if (smartlist_len(needed_ports))
1819 rep_hist_remove_predicted_ports(needed_ports);
1820 }
1821 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1822 smartlist_free(needed_ports);
1823 smartlist_free(supporting);
1824 }
1825
1826 tor_free(n_supported);
1827 if (selected_node) {
1828 log_info(LD_CIRC, "Chose exit server '%s'", node_describe(selected_node));
1829 return selected_node;
1830 }
1831 if (options->ExitNodes) {
1832 log_warn(LD_CIRC,
1833 "No exits in ExitNodes%s seem to be running: "
1834 "can't choose an exit.",
1835 options->ExcludeExitNodesUnion_ ?
1836 ", except possibly those excluded by your configuration, " : "");
1837 }
1838 return NULL;
1839}
1840
1841/*
1842 * Helper function to pick a configured restricted middle node
1843 * (either HSLayer2Nodes or HSLayer3Nodes).
1844 *
1845 * Make sure that the node we chose is alive, and not excluded,
1846 * and return it.
1847 *
1848 * The exclude_set is a routerset of nodes that the selected node
1849 * must not match, and the exclude_list is a simple list of nodes
1850 * that the selected node must not be in. Either or both may be
1851 * NULL.
1852 *
1853 * Return NULL if no usable nodes could be found. */
1854static const node_t *
1856 const routerset_t *pick_from,
1857 const routerset_t *exclude_set,
1858 const smartlist_t *exclude_list,
1859 int position_hint)
1860{
1861 const node_t *middle_node = NULL;
1862
1863 smartlist_t *allowlisted_live_middles = smartlist_new();
1864 smartlist_t *all_live_nodes = smartlist_new();
1865
1866 tor_assert(pick_from);
1867
1868 /* Add all running nodes to all_live_nodes */
1869 router_add_running_nodes_to_smartlist(all_live_nodes, flags);
1870
1871 /* Filter all_live_nodes to only add live *and* allowlisted middles
1872 * to the list allowlisted_live_middles. */
1873 SMARTLIST_FOREACH_BEGIN(all_live_nodes, node_t *, live_node) {
1874 if (routerset_contains_node(pick_from, live_node)) {
1875 smartlist_add(allowlisted_live_middles, live_node);
1876 }
1877 } SMARTLIST_FOREACH_END(live_node);
1878
1879 /* Honor ExcludeNodes */
1880 if (exclude_set) {
1881 routerset_subtract_nodes(allowlisted_live_middles, exclude_set);
1882 }
1883
1884 if (exclude_list) {
1885 smartlist_subtract(allowlisted_live_middles, exclude_list);
1886 }
1887
1888 /**
1889 * Max number of restricted nodes before we alert the user and try
1890 * to load balance for them.
1891 *
1892 * The most aggressive vanguard design had 16 nodes at layer3.
1893 * Let's give a small ceiling above that. */
1894#define MAX_SANE_RESTRICTED_NODES 20
1895 /* If the user (or associated tor controller) selected only a few nodes,
1896 * assume they took load balancing into account and don't do it for them.
1897 *
1898 * If there are a lot of nodes in here, assume they did not load balance
1899 * and do it for them, but also warn them that they may be Doing It Wrong.
1900 */
1901 if (smartlist_len(allowlisted_live_middles) <=
1902 MAX_SANE_RESTRICTED_NODES) {
1903 middle_node = smartlist_choose(allowlisted_live_middles);
1904 } else {
1905 static ratelim_t pinned_notice_limit = RATELIM_INIT(24*3600);
1906 log_fn_ratelim(&pinned_notice_limit, LOG_NOTICE, LD_CIRC,
1907 "Your _HSLayer%dNodes setting has resulted "
1908 "in %d total nodes. This is a lot of nodes. "
1909 "You may want to consider using a Tor controller "
1910 "to select and update a smaller set of nodes instead.",
1911 position_hint, smartlist_len(allowlisted_live_middles));
1912
1913 /* NO_WEIGHTING here just means don't take node flags into account
1914 * (ie: use consensus measurement only). This is done so that
1915 * we don't further surprise the user by not using Exits that they
1916 * specified at all */
1917 middle_node = node_sl_choose_by_bandwidth(allowlisted_live_middles,
1918 NO_WEIGHTING);
1919 }
1920
1921 smartlist_free(allowlisted_live_middles);
1922 smartlist_free(all_live_nodes);
1923
1924 return middle_node;
1925}
1926
1927/** Return a pointer to a suitable router to be the exit node for the
1928 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1929 * if no router is suitable).
1930 *
1931 * For general-purpose circuits, pass it off to
1932 * choose_good_exit_server_general()
1933 *
1934 * For client-side rendezvous circuits, choose a random node, weighted
1935 * toward the preferences in 'options'.
1936 */
1937static const node_t *
1939 router_crn_flags_t flags, int is_internal)
1940{
1941 const or_options_t *options = get_options();
1942 flags |= CRN_NEED_DESC;
1943
1944 switch (TO_CIRCUIT(circ)->purpose) {
1949 /* For these three, we want to pick the exit like a middle hop,
1950 * since it should be random. */
1951 tor_assert_nonfatal(is_internal);
1952 /* We want to avoid picking certain nodes for HS purposes. */
1953 flags |= CRN_FOR_HS;
1954 FALLTHROUGH;
1957 if (is_internal) /* pick it like a middle hop */
1958 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
1959 else
1960 return choose_good_exit_server_general(flags);
1961 }
1962 log_warn(LD_BUG,"Unhandled purpose %d", TO_CIRCUIT(circ)->purpose);
1964 return NULL;
1965}
1966
1967/** Log a warning if the user specified an exit for the circuit that
1968 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1969static void
1971 const extend_info_t *exit_ei)
1972{
1973 const or_options_t *options = get_options();
1974 routerset_t *rs = options->ExcludeNodes;
1975 const char *description;
1976 uint8_t purpose = circ->base_.purpose;
1977
1978 if (circ->build_state->onehop_tunnel)
1979 return;
1980
1981 switch (purpose)
1982 {
1983 default:
1984 case CIRCUIT_PURPOSE_OR:
1988 log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
1989 (int)purpose,
1990 circuit_purpose_to_string(purpose));
1991 return;
1996 case CIRCUIT_PURPOSE_CONFLUX_LINKED:
1997 if (circ->build_state->is_internal)
1998 return;
1999 description = "requested exit node";
2000 rs = options->ExcludeExitNodesUnion_;
2001 break;
2009 return;
2014 description = "chosen rendezvous point";
2015 break;
2017 rs = options->ExcludeExitNodesUnion_;
2018 description = "controller-selected circuit target";
2019 break;
2020 }
2021
2022 if (routerset_contains_extendinfo(rs, exit_ei)) {
2023 /* We should never get here if StrictNodes is set to 1. */
2024 if (options->StrictNodes) {
2025 log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
2026 "even though StrictNodes is set. Please report. "
2027 "(Circuit purpose: %s)",
2028 description, extend_info_describe(exit_ei),
2029 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
2030 circuit_purpose_to_string(purpose));
2031 } else {
2032 log_warn(LD_CIRC, "Using %s '%s' which is listed in "
2033 "ExcludeNodes%s, because no better options were available. To "
2034 "prevent this (and possibly break your Tor functionality), "
2035 "set the StrictNodes configuration option. "
2036 "(Circuit purpose: %s)",
2037 description, extend_info_describe(exit_ei),
2038 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
2039 circuit_purpose_to_string(purpose));
2040 }
2042 }
2043
2044 return;
2045}
2046
2047/* Return a set of generic CRN_* flags based on <b>state</b>.
2048 *
2049 * Called for every position in the circuit. */
2050STATIC int
2051cpath_build_state_to_crn_flags(const cpath_build_state_t *state)
2052{
2053 router_crn_flags_t flags = 0;
2054 /* These flags apply to entry, middle, and exit nodes.
2055 * If a flag only applies to a specific position, it should be checked in
2056 * that function. */
2057 if (state->need_uptime)
2058 flags |= CRN_NEED_UPTIME;
2059 if (state->need_capacity)
2060 flags |= CRN_NEED_CAPACITY;
2061 return flags;
2062}
2063
2064/* Return the CRN_INITIATE_IPV6_EXTEND flag, based on <b>state</b> and
2065 * <b>cur_len</b>.
2066 *
2067 * Only called for middle nodes (for now). Must not be called on single-hop
2068 * circuits. */
2069STATIC int
2070cpath_build_state_to_crn_ipv6_extend_flag(const cpath_build_state_t *state,
2071 int cur_len)
2072{
2073 IF_BUG_ONCE(state->desired_path_len < 2)
2074 return 0;
2075
2076 /* The last node is the relay doing the self-test. So we want to extend over
2077 * IPv6 from the second-last node. */
2078 if (state->is_ipv6_selftest && cur_len == state->desired_path_len - 2)
2079 return CRN_INITIATE_IPV6_EXTEND;
2080 else
2081 return 0;
2082}
2083
2084/** Decide a suitable length for circ's cpath, and pick an exit
2085 * router (or use <b>exit_ei</b> if provided). Store these in the
2086 * cpath.
2087 *
2088 * If <b>is_hs_v3_rp_circuit</b> is set, then this exit should be suitable to
2089 * be used as an HS v3 rendezvous point.
2090 *
2091 * Return 0 if ok, -1 if circuit should be closed. */
2092STATIC int
2094{
2095 cpath_build_state_t *state = circ->build_state;
2096
2097 if (state->onehop_tunnel) {
2098 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel%s.",
2099 (hs_service_allow_non_anonymous_connection(get_options()) ?
2100 ", or intro or rendezvous connection" : ""));
2101 state->desired_path_len = 1;
2102 } else {
2103 int r = new_route_len(circ->base_.purpose, exit_ei, nodelist_get_list());
2104 if (r < 1) /* must be at least 1 */
2105 return -1;
2106 state->desired_path_len = r;
2107 }
2108
2109 if (exit_ei) { /* the circuit-builder pre-requested one */
2110 warn_if_last_router_excluded(circ, exit_ei);
2111 log_info(LD_CIRC,"Using requested exit node '%s'",
2112 extend_info_describe(exit_ei));
2113 exit_ei = extend_info_dup(exit_ei);
2114 } else { /* we have to decide one */
2115 router_crn_flags_t flags = CRN_NEED_DESC;
2116 flags |= cpath_build_state_to_crn_flags(state);
2117 /* Some internal exits are one hop, for example directory connections.
2118 * (Guards are always direct, middles are never direct.) */
2119 if (state->onehop_tunnel)
2120 flags |= CRN_DIRECT_CONN;
2121 if (state->need_conflux)
2122 flags |= CRN_CONFLUX;
2123 const node_t *node =
2124 choose_good_exit_server(circ, flags, state->is_internal);
2125 if (!node) {
2126 log_warn(LD_CIRC,"Failed to choose an exit server");
2127 return -1;
2128 }
2129 exit_ei = extend_info_from_node(node, state->onehop_tunnel,
2130 /* for_exit_use */
2131 !state->is_internal && (
2132 TO_CIRCUIT(circ)->purpose ==
2134 TO_CIRCUIT(circ)->purpose ==
2136 if (BUG(exit_ei == NULL))
2137 return -1;
2138 }
2139 state->chosen_exit = exit_ei;
2140 return 0;
2141}
2142
2143/** Give <b>circ</b> a new exit destination to <b>exit_ei</b>, and add a
2144 * hop to the cpath reflecting this. Don't send the next extend cell --
2145 * the caller will do this if it wants to.
2146 */
2147int
2149{
2150 cpath_build_state_t *state;
2151 tor_assert(exit_ei);
2152 tor_assert(circ);
2153
2154 state = circ->build_state;
2155 tor_assert(state);
2156 extend_info_free(state->chosen_exit);
2157 state->chosen_exit = extend_info_dup(exit_ei);
2158
2160 cpath_append_hop(&circ->cpath, exit_ei);
2161 return 0;
2162}
2163
2164/** Take an open <b>circ</b>, and add a new hop at the end, based on
2165 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
2166 * send the next extend cell to begin connecting to that hop.
2167 */
2168int
2170{
2171 int err_reason = 0;
2172 warn_if_last_router_excluded(circ, exit_ei);
2173
2174 tor_gettimeofday(&circ->base_.timestamp_began);
2175
2176 circuit_append_new_exit(circ, exit_ei);
2178 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
2179 log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
2180 extend_info_describe(exit_ei));
2181 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2182 return -1;
2183 }
2184
2185 return 0;
2186}
2187
2188/** Return the number of routers in <b>nodes</b> that are currently up and
2189 * available for building circuits through.
2190 *
2191 * If <b>direct</b> is true, only count nodes that are suitable for direct
2192 * connections. Counts nodes regardless of whether their addresses are
2193 * preferred.
2194 */
2195MOCK_IMPL(STATIC int,
2196count_acceptable_nodes, (const smartlist_t *nodes, int direct))
2197{
2198 int num=0;
2199 int flags = CRN_NEED_DESC;
2200
2201 if (direct)
2202 flags |= CRN_DIRECT_CONN;
2203
2204 SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
2205 // log_debug(LD_CIRC,
2206 // "Contemplating whether router %d (%s) is a new option.",
2207 // i, r->nickname);
2208 if (!router_can_choose_node(node, flags))
2209 continue;
2210 ++num;
2211 } SMARTLIST_FOREACH_END(node);
2212
2213// log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
2214
2215 return num;
2216}
2217
2218/**
2219 * Build the exclude list for vanguard circuits.
2220 *
2221 * For vanguard circuits we exclude all the already chosen nodes (including the
2222 * exit) from being middle hops to prevent the creation of A - B - A subpaths.
2223 * We also allow the 4th hop to be the same as the guard node so as to not leak
2224 * guard information to RP/IP/HSDirs.
2225 *
2226 * For vanguard circuits, we don't apply any subnet or family restrictions.
2227 * This is to avoid impossible-to-build circuit paths, or just situations where
2228 * our earlier guards prevent us from using most of our later ones.
2229 *
2230 * The alternative is building the circuit in reverse. Reverse calls to
2231 * onion_extend_cpath() (ie: select outer hops first) would then have the
2232 * property that you don't gain information about inner hops by observing
2233 * outer ones. See https://bugs.torproject.org/tpo/core/tor/24487
2234 * for this.
2235 *
2236 * (Note further that we still exclude the exit to prevent A - B - A
2237 * at the end of the path. */
2238static smartlist_t *
2240 cpath_build_state_t *state,
2241 crypt_path_t *head,
2242 int cur_len)
2243{
2244 smartlist_t *excluded;
2245 const node_t *r;
2246 crypt_path_t *cpath;
2247 int i;
2248
2249 (void) purpose;
2250
2251 excluded = smartlist_new();
2252
2253 /* Add the exit to the exclude list (note that the exit/last hop is always
2254 * chosen first in circuit_establish_circuit()). */
2255 if ((r = build_state_get_exit_node(state))) {
2256 smartlist_add(excluded, (node_t*)r);
2257 }
2258
2259 /* If we are picking the 4th hop, allow that node to be the guard too.
2260 * This prevents us from avoiding the Guard for those hops, which
2261 * gives the adversary information about our guard if they control
2262 * the RP, IP, or HSDIR. We don't do this check based on purpose
2263 * because we also want to allow HS_VANGUARDS pre-build circuits
2264 * to use the guard for that last hop.
2265 */
2266 if (cur_len == DEFAULT_ROUTE_LEN+1) {
2267 /* Skip the first hop for the exclude list below */
2268 head = head->next;
2269 cur_len--;
2270 }
2271
2272 for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2273 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2274 smartlist_add(excluded, (node_t*)r);
2275 }
2276 }
2277
2278 return excluded;
2279}
2280
2281/**
2282 * Build a list of nodes to exclude from the choice of this middle
2283 * hop, based on already chosen nodes.
2284 */
2285static smartlist_t *
2287 uint8_t purpose,
2288 cpath_build_state_t *state,
2289 crypt_path_t *head,
2290 int cur_len)
2291{
2292 smartlist_t *excluded;
2293 const node_t *r;
2294 crypt_path_t *cpath;
2295 int i;
2296
2297 /** Vanguard circuits have their own path selection rules */
2298 if (circuit_should_use_vanguards(purpose)) {
2299 return build_vanguard_middle_exclude_list(purpose, state, head, cur_len);
2300 }
2301
2302 excluded = smartlist_new();
2303
2304 // Exclude other middles on pending and built conflux circs
2306
2307 /* For non-vanguard circuits, add the exit and its family to the exclude list
2308 * (note that the exit/last hop is always chosen first in
2309 * circuit_establish_circuit()). */
2310 if ((r = build_state_get_exit_node(state))) {
2311 nodelist_add_node_and_family(excluded, r);
2312 }
2313
2314 /* also exclude all other already chosen nodes and their family */
2315 for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2316 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2317 nodelist_add_node_and_family(excluded, r);
2318 }
2319 }
2320
2321 return excluded;
2322}
2323
2324/** Return true if we MUST use vanguards for picking this middle node. */
2325static int
2327 uint8_t purpose, int cur_len)
2328{
2329 /* If this is not a hidden service circuit, don't use vanguards */
2330 if (!circuit_purpose_is_hidden_service(purpose)) {
2331 return 0;
2332 }
2333
2334 /* Don't even bother if the feature is disabled */
2336 return 0;
2337 }
2338
2339 /* If we are a hidden service circuit, always use either vanguards-lite
2340 * or HSLayer2Nodes for 2nd hop. */
2341 if (cur_len == 1) {
2342 return 1;
2343 }
2344
2345 /* If we have sticky L3 nodes, and this is an L3 pick, use vanguards */
2346 if (options->HSLayer3Nodes && cur_len == 2) {
2347 return 1;
2348 }
2349
2350 return 0;
2351}
2352
2353/** Pick a sticky vanguard middle node or return NULL if not found.
2354 * See doc of pick_restricted_middle_node() for argument details. */
2355static const node_t *
2357 router_crn_flags_t flags, int cur_len,
2358 const smartlist_t *excluded)
2359{
2360 const routerset_t *vanguard_routerset = NULL;
2361 const node_t *node = NULL;
2362
2363 /* Pick the right routerset based on the current hop */
2364 if (cur_len == 1) {
2365 vanguard_routerset = options->HSLayer2Nodes ?
2366 options->HSLayer2Nodes : get_layer2_guards();
2367 } else if (cur_len == 2) {
2368 vanguard_routerset = options->HSLayer3Nodes;
2369 } else {
2370 /* guaranteed by middle_node_should_be_vanguard() */
2372 return NULL;
2373 }
2374
2375 if (BUG(!vanguard_routerset)) {
2376 return NULL;
2377 }
2378
2379 node = pick_restricted_middle_node(flags, vanguard_routerset,
2380 options->ExcludeNodes, excluded,
2381 cur_len+1);
2382
2383 if (!node) {
2384 static ratelim_t pinned_warning_limit = RATELIM_INIT(300);
2385 log_fn_ratelim(&pinned_warning_limit, LOG_WARN, LD_CIRC,
2386 "Could not find a node that matches the configured "
2387 "_HSLayer%dNodes set", cur_len+1);
2388 }
2389
2390 return node;
2391}
2392
2393/** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
2394 * and <b>state</b> and the cpath <b>head</b> (currently populated only
2395 * to length <b>cur_len</b> to decide a suitable middle hop for a
2396 * circuit. In particular, make sure we don't pick the exit node or its
2397 * family, and make sure we don't duplicate any previous nodes or their
2398 * families. */
2399static const node_t *
2401 uint8_t purpose,
2402 cpath_build_state_t *state,
2403 crypt_path_t *head,
2404 int cur_len)
2405{
2406 const node_t *choice;
2407 smartlist_t *excluded;
2408 const or_options_t *options = get_options();
2409 router_crn_flags_t flags = CRN_NEED_DESC;
2410 tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
2411 purpose <= CIRCUIT_PURPOSE_MAX_);
2412
2413 log_debug(LD_CIRC, "Contemplating intermediate hop #%d: random choice.",
2414 cur_len+1);
2415
2416 excluded = build_middle_exclude_list(circ, purpose, state, head, cur_len);
2417
2418 flags |= cpath_build_state_to_crn_flags(state);
2419 flags |= cpath_build_state_to_crn_ipv6_extend_flag(state, cur_len);
2420
2421 /** If a hidden service circuit wants a specific middle node, pin it. */
2422 if (middle_node_must_be_vanguard(options, purpose, cur_len)) {
2423 log_debug(LD_GENERAL, "Picking a sticky node (cur_len = %d)", cur_len);
2424 choice = pick_vanguard_middle_node(options, flags, cur_len, excluded);
2425 smartlist_free(excluded);
2426 return choice;
2427 }
2428
2429 if (options->MiddleNodes) {
2430 smartlist_t *sl = smartlist_new();
2432 options->ExcludeNodes, 1);
2433
2434 smartlist_subtract(sl, excluded);
2435
2436 choice = node_sl_choose_by_bandwidth(sl, WEIGHT_FOR_MID);
2437 smartlist_free(sl);
2438 if (choice) {
2439 log_fn(LOG_INFO, LD_CIRC, "Chose fixed middle node: %s",
2440 hex_str(choice->identity, DIGEST_LEN));
2441 } else {
2442 log_fn(LOG_NOTICE, LD_CIRC, "Restricted middle not available");
2443 }
2444 } else {
2445 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2446 }
2447 smartlist_free(excluded);
2448 return choice;
2449}
2450
2451/** Pick a good entry server for the circuit to be built according to
2452 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
2453 * router (if we're an OR), and respect firewall settings; if we're
2454 * configured to use entry guards, return one.
2455 *
2456 * Set *<b>guard_state_out</b> to information about the guard that
2457 * we're selecting, which we'll use later to remember whether the
2458 * guard worked or not.
2459 */
2460const node_t *
2462 uint8_t purpose, cpath_build_state_t *state,
2463 circuit_guard_state_t **guard_state_out)
2464{
2465 const node_t *choice;
2466 smartlist_t *excluded;
2467 const or_options_t *options = get_options();
2468 /* If possible, choose an entry server with a preferred address,
2469 * otherwise, choose one with an allowed address */
2470 router_crn_flags_t flags = (CRN_NEED_GUARD|CRN_NEED_DESC|CRN_PREF_ADDR|
2471 CRN_DIRECT_CONN);
2472 const node_t *node;
2473
2474 /* Once we used this function to select a node to be a guard. We had
2475 * 'state == NULL' be the signal for that. But we don't do that any more.
2476 */
2477 tor_assert_nonfatal(state);
2478
2479 if (state && options->UseEntryGuards &&
2480 (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
2481 /* This request is for an entry server to use for a regular circuit,
2482 * and we use entry guard nodes. Just return one of the guard nodes. */
2483 tor_assert(guard_state_out);
2484 return guards_choose_guard(circ, state, purpose, guard_state_out);
2485 }
2486
2487 excluded = smartlist_new();
2488
2489 if (state && (node = build_state_get_exit_node(state))) {
2490 /* Exclude the exit node from the state, if we have one. Also exclude its
2491 * family. */
2492 nodelist_add_node_and_family(excluded, node);
2493 }
2494
2495 if (state) {
2496 flags |= cpath_build_state_to_crn_flags(state);
2497 }
2498
2499 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2500 smartlist_free(excluded);
2501 return choice;
2502}
2503
2504/** Choose a suitable next hop for the circuit <b>circ</b>.
2505 * Append the hop info to circ->cpath.
2506 *
2507 * Return 1 if the path is complete, 0 if we successfully added a hop,
2508 * and -1 on error.
2509 */
2510STATIC int
2512{
2513 uint8_t purpose = circ->base_.purpose;
2514 cpath_build_state_t *state = circ->build_state;
2515 int cur_len = circuit_get_cpath_len(circ);
2516 extend_info_t *info = NULL;
2517
2518 if (cur_len >= state->desired_path_len) {
2519 log_debug(LD_CIRC, "Path is complete: %d steps long",
2520 state->desired_path_len);
2521 return 1;
2522 }
2523
2524 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
2525 state->desired_path_len);
2526
2527 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
2528 info = extend_info_dup(state->chosen_exit);
2529 } else if (cur_len == 0) { /* picking first node */
2530 const node_t *r = choose_good_entry_server(circ, purpose, state,
2531 &circ->guard_state);
2532 if (r) {
2533 /* If we're a client, use the preferred address rather than the
2534 primary address, for potentially connecting to an IPv6 OR
2535 port. Servers always want the primary (IPv4) address. */
2536 int client = (server_mode(get_options()) == 0);
2537 info = extend_info_from_node(r, client, false);
2538 /* Clients can fail to find an allowed address */
2539 tor_assert_nonfatal(info || client);
2540 }
2541 } else {
2542 const node_t *r =
2543 choose_good_middle_server(circ, purpose, state, circ->cpath, cur_len);
2544 if (r) {
2545 info = extend_info_from_node(r, 0, false);
2546 }
2547 }
2548
2549 if (!info) {
2550 /* This can happen on first startup, possibly due to insufficient relays
2551 * downloaded to pick vanguards-lite layer2 nodes, or other ephemeral
2552 * reasons. It only happens briefly, is hard to reproduce, and then goes
2553 * away for ever. :/ */
2555 log_info(LD_CIRC,
2556 "Failed to find node for hop #%d of our path. Discarding "
2557 "this circuit.", cur_len+1);
2558 } else {
2559 log_notice(LD_CIRC,
2560 "Failed to find node for hop #%d of our path. Discarding "
2561 "this circuit.", cur_len+1);
2562 }
2563 return -1;
2564 }
2565
2566 log_debug(LD_CIRC,"Chose router %s for hop #%d (exit is %s)",
2568 cur_len+1, build_state_get_exit_nickname(state));
2569
2570 cpath_append_hop(&circ->cpath, info);
2571 extend_info_free(info);
2572 return 0;
2573}
2574
2575/** Return the node_t for the chosen exit router in <b>state</b>.
2576 * If there is no chosen exit, or if we don't know the node_t for
2577 * the chosen exit, return NULL.
2578 */
2579MOCK_IMPL(const node_t *,
2581{
2582 if (!state || !state->chosen_exit)
2583 return NULL;
2585}
2586
2587/** Return the RSA ID digest for the chosen exit router in <b>state</b>.
2588 * If there is no chosen exit, return NULL.
2589 */
2590const uint8_t *
2592{
2593 if (!state || !state->chosen_exit)
2594 return NULL;
2595 return (const uint8_t *) state->chosen_exit->identity_digest;
2596}
2597
2598/** Return the nickname for the chosen exit router in <b>state</b>. If
2599 * there is no chosen exit, or if we don't know the routerinfo_t for the
2600 * chosen exit, return NULL.
2601 */
2602const char *
2604{
2605 if (!state || !state->chosen_exit)
2606 return NULL;
2607 return state->chosen_exit->nickname;
2608}
2609
2610/* Does circ have an onion key which it's allowed to use? */
2611int
2612circuit_has_usable_onion_key(const origin_circuit_t *circ)
2613{
2614 tor_assert(circ);
2615 tor_assert(circ->cpath);
2617 return extend_info_supports_ntor(circ->cpath->extend_info);
2618}
2619
2620/** Find the circuits that are waiting to find out whether their guards are
2621 * usable, and if any are ready to become usable, mark them open and try
2622 * attaching streams as appropriate. */
2623void
2625{
2626 smartlist_t *to_upgrade =
2628
2629 if (to_upgrade == NULL)
2630 return;
2631
2632 log_info(LD_GUARD, "Upgrading %d circuits from 'waiting for better guard' "
2633 "to 'open'.", smartlist_len(to_upgrade));
2634
2635 SMARTLIST_FOREACH_BEGIN(to_upgrade, origin_circuit_t *, circ) {
2637 circuit_has_opened(circ);
2638 } SMARTLIST_FOREACH_END(circ);
2639
2640 smartlist_free(to_upgrade);
2641}
2642
2643// TODO: Find a better place to declare this; it's duplicated in
2644// onion_crypto.c
2645#define EXT_TYPE_SUBPROTO 3
2646
2647/** Add a request for the CGO subprotocol capability to ext.
2648 *
2649 * NOTE: If we need to support other subprotocol extensions,
2650 * do not add separate functions! Instead rename this function
2651 * and adapt it as appropriate.
2652 */
2653static int
2654build_cgo_subproto_request(trn_extension_t *ext)
2655{
2656 trn_extension_field_t *fld = NULL;
2657 trn_subproto_request_t *req = NULL;
2658 trn_subproto_request_ext_t *req_ext = NULL;
2659 int r = 0;
2660
2661 fld = trn_extension_field_new();
2662 req_ext = trn_subproto_request_ext_new();
2663
2664 req = trn_subproto_request_new();
2665 req->protocol_id = PRT_RELAY;
2666 req->proto_cap_number = PROTOVER_RELAY_CRYPT_CGO;
2667 trn_subproto_request_ext_add_reqs(req_ext, req);
2668 req = NULL; // prevent double-free
2669
2670 // TODO: If we add other capabilities here, we need to make
2671 // sure they are correctly sorted.
2672
2673 ssize_t len = trn_subproto_request_ext_encoded_len(req_ext);
2674 if (BUG(len<0))
2675 goto err;
2676 if (BUG(len > UINT8_MAX))
2677 goto err;
2678
2679 trn_extension_field_setlen_field(fld, len);
2680 trn_extension_field_set_field_type(fld, EXT_TYPE_SUBPROTO);
2681 trn_extension_field_set_field_len(fld, len);
2682 uint8_t *out = trn_extension_field_getarray_field(fld);
2683 ssize_t len2 = trn_subproto_request_ext_encode(out, len, req_ext);
2684 if (BUG(len != len2))
2685 goto err;
2686
2687 trn_extension_add_fields(ext, fld);
2688 fld = NULL; // prevent double-free
2689
2690 // We succeeded!
2691 r = 0;
2692
2693 err:
2694 trn_subproto_request_ext_free(req_ext);
2695 trn_subproto_request_free(req);
2696 trn_extension_field_free(fld);
2697
2698 return r;
2699}
2700
2701/** Helper: Comparison function to sort extensions. */
2702static int
2703ext_cmp(const void *a, const void *b)
2704{
2705 const trn_extension_field_t *fa = *(trn_extension_field_t **)a;
2706 const trn_extension_field_t *fb = *(trn_extension_field_t **)b;
2707 uint8_t ta = trn_extension_field_get_field_type(fa);
2708 uint8_t tb = trn_extension_field_get_field_type(fb);
2709 if (ta < tb)
2710 return -1;
2711 else if (ta == tb)
2712 return 0;
2713 else
2714 return 1;
2715}
2716
2717/**
2718 * Try to generate a circuit-negotiation message for communication with a
2719 * given relay. Assumes we are using ntor v3, or some later version that
2720 * supports parameter negotiatoin.
2721 *
2722 * On success, return 0 and pass back a message in the `out` parameters.
2723 * Otherwise, return -1.
2724 **/
2725int
2727 uint8_t **msg_out,
2728 size_t *msg_len_out,
2729 circuit_params_t *params_out)
2730{
2731 tor_assert(ei && msg_out && msg_len_out && params_out);
2732 bool cc_enabled = false;
2733
2734 *msg_out = NULL;
2735
2736 trn_extension_t *ext = trn_extension_new();
2737
2741 goto err;
2742 }
2743 cc_enabled = true;
2744 }
2745
2746 if (cc_enabled && ei->enable_cgo) {
2747 if (build_cgo_subproto_request(ext) < 0) {
2748 goto err;
2749 }
2750 params_out->cell_fmt = RELAY_CELL_FORMAT_V1;
2752 }
2753
2754 size_t n_fields = trn_extension_getlen_fields(ext);
2755 qsort(trn_extension_getarray_fields(ext),
2756 n_fields, sizeof(trn_extension_field_t *),
2757 ext_cmp);
2758
2759 trn_extension_set_num(ext, n_fields);
2760
2761 ssize_t total_len = trn_extension_encoded_len(ext);
2762 if (BUG(total_len < 0))
2763 goto err;
2764
2765 *msg_out = tor_malloc_zero(total_len);
2766 *msg_len_out = total_len;
2767 if (BUG(trn_extension_encode(*msg_out, total_len, ext) < 0)) {
2768 goto err;
2769 }
2770 trn_extension_free(ext);
2771
2772 return 0;
2773 err:
2774 trn_extension_free(ext);
2775 tor_free(*msg_out);
2776 return -1;
2777}
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
time_t approx_time(void)
Definition: approx_time.c:32
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
int extend_info_is_a_configured_bridge(const extend_info_t *ei)
Definition: bridges.c:326
Header file for circuitbuild.c.
Fixed-size cell structure.
void channel_timestamp_client(channel_t *chan)
Definition: channel.c:3198
channel_t * channel_get_for_extend(const char *rsa_id_digest, const ed25519_public_key_t *ed_id, const tor_addr_t *target_ipv4_addr, const tor_addr_t *target_ipv6_addr, bool for_origin_circ, const char **msg_out, int *launch_out)
Definition: channel.c:2416
const char * channel_state_to_string(channel_state_t state)
Definition: channel.c:316
int channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
Definition: channel.c:3295
int channel_remote_identity_matches(const channel_t *chan, const char *rsa_id_digest, const ed25519_public_key_t *ed_id)
Definition: channel.c:668
channel_t * channel_connect(const tor_addr_t *addr, uint16_t port, const char *id_digest, const ed25519_public_key_t *ed_id)
Definition: channel.c:2326
const char * channel_describe_peer(channel_t *chan)
Definition: channel.c:2840
void channel_dump_statistics(channel_t *chan, int severity)
Definition: channel.c:2544
Header file for channel.c.
void channel_mark_as_used_for_origin_circuit(channel_t *chan)
Definition: channeltls.c:391
@ CIRC_ID_TYPE_NEITHER
Definition: channel.h:44
@ CIRC_ID_TYPE_HIGHER
Definition: channel.h:41
int pathbias_count_build_attempt(origin_circuit_t *circ)
Definition: circpathbias.c:446
void pathbias_count_build_success(origin_circuit_t *circ)
Definition: circpathbias.c:534
static int circuit_send_first_onion_skin(origin_circuit_t *circ)
Definition: circuitbuild.c:993
static void circuit_pick_extend_handshake(uint8_t *cell_type_out, uint8_t *create_cell_type_out, uint16_t *handshake_type_out, const extend_info_t *ei)
Definition: circuitbuild.c:904
static int circuit_build_no_more_hops(origin_circuit_t *circ)
int client_circ_negotiation_message(const extend_info_t *ei, uint8_t **msg_out, size_t *msg_len_out, circuit_params_t *params_out)
int circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
STATIC int count_acceptable_nodes(const smartlist_t *nodes, int direct)
const char * build_state_get_exit_nickname(cpath_build_state_t *state)
static int build_cgo_subproto_request(trn_extension_t *ext)
int circuit_handle_first_hop(origin_circuit_t *circ)
Definition: circuitbuild.c:577
static int middle_node_must_be_vanguard(const or_options_t *options, uint8_t purpose, int cur_len)
void circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
Definition: circuitbuild.c:358
static const node_t * pick_restricted_middle_node(router_crn_flags_t flags, const routerset_t *pick_from, const routerset_t *exclude_set, const smartlist_t *exclude_list, int position_hint)
STATIC circid_t get_unique_circ_id_by_chan(channel_t *chan)
Definition: circuitbuild.c:128
static smartlist_t * build_middle_exclude_list(const origin_circuit_t *circ, uint8_t purpose, cpath_build_state_t *state, crypt_path_t *head, int cur_len)
int route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
STATIC int onion_extend_cpath(origin_circuit_t *circ)
static void circuit_pick_create_handshake(uint8_t *cell_type_out, uint16_t *handshake_type_out, const extend_info_t *ei)
Definition: circuitbuild.c:876
char * circuit_list_path_for_controller(origin_circuit_t *circ)
Definition: circuitbuild.c:348
STATIC int new_route_len(uint8_t purpose, extend_info_t *exit_ei, const smartlist_t *nodes)
static const node_t * choose_good_middle_server(const origin_circuit_t *, uint8_t purpose, cpath_build_state_t *state, crypt_path_t *head, int cur_len)
circuit_guard_state_t * origin_circuit_get_guard_state(origin_circuit_t *circ)
Definition: circuitbuild.c:546
static int onion_populate_cpath(origin_circuit_t *circ)
Definition: circuitbuild.c:391
int circuit_deliver_create_cell(circuit_t *circ, const struct create_cell_t *create_cell, int relayed)
Definition: circuitbuild.c:774
static int circuit_may_omit_guard(const origin_circuit_t *circ)
Definition: circuitbuild.c:922
static int ap_stream_wants_exit_attention(connection_t *conn)
STATIC int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
const uint8_t * build_state_get_exit_rsa_id(cpath_build_state_t *state)
void circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
Definition: circuitbuild.c:672
static smartlist_t * build_vanguard_middle_exclude_list(uint8_t purpose, cpath_build_state_t *state, crypt_path_t *head, int cur_len)
static int circuit_cpath_supports_ntor(const origin_circuit_t *circ)
Definition: circuitbuild.c:367
int circuit_timeout_want_to_count_circ(const origin_circuit_t *circ)
Definition: circuitbuild.c:861
static smartlist_t * circuit_get_unhandled_ports(time_t now)
static const node_t * pick_vanguard_middle_node(const or_options_t *options, router_crn_flags_t flags, int cur_len, const smartlist_t *excluded)
static const node_t * choose_good_exit_server(origin_circuit_t *circ, router_crn_flags_t flags, int is_internal)
static void warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit_ei)
origin_circuit_t * circuit_establish_circuit_conflux(const uint8_t *conflux_nonce, uint8_t purpose, extend_info_t *exit_ei, int flags)
Definition: circuitbuild.c:515
channel_t * channel_connect_for_circuit(const extend_info_t *ei)
Definition: circuitbuild.c:105
char * circuit_list_path(origin_circuit_t *circ, int verbose)
Definition: circuitbuild.c:339
int circuit_all_predicted_ports_handled(time_t now, int *need_uptime, int *need_capacity)
void circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
int circuit_send_next_onion_skin(origin_circuit_t *circ)
Definition: circuitbuild.c:959
static int ext_cmp(const void *a, const void *b)
int circuit_finish_handshake(origin_circuit_t *circ, const created_cell_t *reply)
static const node_t * choose_good_exit_server_general(router_crn_flags_t flags)
int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
origin_circuit_t * circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
Definition: circuitbuild.c:479
int circuit_truncated(origin_circuit_t *circ, int reason)
const node_t * choose_good_entry_server(const origin_circuit_t *circ, uint8_t purpose, cpath_build_state_t *state, circuit_guard_state_t **guard_state_out)
static void circuit_chan_publish(const origin_circuit_t *circ, const channel_t *chan)
Definition: circuitbuild.c:561
static bool should_use_create_fast_for_circuit(origin_circuit_t *circ)
Definition: circuitbuild.c:839
static int circuit_send_intermediate_onion_skin(origin_circuit_t *circ, crypt_path_t *hop)
const node_t * build_state_get_exit_node(cpath_build_state_t *state)
static int node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
static char * circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
Definition: circuitbuild.c:265
void circuit_upgrade_circuits_from_guard_wait(void)
origin_circuit_t * origin_circuit_init(uint8_t purpose, int flags)
Definition: circuitbuild.c:448
Header file for circuitbuild.c.
int circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
Definition: circuitlist.c:1574
void circuit_set_n_circid_chan(circuit_t *circ, circid_t id, channel_t *chan)
Definition: circuitlist.c:493
void circuit_mark_all_dirty_circs_as_unusable(void)
Definition: circuitlist.c:2075
void circuit_set_state(circuit_t *circ, uint8_t state)
Definition: circuitlist.c:562
smartlist_t * circuit_find_circuits_to_upgrade_from_guard_wait(void)
Definition: circuitlist.c:1976
origin_circuit_t * origin_circuit_new(void)
Definition: circuitlist.c:1050
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:185
int circuit_get_cpath_len(origin_circuit_t *circ)
Definition: circuitlist.c:2004
int circuit_get_cpath_opened_len(const origin_circuit_t *circ)
Definition: circuitlist.c:2020
void circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
Definition: circuitlist.c:597
int circuit_event_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
Definition: circuitlist.c:518
time_t circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
Definition: circuitlist.c:1587
crypt_path_t * circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
Definition: circuitlist.c:2040
const char * circuit_purpose_to_string(uint8_t purpose)
Definition: circuitlist.c:929
void circuit_mark_all_unused_circs(void)
Definition: circuitlist.c:2056
Header file for circuitlist.c.
#define CIRCUIT_PURPOSE_S_CONNECT_REND
Definition: circuitlist.h:107
#define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
Definition: circuitlist.h:93
#define CIRCUIT_PURPOSE_REND_POINT_WAITING
Definition: circuitlist.h:45
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:32
#define CIRCUIT_STATE_BUILDING
Definition: circuitlist.h:21
#define CIRCUIT_PURPOSE_C_REND_JOINED
Definition: circuitlist.h:88
#define CIRCUIT_PURPOSE_INTRO_POINT
Definition: circuitlist.h:42
#define CIRCUIT_PURPOSE_CONTROLLER
Definition: circuitlist.h:121
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:154
#define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
Definition: circuitlist.h:86
#define CIRCUIT_STATE_GUARD_WAIT
Definition: circuitlist.h:30
#define CIRCUIT_PURPOSE_TESTING
Definition: circuitlist.h:118
#define CIRCUIT_PURPOSE_OR
Definition: circuitlist.h:39
#define CIRCUIT_STATE_CHAN_WAIT
Definition: circuitlist.h:26
#define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
Definition: circuitlist.h:76
#define CIRCUIT_PURPOSE_S_REND_JOINED
Definition: circuitlist.h:110
#define CIRCUIT_PURPOSE_C_REND_READY
Definition: circuitlist.h:83
#define CIRCUIT_PURPOSE_S_HSDIR_POST
Definition: circuitlist.h:112
#define CIRCUIT_PURPOSE_C_HSDIR_GET
Definition: circuitlist.h:90
#define CIRCUIT_PURPOSE_REND_ESTABLISHED
Definition: circuitlist.h:47
#define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
Definition: circuitlist.h:79
#define CIRCUIT_PURPOSE_C_INTRODUCING
Definition: circuitlist.h:73
#define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
Definition: circuitlist.h:101
#define CIRCUIT_PURPOSE_C_ESTABLISH_REND
Definition: circuitlist.h:81
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:70
#define CIRCUIT_PURPOSE_CONFLUX_UNLINKED
Definition: circuitlist.h:137
#define CIRCUIT_PURPOSE_HS_VANGUARDS
Definition: circuitlist.h:131
unsigned int circuitmux_num_active_circuits(circuitmux_t *cmux)
Definition: circuitmux.c:702
unsigned int circuitmux_num_circuits(circuitmux_t *cmux)
Definition: circuitmux.c:714
void circpad_machine_event_circ_added_hop(origin_circuit_t *on_circ)
void circpad_machine_event_circ_built(origin_circuit_t *circ)
Header file for circuitpadding.c.
void circuit_build_times_handle_completed_hop(origin_circuit_t *circ)
Definition: circuitstats.c:679
Header file for circuitstats.c.
int circuit_should_use_vanguards(uint8_t purpose)
Definition: circuituse.c:2018
void circuit_has_opened(origin_circuit_t *circ)
Definition: circuituse.c:1664
void circuit_reset_failure_count(int timeout)
Definition: circuituse.c:2223
int circuit_stream_is_being_handled(entry_connection_t *conn, uint16_t port, int min)
Definition: circuituse.c:1009
void circuit_remove_handled_ports(smartlist_t *needed_ports)
Definition: circuituse.c:984
int circuit_purpose_is_hidden_service(uint8_t purpose)
Definition: circuituse.c:1956
Header file for circuituse.c.
#define CIRCLAUNCH_NEED_CAPACITY
Definition: circuituse.h:43
#define CIRCLAUNCH_IS_IPV6_SELFTEST
Definition: circuituse.h:51
#define CIRCLAUNCH_ONEHOP_TUNNEL
Definition: circuituse.h:39
#define CIRCLAUNCH_IS_INTERNAL
Definition: circuituse.h:46
#define CIRCLAUNCH_NEED_UPTIME
Definition: circuituse.h:41
#define CIRCLAUNCH_NEED_CONFLUX
Definition: circuituse.h:53
void command_setup_channel(channel_t *chan)
Definition: command.c:711
Header file for command.c.
const or_options_t * get_options(void)
Definition: config.c:947
tor_cmdline_mode_t command
Definition: config.c:2477
Header file for config.c.
void conflux_add_middles_to_exclude_list(const origin_circuit_t *orig_circ, smartlist_t *excluded)
Header file for conflux_pool.c.
Header for confmgt.c.
congestion_control_t * congestion_control_new(const circuit_params_t *params, cc_path_t path)
int congestion_control_build_ext_request(trn_extension_t *ext)
bool congestion_control_enabled(void)
Public APIs for congestion control.
#define SBWS_ROUTE_LEN
Header file for connection.c.
#define CONN_TYPE_AP
Definition: connection.h:51
int connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit_node)
int connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
entry_connection_t * TO_ENTRY_CONN(connection_t *c)
edge_connection_t * TO_EDGE_CONN(connection_t *c)
Header file for connection_edge.c.
#define AP_CONN_STATE_CIRCUIT_WAIT
void clear_broken_connection_map(int stop_recording)
Header file for connection_or.c.
void control_event_bootstrap(bootstrap_status_t status, int progress)
int control_event_general_status(int severity, const char *format,...)
int control_event_client_status(int severity, const char *format,...)
Header file for control_events.c.
Circuit-build-stse structure.
crypt_path_t * cpath_get_next_non_open_hop(crypt_path_t *cpath)
Definition: crypt_path.c:188
int cpath_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
Definition: crypt_path.c:59
int cpath_init_circuit_crypto(relay_crypto_alg_t alg, crypt_path_t *cpath, const char *key_data, size_t key_data_len)
Definition: crypt_path.c:148
void cpath_free(crypt_path_t *victim)
Definition: crypt_path.c:159
Header file for crypt_path.c.
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
void ed25519_pubkey_copy(ed25519_public_key_t *dest, const ed25519_public_key_t *src)
int ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
void * smartlist_choose(const smartlist_t *sl)
Definition: crypto_rand.c:594
void crypto_rand(char *to, size_t n)
Definition: crypto_rand.c:479
Common functions for using (pseudo-)random number generators.
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:224
const char * node_describe(const node_t *node)
Definition: describe.c:160
Header file for describe.c.
#define DIGEST_LEN
Definition: digest_sizes.h:20
#define DIGEST256_LEN
Definition: digest_sizes.h:23
Header file for directory.c.
Entry connection structure.
const routerset_t * get_layer2_guards(void)
Definition: entrynodes.c:4315
guard_usable_t entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
Definition: entrynodes.c:2609
bool vanguards_lite_is_enabled(void)
Definition: entrynodes.c:4086
const node_t * guards_choose_guard(const origin_circuit_t *circ, cpath_build_state_t *state, uint8_t purpose, circuit_guard_state_t **guard_state_out)
Definition: entrynodes.c:3872
Header file for circuitbuild.c.
Header file for Tor tracing instrumentation definition.
#define TR_SUBSYS(name)
Definition: events.h:45
Extend-info structure.
extend_info_t * extend_info_dup(extend_info_t *info)
Definition: extendinfo.c:189
extend_info_t * extend_info_from_node(const node_t *node, int for_direct_connect, bool for_exit)
Definition: extendinfo.c:102
const tor_addr_port_t * extend_info_pick_orport(const extend_info_t *ei)
Definition: extendinfo.c:282
const tor_addr_port_t * extend_info_get_orport(const extend_info_t *ei, int family)
Definition: extendinfo.c:267
bool extend_info_any_orport_addr_is_internal(const extend_info_t *ei)
Definition: extendinfo.c:322
Header for core/or/extendinfo.c.
Header for hs_ntor.c.
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:591
#define log_fn(severity, domain, args,...)
Definition: log.h:283
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:288
#define LD_APP
Definition: log.h:78
#define LD_PROTOCOL
Definition: log.h:72
#define LD_BUG
Definition: log.h:86
#define LD_GUARD
Definition: log.h:109
#define LD_GENERAL
Definition: log.h:62
#define LOG_NOTICE
Definition: log.h:50
#define LD_CIRC
Definition: log.h:82
#define LOG_WARN
Definition: log.h:53
#define LOG_INFO
Definition: log.h:45
void note_that_we_maybe_cant_complete_circuits(void)
Definition: mainloop.c:234
int have_completed_a_circuit(void)
Definition: mainloop.c:218
void note_that_we_completed_a_circuit(void)
Definition: mainloop.c:226
smartlist_t * get_connection_array(void)
Definition: mainloop.c:443
void reset_all_main_loop_timers(void)
Definition: mainloop.c:1466
Header file for mainloop.c.
#define tor_free(p)
Definition: malloc.h:56
Header file for microdesc.c.
Header file for networkstatus.c.
int is_legal_nickname(const char *s)
Definition: nickname.c:19
Header file for nickname.c.
const node_t * router_choose_random_node(smartlist_t *excludedsmartlist, routerset_t *excludedset, router_crn_flags_t flags)
Definition: node_select.c:979
const node_t * node_sl_choose_by_bandwidth(const smartlist_t *sl, bandwidth_weight_rule_t rule)
Definition: node_select.c:856
Header file for node_select.c.
router_crn_flags_t
Definition: node_select.h:16
Node information structure.
const node_t * node_get_by_id(const char *identity_digest)
Definition: nodelist.c:226
void nodelist_add_node_and_family(smartlist_t *sl, const node_t *node)
Definition: nodelist.c:2294
const smartlist_t * nodelist_get_list(void)
Definition: nodelist.c:1081
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1543
void node_get_verbose_nickname(const node_t *node, char *verbose_name_out)
Definition: nodelist.c:1576
int router_have_minimum_dir_info(void)
Definition: nodelist.c:2490
int node_exit_policy_rejects_all(const node_t *node)
Definition: nodelist.c:1622
Header file for nodelist.c.
Header file for ocirc_event.c.
int extend_cell_format(uint8_t *command_out, uint16_t *len_out, uint8_t *payload_out, const extend_cell_t *cell_in)
Definition: onion.c:551
Header file for onion.c.
int onion_skin_create(int type, const extend_info_t *node, onion_handshake_state_t *state_out, uint8_t *onion_skin_out, size_t onion_skin_out_maxlen)
Definition: onion_crypto.c:146
void onion_handshake_state_release(onion_handshake_state_t *state)
Definition: onion_crypto.c:113
int onion_skin_client_handshake(int type, const onion_handshake_state_t *handshake_state, const uint8_t *reply, size_t reply_len, uint8_t *keys_out, size_t *keys_len_out, uint8_t *rend_authenticator_out, circuit_params_t *params_out, const char **msg_out)
Definition: onion_crypto.c:590
Header file for onion_crypto.c.
Header file for onion_fast.c.
Master header file for Tor-specific functionality.
#define MAX_NICKNAME_LEN
Definition: or.h:112
#define MIN_CIRCUITS_HANDLING_STREAM
Definition: or.h:180
#define DEFAULT_ROUTE_LEN
Definition: or.h:1001
uint32_t circid_t
Definition: or.h:584
#define END_CIRC_REASON_NOPATH
Definition: or.h:364
#define TO_CIRCUIT(x)
Definition: or.h:947
#define MAX_VERBOSE_NICKNAME_LEN
Definition: or.h:118
#define END_CIRC_REASON_FLAG_REMOTE
Definition: or.h:389
@ CELL_DIRECTION_OUT
Definition: or.h:425
#define RELAY_PAYLOAD_SIZE_MAX
Definition: or.h:572
@ RELAY_CELL_FORMAT_V1
Definition: or.h:538
Origin circuit structure.
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:2907
Header file for policies.c.
addr_policy_result_t
Definition: policies.h:38
@ ADDR_POLICY_PROBABLY_REJECTED
Definition: policies.h:48
@ ADDR_POLICY_REJECTED
Definition: policies.h:42
void rep_hist_remove_predicted_ports(const smartlist_t *rmv_ports)
smartlist_t * rep_hist_get_predicted_ports(time_t now)
Header file for predict_ports.c.
Headers and type declarations for protover.c.
#define PROTOVER_RELAY_CRYPT_CGO
Definition: protover.h:67
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:42
int append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan, cell_t *cell, cell_direction_t direction, streamid_t fromstream)
Definition: relay.c:3357
size_t circuit_max_relay_payload(const circuit_t *circ, const crypt_path_t *cpath, uint8_t relay_command)
Definition: relay.c:3560
Header file for relay.c.
#define MAX_RELAY_KEY_MATERIAL_LEN
Definition: relay_crypto.h:36
@ RELAY_CRYPTO_ALG_CGO_CLIENT
Definition: relay_crypto.h:28
int router_digest_is_me(const char *digest)
Definition: router.c:1775
Header file for router.c.
void router_add_running_nodes_to_smartlist(smartlist_t *sl, int flags)
Definition: routerlist.c:617
Header file for routerlist.c.
int server_mode(const or_options_t *options)
Definition: routermode.c:34
Header file for routermode.c.
int routerset_contains_node(const routerset_t *set, const node_t *node)
Definition: routerset.c:353
void routerset_get_all_nodes(smartlist_t *out, const routerset_t *routerset, const routerset_t *excludeset, int running_only)
Definition: routerset.c:379
int routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
Definition: routerset.c:308
void routerset_subtract_nodes(smartlist_t *lst, const routerset_t *routerset)
Definition: routerset.c:413
Header file for routerset.c.
void router_do_reachability_checks(void)
Definition: selftest.c:290
Header file for selftest.c.
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
int smartlist_contains_int_as_string(const smartlist_t *sl, int num)
Definition: smartlist.c:147
void smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
Definition: smartlist.c:264
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_clear(smartlist_t *sl)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: cell_st.h:17
circid_t circ_id
Definition: cell_st.h:18
channel_state_t state
Definition: channel.h:193
int(* is_canonical)(channel_t *)
Definition: channel.h:354
unsigned int num_n_circuits
Definition: channel.h:411
circ_id_type_bitfield_t circ_id_type
Definition: channel.h:406
char identity_digest[DIGEST_LEN]
Definition: channel.h:379
uint64_t global_identifier
Definition: channel.h:198
channel_usage_info_t channel_usage
Definition: channel.h:229
time_t timestamp_created
Definition: channel.h:299
circuitmux_t * cmux
Definition: channel.h:398
ratelim_t last_warned_circ_ids_exhausted
Definition: channel.h:439
relay_cell_fmt_t cell_fmt
Definition: onion_crypto.h:42
relay_crypto_alg_t crypto_alg
Definition: onion_crypto.h:40
uint8_t state
Definition: circuit_st.h:111
uint8_t purpose
Definition: circuit_st.h:112
struct timeval timestamp_began
Definition: circuit_st.h:176
channel_t * n_chan
Definition: circuit_st.h:70
extend_info_t * n_hop
Definition: circuit_st.h:88
circid_t n_circ_id
Definition: circuit_st.h:79
uint8_t state
Definition: connection_st.h:49
unsigned int type
Definition: connection_st.h:50
uint16_t marked_for_close
extend_info_t * chosen_exit
uint16_t handshake_len
Definition: onion.h:33
uint16_t handshake_type
Definition: onion.h:31
uint8_t onionskin[MAX_CREATE_LEN]
Definition: onion.h:35
uint8_t cell_type
Definition: onion.h:29
uint16_t handshake_len
Definition: onion.h:43
uint8_t reply[MAX_CREATED_LEN]
Definition: onion.h:45
struct crypt_path_t * prev
Definition: crypt_path_st.h:78
uint8_t state
Definition: crypt_path_st.h:71
struct crypt_path_t * next
Definition: crypt_path_st.h:75
relay_cell_fmt_t relay_cell_format
Definition: crypt_path_st.h:90
extend_info_t * extend_info
Definition: crypt_path_st.h:64
char rend_circ_nonce[DIGEST_LEN]
Definition: crypt_path_st.h:61
onion_handshake_state_t handshake_state
Definition: crypt_path_st.h:58
struct congestion_control_t * ccontrol
Definition: crypt_path_st.h:87
struct edge_connection_t * next_stream
tor_addr_port_t orport_ipv4
Definition: onion.h:53
create_cell_t create_cell
Definition: onion.h:63
struct ed25519_public_key_t ed_pubkey
Definition: onion.h:59
uint8_t node_id[DIGEST_LEN]
Definition: onion.h:57
tor_addr_port_t orport_ipv6
Definition: onion.h:55
uint8_t cell_type
Definition: onion.h:51
ed25519_public_key_t ed_identity
char identity_digest[DIGEST_LEN]
char nickname[MAX_HEX_NICKNAME_LEN+1]
bool exit_supports_congestion_control
Definition: node_st.h:34
char identity[DIGEST_LEN]
Definition: node_st.h:46
struct routerset_t * ExcludeExitNodesUnion_
struct routerset_t * ExcludeNodes
struct routerset_t * ExitNodes
struct routerset_t * HSLayer2Nodes
struct smartlist_t * LongLivedPorts
int ExtendAllowPrivateAddresses
struct routerset_t * MiddleNodes
struct routerset_t * HSLayer3Nodes
edge_connection_t * p_streams
unsigned int has_opened
crypt_path_t * cpath
cpath_build_state_t * build_state
struct circuit_guard_state_t * guard_state
unsigned first_hop_from_controller
#define STATIC
Definition: testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
void tor_gettimeofday(struct timeval *timeval)
Headers for transports.c.
#define tor_assert_nonfatal_unreached()
Definition: util_bug.h:177
#define tor_assert(expr)
Definition: util_bug.h:103
#define tor_fragile_assert()
Definition: util_bug.h:278
#define IF_BUG_ONCE(cond)
Definition: util_bug.h:254
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:98