circuituse.c 105 KB

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