Document the purpose argument of circuit_find_to_cannibalize
[tor/rransom.git] / src / or / circuitlist.c
blob4e5d603e1edd7b5cd0709c633d4f034fdfbfeae2
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-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char circuitlist_c_id[] =
8 "$Id$";
10 /**
11 * \file circuitlist.c
12 * \brief Manage the global circuit list.
13 **/
15 #include "or.h"
16 #include "ht.h"
18 /********* START VARIABLES **********/
20 /** A global list of all circuits at this hop. */
21 circuit_t *global_circuitlist=NULL;
23 /** A list of all the circuits in CIRCUIT_STATE_OR_WAIT. */
24 static smartlist_t *circuits_pending_or_conns=NULL;
26 static void circuit_free(circuit_t *circ);
27 static void circuit_free_cpath(crypt_path_t *cpath);
28 static void circuit_free_cpath_node(crypt_path_t *victim);
30 /********* END VARIABLES ************/
32 /** A map from OR connection and circuit ID to circuit. (Lookup performance is
33 * very important here, since we need to do it every time a cell arrives.) */
34 typedef struct orconn_circid_circuit_map_t {
35 HT_ENTRY(orconn_circid_circuit_map_t) node;
36 or_connection_t *or_conn;
37 circid_t circ_id;
38 circuit_t *circuit;
39 } orconn_circid_circuit_map_t;
41 /** Helper for hash tables: compare the OR connection and circuit ID for a and
42 * b, and return less than, equal to, or greater than zero appropriately.
44 static INLINE int
45 _orconn_circid_entries_eq(orconn_circid_circuit_map_t *a,
46 orconn_circid_circuit_map_t *b)
48 return a->or_conn == b->or_conn && a->circ_id == b->circ_id;
51 /** Helper: return a hash based on circuit ID and the pointer value of
52 * or_conn in <b>a</b>. */
53 static INLINE unsigned int
54 _orconn_circid_entry_hash(orconn_circid_circuit_map_t *a)
56 return (((unsigned)a->circ_id)<<8) ^ (unsigned)(uintptr_t)(a->or_conn);
59 /** Map from [orconn,circid] to circuit. */
60 static HT_HEAD(orconn_circid_map, orconn_circid_circuit_map_t)
61 orconn_circid_circuit_map = HT_INITIALIZER();
62 HT_PROTOTYPE(orconn_circid_map, orconn_circid_circuit_map_t, node,
63 _orconn_circid_entry_hash, _orconn_circid_entries_eq)
64 HT_GENERATE(orconn_circid_map, orconn_circid_circuit_map_t, node,
65 _orconn_circid_entry_hash, _orconn_circid_entries_eq, 0.6,
66 malloc, realloc, free)
68 /** The most recently returned entry from circuit_get_by_circid_orconn;
69 * used to improve performance when many cells arrive in a row from the
70 * same circuit.
72 orconn_circid_circuit_map_t *_last_circid_orconn_ent = NULL;
74 /** Implementation helper for circuit_set_{p,n}_circid_orconn: A circuit ID
75 * and/or or_connection for circ has just changed from <b>old_conn, old_id</b>
76 * to <b>conn, id</b>. Adjust the conn,circid map as appropriate, removing
77 * the old entry (if any) and adding a new one. If <b>active</b> is true,
78 * remove the circuit from the list of active circuits on old_conn and add it
79 * to the list of active circuits on conn.
80 * XXX "active" isn't an arg anymore */
81 static void
82 circuit_set_circid_orconn_helper(circuit_t *circ, int direction,
83 circid_t id,
84 or_connection_t *conn)
86 orconn_circid_circuit_map_t search;
87 orconn_circid_circuit_map_t *found;
88 or_connection_t *old_conn, **conn_ptr;
89 circid_t old_id, *circid_ptr;
90 int was_active, make_active;
92 if (direction == CELL_DIRECTION_OUT) {
93 conn_ptr = &circ->n_conn;
94 circid_ptr = &circ->n_circ_id;
95 was_active = circ->next_active_on_n_conn != NULL;
96 make_active = circ->n_conn_cells.n > 0;
97 } else {
98 or_circuit_t *c = TO_OR_CIRCUIT(circ);
99 conn_ptr = &c->p_conn;
100 circid_ptr = &c->p_circ_id;
101 was_active = c->next_active_on_p_conn != NULL;
102 make_active = c->p_conn_cells.n > 0;
104 old_conn = *conn_ptr;
105 old_id = *circid_ptr;
107 if (id == old_id && conn == old_conn)
108 return;
110 if (_last_circid_orconn_ent &&
111 ((old_id == _last_circid_orconn_ent->circ_id &&
112 old_conn == _last_circid_orconn_ent->or_conn) ||
113 (id == _last_circid_orconn_ent->circ_id &&
114 conn == _last_circid_orconn_ent->or_conn))) {
115 _last_circid_orconn_ent = NULL;
118 if (old_conn) { /* we may need to remove it from the conn-circid map */
119 tor_assert(old_conn->_base.magic == OR_CONNECTION_MAGIC);
120 search.circ_id = old_id;
121 search.or_conn = old_conn;
122 found = HT_REMOVE(orconn_circid_map, &orconn_circid_circuit_map, &search);
123 if (found) {
124 tor_free(found);
125 --old_conn->n_circuits;
127 if (was_active && old_conn != conn)
128 make_circuit_inactive_on_conn(circ,old_conn);
131 /* Change the values only after we have possibly made the circuit inactive
132 * on the previous conn. */
133 *conn_ptr = conn;
134 *circid_ptr = id;
136 if (conn == NULL)
137 return;
139 /* now add the new one to the conn-circid map */
140 search.circ_id = id;
141 search.or_conn = conn;
142 found = HT_FIND(orconn_circid_map, &orconn_circid_circuit_map, &search);
143 if (found) {
144 found->circuit = circ;
145 } else {
146 found = tor_malloc_zero(sizeof(orconn_circid_circuit_map_t));
147 found->circ_id = id;
148 found->or_conn = conn;
149 found->circuit = circ;
150 HT_INSERT(orconn_circid_map, &orconn_circid_circuit_map, found);
152 if (make_active && old_conn != conn)
153 make_circuit_active_on_conn(circ,conn);
155 ++conn->n_circuits;
158 /** Set the p_conn field of a circuit <b>circ</b>, along
159 * with the corresponding circuit ID, and add the circuit as appropriate
160 * to the (orconn,id)-\>circuit map. */
161 void
162 circuit_set_p_circid_orconn(or_circuit_t *circ, circid_t id,
163 or_connection_t *conn)
165 circuit_set_circid_orconn_helper(TO_CIRCUIT(circ), CELL_DIRECTION_IN,
166 id, conn);
168 if (conn)
169 tor_assert(bool_eq(circ->p_conn_cells.n, circ->next_active_on_p_conn));
172 /** Set the n_conn field of a circuit <b>circ</b>, along
173 * with the corresponding circuit ID, and add the circuit as appropriate
174 * to the (orconn,id)-\>circuit map. */
175 void
176 circuit_set_n_circid_orconn(circuit_t *circ, circid_t id,
177 or_connection_t *conn)
179 circuit_set_circid_orconn_helper(circ, CELL_DIRECTION_OUT, id, conn);
181 if (conn)
182 tor_assert(bool_eq(circ->n_conn_cells.n, circ->next_active_on_n_conn));
185 /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
186 * it from lists as appropriate. */
187 void
188 circuit_set_state(circuit_t *circ, uint8_t state)
190 tor_assert(circ);
191 if (state == circ->state)
192 return;
193 if (!circuits_pending_or_conns)
194 circuits_pending_or_conns = smartlist_create();
195 if (circ->state == CIRCUIT_STATE_OR_WAIT) {
196 /* remove from waiting-circuit list. */
197 smartlist_remove(circuits_pending_or_conns, circ);
199 if (state == CIRCUIT_STATE_OR_WAIT) {
200 /* add to waiting-circuit list. */
201 smartlist_add(circuits_pending_or_conns, circ);
203 if (state == CIRCUIT_STATE_OPEN)
204 tor_assert(!circ->n_conn_onionskin);
205 circ->state = state;
208 /** Add <b>circ</b> to the global list of circuits. This is called only from
209 * within circuit_new.
211 static void
212 circuit_add(circuit_t *circ)
214 if (!global_circuitlist) { /* first one */
215 global_circuitlist = circ;
216 circ->next = NULL;
217 } else {
218 circ->next = global_circuitlist;
219 global_circuitlist = circ;
223 /** Append to <b>out</b> all circuits in state OR_WAIT waiting for
224 * the given connection. */
225 void
226 circuit_get_all_pending_on_or_conn(smartlist_t *out, or_connection_t *or_conn)
228 tor_assert(out);
229 tor_assert(or_conn);
231 if (!circuits_pending_or_conns)
232 return;
234 SMARTLIST_FOREACH_BEGIN(circuits_pending_or_conns, circuit_t *, circ) {
235 if (circ->marked_for_close)
236 continue;
237 if (!circ->n_hop)
238 continue;
239 tor_assert(circ->state == CIRCUIT_STATE_OR_WAIT);
240 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
241 /* Look at addr/port. This is an unkeyed connection. */
242 if (!tor_addr_eq(&circ->n_hop->addr, &or_conn->_base.addr) ||
243 circ->n_hop->port != or_conn->_base.port)
244 continue;
245 } else {
246 /* We expected a key. See if it's the right one. */
247 if (memcmp(or_conn->identity_digest,
248 circ->n_hop->identity_digest, DIGEST_LEN))
249 continue;
251 smartlist_add(out, circ);
252 } SMARTLIST_FOREACH_END(circ);
255 /** Return the number of circuits in state OR_WAIT, waiting for the given
256 * connection. */
258 circuit_count_pending_on_or_conn(or_connection_t *or_conn)
260 int cnt;
261 smartlist_t *sl = smartlist_create();
262 circuit_get_all_pending_on_or_conn(sl, or_conn);
263 cnt = smartlist_len(sl);
264 smartlist_free(sl);
265 log_debug(LD_CIRC,"or_conn to %s, %d pending circs",
266 or_conn->nickname ? or_conn->nickname : "NULL", cnt);
267 return cnt;
270 /** Detach from the global circuit list, and deallocate, all
271 * circuits that have been marked for close.
273 void
274 circuit_close_all_marked(void)
276 circuit_t *tmp,*m;
278 while (global_circuitlist && global_circuitlist->marked_for_close) {
279 tmp = global_circuitlist->next;
280 circuit_free(global_circuitlist);
281 global_circuitlist = tmp;
284 tmp = global_circuitlist;
285 while (tmp && tmp->next) {
286 if (tmp->next->marked_for_close) {
287 m = tmp->next->next;
288 circuit_free(tmp->next);
289 tmp->next = m;
290 /* Need to check new tmp->next; don't advance tmp. */
291 } else {
292 /* Advance tmp. */
293 tmp = tmp->next;
298 /** Return the head of the global linked list of circuits. */
299 circuit_t *
300 _circuit_get_global_list(void)
302 return global_circuitlist;
305 /** Function to make circ-\>state human-readable */
306 const char *
307 circuit_state_to_string(int state)
309 static char buf[64];
310 switch (state) {
311 case CIRCUIT_STATE_BUILDING: return "doing handshakes";
312 case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
313 case CIRCUIT_STATE_OR_WAIT: return "connecting to server";
314 case CIRCUIT_STATE_OPEN: return "open";
315 default:
316 log_warn(LD_BUG, "Unknown circuit state %d", state);
317 tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
318 return buf;
322 /** Map a circuit purpose to a string suitable to be displayed to a
323 * controller. */
324 const char *
325 circuit_purpose_to_controller_string(uint8_t purpose)
327 static char buf[32];
328 switch (purpose) {
329 case CIRCUIT_PURPOSE_OR:
330 case CIRCUIT_PURPOSE_INTRO_POINT:
331 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
332 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
333 return "SERVER"; /* A controller should never see these, actually. */
335 case CIRCUIT_PURPOSE_C_GENERAL:
336 return "GENERAL";
337 case CIRCUIT_PURPOSE_C_INTRODUCING:
338 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
339 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
340 return "HS_CLIENT_INTRO";
342 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
343 case CIRCUIT_PURPOSE_C_REND_READY:
344 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
345 case CIRCUIT_PURPOSE_C_REND_JOINED:
346 return "HS_CLIENT_REND";
348 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
349 case CIRCUIT_PURPOSE_S_INTRO:
350 return "HS_SERVICE_INTRO";
352 case CIRCUIT_PURPOSE_S_CONNECT_REND:
353 case CIRCUIT_PURPOSE_S_REND_JOINED:
354 return "HS_SERVICE_REND";
356 case CIRCUIT_PURPOSE_TESTING:
357 return "TESTING";
358 case CIRCUIT_PURPOSE_CONTROLLER:
359 return "CONTROLLER";
361 default:
362 tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
363 return buf;
367 /** Initialize the common elements in a circuit_t, and add it to the global
368 * list. */
369 static void
370 init_circuit_base(circuit_t *circ)
372 circ->timestamp_created = time(NULL);
374 circ->package_window = CIRCWINDOW_START;
375 circ->deliver_window = CIRCWINDOW_START;
377 circuit_add(circ);
380 /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
381 * and <b>p_conn</b>. Add it to the global circuit list.
383 origin_circuit_t *
384 origin_circuit_new(void)
386 origin_circuit_t *circ;
387 /* never zero, since a global ID of 0 is treated specially by the
388 * controller */
389 static uint32_t n_circuits_allocated = 1;
391 circ = tor_malloc_zero(sizeof(origin_circuit_t));
392 circ->_base.magic = ORIGIN_CIRCUIT_MAGIC;
394 circ->next_stream_id = crypto_rand_int(1<<16);
395 circ->global_identifier = n_circuits_allocated++;
396 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
397 circ->remaining_relay_early_cells -= crypto_rand_int(2);
399 init_circuit_base(TO_CIRCUIT(circ));
401 return circ;
404 /** Allocate a new or_circuit_t, connected to <b>p_conn</b> as
405 * <b>p_circ_id</b>. If <b>p_conn</b> is NULL, the circuit is unattached. */
406 or_circuit_t *
407 or_circuit_new(circid_t p_circ_id, or_connection_t *p_conn)
409 /* CircIDs */
410 or_circuit_t *circ;
412 circ = tor_malloc_zero(sizeof(or_circuit_t));
413 circ->_base.magic = OR_CIRCUIT_MAGIC;
415 if (p_conn)
416 circuit_set_p_circid_orconn(circ, p_circ_id, p_conn);
418 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
420 init_circuit_base(TO_CIRCUIT(circ));
422 return circ;
425 /** Deallocate space associated with circ.
427 static void
428 circuit_free(circuit_t *circ)
430 void *mem;
431 size_t memlen;
432 tor_assert(circ);
433 if (CIRCUIT_IS_ORIGIN(circ)) {
434 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
435 mem = ocirc;
436 memlen = sizeof(origin_circuit_t);
437 tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
438 if (ocirc->build_state) {
439 if (ocirc->build_state->chosen_exit)
440 extend_info_free(ocirc->build_state->chosen_exit);
441 if (ocirc->build_state->pending_final_cpath)
442 circuit_free_cpath_node(ocirc->build_state->pending_final_cpath);
444 tor_free(ocirc->build_state);
446 circuit_free_cpath(ocirc->cpath);
447 if (ocirc->intro_key)
448 crypto_free_pk_env(ocirc->intro_key);
449 if (ocirc->rend_data)
450 rend_data_free(ocirc->rend_data);
451 } else {
452 or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
453 mem = ocirc;
454 memlen = sizeof(or_circuit_t);
455 tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
457 if (ocirc->p_crypto)
458 crypto_free_cipher_env(ocirc->p_crypto);
459 if (ocirc->p_digest)
460 crypto_free_digest_env(ocirc->p_digest);
461 if (ocirc->n_crypto)
462 crypto_free_cipher_env(ocirc->n_crypto);
463 if (ocirc->n_digest)
464 crypto_free_digest_env(ocirc->n_digest);
466 if (ocirc->rend_splice) {
467 or_circuit_t *other = ocirc->rend_splice;
468 tor_assert(other->_base.magic == OR_CIRCUIT_MAGIC);
469 other->rend_splice = NULL;
472 /* remove from map. */
473 circuit_set_p_circid_orconn(ocirc, 0, NULL);
475 /* Clear cell queue _after_ removing it from the map. Otherwise our
476 * "active" checks will be violated. */
477 cell_queue_clear(&ocirc->p_conn_cells);
480 if (circ->n_hop)
481 extend_info_free(circ->n_hop);
482 tor_free(circ->n_conn_onionskin);
484 /* Remove from map. */
485 circuit_set_n_circid_orconn(circ, 0, NULL);
487 /* Clear cell queue _after_ removing it from the map. Otherwise our
488 * "active" checks will be violated. */
489 cell_queue_clear(&circ->n_conn_cells);
491 memset(circ, 0xAA, memlen); /* poison memory */
492 tor_free(mem);
495 /** Deallocate space associated with the linked list <b>cpath</b>. */
496 static void
497 circuit_free_cpath(crypt_path_t *cpath)
499 crypt_path_t *victim, *head=cpath;
501 if (!cpath)
502 return;
504 /* it's a doubly linked list, so we have to notice when we've
505 * gone through it once. */
506 while (cpath->next && cpath->next != head) {
507 victim = cpath;
508 cpath = victim->next;
509 circuit_free_cpath_node(victim);
512 circuit_free_cpath_node(cpath);
515 /** Release all storage held by circuits. */
516 void
517 circuit_free_all(void)
519 circuit_t *next;
520 while (global_circuitlist) {
521 next = global_circuitlist->next;
522 if (! CIRCUIT_IS_ORIGIN(global_circuitlist)) {
523 or_circuit_t *or_circ = TO_OR_CIRCUIT(global_circuitlist);
524 while (or_circ->resolving_streams) {
525 edge_connection_t *next_conn;
526 next_conn = or_circ->resolving_streams->next_stream;
527 connection_free(TO_CONN(or_circ->resolving_streams));
528 or_circ->resolving_streams = next_conn;
531 circuit_free(global_circuitlist);
532 global_circuitlist = next;
534 if (circuits_pending_or_conns) {
535 smartlist_free(circuits_pending_or_conns);
536 circuits_pending_or_conns = NULL;
538 HT_CLEAR(orconn_circid_map, &orconn_circid_circuit_map);
541 /** Deallocate space associated with the cpath node <b>victim</b>. */
542 static void
543 circuit_free_cpath_node(crypt_path_t *victim)
545 if (victim->f_crypto)
546 crypto_free_cipher_env(victim->f_crypto);
547 if (victim->b_crypto)
548 crypto_free_cipher_env(victim->b_crypto);
549 if (victim->f_digest)
550 crypto_free_digest_env(victim->f_digest);
551 if (victim->b_digest)
552 crypto_free_digest_env(victim->b_digest);
553 if (victim->dh_handshake_state)
554 crypto_dh_free(victim->dh_handshake_state);
555 if (victim->extend_info)
556 extend_info_free(victim->extend_info);
558 memset(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
559 tor_free(victim);
562 /** A helper function for circuit_dump_by_conn() below. Log a bunch
563 * of information about circuit <b>circ</b>.
565 static void
566 circuit_dump_details(int severity, circuit_t *circ, int conn_array_index,
567 const char *type, int this_circid, int other_circid)
569 log(severity, LD_CIRC, "Conn %d has %s circuit: circID %d (other side %d), "
570 "state %d (%s), born %d:",
571 conn_array_index, type, this_circid, other_circid, circ->state,
572 circuit_state_to_string(circ->state), (int)circ->timestamp_created);
573 if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
574 circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
578 /** Log, at severity <b>severity</b>, information about each circuit
579 * that is connected to <b>conn</b>.
581 void
582 circuit_dump_by_conn(connection_t *conn, int severity)
584 circuit_t *circ;
585 edge_connection_t *tmpconn;
587 for (circ=global_circuitlist;circ;circ = circ->next) {
588 circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
589 if (circ->marked_for_close)
590 continue;
592 if (! CIRCUIT_IS_ORIGIN(circ))
593 p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
595 if (! CIRCUIT_IS_ORIGIN(circ) && TO_OR_CIRCUIT(circ)->p_conn &&
596 TO_CONN(TO_OR_CIRCUIT(circ)->p_conn) == conn)
597 circuit_dump_details(severity, circ, conn->conn_array_index, "App-ward",
598 p_circ_id, n_circ_id);
599 if (CIRCUIT_IS_ORIGIN(circ)) {
600 for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
601 tmpconn=tmpconn->next_stream) {
602 if (TO_CONN(tmpconn) == conn) {
603 circuit_dump_details(severity, circ, conn->conn_array_index,
604 "App-ward", p_circ_id, n_circ_id);
608 if (circ->n_conn && TO_CONN(circ->n_conn) == conn)
609 circuit_dump_details(severity, circ, conn->conn_array_index, "Exit-ward",
610 n_circ_id, p_circ_id);
611 if (! CIRCUIT_IS_ORIGIN(circ)) {
612 for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
613 tmpconn=tmpconn->next_stream) {
614 if (TO_CONN(tmpconn) == conn) {
615 circuit_dump_details(severity, circ, conn->conn_array_index,
616 "Exit-ward", n_circ_id, p_circ_id);
620 if (!circ->n_conn && circ->n_hop &&
621 tor_addr_eq(&circ->n_hop->addr, &conn->addr) &&
622 circ->n_hop->port == conn->port &&
623 conn->type == CONN_TYPE_OR &&
624 !memcmp(TO_OR_CONN(conn)->identity_digest,
625 circ->n_hop->identity_digest, DIGEST_LEN)) {
626 circuit_dump_details(severity, circ, conn->conn_array_index,
627 (circ->state == CIRCUIT_STATE_OPEN &&
628 !CIRCUIT_IS_ORIGIN(circ)) ?
629 "Endpoint" : "Pending",
630 n_circ_id, p_circ_id);
635 /** Return the circuit whose global ID is <b>id</b>, or NULL if no
636 * such circuit exists. */
637 origin_circuit_t *
638 circuit_get_by_global_id(uint32_t id)
640 circuit_t *circ;
641 for (circ=global_circuitlist;circ;circ = circ->next) {
642 if (CIRCUIT_IS_ORIGIN(circ) &&
643 TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
644 if (circ->marked_for_close)
645 return NULL;
646 else
647 return TO_ORIGIN_CIRCUIT(circ);
650 return NULL;
653 /** Return a circ such that:
654 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
655 * - circ is attached to <b>conn</b>, either as p_conn or n_conn.
656 * Return NULL if no such circuit exists.
658 static INLINE circuit_t *
659 circuit_get_by_circid_orconn_impl(circid_t circ_id, or_connection_t *conn)
661 orconn_circid_circuit_map_t search;
662 orconn_circid_circuit_map_t *found;
664 if (_last_circid_orconn_ent &&
665 circ_id == _last_circid_orconn_ent->circ_id &&
666 conn == _last_circid_orconn_ent->or_conn) {
667 found = _last_circid_orconn_ent;
668 } else {
669 search.circ_id = circ_id;
670 search.or_conn = conn;
671 found = HT_FIND(orconn_circid_map, &orconn_circid_circuit_map, &search);
672 _last_circid_orconn_ent = found;
674 if (found && found->circuit)
675 return found->circuit;
677 return NULL;
679 /* The rest of this checks for bugs. Disabled by default. */
681 circuit_t *circ;
682 for (circ=global_circuitlist;circ;circ = circ->next) {
683 if (! CIRCUIT_IS_ORIGIN(circ)) {
684 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
685 if (or_circ->p_conn == conn && or_circ->p_circ_id == circ_id) {
686 log_warn(LD_BUG,
687 "circuit matches p_conn, but not in hash table (Bug!)");
688 return circ;
691 if (circ->n_conn == conn && circ->n_circ_id == circ_id) {
692 log_warn(LD_BUG,
693 "circuit matches n_conn, but not in hash table (Bug!)");
694 return circ;
697 return NULL;
701 /** Return a circ such that:
702 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
703 * - circ is attached to <b>conn</b>, either as p_conn or n_conn.
704 * - circ is not marked for close.
705 * Return NULL if no such circuit exists.
707 circuit_t *
708 circuit_get_by_circid_orconn(circid_t circ_id, or_connection_t *conn)
710 circuit_t *circ = circuit_get_by_circid_orconn_impl(circ_id, conn);
711 if (!circ || circ->marked_for_close)
712 return NULL;
713 else
714 return circ;
717 /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
718 * circuit, marked or not, on <b>conn</b>. */
720 circuit_id_in_use_on_orconn(circid_t circ_id, or_connection_t *conn)
722 return circuit_get_by_circid_orconn_impl(circ_id, conn) != NULL;
725 /** Return the circuit that a given edge connection is using. */
726 circuit_t *
727 circuit_get_by_edge_conn(edge_connection_t *conn)
729 circuit_t *circ;
731 circ = conn->on_circuit;
732 tor_assert(!circ ||
733 (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
734 : circ->magic == OR_CIRCUIT_MAGIC));
736 return circ;
739 /** For each circuit that has <b>conn</b> as n_conn or p_conn, unlink the
740 * circuit from the orconn,circid map, and mark it for close if it hasn't
741 * been marked already.
743 void
744 circuit_unlink_all_from_or_conn(or_connection_t *conn, int reason)
746 circuit_t *circ;
748 connection_or_unlink_all_active_circs(conn);
750 for (circ = global_circuitlist; circ; circ = circ->next) {
751 int mark = 0;
752 if (circ->n_conn == conn) {
753 circuit_set_n_circid_orconn(circ, 0, NULL);
754 mark = 1;
756 if (! CIRCUIT_IS_ORIGIN(circ)) {
757 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
758 if (or_circ->p_conn == conn) {
759 circuit_set_p_circid_orconn(or_circ, 0, NULL);
760 mark = 1;
763 if (mark && !circ->marked_for_close)
764 circuit_mark_for_close(circ, reason);
768 /** Return a circ such that:
769 * - circ-\>rend_data-\>query is equal to <b>rend_query</b>, and
770 * - circ-\>purpose is equal to <b>purpose</b>.
772 * Return NULL if no such circuit exists.
774 origin_circuit_t *
775 circuit_get_by_rend_query_and_purpose(const char *rend_query, uint8_t purpose)
777 circuit_t *circ;
779 tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
781 for (circ = global_circuitlist; circ; circ = circ->next) {
782 if (!circ->marked_for_close &&
783 circ->purpose == purpose) {
784 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
785 if (ocirc->rend_data &&
786 !rend_cmp_service_ids(rend_query,
787 ocirc->rend_data->onion_address))
788 return ocirc;
791 return NULL;
794 /** Return the first circuit originating here in global_circuitlist after
795 * <b>start</b> whose purpose is <b>purpose</b>, and where
796 * <b>digest</b> (if set) matches the rend_pk_digest field. Return NULL if no
797 * circuit is found. If <b>start</b> is NULL, begin at the start of the list.
799 origin_circuit_t *
800 circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
801 const char *digest, uint8_t purpose)
803 circuit_t *circ;
804 tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
805 if (start == NULL)
806 circ = global_circuitlist;
807 else
808 circ = TO_CIRCUIT(start)->next;
810 for ( ; circ; circ = circ->next) {
811 if (circ->marked_for_close)
812 continue;
813 if (circ->purpose != purpose)
814 continue;
815 if (!digest)
816 return TO_ORIGIN_CIRCUIT(circ);
817 else if (TO_ORIGIN_CIRCUIT(circ)->rend_data &&
818 !memcmp(TO_ORIGIN_CIRCUIT(circ)->rend_data->rend_pk_digest,
819 digest, DIGEST_LEN))
820 return TO_ORIGIN_CIRCUIT(circ);
822 return NULL;
825 /** Return the first OR circuit in the global list whose purpose is
826 * <b>purpose</b>, and whose rend_token is the <b>len</b>-byte
827 * <b>token</b>. */
828 static or_circuit_t *
829 circuit_get_by_rend_token_and_purpose(uint8_t purpose, const char *token,
830 size_t len)
832 circuit_t *circ;
833 for (circ = global_circuitlist; circ; circ = circ->next) {
834 if (! circ->marked_for_close &&
835 circ->purpose == purpose &&
836 ! memcmp(TO_OR_CIRCUIT(circ)->rend_token, token, len))
837 return TO_OR_CIRCUIT(circ);
839 return NULL;
842 /** Return the circuit waiting for a rendezvous with the provided cookie.
843 * Return NULL if no such circuit is found.
845 or_circuit_t *
846 circuit_get_rendezvous(const char *cookie)
848 return circuit_get_by_rend_token_and_purpose(
849 CIRCUIT_PURPOSE_REND_POINT_WAITING,
850 cookie, REND_COOKIE_LEN);
853 /** Return the circuit waiting for intro cells of the given digest.
854 * Return NULL if no such circuit is found.
856 or_circuit_t *
857 circuit_get_intro_point(const char *digest)
859 return circuit_get_by_rend_token_and_purpose(
860 CIRCUIT_PURPOSE_INTRO_POINT, digest,
861 DIGEST_LEN);
864 /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
865 * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
866 * flags in <b>flags</b>, and if info is defined, does not already use info
867 * as any of its hops; or NULL if no circuit fits this description.
869 * The <b>purpose</b> argument (currently ignored) refers to the purpose of
870 * the circuit we want to create, not the purpose of the circuit we want to
871 * cannibalize.
873 * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
875 origin_circuit_t *
876 circuit_find_to_cannibalize(uint8_t purpose, extend_info_t *info,
877 int flags)
879 circuit_t *_circ;
880 origin_circuit_t *best=NULL;
881 int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
882 int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
883 int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
885 log_debug(LD_CIRC,
886 "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
887 "capacity %d, internal %d",
888 purpose, need_uptime, need_capacity, internal);
890 for (_circ=global_circuitlist; _circ; _circ = _circ->next) {
891 if (CIRCUIT_IS_ORIGIN(_circ) &&
892 _circ->state == CIRCUIT_STATE_OPEN &&
893 !_circ->marked_for_close &&
894 _circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
895 !_circ->timestamp_dirty) {
896 origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(_circ);
897 if ((!need_uptime || circ->build_state->need_uptime) &&
898 (!need_capacity || circ->build_state->need_capacity) &&
899 (internal == circ->build_state->is_internal)) {
900 if (info) {
901 /* need to make sure we don't duplicate hops */
902 crypt_path_t *hop = circ->cpath;
903 routerinfo_t *ri1 = router_get_by_digest(info->identity_digest);
904 do {
905 routerinfo_t *ri2;
906 if (!memcmp(hop->extend_info->identity_digest,
907 info->identity_digest, DIGEST_LEN))
908 goto next;
909 if (ri1 &&
910 (ri2 = router_get_by_digest(hop->extend_info->identity_digest))
911 && routers_in_same_family(ri1, ri2))
912 goto next;
913 hop=hop->next;
914 } while (hop!=circ->cpath);
916 if (!best || (best->build_state->need_uptime && !need_uptime))
917 best = circ;
918 next: ;
922 return best;
925 /** Return the number of hops in circuit's path. */
927 circuit_get_cpath_len(origin_circuit_t *circ)
929 int n = 0;
930 if (circ && circ->cpath) {
931 crypt_path_t *cpath, *cpath_next = NULL;
932 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
933 cpath_next = cpath->next;
934 ++n;
937 return n;
940 /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
941 * aren't that many hops in the list. */
942 crypt_path_t *
943 circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
945 if (circ && circ->cpath && hopnum > 0) {
946 crypt_path_t *cpath, *cpath_next = NULL;
947 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
948 cpath_next = cpath->next;
949 if (--hopnum <= 0)
950 return cpath;
953 return NULL;
956 /** Go through the circuitlist; mark-for-close each circuit that starts
957 * at us but has not yet been used. */
958 void
959 circuit_mark_all_unused_circs(void)
961 circuit_t *circ;
963 for (circ=global_circuitlist; circ; circ = circ->next) {
964 if (CIRCUIT_IS_ORIGIN(circ) &&
965 !circ->marked_for_close &&
966 !circ->timestamp_dirty)
967 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
971 /** Go through the circuitlist; for each circuit that starts at us
972 * and is dirty, frob its timestamp_dirty so we won't use it for any
973 * new streams.
975 * This is useful for letting the user change pseudonyms, so new
976 * streams will not be linkable to old streams.
978 void
979 circuit_expire_all_dirty_circs(void)
981 circuit_t *circ;
982 or_options_t *options = get_options();
984 for (circ=global_circuitlist; circ; circ = circ->next) {
985 if (CIRCUIT_IS_ORIGIN(circ) &&
986 !circ->marked_for_close &&
987 circ->timestamp_dirty)
988 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
992 /** Mark <b>circ</b> to be closed next time we call
993 * circuit_close_all_marked(). Do any cleanup needed:
994 * - If state is onionskin_pending, remove circ from the onion_pending
995 * list.
996 * - If circ isn't open yet: call circuit_build_failed() if we're
997 * the origin, and in either case call circuit_rep_hist_note_result()
998 * to note stats.
999 * - If purpose is C_INTRODUCE_ACK_WAIT, remove the intro point we
1000 * just tried from our list of intro points for that service
1001 * descriptor.
1002 * - Send appropriate destroys and edge_destroys for conns and
1003 * streams attached to circ.
1004 * - If circ->rend_splice is set (we are the midpoint of a joined
1005 * rendezvous stream), then mark the other circuit to close as well.
1007 void
1008 _circuit_mark_for_close(circuit_t *circ, int reason, int line,
1009 const char *file)
1011 int orig_reason = reason; /* Passed to the controller */
1012 assert_circuit_ok(circ);
1013 tor_assert(line);
1014 tor_assert(file);
1016 if (circ->marked_for_close) {
1017 log(LOG_WARN,LD_BUG,
1018 "Duplicate call to circuit_mark_for_close at %s:%d"
1019 " (first at %s:%d)", file, line,
1020 circ->marked_for_close_file, circ->marked_for_close);
1021 return;
1023 if (reason == END_CIRC_AT_ORIGIN) {
1024 if (!CIRCUIT_IS_ORIGIN(circ)) {
1025 log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
1026 "but circuit was not at origin. (called %s:%d, purpose=%d)",
1027 file, line, circ->purpose);
1029 reason = END_CIRC_REASON_NONE;
1031 if (CIRCUIT_IS_ORIGIN(circ)) {
1032 /* We don't send reasons when closing circuits at the origin. */
1033 reason = END_CIRC_REASON_NONE;
1036 if (reason & END_CIRC_REASON_FLAG_REMOTE)
1037 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
1039 if (reason < _END_CIRC_REASON_MIN || reason > _END_CIRC_REASON_MAX) {
1040 if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
1041 log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
1042 reason = END_CIRC_REASON_NONE;
1045 if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
1046 onion_pending_remove(TO_OR_CIRCUIT(circ));
1048 /* If the circuit ever became OPEN, we sent it to the reputation history
1049 * module then. If it isn't OPEN, we send it there now to remember which
1050 * links worked and which didn't.
1052 if (circ->state != CIRCUIT_STATE_OPEN) {
1053 if (CIRCUIT_IS_ORIGIN(circ)) {
1054 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1055 circuit_build_failed(ocirc); /* take actions if necessary */
1056 circuit_rep_hist_note_result(ocirc);
1059 if (circ->state == CIRCUIT_STATE_OR_WAIT) {
1060 if (circuits_pending_or_conns)
1061 smartlist_remove(circuits_pending_or_conns, circ);
1063 if (CIRCUIT_IS_ORIGIN(circ)) {
1064 control_event_circuit_status(TO_ORIGIN_CIRCUIT(circ),
1065 (circ->state == CIRCUIT_STATE_OPEN)?CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
1066 orig_reason);
1068 if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1069 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1070 tor_assert(circ->state == CIRCUIT_STATE_OPEN);
1071 tor_assert(ocirc->build_state->chosen_exit);
1072 tor_assert(ocirc->rend_data);
1073 /* treat this like getting a nack from it */
1074 log_info(LD_REND, "Failed intro circ %s to %s (awaiting ack). "
1075 "Removing from descriptor.",
1076 safe_str(ocirc->rend_data->onion_address),
1077 safe_str(build_state_get_exit_nickname(ocirc->build_state)));
1078 rend_client_remove_intro_point(ocirc->build_state->chosen_exit,
1079 ocirc->rend_data);
1081 if (circ->n_conn)
1082 connection_or_send_destroy(circ->n_circ_id, circ->n_conn, reason);
1084 if (! CIRCUIT_IS_ORIGIN(circ)) {
1085 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1086 edge_connection_t *conn;
1087 for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
1088 connection_edge_destroy(or_circ->p_circ_id, conn);
1090 while (or_circ->resolving_streams) {
1091 conn = or_circ->resolving_streams;
1092 or_circ->resolving_streams = conn->next_stream;
1093 if (!conn->_base.marked_for_close) {
1094 /* The client will see a DESTROY, and infer that the connections
1095 * are closing because the circuit is getting torn down. No need
1096 * to send an end cell. */
1097 conn->edge_has_sent_end = 1;
1098 conn->end_reason = END_STREAM_REASON_DESTROY;
1099 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
1100 connection_mark_for_close(TO_CONN(conn));
1102 conn->on_circuit = NULL;
1105 if (or_circ->p_conn)
1106 connection_or_send_destroy(or_circ->p_circ_id, or_circ->p_conn, reason);
1107 } else {
1108 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1109 edge_connection_t *conn;
1110 for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
1111 connection_edge_destroy(circ->n_circ_id, conn);
1114 circ->marked_for_close = line;
1115 circ->marked_for_close_file = file;
1117 if (!CIRCUIT_IS_ORIGIN(circ)) {
1118 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1119 if (or_circ->rend_splice) {
1120 if (!or_circ->rend_splice->_base.marked_for_close) {
1121 /* do this after marking this circuit, to avoid infinite recursion. */
1122 circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
1124 or_circ->rend_splice = NULL;
1129 /** Verify that cpath layer <b>cp</b> has all of its invariants
1130 * correct. Trigger an assert if anything is invalid.
1132 void
1133 assert_cpath_layer_ok(const crypt_path_t *cp)
1135 // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
1136 // tor_assert(cp->port);
1137 tor_assert(cp);
1138 tor_assert(cp->magic == CRYPT_PATH_MAGIC);
1139 switch (cp->state)
1141 case CPATH_STATE_OPEN:
1142 tor_assert(cp->f_crypto);
1143 tor_assert(cp->b_crypto);
1144 /* fall through */
1145 case CPATH_STATE_CLOSED:
1146 tor_assert(!cp->dh_handshake_state);
1147 break;
1148 case CPATH_STATE_AWAITING_KEYS:
1149 /* tor_assert(cp->dh_handshake_state); */
1150 break;
1151 default:
1152 log_fn(LOG_ERR, LD_BUG, "Unexpected state %d", cp->state);
1153 tor_assert(0);
1155 tor_assert(cp->package_window >= 0);
1156 tor_assert(cp->deliver_window >= 0);
1159 /** Verify that cpath <b>cp</b> has all of its invariants
1160 * correct. Trigger an assert if anything is invalid.
1162 static void
1163 assert_cpath_ok(const crypt_path_t *cp)
1165 const crypt_path_t *start = cp;
1167 do {
1168 assert_cpath_layer_ok(cp);
1169 /* layers must be in sequence of: "open* awaiting? closed*" */
1170 if (cp != start) {
1171 if (cp->state == CPATH_STATE_AWAITING_KEYS) {
1172 tor_assert(cp->prev->state == CPATH_STATE_OPEN);
1173 } else if (cp->state == CPATH_STATE_OPEN) {
1174 tor_assert(cp->prev->state == CPATH_STATE_OPEN);
1177 cp = cp->next;
1178 tor_assert(cp);
1179 } while (cp != start);
1182 /** Verify that circuit <b>c</b> has all of its invariants
1183 * correct. Trigger an assert if anything is invalid.
1185 void
1186 assert_circuit_ok(const circuit_t *c)
1188 edge_connection_t *conn;
1189 const or_circuit_t *or_circ = NULL;
1190 const origin_circuit_t *origin_circ = NULL;
1192 tor_assert(c);
1193 tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
1194 tor_assert(c->purpose >= _CIRCUIT_PURPOSE_MIN &&
1195 c->purpose <= _CIRCUIT_PURPOSE_MAX);
1198 /* Having a separate variable for this pleases GCC 4.2 in ways I hope I
1199 * never understand. -NM. */
1200 circuit_t *nonconst_circ = (circuit_t*) c;
1201 if (CIRCUIT_IS_ORIGIN(c))
1202 origin_circ = TO_ORIGIN_CIRCUIT(nonconst_circ);
1203 else
1204 or_circ = TO_OR_CIRCUIT(nonconst_circ);
1207 if (c->n_conn) {
1208 tor_assert(!c->n_hop);
1210 if (c->n_circ_id) {
1211 /* We use the _impl variant here to make sure we don't fail on marked
1212 * circuits, which would not be returned by the regular function. */
1213 circuit_t *c2 = circuit_get_by_circid_orconn_impl(c->n_circ_id,
1214 c->n_conn);
1215 tor_assert(c == c2);
1218 if (or_circ && or_circ->p_conn) {
1219 if (or_circ->p_circ_id) {
1220 /* ibid */
1221 circuit_t *c2 = circuit_get_by_circid_orconn_impl(or_circ->p_circ_id,
1222 or_circ->p_conn);
1223 tor_assert(c == c2);
1226 #if 0 /* false now that rendezvous exits are attached to p_streams */
1227 if (origin_circ)
1228 for (conn = origin_circ->p_streams; conn; conn = conn->next_stream)
1229 tor_assert(conn->_base.type == CONN_TYPE_AP);
1230 #endif
1231 if (or_circ)
1232 for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
1233 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
1235 tor_assert(c->deliver_window >= 0);
1236 tor_assert(c->package_window >= 0);
1237 if (c->state == CIRCUIT_STATE_OPEN) {
1238 tor_assert(!c->n_conn_onionskin);
1239 if (or_circ) {
1240 tor_assert(or_circ->n_crypto);
1241 tor_assert(or_circ->p_crypto);
1242 tor_assert(or_circ->n_digest);
1243 tor_assert(or_circ->p_digest);
1246 if (c->state == CIRCUIT_STATE_OR_WAIT && !c->marked_for_close) {
1247 tor_assert(circuits_pending_or_conns &&
1248 smartlist_isin(circuits_pending_or_conns, c));
1249 } else {
1250 tor_assert(!circuits_pending_or_conns ||
1251 !smartlist_isin(circuits_pending_or_conns, c));
1253 if (origin_circ && origin_circ->cpath) {
1254 assert_cpath_ok(origin_circ->cpath);
1256 if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
1257 tor_assert(or_circ);
1258 if (!c->marked_for_close) {
1259 tor_assert(or_circ->rend_splice);
1260 tor_assert(or_circ->rend_splice->rend_splice == or_circ);
1262 tor_assert(or_circ->rend_splice != or_circ);
1263 } else {
1264 tor_assert(!or_circ || !or_circ->rend_splice);