circuituse.c 92 KB

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