circuituse.c 65 KB

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