circuit.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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 int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  7. crypt_path_t **layer_hint, char *recognized);
  8. static connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction);
  9. static void circuit_free_cpath_node(crypt_path_t *victim);
  10. static uint16_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type);
  11. static void circuit_rep_hist_note_result(circuit_t *circ);
  12. unsigned long stats_n_relay_cells_relayed = 0;
  13. unsigned long stats_n_relay_cells_delivered = 0;
  14. /********* START VARIABLES **********/
  15. static int circuitlist_len=0;
  16. static circuit_t *global_circuitlist=NULL;
  17. char *circuit_state_to_string[] = {
  18. "doing handshakes", /* 0 */
  19. "processing the onion", /* 1 */
  20. "connecting to firsthop", /* 2 */
  21. "open" /* 3 */
  22. };
  23. /********* END VARIABLES ************/
  24. void circuit_add(circuit_t *circ) {
  25. if(!global_circuitlist) { /* first one */
  26. global_circuitlist = circ;
  27. circ->next = NULL;
  28. } else {
  29. circ->next = global_circuitlist;
  30. global_circuitlist = circ;
  31. }
  32. ++circuitlist_len;
  33. }
  34. void circuit_remove(circuit_t *circ) {
  35. circuit_t *tmpcirc;
  36. assert(circ && global_circuitlist);
  37. if(global_circuitlist == circ) {
  38. global_circuitlist = global_circuitlist->next;
  39. --circuitlist_len;
  40. return;
  41. }
  42. for(tmpcirc = global_circuitlist;tmpcirc->next;tmpcirc = tmpcirc->next) {
  43. if(tmpcirc->next == circ) {
  44. tmpcirc->next = circ->next;
  45. --circuitlist_len;
  46. return;
  47. }
  48. }
  49. }
  50. void circuit_close_all_marked()
  51. {
  52. circuit_t *tmp,*m;
  53. while (global_circuitlist && global_circuitlist->marked_for_close) {
  54. tmp = global_circuitlist->next;
  55. circuit_free(global_circuitlist);
  56. global_circuitlist = tmp;
  57. }
  58. tmp = global_circuitlist;
  59. while (tmp && tmp->next) {
  60. if (tmp->next->marked_for_close) {
  61. m = tmp->next->next;
  62. circuit_free(tmp->next);
  63. tmp->next = m;
  64. /* Need to check new tmp->next; don't advance tmp. */
  65. } else {
  66. /* Advance tmp. */
  67. tmp = tmp->next;
  68. }
  69. }
  70. }
  71. circuit_t *circuit_new(uint16_t p_circ_id, connection_t *p_conn) {
  72. circuit_t *circ;
  73. circ = tor_malloc_zero(sizeof(circuit_t));
  74. circ->magic = CIRCUIT_MAGIC;
  75. circ->timestamp_created = time(NULL);
  76. circ->p_circ_id = p_circ_id;
  77. circ->p_conn = p_conn;
  78. circ->state = CIRCUIT_STATE_ONIONSKIN_PENDING;
  79. /* CircIDs */
  80. circ->p_circ_id = p_circ_id;
  81. /* circ->n_circ_id remains 0 because we haven't identified the next hop yet */
  82. circ->package_window = CIRCWINDOW_START;
  83. circ->deliver_window = CIRCWINDOW_START;
  84. circ->next_stream_id = crypto_pseudo_rand_int(1<<16);
  85. circuit_add(circ);
  86. return circ;
  87. }
  88. void circuit_free(circuit_t *circ) {
  89. assert(circ);
  90. assert(circ->magic == CIRCUIT_MAGIC);
  91. if (circ->n_crypto)
  92. crypto_free_cipher_env(circ->n_crypto);
  93. if (circ->p_crypto)
  94. crypto_free_cipher_env(circ->p_crypto);
  95. if (circ->n_digest)
  96. crypto_free_digest_env(circ->n_digest);
  97. if (circ->p_digest)
  98. crypto_free_digest_env(circ->p_digest);
  99. if(circ->build_state)
  100. tor_free(circ->build_state->chosen_exit);
  101. tor_free(circ->build_state);
  102. circuit_free_cpath(circ->cpath);
  103. memset(circ, 0xAA, sizeof(circuit_t)); /* poison memory */
  104. free(circ);
  105. }
  106. void circuit_free_cpath(crypt_path_t *cpath) {
  107. crypt_path_t *victim, *head=cpath;
  108. if(!cpath)
  109. return;
  110. /* it's a doubly linked list, so we have to notice when we've
  111. * gone through it once. */
  112. while(cpath->next && cpath->next != head) {
  113. victim = cpath;
  114. cpath = victim->next;
  115. circuit_free_cpath_node(victim);
  116. }
  117. circuit_free_cpath_node(cpath);
  118. }
  119. static void circuit_free_cpath_node(crypt_path_t *victim) {
  120. if(victim->f_crypto)
  121. crypto_free_cipher_env(victim->f_crypto);
  122. if(victim->b_crypto)
  123. crypto_free_cipher_env(victim->b_crypto);
  124. if(victim->f_digest)
  125. crypto_free_digest_env(victim->f_digest);
  126. if(victim->b_digest)
  127. crypto_free_digest_env(victim->b_digest);
  128. if(victim->handshake_state)
  129. crypto_dh_free(victim->handshake_state);
  130. free(victim);
  131. }
  132. /* return 0 if can't get a unique circ_id. */
  133. static uint16_t get_unique_circ_id_by_conn(connection_t *conn, int circ_id_type) {
  134. uint16_t test_circ_id;
  135. int attempts=0;
  136. uint16_t high_bit;
  137. assert(conn && conn->type == CONN_TYPE_OR);
  138. high_bit = (circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  139. do {
  140. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  141. * circID such that (high_bit|test_circ_id) is not already used. */
  142. test_circ_id = conn->next_circ_id++;
  143. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  144. test_circ_id = 1;
  145. conn->next_circ_id = 2;
  146. }
  147. if(++attempts > 1<<15) {
  148. /* Make sure we don't loop forever if all circ_id's are used. This
  149. * matters because it's an external DoS vulnerability.
  150. */
  151. log_fn(LOG_WARN,"No unused circ IDs. Failing.");
  152. return 0;
  153. }
  154. test_circ_id |= high_bit;
  155. } while(circuit_get_by_circ_id_conn(test_circ_id, conn));
  156. return test_circ_id;
  157. }
  158. circuit_t *circuit_get_by_circ_id_conn(uint16_t circ_id, connection_t *conn) {
  159. circuit_t *circ;
  160. connection_t *tmpconn;
  161. for(circ=global_circuitlist;circ;circ = circ->next) {
  162. if (circ->marked_for_close)
  163. continue;
  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;
  170. }
  171. }
  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;
  178. }
  179. }
  180. }
  181. return NULL;
  182. }
  183. circuit_t *circuit_get_by_conn(connection_t *conn) {
  184. circuit_t *circ;
  185. connection_t *tmpconn;
  186. for(circ=global_circuitlist;circ;circ = circ->next) {
  187. if (circ->marked_for_close)
  188. continue;
  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;
  199. }
  200. return NULL;
  201. }
  202. /* Find the newest circ that conn can use, preferably one which is
  203. * dirty. Circ must not be too old.
  204. * If !conn, return newest.
  205. *
  206. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  207. */
  208. circuit_t *circuit_get_newest(connection_t *conn, int must_be_open) {
  209. circuit_t *circ, *newest=NULL, *leastdirty=NULL;
  210. routerinfo_t *exitrouter;
  211. for(circ=global_circuitlist;circ;circ = circ->next) {
  212. if(!circ->cpath)
  213. continue; /* this circ doesn't start at us */
  214. if(must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
  215. continue; /* ignore non-open circs */
  216. if (circ->marked_for_close)
  217. continue;
  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) == ADDR_POLICY_REJECTED) {
  224. /* can't exit from this router */
  225. continue;
  226. }
  227. }
  228. if(!newest || newest->timestamp_created < circ->timestamp_created) {
  229. newest = circ;
  230. }
  231. if(conn && circ->timestamp_dirty &&
  232. (!leastdirty || leastdirty->timestamp_dirty < circ->timestamp_dirty)) {
  233. leastdirty = circ;
  234. }
  235. }
  236. if(leastdirty &&
  237. leastdirty->timestamp_dirty+options.NewCircuitPeriod > time(NULL)) {
  238. /* log_fn(LOG_DEBUG,"Choosing in-use circuit %s:%d:%d.",
  239. leastdirty->n_conn->address, leastdirty->n_port, leastdirty->n_circ_id); */
  240. return leastdirty;
  241. }
  242. if(newest) {
  243. /* log_fn(LOG_DEBUG,"Choosing circuit %s:%d:%d.",
  244. newest->n_conn->address, newest->n_port, newest->n_circ_id); */
  245. return newest;
  246. }
  247. return NULL;
  248. }
  249. #define MIN_SECONDS_BEFORE_EXPIRING_CIRC 10
  250. /* circuits that were born at the end of their second might be expired
  251. * after 10.1 seconds; circuits born at the beginning might be expired
  252. * after closer to 11 seconds.
  253. */
  254. /* close all circuits that start at us, aren't open, and were born
  255. * at least MIN_SECONDS_BEFORE_EXPIRING_CIRC seconds ago */
  256. void circuit_expire_building(void) {
  257. int now = time(NULL);
  258. circuit_t *victim, *circ = global_circuitlist;
  259. while(circ) {
  260. victim = circ;
  261. circ = circ->next;
  262. if(victim->cpath &&
  263. victim->state != CIRCUIT_STATE_OPEN &&
  264. victim->timestamp_created + MIN_SECONDS_BEFORE_EXPIRING_CIRC+1 < now &&
  265. !victim->marked_for_close) {
  266. if(victim->n_conn)
  267. log_fn(LOG_INFO,"Abandoning circ %s:%d:%d (state %d:%s)",
  268. victim->n_conn->address, victim->n_port, victim->n_circ_id,
  269. victim->state, circuit_state_to_string[victim->state]);
  270. else
  271. log_fn(LOG_INFO,"Abandoning circ %d (state %d:%s)", victim->n_circ_id,
  272. victim->state, circuit_state_to_string[victim->state]);
  273. circuit_log_path(LOG_INFO,victim);
  274. circuit_mark_for_close(victim);
  275. }
  276. }
  277. }
  278. /* count the number of circs starting at us that aren't open */
  279. int circuit_count_building(void) {
  280. circuit_t *circ;
  281. int num=0;
  282. for(circ=global_circuitlist;circ;circ = circ->next) {
  283. if(circ->cpath
  284. && circ->state != CIRCUIT_STATE_OPEN
  285. && !circ->marked_for_close)
  286. num++;
  287. }
  288. return num;
  289. }
  290. #define MIN_CIRCUITS_HANDLING_STREAM 2
  291. /* return 1 if at least MIN_CIRCUITS_HANDLING_STREAM non-open circuits
  292. * will have an acceptable exit node for conn. Else return 0.
  293. */
  294. int circuit_stream_is_being_handled(connection_t *conn) {
  295. circuit_t *circ;
  296. routerinfo_t *exitrouter;
  297. int num=0;
  298. for(circ=global_circuitlist;circ;circ = circ->next) {
  299. if(circ->cpath && circ->state != CIRCUIT_STATE_OPEN &&
  300. !circ->marked_for_close) {
  301. exitrouter = router_get_by_nickname(circ->build_state->chosen_exit);
  302. if(exitrouter && connection_ap_can_use_exit(conn, exitrouter) != ADDR_POLICY_REJECTED)
  303. if(++num >= MIN_CIRCUITS_HANDLING_STREAM)
  304. return 1;
  305. }
  306. }
  307. return 0;
  308. }
  309. /* update digest from the payload of cell. assign integrity part to cell. */
  310. static void relay_set_digest(crypto_digest_env_t *digest, cell_t *cell) {
  311. char integrity[4];
  312. relay_header_t rh;
  313. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  314. crypto_digest_get_digest(digest, integrity, 4);
  315. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  316. // integrity[0], integrity[1], integrity[2], integrity[3]);
  317. relay_header_unpack(&rh, cell->payload);
  318. memcpy(rh.integrity, integrity, 4);
  319. relay_header_pack(cell->payload, &rh);
  320. }
  321. /* update digest from the payload of cell (with the integrity part set
  322. * to 0). If the integrity part is valid return 1, else restore digest
  323. * and cell to their original state and return 0.
  324. */
  325. static int relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell) {
  326. char received_integrity[4], calculated_integrity[4];
  327. relay_header_t rh;
  328. crypto_digest_env_t *backup_digest=NULL;
  329. backup_digest = crypto_digest_dup(digest);
  330. relay_header_unpack(&rh, cell->payload);
  331. memcpy(received_integrity, rh.integrity, 4);
  332. memset(rh.integrity, 0, 4);
  333. relay_header_pack(cell->payload, &rh);
  334. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  335. // received_integrity[0], received_integrity[1],
  336. // received_integrity[2], received_integrity[3]);
  337. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  338. crypto_digest_get_digest(digest, calculated_integrity, 4);
  339. if(memcmp(received_integrity, calculated_integrity, 4)) {
  340. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  341. // (%d vs %d).", received_integrity, calculated_integrity);
  342. /* restore digest to its old form */
  343. crypto_digest_assign(digest, backup_digest);
  344. /* restore the relay header */
  345. memcpy(rh.integrity, received_integrity, 4);
  346. relay_header_pack(cell->payload, &rh);
  347. crypto_free_digest_env(backup_digest);
  348. return 0;
  349. }
  350. crypto_free_digest_env(backup_digest);
  351. return 1;
  352. }
  353. static int relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
  354. int encrypt_mode) {
  355. char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
  356. relay_header_t rh;
  357. relay_header_unpack(&rh, in);
  358. // log_fn(LOG_DEBUG,"before crypt: %d",rh.recognized);
  359. if(( encrypt_mode && crypto_cipher_encrypt(cipher, in, CELL_PAYLOAD_SIZE, out)) ||
  360. (!encrypt_mode && crypto_cipher_decrypt(cipher, in, CELL_PAYLOAD_SIZE, out))) {
  361. log_fn(LOG_WARN,"Error during crypt: %s", crypto_perror());
  362. return -1;
  363. }
  364. memcpy(in,out,CELL_PAYLOAD_SIZE);
  365. relay_header_unpack(&rh, in);
  366. // log_fn(LOG_DEBUG,"after crypt: %d",rh.recognized);
  367. return 0;
  368. }
  369. /*
  370. receive a relay cell:
  371. - crypt it (encrypt APward, decrypt at AP, decrypt exitward)
  372. - check if recognized (if exitward)
  373. - if recognized, check digest, find right conn, deliver to edge.
  374. - else connection_or_write_cell_to_buf to the right conn
  375. */
  376. int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  377. int cell_direction) {
  378. connection_t *conn=NULL;
  379. crypt_path_t *layer_hint=NULL;
  380. char recognized=0;
  381. assert(cell && circ);
  382. assert(cell_direction == CELL_DIRECTION_OUT || cell_direction == CELL_DIRECTION_IN);
  383. if (circ->marked_for_close)
  384. return 0;
  385. if(relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  386. log_fn(LOG_WARN,"relay crypt failed. Dropping connection.");
  387. return -1;
  388. }
  389. if(recognized) {
  390. conn = relay_lookup_conn(circ, cell, cell_direction);
  391. if(cell_direction == CELL_DIRECTION_OUT) {
  392. ++stats_n_relay_cells_delivered;
  393. log_fn(LOG_DEBUG,"Sending to exit.");
  394. if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_EXIT, NULL) < 0) {
  395. log_fn(LOG_WARN,"connection_edge_process_relay_cell (at exit) failed.");
  396. return -1;
  397. }
  398. }
  399. if(cell_direction == CELL_DIRECTION_IN) {
  400. ++stats_n_relay_cells_delivered;
  401. log_fn(LOG_DEBUG,"Sending to AP.");
  402. if (connection_edge_process_relay_cell(cell, circ, conn, EDGE_AP, layer_hint) < 0) {
  403. log_fn(LOG_WARN,"connection_edge_process_relay_cell (at AP) failed.");
  404. return -1;
  405. }
  406. }
  407. return 0;
  408. }
  409. /* not recognized. pass it on. */
  410. if(cell_direction == CELL_DIRECTION_OUT) {
  411. cell->circ_id = circ->n_circ_id; /* switch it */
  412. conn = circ->n_conn;
  413. } else {
  414. cell->circ_id = circ->p_circ_id; /* switch it */
  415. conn = circ->p_conn;
  416. }
  417. if(!conn) {
  418. log_fn(LOG_WARN,"Didn't recognize cell, but circ stops here! Closing circ.");
  419. return -1;
  420. }
  421. log_fn(LOG_DEBUG,"Passing on unrecognized cell.");
  422. ++stats_n_relay_cells_relayed;
  423. connection_or_write_cell_to_buf(cell, conn);
  424. return 0;
  425. }
  426. /* wrap this into receive_relay_cell one day */
  427. static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  428. crypt_path_t **layer_hint, char *recognized) {
  429. crypt_path_t *thishop;
  430. relay_header_t rh;
  431. assert(circ && cell && recognized);
  432. assert(cell_direction == CELL_DIRECTION_IN || cell_direction == CELL_DIRECTION_OUT);
  433. if(cell_direction == CELL_DIRECTION_IN) {
  434. if(circ->cpath) { /* we're at the beginning of the circuit.
  435. We'll want to do layered crypts. */
  436. thishop = circ->cpath;
  437. if(thishop->state != CPATH_STATE_OPEN) {
  438. log_fn(LOG_WARN,"Relay cell before first created cell? Closing.");
  439. return -1;
  440. }
  441. do { /* Remember: cpath is in forward order, that is, first hop first. */
  442. assert(thishop);
  443. if(relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  444. return -1;
  445. relay_header_unpack(&rh, cell->payload);
  446. if(rh.recognized == 0) {
  447. /* it's possibly recognized. have to check digest to be sure. */
  448. if(relay_digest_matches(thishop->b_digest, cell)) {
  449. *recognized = 1;
  450. *layer_hint = thishop;
  451. return 0;
  452. }
  453. }
  454. thishop = thishop->next;
  455. } while(thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
  456. log_fn(LOG_WARN,"in-cell at OP not recognized. Closing.");
  457. return -1;
  458. } else { /* we're in the middle. Just one crypt. */
  459. if(relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
  460. return -1;
  461. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
  462. }
  463. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  464. /* we're in the middle. Just one crypt. */
  465. if(relay_crypt_one_payload(circ->n_crypto, cell->payload, 0) < 0)
  466. return -1;
  467. relay_header_unpack(&rh, cell->payload);
  468. if (rh.recognized == 0) {
  469. /* it's possibly recognized. have to check digest to be sure. */
  470. if(relay_digest_matches(circ->n_digest, cell)) {
  471. *recognized = 1;
  472. return 0;
  473. }
  474. }
  475. }
  476. return 0;
  477. }
  478. /*
  479. package a relay cell:
  480. 1) encrypt it to the right conn
  481. 2) connection_or_write_cell_to_buf to the right conn
  482. */
  483. int
  484. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  485. int cell_direction,
  486. crypt_path_t *layer_hint)
  487. {
  488. connection_t *conn; /* where to send the cell */
  489. crypt_path_t *thishop; /* counter for repeated crypts */
  490. if(cell_direction == CELL_DIRECTION_OUT) {
  491. conn = circ->n_conn;
  492. if(!conn) {
  493. log_fn(LOG_WARN,"outgoing relay cell has n_conn==NULL. Dropping.");
  494. return 0; /* just drop it */
  495. }
  496. relay_set_digest(layer_hint->f_digest, cell);
  497. thishop = layer_hint;
  498. /* moving from farthest to nearest hop */
  499. do {
  500. assert(thishop);
  501. log_fn(LOG_DEBUG,"crypting a layer of the relay cell.");
  502. if(relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  503. return -1;
  504. }
  505. thishop = thishop->prev;
  506. } while (thishop != circ->cpath->prev);
  507. } else { /* incoming cell */
  508. conn = circ->p_conn;
  509. if(!conn) {
  510. log_fn(LOG_WARN,"incoming relay cell has p_conn==NULL. Dropping.");
  511. return 0; /* just drop it */
  512. }
  513. relay_set_digest(circ->p_digest, cell);
  514. if(relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
  515. return -1;
  516. }
  517. ++stats_n_relay_cells_relayed;
  518. connection_or_write_cell_to_buf(cell, conn);
  519. return 0;
  520. }
  521. static connection_t *
  522. relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction)
  523. {
  524. connection_t *tmpconn;
  525. relay_header_t rh;
  526. relay_header_unpack(&rh, cell->payload);
  527. if(!rh.stream_id)
  528. return NULL;
  529. if(cell_direction == CELL_DIRECTION_OUT)
  530. tmpconn = circ->n_streams;
  531. else
  532. tmpconn = circ->p_streams;
  533. for( ; tmpconn; tmpconn=tmpconn->next_stream) {
  534. if(rh.stream_id == tmpconn->stream_id) {
  535. log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
  536. return tmpconn;
  537. }
  538. // log_fn(LOG_DEBUG,"considered stream %d, not it.",tmpconn->stream_id);
  539. }
  540. return NULL; /* probably a begin relay cell */
  541. }
  542. void circuit_resume_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
  543. connection_t *conn;
  544. assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
  545. log_fn(LOG_DEBUG,"resuming");
  546. if(edge_type == EDGE_EXIT)
  547. conn = circ->n_streams;
  548. else
  549. conn = circ->p_streams;
  550. for( ; conn; conn=conn->next_stream) {
  551. if((edge_type == EDGE_EXIT && conn->package_window > 0) ||
  552. (edge_type == EDGE_AP && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
  553. connection_start_reading(conn);
  554. connection_edge_package_raw_inbuf(conn); /* handle whatever might still be on the inbuf */
  555. /* If the circuit won't accept any more data, return without looking
  556. * at any more of the streams. Any connections that should be stopped
  557. * have already been stopped by connection_edge_package_raw_inbuf. */
  558. if(circuit_consider_stop_edge_reading(circ, edge_type, layer_hint))
  559. return;
  560. }
  561. }
  562. }
  563. /* returns 1 if the window is empty, else 0. If it's empty, tell edge conns to stop reading. */
  564. int circuit_consider_stop_edge_reading(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
  565. connection_t *conn = NULL;
  566. assert(edge_type == EDGE_EXIT || edge_type == EDGE_AP);
  567. assert(edge_type == EDGE_EXIT || layer_hint);
  568. log_fn(LOG_DEBUG,"considering");
  569. if(edge_type == EDGE_EXIT && circ->package_window <= 0)
  570. conn = circ->n_streams;
  571. else if(edge_type == EDGE_AP && layer_hint->package_window <= 0)
  572. conn = circ->p_streams;
  573. else
  574. return 0;
  575. for( ; conn; conn=conn->next_stream)
  576. if(!layer_hint || conn->cpath_layer == layer_hint)
  577. connection_stop_reading(conn);
  578. log_fn(LOG_DEBUG,"yes. stopped.");
  579. return 1;
  580. }
  581. void circuit_consider_sending_sendme(circuit_t *circ, int edge_type, crypt_path_t *layer_hint) {
  582. while((edge_type == EDGE_AP ? layer_hint->deliver_window : circ->deliver_window) <
  583. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  584. log_fn(LOG_DEBUG,"Queueing circuit sendme.");
  585. if(edge_type == EDGE_AP)
  586. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  587. else
  588. circ->deliver_window += CIRCWINDOW_INCREMENT;
  589. if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
  590. NULL, 0, layer_hint) < 0) {
  591. log_fn(LOG_WARN,"connection_edge_send_command failed. Circuit's closed.");
  592. return; /* the circuit's closed, don't continue */
  593. }
  594. }
  595. }
  596. int _circuit_mark_for_close(circuit_t *circ) {
  597. connection_t *conn;
  598. assert_circuit_ok(circ);
  599. if (circ->marked_for_close < 0)
  600. return -1;
  601. if(circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
  602. onion_pending_remove(circ);
  603. }
  604. /* If the circuit ever became OPEN, we sent it to the reputation history
  605. * module then. If it isn't OPEN, we send it there now to remember which
  606. * links worked and which didn't.
  607. */
  608. if (circ->state != CIRCUIT_STATE_OPEN)
  609. circuit_rep_hist_note_result(circ);
  610. if(circ->n_conn)
  611. connection_send_destroy(circ->n_circ_id, circ->n_conn);
  612. for(conn=circ->n_streams; conn; conn=conn->next_stream) {
  613. connection_edge_destroy(circ->n_circ_id, conn);
  614. }
  615. if(circ->p_conn)
  616. connection_send_destroy(circ->n_circ_id, circ->p_conn);
  617. for(conn=circ->p_streams; conn; conn=conn->next_stream) {
  618. connection_edge_destroy(circ->p_circ_id, conn);
  619. }
  620. if (circ->state == CIRCUIT_STATE_BUILDING ||
  621. circ->state == CIRCUIT_STATE_OR_WAIT) {
  622. /* If we never built the circuit, note it as a failure. */
  623. /* Note that we can't just check circ->cpath here, because if
  624. * circuit-building failed immediately, it won't be set yet. */
  625. circuit_increment_failure_count();
  626. }
  627. circ->marked_for_close = 1;
  628. return 0;
  629. }
  630. void circuit_detach_stream(circuit_t *circ, connection_t *conn) {
  631. connection_t *prevconn;
  632. assert(circ);
  633. assert(conn);
  634. if(conn == circ->p_streams) {
  635. circ->p_streams = conn->next_stream;
  636. return;
  637. }
  638. if(conn == circ->n_streams) {
  639. circ->n_streams = conn->next_stream;
  640. return;
  641. }
  642. for(prevconn = circ->p_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
  643. if(prevconn && prevconn->next_stream) {
  644. prevconn->next_stream = conn->next_stream;
  645. return;
  646. }
  647. for(prevconn = circ->n_streams; prevconn && prevconn->next_stream && prevconn->next_stream != conn; prevconn = prevconn->next_stream) ;
  648. if(prevconn && prevconn->next_stream) {
  649. prevconn->next_stream = conn->next_stream;
  650. return;
  651. }
  652. log_fn(LOG_ERR,"edge conn not in circuit's list?");
  653. assert(0); /* should never get here */
  654. }
  655. void circuit_about_to_close_connection(connection_t *conn) {
  656. /* send destroys for all circuits using conn */
  657. /* currently, we assume it's too late to flush conn's buf here.
  658. * down the road, maybe we'll consider that eof doesn't mean can't-write
  659. */
  660. circuit_t *circ;
  661. switch(conn->type) {
  662. case CONN_TYPE_OR:
  663. /* We must close all the circuits on it. */
  664. while((circ = circuit_get_by_conn(conn))) {
  665. if(circ->n_conn == conn) /* it's closing in front of us */
  666. circ->n_conn = NULL;
  667. if(circ->p_conn == conn) /* it's closing behind us */
  668. circ->p_conn = NULL;
  669. circuit_mark_for_close(circ);
  670. }
  671. return;
  672. case CONN_TYPE_AP:
  673. case CONN_TYPE_EXIT:
  674. /* It's an edge conn. Need to remove it from the linked list of
  675. * conn's for this circuit. Confirm that 'end' relay command has
  676. * been sent. But don't kill the circuit.
  677. */
  678. circ = circuit_get_by_conn(conn);
  679. if(!circ)
  680. return;
  681. if(!conn->has_sent_end) {
  682. log_fn(LOG_WARN,"Edge connection hasn't sent end yet? Bug.");
  683. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  684. }
  685. circuit_detach_stream(circ, conn);
  686. } /* end switch */
  687. }
  688. void circuit_log_path(int severity, circuit_t *circ) {
  689. char buf[1024];
  690. char *s = buf;
  691. struct crypt_path_t *hop;
  692. char *states[] = {"closed", "waiting for keys", "open"};
  693. routerinfo_t *router;
  694. assert(circ->cpath);
  695. snprintf(s, sizeof(buf)-1, "circ (length %d, exit %s): ",
  696. circ->build_state->desired_path_len, circ->build_state->chosen_exit);
  697. hop=circ->cpath;
  698. do {
  699. s = buf + strlen(buf);
  700. router = router_get_by_addr_port(hop->addr,hop->port);
  701. if(router) {
  702. snprintf(s, sizeof(buf) - (s - buf), "%s(%s) ",
  703. router->nickname, states[hop->state]);
  704. } else {
  705. snprintf(s, sizeof(buf) - (s - buf), "UNKNOWN ");
  706. }
  707. hop=hop->next;
  708. } while(hop!=circ->cpath);
  709. log_fn(severity,"%s",buf);
  710. }
  711. /* Tell the rep(utation)hist(ory) module about the status of the links
  712. * in circ. Hops that have become OPEN are marked as successfully
  713. * extended; the _first_ hop that isn't open (if any) is marked as
  714. * unable to extend.
  715. */
  716. static void
  717. circuit_rep_hist_note_result(circuit_t *circ)
  718. {
  719. struct crypt_path_t *hop;
  720. char *prev_nickname = NULL;
  721. routerinfo_t *router;
  722. hop = circ->cpath;
  723. if(!hop) {
  724. /* XXX
  725. * if !hop, then we're not the beginning of this circuit.
  726. * for now, just forget about it. later, we should remember when
  727. * extends-through-us failed, too.
  728. */
  729. return;
  730. }
  731. if (options.ORPort) {
  732. prev_nickname = options.Nickname;
  733. }
  734. do {
  735. router = router_get_by_addr_port(hop->addr,hop->port);
  736. if (router) {
  737. if (prev_nickname) {
  738. if (hop->state == CPATH_STATE_OPEN)
  739. rep_hist_note_extend_succeeded(prev_nickname, router->nickname);
  740. else {
  741. rep_hist_note_extend_failed(prev_nickname, router->nickname);
  742. break;
  743. }
  744. }
  745. prev_nickname = router->nickname;
  746. } else {
  747. prev_nickname = NULL;
  748. }
  749. hop=hop->next;
  750. } while (hop!=circ->cpath);
  751. }
  752. static void
  753. circuit_dump_details(int severity, circuit_t *circ, int poll_index,
  754. char *type, int this_circid, int other_circid) {
  755. struct crypt_path_t *hop;
  756. log(severity,"Conn %d has %s circuit: circID %d (other side %d), state %d (%s), born %d",
  757. poll_index, type, this_circid, other_circid, circ->state,
  758. circuit_state_to_string[circ->state], (int)circ->timestamp_created);
  759. if(circ->cpath) { /* circ starts at this node */
  760. if(circ->state == CIRCUIT_STATE_BUILDING)
  761. log(severity,"Building: desired len %d, planned exit node %s.",
  762. circ->build_state->desired_path_len, circ->build_state->chosen_exit);
  763. for(hop=circ->cpath;hop->next != circ->cpath; hop=hop->next)
  764. log(severity,"hop: state %d, addr 0x%.8x, port %d", hop->state,
  765. (unsigned int)hop->addr,
  766. (int)hop->port);
  767. }
  768. }
  769. void circuit_dump_by_conn(connection_t *conn, int severity) {
  770. circuit_t *circ;
  771. connection_t *tmpconn;
  772. for(circ=global_circuitlist;circ;circ = circ->next) {
  773. if(circ->p_conn == conn)
  774. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  775. circ->p_circ_id, circ->n_circ_id);
  776. for(tmpconn=circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  777. if(tmpconn == conn) {
  778. circuit_dump_details(severity, circ, conn->poll_index, "App-ward",
  779. circ->p_circ_id, circ->n_circ_id);
  780. }
  781. }
  782. if(circ->n_conn == conn)
  783. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  784. circ->n_circ_id, circ->p_circ_id);
  785. for(tmpconn=circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  786. if(tmpconn == conn) {
  787. circuit_dump_details(severity, circ, conn->poll_index, "Exit-ward",
  788. circ->n_circ_id, circ->p_circ_id);
  789. }
  790. }
  791. }
  792. }
  793. /* Don't keep more than 10 unused open circuits around. */
  794. #define MAX_UNUSED_OPEN_CIRCUITS 10
  795. void circuit_expire_unused_circuits(void) {
  796. circuit_t *circ;
  797. time_t now = time(NULL);
  798. smartlist_t *unused_open_circs;
  799. int i;
  800. unused_open_circs = smartlist_create(circuitlist_len);
  801. for (circ = global_circuitlist; circ; circ = circ->next) {
  802. if (circ->marked_for_close)
  803. continue;
  804. /* If the circuit has been dirty for too long, and there are no streams
  805. * on it, mark it for close.
  806. */
  807. if (circ->timestamp_dirty &&
  808. circ->timestamp_dirty + options.NewCircuitPeriod < now &&
  809. !circ->p_conn &&
  810. !circ->p_streams) {
  811. log_fn(LOG_DEBUG,"Closing n_circ_id %d",circ->n_circ_id);
  812. circuit_mark_for_close(circ);
  813. } else if (!circ->timestamp_dirty && circ->cpath &&
  814. circ->state == CIRCUIT_STATE_OPEN) {
  815. /* Also, gather a list of open unused circuits that we created.
  816. * Because we add elements to the front of global_circuitlist,
  817. * the last elements of unused_open_circs will be the oldest
  818. * ones.
  819. */
  820. smartlist_add(unused_open_circs, circ);
  821. }
  822. }
  823. for (i = MAX_UNUSED_OPEN_CIRCUITS; i < unused_open_circs->num_used; ++i) {
  824. circuit_t *circ=(circuit_t*)(unused_open_circs->list[i]);
  825. circuit_mark_for_close(circ);
  826. }
  827. smartlist_free(unused_open_circs);
  828. }
  829. /* Number of consecutive failures so far; should only be touched by
  830. * circuit_launch_new and circuit_*_failure_count.
  831. */
  832. static int n_circuit_failures = 0;
  833. /* Return -1 if you aren't going to try to make a circuit, 0 if you did try. */
  834. int circuit_launch_new(void) {
  835. if(!(options.SocksPort||options.RunTesting)) /* no need for circuits. */
  836. return -1;
  837. if(n_circuit_failures > 5) { /* too many failed circs in a row. don't try. */
  838. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  839. return -1;
  840. }
  841. /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
  842. circuit_establish_circuit();
  843. return 0;
  844. }
  845. void circuit_increment_failure_count(void) {
  846. ++n_circuit_failures;
  847. log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
  848. }
  849. void circuit_reset_failure_count(void) {
  850. n_circuit_failures = 0;
  851. }
  852. int circuit_establish_circuit(void) {
  853. routerinfo_t *firsthop;
  854. connection_t *n_conn;
  855. circuit_t *circ;
  856. circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
  857. circ->state = CIRCUIT_STATE_OR_WAIT;
  858. circ->build_state = onion_new_cpath_build_state();
  859. if (! circ->build_state) {
  860. log_fn(LOG_INFO,"Generating cpath length failed.");
  861. circuit_mark_for_close(circ);
  862. return -1;
  863. }
  864. onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop);
  865. if(!circ->cpath) {
  866. log_fn(LOG_INFO,"Generating first cpath hop failed.");
  867. circuit_mark_for_close(circ);
  868. return -1;
  869. }
  870. /* now see if we're already connected to the first OR in 'route' */
  871. log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
  872. firsthop->address,firsthop->or_port);
  873. n_conn = connection_twin_get_by_addr_port(firsthop->addr,firsthop->or_port);
  874. if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
  875. circ->n_addr = firsthop->addr;
  876. circ->n_port = firsthop->or_port;
  877. if(options.ORPort) { /* we would be connected if he were up. and he's not. */
  878. log_fn(LOG_INFO,"Route's firsthop isn't connected.");
  879. circuit_mark_for_close(circ);
  880. return -1;
  881. }
  882. if(!n_conn) { /* launch the connection */
  883. n_conn = connection_or_connect(firsthop);
  884. if(!n_conn) { /* connect failed, forget the whole thing */
  885. log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
  886. circuit_mark_for_close(circ);
  887. return -1;
  888. }
  889. }
  890. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  891. return 0; /* return success. The onion/circuit/etc will be taken care of automatically
  892. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  893. */
  894. } else { /* it (or a twin) is already open. use it. */
  895. circ->n_addr = n_conn->addr;
  896. circ->n_port = n_conn->port;
  897. circ->n_conn = n_conn;
  898. log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
  899. if(circuit_send_next_onion_skin(circ) < 0) {
  900. log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
  901. circuit_mark_for_close(circ);
  902. return -1;
  903. }
  904. }
  905. return 0;
  906. }
  907. /* find circuits that are waiting on me, if any, and get them to send the onion */
  908. void circuit_n_conn_open(connection_t *or_conn) {
  909. circuit_t *circ;
  910. for(circ=global_circuitlist;circ;circ = circ->next) {
  911. if (circ->marked_for_close)
  912. continue;
  913. if(circ->cpath && circ->n_addr == or_conn->addr && circ->n_port == or_conn->port) {
  914. assert(circ->state == CIRCUIT_STATE_OR_WAIT);
  915. log_fn(LOG_DEBUG,"Found circ %d, sending onion skin.", circ->n_circ_id);
  916. circ->n_conn = or_conn;
  917. if(circuit_send_next_onion_skin(circ) < 0) {
  918. log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
  919. circuit_mark_for_close(circ);
  920. continue;
  921. /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
  922. }
  923. }
  924. }
  925. }
  926. int circuit_send_next_onion_skin(circuit_t *circ) {
  927. cell_t cell;
  928. crypt_path_t *hop;
  929. routerinfo_t *router;
  930. int r;
  931. int circ_id_type;
  932. char payload[6+ONIONSKIN_CHALLENGE_LEN];
  933. assert(circ && circ->cpath);
  934. if(circ->cpath->state == CPATH_STATE_CLOSED) {
  935. assert(circ->n_conn && circ->n_conn->type == CONN_TYPE_OR);
  936. log_fn(LOG_DEBUG,"First skin; sending create cell.");
  937. circ_id_type = decide_circ_id_type(options.Nickname,
  938. circ->n_conn->nickname);
  939. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
  940. memset(&cell, 0, sizeof(cell_t));
  941. cell.command = CELL_CREATE;
  942. cell.circ_id = circ->n_circ_id;
  943. if(onion_skin_create(circ->n_conn->onion_pkey, &(circ->cpath->handshake_state), cell.payload) < 0) {
  944. log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
  945. return -1;
  946. }
  947. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  948. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  949. circ->state = CIRCUIT_STATE_BUILDING;
  950. log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
  951. } else {
  952. assert(circ->cpath->state == CPATH_STATE_OPEN);
  953. assert(circ->state == CIRCUIT_STATE_BUILDING);
  954. log_fn(LOG_DEBUG,"starting to send subsequent skin.");
  955. r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
  956. if (r==1) {
  957. /* done building the circuit. whew. */
  958. circ->state = CIRCUIT_STATE_OPEN;
  959. log_fn(LOG_INFO,"circuit built!");
  960. circuit_reset_failure_count();
  961. /* Tell any AP connections that have been waiting for a new
  962. * circuit that one is ready. */
  963. connection_ap_attach_pending();
  964. return 0;
  965. } else if (r<0) {
  966. log_fn(LOG_INFO,"Unable to extend circuit path.");
  967. return -1;
  968. }
  969. hop = circ->cpath->prev;
  970. *(uint32_t*)payload = htonl(hop->addr);
  971. *(uint16_t*)(payload+4) = htons(hop->port);
  972. if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), payload+6) < 0) {
  973. log_fn(LOG_WARN,"onion_skin_create failed.");
  974. return -1;
  975. }
  976. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  977. /* send it to hop->prev, because it will transfer
  978. * it to a create cell and then send to hop */
  979. if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  980. payload, sizeof(payload), hop->prev) < 0)
  981. return 0; /* circuit is closed */
  982. hop->state = CPATH_STATE_AWAITING_KEYS;
  983. }
  984. return 0;
  985. }
  986. /* take the 'extend' cell, pull out addr/port plus the onion skin. Make
  987. * sure we're connected to the next hop, and pass it the onion skin in
  988. * a create cell.
  989. */
  990. int circuit_extend(cell_t *cell, circuit_t *circ) {
  991. connection_t *n_conn;
  992. int circ_id_type;
  993. cell_t newcell;
  994. if(circ->n_conn) {
  995. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  996. return -1;
  997. }
  998. memcpy(&circ->n_addr, cell->payload+RELAY_HEADER_SIZE, 4);
  999. circ->n_addr = ntohl(circ->n_addr);
  1000. memcpy(&circ->n_port, cell->payload+RELAY_HEADER_SIZE+4, 2);
  1001. circ->n_port = ntohs(circ->n_port);
  1002. // circ->n_addr = ntohl(*(uint32_t*)(cell->payload+RELAY_HEADER_SIZE));
  1003. // circ->n_port = ntohs(*(uint16_t*)(cell->payload+RELAY_HEADER_SIZE+4));
  1004. n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
  1005. if(!n_conn || n_conn->type != CONN_TYPE_OR) {
  1006. /* I've disabled making connections through OPs, but it's definitely
  1007. * possible here. I'm not sure if it would be a bug or a feature.
  1008. *
  1009. * Note also that this will close circuits where the onion has the same
  1010. * router twice in a row in the path. I think that's ok.
  1011. */
  1012. struct in_addr in;
  1013. in.s_addr = htonl(circ->n_addr);
  1014. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Closing.", inet_ntoa(in), circ->n_port);
  1015. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  1016. NULL, 0, NULL);
  1017. return 0;
  1018. }
  1019. circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
  1020. circ->n_port = n_conn->port;
  1021. circ->n_conn = n_conn;
  1022. log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
  1023. circ_id_type = decide_circ_id_type(options.Nickname, n_conn->nickname);
  1024. // log_fn(LOG_DEBUG,"circ_id_type = %u.",circ_id_type);
  1025. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
  1026. if(!circ->n_circ_id) {
  1027. log_fn(LOG_WARN,"failed to get unique circID.");
  1028. return -1;
  1029. }
  1030. log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
  1031. memset(&newcell, 0, sizeof(cell_t));
  1032. newcell.command = CELL_CREATE;
  1033. newcell.circ_id = circ->n_circ_id;
  1034. memcpy(newcell.payload, cell->payload+RELAY_HEADER_SIZE+6,
  1035. ONIONSKIN_CHALLENGE_LEN);
  1036. connection_or_write_cell_to_buf(&newcell, circ->n_conn);
  1037. return 0;
  1038. }
  1039. extern int has_completed_circuit;
  1040. int circuit_finish_handshake(circuit_t *circ, char *reply) {
  1041. unsigned char iv[16];
  1042. unsigned char keys[40+32];
  1043. crypt_path_t *hop;
  1044. memset(iv, 0, 16);
  1045. assert(circ->cpath);
  1046. if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  1047. hop = circ->cpath;
  1048. else {
  1049. for(hop=circ->cpath->next;
  1050. hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
  1051. hop=hop->next) ;
  1052. if(hop == circ->cpath) { /* got an extended when we're all done? */
  1053. log_fn(LOG_WARN,"got extended when circ already built? Closing.");
  1054. return -1;
  1055. }
  1056. }
  1057. assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1058. if(onion_skin_client_handshake(hop->handshake_state, reply, keys, 40+32) < 0) {
  1059. log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
  1060. return -1;
  1061. }
  1062. crypto_dh_free(hop->handshake_state); /* don't need it anymore */
  1063. hop->handshake_state = NULL;
  1064. log_fn(LOG_DEBUG,"hop init digest forward 0x%.8x, backward 0x%.8x.",
  1065. (unsigned int)*(uint32_t*)keys, (unsigned int)*(uint32_t*)(keys+20));
  1066. hop->f_digest = crypto_new_digest_env(CRYPTO_SHA1_DIGEST);
  1067. crypto_digest_add_bytes(hop->f_digest, keys, 20);
  1068. hop->b_digest = crypto_new_digest_env(CRYPTO_SHA1_DIGEST);
  1069. crypto_digest_add_bytes(hop->b_digest, keys+20, 20);
  1070. log_fn(LOG_DEBUG,"hop init cipher forward 0x%.8x, backward 0x%.8x.",
  1071. (unsigned int)*(uint32_t*)(keys+40), (unsigned int)*(uint32_t*)(keys+40+16));
  1072. if (!(hop->f_crypto =
  1073. crypto_create_init_cipher(CIRCUIT_CIPHER,keys+40,iv,1))) {
  1074. log(LOG_WARN,"forward cipher initialization failed.");
  1075. return -1;
  1076. }
  1077. if (!(hop->b_crypto =
  1078. crypto_create_init_cipher(CIRCUIT_CIPHER,keys+40+16,iv,0))) {
  1079. log(LOG_WARN,"backward cipher initialization failed.");
  1080. return -1;
  1081. }
  1082. hop->state = CPATH_STATE_OPEN;
  1083. log_fn(LOG_INFO,"finished");
  1084. if(!has_completed_circuit) {
  1085. has_completed_circuit=1;
  1086. log_fn(LOG_WARN,"Tor has successfully opened a circuit. Looks like it's working.");
  1087. }
  1088. circuit_log_path(LOG_INFO,circ);
  1089. circuit_rep_hist_note_result(circ);
  1090. return 0;
  1091. }
  1092. int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
  1093. crypt_path_t *victim;
  1094. connection_t *stream;
  1095. assert(circ);
  1096. assert(layer);
  1097. /* XXX Since we don't ask for truncates currently, getting a truncated
  1098. * means that a connection broke or an extend failed. For now,
  1099. * just give up.
  1100. */
  1101. circuit_mark_for_close(circ);
  1102. return 0;
  1103. while(layer->next != circ->cpath) {
  1104. /* we need to clear out layer->next */
  1105. victim = layer->next;
  1106. log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
  1107. for(stream = circ->p_streams; stream; stream=stream->next_stream) {
  1108. if(stream->cpath_layer == victim) {
  1109. log_fn(LOG_INFO, "Marking stream %d for close.", stream->stream_id);
  1110. /* no need to send 'end' relay cells,
  1111. * because the other side's already dead
  1112. */
  1113. connection_mark_for_close(stream,0);
  1114. }
  1115. }
  1116. layer->next = victim->next;
  1117. circuit_free_cpath_node(victim);
  1118. }
  1119. log_fn(LOG_INFO, "finished");
  1120. return 0;
  1121. }
  1122. void assert_cpath_layer_ok(const crypt_path_t *cp)
  1123. {
  1124. assert(cp->f_crypto);
  1125. assert(cp->b_crypto);
  1126. assert(cp->addr);
  1127. assert(cp->port);
  1128. switch(cp->state)
  1129. {
  1130. case CPATH_STATE_CLOSED:
  1131. case CPATH_STATE_OPEN:
  1132. assert(!cp->handshake_state);
  1133. break;
  1134. case CPATH_STATE_AWAITING_KEYS:
  1135. assert(cp->handshake_state);
  1136. break;
  1137. default:
  1138. assert(0);
  1139. }
  1140. assert(cp->package_window >= 0);
  1141. assert(cp->deliver_window >= 0);
  1142. }
  1143. void assert_cpath_ok(const crypt_path_t *cp)
  1144. {
  1145. while(cp->prev)
  1146. cp = cp->prev;
  1147. while(cp->next) {
  1148. assert_cpath_layer_ok(cp);
  1149. /* layers must be in sequence of: "open* awaiting? closed*" */
  1150. if (cp->prev) {
  1151. if (cp->prev->state == CPATH_STATE_OPEN) {
  1152. assert(cp->state == CPATH_STATE_CLOSED ||
  1153. cp->state == CPATH_STATE_AWAITING_KEYS);
  1154. } else {
  1155. assert(cp->state == CPATH_STATE_CLOSED);
  1156. }
  1157. }
  1158. cp = cp->next;
  1159. }
  1160. }
  1161. void assert_circuit_ok(const circuit_t *c)
  1162. {
  1163. connection_t *conn;
  1164. assert(c);
  1165. assert(c->magic == CIRCUIT_MAGIC);
  1166. if (c->n_conn)
  1167. assert(c->n_conn->type == CONN_TYPE_OR);
  1168. if (c->p_conn)
  1169. assert(c->p_conn->type == CONN_TYPE_OR);
  1170. for (conn = c->p_streams; conn; conn = conn->next_stream)
  1171. assert(conn->type == CONN_TYPE_AP);
  1172. for (conn = c->n_streams; conn; conn = conn->next_stream)
  1173. assert(conn->type == CONN_TYPE_EXIT);
  1174. assert(c->deliver_window >= 0);
  1175. assert(c->package_window >= 0);
  1176. if (c->state == CIRCUIT_STATE_OPEN) {
  1177. if (c->cpath) {
  1178. assert(!c->n_crypto);
  1179. assert(!c->p_crypto);
  1180. assert(!c->n_digest);
  1181. assert(!c->p_digest);
  1182. } else {
  1183. assert(c->n_crypto);
  1184. assert(c->p_crypto);
  1185. assert(c->n_digest);
  1186. assert(c->p_digest);
  1187. }
  1188. }
  1189. if (c->cpath) {
  1190. //XXX assert_cpath_ok(c->cpath);
  1191. }
  1192. }
  1193. /*
  1194. Local Variables:
  1195. mode:c
  1196. indent-tabs-mode:nil
  1197. c-basic-offset:2
  1198. End:
  1199. */