circuituse.c 86 KB

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