circuituse.c 80 KB

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