If configured, write cell statistics to disk periodically.
[tor/rransom.git] / src / or / circuitlist.c
blob5a20e7ebde7ab5ce025fcbc6f5443f794b136f86
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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file circuitlist.c
9 * \brief Manage the global circuit list.
10 **/
12 #include "or.h"
13 #include "ht.h"
15 /********* START VARIABLES **********/
17 /** A global list of all circuits at this hop. */
18 circuit_t *global_circuitlist=NULL;
20 /** A list of all the circuits in CIRCUIT_STATE_OR_WAIT. */
21 static smartlist_t *circuits_pending_or_conns=NULL;
23 static void circuit_free(circuit_t *circ);
24 static void circuit_free_cpath(crypt_path_t *cpath);
25 static void circuit_free_cpath_node(crypt_path_t *victim);
27 /********* END VARIABLES ************/
29 /** A map from OR connection and circuit ID to circuit. (Lookup performance is
30 * very important here, since we need to do it every time a cell arrives.) */
31 typedef struct orconn_circid_circuit_map_t {
32 HT_ENTRY(orconn_circid_circuit_map_t) node;
33 or_connection_t *or_conn;
34 circid_t circ_id;
35 circuit_t *circuit;
36 } orconn_circid_circuit_map_t;
38 /** Helper for hash tables: compare the OR connection and circuit ID for a and
39 * b, and return less than, equal to, or greater than zero appropriately.
41 static INLINE int
42 _orconn_circid_entries_eq(orconn_circid_circuit_map_t *a,
43 orconn_circid_circuit_map_t *b)
45 return a->or_conn == b->or_conn && a->circ_id == b->circ_id;
48 /** Helper: return a hash based on circuit ID and the pointer value of
49 * or_conn in <b>a</b>. */
50 static INLINE unsigned int
51 _orconn_circid_entry_hash(orconn_circid_circuit_map_t *a)
53 return (((unsigned)a->circ_id)<<8) ^ (unsigned)(uintptr_t)(a->or_conn);
56 /** Map from [orconn,circid] to circuit. */
57 static HT_HEAD(orconn_circid_map, orconn_circid_circuit_map_t)
58 orconn_circid_circuit_map = HT_INITIALIZER();
59 HT_PROTOTYPE(orconn_circid_map, orconn_circid_circuit_map_t, node,
60 _orconn_circid_entry_hash, _orconn_circid_entries_eq)
61 HT_GENERATE(orconn_circid_map, orconn_circid_circuit_map_t, node,
62 _orconn_circid_entry_hash, _orconn_circid_entries_eq, 0.6,
63 malloc, realloc, free)
65 /** The most recently returned entry from circuit_get_by_circid_orconn;
66 * used to improve performance when many cells arrive in a row from the
67 * same circuit.
69 orconn_circid_circuit_map_t *_last_circid_orconn_ent = NULL;
71 /** Implementation helper for circuit_set_{p,n}_circid_orconn: A circuit ID
72 * and/or or_connection for circ has just changed from <b>old_conn, old_id</b>
73 * to <b>conn, id</b>. Adjust the conn,circid map as appropriate, removing
74 * the old entry (if any) and adding a new one. If <b>active</b> is true,
75 * remove the circuit from the list of active circuits on old_conn and add it
76 * to the list of active circuits on conn.
77 * XXX "active" isn't an arg anymore */
78 static void
79 circuit_set_circid_orconn_helper(circuit_t *circ, int direction,
80 circid_t id,
81 or_connection_t *conn)
83 orconn_circid_circuit_map_t search;
84 orconn_circid_circuit_map_t *found;
85 or_connection_t *old_conn, **conn_ptr;
86 circid_t old_id, *circid_ptr;
87 int was_active, make_active;
89 if (direction == CELL_DIRECTION_OUT) {
90 conn_ptr = &circ->n_conn;
91 circid_ptr = &circ->n_circ_id;
92 was_active = circ->next_active_on_n_conn != NULL;
93 make_active = circ->n_conn_cells.n > 0;
94 } else {
95 or_circuit_t *c = TO_OR_CIRCUIT(circ);
96 conn_ptr = &c->p_conn;
97 circid_ptr = &c->p_circ_id;
98 was_active = c->next_active_on_p_conn != NULL;
99 make_active = c->p_conn_cells.n > 0;
101 old_conn = *conn_ptr;
102 old_id = *circid_ptr;
104 if (id == old_id && conn == old_conn)
105 return;
107 if (_last_circid_orconn_ent &&
108 ((old_id == _last_circid_orconn_ent->circ_id &&
109 old_conn == _last_circid_orconn_ent->or_conn) ||
110 (id == _last_circid_orconn_ent->circ_id &&
111 conn == _last_circid_orconn_ent->or_conn))) {
112 _last_circid_orconn_ent = NULL;
115 if (old_conn) { /* we may need to remove it from the conn-circid map */
116 tor_assert(old_conn->_base.magic == OR_CONNECTION_MAGIC);
117 search.circ_id = old_id;
118 search.or_conn = old_conn;
119 found = HT_REMOVE(orconn_circid_map, &orconn_circid_circuit_map, &search);
120 if (found) {
121 tor_free(found);
122 --old_conn->n_circuits;
124 if (was_active && old_conn != conn)
125 make_circuit_inactive_on_conn(circ,old_conn);
128 /* Change the values only after we have possibly made the circuit inactive
129 * on the previous conn. */
130 *conn_ptr = conn;
131 *circid_ptr = id;
133 if (conn == NULL)
134 return;
136 /* now add the new one to the conn-circid map */
137 search.circ_id = id;
138 search.or_conn = conn;
139 found = HT_FIND(orconn_circid_map, &orconn_circid_circuit_map, &search);
140 if (found) {
141 found->circuit = circ;
142 } else {
143 found = tor_malloc_zero(sizeof(orconn_circid_circuit_map_t));
144 found->circ_id = id;
145 found->or_conn = conn;
146 found->circuit = circ;
147 HT_INSERT(orconn_circid_map, &orconn_circid_circuit_map, found);
149 if (make_active && old_conn != conn)
150 make_circuit_active_on_conn(circ,conn);
152 ++conn->n_circuits;
155 /** Set the p_conn field of a circuit <b>circ</b>, along
156 * with the corresponding circuit ID, and add the circuit as appropriate
157 * to the (orconn,id)-\>circuit map. */
158 void
159 circuit_set_p_circid_orconn(or_circuit_t *circ, circid_t id,
160 or_connection_t *conn)
162 circuit_set_circid_orconn_helper(TO_CIRCUIT(circ), CELL_DIRECTION_IN,
163 id, conn);
165 if (conn)
166 tor_assert(bool_eq(circ->p_conn_cells.n, circ->next_active_on_p_conn));
169 /** Set the n_conn field of a circuit <b>circ</b>, along
170 * with the corresponding circuit ID, and add the circuit as appropriate
171 * to the (orconn,id)-\>circuit map. */
172 void
173 circuit_set_n_circid_orconn(circuit_t *circ, circid_t id,
174 or_connection_t *conn)
176 circuit_set_circid_orconn_helper(circ, CELL_DIRECTION_OUT, id, conn);
178 if (conn)
179 tor_assert(bool_eq(circ->n_conn_cells.n, circ->next_active_on_n_conn));
182 /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
183 * it from lists as appropriate. */
184 void
185 circuit_set_state(circuit_t *circ, uint8_t state)
187 tor_assert(circ);
188 if (state == circ->state)
189 return;
190 if (!circuits_pending_or_conns)
191 circuits_pending_or_conns = smartlist_create();
192 if (circ->state == CIRCUIT_STATE_OR_WAIT) {
193 /* remove from waiting-circuit list. */
194 smartlist_remove(circuits_pending_or_conns, circ);
196 if (state == CIRCUIT_STATE_OR_WAIT) {
197 /* add to waiting-circuit list. */
198 smartlist_add(circuits_pending_or_conns, circ);
200 if (state == CIRCUIT_STATE_OPEN)
201 tor_assert(!circ->n_conn_onionskin);
202 circ->state = state;
205 /** Add <b>circ</b> to the global list of circuits. This is called only from
206 * within circuit_new.
208 static void
209 circuit_add(circuit_t *circ)
211 if (!global_circuitlist) { /* first one */
212 global_circuitlist = circ;
213 circ->next = NULL;
214 } else {
215 circ->next = global_circuitlist;
216 global_circuitlist = circ;
220 /** Append to <b>out</b> all circuits in state OR_WAIT waiting for
221 * the given connection. */
222 void
223 circuit_get_all_pending_on_or_conn(smartlist_t *out, or_connection_t *or_conn)
225 tor_assert(out);
226 tor_assert(or_conn);
228 if (!circuits_pending_or_conns)
229 return;
231 SMARTLIST_FOREACH_BEGIN(circuits_pending_or_conns, circuit_t *, circ) {
232 if (circ->marked_for_close)
233 continue;
234 if (!circ->n_hop)
235 continue;
236 tor_assert(circ->state == CIRCUIT_STATE_OR_WAIT);
237 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
238 /* Look at addr/port. This is an unkeyed connection. */
239 if (!tor_addr_eq(&circ->n_hop->addr, &or_conn->_base.addr) ||
240 circ->n_hop->port != or_conn->_base.port)
241 continue;
242 } else {
243 /* We expected a key. See if it's the right one. */
244 if (memcmp(or_conn->identity_digest,
245 circ->n_hop->identity_digest, DIGEST_LEN))
246 continue;
248 smartlist_add(out, circ);
249 } SMARTLIST_FOREACH_END(circ);
252 /** Return the number of circuits in state OR_WAIT, waiting for the given
253 * connection. */
255 circuit_count_pending_on_or_conn(or_connection_t *or_conn)
257 int cnt;
258 smartlist_t *sl = smartlist_create();
259 circuit_get_all_pending_on_or_conn(sl, or_conn);
260 cnt = smartlist_len(sl);
261 smartlist_free(sl);
262 log_debug(LD_CIRC,"or_conn to %s, %d pending circs",
263 or_conn->nickname ? or_conn->nickname : "NULL", cnt);
264 return cnt;
267 /** Detach from the global circuit list, and deallocate, all
268 * circuits that have been marked for close.
270 void
271 circuit_close_all_marked(void)
273 circuit_t *tmp,*m;
275 while (global_circuitlist && global_circuitlist->marked_for_close) {
276 tmp = global_circuitlist->next;
277 circuit_free(global_circuitlist);
278 global_circuitlist = tmp;
281 tmp = global_circuitlist;
282 while (tmp && tmp->next) {
283 if (tmp->next->marked_for_close) {
284 m = tmp->next->next;
285 circuit_free(tmp->next);
286 tmp->next = m;
287 /* Need to check new tmp->next; don't advance tmp. */
288 } else {
289 /* Advance tmp. */
290 tmp = tmp->next;
295 /** Return the head of the global linked list of circuits. */
296 circuit_t *
297 _circuit_get_global_list(void)
299 return global_circuitlist;
302 /** Function to make circ-\>state human-readable */
303 const char *
304 circuit_state_to_string(int state)
306 static char buf[64];
307 switch (state) {
308 case CIRCUIT_STATE_BUILDING: return "doing handshakes";
309 case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
310 case CIRCUIT_STATE_OR_WAIT: return "connecting to server";
311 case CIRCUIT_STATE_OPEN: return "open";
312 default:
313 log_warn(LD_BUG, "Unknown circuit state %d", state);
314 tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
315 return buf;
319 /** Map a circuit purpose to a string suitable to be displayed to a
320 * controller. */
321 const char *
322 circuit_purpose_to_controller_string(uint8_t purpose)
324 static char buf[32];
325 switch (purpose) {
326 case CIRCUIT_PURPOSE_OR:
327 case CIRCUIT_PURPOSE_INTRO_POINT:
328 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
329 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
330 return "SERVER"; /* A controller should never see these, actually. */
332 case CIRCUIT_PURPOSE_C_GENERAL:
333 return "GENERAL";
334 case CIRCUIT_PURPOSE_C_INTRODUCING:
335 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
336 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
337 return "HS_CLIENT_INTRO";
339 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
340 case CIRCUIT_PURPOSE_C_REND_READY:
341 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
342 case CIRCUIT_PURPOSE_C_REND_JOINED:
343 return "HS_CLIENT_REND";
345 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
346 case CIRCUIT_PURPOSE_S_INTRO:
347 return "HS_SERVICE_INTRO";
349 case CIRCUIT_PURPOSE_S_CONNECT_REND:
350 case CIRCUIT_PURPOSE_S_REND_JOINED:
351 return "HS_SERVICE_REND";
353 case CIRCUIT_PURPOSE_TESTING:
354 return "TESTING";
355 case CIRCUIT_PURPOSE_CONTROLLER:
356 return "CONTROLLER";
358 default:
359 tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
360 return buf;
364 /** Initialize the common elements in a circuit_t, and add it to the global
365 * list. */
366 static void
367 init_circuit_base(circuit_t *circ)
369 circ->timestamp_created = time(NULL);
371 circ->package_window = CIRCWINDOW_START;
372 circ->deliver_window = CIRCWINDOW_START;
374 circuit_add(circ);
377 /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
378 * and <b>p_conn</b>. Add it to the global circuit list.
380 origin_circuit_t *
381 origin_circuit_new(void)
383 origin_circuit_t *circ;
384 /* never zero, since a global ID of 0 is treated specially by the
385 * controller */
386 static uint32_t n_circuits_allocated = 1;
388 circ = tor_malloc_zero(sizeof(origin_circuit_t));
389 circ->_base.magic = ORIGIN_CIRCUIT_MAGIC;
391 circ->next_stream_id = crypto_rand_int(1<<16);
392 circ->global_identifier = n_circuits_allocated++;
393 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
394 circ->remaining_relay_early_cells -= crypto_rand_int(2);
396 init_circuit_base(TO_CIRCUIT(circ));
398 return circ;
401 /** Allocate a new or_circuit_t, connected to <b>p_conn</b> as
402 * <b>p_circ_id</b>. If <b>p_conn</b> is NULL, the circuit is unattached. */
403 or_circuit_t *
404 or_circuit_new(circid_t p_circ_id, or_connection_t *p_conn)
406 /* CircIDs */
407 or_circuit_t *circ;
409 circ = tor_malloc_zero(sizeof(or_circuit_t));
410 circ->_base.magic = OR_CIRCUIT_MAGIC;
412 if (p_conn)
413 circuit_set_p_circid_orconn(circ, p_circ_id, p_conn);
415 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
417 init_circuit_base(TO_CIRCUIT(circ));
419 return circ;
422 /** Deallocate space associated with circ.
424 static void
425 circuit_free(circuit_t *circ)
427 void *mem;
428 size_t memlen;
429 tor_assert(circ);
430 if (CIRCUIT_IS_ORIGIN(circ)) {
431 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
432 mem = ocirc;
433 memlen = sizeof(origin_circuit_t);
434 tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
435 if (ocirc->build_state) {
436 if (ocirc->build_state->chosen_exit)
437 extend_info_free(ocirc->build_state->chosen_exit);
438 if (ocirc->build_state->pending_final_cpath)
439 circuit_free_cpath_node(ocirc->build_state->pending_final_cpath);
441 tor_free(ocirc->build_state);
443 circuit_free_cpath(ocirc->cpath);
444 if (ocirc->intro_key)
445 crypto_free_pk_env(ocirc->intro_key);
446 if (ocirc->rend_data)
447 rend_data_free(ocirc->rend_data);
448 } else {
449 or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
450 #ifdef ENABLE_BUFFER_STATS
451 /* Remember cell statistics for this circuit before deallocating. */
452 if (get_options()->CellStatistics)
453 add_circ_to_buffer_stats(circ, time(NULL));
454 #endif
455 mem = ocirc;
456 memlen = sizeof(or_circuit_t);
457 tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
459 if (ocirc->p_crypto)
460 crypto_free_cipher_env(ocirc->p_crypto);
461 if (ocirc->p_digest)
462 crypto_free_digest_env(ocirc->p_digest);
463 if (ocirc->n_crypto)
464 crypto_free_cipher_env(ocirc->n_crypto);
465 if (ocirc->n_digest)
466 crypto_free_digest_env(ocirc->n_digest);
468 if (ocirc->rend_splice) {
469 or_circuit_t *other = ocirc->rend_splice;
470 tor_assert(other->_base.magic == OR_CIRCUIT_MAGIC);
471 other->rend_splice = NULL;
474 /* remove from map. */
475 circuit_set_p_circid_orconn(ocirc, 0, NULL);
477 /* Clear cell queue _after_ removing it from the map. Otherwise our
478 * "active" checks will be violated. */
479 cell_queue_clear(&ocirc->p_conn_cells);
482 if (circ->n_hop)
483 extend_info_free(circ->n_hop);
484 tor_free(circ->n_conn_onionskin);
486 /* Remove from map. */
487 circuit_set_n_circid_orconn(circ, 0, NULL);
489 /* Clear cell queue _after_ removing it from the map. Otherwise our
490 * "active" checks will be violated. */
491 cell_queue_clear(&circ->n_conn_cells);
493 memset(circ, 0xAA, memlen); /* poison memory */
494 tor_free(mem);
497 /** Deallocate space associated with the linked list <b>cpath</b>. */
498 static void
499 circuit_free_cpath(crypt_path_t *cpath)
501 crypt_path_t *victim, *head=cpath;
503 if (!cpath)
504 return;
506 /* it's a doubly linked list, so we have to notice when we've
507 * gone through it once. */
508 while (cpath->next && cpath->next != head) {
509 victim = cpath;
510 cpath = victim->next;
511 circuit_free_cpath_node(victim);
514 circuit_free_cpath_node(cpath);
517 /** Release all storage held by circuits. */
518 void
519 circuit_free_all(void)
521 circuit_t *next;
522 while (global_circuitlist) {
523 next = global_circuitlist->next;
524 if (! CIRCUIT_IS_ORIGIN(global_circuitlist)) {
525 or_circuit_t *or_circ = TO_OR_CIRCUIT(global_circuitlist);
526 while (or_circ->resolving_streams) {
527 edge_connection_t *next_conn;
528 next_conn = or_circ->resolving_streams->next_stream;
529 connection_free(TO_CONN(or_circ->resolving_streams));
530 or_circ->resolving_streams = next_conn;
533 circuit_free(global_circuitlist);
534 global_circuitlist = next;
536 if (circuits_pending_or_conns) {
537 smartlist_free(circuits_pending_or_conns);
538 circuits_pending_or_conns = NULL;
540 HT_CLEAR(orconn_circid_map, &orconn_circid_circuit_map);
543 /** Deallocate space associated with the cpath node <b>victim</b>. */
544 static void
545 circuit_free_cpath_node(crypt_path_t *victim)
547 if (victim->f_crypto)
548 crypto_free_cipher_env(victim->f_crypto);
549 if (victim->b_crypto)
550 crypto_free_cipher_env(victim->b_crypto);
551 if (victim->f_digest)
552 crypto_free_digest_env(victim->f_digest);
553 if (victim->b_digest)
554 crypto_free_digest_env(victim->b_digest);
555 if (victim->dh_handshake_state)
556 crypto_dh_free(victim->dh_handshake_state);
557 if (victim->extend_info)
558 extend_info_free(victim->extend_info);
560 memset(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
561 tor_free(victim);
564 /** A helper function for circuit_dump_by_conn() below. Log a bunch
565 * of information about circuit <b>circ</b>.
567 static void
568 circuit_dump_details(int severity, circuit_t *circ, int conn_array_index,
569 const char *type, int this_circid, int other_circid)
571 log(severity, LD_CIRC, "Conn %d has %s circuit: circID %d (other side %d), "
572 "state %d (%s), born %d:",
573 conn_array_index, type, this_circid, other_circid, circ->state,
574 circuit_state_to_string(circ->state), (int)circ->timestamp_created);
575 if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
576 circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
580 /** Log, at severity <b>severity</b>, information about each circuit
581 * that is connected to <b>conn</b>.
583 void
584 circuit_dump_by_conn(connection_t *conn, int severity)
586 circuit_t *circ;
587 edge_connection_t *tmpconn;
589 for (circ=global_circuitlist;circ;circ = circ->next) {
590 circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
591 if (circ->marked_for_close)
592 continue;
594 if (! CIRCUIT_IS_ORIGIN(circ))
595 p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
597 if (! CIRCUIT_IS_ORIGIN(circ) && TO_OR_CIRCUIT(circ)->p_conn &&
598 TO_CONN(TO_OR_CIRCUIT(circ)->p_conn) == conn)
599 circuit_dump_details(severity, circ, conn->conn_array_index, "App-ward",
600 p_circ_id, n_circ_id);
601 if (CIRCUIT_IS_ORIGIN(circ)) {
602 for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
603 tmpconn=tmpconn->next_stream) {
604 if (TO_CONN(tmpconn) == conn) {
605 circuit_dump_details(severity, circ, conn->conn_array_index,
606 "App-ward", p_circ_id, n_circ_id);
610 if (circ->n_conn && TO_CONN(circ->n_conn) == conn)
611 circuit_dump_details(severity, circ, conn->conn_array_index, "Exit-ward",
612 n_circ_id, p_circ_id);
613 if (! CIRCUIT_IS_ORIGIN(circ)) {
614 for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
615 tmpconn=tmpconn->next_stream) {
616 if (TO_CONN(tmpconn) == conn) {
617 circuit_dump_details(severity, circ, conn->conn_array_index,
618 "Exit-ward", n_circ_id, p_circ_id);
622 if (!circ->n_conn && circ->n_hop &&
623 tor_addr_eq(&circ->n_hop->addr, &conn->addr) &&
624 circ->n_hop->port == conn->port &&
625 conn->type == CONN_TYPE_OR &&
626 !memcmp(TO_OR_CONN(conn)->identity_digest,
627 circ->n_hop->identity_digest, DIGEST_LEN)) {
628 circuit_dump_details(severity, circ, conn->conn_array_index,
629 (circ->state == CIRCUIT_STATE_OPEN &&
630 !CIRCUIT_IS_ORIGIN(circ)) ?
631 "Endpoint" : "Pending",
632 n_circ_id, p_circ_id);
637 /** Return the circuit whose global ID is <b>id</b>, or NULL if no
638 * such circuit exists. */
639 origin_circuit_t *
640 circuit_get_by_global_id(uint32_t id)
642 circuit_t *circ;
643 for (circ=global_circuitlist;circ;circ = circ->next) {
644 if (CIRCUIT_IS_ORIGIN(circ) &&
645 TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
646 if (circ->marked_for_close)
647 return NULL;
648 else
649 return TO_ORIGIN_CIRCUIT(circ);
652 return NULL;
655 /** Return a circ such that:
656 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
657 * - circ is attached to <b>conn</b>, either as p_conn or n_conn.
658 * Return NULL if no such circuit exists.
660 static INLINE circuit_t *
661 circuit_get_by_circid_orconn_impl(circid_t circ_id, or_connection_t *conn)
663 orconn_circid_circuit_map_t search;
664 orconn_circid_circuit_map_t *found;
666 if (_last_circid_orconn_ent &&
667 circ_id == _last_circid_orconn_ent->circ_id &&
668 conn == _last_circid_orconn_ent->or_conn) {
669 found = _last_circid_orconn_ent;
670 } else {
671 search.circ_id = circ_id;
672 search.or_conn = conn;
673 found = HT_FIND(orconn_circid_map, &orconn_circid_circuit_map, &search);
674 _last_circid_orconn_ent = found;
676 if (found && found->circuit)
677 return found->circuit;
679 return NULL;
681 /* The rest of this checks for bugs. Disabled by default. */
683 circuit_t *circ;
684 for (circ=global_circuitlist;circ;circ = circ->next) {
685 if (! CIRCUIT_IS_ORIGIN(circ)) {
686 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
687 if (or_circ->p_conn == conn && or_circ->p_circ_id == circ_id) {
688 log_warn(LD_BUG,
689 "circuit matches p_conn, but not in hash table (Bug!)");
690 return circ;
693 if (circ->n_conn == conn && circ->n_circ_id == circ_id) {
694 log_warn(LD_BUG,
695 "circuit matches n_conn, but not in hash table (Bug!)");
696 return circ;
699 return NULL;
703 /** Return a circ such that:
704 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
705 * - circ is attached to <b>conn</b>, either as p_conn or n_conn.
706 * - circ is not marked for close.
707 * Return NULL if no such circuit exists.
709 circuit_t *
710 circuit_get_by_circid_orconn(circid_t circ_id, or_connection_t *conn)
712 circuit_t *circ = circuit_get_by_circid_orconn_impl(circ_id, conn);
713 if (!circ || circ->marked_for_close)
714 return NULL;
715 else
716 return circ;
719 /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
720 * circuit, marked or not, on <b>conn</b>. */
722 circuit_id_in_use_on_orconn(circid_t circ_id, or_connection_t *conn)
724 return circuit_get_by_circid_orconn_impl(circ_id, conn) != NULL;
727 /** Return the circuit that a given edge connection is using. */
728 circuit_t *
729 circuit_get_by_edge_conn(edge_connection_t *conn)
731 circuit_t *circ;
733 circ = conn->on_circuit;
734 tor_assert(!circ ||
735 (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
736 : circ->magic == OR_CIRCUIT_MAGIC));
738 return circ;
741 /** For each circuit that has <b>conn</b> as n_conn or p_conn, unlink the
742 * circuit from the orconn,circid map, and mark it for close if it hasn't
743 * been marked already.
745 void
746 circuit_unlink_all_from_or_conn(or_connection_t *conn, int reason)
748 circuit_t *circ;
750 connection_or_unlink_all_active_circs(conn);
752 for (circ = global_circuitlist; circ; circ = circ->next) {
753 int mark = 0;
754 if (circ->n_conn == conn) {
755 circuit_set_n_circid_orconn(circ, 0, NULL);
756 mark = 1;
758 if (! CIRCUIT_IS_ORIGIN(circ)) {
759 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
760 if (or_circ->p_conn == conn) {
761 circuit_set_p_circid_orconn(or_circ, 0, NULL);
762 mark = 1;
765 if (mark && !circ->marked_for_close)
766 circuit_mark_for_close(circ, reason);
770 /** Return a circ such that:
771 * - circ-\>rend_data-\>query is equal to <b>rend_query</b>, and
772 * - circ-\>purpose is equal to <b>purpose</b>.
774 * Return NULL if no such circuit exists.
776 origin_circuit_t *
777 circuit_get_by_rend_query_and_purpose(const char *rend_query, uint8_t purpose)
779 circuit_t *circ;
781 tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
783 for (circ = global_circuitlist; circ; circ = circ->next) {
784 if (!circ->marked_for_close &&
785 circ->purpose == purpose) {
786 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
787 if (ocirc->rend_data &&
788 !rend_cmp_service_ids(rend_query,
789 ocirc->rend_data->onion_address))
790 return ocirc;
793 return NULL;
796 /** Return the first circuit originating here in global_circuitlist after
797 * <b>start</b> whose purpose is <b>purpose</b>, and where
798 * <b>digest</b> (if set) matches the rend_pk_digest field. Return NULL if no
799 * circuit is found. If <b>start</b> is NULL, begin at the start of the list.
801 origin_circuit_t *
802 circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
803 const char *digest, uint8_t purpose)
805 circuit_t *circ;
806 tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
807 if (start == NULL)
808 circ = global_circuitlist;
809 else
810 circ = TO_CIRCUIT(start)->next;
812 for ( ; circ; circ = circ->next) {
813 if (circ->marked_for_close)
814 continue;
815 if (circ->purpose != purpose)
816 continue;
817 if (!digest)
818 return TO_ORIGIN_CIRCUIT(circ);
819 else if (TO_ORIGIN_CIRCUIT(circ)->rend_data &&
820 !memcmp(TO_ORIGIN_CIRCUIT(circ)->rend_data->rend_pk_digest,
821 digest, DIGEST_LEN))
822 return TO_ORIGIN_CIRCUIT(circ);
824 return NULL;
827 /** Return the first OR circuit in the global list whose purpose is
828 * <b>purpose</b>, and whose rend_token is the <b>len</b>-byte
829 * <b>token</b>. */
830 static or_circuit_t *
831 circuit_get_by_rend_token_and_purpose(uint8_t purpose, const char *token,
832 size_t len)
834 circuit_t *circ;
835 for (circ = global_circuitlist; circ; circ = circ->next) {
836 if (! circ->marked_for_close &&
837 circ->purpose == purpose &&
838 ! memcmp(TO_OR_CIRCUIT(circ)->rend_token, token, len))
839 return TO_OR_CIRCUIT(circ);
841 return NULL;
844 /** Return the circuit waiting for a rendezvous with the provided cookie.
845 * Return NULL if no such circuit is found.
847 or_circuit_t *
848 circuit_get_rendezvous(const char *cookie)
850 return circuit_get_by_rend_token_and_purpose(
851 CIRCUIT_PURPOSE_REND_POINT_WAITING,
852 cookie, REND_COOKIE_LEN);
855 /** Return the circuit waiting for intro cells of the given digest.
856 * Return NULL if no such circuit is found.
858 or_circuit_t *
859 circuit_get_intro_point(const char *digest)
861 return circuit_get_by_rend_token_and_purpose(
862 CIRCUIT_PURPOSE_INTRO_POINT, digest,
863 DIGEST_LEN);
866 /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
867 * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
868 * flags in <b>flags</b>, and if info is defined, does not already use info
869 * as any of its hops; or NULL if no circuit fits this description.
871 * The <b>purpose</b> argument (currently ignored) refers to the purpose of
872 * the circuit we want to create, not the purpose of the circuit we want to
873 * cannibalize.
875 * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
877 origin_circuit_t *
878 circuit_find_to_cannibalize(uint8_t purpose, extend_info_t *info,
879 int flags)
881 circuit_t *_circ;
882 origin_circuit_t *best=NULL;
883 int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
884 int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
885 int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
887 log_debug(LD_CIRC,
888 "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
889 "capacity %d, internal %d",
890 purpose, need_uptime, need_capacity, internal);
892 for (_circ=global_circuitlist; _circ; _circ = _circ->next) {
893 if (CIRCUIT_IS_ORIGIN(_circ) &&
894 _circ->state == CIRCUIT_STATE_OPEN &&
895 !_circ->marked_for_close &&
896 _circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
897 !_circ->timestamp_dirty) {
898 origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(_circ);
899 if ((!need_uptime || circ->build_state->need_uptime) &&
900 (!need_capacity || circ->build_state->need_capacity) &&
901 (internal == circ->build_state->is_internal) &&
902 circ->remaining_relay_early_cells) {
903 if (info) {
904 /* need to make sure we don't duplicate hops */
905 crypt_path_t *hop = circ->cpath;
906 routerinfo_t *ri1 = router_get_by_digest(info->identity_digest);
907 do {
908 routerinfo_t *ri2;
909 if (!memcmp(hop->extend_info->identity_digest,
910 info->identity_digest, DIGEST_LEN))
911 goto next;
912 if (ri1 &&
913 (ri2 = router_get_by_digest(hop->extend_info->identity_digest))
914 && routers_in_same_family(ri1, ri2))
915 goto next;
916 hop=hop->next;
917 } while (hop!=circ->cpath);
919 if (!best || (best->build_state->need_uptime && !need_uptime))
920 best = circ;
921 next: ;
925 return best;
928 /** Return the number of hops in circuit's path. */
930 circuit_get_cpath_len(origin_circuit_t *circ)
932 int n = 0;
933 if (circ && circ->cpath) {
934 crypt_path_t *cpath, *cpath_next = NULL;
935 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
936 cpath_next = cpath->next;
937 ++n;
940 return n;
943 /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
944 * aren't that many hops in the list. */
945 crypt_path_t *
946 circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
948 if (circ && circ->cpath && hopnum > 0) {
949 crypt_path_t *cpath, *cpath_next = NULL;
950 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
951 cpath_next = cpath->next;
952 if (--hopnum <= 0)
953 return cpath;
956 return NULL;
959 /** Go through the circuitlist; mark-for-close each circuit that starts
960 * at us but has not yet been used. */
961 void
962 circuit_mark_all_unused_circs(void)
964 circuit_t *circ;
966 for (circ=global_circuitlist; circ; circ = circ->next) {
967 if (CIRCUIT_IS_ORIGIN(circ) &&
968 !circ->marked_for_close &&
969 !circ->timestamp_dirty)
970 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
974 /** Go through the circuitlist; for each circuit that starts at us
975 * and is dirty, frob its timestamp_dirty so we won't use it for any
976 * new streams.
978 * This is useful for letting the user change pseudonyms, so new
979 * streams will not be linkable to old streams.
981 void
982 circuit_expire_all_dirty_circs(void)
984 circuit_t *circ;
985 or_options_t *options = get_options();
987 for (circ=global_circuitlist; circ; circ = circ->next) {
988 if (CIRCUIT_IS_ORIGIN(circ) &&
989 !circ->marked_for_close &&
990 circ->timestamp_dirty)
991 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
995 /** Mark <b>circ</b> to be closed next time we call
996 * circuit_close_all_marked(). Do any cleanup needed:
997 * - If state is onionskin_pending, remove circ from the onion_pending
998 * list.
999 * - If circ isn't open yet: call circuit_build_failed() if we're
1000 * the origin, and in either case call circuit_rep_hist_note_result()
1001 * to note stats.
1002 * - If purpose is C_INTRODUCE_ACK_WAIT, remove the intro point we
1003 * just tried from our list of intro points for that service
1004 * descriptor.
1005 * - Send appropriate destroys and edge_destroys for conns and
1006 * streams attached to circ.
1007 * - If circ->rend_splice is set (we are the midpoint of a joined
1008 * rendezvous stream), then mark the other circuit to close as well.
1010 void
1011 _circuit_mark_for_close(circuit_t *circ, int reason, int line,
1012 const char *file)
1014 int orig_reason = reason; /* Passed to the controller */
1015 assert_circuit_ok(circ);
1016 tor_assert(line);
1017 tor_assert(file);
1019 if (circ->marked_for_close) {
1020 log(LOG_WARN,LD_BUG,
1021 "Duplicate call to circuit_mark_for_close at %s:%d"
1022 " (first at %s:%d)", file, line,
1023 circ->marked_for_close_file, circ->marked_for_close);
1024 return;
1026 if (reason == END_CIRC_AT_ORIGIN) {
1027 if (!CIRCUIT_IS_ORIGIN(circ)) {
1028 log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
1029 "but circuit was not at origin. (called %s:%d, purpose=%d)",
1030 file, line, circ->purpose);
1032 reason = END_CIRC_REASON_NONE;
1034 if (CIRCUIT_IS_ORIGIN(circ)) {
1035 /* We don't send reasons when closing circuits at the origin. */
1036 reason = END_CIRC_REASON_NONE;
1039 if (reason & END_CIRC_REASON_FLAG_REMOTE)
1040 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
1042 if (reason < _END_CIRC_REASON_MIN || reason > _END_CIRC_REASON_MAX) {
1043 if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
1044 log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
1045 reason = END_CIRC_REASON_NONE;
1048 if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
1049 onion_pending_remove(TO_OR_CIRCUIT(circ));
1051 /* If the circuit ever became OPEN, we sent it to the reputation history
1052 * module then. If it isn't OPEN, we send it there now to remember which
1053 * links worked and which didn't.
1055 if (circ->state != CIRCUIT_STATE_OPEN) {
1056 if (CIRCUIT_IS_ORIGIN(circ)) {
1057 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1058 circuit_build_failed(ocirc); /* take actions if necessary */
1059 circuit_rep_hist_note_result(ocirc);
1062 if (circ->state == CIRCUIT_STATE_OR_WAIT) {
1063 if (circuits_pending_or_conns)
1064 smartlist_remove(circuits_pending_or_conns, circ);
1066 if (CIRCUIT_IS_ORIGIN(circ)) {
1067 control_event_circuit_status(TO_ORIGIN_CIRCUIT(circ),
1068 (circ->state == CIRCUIT_STATE_OPEN)?CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
1069 orig_reason);
1071 if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1072 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1073 tor_assert(circ->state == CIRCUIT_STATE_OPEN);
1074 tor_assert(ocirc->build_state->chosen_exit);
1075 tor_assert(ocirc->rend_data);
1076 /* treat this like getting a nack from it */
1077 log_info(LD_REND, "Failed intro circ %s to %s (awaiting ack). "
1078 "Removing from descriptor.",
1079 safe_str(ocirc->rend_data->onion_address),
1080 safe_str(build_state_get_exit_nickname(ocirc->build_state)));
1081 rend_client_remove_intro_point(ocirc->build_state->chosen_exit,
1082 ocirc->rend_data);
1084 if (circ->n_conn)
1085 connection_or_send_destroy(circ->n_circ_id, circ->n_conn, reason);
1087 if (! CIRCUIT_IS_ORIGIN(circ)) {
1088 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1089 edge_connection_t *conn;
1090 for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
1091 connection_edge_destroy(or_circ->p_circ_id, conn);
1093 while (or_circ->resolving_streams) {
1094 conn = or_circ->resolving_streams;
1095 or_circ->resolving_streams = conn->next_stream;
1096 if (!conn->_base.marked_for_close) {
1097 /* The client will see a DESTROY, and infer that the connections
1098 * are closing because the circuit is getting torn down. No need
1099 * to send an end cell. */
1100 conn->edge_has_sent_end = 1;
1101 conn->end_reason = END_STREAM_REASON_DESTROY;
1102 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
1103 connection_mark_for_close(TO_CONN(conn));
1105 conn->on_circuit = NULL;
1108 if (or_circ->p_conn)
1109 connection_or_send_destroy(or_circ->p_circ_id, or_circ->p_conn, reason);
1110 } else {
1111 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1112 edge_connection_t *conn;
1113 for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
1114 connection_edge_destroy(circ->n_circ_id, conn);
1117 circ->marked_for_close = line;
1118 circ->marked_for_close_file = file;
1120 if (!CIRCUIT_IS_ORIGIN(circ)) {
1121 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1122 if (or_circ->rend_splice) {
1123 if (!or_circ->rend_splice->_base.marked_for_close) {
1124 /* do this after marking this circuit, to avoid infinite recursion. */
1125 circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
1127 or_circ->rend_splice = NULL;
1132 /** Verify that cpath layer <b>cp</b> has all of its invariants
1133 * correct. Trigger an assert if anything is invalid.
1135 void
1136 assert_cpath_layer_ok(const crypt_path_t *cp)
1138 // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
1139 // tor_assert(cp->port);
1140 tor_assert(cp);
1141 tor_assert(cp->magic == CRYPT_PATH_MAGIC);
1142 switch (cp->state)
1144 case CPATH_STATE_OPEN:
1145 tor_assert(cp->f_crypto);
1146 tor_assert(cp->b_crypto);
1147 /* fall through */
1148 case CPATH_STATE_CLOSED:
1149 tor_assert(!cp->dh_handshake_state);
1150 break;
1151 case CPATH_STATE_AWAITING_KEYS:
1152 /* tor_assert(cp->dh_handshake_state); */
1153 break;
1154 default:
1155 log_fn(LOG_ERR, LD_BUG, "Unexpected state %d", cp->state);
1156 tor_assert(0);
1158 tor_assert(cp->package_window >= 0);
1159 tor_assert(cp->deliver_window >= 0);
1162 /** Verify that cpath <b>cp</b> has all of its invariants
1163 * correct. Trigger an assert if anything is invalid.
1165 static void
1166 assert_cpath_ok(const crypt_path_t *cp)
1168 const crypt_path_t *start = cp;
1170 do {
1171 assert_cpath_layer_ok(cp);
1172 /* layers must be in sequence of: "open* awaiting? closed*" */
1173 if (cp != start) {
1174 if (cp->state == CPATH_STATE_AWAITING_KEYS) {
1175 tor_assert(cp->prev->state == CPATH_STATE_OPEN);
1176 } else if (cp->state == CPATH_STATE_OPEN) {
1177 tor_assert(cp->prev->state == CPATH_STATE_OPEN);
1180 cp = cp->next;
1181 tor_assert(cp);
1182 } while (cp != start);
1185 /** Verify that circuit <b>c</b> has all of its invariants
1186 * correct. Trigger an assert if anything is invalid.
1188 void
1189 assert_circuit_ok(const circuit_t *c)
1191 edge_connection_t *conn;
1192 const or_circuit_t *or_circ = NULL;
1193 const origin_circuit_t *origin_circ = NULL;
1195 tor_assert(c);
1196 tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
1197 tor_assert(c->purpose >= _CIRCUIT_PURPOSE_MIN &&
1198 c->purpose <= _CIRCUIT_PURPOSE_MAX);
1201 /* Having a separate variable for this pleases GCC 4.2 in ways I hope I
1202 * never understand. -NM. */
1203 circuit_t *nonconst_circ = (circuit_t*) c;
1204 if (CIRCUIT_IS_ORIGIN(c))
1205 origin_circ = TO_ORIGIN_CIRCUIT(nonconst_circ);
1206 else
1207 or_circ = TO_OR_CIRCUIT(nonconst_circ);
1210 if (c->n_conn) {
1211 tor_assert(!c->n_hop);
1213 if (c->n_circ_id) {
1214 /* We use the _impl variant here to make sure we don't fail on marked
1215 * circuits, which would not be returned by the regular function. */
1216 circuit_t *c2 = circuit_get_by_circid_orconn_impl(c->n_circ_id,
1217 c->n_conn);
1218 tor_assert(c == c2);
1221 if (or_circ && or_circ->p_conn) {
1222 if (or_circ->p_circ_id) {
1223 /* ibid */
1224 circuit_t *c2 = circuit_get_by_circid_orconn_impl(or_circ->p_circ_id,
1225 or_circ->p_conn);
1226 tor_assert(c == c2);
1229 #if 0 /* false now that rendezvous exits are attached to p_streams */
1230 if (origin_circ)
1231 for (conn = origin_circ->p_streams; conn; conn = conn->next_stream)
1232 tor_assert(conn->_base.type == CONN_TYPE_AP);
1233 #endif
1234 if (or_circ)
1235 for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
1236 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
1238 tor_assert(c->deliver_window >= 0);
1239 tor_assert(c->package_window >= 0);
1240 if (c->state == CIRCUIT_STATE_OPEN) {
1241 tor_assert(!c->n_conn_onionskin);
1242 if (or_circ) {
1243 tor_assert(or_circ->n_crypto);
1244 tor_assert(or_circ->p_crypto);
1245 tor_assert(or_circ->n_digest);
1246 tor_assert(or_circ->p_digest);
1249 if (c->state == CIRCUIT_STATE_OR_WAIT && !c->marked_for_close) {
1250 tor_assert(circuits_pending_or_conns &&
1251 smartlist_isin(circuits_pending_or_conns, c));
1252 } else {
1253 tor_assert(!circuits_pending_or_conns ||
1254 !smartlist_isin(circuits_pending_or_conns, c));
1256 if (origin_circ && origin_circ->cpath) {
1257 assert_cpath_ok(origin_circ->cpath);
1259 if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
1260 tor_assert(or_circ);
1261 if (!c->marked_for_close) {
1262 tor_assert(or_circ->rend_splice);
1263 tor_assert(or_circ->rend_splice->rend_splice == or_circ);
1265 tor_assert(or_circ->rend_splice != or_circ);
1266 } else {
1267 tor_assert(!or_circ || !or_circ->rend_splice);