circuituse.c 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335
  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,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. 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. /** Remove any elements in <b>needed_ports</b> that are handled by an
  716. * open or in-progress circuit.
  717. */
  718. void
  719. circuit_remove_handled_ports(smartlist_t *needed_ports)
  720. {
  721. int i;
  722. uint16_t *port;
  723. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  724. port = smartlist_get(needed_ports, i);
  725. tor_assert(*port);
  726. if (circuit_stream_is_being_handled(NULL, *port,
  727. MIN_CIRCUITS_HANDLING_STREAM)) {
  728. // log_debug(LD_CIRC,"Port %d is already being handled; removing.", port);
  729. smartlist_del(needed_ports, i--);
  730. tor_free(port);
  731. } else {
  732. log_debug(LD_CIRC,"Port %d is not handled.", *port);
  733. }
  734. }
  735. }
  736. /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
  737. * will have an acceptable exit node for exit stream <b>conn</b> if it
  738. * is defined, else for "*:port".
  739. * Else return 0.
  740. */
  741. int
  742. circuit_stream_is_being_handled(entry_connection_t *conn,
  743. uint16_t port, int min)
  744. {
  745. circuit_t *circ;
  746. const node_t *exitnode;
  747. int num=0;
  748. time_t now = time(NULL);
  749. int need_uptime = smartlist_contains_int_as_string(
  750. get_options()->LongLivedPorts,
  751. conn ? conn->socks_request->port : port);
  752. TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
  753. if (CIRCUIT_IS_ORIGIN(circ) &&
  754. !circ->marked_for_close &&
  755. circ->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  756. (!circ->timestamp_dirty ||
  757. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
  758. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  759. cpath_build_state_t *build_state = origin_circ->build_state;
  760. if (build_state->is_internal || build_state->onehop_tunnel)
  761. continue;
  762. if (origin_circ->unusable_for_new_conns)
  763. continue;
  764. exitnode = build_state_get_exit_node(build_state);
  765. if (exitnode && (!need_uptime || build_state->need_uptime)) {
  766. int ok;
  767. if (conn) {
  768. ok = connection_ap_can_use_exit(conn, exitnode);
  769. } else {
  770. addr_policy_result_t r;
  771. r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
  772. ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
  773. }
  774. if (ok) {
  775. if (++num >= min)
  776. return 1;
  777. }
  778. }
  779. }
  780. }
  781. return 0;
  782. }
  783. /** Don't keep more than this many unused open circuits around. */
  784. #define MAX_UNUSED_OPEN_CIRCUITS 14
  785. /** Figure out how many circuits we have open that are clean. Make
  786. * sure it's enough for all the upcoming behaviors we predict we'll have.
  787. * But put an upper bound on the total number of circuits.
  788. */
  789. static void
  790. circuit_predict_and_launch_new(void)
  791. {
  792. circuit_t *circ;
  793. int num=0, num_internal=0, num_uptime_internal=0;
  794. int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
  795. int port_needs_uptime=0, port_needs_capacity=1;
  796. time_t now = time(NULL);
  797. int flags = 0;
  798. /* First, count how many of each type of circuit we have already. */
  799. TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
  800. cpath_build_state_t *build_state;
  801. origin_circuit_t *origin_circ;
  802. if (!CIRCUIT_IS_ORIGIN(circ))
  803. continue;
  804. if (circ->marked_for_close)
  805. continue; /* don't mess with marked circs */
  806. if (circ->timestamp_dirty)
  807. continue; /* only count clean circs */
  808. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  809. continue; /* only pay attention to general-purpose circs */
  810. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  811. if (origin_circ->unusable_for_new_conns)
  812. continue;
  813. build_state = origin_circ->build_state;
  814. if (build_state->onehop_tunnel)
  815. continue;
  816. num++;
  817. if (build_state->is_internal)
  818. num_internal++;
  819. if (build_state->need_uptime && build_state->is_internal)
  820. num_uptime_internal++;
  821. }
  822. /* If that's enough, then stop now. */
  823. if (num >= MAX_UNUSED_OPEN_CIRCUITS)
  824. return; /* we already have many, making more probably will hurt */
  825. /* Second, see if we need any more exit circuits. */
  826. /* check if we know of a port that's been requested recently
  827. * and no circuit is currently available that can handle it. */
  828. if (!circuit_all_predicted_ports_handled(now, &port_needs_uptime,
  829. &port_needs_capacity)) {
  830. if (port_needs_uptime)
  831. flags |= CIRCLAUNCH_NEED_UPTIME;
  832. if (port_needs_capacity)
  833. flags |= CIRCLAUNCH_NEED_CAPACITY;
  834. log_info(LD_CIRC,
  835. "Have %d clean circs (%d internal), need another exit circ.",
  836. num, num_internal);
  837. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  838. return;
  839. }
  840. /* Third, see if we need any more hidden service (server) circuits. */
  841. if (num_rend_services() && num_uptime_internal < 3) {
  842. flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
  843. CIRCLAUNCH_IS_INTERNAL);
  844. log_info(LD_CIRC,
  845. "Have %d clean circs (%d internal), need another internal "
  846. "circ for my hidden service.",
  847. num, num_internal);
  848. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  849. return;
  850. }
  851. /* Fourth, see if we need any more hidden service (client) circuits. */
  852. if (rep_hist_get_predicted_internal(now, &hidserv_needs_uptime,
  853. &hidserv_needs_capacity) &&
  854. ((num_uptime_internal<2 && hidserv_needs_uptime) ||
  855. num_internal<2)) {
  856. if (hidserv_needs_uptime)
  857. flags |= CIRCLAUNCH_NEED_UPTIME;
  858. if (hidserv_needs_capacity)
  859. flags |= CIRCLAUNCH_NEED_CAPACITY;
  860. flags |= CIRCLAUNCH_IS_INTERNAL;
  861. log_info(LD_CIRC,
  862. "Have %d clean circs (%d uptime-internal, %d internal), need"
  863. " another hidden service circ.",
  864. num, num_uptime_internal, num_internal);
  865. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  866. return;
  867. }
  868. /* Finally, check to see if we still need more circuits to learn
  869. * a good build timeout. But if we're close to our max number we
  870. * want, don't do another -- we want to leave a few slots open so
  871. * we can still build circuits preemptively as needed. */
  872. if (num < MAX_UNUSED_OPEN_CIRCUITS-2 &&
  873. ! circuit_build_times_disabled() &&
  874. circuit_build_times_needs_circuits_now(get_circuit_build_times())) {
  875. flags = CIRCLAUNCH_NEED_CAPACITY;
  876. log_info(LD_CIRC,
  877. "Have %d clean circs need another buildtime test circ.", num);
  878. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
  879. return;
  880. }
  881. }
  882. /** Build a new test circuit every 5 minutes */
  883. #define TESTING_CIRCUIT_INTERVAL 300
  884. /** This function is called once a second, if router_have_min_dir_info() is
  885. * true. Its job is to make sure all services we offer have enough circuits
  886. * available. Some services just want enough circuits for current tasks,
  887. * whereas others want a minimum set of idle circuits hanging around.
  888. */
  889. void
  890. circuit_build_needed_circs(time_t now)
  891. {
  892. static time_t time_to_new_circuit = 0;
  893. const or_options_t *options = get_options();
  894. /* launch a new circ for any pending streams that need one */
  895. connection_ap_attach_pending();
  896. /* make sure any hidden services have enough intro points */
  897. rend_services_introduce();
  898. if (time_to_new_circuit < now) {
  899. circuit_reset_failure_count(1);
  900. time_to_new_circuit = now + options->NewCircuitPeriod;
  901. if (proxy_mode(get_options()))
  902. addressmap_clean(now);
  903. circuit_expire_old_circuits_clientside();
  904. #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
  905. circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
  906. if (get_options()->RunTesting &&
  907. circ &&
  908. circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
  909. log_fn(LOG_INFO,"Creating a new testing circuit.");
  910. circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
  911. }
  912. #endif
  913. }
  914. if (!options->DisablePredictedCircuits)
  915. circuit_predict_and_launch_new();
  916. }
  917. /** If the stream <b>conn</b> is a member of any of the linked
  918. * lists of <b>circ</b>, then remove it from the list.
  919. */
  920. void
  921. circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
  922. {
  923. edge_connection_t *prevconn;
  924. tor_assert(circ);
  925. tor_assert(conn);
  926. if (conn->base_.type == CONN_TYPE_AP) {
  927. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  928. entry_conn->may_use_optimistic_data = 0;
  929. }
  930. conn->cpath_layer = NULL; /* don't keep a stale pointer */
  931. conn->on_circuit = NULL;
  932. if (CIRCUIT_IS_ORIGIN(circ)) {
  933. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  934. if (conn == origin_circ->p_streams) {
  935. origin_circ->p_streams = conn->next_stream;
  936. return;
  937. }
  938. for (prevconn = origin_circ->p_streams;
  939. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  940. prevconn = prevconn->next_stream)
  941. ;
  942. if (prevconn && prevconn->next_stream) {
  943. prevconn->next_stream = conn->next_stream;
  944. return;
  945. }
  946. } else {
  947. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  948. if (conn == or_circ->n_streams) {
  949. or_circ->n_streams = conn->next_stream;
  950. return;
  951. }
  952. if (conn == or_circ->resolving_streams) {
  953. or_circ->resolving_streams = conn->next_stream;
  954. return;
  955. }
  956. for (prevconn = or_circ->n_streams;
  957. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  958. prevconn = prevconn->next_stream)
  959. ;
  960. if (prevconn && prevconn->next_stream) {
  961. prevconn->next_stream = conn->next_stream;
  962. return;
  963. }
  964. for (prevconn = or_circ->resolving_streams;
  965. prevconn && prevconn->next_stream && prevconn->next_stream != conn;
  966. prevconn = prevconn->next_stream)
  967. ;
  968. if (prevconn && prevconn->next_stream) {
  969. prevconn->next_stream = conn->next_stream;
  970. return;
  971. }
  972. }
  973. log_warn(LD_BUG,"Edge connection not in circuit's list.");
  974. /* Don't give an error here; it's harmless. */
  975. tor_fragile_assert();
  976. }
  977. /** If we haven't yet decided on a good timeout value for circuit
  978. * building, we close idles circuits aggressively so we can get more
  979. * data points. */
  980. #define IDLE_TIMEOUT_WHILE_LEARNING (10*60)
  981. /** Find each circuit that has been unused for too long, or dirty
  982. * for too long and has no streams on it: mark it for close.
  983. */
  984. static void
  985. circuit_expire_old_circuits_clientside(void)
  986. {
  987. circuit_t *circ;
  988. struct timeval cutoff, now;
  989. tor_gettimeofday(&now);
  990. cutoff = now;
  991. if (! circuit_build_times_disabled() &&
  992. circuit_build_times_needs_circuits(get_circuit_build_times())) {
  993. /* Circuits should be shorter lived if we need more of them
  994. * for learning a good build timeout */
  995. cutoff.tv_sec -= IDLE_TIMEOUT_WHILE_LEARNING;
  996. } else {
  997. cutoff.tv_sec -= get_options()->CircuitIdleTimeout;
  998. }
  999. TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
  1000. if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
  1001. continue;
  1002. /* If the circuit has been dirty for too long, and there are no streams
  1003. * on it, mark it for close.
  1004. */
  1005. if (circ->timestamp_dirty &&
  1006. circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
  1007. now.tv_sec &&
  1008. !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
  1009. log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
  1010. "purpose %d)",
  1011. (unsigned)circ->n_circ_id,
  1012. (long)(now.tv_sec - circ->timestamp_dirty),
  1013. circ->purpose);
  1014. /* Don't do this magic for testing circuits. Their death is governed
  1015. * by circuit_expire_building */
  1016. if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
  1017. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1018. } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
  1019. if (timercmp(&circ->timestamp_began, &cutoff, <)) {
  1020. if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
  1021. circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
  1022. circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
  1023. circ->purpose == CIRCUIT_PURPOSE_TESTING ||
  1024. (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  1025. circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
  1026. circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
  1027. log_debug(LD_CIRC,
  1028. "Closing circuit that has been unused for %ld msec.",
  1029. tv_mdiff(&circ->timestamp_began, &now));
  1030. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1031. } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
  1032. /* Server-side rend joined circuits can end up really old, because
  1033. * they are reused by clients for longer than normal. The client
  1034. * controls their lifespan. (They never become dirty, because
  1035. * connection_exit_begin_conn() never marks anything as dirty.)
  1036. * Similarly, server-side intro circuits last a long time. */
  1037. if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
  1038. circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
  1039. log_notice(LD_CIRC,
  1040. "Ancient non-dirty circuit %d is still around after "
  1041. "%ld milliseconds. Purpose: %d (%s)",
  1042. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1043. tv_mdiff(&circ->timestamp_began, &now),
  1044. circ->purpose,
  1045. circuit_purpose_to_string(circ->purpose));
  1046. TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. }
  1052. }
  1053. /** How long do we wait before killing circuits with the properties
  1054. * described below?
  1055. *
  1056. * Probably we could choose a number here as low as 5 to 10 seconds,
  1057. * since these circs are used for begindir, and a) generally you either
  1058. * ask another begindir question right after or you don't for a long time,
  1059. * b) clients at least through 0.2.1.x choose from the whole set of
  1060. * directory mirrors at each choice, and c) re-establishing a one-hop
  1061. * circuit via create-fast is a light operation assuming the TLS conn is
  1062. * still there.
  1063. *
  1064. * I expect "b" to go away one day when we move to using directory
  1065. * guards, but I think "a" and "c" are good enough reasons that a low
  1066. * number is safe even then.
  1067. */
  1068. #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
  1069. /** Find each non-origin circuit that has been unused for too long,
  1070. * has no streams on it, used a create_fast, and ends here: mark it
  1071. * for close.
  1072. */
  1073. void
  1074. circuit_expire_old_circuits_serverside(time_t now)
  1075. {
  1076. circuit_t *circ;
  1077. or_circuit_t *or_circ;
  1078. time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
  1079. TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
  1080. if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
  1081. continue;
  1082. or_circ = TO_OR_CIRCUIT(circ);
  1083. /* If the circuit has been idle for too long, and there are no streams
  1084. * on it, and it ends here, and it used a create_fast, mark it for close.
  1085. */
  1086. if (or_circ->is_first_hop && !circ->n_chan &&
  1087. !or_circ->n_streams && !or_circ->resolving_streams &&
  1088. or_circ->p_chan &&
  1089. channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
  1090. log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
  1091. (unsigned)or_circ->p_circ_id,
  1092. (int)(now - channel_when_last_xmit(or_circ->p_chan)));
  1093. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1094. }
  1095. }
  1096. }
  1097. /** Number of testing circuits we want open before testing our bandwidth. */
  1098. #define NUM_PARALLEL_TESTING_CIRCS 4
  1099. /** True iff we've ever had enough testing circuits open to test our
  1100. * bandwidth. */
  1101. static int have_performed_bandwidth_test = 0;
  1102. /** Reset have_performed_bandwidth_test, so we'll start building
  1103. * testing circuits again so we can exercise our bandwidth. */
  1104. void
  1105. reset_bandwidth_test(void)
  1106. {
  1107. have_performed_bandwidth_test = 0;
  1108. }
  1109. /** Return 1 if we've already exercised our bandwidth, or if we
  1110. * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
  1111. * established or on the way. Else return 0.
  1112. */
  1113. int
  1114. circuit_enough_testing_circs(void)
  1115. {
  1116. circuit_t *circ;
  1117. int num = 0;
  1118. if (have_performed_bandwidth_test)
  1119. return 1;
  1120. TOR_LIST_FOREACH(circ, circuit_get_global_list(), head) {
  1121. if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
  1122. circ->purpose == CIRCUIT_PURPOSE_TESTING &&
  1123. circ->state == CIRCUIT_STATE_OPEN)
  1124. num++;
  1125. }
  1126. return num >= NUM_PARALLEL_TESTING_CIRCS;
  1127. }
  1128. /** A testing circuit has completed. Take whatever stats we want.
  1129. * Noticing reachability is taken care of in onionskin_answer(),
  1130. * so there's no need to record anything here. But if we still want
  1131. * to do the bandwidth test, and we now have enough testing circuits
  1132. * open, do it.
  1133. */
  1134. static void
  1135. circuit_testing_opened(origin_circuit_t *circ)
  1136. {
  1137. if (have_performed_bandwidth_test ||
  1138. !check_whether_orport_reachable()) {
  1139. /* either we've already done everything we want with testing circuits,
  1140. * or this testing circuit became open due to a fluke, e.g. we picked
  1141. * a last hop where we already had the connection open due to an
  1142. * outgoing local circuit. */
  1143. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1144. } else if (circuit_enough_testing_circs()) {
  1145. router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
  1146. have_performed_bandwidth_test = 1;
  1147. } else
  1148. consider_testing_reachability(1, 0);
  1149. }
  1150. /** A testing circuit has failed to build. Take whatever stats we want. */
  1151. static void
  1152. circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
  1153. {
  1154. if (server_mode(get_options()) && check_whether_orport_reachable())
  1155. return;
  1156. log_info(LD_GENERAL,
  1157. "Our testing circuit (to see if your ORPort is reachable) "
  1158. "has failed. I'll try again later.");
  1159. /* These aren't used yet. */
  1160. (void)circ;
  1161. (void)at_last_hop;
  1162. }
  1163. /** The circuit <b>circ</b> has just become open. Take the next
  1164. * step: for rendezvous circuits, we pass circ to the appropriate
  1165. * function in rendclient or rendservice. For general circuits, we
  1166. * call connection_ap_attach_pending, which looks for pending streams
  1167. * that could use circ.
  1168. */
  1169. void
  1170. circuit_has_opened(origin_circuit_t *circ)
  1171. {
  1172. control_event_circuit_status(circ, CIRC_EVENT_BUILT, 0);
  1173. /* Remember that this circuit has finished building. Now if we start
  1174. * it building again later (e.g. by extending it), we will know not
  1175. * to consider its build time. */
  1176. circ->has_opened = 1;
  1177. switch (TO_CIRCUIT(circ)->purpose) {
  1178. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1179. rend_client_rendcirc_has_opened(circ);
  1180. /* Start building an intro circ if we don't have one yet. */
  1181. connection_ap_attach_pending();
  1182. /* This isn't a call to circuit_try_attaching_streams because a
  1183. * circuit in _C_ESTABLISH_REND state isn't connected to its
  1184. * hidden service yet, thus we can't attach streams to it yet,
  1185. * thus circuit_try_attaching_streams would always clear the
  1186. * circuit's isolation state. circuit_try_attaching_streams is
  1187. * called later, when the rend circ enters _C_REND_JOINED
  1188. * state. */
  1189. break;
  1190. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1191. rend_client_introcirc_has_opened(circ);
  1192. break;
  1193. case CIRCUIT_PURPOSE_C_GENERAL:
  1194. /* Tell any AP connections that have been waiting for a new
  1195. * circuit that one is ready. */
  1196. circuit_try_attaching_streams(circ);
  1197. break;
  1198. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1199. /* at Bob, waiting for introductions */
  1200. rend_service_intro_has_opened(circ);
  1201. break;
  1202. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1203. /* at Bob, connecting to rend point */
  1204. rend_service_rendezvous_has_opened(circ);
  1205. break;
  1206. case CIRCUIT_PURPOSE_TESTING:
  1207. circuit_testing_opened(circ);
  1208. break;
  1209. /* default:
  1210. * This won't happen in normal operation, but might happen if the
  1211. * controller did it. Just let it slide. */
  1212. }
  1213. }
  1214. /** If the stream-isolation state of <b>circ</b> can be cleared, clear
  1215. * it. Return non-zero iff <b>circ</b>'s isolation state was cleared. */
  1216. static int
  1217. circuit_try_clearing_isolation_state(origin_circuit_t *circ)
  1218. {
  1219. if (/* The circuit may have become non-open if it was cannibalized.*/
  1220. circ->base_.state == CIRCUIT_STATE_OPEN &&
  1221. /* If !isolation_values_set, there is nothing to clear. */
  1222. circ->isolation_values_set &&
  1223. /* It's not legal to clear a circuit's isolation info if it's ever had
  1224. * streams attached */
  1225. !circ->isolation_any_streams_attached) {
  1226. /* If we have any isolation information set on this circuit, and
  1227. * we didn't manage to attach any streams to it, then we can
  1228. * and should clear it and try again. */
  1229. circuit_clear_isolation(circ);
  1230. return 1;
  1231. } else {
  1232. return 0;
  1233. }
  1234. }
  1235. /** Called when a circuit becomes ready for streams to be attached to
  1236. * it. */
  1237. void
  1238. circuit_try_attaching_streams(origin_circuit_t *circ)
  1239. {
  1240. /* Attach streams to this circuit if we can. */
  1241. connection_ap_attach_pending();
  1242. /* The call to circuit_try_clearing_isolation_state here will do
  1243. * nothing and return 0 if we didn't attach any streams to circ
  1244. * above. */
  1245. if (circuit_try_clearing_isolation_state(circ)) {
  1246. /* Maybe *now* we can attach some streams to this circuit. */
  1247. connection_ap_attach_pending();
  1248. }
  1249. }
  1250. /** Called whenever a circuit could not be successfully built.
  1251. */
  1252. void
  1253. circuit_build_failed(origin_circuit_t *circ)
  1254. {
  1255. channel_t *n_chan = NULL;
  1256. /* we should examine circ and see if it failed because of
  1257. * the last hop or an earlier hop. then use this info below.
  1258. */
  1259. int failed_at_last_hop = 0;
  1260. /* If the last hop isn't open, and the second-to-last is, we failed
  1261. * at the last hop. */
  1262. if (circ->cpath &&
  1263. circ->cpath->prev->state != CPATH_STATE_OPEN &&
  1264. circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
  1265. failed_at_last_hop = 1;
  1266. }
  1267. if (circ->cpath &&
  1268. circ->cpath->state != CPATH_STATE_OPEN &&
  1269. ! circ->base_.received_destroy) {
  1270. /* We failed at the first hop for some reason other than a DESTROY cell.
  1271. * If there's an OR connection to blame, blame it. Also, avoid this relay
  1272. * for a while, and fail any one-hop directory fetches destined for it. */
  1273. const char *n_chan_id = circ->cpath->extend_info->identity_digest;
  1274. int already_marked = 0;
  1275. if (circ->base_.n_chan) {
  1276. n_chan = circ->base_.n_chan;
  1277. if (n_chan->is_bad_for_new_circs) {
  1278. /* We only want to blame this router when a fresh healthy
  1279. * connection fails. So don't mark this router as newly failed,
  1280. * since maybe this was just an old circuit attempt that's
  1281. * finally timing out now. Also, there's no need to blow away
  1282. * circuits/streams/etc, since the failure of an unhealthy conn
  1283. * doesn't tell us much about whether a healthy conn would
  1284. * succeed. */
  1285. already_marked = 1;
  1286. }
  1287. log_info(LD_OR,
  1288. "Our circuit failed to get a response from the first hop "
  1289. "(%s). I'm going to try to rotate to a better connection.",
  1290. channel_get_canonical_remote_descr(n_chan));
  1291. n_chan->is_bad_for_new_circs = 1;
  1292. } else {
  1293. log_info(LD_OR,
  1294. "Our circuit died before the first hop with no connection");
  1295. }
  1296. if (n_chan_id && !already_marked) {
  1297. entry_guard_register_connect_status(n_chan_id, 0, 1, time(NULL));
  1298. /* if there are any one-hop streams waiting on this circuit, fail
  1299. * them now so they can retry elsewhere. */
  1300. connection_ap_fail_onehop(n_chan_id, circ->build_state);
  1301. }
  1302. }
  1303. switch (circ->base_.purpose) {
  1304. case CIRCUIT_PURPOSE_C_GENERAL:
  1305. /* If we never built the circuit, note it as a failure. */
  1306. circuit_increment_failure_count();
  1307. if (failed_at_last_hop) {
  1308. /* Make sure any streams that demand our last hop as their exit
  1309. * know that it's unlikely to happen. */
  1310. circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
  1311. }
  1312. break;
  1313. case CIRCUIT_PURPOSE_TESTING:
  1314. circuit_testing_failed(circ, failed_at_last_hop);
  1315. break;
  1316. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1317. /* at Bob, waiting for introductions */
  1318. if (circ->base_.state != CIRCUIT_STATE_OPEN) {
  1319. circuit_increment_failure_count();
  1320. }
  1321. /* no need to care here, because bob will rebuild intro
  1322. * points periodically. */
  1323. break;
  1324. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1325. /* at Alice, connecting to intro point */
  1326. /* Don't increment failure count, since Bob may have picked
  1327. * the introduction point maliciously */
  1328. /* Alice will pick a new intro point when this one dies, if
  1329. * the stream in question still cares. No need to act here. */
  1330. break;
  1331. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1332. /* at Alice, waiting for Bob */
  1333. circuit_increment_failure_count();
  1334. /* Alice will pick a new rend point when this one dies, if
  1335. * the stream in question still cares. No need to act here. */
  1336. break;
  1337. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1338. /* at Bob, connecting to rend point */
  1339. /* Don't increment failure count, since Alice may have picked
  1340. * the rendezvous point maliciously */
  1341. log_info(LD_REND,
  1342. "Couldn't connect to Alice's chosen rend point %s "
  1343. "(%s hop failed).",
  1344. escaped(build_state_get_exit_nickname(circ->build_state)),
  1345. failed_at_last_hop?"last":"non-last");
  1346. rend_service_relaunch_rendezvous(circ);
  1347. break;
  1348. /* default:
  1349. * This won't happen in normal operation, but might happen if the
  1350. * controller did it. Just let it slide. */
  1351. }
  1352. }
  1353. /** Number of consecutive failures so far; should only be touched by
  1354. * circuit_launch_new and circuit_*_failure_count.
  1355. */
  1356. static int n_circuit_failures = 0;
  1357. /** Before the last time we called circuit_reset_failure_count(), were
  1358. * there a lot of failures? */
  1359. static int did_circs_fail_last_period = 0;
  1360. /** Don't retry launching a new circuit if we try this many times with no
  1361. * success. */
  1362. #define MAX_CIRCUIT_FAILURES 5
  1363. /** Launch a new circuit; see circuit_launch_by_extend_info() for
  1364. * details on arguments. */
  1365. origin_circuit_t *
  1366. circuit_launch(uint8_t purpose, int flags)
  1367. {
  1368. return circuit_launch_by_extend_info(purpose, NULL, flags);
  1369. }
  1370. /** Launch a new circuit with purpose <b>purpose</b> and exit node
  1371. * <b>extend_info</b> (or NULL to select a random exit node). If flags
  1372. * contains CIRCLAUNCH_NEED_UPTIME, choose among routers with high uptime. If
  1373. * CIRCLAUNCH_NEED_CAPACITY is set, choose among routers with high bandwidth.
  1374. * If CIRCLAUNCH_IS_INTERNAL is true, the last hop need not be an exit node.
  1375. * If CIRCLAUNCH_ONEHOP_TUNNEL is set, the circuit will have only one hop.
  1376. * Return the newly allocated circuit on success, or NULL on failure. */
  1377. origin_circuit_t *
  1378. circuit_launch_by_extend_info(uint8_t purpose,
  1379. extend_info_t *extend_info,
  1380. int flags)
  1381. {
  1382. origin_circuit_t *circ;
  1383. int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
  1384. if (!onehop_tunnel && !router_have_minimum_dir_info()) {
  1385. log_debug(LD_CIRC,"Haven't fetched enough directory info yet; canceling "
  1386. "circuit launch.");
  1387. return NULL;
  1388. }
  1389. if ((extend_info || purpose != CIRCUIT_PURPOSE_C_GENERAL) &&
  1390. purpose != CIRCUIT_PURPOSE_TESTING && !onehop_tunnel) {
  1391. /* see if there are appropriate circs available to cannibalize. */
  1392. /* XXX if we're planning to add a hop, perhaps we want to look for
  1393. * internal circs rather than exit circs? -RD */
  1394. circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
  1395. if (circ) {
  1396. uint8_t old_purpose = circ->base_.purpose;
  1397. struct timeval old_timestamp_began = circ->base_.timestamp_began;
  1398. log_info(LD_CIRC,"Cannibalizing circ '%s' for purpose %d (%s)",
  1399. build_state_get_exit_nickname(circ->build_state), purpose,
  1400. circuit_purpose_to_string(purpose));
  1401. if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  1402. purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
  1403. circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
  1404. /* Path bias: Cannibalized rends pre-emptively count as a
  1405. * successfully built but unused closed circuit. We don't
  1406. * wait until the extend (or the close) because the rend
  1407. * point could be malicious.
  1408. *
  1409. * Same deal goes for client side introductions. Clients
  1410. * can be manipulated to connect repeatedly to them
  1411. * (especially web clients).
  1412. *
  1413. * If we decide to probe the initial portion of these circs,
  1414. * (up to the adversary's final hop), we need to remove this,
  1415. * or somehow mark the circuit with a special path state.
  1416. */
  1417. /* This must be called before the purpose change */
  1418. pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
  1419. }
  1420. circuit_change_purpose(TO_CIRCUIT(circ), purpose);
  1421. /* Reset the start date of this circ, else expire_building
  1422. * will see it and think it's been trying to build since it
  1423. * began.
  1424. *
  1425. * Technically, the code should reset this when the
  1426. * create cell is finally sent, but we're close enough
  1427. * here. */
  1428. tor_gettimeofday(&circ->base_.timestamp_began);
  1429. control_event_circuit_cannibalized(circ, old_purpose,
  1430. &old_timestamp_began);
  1431. switch (purpose) {
  1432. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1433. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  1434. /* it's ready right now */
  1435. break;
  1436. case CIRCUIT_PURPOSE_C_INTRODUCING:
  1437. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  1438. case CIRCUIT_PURPOSE_C_GENERAL:
  1439. /* need to add a new hop */
  1440. tor_assert(extend_info);
  1441. if (circuit_extend_to_new_exit(circ, extend_info) < 0)
  1442. return NULL;
  1443. break;
  1444. default:
  1445. log_warn(LD_BUG,
  1446. "unexpected purpose %d when cannibalizing a circ.",
  1447. purpose);
  1448. tor_fragile_assert();
  1449. return NULL;
  1450. }
  1451. return circ;
  1452. }
  1453. }
  1454. if (did_circs_fail_last_period &&
  1455. n_circuit_failures > MAX_CIRCUIT_FAILURES) {
  1456. /* too many failed circs in a row. don't try. */
  1457. // log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
  1458. return NULL;
  1459. }
  1460. /* try a circ. if it fails, circuit_mark_for_close will increment
  1461. * n_circuit_failures */
  1462. return circuit_establish_circuit(purpose, extend_info, flags);
  1463. }
  1464. /** Record another failure at opening a general circuit. When we have
  1465. * too many, we'll stop trying for the remainder of this minute.
  1466. */
  1467. static void
  1468. circuit_increment_failure_count(void)
  1469. {
  1470. ++n_circuit_failures;
  1471. log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
  1472. }
  1473. /** Reset the failure count for opening general circuits. This means
  1474. * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
  1475. * stopping again.
  1476. */
  1477. void
  1478. circuit_reset_failure_count(int timeout)
  1479. {
  1480. if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
  1481. did_circs_fail_last_period = 1;
  1482. else
  1483. did_circs_fail_last_period = 0;
  1484. n_circuit_failures = 0;
  1485. }
  1486. /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
  1487. * there isn't one, and there isn't one on the way, launch one and return
  1488. * 0. If it will never work, return -1.
  1489. *
  1490. * Write the found or in-progress or launched circ into *circp.
  1491. */
  1492. static int
  1493. circuit_get_open_circ_or_launch(entry_connection_t *conn,
  1494. uint8_t desired_circuit_purpose,
  1495. origin_circuit_t **circp)
  1496. {
  1497. origin_circuit_t *circ;
  1498. int check_exit_policy;
  1499. int need_uptime, need_internal;
  1500. int want_onehop;
  1501. const or_options_t *options = get_options();
  1502. tor_assert(conn);
  1503. tor_assert(circp);
  1504. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1505. check_exit_policy =
  1506. conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  1507. !conn->use_begindir &&
  1508. !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
  1509. want_onehop = conn->want_onehop;
  1510. need_uptime = !conn->want_onehop && !conn->use_begindir &&
  1511. smartlist_contains_int_as_string(options->LongLivedPorts,
  1512. conn->socks_request->port);
  1513. if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
  1514. need_internal = 1;
  1515. else if (conn->use_begindir || conn->want_onehop)
  1516. need_internal = 1;
  1517. else
  1518. need_internal = 0;
  1519. circ = circuit_get_best(conn, 1, desired_circuit_purpose,
  1520. need_uptime, need_internal);
  1521. if (circ) {
  1522. *circp = circ;
  1523. return 1; /* we're happy */
  1524. }
  1525. if (!want_onehop && !router_have_minimum_dir_info()) {
  1526. if (!connection_get_by_type(CONN_TYPE_DIR)) {
  1527. int severity = LOG_NOTICE;
  1528. /* FFFF if this is a tunneled directory fetch, don't yell
  1529. * as loudly. the user doesn't even know it's happening. */
  1530. if (entry_list_is_constrained(options) &&
  1531. entries_known_but_down(options)) {
  1532. log_fn(severity, LD_APP|LD_DIR,
  1533. "Application request when we haven't used client functionality "
  1534. "lately. Optimistically trying known %s again.",
  1535. options->UseBridges ? "bridges" : "entrynodes");
  1536. entries_retry_all(options);
  1537. } else if (!options->UseBridges || any_bridge_descriptors_known()) {
  1538. log_fn(severity, LD_APP|LD_DIR,
  1539. "Application request when we haven't used client functionality "
  1540. "lately. Optimistically trying directory fetches again.");
  1541. routerlist_retry_directory_downloads(time(NULL));
  1542. }
  1543. }
  1544. /* the stream will be dealt with when router_have_minimum_dir_info becomes
  1545. * 1, or when all directory attempts fail and directory_all_unreachable()
  1546. * kills it.
  1547. */
  1548. return 0;
  1549. }
  1550. /* Do we need to check exit policy? */
  1551. if (check_exit_policy) {
  1552. if (!conn->chosen_exit_name) {
  1553. struct in_addr in;
  1554. tor_addr_t addr, *addrp=NULL;
  1555. if (tor_inet_aton(conn->socks_request->address, &in)) {
  1556. tor_addr_from_in(&addr, &in);
  1557. addrp = &addr;
  1558. }
  1559. if (router_exit_policy_all_nodes_reject(addrp,
  1560. conn->socks_request->port,
  1561. need_uptime)) {
  1562. log_notice(LD_APP,
  1563. "No Tor server allows exit to %s:%d. Rejecting.",
  1564. safe_str_client(conn->socks_request->address),
  1565. conn->socks_request->port);
  1566. return -1;
  1567. }
  1568. } else {
  1569. /* XXXX024 Duplicates checks in connection_ap_handshake_attach_circuit:
  1570. * refactor into a single function? */
  1571. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1572. int opt = conn->chosen_exit_optional;
  1573. if (node && !connection_ap_can_use_exit(conn, node)) {
  1574. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1575. "Requested exit point '%s' is excluded or "
  1576. "would refuse request. %s.",
  1577. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1578. if (opt) {
  1579. conn->chosen_exit_optional = 0;
  1580. tor_free(conn->chosen_exit_name);
  1581. /* Try again. */
  1582. return circuit_get_open_circ_or_launch(conn,
  1583. desired_circuit_purpose,
  1584. circp);
  1585. }
  1586. return -1;
  1587. }
  1588. }
  1589. }
  1590. /* is one already on the way? */
  1591. circ = circuit_get_best(conn, 0, desired_circuit_purpose,
  1592. need_uptime, need_internal);
  1593. if (circ)
  1594. log_debug(LD_CIRC, "one on the way!");
  1595. if (!circ) {
  1596. extend_info_t *extend_info=NULL;
  1597. uint8_t new_circ_purpose;
  1598. const int n_pending = count_pending_general_client_circuits();
  1599. if (n_pending >= options->MaxClientCircuitsPending) {
  1600. static ratelim_t delay_limit = RATELIM_INIT(10*60);
  1601. char *m;
  1602. if ((m = rate_limit_log(&delay_limit, approx_time()))) {
  1603. log_notice(LD_APP, "We'd like to launch a circuit to handle a "
  1604. "connection, but we already have %d general-purpose client "
  1605. "circuits pending. Waiting until some finish.%s",
  1606. n_pending, m);
  1607. tor_free(m);
  1608. }
  1609. return 0;
  1610. }
  1611. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1612. /* need to pick an intro point */
  1613. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
  1614. tor_assert(rend_data);
  1615. extend_info = rend_client_get_random_intro(rend_data);
  1616. if (!extend_info) {
  1617. log_info(LD_REND,
  1618. "No intro points for '%s': re-fetching service descriptor.",
  1619. safe_str_client(rend_data->onion_address));
  1620. rend_client_refetch_v2_renddesc(rend_data);
  1621. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
  1622. return 0;
  1623. }
  1624. log_info(LD_REND,"Chose %s as intro point for '%s'.",
  1625. extend_info_describe(extend_info),
  1626. safe_str_client(rend_data->onion_address));
  1627. }
  1628. /* If we have specified a particular exit node for our
  1629. * connection, then be sure to open a circuit to that exit node.
  1630. */
  1631. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1632. if (conn->chosen_exit_name) {
  1633. const node_t *r;
  1634. int opt = conn->chosen_exit_optional;
  1635. r = node_get_by_nickname(conn->chosen_exit_name, 1);
  1636. if (r && node_has_descriptor(r)) {
  1637. /* We might want to connect to an IPv6 bridge for loading
  1638. descriptors so we use the preferred address rather than
  1639. the primary. */
  1640. extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0);
  1641. } else {
  1642. log_debug(LD_DIR, "considering %d, %s",
  1643. want_onehop, conn->chosen_exit_name);
  1644. if (want_onehop && conn->chosen_exit_name[0] == '$') {
  1645. /* We're asking for a one-hop circuit to a router that
  1646. * we don't have a routerinfo about. Make up an extend_info. */
  1647. char digest[DIGEST_LEN];
  1648. char *hexdigest = conn->chosen_exit_name+1;
  1649. tor_addr_t addr;
  1650. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1651. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN)<0) {
  1652. log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
  1653. return -1;
  1654. }
  1655. if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
  1656. log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
  1657. escaped_safe_str_client(conn->socks_request->address));
  1658. return -1;
  1659. }
  1660. extend_info = extend_info_new(conn->chosen_exit_name+1,
  1661. digest, NULL, NULL, &addr,
  1662. conn->socks_request->port);
  1663. } else {
  1664. /* We will need an onion key for the router, and we
  1665. * don't have one. Refuse or relax requirements. */
  1666. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1667. "Requested exit point '%s' is not known. %s.",
  1668. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1669. if (opt) {
  1670. conn->chosen_exit_optional = 0;
  1671. tor_free(conn->chosen_exit_name);
  1672. /* Try again with no requested exit */
  1673. return circuit_get_open_circ_or_launch(conn,
  1674. desired_circuit_purpose,
  1675. circp);
  1676. }
  1677. return -1;
  1678. }
  1679. }
  1680. }
  1681. }
  1682. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  1683. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  1684. else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  1685. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  1686. else
  1687. new_circ_purpose = desired_circuit_purpose;
  1688. if (options->Tor2webMode &&
  1689. (new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
  1690. new_circ_purpose == CIRCUIT_PURPOSE_C_INTRODUCING)) {
  1691. want_onehop = 1;
  1692. }
  1693. {
  1694. int flags = CIRCLAUNCH_NEED_CAPACITY;
  1695. if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
  1696. if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
  1697. if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
  1698. circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
  1699. flags);
  1700. }
  1701. extend_info_free(extend_info);
  1702. if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1703. /* We just caused a circuit to get built because of this stream.
  1704. * If this stream has caused a _lot_ of circuits to be built, that's
  1705. * a bad sign: we should tell the user. */
  1706. if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
  1707. ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
  1708. log_info(LD_CIRC, "The application request to %s:%d has launched "
  1709. "%d circuits without finding one it likes.",
  1710. escaped_safe_str_client(conn->socks_request->address),
  1711. conn->socks_request->port,
  1712. conn->num_circuits_launched);
  1713. } else {
  1714. /* help predict this next time */
  1715. rep_hist_note_used_internal(time(NULL), need_uptime, 1);
  1716. if (circ) {
  1717. /* write the service_id into circ */
  1718. circ->rend_data = rend_data_dup(ENTRY_TO_EDGE_CONN(conn)->rend_data);
  1719. if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
  1720. circ->base_.state == CIRCUIT_STATE_OPEN)
  1721. rend_client_rendcirc_has_opened(circ);
  1722. }
  1723. }
  1724. } /* endif (!circ) */
  1725. if (circ) {
  1726. /* Mark the circuit with the isolation fields for this connection.
  1727. * When the circuit arrives, we'll clear these flags: this is
  1728. * just some internal bookkeeping to make sure that we have
  1729. * launched enough circuits.
  1730. */
  1731. connection_edge_update_circuit_isolation(conn, circ, 0);
  1732. } else {
  1733. log_info(LD_APP,
  1734. "No safe circuit (purpose %d) ready for edge "
  1735. "connection; delaying.",
  1736. desired_circuit_purpose);
  1737. }
  1738. *circp = circ;
  1739. return 0;
  1740. }
  1741. /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
  1742. * <b>circ</b>. */
  1743. static int
  1744. cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
  1745. {
  1746. crypt_path_t *cpath, *cpath_next = NULL;
  1747. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1748. cpath_next = cpath->next;
  1749. if (crypt_path == cpath)
  1750. return 1;
  1751. }
  1752. return 0;
  1753. }
  1754. /** Return true iff client-side optimistic data is supported. */
  1755. static int
  1756. optimistic_data_enabled(void)
  1757. {
  1758. const or_options_t *options = get_options();
  1759. if (options->OptimisticData < 0) {
  1760. /* XXX023 consider having auto default to 1 rather than 0 before
  1761. * the 0.2.3 branch goes stable. See bug 3617. -RD */
  1762. const int32_t enabled =
  1763. networkstatus_get_param(NULL, "UseOptimisticData", 0, 0, 1);
  1764. return (int)enabled;
  1765. }
  1766. return options->OptimisticData;
  1767. }
  1768. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  1769. * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
  1770. * hop in circ's cpath if <b>cpath</b> is NULL.
  1771. */
  1772. static void
  1773. link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
  1774. crypt_path_t *cpath)
  1775. {
  1776. const node_t *exitnode;
  1777. /* add it into the linked list of streams on this circuit */
  1778. log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
  1779. (unsigned)circ->base_.n_circ_id);
  1780. /* reset it, so we can measure circ timeouts */
  1781. ENTRY_TO_CONN(apconn)->timestamp_lastread = time(NULL);
  1782. ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
  1783. ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
  1784. /* assert_connection_ok(conn, time(NULL)); */
  1785. circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
  1786. if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
  1787. /* We are attaching a stream to a rendezvous circuit. That means
  1788. * that an attempt to connect to a hidden service just
  1789. * succeeded. Tell rendclient.c. */
  1790. rend_client_note_connection_attempt_ended(
  1791. ENTRY_TO_EDGE_CONN(apconn)->rend_data->onion_address);
  1792. }
  1793. if (cpath) { /* we were given one; use it */
  1794. tor_assert(cpath_is_on_circuit(circ, cpath));
  1795. } else {
  1796. /* use the last hop in the circuit */
  1797. tor_assert(circ->cpath);
  1798. tor_assert(circ->cpath->prev);
  1799. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  1800. cpath = circ->cpath->prev;
  1801. }
  1802. ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
  1803. circ->isolation_any_streams_attached = 1;
  1804. connection_edge_update_circuit_isolation(apconn, circ, 0);
  1805. /* See if we can use optimistic data on this circuit */
  1806. if (cpath->extend_info &&
  1807. (exitnode = node_get_by_id(cpath->extend_info->identity_digest)) &&
  1808. exitnode->rs) {
  1809. /* Okay; we know what exit node this is. */
  1810. if (optimistic_data_enabled() &&
  1811. circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  1812. exitnode->rs->version_supports_optimistic_data)
  1813. apconn->may_use_optimistic_data = 1;
  1814. else
  1815. apconn->may_use_optimistic_data = 0;
  1816. log_info(LD_APP, "Looks like completed circuit to %s %s allow "
  1817. "optimistic data for connection to %s",
  1818. safe_str_client(node_describe(exitnode)),
  1819. apconn->may_use_optimistic_data ? "does" : "doesn't",
  1820. safe_str_client(apconn->socks_request->address));
  1821. }
  1822. }
  1823. /** Return true iff <b>address</b> is matched by one of the entries in
  1824. * TrackHostExits. */
  1825. int
  1826. hostname_in_track_host_exits(const or_options_t *options, const char *address)
  1827. {
  1828. if (!options->TrackHostExits)
  1829. return 0;
  1830. SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
  1831. if (cp[0] == '.') { /* match end */
  1832. if (cp[1] == '\0' ||
  1833. !strcasecmpend(address, cp) ||
  1834. !strcasecmp(address, &cp[1]))
  1835. return 1;
  1836. } else if (strcasecmp(cp, address) == 0) {
  1837. return 1;
  1838. }
  1839. } SMARTLIST_FOREACH_END(cp);
  1840. return 0;
  1841. }
  1842. /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
  1843. * the exit that we *did* choose for use by future connections to
  1844. * <b>conn</b>'s destination.
  1845. */
  1846. static void
  1847. consider_recording_trackhost(const entry_connection_t *conn,
  1848. const origin_circuit_t *circ)
  1849. {
  1850. const or_options_t *options = get_options();
  1851. char *new_address = NULL;
  1852. char fp[HEX_DIGEST_LEN+1];
  1853. /* Search the addressmap for this conn's destination. */
  1854. /* If he's not in the address map.. */
  1855. if (!options->TrackHostExits ||
  1856. addressmap_have_mapping(conn->socks_request->address,
  1857. options->TrackHostExitsExpire))
  1858. return; /* nothing to track, or already mapped */
  1859. if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
  1860. !circ->build_state->chosen_exit)
  1861. return;
  1862. /* write down the fingerprint of the chosen exit, not the nickname,
  1863. * because the chosen exit might not be named. */
  1864. base16_encode(fp, sizeof(fp),
  1865. circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
  1866. /* Add this exit/hostname pair to the addressmap. */
  1867. tor_asprintf(&new_address, "%s.%s.exit",
  1868. conn->socks_request->address, fp);
  1869. addressmap_register(conn->socks_request->address, new_address,
  1870. time(NULL) + options->TrackHostExitsExpire,
  1871. ADDRMAPSRC_TRACKEXIT, 0, 0);
  1872. }
  1873. /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
  1874. * begin or resolve cell as appropriate. Return values are as for
  1875. * connection_ap_handshake_attach_circuit. The stream will exit from the hop
  1876. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1877. * <b>cpath</b> is NULL. */
  1878. int
  1879. connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
  1880. origin_circuit_t *circ,
  1881. crypt_path_t *cpath)
  1882. {
  1883. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1884. tor_assert(conn);
  1885. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
  1886. base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
  1887. tor_assert(conn->socks_request);
  1888. tor_assert(circ);
  1889. tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
  1890. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1891. if (!circ->base_.timestamp_dirty)
  1892. circ->base_.timestamp_dirty = time(NULL);
  1893. pathbias_count_use_attempt(circ);
  1894. link_apconn_to_circ(conn, circ, cpath);
  1895. tor_assert(conn->socks_request);
  1896. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  1897. if (!conn->use_begindir)
  1898. consider_recording_trackhost(conn, circ);
  1899. if (connection_ap_handshake_send_begin(conn) < 0)
  1900. return -1;
  1901. } else {
  1902. if (connection_ap_handshake_send_resolve(conn) < 0)
  1903. return -1;
  1904. }
  1905. return 1;
  1906. }
  1907. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  1908. * we don't find one: if conn cannot be handled by any known nodes,
  1909. * warn and return -1 (conn needs to die, and is maybe already marked);
  1910. * else launch new circuit (if necessary) and return 0.
  1911. * Otherwise, associate conn with a safe live circuit, do the
  1912. * right next step, and return 1.
  1913. */
  1914. /* XXXX this function should mark for close whenever it returns -1;
  1915. * its callers shouldn't have to worry about that. */
  1916. int
  1917. connection_ap_handshake_attach_circuit(entry_connection_t *conn)
  1918. {
  1919. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1920. int retval;
  1921. int conn_age;
  1922. int want_onehop;
  1923. tor_assert(conn);
  1924. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1925. tor_assert(conn->socks_request);
  1926. want_onehop = conn->want_onehop;
  1927. conn_age = (int)(time(NULL) - base_conn->timestamp_created);
  1928. if (conn_age >= get_options()->SocksTimeout) {
  1929. int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
  1930. LOG_INFO : LOG_NOTICE;
  1931. log_fn(severity, LD_APP,
  1932. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  1933. conn_age, safe_str_client(conn->socks_request->address),
  1934. conn->socks_request->port);
  1935. return -1;
  1936. }
  1937. if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
  1938. /* we're a general conn */
  1939. origin_circuit_t *circ=NULL;
  1940. if (conn->chosen_exit_name) {
  1941. const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1942. int opt = conn->chosen_exit_optional;
  1943. if (!node && !want_onehop) {
  1944. /* We ran into this warning when trying to extend a circuit to a
  1945. * hidden service directory for which we didn't have a router
  1946. * descriptor. See flyspray task 767 for more details. We should
  1947. * keep this in mind when deciding to use BEGIN_DIR cells for other
  1948. * directory requests as well. -KL*/
  1949. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1950. "Requested exit point '%s' is not known. %s.",
  1951. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1952. if (opt) {
  1953. conn->chosen_exit_optional = 0;
  1954. tor_free(conn->chosen_exit_name);
  1955. return 0;
  1956. }
  1957. return -1;
  1958. }
  1959. if (node && !connection_ap_can_use_exit(conn, node)) {
  1960. log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
  1961. "Requested exit point '%s' is excluded or "
  1962. "would refuse request. %s.",
  1963. conn->chosen_exit_name, opt ? "Trying others" : "Closing");
  1964. if (opt) {
  1965. conn->chosen_exit_optional = 0;
  1966. tor_free(conn->chosen_exit_name);
  1967. return 0;
  1968. }
  1969. return -1;
  1970. }
  1971. }
  1972. /* find the circuit that we should use, if there is one. */
  1973. retval = circuit_get_open_circ_or_launch(
  1974. conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  1975. if (retval < 1) // XXX023 if we totally fail, this still returns 0 -RD
  1976. return retval;
  1977. log_debug(LD_APP|LD_CIRC,
  1978. "Attaching apconn to circ %u (stream %d sec old).",
  1979. (unsigned)circ->base_.n_circ_id, conn_age);
  1980. /* print the circ's path, so people can figure out which circs are
  1981. * sucking. */
  1982. circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
  1983. /* We have found a suitable circuit for our conn. Hurray. */
  1984. return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
  1985. } else { /* we're a rendezvous conn */
  1986. origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
  1987. tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
  1988. /* start by finding a rendezvous circuit for us */
  1989. retval = circuit_get_open_circ_or_launch(
  1990. conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  1991. if (retval < 0) return -1; /* failed */
  1992. if (retval > 0) {
  1993. tor_assert(rendcirc);
  1994. /* one is already established, attach */
  1995. log_info(LD_REND,
  1996. "rend joined circ %d already here. attaching. "
  1997. "(stream %d sec old)",
  1998. (unsigned)rendcirc->base_.n_circ_id, conn_age);
  1999. /* Mark rendezvous circuits as 'newly dirty' every time you use
  2000. * them, since the process of rebuilding a rendezvous circ is so
  2001. * expensive. There is a tradeoff between linkability and
  2002. * feasibility, at this point.
  2003. */
  2004. rendcirc->base_.timestamp_dirty = time(NULL);
  2005. /* We've also attempted to use them. If they fail, we need to
  2006. * probe them for path bias */
  2007. pathbias_count_use_attempt(rendcirc);
  2008. link_apconn_to_circ(conn, rendcirc, NULL);
  2009. if (connection_ap_handshake_send_begin(conn) < 0)
  2010. return 0; /* already marked, let them fade away */
  2011. return 1;
  2012. }
  2013. if (rendcirc && (rendcirc->base_.purpose ==
  2014. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
  2015. log_info(LD_REND,
  2016. "pending-join circ %u already here, with intro ack. "
  2017. "Stalling. (stream %d sec old)",
  2018. (unsigned)rendcirc->base_.n_circ_id, conn_age);
  2019. return 0;
  2020. }
  2021. /* it's on its way. find an intro circ. */
  2022. retval = circuit_get_open_circ_or_launch(
  2023. conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  2024. if (retval < 0) return -1; /* failed */
  2025. if (retval > 0) {
  2026. /* one has already sent the intro. keep waiting. */
  2027. tor_assert(introcirc);
  2028. log_info(LD_REND, "Intro circ %u present and awaiting ack (rend %u). "
  2029. "Stalling. (stream %d sec old)",
  2030. (unsigned)introcirc->base_.n_circ_id,
  2031. rendcirc ? (unsigned)rendcirc->base_.n_circ_id : 0,
  2032. conn_age);
  2033. return 0;
  2034. }
  2035. /* now rendcirc and introcirc are each either undefined or not finished */
  2036. if (rendcirc && introcirc &&
  2037. rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  2038. log_info(LD_REND,
  2039. "ready rend circ %u already here (no intro-ack yet on "
  2040. "intro %u). (stream %d sec old)",
  2041. (unsigned)rendcirc->base_.n_circ_id,
  2042. (unsigned)introcirc->base_.n_circ_id, conn_age);
  2043. tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  2044. if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
  2045. log_info(LD_REND,"found open intro circ %u (rend %u); sending "
  2046. "introduction. (stream %d sec old)",
  2047. (unsigned)introcirc->base_.n_circ_id,
  2048. (unsigned)rendcirc->base_.n_circ_id,
  2049. conn_age);
  2050. switch (rend_client_send_introduction(introcirc, rendcirc)) {
  2051. case 0: /* success */
  2052. rendcirc->base_.timestamp_dirty = time(NULL);
  2053. introcirc->base_.timestamp_dirty = time(NULL);
  2054. pathbias_count_use_attempt(introcirc);
  2055. pathbias_count_use_attempt(rendcirc);
  2056. assert_circuit_ok(TO_CIRCUIT(rendcirc));
  2057. assert_circuit_ok(TO_CIRCUIT(introcirc));
  2058. return 0;
  2059. case -1: /* transient error */
  2060. return 0;
  2061. case -2: /* permanent error */
  2062. return -1;
  2063. default: /* oops */
  2064. tor_fragile_assert();
  2065. return -1;
  2066. }
  2067. }
  2068. }
  2069. log_info(LD_REND, "Intro (%u) and rend (%u) circs are not both ready. "
  2070. "Stalling conn. (%d sec old)",
  2071. introcirc ? (unsigned)introcirc->base_.n_circ_id : 0,
  2072. rendcirc ? (unsigned)rendcirc->base_.n_circ_id : 0, conn_age);
  2073. return 0;
  2074. }
  2075. }
  2076. /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
  2077. void
  2078. circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
  2079. {
  2080. uint8_t old_purpose;
  2081. /* Don't allow an OR circ to become an origin circ or vice versa. */
  2082. tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
  2083. !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
  2084. if (circ->purpose == new_purpose) return;
  2085. if (CIRCUIT_IS_ORIGIN(circ)) {
  2086. char old_purpose_desc[80] = "";
  2087. strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
  2088. old_purpose_desc[80-1] = '\0';
  2089. log_debug(LD_CIRC,
  2090. "changing purpose of origin circ %d "
  2091. "from \"%s\" (%d) to \"%s\" (%d)",
  2092. TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  2093. old_purpose_desc,
  2094. circ->purpose,
  2095. circuit_purpose_to_string(new_purpose),
  2096. new_purpose);
  2097. }
  2098. old_purpose = circ->purpose;
  2099. circ->purpose = new_purpose;
  2100. if (CIRCUIT_IS_ORIGIN(circ)) {
  2101. control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
  2102. old_purpose);
  2103. }
  2104. }
  2105. /** Mark <b>circ</b> so that no more connections can be attached to it. */
  2106. void
  2107. mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
  2108. {
  2109. const or_options_t *options = get_options();
  2110. tor_assert(circ);
  2111. /* XXXX025 This is a kludge; we're only keeping it around in case there's
  2112. * something that doesn't check unusable_for_new_conns, and to avoid
  2113. * deeper refactoring of our expiration logic. */
  2114. if (! circ->base_.timestamp_dirty)
  2115. circ->base_.timestamp_dirty = approx_time();
  2116. if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
  2117. circ->base_.timestamp_dirty = 1; /* prevent underflow */
  2118. else
  2119. circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
  2120. circ->unusable_for_new_conns = 1;
  2121. }