circuituse.c 118 KB

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