circuituse.c 55 KB

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