circuituse.c 77 KB

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