circuit.c 51 KB

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