circuituse.c 77 KB

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