Remove a possible source of error in circID picking.
[tor.git] / src / or / circuit.c
blobb1a1a6a616731772ff908ba3014d586d2f088eff
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_by_conn(connection_t *conn, int severity) {
601 circuit_t *circ;
602 connection_t *tmpconn;
604 for(circ=global_circuitlist;circ;circ = circ->next) {
605 if(circ->p_conn == conn)
606 log(severity, "Conn %d has App-ward circuit: circID %d (other side %d), state %d (%s)",
607 conn->poll_index, circ->p_circ_id, circ->n_circ_id, circ->state, circuit_state_to_string[circ->state]);
608 for(tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
609 if(tmpconn == conn) {
610 log(severity,"Conn %d has App-ward circuit: circID %d (other side %d), state %d (%s)",
611 conn->poll_index, circ->p_circ_id, circ->n_circ_id, circ->state, circuit_state_to_string[circ->state]);
614 if(circ->n_conn == conn)
615 log(severity,"Conn %d has Exit-ward circuit: circID %d (other side %d), state %d (%s)",
616 conn->poll_index, circ->n_circ_id, circ->p_circ_id, circ->state, circuit_state_to_string[circ->state]);
617 for(tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
618 if(tmpconn == conn) {
619 log(severity,"Conn %d has Exit-ward circuit: circID %d (other side %d), state %d (%s)",
620 conn->poll_index, circ->n_circ_id, circ->p_circ_id, circ->state, circuit_state_to_string[circ->state]);
626 void circuit_expire_unused_circuits(void) {
627 circuit_t *circ, *tmpcirc;
628 time_t now = time(NULL);
630 circ = global_circuitlist;
631 while(circ) {
632 tmpcirc = circ;
633 circ = circ->next;
634 if(tmpcirc->timestamp_dirty &&
635 tmpcirc->timestamp_dirty + options.NewCircuitPeriod < now &&
636 !tmpcirc->p_conn && !tmpcirc->p_streams) {
637 log_fn(LOG_DEBUG,"Closing n_circ_id %d",tmpcirc->n_circ_id);
638 circuit_close(tmpcirc);
643 /* failure_status code: negative means reset failures to 0. Other values mean
644 * add that value to the current number of failures, then if we don't have too
645 * many failures on record, try to make a new circuit.
647 * Return -1 if you aren't going to try to make a circuit, 0 if you did try.
649 int circuit_launch_new(int failure_status) {
650 static int failures=0;
652 if(!options.SocksPort) /* we're not an application proxy. no need for circuits. */
653 return -1;
655 if(failure_status == -1) { /* I was called because a circuit succeeded */
656 failures = 0;
657 return -1;
660 failures += failure_status;
662 if(failures > 5) {
663 return -1;
666 if(circuit_establish_circuit() < 0) {
667 failures++;
668 return 0;
671 failures = 0;
672 return 0;
675 int circuit_establish_circuit(void) {
676 routerinfo_t *firsthop;
677 connection_t *n_conn;
678 circuit_t *circ;
680 circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
681 circ->state = CIRCUIT_STATE_OR_WAIT;
682 circ->build_state = onion_new_cpath_build_state();
684 if (! circ->build_state) {
685 log_fn(LOG_INFO,"Generating cpath length failed.");
686 circuit_close(circ);
687 return -1;
690 onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop);
691 if(!circ->cpath) {
692 log_fn(LOG_INFO,"Generating first cpath hop failed.");
693 circuit_close(circ);
694 return -1;
697 /* now see if we're already connected to the first OR in 'route' */
699 log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
700 firsthop->address,firsthop->or_port);
701 n_conn = connection_twin_get_by_addr_port(firsthop->addr,firsthop->or_port);
702 if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
703 circ->n_addr = firsthop->addr;
704 circ->n_port = firsthop->or_port;
705 if(options.OnionRouter) { /* we would be connected if he were up. but he's not. */
706 log_fn(LOG_INFO,"Route's firsthop isn't connected.");
707 circuit_close(circ);
708 return -1;
711 if(!n_conn) { /* launch the connection */
712 n_conn = connection_or_connect(firsthop);
713 if(!n_conn) { /* connect failed, forget the whole thing */
714 log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
715 circuit_close(circ);
716 return -1;
720 log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
721 return 0; /* return success. The onion/circuit/etc will be taken care of automatically
722 * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
724 } else { /* it (or a twin) is already open. use it. */
725 circ->n_addr = n_conn->addr;
726 circ->n_port = n_conn->port;
727 circ->n_conn = n_conn;
728 log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
729 if(circuit_send_next_onion_skin(circ) < 0) {
730 log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
731 circuit_close(circ);
732 return -1;
735 return 0;
738 /* find circuits that are waiting on me, if any, and get them to send the onion */
739 void circuit_n_conn_open(connection_t *or_conn) {
740 circuit_t *circ;
742 log_fn(LOG_DEBUG,"Starting.");
743 circ = circuit_enumerate_by_naddr_nport(NULL, or_conn->addr, or_conn->port);
744 for(;;) {
745 if(!circ)
746 return;
748 assert(circ->state == CIRCUIT_STATE_OR_WAIT);
749 log_fn(LOG_DEBUG,"Found circ, sending onion skin.");
750 circ->n_conn = or_conn;
751 if(circuit_send_next_onion_skin(circ) < 0) {
752 log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
753 circuit_close(circ);
754 return; /* FIXME will want to try the other circuits too? */
756 circ = circuit_enumerate_by_naddr_nport(circ, or_conn->addr, or_conn->port);
760 int circuit_send_next_onion_skin(circuit_t *circ) {
761 cell_t cell;
762 crypt_path_t *hop;
763 routerinfo_t *router;
764 int r;
766 assert(circ && circ->cpath);
768 if(circ->cpath->state == CPATH_STATE_CLOSED) {
769 assert(circ->n_conn && circ->n_conn->type == CONN_TYPE_OR);
771 log_fn(LOG_DEBUG,"First skin; sending create cell.");
772 circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, CIRC_ID_TYPE_BOTH);
774 memset(&cell, 0, sizeof(cell_t));
775 cell.command = CELL_CREATE;
776 cell.circ_id = circ->n_circ_id;
777 cell.length = DH_ONIONSKIN_LEN;
779 if(onion_skin_create(circ->n_conn->onion_pkey, &(circ->cpath->handshake_state), cell.payload) < 0) {
780 log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
781 return -1;
784 connection_or_write_cell_to_buf(&cell, circ->n_conn);
786 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
787 circ->state = CIRCUIT_STATE_BUILDING;
788 log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
789 } else {
790 assert(circ->cpath->state == CPATH_STATE_OPEN);
791 assert(circ->state == CIRCUIT_STATE_BUILDING);
792 log_fn(LOG_DEBUG,"starting to send subsequent skin.");
793 r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
794 if (r==1) {
795 /* done building the circuit. whew. */
796 circ->state = CIRCUIT_STATE_OPEN;
797 log_fn(LOG_INFO,"circuit built!");
798 /* Tell any AP connections that have been waiting for a new
799 * circuit that one is ready. */
800 connection_ap_attach_pending();
801 return 0;
802 } else if (r<0) {
803 log_fn(LOG_WARN,"Unable to extend circuit path.");
804 return -1;
806 hop = circ->cpath->prev;
808 memset(&cell, 0, sizeof(cell_t));
809 cell.command = CELL_RELAY;
810 cell.circ_id = circ->n_circ_id;
811 SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_EXTEND);
812 SET_CELL_STREAM_ID(cell, ZERO_STREAM);
814 cell.length = RELAY_HEADER_SIZE + 6 + DH_ONIONSKIN_LEN;
815 *(uint32_t*)(cell.payload+RELAY_HEADER_SIZE) = htonl(hop->addr);
816 *(uint16_t*)(cell.payload+RELAY_HEADER_SIZE+4) = htons(hop->port);
817 if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), cell.payload+RELAY_HEADER_SIZE+6) < 0) {
818 log_fn(LOG_WARN,"onion_skin_create failed.");
819 return -1;
822 log_fn(LOG_DEBUG,"Sending extend relay cell.");
823 /* send it to hop->prev, because it will transfer it to a create cell and then send to hop */
824 if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_OUT, hop->prev) < 0) {
825 log_fn(LOG_WARN,"failed to deliver extend cell. Closing.");
826 return -1;
828 hop->state = CPATH_STATE_AWAITING_KEYS;
830 return 0;
833 /* take the 'extend' cell, pull out addr/port plus the onion skin. Make
834 * sure we're connected to the next hop, and pass it the onion skin in
835 * a create cell.
837 int circuit_extend(cell_t *cell, circuit_t *circ) {
838 connection_t *n_conn;
839 int circ_id_type;
840 cell_t newcell;
842 if(circ->n_conn) {
843 log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
844 return -1;
847 circ->n_addr = ntohl(*(uint32_t*)(cell->payload+RELAY_HEADER_SIZE));
848 circ->n_port = ntohs(*(uint16_t*)(cell->payload+RELAY_HEADER_SIZE+4));
850 n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
851 if(!n_conn || n_conn->type != CONN_TYPE_OR) {
852 /* i've disabled making connections through OPs, but it's definitely
853 * possible here. I'm not sure if it would be a bug or a feature. -RD
855 /* note also that this will close circuits where the onion has the same
856 * router twice in a row in the path. i think that's ok. -RD
858 struct in_addr in;
859 in.s_addr = htonl(circ->n_addr);
860 log_fn(LOG_DEBUG,"Next router (%s:%d) not connected. Closing.", inet_ntoa(in), circ->n_port);
861 /* XXX later we should fail more gracefully here, like with a 'truncated' */
862 return -1;
865 circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
866 circ->n_port = n_conn->port;
868 circ->n_conn = n_conn;
869 log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
871 circ_id_type = decide_circ_id_type(options.Nickname, n_conn->nickname);
873 log_fn(LOG_DEBUG,"circ_id_type = %u.",circ_id_type);
874 circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
875 if(!circ->n_circ_id) {
876 log_fn(LOG_WARN,"failed to get unique circID.");
877 return -1;
879 log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
881 memset(&newcell, 0, sizeof(cell_t));
882 newcell.command = CELL_CREATE;
883 newcell.circ_id = circ->n_circ_id;
884 newcell.length = DH_ONIONSKIN_LEN;
886 memcpy(newcell.payload, cell->payload+RELAY_HEADER_SIZE+6, DH_ONIONSKIN_LEN);
888 connection_or_write_cell_to_buf(&newcell, circ->n_conn);
889 return 0;
892 int circuit_finish_handshake(circuit_t *circ, char *reply) {
893 unsigned char iv[16];
894 unsigned char keys[32];
895 crypt_path_t *hop;
897 memset(iv, 0, 16);
899 assert(circ->cpath);
900 if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
901 hop = circ->cpath;
902 else {
903 for(hop=circ->cpath->next;
904 hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
905 hop=hop->next) ;
906 if(hop == circ->cpath) { /* got an extended when we're all done? */
907 log_fn(LOG_WARN,"got extended when circ already built? Closing.");
908 return -1;
911 assert(hop->state == CPATH_STATE_AWAITING_KEYS);
913 if(onion_skin_client_handshake(hop->handshake_state, reply, keys, 32) < 0) {
914 log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
915 return -1;
918 crypto_dh_free(hop->handshake_state); /* don't need it anymore */
919 hop->handshake_state = NULL;
921 log_fn(LOG_DEBUG,"hop %d init cipher forward %d, backward %d.", (uint32_t)hop, *(uint32_t*)keys, *(uint32_t*)(keys+16));
922 if (!(hop->f_crypto =
923 crypto_create_init_cipher(CIRCUIT_CIPHER,keys,iv,1))) {
924 log(LOG_WARN,"forward cipher initialization failed.");
925 return -1;
928 if (!(hop->b_crypto =
929 crypto_create_init_cipher(CIRCUIT_CIPHER,keys+16,iv,0))) {
930 log(LOG_WARN,"backward cipher initialization failed.");
931 return -1;
934 hop->state = CPATH_STATE_OPEN;
935 log_fn(LOG_INFO,"finished");
936 return 0;
939 int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
940 crypt_path_t *victim;
941 connection_t *stream;
943 assert(circ);
944 assert(layer);
946 while(layer->next != circ->cpath) {
947 /* we need to clear out layer->next */
948 victim = layer->next;
949 log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
951 for(stream = circ->p_streams; stream; stream=stream->next_stream) {
952 if(stream->cpath_layer == victim) {
953 log_fn(LOG_INFO, "Marking stream %d for close.", *(int*)stream->stream_id);
954 /* no need to send 'end' relay cells,
955 * because the other side's already dead
957 stream->marked_for_close = 1;
958 stream->has_sent_end = 1;
962 layer->next = victim->next;
963 circuit_free_cpath_node(victim);
966 log_fn(LOG_INFO, "finished");
967 return 0;
971 void assert_cpath_layer_ok(const crypt_path_t *cp)
973 assert(cp->f_crypto);
974 assert(cp->b_crypto);
975 assert(cp->addr);
976 assert(cp->port);
977 switch(cp->state)
979 case CPATH_STATE_CLOSED:
980 case CPATH_STATE_OPEN:
981 assert(!cp->handshake_state);
982 break;
983 case CPATH_STATE_AWAITING_KEYS:
984 assert(cp->handshake_state);
985 break;
986 default:
987 assert(0);
989 assert(cp->package_window >= 0);
990 assert(cp->deliver_window >= 0);
993 void assert_cpath_ok(const crypt_path_t *cp)
995 while(cp->prev)
996 cp = cp->prev;
998 while(cp->next) {
999 assert_cpath_layer_ok(cp);
1000 /* layers must be in sequence of: "open* awaiting? closed*" */
1001 if (cp->prev) {
1002 if (cp->prev->state == CPATH_STATE_OPEN) {
1003 assert(cp->state == CPATH_STATE_CLOSED ||
1004 cp->state == CPATH_STATE_AWAITING_KEYS);
1005 } else {
1006 assert(cp->state == CPATH_STATE_CLOSED);
1009 cp = cp->next;
1013 void assert_circuit_ok(const circuit_t *c)
1015 connection_t *conn;
1017 assert(c->n_addr);
1018 assert(c->n_port);
1019 assert(c->n_conn);
1020 assert(c->n_conn->type == CONN_TYPE_OR);
1021 if (c->p_conn)
1022 assert(c->p_conn->type == CONN_TYPE_OR);
1023 for (conn = c->p_streams; conn; conn = conn->next_stream)
1024 assert(c->p_conn->type == CONN_TYPE_EXIT);
1025 for (conn = c->n_streams; conn; conn = conn->next_stream)
1026 assert(conn->type == CONN_TYPE_EXIT);
1028 assert(c->deliver_window >= 0);
1029 assert(c->package_window >= 0);
1030 if (c->state == CIRCUIT_STATE_OPEN) {
1031 if (c->cpath) {
1032 assert(!c->n_crypto);
1033 assert(!c->p_crypto);
1034 } else {
1035 assert(c->n_crypto);
1036 assert(c->p_crypto);
1039 if (c->cpath) {
1040 assert_cpath_ok(c->cpath);
1045 Local Variables:
1046 mode:c
1047 indent-tabs-mode:nil
1048 c-basic-offset:2
1049 End: