Now that FOO_free(NULL) always works, remove checks before calling it.
[tor.git] / src / or / circuitlist.c
blob2c949def0022a4c369625fe7ce7128a0c86cfcc5
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 /** Pick a reasonable package_window to start out for our circuits.
365 * Originally this was hard-coded at 1000, but now the consensus votes
366 * on the answer. See proposal 168. */
367 int32_t
368 circuit_initial_package_window(void)
370 int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START);
371 /* If the consensus tells us a negative number, we'd assert. */
372 if (num < 0)
373 num = CIRCWINDOW_START;
374 return num;
377 /** Initialize the common elements in a circuit_t, and add it to the global
378 * list. */
379 static void
380 init_circuit_base(circuit_t *circ)
382 circ->timestamp_created = time(NULL);
383 tor_gettimeofday(&circ->highres_created);
385 circ->package_window = circuit_initial_package_window();
386 circ->deliver_window = CIRCWINDOW_START;
388 circuit_add(circ);
391 /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
392 * and <b>p_conn</b>. Add it to the global circuit list.
394 origin_circuit_t *
395 origin_circuit_new(void)
397 origin_circuit_t *circ;
398 /* never zero, since a global ID of 0 is treated specially by the
399 * controller */
400 static uint32_t n_circuits_allocated = 1;
402 circ = tor_malloc_zero(sizeof(origin_circuit_t));
403 circ->_base.magic = ORIGIN_CIRCUIT_MAGIC;
405 circ->next_stream_id = crypto_rand_int(1<<16);
406 circ->global_identifier = n_circuits_allocated++;
407 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
408 circ->remaining_relay_early_cells -= crypto_rand_int(2);
410 init_circuit_base(TO_CIRCUIT(circ));
412 circ_times.last_circ_at = approx_time();
414 return circ;
417 /** Allocate a new or_circuit_t, connected to <b>p_conn</b> as
418 * <b>p_circ_id</b>. If <b>p_conn</b> is NULL, the circuit is unattached. */
419 or_circuit_t *
420 or_circuit_new(circid_t p_circ_id, or_connection_t *p_conn)
422 /* CircIDs */
423 or_circuit_t *circ;
425 circ = tor_malloc_zero(sizeof(or_circuit_t));
426 circ->_base.magic = OR_CIRCUIT_MAGIC;
428 if (p_conn)
429 circuit_set_p_circid_orconn(circ, p_circ_id, p_conn);
431 circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
433 init_circuit_base(TO_CIRCUIT(circ));
435 return circ;
438 /** Deallocate space associated with circ.
440 static void
441 circuit_free(circuit_t *circ)
443 void *mem;
444 size_t memlen;
445 if (!circ)
446 return;
448 if (CIRCUIT_IS_ORIGIN(circ)) {
449 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
450 mem = ocirc;
451 memlen = sizeof(origin_circuit_t);
452 tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
453 if (ocirc->build_state) {
454 extend_info_free(ocirc->build_state->chosen_exit);
455 circuit_free_cpath_node(ocirc->build_state->pending_final_cpath);
457 tor_free(ocirc->build_state);
459 circuit_free_cpath(ocirc->cpath);
461 crypto_free_pk_env(ocirc->intro_key);
462 rend_data_free(ocirc->rend_data);
463 } else {
464 or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
465 /* Remember cell statistics for this circuit before deallocating. */
466 if (get_options()->CellStatistics)
467 rep_hist_buffer_stats_add_circ(circ, time(NULL));
468 mem = ocirc;
469 memlen = sizeof(or_circuit_t);
470 tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
472 crypto_free_cipher_env(ocirc->p_crypto);
473 crypto_free_digest_env(ocirc->p_digest);
474 crypto_free_cipher_env(ocirc->n_crypto);
475 crypto_free_digest_env(ocirc->n_digest);
477 if (ocirc->rend_splice) {
478 or_circuit_t *other = ocirc->rend_splice;
479 tor_assert(other->_base.magic == OR_CIRCUIT_MAGIC);
480 other->rend_splice = NULL;
483 /* remove from map. */
484 circuit_set_p_circid_orconn(ocirc, 0, NULL);
486 /* Clear cell queue _after_ removing it from the map. Otherwise our
487 * "active" checks will be violated. */
488 cell_queue_clear(&ocirc->p_conn_cells);
491 extend_info_free(circ->n_hop);
492 tor_free(circ->n_conn_onionskin);
494 /* Remove from map. */
495 circuit_set_n_circid_orconn(circ, 0, NULL);
497 /* Clear cell queue _after_ removing it from the map. Otherwise our
498 * "active" checks will be violated. */
499 cell_queue_clear(&circ->n_conn_cells);
501 memset(mem, 0xAA, memlen); /* poison memory */
502 tor_free(mem);
505 /** Deallocate space associated with the linked list <b>cpath</b>. */
506 static void
507 circuit_free_cpath(crypt_path_t *cpath)
509 crypt_path_t *victim, *head=cpath;
511 if (!cpath)
512 return;
514 /* it's a doubly linked list, so we have to notice when we've
515 * gone through it once. */
516 while (cpath->next && cpath->next != head) {
517 victim = cpath;
518 cpath = victim->next;
519 circuit_free_cpath_node(victim);
522 circuit_free_cpath_node(cpath);
525 /** Release all storage held by circuits. */
526 void
527 circuit_free_all(void)
529 circuit_t *next;
530 while (global_circuitlist) {
531 next = global_circuitlist->next;
532 if (! CIRCUIT_IS_ORIGIN(global_circuitlist)) {
533 or_circuit_t *or_circ = TO_OR_CIRCUIT(global_circuitlist);
534 while (or_circ->resolving_streams) {
535 edge_connection_t *next_conn;
536 next_conn = or_circ->resolving_streams->next_stream;
537 connection_free(TO_CONN(or_circ->resolving_streams));
538 or_circ->resolving_streams = next_conn;
541 circuit_free(global_circuitlist);
542 global_circuitlist = next;
545 smartlist_free(circuits_pending_or_conns);
546 circuits_pending_or_conns = NULL;
548 HT_CLEAR(orconn_circid_map, &orconn_circid_circuit_map);
551 /** Deallocate space associated with the cpath node <b>victim</b>. */
552 static void
553 circuit_free_cpath_node(crypt_path_t *victim)
555 if (!victim)
556 return;
558 crypto_free_cipher_env(victim->f_crypto);
559 crypto_free_cipher_env(victim->b_crypto);
560 crypto_free_digest_env(victim->f_digest);
561 crypto_free_digest_env(victim->b_digest);
562 crypto_dh_free(victim->dh_handshake_state);
563 extend_info_free(victim->extend_info);
565 memset(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
566 tor_free(victim);
569 /** A helper function for circuit_dump_by_conn() below. Log a bunch
570 * of information about circuit <b>circ</b>.
572 static void
573 circuit_dump_details(int severity, circuit_t *circ, int conn_array_index,
574 const char *type, int this_circid, int other_circid)
576 log(severity, LD_CIRC, "Conn %d has %s circuit: circID %d (other side %d), "
577 "state %d (%s), born %d:",
578 conn_array_index, type, this_circid, other_circid, circ->state,
579 circuit_state_to_string(circ->state), (int)circ->timestamp_created);
580 if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
581 circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
585 /** Log, at severity <b>severity</b>, information about each circuit
586 * that is connected to <b>conn</b>.
588 void
589 circuit_dump_by_conn(connection_t *conn, int severity)
591 circuit_t *circ;
592 edge_connection_t *tmpconn;
594 for (circ=global_circuitlist;circ;circ = circ->next) {
595 circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
596 if (circ->marked_for_close)
597 continue;
599 if (! CIRCUIT_IS_ORIGIN(circ))
600 p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
602 if (! CIRCUIT_IS_ORIGIN(circ) && TO_OR_CIRCUIT(circ)->p_conn &&
603 TO_CONN(TO_OR_CIRCUIT(circ)->p_conn) == conn)
604 circuit_dump_details(severity, circ, conn->conn_array_index, "App-ward",
605 p_circ_id, n_circ_id);
606 if (CIRCUIT_IS_ORIGIN(circ)) {
607 for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
608 tmpconn=tmpconn->next_stream) {
609 if (TO_CONN(tmpconn) == conn) {
610 circuit_dump_details(severity, circ, conn->conn_array_index,
611 "App-ward", p_circ_id, n_circ_id);
615 if (circ->n_conn && TO_CONN(circ->n_conn) == conn)
616 circuit_dump_details(severity, circ, conn->conn_array_index, "Exit-ward",
617 n_circ_id, p_circ_id);
618 if (! CIRCUIT_IS_ORIGIN(circ)) {
619 for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
620 tmpconn=tmpconn->next_stream) {
621 if (TO_CONN(tmpconn) == conn) {
622 circuit_dump_details(severity, circ, conn->conn_array_index,
623 "Exit-ward", n_circ_id, p_circ_id);
627 if (!circ->n_conn && circ->n_hop &&
628 tor_addr_eq(&circ->n_hop->addr, &conn->addr) &&
629 circ->n_hop->port == conn->port &&
630 conn->type == CONN_TYPE_OR &&
631 !memcmp(TO_OR_CONN(conn)->identity_digest,
632 circ->n_hop->identity_digest, DIGEST_LEN)) {
633 circuit_dump_details(severity, circ, conn->conn_array_index,
634 (circ->state == CIRCUIT_STATE_OPEN &&
635 !CIRCUIT_IS_ORIGIN(circ)) ?
636 "Endpoint" : "Pending",
637 n_circ_id, p_circ_id);
642 /** Return the circuit whose global ID is <b>id</b>, or NULL if no
643 * such circuit exists. */
644 origin_circuit_t *
645 circuit_get_by_global_id(uint32_t id)
647 circuit_t *circ;
648 for (circ=global_circuitlist;circ;circ = circ->next) {
649 if (CIRCUIT_IS_ORIGIN(circ) &&
650 TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
651 if (circ->marked_for_close)
652 return NULL;
653 else
654 return TO_ORIGIN_CIRCUIT(circ);
657 return NULL;
660 /** Return a circ such that:
661 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
662 * - circ is attached to <b>conn</b>, either as p_conn or n_conn.
663 * Return NULL if no such circuit exists.
665 static INLINE circuit_t *
666 circuit_get_by_circid_orconn_impl(circid_t circ_id, or_connection_t *conn)
668 orconn_circid_circuit_map_t search;
669 orconn_circid_circuit_map_t *found;
671 if (_last_circid_orconn_ent &&
672 circ_id == _last_circid_orconn_ent->circ_id &&
673 conn == _last_circid_orconn_ent->or_conn) {
674 found = _last_circid_orconn_ent;
675 } else {
676 search.circ_id = circ_id;
677 search.or_conn = conn;
678 found = HT_FIND(orconn_circid_map, &orconn_circid_circuit_map, &search);
679 _last_circid_orconn_ent = found;
681 if (found && found->circuit)
682 return found->circuit;
684 return NULL;
686 /* The rest of this checks for bugs. Disabled by default. */
688 circuit_t *circ;
689 for (circ=global_circuitlist;circ;circ = circ->next) {
690 if (! CIRCUIT_IS_ORIGIN(circ)) {
691 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
692 if (or_circ->p_conn == conn && or_circ->p_circ_id == circ_id) {
693 log_warn(LD_BUG,
694 "circuit matches p_conn, but not in hash table (Bug!)");
695 return circ;
698 if (circ->n_conn == conn && circ->n_circ_id == circ_id) {
699 log_warn(LD_BUG,
700 "circuit matches n_conn, but not in hash table (Bug!)");
701 return circ;
704 return NULL;
708 /** Return a circ such that:
709 * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
710 * - circ is attached to <b>conn</b>, either as p_conn or n_conn.
711 * - circ is not marked for close.
712 * Return NULL if no such circuit exists.
714 circuit_t *
715 circuit_get_by_circid_orconn(circid_t circ_id, or_connection_t *conn)
717 circuit_t *circ = circuit_get_by_circid_orconn_impl(circ_id, conn);
718 if (!circ || circ->marked_for_close)
719 return NULL;
720 else
721 return circ;
724 /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
725 * circuit, marked or not, on <b>conn</b>. */
727 circuit_id_in_use_on_orconn(circid_t circ_id, or_connection_t *conn)
729 return circuit_get_by_circid_orconn_impl(circ_id, conn) != NULL;
732 /** Return the circuit that a given edge connection is using. */
733 circuit_t *
734 circuit_get_by_edge_conn(edge_connection_t *conn)
736 circuit_t *circ;
738 circ = conn->on_circuit;
739 tor_assert(!circ ||
740 (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
741 : circ->magic == OR_CIRCUIT_MAGIC));
743 return circ;
746 /** For each circuit that has <b>conn</b> as n_conn or p_conn, unlink the
747 * circuit from the orconn,circid map, and mark it for close if it hasn't
748 * been marked already.
750 void
751 circuit_unlink_all_from_or_conn(or_connection_t *conn, int reason)
753 circuit_t *circ;
755 connection_or_unlink_all_active_circs(conn);
757 for (circ = global_circuitlist; circ; circ = circ->next) {
758 int mark = 0;
759 if (circ->n_conn == conn) {
760 circuit_set_n_circid_orconn(circ, 0, NULL);
761 mark = 1;
763 if (! CIRCUIT_IS_ORIGIN(circ)) {
764 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
765 if (or_circ->p_conn == conn) {
766 circuit_set_p_circid_orconn(or_circ, 0, NULL);
767 mark = 1;
770 if (mark && !circ->marked_for_close)
771 circuit_mark_for_close(circ, reason);
775 /** Return a circ such that:
776 * - circ-\>rend_data-\>query is equal to <b>rend_query</b>, and
777 * - circ-\>purpose is equal to <b>purpose</b>.
779 * Return NULL if no such circuit exists.
781 origin_circuit_t *
782 circuit_get_by_rend_query_and_purpose(const char *rend_query, uint8_t purpose)
784 circuit_t *circ;
786 tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
788 for (circ = global_circuitlist; circ; circ = circ->next) {
789 if (!circ->marked_for_close &&
790 circ->purpose == purpose) {
791 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
792 if (ocirc->rend_data &&
793 !rend_cmp_service_ids(rend_query,
794 ocirc->rend_data->onion_address))
795 return ocirc;
798 return NULL;
801 /** Return the first circuit originating here in global_circuitlist after
802 * <b>start</b> whose purpose is <b>purpose</b>, and where
803 * <b>digest</b> (if set) matches the rend_pk_digest field. Return NULL if no
804 * circuit is found. If <b>start</b> is NULL, begin at the start of the list.
806 origin_circuit_t *
807 circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
808 const char *digest, uint8_t purpose)
810 circuit_t *circ;
811 tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
812 if (start == NULL)
813 circ = global_circuitlist;
814 else
815 circ = TO_CIRCUIT(start)->next;
817 for ( ; circ; circ = circ->next) {
818 if (circ->marked_for_close)
819 continue;
820 if (circ->purpose != purpose)
821 continue;
822 if (!digest)
823 return TO_ORIGIN_CIRCUIT(circ);
824 else if (TO_ORIGIN_CIRCUIT(circ)->rend_data &&
825 !memcmp(TO_ORIGIN_CIRCUIT(circ)->rend_data->rend_pk_digest,
826 digest, DIGEST_LEN))
827 return TO_ORIGIN_CIRCUIT(circ);
829 return NULL;
832 /** Return the first OR circuit in the global list whose purpose is
833 * <b>purpose</b>, and whose rend_token is the <b>len</b>-byte
834 * <b>token</b>. */
835 static or_circuit_t *
836 circuit_get_by_rend_token_and_purpose(uint8_t purpose, const char *token,
837 size_t len)
839 circuit_t *circ;
840 for (circ = global_circuitlist; circ; circ = circ->next) {
841 if (! circ->marked_for_close &&
842 circ->purpose == purpose &&
843 ! memcmp(TO_OR_CIRCUIT(circ)->rend_token, token, len))
844 return TO_OR_CIRCUIT(circ);
846 return NULL;
849 /** Return the circuit waiting for a rendezvous with the provided cookie.
850 * Return NULL if no such circuit is found.
852 or_circuit_t *
853 circuit_get_rendezvous(const char *cookie)
855 return circuit_get_by_rend_token_and_purpose(
856 CIRCUIT_PURPOSE_REND_POINT_WAITING,
857 cookie, REND_COOKIE_LEN);
860 /** Return the circuit waiting for intro cells of the given digest.
861 * Return NULL if no such circuit is found.
863 or_circuit_t *
864 circuit_get_intro_point(const char *digest)
866 return circuit_get_by_rend_token_and_purpose(
867 CIRCUIT_PURPOSE_INTRO_POINT, digest,
868 DIGEST_LEN);
871 /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
872 * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
873 * flags in <b>flags</b>, and if info is defined, does not already use info
874 * as any of its hops; or NULL if no circuit fits this description.
876 * The <b>purpose</b> argument (currently ignored) refers to the purpose of
877 * the circuit we want to create, not the purpose of the circuit we want to
878 * cannibalize.
880 * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
882 origin_circuit_t *
883 circuit_find_to_cannibalize(uint8_t purpose, extend_info_t *info,
884 int flags)
886 circuit_t *_circ;
887 origin_circuit_t *best=NULL;
888 int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
889 int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
890 int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
892 log_debug(LD_CIRC,
893 "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
894 "capacity %d, internal %d",
895 purpose, need_uptime, need_capacity, internal);
897 for (_circ=global_circuitlist; _circ; _circ = _circ->next) {
898 if (CIRCUIT_IS_ORIGIN(_circ) &&
899 _circ->state == CIRCUIT_STATE_OPEN &&
900 !_circ->marked_for_close &&
901 _circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
902 !_circ->timestamp_dirty) {
903 origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(_circ);
904 if ((!need_uptime || circ->build_state->need_uptime) &&
905 (!need_capacity || circ->build_state->need_capacity) &&
906 (internal == circ->build_state->is_internal) &&
907 circ->remaining_relay_early_cells) {
908 if (info) {
909 /* need to make sure we don't duplicate hops */
910 crypt_path_t *hop = circ->cpath;
911 routerinfo_t *ri1 = router_get_by_digest(info->identity_digest);
912 do {
913 routerinfo_t *ri2;
914 if (!memcmp(hop->extend_info->identity_digest,
915 info->identity_digest, DIGEST_LEN))
916 goto next;
917 if (ri1 &&
918 (ri2 = router_get_by_digest(hop->extend_info->identity_digest))
919 && routers_in_same_family(ri1, ri2))
920 goto next;
921 hop=hop->next;
922 } while (hop!=circ->cpath);
924 if (!best || (best->build_state->need_uptime && !need_uptime))
925 best = circ;
926 next: ;
930 return best;
933 /** Return the number of hops in circuit's path. */
935 circuit_get_cpath_len(origin_circuit_t *circ)
937 int n = 0;
938 if (circ && circ->cpath) {
939 crypt_path_t *cpath, *cpath_next = NULL;
940 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
941 cpath_next = cpath->next;
942 ++n;
945 return n;
948 /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
949 * aren't that many hops in the list. */
950 crypt_path_t *
951 circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
953 if (circ && circ->cpath && hopnum > 0) {
954 crypt_path_t *cpath, *cpath_next = NULL;
955 for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
956 cpath_next = cpath->next;
957 if (--hopnum <= 0)
958 return cpath;
961 return NULL;
964 /** Go through the circuitlist; mark-for-close each circuit that starts
965 * at us but has not yet been used. */
966 void
967 circuit_mark_all_unused_circs(void)
969 circuit_t *circ;
971 for (circ=global_circuitlist; circ; circ = circ->next) {
972 if (CIRCUIT_IS_ORIGIN(circ) &&
973 !circ->marked_for_close &&
974 !circ->timestamp_dirty)
975 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
979 /** Go through the circuitlist; for each circuit that starts at us
980 * and is dirty, frob its timestamp_dirty so we won't use it for any
981 * new streams.
983 * This is useful for letting the user change pseudonyms, so new
984 * streams will not be linkable to old streams.
986 void
987 circuit_expire_all_dirty_circs(void)
989 circuit_t *circ;
990 or_options_t *options = get_options();
992 for (circ=global_circuitlist; circ; circ = circ->next) {
993 if (CIRCUIT_IS_ORIGIN(circ) &&
994 !circ->marked_for_close &&
995 circ->timestamp_dirty)
996 circ->timestamp_dirty -= options->MaxCircuitDirtiness;
1000 /** Mark <b>circ</b> to be closed next time we call
1001 * circuit_close_all_marked(). Do any cleanup needed:
1002 * - If state is onionskin_pending, remove circ from the onion_pending
1003 * list.
1004 * - If circ isn't open yet: call circuit_build_failed() if we're
1005 * the origin, and in either case call circuit_rep_hist_note_result()
1006 * to note stats.
1007 * - If purpose is C_INTRODUCE_ACK_WAIT, remove the intro point we
1008 * just tried from our list of intro points for that service
1009 * descriptor.
1010 * - Send appropriate destroys and edge_destroys for conns and
1011 * streams attached to circ.
1012 * - If circ->rend_splice is set (we are the midpoint of a joined
1013 * rendezvous stream), then mark the other circuit to close as well.
1015 void
1016 _circuit_mark_for_close(circuit_t *circ, int reason, int line,
1017 const char *file)
1019 int orig_reason = reason; /* Passed to the controller */
1020 assert_circuit_ok(circ);
1021 tor_assert(line);
1022 tor_assert(file);
1024 if (circ->marked_for_close) {
1025 log(LOG_WARN,LD_BUG,
1026 "Duplicate call to circuit_mark_for_close at %s:%d"
1027 " (first at %s:%d)", file, line,
1028 circ->marked_for_close_file, circ->marked_for_close);
1029 return;
1031 if (reason == END_CIRC_AT_ORIGIN) {
1032 if (!CIRCUIT_IS_ORIGIN(circ)) {
1033 log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
1034 "but circuit was not at origin. (called %s:%d, purpose=%d)",
1035 file, line, circ->purpose);
1037 reason = END_CIRC_REASON_NONE;
1039 if (CIRCUIT_IS_ORIGIN(circ)) {
1040 /* We don't send reasons when closing circuits at the origin. */
1041 reason = END_CIRC_REASON_NONE;
1044 if (reason & END_CIRC_REASON_FLAG_REMOTE)
1045 reason &= ~END_CIRC_REASON_FLAG_REMOTE;
1047 if (reason < _END_CIRC_REASON_MIN || reason > _END_CIRC_REASON_MAX) {
1048 if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
1049 log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
1050 reason = END_CIRC_REASON_NONE;
1053 if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
1054 onion_pending_remove(TO_OR_CIRCUIT(circ));
1056 /* If the circuit ever became OPEN, we sent it to the reputation history
1057 * module then. If it isn't OPEN, we send it there now to remember which
1058 * links worked and which didn't.
1060 if (circ->state != CIRCUIT_STATE_OPEN) {
1061 if (CIRCUIT_IS_ORIGIN(circ)) {
1062 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1063 circuit_build_failed(ocirc); /* take actions if necessary */
1064 circuit_rep_hist_note_result(ocirc);
1067 if (circ->state == CIRCUIT_STATE_OR_WAIT) {
1068 if (circuits_pending_or_conns)
1069 smartlist_remove(circuits_pending_or_conns, circ);
1071 if (CIRCUIT_IS_ORIGIN(circ)) {
1072 control_event_circuit_status(TO_ORIGIN_CIRCUIT(circ),
1073 (circ->state == CIRCUIT_STATE_OPEN)?CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
1074 orig_reason);
1076 if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
1077 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1078 tor_assert(circ->state == CIRCUIT_STATE_OPEN);
1079 tor_assert(ocirc->build_state->chosen_exit);
1080 tor_assert(ocirc->rend_data);
1081 /* treat this like getting a nack from it */
1082 log_info(LD_REND, "Failed intro circ %s to %s (awaiting ack). "
1083 "Removing from descriptor.",
1084 safe_str(ocirc->rend_data->onion_address),
1085 safe_str(build_state_get_exit_nickname(ocirc->build_state)));
1086 rend_client_remove_intro_point(ocirc->build_state->chosen_exit,
1087 ocirc->rend_data);
1089 if (circ->n_conn)
1090 connection_or_send_destroy(circ->n_circ_id, circ->n_conn, reason);
1092 if (! CIRCUIT_IS_ORIGIN(circ)) {
1093 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1094 edge_connection_t *conn;
1095 for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
1096 connection_edge_destroy(or_circ->p_circ_id, conn);
1097 or_circ->n_streams = NULL;
1099 while (or_circ->resolving_streams) {
1100 conn = or_circ->resolving_streams;
1101 or_circ->resolving_streams = conn->next_stream;
1102 if (!conn->_base.marked_for_close) {
1103 /* The client will see a DESTROY, and infer that the connections
1104 * are closing because the circuit is getting torn down. No need
1105 * to send an end cell. */
1106 conn->edge_has_sent_end = 1;
1107 conn->end_reason = END_STREAM_REASON_DESTROY;
1108 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
1109 connection_mark_for_close(TO_CONN(conn));
1111 conn->on_circuit = NULL;
1114 if (or_circ->p_conn)
1115 connection_or_send_destroy(or_circ->p_circ_id, or_circ->p_conn, reason);
1116 } else {
1117 origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
1118 edge_connection_t *conn;
1119 for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
1120 connection_edge_destroy(circ->n_circ_id, conn);
1121 ocirc->p_streams = NULL;
1124 circ->marked_for_close = line;
1125 circ->marked_for_close_file = file;
1127 if (!CIRCUIT_IS_ORIGIN(circ)) {
1128 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
1129 if (or_circ->rend_splice) {
1130 if (!or_circ->rend_splice->_base.marked_for_close) {
1131 /* do this after marking this circuit, to avoid infinite recursion. */
1132 circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
1134 or_circ->rend_splice = NULL;
1139 /** Verify that cpath layer <b>cp</b> has all of its invariants
1140 * correct. Trigger an assert if anything is invalid.
1142 void
1143 assert_cpath_layer_ok(const crypt_path_t *cp)
1145 // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
1146 // tor_assert(cp->port);
1147 tor_assert(cp);
1148 tor_assert(cp->magic == CRYPT_PATH_MAGIC);
1149 switch (cp->state)
1151 case CPATH_STATE_OPEN:
1152 tor_assert(cp->f_crypto);
1153 tor_assert(cp->b_crypto);
1154 /* fall through */
1155 case CPATH_STATE_CLOSED:
1156 tor_assert(!cp->dh_handshake_state);
1157 break;
1158 case CPATH_STATE_AWAITING_KEYS:
1159 /* tor_assert(cp->dh_handshake_state); */
1160 break;
1161 default:
1162 log_fn(LOG_ERR, LD_BUG, "Unexpected state %d", cp->state);
1163 tor_assert(0);
1165 tor_assert(cp->package_window >= 0);
1166 tor_assert(cp->deliver_window >= 0);
1169 /** Verify that cpath <b>cp</b> has all of its invariants
1170 * correct. Trigger an assert if anything is invalid.
1172 static void
1173 assert_cpath_ok(const crypt_path_t *cp)
1175 const crypt_path_t *start = cp;
1177 do {
1178 assert_cpath_layer_ok(cp);
1179 /* layers must be in sequence of: "open* awaiting? closed*" */
1180 if (cp != start) {
1181 if (cp->state == CPATH_STATE_AWAITING_KEYS) {
1182 tor_assert(cp->prev->state == CPATH_STATE_OPEN);
1183 } else if (cp->state == CPATH_STATE_OPEN) {
1184 tor_assert(cp->prev->state == CPATH_STATE_OPEN);
1187 cp = cp->next;
1188 tor_assert(cp);
1189 } while (cp != start);
1192 /** Verify that circuit <b>c</b> has all of its invariants
1193 * correct. Trigger an assert if anything is invalid.
1195 void
1196 assert_circuit_ok(const circuit_t *c)
1198 edge_connection_t *conn;
1199 const or_circuit_t *or_circ = NULL;
1200 const origin_circuit_t *origin_circ = NULL;
1202 tor_assert(c);
1203 tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
1204 tor_assert(c->purpose >= _CIRCUIT_PURPOSE_MIN &&
1205 c->purpose <= _CIRCUIT_PURPOSE_MAX);
1208 /* Having a separate variable for this pleases GCC 4.2 in ways I hope I
1209 * never understand. -NM. */
1210 circuit_t *nonconst_circ = (circuit_t*) c;
1211 if (CIRCUIT_IS_ORIGIN(c))
1212 origin_circ = TO_ORIGIN_CIRCUIT(nonconst_circ);
1213 else
1214 or_circ = TO_OR_CIRCUIT(nonconst_circ);
1217 if (c->n_conn) {
1218 tor_assert(!c->n_hop);
1220 if (c->n_circ_id) {
1221 /* We use the _impl variant here to make sure we don't fail on marked
1222 * circuits, which would not be returned by the regular function. */
1223 circuit_t *c2 = circuit_get_by_circid_orconn_impl(c->n_circ_id,
1224 c->n_conn);
1225 tor_assert(c == c2);
1228 if (or_circ && or_circ->p_conn) {
1229 if (or_circ->p_circ_id) {
1230 /* ibid */
1231 circuit_t *c2 = circuit_get_by_circid_orconn_impl(or_circ->p_circ_id,
1232 or_circ->p_conn);
1233 tor_assert(c == c2);
1236 #if 0 /* false now that rendezvous exits are attached to p_streams */
1237 if (origin_circ)
1238 for (conn = origin_circ->p_streams; conn; conn = conn->next_stream)
1239 tor_assert(conn->_base.type == CONN_TYPE_AP);
1240 #endif
1241 if (or_circ)
1242 for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
1243 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
1245 tor_assert(c->deliver_window >= 0);
1246 tor_assert(c->package_window >= 0);
1247 if (c->state == CIRCUIT_STATE_OPEN) {
1248 tor_assert(!c->n_conn_onionskin);
1249 if (or_circ) {
1250 tor_assert(or_circ->n_crypto);
1251 tor_assert(or_circ->p_crypto);
1252 tor_assert(or_circ->n_digest);
1253 tor_assert(or_circ->p_digest);
1256 if (c->state == CIRCUIT_STATE_OR_WAIT && !c->marked_for_close) {
1257 tor_assert(circuits_pending_or_conns &&
1258 smartlist_isin(circuits_pending_or_conns, c));
1259 } else {
1260 tor_assert(!circuits_pending_or_conns ||
1261 !smartlist_isin(circuits_pending_or_conns, c));
1263 if (origin_circ && origin_circ->cpath) {
1264 assert_cpath_ok(origin_circ->cpath);
1266 if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
1267 tor_assert(or_circ);
1268 if (!c->marked_for_close) {
1269 tor_assert(or_circ->rend_splice);
1270 tor_assert(or_circ->rend_splice->rend_splice == or_circ);
1272 tor_assert(or_circ->rend_splice != or_circ);
1273 } else {
1274 tor_assert(!or_circ || !or_circ->rend_splice);