In routerlist_assert_ok(), check r2 before taking &(r2->cache_info)
[tor.git] / src / or / circuitlist.c
blobf3a83503efdb60095c59f563bb9944cf1a73f22f
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-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file circuitlist.c
9 * \brief Manage the global circuit list.
10 **/
11 #define CIRCUITLIST_PRIVATE
12 #include "or.h"
13 #include "channel.h"
14 #include "circpathbias.h"
15 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "circuituse.h"
18 #include "circuitstats.h"
19 #include "connection.h"
20 #include "config.h"
21 #include "connection_edge.h"
22 #include "connection_or.h"
23 #include "control.h"
24 #include "networkstatus.h"
25 #include "nodelist.h"
26 #include "onion.h"
27 #include "onion_fast.h"
28 #include "policies.h"
29 #include "relay.h"
30 #include "rendclient.h"
31 #include "rendcommon.h"
32 #include "rephist.h"
33 #include "routerlist.h"
34 #include "routerset.h"
36 #include "ht.h"
38 /********* START VARIABLES **********/
40 /** A global list of all circuits at this hop. */
41 struct global_circuitlist_s global_circuitlist =
42 TOR_LIST_HEAD_INITIALIZER(global_circuitlist);
44 /** A list of all the circuits in CIRCUIT_STATE_CHAN_WAIT. */
45 static smartlist_t *circuits_pending_chans = NULL;
47 static void circuit_free_cpath_node(crypt_path_t *victim);
48 static void cpath_ref_decref(crypt_path_reference_t *cpath_ref);
49 //static void circuit_set_rend_token(or_circuit_t *circ, int is_rend_circ,
50 // const uint8_t *token);
51 static void circuit_clear_rend_token(or_circuit_t *circ);
53 /********* END VARIABLES ************/
55 /** A map from channel and circuit ID to circuit. (Lookup performance is
56 * very important here, since we need to do it every time a cell arrives.) */
57 typedef struct chan_circid_circuit_map_t {
58 HT_ENTRY(chan_circid_circuit_map_t) node;
59 channel_t *chan;
60 circid_t circ_id;
61 circuit_t *circuit;
62 /* For debugging 12184: when was this placeholder item added? */
63 time_t made_placeholder_at;
64 } chan_circid_circuit_map_t;
66 /** Helper for hash tables: compare the channel and circuit ID for a and
67 * b, and return less than, equal to, or greater than zero appropriately.
69 static INLINE int
70 chan_circid_entries_eq_(chan_circid_circuit_map_t *a,
71 chan_circid_circuit_map_t *b)
73 return a->chan == b->chan && a->circ_id == b->circ_id;
76 /** Helper: return a hash based on circuit ID and the pointer value of
77 * chan in <b>a</b>. */
78 static INLINE unsigned int
79 chan_circid_entry_hash_(chan_circid_circuit_map_t *a)
81 /* Try to squeze the siphash input into 8 bytes to save any extra siphash
82 * rounds. This hash function is in the critical path. */
83 uintptr_t chan = (uintptr_t) (void*) a->chan;
84 uint32_t array[2];
85 array[0] = a->circ_id;
86 /* The low bits of the channel pointer are uninteresting, since the channel
87 * is a pretty big structure. */
88 array[1] = (uint32_t) (chan >> 6);
89 return (unsigned) siphash24g(array, sizeof(array));
92 /** Map from [chan,circid] to circuit. */
93 static HT_HEAD(chan_circid_map, chan_circid_circuit_map_t)
94 chan_circid_map = HT_INITIALIZER();
95 HT_PROTOTYPE(chan_circid_map, chan_circid_circuit_map_t, node,
96 chan_circid_entry_hash_, chan_circid_entries_eq_)
97 HT_GENERATE(chan_circid_map, chan_circid_circuit_map_t, node,
98 chan_circid_entry_hash_, chan_circid_entries_eq_, 0.6,
99 malloc, realloc, free)
101 /** The most recently returned entry from circuit_get_by_circid_chan;
102 * used to improve performance when many cells arrive in a row from the
103 * same circuit.
105 chan_circid_circuit_map_t *_last_circid_chan_ent = NULL;
107 /** Implementation helper for circuit_set_{p,n}_circid_channel: A circuit ID
108 * and/or channel for circ has just changed from <b>old_chan, old_id</b>
109 * to <b>chan, id</b>. Adjust the chan,circid map as appropriate, removing
110 * the old entry (if any) and adding a new one. */
111 static void
112 circuit_set_circid_chan_helper(circuit_t *circ, int direction,
113 circid_t id,
114 channel_t *chan)
116 chan_circid_circuit_map_t search;
117 chan_circid_circuit_map_t *found;
118 channel_t *old_chan, **chan_ptr;
119 circid_t old_id, *circid_ptr;
120 int make_active, attached = 0;
122 if (direction == CELL_DIRECTION_OUT) {
123 chan_ptr = &circ->n_chan;
124 circid_ptr = &circ->n_circ_id;
125 make_active = circ->n_chan_cells.n > 0;
126 } else {
127 or_circuit_t *c = TO_OR_CIRCUIT(circ);
128 chan_ptr = &c->p_chan;
129 circid_ptr = &c->p_circ_id;
130 make_active = c->p_chan_cells.n > 0;
132 old_chan = *chan_ptr;
133 old_id = *circid_ptr;
135 if (id == old_id && chan == old_chan)
136 return;
138 if (_last_circid_chan_ent &&
139 ((old_id == _last_circid_chan_ent->circ_id &&
140 old_chan == _last_circid_chan_ent->chan) ||
141 (id == _last_circid_chan_ent->circ_id &&
142 chan == _last_circid_chan_ent->chan))) {
143 _last_circid_chan_ent = NULL;
146 if (old_chan) {
148 * If we're changing channels or ID and had an old channel and a non
149 * zero old ID and weren't marked for close (i.e., we should have been
150 * attached), detach the circuit. ID changes require this because
151 * circuitmux hashes on (channel_id, circuit_id).
153 if (old_id != 0 && (old_chan != chan || old_id != id) &&
154 !(circ->marked_for_close)) {
155 tor_assert(old_chan->cmux);
156 circuitmux_detach_circuit(old_chan->cmux, circ);
159 /* we may need to remove it from the conn-circid map */
160 search.circ_id = old_id;
161 search.chan = old_chan;
162 found = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
163 if (found) {
164 tor_free(found);
165 if (direction == CELL_DIRECTION_OUT) {
166 /* One fewer circuits use old_chan as n_chan */
167 --(old_chan->num_n_circuits);
168 } else {
169 /* One fewer circuits use old_chan as p_chan */
170 --(old_chan->num_p_circuits);
175 /* Change the values only after we have possibly made the circuit inactive
176 * on the previous chan. */
177 *chan_ptr = chan;
178 *circid_ptr = id;
180 if (chan == NULL)
181 return;
183 /* now add the new one to the conn-circid map */
184 search.circ_id = id;
185 search.chan = chan;
186 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
187 if (found) {
188 found->circuit = circ;
189 found->made_placeholder_at = 0;
190 } else {
191 found = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
192 found->circ_id = id;
193 found->chan = chan;
194 found->circuit = circ;
195 HT_INSERT(chan_circid_map, &chan_circid_map, found);
199 * Attach to the circuitmux if we're changing channels or IDs and
200 * have a new channel and ID to use and the circuit is not marked for
201 * close.
203 if (chan && id != 0 && (old_chan != chan || old_id != id) &&
204 !(circ->marked_for_close)) {
205 tor_assert(chan->cmux);
206 circuitmux_attach_circuit(chan->cmux, circ, direction);
207 attached = 1;
211 * This is a no-op if we have no cells, but if we do it marks us active to
212 * the circuitmux
214 if (make_active && attached)
215 update_circuit_on_cmux(circ, direction);
217 /* Adjust circuit counts on new channel */
218 if (direction == CELL_DIRECTION_OUT) {
219 ++chan->num_n_circuits;
220 } else {
221 ++chan->num_p_circuits;
225 /** Mark that circuit id <b>id</b> shouldn't be used on channel <b>chan</b>,
226 * even if there is no circuit on the channel. We use this to keep the
227 * circuit id from getting re-used while we have queued but not yet sent
228 * a destroy cell. */
229 void
230 channel_mark_circid_unusable(channel_t *chan, circid_t id)
232 chan_circid_circuit_map_t search;
233 chan_circid_circuit_map_t *ent;
235 /* See if there's an entry there. That wouldn't be good. */
236 memset(&search, 0, sizeof(search));
237 search.chan = chan;
238 search.circ_id = id;
239 ent = HT_FIND(chan_circid_map, &chan_circid_map, &search);
241 if (ent && ent->circuit) {
242 /* we have a problem. */
243 log_warn(LD_BUG, "Tried to mark %u unusable on %p, but there was already "
244 "a circuit there.", (unsigned)id, chan);
245 } else if (ent) {
246 /* It's already marked. */
247 if (!ent->made_placeholder_at)
248 ent->made_placeholder_at = approx_time();
249 } else {
250 ent = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
251 ent->chan = chan;
252 ent->circ_id = id;
253 /* leave circuit at NULL. */
254 ent->made_placeholder_at = approx_time();
255 HT_INSERT(chan_circid_map, &chan_circid_map, ent);
259 /** Mark that a circuit id <b>id</b> can be used again on <b>chan</b>.
260 * We use this to re-enable the circuit ID after we've sent a destroy cell.
262 void
263 channel_mark_circid_usable(channel_t *chan, circid_t id)
265 chan_circid_circuit_map_t search;
266 chan_circid_circuit_map_t *ent;
268 /* See if there's an entry there. That wouldn't be good. */
269 memset(&search, 0, sizeof(search));
270 search.chan = chan;
271 search.circ_id = id;
272 ent = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
273 if (ent && ent->circuit) {
274 log_warn(LD_BUG, "Tried to mark %u usable on %p, but there was already "
275 "a circuit there.", (unsigned)id, chan);
276 return;
278 if (_last_circid_chan_ent == ent)
279 _last_circid_chan_ent = NULL;
280 tor_free(ent);
283 /** Called to indicate that a DESTROY is pending on <b>chan</b> with
284 * circuit ID <b>id</b>, but hasn't been sent yet. */
285 void
286 channel_note_destroy_pending(channel_t *chan, circid_t id)
288 circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
289 if (circ) {
290 if (circ->n_chan == chan && circ->n_circ_id == id) {
291 circ->n_delete_pending = 1;
292 } else {
293 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
294 if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
295 circ->p_delete_pending = 1;
298 return;
300 channel_mark_circid_unusable(chan, id);
303 /** Called to indicate that a DESTROY is no longer pending on <b>chan</b> with
304 * circuit ID <b>id</b> -- typically, because it has been sent. */
305 void
306 channel_note_destroy_not_pending(channel_t *chan, circid_t id)
308 circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
309 if (circ) {
310 if (circ->n_chan == chan && circ->n_circ_id == id) {
311 circ->n_delete_pending = 0;
312 } else {
313 or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
314 if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
315 circ->p_delete_pending = 0;
318 /* XXXX this shouldn't happen; log a bug here. */
319 return;
321 channel_mark_circid_usable(chan, id);
324 /** Set the p_conn field of a circuit <b>circ</b>, along
325 * with the corresponding circuit ID, and add the circuit as appropriate
326 * to the (chan,id)-\>circuit map. */
327 void
328 circuit_set_p_circid_chan(or_circuit_t *or_circ, circid_t id,
329 channel_t *chan)
331 circuit_t *circ = TO_CIRCUIT(or_circ);
332 channel_t *old_chan = or_circ->p_chan;
333 circid_t old_id = or_circ->p_circ_id;
335 circuit_set_circid_chan_helper(circ, CELL_DIRECTION_IN, id, chan);
337 if (chan) {
338 tor_assert(bool_eq(or_circ->p_chan_cells.n,
339 or_circ->next_active_on_p_chan));
341 chan->timestamp_last_had_circuits = approx_time();
344 if (circ->p_delete_pending && old_chan) {
345 channel_mark_circid_unusable(old_chan, old_id);
346 circ->p_delete_pending = 0;
350 /** Set the n_conn field of a circuit <b>circ</b>, along
351 * with the corresponding circuit ID, and add the circuit as appropriate
352 * to the (chan,id)-\>circuit map. */
353 void
354 circuit_set_n_circid_chan(circuit_t *circ, circid_t id,
355 channel_t *chan)
357 channel_t *old_chan = circ->n_chan;
358 circid_t old_id = circ->n_circ_id;
360 circuit_set_circid_chan_helper(circ, CELL_DIRECTION_OUT, id, chan);
362 if (chan) {
363 tor_assert(bool_eq(circ->n_chan_cells.n, circ->next_active_on_n_chan));
365 chan->timestamp_last_had_circuits = approx_time();
368 if (circ->n_delete_pending && old_chan) {
369 channel_mark_circid_unusable(old_chan, old_id);
370 circ->n_delete_pending = 0;
374 /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
375 * it from lists as appropriate. */
376 void
377 circuit_set_state(circuit_t *circ, uint8_t state)
379 tor_assert(circ);
380 if (state == circ->state)
381 return;
382 if (!circuits_pending_chans)
383 circuits_pending_chans = smartlist_new();
384 if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
385 /* remove from waiting-circuit list. */
386 smartlist_remove(circuits_pending_chans, circ);
388 if (state == CIRCUIT_STATE_CHAN_WAIT) {
389 /* add to waiting-circuit list. */
390 smartlist_add(circuits_pending_chans, circ);
392 if (state == CIRCUIT_STATE_OPEN)
393 tor_assert(!circ->n_chan_create_cell);
394 circ->state = state;
397 /** Append to <b>out</b> all circuits in state CHAN_WAIT waiting for
398 * the given connection. */
399 void
400 circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
402 tor_assert(out);
403 tor_assert(chan);
405 if (!circuits_pending_chans)
406 return;
408 SMARTLIST_FOREACH_BEGIN(circuits_pending_chans, circuit_t *, circ) {
409 if (circ->marked_for_close)
410 continue;
411 if (!circ->n_hop)
412 continue;
413 tor_assert(circ->state == CIRCUIT_STATE_CHAN_WAIT);
414 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
415 /* Look at addr/port. This is an unkeyed connection. */
416 if (!channel_matches_extend_info(chan, circ->n_hop))
417 continue;
418 } else {
419 /* We expected a key. See if it's the right one. */
420 if (tor_memneq(chan->identity_digest,
421 circ->n_hop->identity_digest, DIGEST_LEN))
422 continue;
424 smartlist_add(out, circ);
425 } SMARTLIST_FOREACH_END(circ);
428 /** Return the number of circuits in state CHAN_WAIT, waiting for the given
429 * channel. */
431 circuit_count_pending_on_channel(channel_t *chan)
433 int cnt;
434 smartlist_t *sl = smartlist_new();
436 tor_assert(chan);
438 circuit_get_all_pending_on_channel(sl, chan);
439 cnt = smartlist_len(sl);
440 smartlist_free(sl);
441 log_debug(LD_CIRC,"or_conn to %s at %s, %d pending circs",
442 chan->nickname ? chan->nickname : "NULL",
443 channel_get_canonical_remote_descr(chan),
444 cnt);
445 return cnt;
448 /** Detach from the global circuit list, and deallocate, all
449 * circuits that have been marked for close.
451 void
452 circuit_close_all_marked(void)
454 circuit_t *circ, *tmp;
455 TOR_LIST_FOREACH_SAFE(circ, &global_circuitlist, head, tmp)
456 if (circ->marked_for_close)
457 circuit_free(circ);
460 /** Return the head of the global linked list of circuits. */
461 MOCK_IMPL(struct global_circuitlist_s *,
462 circuit_get_global_list,(void))
464 return &global_circuitlist;
467 /** Function to make circ-\>state human-readable */
468 const char *
469 circuit_state_to_string(int state)
471 static char buf[64];
472 switch (state) {
473 case CIRCUIT_STATE_BUILDING: return "doing handshakes";
474 case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
475 case CIRCUIT_STATE_CHAN_WAIT: return "connecting to server";
476 case CIRCUIT_STATE_OPEN: return "open";
477 default:
478 log_warn(LD_BUG, "Unknown circuit state %d", state);
479 tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
480 return buf;
484 /** Map a circuit purpose to a string suitable to be displayed to a
485 * controller. */
486 const char *
487 circuit_purpose_to_controller_string(uint8_t purpose)
489 static char buf[32];
490 switch (purpose) {
491 case CIRCUIT_PURPOSE_OR:
492 case CIRCUIT_PURPOSE_INTRO_POINT:
493 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
494 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
495 return "SERVER"; /* A controller should never see these, actually. */
497 case CIRCUIT_PURPOSE_C_GENERAL:
498 return "GENERAL";
499 case CIRCUIT_PURPOSE_C_INTRODUCING:
500 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
501 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
502 return "HS_CLIENT_INTRO";
504 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
505 case CIRCUIT_PURPOSE_C_REND_READY:
506 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
507 case CIRCUIT_PURPOSE_C_REND_JOINED:
508 return "HS_CLIENT_REND";
510 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
511 case CIRCUIT_PURPOSE_S_INTRO:
512 return "HS_SERVICE_INTRO";
514 case CIRCUIT_PURPOSE_S_CONNECT_REND:
515 case CIRCUIT_PURPOSE_S_REND_JOINED:
516 return "HS_SERVICE_REND";
518 case CIRCUIT_PURPOSE_TESTING:
519 return "TESTING";
520 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
521 return "MEASURE_TIMEOUT";
522 case CIRCUIT_PURPOSE_CONTROLLER:
523 return "CONTROLLER";
524 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
525 return "PATH_BIAS_TESTING";
527 default:
528 tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
529 return buf;
533 /** Return a string specifying the state of the hidden-service circuit
534 * purpose <b>purpose</b>, or NULL if <b>purpose</b> is not a
535 * hidden-service-related circuit purpose. */
536 const char *
537 circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
539 switch (purpose)
541 default:
542 log_fn(LOG_WARN, LD_BUG,
543 "Unrecognized circuit purpose: %d",
544 (int)purpose);
545 tor_fragile_assert();
546 /* fall through */
548 case CIRCUIT_PURPOSE_OR:
549 case CIRCUIT_PURPOSE_C_GENERAL:
550 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
551 case CIRCUIT_PURPOSE_TESTING:
552 case CIRCUIT_PURPOSE_CONTROLLER:
553 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
554 return NULL;
556 case CIRCUIT_PURPOSE_INTRO_POINT:
557 return "OR_HSSI_ESTABLISHED";
558 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
559 return "OR_HSCR_ESTABLISHED";
560 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
561 return "OR_HS_R_JOINED";
563 case CIRCUIT_PURPOSE_C_INTRODUCING:
564 return "HSCI_CONNECTING";
565 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
566 return "HSCI_INTRO_SENT";
567 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
568 return "HSCI_DONE";
570 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
571 return "HSCR_CONNECTING";
572 case CIRCUIT_PURPOSE_C_REND_READY:
573 return "HSCR_ESTABLISHED_IDLE";
574 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
575 return "HSCR_ESTABLISHED_WAITING";
576 case CIRCUIT_PURPOSE_C_REND_JOINED:
577 return "HSCR_JOINED";
579 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
580 return "HSSI_CONNECTING";
581 case CIRCUIT_PURPOSE_S_INTRO:
582 return "HSSI_ESTABLISHED";
584 case CIRCUIT_PURPOSE_S_CONNECT_REND:
585 return "HSSR_CONNECTING";
586 case CIRCUIT_PURPOSE_S_REND_JOINED:
587 return "HSSR_JOINED";
591 /** Return a human-readable string for the circuit purpose <b>purpose</b>. */
592 const char *
593 circuit_purpose_to_string(uint8_t purpose)
595 static char buf[32];
597 switch (purpose)
599 case CIRCUIT_PURPOSE_OR:
600 return "Circuit at relay";
601 case CIRCUIT_PURPOSE_INTRO_POINT:
602 return "Acting as intro point";
603 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
604 return "Acting as rendevous (pending)";
605 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
606 return "Acting as rendevous (established)";
607 case CIRCUIT_PURPOSE_C_GENERAL:
608 return "General-purpose client";
609 case CIRCUIT_PURPOSE_C_INTRODUCING:
610 return "Hidden service client: Connecting to intro point";
611 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
612 return "Hidden service client: Waiting for ack from intro point";
613 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
614 return "Hidden service client: Received ack from intro point";
615 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
616 return "Hidden service client: Establishing rendezvous point";
617 case CIRCUIT_PURPOSE_C_REND_READY:
618 return "Hidden service client: Pending rendezvous point";
619 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
620 return "Hidden service client: Pending rendezvous point (ack received)";
621 case CIRCUIT_PURPOSE_C_REND_JOINED:
622 return "Hidden service client: Active rendezvous point";
623 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
624 return "Measuring circuit timeout";
626 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
627 return "Hidden service: Establishing introduction point";
628 case CIRCUIT_PURPOSE_S_INTRO:
629 return "Hidden service: Introduction point";
630 case CIRCUIT_PURPOSE_S_CONNECT_REND:
631 return "Hidden service: Connecting to rendezvous point";
632 case CIRCUIT_PURPOSE_S_REND_JOINED:
633 return "Hidden service: Active rendezvous point";
635 case CIRCUIT_PURPOSE_TESTING:
636 return "Testing circuit";
638 case CIRCUIT_PURPOSE_CONTROLLER:
639 return "Circuit made by controller";
641 case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
642 return "Path-bias testing circuit";
644 default:
645 tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
646 return buf;
650 /** Pick a reasonable package_window to start out for our circuits.
651 * Originally this was hard-coded at 1000, but now the consensus votes
652 * on the answer. See proposal 168. */
653 int32_t
654 circuit_initial_package_window(void)
656 int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START,
657 CIRCWINDOW_START_MIN,
658 CIRCWINDOW_START_MAX);
659 /* If the consensus tells us a negative number, we'd assert. */
660 if (num < 0)
661 num = CIRCWINDOW_START;
662 return num;
665 /** Initialize the common elements in a circuit_t, and add it to the global
666 * list. */
667 static void
668 init_circuit_base(circuit_t *circ)
670 tor_gettimeofday(&circ->timestamp_created);
672 // Gets reset when we send CREATE_FAST.
673 // circuit_expire_building() expects these to be equal
674 // until the orconn is built.
675 circ->timestamp_began = circ->timestamp_created;
677 circ->package_window = circuit_initial_package_window();
678 circ->deliver_window = CIRCWINDOW_START;
679 cell_queue_init(&circ->n_chan_cells);
681 TOR_LIST_INSERT_HEAD(&global_circuitlist, circ, head);
684 /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
685 * and <b>p_conn</b>. Add it to the global circuit list.
687 origin_circuit_t *
688 origin_circuit_new(void)
690 origin_circuit_t *circ;
691 /* never zero, since a global ID of 0 is treated specially by the
692 * controller */
693 static uint32_t n_circuits_allocated = 1;
695 circ = tor_malloc_zero(sizeof(origin_circuit_t));
696 circ->base_.magic = ORIGIN_CIRCUIT_MAGIC;
698 circ->next_stream_id = crypto_rand_int(1<<16);
699 circ->global_identifier = n_circuits_allocated++;
700 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
701 circ->remaining_relay_early_cells -= crypto_rand_int(2);
703 init_circuit_base(TO_CIRCUIT(circ));
705 circuit_build_times_update_last_circ(get_circuit_build_times_mutable());
707 return circ;
710 /** Allocate a new or_circuit_t, connected to <b>p_conn</b> as
711 * <b>p_circ_id</b>. If <b>p_conn</b> is NULL, the circuit is unattached. */
712 or_circuit_t *
713 or_circuit_new(circid_t p_circ_id, channel_t *p_chan)
715 /* CircIDs */
716 or_circuit_t *circ;
718 circ = tor_malloc_zero(sizeof(or_circuit_t));
719 circ->base_.magic = OR_CIRCUIT_MAGIC;
721 if (p_chan)
722 circuit_set_p_circid_chan(circ, p_circ_id, p_chan);
724 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
725 cell_queue_init(&circ->p_chan_cells);
727 init_circuit_base(TO_CIRCUIT(circ));
729 return circ;
732 /** Deallocate space associated with circ.
734 STATIC void
735 circuit_free(circuit_t *circ)
737 void *mem;
738 size_t memlen;
739 if (!circ)
740 return;
742 if (CIRCUIT_IS_ORIGIN(circ)) {
743 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
744 mem = ocirc;
745 memlen = sizeof(origin_circuit_t);
746 tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
747 if (ocirc->build_state) {
748 extend_info_free(ocirc->build_state->chosen_exit);
749 circuit_free_cpath_node(ocirc->build_state->pending_final_cpath);
750 cpath_ref_decref(ocirc->build_state->service_pending_final_cpath_ref);
752 tor_free(ocirc->build_state);
754 circuit_clear_cpath(ocirc);
756 crypto_pk_free(ocirc->intro_key);
757 rend_data_free(ocirc->rend_data);
759 tor_free(ocirc->dest_address);
760 if (ocirc->socks_username) {
761 memwipe(ocirc->socks_username, 0x12, ocirc->socks_username_len);
762 tor_free(ocirc->socks_username);
764 if (ocirc->socks_password) {
765 memwipe(ocirc->socks_password, 0x06, ocirc->socks_password_len);
766 tor_free(ocirc->socks_password);
768 addr_policy_list_free(ocirc->prepend_policy);
769 } else {
770 or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
771 /* Remember cell statistics for this circuit before deallocating. */
772 if (get_options()->CellStatistics)
773 rep_hist_buffer_stats_add_circ(circ, time(NULL));
774 mem = ocirc;
775 memlen = sizeof(or_circuit_t);
776 tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
778 crypto_cipher_free(ocirc->p_crypto);
779 crypto_digest_free(ocirc->p_digest);
780 crypto_cipher_free(ocirc->n_crypto);
781 crypto_digest_free(ocirc->n_digest);
783 circuit_clear_rend_token(ocirc);
785 if (ocirc->rend_splice) {
786 or_circuit_t *other = ocirc->rend_splice;
787 tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
788 other->rend_splice = NULL;
791 /* remove from map. */
792 circuit_set_p_circid_chan(ocirc, 0, NULL);
794 /* Clear cell queue _after_ removing it from the map. Otherwise our
795 * "active" checks will be violated. */
796 cell_queue_clear(&ocirc->p_chan_cells);
799 extend_info_free(circ->n_hop);
800 tor_free(circ->n_chan_create_cell);
802 TOR_LIST_REMOVE(circ, head);
804 /* Remove from map. */
805 circuit_set_n_circid_chan(circ, 0, NULL);
807 /* Clear cell queue _after_ removing it from the map. Otherwise our
808 * "active" checks will be violated. */
809 cell_queue_clear(&circ->n_chan_cells);
811 memwipe(mem, 0xAA, memlen); /* poison memory */
812 tor_free(mem);
815 /** Deallocate the linked list circ-><b>cpath</b>, and remove the cpath from
816 * <b>circ</b>. */
817 void
818 circuit_clear_cpath(origin_circuit_t *circ)
820 crypt_path_t *victim, *head, *cpath;
822 head = cpath = circ->cpath;
824 if (!cpath)
825 return;
827 /* it's a circular list, so we have to notice when we've
828 * gone through it once. */
829 while (cpath->next && cpath->next != head) {
830 victim = cpath;
831 cpath = victim->next;
832 circuit_free_cpath_node(victim);
835 circuit_free_cpath_node(cpath);
837 circ->cpath = NULL;
840 /** Release all storage held by circuits. */
841 void
842 circuit_free_all(void)
844 circuit_t *tmp, *tmp2;
846 TOR_LIST_FOREACH_SAFE(tmp, &global_circuitlist, head, tmp2) {
847 if (! CIRCUIT_IS_ORIGIN(tmp)) {
848 or_circuit_t *or_circ = TO_OR_CIRCUIT(tmp);
849 while (or_circ->resolving_streams) {
850 edge_connection_t *next_conn;
851 next_conn = or_circ->resolving_streams->next_stream;
852 connection_free(TO_CONN(or_circ->resolving_streams));
853 or_circ->resolving_streams = next_conn;
856 circuit_free(tmp);
859 smartlist_free(circuits_pending_chans);
860 circuits_pending_chans = NULL;
863 chan_circid_circuit_map_t **elt, **next, *c;
864 for (elt = HT_START(chan_circid_map, &chan_circid_map);
865 elt;
866 elt = next) {
867 c = *elt;
868 next = HT_NEXT_RMV(chan_circid_map, &chan_circid_map, elt);
870 tor_assert(c->circuit == NULL);
871 tor_free(c);
874 HT_CLEAR(chan_circid_map, &chan_circid_map);
877 /** Deallocate space associated with the cpath node <b>victim</b>. */
878 static void
879 circuit_free_cpath_node(crypt_path_t *victim)
881 if (!victim)
882 return;
884 crypto_cipher_free(victim->f_crypto);
885 crypto_cipher_free(victim->b_crypto);
886 crypto_digest_free(victim->f_digest);
887 crypto_digest_free(victim->b_digest);
888 onion_handshake_state_release(&victim->handshake_state);
889 crypto_dh_free(victim->rend_dh_handshake_state);
890 extend_info_free(victim->extend_info);
892 memwipe(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
893 tor_free(victim);
896 /** Release a crypt_path_reference_t*, which may be NULL. */
897 static void
898 cpath_ref_decref(crypt_path_reference_t *cpath_ref)
900 if (cpath_ref != NULL) {
901 if (--(cpath_ref->refcount) == 0) {
902 circuit_free_cpath_node(cpath_ref->cpath);
903 tor_free(cpath_ref);
908 /** A helper function for circuit_dump_by_conn() below. Log a bunch
909 * of information about circuit <b>circ</b>.
911 static void
912 circuit_dump_conn_details(int severity,
913 circuit_t *circ,
914 int conn_array_index,
915 const char *type,
916 circid_t this_circid,
917 circid_t other_circid)
919 tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
920 "(other side %u), state %d (%s), born %ld:",
921 conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
922 circ->state, circuit_state_to_string(circ->state),
923 (long)circ->timestamp_began.tv_sec);
924 if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
925 circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
929 /** Log, at severity <b>severity</b>, information about each circuit
930 * that is connected to <b>conn</b>.
932 void
933 circuit_dump_by_conn(connection_t *conn, int severity)
935 circuit_t *circ;
936 edge_connection_t *tmpconn;
938 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
939 circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
941 if (circ->marked_for_close) {
942 continue;
945 if (!CIRCUIT_IS_ORIGIN(circ)) {
946 p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
949 if (CIRCUIT_IS_ORIGIN(circ)) {
950 for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
951 tmpconn=tmpconn->next_stream) {
952 if (TO_CONN(tmpconn) == conn) {
953 circuit_dump_conn_details(severity, circ, conn->conn_array_index,
954 "App-ward", p_circ_id, n_circ_id);
959 if (! CIRCUIT_IS_ORIGIN(circ)) {
960 for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
961 tmpconn=tmpconn->next_stream) {
962 if (TO_CONN(tmpconn) == conn) {
963 circuit_dump_conn_details(severity, circ, conn->conn_array_index,
964 "Exit-ward", n_circ_id, p_circ_id);
971 /** Return the circuit whose global ID is <b>id</b>, or NULL if no
972 * such circuit exists. */
973 origin_circuit_t *
974 circuit_get_by_global_id(uint32_t id)
976 circuit_t *circ;
977 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
978 if (CIRCUIT_IS_ORIGIN(circ) &&
979 TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
980 if (circ->marked_for_close)
981 return NULL;
982 else
983 return TO_ORIGIN_CIRCUIT(circ);
986 return NULL;
989 /** Return a circ such that:
990 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
991 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
992 * Return NULL if no such circuit exists.
994 * If <b>found_entry_out</b> is provided, set it to true if we have a
995 * placeholder entry for circid/chan, and leave it unset otherwise.
997 static INLINE circuit_t *
998 circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan,
999 int *found_entry_out)
1001 chan_circid_circuit_map_t search;
1002 chan_circid_circuit_map_t *found;
1004 if (_last_circid_chan_ent &&
1005 circ_id == _last_circid_chan_ent->circ_id &&
1006 chan == _last_circid_chan_ent->chan) {
1007 found = _last_circid_chan_ent;
1008 } else {
1009 search.circ_id = circ_id;
1010 search.chan = chan;
1011 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
1012 _last_circid_chan_ent = found;
1014 if (found && found->circuit) {
1015 log_debug(LD_CIRC,
1016 "circuit_get_by_circid_channel_impl() returning circuit %p for"
1017 " circ_id %u, channel ID " U64_FORMAT " (%p)",
1018 found->circuit, (unsigned)circ_id,
1019 U64_PRINTF_ARG(chan->global_identifier), chan);
1020 if (found_entry_out)
1021 *found_entry_out = 1;
1022 return found->circuit;
1025 log_debug(LD_CIRC,
1026 "circuit_get_by_circid_channel_impl() found %s for"
1027 " circ_id %u, channel ID " U64_FORMAT " (%p)",
1028 found ? "placeholder" : "nothing",
1029 (unsigned)circ_id,
1030 U64_PRINTF_ARG(chan->global_identifier), chan);
1032 if (found_entry_out)
1033 *found_entry_out = found ? 1 : 0;
1035 return NULL;
1036 /* The rest of this checks for bugs. Disabled by default. */
1037 /* We comment it out because coverity complains otherwise.
1039 circuit_t *circ;
1040 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
1041 if (! CIRCUIT_IS_ORIGIN(circ)) {
1042 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1043 if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
1044 log_warn(LD_BUG,
1045 "circuit matches p_chan, but not in hash table (Bug!)");
1046 return circ;
1049 if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
1050 log_warn(LD_BUG,
1051 "circuit matches n_chan, but not in hash table (Bug!)");
1052 return circ;
1055 return NULL;
1056 } */
1059 /** Return a circ such that:
1060 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
1061 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
1062 * - circ is not marked for close.
1063 * Return NULL if no such circuit exists.
1065 circuit_t *
1066 circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
1068 circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
1069 if (!circ || circ->marked_for_close)
1070 return NULL;
1071 else
1072 return circ;
1075 /** Return a circ such that:
1076 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
1077 * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
1078 * Return NULL if no such circuit exists.
1080 circuit_t *
1081 circuit_get_by_circid_channel_even_if_marked(circid_t circ_id,
1082 channel_t *chan)
1084 return circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
1087 /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
1088 * circuit, marked or not, on <b>chan</b>, or if the circ ID is reserved until
1089 * a queued destroy cell can be sent.
1091 * (Return 1 if the circuit is present, marked or not; Return 2
1092 * if the circuit ID is pending a destroy.)
1095 circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
1097 int found = 0;
1098 if (circuit_get_by_circid_channel_impl(circ_id, chan, &found) != NULL)
1099 return 1;
1100 if (found)
1101 return 2;
1102 return 0;
1105 /** Helper for debugging 12184. Returns the time since which 'circ_id' has
1106 * been marked unusable on 'chan'. */
1107 time_t
1108 circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
1110 chan_circid_circuit_map_t search;
1111 chan_circid_circuit_map_t *found;
1113 memset(&search, 0, sizeof(search));
1114 search.circ_id = circ_id;
1115 search.chan = chan;
1117 found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
1119 if (! found || found->circuit)
1120 return 0;
1122 return found->made_placeholder_at;
1125 /** Return the circuit that a given edge connection is using. */
1126 circuit_t *
1127 circuit_get_by_edge_conn(edge_connection_t *conn)
1129 circuit_t *circ;
1131 circ = conn->on_circuit;
1132 tor_assert(!circ ||
1133 (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
1134 : circ->magic == OR_CIRCUIT_MAGIC));
1136 return circ;
1139 /** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
1140 * circuit from the chan,circid map, and mark it for close if it hasn't
1141 * been marked already.
1143 void
1144 circuit_unlink_all_from_channel(channel_t *chan, int reason)
1146 smartlist_t *detached = smartlist_new();
1148 /* #define DEBUG_CIRCUIT_UNLINK_ALL */
1150 channel_unlink_all_circuits(chan, detached);
1152 #ifdef DEBUG_CIRCUIT_UNLINK_ALL
1154 circuit_t *circ;
1155 smartlist_t *detached_2 = smartlist_new();
1156 int mismatch = 0, badlen = 0;
1158 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
1159 if (circ->n_chan == chan ||
1160 (!CIRCUIT_IS_ORIGIN(circ) &&
1161 TO_OR_CIRCUIT(circ)->p_chan == chan)) {
1162 smartlist_add(detached_2, circ);
1166 if (smartlist_len(detached) != smartlist_len(detached_2)) {
1167 log_warn(LD_BUG, "List of detached circuits had the wrong length! "
1168 "(got %d, should have gotten %d)",
1169 (int)smartlist_len(detached),
1170 (int)smartlist_len(detached_2));
1171 badlen = 1;
1173 smartlist_sort_pointers(detached);
1174 smartlist_sort_pointers(detached_2);
1176 SMARTLIST_FOREACH(detached, circuit_t *, c,
1177 if (c != smartlist_get(detached_2, c_sl_idx))
1178 mismatch = 1;
1181 if (mismatch)
1182 log_warn(LD_BUG, "Mismatch in list of detached circuits.");
1184 if (badlen || mismatch) {
1185 smartlist_free(detached);
1186 detached = detached_2;
1187 } else {
1188 log_notice(LD_CIRC, "List of %d circuits was as expected.",
1189 (int)smartlist_len(detached));
1190 smartlist_free(detached_2);
1193 #endif
1195 SMARTLIST_FOREACH_BEGIN(detached, circuit_t *, circ) {
1196 int mark = 0;
1197 if (circ->n_chan == chan) {
1199 circuit_set_n_circid_chan(circ, 0, NULL);
1200 mark = 1;
1202 /* If we didn't request this closure, pass the remote
1203 * bit to mark_for_close. */
1204 if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
1205 reason |= END_CIRC_REASON_FLAG_REMOTE;
1207 if (! CIRCUIT_IS_ORIGIN(circ)) {
1208 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1209 if (or_circ->p_chan == chan) {
1210 circuit_set_p_circid_chan(or_circ, 0, NULL);
1211 mark = 1;
1214 if (!mark) {
1215 log_warn(LD_BUG, "Circuit on detached list which I had no reason "
1216 "to mark");
1217 continue;
1219 if (!circ->marked_for_close)
1220 circuit_mark_for_close(circ, reason);
1221 } SMARTLIST_FOREACH_END(circ);
1223 smartlist_free(detached);
1226 /** Return a circ such that
1227 * - circ-\>rend_data-\>onion_address is equal to
1228 * <b>rend_data</b>-\>onion_address,
1229 * - circ-\>rend_data-\>rend_cookie is equal to
1230 * <b>rend_data</b>-\>rend_cookie, and
1231 * - circ-\>purpose is equal to CIRCUIT_PURPOSE_C_REND_READY.
1233 * Return NULL if no such circuit exists.
1235 origin_circuit_t *
1236 circuit_get_ready_rend_circ_by_rend_data(const rend_data_t *rend_data)
1238 circuit_t *circ;
1239 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
1240 if (!circ->marked_for_close &&
1241 circ->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
1242 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1243 if (ocirc->rend_data &&
1244 !rend_cmp_service_ids(rend_data->onion_address,
1245 ocirc->rend_data->onion_address) &&
1246 tor_memeq(ocirc->rend_data->rend_cookie,
1247 rend_data->rend_cookie,
1248 REND_COOKIE_LEN))
1249 return ocirc;
1252 return NULL;
1255 /** Return the first circuit originating here in global_circuitlist after
1256 * <b>start</b> whose purpose is <b>purpose</b>, and where
1257 * <b>digest</b> (if set) matches the rend_pk_digest field. Return NULL if no
1258 * circuit is found. If <b>start</b> is NULL, begin at the start of the list.
1260 origin_circuit_t *
1261 circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
1262 const char *digest, uint8_t purpose)
1264 circuit_t *circ;
1265 tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
1266 if (start == NULL)
1267 circ = TOR_LIST_FIRST(&global_circuitlist);
1268 else
1269 circ = TOR_LIST_NEXT(TO_CIRCUIT(start), head);
1271 for ( ; circ; circ = TOR_LIST_NEXT(circ, head)) {
1272 if (circ->marked_for_close)
1273 continue;
1274 if (circ->purpose != purpose)
1275 continue;
1276 if (!digest)
1277 return TO_ORIGIN_CIRCUIT(circ);
1278 else if (TO_ORIGIN_CIRCUIT(circ)->rend_data &&
1279 tor_memeq(TO_ORIGIN_CIRCUIT(circ)->rend_data->rend_pk_digest,
1280 digest, DIGEST_LEN))
1281 return TO_ORIGIN_CIRCUIT(circ);
1283 return NULL;
1286 /** Map from rendezvous cookie to or_circuit_t */
1287 static digestmap_t *rend_cookie_map = NULL;
1289 /** Map from introduction point digest to or_circuit_t */
1290 static digestmap_t *intro_digest_map = NULL;
1292 /** Return the OR circuit whose purpose is <b>purpose</b>, and whose
1293 * rend_token is the REND_TOKEN_LEN-byte <b>token</b>. If <b>is_rend_circ</b>,
1294 * look for rendezvous point circuits; otherwise look for introduction point
1295 * circuits. */
1296 static or_circuit_t *
1297 circuit_get_by_rend_token_and_purpose(uint8_t purpose, int is_rend_circ,
1298 const char *token)
1300 or_circuit_t *circ;
1301 digestmap_t *map = is_rend_circ ? rend_cookie_map : intro_digest_map;
1303 if (!map)
1304 return NULL;
1306 circ = digestmap_get(map, token);
1307 if (!circ ||
1308 circ->base_.purpose != purpose ||
1309 circ->base_.marked_for_close)
1310 return NULL;
1312 if (!circ->rendinfo) {
1313 char *t = tor_strdup(hex_str(token, REND_TOKEN_LEN));
1314 log_warn(LD_BUG, "Wanted a circuit with %s:%d, but lookup returned a "
1315 "circuit with no rendinfo set.",
1316 safe_str(t), is_rend_circ);
1317 tor_free(t);
1318 return NULL;
1321 if (! bool_eq(circ->rendinfo->is_rend_circ, is_rend_circ) ||
1322 tor_memneq(circ->rendinfo->rend_token, token, REND_TOKEN_LEN)) {
1323 char *t = tor_strdup(hex_str(token, REND_TOKEN_LEN));
1324 log_warn(LD_BUG, "Wanted a circuit with %s:%d, but lookup returned %s:%d",
1325 safe_str(t), is_rend_circ,
1326 safe_str(hex_str(circ->rendinfo->rend_token, REND_TOKEN_LEN)),
1327 (int)circ->rendinfo->is_rend_circ);
1328 tor_free(t);
1329 return NULL;
1332 return circ;
1335 /** Clear the rendezvous cookie or introduction point key digest that's
1336 * configured on <b>circ</b>, if any, and remove it from any such maps. */
1337 static void
1338 circuit_clear_rend_token(or_circuit_t *circ)
1340 or_circuit_t *found_circ;
1341 digestmap_t *map;
1343 if (!circ || !circ->rendinfo)
1344 return;
1346 map = circ->rendinfo->is_rend_circ ? rend_cookie_map : intro_digest_map;
1348 if (!map) {
1349 log_warn(LD_BUG, "Tried to clear rend token on circuit, but found no map");
1350 return;
1353 found_circ = digestmap_get(map, circ->rendinfo->rend_token);
1354 if (found_circ == circ) {
1355 /* Great, this is the right one. */
1356 digestmap_remove(map, circ->rendinfo->rend_token);
1357 } else if (found_circ) {
1358 log_warn(LD_BUG, "Tried to clear rend token on circuit, but "
1359 "it was already replaced in the map.");
1360 } else {
1361 log_warn(LD_BUG, "Tried to clear rend token on circuit, but "
1362 "it not in the map at all.");
1365 tor_free(circ->rendinfo); /* Sets it to NULL too */
1368 /** Set the rendezvous cookie (if is_rend_circ), or the introduction point
1369 * digest (if ! is_rend_circ) of <b>circ</b> to the REND_TOKEN_LEN-byte value
1370 * in <b>token</b>, and add it to the appropriate map. If it previously had a
1371 * token, clear it. If another circuit previously had the same
1372 * cookie/intro-digest, mark that circuit and remove it from the map. */
1373 static void
1374 circuit_set_rend_token(or_circuit_t *circ, int is_rend_circ,
1375 const uint8_t *token)
1377 digestmap_t **map_p, *map;
1378 or_circuit_t *found_circ;
1380 /* Find the right map, creating it as needed */
1381 map_p = is_rend_circ ? &rend_cookie_map : &intro_digest_map;
1383 if (!*map_p)
1384 *map_p = digestmap_new();
1386 map = *map_p;
1388 /* If this circuit already has a token, we need to remove that. */
1389 if (circ->rendinfo)
1390 circuit_clear_rend_token(circ);
1392 if (token == NULL) {
1393 /* We were only trying to remove this token, not set a new one. */
1394 return;
1397 found_circ = digestmap_get(map, (const char *)token);
1398 if (found_circ) {
1399 tor_assert(found_circ != circ);
1400 circuit_clear_rend_token(found_circ);
1401 if (! found_circ->base_.marked_for_close) {
1402 circuit_mark_for_close(TO_CIRCUIT(found_circ), END_CIRC_REASON_FINISHED);
1403 if (is_rend_circ) {
1404 log_fn(LOG_PROTOCOL_WARN, LD_REND,
1405 "Duplicate rendezvous cookie (%s...) used on two circuits",
1406 hex_str((const char*)token, 4)); /* only log first 4 chars */
1411 /* Now set up the rendinfo */
1412 circ->rendinfo = tor_malloc(sizeof(*circ->rendinfo));
1413 memcpy(circ->rendinfo->rend_token, token, REND_TOKEN_LEN);
1414 circ->rendinfo->is_rend_circ = is_rend_circ ? 1 : 0;
1416 digestmap_set(map, (const char *)token, circ);
1419 /** Return the circuit waiting for a rendezvous with the provided cookie.
1420 * Return NULL if no such circuit is found.
1422 or_circuit_t *
1423 circuit_get_rendezvous(const uint8_t *cookie)
1425 return circuit_get_by_rend_token_and_purpose(
1426 CIRCUIT_PURPOSE_REND_POINT_WAITING,
1427 1, (const char*)cookie);
1430 /** Return the circuit waiting for intro cells of the given digest.
1431 * Return NULL if no such circuit is found.
1433 or_circuit_t *
1434 circuit_get_intro_point(const uint8_t *digest)
1436 return circuit_get_by_rend_token_and_purpose(
1437 CIRCUIT_PURPOSE_INTRO_POINT, 0,
1438 (const char *)digest);
1441 /** Set the rendezvous cookie of <b>circ</b> to <b>cookie</b>. If another
1442 * circuit previously had that cookie, mark it. */
1443 void
1444 circuit_set_rendezvous_cookie(or_circuit_t *circ, const uint8_t *cookie)
1446 circuit_set_rend_token(circ, 1, cookie);
1449 /** Set the intro point key digest of <b>circ</b> to <b>cookie</b>. If another
1450 * circuit previously had that intro point digest, mark it. */
1451 void
1452 circuit_set_intro_point_digest(or_circuit_t *circ, const uint8_t *digest)
1454 circuit_set_rend_token(circ, 0, digest);
1457 /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
1458 * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
1459 * flags in <b>flags</b>, and if info is defined, does not already use info
1460 * as any of its hops; or NULL if no circuit fits this description.
1462 * The <b>purpose</b> argument (currently ignored) refers to the purpose of
1463 * the circuit we want to create, not the purpose of the circuit we want to
1464 * cannibalize.
1466 * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
1468 origin_circuit_t *
1469 circuit_find_to_cannibalize(uint8_t purpose, extend_info_t *info,
1470 int flags)
1472 circuit_t *circ_;
1473 origin_circuit_t *best=NULL;
1474 int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
1475 int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
1476 int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
1477 const or_options_t *options = get_options();
1479 /* Make sure we're not trying to create a onehop circ by
1480 * cannibalization. */
1481 tor_assert(!(flags & CIRCLAUNCH_ONEHOP_TUNNEL));
1483 log_debug(LD_CIRC,
1484 "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
1485 "capacity %d, internal %d",
1486 purpose, need_uptime, need_capacity, internal);
1488 TOR_LIST_FOREACH(circ_, &global_circuitlist, head) {
1489 if (CIRCUIT_IS_ORIGIN(circ_) &&
1490 circ_->state == CIRCUIT_STATE_OPEN &&
1491 !circ_->marked_for_close &&
1492 circ_->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
1493 !circ_->timestamp_dirty) {
1494 origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
1495 if ((!need_uptime || circ->build_state->need_uptime) &&
1496 (!need_capacity || circ->build_state->need_capacity) &&
1497 (internal == circ->build_state->is_internal) &&
1498 !circ->unusable_for_new_conns &&
1499 circ->remaining_relay_early_cells &&
1500 circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN &&
1501 !circ->build_state->onehop_tunnel &&
1502 !circ->isolation_values_set) {
1503 if (info) {
1504 /* need to make sure we don't duplicate hops */
1505 crypt_path_t *hop = circ->cpath;
1506 const node_t *ri1 = node_get_by_id(info->identity_digest);
1507 do {
1508 const node_t *ri2;
1509 if (tor_memeq(hop->extend_info->identity_digest,
1510 info->identity_digest, DIGEST_LEN))
1511 goto next;
1512 if (ri1 &&
1513 (ri2 = node_get_by_id(hop->extend_info->identity_digest))
1514 && nodes_in_same_family(ri1, ri2))
1515 goto next;
1516 hop=hop->next;
1517 } while (hop!=circ->cpath);
1519 if (options->ExcludeNodes) {
1520 /* Make sure no existing nodes in the circuit are excluded for
1521 * general use. (This may be possible if StrictNodes is 0, and we
1522 * thought we needed to use an otherwise excluded node for, say, a
1523 * directory operation.) */
1524 crypt_path_t *hop = circ->cpath;
1525 do {
1526 if (routerset_contains_extendinfo(options->ExcludeNodes,
1527 hop->extend_info))
1528 goto next;
1529 hop = hop->next;
1530 } while (hop != circ->cpath);
1532 if (!best || (best->build_state->need_uptime && !need_uptime))
1533 best = circ;
1534 next: ;
1538 return best;
1541 /** Return the number of hops in circuit's path. */
1543 circuit_get_cpath_len(origin_circuit_t *circ)
1545 int n = 0;
1546 if (circ && circ->cpath) {
1547 crypt_path_t *cpath, *cpath_next = NULL;
1548 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1549 cpath_next = cpath->next;
1550 ++n;
1553 return n;
1556 /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
1557 * aren't that many hops in the list. */
1558 crypt_path_t *
1559 circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
1561 if (circ && circ->cpath && hopnum > 0) {
1562 crypt_path_t *cpath, *cpath_next = NULL;
1563 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
1564 cpath_next = cpath->next;
1565 if (--hopnum <= 0)
1566 return cpath;
1569 return NULL;
1572 /** Go through the circuitlist; mark-for-close each circuit that starts
1573 * at us but has not yet been used. */
1574 void
1575 circuit_mark_all_unused_circs(void)
1577 circuit_t *circ;
1578 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
1579 if (CIRCUIT_IS_ORIGIN(circ) &&
1580 !circ->marked_for_close &&
1581 !circ->timestamp_dirty)
1582 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1586 /** Go through the circuitlist; for each circuit that starts at us
1587 * and is dirty, frob its timestamp_dirty so we won't use it for any
1588 * new streams.
1590 * This is useful for letting the user change pseudonyms, so new
1591 * streams will not be linkable to old streams.
1593 void
1594 circuit_mark_all_dirty_circs_as_unusable(void)
1596 circuit_t *circ;
1597 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
1598 if (CIRCUIT_IS_ORIGIN(circ) &&
1599 !circ->marked_for_close &&
1600 circ->timestamp_dirty) {
1601 mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
1606 /** Mark <b>circ</b> to be closed next time we call
1607 * circuit_close_all_marked(). Do any cleanup needed:
1608 * - If state is onionskin_pending, remove circ from the onion_pending
1609 * list.
1610 * - If circ isn't open yet: call circuit_build_failed() if we're
1611 * the origin, and in either case call circuit_rep_hist_note_result()
1612 * to note stats.
1613 * - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
1614 * failure we just had to the hidden service client module.
1615 * - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
1616 * report to the hidden service client module that the intro point
1617 * we just tried may be unreachable.
1618 * - Send appropriate destroys and edge_destroys for conns and
1619 * streams attached to circ.
1620 * - If circ->rend_splice is set (we are the midpoint of a joined
1621 * rendezvous stream), then mark the other circuit to close as well.
1623 MOCK_IMPL(void,
1624 circuit_mark_for_close_, (circuit_t *circ, int reason, int line,
1625 const char *file))
1627 int orig_reason = reason; /* Passed to the controller */
1628 assert_circuit_ok(circ);
1629 tor_assert(line);
1630 tor_assert(file);
1632 if (circ->marked_for_close) {
1633 log_warn(LD_BUG,
1634 "Duplicate call to circuit_mark_for_close at %s:%d"
1635 " (first at %s:%d)", file, line,
1636 circ->marked_for_close_file, circ->marked_for_close);
1637 return;
1639 if (reason == END_CIRC_AT_ORIGIN) {
1640 if (!CIRCUIT_IS_ORIGIN(circ)) {
1641 log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
1642 "but circuit was not at origin. (called %s:%d, purpose=%d)",
1643 file, line, circ->purpose);
1645 reason = END_CIRC_REASON_NONE;
1648 if (CIRCUIT_IS_ORIGIN(circ)) {
1649 if (pathbias_check_close(TO_ORIGIN_CIRCUIT(circ), reason) == -1) {
1650 /* Don't close it yet, we need to test it first */
1651 return;
1654 /* We don't send reasons when closing circuits at the origin. */
1655 reason = END_CIRC_REASON_NONE;
1658 if (reason & END_CIRC_REASON_FLAG_REMOTE)
1659 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
1661 if (reason < END_CIRC_REASON_MIN_ || reason > END_CIRC_REASON_MAX_) {
1662 if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
1663 log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
1664 reason = END_CIRC_REASON_NONE;
1667 if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
1668 onion_pending_remove(TO_OR_CIRCUIT(circ));
1670 /* If the circuit ever became OPEN, we sent it to the reputation history
1671 * module then. If it isn't OPEN, we send it there now to remember which
1672 * links worked and which didn't.
1674 if (circ->state != CIRCUIT_STATE_OPEN) {
1675 if (CIRCUIT_IS_ORIGIN(circ)) {
1676 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1677 circuit_build_failed(ocirc); /* take actions if necessary */
1678 circuit_rep_hist_note_result(ocirc);
1681 if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
1682 if (circuits_pending_chans)
1683 smartlist_remove(circuits_pending_chans, circ);
1685 if (CIRCUIT_IS_ORIGIN(circ)) {
1686 control_event_circuit_status(TO_ORIGIN_CIRCUIT(circ),
1687 (circ->state == CIRCUIT_STATE_OPEN)?CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
1688 orig_reason);
1690 if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1691 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1692 int timed_out = (reason == END_CIRC_REASON_TIMEOUT);
1693 tor_assert(circ->state == CIRCUIT_STATE_OPEN);
1694 tor_assert(ocirc->build_state->chosen_exit);
1695 tor_assert(ocirc->rend_data);
1696 /* treat this like getting a nack from it */
1697 log_info(LD_REND, "Failed intro circ %s to %s (awaiting ack). %s",
1698 safe_str_client(ocirc->rend_data->onion_address),
1699 safe_str_client(build_state_get_exit_nickname(ocirc->build_state)),
1700 timed_out ? "Recording timeout." : "Removing from descriptor.");
1701 rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
1702 ocirc->rend_data,
1703 timed_out ?
1704 INTRO_POINT_FAILURE_TIMEOUT :
1705 INTRO_POINT_FAILURE_GENERIC);
1706 } else if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
1707 reason != END_CIRC_REASON_TIMEOUT) {
1708 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1709 if (ocirc->build_state->chosen_exit && ocirc->rend_data) {
1710 log_info(LD_REND, "Failed intro circ %s to %s "
1711 "(building circuit to intro point). "
1712 "Marking intro point as possibly unreachable.",
1713 safe_str_client(ocirc->rend_data->onion_address),
1714 safe_str_client(build_state_get_exit_nickname(ocirc->build_state)));
1715 rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
1716 ocirc->rend_data,
1717 INTRO_POINT_FAILURE_UNREACHABLE);
1720 if (circ->n_chan) {
1721 circuit_clear_cell_queue(circ, circ->n_chan);
1722 /* Only send destroy if the channel isn't closing anyway */
1723 if (!(circ->n_chan->state == CHANNEL_STATE_CLOSING ||
1724 circ->n_chan->state == CHANNEL_STATE_CLOSED ||
1725 circ->n_chan->state == CHANNEL_STATE_ERROR)) {
1726 channel_send_destroy(circ->n_circ_id, circ->n_chan, reason);
1728 circuitmux_detach_circuit(circ->n_chan->cmux, circ);
1729 circuit_set_n_circid_chan(circ, 0, NULL);
1732 if (! CIRCUIT_IS_ORIGIN(circ)) {
1733 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1734 edge_connection_t *conn;
1735 for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
1736 connection_edge_destroy(or_circ->p_circ_id, conn);
1737 or_circ->n_streams = NULL;
1739 while (or_circ->resolving_streams) {
1740 conn = or_circ->resolving_streams;
1741 or_circ->resolving_streams = conn->next_stream;
1742 if (!conn->base_.marked_for_close) {
1743 /* The client will see a DESTROY, and infer that the connections
1744 * are closing because the circuit is getting torn down. No need
1745 * to send an end cell. */
1746 conn->edge_has_sent_end = 1;
1747 conn->end_reason = END_STREAM_REASON_DESTROY;
1748 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
1749 connection_mark_for_close(TO_CONN(conn));
1751 conn->on_circuit = NULL;
1754 if (or_circ->p_chan) {
1755 circuit_clear_cell_queue(circ, or_circ->p_chan);
1756 /* Only send destroy if the channel isn't closing anyway */
1757 if (!(or_circ->p_chan->state == CHANNEL_STATE_CLOSING ||
1758 or_circ->p_chan->state == CHANNEL_STATE_CLOSED ||
1759 or_circ->p_chan->state == CHANNEL_STATE_ERROR)) {
1760 channel_send_destroy(or_circ->p_circ_id, or_circ->p_chan, reason);
1762 circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
1763 circuit_set_p_circid_chan(or_circ, 0, NULL);
1765 } else {
1766 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1767 edge_connection_t *conn;
1768 for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
1769 connection_edge_destroy(circ->n_circ_id, conn);
1770 ocirc->p_streams = NULL;
1773 circ->marked_for_close = line;
1774 circ->marked_for_close_file = file;
1776 if (!CIRCUIT_IS_ORIGIN(circ)) {
1777 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1778 if (or_circ->rend_splice) {
1779 if (!or_circ->rend_splice->base_.marked_for_close) {
1780 /* do this after marking this circuit, to avoid infinite recursion. */
1781 circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
1783 or_circ->rend_splice = NULL;
1788 /** Given a marked circuit <b>circ</b>, aggressively free its cell queues to
1789 * recover memory. */
1790 static void
1791 marked_circuit_free_cells(circuit_t *circ)
1793 if (!circ->marked_for_close) {
1794 log_warn(LD_BUG, "Called on non-marked circuit");
1795 return;
1797 cell_queue_clear(&circ->n_chan_cells);
1798 if (! CIRCUIT_IS_ORIGIN(circ))
1799 cell_queue_clear(& TO_OR_CIRCUIT(circ)->p_chan_cells);
1802 /** Aggressively free buffer contents on all the buffers of all streams in the
1803 * list starting at <b>stream</b>. Return the number of bytes recovered. */
1804 static size_t
1805 marked_circuit_streams_free_bytes(edge_connection_t *stream)
1807 size_t result = 0;
1808 for ( ; stream; stream = stream->next_stream) {
1809 connection_t *conn = TO_CONN(stream);
1810 if (conn->inbuf) {
1811 result += buf_allocation(conn->inbuf);
1812 buf_clear(conn->inbuf);
1814 if (conn->outbuf) {
1815 result += buf_allocation(conn->outbuf);
1816 buf_clear(conn->outbuf);
1819 return result;
1822 /** Aggressively free buffer contents on all the buffers of all streams on
1823 * circuit <b>c</b>. Return the number of bytes recovered. */
1824 static size_t
1825 marked_circuit_free_stream_bytes(circuit_t *c)
1827 if (CIRCUIT_IS_ORIGIN(c)) {
1828 return marked_circuit_streams_free_bytes(TO_ORIGIN_CIRCUIT(c)->p_streams);
1829 } else {
1830 return marked_circuit_streams_free_bytes(TO_OR_CIRCUIT(c)->n_streams);
1834 /** Return the number of cells used by the circuit <b>c</b>'s cell queues. */
1835 STATIC size_t
1836 n_cells_in_circ_queues(const circuit_t *c)
1838 size_t n = c->n_chan_cells.n;
1839 if (! CIRCUIT_IS_ORIGIN(c)) {
1840 circuit_t *cc = (circuit_t *) c;
1841 n += TO_OR_CIRCUIT(cc)->p_chan_cells.n;
1843 return n;
1847 * Return the age of the oldest cell queued on <b>c</b>, in milliseconds.
1848 * Return 0 if there are no cells queued on c. Requires that <b>now</b> be
1849 * the current time in milliseconds since the epoch, truncated.
1851 * This function will return incorrect results if the oldest cell queued on
1852 * the circuit is older than 2**32 msec (about 49 days) old.
1854 STATIC uint32_t
1855 circuit_max_queued_cell_age(const circuit_t *c, uint32_t now)
1857 uint32_t age = 0;
1858 packed_cell_t *cell;
1860 if (NULL != (cell = TOR_SIMPLEQ_FIRST(&c->n_chan_cells.head)))
1861 age = now - cell->inserted_time;
1863 if (! CIRCUIT_IS_ORIGIN(c)) {
1864 const or_circuit_t *orcirc = CONST_TO_OR_CIRCUIT(c);
1865 if (NULL != (cell = TOR_SIMPLEQ_FIRST(&orcirc->p_chan_cells.head))) {
1866 uint32_t age2 = now - cell->inserted_time;
1867 if (age2 > age)
1868 return age2;
1871 return age;
1874 /** Return the age in milliseconds of the oldest buffer chunk on any stream in
1875 * the linked list <b>stream</b>, where age is taken in milliseconds before
1876 * the time <b>now</b> (in truncated milliseconds since the epoch). */
1877 static uint32_t
1878 circuit_get_streams_max_data_age(const edge_connection_t *stream, uint32_t now)
1880 uint32_t age = 0, age2;
1881 for (; stream; stream = stream->next_stream) {
1882 const connection_t *conn = TO_CONN(stream);
1883 if (conn->outbuf) {
1884 age2 = buf_get_oldest_chunk_timestamp(conn->outbuf, now);
1885 if (age2 > age)
1886 age = age2;
1888 if (conn->inbuf) {
1889 age2 = buf_get_oldest_chunk_timestamp(conn->inbuf, now);
1890 if (age2 > age)
1891 age = age2;
1895 return age;
1898 /** Return the age in milliseconds of the oldest buffer chunk on any stream
1899 * attached to the circuit <b>c</b>, where age is taken in milliseconds before
1900 * the time <b>now</b> (in truncated milliseconds since the epoch). */
1901 STATIC uint32_t
1902 circuit_max_queued_data_age(const circuit_t *c, uint32_t now)
1904 if (CIRCUIT_IS_ORIGIN(c)) {
1905 return circuit_get_streams_max_data_age(
1906 CONST_TO_ORIGIN_CIRCUIT(c)->p_streams, now);
1907 } else {
1908 return circuit_get_streams_max_data_age(
1909 CONST_TO_OR_CIRCUIT(c)->n_streams, now);
1913 /** Return the age of the oldest cell or stream buffer chunk on the circuit
1914 * <b>c</b>, where age is taken in milliseconds before the time <b>now</b> (in
1915 * truncated milliseconds since the epoch). */
1916 STATIC uint32_t
1917 circuit_max_queued_item_age(const circuit_t *c, uint32_t now)
1919 uint32_t cell_age = circuit_max_queued_cell_age(c, now);
1920 uint32_t data_age = circuit_max_queued_data_age(c, now);
1921 if (cell_age > data_age)
1922 return cell_age;
1923 else
1924 return data_age;
1927 /** Helper to sort a list of circuit_t by age of oldest item, in descending
1928 * order. */
1929 static int
1930 circuits_compare_by_oldest_queued_item_(const void **a_, const void **b_)
1932 const circuit_t *a = *a_;
1933 const circuit_t *b = *b_;
1934 uint32_t age_a = a->age_tmp;
1935 uint32_t age_b = b->age_tmp;
1937 if (age_a < age_b)
1938 return 1;
1939 else if (age_a == age_b)
1940 return 0;
1941 else
1942 return -1;
1945 #define FRACTION_OF_DATA_TO_RETAIN_ON_OOM 0.90
1947 /** We're out of memory for cells, having allocated <b>current_allocation</b>
1948 * bytes' worth. Kill the 'worst' circuits until we're under
1949 * FRACTION_OF_DATA_TO_RETAIN_ON_OOM of our maximum usage. */
1950 void
1951 circuits_handle_oom(size_t current_allocation)
1953 /* Let's hope there's enough slack space for this allocation here... */
1954 smartlist_t *circlist = smartlist_new();
1955 circuit_t *circ;
1956 size_t mem_to_recover;
1957 size_t mem_recovered=0;
1958 int n_circuits_killed=0;
1959 struct timeval now;
1960 uint32_t now_ms;
1961 log_notice(LD_GENERAL, "We're low on memory. Killing circuits with "
1962 "over-long queues. (This behavior is controlled by "
1963 "MaxMemInQueues.)");
1966 const size_t recovered = buf_shrink_freelists(1);
1967 if (recovered >= current_allocation) {
1968 log_warn(LD_BUG, "We somehow recovered more memory from freelists "
1969 "than we thought we had allocated");
1970 current_allocation = 0;
1971 } else {
1972 current_allocation -= recovered;
1977 size_t mem_target = (size_t)(get_options()->MaxMemInQueues *
1978 FRACTION_OF_DATA_TO_RETAIN_ON_OOM);
1979 if (current_allocation <= mem_target)
1980 return;
1981 mem_to_recover = current_allocation - mem_target;
1984 tor_gettimeofday_cached_monotonic(&now);
1985 now_ms = (uint32_t)tv_to_msec(&now);
1987 /* This algorithm itself assumes that you've got enough memory slack
1988 * to actually run it. */
1989 TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
1990 circ->age_tmp = circuit_max_queued_item_age(circ, now_ms);
1991 smartlist_add(circlist, circ);
1994 /* This is O(n log n); there are faster algorithms we could use instead.
1995 * Let's hope this doesn't happen enough to be in the critical path. */
1996 smartlist_sort(circlist, circuits_compare_by_oldest_queued_item_);
1998 /* Okay, now the worst circuits are at the front of the list. Let's mark
1999 * them, and reclaim their storage aggressively. */
2000 SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
2001 size_t n = n_cells_in_circ_queues(circ);
2002 size_t freed;
2003 if (! circ->marked_for_close) {
2004 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
2006 marked_circuit_free_cells(circ);
2007 freed = marked_circuit_free_stream_bytes(circ);
2009 ++n_circuits_killed;
2011 mem_recovered += n * packed_cell_mem_cost();
2012 mem_recovered += freed;
2014 if (mem_recovered >= mem_to_recover)
2015 break;
2016 } SMARTLIST_FOREACH_END(circ);
2018 #ifdef ENABLE_MEMPOOLS
2019 clean_cell_pool(); /* In case this helps. */
2020 #endif /* ENABLE_MEMPOOLS */
2021 buf_shrink_freelists(1); /* This is necessary to actually release buffer
2022 chunks. */
2024 log_notice(LD_GENERAL, "Removed "U64_FORMAT" bytes by killing %d circuits; "
2025 "%d circuits remain alive.",
2026 U64_PRINTF_ARG(mem_recovered),
2027 n_circuits_killed,
2028 smartlist_len(circlist) - n_circuits_killed);
2030 smartlist_free(circlist);
2033 /** Verify that cpath layer <b>cp</b> has all of its invariants
2034 * correct. Trigger an assert if anything is invalid.
2036 void
2037 assert_cpath_layer_ok(const crypt_path_t *cp)
2039 // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
2040 // tor_assert(cp->port);
2041 tor_assert(cp);
2042 tor_assert(cp->magic == CRYPT_PATH_MAGIC);
2043 switch (cp->state)
2045 case CPATH_STATE_OPEN:
2046 tor_assert(cp->f_crypto);
2047 tor_assert(cp->b_crypto);
2048 /* fall through */
2049 case CPATH_STATE_CLOSED:
2050 /*XXXX Assert that there's no handshake_state either. */
2051 tor_assert(!cp->rend_dh_handshake_state);
2052 break;
2053 case CPATH_STATE_AWAITING_KEYS:
2054 /* tor_assert(cp->dh_handshake_state); */
2055 break;
2056 default:
2057 log_fn(LOG_ERR, LD_BUG, "Unexpected state %d", cp->state);
2058 tor_assert(0);
2060 tor_assert(cp->package_window >= 0);
2061 tor_assert(cp->deliver_window >= 0);
2064 /** Verify that cpath <b>cp</b> has all of its invariants
2065 * correct. Trigger an assert if anything is invalid.
2067 static void
2068 assert_cpath_ok(const crypt_path_t *cp)
2070 const crypt_path_t *start = cp;
2072 do {
2073 assert_cpath_layer_ok(cp);
2074 /* layers must be in sequence of: "open* awaiting? closed*" */
2075 if (cp != start) {
2076 if (cp->state == CPATH_STATE_AWAITING_KEYS) {
2077 tor_assert(cp->prev->state == CPATH_STATE_OPEN);
2078 } else if (cp->state == CPATH_STATE_OPEN) {
2079 tor_assert(cp->prev->state == CPATH_STATE_OPEN);
2082 cp = cp->next;
2083 tor_assert(cp);
2084 } while (cp != start);
2087 /** Verify that circuit <b>c</b> has all of its invariants
2088 * correct. Trigger an assert if anything is invalid.
2090 void
2091 assert_circuit_ok(const circuit_t *c)
2093 edge_connection_t *conn;
2094 const or_circuit_t *or_circ = NULL;
2095 const origin_circuit_t *origin_circ = NULL;
2097 tor_assert(c);
2098 tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
2099 tor_assert(c->purpose >= CIRCUIT_PURPOSE_MIN_ &&
2100 c->purpose <= CIRCUIT_PURPOSE_MAX_);
2102 if (CIRCUIT_IS_ORIGIN(c))
2103 origin_circ = CONST_TO_ORIGIN_CIRCUIT(c);
2104 else
2105 or_circ = CONST_TO_OR_CIRCUIT(c);
2107 if (c->n_chan) {
2108 tor_assert(!c->n_hop);
2110 if (c->n_circ_id) {
2111 /* We use the _impl variant here to make sure we don't fail on marked
2112 * circuits, which would not be returned by the regular function. */
2113 circuit_t *c2 = circuit_get_by_circid_channel_impl(c->n_circ_id,
2114 c->n_chan, NULL);
2115 tor_assert(c == c2);
2118 if (or_circ && or_circ->p_chan) {
2119 if (or_circ->p_circ_id) {
2120 /* ibid */
2121 circuit_t *c2 =
2122 circuit_get_by_circid_channel_impl(or_circ->p_circ_id,
2123 or_circ->p_chan, NULL);
2124 tor_assert(c == c2);
2127 if (or_circ)
2128 for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
2129 tor_assert(conn->base_.type == CONN_TYPE_EXIT);
2131 tor_assert(c->deliver_window >= 0);
2132 tor_assert(c->package_window >= 0);
2133 if (c->state == CIRCUIT_STATE_OPEN) {
2134 tor_assert(!c->n_chan_create_cell);
2135 if (or_circ) {
2136 tor_assert(or_circ->n_crypto);
2137 tor_assert(or_circ->p_crypto);
2138 tor_assert(or_circ->n_digest);
2139 tor_assert(or_circ->p_digest);
2142 if (c->state == CIRCUIT_STATE_CHAN_WAIT && !c->marked_for_close) {
2143 tor_assert(circuits_pending_chans &&
2144 smartlist_contains(circuits_pending_chans, c));
2145 } else {
2146 tor_assert(!circuits_pending_chans ||
2147 !smartlist_contains(circuits_pending_chans, c));
2149 if (origin_circ && origin_circ->cpath) {
2150 assert_cpath_ok(origin_circ->cpath);
2152 if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
2153 tor_assert(or_circ);
2154 if (!c->marked_for_close) {
2155 tor_assert(or_circ->rend_splice);
2156 tor_assert(or_circ->rend_splice->rend_splice == or_circ);
2158 tor_assert(or_circ->rend_splice != or_circ);
2159 } else {
2160 tor_assert(!or_circ || !or_circ->rend_splice);