circuituse.c 56 KB

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