circuit.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. extern or_options_t options; /* command-line and config-file options */
  6. static void circuit_free_cpath_node(crypt_path_t *victim);
  7. static circ_id_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type);
  8. unsigned long stats_n_relay_cells_relayed = 0;
  9. unsigned long stats_n_relay_cells_delivered = 0;
  10. /********* START VARIABLES **********/
  11. static circuit_t *global_circuitlist=NULL;
  12. char *circuit_state_to_string[] = {
  13. "doing handshakes", /* 0 */
  14. "processing the onion", /* 1 */
  15. "connecting to firsthop", /* 2 */
  16. "open" /* 3 */
  17. };
  18. /********* END VARIABLES ************/
  19. void circuit_add(circuit_t *circ) {
  20. if(!global_circuitlist) { /* first one */
  21. global_circuitlist = circ;
  22. circ->next = NULL;
  23. } else {
  24. circ->next = global_circuitlist;
  25. global_circuitlist = circ;
  26. }
  27. }
  28. void circuit_remove(circuit_t *circ) {
  29. circuit_t *tmpcirc;
  30. assert(circ && global_circuitlist);
  31. if(global_circuitlist == circ) {
  32. global_circuitlist = global_circuitlist->next;
  33. return;
  34. }
  35. for(tmpcirc = global_circuitlist;tmpcirc->next;tmpcirc = tmpcirc->next) {
  36. if(tmpcirc->next == circ) {
  37. tmpcirc->next = circ->next;
  38. return;
  39. }
  40. }
  41. }
  42. circuit_t *circuit_new(circ_id_t p_circ_id, connection_t *p_conn) {
  43. circuit_t *circ;
  44. circ = tor_malloc_zero(sizeof(circuit_t));
  45. circ->timestamp_created = time(NULL);
  46. circ->p_circ_id = p_circ_id;
  47. circ->p_conn = p_conn;
  48. circ->state = CIRCUIT_STATE_ONIONSKIN_PENDING;
  49. /* CircIDs */
  50. circ->p_circ_id = p_circ_id;
  51. /* circ->n_circ_id remains 0 because we haven't identified the next hop yet */
  52. circ->package_window = CIRCWINDOW_START;
  53. circ->deliver_window = CIRCWINDOW_START;
  54. circuit_add(circ);
  55. return circ;
  56. }
  57. void circuit_free(circuit_t *circ) {
  58. assert(circ);
  59. if (circ->n_crypto)
  60. crypto_free_cipher_env(circ->n_crypto);
  61. if (circ->p_crypto)
  62. crypto_free_cipher_env(circ->p_crypto);
  63. if(circ->build_state)
  64. tor_free(circ->build_state->chosen_exit);
  65. tor_free(circ->build_state);
  66. circuit_free_cpath(circ->cpath);
  67. free(circ);
  68. }
  69. void circuit_free_cpath(crypt_path_t *cpath) {
  70. crypt_path_t *victim, *head=cpath;
  71. if(!cpath)
  72. return;
  73. /* it's a doubly linked list, so we have to notice when we've
  74. * gone through it once. */
  75. while(cpath->next && cpath->next != head) {
  76. victim = cpath;
  77. cpath = victim->next;
  78. circuit_free_cpath_node(victim);
  79. }
  80. circuit_free_cpath_node(cpath);
  81. }
  82. static void circuit_free_cpath_node(crypt_path_t *victim) {
  83. if(victim->f_crypto)
  84. crypto_free_cipher_env(victim->f_crypto);
  85. if(victim->b_crypto)
  86. crypto_free_cipher_env(victim->b_crypto);
  87. if(victim->handshake_state)
  88. crypto_dh_free(victim->handshake_state);
  89. free(victim);
  90. }
  91. /* return 0 if can't get a unique circ_id. */
  92. static circ_id_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type) {
  93. circ_id_t test_circ_id;
  94. uint16_t high_bit;
  95. assert(conn && conn->type == CONN_TYPE_OR);
  96. high_bit = (circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  97. do {
  98. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find an
  99. * circID such that (high_bit|test_circ_id) is not already used. */
  100. /* XXX Will loop forever if all circ_id's in our range are used.
  101. * This matters because it's an external DoS vulnerability. */
  102. test_circ_id = conn->next_circ_id++;
  103. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  104. test_circ_id = 1;
  105. conn->next_circ_id = 2;
  106. }
  107. test_circ_id |= high_bit;
  108. } while(circuit_get_by_circ_id_conn(test_circ_id, conn));
  109. return test_circ_id;
  110. }
  111. circuit_t *circuit_get_by_circ_id_conn(circ_id_t circ_id, connection_t *conn) {
  112. circuit_t *circ;
  113. connection_t *tmpconn;
  114. for(circ=global_circuitlist;circ;circ = circ->next) {
  115. if(circ->p_circ_id == circ_id) {
  116. if(circ->p_conn == conn)
  117. return circ;
  118. for(tmpconn = circ->p_streams; tmpconn; tmpconn = tmpconn->next_stream) {
  119. if(tmpconn == conn)
  120. return circ;
  121. }
  122. }
  123. if(circ->n_circ_id == circ_id) {
  124. if(circ->n_conn == conn)
  125. return circ;
  126. for(tmpconn = circ->n_streams; tmpconn; tmpconn = tmpconn->next_stream) {
  127. if(tmpconn == conn)
  128. return circ;
  129. }
  130. }
  131. }
  132. return NULL;
  133. }
  134. circuit_t *circuit_get_by_conn(connection_t *conn) {
  135. circuit_t *circ;
  136. connection_t *tmpconn;
  137. for(circ=global_circuitlist;circ;circ = circ->next) {
  138. if(circ->p_conn == conn)
  139. return circ;
  140. if(circ->n_conn == conn)
  141. return circ;
  142. for(tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  143. if(tmpconn == conn)
  144. return circ;
  145. for(tmpconn = circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream)
  146. if(tmpconn == conn)
  147. return circ;
  148. }
  149. return NULL;
  150. }
  151. /* Find the newest circ that conn can use, preferably one which is
  152. * dirty and not too old.
  153. * If !conn, return newest.
  154. *
  155. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  156. */
  157. circuit_t *circuit_get_newest(connection_t *conn, int must_be_open) {
  158. circuit_t *circ, *newest=NULL, *leastdirty=NULL;
  159. routerinfo_t *exitrouter;
  160. for(circ=global_circuitlist;circ;circ = circ->next) {
  161. if(!circ->cpath)
  162. continue; /* this circ doesn't start at us */
  163. if(must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
  164. continue; /* ignore non-open circs */
  165. if(conn) {
  166. if(circ->state == CIRCUIT_STATE_OPEN && circ->n_conn) /* open */
  167. exitrouter = router_get_by_addr_port(circ->cpath->prev->addr, circ->cpath->prev->port);
  168. else /* not open */
  169. exitrouter = router_get_by_nickname(circ->build_state->chosen_exit);
  170. if(!exitrouter || connection_ap_can_use_exit(conn, exitrouter) < 0) {
  171. /* can't exit from this router */
  172. continue;
  173. }
  174. }
  175. if(!newest || newest->timestamp_created < circ->timestamp_created) {
  176. assert(circ->n_circ_id);
  177. newest = circ;
  178. }
  179. if(conn && circ->timestamp_dirty &&
  180. (!leastdirty || leastdirty->timestamp_dirty < circ->timestamp_dirty)) {
  181. assert(circ->n_circ_id);
  182. leastdirty = circ;
  183. }
  184. }
  185. if(leastdirty &&
  186. leastdirty->timestamp_dirty+options.NewCircuitPeriod > time(NULL)) {
  187. /* log_fn(LOG_DEBUG,"Choosing in-use circuit %s:%d:%d.",
  188. leastdirty->n_conn->address, leastdirty->n_port, leastdirty->n_circ_id); */
  189. return leastdirty;
  190. }
  191. if(newest) {
  192. /* log_fn(LOG_DEBUG,"Choosing circuit %s:%d:%d.",
  193. newest->n_conn->address, newest->n_port, newest->n_circ_id); */
  194. return newest;
  195. }
  196. return NULL;
  197. }
  198. #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 3
  199. /* circuits that were born at the end of their second might be expired
  200. * after 3.1 seconds; circuits born at the beginning might be expired
  201. * after closer to 4 seconds.
  202. */
  203. /* close all circuits that start at us, aren't open, and were born
  204. * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago */
  205. void circuit_expire_building(void) {
  206. int now = time(NULL);
  207. circuit_t *victim, *circ = global_circuitlist;
  208. while(circ) {
  209. victim = circ;
  210. circ = circ->next;
  211. if(victim->cpath &&
  212. victim->state != CIRCUIT_STATE_OPEN &&
  213. victim->timestamp_created + MIN_SECONDS_BEFORE_EXPIRING_CIRC+1 < now) {
  214. if(victim->n_conn)
  215. log_fn(LOG_INFO,"Abandoning circ %s:%d:%d (state %d:%s)",
  216. victim->n_conn->address, victim->n_port, victim->n_circ_id,
  217. victim->state, circuit_state_to_string[victim->state]);
  218. else
  219. log_fn(LOG_INFO,"Abandoning circ %d (state %d:%s)", victim->n_circ_id,
  220. victim->state, circuit_state_to_string[victim->state]);
  221. circuit_close(victim);
  222. }
  223. }
  224. }
  225. /* count the number of circs starting at us that aren't open */
  226. int circuit_count_building(void) {
  227. circuit_t *circ;
  228. int num=0;
  229. for(circ=global_circuitlist;circ;circ = circ->next) {
  230. if(circ->cpath && circ->state != CIRCUIT_STATE_OPEN)
  231. num++;
  232. }
  233. return num;
  234. }
  235. int circuit_deliver_relay_cell(cell_t *cell, circuit_t *circ,
  236. int cell_direction, crypt_path_t *layer_hint) {
  237. connection_t *conn=NULL;
  238. char recognized=0;
  239. char buf[1+CELL_PAYLOAD_SIZE];
  240. assert(cell && circ);
  241. assert(cell_direction == CELL_DIRECTION_OUT || cell_direction == CELL_DIRECTION_IN);
  242. buf[0] = cell->length;
  243. memcpy(buf+1, cell->payload, CELL_PAYLOAD_SIZE);
  244. log_fn(LOG_DEBUG,"direction %d, streamid %d before crypt.", cell_direction, *(int*)(cell->payload+1));
  245. if(relay_crypt(circ, buf, 1+CELL_PAYLOAD_SIZE, cell_direction, &layer_hint, &recognized, &conn) < 0) {
  246. log_fn(LOG_WARN,"relay crypt failed. Dropping connection.");
  247. return -1;
  248. }
  249. cell->length = buf[0];
  250. memcpy(cell->payload, buf+1, CELL_PAYLOAD_SIZE);
  251. if(recognized) {
  252. if(cell_direction == CELL_DIRECTION_OUT) {
  253. ++stats_n_relay_cells_delivered;
  254. log_fn(LOG_DEBUG,"Sending to exit.");
  255. if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_EXIT, NULL) < 0) {
  256. log_fn(LOG_WARN,"connection_edge_process_relay_cell (at exit) failed.");
  257. return -1;
  258. }
  259. }
  260. if(cell_direction == CELL_DIRECTION_IN) {
  261. ++stats_n_relay_cells_delivered;
  262. log_fn(LOG_DEBUG,"Sending to AP.");
  263. if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_AP, layer_hint) < 0) {
  264. log_fn(LOG_WARN,"connection_edge_process_relay_cell (at AP) failed.");
  265. return -1;
  266. }
  267. }
  268. return 0;
  269. }
  270. /* not recognized. pass it on. */
  271. if(cell_direction == CELL_DIRECTION_OUT)
  272. conn = circ->n_conn;
  273. else
  274. conn = circ->p_conn;
  275. if(!conn) {
  276. log_fn(LOG_INFO,"Didn't recognize cell (%d), but circ stops here! Dropping.",
  277. *(int *)(cell->payload+1));
  278. return 0;
  279. }
  280. log_fn(LOG_DEBUG,"Passing on unrecognized cell.");
  281. ++stats_n_relay_cells_relayed;
  282. connection_or_write_cell_to_buf(cell, conn);
  283. return 0;
  284. }
  285. int relay_crypt(circuit_t *circ, char *in, int inlen, char cell_direction,
  286. crypt_path_t **layer_hint, char *recognized, connection_t **conn) {
  287. crypt_path_t *thishop;
  288. char out[256];
  289. assert(circ && in && recognized && conn);
  290. assert(inlen < 256);
  291. if(cell_direction == CELL_DIRECTION_IN) {
  292. if(circ->cpath) { /* we're at the beginning of the circuit. We'll want to do layered crypts. */
  293. thishop = circ->cpath;
  294. if(thishop->state != CPATH_STATE_OPEN) {
  295. log_fn(LOG_WARN,"Relay cell before first created cell?");
  296. return -1;
  297. }
  298. do { /* Remember: cpath is in forward order, that is, first hop first. */
  299. assert(thishop);
  300. log_fn(LOG_DEBUG,"before decrypt: %d",*(int*)(in+2));
  301. /* decrypt */
  302. if(crypto_cipher_decrypt(thishop->b_crypto, in, inlen, out)) {
  303. log_fn(LOG_WARN,"Error performing onion decryption: %s", crypto_perror());
  304. return -1;
  305. }
  306. memcpy(in,out,inlen);
  307. log_fn(LOG_DEBUG,"after decrypt: %d",*(int*)(in+2));
  308. if( (*recognized = relay_check_recognized(circ, cell_direction, in+2, conn))) {
  309. *layer_hint = thishop;
  310. return 0;
  311. }
  312. thishop = thishop->next;
  313. } while(thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
  314. log_fn(LOG_INFO,"in-cell at OP not recognized. Dropping.");
  315. return 0;
  316. } else { /* we're in the middle. Just one crypt. */
  317. log_fn(LOG_DEBUG,"before encrypt: %d",*(int*)(in+2));
  318. if(crypto_cipher_encrypt(circ->p_crypto, in, inlen, out)) {
  319. log_fn(LOG_WARN,"Onion encryption failed for circID %u: %s",
  320. circ->p_circ_id, crypto_perror());
  321. return -1;
  322. }
  323. memcpy(in,out,inlen);
  324. log_fn(LOG_DEBUG,"after encrypt: %d",*(int*)(in+2));
  325. log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
  326. /* don't check for recognized. only the OP can recognize a stream on the way back. */
  327. }
  328. } else if(cell_direction == CELL_DIRECTION_OUT) {
  329. if(circ->cpath) { /* we're at the beginning of the circuit. We'll want to do layered crypts. */
  330. thishop = *layer_hint; /* we already know which layer, from when we package_raw_inbuf'ed */
  331. /* moving from last to first hop */
  332. do {
  333. assert(thishop);
  334. log_fn(LOG_DEBUG,"before encrypt: %d",*(int*)(in+2));
  335. if(crypto_cipher_encrypt(thishop->f_crypto, in, inlen, out)) {
  336. log_fn(LOG_WARN,"Error performing encryption: %s", crypto_perror());
  337. return -1;
  338. }
  339. memcpy(in,out,inlen);
  340. log_fn(LOG_DEBUG,"after encrypt: %d",*(int*)(in+2));
  341. thishop = thishop->prev;
  342. } while(thishop != circ->cpath->prev);
  343. } else { /* we're in the middle. Just one crypt. */
  344. if(crypto_cipher_decrypt(circ->n_crypto,in, inlen, out)) {
  345. log_fn(LOG_WARN,"Decryption failed for circID %u: %s",
  346. circ->n_circ_id, crypto_perror());
  347. return -1;
  348. }
  349. memcpy(in,out,inlen);
  350. if( (*recognized = relay_check_recognized(circ, cell_direction, in+2, conn)))
  351. return 0;
  352. }
  353. } else {
  354. log_fn(LOG_ERR,"unknown cell direction %d.", cell_direction);
  355. assert(0);
  356. }
  357. return 0;
  358. }
  359. int relay_check_recognized(circuit_t *circ, int cell_direction, char *stream, connection_t **conn) {
  360. /* FIXME can optimize by passing thishop in */
  361. connection_t *tmpconn;
  362. if(!memcmp(stream,ZERO_STREAM,STREAM_ID_SIZE)) {
  363. log_fn(LOG_DEBUG,"It's the zero stream. Recognized.");
  364. return 1; /* the zero stream is always recognized */
  365. }
  366. log_fn(LOG_DEBUG,"not the zero stream.");
  367. if(cell_direction == CELL_DIRECTION_OUT)
  368. tmpconn = circ->n_streams;
  369. else
  370. tmpconn = circ->p_streams;
  371. if(!tmpconn) {
  372. log_fn(LOG_DEBUG,"No conns. Not recognized.");
  373. return 0;
  374. }
  375. for( ; tmpconn; tmpconn=tmpconn->next_stream) {
  376. if(!memcmp(stream,tmpconn->stream_id, STREAM_ID_SIZE)) {
  377. log_fn(LOG_DEBUG,"recognized stream %d.", *(int*)stream);
  378. *conn = tmpconn;
  379. return 1;
  380. }
  381. log_fn(LOG_DEBUG,"considered stream %d, not it.",*(int*)tmpconn->stream_id);
  382. }
  383. log_fn(LOG_DEBUG,"Didn't recognize on this iteration of decryption.");
  384. return 0;
  385. }
  386. void circuit_resume_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
  387. connection_t *conn;
  388. assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
  389. log_fn(LOG_DEBUG,"resuming");
  390. if(edge_type == EDGE_EXIT)
  391. conn = circ->n_streams;
  392. else
  393. conn = circ->p_streams;
  394. for( ; conn; conn=conn->next_stream) {
  395. if((edge_type == EDGE_EXIT && conn->package_window > 0) ||
  396. (edge_type == EDGE_AP && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
  397. connection_start_reading(conn);
  398. connection_edge_package_raw_inbuf(conn); /* handle whatever might still be on the inbuf */
  399. /* If the circuit won't accept any more data, return without looking
  400. * at any more of the streams. Any connections that should be stopped
  401. * have already been stopped by connection_edge_package_raw_inbuf. */
  402. if(circuit_consider_stop_edge_reading(circ, edge_type, layer_hint))
  403. return;
  404. }
  405. }
  406. }
  407. /* returns 1 if the window is empty, else 0. If it's empty, tell edge conns to stop reading. */
  408. int circuit_consider_stop_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
  409. connection_t *conn = NULL;
  410. assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
  411. assert(edge_type == EDGE_EXIT || layer_hint);
  412. log_fn(LOG_DEBUG,"considering");
  413. if(edge_type == EDGE_EXIT && circ->package_window <= 0)
  414. conn = circ->n_streams;
  415. else if(edge_type == EDGE_AP && layer_hint->package_window <= 0)
  416. conn = circ->p_streams;
  417. else
  418. return 0;
  419. for( ; conn; conn=conn->next_stream)
  420. if(!layer_hint || conn->cpath_layer == layer_hint)
  421. connection_stop_reading(conn);
  422. log_fn(LOG_DEBUG,"yes. stopped.");
  423. return 1;
  424. }
  425. int circuit_consider_sending_sendme(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
  426. cell_t cell;
  427. assert(circ);
  428. memset(&cell, 0, sizeof(cell_t));
  429. cell.command = CELL_RELAY;
  430. SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_SENDME);
  431. SET_CELL_STREAM_ID(cell, ZERO_STREAM);
  432. cell.length = RELAY_HEADER_SIZE;
  433. if(edge_type == EDGE_AP) { /* i'm the AP */
  434. cell.circ_id = circ->n_circ_id;
  435. while(layer_hint->deliver_window < CIRCWINDOW_START-CIRCWINDOW_INCREMENT) {
  436. log_fn(LOG_DEBUG,"deliver_window %d, Queueing sendme forward.", layer_hint->deliver_window);
  437. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  438. if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_OUT, layer_hint) < 0) {
  439. log_fn(LOG_WARN,"At AP: circuit_deliver_relay_cell failed.");
  440. return -1;
  441. }
  442. }
  443. } else if(edge_type == EDGE_EXIT) { /* i'm the exit */
  444. cell.circ_id = circ->p_circ_id;
  445. while(circ->deliver_window < CIRCWINDOW_START-CIRCWINDOW_INCREMENT) {
  446. log_fn(LOG_DEBUG,"deliver_window %d, Queueing sendme back.", circ->deliver_window);
  447. circ->deliver_window += CIRCWINDOW_INCREMENT;
  448. if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_IN, layer_hint) < 0) {
  449. log_fn(LOG_WARN,"At exit: circuit_deliver_relay_cell failed.");
  450. return -1;
  451. }
  452. }
  453. }
  454. return 0;
  455. }
  456. void circuit_close(circuit_t *circ) {
  457. connection_t *conn;
  458. assert(circ);
  459. circuit_remove(circ);
  460. if(circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
  461. onion_pending_remove(circ);
  462. }
  463. if(circ->n_conn)
  464. connection_send_destroy(circ->n_circ_id, circ->n_conn);
  465. for(conn=circ->n_streams; conn; conn=conn->next_stream) {
  466. connection_send_destroy(circ->n_circ_id, conn);
  467. }
  468. if(circ->p_conn)
  469. connection_send_destroy(circ->n_circ_id, circ->p_conn);
  470. for(conn=circ->p_streams; conn; conn=conn->next_stream) {
  471. connection_send_destroy(circ->p_circ_id, conn);
  472. }
  473. if (circ->state != CIRCUIT_STATE_OPEN && circ->cpath) {
  474. /* If we never built the circuit, note it as a failure. */
  475. circuit_increment_failure_count();
  476. }
  477. circuit_free(circ);
  478. }
  479. void circuit_about_to_close_connection(connection_t *conn) {
  480. /* send destroys for all circuits using conn */
  481. /* currently, we assume it's too late to flush conn's buf here.
  482. * down the road, maybe we'll consider that eof doesn't mean can't-write
  483. */
  484. circuit_t *circ;
  485. connection_t *prevconn;
  486. switch(conn->type) {
  487. case CONN_TYPE_OR:
  488. /* We must close all the circuits on it. */
  489. while((circ = circuit_get_by_conn(conn))) {
  490. if(circ->n_conn == conn) /* it's closing in front of us */
  491. circ->n_conn = NULL;
  492. if(circ->p_conn == conn) /* it's closing behind us */
  493. circ->p_conn = NULL;
  494. circuit_close(circ);
  495. }
  496. return;
  497. case CONN_TYPE_AP:
  498. case CONN_TYPE_EXIT:
  499. /* It's an edge conn. Need to remove it from the linked list of
  500. * conn's for this circuit. Confirm that 'end' relay command has
  501. * been sent. But don't kill the circuit.
  502. */
  503. circ = circuit_get_by_conn(conn);
  504. if(!circ)
  505. return;
  506. if(!conn->has_sent_end) {
  507. log_fn(LOG_INFO,"Edge connection hasn't sent end yet? Bug.");
  508. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  509. }
  510. if(conn == circ->p_streams) {
  511. circ->p_streams = conn->next_stream;
  512. return;
  513. }
  514. if(conn == circ->n_streams) {
  515. circ->n_streams = conn->next_stream;
  516. return;
  517. }
  518. for(prevconn = circ->p_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
  519. if(prevconn && prevconn->next_stream) {
  520. prevconn->next_stream = conn->next_stream;
  521. return;
  522. }
  523. for(prevconn = circ->n_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
  524. if(prevconn && prevconn->next_stream) {
  525. prevconn->next_stream = conn->next_stream;
  526. return;
  527. }
  528. log_fn(LOG_ERR,"edge conn not in circuit's list?");
  529. assert(0); /* should never get here */
  530. } /* end switch */
  531. }
  532. void circuit_dump_details(int severity, circuit_t *circ, int poll_index,
  533. char *type, int this_circid, int other_circid) {
  534. struct crypt_path_t *hop;
  535. log(severity,"Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d",
  536. poll_index, type, this_circid, other_circid, circ->state,
  537. circuit_state_to_string[circ->state], (int)circ->timestamp_created);
  538. if(circ->cpath) { /* circ starts at this node */
  539. if(circ->state == CIRCUIT_STATE_BUILDING)
  540. log(severity,"Building: desired len %d, planned exit node %s.",
  541. circ->build_state->desired_path_len, circ->build_state->chosen_exit);
  542. for(hop=circ->cpath;hop->next != circ->cpath; hop=hop->next)
  543. log(severity,"hop: state %d, addr %d, port %d", hop->state, hop->addr, hop->port);
  544. }
  545. }
  546. void circuit_dump_by_conn(connection_t *conn, int severity) {
  547. circuit_t *circ;
  548. connection_t *tmpconn;
  549. for(circ=global_circuitlist;circ;circ = circ->next) {
  550. if(circ->p_conn == conn)
  551. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  552. circ->p_circ_id, circ->n_circ_id);
  553. for(tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  554. if(tmpconn == conn) {
  555. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  556. circ->p_circ_id, circ->n_circ_id);
  557. }
  558. }
  559. if(circ->n_conn == conn)
  560. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  561. circ->n_circ_id, circ->p_circ_id);
  562. for(tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  563. if(tmpconn == conn) {
  564. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  565. circ->n_circ_id, circ->p_circ_id);
  566. }
  567. }
  568. }
  569. }
  570. void circuit_expire_unused_circuits(void) {
  571. circuit_t *circ, *tmpcirc;
  572. time_t now = time(NULL);
  573. circ = global_circuitlist;
  574. while(circ) {
  575. tmpcirc = circ;
  576. circ = circ->next;
  577. if(tmpcirc->timestamp_dirty &&
  578. tmpcirc->timestamp_dirty + options.NewCircuitPeriod < now &&
  579. !tmpcirc->p_conn && !tmpcirc->p_streams) {
  580. log_fn(LOG_DEBUG,"Closing n_circ_id %d",tmpcirc->n_circ_id);
  581. circuit_close(tmpcirc);
  582. }
  583. }
  584. }
  585. /* Number of consecutive failures so far; should only be touched by
  586. * circuit_launch_new and circuit_*_failure_count.
  587. */
  588. static int n_circuit_failures = 0;
  589. /* Return -1 if you aren't going to try to make a circuit, 0 if you did try. */
  590. int circuit_launch_new(void) {
  591. if(!options.SocksPort) /* we're not an application proxy. no need for circuits. */
  592. return -1;
  593. if(n_circuit_failures > 5) /* too many failed circs in a row. don't try. */
  594. return -1;
  595. /* try a circ. if it fails, circuit_close will increment n_circuit_failures */
  596. circuit_establish_circuit();
  597. return 0;
  598. }
  599. void circuit_increment_failure_count(void) {
  600. ++n_circuit_failures;
  601. }
  602. void circuit_reset_failure_count(void) {
  603. n_circuit_failures = 0;
  604. }
  605. int circuit_establish_circuit(void) {
  606. routerinfo_t *firsthop;
  607. connection_t *n_conn;
  608. circuit_t *circ;
  609. circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
  610. circ->state = CIRCUIT_STATE_OR_WAIT;
  611. circ->build_state = onion_new_cpath_build_state();
  612. if (! circ->build_state) {
  613. log_fn(LOG_INFO,"Generating cpath length failed.");
  614. circuit_close(circ);
  615. return -1;
  616. }
  617. onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop);
  618. if(!circ->cpath) {
  619. log_fn(LOG_INFO,"Generating first cpath hop failed.");
  620. circuit_close(circ);
  621. return -1;
  622. }
  623. /* now see if we're already connected to the first OR in 'route' */
  624. log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
  625. firsthop->address,firsthop->or_port);
  626. n_conn = connection_twin_get_by_addr_port(firsthop->addr,firsthop->or_port);
  627. if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
  628. circ->n_addr = firsthop->addr;
  629. circ->n_port = firsthop->or_port;
  630. if(options.ORPort) { /* we would be connected if he were up. and he's not. */
  631. log_fn(LOG_INFO,"Route's firsthop isn't connected.");
  632. circuit_close(circ);
  633. return -1;
  634. }
  635. if(!n_conn) { /* launch the connection */
  636. n_conn = connection_or_connect(firsthop);
  637. if(!n_conn) { /* connect failed, forget the whole thing */
  638. log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
  639. circuit_close(circ);
  640. return -1;
  641. }
  642. }
  643. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  644. return 0; /* return success. The onion/circuit/etc will be taken care of automatically
  645. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  646. */
  647. } else { /* it (or a twin) is already open. use it. */
  648. circ->n_addr = n_conn->addr;
  649. circ->n_port = n_conn->port;
  650. circ->n_conn = n_conn;
  651. log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
  652. if(circuit_send_next_onion_skin(circ) < 0) {
  653. log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
  654. circuit_close(circ);
  655. return -1;
  656. }
  657. }
  658. return 0;
  659. }
  660. /* find circuits that are waiting on me, if any, and get them to send the onion */
  661. void circuit_n_conn_open(connection_t *or_conn) {
  662. circuit_t *circ;
  663. for(circ=global_circuitlist;circ;circ = circ->next) {
  664. if(circ->cpath && circ->n_addr == or_conn->addr && circ->n_port == or_conn->port) {
  665. assert(circ->state == CIRCUIT_STATE_OR_WAIT);
  666. log_fn(LOG_DEBUG,"Found circ %d, sending onion skin.", circ->n_circ_id);
  667. circ->n_conn = or_conn;
  668. if(circuit_send_next_onion_skin(circ) < 0) {
  669. log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
  670. circuit_close(circ);
  671. continue;
  672. /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
  673. }
  674. }
  675. }
  676. }
  677. int circuit_send_next_onion_skin(circuit_t *circ) {
  678. cell_t cell;
  679. crypt_path_t *hop;
  680. routerinfo_t *router;
  681. int r;
  682. int circ_id_type;
  683. assert(circ && circ->cpath);
  684. if(circ->cpath->state == CPATH_STATE_CLOSED) {
  685. assert(circ->n_conn && circ->n_conn->type == CONN_TYPE_OR);
  686. log_fn(LOG_DEBUG,"First skin; sending create cell.");
  687. circ_id_type = decide_circ_id_type(options.Nickname,
  688. circ->n_conn->nickname);
  689. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
  690. memset(&cell, 0, sizeof(cell_t));
  691. cell.command = CELL_CREATE;
  692. cell.circ_id = circ->n_circ_id;
  693. cell.length = DH_ONIONSKIN_LEN;
  694. if(onion_skin_create(circ->n_conn->onion_pkey, &(circ->cpath->handshake_state), cell.payload) < 0) {
  695. log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
  696. return -1;
  697. }
  698. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  699. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  700. circ->state = CIRCUIT_STATE_BUILDING;
  701. log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
  702. } else {
  703. assert(circ->cpath->state == CPATH_STATE_OPEN);
  704. assert(circ->state == CIRCUIT_STATE_BUILDING);
  705. log_fn(LOG_DEBUG,"starting to send subsequent skin.");
  706. r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
  707. if (r==1) {
  708. /* done building the circuit. whew. */
  709. circ->state = CIRCUIT_STATE_OPEN;
  710. log_fn(LOG_INFO,"circuit built!");
  711. circuit_reset_failure_count();
  712. /* Tell any AP connections that have been waiting for a new
  713. * circuit that one is ready. */
  714. connection_ap_attach_pending();
  715. return 0;
  716. } else if (r<0) {
  717. log_fn(LOG_INFO,"Unable to extend circuit path.");
  718. return -1;
  719. }
  720. hop = circ->cpath->prev;
  721. memset(&cell, 0, sizeof(cell_t));
  722. cell.command = CELL_RELAY;
  723. cell.circ_id = circ->n_circ_id;
  724. SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_EXTEND);
  725. SET_CELL_STREAM_ID(cell, ZERO_STREAM);
  726. cell.length = RELAY_HEADER_SIZE + 6 + DH_ONIONSKIN_LEN;
  727. *(uint32_t*)(cell.payload+RELAY_HEADER_SIZE) = htonl(hop->addr);
  728. *(uint16_t*)(cell.payload+RELAY_HEADER_SIZE+4) = htons(hop->port);
  729. if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), cell.payload+RELAY_HEADER_SIZE+6) < 0) {
  730. log_fn(LOG_WARN,"onion_skin_create failed.");
  731. return -1;
  732. }
  733. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  734. /* send it to hop->prev, because it will transfer it to a create cell and then send to hop */
  735. if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_OUT, hop->prev) < 0) {
  736. log_fn(LOG_WARN,"failed to deliver extend cell. Closing.");
  737. return -1;
  738. }
  739. hop->state = CPATH_STATE_AWAITING_KEYS;
  740. }
  741. return 0;
  742. }
  743. /* take the 'extend' cell, pull out addr/port plus the onion skin. Make
  744. * sure we're connected to the next hop, and pass it the onion skin in
  745. * a create cell.
  746. */
  747. int circuit_extend(cell_t *cell, circuit_t *circ) {
  748. connection_t *n_conn;
  749. int circ_id_type;
  750. cell_t newcell;
  751. if(circ->n_conn) {
  752. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  753. return -1;
  754. }
  755. circ->n_addr = ntohl(*(uint32_t*)(cell->payload+RELAY_HEADER_SIZE));
  756. circ->n_port = ntohs(*(uint16_t*)(cell->payload+RELAY_HEADER_SIZE+4));
  757. n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
  758. if(!n_conn || n_conn->type != CONN_TYPE_OR) {
  759. /* i've disabled making connections through OPs, but it's definitely
  760. * possible here. I'm not sure if it would be a bug or a feature. -RD
  761. */
  762. /* note also that this will close circuits where the onion has the same
  763. * router twice in a row in the path. i think that's ok. -RD
  764. */
  765. struct in_addr in;
  766. in.s_addr = htonl(circ->n_addr);
  767. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Closing.", inet_ntoa(in), circ->n_port);
  768. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  769. NULL, 0, NULL);
  770. return 0;
  771. }
  772. circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
  773. circ->n_port = n_conn->port;
  774. circ->n_conn = n_conn;
  775. log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
  776. circ_id_type = decide_circ_id_type(options.Nickname, n_conn->nickname);
  777. log_fn(LOG_DEBUG,"circ_id_type = %u.",circ_id_type);
  778. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
  779. if(!circ->n_circ_id) {
  780. log_fn(LOG_WARN,"failed to get unique circID.");
  781. return -1;
  782. }
  783. log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
  784. memset(&newcell, 0, sizeof(cell_t));
  785. newcell.command = CELL_CREATE;
  786. newcell.circ_id = circ->n_circ_id;
  787. newcell.length = DH_ONIONSKIN_LEN;
  788. memcpy(newcell.payload, cell->payload+RELAY_HEADER_SIZE+6, DH_ONIONSKIN_LEN);
  789. connection_or_write_cell_to_buf(&newcell, circ->n_conn);
  790. return 0;
  791. }
  792. int circuit_finish_handshake(circuit_t *circ, char *reply) {
  793. unsigned char iv[16];
  794. unsigned char keys[32];
  795. crypt_path_t *hop;
  796. memset(iv, 0, 16);
  797. assert(circ->cpath);
  798. if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  799. hop = circ->cpath;
  800. else {
  801. for(hop=circ->cpath->next;
  802. hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
  803. hop=hop->next) ;
  804. if(hop == circ->cpath) { /* got an extended when we're all done? */
  805. log_fn(LOG_WARN,"got extended when circ already built? Closing.");
  806. return -1;
  807. }
  808. }
  809. assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  810. if(onion_skin_client_handshake(hop->handshake_state, reply, keys, 32) < 0) {
  811. log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
  812. return -1;
  813. }
  814. crypto_dh_free(hop->handshake_state); /* don't need it anymore */
  815. hop->handshake_state = NULL;
  816. log_fn(LOG_DEBUG,"hop %d init cipher forward %d, backward %d.", (uint32_t)hop, *(uint32_t*)keys, *(uint32_t*)(keys+16));
  817. if (!(hop->f_crypto =
  818. crypto_create_init_cipher(CIRCUIT_CIPHER,keys,iv,1))) {
  819. log(LOG_WARN,"forward cipher initialization failed.");
  820. return -1;
  821. }
  822. if (!(hop->b_crypto =
  823. crypto_create_init_cipher(CIRCUIT_CIPHER,keys+16,iv,0))) {
  824. log(LOG_WARN,"backward cipher initialization failed.");
  825. return -1;
  826. }
  827. hop->state = CPATH_STATE_OPEN;
  828. log_fn(LOG_INFO,"finished");
  829. return 0;
  830. }
  831. int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
  832. crypt_path_t *victim;
  833. connection_t *stream;
  834. assert(circ);
  835. assert(layer);
  836. while(layer->next != circ->cpath) {
  837. /* we need to clear out layer->next */
  838. victim = layer->next;
  839. log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
  840. for(stream = circ->p_streams; stream; stream=stream->next_stream) {
  841. if(stream->cpath_layer == victim) {
  842. log_fn(LOG_INFO, "Marking stream %d for close.", *(int*)stream->stream_id);
  843. /* no need to send 'end' relay cells,
  844. * because the other side's already dead
  845. */
  846. stream->marked_for_close = 1;
  847. stream->has_sent_end = 1;
  848. }
  849. }
  850. layer->next = victim->next;
  851. circuit_free_cpath_node(victim);
  852. }
  853. log_fn(LOG_INFO, "finished");
  854. return 0;
  855. }
  856. void assert_cpath_layer_ok(const crypt_path_t *cp)
  857. {
  858. assert(cp->f_crypto);
  859. assert(cp->b_crypto);
  860. assert(cp->addr);
  861. assert(cp->port);
  862. switch(cp->state)
  863. {
  864. case CPATH_STATE_CLOSED:
  865. case CPATH_STATE_OPEN:
  866. assert(!cp->handshake_state);
  867. break;
  868. case CPATH_STATE_AWAITING_KEYS:
  869. assert(cp->handshake_state);
  870. break;
  871. default:
  872. assert(0);
  873. }
  874. assert(cp->package_window >= 0);
  875. assert(cp->deliver_window >= 0);
  876. }
  877. void assert_cpath_ok(const crypt_path_t *cp)
  878. {
  879. while(cp->prev)
  880. cp = cp->prev;
  881. while(cp->next) {
  882. assert_cpath_layer_ok(cp);
  883. /* layers must be in sequence of: "open* awaiting? closed*" */
  884. if (cp->prev) {
  885. if (cp->prev->state == CPATH_STATE_OPEN) {
  886. assert(cp->state == CPATH_STATE_CLOSED ||
  887. cp->state == CPATH_STATE_AWAITING_KEYS);
  888. } else {
  889. assert(cp->state == CPATH_STATE_CLOSED);
  890. }
  891. }
  892. cp = cp->next;
  893. }
  894. }
  895. void assert_circuit_ok(const circuit_t *c)
  896. {
  897. connection_t *conn;
  898. assert(c->n_addr);
  899. assert(c->n_port);
  900. assert(c->n_conn);
  901. assert(c->n_conn->type == CONN_TYPE_OR);
  902. if (c->p_conn)
  903. assert(c->p_conn->type == CONN_TYPE_OR);
  904. for (conn = c->p_streams; conn; conn = conn->next_stream)
  905. assert(c->p_conn->type == CONN_TYPE_EXIT);
  906. for (conn = c->n_streams; conn; conn = conn->next_stream)
  907. assert(conn->type == CONN_TYPE_EXIT);
  908. assert(c->deliver_window >= 0);
  909. assert(c->package_window >= 0);
  910. if (c->state == CIRCUIT_STATE_OPEN) {
  911. if (c->cpath) {
  912. assert(!c->n_crypto);
  913. assert(!c->p_crypto);
  914. } else {
  915. assert(c->n_crypto);
  916. assert(c->p_crypto);
  917. }
  918. }
  919. if (c->cpath) {
  920. assert_cpath_ok(c->cpath);
  921. }
  922. }
  923. /*
  924. Local Variables:
  925. mode:c
  926. indent-tabs-mode:nil
  927. c-basic-offset:2
  928. End:
  929. */