circuituse.c 75 KB

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