Tor 0.4.9.13
Loading...
Searching...
No Matches
circuitlist.c
Go to the documentation of this file.
1/* Copyright 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 circuitlist.c
9 *
10 * \brief Manage global structures that list and index circuits, and
11 * look up circuits within them.
12 *
13 * One of the most frequent operations in Tor occurs every time that
14 * a relay cell arrives on a channel. When that happens, we need to
15 * find which circuit it is associated with, based on the channel and the
16 * circuit ID in the relay cell.
17 *
18 * To handle that, we maintain a global list of circuits, and a hashtable
19 * mapping [channel,circID] pairs to circuits. Circuits are added to and
20 * removed from this mapping using circuit_set_p_circid_chan() and
21 * circuit_set_n_circid_chan(). To look up a circuit from this map, most
22 * callers should use circuit_get_by_circid_channel(), though
23 * circuit_get_by_circid_channel_even_if_marked() is appropriate under some
24 * circumstances.
25 *
26 * We also need to allow for the possibility that we have blocked use of a
27 * circuit ID (because we are waiting to send a DESTROY cell), but the
28 * circuit is not there any more. For that case, we allow placeholder
29 * entries in the table, using channel_mark_circid_unusable().
30 *
31 * To efficiently handle a channel that has just opened, we also maintain a
32 * list of the circuits waiting for channels, so we can attach them as
33 * needed without iterating through the whole list of circuits, using
34 * circuit_get_all_pending_on_channel().
35 *
36 * In this module, we also handle the list of circuits that have been
37 * marked for close elsewhere, and close them as needed. (We use this
38 * "mark now, close later" pattern here and elsewhere to avoid
39 * unpredictable recursion if we closed every circuit immediately upon
40 * realizing it needed to close.) See circuit_mark_for_close() for the
41 * mark function, and circuit_close_all_marked() for the close function.
42 *
43 * For hidden services, we need to be able to look up introduction point
44 * circuits and rendezvous circuits by cookie, key, etc. These are
45 * currently handled with linear searches in
46 * circuit_get_next_by_pk_and_purpose(), and with hash lookups in
47 * circuit_get_rendezvous() and circuit_get_intro_point().
48 *
49 * This module is also the entry point for our out-of-memory handler
50 * logic, which was originally circuit-focused.
51 **/
52#define CIRCUITLIST_PRIVATE
53#define OCIRC_EVENT_PRIVATE
54#include "lib/cc/torint.h" /* TOR_PRIuSZ */
55
56#include "core/or/or.h"
57#include "core/or/channel.h"
58#include "core/or/channeltls.h"
59#include "feature/client/circpathbias.h"
61#include "core/or/circuitlist.h"
62#include "core/or/circuituse.h"
65#include "core/or/conflux.h"
67#include "core/or/crypt_path.h"
68#include "core/or/dos.h"
69#include "core/or/extendinfo.h"
70#include "core/or/status.h"
71#include "core/or/trace_probes_circuit.h"
73#include "app/config/config.h"
83#include "feature/hs/hs_cache.h"
86#include "feature/hs/hs_ident.h"
92#include "core/or/policies.h"
93#include "core/or/relay.h"
101#include "core/or/channelpadding.h"
106#include "lib/buf/buffers.h"
109#include "lib/math/stats.h"
110
111#include "core/or/ocirc_event.h"
112
113#include "ht.h"
114
119#include "core/or/half_edge_st.h"
121#include "core/or/or_circuit_st.h"
123
124#include "core/or/conflux_util.h"
125/********* START VARIABLES **********/
126
127/** A global list of all circuits at this hop. */
129
130/** A global list of all origin circuits. Every element of this is also
131 * an element of global_circuitlist. */
133
134/** A list of all the circuits in CIRCUIT_STATE_CHAN_WAIT. */
136
137/** List of all the (origin) circuits whose state is
138 * CIRCUIT_STATE_GUARD_WAIT. */
140
141/** A list of all the circuits that have been marked with
142 * circuit_mark_for_close and which are waiting for circuit_about_to_free. */
144
145static void circuit_about_to_free_atexit(circuit_t *circ);
146static void circuit_about_to_free(circuit_t *circ);
147
148/**
149 * A cached value of the current state of the origin circuit list. Has the
150 * value 1 if we saw any opened circuits recently (since the last call to
151 * circuit_any_opened_circuits(), which gets called around once a second by
152 * circuit_expire_building). 0 otherwise.
153 */
155
156/** Moving average of the cc->cwnd from each closed circuit. */
158/** Moving average of the cc->cwnd from each closed slow-start circuit. */
160
161uint64_t cc_stats_circs_closed = 0;
162
163/** Total number of circuit protocol violation. This is incremented when the
164 * END_CIRC_REASON_TORPROTOCOL is used to close a circuit. */
166
167/********* END VARIABLES ************/
168
169/* Implement circuit handle helpers. */
170HANDLE_IMPL(circuit, circuit_t,)
171
174{
175 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
176 return DOWNCAST(or_circuit_t, x);
177}
178const or_circuit_t *
179CONST_TO_OR_CIRCUIT(const circuit_t *x)
180{
182 return DOWNCAST(or_circuit_t, x);
183}
190const origin_circuit_t *
191CONST_TO_ORIGIN_CIRCUIT(const circuit_t *x)
192{
194 return DOWNCAST(origin_circuit_t, x);
195}
196
197/** A map from channel and circuit ID to circuit. (Lookup performance is
198 * very important here, since we need to do it every time a cell arrives.) */
200 HT_ENTRY(chan_circid_circuit_map_t) node;
201 channel_t *chan;
202 circid_t circ_id;
203 circuit_t *circuit;
204 /* For debugging 12184: when was this placeholder item added? */
205 time_t made_placeholder_at;
207
208/** Helper for hash tables: compare the channel and circuit ID for a and
209 * b, and return less than, equal to, or greater than zero appropriately.
210 */
211static inline int
214{
215 return a->chan == b->chan && a->circ_id == b->circ_id;
216}
217
218/** Helper: return a hash based on circuit ID and the pointer value of
219 * chan in <b>a</b>. */
220static inline unsigned int
222{
223 /* Try to squeze the siphash input into 8 bytes to save any extra siphash
224 * rounds. This hash function is in the critical path. */
225 uintptr_t chan = (uintptr_t) (void*) a->chan;
226 uint32_t array[2];
227 array[0] = a->circ_id;
228 /* The low bits of the channel pointer are uninteresting, since the channel
229 * is a pretty big structure. */
230 array[1] = (uint32_t) (chan >> 6);
231 return (unsigned) siphash24g(array, sizeof(array));
232}
233
234/** Map from [chan,circid] to circuit. */
235static HT_HEAD(chan_circid_map, chan_circid_circuit_map_t)
236 chan_circid_map = HT_INITIALIZER();
237HT_PROTOTYPE(chan_circid_map, chan_circid_circuit_map_t, node,
239HT_GENERATE2(chan_circid_map, chan_circid_circuit_map_t, node,
242
243/** The most recently returned entry from circuit_get_by_circid_chan;
244 * used to improve performance when many cells arrive in a row from the
245 * same circuit.
246 */
247static chan_circid_circuit_map_t *_last_circid_chan_ent = NULL;
248
249/** Implementation helper for circuit_set_{p,n}_circid_channel: A circuit ID
250 * and/or channel for circ has just changed from <b>old_chan, old_id</b>
251 * to <b>chan, id</b>. Adjust the chan,circid map as appropriate, removing
252 * the old entry (if any) and adding a new one. */
253static void
254circuit_set_circid_chan_helper(circuit_t *circ, int direction,
255 circid_t id,
256 channel_t *chan)
257{
260 channel_t *old_chan, **chan_ptr;
261 circid_t old_id, *circid_ptr;
262 int make_active, attached = 0;
263
264 if (direction == CELL_DIRECTION_OUT) {
265 chan_ptr = &circ->n_chan;
266 circid_ptr = &circ->n_circ_id;
267 make_active = circ->n_chan_cells.n > 0;
268 } else {
269 or_circuit_t *c = TO_OR_CIRCUIT(circ);
270 chan_ptr = &c->p_chan;
271 circid_ptr = &c->p_circ_id;
272 make_active = c->p_chan_cells.n > 0;
273 }
274 old_chan = *chan_ptr;
275 old_id = *circid_ptr;
276
277 if (id == old_id && chan == old_chan)
278 return;
279
280 if (_last_circid_chan_ent &&
281 ((old_id == _last_circid_chan_ent->circ_id &&
282 old_chan == _last_circid_chan_ent->chan) ||
283 (id == _last_circid_chan_ent->circ_id &&
284 chan == _last_circid_chan_ent->chan))) {
285 _last_circid_chan_ent = NULL;
286 }
287
288 if (old_chan) {
289 /*
290 * If we're changing channels or ID and had an old channel and a non
291 * zero old ID and weren't marked for close (i.e., we should have been
292 * attached), detach the circuit. ID changes require this because
293 * circuitmux hashes on (channel_id, circuit_id).
294 */
295 if (old_id != 0 && (old_chan != chan || old_id != id) &&
296 !(circ->marked_for_close)) {
297 tor_assert(old_chan->cmux);
298 circuitmux_detach_circuit(old_chan->cmux, circ);
299 }
300
301 /* we may need to remove it from the conn-circid map */
302 search.circ_id = old_id;
303 search.chan = old_chan;
304 found = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
305 if (found) {
306 tor_free(found);
307 if (direction == CELL_DIRECTION_OUT) {
308 /* One fewer circuits use old_chan as n_chan */
309 --(old_chan->num_n_circuits);
310 } else {
311 /* One fewer circuits use old_chan as p_chan */
312 --(old_chan->num_p_circuits);
313 }
314 }
315 }
316
317 /* Change the values only after we have possibly made the circuit inactive
318 * on the previous chan. */
319 *chan_ptr = chan;
320 *circid_ptr = id;
321
322 if (chan == NULL)
323 return;
324
325 /* now add the new one to the conn-circid map */
326 search.circ_id = id;
327 search.chan = chan;
328 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
329 if (found) {
330 found->circuit = circ;
331 found->made_placeholder_at = 0;
332 } else {
333 found = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
334 found->circ_id = id;
335 found->chan = chan;
336 found->circuit = circ;
337 HT_INSERT(chan_circid_map, &chan_circid_map, found);
338 }
339
340 /*
341 * Attach to the circuitmux if we're changing channels or IDs and
342 * have a new channel and ID to use and the circuit is not marked for
343 * close.
344 */
345 if (chan && id != 0 && (old_chan != chan || old_id != id) &&
346 !(circ->marked_for_close)) {
347 tor_assert(chan->cmux);
348 circuitmux_attach_circuit(chan->cmux, circ, direction);
349 attached = 1;
350 }
351
352 /*
353 * This is a no-op if we have no cells, but if we do it marks us active to
354 * the circuitmux
355 */
356 if (make_active && attached)
357 update_circuit_on_cmux(circ, direction);
358
359 /* Adjust circuit counts on new channel */
360 if (direction == CELL_DIRECTION_OUT) {
361 ++chan->num_n_circuits;
362 } else {
363 ++chan->num_p_circuits;
364 }
365}
366
367/** Mark that circuit id <b>id</b> shouldn't be used on channel <b>chan</b>,
368 * even if there is no circuit on the channel. We use this to keep the
369 * circuit id from getting re-used while we have queued but not yet sent
370 * a destroy cell. */
371void
373{
376
377 /* See if there's an entry there. That wouldn't be good. */
378 memset(&search, 0, sizeof(search));
379 search.chan = chan;
380 search.circ_id = id;
381 ent = HT_FIND(chan_circid_map, &chan_circid_map, &search);
382
383 if (ent && ent->circuit) {
384 /* we have a problem. */
385 log_warn(LD_BUG, "Tried to mark %u unusable on %p, but there was already "
386 "a circuit there.", (unsigned)id, chan);
387 } else if (ent) {
388 /* It's already marked. */
389 if (!ent->made_placeholder_at)
390 ent->made_placeholder_at = approx_time();
391 } else {
392 ent = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
393 ent->chan = chan;
394 ent->circ_id = id;
395 /* leave circuit at NULL. */
396 ent->made_placeholder_at = approx_time();
397 HT_INSERT(chan_circid_map, &chan_circid_map, ent);
398 }
399}
400
401/** Mark that a circuit id <b>id</b> can be used again on <b>chan</b>.
402 * We use this to re-enable the circuit ID after we've sent a destroy cell.
403 */
404void
406{
409
410 /* See if there's an entry there. That wouldn't be good. */
411 memset(&search, 0, sizeof(search));
412 search.chan = chan;
413 search.circ_id = id;
414 ent = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
415 if (ent && ent->circuit) {
416 log_warn(LD_BUG, "Tried to mark %u usable on %p, but there was already "
417 "a circuit there.", (unsigned)id, chan);
418 return;
419 }
420 if (_last_circid_chan_ent == ent)
421 _last_circid_chan_ent = NULL;
422 tor_free(ent);
423}
424
425/** Called to indicate that a DESTROY is pending on <b>chan</b> with
426 * circuit ID <b>id</b>, but hasn't been sent yet. */
427void
429{
431 if (circ) {
432 if (circ->n_chan == chan && circ->n_circ_id == id) {
433 circ->n_delete_pending = 1;
434 } else {
435 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
436 if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
437 circ->p_delete_pending = 1;
438 }
439 }
440 return;
441 }
443}
444
445/** Called to indicate that a DESTROY is no longer pending on <b>chan</b> with
446 * circuit ID <b>id</b> -- typically, because it has been sent. */
447MOCK_IMPL(void,
449{
451 if (circ) {
452 if (circ->n_chan == chan && circ->n_circ_id == id) {
453 circ->n_delete_pending = 0;
454 } else {
455 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
456 if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
457 circ->p_delete_pending = 0;
458 }
459 }
460 /* XXXX this shouldn't happen; log a bug here. */
461 return;
462 }
464}
465
466/** Set the p_conn field of a circuit <b>circ</b>, along
467 * with the corresponding circuit ID, and add the circuit as appropriate
468 * to the (chan,id)->circuit map. */
469void
471 channel_t *chan)
472{
473 circuit_t *circ = TO_CIRCUIT(or_circ);
474 channel_t *old_chan = or_circ->p_chan;
475 circid_t old_id = or_circ->p_circ_id;
476
477 circuit_set_circid_chan_helper(circ, CELL_DIRECTION_IN, id, chan);
478
479 if (chan) {
481 }
482
483 if (circ->p_delete_pending && old_chan) {
484 channel_mark_circid_unusable(old_chan, old_id);
485 circ->p_delete_pending = 0;
486 }
487}
488
489/** Set the n_conn field of a circuit <b>circ</b>, along
490 * with the corresponding circuit ID, and add the circuit as appropriate
491 * to the (chan,id)->circuit map. */
492void
494 channel_t *chan)
495{
496 channel_t *old_chan = circ->n_chan;
497 circid_t old_id = circ->n_circ_id;
498
499 circuit_set_circid_chan_helper(circ, CELL_DIRECTION_OUT, id, chan);
500
501 if (chan) {
503 }
504
505 if (circ->n_delete_pending && old_chan) {
506 channel_mark_circid_unusable(old_chan, old_id);
507 circ->n_delete_pending = 0;
508 }
509}
510
511/**
512 * Helper function to publish a message about events on an origin circuit
513 *
514 * Publishes a message to subscribers of origin circuit events, and
515 * sends the control event.
516 **/
517int
519 int reason_code)
520{
521 ocirc_cevent_msg_t *msg = tor_malloc(sizeof(*msg));
522
523 tor_assert(circ);
524
525 msg->gid = circ->global_identifier;
526 msg->evtype = tp;
527 msg->reason = reason_code;
528 msg->onehop = circ->build_state->onehop_tunnel;
529
530 ocirc_cevent_publish(msg);
531 return control_event_circuit_status(circ, tp, reason_code);
532}
533
534/**
535 * Helper function to publish a state change message
536 *
537 * circuit_set_state() calls this to notify subscribers about a change
538 * of the state of an origin circuit. @a circ must be an origin
539 * circuit.
540 **/
541static void
543{
544 ocirc_state_msg_t *msg = tor_malloc(sizeof(*msg));
545 const origin_circuit_t *ocirc;
546
548 ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
549 /* Only inbound OR circuits can be in this state, not origin circuits. */
551
552 msg->gid = ocirc->global_identifier;
553 msg->state = circ->state;
554 msg->onehop = ocirc->build_state->onehop_tunnel;
555
556 ocirc_state_publish(msg);
557}
558
559/** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
560 * it from lists as appropriate. */
561void
562circuit_set_state(circuit_t *circ, uint8_t state)
563{
564 tor_assert(circ);
565 if (state == circ->state)
566 return;
567 if (PREDICT_UNLIKELY(!circuits_pending_chans))
569 if (PREDICT_UNLIKELY(!circuits_pending_other_guards))
571 if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
572 /* remove from waiting-circuit list. */
574 }
575 if (state == CIRCUIT_STATE_CHAN_WAIT) {
576 /* add to waiting-circuit list. */
578 }
579 if (circ->state == CIRCUIT_STATE_GUARD_WAIT) {
581 }
582 if (state == CIRCUIT_STATE_GUARD_WAIT) {
584 }
585 if (state == CIRCUIT_STATE_GUARD_WAIT || state == CIRCUIT_STATE_OPEN)
587
588 tor_trace(TR_SUBSYS(circuit), TR_EV(change_state), circ, circ->state, state);
589 circ->state = state;
590 if (CIRCUIT_IS_ORIGIN(circ))
592}
593
594/** Append to <b>out</b> all circuits in state CHAN_WAIT waiting for
595 * the given connection. */
596void
598{
599 tor_assert(out);
600 tor_assert(chan);
601
603 return;
604
606 if (circ->marked_for_close)
607 continue;
608 if (!circ->n_hop)
609 continue;
612 /* Look at addr/port. This is an unkeyed connection. */
613 if (!channel_matches_extend_info(chan, circ->n_hop))
614 continue;
615 } else {
616 /* We expected a key. See if it's the right one. */
617 if (tor_memneq(chan->identity_digest,
619 continue;
620 }
621 smartlist_add(out, circ);
622 } SMARTLIST_FOREACH_END(circ);
623}
624
625/** Return the number of circuits in state CHAN_WAIT, waiting for the given
626 * channel. */
627int
629{
630 int cnt;
632
633 tor_assert(chan);
634
636 cnt = smartlist_len(sl);
637 smartlist_free(sl);
638 log_debug(LD_CIRC,"or_conn to %s, %d pending circs",
640 cnt);
641 return cnt;
642}
643
644/** Remove <b>origin_circ</b> from the global list of origin circuits.
645 * Called when we are freeing a circuit.
646 */
647static void
649{
650 int origin_idx = origin_circ->global_origin_circuit_list_idx;
651 if (origin_idx < 0)
652 return;
654 tor_assert(origin_idx <= smartlist_len(global_origin_circuit_list));
655 c2 = smartlist_get(global_origin_circuit_list, origin_idx);
656 tor_assert(origin_circ == c2);
658 if (origin_idx < smartlist_len(global_origin_circuit_list)) {
659 origin_circuit_t *replacement =
660 smartlist_get(global_origin_circuit_list, origin_idx);
661 replacement->global_origin_circuit_list_idx = origin_idx;
662 }
663 origin_circ->global_origin_circuit_list_idx = -1;
664}
665
666/** Add <b>origin_circ</b> to the global list of origin circuits. Called
667 * when creating the circuit. */
668static void
670{
671 tor_assert(origin_circ->global_origin_circuit_list_idx == -1);
673 smartlist_add(lst, origin_circ);
674 origin_circ->global_origin_circuit_list_idx = smartlist_len(lst) - 1;
675}
676
677/** Detach from the global circuit list, and deallocate, all
678 * circuits that have been marked for close.
679 */
680void
682{
683 if (circuits_pending_close == NULL)
684 return;
685
689
690 /* Remove it from the circuit list. */
691 int idx = circ->global_circuitlist_idx;
692 smartlist_del(lst, idx);
693 if (idx < smartlist_len(lst)) {
694 circuit_t *replacement = smartlist_get(lst, idx);
695 replacement->global_circuitlist_idx = idx;
696 }
697 circ->global_circuitlist_idx = -1;
698
699 /* Remove it from the origin circuit list, if appropriate. */
700 if (CIRCUIT_IS_ORIGIN(circ)) {
702 }
703
705 circuit_free(circ);
706 } SMARTLIST_FOREACH_END(circ);
707
709}
710
711#ifdef TOR_UNIT_TESTS
712/** Return the number of circuits on the circuits_pending_close list.
713 * Exposed for testing. */
714STATIC int
715circuit_count_pending_close(void)
716{
718 return 0;
719 return smartlist_len(circuits_pending_close);
720}
721#endif
722
723/** Return a pointer to the global list of circuits. */
731
732/** Return a pointer to the global list of origin circuits. */
740
741/**
742 * Return true if we have any opened general-purpose 3 hop
743 * origin circuits.
744 *
745 * The result from this function is cached for use by
746 * circuit_any_opened_circuits_cached().
747 */
748int
750{
752 const origin_circuit_t *, next_circ) {
753 if (!TO_CIRCUIT(next_circ)->marked_for_close &&
754 next_circ->has_opened &&
755 TO_CIRCUIT(next_circ)->state == CIRCUIT_STATE_OPEN &&
756 TO_CIRCUIT(next_circ)->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
757 next_circ->build_state &&
758 next_circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN) {
760 return 1;
761 }
762 } SMARTLIST_FOREACH_END(next_circ);
763
765 return 0;
766}
767
768/**
769 * Cache the "any circuits opened" state, as specified in param
770 * circuits_are_opened. This is a helper function to update
771 * the circuit opened status whenever we happen to look at the
772 * circuit list.
773 */
774void
776{
777 any_opened_circs_cached_val = circuits_are_opened;
778}
779
780/**
781 * Return true if there were any opened circuits since the last call to
782 * circuit_any_opened_circuits(), or since circuit_expire_building() last
783 * ran (it runs roughly once per second).
784 */
785int
790
791/** Function to make circ->state human-readable */
792const char *
794{
795 static char buf[64];
796 switch (state) {
797 case CIRCUIT_STATE_BUILDING: return "doing handshakes";
798 case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
799 case CIRCUIT_STATE_CHAN_WAIT: return "connecting to server";
800 case CIRCUIT_STATE_GUARD_WAIT: return "waiting to see how other "
801 "guards perform";
802 case CIRCUIT_STATE_OPEN: return "open";
803 default:
804 log_warn(LD_BUG, "Unknown circuit state %d", state);
805 tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
806 return buf;
807 }
808}
809
810/** Map a circuit purpose to a string suitable to be displayed to a
811 * controller. */
812const char *
814{
815 static char buf[32];
816 switch (purpose) {
821 return "SERVER"; /* A controller should never see these, actually. */
822
824 return "GENERAL";
825
827 return "HS_CLIENT_HSDIR";
828
832 return "HS_CLIENT_INTRO";
833
838 return "HS_CLIENT_REND";
839
841 return "HS_SERVICE_HSDIR";
842
845 return "HS_SERVICE_INTRO";
846
849 return "HS_SERVICE_REND";
850
852 return "TESTING";
854 return "MEASURE_TIMEOUT";
856 return "CONTROLLER";
858 return "PATH_BIAS_TESTING";
860 return "HS_VANGUARDS";
862 return "CIRCUIT_PADDING";
863
865 return "CONFLUX_UNLINKED";
866 case CIRCUIT_PURPOSE_CONFLUX_LINKED:
867 return "CONFLUX_LINKED";
868
869 default:
870 tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
871 return buf;
872 }
873}
874
875/** Return a string specifying the state of the hidden-service circuit
876 * purpose <b>purpose</b>, or NULL if <b>purpose</b> is not a
877 * hidden-service-related circuit purpose. */
878const char *
880{
881 switch (purpose)
882 {
883 default:
885 "Unrecognized circuit purpose: %d",
886 (int)purpose);
889
899 case CIRCUIT_PURPOSE_CONFLUX_LINKED:
900 return NULL;
901
903 return "OR_HSSI_ESTABLISHED";
905 return "OR_HSCR_ESTABLISHED";
907 return "OR_HS_R_JOINED";
908
911 return "HSCI_CONNECTING";
913 return "HSCI_INTRO_SENT";
915 return "HSCI_DONE";
916
918 return "HSCR_CONNECTING";
920 return "HSCR_ESTABLISHED_IDLE";
922 return "HSCR_ESTABLISHED_WAITING";
924 return "HSCR_JOINED";
925
928 return "HSSI_CONNECTING";
930 return "HSSI_ESTABLISHED";
931
933 return "HSSR_CONNECTING";
935 return "HSSR_JOINED";
936 }
937}
938
939/** Return a human-readable string for the circuit purpose <b>purpose</b>. */
940const char *
942{
943 static char buf[32];
944
945 switch (purpose)
946 {
948 return "Circuit at relay";
950 return "Acting as intro point";
952 return "Acting as rendezvous (pending)";
954 return "Acting as rendezvous (established)";
956 return "General-purpose client";
958 return "Hidden service client: Connecting to intro point";
960 return "Hidden service client: Waiting for ack from intro point";
962 return "Hidden service client: Received ack from intro point";
964 return "Hidden service client: Establishing rendezvous point";
966 return "Hidden service client: Pending rendezvous point";
968 return "Hidden service client: Pending rendezvous point (ack received)";
970 return "Hidden service client: Active rendezvous point";
972 return "Hidden service client: Fetching HS descriptor";
973
975 return "Measuring circuit timeout";
976
978 return "Hidden service: Establishing introduction point";
980 return "Hidden service: Introduction point";
982 return "Hidden service: Connecting to rendezvous point";
984 return "Hidden service: Active rendezvous point";
986 return "Hidden service: Uploading HS descriptor";
987
989 return "Testing circuit";
990
992 return "Circuit made by controller";
993
995 return "Path-bias testing circuit";
996
998 return "Hidden service: Pre-built vanguard circuit";
999
1001 return "Circuit kept open for padding";
1002
1004 return "Unlinked conflux circuit";
1005
1006 case CIRCUIT_PURPOSE_CONFLUX_LINKED:
1007 return "Linked conflux circuit";
1008
1009 default:
1010 tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
1011 return buf;
1012 }
1013}
1014
1015/** Pick a reasonable package_window to start out for our circuits.
1016 * Originally this was hard-coded at 1000, but now the consensus votes
1017 * on the answer. See proposal 168. */
1018int32_t
1020{
1021 int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START,
1022 CIRCWINDOW_START_MIN,
1023 CIRCWINDOW_START_MAX);
1024 /* If the consensus tells us a negative number, we'd assert. */
1025 if (num < 0)
1026 num = CIRCWINDOW_START;
1027 return num;
1028}
1029
1030/** Initialize the common elements in a circuit_t, and add it to the global
1031 * list. */
1032static void
1034{
1036
1037 // Gets reset when we send CREATE_FAST.
1038 // circuit_expire_building() expects these to be equal
1039 // until the orconn is built.
1040 circ->timestamp_began = circ->timestamp_created;
1041
1046
1048 circ->global_circuitlist_idx = smartlist_len(circuit_get_global_list()) - 1;
1049}
1050
1051/** If we haven't yet decided on a good timeout value for circuit
1052 * building, we close idle circuits aggressively so we can get more
1053 * data points. These are the default, min, and max consensus values */
1054#define DFLT_IDLE_TIMEOUT_WHILE_LEARNING (3*60)
1055#define MIN_IDLE_TIMEOUT_WHILE_LEARNING (10)
1056#define MAX_IDLE_TIMEOUT_WHILE_LEARNING (1000*60)
1057
1058/** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
1059 * and <b>p_conn</b>. Add it to the global circuit list.
1060 */
1063{
1064 origin_circuit_t *circ;
1065 /* never zero, since a global ID of 0 is treated specially by the
1066 * controller */
1067 static uint32_t n_circuits_allocated = 1;
1068
1069 circ = tor_malloc_zero(sizeof(origin_circuit_t));
1070 circ->base_.magic = ORIGIN_CIRCUIT_MAGIC;
1071
1072 circ->next_stream_id = crypto_rand_int(1<<16);
1073 circ->global_identifier = n_circuits_allocated++;
1076
1078
1079 /* Add to origin-list. */
1082
1083 circuit_build_times_update_last_circ(get_circuit_build_times_mutable());
1084
1087 /* Circuits should be shorter lived if we need more of them
1088 * for learning a good build timeout */
1089 circ->circuit_idle_timeout =
1090 networkstatus_get_param(NULL, "cbtlearntimeout",
1092 MIN_IDLE_TIMEOUT_WHILE_LEARNING,
1093 MAX_IDLE_TIMEOUT_WHILE_LEARNING);
1094 } else {
1095 // This should always be larger than the current port prediction time
1096 // remaining, or else we'll end up with the case where a circuit times out
1097 // and another one is built, effectively doubling the timeout window.
1098 //
1099 // We also randomize it by up to 5% more (ie 5% of 0 to 3600 seconds,
1100 // depending on how much circuit prediction time is remaining) so that
1101 // we don't close a bunch of unused circuits all at the same time.
1102 int prediction_time_remaining =
1104 circ->circuit_idle_timeout = prediction_time_remaining+1+
1105 crypto_rand_int(1+prediction_time_remaining/20);
1106
1107 if (circ->circuit_idle_timeout <= 0) {
1108 log_warn(LD_BUG,
1109 "Circuit chose a negative idle timeout of %d based on "
1110 "%d seconds of predictive building remaining.",
1112 prediction_time_remaining);
1113 circ->circuit_idle_timeout =
1114 networkstatus_get_param(NULL, "cbtlearntimeout",
1116 MIN_IDLE_TIMEOUT_WHILE_LEARNING,
1117 MAX_IDLE_TIMEOUT_WHILE_LEARNING);
1118 }
1119
1120 log_info(LD_CIRC,
1121 "Circuit %"PRIu32" chose an idle timeout of %d based on "
1122 "%d seconds of predictive building remaining.",
1123 (circ->global_identifier),
1125 prediction_time_remaining);
1126 }
1127
1128 tor_trace(TR_SUBSYS(circuit), TR_EV(new_origin), circ);
1129 return circ;
1130}
1131
1132/** Allocate a new or_circuit_t, connected to <b>p_chan</b> as
1133 * <b>p_circ_id</b>. If <b>p_chan</b> is NULL, the circuit is unattached. */
1136{
1137 /* CircIDs */
1138 or_circuit_t *circ;
1139
1140 circ = tor_malloc_zero(sizeof(or_circuit_t));
1141 circ->base_.magic = OR_CIRCUIT_MAGIC;
1142
1143 if (p_chan)
1144 circuit_set_p_circid_chan(circ, p_circ_id, p_chan);
1145
1148
1150 dos_stream_init_circ_tbf(circ);
1151
1152 tor_trace(TR_SUBSYS(circuit), TR_EV(new_or), circ);
1153 return circ;
1154}
1155
1156/** Free all storage held in circ->testing_cell_stats */
1157void
1159{
1160 if (!circ || !circ->testing_cell_stats)
1161 return;
1163 ent, tor_free(ent));
1164 smartlist_free(circ->testing_cell_stats);
1165 circ->testing_cell_stats = NULL;
1166}
1167
1168/** Deallocate space associated with circ.
1169 */
1170STATIC void
1172{
1173 circid_t n_circ_id = 0;
1174 void *mem;
1175 size_t memlen;
1176 int should_free = 1;
1177 if (!circ)
1178 return;
1179
1180 /* We keep a copy of this so we can log its value before it gets unset. */
1181 n_circ_id = circ->n_circ_id;
1182
1184
1185 /* Cleanup circuit from anything HS v3 related. We also do this when the
1186 * circuit is closed. This is to avoid any code path that free registered
1187 * circuits without closing them before. This needs to be done before the
1188 * hs identifier is freed. */
1190
1192
1193 if (CIRCUIT_IS_ORIGIN(circ)) {
1194 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1195 mem = ocirc;
1196 memlen = sizeof(origin_circuit_t);
1198
1200
1201 if (ocirc->half_streams) {
1203 half_conn) {
1204 half_edge_free(half_conn);
1205 } SMARTLIST_FOREACH_END(half_conn);
1206 smartlist_free(ocirc->half_streams);
1207 }
1208
1209 if (ocirc->build_state) {
1210 extend_info_free(ocirc->build_state->chosen_exit);
1211 }
1212 tor_free(ocirc->build_state);
1213
1214 /* Cancel before freeing, if we haven't already succeeded or failed. */
1215 if (ocirc->guard_state) {
1217 }
1218 circuit_guard_state_free(ocirc->guard_state);
1219
1220 circuit_clear_cpath(ocirc);
1221
1222 crypto_pk_free(ocirc->intro_key);
1223
1224 /* Finally, free the identifier of the circuit and nullify it so multiple
1225 * cleanup will work. */
1226 hs_ident_circuit_free(ocirc->hs_ident);
1227 ocirc->hs_ident = NULL;
1228
1229 tor_free(ocirc->dest_address);
1230 if (ocirc->socks_username) {
1231 memwipe(ocirc->socks_username, 0x12, ocirc->socks_username_len);
1232 tor_free(ocirc->socks_username);
1233 }
1234 if (ocirc->socks_password) {
1235 memwipe(ocirc->socks_password, 0x06, ocirc->socks_password_len);
1236 tor_free(ocirc->socks_password);
1237 }
1238 addr_policy_list_free(ocirc->prepend_policy);
1239 } else {
1240 or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
1241 /* Remember cell statistics for this circuit before deallocating. */
1242 if (get_options()->CellStatistics)
1243 rep_hist_buffer_stats_add_circ(circ, time(NULL));
1244 mem = ocirc;
1245 memlen = sizeof(or_circuit_t);
1247
1248 should_free = (ocirc->workqueue_entry == NULL);
1249
1250 relay_crypto_clear(&ocirc->crypto);
1251
1252 if (ocirc->rend_splice) {
1253 or_circuit_t *other = ocirc->rend_splice;
1254 tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
1255 other->rend_splice = NULL;
1256 }
1257
1258 /* remove from map. */
1259 circuit_set_p_circid_chan(ocirc, 0, NULL);
1260
1261 /* Clear cell queue _after_ removing it from the map. Otherwise our
1262 * "active" checks will be violated. */
1264 }
1265
1266 extend_info_free(circ->n_hop);
1268
1269 if (circ->global_circuitlist_idx != -1) {
1270 int idx = circ->global_circuitlist_idx;
1271 circuit_t *c2 = smartlist_get(global_circuitlist, idx);
1272 tor_assert(c2 == circ);
1274 if (idx < smartlist_len(global_circuitlist)) {
1275 c2 = smartlist_get(global_circuitlist, idx);
1276 c2->global_circuitlist_idx = idx;
1277 }
1278 }
1279
1280 /* Remove from map. */
1281 circuit_set_n_circid_chan(circ, 0, NULL);
1282
1283 /* Clear cell queue _after_ removing it from the map. Otherwise our
1284 * "active" checks will be violated. */
1286
1287 /* Cleanup possible SENDME state. */
1288 if (circ->sendme_last_digests) {
1289 SMARTLIST_FOREACH(circ->sendme_last_digests, uint8_t *, d, tor_free(d));
1290 smartlist_free(circ->sendme_last_digests);
1291 }
1292
1293 log_info(LD_CIRC, "Circuit %u (id: %" PRIu32 ") has been freed.",
1294 n_circ_id,
1295 CIRCUIT_IS_ORIGIN(circ) ?
1296 TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0);
1297
1298 /* Free any circuit padding structures */
1300
1301 /* Clear all dangling handle references. */
1302 circuit_handles_clear(circ);
1303
1304 /* Tracepoint. Data within the circuit object is recorded so do this before
1305 * the actual memory free. */
1306 tor_trace(TR_SUBSYS(circuit), TR_EV(free), circ);
1307
1308 if (should_free) {
1309 memwipe(mem, 0xAA, memlen); /* poison memory */
1310 tor_free(mem);
1311 } else {
1312 /* If we made it here, this is an or_circuit_t that still has a pending
1313 * cpuworker request which we weren't able to cancel. Instead, set up
1314 * the magic value so that when the reply comes back, we'll know to discard
1315 * the reply and free this structure.
1316 */
1317 memwipe(mem, 0xAA, memlen);
1318 circ->magic = DEAD_CIRCUIT_MAGIC;
1319 }
1320}
1321
1322/** Deallocate the linked list circ-><b>cpath</b>, and remove the cpath from
1323 * <b>circ</b>. */
1324void
1326{
1327 crypt_path_t *victim, *head, *cpath;
1328
1329 head = cpath = circ->cpath;
1330
1331 if (!cpath)
1332 return;
1333
1334 /* it's a circular list, so we have to notice when we've
1335 * gone through it once. */
1336 while (cpath->next && cpath->next != head) {
1337 victim = cpath;
1338 cpath = victim->next;
1339 cpath_free(victim);
1340 }
1341
1342 cpath_free(cpath);
1343
1344 circ->cpath = NULL;
1345 /* This will ensure that we don't accept any more authenticated
1346 * SENDMEs on this circuit if we have already registered a hop,
1347 * since an origin circuit never receives a relay cell from
1348 * a NULL layer.
1349 *
1350 * In practice this funciton is only called from tests and form
1351 * circuit_free_, so there's no actual risk of confusion.
1352 */
1353 circ->base_.sendme_digest_hop = NULL;
1354}
1355
1356/** Release all storage held by circuits. */
1357void
1359{
1361
1362 SMARTLIST_FOREACH_BEGIN(lst, circuit_t *, tmp) {
1363 tmp->global_circuitlist_idx = -1;
1364 /* Must run before the resolving_streams loop below: for conflux circuits,
1365 * this calls linked_circuit_free() -> linked_nullify_streams(), which
1366 * NULLs the shared stream pointer on non-last legs so that the loop is
1367 * a no-op for them and only the last leg actually frees the streams. */
1369 if (! CIRCUIT_IS_ORIGIN(tmp)) {
1370 or_circuit_t *or_circ = TO_OR_CIRCUIT(tmp);
1371 while (or_circ->resolving_streams) {
1372 edge_connection_t *next_conn;
1373 next_conn = or_circ->resolving_streams->next_stream;
1375 or_circ->resolving_streams = next_conn;
1376 }
1377 }
1378 circuit_free(tmp);
1379 SMARTLIST_DEL_CURRENT(lst, tmp);
1380 } SMARTLIST_FOREACH_END(tmp);
1381
1382 smartlist_free(lst);
1383 global_circuitlist = NULL;
1384
1385 smartlist_free(global_origin_circuit_list);
1387
1388 smartlist_free(circuits_pending_chans);
1390
1391 smartlist_free(circuits_pending_close);
1393
1394 smartlist_free(circuits_pending_other_guards);
1396
1397 {
1398 chan_circid_circuit_map_t **elt, **next, *c;
1399 for (elt = HT_START(chan_circid_map, &chan_circid_map);
1400 elt;
1401 elt = next) {
1402 c = *elt;
1403 next = HT_NEXT_RMV(chan_circid_map, &chan_circid_map, elt);
1404
1405 tor_assert(c->circuit == NULL);
1406 tor_free(c);
1407 }
1408 }
1409 HT_CLEAR(chan_circid_map, &chan_circid_map);
1410}
1411
1412/** A helper function for circuit_dump_by_conn() below. Log a bunch
1413 * of information about circuit <b>circ</b>.
1414 */
1415static void
1417 circuit_t *circ,
1418 int conn_array_index,
1419 const char *type,
1420 circid_t this_circid,
1421 circid_t other_circid)
1422{
1423 tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
1424 "(other side %u), state %d (%s), born %ld:",
1425 conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
1426 circ->state, circuit_state_to_string(circ->state),
1427 (long)circ->timestamp_began.tv_sec);
1428 if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
1429 circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
1430 }
1431}
1432
1433/** Log, at severity <b>severity</b>, information about each circuit
1434 * that is connected to <b>conn</b>.
1435 */
1436void
1438{
1439 edge_connection_t *tmpconn;
1440
1442 circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
1443
1444 if (circ->marked_for_close) {
1445 continue;
1446 }
1447
1448 if (!CIRCUIT_IS_ORIGIN(circ)) {
1449 p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
1450 }
1451
1452 if (CIRCUIT_IS_ORIGIN(circ)) {
1453 for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
1454 tmpconn=tmpconn->next_stream) {
1455 if (TO_CONN(tmpconn) == conn) {
1456 circuit_dump_conn_details(severity, circ, conn->conn_array_index,
1457 "App-ward", p_circ_id, n_circ_id);
1458 }
1459 }
1460 }
1461
1462 if (! CIRCUIT_IS_ORIGIN(circ)) {
1463 for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
1464 tmpconn=tmpconn->next_stream) {
1465 if (TO_CONN(tmpconn) == conn) {
1466 circuit_dump_conn_details(severity, circ, conn->conn_array_index,
1467 "Exit-ward", n_circ_id, p_circ_id);
1468 }
1469 }
1470 }
1471 }
1472 SMARTLIST_FOREACH_END(circ);
1473}
1474
1475/** Return the circuit whose global ID is <b>id</b>, or NULL if no
1476 * such circuit exists. */
1479{
1481 if (CIRCUIT_IS_ORIGIN(circ) &&
1482 TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
1483 if (circ->marked_for_close)
1484 return NULL;
1485 else
1486 return TO_ORIGIN_CIRCUIT(circ);
1487 }
1488 }
1489 SMARTLIST_FOREACH_END(circ);
1490 return NULL;
1491}
1492
1493/** Return a circ such that:
1494 * - circ->n_circ_id or circ->p_circ_id is equal to <b>circ_id</b>, and
1495 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
1496 * Return NULL if no such circuit exists.
1497 *
1498 * If <b>found_entry_out</b> is provided, set it to true if we have a
1499 * placeholder entry for circid/chan, and leave it unset otherwise.
1500 */
1501static inline circuit_t *
1503 int *found_entry_out)
1504{
1507
1508 if (_last_circid_chan_ent &&
1509 circ_id == _last_circid_chan_ent->circ_id &&
1510 chan == _last_circid_chan_ent->chan) {
1511 found = _last_circid_chan_ent;
1512 } else {
1513 search.circ_id = circ_id;
1514 search.chan = chan;
1515 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
1516 _last_circid_chan_ent = found;
1517 }
1518 if (found && found->circuit) {
1519 log_debug(LD_CIRC,
1520 "circuit_get_by_circid_channel_impl() returning circuit %p for"
1521 " circ_id %u, channel ID %"PRIu64 " (%p)",
1522 found->circuit, (unsigned)circ_id,
1523 (chan->global_identifier), chan);
1524 if (found_entry_out)
1525 *found_entry_out = 1;
1526 return found->circuit;
1527 }
1528
1529 log_debug(LD_CIRC,
1530 "circuit_get_by_circid_channel_impl() found %s for"
1531 " circ_id %u, channel ID %"PRIu64 " (%p)",
1532 found ? "placeholder" : "nothing",
1533 (unsigned)circ_id,
1534 (chan->global_identifier), chan);
1535
1536 if (found_entry_out)
1537 *found_entry_out = found ? 1 : 0;
1538
1539 return NULL;
1540 /* The rest of this checks for bugs. Disabled by default. */
1541 /* We comment it out because coverity complains otherwise.
1542 {
1543 circuit_t *circ;
1544 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
1545 if (! CIRCUIT_IS_ORIGIN(circ)) {
1546 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1547 if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
1548 log_warn(LD_BUG,
1549 "circuit matches p_chan, but not in hash table (Bug!)");
1550 return circ;
1551 }
1552 }
1553 if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
1554 log_warn(LD_BUG,
1555 "circuit matches n_chan, but not in hash table (Bug!)");
1556 return circ;
1557 }
1558 }
1559 return NULL;
1560 } */
1561}
1562
1563/** Return a circ such that:
1564 * - circ->n_circ_id or circ->p_circ_id is equal to <b>circ_id</b>, and
1565 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
1566 * - circ is not marked for close.
1567 * Return NULL if no such circuit exists.
1568 */
1569circuit_t *
1571{
1572 circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
1573 if (!circ || circ->marked_for_close)
1574 return NULL;
1575 else
1576 return circ;
1577}
1578
1579/** Return a circ such that:
1580 * - circ->n_circ_id or circ->p_circ_id is equal to <b>circ_id</b>, and
1581 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
1582 * Return NULL if no such circuit exists.
1583 */
1584circuit_t *
1586 channel_t *chan)
1587{
1588 return circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
1589}
1590
1591/** Return true iff the circuit ID <b>circ_id</b> is currently used by a
1592 * circuit, marked or not, on <b>chan</b>, or if the circ ID is reserved until
1593 * a queued destroy cell can be sent.
1594 *
1595 * (Return 1 if the circuit is present, marked or not; Return 2
1596 * if the circuit ID is pending a destroy.)
1597 **/
1598int
1600{
1601 int found = 0;
1602 if (circuit_get_by_circid_channel_impl(circ_id, chan, &found) != NULL)
1603 return 1;
1604 if (found)
1605 return 2;
1606 return 0;
1607}
1608
1609/** Helper for debugging 12184. Returns the time since which 'circ_id' has
1610 * been marked unusable on 'chan'. */
1611time_t
1613{
1616
1617 memset(&search, 0, sizeof(search));
1618 search.circ_id = circ_id;
1619 search.chan = chan;
1620
1621 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
1622
1623 if (! found || found->circuit)
1624 return 0;
1625
1626 return found->made_placeholder_at;
1627}
1628
1629/** Return the circuit that a given edge connection is using. */
1630circuit_t *
1632{
1633 circuit_t *circ;
1634
1635 circ = conn->on_circuit;
1636 tor_assert(!circ ||
1638 : circ->magic == OR_CIRCUIT_MAGIC));
1639
1640 return circ;
1641}
1642
1643/** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
1644 * circuit from the chan,circid map, and mark it for close if it hasn't
1645 * been marked already.
1646 */
1647void
1649{
1650 smartlist_t *detached = smartlist_new();
1651
1652/* #define DEBUG_CIRCUIT_UNLINK_ALL */
1653
1654 channel_unlink_all_circuits(chan, detached);
1655
1656#ifdef DEBUG_CIRCUIT_UNLINK_ALL
1657 {
1658 smartlist_t *detached_2 = smartlist_new();
1659 int mismatch = 0, badlen = 0;
1660
1662 if (circ->n_chan == chan ||
1663 (!CIRCUIT_IS_ORIGIN(circ) &&
1664 TO_OR_CIRCUIT(circ)->p_chan == chan)) {
1665 smartlist_add(detached_2, circ);
1666 }
1667 }
1668 SMARTLIST_FOREACH_END(circ);
1669
1670 if (smartlist_len(detached) != smartlist_len(detached_2)) {
1671 log_warn(LD_BUG, "List of detached circuits had the wrong length! "
1672 "(got %d, should have gotten %d)",
1673 (int)smartlist_len(detached),
1674 (int)smartlist_len(detached_2));
1675 badlen = 1;
1676 }
1677 smartlist_sort_pointers(detached);
1678 smartlist_sort_pointers(detached_2);
1679
1680 SMARTLIST_FOREACH(detached, circuit_t *, c,
1681 if (c != smartlist_get(detached_2, c_sl_idx))
1682 mismatch = 1;
1683 );
1684
1685 if (mismatch)
1686 log_warn(LD_BUG, "Mismatch in list of detached circuits.");
1687
1688 if (badlen || mismatch) {
1689 smartlist_free(detached);
1690 detached = detached_2;
1691 } else {
1692 log_notice(LD_CIRC, "List of %d circuits was as expected.",
1693 (int)smartlist_len(detached));
1694 smartlist_free(detached_2);
1695 }
1696 }
1697#endif /* defined(DEBUG_CIRCUIT_UNLINK_ALL) */
1698
1699 SMARTLIST_FOREACH_BEGIN(detached, circuit_t *, circ) {
1700 int mark = 0;
1701 if (circ->n_chan == chan) {
1702
1703 circuit_set_n_circid_chan(circ, 0, NULL);
1704 mark = 1;
1705
1706 /* If we didn't request this closure, pass the remote
1707 * bit to mark_for_close. */
1708 if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
1710 }
1711 if (! CIRCUIT_IS_ORIGIN(circ)) {
1712 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1713 if (or_circ->p_chan == chan) {
1714 circuit_set_p_circid_chan(or_circ, 0, NULL);
1715 mark = 1;
1716 }
1717 }
1718 if (!mark) {
1719 log_warn(LD_BUG, "Circuit on detached list which I had no reason "
1720 "to mark");
1721 continue;
1722 }
1723 if (!circ->marked_for_close)
1724 circuit_mark_for_close(circ, reason);
1725 } SMARTLIST_FOREACH_END(circ);
1726
1727 smartlist_free(detached);
1728}
1729
1730/** Return the first introduction circuit originating from the global circuit
1731 * list after <b>start</b> or at the start of the list if <b>start</b> is
1732 * NULL. Return NULL if no circuit is found.
1733 *
1734 * If <b>want_client_circ</b> is true, then we are looking for client-side
1735 * introduction circuits: A client introduction point circuit has a purpose of
1736 * either CIRCUIT_PURPOSE_C_INTRODUCING, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
1737 * or CIRCUIT_PURPOSE_C_INTRODUCE_ACKED. This does not return a circuit marked
1738 * for close, but it returns circuits regardless of their circuit state.
1739 *
1740 * If <b>want_client_circ</b> is false, then we are looking for service-side
1741 * introduction circuits: A service introduction point circuit has a purpose of
1742 * either CIRCUIT_PURPOSE_S_ESTABLISH_INTRO or CIRCUIT_PURPOSE_S_INTRO. This
1743 * does not return circuits marked for close, or in any state other than open.
1744 */
1747 bool want_client_circ)
1748{
1749 int idx = 0;
1751
1752 if (start) {
1753 idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
1754 }
1755
1756 for ( ; idx < smartlist_len(lst); ++idx) {
1757 circuit_t *circ = smartlist_get(lst, idx);
1758
1759 /* Ignore a marked for close circuit or if the state is not open. */
1760 if (circ->marked_for_close) {
1761 continue;
1762 }
1763
1764 /* Depending on whether we are looking for client or service circs, skip
1765 * circuits with other purposes. */
1766 if (want_client_circ) {
1770 continue;
1771 }
1772 } else { /* we are looking for service-side circs */
1773 if (circ->state != CIRCUIT_STATE_OPEN) {
1774 continue;
1775 }
1778 continue;
1779 }
1780 }
1781
1782 /* The purposes we are looking for are only for origin circuits so the
1783 * following is valid. */
1784 return TO_ORIGIN_CIRCUIT(circ);
1785 }
1786 /* Not found. */
1787 return NULL;
1788}
1789
1790/** Return the first service rendezvous circuit originating from the global
1791 * circuit list after <b>start</b> or at the start of the list if <b>start</b>
1792 * is NULL. Return NULL if no circuit is found.
1793 *
1794 * A service rendezvous point circuit has a purpose of either
1795 * CIRCUIT_PURPOSE_S_CONNECT_REND or CIRCUIT_PURPOSE_S_REND_JOINED. This does
1796 * not return a circuit marked for close and its state must be open. */
1799{
1800 int idx = 0;
1802
1803 if (start) {
1804 idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
1805 }
1806
1807 for ( ; idx < smartlist_len(lst); ++idx) {
1808 circuit_t *circ = smartlist_get(lst, idx);
1809
1810 /* Ignore a marked for close circuit or purpose not matching a service
1811 * intro point or if the state is not open. */
1812 if (circ->marked_for_close || circ->state != CIRCUIT_STATE_OPEN ||
1815 continue;
1816 }
1817 /* The purposes we are looking for are only for origin circuits so the
1818 * following is valid. */
1819 return TO_ORIGIN_CIRCUIT(circ);
1820 }
1821 /* Not found. */
1822 return NULL;
1823}
1824
1825/** Return the first circuit originating here in global_circuitlist after
1826 * <b>start</b> whose purpose is <b>purpose</b>. Return NULL if no circuit is
1827 * found. If <b>start</b> is NULL, begin at the start of the list. */
1830{
1831 int idx;
1834 if (start == NULL)
1835 idx = 0;
1836 else
1837 idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
1838
1839 for ( ; idx < smartlist_len(lst); ++idx) {
1840 circuit_t *circ = smartlist_get(lst, idx);
1841
1842 if (circ->marked_for_close)
1843 continue;
1844 if (circ->purpose != purpose)
1845 continue;
1846 /* At this point we should be able to get a valid origin circuit because
1847 * the origin purpose we are looking for matches this circuit. */
1848 if (BUG(!CIRCUIT_PURPOSE_IS_ORIGIN(circ->purpose))) {
1849 break;
1850 }
1851 return TO_ORIGIN_CIRCUIT(circ);
1852 }
1853 return NULL;
1854}
1855
1856/** We are trying to create a circuit of purpose <b>purpose</b> and we are
1857 * looking for cannibalizable circuits. Return the circuit purpose we would be
1858 * willing to cannibalize. */
1859static uint8_t
1861{
1862 if (circuit_should_use_vanguards(purpose)) {
1863 /* If we are using vanguards, then we should only cannibalize vanguard
1864 * circuits so that we get the same path construction logic. */
1866 } else {
1867 /* Conflux purposes should never get here */
1868 tor_assert_nonfatal(purpose != CIRCUIT_PURPOSE_CONFLUX_UNLINKED &&
1869 purpose != CIRCUIT_PURPOSE_CONFLUX_LINKED);
1870 /* If no vanguards are used just get a general circuit! */
1872 }
1873}
1874
1875/** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
1876 * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
1877 * flags in <b>flags</b>, and if info is defined, does not already use info
1878 * as any of its hops; or NULL if no circuit fits this description.
1879 *
1880 * The <b>purpose</b> argument refers to the purpose of the circuit we want to
1881 * create, not the purpose of the circuit we want to cannibalize.
1882 *
1883 * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
1884 *
1885 * To "cannibalize" a circuit means to extend it an extra hop, and use it
1886 * for some other purpose than we had originally intended. We do this when
1887 * we want to perform some low-bandwidth task at a specific relay, and we
1888 * would like the circuit to complete as soon as possible. (If we were going
1889 * to use a lot of bandwidth, we wouldn't want a circuit with an extra hop.
1890 * If we didn't care about circuit completion latency, we would just build
1891 * a new circuit.)
1892 */
1894circuit_find_to_cannibalize(uint8_t purpose_to_produce, extend_info_t *info,
1895 int flags)
1896{
1897 origin_circuit_t *best=NULL;
1898 int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
1899 int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
1900 int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
1901 const or_options_t *options = get_options();
1902 /* We want the circuit we are trying to cannibalize to have this purpose */
1903 int purpose_to_search_for;
1904
1905 /* Make sure we're not trying to create a onehop circ by
1906 * cannibalization. */
1908
1909 purpose_to_search_for = get_circuit_purpose_needed_to_cannibalize(
1910 purpose_to_produce);
1911
1912 tor_assert_nonfatal(purpose_to_search_for == CIRCUIT_PURPOSE_C_GENERAL ||
1913 purpose_to_search_for == CIRCUIT_PURPOSE_HS_VANGUARDS);
1914
1915 tor_assert_nonfatal(purpose_to_search_for !=
1917 tor_assert_nonfatal(purpose_to_produce != CIRCUIT_PURPOSE_CONFLUX_UNLINKED);
1918
1919 log_debug(LD_CIRC,
1920 "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
1921 "capacity %d, internal %d",
1922 purpose_to_produce, need_uptime, need_capacity, internal);
1923
1925 if (CIRCUIT_IS_ORIGIN(circ_) &&
1926 circ_->state == CIRCUIT_STATE_OPEN &&
1927 !circ_->marked_for_close &&
1928 circ_->purpose == purpose_to_search_for &&
1929 !circ_->timestamp_dirty) {
1930 origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
1931
1932 /* Only cannibalize from reasonable length circuits. If we
1933 * want C_GENERAL, then only choose 3 hop circs. If we want
1934 * HS_VANGUARDS, only choose 4 hop circs.
1935 */
1936 if (circ->build_state->desired_path_len !=
1937 route_len_for_purpose(purpose_to_search_for, NULL)) {
1938 goto next;
1939 }
1940
1941 /* Ignore any circuits for which we can't use the Guard. It is possible
1942 * that the Guard was removed from the sampled set after the circuit
1943 * was created, so avoid using it. */
1945 goto next;
1946 }
1947
1948 if ((!need_uptime || circ->build_state->need_uptime) &&
1949 (!need_capacity || circ->build_state->need_capacity) &&
1950 (internal == circ->build_state->is_internal) &&
1951 !circ->unusable_for_new_conns &&
1953 !circ->build_state->onehop_tunnel &&
1954 !circ->isolation_values_set) {
1955 if (info) {
1956 /* need to make sure we don't duplicate hops */
1957 crypt_path_t *hop = circ->cpath;
1958 const node_t *ri1 = node_get_by_id(info->identity_digest);
1959 do {
1960 const node_t *ri2;
1963 goto next;
1964 if (ri1 &&
1966 && nodes_in_same_family(ri1, ri2))
1967 goto next;
1968 hop=hop->next;
1969 } while (hop!=circ->cpath);
1970 }
1971 if (options->ExcludeNodes) {
1972 /* Make sure no existing nodes in the circuit are excluded for
1973 * general use. (This may be possible if StrictNodes is 0, and we
1974 * thought we needed to use an otherwise excluded node for, say, a
1975 * directory operation.) */
1976 crypt_path_t *hop = circ->cpath;
1977 do {
1979 hop->extend_info))
1980 goto next;
1981 hop = hop->next;
1982 } while (hop != circ->cpath);
1983 }
1984
1985 if (!best || (best->build_state->need_uptime && !need_uptime))
1986 best = circ;
1987 next: ;
1988 }
1989 }
1990 }
1991 SMARTLIST_FOREACH_END(circ_);
1992 return best;
1993}
1994
1995/**
1996 * Check whether any of the origin circuits that are waiting to see if
1997 * their guard is good enough to use can be upgraded to "ready". If so,
1998 * return a new smartlist containing them. Otherwise return NULL.
1999 */
2002{
2003 /* Only if some circuit is actually waiting on an upgrade should we
2004 * run the algorithm. */
2006 smartlist_len(circuits_pending_other_guards)==0)
2007 return NULL;
2008 /* Only if we have some origin circuits should we run the algorithm. */
2010 return NULL;
2011
2012 /* Okay; we can pass our circuit list to entrynodes.c.*/
2013 smartlist_t *result = smartlist_new();
2014 int circuits_upgraded = entry_guards_upgrade_waiting_circuits(
2017 result);
2018 if (circuits_upgraded && smartlist_len(result)) {
2019 return result;
2020 } else {
2021 smartlist_free(result);
2022 return NULL;
2023 }
2024}
2025
2026/** Return the number of hops in circuit's path. If circ has no entries,
2027 * or is NULL, returns 0. */
2028int
2030{
2031 int n = 0;
2032 if (circ && circ->cpath) {
2033 crypt_path_t *cpath, *cpath_next = NULL;
2034 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2035 cpath_next = cpath->next;
2036 ++n;
2037 }
2038 }
2039 return n;
2040}
2041
2042/** Return the number of opened hops in circuit's path.
2043 * If circ has no entries, or is NULL, returns 0. */
2044int
2046{
2047 int n = 0;
2048 if (circ && circ->cpath) {
2049 crypt_path_t *cpath, *cpath_next = NULL;
2050 for (cpath = circ->cpath;
2051 cpath->state == CPATH_STATE_OPEN
2052 && cpath_next != circ->cpath;
2053 cpath = cpath_next) {
2054 cpath_next = cpath->next;
2055 ++n;
2056 }
2057 }
2058 return n;
2059}
2060
2061/** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
2062 * aren't that many hops in the list. <b>hopnum</b> starts at 1.
2063 * Returns NULL if <b>hopnum</b> is 0 or negative. */
2066{
2067 if (circ && circ->cpath && hopnum > 0) {
2068 crypt_path_t *cpath, *cpath_next = NULL;
2069 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2070 cpath_next = cpath->next;
2071 if (--hopnum <= 0)
2072 return cpath;
2073 }
2074 }
2075 return NULL;
2076}
2077
2078/** Go through the circuitlist; mark-for-close each circuit that starts
2079 * at us but has not yet been used. */
2080void
2082{
2084 if (CIRCUIT_IS_ORIGIN(circ) &&
2085 !circ->marked_for_close &&
2086 !circ->timestamp_dirty)
2087 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
2088 }
2089 SMARTLIST_FOREACH_END(circ);
2090}
2091
2092/** Go through the circuitlist; for each circuit that starts at us
2093 * and is dirty, frob its timestamp_dirty so we won't use it for any
2094 * new streams.
2095 *
2096 * This is useful for letting the user change pseudonyms, so new
2097 * streams will not be linkable to old streams.
2098 */
2099void
2101{
2103 if (CIRCUIT_IS_ORIGIN(circ) &&
2104 !circ->marked_for_close &&
2105 circ->timestamp_dirty) {
2107 }
2108 }
2109 SMARTLIST_FOREACH_END(circ);
2110}
2111
2112/**
2113 * Report any queued cells on or_circuits as written in our bandwidth
2114 * totals, for the specified channel direction.
2115 *
2116 * When we close a circuit or clear its cell queues, we've read
2117 * data and recorded those bytes in our read statistics, but we're
2118 * not going to write it. This discrepancy can be used by an adversary
2119 * to infer information from our public relay statistics and perform
2120 * attacks such as guard discovery.
2121 *
2122 * This function is in the critical path of circuit_mark_for_close().
2123 * It must be (and is) O(1)!
2124 *
2125 * See https://bugs.torproject.org/tpo/core/tor/23512
2126 */
2127void
2130{
2131 uint64_t cells;
2132 uint64_t cell_size;
2133 uint64_t written_sync;
2134 const channel_t *chan = NULL;
2135 const or_circuit_t *or_circ;
2136
2137 if (!CIRCUIT_IS_ORCIRC(c))
2138 return;
2139
2140 or_circ = CONST_TO_OR_CIRCUIT(c);
2141
2142 if (dir == CIRCUIT_N_CHAN) {
2143 chan = c->n_chan;
2144 cells = c->n_chan_cells.n;
2145 } else {
2146 chan = or_circ->p_chan;
2147 cells = or_circ->p_chan_cells.n;
2148 }
2149
2150 /* If we still know the chan, determine real cell size. Otherwise,
2151 * assume it's a wide circid channel */
2152 if (chan)
2153 cell_size = get_cell_network_size(chan->wide_circ_ids);
2154 else
2155 cell_size = CELL_MAX_NETWORK_SIZE;
2156
2157 /* If we know the channel, find out if it's IPv6. */
2158 tor_addr_t remote_addr;
2159 bool is_ipv6 = chan &&
2160 channel_get_addr_if_possible(chan, &remote_addr) &&
2161 tor_addr_family(&remote_addr) == AF_INET6;
2162
2163 /* The missing written bytes are the cell counts times their cell
2164 * size plus TLS per cell overhead */
2165 written_sync = cells*(cell_size+TLS_PER_CELL_OVERHEAD);
2166
2167 /* Report the missing bytes as written, to avoid asymmetry.
2168 * We must use time() for consistency with rephist, even though on
2169 * some very old rare platforms, approx_time() may be faster. */
2170 bwhist_note_bytes_written(written_sync, time(NULL), is_ipv6);
2171}
2172
2173/** Mark <b>circ</b> to be closed next time we call
2174 * circuit_close_all_marked(). Do any cleanup needed:
2175 * - If state is CHAN_WAIT, remove circ from circuits_pending_chans.
2176 * - If state is onionskin_pending, remove circ from the onion_pending
2177 * list.
2178 * - If circ isn't open yet: call circuit_build_failed() if we're
2179 * the origin.
2180 * - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
2181 * failure we just had to the hidden service client module.
2182 * - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
2183 * report to the hidden service client module that the intro point
2184 * we just tried may be unreachable.
2185 * - Send appropriate destroys and edge_destroys for conns and
2186 * streams attached to circ.
2187 * - If circ->rend_splice is set (we are the midpoint of a joined
2188 * rendezvous stream), then mark the other circuit to close as well.
2189 */
2190MOCK_IMPL(void,
2191circuit_mark_for_close_, (circuit_t *circ, int reason, int line,
2192 const char *file))
2193{
2194 int orig_reason = reason; /* Passed to the controller */
2195 assert_circuit_ok(circ);
2196 tor_assert(line);
2197 tor_assert(file);
2198
2199 if (reason == END_CIRC_REASON_TORPROTOCOL) {
2201 }
2202
2203 /* Check whether the circuitpadding subsystem wants to block this close */
2204 if (circpad_marked_circuit_for_padding(circ, reason)) {
2205 return;
2206 }
2207
2208 if (circ->marked_for_close) {
2209 log_warn(LD_BUG,
2210 "Duplicate call to circuit_mark_for_close at %s:%d"
2211 " (first at %s:%d)", file, line,
2213 return;
2214 }
2215 if (reason == END_CIRC_AT_ORIGIN) {
2216 if (!CIRCUIT_IS_ORIGIN(circ)) {
2217 log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
2218 "but circuit was not at origin. (called %s:%d, purpose=%d)",
2219 file, line, circ->purpose);
2220 }
2221 reason = END_CIRC_REASON_NONE;
2222 }
2223
2224 if (CIRCUIT_IS_ORIGIN(circ)) {
2225 if (pathbias_check_close(TO_ORIGIN_CIRCUIT(circ), reason) == -1) {
2226 /* Don't close it yet, we need to test it first */
2227 return;
2228 }
2229
2230 /* We don't send reasons when closing circuits at the origin. */
2231 reason = END_CIRC_REASON_NONE;
2232 }
2233
2234 /* If a callback above (e.g. pathbias probing failing to send on a full
2235 * queue) recursively called circuit_mark_for_close on this circuit, it is
2236 * already marked and on circuits_pending_close. Bail out to avoid
2237 * performing cleanup twice. */
2238 if (circ->marked_for_close) {
2239 return;
2240 }
2241
2242 circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_N_CHAN);
2243 circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_P_CHAN);
2244
2245 if (reason & END_CIRC_REASON_FLAG_REMOTE)
2246 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
2247
2248 if (reason < END_CIRC_REASON_MIN_ || reason > END_CIRC_REASON_MAX_) {
2249 if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
2250 log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
2251 reason = END_CIRC_REASON_NONE;
2252 }
2253
2254 circ->marked_for_close = line;
2255 circ->marked_for_close_file = file;
2256 circ->marked_for_close_reason = reason;
2257 circ->marked_for_close_orig_reason = orig_reason;
2258
2259 /* Marked circuits must not remain on the pending channel list (waiting for a
2260 * n_chan) even before the deferred cleanup in circuit_about_to_free(). */
2261 if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
2264 }
2265 }
2266
2267 if (!CIRCUIT_IS_ORIGIN(circ)) {
2268 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2269 if (or_circ->rend_splice) {
2270 if (!or_circ->rend_splice->base_.marked_for_close) {
2271 /* do this after marking this circuit, to avoid infinite recursion. */
2272 circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
2273 }
2274 or_circ->rend_splice = NULL;
2275 }
2276 }
2277
2278 /* Notify the HS subsystem that this circuit is closing. */
2280
2281 /* Specific actions if this is a conflux related circuit. */
2282 if (CIRCUIT_IS_CONFLUX(circ)) {
2284 }
2285
2286 /* Update stats. */
2287 if (circ->ccontrol) {
2288 if (circ->ccontrol->in_slow_start) {
2289 /* If we are in slow start, only count the ss cwnd if we've sent
2290 * enough data to get RTT measurements such that we have a min
2291 * and a max RTT, and they are not the same. This prevents us from
2292 * averaging and reporting unused and low-use circuits here */
2293 if (circ->ccontrol->max_rtt_usec != circ->ccontrol->min_rtt_usec) {
2295 stats_update_running_avg(cc_stats_circ_close_ss_cwnd_ma,
2296 circ->ccontrol->cwnd);
2297 }
2298 } else {
2300 stats_update_running_avg(cc_stats_circ_close_cwnd_ma,
2301 circ->ccontrol->cwnd);
2302 }
2303 cc_stats_circs_closed++;
2304 }
2305
2306 if (circuits_pending_close == NULL)
2308
2311
2312 log_info(LD_GENERAL, "Circuit %u (id: %" PRIu32 ") marked for close at "
2313 "%s:%d (orig reason: %d, new reason: %d)",
2314 circ->n_circ_id,
2315 CIRCUIT_IS_ORIGIN(circ) ?
2316 TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0,
2317 file, line, orig_reason, reason);
2318 tor_trace(TR_SUBSYS(circuit), TR_EV(mark_for_close), circ);
2319}
2320
2321/** Called immediately before freeing a marked circuit <b>circ</b> from
2322 * circuit_free_all() while shutting down Tor; this is a safe-at-shutdown
2323 * version of circuit_about_to_free(). It's important that it at least
2324 * do circuitmux_detach_circuit() when appropriate.
2325 */
2326static void
2328{
2329 /* Cleanup conflux specifics. */
2331
2332 if (circ->n_chan) {
2333 circuit_clear_cell_queue(circ, circ->n_chan);
2335 circuit_set_n_circid_chan(circ, 0, NULL);
2336 }
2337
2338 if (! CIRCUIT_IS_ORIGIN(circ)) {
2339 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2340
2341 if (or_circ->p_chan) {
2342 circuit_clear_cell_queue(circ, or_circ->p_chan);
2343 circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
2344 circuit_set_p_circid_chan(or_circ, 0, NULL);
2345 }
2346 }
2347}
2348
2349/** Called immediately before freeing a marked circuit <b>circ</b>.
2350 * Disconnects the circuit from other data structures, launches events
2351 * as appropriate, and performs other housekeeping.
2352 */
2353static void
2355{
2356
2357 int reason = circ->marked_for_close_reason;
2358 int orig_reason = circ->marked_for_close_orig_reason;
2359
2360 /* Cleanup conflux specifics. */
2362
2365 }
2366 /* If the circuit ever became OPEN, we sent it to the reputation history
2367 * module then. If it isn't OPEN, we send it there now to remember which
2368 * links worked and which didn't.
2369 */
2370 if (circ->state != CIRCUIT_STATE_OPEN &&
2372 if (CIRCUIT_IS_ORIGIN(circ)) {
2373 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
2374 circuit_build_failed(ocirc); /* take actions if necessary */
2375 }
2376 }
2379 }
2380 if (CIRCUIT_IS_ORIGIN(circ)) {
2382 (circ->state == CIRCUIT_STATE_OPEN ||
2384 CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
2385 orig_reason);
2386 }
2387
2388 if (circ->n_chan) {
2389 circuit_clear_cell_queue(circ, circ->n_chan);
2390 /* Only send destroy if the channel isn't closing anyway */
2391 if (!CHANNEL_CONDEMNED(circ->n_chan)) {
2392 channel_send_destroy(circ->n_circ_id, circ->n_chan, reason);
2393 }
2395 circuit_set_n_circid_chan(circ, 0, NULL);
2396 }
2397
2398 if (! CIRCUIT_IS_ORIGIN(circ)) {
2399 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2400 edge_connection_t *conn;
2401
2402 for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
2403 connection_edge_destroy(or_circ->p_circ_id, conn);
2404 or_circ->n_streams = NULL;
2405
2406 while (or_circ->resolving_streams) {
2407 conn = or_circ->resolving_streams;
2408 or_circ->resolving_streams = conn->next_stream;
2409 if (!conn->base_.marked_for_close) {
2410 /* The client will see a DESTROY, and infer that the connections
2411 * are closing because the circuit is getting torn down. No need
2412 * to send an end cell. */
2413 conn->edge_has_sent_end = 1;
2414 conn->end_reason = END_STREAM_REASON_DESTROY;
2416 connection_mark_for_close(TO_CONN(conn));
2417 }
2418 conn->on_circuit = NULL;
2419 }
2420
2421 if (or_circ->p_chan) {
2422 circuit_clear_cell_queue(circ, or_circ->p_chan);
2423 /* Only send destroy if the channel isn't closing anyway */
2424 if (!CHANNEL_CONDEMNED(or_circ->p_chan)) {
2425 channel_send_destroy(or_circ->p_circ_id, or_circ->p_chan, reason);
2426 }
2427 circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
2428 circuit_set_p_circid_chan(or_circ, 0, NULL);
2429 }
2430
2431 if (or_circ->n_cells_discarded_at_end) {
2432 time_t age = approx_time() - circ->timestamp_created.tv_sec;
2434 age, or_circ->n_cells_discarded_at_end);
2435 }
2436 } else {
2437 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
2438 edge_connection_t *conn;
2439 for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
2441 ocirc->p_streams = NULL;
2442 }
2443}
2444
2445/** Given a marked circuit <b>circ</b>, aggressively free its cell queues to
2446 * recover memory. */
2447static void
2449{
2450 if (!circ->marked_for_close) {
2451 log_warn(LD_BUG, "Called on non-marked circuit");
2452 return;
2453 }
2455 if (! CIRCUIT_IS_ORIGIN(circ)) {
2456 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
2458 }
2459}
2460
2461static size_t
2462single_conn_free_bytes(connection_t *conn)
2463{
2464 size_t result = 0;
2465 if (conn->inbuf) {
2466 result += buf_allocation(conn->inbuf);
2467 buf_clear(conn->inbuf);
2468 }
2469 if (conn->outbuf) {
2470 result += buf_allocation(conn->outbuf);
2471 buf_clear(conn->outbuf);
2472 }
2473 if (conn->type == CONN_TYPE_DIR) {
2474 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
2475 if (dir_conn->compress_state) {
2476 result += tor_compress_state_size(dir_conn->compress_state);
2477 tor_compress_free(dir_conn->compress_state);
2478 dir_conn->compress_state = NULL;
2479 }
2480 }
2481 return result;
2482}
2483
2484/** Aggressively free buffer contents on all the buffers of all streams in the
2485 * list starting at <b>stream</b>. Return the number of bytes recovered. */
2486static size_t
2488{
2489 size_t result = 0;
2490 for ( ; stream; stream = stream->next_stream) {
2491 connection_t *conn = TO_CONN(stream);
2492 result += single_conn_free_bytes(conn);
2493 if (conn->linked_conn) {
2494 result += single_conn_free_bytes(conn->linked_conn);
2495 }
2496 }
2497 return result;
2498}
2499
2500/** Aggressively free buffer contents on all the buffers of all streams on
2501 * circuit <b>c</b>. Return the number of bytes recovered. */
2502static size_t
2504{
2505 if (CIRCUIT_IS_ORIGIN(c)) {
2507 } else {
2509 }
2510}
2511
2512/** Return the number of cells used by the circuit <b>c</b>'s cell queues. */
2513STATIC size_t
2515{
2516 size_t n = c->n_chan_cells.n;
2517 if (! CIRCUIT_IS_ORIGIN(c)) {
2518 circuit_t *cc = (circuit_t *) c;
2519 n += TO_OR_CIRCUIT(cc)->p_chan_cells.n;
2520 }
2521 return n;
2522}
2523
2524/** Return the number of bytes allocated for <b>c</b>'s half-open streams. */
2525static size_t
2527{
2528 if (! CIRCUIT_IS_ORIGIN(c)) {
2529 return 0;
2530 }
2531 const origin_circuit_t *ocirc = CONST_TO_ORIGIN_CIRCUIT(c);
2532 if (ocirc->half_streams)
2533 return smartlist_len(ocirc->half_streams) * sizeof(half_edge_t);
2534 else
2535 return 0;
2536}
2537
2538/**
2539 * Return the age of the oldest cell queued on <b>c</b>, in timestamp units.
2540 * Return 0 if there are no cells queued on c. Requires that <b>now</b> be
2541 * the current coarse timestamp.
2542 *
2543 * This function will return incorrect results if the oldest cell queued on
2544 * the circuit is older than about 2**32 msec (about 49 days) old.
2545 */
2546STATIC uint32_t
2548{
2549 uint32_t age = 0;
2550 packed_cell_t *cell;
2551
2552 if (NULL != (cell = TOR_SIMPLEQ_FIRST(&c->n_chan_cells.head)))
2553 age = now - cell->inserted_timestamp;
2554
2555 if (! CIRCUIT_IS_ORIGIN(c)) {
2556 const or_circuit_t *orcirc = CONST_TO_OR_CIRCUIT(c);
2557 if (NULL != (cell = TOR_SIMPLEQ_FIRST(&orcirc->p_chan_cells.head))) {
2558 uint32_t age2 = now - cell->inserted_timestamp;
2559 if (age2 > age)
2560 return age2;
2561 }
2562 }
2563 return age;
2564}
2565
2566/** Return the age of the oldest buffer chunk on <b>conn</b>, where age is
2567 * taken in timestamp units before the time <b>now</b>. If the connection has
2568 * no data, treat it as having age zero.
2569 **/
2570static uint32_t
2571conn_get_buffer_age(const connection_t *conn, uint32_t now_ts)
2572{
2573 uint32_t age = 0, age2;
2574 if (conn->outbuf) {
2575 age2 = buf_get_oldest_chunk_timestamp(conn->outbuf, now_ts);
2576 if (age2 > age)
2577 age = age2;
2578 }
2579 if (conn->inbuf) {
2580 age2 = buf_get_oldest_chunk_timestamp(conn->inbuf, now_ts);
2581 if (age2 > age)
2582 age = age2;
2583 }
2584 return age;
2585}
2586
2587/** Return the age in timestamp units of the oldest buffer chunk on any stream
2588 * in the linked list <b>stream</b>, where age is taken in timestamp units
2589 * before the timestamp <b>now</b>. */
2590static uint32_t
2592{
2593 uint32_t age = 0, age2;
2594 for (; stream; stream = stream->next_stream) {
2595 const connection_t *conn = TO_CONN(stream);
2596 age2 = conn_get_buffer_age(conn, now);
2597 if (age2 > age)
2598 age = age2;
2599 if (conn->linked_conn) {
2600 age2 = conn_get_buffer_age(conn->linked_conn, now);
2601 if (age2 > age)
2602 age = age2;
2603 }
2604 }
2605 return age;
2606}
2607
2608/** Return the age in timestamp units of the oldest buffer chunk on any stream
2609 * attached to the circuit <b>c</b>, where age is taken before the timestamp
2610 * <b>now</b>. */
2611STATIC uint32_t
2613{
2614 if (CIRCUIT_IS_ORIGIN(c)) {
2616 CONST_TO_ORIGIN_CIRCUIT(c)->p_streams, now);
2617 } else {
2619 CONST_TO_OR_CIRCUIT(c)->n_streams, now);
2620 }
2621}
2622
2623/** Return the age of the oldest cell or stream buffer chunk on the circuit
2624 * <b>c</b>, where age is taken in timestamp units before the timestamp
2625 * <b>now</b> */
2626STATIC uint32_t
2628{
2629 uint32_t cell_age = circuit_max_queued_cell_age(c, now);
2630 uint32_t data_age = circuit_max_queued_data_age(c, now);
2631 if (cell_age > data_age)
2632 return cell_age;
2633 else
2634 return data_age;
2635}
2636
2637/** Helper to sort a list of circuit_t by age of oldest item, in descending
2638 * order. */
2639static int
2640circuits_compare_by_oldest_queued_item_(const void **a_, const void **b_)
2641{
2642 const circuit_t *a = *a_;
2643 const circuit_t *b = *b_;
2644 uint32_t age_a = a->age_tmp;
2645 uint32_t age_b = b->age_tmp;
2646
2647 if (age_a < age_b)
2648 return 1;
2649 else if (age_a == age_b)
2650 return 0;
2651 else
2652 return -1;
2653}
2654
2655static uint32_t now_ts_for_buf_cmp;
2656
2657/** Helper to sort a list of circuit_t by age of oldest item, in descending
2658 * order. */
2659static int
2660conns_compare_by_buffer_age_(const void **a_, const void **b_)
2661{
2662 const connection_t *a = *a_;
2663 const connection_t *b = *b_;
2664 time_t age_a = conn_get_buffer_age(a, now_ts_for_buf_cmp);
2665 time_t age_b = conn_get_buffer_age(b, now_ts_for_buf_cmp);
2666
2667 if (age_a < age_b)
2668 return 1;
2669 else if (age_a == age_b)
2670 return 0;
2671 else
2672 return -1;
2673}
2674
2675#define FRACTION_OF_DATA_TO_RETAIN_ON_OOM 0.90
2676
2677/** We're out of memory for cells, having allocated <b>current_allocation</b>
2678 * bytes' worth. Kill the 'worst' circuits until we're under
2679 * FRACTION_OF_DATA_TO_RETAIN_ON_OOM of our maximum usage.
2680 *
2681 * Return the number of bytes removed. */
2682size_t
2683circuits_handle_oom(size_t current_allocation)
2684{
2685 smartlist_t *circlist;
2687 int conn_idx;
2688 size_t mem_to_recover;
2689 size_t mem_recovered=0;
2690 int n_circuits_killed=0;
2691 int n_dirconns_killed=0;
2692 int n_edgeconns_killed = 0;
2693 uint32_t now_ts;
2694 log_notice(LD_GENERAL, "We're low on memory (cell queues total alloc:"
2695 " %"TOR_PRIuSZ" buffer total alloc: %" TOR_PRIuSZ ","
2696 " tor compress total alloc: %" TOR_PRIuSZ
2697 " (zlib: %" TOR_PRIuSZ ", zstd: %" TOR_PRIuSZ ","
2698 " lzma: %" TOR_PRIuSZ "),"
2699 " rendezvous cache total alloc: %" TOR_PRIuSZ "). Killing"
2700 " circuits withover-long queues. (This behavior is controlled by"
2701 " MaxMemInQueues.)",
2702 cell_queues_get_total_allocation(),
2703 buf_get_total_allocation(),
2708 hs_cache_get_total_allocation());
2709 {
2710 size_t mem_target = (size_t)(get_options()->MaxMemInQueues *
2711 FRACTION_OF_DATA_TO_RETAIN_ON_OOM);
2712 if (current_allocation <= mem_target)
2713 return 0;
2714 mem_to_recover = current_allocation - mem_target;
2715 }
2716
2717 now_ts = monotime_coarse_get_stamp();
2718
2719 circlist = circuit_get_global_list();
2720 SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
2721 circ->age_tmp = circuit_max_queued_item_age(circ, now_ts);
2722 } SMARTLIST_FOREACH_END(circ);
2723
2724 /* This is O(n log n); there are faster algorithms we could use instead.
2725 * Let's hope this doesn't happen enough to be in the critical path. */
2727
2728 /* Fix up the indices before we run into trouble */
2729 SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
2730 circ->global_circuitlist_idx = circ_sl_idx;
2731 } SMARTLIST_FOREACH_END(circ);
2732
2733 /* Now sort the connection array ... */
2734 now_ts_for_buf_cmp = now_ts;
2736 now_ts_for_buf_cmp = 0;
2737
2738 /* Fix up the connection array to its new order. */
2740 conn->conn_array_index = conn_sl_idx;
2741 } SMARTLIST_FOREACH_END(conn);
2742
2743 /* Okay, now the worst circuits and connections are at the front of their
2744 * respective lists. Let's mark them, and reclaim their storage
2745 * aggressively. */
2746 conn_idx = 0;
2747 SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
2748 size_t n;
2749 size_t freed;
2750
2751 /* Free storage in any non-linked directory connections that have buffered
2752 * data older than this circuit. */
2753 while (conn_idx < smartlist_len(connection_array)) {
2754 connection_t *conn = smartlist_get(connection_array, conn_idx);
2755 uint32_t conn_age = conn_get_buffer_age(conn, now_ts);
2756 if (conn_age < circ->age_tmp) {
2757 break;
2758 }
2759 /* Also consider edge connections so we don't accumulate bytes on the
2760 * outbuf due to a malicious destination holding off the read on us. */
2761 if ((conn->type == CONN_TYPE_DIR && conn->linked_conn == NULL) ||
2762 CONN_IS_EDGE(conn)) {
2763 if (!conn->marked_for_close) {
2764 if (CONN_IS_EDGE(conn)) {
2765 TO_EDGE_CONN(conn)->end_reason = END_STREAM_REASON_RESOURCELIMIT;
2766 }
2767 connection_mark_for_close(conn);
2768 }
2769 mem_recovered += single_conn_free_bytes(conn);
2770
2771 if (conn->type == CONN_TYPE_DIR) {
2772 ++n_dirconns_killed;
2773 } else {
2774 ++n_edgeconns_killed;
2775 }
2776
2777 if (mem_recovered >= mem_to_recover)
2778 goto done_recovering_mem;
2779 }
2780 ++conn_idx;
2781 }
2782
2783 /* Now, kill the circuit. */
2784 n = n_cells_in_circ_queues(circ);
2785 const size_t half_stream_alloc = circuit_alloc_in_half_streams(circ);
2786 if (! circ->marked_for_close) {
2787 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
2788 }
2791
2792 ++n_circuits_killed;
2793
2794 mem_recovered += n * packed_cell_mem_cost();
2795 mem_recovered += half_stream_alloc;
2796 mem_recovered += freed;
2797 mem_recovered += conflux_get_circ_bytes_allocation(circ);
2798
2799 if (mem_recovered >= mem_to_recover)
2800 goto done_recovering_mem;
2801 } SMARTLIST_FOREACH_END(circ);
2802
2803 done_recovering_mem:
2804 log_notice(LD_GENERAL, "Removed %"TOR_PRIuSZ" bytes by killing %d circuits; "
2805 "%d circuits remain alive. Also killed %d non-linked directory "
2806 "connections. Killed %d edge connections",
2807 mem_recovered,
2808 n_circuits_killed,
2809 smartlist_len(circlist) - n_circuits_killed,
2810 n_dirconns_killed,
2811 n_edgeconns_killed);
2812
2813 return mem_recovered;
2814}
2815
2816/** Verify that circuit <b>c</b> has all of its invariants
2817 * correct. Trigger an assert if anything is invalid.
2818 */
2819MOCK_IMPL(void,
2821{
2822 edge_connection_t *conn;
2823 const or_circuit_t *or_circ = NULL;
2824 const origin_circuit_t *origin_circ = NULL;
2825
2826 tor_assert(c);
2828 tor_assert(c->purpose >= CIRCUIT_PURPOSE_MIN_ &&
2829 c->purpose <= CIRCUIT_PURPOSE_MAX_);
2830
2831 if (CIRCUIT_IS_ORIGIN(c))
2832 origin_circ = CONST_TO_ORIGIN_CIRCUIT(c);
2833 else
2834 or_circ = CONST_TO_OR_CIRCUIT(c);
2835
2836 if (c->n_chan) {
2837 tor_assert(!c->n_hop);
2838
2839 if (c->n_circ_id) {
2840 /* We use the _impl variant here to make sure we don't fail on marked
2841 * circuits, which would not be returned by the regular function. */
2843 c->n_chan, NULL);
2844 tor_assert(c == c2);
2845 }
2846 }
2847 if (or_circ && or_circ->p_chan) {
2848 if (or_circ->p_circ_id) {
2849 /* ibid */
2850 circuit_t *c2 =
2852 or_circ->p_chan, NULL);
2853 tor_assert(c == c2);
2854 }
2855 }
2856 if (or_circ)
2857 for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
2858 tor_assert(conn->base_.type == CONN_TYPE_EXIT);
2859
2860 tor_assert(c->deliver_window >= 0);
2861 tor_assert(c->package_window >= 0);
2862 if (c->state == CIRCUIT_STATE_OPEN ||
2865 if (or_circ) {
2866 relay_crypto_assert_ok(&or_circ->crypto);
2867 }
2868 }
2872 } else {
2875 }
2876 if (origin_circ && origin_circ->cpath) {
2877 cpath_assert_ok(origin_circ->cpath);
2878 }
2880 tor_assert(or_circ);
2881 if (!c->marked_for_close) {
2882 tor_assert(or_circ->rend_splice);
2883 tor_assert(or_circ->rend_splice->rend_splice == or_circ);
2884 }
2885 tor_assert(or_circ->rend_splice != or_circ);
2886 } else {
2887 tor_assert(!or_circ || !or_circ->rend_splice);
2888 }
2889}
2890
2891/** Return true iff the circuit queue for the given direction is full that is
2892 * above the high watermark. */
2893bool
2895{
2896 int queue_size;
2897
2898 tor_assert(circ);
2899
2900 /* Gather objects we need based on cell direction. */
2901 if (direction == CELL_DIRECTION_OUT) {
2902 /* Outbound. */
2903 queue_size = circ->n_chan_cells.n;
2904 } else {
2905 /* Inbound. */
2906 queue_size = CONST_TO_OR_CIRCUIT(circ)->p_chan_cells.n;
2907 }
2908
2909 /* Then check if our cell queue has reached its high watermark as in its
2910 * upper limit. This is so we avoid too much memory pressure by queuing a
2911 * large amount of cells. */
2912 return queue_size >= cell_queue_highwatermark();
2913}
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition address.h:189
time_t approx_time(void)
Definition approx_time.c:32
void buf_clear(buf_t *buf)
Definition buffers.c:381
size_t buf_allocation(const buf_t *buf)
Definition buffers.c:401
uint32_t buf_get_oldest_chunk_timestamp(const buf_t *buf, uint32_t now)
Definition buffers.c:506
Header file for buffers.c.
void bwhist_note_bytes_written(uint64_t num_bytes, time_t when, bool ipv6)
Definition bwhist.c:164
Header for feature/stats/bwhist.c.
int channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
Definition channel.c:3364
int channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
Definition channel.c:2100
int channel_get_addr_if_possible(const channel_t *chan, tor_addr_t *addr_out)
Definition channel.c:2929
const char * channel_describe_peer(channel_t *chan)
Definition channel.c:2909
Header file for channel.c.
Header file for channeltls.c.
int pathbias_check_close(origin_circuit_t *ocirc, int reason)
#define DEAD_CIRCUIT_MAGIC
Definition circuit_st.h:37
#define ORIGIN_CIRCUIT_MAGIC
Definition circuit_st.h:31
#define OR_CIRCUIT_MAGIC
Definition circuit_st.h:33
void circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
int route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
Header file for circuitbuild.c.
static circuit_t * circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan, int *found_entry_out)
STATIC uint32_t circuit_max_queued_item_age(const circuit_t *c, uint32_t now)
static int chan_circid_entries_eq_(chan_circid_circuit_map_t *a, chan_circid_circuit_map_t *b)
static uint32_t circuit_get_streams_max_data_age(const edge_connection_t *stream, uint32_t now)
STATIC void circuit_free_(circuit_t *circ)
void circuit_close_all_marked(void)
const char * circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
void circuit_mark_for_close_(circuit_t *circ, int reason, int line, const char *file)
static smartlist_t * global_circuitlist
int circuit_any_opened_circuits_cached(void)
void channel_note_destroy_pending(channel_t *chan, circid_t id)
static int any_opened_circs_cached_val
uint64_t circ_n_proto_violation
circuit_t * circuit_get_by_circid_channel_even_if_marked(circid_t circ_id, channel_t *chan)
void circuit_set_p_circid_chan(or_circuit_t *or_circ, circid_t id, channel_t *chan)
origin_circuit_t * circuit_get_next_by_purpose(origin_circuit_t *start, uint8_t purpose)
int circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
STATIC size_t n_cells_in_circ_queues(const circuit_t *c)
static void circuit_dump_conn_details(int severity, circuit_t *circ, int conn_array_index, const char *type, circid_t this_circid, circid_t other_circid)
or_circuit_t * or_circuit_new(circid_t p_circ_id, channel_t *p_chan)
void circuit_synchronize_written_or_bandwidth(const circuit_t *c, circuit_channel_direction_t dir)
void circuit_set_n_circid_chan(circuit_t *circ, circid_t id, channel_t *chan)
double cc_stats_circ_close_ss_cwnd_ma
static void init_circuit_base(circuit_t *circ)
static uint32_t conn_get_buffer_age(const connection_t *conn, uint32_t now_ts)
void circuit_mark_all_dirty_circs_as_unusable(void)
static int circuits_compare_by_oldest_queued_item_(const void **a_, const void **b_)
void circuit_clear_cpath(origin_circuit_t *circ)
void circuit_set_state(circuit_t *circ, uint8_t state)
void circuit_free_all(void)
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
smartlist_t * circuit_find_circuits_to_upgrade_from_guard_wait(void)
origin_circuit_t * circuit_get_next_intro_circ(const origin_circuit_t *start, bool want_client_circ)
origin_circuit_t * circuit_get_by_global_id(uint32_t id)
origin_circuit_t * origin_circuit_new(void)
static unsigned int chan_circid_entry_hash_(chan_circid_circuit_map_t *a)
void channel_mark_circid_unusable(channel_t *chan, circid_t id)
void circuit_dump_by_conn(connection_t *conn, int severity)
int circuit_any_opened_circuits(void)
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
STATIC uint32_t circuit_max_queued_data_age(const circuit_t *c, uint32_t now)
int circuit_get_cpath_len(origin_circuit_t *circ)
void channel_mark_circid_usable(channel_t *chan, circid_t id)
static smartlist_t * circuits_pending_close
int circuit_get_cpath_opened_len(const origin_circuit_t *circ)
const char * circuit_purpose_to_controller_string(uint8_t purpose)
void assert_circuit_ok(const circuit_t *c)
static void circuit_remove_from_origin_circuit_list(origin_circuit_t *origin_circ)
static smartlist_t * circuits_pending_other_guards
const char * circuit_state_to_string(int state)
static size_t marked_circuit_free_stream_bytes(circuit_t *c)
int circuit_count_pending_on_channel(channel_t *chan)
STATIC uint32_t circuit_max_queued_cell_age(const circuit_t *c, uint32_t now)
static int conns_compare_by_buffer_age_(const void **a_, const void **b_)
size_t circuits_handle_oom(size_t current_allocation)
void circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
static void circuit_about_to_free(circuit_t *circ)
int circuit_event_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
static void circuit_about_to_free_atexit(circuit_t *circ)
static size_t marked_circuit_streams_free_bytes(edge_connection_t *stream)
time_t circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
void circuit_cache_opened_circuit_state(int circuits_are_opened)
#define DFLT_IDLE_TIMEOUT_WHILE_LEARNING
origin_circuit_t * circuit_get_next_service_rp_circ(origin_circuit_t *start)
circuit_t * circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
static void circuit_add_to_origin_circuit_list(origin_circuit_t *origin_circ)
double cc_stats_circ_close_cwnd_ma
static smartlist_t * circuits_pending_chans
crypt_path_t * circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
origin_circuit_t * circuit_find_to_cannibalize(uint8_t purpose_to_produce, extend_info_t *info, int flags)
const char * circuit_purpose_to_string(uint8_t purpose)
static uint8_t get_circuit_purpose_needed_to_cannibalize(uint8_t purpose)
void channel_note_destroy_not_pending(channel_t *chan, circid_t id)
static void circuit_state_publish(const circuit_t *circ)
void circuit_clear_testing_cell_stats(circuit_t *circ)
static size_t circuit_alloc_in_half_streams(const circuit_t *c)
smartlist_t * circuit_get_global_origin_circuit_list(void)
bool circuit_is_queue_full(const circuit_t *circ, cell_direction_t direction)
smartlist_t * circuit_get_global_list(void)
void circuit_unlink_all_from_channel(channel_t *chan, int reason)
static void marked_circuit_free_cells(circuit_t *circ)
static smartlist_t * global_origin_circuit_list
void circuit_mark_all_unused_circs(void)
int32_t circuit_initial_package_window(void)
Header file for circuitlist.c.
#define CIRCUIT_PURPOSE_S_CONNECT_REND
#define CIRCUIT_STATE_ONIONSKIN_PENDING
Definition circuitlist.h:23
#define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
Definition circuitlist.h:93
#define CIRCUIT_PURPOSE_REND_POINT_WAITING
Definition circuitlist.h:45
#define CIRCUIT_PURPOSE_PATH_BIAS_TESTING
#define CIRCUIT_STATE_OPEN
Definition circuitlist.h:32
#define CIRCUIT_IS_ORCIRC(c)
#define CIRCUIT_PURPOSE_IS_ORIGIN(p)
#define CIRCUIT_STATE_BUILDING
Definition circuitlist.h:21
#define CIRCUIT_PURPOSE_C_REND_JOINED
Definition circuitlist.h:88
#define CIRCUIT_PURPOSE_S_INTRO
#define CIRCUIT_PURPOSE_INTRO_POINT
Definition circuitlist.h:42
#define CIRCUIT_PURPOSE_CONTROLLER
#define CIRCUIT_IS_ORIGIN(c)
#define CIRCUIT_PURPOSE_C_CIRCUIT_PADDING
Definition circuitlist.h:95
#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
#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
#define CIRCUIT_PURPOSE_C_REND_READY
Definition circuitlist.h:83
#define CIRCUIT_PURPOSE_S_HSDIR_POST
#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
#define CIRCUIT_PURPOSE_C_ESTABLISH_REND
Definition circuitlist.h:81
#define CIRCUIT_PURPOSE_C_GENERAL
Definition circuitlist.h:70
#define CIRCUIT_PURPOSE_CONFLUX_UNLINKED
#define CIRCUIT_PURPOSE_HS_VANGUARDS
void circuitmux_attach_circuit(circuitmux_t *cmux, circuit_t *circ, cell_direction_t direction)
Definition circuitmux.c:731
void circuitmux_detach_circuit(circuitmux_t *cmux, circuit_t *circ)
Definition circuitmux.c:852
void circpad_circuit_free_all_machineinfos(circuit_t *circ)
int circpad_marked_circuit_for_padding(circuit_t *circ, int reason)
Header file for circuitpadding.c.
circuit_build_times_t * get_circuit_build_times_mutable(void)
const circuit_build_times_t * get_circuit_build_times(void)
int circuit_build_times_disabled(const or_options_t *options)
int circuit_build_times_needs_circuits(const circuit_build_times_t *cbt)
Header file for circuitstats.c.
void circuit_build_failed(origin_circuit_t *circ)
int circuit_should_use_vanguards(uint8_t purpose)
void mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
Header file for circuituse.c.
#define CIRCLAUNCH_NEED_CAPACITY
Definition circuituse.h:47
#define CIRCLAUNCH_ONEHOP_TUNNEL
Definition circuituse.h:43
#define CIRCLAUNCH_IS_INTERNAL
Definition circuituse.h:50
#define CIRCLAUNCH_NEED_UPTIME
Definition circuituse.h:45
uint32_t monotime_coarse_get_stamp(void)
size_t tor_compress_state_size(const tor_compress_state_t *state)
Definition compress.c:669
size_t tor_compress_get_total_allocation(void)
Definition compress.c:488
Headers for compress.c.
size_t tor_lzma_get_total_allocation(void)
Header for compress_lzma.c.
size_t tor_zlib_get_total_allocation(void)
Header for compress_zlib.c.
size_t tor_zstd_get_total_allocation(void)
Header for compress_zstd.c.
const or_options_t * get_options(void)
Definition config.c:949
Header file for config.c.
uint64_t conflux_get_circ_bytes_allocation(const circuit_t *circ)
Definition conflux.c:181
Public APIs for conflux multipath support.
void conflux_circuit_has_closed(circuit_t *circ)
void conflux_circuit_about_to_free(circuit_t *circ)
Header file for conflux_pool.c.
Header file for conflux_util.c.
Public APIs for congestion control.
#define congestion_control_free(cc)
static int32_t cell_queue_highwatermark(void)
Structure definitions for congestion control.
void connection_free_(connection_t *conn)
Definition connection.c:965
Header file for connection.c.
#define CONN_TYPE_DIR
Definition connection.h:55
#define CONN_TYPE_EXIT
Definition connection.h:46
int connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
edge_connection_t * TO_EDGE_CONN(connection_t *c)
Header file for connection_edge.c.
Header file for connection_or.c.
#define CONN_IS_EDGE(x)
int control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
Header file for control_events.c.
Circuit-build-stse structure.
void cpath_assert_ok(const crypt_path_t *cp)
Definition crypt_path.c:84
void cpath_free(crypt_path_t *victim)
Definition crypt_path.c:159
Header file for crypt_path.c.
reference-counting structure for crypt_path_t
Headers for crypto_dh.c.
Common functions for using (pseudo-)random number generators.
int crypto_rand_int(unsigned int max)
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition crypto_util.c:55
Common functions for cryptographic routines.
int tor_memeq(const void *a, const void *b, size_t sz)
Definition di_ops.c:107
#define tor_memneq(a, b, sz)
Definition di_ops.h:21
#define DIGEST_LEN
Client/server directory connection structure.
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition directory.c:89
Header file for directory.c.
Edge-connection structure.
void entry_guard_cancel(circuit_guard_state_t **guard_state_p)
int entry_guards_upgrade_waiting_circuits(guard_selection_t *gs, const smartlist_t *all_circuits_in, smartlist_t *newly_complete_out)
int entry_guard_could_succeed(const circuit_guard_state_t *guard_state)
guard_selection_t * get_guard_selection_info(void)
Definition entrynodes.c:313
Header file for circuitbuild.c.
#define TR_SUBSYS(name)
Definition events.h:45
Extend-info structure.
Header for core/or/extendinfo.c.
Half-open connection structure.
Header file for hs_cache.c.
void hs_circ_cleanup_on_close(circuit_t *circ)
void hs_circ_cleanup_on_free(circuit_t *circ)
Header file containing circuit data for the whole HS subsystem.
Header file for hs_circuitmap.c.
Header file containing circuit and connection identifier data for the whole HS subsystem.
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 LD_BUG
Definition log.h:86
#define LD_GENERAL
Definition log.h:62
#define LD_CIRC
Definition log.h:82
#define LOG_WARN
Definition log.h:53
smartlist_t * get_connection_array(void)
Definition mainloop.c:444
STATIC smartlist_t * connection_array
Definition mainloop.c:165
void mainloop_schedule_postloop_cleanup(void)
Definition mainloop.c:1658
Header file for mainloop.c.
void * tor_reallocarray_(void *ptr, size_t sz1, size_t sz2)
Definition malloc.c:146
void tor_free_(void *mem)
Definition malloc.c:227
#define tor_free(p)
Definition malloc.h:56
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
Header file for networkstatus.c.
const node_t * node_get_by_id(const char *identity_digest)
Definition nodelist.c:226
int nodes_in_same_family(const node_t *node1, const node_t *node2)
Definition nodelist.c:2230
Header file for nodelist.c.
Header file for ocirc_event.c.
circuit_status_event_t
Definition ocirc_event.h:19
Header file for onion_crypto.c.
Header file for onion_fast.c.
void onion_pending_remove(or_circuit_t *circ)
Header file for onion_queue.c.
Master header file for Tor-specific functionality.
#define DEFAULT_ROUTE_LEN
Definition or.h:1005
#define MAX_RELAY_EARLY_CELLS_PER_CIRCUIT
Definition or.h:940
#define CELL_MAX_NETWORK_SIZE
Definition or.h:532
uint32_t circid_t
Definition or.h:588
#define TO_CIRCUIT(x)
Definition or.h:951
#define CIRCWINDOW_START
Definition or.h:446
#define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
Definition or.h:342
#define TO_CONN(c)
Definition or.h:709
#define END_CIRC_REASON_FLAG_REMOTE
Definition or.h:393
cell_direction_t
Definition or.h:427
@ CELL_DIRECTION_OUT
Definition or.h:429
@ CELL_DIRECTION_IN
Definition or.h:428
#define DOWNCAST(to, ptr)
Definition or.h:109
#define END_CIRC_AT_ORIGIN
Definition or.h:370
circuit_channel_direction_t
Definition or.h:439
Origin circuit structure.
Header file for policies.c.
int predicted_ports_prediction_time_remaining(time_t now)
Header file for predict_ports.c.
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition printf.c:27
void channel_unlink_all_circuits(channel_t *chan, smartlist_t *circuits_out)
Definition relay.c:3069
void circuit_reset_sendme_randomness(circuit_t *circ)
Definition relay.c:2231
void cell_queue_clear(cell_queue_t *queue)
Definition relay.c:2775
void circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
Definition relay.c:3582
void cell_queue_init(cell_queue_t *queue)
Definition relay.c:2767
size_t packed_cell_mem_cost(void)
Definition relay.c:2868
Header file for relay.c.
Header for relay_crypto.c.
Header file for rendcommon.c.
void rep_hist_buffer_stats_add_circ(circuit_t *circ, time_t end_of_interval)
Definition rephist.c:1872
Header file for rephist.c.
Header file for routerlist.c.
int routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
Definition routerset.c:308
Header file for routerset.c.
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition smartlist.c:334
void smartlist_sort_pointers(smartlist_t *sl)
Definition smartlist.c:594
int smartlist_contains(const smartlist_t *sl, const void *element)
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_clear(smartlist_t *sl)
void smartlist_remove(smartlist_t *sl, const void *element)
void smartlist_del(smartlist_t *sl, int idx)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
#define SMARTLIST_DEL_CURRENT(sl, var)
Header for stats.c.
void note_circ_closed_for_unrecognized_cells(time_t n_seconds, uint32_t n_cells)
Definition status.c:172
Header for status.c.
enum channel_t::@9 reason_for_closing
time_t timestamp_last_had_circuits
Definition channel.h:454
unsigned int num_n_circuits
Definition channel.h:411
char identity_digest[DIGEST_LEN]
Definition channel.h:379
uint64_t global_identifier
Definition channel.h:198
circuitmux_t * cmux
Definition channel.h:398
uint32_t age_tmp
Definition circuit_st.h:170
unsigned int p_delete_pending
Definition circuit_st.h:99
int marked_for_close_reason
Definition circuit_st.h:217
uint8_t state
Definition circuit_st.h:111
int global_circuitlist_idx
Definition circuit_st.h:227
int marked_for_close_orig_reason
Definition circuit_st.h:221
struct create_cell_t * n_chan_create_cell
Definition circuit_st.h:173
time_t timestamp_dirty
Definition circuit_st.h:207
cell_queue_t n_chan_cells
Definition circuit_st.h:82
uint32_t magic
Definition circuit_st.h:63
smartlist_t * sendme_last_digests
Definition circuit_st.h:158
uint16_t marked_for_close
Definition circuit_st.h:209
const struct crypt_path_t * sendme_digest_hop
Definition circuit_st.h:167
uint8_t purpose
Definition circuit_st.h:112
const char * marked_for_close_file
Definition circuit_st.h:212
unsigned int n_delete_pending
Definition circuit_st.h:102
struct timeval timestamp_began
Definition circuit_st.h:185
int deliver_window
Definition circuit_st.h:122
int package_window
Definition circuit_st.h:117
smartlist_t * testing_cell_stats
Definition circuit_st.h:232
struct timeval timestamp_created
Definition circuit_st.h:188
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
struct congestion_control_t * ccontrol
Definition circuit_st.h:269
struct buf_t * inbuf
struct connection_t * linked_conn
unsigned int type
struct buf_t * outbuf
uint16_t marked_for_close
extend_info_t * chosen_exit
struct crypt_path_t * next
extend_info_t * extend_info
struct tor_compress_state_t * compress_state
struct edge_connection_t * next_stream
unsigned int edge_has_sent_end
struct circuit_t * on_circuit
char identity_digest[DIGEST_LEN]
edge_connection_t * resolving_streams
channel_t * p_chan
unsigned int remaining_relay_early_cells
struct workqueue_entry_t * workqueue_entry
uint32_t n_cells_discarded_at_end
circid_t p_circ_id
cell_queue_t p_chan_cells
struct or_circuit_t * rend_splice
edge_connection_t * n_streams
relay_crypto_t crypto
struct routerset_t * ExcludeNodes
struct hs_ident_circuit_t * hs_ident
edge_connection_t * p_streams
unsigned int isolation_values_set
unsigned int remaining_relay_early_cells
smartlist_t * prepend_policy
crypt_path_t * cpath
cpath_build_state_t * build_state
struct circuit_guard_state_t * guard_state
smartlist_t * half_streams
uint32_t inserted_timestamp
Definition or.h:923
#define STATIC
Definition testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
void tor_gettimeofday(struct timeval *timeval)
Integer definitions used throughout Tor.
#define FALLTHROUGH_UNLESS_ALL_BUGS_ARE_FATAL
Definition util_bug.h:268
#define tor_assert(expr)
Definition util_bug.h:103
#define tor_fragile_assert()
Definition util_bug.h:278
int tor_digest_is_zero(const char *digest)
Definition util_string.c:98