circuituse.c 55 KB

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