move cell size to 512 bytes
[tor.git] / src / or / circuit.c
blob7a7cc13b6338bf24a8ce10b49a2376ef4eadf6b7
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 void circuit_free_cpath_node(crypt_path_t *victim);
10 static circ_id_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type);
12 unsigned long stats_n_relay_cells_relayed = 0;
13 unsigned long stats_n_relay_cells_delivered = 0;
15 /********* START VARIABLES **********/
17 static circuit_t *global_circuitlist=NULL;
19 char *circuit_state_to_string[] = {
20 "doing handshakes", /* 0 */
21 "processing the onion", /* 1 */
22 "connecting to firsthop", /* 2 */
23 "open" /* 3 */
26 /********* END VARIABLES ************/
28 void circuit_add(circuit_t *circ) {
30 if(!global_circuitlist) { /* first one */
31 global_circuitlist = circ;
32 circ->next = NULL;
33 } else {
34 circ->next = global_circuitlist;
35 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 circuit_t *circuit_new(circ_id_t p_circ_id, connection_t *p_conn) {
59 circuit_t *circ;
61 circ = tor_malloc_zero(sizeof(circuit_t));
63 circ->timestamp_created = time(NULL);
65 circ->p_circ_id = p_circ_id;
66 circ->p_conn = p_conn;
68 circ->state = CIRCUIT_STATE_ONIONSKIN_PENDING;
70 /* CircIDs */
71 circ->p_circ_id = p_circ_id;
72 /* circ->n_circ_id remains 0 because we haven't identified the next hop yet */
74 circ->package_window = CIRCWINDOW_START;
75 circ->deliver_window = CIRCWINDOW_START;
77 circuit_add(circ);
79 return circ;
82 void circuit_free(circuit_t *circ) {
83 assert(circ);
84 if (circ->n_crypto)
85 crypto_free_cipher_env(circ->n_crypto);
86 if (circ->p_crypto)
87 crypto_free_cipher_env(circ->p_crypto);
88 if(circ->build_state)
89 tor_free(circ->build_state->chosen_exit);
90 tor_free(circ->build_state);
91 circuit_free_cpath(circ->cpath);
92 free(circ);
95 void circuit_free_cpath(crypt_path_t *cpath) {
96 crypt_path_t *victim, *head=cpath;
98 if(!cpath)
99 return;
101 /* it's a doubly linked list, so we have to notice when we've
102 * gone through it once. */
103 while(cpath->next && cpath->next != head) {
104 victim = cpath;
105 cpath = victim->next;
106 circuit_free_cpath_node(victim);
109 circuit_free_cpath_node(cpath);
112 static void circuit_free_cpath_node(crypt_path_t *victim) {
113 if(victim->f_crypto)
114 crypto_free_cipher_env(victim->f_crypto);
115 if(victim->b_crypto)
116 crypto_free_cipher_env(victim->b_crypto);
117 if(victim->f_digest)
118 crypto_free_digest_env(victim->f_digest);
119 if(victim->b_digest)
120 crypto_free_digest_env(victim->b_digest);
121 if(victim->handshake_state)
122 crypto_dh_free(victim->handshake_state);
123 free(victim);
126 /* return 0 if can't get a unique circ_id. */
127 static circ_id_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type) {
128 circ_id_t test_circ_id;
129 uint16_t high_bit;
130 assert(conn && conn->type == CONN_TYPE_OR);
132 high_bit = (circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
133 do {
134 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find an
135 * circID such that (high_bit|test_circ_id) is not already used. */
136 /* XXX Will loop forever if all circ_id's in our range are used.
137 * This matters because it's an external DoS vulnerability. */
138 test_circ_id = conn->next_circ_id++;
139 if (test_circ_id == 0 || test_circ_id >= 1<<15) {
140 test_circ_id = 1;
141 conn->next_circ_id = 2;
143 test_circ_id |= high_bit;
144 } while(circuit_get_by_circ_id_conn(test_circ_id, conn));
145 return test_circ_id;
148 circuit_t *circuit_get_by_circ_id_conn(circ_id_t circ_id, connection_t *conn) {
149 circuit_t *circ;
150 connection_t *tmpconn;
152 for(circ=global_circuitlist;circ;circ = circ->next) {
153 if(circ->p_circ_id == circ_id) {
154 if(circ->p_conn == conn)
155 return circ;
156 for(tmpconn = circ->p_streams; tmpconn; tmpconn = tmpconn->next_stream) {
157 if(tmpconn == conn)
158 return circ;
161 if(circ->n_circ_id == circ_id) {
162 if(circ->n_conn == conn)
163 return circ;
164 for(tmpconn = circ->n_streams; tmpconn; tmpconn = tmpconn->next_stream) {
165 if(tmpconn == conn)
166 return circ;
170 return NULL;
173 circuit_t *circuit_get_by_conn(connection_t *conn) {
174 circuit_t *circ;
175 connection_t *tmpconn;
177 for(circ=global_circuitlist;circ;circ = circ->next) {
178 if(circ->p_conn == conn)
179 return circ;
180 if(circ->n_conn == conn)
181 return circ;
182 for(tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
183 if(tmpconn == conn)
184 return circ;
185 for(tmpconn = circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream)
186 if(tmpconn == conn)
187 return circ;
189 return NULL;
192 /* Find the newest circ that conn can use, preferably one which is
193 * dirty and not too old.
194 * If !conn, return newest.
196 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
198 circuit_t *circuit_get_newest(connection_t *conn, int must_be_open) {
199 circuit_t *circ, *newest=NULL, *leastdirty=NULL;
200 routerinfo_t *exitrouter;
202 for(circ=global_circuitlist;circ;circ = circ->next) {
203 if(!circ->cpath)
204 continue; /* this circ doesn't start at us */
205 if(must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
206 continue; /* ignore non-open circs */
207 if(conn) {
208 if(circ->state == CIRCUIT_STATE_OPEN && circ->n_conn) /* open */
209 exitrouter = router_get_by_addr_port(circ->cpath->prev->addr, circ->cpath->prev->port);
210 else /* not open */
211 exitrouter = router_get_by_nickname(circ->build_state->chosen_exit);
212 if(!exitrouter || connection_ap_can_use_exit(conn, exitrouter) < 0) {
213 /* can't exit from this router */
214 continue;
217 if(!newest || newest->timestamp_created < circ->timestamp_created) {
218 newest = circ;
220 if(conn && circ->timestamp_dirty &&
221 (!leastdirty || leastdirty->timestamp_dirty < circ->timestamp_dirty)) {
222 leastdirty = circ;
226 if(leastdirty &&
227 leastdirty->timestamp_dirty+options.NewCircuitPeriod > time(NULL)) {
228 /* log_fn(LOG_DEBUG,"Choosing in-use circuit %s:%d:%d.",
229 leastdirty->n_conn->address, leastdirty->n_port, leastdirty->n_circ_id); */
230 return leastdirty;
232 if(newest) {
233 /* log_fn(LOG_DEBUG,"Choosing circuit %s:%d:%d.",
234 newest->n_conn->address, newest->n_port, newest->n_circ_id); */
235 return newest;
237 return NULL;
240 #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 3
241 /* circuits that were born at the end of their second might be expired
242 * after 3.1 seconds; circuits born at the beginning might be expired
243 * after closer to 4 seconds.
246 /* close all circuits that start at us, aren't open, and were born
247 * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago */
248 void circuit_expire_building(void) {
249 int now = time(NULL);
250 circuit_t *victim, *circ = global_circuitlist;
252 while(circ) {
253 victim = circ;
254 circ = circ->next;
255 if(victim->cpath &&
256 victim->state != CIRCUIT_STATE_OPEN &&
257 victim->timestamp_created + MIN_SECONDS_BEFORE_EXPIRING_CIRC+1 < now) {
258 if(victim->n_conn)
259 log_fn(LOG_INFO,"Abandoning circ %s:%d:%d (state %d:%s)",
260 victim->n_conn->address, victim->n_port, victim->n_circ_id,
261 victim->state, circuit_state_to_string[victim->state]);
262 else
263 log_fn(LOG_INFO,"Abandoning circ %d (state %d:%s)", victim->n_circ_id,
264 victim->state, circuit_state_to_string[victim->state]);
265 circuit_close(victim);
270 /* count the number of circs starting at us that aren't open */
271 int circuit_count_building(void) {
272 circuit_t *circ;
273 int num=0;
275 for(circ=global_circuitlist;circ;circ = circ->next) {
276 if(circ->cpath && circ->state != CIRCUIT_STATE_OPEN)
277 num++;
279 return num;
282 #define MIN_CIRCUITS_HANDLING_STREAM 2
283 /* return 1 if at least MIN_CIRCUITS_HANDLING_STREAM non-open circuits
284 * will have an acceptable exit node for conn. Else return 0.
286 int circuit_stream_is_being_handled(connection_t *conn) {
287 circuit_t *circ;
288 routerinfo_t *exitrouter;
289 int num=0;
291 for(circ=global_circuitlist;circ;circ = circ->next) {
292 if(circ->cpath && circ->state != CIRCUIT_STATE_OPEN) {
293 exitrouter = router_get_by_nickname(circ->build_state->chosen_exit);
294 if(exitrouter && connection_ap_can_use_exit(conn, exitrouter) >= 0)
295 if(++num >= MIN_CIRCUITS_HANDLING_STREAM)
296 return 1;
299 return 0;
302 int circuit_deliver_relay_cell(cell_t *cell, circuit_t *circ,
303 int cell_direction, crypt_path_t *layer_hint) {
304 connection_t *conn=NULL;
305 char recognized=0;
307 assert(cell && circ);
308 assert(cell_direction == CELL_DIRECTION_OUT || cell_direction == CELL_DIRECTION_IN);
310 log_fn(LOG_DEBUG,"direction %d, streamid %d before crypt.", cell_direction, *(int*)(cell->payload+1));
312 if(relay_crypt(circ, cell->payload, CELL_PAYLOAD_SIZE, cell_direction,
313 &layer_hint, &recognized, &conn) < 0) {
314 log_fn(LOG_WARN,"relay crypt failed. Dropping connection.");
315 return -1;
318 if(recognized) {
319 if(cell_direction == CELL_DIRECTION_OUT) {
320 #if 0
321 if(relay_update_digest(circ->n_digest, cell) < 0) {
322 log_fn(LOG_WARN,"outgoing cell failed integrity check. Closing circ.");
323 return -1;
325 #endif
326 ++stats_n_relay_cells_delivered;
327 log_fn(LOG_DEBUG,"Sending to exit.");
328 if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_EXIT, NULL) < 0) {
329 log_fn(LOG_WARN,"connection_edge_process_relay_cell (at exit) failed.");
330 return -1;
333 if(cell_direction == CELL_DIRECTION_IN) {
334 #if 0
335 if(relay_update_digest(layer_hint->p_digest, cell) < 0) {
336 log_fn(LOG_WARN,"outgoing cell failed integrity check. Closing circ.");
337 return -1;
339 #endif
340 ++stats_n_relay_cells_delivered;
341 log_fn(LOG_DEBUG,"Sending to AP.");
342 if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_AP, layer_hint) < 0) {
343 log_fn(LOG_WARN,"connection_edge_process_relay_cell (at AP) failed.");
344 return -1;
347 return 0;
350 /* not recognized. pass it on. */
351 if(cell_direction == CELL_DIRECTION_OUT)
352 conn = circ->n_conn;
353 else
354 conn = circ->p_conn;
356 if(!conn) {
357 log_fn(LOG_INFO,"Didn't recognize cell (%d), but circ stops here! Dropping.",
358 *(int *)(cell->payload+1));
359 return 0;
362 log_fn(LOG_DEBUG,"Passing on unrecognized cell.");
363 ++stats_n_relay_cells_relayed;
364 connection_or_write_cell_to_buf(cell, conn);
365 return 0;
368 int relay_crypt(circuit_t *circ, char *in, int inlen, char cell_direction,
369 crypt_path_t **layer_hint, char *recognized, connection_t **conn) {
370 crypt_path_t *thishop;
371 char out[CELL_NETWORK_SIZE];
373 assert(circ && in && recognized && conn);
375 assert(inlen < CELL_NETWORK_SIZE);
377 if(cell_direction == CELL_DIRECTION_IN) {
378 if(circ->cpath) { /* we're at the beginning of the circuit.
379 We'll want to do layered crypts. */
380 thishop = circ->cpath;
381 if(thishop->state != CPATH_STATE_OPEN) {
382 log_fn(LOG_WARN,"Relay cell before first created cell?");
383 return -1;
385 do { /* Remember: cpath is in forward order, that is, first hop first. */
386 assert(thishop);
388 log_fn(LOG_DEBUG,"before decrypt: %d",*(int*)(in+1));
389 /* decrypt */
390 if(crypto_cipher_decrypt(thishop->b_crypto, in, inlen, out)) {
391 log_fn(LOG_WARN,"Error performing onion decryption: %s", crypto_perror());
392 return -1;
394 memcpy(in,out,inlen);
395 log_fn(LOG_DEBUG,"after decrypt: %d",*(int*)(in+1));
397 if( (*recognized = relay_check_recognized(circ, cell_direction, in+1, conn))) {
398 *layer_hint = thishop;
399 return 0;
402 thishop = thishop->next;
403 } while(thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
404 log_fn(LOG_INFO,"in-cell at OP not recognized. Dropping.");
405 return 0;
406 } else { /* we're in the middle. Just one crypt. */
408 log_fn(LOG_DEBUG,"before encrypt: %d",*(int*)(in+1));
409 if(crypto_cipher_encrypt(circ->p_crypto, in, inlen, out)) {
410 log_fn(LOG_WARN,"Onion encryption failed for circID %u: %s",
411 circ->p_circ_id, crypto_perror());
412 return -1;
414 memcpy(in,out,inlen);
415 log_fn(LOG_DEBUG,"after encrypt: %d",*(int*)(in+1));
417 log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
418 /* don't check for recognized. only the OP can recognize a stream on the way back. */
421 } else if(cell_direction == CELL_DIRECTION_OUT) {
422 if(circ->cpath) { /* we're at the beginning of the circuit. We'll want to do layered crypts. */
424 thishop = *layer_hint; /* we already know which layer, from when we package_raw_inbuf'ed */
425 /* moving from last to first hop */
426 do {
427 assert(thishop);
429 log_fn(LOG_DEBUG,"before encrypt: %d",*(int*)(in+1));
430 if(crypto_cipher_encrypt(thishop->f_crypto, in, inlen, out)) {
431 log_fn(LOG_WARN,"Error performing encryption: %s", crypto_perror());
432 return -1;
434 memcpy(in,out,inlen);
435 log_fn(LOG_DEBUG,"after encrypt: %d",*(int*)(in+1));
437 thishop = thishop->prev;
438 } while(thishop != circ->cpath->prev);
439 } else { /* we're in the middle. Just one crypt. */
441 if(crypto_cipher_decrypt(circ->n_crypto,in, inlen, out)) {
442 log_fn(LOG_WARN,"Decryption failed for circID %u: %s",
443 circ->n_circ_id, crypto_perror());
444 return -1;
446 memcpy(in,out,inlen);
448 if( (*recognized = relay_check_recognized(circ, cell_direction, in+1, conn)))
449 return 0;
452 } else {
453 log_fn(LOG_ERR,"unknown cell direction %d.", cell_direction);
454 assert(0);
457 return 0;
460 int relay_check_recognized(circuit_t *circ, int cell_direction, char *stream, connection_t **conn) {
461 /* FIXME can optimize by passing thishop in */
462 connection_t *tmpconn;
464 if(!memcmp(stream,ZERO_STREAM,STREAM_ID_SIZE)) {
465 log_fn(LOG_DEBUG,"It's the zero stream. Recognized.");
466 return 1; /* the zero stream is always recognized */
468 log_fn(LOG_DEBUG,"not the zero stream.");
470 if(cell_direction == CELL_DIRECTION_OUT)
471 tmpconn = circ->n_streams;
472 else
473 tmpconn = circ->p_streams;
475 if(!tmpconn) {
476 log_fn(LOG_DEBUG,"No conns. Not recognized.");
477 return 0;
480 for( ; tmpconn; tmpconn=tmpconn->next_stream) {
481 if(!memcmp(stream,tmpconn->stream_id, STREAM_ID_SIZE)) {
482 log_fn(LOG_DEBUG,"recognized stream %d.", *(int*)stream);
483 *conn = tmpconn;
484 return 1;
486 log_fn(LOG_DEBUG,"considered stream %d, not it.",*(int*)tmpconn->stream_id);
489 log_fn(LOG_DEBUG,"Didn't recognize on this iteration of decryption.");
490 return 0;
494 void circuit_resume_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
495 connection_t *conn;
497 assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
499 log_fn(LOG_DEBUG,"resuming");
501 if(edge_type == EDGE_EXIT)
502 conn = circ->n_streams;
503 else
504 conn = circ->p_streams;
506 for( ; conn; conn=conn->next_stream) {
507 if((edge_type == EDGE_EXIT && conn->package_window > 0) ||
508 (edge_type == EDGE_AP && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
509 connection_start_reading(conn);
510 connection_edge_package_raw_inbuf(conn); /* handle whatever might still be on the inbuf */
512 /* If the circuit won't accept any more data, return without looking
513 * at any more of the streams. Any connections that should be stopped
514 * have already been stopped by connection_edge_package_raw_inbuf. */
515 if(circuit_consider_stop_edge_reading(circ, edge_type, layer_hint))
516 return;
521 /* returns 1 if the window is empty, else 0. If it's empty, tell edge conns to stop reading. */
522 int circuit_consider_stop_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
523 connection_t *conn = NULL;
525 assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
526 assert(edge_type == EDGE_EXIT || layer_hint);
528 log_fn(LOG_DEBUG,"considering");
529 if(edge_type == EDGE_EXIT && circ->package_window <= 0)
530 conn = circ->n_streams;
531 else if(edge_type == EDGE_AP && layer_hint->package_window <= 0)
532 conn = circ->p_streams;
533 else
534 return 0;
536 for( ; conn; conn=conn->next_stream)
537 if(!layer_hint || conn->cpath_layer == layer_hint)
538 connection_stop_reading(conn);
540 log_fn(LOG_DEBUG,"yes. stopped.");
541 return 1;
544 int circuit_consider_sending_sendme(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
545 cell_t cell;
547 assert(circ);
549 memset(&cell, 0, sizeof(cell_t));
550 cell.command = CELL_RELAY;
551 SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_SENDME);
552 SET_CELL_STREAM_ID(cell, ZERO_STREAM);
553 SET_CELL_RELAY_LENGTH(cell, 0);
555 if(edge_type == EDGE_AP) { /* i'm the AP */
556 cell.circ_id = circ->n_circ_id;
557 while(layer_hint->deliver_window < CIRCWINDOW_START-CIRCWINDOW_INCREMENT) {
558 log_fn(LOG_DEBUG,"deliver_window %d, Queueing sendme forward.", layer_hint->deliver_window);
559 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
560 if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_OUT, layer_hint) < 0) {
561 log_fn(LOG_WARN,"At AP: circuit_deliver_relay_cell failed.");
562 return -1;
565 } else if(edge_type == EDGE_EXIT) { /* i'm the exit */
566 cell.circ_id = circ->p_circ_id;
567 while(circ->deliver_window < CIRCWINDOW_START-CIRCWINDOW_INCREMENT) {
568 log_fn(LOG_DEBUG,"deliver_window %d, Queueing sendme back.", circ->deliver_window);
569 circ->deliver_window += CIRCWINDOW_INCREMENT;
570 if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_IN, layer_hint) < 0) {
571 log_fn(LOG_WARN,"At exit: circuit_deliver_relay_cell failed.");
572 return -1;
576 return 0;
579 void circuit_close(circuit_t *circ) {
580 connection_t *conn;
582 assert(circ);
583 circuit_remove(circ);
584 if(circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
585 onion_pending_remove(circ);
588 if(circ->n_conn)
589 connection_send_destroy(circ->n_circ_id, circ->n_conn);
590 for(conn=circ->n_streams; conn; conn=conn->next_stream) {
591 connection_send_destroy(circ->n_circ_id, conn);
593 if(circ->p_conn)
594 connection_send_destroy(circ->n_circ_id, circ->p_conn);
595 for(conn=circ->p_streams; conn; conn=conn->next_stream) {
596 connection_send_destroy(circ->p_circ_id, conn);
598 if (circ->state == CIRCUIT_STATE_BUILDING ||
599 circ->state == CIRCUIT_STATE_OR_WAIT) {
600 /* If we never built the circuit, note it as a failure. */
601 circuit_increment_failure_count();
603 circuit_free(circ);
606 void circuit_about_to_close_connection(connection_t *conn) {
607 /* send destroys for all circuits using conn */
608 /* currently, we assume it's too late to flush conn's buf here.
609 * down the road, maybe we'll consider that eof doesn't mean can't-write
611 circuit_t *circ;
612 connection_t *prevconn;
614 switch(conn->type) {
615 case CONN_TYPE_OR:
616 /* We must close all the circuits on it. */
617 while((circ = circuit_get_by_conn(conn))) {
618 if(circ->n_conn == conn) /* it's closing in front of us */
619 circ->n_conn = NULL;
620 if(circ->p_conn == conn) /* it's closing behind us */
621 circ->p_conn = NULL;
622 circuit_close(circ);
624 return;
625 case CONN_TYPE_AP:
626 case CONN_TYPE_EXIT:
628 /* It's an edge conn. Need to remove it from the linked list of
629 * conn's for this circuit. Confirm that 'end' relay command has
630 * been sent. But don't kill the circuit.
633 circ = circuit_get_by_conn(conn);
634 if(!circ)
635 return;
637 if(!conn->has_sent_end) {
638 log_fn(LOG_INFO,"Edge connection hasn't sent end yet? Bug.");
639 if(connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer) < 0)
640 log_fn(LOG_WARN,"1: I called connection_edge_end redundantly.");
643 if(conn == circ->p_streams) {
644 circ->p_streams = conn->next_stream;
645 return;
647 if(conn == circ->n_streams) {
648 circ->n_streams = conn->next_stream;
649 return;
651 for(prevconn = circ->p_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
652 if(prevconn && prevconn->next_stream) {
653 prevconn->next_stream = conn->next_stream;
654 return;
656 for(prevconn = circ->n_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
657 if(prevconn && prevconn->next_stream) {
658 prevconn->next_stream = conn->next_stream;
659 return;
661 log_fn(LOG_ERR,"edge conn not in circuit's list?");
662 assert(0); /* should never get here */
663 } /* end switch */
666 void circuit_dump_details(int severity, circuit_t *circ, int poll_index,
667 char *type, int this_circid, int other_circid) {
668 struct crypt_path_t *hop;
669 log(severity,"Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d",
670 poll_index, type, this_circid, other_circid, circ->state,
671 circuit_state_to_string[circ->state], (int)circ->timestamp_created);
672 if(circ->cpath) { /* circ starts at this node */
673 if(circ->state == CIRCUIT_STATE_BUILDING)
674 log(severity,"Building: desired len %d, planned exit node %s.",
675 circ->build_state->desired_path_len, circ->build_state->chosen_exit);
676 for(hop=circ->cpath;hop->next != circ->cpath; hop=hop->next)
677 log(severity,"hop: state %d, addr %x, port %d", hop->state,
678 (unsigned int)hop->addr,
679 (int)hop->port);
683 void circuit_dump_by_conn(connection_t *conn, int severity) {
684 circuit_t *circ;
685 connection_t *tmpconn;
687 for(circ=global_circuitlist;circ;circ = circ->next) {
688 if(circ->p_conn == conn)
689 circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
690 circ->p_circ_id, circ->n_circ_id);
691 for(tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
692 if(tmpconn == conn) {
693 circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
694 circ->p_circ_id, circ->n_circ_id);
697 if(circ->n_conn == conn)
698 circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
699 circ->n_circ_id, circ->p_circ_id);
700 for(tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
701 if(tmpconn == conn) {
702 circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
703 circ->n_circ_id, circ->p_circ_id);
709 void circuit_expire_unused_circuits(void) {
710 circuit_t *circ, *tmpcirc;
711 time_t now = time(NULL);
713 circ = global_circuitlist;
714 while(circ) {
715 tmpcirc = circ;
716 circ = circ->next;
717 if(tmpcirc->timestamp_dirty &&
718 tmpcirc->timestamp_dirty + options.NewCircuitPeriod < now &&
719 !tmpcirc->p_conn && !tmpcirc->p_streams) {
720 log_fn(LOG_DEBUG,"Closing n_circ_id %d",tmpcirc->n_circ_id);
721 circuit_close(tmpcirc);
726 /* Number of consecutive failures so far; should only be touched by
727 * circuit_launch_new and circuit_*_failure_count.
729 static int n_circuit_failures = 0;
731 /* Return -1 if you aren't going to try to make a circuit, 0 if you did try. */
732 int circuit_launch_new(void) {
734 if(!options.SocksPort) /* we're not an application proxy. no need for circuits. */
735 return -1;
737 if(n_circuit_failures > 5) { /* too many failed circs in a row. don't try. */
738 // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
739 return -1;
742 /* try a circ. if it fails, circuit_close will increment n_circuit_failures */
743 circuit_establish_circuit();
745 return 0;
748 void circuit_increment_failure_count(void) {
749 ++n_circuit_failures;
750 log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
753 void circuit_reset_failure_count(void) {
754 n_circuit_failures = 0;
757 int circuit_establish_circuit(void) {
758 routerinfo_t *firsthop;
759 connection_t *n_conn;
760 circuit_t *circ;
762 circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
763 circ->state = CIRCUIT_STATE_OR_WAIT;
764 circ->build_state = onion_new_cpath_build_state();
766 if (! circ->build_state) {
767 log_fn(LOG_INFO,"Generating cpath length failed.");
768 circuit_close(circ);
769 return -1;
772 onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop);
773 if(!circ->cpath) {
774 log_fn(LOG_INFO,"Generating first cpath hop failed.");
775 circuit_close(circ);
776 return -1;
779 /* now see if we're already connected to the first OR in 'route' */
781 log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
782 firsthop->address,firsthop->or_port);
783 n_conn = connection_twin_get_by_addr_port(firsthop->addr,firsthop->or_port);
784 if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
785 circ->n_addr = firsthop->addr;
786 circ->n_port = firsthop->or_port;
787 if(options.ORPort) { /* we would be connected if he were up. and he's not. */
788 log_fn(LOG_INFO,"Route's firsthop isn't connected.");
789 circuit_close(circ);
790 return -1;
793 if(!n_conn) { /* launch the connection */
794 n_conn = connection_or_connect(firsthop);
795 if(!n_conn) { /* connect failed, forget the whole thing */
796 log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
797 circuit_close(circ);
798 return -1;
802 log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
803 return 0; /* return success. The onion/circuit/etc will be taken care of automatically
804 * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
806 } else { /* it (or a twin) is already open. use it. */
807 circ->n_addr = n_conn->addr;
808 circ->n_port = n_conn->port;
809 circ->n_conn = n_conn;
810 log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
811 if(circuit_send_next_onion_skin(circ) < 0) {
812 log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
813 circuit_close(circ);
814 return -1;
817 return 0;
820 /* find circuits that are waiting on me, if any, and get them to send the onion */
821 void circuit_n_conn_open(connection_t *or_conn) {
822 circuit_t *circ;
824 for(circ=global_circuitlist;circ;circ = circ->next) {
825 if(circ->cpath && circ->n_addr == or_conn->addr && circ->n_port == or_conn->port) {
826 assert(circ->state == CIRCUIT_STATE_OR_WAIT);
827 log_fn(LOG_DEBUG,"Found circ %d, sending onion skin.", circ->n_circ_id);
828 circ->n_conn = or_conn;
829 if(circuit_send_next_onion_skin(circ) < 0) {
830 log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
831 circuit_close(circ);
832 continue;
833 /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
839 int circuit_send_next_onion_skin(circuit_t *circ) {
840 cell_t cell;
841 crypt_path_t *hop;
842 routerinfo_t *router;
843 int r;
844 int circ_id_type;
846 assert(circ && circ->cpath);
848 if(circ->cpath->state == CPATH_STATE_CLOSED) {
849 assert(circ->n_conn && circ->n_conn->type == CONN_TYPE_OR);
851 log_fn(LOG_DEBUG,"First skin; sending create cell.");
852 circ_id_type = decide_circ_id_type(options.Nickname,
853 circ->n_conn->nickname);
854 circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
856 memset(&cell, 0, sizeof(cell_t));
857 cell.command = CELL_CREATE;
858 cell.circ_id = circ->n_circ_id;
860 if(onion_skin_create(circ->n_conn->onion_pkey, &(circ->cpath->handshake_state), cell.payload) < 0) {
861 log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
862 return -1;
865 connection_or_write_cell_to_buf(&cell, circ->n_conn);
867 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
868 circ->state = CIRCUIT_STATE_BUILDING;
869 log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
870 } else {
871 assert(circ->cpath->state == CPATH_STATE_OPEN);
872 assert(circ->state == CIRCUIT_STATE_BUILDING);
873 log_fn(LOG_DEBUG,"starting to send subsequent skin.");
874 r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
875 if (r==1) {
876 /* done building the circuit. whew. */
877 circ->state = CIRCUIT_STATE_OPEN;
878 log_fn(LOG_INFO,"circuit built!");
879 circuit_reset_failure_count();
880 /* Tell any AP connections that have been waiting for a new
881 * circuit that one is ready. */
882 connection_ap_attach_pending();
883 return 0;
884 } else if (r<0) {
885 log_fn(LOG_INFO,"Unable to extend circuit path.");
886 return -1;
888 hop = circ->cpath->prev;
890 memset(&cell, 0, sizeof(cell_t));
891 cell.command = CELL_RELAY;
892 cell.circ_id = circ->n_circ_id;
893 SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_EXTEND);
894 SET_CELL_STREAM_ID(cell, ZERO_STREAM);
895 SET_CELL_RELAY_LENGTH(cell, 6+ONIONSKIN_CHALLENGE_LEN);
897 *(uint32_t*)(cell.payload+RELAY_HEADER_SIZE) = htonl(hop->addr);
898 *(uint16_t*)(cell.payload+RELAY_HEADER_SIZE+4) = htons(hop->port);
899 if(onion_skin_create(router->onion_pkey, &(hop->handshake_state),
900 cell.payload+RELAY_HEADER_SIZE+6) < 0) {
901 log_fn(LOG_WARN,"onion_skin_create failed.");
902 return -1;
905 log_fn(LOG_DEBUG,"Sending extend relay cell.");
906 /* send it to hop->prev, because it will transfer it to a create cell and then send to hop */
907 if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_OUT, hop->prev) < 0) {
908 log_fn(LOG_WARN,"failed to deliver extend cell. Closing.");
909 return -1;
911 hop->state = CPATH_STATE_AWAITING_KEYS;
913 return 0;
916 /* take the 'extend' cell, pull out addr/port plus the onion skin. Make
917 * sure we're connected to the next hop, and pass it the onion skin in
918 * a create cell.
920 int circuit_extend(cell_t *cell, circuit_t *circ) {
921 connection_t *n_conn;
922 int circ_id_type;
923 cell_t newcell;
925 if(circ->n_conn) {
926 log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
927 return -1;
930 circ->n_addr = ntohl(*(uint32_t*)(cell->payload+RELAY_HEADER_SIZE));
931 circ->n_port = ntohs(*(uint16_t*)(cell->payload+RELAY_HEADER_SIZE+4));
933 n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
934 if(!n_conn || n_conn->type != CONN_TYPE_OR) {
935 /* i've disabled making connections through OPs, but it's definitely
936 * possible here. I'm not sure if it would be a bug or a feature. -RD
938 /* note also that this will close circuits where the onion has the same
939 * router twice in a row in the path. i think that's ok. -RD
941 struct in_addr in;
942 in.s_addr = htonl(circ->n_addr);
943 log_fn(LOG_INFO,"Next router (%s:%d) not connected. Closing.", inet_ntoa(in), circ->n_port);
944 connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
945 NULL, 0, NULL);
946 return 0;
949 circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
950 circ->n_port = n_conn->port;
952 circ->n_conn = n_conn;
953 log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
955 circ_id_type = decide_circ_id_type(options.Nickname, n_conn->nickname);
957 log_fn(LOG_DEBUG,"circ_id_type = %u.",circ_id_type);
958 circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
959 if(!circ->n_circ_id) {
960 log_fn(LOG_WARN,"failed to get unique circID.");
961 return -1;
963 log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
965 memset(&newcell, 0, sizeof(cell_t));
966 newcell.command = CELL_CREATE;
967 newcell.circ_id = circ->n_circ_id;
969 memcpy(newcell.payload, cell->payload+RELAY_HEADER_SIZE+6,
970 ONIONSKIN_CHALLENGE_LEN);
972 connection_or_write_cell_to_buf(&newcell, circ->n_conn);
973 return 0;
976 int circuit_finish_handshake(circuit_t *circ, char *reply) {
977 unsigned char iv[16];
978 unsigned char keys[32];
979 crypt_path_t *hop;
981 memset(iv, 0, 16);
983 assert(circ->cpath);
984 if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
985 hop = circ->cpath;
986 else {
987 for(hop=circ->cpath->next;
988 hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
989 hop=hop->next) ;
990 if(hop == circ->cpath) { /* got an extended when we're all done? */
991 log_fn(LOG_WARN,"got extended when circ already built? Closing.");
992 return -1;
995 assert(hop->state == CPATH_STATE_AWAITING_KEYS);
997 if(onion_skin_client_handshake(hop->handshake_state, reply, keys, 32) < 0) {
998 log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
999 return -1;
1002 crypto_dh_free(hop->handshake_state); /* don't need it anymore */
1003 hop->handshake_state = NULL;
1005 log_fn(LOG_DEBUG,"hop %d init cipher forward %u, backward %u.",
1006 (int)hop, (unsigned)*(uint32_t*)keys, (unsigned) *(uint32_t*)(keys+16));
1007 if (!(hop->f_crypto =
1008 crypto_create_init_cipher(CIRCUIT_CIPHER,keys,iv,1))) {
1009 log(LOG_WARN,"forward cipher initialization failed.");
1010 return -1;
1013 if (!(hop->b_crypto =
1014 crypto_create_init_cipher(CIRCUIT_CIPHER,keys+16,iv,0))) {
1015 log(LOG_WARN,"backward cipher initialization failed.");
1016 return -1;
1019 hop->state = CPATH_STATE_OPEN;
1020 log_fn(LOG_INFO,"finished");
1021 return 0;
1024 int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
1025 crypt_path_t *victim;
1026 connection_t *stream;
1028 assert(circ);
1029 assert(layer);
1031 /* XXX Since we don't ask for truncates currently, getting a truncated
1032 * means that a connection broke or an extend failed. For now,
1033 * just give up.
1035 circuit_close(circ);
1036 return 0;
1038 while(layer->next != circ->cpath) {
1039 /* we need to clear out layer->next */
1040 victim = layer->next;
1041 log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
1043 for(stream = circ->p_streams; stream; stream=stream->next_stream) {
1044 if(stream->cpath_layer == victim) {
1045 log_fn(LOG_INFO, "Marking stream %d for close.", *(int*)stream->stream_id);
1046 /* no need to send 'end' relay cells,
1047 * because the other side's already dead
1049 stream->marked_for_close = 1;
1050 stream->has_sent_end = 1;
1054 layer->next = victim->next;
1055 circuit_free_cpath_node(victim);
1058 log_fn(LOG_INFO, "finished");
1059 return 0;
1063 void assert_cpath_layer_ok(const crypt_path_t *cp)
1065 assert(cp->f_crypto);
1066 assert(cp->b_crypto);
1067 assert(cp->addr);
1068 assert(cp->port);
1069 switch(cp->state)
1071 case CPATH_STATE_CLOSED:
1072 case CPATH_STATE_OPEN:
1073 assert(!cp->handshake_state);
1074 break;
1075 case CPATH_STATE_AWAITING_KEYS:
1076 assert(cp->handshake_state);
1077 break;
1078 default:
1079 assert(0);
1081 assert(cp->package_window >= 0);
1082 assert(cp->deliver_window >= 0);
1085 void assert_cpath_ok(const crypt_path_t *cp)
1087 while(cp->prev)
1088 cp = cp->prev;
1090 while(cp->next) {
1091 assert_cpath_layer_ok(cp);
1092 /* layers must be in sequence of: "open* awaiting? closed*" */
1093 if (cp->prev) {
1094 if (cp->prev->state == CPATH_STATE_OPEN) {
1095 assert(cp->state == CPATH_STATE_CLOSED ||
1096 cp->state == CPATH_STATE_AWAITING_KEYS);
1097 } else {
1098 assert(cp->state == CPATH_STATE_CLOSED);
1101 cp = cp->next;
1105 void assert_circuit_ok(const circuit_t *c)
1107 connection_t *conn;
1109 assert(c->n_addr);
1110 assert(c->n_port);
1111 assert(c->n_conn);
1112 assert(c->n_conn->type == CONN_TYPE_OR);
1113 if (c->p_conn)
1114 assert(c->p_conn->type == CONN_TYPE_OR);
1115 for (conn = c->p_streams; conn; conn = conn->next_stream)
1116 assert(c->p_conn->type == CONN_TYPE_EXIT);
1117 for (conn = c->n_streams; conn; conn = conn->next_stream)
1118 assert(conn->type == CONN_TYPE_EXIT);
1120 assert(c->deliver_window >= 0);
1121 assert(c->package_window >= 0);
1122 if (c->state == CIRCUIT_STATE_OPEN) {
1123 if (c->cpath) {
1124 assert(!c->n_crypto);
1125 assert(!c->p_crypto);
1126 } else {
1127 assert(c->n_crypto);
1128 assert(c->p_crypto);
1131 if (c->cpath) {
1132 assert_cpath_ok(c->cpath);
1137 Local Variables:
1138 mode:c
1139 indent-tabs-mode:nil
1140 c-basic-offset:2
1141 End: