Fix possible bug in circID selection when building circuits on combination OP/OR...
[tor.git] / src / or / circuit.c
blob47911f2dde3dc85da31e875e1258bc2e2b0133dc
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 = (circuit_t *)tor_malloc(sizeof(circuit_t));
62 memset(circ,0,sizeof(circuit_t)); /* zero it out */
64 circ->timestamp_created = time(NULL);
66 circ->p_circ_id = p_circ_id;
67 circ->p_conn = p_conn;
69 circ->state = CIRCUIT_STATE_ONIONSKIN_PENDING;
71 /* CircIDs */
72 circ->p_circ_id = p_circ_id;
73 /* circ->n_circ_id remains 0 because we haven't identified the next hop yet */
75 circ->package_window = CIRCWINDOW_START;
76 circ->deliver_window = CIRCWINDOW_START;
78 circuit_add(circ);
80 return circ;
83 void circuit_free(circuit_t *circ) {
84 assert(circ);
85 if (circ->n_crypto)
86 crypto_free_cipher_env(circ->n_crypto);
87 if (circ->p_crypto)
88 crypto_free_cipher_env(circ->p_crypto);
89 if(circ->build_state)
90 tor_free(circ->build_state->chosen_exit);
91 tor_free(circ->build_state);
92 circuit_free_cpath(circ->cpath);
93 free(circ);
96 void circuit_free_cpath(crypt_path_t *cpath) {
97 crypt_path_t *victim, *head=cpath;
99 if(!cpath)
100 return;
102 /* it's a doubly linked list, so we have to notice when we've
103 * gone through it once. */
104 while(cpath->next && cpath->next != head) {
105 victim = cpath;
106 cpath = victim->next;
107 circuit_free_cpath_node(victim);
110 circuit_free_cpath_node(cpath);
113 static void circuit_free_cpath_node(crypt_path_t *victim) {
114 if(victim->f_crypto)
115 crypto_free_cipher_env(victim->f_crypto);
116 if(victim->b_crypto)
117 crypto_free_cipher_env(victim->b_crypto);
118 if(victim->handshake_state)
119 crypto_dh_free(victim->handshake_state);
120 free(victim);
123 /* return 0 if can't get a unique circ_id. */
124 static circ_id_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type) {
125 circ_id_t test_circ_id;
126 uint16_t high_bit;
127 assert(conn && conn->type == CONN_TYPE_OR);
129 high_bit = (circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
130 do {
131 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find an
132 * circID such that (high_bit|test_circ_id) is not already used. */
133 /* XXX Will loop forever if all circ_id's in our range are used.
134 * This matters because it's an external DoS vulnerability. */
135 test_circ_id = conn->next_circ_id++;
136 if (test_circ_id == 0 || test_circ_id >= 1<<15) {
137 test_circ_id = 1;
138 conn->next_circ_id = 2;
140 test_circ_id |= high_bit;
141 } while(circuit_get_by_circ_id_conn(test_circ_id, conn));
142 return test_circ_id;
145 circuit_t *circuit_enumerate_by_naddr_nport(circuit_t *circ, uint32_t naddr, uint16_t nport) {
147 if(!circ) /* use circ if it's defined, else start from the beginning */
148 circ = global_circuitlist;
149 else
150 circ = circ->next;
152 for( ; circ; circ = circ->next) {
153 if(circ->n_addr == naddr && circ->n_port == nport)
154 return circ;
156 return NULL;
159 circuit_t *circuit_get_by_circ_id_conn(circ_id_t circ_id, connection_t *conn) {
160 circuit_t *circ;
161 connection_t *tmpconn;
163 for(circ=global_circuitlist;circ;circ = circ->next) {
164 if(circ->p_circ_id == circ_id) {
165 if(circ->p_conn == conn)
166 return circ;
167 for(tmpconn = circ->p_streams; tmpconn; tmpconn = tmpconn->next_stream) {
168 if(tmpconn == conn)
169 return circ;
172 if(circ->n_circ_id == circ_id) {
173 if(circ->n_conn == conn)
174 return circ;
175 for(tmpconn = circ->n_streams; tmpconn; tmpconn = tmpconn->next_stream) {
176 if(tmpconn == conn)
177 return circ;
181 return NULL;
184 circuit_t *circuit_get_by_conn(connection_t *conn) {
185 circuit_t *circ;
186 connection_t *tmpconn;
188 for(circ=global_circuitlist;circ;circ = circ->next) {
189 if(circ->p_conn == conn)
190 return circ;
191 if(circ->n_conn == conn)
192 return circ;
193 for(tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
194 if(tmpconn == conn)
195 return circ;
196 for(tmpconn = circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream)
197 if(tmpconn == conn)
198 return circ;
200 return NULL;
203 /* Find the newest circ that conn can use, preferably one which is
204 * dirty and not too old.
205 * If !conn, return newest.
207 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
209 circuit_t *circuit_get_newest(connection_t *conn, int must_be_open) {
210 circuit_t *circ, *newest=NULL, *leastdirty=NULL;
211 routerinfo_t *exitrouter;
213 for(circ=global_circuitlist;circ;circ = circ->next) {
214 if(!circ->cpath)
215 continue; /* this circ doesn't start at us */
216 if(must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
217 continue; /* ignore non-open circs */
218 if(conn) {
219 if(circ->state == CIRCUIT_STATE_OPEN && circ->n_conn) /* open */
220 exitrouter = router_get_by_addr_port(circ->cpath->prev->addr, circ->cpath->prev->port);
221 else /* not open */
222 exitrouter = router_get_by_nickname(circ->build_state->chosen_exit);
223 if(!exitrouter || connection_ap_can_use_exit(conn, exitrouter) < 0) {
224 /* can't exit from this router */
225 continue;
228 if(!newest || newest->timestamp_created < circ->timestamp_created) {
229 assert(circ->n_circ_id);
230 newest = circ;
232 if(conn && circ->timestamp_dirty &&
233 (!leastdirty || leastdirty->timestamp_dirty < circ->timestamp_dirty)) {
234 assert(circ->n_circ_id);
235 leastdirty = circ;
239 if(leastdirty &&
240 leastdirty->timestamp_dirty+options.NewCircuitPeriod > time(NULL)) {
241 log_fn(LOG_DEBUG,"Choosing in-use circuit %s:%d:%d.",
242 leastdirty->n_conn->address, leastdirty->n_port, leastdirty->n_circ_id);
243 return leastdirty;
245 if(newest) {
246 log_fn(LOG_DEBUG,"Choosing circuit %s:%d:%d.",
247 newest->n_conn->address, newest->n_port, newest->n_circ_id);
248 return newest;
250 return NULL;
253 int circuit_deliver_relay_cell(cell_t *cell, circuit_t *circ,
254 int cell_direction, crypt_path_t *layer_hint) {
255 connection_t *conn=NULL;
256 char recognized=0;
257 char buf[256];
259 assert(cell && circ);
260 assert(cell_direction == CELL_DIRECTION_OUT || cell_direction == CELL_DIRECTION_IN);
262 buf[0] = cell->length;
263 memcpy(buf+1, cell->payload, CELL_PAYLOAD_SIZE);
265 log_fn(LOG_DEBUG,"direction %d, streamid %d before crypt.", cell_direction, *(int*)(cell->payload+1));
267 if(relay_crypt(circ, buf, 1+CELL_PAYLOAD_SIZE, cell_direction, &layer_hint, &recognized, &conn) < 0) {
268 log_fn(LOG_WARN,"relay crypt failed. Dropping connection.");
269 return -1;
272 cell->length = buf[0];
273 memcpy(cell->payload, buf+1, CELL_PAYLOAD_SIZE);
275 if(recognized) {
276 if(cell_direction == CELL_DIRECTION_OUT) {
277 ++stats_n_relay_cells_delivered;
278 log_fn(LOG_DEBUG,"Sending to exit.");
279 if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_EXIT, NULL) < 0) {
280 log_fn(LOG_WARN,"connection_edge_process_relay_cell (at exit) failed.");
281 return -1;
284 if(cell_direction == CELL_DIRECTION_IN) {
285 ++stats_n_relay_cells_delivered;
286 log_fn(LOG_DEBUG,"Sending to AP.");
287 if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_AP, layer_hint) < 0) {
288 log_fn(LOG_WARN,"connection_edge_process_relay_cell (at AP) failed.");
289 return -1;
292 return 0;
295 /* not recognized. pass it on. */
296 if(cell_direction == CELL_DIRECTION_OUT)
297 conn = circ->n_conn;
298 else
299 conn = circ->p_conn;
301 if(!conn) {
302 log_fn(LOG_INFO,"Didn't recognize cell (%d), but circ stops here! Dropping.",
303 *(int *)(cell->payload+1));
304 return 0;
307 log_fn(LOG_DEBUG,"Passing on unrecognized cell.");
308 ++stats_n_relay_cells_relayed;
309 connection_or_write_cell_to_buf(cell, conn);
310 return 0;
313 int relay_crypt(circuit_t *circ, char *in, int inlen, char cell_direction,
314 crypt_path_t **layer_hint, char *recognized, connection_t **conn) {
315 crypt_path_t *thishop;
316 char out[256];
318 assert(circ && in && recognized && conn);
320 assert(inlen < 256);
322 if(cell_direction == CELL_DIRECTION_IN) {
323 if(circ->cpath) { /* we're at the beginning of the circuit. We'll want to do layered crypts. */
324 thishop = circ->cpath;
325 if(thishop->state != CPATH_STATE_OPEN) {
326 log_fn(LOG_WARN,"Relay cell before first created cell?");
327 return -1;
329 do { /* Remember: cpath is in forward order, that is, first hop first. */
330 assert(thishop);
332 log_fn(LOG_DEBUG,"before decrypt: %d",*(int*)(in+2));
333 /* decrypt */
334 if(crypto_cipher_decrypt(thishop->b_crypto, in, inlen, out)) {
335 log_fn(LOG_WARN,"Error performing onion decryption: %s", crypto_perror());
336 return -1;
338 memcpy(in,out,inlen);
339 log_fn(LOG_DEBUG,"after decrypt: %d",*(int*)(in+2));
341 if( (*recognized = relay_check_recognized(circ, cell_direction, in+2, conn))) {
342 *layer_hint = thishop;
343 return 0;
346 thishop = thishop->next;
347 } while(thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
348 log_fn(LOG_INFO,"in-cell at OP not recognized. Dropping.");
349 return 0;
350 } else { /* we're in the middle. Just one crypt. */
352 log_fn(LOG_DEBUG,"before encrypt: %d",*(int*)(in+2));
353 if(crypto_cipher_encrypt(circ->p_crypto, in, inlen, out)) {
354 log_fn(LOG_WARN,"Onion encryption failed for circID %u: %s",
355 circ->p_circ_id, crypto_perror());
356 return -1;
358 memcpy(in,out,inlen);
359 log_fn(LOG_DEBUG,"after encrypt: %d",*(int*)(in+2));
361 log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
362 /* don't check for recognized. only the OP can recognize a stream on the way back. */
365 } else if(cell_direction == CELL_DIRECTION_OUT) {
366 if(circ->cpath) { /* we're at the beginning of the circuit. We'll want to do layered crypts. */
368 thishop = *layer_hint; /* we already know which layer, from when we package_raw_inbuf'ed */
369 /* moving from last to first hop */
370 do {
371 assert(thishop);
373 log_fn(LOG_DEBUG,"before encrypt: %d",*(int*)(in+2));
374 if(crypto_cipher_encrypt(thishop->f_crypto, in, inlen, out)) {
375 log_fn(LOG_WARN,"Error performing encryption: %s", crypto_perror());
376 return -1;
378 memcpy(in,out,inlen);
379 log_fn(LOG_DEBUG,"after encrypt: %d",*(int*)(in+2));
381 thishop = thishop->prev;
382 } while(thishop != circ->cpath->prev);
383 } else { /* we're in the middle. Just one crypt. */
385 if(crypto_cipher_decrypt(circ->n_crypto,in, inlen, out)) {
386 log_fn(LOG_WARN,"Decryption failed for circID %u: %s",
387 circ->n_circ_id, crypto_perror());
388 return -1;
390 memcpy(in,out,inlen);
392 if( (*recognized = relay_check_recognized(circ, cell_direction, in+2, conn)))
393 return 0;
396 } else {
397 log_fn(LOG_ERR,"unknown cell direction %d.", cell_direction);
398 assert(0);
401 return 0;
404 int relay_check_recognized(circuit_t *circ, int cell_direction, char *stream, connection_t **conn) {
405 /* FIXME can optimize by passing thishop in */
406 connection_t *tmpconn;
408 if(!memcmp(stream,ZERO_STREAM,STREAM_ID_SIZE)) {
409 log_fn(LOG_DEBUG,"It's the zero stream. Recognized.");
410 return 1; /* the zero stream is always recognized */
412 log_fn(LOG_DEBUG,"not the zero stream.");
414 if(cell_direction == CELL_DIRECTION_OUT)
415 tmpconn = circ->n_streams;
416 else
417 tmpconn = circ->p_streams;
419 if(!tmpconn) {
420 log_fn(LOG_DEBUG,"No conns. Not recognized.");
421 return 0;
424 for( ; tmpconn; tmpconn=tmpconn->next_stream) {
425 if(!memcmp(stream,tmpconn->stream_id, STREAM_ID_SIZE)) {
426 log_fn(LOG_DEBUG,"recognized stream %d.", *(int*)stream);
427 *conn = tmpconn;
428 return 1;
430 log_fn(LOG_DEBUG,"considered stream %d, not it.",*(int*)tmpconn->stream_id);
433 log_fn(LOG_DEBUG,"Didn't recognize on this iteration of decryption.");
434 return 0;
438 void circuit_resume_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
439 connection_t *conn;
441 assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
443 log_fn(LOG_DEBUG,"resuming");
445 if(edge_type == EDGE_EXIT)
446 conn = circ->n_streams;
447 else
448 conn = circ->p_streams;
450 for( ; conn; conn=conn->next_stream) {
451 if((edge_type == EDGE_EXIT && conn->package_window > 0) ||
452 (edge_type == EDGE_AP && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
453 connection_start_reading(conn);
454 connection_edge_package_raw_inbuf(conn); /* handle whatever might still be on the inbuf */
456 /* If the circuit won't accept any more data, return without looking
457 * at any more of the streams. Any connections that should be stopped
458 * have already been stopped by connection_edge_package_raw_inbuf. */
459 if(circuit_consider_stop_edge_reading(circ, edge_type, layer_hint))
460 return;
465 /* returns 1 if the window is empty, else 0. If it's empty, tell edge conns to stop reading. */
466 int circuit_consider_stop_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
467 connection_t *conn = NULL;
469 assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
470 assert(edge_type == EDGE_EXIT || layer_hint);
472 log_fn(LOG_DEBUG,"considering");
473 if(edge_type == EDGE_EXIT && circ->package_window <= 0)
474 conn = circ->n_streams;
475 else if(edge_type == EDGE_AP && layer_hint->package_window <= 0)
476 conn = circ->p_streams;
477 else
478 return 0;
480 for( ; conn; conn=conn->next_stream)
481 if(!layer_hint || conn->cpath_layer == layer_hint)
482 connection_stop_reading(conn);
484 log_fn(LOG_DEBUG,"yes. stopped.");
485 return 1;
488 int circuit_consider_sending_sendme(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
489 cell_t cell;
491 assert(circ);
493 memset(&cell, 0, sizeof(cell_t));
494 cell.command = CELL_RELAY;
495 SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_SENDME);
496 SET_CELL_STREAM_ID(cell, ZERO_STREAM);
498 cell.length = RELAY_HEADER_SIZE;
499 if(edge_type == EDGE_AP) { /* i'm the AP */
500 cell.circ_id = circ->n_circ_id;
501 while(layer_hint->deliver_window < CIRCWINDOW_START-CIRCWINDOW_INCREMENT) {
502 log_fn(LOG_DEBUG,"deliver_window %d, Queueing sendme forward.", layer_hint->deliver_window);
503 layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
504 if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_OUT, layer_hint) < 0) {
505 log_fn(LOG_WARN,"At AP: circuit_deliver_relay_cell failed.");
506 return -1;
509 } else if(edge_type == EDGE_EXIT) { /* i'm the exit */
510 cell.circ_id = circ->p_circ_id;
511 while(circ->deliver_window < CIRCWINDOW_START-CIRCWINDOW_INCREMENT) {
512 log_fn(LOG_DEBUG,"deliver_window %d, Queueing sendme back.", circ->deliver_window);
513 circ->deliver_window += CIRCWINDOW_INCREMENT;
514 if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_IN, layer_hint) < 0) {
515 log_fn(LOG_WARN,"At exit: circuit_deliver_relay_cell failed.");
516 return -1;
520 return 0;
523 void circuit_close(circuit_t *circ) {
524 connection_t *conn;
526 assert(circ);
527 circuit_remove(circ);
528 if(circ->n_conn)
529 connection_send_destroy(circ->n_circ_id, circ->n_conn);
530 for(conn=circ->n_streams; conn; conn=conn->next_stream) {
531 connection_send_destroy(circ->n_circ_id, conn);
533 if(circ->p_conn)
534 connection_send_destroy(circ->n_circ_id, circ->p_conn);
535 for(conn=circ->p_streams; conn; conn=conn->next_stream) {
536 connection_send_destroy(circ->p_circ_id, conn);
538 circuit_free(circ);
541 void circuit_about_to_close_connection(connection_t *conn) {
542 /* send destroys for all circuits using conn */
543 /* currently, we assume it's too late to flush conn's buf here.
544 * down the road, maybe we'll consider that eof doesn't mean can't-write
546 circuit_t *circ;
547 connection_t *prevconn;
549 switch(conn->type) {
550 case CONN_TYPE_OR:
551 /* We must close all the circuits on it. */
552 while((circ = circuit_get_by_conn(conn))) {
553 if(circ->n_conn == conn) /* it's closing in front of us */
554 circ->n_conn = NULL;
555 if(circ->p_conn == conn) /* it's closing behind us */
556 circ->p_conn = NULL;
557 circuit_close(circ);
559 return;
560 case CONN_TYPE_AP:
561 case CONN_TYPE_EXIT:
563 /* It's an edge conn. Need to remove it from the linked list of
564 * conn's for this circuit. Confirm that 'end' relay command has
565 * been sent. But don't kill the circuit.
568 circ = circuit_get_by_conn(conn);
569 if(!circ)
570 return;
572 if(!conn->has_sent_end) {
573 log_fn(LOG_INFO,"Edge connection hasn't sent end yet? Bug.");
574 connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
577 if(conn == circ->p_streams) {
578 circ->p_streams = conn->next_stream;
579 return;
581 if(conn == circ->n_streams) {
582 circ->n_streams = conn->next_stream;
583 return;
585 for(prevconn = circ->p_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
586 if(prevconn && prevconn->next_stream) {
587 prevconn->next_stream = conn->next_stream;
588 return;
590 for(prevconn = circ->n_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
591 if(prevconn && prevconn->next_stream) {
592 prevconn->next_stream = conn->next_stream;
593 return;
595 log_fn(LOG_ERR,"edge conn not in circuit's list?");
596 assert(0); /* should never get here */
597 } /* end switch */
600 void circuit_dump_details(int severity, circuit_t *circ, int poll_index,
601 char *type, int this_circid, int other_circid) {
602 struct crypt_path_t *hop;
603 log(severity,"Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d",
604 poll_index, type, this_circid, other_circid, circ->state,
605 circuit_state_to_string[circ->state], (int)circ->timestamp_created);
606 if(circ->cpath) { /* circ starts at this node */
607 if(circ->state == CIRCUIT_STATE_BUILDING)
608 log(severity,"Building: desired len %d, planned exit node %s.",
609 circ->build_state->desired_path_len, circ->build_state->chosen_exit);
610 for(hop=circ->cpath;hop->next != circ->cpath; hop=hop->next)
611 log(severity,"hop: state %d, addr %d, port %d", hop->state, hop->addr, hop->port);
615 void circuit_dump_by_conn(connection_t *conn, int severity) {
616 circuit_t *circ;
617 connection_t *tmpconn;
619 for(circ=global_circuitlist;circ;circ = circ->next) {
620 if(circ->p_conn == conn)
621 circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
622 circ->p_circ_id, circ->n_circ_id);
623 for(tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
624 if(tmpconn == conn) {
625 circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
626 circ->p_circ_id, circ->n_circ_id);
629 if(circ->n_conn == conn)
630 circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
631 circ->n_circ_id, circ->p_circ_id);
632 for(tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
633 if(tmpconn == conn) {
634 circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
635 circ->n_circ_id, circ->p_circ_id);
641 void circuit_expire_unused_circuits(void) {
642 circuit_t *circ, *tmpcirc;
643 time_t now = time(NULL);
645 circ = global_circuitlist;
646 while(circ) {
647 tmpcirc = circ;
648 circ = circ->next;
649 if(tmpcirc->timestamp_dirty &&
650 tmpcirc->timestamp_dirty + options.NewCircuitPeriod < now &&
651 !tmpcirc->p_conn && !tmpcirc->p_streams) {
652 log_fn(LOG_DEBUG,"Closing n_circ_id %d",tmpcirc->n_circ_id);
653 circuit_close(tmpcirc);
658 /* failure_status code: negative means reset failures to 0. Other values mean
659 * add that value to the current number of failures, then if we don't have too
660 * many failures on record, try to make a new circuit.
662 * Return -1 if you aren't going to try to make a circuit, 0 if you did try.
664 int circuit_launch_new(int failure_status) {
665 static int failures=0;
667 if(!options.SocksPort) /* we're not an application proxy. no need for circuits. */
668 return -1;
670 if(failure_status == -1) { /* I was called because a circuit succeeded */
671 failures = 0;
672 return -1;
675 failures += failure_status;
677 if(failures > 5) {
678 return -1;
681 if(circuit_establish_circuit() < 0) {
682 failures++;
683 return 0;
686 failures = 0;
687 return 0;
690 int circuit_establish_circuit(void) {
691 routerinfo_t *firsthop;
692 connection_t *n_conn;
693 circuit_t *circ;
695 circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
696 circ->state = CIRCUIT_STATE_OR_WAIT;
697 circ->build_state = onion_new_cpath_build_state();
699 if (! circ->build_state) {
700 log_fn(LOG_INFO,"Generating cpath length failed.");
701 circuit_close(circ);
702 return -1;
705 onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop);
706 if(!circ->cpath) {
707 log_fn(LOG_INFO,"Generating first cpath hop failed.");
708 circuit_close(circ);
709 return -1;
712 /* now see if we're already connected to the first OR in 'route' */
714 log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
715 firsthop->address,firsthop->or_port);
716 n_conn = connection_twin_get_by_addr_port(firsthop->addr,firsthop->or_port);
717 if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
718 circ->n_addr = firsthop->addr;
719 circ->n_port = firsthop->or_port;
720 if(options.OnionRouter) { /* we would be connected if he were up. but he's not. */
721 log_fn(LOG_INFO,"Route's firsthop isn't connected.");
722 circuit_close(circ);
723 return -1;
726 if(!n_conn) { /* launch the connection */
727 n_conn = connection_or_connect(firsthop);
728 if(!n_conn) { /* connect failed, forget the whole thing */
729 log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
730 circuit_close(circ);
731 return -1;
735 log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
736 return 0; /* return success. The onion/circuit/etc will be taken care of automatically
737 * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
739 } else { /* it (or a twin) is already open. use it. */
740 circ->n_addr = n_conn->addr;
741 circ->n_port = n_conn->port;
742 circ->n_conn = n_conn;
743 log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
744 if(circuit_send_next_onion_skin(circ) < 0) {
745 log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
746 circuit_close(circ);
747 return -1;
750 return 0;
753 /* find circuits that are waiting on me, if any, and get them to send the onion */
754 void circuit_n_conn_open(connection_t *or_conn) {
755 circuit_t *circ;
757 log_fn(LOG_DEBUG,"Starting.");
758 circ = circuit_enumerate_by_naddr_nport(NULL, or_conn->addr, or_conn->port);
759 for(;;) {
760 if(!circ)
761 return;
763 assert(circ->state == CIRCUIT_STATE_OR_WAIT);
764 log_fn(LOG_DEBUG,"Found circ, sending onion skin.");
765 circ->n_conn = or_conn;
766 if(circuit_send_next_onion_skin(circ) < 0) {
767 log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
768 circuit_close(circ);
769 return; /* FIXME will want to try the other circuits too? */
771 circ = circuit_enumerate_by_naddr_nport(circ, or_conn->addr, or_conn->port);
775 int circuit_send_next_onion_skin(circuit_t *circ) {
776 cell_t cell;
777 crypt_path_t *hop;
778 routerinfo_t *router;
779 int r;
780 int circ_id_type;
782 assert(circ && circ->cpath);
784 if(circ->cpath->state == CPATH_STATE_CLOSED) {
785 assert(circ->n_conn && circ->n_conn->type == CONN_TYPE_OR);
787 log_fn(LOG_DEBUG,"First skin; sending create cell.");
788 circ_id_type = decide_circ_id_type(options.Nickname,
789 circ->n_conn->nickname);
790 circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
792 memset(&cell, 0, sizeof(cell_t));
793 cell.command = CELL_CREATE;
794 cell.circ_id = circ->n_circ_id;
795 cell.length = DH_ONIONSKIN_LEN;
797 if(onion_skin_create(circ->n_conn->onion_pkey, &(circ->cpath->handshake_state), cell.payload) < 0) {
798 log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
799 return -1;
802 connection_or_write_cell_to_buf(&cell, circ->n_conn);
804 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
805 circ->state = CIRCUIT_STATE_BUILDING;
806 log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
807 } else {
808 assert(circ->cpath->state == CPATH_STATE_OPEN);
809 assert(circ->state == CIRCUIT_STATE_BUILDING);
810 log_fn(LOG_DEBUG,"starting to send subsequent skin.");
811 r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
812 if (r==1) {
813 /* done building the circuit. whew. */
814 circ->state = CIRCUIT_STATE_OPEN;
815 log_fn(LOG_INFO,"circuit built!");
816 /* Tell any AP connections that have been waiting for a new
817 * circuit that one is ready. */
818 connection_ap_attach_pending();
819 return 0;
820 } else if (r<0) {
821 log_fn(LOG_WARN,"Unable to extend circuit path.");
822 return -1;
824 hop = circ->cpath->prev;
826 memset(&cell, 0, sizeof(cell_t));
827 cell.command = CELL_RELAY;
828 cell.circ_id = circ->n_circ_id;
829 SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_EXTEND);
830 SET_CELL_STREAM_ID(cell, ZERO_STREAM);
832 cell.length = RELAY_HEADER_SIZE + 6 + DH_ONIONSKIN_LEN;
833 *(uint32_t*)(cell.payload+RELAY_HEADER_SIZE) = htonl(hop->addr);
834 *(uint16_t*)(cell.payload+RELAY_HEADER_SIZE+4) = htons(hop->port);
835 if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), cell.payload+RELAY_HEADER_SIZE+6) < 0) {
836 log_fn(LOG_WARN,"onion_skin_create failed.");
837 return -1;
840 log_fn(LOG_DEBUG,"Sending extend relay cell.");
841 /* send it to hop->prev, because it will transfer it to a create cell and then send to hop */
842 if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_OUT, hop->prev) < 0) {
843 log_fn(LOG_WARN,"failed to deliver extend cell. Closing.");
844 return -1;
846 hop->state = CPATH_STATE_AWAITING_KEYS;
848 return 0;
851 /* take the 'extend' cell, pull out addr/port plus the onion skin. Make
852 * sure we're connected to the next hop, and pass it the onion skin in
853 * a create cell.
855 int circuit_extend(cell_t *cell, circuit_t *circ) {
856 connection_t *n_conn;
857 int circ_id_type;
858 cell_t newcell;
860 if(circ->n_conn) {
861 log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
862 return -1;
865 circ->n_addr = ntohl(*(uint32_t*)(cell->payload+RELAY_HEADER_SIZE));
866 circ->n_port = ntohs(*(uint16_t*)(cell->payload+RELAY_HEADER_SIZE+4));
868 n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
869 if(!n_conn || n_conn->type != CONN_TYPE_OR) {
870 /* i've disabled making connections through OPs, but it's definitely
871 * possible here. I'm not sure if it would be a bug or a feature. -RD
873 /* note also that this will close circuits where the onion has the same
874 * router twice in a row in the path. i think that's ok. -RD
876 struct in_addr in;
877 in.s_addr = htonl(circ->n_addr);
878 log_fn(LOG_INFO,"Next router (%s:%d) not connected. Closing.", inet_ntoa(in), circ->n_port);
879 connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
880 NULL, 0, NULL);
881 return 0;
884 circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
885 circ->n_port = n_conn->port;
887 circ->n_conn = n_conn;
888 log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
890 circ_id_type = decide_circ_id_type(options.Nickname, n_conn->nickname);
892 log_fn(LOG_DEBUG,"circ_id_type = %u.",circ_id_type);
893 circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
894 if(!circ->n_circ_id) {
895 log_fn(LOG_WARN,"failed to get unique circID.");
896 return -1;
898 log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
900 memset(&newcell, 0, sizeof(cell_t));
901 newcell.command = CELL_CREATE;
902 newcell.circ_id = circ->n_circ_id;
903 newcell.length = DH_ONIONSKIN_LEN;
905 memcpy(newcell.payload, cell->payload+RELAY_HEADER_SIZE+6, DH_ONIONSKIN_LEN);
907 connection_or_write_cell_to_buf(&newcell, circ->n_conn);
908 return 0;
911 int circuit_finish_handshake(circuit_t *circ, char *reply) {
912 unsigned char iv[16];
913 unsigned char keys[32];
914 crypt_path_t *hop;
916 memset(iv, 0, 16);
918 assert(circ->cpath);
919 if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
920 hop = circ->cpath;
921 else {
922 for(hop=circ->cpath->next;
923 hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
924 hop=hop->next) ;
925 if(hop == circ->cpath) { /* got an extended when we're all done? */
926 log_fn(LOG_WARN,"got extended when circ already built? Closing.");
927 return -1;
930 assert(hop->state == CPATH_STATE_AWAITING_KEYS);
932 if(onion_skin_client_handshake(hop->handshake_state, reply, keys, 32) < 0) {
933 log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
934 return -1;
937 crypto_dh_free(hop->handshake_state); /* don't need it anymore */
938 hop->handshake_state = NULL;
940 log_fn(LOG_DEBUG,"hop %d init cipher forward %d, backward %d.", (uint32_t)hop, *(uint32_t*)keys, *(uint32_t*)(keys+16));
941 if (!(hop->f_crypto =
942 crypto_create_init_cipher(CIRCUIT_CIPHER,keys,iv,1))) {
943 log(LOG_WARN,"forward cipher initialization failed.");
944 return -1;
947 if (!(hop->b_crypto =
948 crypto_create_init_cipher(CIRCUIT_CIPHER,keys+16,iv,0))) {
949 log(LOG_WARN,"backward cipher initialization failed.");
950 return -1;
953 hop->state = CPATH_STATE_OPEN;
954 log_fn(LOG_INFO,"finished");
955 return 0;
958 int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
959 crypt_path_t *victim;
960 connection_t *stream;
962 assert(circ);
963 assert(layer);
965 while(layer->next != circ->cpath) {
966 /* we need to clear out layer->next */
967 victim = layer->next;
968 log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
970 for(stream = circ->p_streams; stream; stream=stream->next_stream) {
971 if(stream->cpath_layer == victim) {
972 log_fn(LOG_INFO, "Marking stream %d for close.", *(int*)stream->stream_id);
973 /* no need to send 'end' relay cells,
974 * because the other side's already dead
976 stream->marked_for_close = 1;
977 stream->has_sent_end = 1;
981 layer->next = victim->next;
982 circuit_free_cpath_node(victim);
985 log_fn(LOG_INFO, "finished");
986 return 0;
990 void assert_cpath_layer_ok(const crypt_path_t *cp)
992 assert(cp->f_crypto);
993 assert(cp->b_crypto);
994 assert(cp->addr);
995 assert(cp->port);
996 switch(cp->state)
998 case CPATH_STATE_CLOSED:
999 case CPATH_STATE_OPEN:
1000 assert(!cp->handshake_state);
1001 break;
1002 case CPATH_STATE_AWAITING_KEYS:
1003 assert(cp->handshake_state);
1004 break;
1005 default:
1006 assert(0);
1008 assert(cp->package_window >= 0);
1009 assert(cp->deliver_window >= 0);
1012 void assert_cpath_ok(const crypt_path_t *cp)
1014 while(cp->prev)
1015 cp = cp->prev;
1017 while(cp->next) {
1018 assert_cpath_layer_ok(cp);
1019 /* layers must be in sequence of: "open* awaiting? closed*" */
1020 if (cp->prev) {
1021 if (cp->prev->state == CPATH_STATE_OPEN) {
1022 assert(cp->state == CPATH_STATE_CLOSED ||
1023 cp->state == CPATH_STATE_AWAITING_KEYS);
1024 } else {
1025 assert(cp->state == CPATH_STATE_CLOSED);
1028 cp = cp->next;
1032 void assert_circuit_ok(const circuit_t *c)
1034 connection_t *conn;
1036 assert(c->n_addr);
1037 assert(c->n_port);
1038 assert(c->n_conn);
1039 assert(c->n_conn->type == CONN_TYPE_OR);
1040 if (c->p_conn)
1041 assert(c->p_conn->type == CONN_TYPE_OR);
1042 for (conn = c->p_streams; conn; conn = conn->next_stream)
1043 assert(c->p_conn->type == CONN_TYPE_EXIT);
1044 for (conn = c->n_streams; conn; conn = conn->next_stream)
1045 assert(conn->type == CONN_TYPE_EXIT);
1047 assert(c->deliver_window >= 0);
1048 assert(c->package_window >= 0);
1049 if (c->state == CIRCUIT_STATE_OPEN) {
1050 if (c->cpath) {
1051 assert(!c->n_crypto);
1052 assert(!c->p_crypto);
1053 } else {
1054 assert(c->n_crypto);
1055 assert(c->p_crypto);
1058 if (c->cpath) {
1059 assert_cpath_ok(c->cpath);
1064 Local Variables:
1065 mode:c
1066 indent-tabs-mode:nil
1067 c-basic-offset:2
1068 End: