Nth time is the charm on list manip.
[tor.git] / src / or / circuit.c
blob11eb7a6944b01cae4fcf8559ebb62e2771df24c5
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 #include "or.h"
7 extern or_options_t options; /* command-line and config-file options */
9 static int relay_crypt(circuit_t *circ, cell_t *cell, char cell_direction,
10 crypt_path_t **layer_hint, char *recognized);
11 static connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction);
12 static void circuit_free_cpath_node(crypt_path_t *victim);
13 static uint16_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type);
15 unsigned long stats_n_relay_cells_relayed = 0;
16 unsigned long stats_n_relay_cells_delivered = 0;
18 /********* START VARIABLES **********/
20 static circuit_t *global_circuitlist=NULL;
21 char *circuit_state_to_string[] = {
22 "doing handshakes", /* 0 */
23 "processing the onion", /* 1 */
24 "connecting to firsthop", /* 2 */
25 "open" /* 3 */
28 /********* END VARIABLES ************/
30 void circuit_add(circuit_t *circ) {
31 if(!global_circuitlist) { /* first one */
32 global_circuitlist = circ;
33 circ->next = NULL;
34 } else {
35 circ->next = global_circuitlist;
36 global_circuitlist = circ;
40 void circuit_remove(circuit_t *circ) {
41 circuit_t *tmpcirc;
43 assert(circ && global_circuitlist);
45 if(global_circuitlist == circ) {
46 global_circuitlist = global_circuitlist->next;
47 return;
50 for(tmpcirc = global_circuitlist;tmpcirc->next;tmpcirc = tmpcirc->next) {
51 if(tmpcirc->next == circ) {
52 tmpcirc->next = circ->next;
53 return;
58 void circuit_close_all_marked()
60 circuit_t *tmp,*m;
62 while (global_circuitlist && global_circuitlist->marked_for_close) {
63 tmp = global_circuitlist->next;
64 circuit_free(global_circuitlist);
65 global_circuitlist = tmp;
68 tmp = global_circuitlist;
69 while (tmp && tmp->next) {
70 if (tmp->next->marked_for_close) {
71 m = tmp->next->next;
72 circuit_free(tmp->next);
73 tmp->next = m;
74 /* Need to check new tmp->next; don't advance tmp. */
75 } else {
76 /* Advance tmp. */
77 tmp = tmp->next;
83 circuit_t *circuit_new(uint16_t p_circ_id, connection_t *p_conn) {
84 circuit_t *circ;
86 circ = tor_malloc_zero(sizeof(circuit_t));
87 circ->magic = CIRCUIT_MAGIC;
89 circ->timestamp_created = time(NULL);
91 circ->p_circ_id = p_circ_id;
92 circ->p_conn = p_conn;
94 circ->state = CIRCUIT_STATE_ONIONSKIN_PENDING;
96 /* CircIDs */
97 circ->p_circ_id = p_circ_id;
98 /* circ->n_circ_id remains 0 because we haven't identified the next hop yet */
100 circ->package_window = CIRCWINDOW_START;
101 circ->deliver_window = CIRCWINDOW_START;
103 circ->next_stream_id = crypto_pseudo_rand_int(1<<16);
105 circuit_add(circ);
107 return circ;
110 void circuit_free(circuit_t *circ) {
111 assert(circ);
112 assert(circ->magic == CIRCUIT_MAGIC);
113 if (circ->n_crypto)
114 crypto_free_cipher_env(circ->n_crypto);
115 if (circ->p_crypto)
116 crypto_free_cipher_env(circ->p_crypto);
117 if (circ->n_digest)
118 crypto_free_digest_env(circ->n_digest);
119 if (circ->p_digest)
120 crypto_free_digest_env(circ->p_digest);
121 if(circ->build_state)
122 tor_free(circ->build_state->chosen_exit);
123 tor_free(circ->build_state);
124 circuit_free_cpath(circ->cpath);
125 memset(circ, 0xAA, sizeof(circuit_t)); /* poison memory */
126 free(circ);
129 void circuit_free_cpath(crypt_path_t *cpath) {
130 crypt_path_t *victim, *head=cpath;
132 if(!cpath)
133 return;
135 /* it's a doubly linked list, so we have to notice when we've
136 * gone through it once. */
137 while(cpath->next && cpath->next != head) {
138 victim = cpath;
139 cpath = victim->next;
140 circuit_free_cpath_node(victim);
143 circuit_free_cpath_node(cpath);
146 static void circuit_free_cpath_node(crypt_path_t *victim) {
147 if(victim->f_crypto)
148 crypto_free_cipher_env(victim->f_crypto);
149 if(victim->b_crypto)
150 crypto_free_cipher_env(victim->b_crypto);
151 if(victim->f_digest)
152 crypto_free_digest_env(victim->f_digest);
153 if(victim->b_digest)
154 crypto_free_digest_env(victim->b_digest);
155 if(victim->handshake_state)
156 crypto_dh_free(victim->handshake_state);
157 free(victim);
160 /* return 0 if can't get a unique circ_id. */
161 static uint16_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type) {
162 uint16_t test_circ_id;
163 int attempts=0;
164 uint16_t high_bit;
166 assert(conn && conn->type == CONN_TYPE_OR);
167 high_bit = (circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
168 do {
169 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
170 * circID such that (high_bit|test_circ_id) is not already used. */
171 test_circ_id = conn->next_circ_id++;
172 if (test_circ_id == 0 || test_circ_id >= 1<<15) {
173 test_circ_id = 1;
174 conn->next_circ_id = 2;
176 if(++attempts > 1<<15) {
177 /* Make sure we don't loop forever if all circ_id's are used. This
178 * matters because it's an external DoS vulnerability.
180 log_fn(LOG_WARN,"No unused circ IDs. Failing.");
181 return 0;
183 test_circ_id |= high_bit;
184 } while(circuit_get_by_circ_id_conn(test_circ_id, conn));
185 return test_circ_id;
188 circuit_t *circuit_get_by_circ_id_conn(uint16_t circ_id, connection_t *conn) {
189 circuit_t *circ;
190 connection_t *tmpconn;
192 for(circ=global_circuitlist;circ;circ = circ->next) {
193 if (circ->marked_for_close)
194 continue;
196 if(circ->p_circ_id == circ_id) {
197 if(circ->p_conn == conn)
198 return circ;
199 for(tmpconn = circ->p_streams; tmpconn; tmpconn = tmpconn->next_stream) {
200 if(tmpconn == conn)
201 return circ;
204 if(circ->n_circ_id == circ_id) {
205 if(circ->n_conn == conn)
206 return circ;
207 for(tmpconn = circ->n_streams; tmpconn; tmpconn = tmpconn->next_stream) {
208 if(tmpconn == conn)
209 return circ;
213 return NULL;
216 circuit_t *circuit_get_by_conn(connection_t *conn) {
217 circuit_t *circ;
218 connection_t *tmpconn;
220 for(circ=global_circuitlist;circ;circ = circ->next) {
221 if (circ->marked_for_close)
222 continue;
224 if(circ->p_conn == conn)
225 return circ;
226 if(circ->n_conn == conn)
227 return circ;
228 for(tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
229 if(tmpconn == conn)
230 return circ;
231 for(tmpconn = circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream)
232 if(tmpconn == conn)
233 return circ;
235 return NULL;
238 /* Find the newest circ that conn can use, preferably one which is
239 * dirty. Circ must not be too old.
240 * If !conn, return newest.
242 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
244 circuit_t *circuit_get_newest(connection_t *conn, int must_be_open) {
245 circuit_t *circ, *newest=NULL, *leastdirty=NULL;
246 routerinfo_t *exitrouter;
248 for(circ=global_circuitlist;circ;circ = circ->next) {
249 if(!circ->cpath)
250 continue; /* this circ doesn't start at us */
251 if(must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
252 continue; /* ignore non-open circs */
253 if (circ->marked_for_close)
254 continue;
255 if(conn) {
256 if(circ->state == CIRCUIT_STATE_OPEN && circ->n_conn) /* open */
257 exitrouter = router_get_by_addr_port(circ->cpath->prev->addr, circ->cpath->prev->port);
258 else /* not open */
259 exitrouter = router_get_by_nickname(circ->build_state->chosen_exit);
260 if(!exitrouter || connection_ap_can_use_exit(conn, exitrouter) == ADDR_POLICY_REJECTED) {
261 /* can't exit from this router */
262 continue;
265 if(!newest || newest->timestamp_created < circ->timestamp_created) {
266 newest = circ;
268 if(conn && circ->timestamp_dirty &&
269 (!leastdirty || leastdirty->timestamp_dirty < circ->timestamp_dirty)) {
270 leastdirty = circ;
274 if(leastdirty &&
275 leastdirty->timestamp_dirty+options.NewCircuitPeriod > time(NULL)) {
276 /* log_fn(LOG_DEBUG,"Choosing in-use circuit %s:%d:%d.",
277 leastdirty->n_conn->address, leastdirty->n_port, leastdirty->n_circ_id); */
278 return leastdirty;
280 if(newest) {
281 /* log_fn(LOG_DEBUG,"Choosing circuit %s:%d:%d.",
282 newest->n_conn->address, newest->n_port, newest->n_circ_id); */
283 return newest;
285 return NULL;
288 #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 10
289 /* circuits that were born at the end of their second might be expired
290 * after 10.1 seconds; circuits born at the beginning might be expired
291 * after closer to 11 seconds.
294 /* close all circuits that start at us, aren't open, and were born
295 * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago */
296 void circuit_expire_building(void) {
297 int now = time(NULL);
298 circuit_t *victim, *circ = global_circuitlist;
300 while(circ) {
301 victim = circ;
302 circ = circ->next;
303 if(victim->cpath &&
304 victim->state != CIRCUIT_STATE_OPEN &&
305 victim->timestamp_created + MIN_SECONDS_BEFORE_EXPIRING_CIRC+1 < now &&
306 !victim->marked_for_close) {
307 if(victim->n_conn)
308 log_fn(LOG_INFO,"Abandoning circ %s:%d:%d (state %d:%s)",
309 victim->n_conn->address, victim->n_port, victim->n_circ_id,
310 victim->state, circuit_state_to_string[victim->state]);
311 else
312 log_fn(LOG_INFO,"Abandoning circ %d (state %d:%s)", victim->n_circ_id,
313 victim->state, circuit_state_to_string[victim->state]);
314 circuit_log_path(LOG_INFO,victim);
315 circuit_mark_for_close(victim);
320 /* count the number of circs starting at us that aren't open */
321 int circuit_count_building(void) {
322 circuit_t *circ;
323 int num=0;
325 for(circ=global_circuitlist;circ;circ = circ->next) {
326 if(circ->cpath
327 && circ->state != CIRCUIT_STATE_OPEN
328 && !circ->marked_for_close)
329 num++;
331 return num;
334 #define MIN_CIRCUITS_HANDLING_STREAM 2
335 /* return 1 if at least MIN_CIRCUITS_HANDLING_STREAM non-open circuits
336 * will have an acceptable exit node for conn. Else return 0.
338 int circuit_stream_is_being_handled(connection_t *conn) {
339 circuit_t *circ;
340 routerinfo_t *exitrouter;
341 int num=0;
343 for(circ=global_circuitlist;circ;circ = circ->next) {
344 if(circ->cpath && circ->state != CIRCUIT_STATE_OPEN &&
345 !circ->marked_for_close) {
346 exitrouter = router_get_by_nickname(circ->build_state->chosen_exit);
347 if(exitrouter && connection_ap_can_use_exit(conn, exitrouter) != ADDR_POLICY_REJECTED)
348 if(++num >= MIN_CIRCUITS_HANDLING_STREAM)
349 return 1;
352 return 0;
355 /* update digest from the payload of cell. assign integrity part to cell. */
356 static void relay_set_digest(crypto_digest_env_t *digest, cell_t *cell) {
357 char integrity[4];
358 relay_header_t rh;
360 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
361 crypto_digest_get_digest(digest, integrity, 4);
362 // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
363 // integrity[0], integrity[1], integrity[2], integrity[3]);
364 relay_header_unpack(&rh, cell->payload);
365 memcpy(rh.integrity, integrity, 4);
366 relay_header_pack(cell->payload, &rh);
369 /* update digest from the payload of cell (with the integrity part set
370 * to 0). If the integrity part is valid return 1, else restore digest
371 * and cell to their original state and return 0.
373 static int relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell) {
374 char received_integrity[4], calculated_integrity[4];
375 relay_header_t rh;
376 crypto_digest_env_t *backup_digest=NULL;
378 backup_digest = crypto_digest_dup(digest);
380 relay_header_unpack(&rh, cell->payload);
381 memcpy(received_integrity, rh.integrity, 4);
382 memset(rh.integrity, 0, 4);
383 relay_header_pack(cell->payload, &rh);
385 // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
386 // received_integrity[0], received_integrity[1],
387 // received_integrity[2], received_integrity[3]);
389 crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
390 crypto_digest_get_digest(digest, calculated_integrity, 4);
392 if(memcmp(received_integrity, calculated_integrity, 4)) {
393 // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
394 // (%d vs %d).", received_integrity, calculated_integrity);
395 /* restore digest to its old form */
396 crypto_digest_assign(digest, backup_digest);
397 /* restore the relay header */
398 memcpy(rh.integrity, received_integrity, 4);
399 relay_header_pack(cell->payload, &rh);
400 crypto_free_digest_env(backup_digest);
401 return 0;
403 crypto_free_digest_env(backup_digest);
404 return 1;
407 static int relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
408 int encrypt_mode) {
409 char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
410 relay_header_t rh;
412 relay_header_unpack(&rh, in);
413 // log_fn(LOG_DEBUG,"before crypt: %d",rh.recognized);
414 if(( encrypt_mode && crypto_cipher_encrypt(cipher, in, CELL_PAYLOAD_SIZE, out)) ||
415 (!encrypt_mode && crypto_cipher_decrypt(cipher, in, CELL_PAYLOAD_SIZE, out))) {
416 log_fn(LOG_WARN,"Error during crypt: %s", crypto_perror());
417 return -1;
419 memcpy(in,out,CELL_PAYLOAD_SIZE);
420 relay_header_unpack(&rh, in);
421 // log_fn(LOG_DEBUG,"after crypt: %d",rh.recognized);
422 return 0;
426 receive a relay cell:
427 - crypt it (encrypt APward, decrypt at AP, decrypt exitward)
428 - check if recognized (if exitward)
429 - if recognized, check digest, find right conn, deliver to edge.
430 - else connection_or_write_cell_to_buf to the right conn
432 int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
433 int cell_direction) {
434 connection_t *conn=NULL;
435 crypt_path_t *layer_hint=NULL;
436 char recognized=0;
438 assert(cell && circ);
439 assert(cell_direction == CELL_DIRECTION_OUT || cell_direction == CELL_DIRECTION_IN);
440 if (circ->marked_for_close)
441 return 0;
443 if(relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
444 log_fn(LOG_WARN,"relay crypt failed. Dropping connection.");
445 return -1;
448 if(recognized) {
449 conn = relay_lookup_conn(circ, cell, cell_direction);
450 if(cell_direction == CELL_DIRECTION_OUT) {
451 ++stats_n_relay_cells_delivered;
452 log_fn(LOG_DEBUG,"Sending to exit.");
453 if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_EXIT, NULL) < 0) {
454 log_fn(LOG_WARN,"connection_edge_process_relay_cell (at exit) failed.");
455 return -1;
458 if(cell_direction == CELL_DIRECTION_IN) {
459 ++stats_n_relay_cells_delivered;
460 log_fn(LOG_DEBUG,"Sending to AP.");
461 if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_AP, layer_hint) < 0) {
462 log_fn(LOG_WARN,"connection_edge_process_relay_cell (at AP) failed.");
463 return -1;
466 return 0;
469 /* not recognized. pass it on. */
470 if(cell_direction == CELL_DIRECTION_OUT) {
471 cell->circ_id = circ->n_circ_id; /* switch it */
472 conn = circ->n_conn;
473 } else {
474 cell->circ_id = circ->p_circ_id; /* switch it */
475 conn = circ->p_conn;
478 if(!conn) {
479 log_fn(LOG_WARN,"Didn't recognize cell, but circ stops here! Closing circ.");
480 return -1;
483 log_fn(LOG_DEBUG,"Passing on unrecognized cell.");
484 ++stats_n_relay_cells_relayed;
485 connection_or_write_cell_to_buf(cell, conn);
486 return 0;
489 /* wrap this into receive_relay_cell one day */
490 static int relay_crypt(circuit_t *circ, cell_t *cell, char cell_direction,
491 crypt_path_t **layer_hint, char *recognized) {
492 crypt_path_t *thishop;
493 relay_header_t rh;
495 assert(circ && cell && recognized);
496 assert(cell_direction == CELL_DIRECTION_IN || cell_direction == CELL_DIRECTION_OUT);
498 if(cell_direction == CELL_DIRECTION_IN) {
499 if(circ->cpath) { /* we're at the beginning of the circuit.
500 We'll want to do layered crypts. */
501 thishop = circ->cpath;
502 if(thishop->state != CPATH_STATE_OPEN) {
503 log_fn(LOG_WARN,"Relay cell before first created cell? Closing.");
504 return -1;
506 do { /* Remember: cpath is in forward order, that is, first hop first. */
507 assert(thishop);
509 if(relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
510 return -1;
512 relay_header_unpack(&rh, cell->payload);
513 if(rh.recognized == 0) {
514 /* it's possibly recognized. have to check digest to be sure. */
515 if(relay_digest_matches(thishop->b_digest, cell)) {
516 *recognized = 1;
517 *layer_hint = thishop;
518 return 0;
522 thishop = thishop->next;
523 } while(thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
524 log_fn(LOG_WARN,"in-cell at OP not recognized. Closing.");
525 return -1;
526 } else { /* we're in the middle. Just one crypt. */
527 if(relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
528 return -1;
529 // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
531 } else /* cell_direction == CELL_DIRECTION_OUT */ {
532 /* we're in the middle. Just one crypt. */
534 if(relay_crypt_one_payload(circ->n_crypto, cell->payload, 0) < 0)
535 return -1;
537 relay_header_unpack(&rh, cell->payload);
538 if (rh.recognized == 0) {
539 /* it's possibly recognized. have to check digest to be sure. */
540 if(relay_digest_matches(circ->n_digest, cell)) {
541 *recognized = 1;
542 return 0;
546 return 0;
550 package a relay cell:
551 1) encrypt it to the right conn
552 2) connection_or_write_cell_to_buf to the right conn
555 circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
556 int cell_direction,
557 crypt_path_t *layer_hint)
559 connection_t *conn; /* where to send the cell */
560 crypt_path_t *thishop; /* counter for repeated crypts */
562 if(cell_direction == CELL_DIRECTION_OUT) {
563 conn = circ->n_conn;
564 if(!conn) {
565 log_fn(LOG_WARN,"outgoing relay cell has n_conn==NULL. Dropping.");
566 return 0; /* just drop it */
568 relay_set_digest(layer_hint->f_digest, cell);
570 thishop = layer_hint;
571 /* moving from farthest to nearest hop */
572 do {
573 assert(thishop);
575 log_fn(LOG_DEBUG,"crypting a layer of the relay cell.");
576 if(relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
577 return -1;
580 thishop = thishop->prev;
581 } while (thishop != circ->cpath->prev);
583 } else { /* incoming cell */
584 conn = circ->p_conn;
585 if(!conn) {
586 log_fn(LOG_WARN,"incoming relay cell has p_conn==NULL. Dropping.");
587 return 0; /* just drop it */
589 relay_set_digest(circ->p_digest, cell);
590 if(relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
591 return -1;
593 ++stats_n_relay_cells_relayed;
594 connection_or_write_cell_to_buf(cell, conn);
595 return 0;
598 static connection_t *
599 relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction)
601 connection_t *tmpconn;
602 relay_header_t rh;
604 relay_header_unpack(&rh, cell->payload);
606 if(!rh.stream_id)
607 return NULL;
609 if(cell_direction == CELL_DIRECTION_OUT)
610 tmpconn = circ->n_streams;
611 else
612 tmpconn = circ->p_streams;
614 for( ; tmpconn; tmpconn=tmpconn->next_stream) {
615 if(rh.stream_id == tmpconn->stream_id) {
616 log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
617 return tmpconn;
619 // log_fn(LOG_DEBUG,"considered stream %d, not it.",tmpconn->stream_id);
621 return NULL; /* probably a begin relay cell */
624 void circuit_resume_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
625 connection_t *conn;
627 assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
629 log_fn(LOG_DEBUG,"resuming");
631 if(edge_type == EDGE_EXIT)
632 conn = circ->n_streams;
633 else
634 conn = circ->p_streams;
636 for( ; conn; conn=conn->next_stream) {
637 if((edge_type == EDGE_EXIT && conn->package_window > 0) ||
638 (edge_type == EDGE_AP && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
639 connection_start_reading(conn);
640 connection_edge_package_raw_inbuf(conn); /* handle whatever might still be on the inbuf */
642 /* If the circuit won't accept any more data, return without looking
643 * at any more of the streams. Any connections that should be stopped
644 * have already been stopped by connection_edge_package_raw_inbuf. */
645 if(circuit_consider_stop_edge_reading(circ, edge_type, layer_hint))
646 return;
651 /* returns 1 if the window is empty, else 0. If it's empty, tell edge conns to stop reading. */
652 int circuit_consider_stop_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
653 connection_t *conn = NULL;
655 assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
656 assert(edge_type == EDGE_EXIT || layer_hint);
658 log_fn(LOG_DEBUG,"considering");
659 if(edge_type == EDGE_EXIT && circ->package_window <= 0)
660 conn = circ->n_streams;
661 else if(edge_type == EDGE_AP && layer_hint->package_window <= 0)
662 conn = circ->p_streams;
663 else
664 return 0;
666 for( ; conn; conn=conn->next_stream)
667 if(!layer_hint || conn->cpath_layer == layer_hint)
668 connection_stop_reading(conn);
670 log_fn(LOG_DEBUG,"yes. stopped.");
671 return 1;
674 void circuit_consider_sending_sendme(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
675 while((edge_type == EDGE_AP ? layer_hint->deliver_window : circ->deliver_window) <
676 CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
677 log_fn(LOG_DEBUG,"Queueing circuit sendme.");
678 if(edge_type == EDGE_AP)
679 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
680 else
681 circ->deliver_window += CIRCWINDOW_INCREMENT;
682 if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
683 NULL, 0, layer_hint) < 0) {
684 log_fn(LOG_WARN,"connection_edge_send_command failed. Circuit's closed.");
685 return; /* the circuit's closed, don't continue */
690 int _circuit_mark_for_close(circuit_t *circ) {
691 connection_t *conn;
693 assert_circuit_ok(circ);
694 if (circ->marked_for_close < 0)
695 return -1;
697 if(circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
698 onion_pending_remove(circ);
701 if(circ->n_conn)
702 connection_send_destroy(circ->n_circ_id, circ->n_conn);
703 for(conn=circ->n_streams; conn; conn=conn->next_stream) {
704 connection_edge_destroy(circ->n_circ_id, conn);
706 if(circ->p_conn)
707 connection_send_destroy(circ->n_circ_id, circ->p_conn);
708 for(conn=circ->p_streams; conn; conn=conn->next_stream) {
709 connection_edge_destroy(circ->p_circ_id, conn);
711 if (circ->state == CIRCUIT_STATE_BUILDING ||
712 circ->state == CIRCUIT_STATE_OR_WAIT) {
713 /* If we never built the circuit, note it as a failure. */
714 /* Note that we can't just check circ->cpath here, because if
715 * circuit-building failed immediately, it won't be set yet. */
716 circuit_increment_failure_count();
719 circ->marked_for_close = 1;
720 return 0;
723 void circuit_detach_stream(circuit_t *circ, connection_t *conn) {
724 connection_t *prevconn;
726 assert(circ);
727 assert(conn);
729 if(conn == circ->p_streams) {
730 circ->p_streams = conn->next_stream;
731 return;
733 if(conn == circ->n_streams) {
734 circ->n_streams = conn->next_stream;
735 return;
737 for(prevconn = circ->p_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
738 if(prevconn && prevconn->next_stream) {
739 prevconn->next_stream = conn->next_stream;
740 return;
742 for(prevconn = circ->n_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
743 if(prevconn && prevconn->next_stream) {
744 prevconn->next_stream = conn->next_stream;
745 return;
747 log_fn(LOG_ERR,"edge conn not in circuit's list?");
748 assert(0); /* should never get here */
751 void circuit_about_to_close_connection(connection_t *conn) {
752 /* send destroys for all circuits using conn */
753 /* currently, we assume it's too late to flush conn's buf here.
754 * down the road, maybe we'll consider that eof doesn't mean can't-write
756 circuit_t *circ;
758 switch(conn->type) {
759 case CONN_TYPE_OR:
760 /* We must close all the circuits on it. */
761 while((circ = circuit_get_by_conn(conn))) {
762 if(circ->n_conn == conn) /* it's closing in front of us */
763 circ->n_conn = NULL;
764 if(circ->p_conn == conn) /* it's closing behind us */
765 circ->p_conn = NULL;
766 circuit_mark_for_close(circ);
768 return;
769 case CONN_TYPE_AP:
770 case CONN_TYPE_EXIT:
772 /* It's an edge conn. Need to remove it from the linked list of
773 * conn's for this circuit. Confirm that 'end' relay command has
774 * been sent. But don't kill the circuit.
777 circ = circuit_get_by_conn(conn);
778 if(!circ)
779 return;
781 if(!conn->has_sent_end) {
782 log_fn(LOG_WARN,"Edge connection hasn't sent end yet? Bug.");
783 connection_mark_for_close(conn, END_STREAM_REASON_MISC);
786 circuit_detach_stream(circ, conn);
788 } /* end switch */
791 void circuit_log_path(int severity, circuit_t *circ) {
792 static char b[1024];
793 struct crypt_path_t *hop;
794 char *states[] = {"closed", "waiting for keys", "open"};
795 routerinfo_t *router;
796 assert(circ->cpath);
798 sprintf(b,"circ (length %d, exit %s): ",
799 circ->build_state->desired_path_len, circ->build_state->chosen_exit);
800 hop=circ->cpath;
801 do {
802 router = router_get_by_addr_port(hop->addr,hop->port);
803 if(router) {
804 /* XXX strcat allows buffer overflow */
805 strcat(b,router->nickname);
806 strcat(b,"(");
807 strcat(b,states[hop->state]);
808 strcat(b,"),");
809 } else {
810 strcat(b,"UNKNOWN,");
812 hop=hop->next;
813 } while(hop!=circ->cpath);
814 log_fn(severity,"%s",b);
817 static void
818 circuit_dump_details(int severity, circuit_t *circ, int poll_index,
819 char *type, int this_circid, int other_circid) {
820 struct crypt_path_t *hop;
821 log(severity,"Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d",
822 poll_index, type, this_circid, other_circid, circ->state,
823 circuit_state_to_string[circ->state], (int)circ->timestamp_created);
824 if(circ->cpath) { /* circ starts at this node */
825 if(circ->state == CIRCUIT_STATE_BUILDING)
826 log(severity,"Building: desired len %d, planned exit node %s.",
827 circ->build_state->desired_path_len, circ->build_state->chosen_exit);
828 for(hop=circ->cpath;hop->next != circ->cpath; hop=hop->next)
829 log(severity,"hop: state %d, addr %x, port %d", hop->state,
830 (unsigned int)hop->addr,
831 (int)hop->port);
835 void circuit_dump_by_conn(connection_t *conn, int severity) {
836 circuit_t *circ;
837 connection_t *tmpconn;
839 for(circ=global_circuitlist;circ;circ = circ->next) {
840 if(circ->p_conn == conn)
841 circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
842 circ->p_circ_id, circ->n_circ_id);
843 for(tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
844 if(tmpconn == conn) {
845 circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
846 circ->p_circ_id, circ->n_circ_id);
849 if(circ->n_conn == conn)
850 circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
851 circ->n_circ_id, circ->p_circ_id);
852 for(tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
853 if(tmpconn == conn) {
854 circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
855 circ->n_circ_id, circ->p_circ_id);
861 void circuit_expire_unused_circuits(void) {
862 circuit_t *circ, *tmpcirc;
863 time_t now = time(NULL);
865 circ = global_circuitlist;
866 while(circ) {
867 tmpcirc = circ;
868 circ = circ->next;
869 if(tmpcirc->timestamp_dirty &&
870 tmpcirc->timestamp_dirty + options.NewCircuitPeriod < now &&
871 !tmpcirc->p_conn && !tmpcirc->p_streams && !tmpcirc->marked_for_close) {
872 log_fn(LOG_DEBUG,"Closing n_circ_id %d",tmpcirc->n_circ_id);
873 circuit_mark_for_close(tmpcirc);
878 /* Number of consecutive failures so far; should only be touched by
879 * circuit_launch_new and circuit_*_failure_count.
881 static int n_circuit_failures = 0;
883 /* Return -1 if you aren't going to try to make a circuit, 0 if you did try. */
884 int circuit_launch_new(void) {
886 if(!options.SocksPort) /* we're not an application proxy. no need for circuits. */
887 return -1;
889 if(n_circuit_failures > 5) { /* too many failed circs in a row. don't try. */
890 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
891 return -1;
894 /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
895 circuit_establish_circuit();
897 return 0;
900 void circuit_increment_failure_count(void) {
901 ++n_circuit_failures;
902 log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
905 void circuit_reset_failure_count(void) {
906 n_circuit_failures = 0;
909 int circuit_establish_circuit(void) {
910 routerinfo_t *firsthop;
911 connection_t *n_conn;
912 circuit_t *circ;
914 circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
915 circ->state = CIRCUIT_STATE_OR_WAIT;
916 circ->build_state = onion_new_cpath_build_state();
918 if (! circ->build_state) {
919 log_fn(LOG_INFO,"Generating cpath length failed.");
920 circuit_mark_for_close(circ);
921 return -1;
924 onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop);
925 if(!circ->cpath) {
926 log_fn(LOG_INFO,"Generating first cpath hop failed.");
927 circuit_mark_for_close(circ);
928 return -1;
931 /* now see if we're already connected to the first OR in 'route' */
933 log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
934 firsthop->address,firsthop->or_port);
935 n_conn = connection_twin_get_by_addr_port(firsthop->addr,firsthop->or_port);
936 if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
937 circ->n_addr = firsthop->addr;
938 circ->n_port = firsthop->or_port;
939 if(options.ORPort) { /* we would be connected if he were up. and he's not. */
940 log_fn(LOG_INFO,"Route's firsthop isn't connected.");
941 circuit_mark_for_close(circ);
942 return -1;
945 if(!n_conn) { /* launch the connection */
946 n_conn = connection_or_connect(firsthop);
947 if(!n_conn) { /* connect failed, forget the whole thing */
948 log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
949 circuit_mark_for_close(circ);
950 return -1;
954 log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
955 return 0; /* return success. The onion/circuit/etc will be taken care of automatically
956 * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
958 } else { /* it (or a twin) is already open. use it. */
959 circ->n_addr = n_conn->addr;
960 circ->n_port = n_conn->port;
961 circ->n_conn = n_conn;
962 log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
963 if(circuit_send_next_onion_skin(circ) < 0) {
964 log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
965 circuit_mark_for_close(circ);
966 return -1;
969 return 0;
972 /* find circuits that are waiting on me, if any, and get them to send the onion */
973 void circuit_n_conn_open(connection_t *or_conn) {
974 circuit_t *circ;
976 for(circ=global_circuitlist;circ;circ = circ->next) {
977 if (circ->marked_for_close)
978 continue;
979 if(circ->cpath && circ->n_addr == or_conn->addr && circ->n_port == or_conn->port) {
980 assert(circ->state == CIRCUIT_STATE_OR_WAIT);
981 log_fn(LOG_DEBUG,"Found circ %d, sending onion skin.", circ->n_circ_id);
982 circ->n_conn = or_conn;
983 if(circuit_send_next_onion_skin(circ) < 0) {
984 log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
985 circuit_mark_for_close(circ);
986 continue;
987 /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
993 int circuit_send_next_onion_skin(circuit_t *circ) {
994 cell_t cell;
995 crypt_path_t *hop;
996 routerinfo_t *router;
997 int r;
998 int circ_id_type;
999 char payload[6+ONIONSKIN_CHALLENGE_LEN];
1001 assert(circ && circ->cpath);
1003 if(circ->cpath->state == CPATH_STATE_CLOSED) {
1004 assert(circ->n_conn && circ->n_conn->type == CONN_TYPE_OR);
1006 log_fn(LOG_DEBUG,"First skin; sending create cell.");
1007 circ_id_type = decide_circ_id_type(options.Nickname,
1008 circ->n_conn->nickname);
1009 circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
1011 memset(&cell, 0, sizeof(cell_t));
1012 cell.command = CELL_CREATE;
1013 cell.circ_id = circ->n_circ_id;
1015 if(onion_skin_create(circ->n_conn->onion_pkey, &(circ->cpath->handshake_state), cell.payload) < 0) {
1016 log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
1017 return -1;
1020 connection_or_write_cell_to_buf(&cell, circ->n_conn);
1022 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
1023 circ->state = CIRCUIT_STATE_BUILDING;
1024 log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
1025 } else {
1026 assert(circ->cpath->state == CPATH_STATE_OPEN);
1027 assert(circ->state == CIRCUIT_STATE_BUILDING);
1028 log_fn(LOG_DEBUG,"starting to send subsequent skin.");
1029 r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
1030 if (r==1) {
1031 /* done building the circuit. whew. */
1032 circ->state = CIRCUIT_STATE_OPEN;
1033 log_fn(LOG_INFO,"circuit built!");
1034 circuit_reset_failure_count();
1035 /* Tell any AP connections that have been waiting for a new
1036 * circuit that one is ready. */
1037 connection_ap_attach_pending();
1038 return 0;
1039 } else if (r<0) {
1040 log_fn(LOG_INFO,"Unable to extend circuit path.");
1041 return -1;
1043 hop = circ->cpath->prev;
1045 *(uint32_t*)payload = htonl(hop->addr);
1046 *(uint16_t*)(payload+4) = htons(hop->port);
1047 if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), payload+6) < 0) {
1048 log_fn(LOG_WARN,"onion_skin_create failed.");
1049 return -1;
1052 log_fn(LOG_DEBUG,"Sending extend relay cell.");
1053 /* send it to hop->prev, because it will transfer
1054 * it to a create cell and then send to hop */
1055 if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
1056 payload, sizeof(payload), hop->prev) < 0)
1057 return 0; /* circuit is closed */
1059 hop->state = CPATH_STATE_AWAITING_KEYS;
1061 return 0;
1064 /* take the 'extend' cell, pull out addr/port plus the onion skin. Make
1065 * sure we're connected to the next hop, and pass it the onion skin in
1066 * a create cell.
1068 int circuit_extend(cell_t *cell, circuit_t *circ) {
1069 connection_t *n_conn;
1070 int circ_id_type;
1071 cell_t newcell;
1073 if(circ->n_conn) {
1074 log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
1075 return -1;
1078 circ->n_addr = ntohl(*(uint32_t*)(cell->payload+RELAY_HEADER_SIZE));
1079 circ->n_port = ntohs(*(uint16_t*)(cell->payload+RELAY_HEADER_SIZE+4));
1081 n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
1082 if(!n_conn || n_conn->type != CONN_TYPE_OR) {
1083 /* I've disabled making connections through OPs, but it's definitely
1084 * possible here. I'm not sure if it would be a bug or a feature.
1086 * Note also that this will close circuits where the onion has the same
1087 * router twice in a row in the path. I think that's ok.
1089 struct in_addr in;
1090 in.s_addr = htonl(circ->n_addr);
1091 log_fn(LOG_INFO,"Next router (%s:%d) not connected. Closing.", inet_ntoa(in), circ->n_port);
1092 connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
1093 NULL, 0, NULL);
1094 return 0;
1097 circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
1098 circ->n_port = n_conn->port;
1100 circ->n_conn = n_conn;
1101 log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
1103 circ_id_type = decide_circ_id_type(options.Nickname, n_conn->nickname);
1105 // log_fn(LOG_DEBUG,"circ_id_type = %u.",circ_id_type);
1106 circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
1107 if(!circ->n_circ_id) {
1108 log_fn(LOG_WARN,"failed to get unique circID.");
1109 return -1;
1111 log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
1113 memset(&newcell, 0, sizeof(cell_t));
1114 newcell.command = CELL_CREATE;
1115 newcell.circ_id = circ->n_circ_id;
1117 memcpy(newcell.payload, cell->payload+RELAY_HEADER_SIZE+6,
1118 ONIONSKIN_CHALLENGE_LEN);
1120 connection_or_write_cell_to_buf(&newcell, circ->n_conn);
1121 return 0;
1124 extern int has_completed_circuit;
1126 int circuit_finish_handshake(circuit_t *circ, char *reply) {
1127 unsigned char iv[16];
1128 unsigned char keys[40+32];
1129 crypt_path_t *hop;
1131 memset(iv, 0, 16);
1133 assert(circ->cpath);
1134 if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
1135 hop = circ->cpath;
1136 else {
1137 for(hop=circ->cpath->next;
1138 hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
1139 hop=hop->next) ;
1140 if(hop == circ->cpath) { /* got an extended when we're all done? */
1141 log_fn(LOG_WARN,"got extended when circ already built? Closing.");
1142 return -1;
1145 assert(hop->state == CPATH_STATE_AWAITING_KEYS);
1147 if(onion_skin_client_handshake(hop->handshake_state, reply, keys, 40+32) < 0) {
1148 log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
1149 return -1;
1152 crypto_dh_free(hop->handshake_state); /* don't need it anymore */
1153 hop->handshake_state = NULL;
1155 log_fn(LOG_DEBUG,"hop init digest forward %u, backward %u.",
1156 (unsigned)*(uint32_t*)keys, (unsigned)*(uint32_t*)(keys+20));
1157 hop->f_digest = crypto_new_digest_env(CRYPTO_SHA1_DIGEST);
1158 crypto_digest_add_bytes(hop->f_digest, keys, 20);
1159 hop->b_digest = crypto_new_digest_env(CRYPTO_SHA1_DIGEST);
1160 crypto_digest_add_bytes(hop->b_digest, keys+20, 20);
1162 log_fn(LOG_DEBUG,"hop init cipher forward %u, backward %u.",
1163 (unsigned)*(uint32_t*)(keys+40), (unsigned) *(uint32_t*)(keys+40+16));
1164 if (!(hop->f_crypto =
1165 crypto_create_init_cipher(CIRCUIT_CIPHER,keys+40,iv,1))) {
1166 log(LOG_WARN,"forward cipher initialization failed.");
1167 return -1;
1169 if (!(hop->b_crypto =
1170 crypto_create_init_cipher(CIRCUIT_CIPHER,keys+40+16,iv,0))) {
1171 log(LOG_WARN,"backward cipher initialization failed.");
1172 return -1;
1175 hop->state = CPATH_STATE_OPEN;
1176 log_fn(LOG_INFO,"finished");
1177 if(!has_completed_circuit) {
1178 has_completed_circuit=1;
1179 log_fn(LOG_WARN,"Tor has successfully opened a circuit. Looks like it's working.");
1181 circuit_log_path(LOG_INFO,circ);
1182 return 0;
1185 int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
1186 crypt_path_t *victim;
1187 connection_t *stream;
1189 assert(circ);
1190 assert(layer);
1192 /* XXX Since we don't ask for truncates currently, getting a truncated
1193 * means that a connection broke or an extend failed. For now,
1194 * just give up.
1196 circuit_mark_for_close(circ);
1197 return 0;
1199 while(layer->next != circ->cpath) {
1200 /* we need to clear out layer->next */
1201 victim = layer->next;
1202 log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
1204 for(stream = circ->p_streams; stream; stream=stream->next_stream) {
1205 if(stream->cpath_layer == victim) {
1206 log_fn(LOG_INFO, "Marking stream %d for close.", stream->stream_id);
1207 /* no need to send 'end' relay cells,
1208 * because the other side's already dead
1210 connection_mark_for_close(stream,0);
1214 layer->next = victim->next;
1215 circuit_free_cpath_node(victim);
1218 log_fn(LOG_INFO, "finished");
1219 return 0;
1222 void assert_cpath_layer_ok(const crypt_path_t *cp)
1224 assert(cp->f_crypto);
1225 assert(cp->b_crypto);
1226 assert(cp->addr);
1227 assert(cp->port);
1228 switch(cp->state)
1230 case CPATH_STATE_CLOSED:
1231 case CPATH_STATE_OPEN:
1232 assert(!cp->handshake_state);
1233 break;
1234 case CPATH_STATE_AWAITING_KEYS:
1235 assert(cp->handshake_state);
1236 break;
1237 default:
1238 assert(0);
1240 assert(cp->package_window >= 0);
1241 assert(cp->deliver_window >= 0);
1244 void assert_cpath_ok(const crypt_path_t *cp)
1246 while(cp->prev)
1247 cp = cp->prev;
1249 while(cp->next) {
1250 assert_cpath_layer_ok(cp);
1251 /* layers must be in sequence of: "open* awaiting? closed*" */
1252 if (cp->prev) {
1253 if (cp->prev->state == CPATH_STATE_OPEN) {
1254 assert(cp->state == CPATH_STATE_CLOSED ||
1255 cp->state == CPATH_STATE_AWAITING_KEYS);
1256 } else {
1257 assert(cp->state == CPATH_STATE_CLOSED);
1260 cp = cp->next;
1264 void assert_circuit_ok(const circuit_t *c)
1266 connection_t *conn;
1268 assert(c);
1269 assert(c->magic == CIRCUIT_MAGIC);
1271 return;
1273 assert(c->n_addr);
1274 assert(c->n_port);
1275 assert(c->n_conn);
1276 assert(c->n_conn->type == CONN_TYPE_OR);
1277 if (c->p_conn)
1278 assert(c->p_conn->type == CONN_TYPE_OR);
1279 for (conn = c->p_streams; conn; conn = conn->next_stream)
1280 assert(c->p_conn->type == CONN_TYPE_EXIT);
1281 for (conn = c->n_streams; conn; conn = conn->next_stream)
1282 assert(conn->type == CONN_TYPE_EXIT);
1284 assert(c->deliver_window >= 0);
1285 assert(c->package_window >= 0);
1286 if (c->state == CIRCUIT_STATE_OPEN) {
1287 if (c->cpath) {
1288 assert(!c->n_crypto);
1289 assert(!c->p_crypto);
1290 assert(!c->n_digest);
1291 assert(!c->p_digest);
1292 } else {
1293 assert(c->n_crypto);
1294 assert(c->p_crypto);
1295 assert(c->n_digest);
1296 assert(c->p_digest);
1299 if (c->cpath) {
1300 assert_cpath_ok(c->cpath);
1305 Local Variables:
1306 mode:c
1307 indent-tabs-mode:nil
1308 c-basic-offset:2
1309 End: