circuit.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841
  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 && /* AP connections */
  1081. !circ->n_streams /* exit connections */ ) {
  1082. log_fn(LOG_DEBUG,"Closing n_circ_id %d (dirty %d secs ago)",circ->n_circ_id,
  1083. (int)(now - circ->timestamp_dirty));
  1084. circuit_mark_for_close(circ);
  1085. } else if (!circ->timestamp_dirty && CIRCUIT_IS_ORIGIN(circ) &&
  1086. circ->state == CIRCUIT_STATE_OPEN &&
  1087. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1088. /* Also, gather a list of open unused general circuits that we created.
  1089. * Because we add elements to the front of global_circuitlist,
  1090. * the last elements of unused_open_circs will be the oldest
  1091. * ones.
  1092. */
  1093. smartlist_add(unused_open_circs, circ);
  1094. }
  1095. }
  1096. for (i = MAX_UNUSED_OPEN_CIRCUITS; i < smartlist_len(unused_open_circs); ++i) {
  1097. circuit_t *circ = smartlist_get(unused_open_circs, i);
  1098. circuit_mark_for_close(circ);
  1099. }
  1100. smartlist_free(unused_open_circs);
  1101. }
  1102. static void circuit_is_open(circuit_t *circ) {
  1103. switch(circ->purpose) {
  1104. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1105. rend_client_rendcirc_is_open(circ);
  1106. break;
  1107. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1108. rend_client_introcirc_is_open(circ);
  1109. break;
  1110. case CIRCUIT_PURPOSE_C_GENERAL:
  1111. /* Tell any AP connections that have been waiting for a new
  1112. * circuit that one is ready. */
  1113. connection_ap_attach_pending();
  1114. break;
  1115. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1116. /* at Bob, waiting for introductions */
  1117. rend_service_intro_is_ready(circ);
  1118. break;
  1119. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1120. /* at Bob, connecting to rend point */
  1121. rend_service_rendezvous_is_ready(circ);
  1122. break;
  1123. default:
  1124. log_fn(LOG_ERR,"unhandled purpose %d",circ->purpose);
  1125. tor_assert(0);
  1126. }
  1127. }
  1128. /* Called whenever a circuit could not be successfully built.
  1129. */
  1130. static void circuit_build_failed(circuit_t *circ) {
  1131. /* we should examine circ and see if it failed because of
  1132. * the last hop or an earlier hop. then use this info below.
  1133. */
  1134. int failed_at_last_hop = 0;
  1135. /* If the last hop isn't open, and the second-to-last is, we failed
  1136. * at the last hop. */
  1137. if (circ->cpath &&
  1138. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  1139. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  1140. failed_at_last_hop = 1;
  1141. }
  1142. switch(circ->purpose) {
  1143. case CIRCUIT_PURPOSE_C_GENERAL:
  1144. if (circ->state != CIRCUIT_STATE_OPEN) {
  1145. /* If we never built the circuit, note it as a failure. */
  1146. /* Note that we can't just check circ->cpath here, because if
  1147. * circuit-building failed immediately, it won't be set yet. */
  1148. circuit_increment_failure_count();
  1149. }
  1150. break;
  1151. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1152. /* at Bob, waiting for introductions */
  1153. if (circ->state != CIRCUIT_STATE_OPEN) {
  1154. circuit_increment_failure_count();
  1155. }
  1156. /* no need to care here, because bob will rebuild intro
  1157. * points periodically. */
  1158. break;
  1159. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1160. /* at Alice, connecting to intro point */
  1161. /* Don't increment failure count, since Bob may have picked
  1162. * the introduction point maliciously */
  1163. /* Alice will pick a new intro point when this one dies, if
  1164. * the stream in question still cares. No need to act here. */
  1165. break;
  1166. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1167. /* at Alice, waiting for Bob */
  1168. if (circ->state != CIRCUIT_STATE_OPEN) {
  1169. circuit_increment_failure_count();
  1170. }
  1171. /* Alice will pick a new rend point when this one dies, if
  1172. * the stream in question still cares. No need to act here. */
  1173. break;
  1174. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1175. /* at Bob, connecting to rend point */
  1176. /* Don't increment failure count, since Alice may have picked
  1177. * the rendezvous point maliciously */
  1178. if (failed_at_last_hop) {
  1179. log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s. Sucks to be Alice.", circ->build_state->chosen_exit);
  1180. } else {
  1181. log_fn(LOG_INFO,"Couldn't connect to Alice's chosen rend point %s, because an earlier node failed.",
  1182. circ->build_state->chosen_exit);
  1183. rend_service_relaunch_rendezvous(circ);
  1184. }
  1185. break;
  1186. default:
  1187. /* Other cases are impossible, since this function is only called with
  1188. * unbuilt circuits. */
  1189. tor_assert(0);
  1190. }
  1191. }
  1192. /* Number of consecutive failures so far; should only be touched by
  1193. * circuit_launch_new and circuit_*_failure_count.
  1194. */
  1195. static int n_circuit_failures = 0;
  1196. /* Don't retry launching a new circuit if we try this many times with no
  1197. * success. */
  1198. #define MAX_CIRCUIT_FAILURES 5
  1199. /* Launch a new circuit and return a pointer to it. Return NULL if you failed. */
  1200. circuit_t *circuit_launch_new(uint8_t purpose, const char *exit_nickname) {
  1201. if (n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  1202. /* too many failed circs in a row. don't try. */
  1203. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  1204. return NULL;
  1205. }
  1206. /* try a circ. if it fails, circuit_mark_for_close will increment n_circuit_failures */
  1207. return circuit_establish_circuit(purpose, exit_nickname);
  1208. }
  1209. void circuit_increment_failure_count(void) {
  1210. ++n_circuit_failures;
  1211. log_fn(LOG_DEBUG,"n_circuit_failures now %d.",n_circuit_failures);
  1212. }
  1213. void circuit_reset_failure_count(void) {
  1214. n_circuit_failures = 0;
  1215. }
  1216. static circuit_t *circuit_establish_circuit(uint8_t purpose,
  1217. const char *exit_nickname) {
  1218. routerinfo_t *firsthop;
  1219. connection_t *n_conn;
  1220. circuit_t *circ;
  1221. circ = circuit_new(0, NULL); /* sets circ->p_circ_id and circ->p_conn */
  1222. circ->state = CIRCUIT_STATE_OR_WAIT;
  1223. circ->build_state = onion_new_cpath_build_state(purpose, exit_nickname);
  1224. circ->purpose = purpose;
  1225. if (! circ->build_state) {
  1226. log_fn(LOG_INFO,"Generating cpath failed.");
  1227. circuit_mark_for_close(circ);
  1228. return NULL;
  1229. }
  1230. onion_extend_cpath(&circ->cpath, circ->build_state, &firsthop);
  1231. if(!CIRCUIT_IS_ORIGIN(circ)) {
  1232. log_fn(LOG_INFO,"Generating first cpath hop failed.");
  1233. circuit_mark_for_close(circ);
  1234. return NULL;
  1235. }
  1236. /* now see if we're already connected to the first OR in 'route' */
  1237. log_fn(LOG_DEBUG,"Looking for firsthop '%s:%u'",
  1238. firsthop->address,firsthop->or_port);
  1239. n_conn = connection_twin_get_by_addr_port(firsthop->addr,firsthop->or_port);
  1240. if(!n_conn || n_conn->state != OR_CONN_STATE_OPEN) { /* not currently connected */
  1241. circ->n_addr = firsthop->addr;
  1242. circ->n_port = firsthop->or_port;
  1243. if(!n_conn) { /* launch the connection */
  1244. n_conn = connection_or_connect(firsthop);
  1245. if(!n_conn) { /* connect failed, forget the whole thing */
  1246. log_fn(LOG_INFO,"connect to firsthop failed. Closing.");
  1247. circuit_mark_for_close(circ);
  1248. return NULL;
  1249. }
  1250. }
  1251. log_fn(LOG_DEBUG,"connecting in progress (or finished). Good.");
  1252. /* return success. The onion/circuit/etc will be taken care of automatically
  1253. * (may already have been) whenever n_conn reaches OR_CONN_STATE_OPEN.
  1254. */
  1255. return circ;
  1256. } else { /* it (or a twin) is already open. use it. */
  1257. circ->n_addr = n_conn->addr;
  1258. circ->n_port = n_conn->port;
  1259. circ->n_conn = n_conn;
  1260. log_fn(LOG_DEBUG,"Conn open. Delivering first onion skin.");
  1261. if(circuit_send_next_onion_skin(circ) < 0) {
  1262. log_fn(LOG_INFO,"circuit_send_next_onion_skin failed.");
  1263. circuit_mark_for_close(circ);
  1264. return NULL;
  1265. }
  1266. }
  1267. return circ;
  1268. }
  1269. /* find circuits that are waiting on me, if any, and get them to send the onion */
  1270. void circuit_n_conn_open(connection_t *or_conn) {
  1271. circuit_t *circ;
  1272. for(circ=global_circuitlist;circ;circ = circ->next) {
  1273. if (circ->marked_for_close)
  1274. continue;
  1275. if(CIRCUIT_IS_ORIGIN(circ) && circ->n_addr == or_conn->addr && circ->n_port == or_conn->port) {
  1276. tor_assert(circ->state == CIRCUIT_STATE_OR_WAIT);
  1277. log_fn(LOG_DEBUG,"Found circ %d, sending onion skin.", circ->n_circ_id);
  1278. circ->n_conn = or_conn;
  1279. if(circuit_send_next_onion_skin(circ) < 0) {
  1280. log_fn(LOG_INFO,"send_next_onion_skin failed; circuit marked for closing.");
  1281. circuit_mark_for_close(circ);
  1282. continue;
  1283. /* XXX could this be bad, eg if next_onion_skin failed because conn died? */
  1284. }
  1285. }
  1286. }
  1287. }
  1288. extern int has_completed_circuit;
  1289. int circuit_send_next_onion_skin(circuit_t *circ) {
  1290. cell_t cell;
  1291. crypt_path_t *hop;
  1292. routerinfo_t *router;
  1293. int r;
  1294. int circ_id_type;
  1295. char payload[2+4+ONIONSKIN_CHALLENGE_LEN];
  1296. tor_assert(circ && CIRCUIT_IS_ORIGIN(circ));
  1297. if(circ->cpath->state == CPATH_STATE_CLOSED) {
  1298. tor_assert(circ->n_conn && circ->n_conn->type == CONN_TYPE_OR);
  1299. log_fn(LOG_DEBUG,"First skin; sending create cell.");
  1300. circ_id_type = decide_circ_id_type(options.Nickname,
  1301. circ->n_conn->nickname);
  1302. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
  1303. memset(&cell, 0, sizeof(cell_t));
  1304. cell.command = CELL_CREATE;
  1305. cell.circ_id = circ->n_circ_id;
  1306. router = router_get_by_nickname(circ->n_conn->nickname);
  1307. if (!router) {
  1308. log_fn(LOG_WARN,"Couldn't find routerinfo for %s",
  1309. circ->n_conn->nickname);
  1310. return -1;
  1311. }
  1312. if(onion_skin_create(router->onion_pkey,
  1313. &(circ->cpath->handshake_state),
  1314. cell.payload) < 0) {
  1315. log_fn(LOG_WARN,"onion_skin_create (first hop) failed.");
  1316. return -1;
  1317. }
  1318. connection_or_write_cell_to_buf(&cell, circ->n_conn);
  1319. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  1320. circ->state = CIRCUIT_STATE_BUILDING;
  1321. log_fn(LOG_DEBUG,"first skin; finished sending create cell.");
  1322. } else {
  1323. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  1324. tor_assert(circ->state == CIRCUIT_STATE_BUILDING);
  1325. log_fn(LOG_DEBUG,"starting to send subsequent skin.");
  1326. r = onion_extend_cpath(&circ->cpath, circ->build_state, &router);
  1327. if (r==1) {
  1328. /* done building the circuit. whew. */
  1329. circ->state = CIRCUIT_STATE_OPEN;
  1330. log_fn(LOG_INFO,"circuit built!");
  1331. circuit_reset_failure_count();
  1332. if(!has_completed_circuit) {
  1333. has_completed_circuit=1;
  1334. log_fn(LOG_NOTICE,"Tor has successfully opened a circuit. Looks like it's working.");
  1335. }
  1336. circuit_rep_hist_note_result(circ);
  1337. circuit_is_open(circ); /* do other actions as necessary */
  1338. return 0;
  1339. } else if (r<0) {
  1340. log_fn(LOG_INFO,"Unable to extend circuit path.");
  1341. return -1;
  1342. }
  1343. hop = circ->cpath->prev;
  1344. *(uint32_t*)payload = htonl(hop->addr);
  1345. *(uint16_t*)(payload+4) = htons(hop->port);
  1346. if(onion_skin_create(router->onion_pkey, &(hop->handshake_state), payload+6) < 0) {
  1347. log_fn(LOG_WARN,"onion_skin_create failed.");
  1348. return -1;
  1349. }
  1350. log_fn(LOG_DEBUG,"Sending extend relay cell.");
  1351. /* send it to hop->prev, because it will transfer
  1352. * it to a create cell and then send to hop */
  1353. if(connection_edge_send_command(NULL, circ, RELAY_COMMAND_EXTEND,
  1354. payload, sizeof(payload), hop->prev) < 0)
  1355. return 0; /* circuit is closed */
  1356. hop->state = CPATH_STATE_AWAITING_KEYS;
  1357. }
  1358. return 0;
  1359. }
  1360. /* take the 'extend' cell, pull out addr/port plus the onion skin. Make
  1361. * sure we're connected to the next hop, and pass it the onion skin in
  1362. * a create cell.
  1363. */
  1364. int circuit_extend(cell_t *cell, circuit_t *circ) {
  1365. connection_t *n_conn;
  1366. int circ_id_type;
  1367. cell_t newcell;
  1368. if(circ->n_conn) {
  1369. log_fn(LOG_WARN,"n_conn already set. Bug/attack. Closing.");
  1370. return -1;
  1371. }
  1372. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  1373. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  1374. n_conn = connection_twin_get_by_addr_port(circ->n_addr,circ->n_port);
  1375. if(!n_conn || n_conn->type != CONN_TYPE_OR) {
  1376. /* I've disabled making connections through OPs, but it's definitely
  1377. * possible here. I'm not sure if it would be a bug or a feature.
  1378. *
  1379. * Note also that this will close circuits where the onion has the same
  1380. * router twice in a row in the path. I think that's ok.
  1381. */
  1382. struct in_addr in;
  1383. in.s_addr = htonl(circ->n_addr);
  1384. log_fn(LOG_INFO,"Next router (%s:%d) not connected. Closing.", inet_ntoa(in), circ->n_port);
  1385. #if 0 /* if we do truncateds, no need to kill circ */
  1386. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  1387. NULL, 0, NULL);
  1388. return 0;
  1389. #endif
  1390. return -1;
  1391. }
  1392. circ->n_addr = n_conn->addr; /* these are different if we found a twin instead */
  1393. circ->n_port = n_conn->port;
  1394. circ->n_conn = n_conn;
  1395. log_fn(LOG_DEBUG,"n_conn is %s:%u",n_conn->address,n_conn->port);
  1396. circ_id_type = decide_circ_id_type(options.Nickname, n_conn->nickname);
  1397. // log_fn(LOG_DEBUG,"circ_id_type = %u.",circ_id_type);
  1398. circ->n_circ_id = get_unique_circ_id_by_conn(circ->n_conn, circ_id_type);
  1399. if(!circ->n_circ_id) {
  1400. log_fn(LOG_WARN,"failed to get unique circID.");
  1401. return -1;
  1402. }
  1403. log_fn(LOG_DEBUG,"Chosen circID %u.",circ->n_circ_id);
  1404. memset(&newcell, 0, sizeof(cell_t));
  1405. newcell.command = CELL_CREATE;
  1406. newcell.circ_id = circ->n_circ_id;
  1407. memcpy(newcell.payload, cell->payload+RELAY_HEADER_SIZE+2+4,
  1408. ONIONSKIN_CHALLENGE_LEN);
  1409. connection_or_write_cell_to_buf(&newcell, circ->n_conn);
  1410. return 0;
  1411. }
  1412. /* Initialize cpath->{f|b}_{crypto|digest} from the key material in
  1413. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  1414. * used as follows:
  1415. * 20 to initialize f_digest
  1416. * 20 to initialize b_digest
  1417. * 16 to key f_crypto
  1418. * 16 to key b_crypto
  1419. *
  1420. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  1421. */
  1422. int circuit_init_cpath_crypto(crypt_path_t *cpath, char *key_data, int reverse)
  1423. {
  1424. unsigned char iv[CIPHER_IV_LEN];
  1425. crypto_digest_env_t *tmp_digest;
  1426. crypto_cipher_env_t *tmp_crypto;
  1427. tor_assert(cpath && key_data);
  1428. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  1429. cpath->f_digest || cpath->b_digest));
  1430. memset(iv, 0, CIPHER_IV_LEN);
  1431. log_fn(LOG_DEBUG,"hop init digest forward 0x%.8x, backward 0x%.8x.",
  1432. (unsigned int)*(uint32_t*)key_data, (unsigned int)*(uint32_t*)(key_data+20));
  1433. cpath->f_digest = crypto_new_digest_env();
  1434. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  1435. cpath->b_digest = crypto_new_digest_env();
  1436. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  1437. log_fn(LOG_DEBUG,"hop init cipher forward 0x%.8x, backward 0x%.8x.",
  1438. (unsigned int)*(uint32_t*)(key_data+40), (unsigned int)*(uint32_t*)(key_data+40+16));
  1439. if (!(cpath->f_crypto =
  1440. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),iv,1))) {
  1441. log(LOG_WARN,"forward cipher initialization failed.");
  1442. return -1;
  1443. }
  1444. if (!(cpath->b_crypto =
  1445. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,iv,0))) {
  1446. log(LOG_WARN,"backward cipher initialization failed.");
  1447. return -1;
  1448. }
  1449. if (reverse) {
  1450. tmp_digest = cpath->f_digest;
  1451. cpath->f_digest = cpath->b_digest;
  1452. cpath->b_digest = tmp_digest;
  1453. tmp_crypto = cpath->f_crypto;
  1454. cpath->f_crypto = cpath->b_crypto;
  1455. cpath->b_crypto = tmp_crypto;
  1456. }
  1457. return 0;
  1458. }
  1459. int circuit_finish_handshake(circuit_t *circ, char *reply) {
  1460. unsigned char keys[CPATH_KEY_MATERIAL_LEN];
  1461. crypt_path_t *hop;
  1462. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  1463. if(circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  1464. hop = circ->cpath;
  1465. else {
  1466. for(hop=circ->cpath->next;
  1467. hop != circ->cpath && hop->state == CPATH_STATE_OPEN;
  1468. hop=hop->next) ;
  1469. if(hop == circ->cpath) { /* got an extended when we're all done? */
  1470. log_fn(LOG_WARN,"got extended when circ already built? Closing.");
  1471. return -1;
  1472. }
  1473. }
  1474. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  1475. if(onion_skin_client_handshake(hop->handshake_state, reply, keys,
  1476. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  1477. log_fn(LOG_WARN,"onion_skin_client_handshake failed.");
  1478. return -1;
  1479. }
  1480. crypto_dh_free(hop->handshake_state); /* don't need it anymore */
  1481. hop->handshake_state = NULL;
  1482. /* Remember hash of g^xy */
  1483. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  1484. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  1485. return -1;
  1486. }
  1487. hop->state = CPATH_STATE_OPEN;
  1488. log_fn(LOG_INFO,"finished");
  1489. circuit_log_path(LOG_INFO,circ);
  1490. return 0;
  1491. }
  1492. int circuit_truncated(circuit_t *circ, crypt_path_t *layer) {
  1493. crypt_path_t *victim;
  1494. connection_t *stream;
  1495. tor_assert(circ && CIRCUIT_IS_ORIGIN(circ));
  1496. tor_assert(layer);
  1497. /* XXX Since we don't ask for truncates currently, getting a truncated
  1498. * means that a connection broke or an extend failed. For now,
  1499. * just give up.
  1500. */
  1501. circuit_mark_for_close(circ);
  1502. return 0;
  1503. while(layer->next != circ->cpath) {
  1504. /* we need to clear out layer->next */
  1505. victim = layer->next;
  1506. log_fn(LOG_DEBUG, "Killing a layer of the cpath.");
  1507. for(stream = circ->p_streams; stream; stream=stream->next_stream) {
  1508. if(stream->cpath_layer == victim) {
  1509. log_fn(LOG_INFO, "Marking stream %d for close.", stream->stream_id);
  1510. /* no need to send 'end' relay cells,
  1511. * because the other side's already dead
  1512. */
  1513. connection_mark_for_close(stream,0);
  1514. }
  1515. }
  1516. layer->next = victim->next;
  1517. circuit_free_cpath_node(victim);
  1518. }
  1519. log_fn(LOG_INFO, "finished");
  1520. return 0;
  1521. }
  1522. void assert_cpath_layer_ok(const crypt_path_t *cp)
  1523. {
  1524. tor_assert(cp->f_crypto);
  1525. tor_assert(cp->b_crypto);
  1526. // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
  1527. // tor_assert(cp->port);
  1528. switch(cp->state)
  1529. {
  1530. case CPATH_STATE_CLOSED:
  1531. case CPATH_STATE_OPEN:
  1532. tor_assert(!cp->handshake_state);
  1533. break;
  1534. case CPATH_STATE_AWAITING_KEYS:
  1535. tor_assert(cp->handshake_state);
  1536. break;
  1537. default:
  1538. tor_assert(0);
  1539. }
  1540. tor_assert(cp->package_window >= 0);
  1541. tor_assert(cp->deliver_window >= 0);
  1542. }
  1543. void assert_cpath_ok(const crypt_path_t *cp)
  1544. {
  1545. while(cp->prev)
  1546. cp = cp->prev;
  1547. while(cp->next) {
  1548. assert_cpath_layer_ok(cp);
  1549. /* layers must be in sequence of: "open* awaiting? closed*" */
  1550. if (cp->prev) {
  1551. if (cp->prev->state == CPATH_STATE_OPEN) {
  1552. tor_assert(cp->state == CPATH_STATE_CLOSED ||
  1553. cp->state == CPATH_STATE_AWAITING_KEYS);
  1554. } else {
  1555. tor_assert(cp->state == CPATH_STATE_CLOSED);
  1556. }
  1557. }
  1558. cp = cp->next;
  1559. }
  1560. }
  1561. void assert_circuit_ok(const circuit_t *c)
  1562. {
  1563. connection_t *conn;
  1564. tor_assert(c);
  1565. tor_assert(c->magic == CIRCUIT_MAGIC);
  1566. tor_assert(c->purpose >= _CIRCUIT_PURPOSE_MIN &&
  1567. c->purpose <= _CIRCUIT_PURPOSE_MAX);
  1568. if (c->n_conn)
  1569. tor_assert(c->n_conn->type == CONN_TYPE_OR);
  1570. if (c->p_conn)
  1571. tor_assert(c->p_conn->type == CONN_TYPE_OR);
  1572. for (conn = c->p_streams; conn; conn = conn->next_stream)
  1573. tor_assert(conn->type == CONN_TYPE_AP);
  1574. for (conn = c->n_streams; conn; conn = conn->next_stream)
  1575. tor_assert(conn->type == CONN_TYPE_EXIT);
  1576. tor_assert(c->deliver_window >= 0);
  1577. tor_assert(c->package_window >= 0);
  1578. if (c->state == CIRCUIT_STATE_OPEN) {
  1579. if (c->cpath) {
  1580. tor_assert(CIRCUIT_IS_ORIGIN(c));
  1581. tor_assert(!c->n_crypto);
  1582. tor_assert(!c->p_crypto);
  1583. tor_assert(!c->n_digest);
  1584. tor_assert(!c->p_digest);
  1585. } else {
  1586. tor_assert(!CIRCUIT_IS_ORIGIN(c));
  1587. tor_assert(c->n_crypto);
  1588. tor_assert(c->p_crypto);
  1589. tor_assert(c->n_digest);
  1590. tor_assert(c->p_digest);
  1591. }
  1592. }
  1593. if (c->cpath) {
  1594. //XXX assert_cpath_ok(c->cpath);
  1595. }
  1596. if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
  1597. if (!c->marked_for_close) {
  1598. tor_assert(c->rend_splice);
  1599. tor_assert(c->rend_splice->rend_splice == c);
  1600. }
  1601. tor_assert(c->rend_splice != c);
  1602. } else {
  1603. tor_assert(!c->rend_splice);
  1604. }
  1605. }
  1606. /*
  1607. Local Variables:
  1608. mode:c
  1609. indent-tabs-mode:nil
  1610. c-basic-offset:2
  1611. End:
  1612. */