circuituse.c 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuituse.c
  8. * \brief Launch the right sort of circuits and attach streams to them.
  9. **/
  10. #include "or.h"
  11. #include "circuitbuild.h"
  12. #include "circuitlist.h"
  13. #include "circuituse.h"
  14. #include "config.h"
  15. #include "connection.h"
  16. #include "connection_edge.h"
  17. #include "control.h"
  18. #include "nodelist.h"
  19. #include "networkstatus.h"
  20. #include "policies.h"
  21. #include "rendclient.h"
  22. #include "rendcommon.h"
  23. #include "rendservice.h"
  24. #include "rephist.h"
  25. #include "router.h"
  26. #include "routerlist.h"
  27. /********* START VARIABLES **********/
  28. extern circuit_t *global_circuitlist; /* from circuitlist.c */
  29. /********* END VARIABLES ************/
  30. static void circuit_expire_old_circuits_clientside(void);
  31. static void circuit_increment_failure_count(void);
  32. /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
  33. * Else return 0.
  34. */
  35. static int
  36. circuit_is_acceptable(const origin_circuit_t *origin_circ,
  37. const edge_connection_t *conn,
  38. int must_be_open, uint8_t purpose,
  39. int need_uptime, int need_internal,
  40. time_t now)
  41. {
  42. const circuit_t *circ = TO_CIRCUIT(origin_circ);
  43. const node_t *exitnode;
  44. cpath_build_state_t *build_state;
  45. tor_assert(circ);
  46. tor_assert(conn);
  47. tor_assert(conn->socks_request);
  48. if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_conn))
  49. return 0; /* ignore non-open circs */
  50. if (circ->marked_for_close)
  51. return 0;
  52. /* if this circ isn't our purpose, skip. */
  53. if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
  54. if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  55. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  56. circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
  57. circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
  58. return 0;
  59. } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  60. !must_be_open) {
  61. if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
  62. circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  63. return 0;
  64. } else {
  65. if (purpose != circ->purpose)
  66. return 0;
  67. }
  68. if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  69. purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  70. if (circ->timestamp_dirty &&
  71. circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
  72. return 0;
  73. /* decide if this circ is suitable for this conn */
  74. /* for rend circs, circ->cpath->prev is not the last router in the
  75. * circuit, it's the magical extra bob hop. so just check the nickname
  76. * of the one we meant to finish at.
  77. */
  78. build_state = origin_circ->build_state;
  79. exitnode = build_state_get_exit_node(build_state);
  80. if (need_uptime && !build_state->need_uptime)
  81. return 0;
  82. if (need_internal != build_state->is_internal)
  83. return 0;
  84. if (purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  85. if (!exitnode && !build_state->onehop_tunnel) {
  86. log_debug(LD_CIRC,"Not considering circuit with unknown router.");
  87. return 0; /* this circuit is screwed and doesn't know it yet,
  88. * or is a rendezvous circuit. */
  89. }
  90. if (build_state->onehop_tunnel) {
  91. if (!conn->want_onehop) {
  92. log_debug(LD_CIRC,"Skipping one-hop circuit.");
  93. return 0;
  94. }
  95. tor_assert(conn->chosen_exit_name);
  96. if (build_state->chosen_exit) {
  97. char digest[DIGEST_LEN];
  98. if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
  99. return 0; /* broken digest, we don't want it */
  100. if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
  101. DIGEST_LEN))
  102. return 0; /* this is a circuit to somewhere else */
  103. if (tor_digest_is_zero(digest)) {
  104. /* we don't know the digest; have to compare addr:port */
  105. tor_addr_t addr;
  106. int r = tor_addr_from_str(&addr, conn->socks_request->address);
  107. if (r < 0 ||
  108. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  109. build_state->chosen_exit->port != conn->socks_request->port)
  110. return 0;
  111. }
  112. }
  113. } else {
  114. if (conn->want_onehop) {
  115. /* don't use three-hop circuits -- that could hurt our anonymity. */
  116. return 0;
  117. }
  118. }
  119. if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
  120. /* can't exit from this router */
  121. return 0;
  122. }
  123. } else { /* not general */
  124. if ((conn->rend_data && !origin_circ->rend_data) ||
  125. (!conn->rend_data && origin_circ->rend_data) ||
  126. (conn->rend_data && origin_circ->rend_data &&
  127. rend_cmp_service_ids(conn->rend_data->onion_address,
  128. origin_circ->rend_data->onion_address))) {
  129. /* this circ is not for this conn */
  130. return 0;
  131. }
  132. }
  133. if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
  134. /* conn needs to be isolated from other conns that have already used
  135. * origin_circ */
  136. return 0;
  137. }
  138. return 1;
  139. }
  140. /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
  141. * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
  142. */
  143. static int
  144. circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
  145. const edge_connection_t *conn)
  146. {
  147. const circuit_t *a = TO_CIRCUIT(oa);
  148. const circuit_t *b = TO_CIRCUIT(ob);
  149. const uint8_t purpose = conn->_base.purpose;
  150. int a_bits, b_bits;
  151. switch (purpose) {
  152. case CIRCUIT_PURPOSE_C_GENERAL:
  153. /* if it's used but less dirty it's best;
  154. * else if it's more recently created it's best
  155. */
  156. if (b->timestamp_dirty) {
  157. if (a->timestamp_dirty &&
  158. a->timestamp_dirty > b->timestamp_dirty)
  159. return 1;
  160. } else {
  161. if (a->timestamp_dirty ||
  162. timercmp(&a->timestamp_created, &b->timestamp_created, >))
  163. return 1;
  164. if (ob->build_state->is_internal)
  165. /* XXX023 what the heck is this internal thing doing here. I
  166. * think we can get rid of it. circuit_is_acceptable() already
  167. * makes sure that is_internal is exactly what we need it to
  168. * be. -RD */
  169. return 1;
  170. }
  171. break;
  172. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  173. /* the closer it is to ack_wait the better it is */
  174. if (a->purpose > b->purpose)
  175. return 1;
  176. break;
  177. case CIRCUIT_PURPOSE_C_REND_JOINED:
  178. /* the closer it is to rend_joined the better it is */
  179. if (a->purpose > b->purpose)
  180. return 1;
  181. break;
  182. }
  183. /* XXXX023 Maybe this check should get a higher priority to avoid
  184. * using up circuits too rapidly. */
  185. a_bits = connection_edge_update_circuit_isolation(conn,
  186. (origin_circuit_t*)oa, 1);
  187. b_bits = connection_edge_update_circuit_isolation(conn,
  188. (origin_circuit_t*)ob, 1);
  189. /* if x_bits < 0, then we have not used x for anything; better not to dirty
  190. * a connection if we can help it. */
  191. if (a_bits < 0) {
  192. return 0;
  193. } else if (b_bits < 0) {
  194. return 1;
  195. }
  196. a_bits &= ~ oa->isolation_flags_mixed;
  197. a_bits &= ~ ob->isolation_flags_mixed;
  198. if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
  199. /* The fewer new restrictions we need to make on a circuit for stream
  200. * isolation, the better. */
  201. return 1;
  202. }
  203. return 0;
  204. }
  205. /** Find the best circ that conn can use, preferably one which is
  206. * dirty. Circ must not be too old.
  207. *
  208. * Conn must be defined.
  209. *
  210. * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
  211. *
  212. * circ_purpose specifies what sort of circuit we must have.
  213. * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
  214. *
  215. * If it's REND_JOINED and must_be_open==0, then return the closest
  216. * rendezvous-purposed circuit that you can find.
  217. *
  218. * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
  219. * closest introduce-purposed circuit that you can find.
  220. */
  221. static origin_circuit_t *
  222. circuit_get_best(const edge_connection_t *conn,
  223. int must_be_open, uint8_t purpose,
  224. int need_uptime, int need_internal)
  225. {
  226. circuit_t *circ;
  227. origin_circuit_t *best=NULL;
  228. struct timeval now;
  229. int intro_going_on_but_too_old = 0;
  230. tor_assert(conn);
  231. tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  232. purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
  233. purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
  234. tor_gettimeofday(&now);
  235. for (circ=global_circuitlist;circ;circ = circ->next) {
  236. origin_circuit_t *origin_circ;
  237. if (!CIRCUIT_IS_ORIGIN(circ))
  238. continue;
  239. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  240. if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
  241. need_uptime,need_internal,now.tv_sec))
  242. continue;
  243. if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
  244. !must_be_open && circ->state != CIRCUIT_STATE_OPEN &&
  245. tv_mdiff(&now, &circ->timestamp_created) > circ_times.timeout_ms) {
  246. intro_going_on_but_too_old = 1;
  247. continue;
  248. }
  249. /* now this is an acceptable circ to hand back. but that doesn't
  250. * mean it's the *best* circ to hand back. try to decide.
  251. */
  252. if (!best || circuit_is_better(origin_circ,best,conn))
  253. best = origin_circ;
  254. }
  255. if (!best && intro_going_on_but_too_old)
  256. log_info(LD_REND|LD_CIRC, "There is an intro circuit being created "
  257. "right now, but it has already taken quite a while. Starting "
  258. "one in parallel.");
  259. return best;
  260. }
  261. /** Return the number of not-yet-open general-purpose origin circuits. */
  262. static int
  263. count_pending_general_client_circuits(void)
  264. {
  265. const circuit_t *circ;
  266. int count = 0;
  267. for (circ = global_circuitlist; circ; circ = circ->next) {
  268. if (circ->marked_for_close ||
  269. circ->state == CIRCUIT_STATE_OPEN ||
  270. circ->purpose != CIRCUIT_PURPOSE_C_GENERAL ||
  271. !CIRCUIT_IS_ORIGIN(circ))
  272. continue;
  273. ++count;
  274. }
  275. return count;
  276. }
  277. #if 0
  278. /** Check whether, according to the policies in <b>options</b>, the
  279. * circuit <b>circ</b> makes sense. */
  280. /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
  281. * Also, it doesn't have the right definition of an exit circuit. Also,
  282. * it's never called. */
  283. int
  284. circuit_conforms_to_options(const origin_circuit_t *circ,
  285. const or_options_t *options)
  286. {
  287. const crypt_path_t *cpath, *cpath_next = NULL;
  288. /* first check if it includes any excluded nodes */
  289. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  290. cpath_next = cpath->next;
  291. if (routerset_contains_extendinfo(options->ExcludeNodes,
  292. cpath->extend_info))
  293. return 0;
  294. }
  295. /* then consider the final hop */
  296. if (routerset_contains_extendinfo(options->ExcludeExitNodes,
  297. circ->cpath->prev->extend_info))
  298. return 0;
  299. return 1;
  300. }
  301. #endif
  302. /** Close all circuits that start at us, aren't open, and were born
  303. * at least CircuitBuildTimeout seconds ago.
  304. */
  305. void
  306. circuit_expire_building(void)
  307. {
  308. circuit_t *victim, *next_circ = global_circuitlist;
  309. /* circ_times.timeout_ms and circ_times.close_ms are from
  310. * circuit_build_times_get_initial_timeout() if we haven't computed
  311. * custom timeouts yet */
  312. struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
  313. cannibalize_cutoff, close_cutoff, extremely_old_cutoff;
  314. struct timeval now;
  315. cpath_build_state_t *build_state;
  316. tor_gettimeofday(&now);
  317. #define SET_CUTOFF(target, msec) do { \
  318. long ms = tor_lround(msec); \
  319. struct timeval diff; \
  320. diff.tv_sec = ms / 1000; \
  321. diff.tv_usec = (int)((ms % 1000) * 1000); \
  322. timersub(&now, &diff, &target); \
  323. } while (0)
  324. SET_CUTOFF(general_cutoff, circ_times.timeout_ms);
  325. SET_CUTOFF(begindir_cutoff, circ_times.timeout_ms / 2.0);
  326. SET_CUTOFF(fourhop_cutoff, circ_times.timeout_ms * (4/3.0));
  327. SET_CUTOFF(cannibalize_cutoff, circ_times.timeout_ms / 2.0);
  328. SET_CUTOFF(close_cutoff, circ_times.close_ms);
  329. SET_CUTOFF(extremely_old_cutoff, circ_times.close_ms*2 + 1000);
  330. while (next_circ) {
  331. struct timeval cutoff;
  332. victim = next_circ;
  333. next_circ = next_circ->next;
  334. if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
  335. victim->marked_for_close) /* don't mess with marked circs */
  336. continue;
  337. build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
  338. if (build_state && build_state->onehop_tunnel)
  339. cutoff = begindir_cutoff;
  340. else if (build_state && build_state->desired_path_len == 4
  341. && !TO_ORIGIN_CIRCUIT(victim)->has_opened)
  342. cutoff = fourhop_cutoff;
  343. else if (TO_ORIGIN_CIRCUIT(victim)->has_opened)
  344. cutoff = cannibalize_cutoff;
  345. else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  346. cutoff = close_cutoff;
  347. else
  348. cutoff = general_cutoff;
  349. if (timercmp(&victim->timestamp_created, &cutoff, >))
  350. continue; /* it's still young, leave it alone */
  351. #if 0
  352. /* some debug logs, to help track bugs */
  353. if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  354. victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  355. if (!victim->timestamp_dirty)
  356. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
  357. "(clean).",
  358. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  359. victim->purpose, victim->build_state->chosen_exit_name,
  360. victim->n_circ_id);
  361. else
  362. log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
  363. "%d secs since dirty.",
  364. victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
  365. victim->purpose, victim->build_state->chosen_exit_name,
  366. victim->n_circ_id,
  367. (int)(now - victim->timestamp_dirty));
  368. }
  369. #endif
  370. /* if circ is !open, or if it's open but purpose is a non-finished
  371. * intro or rend, then mark it for close */
  372. if (victim->state == CIRCUIT_STATE_OPEN) {
  373. switch (victim->purpose) {
  374. default: /* most open circuits can be left alone. */
  375. continue; /* yes, continue inside a switch refers to the nearest
  376. * enclosing loop. C is smart. */
  377. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  378. case CIRCUIT_PURPOSE_C_INTRODUCING:
  379. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  380. break; /* too old, need to die */
  381. case CIRCUIT_PURPOSE_C_REND_READY:
  382. /* it's a rend_ready circ -- has it already picked a query? */
  383. /* c_rend_ready circs measure age since timestamp_dirty,
  384. * because that's set when they switch purposes
  385. */
  386. if (TO_ORIGIN_CIRCUIT(victim)->rend_data ||
  387. victim->timestamp_dirty > cutoff.tv_sec)
  388. continue;
  389. break;
  390. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  391. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  392. /* rend and intro circs become dirty each time they
  393. * make an introduction attempt. so timestamp_dirty
  394. * will reflect the time since the last attempt.
  395. */
  396. if (victim->timestamp_dirty > cutoff.tv_sec)
  397. continue;
  398. break;
  399. }
  400. } else { /* circuit not open, consider recording failure as timeout */
  401. int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
  402. TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
  403. if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
  404. log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
  405. "yet has attached streams!",
  406. TO_ORIGIN_CIRCUIT(victim)->global_identifier,
  407. victim->purpose,
  408. circuit_purpose_to_string(victim->purpose));
  409. tor_fragile_assert();
  410. continue;
  411. }
  412. if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
  413. circuit_build_times_enough_to_compute(&circ_times)) {
  414. /* Circuits are allowed to last longer for measurement.
  415. * Switch their purpose and wait. */
  416. if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  417. control_event_circuit_status(TO_ORIGIN_CIRCUIT(victim),
  418. CIRC_EVENT_FAILED,
  419. END_CIRC_REASON_TIMEOUT);
  420. victim->purpose = CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT;
  421. /* Record this failure to check for too many timeouts
  422. * in a row. This function does not record a time value yet
  423. * (we do that later); it only counts the fact that we did
  424. * have a timeout. */
  425. circuit_build_times_count_timeout(&circ_times,
  426. first_hop_succeeded);
  427. continue;
  428. }
  429. /*
  430. * If the circuit build time is much greater than we would have cut
  431. * it off at, we probably had a suspend event along this codepath,
  432. * and we should discard the value.
  433. */
  434. if (timercmp(&victim->timestamp_created, &extremely_old_cutoff, <)) {
  435. log_notice(LD_CIRC,
  436. "Extremely large value for circuit build timeout: %lds. "
  437. "Assuming clock jump. Purpose %d (%s)",
  438. (long)(now.tv_sec - victim->timestamp_created.tv_sec),
  439. victim->purpose,
  440. circuit_purpose_to_string(victim->purpose));
  441. } else if (circuit_build_times_count_close(&circ_times,
  442. first_hop_succeeded,
  443. victim->timestamp_created.tv_sec)) {
  444. circuit_build_times_set_timeout(&circ_times);
  445. }
  446. }
  447. }
  448. if (victim->n_conn)
  449. log_info(LD_CIRC,"Abandoning circ %s:%d:%d (state %d:%s, purpose %d)",
  450. victim->n_conn->_base.address, victim->n_conn->_base.port,
  451. victim->n_circ_id,
  452. victim->state, circuit_state_to_string(victim->state),
  453. victim->purpose);
  454. else
  455. log_info(LD_CIRC,"Abandoning circ %d (state %d:%s, purpose %d)",
  456. victim->n_circ_id, victim->state,
  457. circuit_state_to_string(victim->state), victim->purpose);
  458. circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
  459. if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
  460. circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
  461. else
  462. circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
  463. }
  464. }
  465. /** Remove any elements in <b>needed_ports</b> that are handled by an
  466. * open or in-progress circuit.
  467. */
  468. void
  469. circuit_remove_handled_ports(smartlist_t *needed_ports)
  470. {
  471. int i;
  472. uint16_t *port;
  473. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  474. port = smartlist_get(needed_ports, i);
  475. tor_assert(*port);
  476. if (circuit_stream_is_being_handled(NULL, *port,
  477. MIN_CIRCUITS_HANDLING_STREAM)) {
  478. // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
  479. smartlist_del(needed_ports, i--);
  480. tor_free(port);
  481. } else {
  482. log_debug(LD_CIRC,"Port %d is not handled.", *port);
  483. }
  484. }
  485. }
  486. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  487. * will have an acceptable exit node for exit stream <b>conn</b> if it
  488. * is defined, else for "*:port".
  489. * Else return 0.
  490. */
  491. int
  492. circuit_stream_is_being_handled(edge_connection_t *conn,
  493. uint16_t port, int min)
  494. {
  495. circuit_t *circ;
  496. const node_t *exitnode;
  497. int num=0;
  498. time_t now = time(NULL);
  499. int need_uptime = smartlist_string_num_isin(get_options()->LongLivedPorts,
  500. conn ? conn->socks_request->port : port);
  501. for (circ=global_circuitlist;circ;circ = circ->next) {
  502. if (CIRCUIT_IS_ORIGIN(circ) &&
  503. !circ->marked_for_close &&
  504. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  505. (!circ->timestamp_dirty ||
  506. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
  507. cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  508. if (build_state->is_internal || build_state->onehop_tunnel)
  509. continue;
  510. exitnode = build_state_get_exit_node(build_state);
  511. if (exitnode && (!need_uptime || build_state->need_uptime)) {
  512. int ok;
  513. if (conn) {
  514. ok = connection_ap_can_use_exit(conn, exitnode);
  515. } else {
  516. addr_policy_result_t r;
  517. r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
  518. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  519. }
  520. if (ok) {
  521. if (++num >= min)
  522. return 1;
  523. }
  524. }
  525. }
  526. }
  527. return 0;
  528. }
  529. /** Don't keep more than this many unused open circuits around. */
  530. #define MAX_UNUSED_OPEN_CIRCUITS 14
  531. /** Figure out how many circuits we have open that are clean. Make
  532. * sure it's enough for all the upcoming behaviors we predict we'll have.
  533. * But put an upper bound on the total number of circuits.
  534. */
  535. static void
  536. circuit_predict_and_launch_new(void)
  537. {
  538. circuit_t *circ;
  539. int num=0, num_internal=0, num_uptime_internal=0;
  540. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  541. int port_needs_uptime=0, port_needs_capacity=1;
  542. time_t now = time(NULL);
  543. int flags = 0;
  544. /* First, count how many of each type of circuit we have already. */
  545. for (circ=global_circuitlist;circ;circ = circ->next) {
  546. cpath_build_state_t *build_state;
  547. if (!CIRCUIT_IS_ORIGIN(circ))
  548. continue;
  549. if (circ->marked_for_close)
  550. continue; /* don't mess with marked circs */
  551. if (circ->timestamp_dirty)
  552. continue; /* only count clean circs */
  553. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  554. continue; /* only pay attention to general-purpose circs */
  555. build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
  556. if (build_state->onehop_tunnel)
  557. continue;
  558. num++;
  559. if (build_state->is_internal)
  560. num_internal++;
  561. if (build_state->need_uptime && build_state->is_internal)
  562. num_uptime_internal++;
  563. }
  564. /* If that's enough, then stop now. */
  565. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  566. return; /* we already have many, making more probably will hurt */
  567. /* Second, see if we need any more exit circuits. */
  568. /* check if we know of a port that's been requested recently
  569. * and no circuit is currently available that can handle it. */
  570. if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
  571. &port_needs_capacity)) {
  572. if (port_needs_uptime)
  573. flags |= CIRCLAUNCH_NEED_UPTIME;
  574. if (port_needs_capacity)
  575. flags |= CIRCLAUNCH_NEED_CAPACITY;
  576. log_info(LD_CIRC,
  577. "Have %d clean circs (%d internal), need another exit circ.",
  578. num, num_internal);
  579. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  580. return;
  581. }
  582. /* Third, see if we need any more hidden service (server) circuits. */
  583. if (num_rend_services() && num_uptime_internal < 3) {
  584. flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
  585. CIRCLAUNCH_IS_INTERNAL);
  586. log_info(LD_CIRC,
  587. "Have %d clean circs (%d internal), need another internal "
  588. "circ for my hidden service.",
  589. num, num_internal);
  590. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  591. return;
  592. }
  593. /* Fourth, see if we need any more hidden service (client) circuits. */
  594. if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
  595. &hidserv_needs_capacity) &&
  596. ((num_uptime_internal<2 && hidserv_needs_uptime) ||
  597. num_internal<2)) {
  598. if (hidserv_needs_uptime)
  599. flags |= CIRCLAUNCH_NEED_UPTIME;
  600. if (hidserv_needs_capacity)
  601. flags |= CIRCLAUNCH_NEED_CAPACITY;
  602. flags |= CIRCLAUNCH_IS_INTERNAL;
  603. log_info(LD_CIRC,
  604. "Have %d clean circs (%d uptime-internal, %d internal), need"
  605. " another hidden service circ.",
  606. num, num_uptime_internal, num_internal);
  607. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  608. return;
  609. }
  610. /* Finally, check to see if we still need more circuits to learn
  611. * a good build timeout. But if we're close to our max number we
  612. * want, don't do another -- we want to leave a few slots open so
  613. * we can still build circuits preemptively as needed. */
  614. if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
  615. circuit_build_times_needs_circuits_now(&circ_times)) {
  616. flags = CIRCLAUNCH_NEED_CAPACITY;
  617. log_info(LD_CIRC,
  618. "Have %d clean circs need another buildtime test circ.", num);
  619. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  620. return;
  621. }
  622. }
  623. /** Build a new test circuit every 5 minutes */
  624. #define TESTING_CIRCUIT_INTERVAL 300
  625. /** This function is called once a second, if router_have_min_dir_info() is
  626. * true. Its job is to make sure all services we offer have enough circuits
  627. * available. Some services just want enough circuits for current tasks,
  628. * whereas others want a minimum set of idle circuits hanging around.
  629. */
  630. void
  631. circuit_build_needed_circs(time_t now)
  632. {
  633. static time_t time_to_new_circuit = 0;
  634. const or_options_t *options = get_options();
  635. /* launch a new circ for any pending streams that need one */
  636. connection_ap_attach_pending();
  637. /* make sure any hidden services have enough intro points */
  638. rend_services_introduce();
  639. if (time_to_new_circuit < now) {
  640. circuit_reset_failure_count(1);
  641. time_to_new_circuit = now + options->NewCircuitPeriod;
  642. if (proxy_mode(get_options()))
  643. addressmap_clean(now);
  644. circuit_expire_old_circuits_clientside();
  645. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  646. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  647. if (get_options()->RunTesting &&
  648. circ &&
  649. circ->timestamp_created.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
  650. log_fn(LOG_INFO,"Creating a new testing circuit.");
  651. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
  652. }
  653. #endif
  654. }
  655. if (!options->DisablePredictedCircuits)
  656. circuit_predict_and_launch_new();
  657. }
  658. /** If the stream <b>conn</b> is a member of any of the linked
  659. * lists of <b>circ</b>, then remove it from the list.
  660. */
  661. void
  662. circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
  663. {
  664. edge_connection_t *prevconn;
  665. tor_assert(circ);
  666. tor_assert(conn);
  667. conn->cpath_layer = NULL; /* make sure we don't keep a stale pointer */
  668. conn->exit_allows_optimistic_data = 0;
  669. conn->on_circuit = NULL;
  670. if (CIRCUIT_IS_ORIGIN(circ)) {
  671. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  672. if (conn == origin_circ->p_streams) {
  673. origin_circ->p_streams = conn->next_stream;
  674. return;
  675. }
  676. for (prevconn = origin_circ->p_streams;
  677. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  678. prevconn = prevconn->next_stream)
  679. ;
  680. if (prevconn && prevconn->next_stream) {
  681. prevconn->next_stream = conn->next_stream;
  682. return;
  683. }
  684. } else {
  685. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  686. if (conn == or_circ->n_streams) {
  687. or_circ->n_streams = conn->next_stream;
  688. return;
  689. }
  690. if (conn == or_circ->resolving_streams) {
  691. or_circ->resolving_streams = conn->next_stream;
  692. return;
  693. }
  694. for (prevconn = or_circ->n_streams;
  695. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  696. prevconn = prevconn->next_stream)
  697. ;
  698. if (prevconn && prevconn->next_stream) {
  699. prevconn->next_stream = conn->next_stream;
  700. return;
  701. }
  702. for (prevconn = or_circ->resolving_streams;
  703. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  704. prevconn = prevconn->next_stream)
  705. ;
  706. if (prevconn && prevconn->next_stream) {
  707. prevconn->next_stream = conn->next_stream;
  708. return;
  709. }
  710. }
  711. log_warn(LD_BUG,"Edge connection not in circuit's list.");
  712. /* Don't give an error here; it's harmless. */
  713. tor_fragile_assert();
  714. }
  715. /** If we haven't yet decided on a good timeout value for circuit
  716. * building, we close idles circuits aggressively so we can get more
  717. * data points. */
  718. #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
  719. /** Find each circuit that has been unused for too long, or dirty
  720. * for too long and has no streams on it: mark it for close.
  721. */
  722. static void
  723. circuit_expire_old_circuits_clientside(void)
  724. {
  725. circuit_t *circ;
  726. struct timeval cutoff, now;
  727. tor_gettimeofday(&now);
  728. cutoff = now;
  729. if (circuit_build_times_needs_circuits(&circ_times)) {
  730. /* Circuits should be shorter lived if we need more of them
  731. * for learning a good build timeout */
  732. cutoff.tv_sec -= IDLE_TIMEOUT_WHILE_LEARNING;
  733. } else {
  734. cutoff.tv_sec -= get_options()->CircuitIdleTimeout;
  735. }
  736. for (circ = global_circuitlist; circ; circ = circ->next) {
  737. if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
  738. continue;
  739. /* If the circuit has been dirty for too long, and there are no streams
  740. * on it, mark it for close.
  741. */
  742. if (circ->timestamp_dirty &&
  743. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
  744. now.tv_sec &&
  745. !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
  746. log_debug(LD_CIRC, "Closing n_circ_id %d (dirty %ld sec ago, "
  747. "purpose %d)",
  748. circ->n_circ_id, (long)(now.tv_sec - circ->timestamp_dirty),
  749. circ->purpose);
  750. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  751. } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
  752. if (timercmp(&circ->timestamp_created, &cutoff, <)) {
  753. if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  754. circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
  755. circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  756. circ->purpose == CIRCUIT_PURPOSE_TESTING ||
  757. (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  758. circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
  759. circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  760. log_debug(LD_CIRC,
  761. "Closing circuit that has been unused for %ld msec.",
  762. tv_mdiff(&circ->timestamp_created, &now));
  763. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  764. } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
  765. /* Server-side rend joined circuits can end up really old, because
  766. * they are reused by clients for longer than normal. The client
  767. * controls their lifespan. (They never become dirty, because
  768. * connection_exit_begin_conn() never marks anything as dirty.)
  769. * Similarly, server-side intro circuits last a long time. */
  770. if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
  771. circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  772. log_notice(LD_CIRC,
  773. "Ancient non-dirty circuit %d is still around after "
  774. "%ld milliseconds. Purpose: %d (%s)",
  775. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  776. tv_mdiff(&circ->timestamp_created, &now),
  777. circ->purpose,
  778. circuit_purpose_to_string(circ->purpose));
  779. TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
  780. }
  781. }
  782. }
  783. }
  784. }
  785. }
  786. /** How long do we wait before killing circuits with the properties
  787. * described below?
  788. *
  789. * Probably we could choose a number here as low as 5 to 10 seconds,
  790. * since these circs are used for begindir, and a) generally you either
  791. * ask another begindir question right after or you don't for a long time,
  792. * b) clients at least through 0.2.1.x choose from the whole set of
  793. * directory mirrors at each choice, and c) re-establishing a one-hop
  794. * circuit via create-fast is a light operation assuming the TLS conn is
  795. * still there.
  796. *
  797. * I expect "b" to go away one day when we move to using directory
  798. * guards, but I think "a" and "c" are good enough reasons that a low
  799. * number is safe even then.
  800. */
  801. #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
  802. /** Find each non-origin circuit that has been unused for too long,
  803. * has no streams on it, used a create_fast, and ends here: mark it
  804. * for close.
  805. */
  806. void
  807. circuit_expire_old_circuits_serverside(time_t now)
  808. {
  809. circuit_t *circ;
  810. or_circuit_t *or_circ;
  811. time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
  812. for (circ = global_circuitlist; circ; circ = circ->next) {
  813. if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
  814. continue;
  815. or_circ = TO_OR_CIRCUIT(circ);
  816. /* If the circuit has been idle for too long, and there are no streams
  817. * on it, and it ends here, and it used a create_fast, mark it for close.
  818. */
  819. if (or_circ->is_first_hop && !circ->n_conn &&
  820. !or_circ->n_streams && !or_circ->resolving_streams &&
  821. or_circ->p_conn &&
  822. or_circ->p_conn->timestamp_last_added_nonpadding <= cutoff) {
  823. log_info(LD_CIRC, "Closing circ_id %d (empty %d secs ago)",
  824. or_circ->p_circ_id,
  825. (int)(now - or_circ->p_conn->timestamp_last_added_nonpadding));
  826. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  827. }
  828. }
  829. }
  830. /** Number of testing circuits we want open before testing our bandwidth. */
  831. #define NUM_PARALLEL_TESTING_CIRCS 4
  832. /** True iff we've ever had enough testing circuits open to test our
  833. * bandwidth. */
  834. static int have_performed_bandwidth_test = 0;
  835. /** Reset have_performed_bandwidth_test, so we'll start building
  836. * testing circuits again so we can exercise our bandwidth. */
  837. void
  838. reset_bandwidth_test(void)
  839. {
  840. have_performed_bandwidth_test = 0;
  841. }
  842. /** Return 1 if we've already exercised our bandwidth, or if we
  843. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  844. * established or on the way. Else return 0.
  845. */
  846. int
  847. circuit_enough_testing_circs(void)
  848. {
  849. circuit_t *circ;
  850. int num = 0;
  851. if (have_performed_bandwidth_test)
  852. return 1;
  853. for (circ = global_circuitlist; circ; circ = circ->next) {
  854. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  855. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  856. circ->state == CIRCUIT_STATE_OPEN)
  857. num++;
  858. }
  859. return num >= NUM_PARALLEL_TESTING_CIRCS;
  860. }
  861. /** A testing circuit has completed. Take whatever stats we want.
  862. * Noticing reachability is taken care of in onionskin_answer(),
  863. * so there's no need to record anything here. But if we still want
  864. * to do the bandwidth test, and we now have enough testing circuits
  865. * open, do it.
  866. */
  867. static void
  868. circuit_testing_opened(origin_circuit_t *circ)
  869. {
  870. if (have_performed_bandwidth_test ||
  871. !check_whether_orport_reachable()) {
  872. /* either we've already done everything we want with testing circuits,
  873. * or this testing circuit became open due to a fluke, e.g. we picked
  874. * a last hop where we already had the connection open due to an
  875. * outgoing local circuit. */
  876. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  877. } else if (circuit_enough_testing_circs()) {
  878. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  879. have_performed_bandwidth_test = 1;
  880. } else
  881. consider_testing_reachability(1, 0);
  882. }
  883. /** A testing circuit has failed to build. Take whatever stats we want. */
  884. static void
  885. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  886. {
  887. if (server_mode(get_options()) && check_whether_orport_reachable())
  888. return;
  889. log_info(LD_GENERAL,
  890. "Our testing circuit (to see if your ORPort is reachable) "
  891. "has failed. I'll try again later.");
  892. /* These aren't used yet. */
  893. (void)circ;
  894. (void)at_last_hop;
  895. }
  896. /** The circuit <b>circ</b> has just become open. Take the next
  897. * step: for rendezvous circuits, we pass circ to the appropriate
  898. * function in rendclient or rendservice. For general circuits, we
  899. * call connection_ap_attach_pending, which looks for pending streams
  900. * that could use circ.
  901. */
  902. void
  903. circuit_has_opened(origin_circuit_t *circ)
  904. {
  905. int can_try_clearing_isolation = 0, tried_clearing_isolation = 0;
  906. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  907. /* Remember that this circuit has finished building. Now if we start
  908. * it building again later (e.g. by extending it), we will know not
  909. * to consider its build time. */
  910. circ->has_opened = 1;
  911. again:
  912. switch (TO_CIRCUIT(circ)->purpose) {
  913. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  914. rend_client_rendcirc_has_opened(circ);
  915. can_try_clearing_isolation = 1;
  916. connection_ap_attach_pending();
  917. break;
  918. case CIRCUIT_PURPOSE_C_INTRODUCING:
  919. rend_client_introcirc_has_opened(circ);
  920. break;
  921. case CIRCUIT_PURPOSE_C_GENERAL:
  922. /* Tell any AP connections that have been waiting for a new
  923. * circuit that one is ready. */
  924. can_try_clearing_isolation = 1;
  925. connection_ap_attach_pending();
  926. break;
  927. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  928. /* at Bob, waiting for introductions */
  929. rend_service_intro_has_opened(circ);
  930. break;
  931. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  932. /* at Bob, connecting to rend point */
  933. rend_service_rendezvous_has_opened(circ);
  934. break;
  935. case CIRCUIT_PURPOSE_TESTING:
  936. circuit_testing_opened(circ);
  937. break;
  938. /* default:
  939. * This won't happen in normal operation, but might happen if the
  940. * controller did it. Just let it slide. */
  941. }
  942. if (can_try_clearing_isolation && !tried_clearing_isolation &&
  943. circ->isolation_values_set &&
  944. !circ->isolation_any_streams_attached) {
  945. /* If we have any isolation information set on this circuit, and
  946. * we didn't manage to attach any streams to it, then we can
  947. * and should clear it and try again. */
  948. circuit_clear_isolation(circ);
  949. tried_clearing_isolation = 1;
  950. goto again;
  951. }
  952. }
  953. /** Called whenever a circuit could not be successfully built.
  954. */
  955. void
  956. circuit_build_failed(origin_circuit_t *circ)
  957. {
  958. /* we should examine circ and see if it failed because of
  959. * the last hop or an earlier hop. then use this info below.
  960. */
  961. int failed_at_last_hop = 0;
  962. /* If the last hop isn't open, and the second-to-last is, we failed
  963. * at the last hop. */
  964. if (circ->cpath &&
  965. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  966. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  967. failed_at_last_hop = 1;
  968. }
  969. if (circ->cpath &&
  970. circ->cpath->state != CPATH_STATE_OPEN) {
  971. /* We failed at the first hop. If there's an OR connection
  972. * to blame, blame it. Also, avoid this relay for a while, and
  973. * fail any one-hop directory fetches destined for it. */
  974. const char *n_conn_id = circ->cpath->extend_info->identity_digest;
  975. int already_marked = 0;
  976. if (circ->_base.n_conn) {
  977. or_connection_t *n_conn = circ->_base.n_conn;
  978. if (n_conn->is_bad_for_new_circs) {
  979. /* We only want to blame this router when a fresh healthy
  980. * connection fails. So don't mark this router as newly failed,
  981. * since maybe this was just an old circuit attempt that's
  982. * finally timing out now. Also, there's no need to blow away
  983. * circuits/streams/etc, since the failure of an unhealthy conn
  984. * doesn't tell us much about whether a healthy conn would
  985. * succeed. */
  986. already_marked = 1;
  987. }
  988. log_info(LD_OR,
  989. "Our circuit failed to get a response from the first hop "
  990. "(%s:%d). I'm going to try to rotate to a better connection.",
  991. n_conn->_base.address, n_conn->_base.port);
  992. n_conn->is_bad_for_new_circs = 1;
  993. } else {
  994. log_info(LD_OR,
  995. "Our circuit died before the first hop with no connection");
  996. }
  997. if (n_conn_id && !already_marked) {
  998. entry_guard_register_connect_status(n_conn_id, 0, 1, time(NULL));
  999. /* if there are any one-hop streams waiting on this circuit, fail
  1000. * them now so they can retry elsewhere. */
  1001. connection_ap_fail_onehop(n_conn_id, circ->build_state);
  1002. }
  1003. }
  1004. switch (circ->_base.purpose) {
  1005. case CIRCUIT_PURPOSE_C_GENERAL:
  1006. /* If we never built the circuit, note it as a failure. */
  1007. circuit_increment_failure_count();
  1008. if (failed_at_last_hop) {
  1009. /* Make sure any streams that demand our last hop as their exit
  1010. * know that it's unlikely to happen. */
  1011. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  1012. }
  1013. break;
  1014. case CIRCUIT_PURPOSE_TESTING:
  1015. circuit_testing_failed(circ, failed_at_last_hop);
  1016. break;
  1017. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1018. /* at Bob, waiting for introductions */
  1019. if (circ->_base.state != CIRCUIT_STATE_OPEN) {
  1020. circuit_increment_failure_count();
  1021. }
  1022. /* no need to care here, because bob will rebuild intro
  1023. * points periodically. */
  1024. break;
  1025. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1026. /* at Alice, connecting to intro point */
  1027. /* Don't increment failure count, since Bob may have picked
  1028. * the introduction point maliciously */
  1029. /* Alice will pick a new intro point when this one dies, if
  1030. * the stream in question still cares. No need to act here. */
  1031. break;
  1032. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1033. /* at Alice, waiting for Bob */
  1034. circuit_increment_failure_count();
  1035. /* Alice will pick a new rend point when this one dies, if
  1036. * the stream in question still cares. No need to act here. */
  1037. break;
  1038. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1039. /* at Bob, connecting to rend point */
  1040. /* Don't increment failure count, since Alice may have picked
  1041. * the rendezvous point maliciously */
  1042. log_info(LD_REND,
  1043. "Couldn't connect to Alice's chosen rend point %s "
  1044. "(%s hop failed).",
  1045. escaped(build_state_get_exit_nickname(circ->build_state)),
  1046. failed_at_last_hop?"last":"non-last");
  1047. rend_service_relaunch_rendezvous(circ);
  1048. break;
  1049. /* default:
  1050. * This won't happen in normal operation, but might happen if the
  1051. * controller did it. Just let it slide. */
  1052. }
  1053. }
  1054. /** Number of consecutive failures so far; should only be touched by
  1055. * circuit_launch_new and circuit_*_failure_count.
  1056. */
  1057. static int n_circuit_failures = 0;
  1058. /** Before the last time we called circuit_reset_failure_count(), were
  1059. * there a lot of failures? */
  1060. static int did_circs_fail_last_period = 0;
  1061. /** Don't retry launching a new circuit if we try this many times with no
  1062. * success. */
  1063. #define MAX_CIRCUIT_FAILURES 5
  1064. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  1065. * details on arguments. */
  1066. origin_circuit_t *
  1067. circuit_launch(uint8_t purpose, int flags)
  1068. {
  1069. return circuit_launch_by_extend_info(purpose, NULL, flags);
  1070. }
  1071. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  1072. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  1073. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  1074. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  1075. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  1076. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  1077. * Return the newly allocated circuit on success, or NULL on failure. */
  1078. origin_circuit_t *
  1079. circuit_launch_by_extend_info(uint8_t purpose,
  1080. extend_info_t *extend_info,
  1081. int flags)
  1082. {
  1083. origin_circuit_t *circ;
  1084. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  1085. if (!onehop_tunnel && !router_have_minimum_dir_info()) {
  1086. log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  1087. "circuit launch.");
  1088. return NULL;
  1089. }
  1090. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  1091. purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
  1092. /* see if there are appropriate circs available to cannibalize. */
  1093. /* XXX if we're planning to add a hop, perhaps we want to look for
  1094. * internal circs rather than exit circs? -RD */
  1095. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  1096. if (circ) {
  1097. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d (%s)",
  1098. build_state_get_exit_nickname(circ->build_state), purpose,
  1099. circuit_purpose_to_string(purpose));
  1100. circ->_base.purpose = purpose;
  1101. /* reset the birth date of this circ, else expire_building
  1102. * will see it and think it's been trying to build since it
  1103. * began. */
  1104. tor_gettimeofday(&circ->_base.timestamp_created);
  1105. switch (purpose) {
  1106. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1107. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1108. /* it's ready right now */
  1109. break;
  1110. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1111. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1112. case CIRCUIT_PURPOSE_C_GENERAL:
  1113. /* need to add a new hop */
  1114. tor_assert(extend_info);
  1115. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  1116. return NULL;
  1117. break;
  1118. default:
  1119. log_warn(LD_BUG,
  1120. "unexpected purpose %d when cannibalizing a circ.",
  1121. purpose);
  1122. tor_fragile_assert();
  1123. return NULL;
  1124. }
  1125. return circ;
  1126. }
  1127. }
  1128. if (did_circs_fail_last_period &&
  1129. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  1130. /* too many failed circs in a row. don't try. */
  1131. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  1132. return NULL;
  1133. }
  1134. /* try a circ. if it fails, circuit_mark_for_close will increment
  1135. * n_circuit_failures */
  1136. return circuit_establish_circuit(purpose, extend_info, flags);
  1137. }
  1138. /** Record another failure at opening a general circuit. When we have
  1139. * too many, we'll stop trying for the remainder of this minute.
  1140. */
  1141. static void
  1142. circuit_increment_failure_count(void)
  1143. {
  1144. ++n_circuit_failures;
  1145. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  1146. }
  1147. /** Reset the failure count for opening general circuits. This means
  1148. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  1149. * stopping again.
  1150. */
  1151. void
  1152. circuit_reset_failure_count(int timeout)
  1153. {
  1154. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  1155. did_circs_fail_last_period = 1;
  1156. else
  1157. did_circs_fail_last_period = 0;
  1158. n_circuit_failures = 0;
  1159. }
  1160. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  1161. * there isn't one, and there isn't one on the way, launch one and return
  1162. * 0. If it will never work, return -1.
  1163. *
  1164. * Write the found or in-progress or launched circ into *circp.
  1165. */
  1166. static int
  1167. circuit_get_open_circ_or_launch(edge_connection_t *conn,
  1168. uint8_t desired_circuit_purpose,
  1169. origin_circuit_t **circp)
  1170. {
  1171. origin_circuit_t *circ;
  1172. int check_exit_policy;
  1173. int need_uptime, need_internal;
  1174. int want_onehop;
  1175. const or_options_t *options = get_options();
  1176. tor_assert(conn);
  1177. tor_assert(circp);
  1178. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1179. check_exit_policy =
  1180. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  1181. !conn->use_begindir &&
  1182. !connection_edge_is_rendezvous_stream(conn);
  1183. want_onehop = conn->want_onehop;
  1184. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  1185. smartlist_string_num_isin(options->LongLivedPorts,
  1186. conn->socks_request->port);
  1187. need_internal = desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL;
  1188. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  1189. need_uptime, need_internal);
  1190. if (circ) {
  1191. *circp = circ;
  1192. return 1; /* we're happy */
  1193. }
  1194. if (!want_onehop && !router_have_minimum_dir_info()) {
  1195. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  1196. int severity = LOG_NOTICE;
  1197. /* FFFF if this is a tunneled directory fetch, don't yell
  1198. * as loudly. the user doesn't even know it's happening. */
  1199. if (entry_list_is_constrained(options) &&
  1200. entries_known_but_down(options)) {
  1201. log_fn(severity, LD_APP|LD_DIR,
  1202. "Application request when we haven't used client functionality "
  1203. "lately. Optimistically trying known %s again.",
  1204. options->UseBridges ? "bridges" : "entrynodes");
  1205. entries_retry_all(options);
  1206. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  1207. log_fn(severity, LD_APP|LD_DIR,
  1208. "Application request when we haven't used client functionality "
  1209. "lately. Optimistically trying directory fetches again.");
  1210. routerlist_retry_directory_downloads(time(NULL));
  1211. }
  1212. }
  1213. /* the stream will be dealt with when router_have_minimum_dir_info becomes
  1214. * 1, or when all directory attempts fail and directory_all_unreachable()
  1215. * kills it.
  1216. */
  1217. return 0;
  1218. }
  1219. /* Do we need to check exit policy? */
  1220. if (check_exit_policy) {
  1221. if (!conn->chosen_exit_name) {
  1222. struct in_addr in;
  1223. tor_addr_t addr, *addrp=NULL;
  1224. if (tor_inet_aton(conn->socks_request->address, &in)) {
  1225. tor_addr_from_in(&addr, &in);
  1226. addrp = &addr;
  1227. }
  1228. if (router_exit_policy_all_nodes_reject(addrp,
  1229. conn->socks_request->port,
  1230. need_uptime)) {
  1231. log_notice(LD_APP,
  1232. "No Tor server allows exit to %s:%d. Rejecting.",
  1233. safe_str_client(conn->socks_request->address),
  1234. conn->socks_request->port);
  1235. return -1;
  1236. }
  1237. } else {
  1238. /* XXXX023 Duplicates checks in connection_ap_handshake_attach_circuit:
  1239. * refactor into a single function? */
  1240. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1241. int opt = conn->chosen_exit_optional;
  1242. if (node && !connection_ap_can_use_exit(conn, node)) {
  1243. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1244. "Requested exit point '%s' is excluded or "
  1245. "would refuse request. %s.",
  1246. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1247. if (opt) {
  1248. conn->chosen_exit_optional = 0;
  1249. tor_free(conn->chosen_exit_name);
  1250. /* Try again. */
  1251. return circuit_get_open_circ_or_launch(conn,
  1252. desired_circuit_purpose,
  1253. circp);
  1254. }
  1255. return -1;
  1256. }
  1257. }
  1258. }
  1259. /* is one already on the way? */
  1260. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  1261. need_uptime, need_internal);
  1262. if (circ)
  1263. log_debug(LD_CIRC, "one on the way!");
  1264. if (!circ) {
  1265. extend_info_t *extend_info=NULL;
  1266. uint8_t new_circ_purpose;
  1267. const int n_pending = count_pending_general_client_circuits();
  1268. if (n_pending >= options->MaxClientCircuitsPending) {
  1269. static ratelim_t delay_limit = RATELIM_INIT(10*60);
  1270. char *m;
  1271. if ((m = rate_limit_log(&delay_limit, approx_time()))) {
  1272. log_notice(LD_APP, "We'd like to launch a circuit to handle a "
  1273. "connection, but we already have %d general-purpose client "
  1274. "circuits pending. Waiting until some finish.",
  1275. n_pending);
  1276. tor_free(m);
  1277. }
  1278. return 0;
  1279. }
  1280. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1281. /* need to pick an intro point */
  1282. tor_assert(conn->rend_data);
  1283. extend_info = rend_client_get_random_intro(conn->rend_data);
  1284. if (!extend_info) {
  1285. log_info(LD_REND,
  1286. "No intro points for '%s': re-fetching service descriptor.",
  1287. safe_str_client(conn->rend_data->onion_address));
  1288. rend_client_refetch_v2_renddesc(conn->rend_data);
  1289. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1290. return 0;
  1291. }
  1292. log_info(LD_REND,"Chose %s as intro point for '%s'.",
  1293. extend_info_describe(extend_info),
  1294. safe_str_client(conn->rend_data->onion_address));
  1295. }
  1296. /* If we have specified a particular exit node for our
  1297. * connection, then be sure to open a circuit to that exit node.
  1298. */
  1299. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1300. if (conn->chosen_exit_name) {
  1301. const node_t *r;
  1302. int opt = conn->chosen_exit_optional;
  1303. r = node_get_by_nickname(conn->chosen_exit_name, 1);
  1304. if (r && node_has_descriptor(r)) {
  1305. extend_info = extend_info_from_node(r);
  1306. } else {
  1307. log_debug(LD_DIR, "considering %d, %s",
  1308. want_onehop, conn->chosen_exit_name);
  1309. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  1310. /* We're asking for a one-hop circuit to a router that
  1311. * we don't have a routerinfo about. Make up an extend_info. */
  1312. char digest[DIGEST_LEN];
  1313. char *hexdigest = conn->chosen_exit_name+1;
  1314. tor_addr_t addr;
  1315. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1316. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
  1317. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  1318. return -1;
  1319. }
  1320. if (tor_addr_from_str(&addr, conn->socks_request->address) < 0) {
  1321. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  1322. escaped_safe_str_client(conn->socks_request->address));
  1323. return -1;
  1324. }
  1325. extend_info = extend_info_alloc(conn->chosen_exit_name+1,
  1326. digest, NULL, &addr,
  1327. conn->socks_request->port);
  1328. } else {
  1329. /* We will need an onion key for the router, and we
  1330. * don't have one. Refuse or relax requirements. */
  1331. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1332. "Requested exit point '%s' is not known. %s.",
  1333. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1334. if (opt) {
  1335. conn->chosen_exit_optional = 0;
  1336. tor_free(conn->chosen_exit_name);
  1337. /* Try again with no requested exit */
  1338. return circuit_get_open_circ_or_launch(conn,
  1339. desired_circuit_purpose,
  1340. circp);
  1341. }
  1342. return -1;
  1343. }
  1344. }
  1345. }
  1346. }
  1347. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  1348. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  1349. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1350. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  1351. else
  1352. new_circ_purpose = desired_circuit_purpose;
  1353. {
  1354. int flags = CIRCLAUNCH_NEED_CAPACITY;
  1355. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  1356. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1357. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  1358. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  1359. flags);
  1360. }
  1361. extend_info_free(extend_info);
  1362. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1363. /* We just caused a circuit to get built because of this stream.
  1364. * If this stream has caused a _lot_ of circuits to be built, that's
  1365. * a bad sign: we should tell the user. */
  1366. if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
  1367. ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
  1368. log_info(LD_CIRC, "The application request to %s:%d has launched "
  1369. "%d circuits without finding one it likes.",
  1370. escaped_safe_str_client(conn->socks_request->address),
  1371. conn->socks_request->port,
  1372. conn->num_circuits_launched);
  1373. } else {
  1374. /* help predict this next time */
  1375. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  1376. if (circ) {
  1377. /* write the service_id into circ */
  1378. circ->rend_data = rend_data_dup(conn->rend_data);
  1379. if (circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  1380. circ->_base.state == CIRCUIT_STATE_OPEN)
  1381. rend_client_rendcirc_has_opened(circ);
  1382. }
  1383. }
  1384. } /* endif (!circ) */
  1385. if (circ) {
  1386. /* Mark the circuit with the isolation fields for this connection.
  1387. * When the circuit arrives, we'll clear these flags: this is
  1388. * just some internal bookkeeping to make sure that we have
  1389. * launched enough circuits.
  1390. */
  1391. connection_edge_update_circuit_isolation(conn, circ, 0);
  1392. } else {
  1393. log_info(LD_APP,
  1394. "No safe circuit (purpose %d) ready for edge "
  1395. "connection; delaying.",
  1396. desired_circuit_purpose);
  1397. }
  1398. *circp = circ;
  1399. return 0;
  1400. }
  1401. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  1402. * <b>circ</b>. */
  1403. static int
  1404. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  1405. {
  1406. crypt_path_t *cpath, *cpath_next = NULL;
  1407. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1408. cpath_next = cpath->next;
  1409. if (crypt_path == cpath)
  1410. return 1;
  1411. }
  1412. return 0;
  1413. }
  1414. /** Return true iff client-side optimistic data is supported. */
  1415. static int
  1416. optimistic_data_enabled(void)
  1417. {
  1418. const or_options_t *options = get_options();
  1419. if (options->OptimisticData < 0) {
  1420. const int32_t enabled =
  1421. networkstatus_get_param(NULL, "UseOptimisticData", 0, 0, 1);
  1422. return (int)enabled;
  1423. }
  1424. return options->OptimisticData;
  1425. }
  1426. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  1427. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  1428. * hop in circ's cpath if <b>cpath</b> is NULL.
  1429. */
  1430. static void
  1431. link_apconn_to_circ(edge_connection_t *apconn, origin_circuit_t *circ,
  1432. crypt_path_t *cpath)
  1433. {
  1434. const node_t *exitnode;
  1435. /* add it into the linked list of streams on this circuit */
  1436. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
  1437. circ->_base.n_circ_id);
  1438. /* reset it, so we can measure circ timeouts */
  1439. apconn->_base.timestamp_lastread = time(NULL);
  1440. apconn->next_stream = circ->p_streams;
  1441. apconn->on_circuit = TO_CIRCUIT(circ);
  1442. /* assert_connection_ok(conn, time(NULL)); */
  1443. circ->p_streams = apconn;
  1444. if (cpath) { /* we were given one; use it */
  1445. tor_assert(cpath_is_on_circuit(circ, cpath));
  1446. apconn->cpath_layer = cpath;
  1447. } else { /* use the last hop in the circuit */
  1448. tor_assert(circ->cpath);
  1449. tor_assert(circ->cpath->prev);
  1450. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  1451. apconn->cpath_layer = circ->cpath->prev;
  1452. }
  1453. circ->isolation_any_streams_attached = 1;
  1454. connection_edge_update_circuit_isolation(apconn, circ, 0);
  1455. /* See if we can use optimistic data on this circuit */
  1456. if (apconn->cpath_layer->extend_info &&
  1457. (exitnode = node_get_by_id(
  1458. apconn->cpath_layer->extend_info->identity_digest)) &&
  1459. exitnode->rs) {
  1460. /* Okay; we know what exit node this is. */
  1461. if (optimistic_data_enabled() &&
  1462. circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  1463. exitnode->rs->version_supports_optimistic_data)
  1464. apconn->exit_allows_optimistic_data = 1;
  1465. else
  1466. apconn->exit_allows_optimistic_data = 0;
  1467. log_info(LD_APP, "Looks like completed circuit to %s %s allow "
  1468. "optimistic data for connection to %s",
  1469. safe_str_client(node_describe(exitnode)),
  1470. apconn->exit_allows_optimistic_data ? "does" : "doesn't",
  1471. safe_str_client(apconn->socks_request->address));
  1472. }
  1473. }
  1474. /** Return true iff <b>address</b> is matched by one of the entries in
  1475. * TrackHostExits. */
  1476. int
  1477. hostname_in_track_host_exits(const or_options_t *options, const char *address)
  1478. {
  1479. if (!options->TrackHostExits)
  1480. return 0;
  1481. SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
  1482. if (cp[0] == '.') { /* match end */
  1483. if (cp[1] == '\0' ||
  1484. !strcasecmpend(address, cp) ||
  1485. !strcasecmp(address, &cp[1]))
  1486. return 1;
  1487. } else if (strcasecmp(cp, address) == 0) {
  1488. return 1;
  1489. }
  1490. } SMARTLIST_FOREACH_END(cp);
  1491. return 0;
  1492. }
  1493. /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
  1494. * the exit that we *did* choose for use by future connections to
  1495. * <b>conn</b>'s destination.
  1496. */
  1497. static void
  1498. consider_recording_trackhost(const edge_connection_t *conn,
  1499. const origin_circuit_t *circ)
  1500. {
  1501. const or_options_t *options = get_options();
  1502. char *new_address = NULL;
  1503. char fp[HEX_DIGEST_LEN+1];
  1504. /* Search the addressmap for this conn's destination. */
  1505. /* If he's not in the address map.. */
  1506. if (!options->TrackHostExits ||
  1507. addressmap_have_mapping(conn->socks_request->address,
  1508. options->TrackHostExitsExpire))
  1509. return; /* nothing to track, or already mapped */
  1510. if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
  1511. !circ->build_state->chosen_exit)
  1512. return;
  1513. /* write down the fingerprint of the chosen exit, not the nickname,
  1514. * because the chosen exit might not be named. */
  1515. base16_encode(fp, sizeof(fp),
  1516. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  1517. /* Add this exit/hostname pair to the addressmap. */
  1518. tor_asprintf(&new_address, "%s.%s.exit",
  1519. conn->socks_request->address, fp);
  1520. addressmap_register(conn->socks_request->address, new_address,
  1521. time(NULL) + options->TrackHostExitsExpire,
  1522. ADDRMAPSRC_TRACKEXIT);
  1523. }
  1524. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  1525. * begin or resolve cell as appropriate. Return values are as for
  1526. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  1527. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1528. * <b>cpath</b> is NULL. */
  1529. int
  1530. connection_ap_handshake_attach_chosen_circuit(edge_connection_t *conn,
  1531. origin_circuit_t *circ,
  1532. crypt_path_t *cpath)
  1533. {
  1534. tor_assert(conn);
  1535. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT ||
  1536. conn->_base.state == AP_CONN_STATE_CONTROLLER_WAIT);
  1537. tor_assert(conn->socks_request);
  1538. tor_assert(circ);
  1539. tor_assert(circ->_base.state == CIRCUIT_STATE_OPEN);
  1540. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1541. if (!circ->_base.timestamp_dirty)
  1542. circ->_base.timestamp_dirty = time(NULL);
  1543. link_apconn_to_circ(conn, circ, cpath);
  1544. tor_assert(conn->socks_request);
  1545. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  1546. if (!conn->use_begindir)
  1547. consider_recording_trackhost(conn, circ);
  1548. if (connection_ap_handshake_send_begin(conn) < 0)
  1549. return -1;
  1550. } else {
  1551. if (connection_ap_handshake_send_resolve(conn) < 0)
  1552. return -1;
  1553. }
  1554. return 1;
  1555. }
  1556. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1557. * we don't find one: if conn cannot be handled by any known nodes,
  1558. * warn and return -1 (conn needs to die, and is maybe already marked);
  1559. * else launch new circuit (if necessary) and return 0.
  1560. * Otherwise, associate conn with a safe live circuit, do the
  1561. * right next step, and return 1.
  1562. */
  1563. /* XXXX this function should mark for close whenever it returns -1;
  1564. * its callers shouldn't have to worry about that. */
  1565. int
  1566. connection_ap_handshake_attach_circuit(edge_connection_t *conn)
  1567. {
  1568. int retval;
  1569. int conn_age;
  1570. int want_onehop;
  1571. tor_assert(conn);
  1572. tor_assert(conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1573. tor_assert(conn->socks_request);
  1574. want_onehop = conn->want_onehop;
  1575. conn_age = (int)(time(NULL) - conn->_base.timestamp_created);
  1576. if (conn_age >= get_options()->SocksTimeout) {
  1577. int severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port) ?
  1578. LOG_INFO : LOG_NOTICE;
  1579. log_fn(severity, LD_APP,
  1580. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1581. conn_age, safe_str_client(conn->socks_request->address),
  1582. conn->socks_request->port);
  1583. return -1;
  1584. }
  1585. if (!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  1586. origin_circuit_t *circ=NULL;
  1587. if (conn->chosen_exit_name) {
  1588. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1589. int opt = conn->chosen_exit_optional;
  1590. if (!node && !want_onehop) {
  1591. /* We ran into this warning when trying to extend a circuit to a
  1592. * hidden service directory for which we didn't have a router
  1593. * descriptor. See flyspray task 767 for more details. We should
  1594. * keep this in mind when deciding to use BEGIN_DIR cells for other
  1595. * directory requests as well. -KL*/
  1596. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1597. "Requested exit point '%s' is not known. %s.",
  1598. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1599. if (opt) {
  1600. conn->chosen_exit_optional = 0;
  1601. tor_free(conn->chosen_exit_name);
  1602. return 0;
  1603. }
  1604. return -1;
  1605. }
  1606. if (node && !connection_ap_can_use_exit(conn, node)) {
  1607. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1608. "Requested exit point '%s' is excluded or "
  1609. "would refuse request. %s.",
  1610. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1611. if (opt) {
  1612. conn->chosen_exit_optional = 0;
  1613. tor_free(conn->chosen_exit_name);
  1614. return 0;
  1615. }
  1616. return -1;
  1617. }
  1618. }
  1619. /* find the circuit that we should use, if there is one. */
  1620. retval = circuit_get_open_circ_or_launch(
  1621. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1622. if (retval < 1) // XXX022 if we totally fail, this still returns 0 -RD
  1623. return retval;
  1624. log_debug(LD_APP|LD_CIRC,
  1625. "Attaching apconn to circ %d (stream %d sec old).",
  1626. circ->_base.n_circ_id, conn_age);
  1627. /* print the circ's path, so people can figure out which circs are
  1628. * sucking. */
  1629. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1630. /* We have found a suitable circuit for our conn. Hurray. */
  1631. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  1632. } else { /* we're a rendezvous conn */
  1633. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  1634. tor_assert(!conn->cpath_layer);
  1635. /* start by finding a rendezvous circuit for us */
  1636. retval = circuit_get_open_circ_or_launch(
  1637. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1638. if (retval < 0) return -1; /* failed */
  1639. if (retval > 0) {
  1640. tor_assert(rendcirc);
  1641. /* one is already established, attach */
  1642. log_info(LD_REND,
  1643. "rend joined circ %d already here. attaching. "
  1644. "(stream %d sec old)",
  1645. rendcirc->_base.n_circ_id, conn_age);
  1646. /* Mark rendezvous circuits as 'newly dirty' every time you use
  1647. * them, since the process of rebuilding a rendezvous circ is so
  1648. * expensive. There is a tradeoff between linkability and
  1649. * feasibility, at this point.
  1650. */
  1651. rendcirc->_base.timestamp_dirty = time(NULL);
  1652. link_apconn_to_circ(conn, rendcirc, NULL);
  1653. if (connection_ap_handshake_send_begin(conn) < 0)
  1654. return 0; /* already marked, let them fade away */
  1655. return 1;
  1656. }
  1657. if (rendcirc && (rendcirc->_base.purpose ==
  1658. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  1659. log_info(LD_REND,
  1660. "pending-join circ %d already here, with intro ack. "
  1661. "Stalling. (stream %d sec old)",
  1662. rendcirc->_base.n_circ_id, conn_age);
  1663. return 0;
  1664. }
  1665. /* it's on its way. find an intro circ. */
  1666. retval = circuit_get_open_circ_or_launch(
  1667. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  1668. if (retval < 0) return -1; /* failed */
  1669. if (retval > 0) {
  1670. /* one has already sent the intro. keep waiting. */
  1671. circuit_t *c = NULL;
  1672. tor_assert(introcirc);
  1673. log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
  1674. "Stalling. (stream %d sec old)",
  1675. introcirc->_base.n_circ_id,
  1676. rendcirc ? rendcirc->_base.n_circ_id : 0,
  1677. conn_age);
  1678. /* abort parallel intro circs, if any */
  1679. for (c = global_circuitlist; c; c = c->next) {
  1680. if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1681. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  1682. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  1683. if (oc->rend_data &&
  1684. !rend_cmp_service_ids(conn->rend_data->onion_address,
  1685. oc->rend_data->onion_address)) {
  1686. log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
  1687. "built in parallel.");
  1688. circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
  1689. }
  1690. }
  1691. }
  1692. return 0;
  1693. }
  1694. /* now rendcirc and introcirc are each either undefined or not finished */
  1695. if (rendcirc && introcirc &&
  1696. rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1697. log_info(LD_REND,
  1698. "ready rend circ %d already here (no intro-ack yet on "
  1699. "intro %d). (stream %d sec old)",
  1700. rendcirc->_base.n_circ_id,
  1701. introcirc->_base.n_circ_id, conn_age);
  1702. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  1703. if (introcirc->_base.state == CIRCUIT_STATE_OPEN) {
  1704. log_info(LD_REND,"found open intro circ %d (rend %d); sending "
  1705. "introduction. (stream %d sec old)",
  1706. introcirc->_base.n_circ_id, rendcirc->_base.n_circ_id,
  1707. conn_age);
  1708. switch (rend_client_send_introduction(introcirc, rendcirc)) {
  1709. case 0: /* success */
  1710. rendcirc->_base.timestamp_dirty = time(NULL);
  1711. introcirc->_base.timestamp_dirty = time(NULL);
  1712. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  1713. assert_circuit_ok(TO_CIRCUIT(introcirc));
  1714. return 0;
  1715. case -1: /* transient error */
  1716. return 0;
  1717. case -2: /* permanent error */
  1718. return -1;
  1719. default: /* oops */
  1720. tor_fragile_assert();
  1721. return -1;
  1722. }
  1723. }
  1724. }
  1725. log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
  1726. "Stalling conn. (%d sec old)",
  1727. introcirc ? introcirc->_base.n_circ_id : 0,
  1728. rendcirc ? rendcirc->_base.n_circ_id : 0, conn_age);
  1729. return 0;
  1730. }
  1731. }