circuituse.c 82 KB

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