circuituse.c 99 KB

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