math: Replace naughty macro by an inline function
[tor.git] / src / core / or / circuitlist.c
blobd1c734bdd2088d247975c9caa33062178b17e369
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 */
7 /**
8 * \file circuitlist.c
10 * \brief Manage global structures that list and index circuits, and
11 * look up circuits within them.
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.
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.
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().
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().
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.
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().
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 */
56 #include "core/or/or.h"
57 #include "core/or/channel.h"
58 #include "core/or/channeltls.h"
59 #include "feature/client/circpathbias.h"
60 #include "core/or/circuitbuild.h"
61 #include "core/or/circuitlist.h"
62 #include "core/or/circuituse.h"
63 #include "core/or/circuitstats.h"
64 #include "core/or/circuitpadding.h"
65 #include "core/or/crypt_path.h"
66 #include "core/or/extendinfo.h"
67 #include "core/or/status.h"
68 #include "core/or/trace_probes_circuit.h"
69 #include "core/mainloop/connection.h"
70 #include "app/config/config.h"
71 #include "core/or/connection_edge.h"
72 #include "core/or/connection_or.h"
73 #include "feature/control/control_events.h"
74 #include "lib/crypt_ops/crypto_rand.h"
75 #include "lib/crypt_ops/crypto_util.h"
76 #include "lib/crypt_ops/crypto_dh.h"
77 #include "feature/dircommon/directory.h"
78 #include "feature/client/entrynodes.h"
79 #include "core/mainloop/mainloop.h"
80 #include "feature/hs/hs_cache.h"
81 #include "feature/hs/hs_circuit.h"
82 #include "feature/hs/hs_circuitmap.h"
83 #include "feature/hs/hs_ident.h"
84 #include "feature/nodelist/networkstatus.h"
85 #include "feature/nodelist/nodelist.h"
86 #include "feature/relay/onion_queue.h"
87 #include "core/crypto/onion_crypto.h"
88 #include "core/crypto/onion_fast.h"
89 #include "core/or/policies.h"
90 #include "core/or/relay.h"
91 #include "core/crypto/relay_crypto.h"
92 #include "feature/rend/rendcommon.h"
93 #include "feature/stats/predict_ports.h"
94 #include "feature/stats/bwhist.h"
95 #include "feature/stats/rephist.h"
96 #include "feature/nodelist/routerlist.h"
97 #include "feature/nodelist/routerset.h"
98 #include "core/or/channelpadding.h"
99 #include "lib/compress/compress.h"
100 #include "lib/compress/compress_lzma.h"
101 #include "lib/compress/compress_zlib.h"
102 #include "lib/compress/compress_zstd.h"
103 #include "lib/buf/buffers.h"
104 #include "core/or/congestion_control_common.h"
105 #include "core/or/congestion_control_st.h"
106 #include "lib/math/stats.h"
108 #include "core/or/ocirc_event.h"
110 #include "ht.h"
112 #include "core/or/cpath_build_state_st.h"
113 #include "core/or/crypt_path_reference_st.h"
114 #include "feature/dircommon/dir_connection_st.h"
115 #include "core/or/edge_connection_st.h"
116 #include "core/or/half_edge_st.h"
117 #include "core/or/extend_info_st.h"
118 #include "core/or/or_circuit_st.h"
119 #include "core/or/origin_circuit_st.h"
121 /********* START VARIABLES **********/
123 /** A global list of all circuits at this hop. */
124 static smartlist_t *global_circuitlist = NULL;
126 /** A global list of all origin circuits. Every element of this is also
127 * an element of global_circuitlist. */
128 static smartlist_t *global_origin_circuit_list = NULL;
130 /** A list of all the circuits in CIRCUIT_STATE_CHAN_WAIT. */
131 static smartlist_t *circuits_pending_chans = NULL;
133 /** List of all the (origin) circuits whose state is
134 * CIRCUIT_STATE_GUARD_WAIT. */
135 static smartlist_t *circuits_pending_other_guards = NULL;
137 /** A list of all the circuits that have been marked with
138 * circuit_mark_for_close and which are waiting for circuit_about_to_free. */
139 static smartlist_t *circuits_pending_close = NULL;
141 static void circuit_about_to_free_atexit(circuit_t *circ);
142 static void circuit_about_to_free(circuit_t *circ);
145 * A cached value of the current state of the origin circuit list. Has the
146 * value 1 if we saw any opened circuits recently (since the last call to
147 * circuit_any_opened_circuits(), which gets called around once a second by
148 * circuit_expire_building). 0 otherwise.
150 static int any_opened_circs_cached_val = 0;
152 /** Moving average of the cc->cwnd from each closed circuit. */
153 double cc_stats_circ_close_cwnd_ma = 0;
154 /** Moving average of the cc->cwnd from each closed slow-start circuit. */
155 double cc_stats_circ_close_ss_cwnd_ma = 0;
157 /* Running count of the above moving averages. Needed so we can update it. */
158 static double stats_circ_close_cwnd_ma_count = 0;
159 static double stats_circ_close_ss_cwnd_ma_count = 0;
161 /********* END VARIABLES ************/
163 /* Implement circuit handle helpers. */
164 HANDLE_IMPL(circuit, circuit_t,)
166 or_circuit_t *
167 TO_OR_CIRCUIT(circuit_t *x)
169 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
170 return DOWNCAST(or_circuit_t, x);
172 const or_circuit_t *
173 CONST_TO_OR_CIRCUIT(const circuit_t *x)
175 tor_assert(x->magic == OR_CIRCUIT_MAGIC);
176 return DOWNCAST(or_circuit_t, x);
178 origin_circuit_t *
179 TO_ORIGIN_CIRCUIT(circuit_t *x)
181 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
182 return DOWNCAST(origin_circuit_t, x);
184 const origin_circuit_t *
185 CONST_TO_ORIGIN_CIRCUIT(const circuit_t *x)
187 tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
188 return DOWNCAST(origin_circuit_t, x);
191 /** A map from channel and circuit ID to circuit. (Lookup performance is
192 * very important here, since we need to do it every time a cell arrives.) */
193 typedef struct chan_circid_circuit_map_t {
194 HT_ENTRY(chan_circid_circuit_map_t) node;
195 channel_t *chan;
196 circid_t circ_id;
197 circuit_t *circuit;
198 /* For debugging 12184: when was this placeholder item added? */
199 time_t made_placeholder_at;
200 } chan_circid_circuit_map_t;
202 /** Helper for hash tables: compare the channel and circuit ID for a and
203 * b, and return less than, equal to, or greater than zero appropriately.
205 static inline int
206 chan_circid_entries_eq_(chan_circid_circuit_map_t *a,
207 chan_circid_circuit_map_t *b)
209 return a->chan == b->chan && a->circ_id == b->circ_id;
212 /** Helper: return a hash based on circuit ID and the pointer value of
213 * chan in <b>a</b>. */
214 static inline unsigned int
215 chan_circid_entry_hash_(chan_circid_circuit_map_t *a)
217 /* Try to squeze the siphash input into 8 bytes to save any extra siphash
218 * rounds. This hash function is in the critical path. */
219 uintptr_t chan = (uintptr_t) (void*) a->chan;
220 uint32_t array[2];
221 array[0] = a->circ_id;
222 /* The low bits of the channel pointer are uninteresting, since the channel
223 * is a pretty big structure. */
224 array[1] = (uint32_t) (chan >> 6);
225 return (unsigned) siphash24g(array, sizeof(array));
228 /** Map from [chan,circid] to circuit. */
229 static HT_HEAD(chan_circid_map, chan_circid_circuit_map_t)
230 chan_circid_map = HT_INITIALIZER();
231 HT_PROTOTYPE(chan_circid_map, chan_circid_circuit_map_t, node,
232 chan_circid_entry_hash_, chan_circid_entries_eq_);
233 HT_GENERATE2(chan_circid_map, chan_circid_circuit_map_t, node,
234 chan_circid_entry_hash_, chan_circid_entries_eq_, 0.6,
235 tor_reallocarray_, tor_free_);
237 /** The most recently returned entry from circuit_get_by_circid_chan;
238 * used to improve performance when many cells arrive in a row from the
239 * same circuit.
241 static chan_circid_circuit_map_t *_last_circid_chan_ent = NULL;
243 /** Implementation helper for circuit_set_{p,n}_circid_channel: A circuit ID
244 * and/or channel for circ has just changed from <b>old_chan, old_id</b>
245 * to <b>chan, id</b>. Adjust the chan,circid map as appropriate, removing
246 * the old entry (if any) and adding a new one. */
247 static void
248 circuit_set_circid_chan_helper(circuit_t *circ, int direction,
249 circid_t id,
250 channel_t *chan)
252 chan_circid_circuit_map_t search;
253 chan_circid_circuit_map_t *found;
254 channel_t *old_chan, **chan_ptr;
255 circid_t old_id, *circid_ptr;
256 int make_active, attached = 0;
258 if (direction == CELL_DIRECTION_OUT) {
259 chan_ptr = &circ->n_chan;
260 circid_ptr = &circ->n_circ_id;
261 make_active = circ->n_chan_cells.n > 0;
262 } else {
263 or_circuit_t *c = TO_OR_CIRCUIT(circ);
264 chan_ptr = &c->p_chan;
265 circid_ptr = &c->p_circ_id;
266 make_active = c->p_chan_cells.n > 0;
268 old_chan = *chan_ptr;
269 old_id = *circid_ptr;
271 if (id == old_id && chan == old_chan)
272 return;
274 if (_last_circid_chan_ent &&
275 ((old_id == _last_circid_chan_ent->circ_id &&
276 old_chan == _last_circid_chan_ent->chan) ||
277 (id == _last_circid_chan_ent->circ_id &&
278 chan == _last_circid_chan_ent->chan))) {
279 _last_circid_chan_ent = NULL;
282 if (old_chan) {
284 * If we're changing channels or ID and had an old channel and a non
285 * zero old ID and weren't marked for close (i.e., we should have been
286 * attached), detach the circuit. ID changes require this because
287 * circuitmux hashes on (channel_id, circuit_id).
289 if (old_id != 0 && (old_chan != chan || old_id != id) &&
290 !(circ->marked_for_close)) {
291 tor_assert(old_chan->cmux);
292 circuitmux_detach_circuit(old_chan->cmux, circ);
295 /* we may need to remove it from the conn-circid map */
296 search.circ_id = old_id;
297 search.chan = old_chan;
298 found = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
299 if (found) {
300 tor_free(found);
301 if (direction == CELL_DIRECTION_OUT) {
302 /* One fewer circuits use old_chan as n_chan */
303 --(old_chan->num_n_circuits);
304 } else {
305 /* One fewer circuits use old_chan as p_chan */
306 --(old_chan->num_p_circuits);
311 /* Change the values only after we have possibly made the circuit inactive
312 * on the previous chan. */
313 *chan_ptr = chan;
314 *circid_ptr = id;
316 if (chan == NULL)
317 return;
319 /* now add the new one to the conn-circid map */
320 search.circ_id = id;
321 search.chan = chan;
322 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
323 if (found) {
324 found->circuit = circ;
325 found->made_placeholder_at = 0;
326 } else {
327 found = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
328 found->circ_id = id;
329 found->chan = chan;
330 found->circuit = circ;
331 HT_INSERT(chan_circid_map, &chan_circid_map, found);
335 * Attach to the circuitmux if we're changing channels or IDs and
336 * have a new channel and ID to use and the circuit is not marked for
337 * close.
339 if (chan && id != 0 && (old_chan != chan || old_id != id) &&
340 !(circ->marked_for_close)) {
341 tor_assert(chan->cmux);
342 circuitmux_attach_circuit(chan->cmux, circ, direction);
343 attached = 1;
347 * This is a no-op if we have no cells, but if we do it marks us active to
348 * the circuitmux
350 if (make_active && attached)
351 update_circuit_on_cmux(circ, direction);
353 /* Adjust circuit counts on new channel */
354 if (direction == CELL_DIRECTION_OUT) {
355 ++chan->num_n_circuits;
356 } else {
357 ++chan->num_p_circuits;
361 /** Mark that circuit id <b>id</b> shouldn't be used on channel <b>chan</b>,
362 * even if there is no circuit on the channel. We use this to keep the
363 * circuit id from getting re-used while we have queued but not yet sent
364 * a destroy cell. */
365 void
366 channel_mark_circid_unusable(channel_t *chan, circid_t id)
368 chan_circid_circuit_map_t search;
369 chan_circid_circuit_map_t *ent;
371 /* See if there's an entry there. That wouldn't be good. */
372 memset(&search, 0, sizeof(search));
373 search.chan = chan;
374 search.circ_id = id;
375 ent = HT_FIND(chan_circid_map, &chan_circid_map, &search);
377 if (ent && ent->circuit) {
378 /* we have a problem. */
379 log_warn(LD_BUG, "Tried to mark %u unusable on %p, but there was already "
380 "a circuit there.", (unsigned)id, chan);
381 } else if (ent) {
382 /* It's already marked. */
383 if (!ent->made_placeholder_at)
384 ent->made_placeholder_at = approx_time();
385 } else {
386 ent = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
387 ent->chan = chan;
388 ent->circ_id = id;
389 /* leave circuit at NULL. */
390 ent->made_placeholder_at = approx_time();
391 HT_INSERT(chan_circid_map, &chan_circid_map, ent);
395 /** Mark that a circuit id <b>id</b> can be used again on <b>chan</b>.
396 * We use this to re-enable the circuit ID after we've sent a destroy cell.
398 void
399 channel_mark_circid_usable(channel_t *chan, circid_t id)
401 chan_circid_circuit_map_t search;
402 chan_circid_circuit_map_t *ent;
404 /* See if there's an entry there. That wouldn't be good. */
405 memset(&search, 0, sizeof(search));
406 search.chan = chan;
407 search.circ_id = id;
408 ent = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
409 if (ent && ent->circuit) {
410 log_warn(LD_BUG, "Tried to mark %u usable on %p, but there was already "
411 "a circuit there.", (unsigned)id, chan);
412 return;
414 if (_last_circid_chan_ent == ent)
415 _last_circid_chan_ent = NULL;
416 tor_free(ent);
419 /** Called to indicate that a DESTROY is pending on <b>chan</b> with
420 * circuit ID <b>id</b>, but hasn't been sent yet. */
421 void
422 channel_note_destroy_pending(channel_t *chan, circid_t id)
424 circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
425 if (circ) {
426 if (circ->n_chan == chan && circ->n_circ_id == id) {
427 circ->n_delete_pending = 1;
428 } else {
429 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
430 if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
431 circ->p_delete_pending = 1;
434 return;
436 channel_mark_circid_unusable(chan, id);
439 /** Called to indicate that a DESTROY is no longer pending on <b>chan</b> with
440 * circuit ID <b>id</b> -- typically, because it has been sent. */
441 MOCK_IMPL(void,
442 channel_note_destroy_not_pending,(channel_t *chan, circid_t id))
444 circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
445 if (circ) {
446 if (circ->n_chan == chan && circ->n_circ_id == id) {
447 circ->n_delete_pending = 0;
448 } else {
449 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
450 if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
451 circ->p_delete_pending = 0;
454 /* XXXX this shouldn't happen; log a bug here. */
455 return;
457 channel_mark_circid_usable(chan, id);
460 /** Set the p_conn field of a circuit <b>circ</b>, along
461 * with the corresponding circuit ID, and add the circuit as appropriate
462 * to the (chan,id)-\>circuit map. */
463 void
464 circuit_set_p_circid_chan(or_circuit_t *or_circ, circid_t id,
465 channel_t *chan)
467 circuit_t *circ = TO_CIRCUIT(or_circ);
468 channel_t *old_chan = or_circ->p_chan;
469 circid_t old_id = or_circ->p_circ_id;
471 circuit_set_circid_chan_helper(circ, CELL_DIRECTION_IN, id, chan);
473 if (chan) {
474 chan->timestamp_last_had_circuits = approx_time();
477 if (circ->p_delete_pending && old_chan) {
478 channel_mark_circid_unusable(old_chan, old_id);
479 circ->p_delete_pending = 0;
483 /** Set the n_conn field of a circuit <b>circ</b>, along
484 * with the corresponding circuit ID, and add the circuit as appropriate
485 * to the (chan,id)-\>circuit map. */
486 void
487 circuit_set_n_circid_chan(circuit_t *circ, circid_t id,
488 channel_t *chan)
490 channel_t *old_chan = circ->n_chan;
491 circid_t old_id = circ->n_circ_id;
493 circuit_set_circid_chan_helper(circ, CELL_DIRECTION_OUT, id, chan);
495 if (chan) {
496 chan->timestamp_last_had_circuits = approx_time();
499 if (circ->n_delete_pending && old_chan) {
500 channel_mark_circid_unusable(old_chan, old_id);
501 circ->n_delete_pending = 0;
506 * Helper function to publish a message about events on an origin circuit
508 * Publishes a message to subscribers of origin circuit events, and
509 * sends the control event.
512 circuit_event_status(origin_circuit_t *circ, circuit_status_event_t tp,
513 int reason_code)
515 ocirc_cevent_msg_t *msg = tor_malloc(sizeof(*msg));
517 tor_assert(circ);
519 msg->gid = circ->global_identifier;
520 msg->evtype = tp;
521 msg->reason = reason_code;
522 msg->onehop = circ->build_state->onehop_tunnel;
524 ocirc_cevent_publish(msg);
525 return control_event_circuit_status(circ, tp, reason_code);
529 * Helper function to publish a state change message
531 * circuit_set_state() calls this to notify subscribers about a change
532 * of the state of an origin circuit. @a circ must be an origin
533 * circuit.
535 static void
536 circuit_state_publish(const circuit_t *circ)
538 ocirc_state_msg_t *msg = tor_malloc(sizeof(*msg));
539 const origin_circuit_t *ocirc;
541 tor_assert(CIRCUIT_IS_ORIGIN(circ));
542 ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
543 /* Only inbound OR circuits can be in this state, not origin circuits. */
544 tor_assert(circ->state != CIRCUIT_STATE_ONIONSKIN_PENDING);
546 msg->gid = ocirc->global_identifier;
547 msg->state = circ->state;
548 msg->onehop = ocirc->build_state->onehop_tunnel;
550 ocirc_state_publish(msg);
553 /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
554 * it from lists as appropriate. */
555 void
556 circuit_set_state(circuit_t *circ, uint8_t state)
558 tor_assert(circ);
559 if (state == circ->state)
560 return;
561 if (PREDICT_UNLIKELY(!circuits_pending_chans))
562 circuits_pending_chans = smartlist_new();
563 if (PREDICT_UNLIKELY(!circuits_pending_other_guards))
564 circuits_pending_other_guards = smartlist_new();
565 if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
566 /* remove from waiting-circuit list. */
567 smartlist_remove(circuits_pending_chans, circ);
569 if (state == CIRCUIT_STATE_CHAN_WAIT) {
570 /* add to waiting-circuit list. */
571 smartlist_add(circuits_pending_chans, circ);
573 if (circ->state == CIRCUIT_STATE_GUARD_WAIT) {
574 smartlist_remove(circuits_pending_other_guards, circ);
576 if (state == CIRCUIT_STATE_GUARD_WAIT) {
577 smartlist_add(circuits_pending_other_guards, circ);
579 if (state == CIRCUIT_STATE_GUARD_WAIT || state == CIRCUIT_STATE_OPEN)
580 tor_assert(!circ->n_chan_create_cell);
582 tor_trace(TR_SUBSYS(circuit), TR_EV(change_state), circ, circ->state, state);
583 circ->state = state;
584 if (CIRCUIT_IS_ORIGIN(circ))
585 circuit_state_publish(circ);
588 /** Append to <b>out</b> all circuits in state CHAN_WAIT waiting for
589 * the given connection. */
590 void
591 circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
593 tor_assert(out);
594 tor_assert(chan);
596 if (!circuits_pending_chans)
597 return;
599 SMARTLIST_FOREACH_BEGIN(circuits_pending_chans, circuit_t *, circ) {
600 if (circ->marked_for_close)
601 continue;
602 if (!circ->n_hop)
603 continue;
604 tor_assert(circ->state == CIRCUIT_STATE_CHAN_WAIT);
605 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
606 /* Look at addr/port. This is an unkeyed connection. */
607 if (!channel_matches_extend_info(chan, circ->n_hop))
608 continue;
609 } else {
610 /* We expected a key. See if it's the right one. */
611 if (tor_memneq(chan->identity_digest,
612 circ->n_hop->identity_digest, DIGEST_LEN))
613 continue;
615 smartlist_add(out, circ);
616 } SMARTLIST_FOREACH_END(circ);
619 /** Return the number of circuits in state CHAN_WAIT, waiting for the given
620 * channel. */
622 circuit_count_pending_on_channel(channel_t *chan)
624 int cnt;
625 smartlist_t *sl = smartlist_new();
627 tor_assert(chan);
629 circuit_get_all_pending_on_channel(sl, chan);
630 cnt = smartlist_len(sl);
631 smartlist_free(sl);
632 log_debug(LD_CIRC,"or_conn to %s, %d pending circs",
633 channel_describe_peer(chan),
634 cnt);
635 return cnt;
638 /** Remove <b>origin_circ</b> from the global list of origin circuits.
639 * Called when we are freeing a circuit.
641 static void
642 circuit_remove_from_origin_circuit_list(origin_circuit_t *origin_circ)
644 int origin_idx = origin_circ->global_origin_circuit_list_idx;
645 if (origin_idx < 0)
646 return;
647 origin_circuit_t *c2;
648 tor_assert(origin_idx <= smartlist_len(global_origin_circuit_list));
649 c2 = smartlist_get(global_origin_circuit_list, origin_idx);
650 tor_assert(origin_circ == c2);
651 smartlist_del(global_origin_circuit_list, origin_idx);
652 if (origin_idx < smartlist_len(global_origin_circuit_list)) {
653 origin_circuit_t *replacement =
654 smartlist_get(global_origin_circuit_list, origin_idx);
655 replacement->global_origin_circuit_list_idx = origin_idx;
657 origin_circ->global_origin_circuit_list_idx = -1;
660 /** Add <b>origin_circ</b> to the global list of origin circuits. Called
661 * when creating the circuit. */
662 static void
663 circuit_add_to_origin_circuit_list(origin_circuit_t *origin_circ)
665 tor_assert(origin_circ->global_origin_circuit_list_idx == -1);
666 smartlist_t *lst = circuit_get_global_origin_circuit_list();
667 smartlist_add(lst, origin_circ);
668 origin_circ->global_origin_circuit_list_idx = smartlist_len(lst) - 1;
671 /** Detach from the global circuit list, and deallocate, all
672 * circuits that have been marked for close.
674 void
675 circuit_close_all_marked(void)
677 if (circuits_pending_close == NULL)
678 return;
680 smartlist_t *lst = circuit_get_global_list();
681 SMARTLIST_FOREACH_BEGIN(circuits_pending_close, circuit_t *, circ) {
682 tor_assert(circ->marked_for_close);
684 /* Remove it from the circuit list. */
685 int idx = circ->global_circuitlist_idx;
686 smartlist_del(lst, idx);
687 if (idx < smartlist_len(lst)) {
688 circuit_t *replacement = smartlist_get(lst, idx);
689 replacement->global_circuitlist_idx = idx;
691 circ->global_circuitlist_idx = -1;
693 /* Remove it from the origin circuit list, if appropriate. */
694 if (CIRCUIT_IS_ORIGIN(circ)) {
695 circuit_remove_from_origin_circuit_list(TO_ORIGIN_CIRCUIT(circ));
698 circuit_about_to_free(circ);
699 circuit_free(circ);
700 } SMARTLIST_FOREACH_END(circ);
702 smartlist_clear(circuits_pending_close);
705 /** Return a pointer to the global list of circuits. */
706 MOCK_IMPL(smartlist_t *,
707 circuit_get_global_list,(void))
709 if (NULL == global_circuitlist)
710 global_circuitlist = smartlist_new();
711 return global_circuitlist;
714 /** Return a pointer to the global list of origin circuits. */
715 smartlist_t *
716 circuit_get_global_origin_circuit_list(void)
718 if (NULL == global_origin_circuit_list)
719 global_origin_circuit_list = smartlist_new();
720 return global_origin_circuit_list;
724 * Return true if we have any opened general-purpose 3 hop
725 * origin circuits.
727 * The result from this function is cached for use by
728 * circuit_any_opened_circuits_cached().
731 circuit_any_opened_circuits(void)
733 SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
734 const origin_circuit_t *, next_circ) {
735 if (!TO_CIRCUIT(next_circ)->marked_for_close &&
736 next_circ->has_opened &&
737 TO_CIRCUIT(next_circ)->state == CIRCUIT_STATE_OPEN &&
738 TO_CIRCUIT(next_circ)->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
739 next_circ->build_state &&
740 next_circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN) {
741 circuit_cache_opened_circuit_state(1);
742 return 1;
744 } SMARTLIST_FOREACH_END(next_circ);
746 circuit_cache_opened_circuit_state(0);
747 return 0;
751 * Cache the "any circuits opened" state, as specified in param
752 * circuits_are_opened. This is a helper function to update
753 * the circuit opened status whenever we happen to look at the
754 * circuit list.
756 void
757 circuit_cache_opened_circuit_state(int circuits_are_opened)
759 any_opened_circs_cached_val = circuits_are_opened;
763 * Return true if there were any opened circuits since the last call to
764 * circuit_any_opened_circuits(), or since circuit_expire_building() last
765 * ran (it runs roughly once per second).
768 circuit_any_opened_circuits_cached(void)
770 return any_opened_circs_cached_val;
773 /** Function to make circ-\>state human-readable */
774 const char *
775 circuit_state_to_string(int state)
777 static char buf[64];
778 switch (state) {
779 case CIRCUIT_STATE_BUILDING: return "doing handshakes";
780 case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
781 case CIRCUIT_STATE_CHAN_WAIT: return "connecting to server";
782 case CIRCUIT_STATE_GUARD_WAIT: return "waiting to see how other "
783 "guards perform";
784 case CIRCUIT_STATE_OPEN: return "open";
785 default:
786 log_warn(LD_BUG, "Unknown circuit state %d", state);
787 tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
788 return buf;
792 /** Map a circuit purpose to a string suitable to be displayed to a
793 * controller. */
794 const char *
795 circuit_purpose_to_controller_string(uint8_t purpose)
797 static char buf[32];
798 switch (purpose) {
799 case CIRCUIT_PURPOSE_OR:
800 case CIRCUIT_PURPOSE_INTRO_POINT:
801 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
802 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
803 return "SERVER"; /* A controller should never see these, actually. */
805 case CIRCUIT_PURPOSE_C_GENERAL:
806 return "GENERAL";
808 case CIRCUIT_PURPOSE_C_HSDIR_GET:
809 return "HS_CLIENT_HSDIR";
811 case CIRCUIT_PURPOSE_C_INTRODUCING:
812 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
813 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
814 return "HS_CLIENT_INTRO";
816 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
817 case CIRCUIT_PURPOSE_C_REND_READY:
818 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
819 case CIRCUIT_PURPOSE_C_REND_JOINED:
820 return "HS_CLIENT_REND";
822 case CIRCUIT_PURPOSE_S_HSDIR_POST:
823 return "HS_SERVICE_HSDIR";
825 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
826 case CIRCUIT_PURPOSE_S_INTRO:
827 return "HS_SERVICE_INTRO";
829 case CIRCUIT_PURPOSE_S_CONNECT_REND:
830 case CIRCUIT_PURPOSE_S_REND_JOINED:
831 return "HS_SERVICE_REND";
833 case CIRCUIT_PURPOSE_TESTING:
834 return "TESTING";
835 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
836 return "MEASURE_TIMEOUT";
837 case CIRCUIT_PURPOSE_CONTROLLER:
838 return "CONTROLLER";
839 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
840 return "PATH_BIAS_TESTING";
841 case CIRCUIT_PURPOSE_HS_VANGUARDS:
842 return "HS_VANGUARDS";
843 case CIRCUIT_PURPOSE_C_CIRCUIT_PADDING:
844 return "CIRCUIT_PADDING";
846 default:
847 tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
848 return buf;
852 /** Return a string specifying the state of the hidden-service circuit
853 * purpose <b>purpose</b>, or NULL if <b>purpose</b> is not a
854 * hidden-service-related circuit purpose. */
855 const char *
856 circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
858 switch (purpose)
860 default:
861 log_fn(LOG_WARN, LD_BUG,
862 "Unrecognized circuit purpose: %d",
863 (int)purpose);
864 tor_fragile_assert();
865 FALLTHROUGH_UNLESS_ALL_BUGS_ARE_FATAL;
867 case CIRCUIT_PURPOSE_OR:
868 case CIRCUIT_PURPOSE_C_GENERAL:
869 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
870 case CIRCUIT_PURPOSE_TESTING:
871 case CIRCUIT_PURPOSE_CONTROLLER:
872 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
873 case CIRCUIT_PURPOSE_HS_VANGUARDS:
874 case CIRCUIT_PURPOSE_C_CIRCUIT_PADDING:
875 return NULL;
877 case CIRCUIT_PURPOSE_INTRO_POINT:
878 return "OR_HSSI_ESTABLISHED";
879 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
880 return "OR_HSCR_ESTABLISHED";
881 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
882 return "OR_HS_R_JOINED";
884 case CIRCUIT_PURPOSE_C_HSDIR_GET:
885 case CIRCUIT_PURPOSE_C_INTRODUCING:
886 return "HSCI_CONNECTING";
887 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
888 return "HSCI_INTRO_SENT";
889 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
890 return "HSCI_DONE";
892 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
893 return "HSCR_CONNECTING";
894 case CIRCUIT_PURPOSE_C_REND_READY:
895 return "HSCR_ESTABLISHED_IDLE";
896 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
897 return "HSCR_ESTABLISHED_WAITING";
898 case CIRCUIT_PURPOSE_C_REND_JOINED:
899 return "HSCR_JOINED";
901 case CIRCUIT_PURPOSE_S_HSDIR_POST:
902 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
903 return "HSSI_CONNECTING";
904 case CIRCUIT_PURPOSE_S_INTRO:
905 return "HSSI_ESTABLISHED";
907 case CIRCUIT_PURPOSE_S_CONNECT_REND:
908 return "HSSR_CONNECTING";
909 case CIRCUIT_PURPOSE_S_REND_JOINED:
910 return "HSSR_JOINED";
914 /** Return a human-readable string for the circuit purpose <b>purpose</b>. */
915 const char *
916 circuit_purpose_to_string(uint8_t purpose)
918 static char buf[32];
920 switch (purpose)
922 case CIRCUIT_PURPOSE_OR:
923 return "Circuit at relay";
924 case CIRCUIT_PURPOSE_INTRO_POINT:
925 return "Acting as intro point";
926 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
927 return "Acting as rendezvous (pending)";
928 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
929 return "Acting as rendezvous (established)";
930 case CIRCUIT_PURPOSE_C_GENERAL:
931 return "General-purpose client";
932 case CIRCUIT_PURPOSE_C_INTRODUCING:
933 return "Hidden service client: Connecting to intro point";
934 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
935 return "Hidden service client: Waiting for ack from intro point";
936 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
937 return "Hidden service client: Received ack from intro point";
938 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
939 return "Hidden service client: Establishing rendezvous point";
940 case CIRCUIT_PURPOSE_C_REND_READY:
941 return "Hidden service client: Pending rendezvous point";
942 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
943 return "Hidden service client: Pending rendezvous point (ack received)";
944 case CIRCUIT_PURPOSE_C_REND_JOINED:
945 return "Hidden service client: Active rendezvous point";
946 case CIRCUIT_PURPOSE_C_HSDIR_GET:
947 return "Hidden service client: Fetching HS descriptor";
949 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
950 return "Measuring circuit timeout";
952 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
953 return "Hidden service: Establishing introduction point";
954 case CIRCUIT_PURPOSE_S_INTRO:
955 return "Hidden service: Introduction point";
956 case CIRCUIT_PURPOSE_S_CONNECT_REND:
957 return "Hidden service: Connecting to rendezvous point";
958 case CIRCUIT_PURPOSE_S_REND_JOINED:
959 return "Hidden service: Active rendezvous point";
960 case CIRCUIT_PURPOSE_S_HSDIR_POST:
961 return "Hidden service: Uploading HS descriptor";
963 case CIRCUIT_PURPOSE_TESTING:
964 return "Testing circuit";
966 case CIRCUIT_PURPOSE_CONTROLLER:
967 return "Circuit made by controller";
969 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
970 return "Path-bias testing circuit";
972 case CIRCUIT_PURPOSE_HS_VANGUARDS:
973 return "Hidden service: Pre-built vanguard circuit";
975 case CIRCUIT_PURPOSE_C_CIRCUIT_PADDING:
976 return "Circuit kept open for padding";
978 default:
979 tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
980 return buf;
984 /** Pick a reasonable package_window to start out for our circuits.
985 * Originally this was hard-coded at 1000, but now the consensus votes
986 * on the answer. See proposal 168. */
987 int32_t
988 circuit_initial_package_window(void)
990 int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START,
991 CIRCWINDOW_START_MIN,
992 CIRCWINDOW_START_MAX);
993 /* If the consensus tells us a negative number, we'd assert. */
994 if (num < 0)
995 num = CIRCWINDOW_START;
996 return num;
999 /** Initialize the common elements in a circuit_t, and add it to the global
1000 * list. */
1001 static void
1002 init_circuit_base(circuit_t *circ)
1004 tor_gettimeofday(&circ->timestamp_created);
1006 // Gets reset when we send CREATE_FAST.
1007 // circuit_expire_building() expects these to be equal
1008 // until the orconn is built.
1009 circ->timestamp_began = circ->timestamp_created;
1011 circ->package_window = circuit_initial_package_window();
1012 circ->deliver_window = CIRCWINDOW_START;
1013 circuit_reset_sendme_randomness(circ);
1014 cell_queue_init(&circ->n_chan_cells);
1016 smartlist_add(circuit_get_global_list(), circ);
1017 circ->global_circuitlist_idx = smartlist_len(circuit_get_global_list()) - 1;
1020 /** If we haven't yet decided on a good timeout value for circuit
1021 * building, we close idle circuits aggressively so we can get more
1022 * data points. These are the default, min, and max consensus values */
1023 #define DFLT_IDLE_TIMEOUT_WHILE_LEARNING (3*60)
1024 #define MIN_IDLE_TIMEOUT_WHILE_LEARNING (10)
1025 #define MAX_IDLE_TIMEOUT_WHILE_LEARNING (1000*60)
1027 /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
1028 * and <b>p_conn</b>. Add it to the global circuit list.
1030 origin_circuit_t *
1031 origin_circuit_new(void)
1033 origin_circuit_t *circ;
1034 /* never zero, since a global ID of 0 is treated specially by the
1035 * controller */
1036 static uint32_t n_circuits_allocated = 1;
1038 circ = tor_malloc_zero(sizeof(origin_circuit_t));
1039 circ->base_.magic = ORIGIN_CIRCUIT_MAGIC;
1041 circ->next_stream_id = crypto_rand_int(1<<16);
1042 circ->global_identifier = n_circuits_allocated++;
1043 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
1044 circ->remaining_relay_early_cells -= crypto_rand_int(2);
1046 init_circuit_base(TO_CIRCUIT(circ));
1048 /* Add to origin-list. */
1049 circ->global_origin_circuit_list_idx = -1;
1050 circuit_add_to_origin_circuit_list(circ);
1052 circuit_build_times_update_last_circ(get_circuit_build_times_mutable());
1054 if (! circuit_build_times_disabled(get_options()) &&
1055 circuit_build_times_needs_circuits(get_circuit_build_times())) {
1056 /* Circuits should be shorter lived if we need more of them
1057 * for learning a good build timeout */
1058 circ->circuit_idle_timeout =
1059 networkstatus_get_param(NULL, "cbtlearntimeout",
1060 DFLT_IDLE_TIMEOUT_WHILE_LEARNING,
1061 MIN_IDLE_TIMEOUT_WHILE_LEARNING,
1062 MAX_IDLE_TIMEOUT_WHILE_LEARNING);
1063 } else {
1064 // This should always be larger than the current port prediction time
1065 // remaining, or else we'll end up with the case where a circuit times out
1066 // and another one is built, effectively doubling the timeout window.
1068 // We also randomize it by up to 5% more (ie 5% of 0 to 3600 seconds,
1069 // depending on how much circuit prediction time is remaining) so that
1070 // we don't close a bunch of unused circuits all at the same time.
1071 int prediction_time_remaining =
1072 predicted_ports_prediction_time_remaining(time(NULL));
1073 circ->circuit_idle_timeout = prediction_time_remaining+1+
1074 crypto_rand_int(1+prediction_time_remaining/20);
1076 if (circ->circuit_idle_timeout <= 0) {
1077 log_warn(LD_BUG,
1078 "Circuit chose a negative idle timeout of %d based on "
1079 "%d seconds of predictive building remaining.",
1080 circ->circuit_idle_timeout,
1081 prediction_time_remaining);
1082 circ->circuit_idle_timeout =
1083 networkstatus_get_param(NULL, "cbtlearntimeout",
1084 DFLT_IDLE_TIMEOUT_WHILE_LEARNING,
1085 MIN_IDLE_TIMEOUT_WHILE_LEARNING,
1086 MAX_IDLE_TIMEOUT_WHILE_LEARNING);
1089 log_info(LD_CIRC,
1090 "Circuit %"PRIu32" chose an idle timeout of %d based on "
1091 "%d seconds of predictive building remaining.",
1092 (circ->global_identifier),
1093 circ->circuit_idle_timeout,
1094 prediction_time_remaining);
1097 tor_trace(TR_SUBSYS(circuit), TR_EV(new_origin), circ);
1098 return circ;
1101 /** Allocate a new or_circuit_t, connected to <b>p_chan</b> as
1102 * <b>p_circ_id</b>. If <b>p_chan</b> is NULL, the circuit is unattached. */
1103 or_circuit_t *
1104 or_circuit_new(circid_t p_circ_id, channel_t *p_chan)
1106 /* CircIDs */
1107 or_circuit_t *circ;
1109 circ = tor_malloc_zero(sizeof(or_circuit_t));
1110 circ->base_.magic = OR_CIRCUIT_MAGIC;
1112 if (p_chan)
1113 circuit_set_p_circid_chan(circ, p_circ_id, p_chan);
1115 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
1116 cell_queue_init(&circ->p_chan_cells);
1118 init_circuit_base(TO_CIRCUIT(circ));
1120 tor_trace(TR_SUBSYS(circuit), TR_EV(new_or), circ);
1121 return circ;
1124 /** Free all storage held in circ->testing_cell_stats */
1125 void
1126 circuit_clear_testing_cell_stats(circuit_t *circ)
1128 if (!circ || !circ->testing_cell_stats)
1129 return;
1130 SMARTLIST_FOREACH(circ->testing_cell_stats, testing_cell_stats_entry_t *,
1131 ent, tor_free(ent));
1132 smartlist_free(circ->testing_cell_stats);
1133 circ->testing_cell_stats = NULL;
1136 /** Deallocate space associated with circ.
1138 STATIC void
1139 circuit_free_(circuit_t *circ)
1141 circid_t n_circ_id = 0;
1142 void *mem;
1143 size_t memlen;
1144 int should_free = 1;
1145 if (!circ)
1146 return;
1148 /* We keep a copy of this so we can log its value before it gets unset. */
1149 n_circ_id = circ->n_circ_id;
1151 circuit_clear_testing_cell_stats(circ);
1153 /* Cleanup circuit from anything HS v3 related. We also do this when the
1154 * circuit is closed. This is to avoid any code path that free registered
1155 * circuits without closing them before. This needs to be done before the
1156 * hs identifier is freed. */
1157 hs_circ_cleanup_on_free(circ);
1159 congestion_control_free(circ->ccontrol);
1161 if (CIRCUIT_IS_ORIGIN(circ)) {
1162 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1163 mem = ocirc;
1164 memlen = sizeof(origin_circuit_t);
1165 tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
1167 circuit_remove_from_origin_circuit_list(ocirc);
1169 if (ocirc->half_streams) {
1170 SMARTLIST_FOREACH_BEGIN(ocirc->half_streams, half_edge_t *,
1171 half_conn) {
1172 half_edge_free(half_conn);
1173 } SMARTLIST_FOREACH_END(half_conn);
1174 smartlist_free(ocirc->half_streams);
1177 if (ocirc->build_state) {
1178 extend_info_free(ocirc->build_state->chosen_exit);
1180 tor_free(ocirc->build_state);
1182 /* Cancel before freeing, if we haven't already succeeded or failed. */
1183 if (ocirc->guard_state) {
1184 entry_guard_cancel(&ocirc->guard_state);
1186 circuit_guard_state_free(ocirc->guard_state);
1188 circuit_clear_cpath(ocirc);
1190 crypto_pk_free(ocirc->intro_key);
1192 /* Finally, free the identifier of the circuit and nullify it so multiple
1193 * cleanup will work. */
1194 hs_ident_circuit_free(ocirc->hs_ident);
1195 ocirc->hs_ident = NULL;
1197 tor_free(ocirc->dest_address);
1198 if (ocirc->socks_username) {
1199 memwipe(ocirc->socks_username, 0x12, ocirc->socks_username_len);
1200 tor_free(ocirc->socks_username);
1202 if (ocirc->socks_password) {
1203 memwipe(ocirc->socks_password, 0x06, ocirc->socks_password_len);
1204 tor_free(ocirc->socks_password);
1206 addr_policy_list_free(ocirc->prepend_policy);
1207 } else {
1208 or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
1209 /* Remember cell statistics for this circuit before deallocating. */
1210 if (get_options()->CellStatistics)
1211 rep_hist_buffer_stats_add_circ(circ, time(NULL));
1212 mem = ocirc;
1213 memlen = sizeof(or_circuit_t);
1214 tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
1216 should_free = (ocirc->workqueue_entry == NULL);
1218 relay_crypto_clear(&ocirc->crypto);
1220 if (ocirc->rend_splice) {
1221 or_circuit_t *other = ocirc->rend_splice;
1222 tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
1223 other->rend_splice = NULL;
1226 /* remove from map. */
1227 circuit_set_p_circid_chan(ocirc, 0, NULL);
1229 /* Clear cell queue _after_ removing it from the map. Otherwise our
1230 * "active" checks will be violated. */
1231 cell_queue_clear(&ocirc->p_chan_cells);
1234 extend_info_free(circ->n_hop);
1235 tor_free(circ->n_chan_create_cell);
1237 if (circ->global_circuitlist_idx != -1) {
1238 int idx = circ->global_circuitlist_idx;
1239 circuit_t *c2 = smartlist_get(global_circuitlist, idx);
1240 tor_assert(c2 == circ);
1241 smartlist_del(global_circuitlist, idx);
1242 if (idx < smartlist_len(global_circuitlist)) {
1243 c2 = smartlist_get(global_circuitlist, idx);
1244 c2->global_circuitlist_idx = idx;
1248 /* Remove from map. */
1249 circuit_set_n_circid_chan(circ, 0, NULL);
1251 /* Clear cell queue _after_ removing it from the map. Otherwise our
1252 * "active" checks will be violated. */
1253 cell_queue_clear(&circ->n_chan_cells);
1255 /* Cleanup possible SENDME state. */
1256 if (circ->sendme_last_digests) {
1257 SMARTLIST_FOREACH(circ->sendme_last_digests, uint8_t *, d, tor_free(d));
1258 smartlist_free(circ->sendme_last_digests);
1261 log_info(LD_CIRC, "Circuit %u (id: %" PRIu32 ") has been freed.",
1262 n_circ_id,
1263 CIRCUIT_IS_ORIGIN(circ) ?
1264 TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0);
1266 /* Free any circuit padding structures */
1267 circpad_circuit_free_all_machineinfos(circ);
1269 /* Clear all dangling handle references. */
1270 circuit_handles_clear(circ);
1272 /* Tracepoint. Data within the circuit object is recorded so do this before
1273 * the actual memory free. */
1274 tor_trace(TR_SUBSYS(circuit), TR_EV(free), circ);
1276 if (should_free) {
1277 memwipe(mem, 0xAA, memlen); /* poison memory */
1278 tor_free(mem);
1279 } else {
1280 /* If we made it here, this is an or_circuit_t that still has a pending
1281 * cpuworker request which we weren't able to cancel. Instead, set up
1282 * the magic value so that when the reply comes back, we'll know to discard
1283 * the reply and free this structure.
1285 memwipe(mem, 0xAA, memlen);
1286 circ->magic = DEAD_CIRCUIT_MAGIC;
1290 /** Deallocate the linked list circ-><b>cpath</b>, and remove the cpath from
1291 * <b>circ</b>. */
1292 void
1293 circuit_clear_cpath(origin_circuit_t *circ)
1295 crypt_path_t *victim, *head, *cpath;
1297 head = cpath = circ->cpath;
1299 if (!cpath)
1300 return;
1302 /* it's a circular list, so we have to notice when we've
1303 * gone through it once. */
1304 while (cpath->next && cpath->next != head) {
1305 victim = cpath;
1306 cpath = victim->next;
1307 cpath_free(victim);
1310 cpath_free(cpath);
1312 circ->cpath = NULL;
1315 /** Release all storage held by circuits. */
1316 void
1317 circuit_free_all(void)
1319 smartlist_t *lst = circuit_get_global_list();
1321 SMARTLIST_FOREACH_BEGIN(lst, circuit_t *, tmp) {
1322 if (! CIRCUIT_IS_ORIGIN(tmp)) {
1323 or_circuit_t *or_circ = TO_OR_CIRCUIT(tmp);
1324 while (or_circ->resolving_streams) {
1325 edge_connection_t *next_conn;
1326 next_conn = or_circ->resolving_streams->next_stream;
1327 connection_free_(TO_CONN(or_circ->resolving_streams));
1328 or_circ->resolving_streams = next_conn;
1331 tmp->global_circuitlist_idx = -1;
1332 circuit_about_to_free_atexit(tmp);
1333 circuit_free(tmp);
1334 SMARTLIST_DEL_CURRENT(lst, tmp);
1335 } SMARTLIST_FOREACH_END(tmp);
1337 smartlist_free(lst);
1338 global_circuitlist = NULL;
1340 smartlist_free(global_origin_circuit_list);
1341 global_origin_circuit_list = NULL;
1343 smartlist_free(circuits_pending_chans);
1344 circuits_pending_chans = NULL;
1346 smartlist_free(circuits_pending_close);
1347 circuits_pending_close = NULL;
1349 smartlist_free(circuits_pending_other_guards);
1350 circuits_pending_other_guards = NULL;
1353 chan_circid_circuit_map_t **elt, **next, *c;
1354 for (elt = HT_START(chan_circid_map, &chan_circid_map);
1355 elt;
1356 elt = next) {
1357 c = *elt;
1358 next = HT_NEXT_RMV(chan_circid_map, &chan_circid_map, elt);
1360 tor_assert(c->circuit == NULL);
1361 tor_free(c);
1364 HT_CLEAR(chan_circid_map, &chan_circid_map);
1367 /** A helper function for circuit_dump_by_conn() below. Log a bunch
1368 * of information about circuit <b>circ</b>.
1370 static void
1371 circuit_dump_conn_details(int severity,
1372 circuit_t *circ,
1373 int conn_array_index,
1374 const char *type,
1375 circid_t this_circid,
1376 circid_t other_circid)
1378 tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
1379 "(other side %u), state %d (%s), born %ld:",
1380 conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
1381 circ->state, circuit_state_to_string(circ->state),
1382 (long)circ->timestamp_began.tv_sec);
1383 if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
1384 circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
1388 /** Log, at severity <b>severity</b>, information about each circuit
1389 * that is connected to <b>conn</b>.
1391 void
1392 circuit_dump_by_conn(connection_t *conn, int severity)
1394 edge_connection_t *tmpconn;
1396 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1397 circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
1399 if (circ->marked_for_close) {
1400 continue;
1403 if (!CIRCUIT_IS_ORIGIN(circ)) {
1404 p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
1407 if (CIRCUIT_IS_ORIGIN(circ)) {
1408 for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
1409 tmpconn=tmpconn->next_stream) {
1410 if (TO_CONN(tmpconn) == conn) {
1411 circuit_dump_conn_details(severity, circ, conn->conn_array_index,
1412 "App-ward", p_circ_id, n_circ_id);
1417 if (! CIRCUIT_IS_ORIGIN(circ)) {
1418 for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
1419 tmpconn=tmpconn->next_stream) {
1420 if (TO_CONN(tmpconn) == conn) {
1421 circuit_dump_conn_details(severity, circ, conn->conn_array_index,
1422 "Exit-ward", n_circ_id, p_circ_id);
1427 SMARTLIST_FOREACH_END(circ);
1430 /** Return the circuit whose global ID is <b>id</b>, or NULL if no
1431 * such circuit exists. */
1432 origin_circuit_t *
1433 circuit_get_by_global_id(uint32_t id)
1435 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1436 if (CIRCUIT_IS_ORIGIN(circ) &&
1437 TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
1438 if (circ->marked_for_close)
1439 return NULL;
1440 else
1441 return TO_ORIGIN_CIRCUIT(circ);
1444 SMARTLIST_FOREACH_END(circ);
1445 return NULL;
1448 /** Return a circ such that:
1449 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
1450 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
1451 * Return NULL if no such circuit exists.
1453 * If <b>found_entry_out</b> is provided, set it to true if we have a
1454 * placeholder entry for circid/chan, and leave it unset otherwise.
1456 static inline circuit_t *
1457 circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan,
1458 int *found_entry_out)
1460 chan_circid_circuit_map_t search;
1461 chan_circid_circuit_map_t *found;
1463 if (_last_circid_chan_ent &&
1464 circ_id == _last_circid_chan_ent->circ_id &&
1465 chan == _last_circid_chan_ent->chan) {
1466 found = _last_circid_chan_ent;
1467 } else {
1468 search.circ_id = circ_id;
1469 search.chan = chan;
1470 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
1471 _last_circid_chan_ent = found;
1473 if (found && found->circuit) {
1474 log_debug(LD_CIRC,
1475 "circuit_get_by_circid_channel_impl() returning circuit %p for"
1476 " circ_id %u, channel ID %"PRIu64 " (%p)",
1477 found->circuit, (unsigned)circ_id,
1478 (chan->global_identifier), chan);
1479 if (found_entry_out)
1480 *found_entry_out = 1;
1481 return found->circuit;
1484 log_debug(LD_CIRC,
1485 "circuit_get_by_circid_channel_impl() found %s for"
1486 " circ_id %u, channel ID %"PRIu64 " (%p)",
1487 found ? "placeholder" : "nothing",
1488 (unsigned)circ_id,
1489 (chan->global_identifier), chan);
1491 if (found_entry_out)
1492 *found_entry_out = found ? 1 : 0;
1494 return NULL;
1495 /* The rest of this checks for bugs. Disabled by default. */
1496 /* We comment it out because coverity complains otherwise.
1498 circuit_t *circ;
1499 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
1500 if (! CIRCUIT_IS_ORIGIN(circ)) {
1501 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1502 if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
1503 log_warn(LD_BUG,
1504 "circuit matches p_chan, but not in hash table (Bug!)");
1505 return circ;
1508 if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
1509 log_warn(LD_BUG,
1510 "circuit matches n_chan, but not in hash table (Bug!)");
1511 return circ;
1514 return NULL;
1515 } */
1518 /** Return a circ such that:
1519 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
1520 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
1521 * - circ is not marked for close.
1522 * Return NULL if no such circuit exists.
1524 circuit_t *
1525 circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
1527 circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
1528 if (!circ || circ->marked_for_close)
1529 return NULL;
1530 else
1531 return circ;
1534 /** Return a circ such that:
1535 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
1536 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
1537 * Return NULL if no such circuit exists.
1539 circuit_t *
1540 circuit_get_by_circid_channel_even_if_marked(circid_t circ_id,
1541 channel_t *chan)
1543 return circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
1546 /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
1547 * circuit, marked or not, on <b>chan</b>, or if the circ ID is reserved until
1548 * a queued destroy cell can be sent.
1550 * (Return 1 if the circuit is present, marked or not; Return 2
1551 * if the circuit ID is pending a destroy.)
1554 circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
1556 int found = 0;
1557 if (circuit_get_by_circid_channel_impl(circ_id, chan, &found) != NULL)
1558 return 1;
1559 if (found)
1560 return 2;
1561 return 0;
1564 /** Helper for debugging 12184. Returns the time since which 'circ_id' has
1565 * been marked unusable on 'chan'. */
1566 time_t
1567 circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
1569 chan_circid_circuit_map_t search;
1570 chan_circid_circuit_map_t *found;
1572 memset(&search, 0, sizeof(search));
1573 search.circ_id = circ_id;
1574 search.chan = chan;
1576 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
1578 if (! found || found->circuit)
1579 return 0;
1581 return found->made_placeholder_at;
1584 /** Return the circuit that a given edge connection is using. */
1585 circuit_t *
1586 circuit_get_by_edge_conn(edge_connection_t *conn)
1588 circuit_t *circ;
1590 circ = conn->on_circuit;
1591 tor_assert(!circ ||
1592 (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
1593 : circ->magic == OR_CIRCUIT_MAGIC));
1595 return circ;
1598 /** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
1599 * circuit from the chan,circid map, and mark it for close if it hasn't
1600 * been marked already.
1602 void
1603 circuit_unlink_all_from_channel(channel_t *chan, int reason)
1605 smartlist_t *detached = smartlist_new();
1607 /* #define DEBUG_CIRCUIT_UNLINK_ALL */
1609 channel_unlink_all_circuits(chan, detached);
1611 #ifdef DEBUG_CIRCUIT_UNLINK_ALL
1613 smartlist_t *detached_2 = smartlist_new();
1614 int mismatch = 0, badlen = 0;
1616 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1617 if (circ->n_chan == chan ||
1618 (!CIRCUIT_IS_ORIGIN(circ) &&
1619 TO_OR_CIRCUIT(circ)->p_chan == chan)) {
1620 smartlist_add(detached_2, circ);
1623 SMARTLIST_FOREACH_END(circ);
1625 if (smartlist_len(detached) != smartlist_len(detached_2)) {
1626 log_warn(LD_BUG, "List of detached circuits had the wrong length! "
1627 "(got %d, should have gotten %d)",
1628 (int)smartlist_len(detached),
1629 (int)smartlist_len(detached_2));
1630 badlen = 1;
1632 smartlist_sort_pointers(detached);
1633 smartlist_sort_pointers(detached_2);
1635 SMARTLIST_FOREACH(detached, circuit_t *, c,
1636 if (c != smartlist_get(detached_2, c_sl_idx))
1637 mismatch = 1;
1640 if (mismatch)
1641 log_warn(LD_BUG, "Mismatch in list of detached circuits.");
1643 if (badlen || mismatch) {
1644 smartlist_free(detached);
1645 detached = detached_2;
1646 } else {
1647 log_notice(LD_CIRC, "List of %d circuits was as expected.",
1648 (int)smartlist_len(detached));
1649 smartlist_free(detached_2);
1652 #endif /* defined(DEBUG_CIRCUIT_UNLINK_ALL) */
1654 SMARTLIST_FOREACH_BEGIN(detached, circuit_t *, circ) {
1655 int mark = 0;
1656 if (circ->n_chan == chan) {
1658 circuit_set_n_circid_chan(circ, 0, NULL);
1659 mark = 1;
1661 /* If we didn't request this closure, pass the remote
1662 * bit to mark_for_close. */
1663 if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
1664 reason |= END_CIRC_REASON_FLAG_REMOTE;
1666 if (! CIRCUIT_IS_ORIGIN(circ)) {
1667 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1668 if (or_circ->p_chan == chan) {
1669 circuit_set_p_circid_chan(or_circ, 0, NULL);
1670 mark = 1;
1673 if (!mark) {
1674 log_warn(LD_BUG, "Circuit on detached list which I had no reason "
1675 "to mark");
1676 continue;
1678 if (!circ->marked_for_close)
1679 circuit_mark_for_close(circ, reason);
1680 } SMARTLIST_FOREACH_END(circ);
1682 smartlist_free(detached);
1685 /** Return the first introduction circuit originating from the global circuit
1686 * list after <b>start</b> or at the start of the list if <b>start</b> is
1687 * NULL. Return NULL if no circuit is found.
1689 * If <b>want_client_circ</b> is true, then we are looking for client-side
1690 * introduction circuits: A client introduction point circuit has a purpose of
1691 * either CIRCUIT_PURPOSE_C_INTRODUCING, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
1692 * or CIRCUIT_PURPOSE_C_INTRODUCE_ACKED. This does not return a circuit marked
1693 * for close, but it returns circuits regardless of their circuit state.
1695 * If <b>want_client_circ</b> is false, then we are looking for service-side
1696 * introduction circuits: A service introduction point circuit has a purpose of
1697 * either CIRCUIT_PURPOSE_S_ESTABLISH_INTRO or CIRCUIT_PURPOSE_S_INTRO. This
1698 * does not return circuits marked for close, or in any state other than open.
1700 origin_circuit_t *
1701 circuit_get_next_intro_circ(const origin_circuit_t *start,
1702 bool want_client_circ)
1704 int idx = 0;
1705 smartlist_t *lst = circuit_get_global_list();
1707 if (start) {
1708 idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
1711 for ( ; idx < smartlist_len(lst); ++idx) {
1712 circuit_t *circ = smartlist_get(lst, idx);
1714 /* Ignore a marked for close circuit or if the state is not open. */
1715 if (circ->marked_for_close) {
1716 continue;
1719 /* Depending on whether we are looking for client or service circs, skip
1720 * circuits with other purposes. */
1721 if (want_client_circ) {
1722 if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
1723 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
1724 circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACKED) {
1725 continue;
1727 } else { /* we are looking for service-side circs */
1728 if (circ->state != CIRCUIT_STATE_OPEN) {
1729 continue;
1731 if (circ->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO &&
1732 circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
1733 continue;
1737 /* The purposes we are looking for are only for origin circuits so the
1738 * following is valid. */
1739 return TO_ORIGIN_CIRCUIT(circ);
1741 /* Not found. */
1742 return NULL;
1745 /** Return the first service rendezvous circuit originating from the global
1746 * circuit list after <b>start</b> or at the start of the list if <b>start</b>
1747 * is NULL. Return NULL if no circuit is found.
1749 * A service rendezvous point circuit has a purpose of either
1750 * CIRCUIT_PURPOSE_S_CONNECT_REND or CIRCUIT_PURPOSE_S_REND_JOINED. This does
1751 * not return a circuit marked for close and its state must be open. */
1752 origin_circuit_t *
1753 circuit_get_next_service_rp_circ(origin_circuit_t *start)
1755 int idx = 0;
1756 smartlist_t *lst = circuit_get_global_list();
1758 if (start) {
1759 idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
1762 for ( ; idx < smartlist_len(lst); ++idx) {
1763 circuit_t *circ = smartlist_get(lst, idx);
1765 /* Ignore a marked for close circuit or purpose not matching a service
1766 * intro point or if the state is not open. */
1767 if (circ->marked_for_close || circ->state != CIRCUIT_STATE_OPEN ||
1768 (circ->purpose != CIRCUIT_PURPOSE_S_CONNECT_REND &&
1769 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED)) {
1770 continue;
1772 /* The purposes we are looking for are only for origin circuits so the
1773 * following is valid. */
1774 return TO_ORIGIN_CIRCUIT(circ);
1776 /* Not found. */
1777 return NULL;
1780 /** Return the first circuit originating here in global_circuitlist after
1781 * <b>start</b> whose purpose is <b>purpose</b>. Return NULL if no circuit is
1782 * found. If <b>start</b> is NULL, begin at the start of the list. */
1783 origin_circuit_t *
1784 circuit_get_next_by_purpose(origin_circuit_t *start, uint8_t purpose)
1786 int idx;
1787 smartlist_t *lst = circuit_get_global_list();
1788 tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
1789 if (start == NULL)
1790 idx = 0;
1791 else
1792 idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
1794 for ( ; idx < smartlist_len(lst); ++idx) {
1795 circuit_t *circ = smartlist_get(lst, idx);
1797 if (circ->marked_for_close)
1798 continue;
1799 if (circ->purpose != purpose)
1800 continue;
1801 /* At this point we should be able to get a valid origin circuit because
1802 * the origin purpose we are looking for matches this circuit. */
1803 if (BUG(!CIRCUIT_PURPOSE_IS_ORIGIN(circ->purpose))) {
1804 break;
1806 return TO_ORIGIN_CIRCUIT(circ);
1808 return NULL;
1811 /** We might cannibalize this circuit: Return true if its last hop can be used
1812 * as a v3 rendezvous point. */
1813 static int
1814 circuit_can_be_cannibalized_for_v3_rp(const origin_circuit_t *circ)
1816 if (!circ->build_state) {
1817 return 0;
1820 extend_info_t *chosen_exit = circ->build_state->chosen_exit;
1821 if (BUG(!chosen_exit)) {
1822 return 0;
1825 const node_t *rp_node = node_get_by_id(chosen_exit->identity_digest);
1826 if (rp_node) {
1827 if (node_supports_v3_rendezvous_point(rp_node)) {
1828 return 1;
1832 return 0;
1835 /** We are trying to create a circuit of purpose <b>purpose</b> and we are
1836 * looking for cannibalizable circuits. Return the circuit purpose we would be
1837 * willing to cannibalize. */
1838 static uint8_t
1839 get_circuit_purpose_needed_to_cannibalize(uint8_t purpose)
1841 if (circuit_should_use_vanguards(purpose)) {
1842 /* If we are using vanguards, then we should only cannibalize vanguard
1843 * circuits so that we get the same path construction logic. */
1844 return CIRCUIT_PURPOSE_HS_VANGUARDS;
1845 } else {
1846 /* If no vanguards are used just get a general circuit! */
1847 return CIRCUIT_PURPOSE_C_GENERAL;
1851 /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
1852 * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
1853 * flags in <b>flags</b>, and if info is defined, does not already use info
1854 * as any of its hops; or NULL if no circuit fits this description.
1856 * The <b>purpose</b> argument refers to the purpose of the circuit we want to
1857 * create, not the purpose of the circuit we want to cannibalize.
1859 * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
1861 * To "cannibalize" a circuit means to extend it an extra hop, and use it
1862 * for some other purpose than we had originally intended. We do this when
1863 * we want to perform some low-bandwidth task at a specific relay, and we
1864 * would like the circuit to complete as soon as possible. (If we were going
1865 * to use a lot of bandwidth, we wouldn't want a circuit with an extra hop.
1866 * If we didn't care about circuit completion latency, we would just build
1867 * a new circuit.)
1869 origin_circuit_t *
1870 circuit_find_to_cannibalize(uint8_t purpose_to_produce, extend_info_t *info,
1871 int flags)
1873 origin_circuit_t *best=NULL;
1874 int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
1875 int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
1876 int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
1877 const or_options_t *options = get_options();
1878 /* We want the circuit we are trying to cannibalize to have this purpose */
1879 int purpose_to_search_for;
1881 /* Make sure we're not trying to create a onehop circ by
1882 * cannibalization. */
1883 tor_assert(!(flags & CIRCLAUNCH_ONEHOP_TUNNEL));
1885 purpose_to_search_for = get_circuit_purpose_needed_to_cannibalize(
1886 purpose_to_produce);
1888 tor_assert_nonfatal(purpose_to_search_for == CIRCUIT_PURPOSE_C_GENERAL ||
1889 purpose_to_search_for == CIRCUIT_PURPOSE_HS_VANGUARDS);
1891 log_debug(LD_CIRC,
1892 "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
1893 "capacity %d, internal %d",
1894 purpose_to_produce, need_uptime, need_capacity, internal);
1896 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
1897 if (CIRCUIT_IS_ORIGIN(circ_) &&
1898 circ_->state == CIRCUIT_STATE_OPEN &&
1899 !circ_->marked_for_close &&
1900 circ_->purpose == purpose_to_search_for &&
1901 !circ_->timestamp_dirty) {
1902 origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
1904 /* Only cannibalize from reasonable length circuits. If we
1905 * want C_GENERAL, then only choose 3 hop circs. If we want
1906 * HS_VANGUARDS, only choose 4 hop circs.
1908 if (circ->build_state->desired_path_len !=
1909 route_len_for_purpose(purpose_to_search_for, NULL)) {
1910 goto next;
1913 /* Ignore any circuits for which we can't use the Guard. It is possible
1914 * that the Guard was removed from the sampled set after the circuit
1915 * was created, so avoid using it. */
1916 if (!entry_guard_could_succeed(circ->guard_state)) {
1917 goto next;
1920 if ((!need_uptime || circ->build_state->need_uptime) &&
1921 (!need_capacity || circ->build_state->need_capacity) &&
1922 (internal == circ->build_state->is_internal) &&
1923 !circ->unusable_for_new_conns &&
1924 circ->remaining_relay_early_cells &&
1925 !circ->build_state->onehop_tunnel &&
1926 !circ->isolation_values_set) {
1927 if (info) {
1928 /* need to make sure we don't duplicate hops */
1929 crypt_path_t *hop = circ->cpath;
1930 const node_t *ri1 = node_get_by_id(info->identity_digest);
1931 do {
1932 const node_t *ri2;
1933 if (tor_memeq(hop->extend_info->identity_digest,
1934 info->identity_digest, DIGEST_LEN))
1935 goto next;
1936 if (ri1 &&
1937 (ri2 = node_get_by_id(hop->extend_info->identity_digest))
1938 && nodes_in_same_family(ri1, ri2))
1939 goto next;
1940 hop=hop->next;
1941 } while (hop!=circ->cpath);
1943 if (options->ExcludeNodes) {
1944 /* Make sure no existing nodes in the circuit are excluded for
1945 * general use. (This may be possible if StrictNodes is 0, and we
1946 * thought we needed to use an otherwise excluded node for, say, a
1947 * directory operation.) */
1948 crypt_path_t *hop = circ->cpath;
1949 do {
1950 if (routerset_contains_extendinfo(options->ExcludeNodes,
1951 hop->extend_info))
1952 goto next;
1953 hop = hop->next;
1954 } while (hop != circ->cpath);
1957 if ((flags & CIRCLAUNCH_IS_V3_RP) &&
1958 !circuit_can_be_cannibalized_for_v3_rp(circ)) {
1959 log_debug(LD_GENERAL, "Skipping uncannibalizable circuit for v3 "
1960 "rendezvous point.");
1961 goto next;
1964 if (!best || (best->build_state->need_uptime && !need_uptime))
1965 best = circ;
1966 next: ;
1970 SMARTLIST_FOREACH_END(circ_);
1971 return best;
1975 * Check whether any of the origin circuits that are waiting to see if
1976 * their guard is good enough to use can be upgraded to "ready". If so,
1977 * return a new smartlist containing them. Otherwise return NULL.
1979 smartlist_t *
1980 circuit_find_circuits_to_upgrade_from_guard_wait(void)
1982 /* Only if some circuit is actually waiting on an upgrade should we
1983 * run the algorithm. */
1984 if (! circuits_pending_other_guards ||
1985 smartlist_len(circuits_pending_other_guards)==0)
1986 return NULL;
1987 /* Only if we have some origin circuits should we run the algorithm. */
1988 if (!global_origin_circuit_list)
1989 return NULL;
1991 /* Okay; we can pass our circuit list to entrynodes.c.*/
1992 smartlist_t *result = smartlist_new();
1993 int circuits_upgraded = entry_guards_upgrade_waiting_circuits(
1994 get_guard_selection_info(),
1995 global_origin_circuit_list,
1996 result);
1997 if (circuits_upgraded && smartlist_len(result)) {
1998 return result;
1999 } else {
2000 smartlist_free(result);
2001 return NULL;
2005 /** Return the number of hops in circuit's path. If circ has no entries,
2006 * or is NULL, returns 0. */
2008 circuit_get_cpath_len(origin_circuit_t *circ)
2010 int n = 0;
2011 if (circ && circ->cpath) {
2012 crypt_path_t *cpath, *cpath_next = NULL;
2013 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2014 cpath_next = cpath->next;
2015 ++n;
2018 return n;
2021 /** Return the number of opened hops in circuit's path.
2022 * If circ has no entries, or is NULL, returns 0. */
2024 circuit_get_cpath_opened_len(const origin_circuit_t *circ)
2026 int n = 0;
2027 if (circ && circ->cpath) {
2028 crypt_path_t *cpath, *cpath_next = NULL;
2029 for (cpath = circ->cpath;
2030 cpath->state == CPATH_STATE_OPEN
2031 && cpath_next != circ->cpath;
2032 cpath = cpath_next) {
2033 cpath_next = cpath->next;
2034 ++n;
2037 return n;
2040 /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
2041 * aren't that many hops in the list. <b>hopnum</b> starts at 1.
2042 * Returns NULL if <b>hopnum</b> is 0 or negative. */
2043 crypt_path_t *
2044 circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
2046 if (circ && circ->cpath && hopnum > 0) {
2047 crypt_path_t *cpath, *cpath_next = NULL;
2048 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
2049 cpath_next = cpath->next;
2050 if (--hopnum <= 0)
2051 return cpath;
2054 return NULL;
2057 /** Go through the circuitlist; mark-for-close each circuit that starts
2058 * at us but has not yet been used. */
2059 void
2060 circuit_mark_all_unused_circs(void)
2062 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
2063 if (CIRCUIT_IS_ORIGIN(circ) &&
2064 !circ->marked_for_close &&
2065 !circ->timestamp_dirty)
2066 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
2068 SMARTLIST_FOREACH_END(circ);
2071 /** Go through the circuitlist; for each circuit that starts at us
2072 * and is dirty, frob its timestamp_dirty so we won't use it for any
2073 * new streams.
2075 * This is useful for letting the user change pseudonyms, so new
2076 * streams will not be linkable to old streams.
2078 void
2079 circuit_mark_all_dirty_circs_as_unusable(void)
2081 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
2082 if (CIRCUIT_IS_ORIGIN(circ) &&
2083 !circ->marked_for_close &&
2084 circ->timestamp_dirty) {
2085 mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
2088 SMARTLIST_FOREACH_END(circ);
2092 * Report any queued cells on or_circuits as written in our bandwidth
2093 * totals, for the specified channel direction.
2095 * When we close a circuit or clear its cell queues, we've read
2096 * data and recorded those bytes in our read statistics, but we're
2097 * not going to write it. This discrepancy can be used by an adversary
2098 * to infer information from our public relay statistics and perform
2099 * attacks such as guard discovery.
2101 * This function is in the critical path of circuit_mark_for_close().
2102 * It must be (and is) O(1)!
2104 * See https://bugs.torproject.org/tpo/core/tor/23512
2106 void
2107 circuit_synchronize_written_or_bandwidth(const circuit_t *c,
2108 circuit_channel_direction_t dir)
2110 uint64_t cells;
2111 uint64_t cell_size;
2112 uint64_t written_sync;
2113 const channel_t *chan = NULL;
2114 const or_circuit_t *or_circ;
2116 if (!CIRCUIT_IS_ORCIRC(c))
2117 return;
2119 or_circ = CONST_TO_OR_CIRCUIT(c);
2121 if (dir == CIRCUIT_N_CHAN) {
2122 chan = c->n_chan;
2123 cells = c->n_chan_cells.n;
2124 } else {
2125 chan = or_circ->p_chan;
2126 cells = or_circ->p_chan_cells.n;
2129 /* If we still know the chan, determine real cell size. Otherwise,
2130 * assume it's a wide circid channel */
2131 if (chan)
2132 cell_size = get_cell_network_size(chan->wide_circ_ids);
2133 else
2134 cell_size = CELL_MAX_NETWORK_SIZE;
2136 /* If we know the channel, find out if it's IPv6. */
2137 tor_addr_t remote_addr;
2138 bool is_ipv6 = chan &&
2139 channel_get_addr_if_possible(chan, &remote_addr) &&
2140 tor_addr_family(&remote_addr) == AF_INET6;
2142 /* The missing written bytes are the cell counts times their cell
2143 * size plus TLS per cell overhead */
2144 written_sync = cells*(cell_size+TLS_PER_CELL_OVERHEAD);
2146 /* Report the missing bytes as written, to avoid asymmetry.
2147 * We must use time() for consistency with rephist, even though on
2148 * some very old rare platforms, approx_time() may be faster. */
2149 bwhist_note_bytes_written(written_sync, time(NULL), is_ipv6);
2152 /** Mark <b>circ</b> to be closed next time we call
2153 * circuit_close_all_marked(). Do any cleanup needed:
2154 * - If state is onionskin_pending, remove circ from the onion_pending
2155 * list.
2156 * - If circ isn't open yet: call circuit_build_failed() if we're
2157 * the origin.
2158 * - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
2159 * failure we just had to the hidden service client module.
2160 * - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
2161 * report to the hidden service client module that the intro point
2162 * we just tried may be unreachable.
2163 * - Send appropriate destroys and edge_destroys for conns and
2164 * streams attached to circ.
2165 * - If circ->rend_splice is set (we are the midpoint of a joined
2166 * rendezvous stream), then mark the other circuit to close as well.
2168 MOCK_IMPL(void,
2169 circuit_mark_for_close_, (circuit_t *circ, int reason, int line,
2170 const char *file))
2172 int orig_reason = reason; /* Passed to the controller */
2173 assert_circuit_ok(circ);
2174 tor_assert(line);
2175 tor_assert(file);
2177 /* Check whether the circuitpadding subsystem wants to block this close */
2178 if (circpad_marked_circuit_for_padding(circ, reason)) {
2179 return;
2182 if (circ->marked_for_close) {
2183 log_warn(LD_BUG,
2184 "Duplicate call to circuit_mark_for_close at %s:%d"
2185 " (first at %s:%d)", file, line,
2186 circ->marked_for_close_file, circ->marked_for_close);
2187 return;
2189 if (reason == END_CIRC_AT_ORIGIN) {
2190 if (!CIRCUIT_IS_ORIGIN(circ)) {
2191 log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
2192 "but circuit was not at origin. (called %s:%d, purpose=%d)",
2193 file, line, circ->purpose);
2195 reason = END_CIRC_REASON_NONE;
2198 if (CIRCUIT_IS_ORIGIN(circ)) {
2199 if (pathbias_check_close(TO_ORIGIN_CIRCUIT(circ), reason) == -1) {
2200 /* Don't close it yet, we need to test it first */
2201 return;
2204 /* We don't send reasons when closing circuits at the origin. */
2205 reason = END_CIRC_REASON_NONE;
2208 circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_N_CHAN);
2209 circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_P_CHAN);
2211 if (reason & END_CIRC_REASON_FLAG_REMOTE)
2212 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
2214 if (reason < END_CIRC_REASON_MIN_ || reason > END_CIRC_REASON_MAX_) {
2215 if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
2216 log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
2217 reason = END_CIRC_REASON_NONE;
2220 circ->marked_for_close = line;
2221 circ->marked_for_close_file = file;
2222 circ->marked_for_close_reason = reason;
2223 circ->marked_for_close_orig_reason = orig_reason;
2225 if (!CIRCUIT_IS_ORIGIN(circ)) {
2226 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2227 if (or_circ->rend_splice) {
2228 if (!or_circ->rend_splice->base_.marked_for_close) {
2229 /* do this after marking this circuit, to avoid infinite recursion. */
2230 circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
2232 or_circ->rend_splice = NULL;
2236 /* Notify the HS subsystem that this circuit is closing. */
2237 hs_circ_cleanup_on_close(circ);
2239 /* Update stats. */
2240 if (circ->ccontrol) {
2241 if (circ->ccontrol->in_slow_start) {
2242 /* If we are in slow start, only count the ss cwnd if we've sent
2243 * enough data to get RTT measurements such that we have a min
2244 * and a max RTT, and they are not the same. This prevents us from
2245 * averaging and reporting unused and low-use circuits here */
2246 if (circ->ccontrol->max_rtt_usec != circ->ccontrol->min_rtt_usec) {
2247 stats_circ_close_ss_cwnd_ma_count++;
2248 cc_stats_circ_close_ss_cwnd_ma =
2249 stats_update_running_avg(cc_stats_circ_close_ss_cwnd_ma,
2250 circ->ccontrol->cwnd,
2251 stats_circ_close_ss_cwnd_ma_count);
2253 } else {
2254 stats_circ_close_cwnd_ma_count++;
2255 cc_stats_circ_close_cwnd_ma =
2256 stats_update_running_avg(cc_stats_circ_close_cwnd_ma,
2257 circ->ccontrol->cwnd,
2258 stats_circ_close_cwnd_ma_count);
2262 if (circuits_pending_close == NULL)
2263 circuits_pending_close = smartlist_new();
2265 smartlist_add(circuits_pending_close, circ);
2266 mainloop_schedule_postloop_cleanup();
2268 log_info(LD_GENERAL, "Circuit %u (id: %" PRIu32 ") marked for close at "
2269 "%s:%d (orig reason: %d, new reason: %d)",
2270 circ->n_circ_id,
2271 CIRCUIT_IS_ORIGIN(circ) ?
2272 TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0,
2273 file, line, orig_reason, reason);
2274 tor_trace(TR_SUBSYS(circuit), TR_EV(mark_for_close), circ);
2277 /** Called immediately before freeing a marked circuit <b>circ</b> from
2278 * circuit_free_all() while shutting down Tor; this is a safe-at-shutdown
2279 * version of circuit_about_to_free(). It's important that it at least
2280 * do circuitmux_detach_circuit() when appropriate.
2282 static void
2283 circuit_about_to_free_atexit(circuit_t *circ)
2286 if (circ->n_chan) {
2287 circuit_clear_cell_queue(circ, circ->n_chan);
2288 circuitmux_detach_circuit(circ->n_chan->cmux, circ);
2289 circuit_set_n_circid_chan(circ, 0, NULL);
2292 if (! CIRCUIT_IS_ORIGIN(circ)) {
2293 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2295 if (or_circ->p_chan) {
2296 circuit_clear_cell_queue(circ, or_circ->p_chan);
2297 circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
2298 circuit_set_p_circid_chan(or_circ, 0, NULL);
2303 /** Called immediately before freeing a marked circuit <b>circ</b>.
2304 * Disconnects the circuit from other data structures, launches events
2305 * as appropriate, and performs other housekeeping.
2307 static void
2308 circuit_about_to_free(circuit_t *circ)
2311 int reason = circ->marked_for_close_reason;
2312 int orig_reason = circ->marked_for_close_orig_reason;
2314 if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
2315 onion_pending_remove(TO_OR_CIRCUIT(circ));
2317 /* If the circuit ever became OPEN, we sent it to the reputation history
2318 * module then. If it isn't OPEN, we send it there now to remember which
2319 * links worked and which didn't.
2321 if (circ->state != CIRCUIT_STATE_OPEN &&
2322 circ->state != CIRCUIT_STATE_GUARD_WAIT) {
2323 if (CIRCUIT_IS_ORIGIN(circ)) {
2324 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
2325 circuit_build_failed(ocirc); /* take actions if necessary */
2328 if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
2329 if (circuits_pending_chans)
2330 smartlist_remove(circuits_pending_chans, circ);
2332 if (circuits_pending_other_guards) {
2333 smartlist_remove(circuits_pending_other_guards, circ);
2335 if (CIRCUIT_IS_ORIGIN(circ)) {
2336 circuit_event_status(TO_ORIGIN_CIRCUIT(circ),
2337 (circ->state == CIRCUIT_STATE_OPEN ||
2338 circ->state == CIRCUIT_STATE_GUARD_WAIT) ?
2339 CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
2340 orig_reason);
2343 if (circ->n_chan) {
2344 circuit_clear_cell_queue(circ, circ->n_chan);
2345 /* Only send destroy if the channel isn't closing anyway */
2346 if (!CHANNEL_CONDEMNED(circ->n_chan)) {
2347 channel_send_destroy(circ->n_circ_id, circ->n_chan, reason);
2349 circuitmux_detach_circuit(circ->n_chan->cmux, circ);
2350 circuit_set_n_circid_chan(circ, 0, NULL);
2353 if (! CIRCUIT_IS_ORIGIN(circ)) {
2354 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
2355 edge_connection_t *conn;
2356 for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
2357 connection_edge_destroy(or_circ->p_circ_id, conn);
2358 or_circ->n_streams = NULL;
2360 while (or_circ->resolving_streams) {
2361 conn = or_circ->resolving_streams;
2362 or_circ->resolving_streams = conn->next_stream;
2363 if (!conn->base_.marked_for_close) {
2364 /* The client will see a DESTROY, and infer that the connections
2365 * are closing because the circuit is getting torn down. No need
2366 * to send an end cell. */
2367 conn->edge_has_sent_end = 1;
2368 conn->end_reason = END_STREAM_REASON_DESTROY;
2369 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
2370 connection_mark_for_close(TO_CONN(conn));
2372 conn->on_circuit = NULL;
2375 if (or_circ->p_chan) {
2376 circuit_clear_cell_queue(circ, or_circ->p_chan);
2377 /* Only send destroy if the channel isn't closing anyway */
2378 if (!CHANNEL_CONDEMNED(or_circ->p_chan)) {
2379 channel_send_destroy(or_circ->p_circ_id, or_circ->p_chan, reason);
2381 circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
2382 circuit_set_p_circid_chan(or_circ, 0, NULL);
2385 if (or_circ->n_cells_discarded_at_end) {
2386 time_t age = approx_time() - circ->timestamp_created.tv_sec;
2387 note_circ_closed_for_unrecognized_cells(
2388 age, or_circ->n_cells_discarded_at_end);
2390 } else {
2391 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
2392 edge_connection_t *conn;
2393 for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
2394 connection_edge_destroy(circ->n_circ_id, conn);
2395 ocirc->p_streams = NULL;
2399 /** Given a marked circuit <b>circ</b>, aggressively free its cell queues to
2400 * recover memory. */
2401 static void
2402 marked_circuit_free_cells(circuit_t *circ)
2404 if (!circ->marked_for_close) {
2405 log_warn(LD_BUG, "Called on non-marked circuit");
2406 return;
2408 cell_queue_clear(&circ->n_chan_cells);
2409 if (! CIRCUIT_IS_ORIGIN(circ)) {
2410 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
2411 cell_queue_clear(&orcirc->p_chan_cells);
2415 static size_t
2416 single_conn_free_bytes(connection_t *conn)
2418 size_t result = 0;
2419 if (conn->inbuf) {
2420 result += buf_allocation(conn->inbuf);
2421 buf_clear(conn->inbuf);
2423 if (conn->outbuf) {
2424 result += buf_allocation(conn->outbuf);
2425 buf_clear(conn->outbuf);
2427 if (conn->type == CONN_TYPE_DIR) {
2428 dir_connection_t *dir_conn = TO_DIR_CONN(conn);
2429 if (dir_conn->compress_state) {
2430 result += tor_compress_state_size(dir_conn->compress_state);
2431 tor_compress_free(dir_conn->compress_state);
2432 dir_conn->compress_state = NULL;
2435 return result;
2438 /** Aggressively free buffer contents on all the buffers of all streams in the
2439 * list starting at <b>stream</b>. Return the number of bytes recovered. */
2440 static size_t
2441 marked_circuit_streams_free_bytes(edge_connection_t *stream)
2443 size_t result = 0;
2444 for ( ; stream; stream = stream->next_stream) {
2445 connection_t *conn = TO_CONN(stream);
2446 result += single_conn_free_bytes(conn);
2447 if (conn->linked_conn) {
2448 result += single_conn_free_bytes(conn->linked_conn);
2451 return result;
2454 /** Aggressively free buffer contents on all the buffers of all streams on
2455 * circuit <b>c</b>. Return the number of bytes recovered. */
2456 static size_t
2457 marked_circuit_free_stream_bytes(circuit_t *c)
2459 if (CIRCUIT_IS_ORIGIN(c)) {
2460 return marked_circuit_streams_free_bytes(TO_ORIGIN_CIRCUIT(c)->p_streams);
2461 } else {
2462 return marked_circuit_streams_free_bytes(TO_OR_CIRCUIT(c)->n_streams);
2466 /** Return the number of cells used by the circuit <b>c</b>'s cell queues. */
2467 STATIC size_t
2468 n_cells_in_circ_queues(const circuit_t *c)
2470 size_t n = c->n_chan_cells.n;
2471 if (! CIRCUIT_IS_ORIGIN(c)) {
2472 circuit_t *cc = (circuit_t *) c;
2473 n += TO_OR_CIRCUIT(cc)->p_chan_cells.n;
2475 return n;
2478 /** Return the number of bytes allocated for <b>c</b>'s half-open streams. */
2479 static size_t
2480 circuit_alloc_in_half_streams(const circuit_t *c)
2482 if (! CIRCUIT_IS_ORIGIN(c)) {
2483 return 0;
2485 const origin_circuit_t *ocirc = CONST_TO_ORIGIN_CIRCUIT(c);
2486 if (ocirc->half_streams)
2487 return smartlist_len(ocirc->half_streams) * sizeof(half_edge_t);
2488 else
2489 return 0;
2493 * Return the age of the oldest cell queued on <b>c</b>, in timestamp units.
2494 * Return 0 if there are no cells queued on c. Requires that <b>now</b> be
2495 * the current coarse timestamp.
2497 * This function will return incorrect results if the oldest cell queued on
2498 * the circuit is older than about 2**32 msec (about 49 days) old.
2500 STATIC uint32_t
2501 circuit_max_queued_cell_age(const circuit_t *c, uint32_t now)
2503 uint32_t age = 0;
2504 packed_cell_t *cell;
2506 if (NULL != (cell = TOR_SIMPLEQ_FIRST(&c->n_chan_cells.head)))
2507 age = now - cell->inserted_timestamp;
2509 if (! CIRCUIT_IS_ORIGIN(c)) {
2510 const or_circuit_t *orcirc = CONST_TO_OR_CIRCUIT(c);
2511 if (NULL != (cell = TOR_SIMPLEQ_FIRST(&orcirc->p_chan_cells.head))) {
2512 uint32_t age2 = now - cell->inserted_timestamp;
2513 if (age2 > age)
2514 return age2;
2517 return age;
2520 /** Return the age of the oldest buffer chunk on <b>conn</b>, where age is
2521 * taken in timestamp units before the time <b>now</b>. If the connection has
2522 * no data, treat it as having age zero.
2524 static uint32_t
2525 conn_get_buffer_age(const connection_t *conn, uint32_t now_ts)
2527 uint32_t age = 0, age2;
2528 if (conn->outbuf) {
2529 age2 = buf_get_oldest_chunk_timestamp(conn->outbuf, now_ts);
2530 if (age2 > age)
2531 age = age2;
2533 if (conn->inbuf) {
2534 age2 = buf_get_oldest_chunk_timestamp(conn->inbuf, now_ts);
2535 if (age2 > age)
2536 age = age2;
2538 return age;
2541 /** Return the age in timestamp units of the oldest buffer chunk on any stream
2542 * in the linked list <b>stream</b>, where age is taken in timestamp units
2543 * before the timestamp <b>now</b>. */
2544 static uint32_t
2545 circuit_get_streams_max_data_age(const edge_connection_t *stream, uint32_t now)
2547 uint32_t age = 0, age2;
2548 for (; stream; stream = stream->next_stream) {
2549 const connection_t *conn = TO_CONN(stream);
2550 age2 = conn_get_buffer_age(conn, now);
2551 if (age2 > age)
2552 age = age2;
2553 if (conn->linked_conn) {
2554 age2 = conn_get_buffer_age(conn->linked_conn, now);
2555 if (age2 > age)
2556 age = age2;
2559 return age;
2562 /** Return the age in timestamp units of the oldest buffer chunk on any stream
2563 * attached to the circuit <b>c</b>, where age is taken before the timestamp
2564 * <b>now</b>. */
2565 STATIC uint32_t
2566 circuit_max_queued_data_age(const circuit_t *c, uint32_t now)
2568 if (CIRCUIT_IS_ORIGIN(c)) {
2569 return circuit_get_streams_max_data_age(
2570 CONST_TO_ORIGIN_CIRCUIT(c)->p_streams, now);
2571 } else {
2572 return circuit_get_streams_max_data_age(
2573 CONST_TO_OR_CIRCUIT(c)->n_streams, now);
2577 /** Return the age of the oldest cell or stream buffer chunk on the circuit
2578 * <b>c</b>, where age is taken in timestamp units before the timestamp
2579 * <b>now</b> */
2580 STATIC uint32_t
2581 circuit_max_queued_item_age(const circuit_t *c, uint32_t now)
2583 uint32_t cell_age = circuit_max_queued_cell_age(c, now);
2584 uint32_t data_age = circuit_max_queued_data_age(c, now);
2585 if (cell_age > data_age)
2586 return cell_age;
2587 else
2588 return data_age;
2591 /** Helper to sort a list of circuit_t by age of oldest item, in descending
2592 * order. */
2593 static int
2594 circuits_compare_by_oldest_queued_item_(const void **a_, const void **b_)
2596 const circuit_t *a = *a_;
2597 const circuit_t *b = *b_;
2598 uint32_t age_a = a->age_tmp;
2599 uint32_t age_b = b->age_tmp;
2601 if (age_a < age_b)
2602 return 1;
2603 else if (age_a == age_b)
2604 return 0;
2605 else
2606 return -1;
2609 static uint32_t now_ts_for_buf_cmp;
2611 /** Helper to sort a list of circuit_t by age of oldest item, in descending
2612 * order. */
2613 static int
2614 conns_compare_by_buffer_age_(const void **a_, const void **b_)
2616 const connection_t *a = *a_;
2617 const connection_t *b = *b_;
2618 time_t age_a = conn_get_buffer_age(a, now_ts_for_buf_cmp);
2619 time_t age_b = conn_get_buffer_age(b, now_ts_for_buf_cmp);
2621 if (age_a < age_b)
2622 return 1;
2623 else if (age_a == age_b)
2624 return 0;
2625 else
2626 return -1;
2629 #define FRACTION_OF_DATA_TO_RETAIN_ON_OOM 0.90
2631 /** We're out of memory for cells, having allocated <b>current_allocation</b>
2632 * bytes' worth. Kill the 'worst' circuits until we're under
2633 * FRACTION_OF_DATA_TO_RETAIN_ON_OOM of our maximum usage.
2635 * Return the number of bytes removed. */
2636 size_t
2637 circuits_handle_oom(size_t current_allocation)
2639 smartlist_t *circlist;
2640 smartlist_t *connection_array = get_connection_array();
2641 int conn_idx;
2642 size_t mem_to_recover;
2643 size_t mem_recovered=0;
2644 int n_circuits_killed=0;
2645 int n_dirconns_killed=0;
2646 int n_edgeconns_killed = 0;
2647 uint32_t now_ts;
2648 log_notice(LD_GENERAL, "We're low on memory (cell queues total alloc:"
2649 " %"TOR_PRIuSZ" buffer total alloc: %" TOR_PRIuSZ ","
2650 " tor compress total alloc: %" TOR_PRIuSZ
2651 " (zlib: %" TOR_PRIuSZ ", zstd: %" TOR_PRIuSZ ","
2652 " lzma: %" TOR_PRIuSZ "),"
2653 " rendezvous cache total alloc: %" TOR_PRIuSZ "). Killing"
2654 " circuits withover-long queues. (This behavior is controlled by"
2655 " MaxMemInQueues.)",
2656 cell_queues_get_total_allocation(),
2657 buf_get_total_allocation(),
2658 tor_compress_get_total_allocation(),
2659 tor_zlib_get_total_allocation(),
2660 tor_zstd_get_total_allocation(),
2661 tor_lzma_get_total_allocation(),
2662 hs_cache_get_total_allocation());
2664 size_t mem_target = (size_t)(get_options()->MaxMemInQueues *
2665 FRACTION_OF_DATA_TO_RETAIN_ON_OOM);
2666 if (current_allocation <= mem_target)
2667 return 0;
2668 mem_to_recover = current_allocation - mem_target;
2671 now_ts = monotime_coarse_get_stamp();
2673 circlist = circuit_get_global_list();
2674 SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
2675 circ->age_tmp = circuit_max_queued_item_age(circ, now_ts);
2676 } SMARTLIST_FOREACH_END(circ);
2678 /* This is O(n log n); there are faster algorithms we could use instead.
2679 * Let's hope this doesn't happen enough to be in the critical path. */
2680 smartlist_sort(circlist, circuits_compare_by_oldest_queued_item_);
2682 /* Fix up the indices before we run into trouble */
2683 SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
2684 circ->global_circuitlist_idx = circ_sl_idx;
2685 } SMARTLIST_FOREACH_END(circ);
2687 /* Now sort the connection array ... */
2688 now_ts_for_buf_cmp = now_ts;
2689 smartlist_sort(connection_array, conns_compare_by_buffer_age_);
2690 now_ts_for_buf_cmp = 0;
2692 /* Fix up the connection array to its new order. */
2693 SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
2694 conn->conn_array_index = conn_sl_idx;
2695 } SMARTLIST_FOREACH_END(conn);
2697 /* Okay, now the worst circuits and connections are at the front of their
2698 * respective lists. Let's mark them, and reclaim their storage
2699 * aggressively. */
2700 conn_idx = 0;
2701 SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
2702 size_t n;
2703 size_t freed;
2705 /* Free storage in any non-linked directory connections that have buffered
2706 * data older than this circuit. */
2707 while (conn_idx < smartlist_len(connection_array)) {
2708 connection_t *conn = smartlist_get(connection_array, conn_idx);
2709 uint32_t conn_age = conn_get_buffer_age(conn, now_ts);
2710 if (conn_age < circ->age_tmp) {
2711 break;
2713 /* Also consider edge connections so we don't accumulate bytes on the
2714 * outbuf due to a malicious destination holding off the read on us. */
2715 if ((conn->type == CONN_TYPE_DIR && conn->linked_conn == NULL) ||
2716 CONN_IS_EDGE(conn)) {
2717 if (!conn->marked_for_close)
2718 connection_mark_for_close(conn);
2719 mem_recovered += single_conn_free_bytes(conn);
2721 if (conn->type == CONN_TYPE_DIR) {
2722 ++n_dirconns_killed;
2723 } else {
2724 ++n_edgeconns_killed;
2727 if (mem_recovered >= mem_to_recover)
2728 goto done_recovering_mem;
2730 ++conn_idx;
2733 /* Now, kill the circuit. */
2734 n = n_cells_in_circ_queues(circ);
2735 const size_t half_stream_alloc = circuit_alloc_in_half_streams(circ);
2736 if (! circ->marked_for_close) {
2737 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
2739 marked_circuit_free_cells(circ);
2740 freed = marked_circuit_free_stream_bytes(circ);
2742 ++n_circuits_killed;
2744 mem_recovered += n * packed_cell_mem_cost();
2745 mem_recovered += half_stream_alloc;
2746 mem_recovered += freed;
2748 if (mem_recovered >= mem_to_recover)
2749 goto done_recovering_mem;
2750 } SMARTLIST_FOREACH_END(circ);
2752 done_recovering_mem:
2753 log_notice(LD_GENERAL, "Removed %"TOR_PRIuSZ" bytes by killing %d circuits; "
2754 "%d circuits remain alive. Also killed %d non-linked directory "
2755 "connections. Killed %d edge connections",
2756 mem_recovered,
2757 n_circuits_killed,
2758 smartlist_len(circlist) - n_circuits_killed,
2759 n_dirconns_killed,
2760 n_edgeconns_killed);
2762 return mem_recovered;
2765 /** Verify that circuit <b>c</b> has all of its invariants
2766 * correct. Trigger an assert if anything is invalid.
2768 MOCK_IMPL(void,
2769 assert_circuit_ok,(const circuit_t *c))
2771 edge_connection_t *conn;
2772 const or_circuit_t *or_circ = NULL;
2773 const origin_circuit_t *origin_circ = NULL;
2775 tor_assert(c);
2776 tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
2777 tor_assert(c->purpose >= CIRCUIT_PURPOSE_MIN_ &&
2778 c->purpose <= CIRCUIT_PURPOSE_MAX_);
2780 if (CIRCUIT_IS_ORIGIN(c))
2781 origin_circ = CONST_TO_ORIGIN_CIRCUIT(c);
2782 else
2783 or_circ = CONST_TO_OR_CIRCUIT(c);
2785 if (c->n_chan) {
2786 tor_assert(!c->n_hop);
2788 if (c->n_circ_id) {
2789 /* We use the _impl variant here to make sure we don't fail on marked
2790 * circuits, which would not be returned by the regular function. */
2791 circuit_t *c2 = circuit_get_by_circid_channel_impl(c->n_circ_id,
2792 c->n_chan, NULL);
2793 tor_assert(c == c2);
2796 if (or_circ && or_circ->p_chan) {
2797 if (or_circ->p_circ_id) {
2798 /* ibid */
2799 circuit_t *c2 =
2800 circuit_get_by_circid_channel_impl(or_circ->p_circ_id,
2801 or_circ->p_chan, NULL);
2802 tor_assert(c == c2);
2805 if (or_circ)
2806 for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
2807 tor_assert(conn->base_.type == CONN_TYPE_EXIT);
2809 tor_assert(c->deliver_window >= 0);
2810 tor_assert(c->package_window >= 0);
2811 if (c->state == CIRCUIT_STATE_OPEN ||
2812 c->state == CIRCUIT_STATE_GUARD_WAIT) {
2813 tor_assert(!c->n_chan_create_cell);
2814 if (or_circ) {
2815 relay_crypto_assert_ok(&or_circ->crypto);
2818 if (c->state == CIRCUIT_STATE_CHAN_WAIT && !c->marked_for_close) {
2819 tor_assert(circuits_pending_chans &&
2820 smartlist_contains(circuits_pending_chans, c));
2821 } else {
2822 tor_assert(!circuits_pending_chans ||
2823 !smartlist_contains(circuits_pending_chans, c));
2825 if (origin_circ && origin_circ->cpath) {
2826 cpath_assert_ok(origin_circ->cpath);
2828 if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
2829 tor_assert(or_circ);
2830 if (!c->marked_for_close) {
2831 tor_assert(or_circ->rend_splice);
2832 tor_assert(or_circ->rend_splice->rend_splice == or_circ);
2834 tor_assert(or_circ->rend_splice != or_circ);
2835 } else {
2836 tor_assert(!or_circ || !or_circ->rend_splice);