circuit.c 49 KB

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