circuituse.c 84 KB

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