circuit.c 34 KB

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