circuit.c 34 KB

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