circuit.c 60 KB

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