circuit.c 44 KB

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