circuituse.c 104 KB

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