circuituse.c 99 KB

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