circuituse.c 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083
  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. if (n_chan->is_bad_for_new_circs) {
  1080. /* We only want to blame this router when a fresh healthy
  1081. * connection fails. So don't mark this router as newly failed,
  1082. * since maybe this was just an old circuit attempt that's
  1083. * finally timing out now. Also, there's no need to blow away
  1084. * circuits/streams/etc, since the failure of an unhealthy conn
  1085. * doesn't tell us much about whether a healthy conn would
  1086. * succeed. */
  1087. already_marked = 1;
  1088. }
  1089. log_info(LD_OR,
  1090. "Our circuit failed to get a response from the first hop "
  1091. "(%s). I'm going to try to rotate to a better connection.",
  1092. channel_get_canonical_remote_descr(n_chan));
  1093. n_chan->is_bad_for_new_circs = 1;
  1094. } else {
  1095. log_info(LD_OR,
  1096. "Our circuit died before the first hop with no connection");
  1097. }
  1098. if (n_chan_id && !already_marked) {
  1099. entry_guard_register_connect_status(n_chan_id, 0, 1, time(NULL));
  1100. /* if there are any one-hop streams waiting on this circuit, fail
  1101. * them now so they can retry elsewhere. */
  1102. connection_ap_fail_onehop(n_chan_id, circ->build_state);
  1103. }
  1104. }
  1105. switch (circ->base_.purpose) {
  1106. case CIRCUIT_PURPOSE_C_GENERAL:
  1107. /* If we never built the circuit, note it as a failure. */
  1108. circuit_increment_failure_count();
  1109. if (failed_at_last_hop) {
  1110. /* Make sure any streams that demand our last hop as their exit
  1111. * know that it's unlikely to happen. */
  1112. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  1113. }
  1114. break;
  1115. case CIRCUIT_PURPOSE_TESTING:
  1116. circuit_testing_failed(circ, failed_at_last_hop);
  1117. break;
  1118. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1119. /* at Bob, waiting for introductions */
  1120. if (circ->base_.state != CIRCUIT_STATE_OPEN) {
  1121. circuit_increment_failure_count();
  1122. }
  1123. /* no need to care here, because bob will rebuild intro
  1124. * points periodically. */
  1125. break;
  1126. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1127. /* at Alice, connecting to intro point */
  1128. /* Don't increment failure count, since Bob may have picked
  1129. * the introduction point maliciously */
  1130. /* Alice will pick a new intro point when this one dies, if
  1131. * the stream in question still cares. No need to act here. */
  1132. break;
  1133. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1134. /* at Alice, waiting for Bob */
  1135. circuit_increment_failure_count();
  1136. /* Alice will pick a new rend point when this one dies, if
  1137. * the stream in question still cares. No need to act here. */
  1138. break;
  1139. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1140. /* at Bob, connecting to rend point */
  1141. /* Don't increment failure count, since Alice may have picked
  1142. * the rendezvous point maliciously */
  1143. log_info(LD_REND,
  1144. "Couldn't connect to Alice's chosen rend point %s "
  1145. "(%s hop failed).",
  1146. escaped(build_state_get_exit_nickname(circ->build_state)),
  1147. failed_at_last_hop?"last":"non-last");
  1148. rend_service_relaunch_rendezvous(circ);
  1149. break;
  1150. /* default:
  1151. * This won't happen in normal operation, but might happen if the
  1152. * controller did it. Just let it slide. */
  1153. }
  1154. }
  1155. /** Number of consecutive failures so far; should only be touched by
  1156. * circuit_launch_new and circuit_*_failure_count.
  1157. */
  1158. static int n_circuit_failures = 0;
  1159. /** Before the last time we called circuit_reset_failure_count(), were
  1160. * there a lot of failures? */
  1161. static int did_circs_fail_last_period = 0;
  1162. /** Don't retry launching a new circuit if we try this many times with no
  1163. * success. */
  1164. #define MAX_CIRCUIT_FAILURES 5
  1165. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  1166. * details on arguments. */
  1167. origin_circuit_t *
  1168. circuit_launch(uint8_t purpose, int flags)
  1169. {
  1170. return circuit_launch_by_extend_info(purpose, NULL, flags);
  1171. }
  1172. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  1173. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  1174. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  1175. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  1176. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  1177. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  1178. * Return the newly allocated circuit on success, or NULL on failure. */
  1179. origin_circuit_t *
  1180. circuit_launch_by_extend_info(uint8_t purpose,
  1181. extend_info_t *extend_info,
  1182. int flags)
  1183. {
  1184. origin_circuit_t *circ;
  1185. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  1186. if (!onehop_tunnel && !router_have_minimum_dir_info()) {
  1187. log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  1188. "circuit launch.");
  1189. return NULL;
  1190. }
  1191. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  1192. purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
  1193. /* see if there are appropriate circs available to cannibalize. */
  1194. /* XXX if we're planning to add a hop, perhaps we want to look for
  1195. * internal circs rather than exit circs? -RD */
  1196. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  1197. if (circ) {
  1198. uint8_t old_purpose = circ->base_.purpose;
  1199. struct timeval old_timestamp_created;
  1200. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d (%s)",
  1201. build_state_get_exit_nickname(circ->build_state), purpose,
  1202. circuit_purpose_to_string(purpose));
  1203. circuit_change_purpose(TO_CIRCUIT(circ), purpose);
  1204. /* reset the birth date of this circ, else expire_building
  1205. * will see it and think it's been trying to build since it
  1206. * began. */
  1207. tor_gettimeofday(&circ->base_.timestamp_created);
  1208. control_event_circuit_cannibalized(circ, old_purpose,
  1209. &old_timestamp_created);
  1210. switch (purpose) {
  1211. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1212. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1213. /* it's ready right now */
  1214. break;
  1215. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1216. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1217. case CIRCUIT_PURPOSE_C_GENERAL:
  1218. /* need to add a new hop */
  1219. tor_assert(extend_info);
  1220. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  1221. return NULL;
  1222. break;
  1223. default:
  1224. log_warn(LD_BUG,
  1225. "unexpected purpose %d when cannibalizing a circ.",
  1226. purpose);
  1227. tor_fragile_assert();
  1228. return NULL;
  1229. }
  1230. return circ;
  1231. }
  1232. }
  1233. if (did_circs_fail_last_period &&
  1234. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  1235. /* too many failed circs in a row. don't try. */
  1236. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  1237. return NULL;
  1238. }
  1239. /* try a circ. if it fails, circuit_mark_for_close will increment
  1240. * n_circuit_failures */
  1241. return circuit_establish_circuit(purpose, extend_info, flags);
  1242. }
  1243. /** Record another failure at opening a general circuit. When we have
  1244. * too many, we'll stop trying for the remainder of this minute.
  1245. */
  1246. static void
  1247. circuit_increment_failure_count(void)
  1248. {
  1249. ++n_circuit_failures;
  1250. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  1251. }
  1252. /** Reset the failure count for opening general circuits. This means
  1253. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  1254. * stopping again.
  1255. */
  1256. void
  1257. circuit_reset_failure_count(int timeout)
  1258. {
  1259. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  1260. did_circs_fail_last_period = 1;
  1261. else
  1262. did_circs_fail_last_period = 0;
  1263. n_circuit_failures = 0;
  1264. }
  1265. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  1266. * there isn't one, and there isn't one on the way, launch one and return
  1267. * 0. If it will never work, return -1.
  1268. *
  1269. * Write the found or in-progress or launched circ into *circp.
  1270. */
  1271. static int
  1272. circuit_get_open_circ_or_launch(entry_connection_t *conn,
  1273. uint8_t desired_circuit_purpose,
  1274. origin_circuit_t **circp)
  1275. {
  1276. origin_circuit_t *circ;
  1277. int check_exit_policy;
  1278. int need_uptime, need_internal;
  1279. int want_onehop;
  1280. const or_options_t *options = get_options();
  1281. tor_assert(conn);
  1282. tor_assert(circp);
  1283. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1284. check_exit_policy =
  1285. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  1286. !conn->use_begindir &&
  1287. !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
  1288. want_onehop = conn->want_onehop;
  1289. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  1290. smartlist_string_num_isin(options->LongLivedPorts,
  1291. conn->socks_request->port);
  1292. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
  1293. need_internal = 1;
  1294. else if (conn->use_begindir || conn->want_onehop)
  1295. need_internal = 1;
  1296. else
  1297. need_internal = 0;
  1298. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  1299. need_uptime, need_internal);
  1300. if (circ) {
  1301. *circp = circ;
  1302. return 1; /* we're happy */
  1303. }
  1304. if (!want_onehop && !router_have_minimum_dir_info()) {
  1305. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  1306. int severity = LOG_NOTICE;
  1307. /* FFFF if this is a tunneled directory fetch, don't yell
  1308. * as loudly. the user doesn't even know it's happening. */
  1309. if (entry_list_is_constrained(options) &&
  1310. entries_known_but_down(options)) {
  1311. log_fn(severity, LD_APP|LD_DIR,
  1312. "Application request when we haven't used client functionality "
  1313. "lately. Optimistically trying known %s again.",
  1314. options->UseBridges ? "bridges" : "entrynodes");
  1315. entries_retry_all(options);
  1316. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  1317. log_fn(severity, LD_APP|LD_DIR,
  1318. "Application request when we haven't used client functionality "
  1319. "lately. Optimistically trying directory fetches again.");
  1320. routerlist_retry_directory_downloads(time(NULL));
  1321. }
  1322. }
  1323. /* the stream will be dealt with when router_have_minimum_dir_info becomes
  1324. * 1, or when all directory attempts fail and directory_all_unreachable()
  1325. * kills it.
  1326. */
  1327. return 0;
  1328. }
  1329. /* Do we need to check exit policy? */
  1330. if (check_exit_policy) {
  1331. if (!conn->chosen_exit_name) {
  1332. struct in_addr in;
  1333. tor_addr_t addr, *addrp=NULL;
  1334. if (tor_inet_aton(conn->socks_request->address, &in)) {
  1335. tor_addr_from_in(&addr, &in);
  1336. addrp = &addr;
  1337. }
  1338. if (router_exit_policy_all_nodes_reject(addrp,
  1339. conn->socks_request->port,
  1340. need_uptime)) {
  1341. log_notice(LD_APP,
  1342. "No Tor server allows exit to %s:%d. Rejecting.",
  1343. safe_str_client(conn->socks_request->address),
  1344. conn->socks_request->port);
  1345. return -1;
  1346. }
  1347. } else {
  1348. /* XXXX024 Duplicates checks in connection_ap_handshake_attach_circuit:
  1349. * refactor into a single function? */
  1350. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1351. int opt = conn->chosen_exit_optional;
  1352. if (node && !connection_ap_can_use_exit(conn, node)) {
  1353. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1354. "Requested exit point '%s' is excluded or "
  1355. "would refuse request. %s.",
  1356. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1357. if (opt) {
  1358. conn->chosen_exit_optional = 0;
  1359. tor_free(conn->chosen_exit_name);
  1360. /* Try again. */
  1361. return circuit_get_open_circ_or_launch(conn,
  1362. desired_circuit_purpose,
  1363. circp);
  1364. }
  1365. return -1;
  1366. }
  1367. }
  1368. }
  1369. /* is one already on the way? */
  1370. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  1371. need_uptime, need_internal);
  1372. if (circ)
  1373. log_debug(LD_CIRC, "one on the way!");
  1374. if (!circ) {
  1375. extend_info_t *extend_info=NULL;
  1376. uint8_t new_circ_purpose;
  1377. const int n_pending = count_pending_general_client_circuits();
  1378. if (n_pending >= options->MaxClientCircuitsPending) {
  1379. static ratelim_t delay_limit = RATELIM_INIT(10*60);
  1380. char *m;
  1381. if ((m = rate_limit_log(&delay_limit, approx_time()))) {
  1382. log_notice(LD_APP, "We'd like to launch a circuit to handle a "
  1383. "connection, but we already have %d general-purpose client "
  1384. "circuits pending. Waiting until some finish.%s",
  1385. n_pending, m);
  1386. tor_free(m);
  1387. }
  1388. return 0;
  1389. }
  1390. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1391. /* need to pick an intro point */
  1392. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
  1393. tor_assert(rend_data);
  1394. extend_info = rend_client_get_random_intro(rend_data);
  1395. if (!extend_info) {
  1396. log_info(LD_REND,
  1397. "No intro points for '%s': re-fetching service descriptor.",
  1398. safe_str_client(rend_data->onion_address));
  1399. rend_client_refetch_v2_renddesc(rend_data);
  1400. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
  1401. return 0;
  1402. }
  1403. log_info(LD_REND,"Chose %s as intro point for '%s'.",
  1404. extend_info_describe(extend_info),
  1405. safe_str_client(rend_data->onion_address));
  1406. }
  1407. /* If we have specified a particular exit node for our
  1408. * connection, then be sure to open a circuit to that exit node.
  1409. */
  1410. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1411. if (conn->chosen_exit_name) {
  1412. const node_t *r;
  1413. int opt = conn->chosen_exit_optional;
  1414. r = node_get_by_nickname(conn->chosen_exit_name, 1);
  1415. if (r && node_has_descriptor(r)) {
  1416. /* We might want to connect to an IPv6 bridge for loading
  1417. descriptors so we use the preferred address rather than
  1418. the primary. */
  1419. extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
  1420. } else {
  1421. log_debug(LD_DIR, "considering %d, %s",
  1422. want_onehop, conn->chosen_exit_name);
  1423. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  1424. /* We're asking for a one-hop circuit to a router that
  1425. * we don't have a routerinfo about. Make up an extend_info. */
  1426. char digest[DIGEST_LEN];
  1427. char *hexdigest = conn->chosen_exit_name+1;
  1428. tor_addr_t addr;
  1429. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1430. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
  1431. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  1432. return -1;
  1433. }
  1434. if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
  1435. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  1436. escaped_safe_str_client(conn->socks_request->address));
  1437. return -1;
  1438. }
  1439. extend_info = extend_info_new(conn->chosen_exit_name+1,
  1440. digest, NULL, &addr,
  1441. conn->socks_request->port);
  1442. } else {
  1443. /* We will need an onion key for the router, and we
  1444. * don't have one. Refuse or relax requirements. */
  1445. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1446. "Requested exit point '%s' is not known. %s.",
  1447. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1448. if (opt) {
  1449. conn->chosen_exit_optional = 0;
  1450. tor_free(conn->chosen_exit_name);
  1451. /* Try again with no requested exit */
  1452. return circuit_get_open_circ_or_launch(conn,
  1453. desired_circuit_purpose,
  1454. circp);
  1455. }
  1456. return -1;
  1457. }
  1458. }
  1459. }
  1460. }
  1461. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  1462. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  1463. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1464. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  1465. else
  1466. new_circ_purpose = desired_circuit_purpose;
  1467. if (options->Tor2webMode &&
  1468. (new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
  1469. new_circ_purpose == CIRCUIT_PURPOSE_C_INTRODUCING)) {
  1470. want_onehop = 1;
  1471. }
  1472. {
  1473. int flags = CIRCLAUNCH_NEED_CAPACITY;
  1474. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  1475. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1476. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  1477. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  1478. flags);
  1479. }
  1480. extend_info_free(extend_info);
  1481. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1482. /* We just caused a circuit to get built because of this stream.
  1483. * If this stream has caused a _lot_ of circuits to be built, that's
  1484. * a bad sign: we should tell the user. */
  1485. if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
  1486. ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
  1487. log_info(LD_CIRC, "The application request to %s:%d has launched "
  1488. "%d circuits without finding one it likes.",
  1489. escaped_safe_str_client(conn->socks_request->address),
  1490. conn->socks_request->port,
  1491. conn->num_circuits_launched);
  1492. } else {
  1493. /* help predict this next time */
  1494. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  1495. if (circ) {
  1496. /* write the service_id into circ */
  1497. circ->rend_data = rend_data_dup(ENTRY_TO_EDGE_CONN(conn)->rend_data);
  1498. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  1499. circ->base_.state == CIRCUIT_STATE_OPEN)
  1500. rend_client_rendcirc_has_opened(circ);
  1501. }
  1502. }
  1503. } /* endif (!circ) */
  1504. if (circ) {
  1505. /* Mark the circuit with the isolation fields for this connection.
  1506. * When the circuit arrives, we'll clear these flags: this is
  1507. * just some internal bookkeeping to make sure that we have
  1508. * launched enough circuits.
  1509. */
  1510. connection_edge_update_circuit_isolation(conn, circ, 0);
  1511. } else {
  1512. log_info(LD_APP,
  1513. "No safe circuit (purpose %d) ready for edge "
  1514. "connection; delaying.",
  1515. desired_circuit_purpose);
  1516. }
  1517. *circp = circ;
  1518. return 0;
  1519. }
  1520. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  1521. * <b>circ</b>. */
  1522. static int
  1523. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  1524. {
  1525. crypt_path_t *cpath, *cpath_next = NULL;
  1526. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1527. cpath_next = cpath->next;
  1528. if (crypt_path == cpath)
  1529. return 1;
  1530. }
  1531. return 0;
  1532. }
  1533. /** Return true iff client-side optimistic data is supported. */
  1534. static int
  1535. optimistic_data_enabled(void)
  1536. {
  1537. const or_options_t *options = get_options();
  1538. if (options->OptimisticData < 0) {
  1539. /* XXX023 consider having auto default to 1 rather than 0 before
  1540. * the 0.2.3 branch goes stable. See bug 3617. -RD */
  1541. const int32_t enabled =
  1542. networkstatus_get_param(NULL, "UseOptimisticData", 0, 0, 1);
  1543. return (int)enabled;
  1544. }
  1545. return options->OptimisticData;
  1546. }
  1547. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  1548. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  1549. * hop in circ's cpath if <b>cpath</b> is NULL.
  1550. */
  1551. static void
  1552. link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
  1553. crypt_path_t *cpath)
  1554. {
  1555. const node_t *exitnode;
  1556. /* add it into the linked list of streams on this circuit */
  1557. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %d.",
  1558. circ->base_.n_circ_id);
  1559. /* reset it, so we can measure circ timeouts */
  1560. ENTRY_TO_CONN(apconn)->timestamp_lastread = time(NULL);
  1561. ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
  1562. ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
  1563. /* assert_connection_ok(conn, time(NULL)); */
  1564. circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
  1565. if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
  1566. /* We are attaching a stream to a rendezvous circuit. That means
  1567. * that an attempt to connect to a hidden service just
  1568. * succeeded. Tell rendclient.c. */
  1569. rend_client_note_connection_attempt_ended(
  1570. ENTRY_TO_EDGE_CONN(apconn)->rend_data->onion_address);
  1571. }
  1572. if (cpath) { /* we were given one; use it */
  1573. tor_assert(cpath_is_on_circuit(circ, cpath));
  1574. } else {
  1575. /* use the last hop in the circuit */
  1576. tor_assert(circ->cpath);
  1577. tor_assert(circ->cpath->prev);
  1578. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  1579. cpath = circ->cpath->prev;
  1580. }
  1581. ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
  1582. circ->isolation_any_streams_attached = 1;
  1583. connection_edge_update_circuit_isolation(apconn, circ, 0);
  1584. /* See if we can use optimistic data on this circuit */
  1585. if (cpath->extend_info &&
  1586. (exitnode = node_get_by_id(cpath->extend_info->identity_digest)) &&
  1587. exitnode->rs) {
  1588. /* Okay; we know what exit node this is. */
  1589. if (optimistic_data_enabled() &&
  1590. circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  1591. exitnode->rs->version_supports_optimistic_data)
  1592. apconn->may_use_optimistic_data = 1;
  1593. else
  1594. apconn->may_use_optimistic_data = 0;
  1595. log_info(LD_APP, "Looks like completed circuit to %s %s allow "
  1596. "optimistic data for connection to %s",
  1597. safe_str_client(node_describe(exitnode)),
  1598. apconn->may_use_optimistic_data ? "does" : "doesn't",
  1599. safe_str_client(apconn->socks_request->address));
  1600. }
  1601. }
  1602. /** Return true iff <b>address</b> is matched by one of the entries in
  1603. * TrackHostExits. */
  1604. int
  1605. hostname_in_track_host_exits(const or_options_t *options, const char *address)
  1606. {
  1607. if (!options->TrackHostExits)
  1608. return 0;
  1609. SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
  1610. if (cp[0] == '.') { /* match end */
  1611. if (cp[1] == '\0' ||
  1612. !strcasecmpend(address, cp) ||
  1613. !strcasecmp(address, &cp[1]))
  1614. return 1;
  1615. } else if (strcasecmp(cp, address) == 0) {
  1616. return 1;
  1617. }
  1618. } SMARTLIST_FOREACH_END(cp);
  1619. return 0;
  1620. }
  1621. /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
  1622. * the exit that we *did* choose for use by future connections to
  1623. * <b>conn</b>'s destination.
  1624. */
  1625. static void
  1626. consider_recording_trackhost(const entry_connection_t *conn,
  1627. const origin_circuit_t *circ)
  1628. {
  1629. const or_options_t *options = get_options();
  1630. char *new_address = NULL;
  1631. char fp[HEX_DIGEST_LEN+1];
  1632. /* Search the addressmap for this conn's destination. */
  1633. /* If he's not in the address map.. */
  1634. if (!options->TrackHostExits ||
  1635. addressmap_have_mapping(conn->socks_request->address,
  1636. options->TrackHostExitsExpire))
  1637. return; /* nothing to track, or already mapped */
  1638. if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
  1639. !circ->build_state->chosen_exit)
  1640. return;
  1641. /* write down the fingerprint of the chosen exit, not the nickname,
  1642. * because the chosen exit might not be named. */
  1643. base16_encode(fp, sizeof(fp),
  1644. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  1645. /* Add this exit/hostname pair to the addressmap. */
  1646. tor_asprintf(&new_address, "%s.%s.exit",
  1647. conn->socks_request->address, fp);
  1648. addressmap_register(conn->socks_request->address, new_address,
  1649. time(NULL) + options->TrackHostExitsExpire,
  1650. ADDRMAPSRC_TRACKEXIT, 0, 0);
  1651. }
  1652. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  1653. * begin or resolve cell as appropriate. Return values are as for
  1654. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  1655. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1656. * <b>cpath</b> is NULL. */
  1657. int
  1658. connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
  1659. origin_circuit_t *circ,
  1660. crypt_path_t *cpath)
  1661. {
  1662. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1663. tor_assert(conn);
  1664. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
  1665. base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
  1666. tor_assert(conn->socks_request);
  1667. tor_assert(circ);
  1668. tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
  1669. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1670. if (!circ->base_.timestamp_dirty)
  1671. circ->base_.timestamp_dirty = time(NULL);
  1672. link_apconn_to_circ(conn, circ, cpath);
  1673. tor_assert(conn->socks_request);
  1674. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  1675. if (!conn->use_begindir)
  1676. consider_recording_trackhost(conn, circ);
  1677. if (connection_ap_handshake_send_begin(conn) < 0)
  1678. return -1;
  1679. } else {
  1680. if (connection_ap_handshake_send_resolve(conn) < 0)
  1681. return -1;
  1682. }
  1683. return 1;
  1684. }
  1685. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1686. * we don't find one: if conn cannot be handled by any known nodes,
  1687. * warn and return -1 (conn needs to die, and is maybe already marked);
  1688. * else launch new circuit (if necessary) and return 0.
  1689. * Otherwise, associate conn with a safe live circuit, do the
  1690. * right next step, and return 1.
  1691. */
  1692. /* XXXX this function should mark for close whenever it returns -1;
  1693. * its callers shouldn't have to worry about that. */
  1694. int
  1695. connection_ap_handshake_attach_circuit(entry_connection_t *conn)
  1696. {
  1697. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1698. int retval;
  1699. int conn_age;
  1700. int want_onehop;
  1701. tor_assert(conn);
  1702. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1703. tor_assert(conn->socks_request);
  1704. want_onehop = conn->want_onehop;
  1705. conn_age = (int)(time(NULL) - base_conn->timestamp_created);
  1706. if (conn_age >= get_options()->SocksTimeout) {
  1707. int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
  1708. LOG_INFO : LOG_NOTICE;
  1709. log_fn(severity, LD_APP,
  1710. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1711. conn_age, safe_str_client(conn->socks_request->address),
  1712. conn->socks_request->port);
  1713. return -1;
  1714. }
  1715. if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
  1716. /* we're a general conn */
  1717. origin_circuit_t *circ=NULL;
  1718. if (conn->chosen_exit_name) {
  1719. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1720. int opt = conn->chosen_exit_optional;
  1721. if (!node && !want_onehop) {
  1722. /* We ran into this warning when trying to extend a circuit to a
  1723. * hidden service directory for which we didn't have a router
  1724. * descriptor. See flyspray task 767 for more details. We should
  1725. * keep this in mind when deciding to use BEGIN_DIR cells for other
  1726. * directory requests as well. -KL*/
  1727. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1728. "Requested exit point '%s' is not known. %s.",
  1729. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1730. if (opt) {
  1731. conn->chosen_exit_optional = 0;
  1732. tor_free(conn->chosen_exit_name);
  1733. return 0;
  1734. }
  1735. return -1;
  1736. }
  1737. if (node && !connection_ap_can_use_exit(conn, node)) {
  1738. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1739. "Requested exit point '%s' is excluded or "
  1740. "would refuse request. %s.",
  1741. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1742. if (opt) {
  1743. conn->chosen_exit_optional = 0;
  1744. tor_free(conn->chosen_exit_name);
  1745. return 0;
  1746. }
  1747. return -1;
  1748. }
  1749. }
  1750. /* find the circuit that we should use, if there is one. */
  1751. retval = circuit_get_open_circ_or_launch(
  1752. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1753. if (retval < 1) // XXX023 if we totally fail, this still returns 0 -RD
  1754. return retval;
  1755. log_debug(LD_APP|LD_CIRC,
  1756. "Attaching apconn to circ %d (stream %d sec old).",
  1757. circ->base_.n_circ_id, conn_age);
  1758. /* print the circ's path, so people can figure out which circs are
  1759. * sucking. */
  1760. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1761. /* We have found a suitable circuit for our conn. Hurray. */
  1762. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  1763. } else { /* we're a rendezvous conn */
  1764. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  1765. tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
  1766. /* start by finding a rendezvous circuit for us */
  1767. retval = circuit_get_open_circ_or_launch(
  1768. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1769. if (retval < 0) return -1; /* failed */
  1770. if (retval > 0) {
  1771. tor_assert(rendcirc);
  1772. /* one is already established, attach */
  1773. log_info(LD_REND,
  1774. "rend joined circ %d already here. attaching. "
  1775. "(stream %d sec old)",
  1776. rendcirc->base_.n_circ_id, conn_age);
  1777. /* Mark rendezvous circuits as 'newly dirty' every time you use
  1778. * them, since the process of rebuilding a rendezvous circ is so
  1779. * expensive. There is a tradeoff between linkability and
  1780. * feasibility, at this point.
  1781. */
  1782. rendcirc->base_.timestamp_dirty = time(NULL);
  1783. link_apconn_to_circ(conn, rendcirc, NULL);
  1784. if (connection_ap_handshake_send_begin(conn) < 0)
  1785. return 0; /* already marked, let them fade away */
  1786. return 1;
  1787. }
  1788. if (rendcirc && (rendcirc->base_.purpose ==
  1789. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  1790. log_info(LD_REND,
  1791. "pending-join circ %d already here, with intro ack. "
  1792. "Stalling. (stream %d sec old)",
  1793. rendcirc->base_.n_circ_id, conn_age);
  1794. return 0;
  1795. }
  1796. /* it's on its way. find an intro circ. */
  1797. retval = circuit_get_open_circ_or_launch(
  1798. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  1799. if (retval < 0) return -1; /* failed */
  1800. if (retval > 0) {
  1801. /* one has already sent the intro. keep waiting. */
  1802. circuit_t *c = NULL;
  1803. tor_assert(introcirc);
  1804. log_info(LD_REND, "Intro circ %d present and awaiting ack (rend %d). "
  1805. "Stalling. (stream %d sec old)",
  1806. introcirc->base_.n_circ_id,
  1807. rendcirc ? rendcirc->base_.n_circ_id : 0,
  1808. conn_age);
  1809. /* abort parallel intro circs, if any */
  1810. for (c = global_circuitlist; c; c = c->next) {
  1811. if (c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1812. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  1813. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  1814. if (oc->rend_data &&
  1815. !rend_cmp_service_ids(
  1816. ENTRY_TO_EDGE_CONN(conn)->rend_data->onion_address,
  1817. oc->rend_data->onion_address)) {
  1818. log_info(LD_REND|LD_CIRC, "Closing introduction circuit that we "
  1819. "built in parallel.");
  1820. circuit_mark_for_close(c, END_CIRC_REASON_TIMEOUT);
  1821. }
  1822. }
  1823. }
  1824. return 0;
  1825. }
  1826. /* now rendcirc and introcirc are each either undefined or not finished */
  1827. if (rendcirc && introcirc &&
  1828. rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  1829. log_info(LD_REND,
  1830. "ready rend circ %d already here (no intro-ack yet on "
  1831. "intro %d). (stream %d sec old)",
  1832. rendcirc->base_.n_circ_id,
  1833. introcirc->base_.n_circ_id, conn_age);
  1834. tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  1835. if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
  1836. log_info(LD_REND,"found open intro circ %d (rend %d); sending "
  1837. "introduction. (stream %d sec old)",
  1838. introcirc->base_.n_circ_id, rendcirc->base_.n_circ_id,
  1839. conn_age);
  1840. switch (rend_client_send_introduction(introcirc, rendcirc)) {
  1841. case 0: /* success */
  1842. rendcirc->base_.timestamp_dirty = time(NULL);
  1843. introcirc->base_.timestamp_dirty = time(NULL);
  1844. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  1845. assert_circuit_ok(TO_CIRCUIT(introcirc));
  1846. return 0;
  1847. case -1: /* transient error */
  1848. return 0;
  1849. case -2: /* permanent error */
  1850. return -1;
  1851. default: /* oops */
  1852. tor_fragile_assert();
  1853. return -1;
  1854. }
  1855. }
  1856. }
  1857. log_info(LD_REND, "Intro (%d) and rend (%d) circs are not both ready. "
  1858. "Stalling conn. (%d sec old)",
  1859. introcirc ? introcirc->base_.n_circ_id : 0,
  1860. rendcirc ? rendcirc->base_.n_circ_id : 0, conn_age);
  1861. return 0;
  1862. }
  1863. }
  1864. /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
  1865. void
  1866. circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
  1867. {
  1868. uint8_t old_purpose;
  1869. /* Don't allow an OR circ to become an origin circ or vice versa. */
  1870. tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
  1871. !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
  1872. if (circ->purpose == new_purpose) return;
  1873. if (CIRCUIT_IS_ORIGIN(circ)) {
  1874. char old_purpose_desc[80] = "";
  1875. strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
  1876. old_purpose_desc[80-1] = '\0';
  1877. log_debug(LD_CIRC,
  1878. "changing purpose of origin circ %d "
  1879. "from \"%s\" (%d) to \"%s\" (%d)",
  1880. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1881. old_purpose_desc,
  1882. circ->purpose,
  1883. circuit_purpose_to_string(new_purpose),
  1884. new_purpose);
  1885. }
  1886. old_purpose = circ->purpose;
  1887. circ->purpose = new_purpose;
  1888. if (CIRCUIT_IS_ORIGIN(circ)) {
  1889. control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
  1890. old_purpose);
  1891. }
  1892. }