circuituse.c 65 KB

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