circuituse.c 77 KB

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